From 27b6211133a03c6017a7abdb09975efae4928a8d Mon Sep 17 00:00:00 2001 From: z30053788 Date: Fri, 9 Aug 2024 10:50:10 +0800 Subject: [PATCH 001/167] cherry pick 1d46944 from https://gitee.com/zhaobaoxin1/notification_distributed_notification_service/pulls/2003 update Signed-off-by: z30053788 Change-Id: I0b81337eb9b1f6d35a7c91047e172e501d7bd29e --- frameworks/js/napi/src/publish.cpp | 3 --- 1 file changed, 3 deletions(-) diff --git a/frameworks/js/napi/src/publish.cpp b/frameworks/js/napi/src/publish.cpp index 74a187cd3..64a02fe10 100644 --- a/frameworks/js/napi/src/publish.cpp +++ b/frameworks/js/napi/src/publish.cpp @@ -239,7 +239,6 @@ napi_value ParseShowOptions(const napi_env &env, const napi_callback_info &info, NAPI_CALL(env, napi_get_cb_info(env, info, &argc, argv, NULL, NULL)); if (argc == 0) { ANS_LOGW("Wrong number of arguments."); - Common::NapiThrow(env, ERROR_PARAM_INVALID, MANDATORY_PARAMETER_ARE_LEFT_UNSPECIFIED); return nullptr; } @@ -248,8 +247,6 @@ napi_value ParseShowOptions(const napi_env &env, const napi_callback_info &info, NAPI_CALL(env, napi_typeof(env, argv[PARAM0], &valuetype)); if (valuetype != napi_object) { ANS_LOGW("Wrong argument type. Object expected."); - std::string msg = "Incorrect parameter types.The type of param must be object."; - Common::NapiThrow(env, ERROR_PARAM_INVALID, msg); return nullptr; } -- Gitee From ca08921971703b658babf844aea768e92251b210 Mon Sep 17 00:00:00 2001 From: xdongs Date: Thu, 8 Aug 2024 14:23:49 +0800 Subject: [PATCH 002/167] =?UTF-8?q?errorCode=20=EF=BC=88cherry=20picked=20?= =?UTF-8?q?commit=20from=20?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- frameworks/js/napi/src/common_utils.cpp | 4 +++- frameworks/js/napi/src/manager/napi_enable_notification.cpp | 4 ++-- services/ans/src/advanced_notification_publish_service.cpp | 2 +- 3 files changed, 6 insertions(+), 4 deletions(-) diff --git a/frameworks/js/napi/src/common_utils.cpp b/frameworks/js/napi/src/common_utils.cpp index 74568771c..148fbd8ab 100644 --- a/frameworks/js/napi/src/common_utils.cpp +++ b/frameworks/js/napi/src/common_utils.cpp @@ -49,6 +49,7 @@ static const std::unordered_map ERROR_CODE_MESSAGE { {ERROR_NO_MEMORY, "No memory space"}, {ERROR_BUNDLE_NOT_FOUND, "The specified bundle name was not found"}, {ERROR_NO_AGENT_SETTING, "There is no corresponding agent relationship configuration"}, + {ERROR_DIALOG_IS_POPPING, "Dialog is popping"}, }; } @@ -313,7 +314,8 @@ int32_t Common::ErrorToExternal(uint32_t errCode) {ERR_ANS_PUSH_CHECK_FAILED, ERROR_NO_RIGHT}, {ERR_ANS_PUSH_CHECK_UNREGISTERED, ERROR_NO_RIGHT}, {ERR_ANS_PUSH_CHECK_NETWORK_UNREACHABLE, ERROR_NETWORK_UNREACHABLE}, - {ERR_ANS_NO_AGENT_SETTING, ERROR_NO_AGENT_SETTING} + {ERR_ANS_NO_AGENT_SETTING, ERROR_NO_AGENT_SETTING}, + {ERR_ANS_DIALOG_IS_POPPING, ERROR_DIALOG_IS_POPPING} }; int32_t ExternalCode = ERROR_INTERNAL_ERROR; diff --git a/frameworks/js/napi/src/manager/napi_enable_notification.cpp b/frameworks/js/napi/src/manager/napi_enable_notification.cpp index 7b7f7ac7f..67a0fbd4f 100644 --- a/frameworks/js/napi/src/manager/napi_enable_notification.cpp +++ b/frameworks/js/napi/src/manager/napi_enable_notification.cpp @@ -253,7 +253,7 @@ void NapiAsyncCompleteCallbackRequestEnableNotification(napi_env env, void *data napi_value NapiRequestEnableNotification(napi_env env, napi_callback_info info) { - ANS_LOGI("enter"); + ANS_LOGI("NapiRequestEnableNotification enter"); IsEnableParams params {}; if (ParseRequestEnableParameters(env, info, params) == nullptr) { Common::NapiThrow(env, ERROR_PARAM_INVALID); @@ -617,7 +617,7 @@ void ModalExtensionCallback::OnReceive(const AAFwk::WantParams& receive) */ void ModalExtensionCallback::OnRelease(int32_t releaseCode) { - ANS_LOGD("OnRelease"); + ANS_LOGI("OnRelease"); ReleaseOrErrorHandle(releaseCode); } diff --git a/services/ans/src/advanced_notification_publish_service.cpp b/services/ans/src/advanced_notification_publish_service.cpp index 0b95ab3ce..60c1825b7 100644 --- a/services/ans/src/advanced_notification_publish_service.cpp +++ b/services/ans/src/advanced_notification_publish_service.cpp @@ -963,7 +963,7 @@ ErrCode AdvancedNotificationService::CanPopEnableNotificationDialog( return ERROR_INTERNAL_ERROR; } if (hasPopped) { - return ERR_OK; + return ERR_ANS_NOT_ALLOWED; } if (!CreateDialogManager()) { -- Gitee From 5bb48807adbdfd07ba03e90dbd8c50f950b04e24 Mon Sep 17 00:00:00 2001 From: xdongs Date: Thu, 8 Aug 2024 15:59:00 +0800 Subject: [PATCH 003/167] merge Signed-off-by: xdongs --- services/ans/src/advanced_notification_utils.cpp | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/services/ans/src/advanced_notification_utils.cpp b/services/ans/src/advanced_notification_utils.cpp index decf7240d..0b1c2694e 100644 --- a/services/ans/src/advanced_notification_utils.cpp +++ b/services/ans/src/advanced_notification_utils.cpp @@ -1201,8 +1201,10 @@ std::vector AdvancedNotificationService::GetLocalNotificationKeys( std::vector keys; for (auto record : notificationList_) { - if ((bundleOption != nullptr) && (record->bundleOption->GetBundleName() != bundleOption->GetBundleName()) && - (record->bundleOption->GetUid() != bundleOption->GetUid()) && record->deviceId.empty()) { + if ((bundleOption != nullptr) && + ((record->bundleOption->GetBundleName() != bundleOption->GetBundleName()) || + (record->bundleOption->GetUid() != bundleOption->GetUid())) && + record->deviceId.empty()) { continue; } keys.push_back(record->notification->GetKey()); -- Gitee From d9066cf7aa05fccfe5bf41c0ab88b4e9c9a12ebe Mon Sep 17 00:00:00 2001 From: xdongs Date: Mon, 12 Aug 2024 10:24:38 +0800 Subject: [PATCH 004/167] =?UTF-8?q?unsubscribe=20=EF=BC=88cherry=20picked?= =?UTF-8?q?=20commit=20from=20?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- frameworks/js/napi/src/subscribe.cpp | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/frameworks/js/napi/src/subscribe.cpp b/frameworks/js/napi/src/subscribe.cpp index ee3b923d2..043c7549a 100644 --- a/frameworks/js/napi/src/subscribe.cpp +++ b/frameworks/js/napi/src/subscribe.cpp @@ -509,7 +509,7 @@ void ThreadSafeOnDisconnected(napi_env env, napi_value jsCallback, void* context } Common::SetCallback(dataWorkerData->env, dataWorkerData->ref, Common::NapiGetNull(dataWorkerData->env)); - + DelSubscriberInstancesInfo(dataWorkerData->env, dataWorkerData->subscriber); delete dataWorkerData; dataWorkerData = nullptr; } @@ -541,7 +541,6 @@ void SubscriberInstance::OnDisconnected() napi_acquire_threadsafe_function(unsubscribeCallbackInfo_.tsfn); napi_call_threadsafe_function(unsubscribeCallbackInfo_.tsfn, dataWorker, napi_tsfn_nonblocking); napi_release_threadsafe_function(unsubscribeCallbackInfo_.tsfn, napi_tsfn_abort); - DelSubscriberInstancesInfo(dataWorker->env, dataWorker->subscriber); } void ThreadSafeOnDestroy(napi_env env, napi_value jsCallback, void* context, void* data) -- Gitee From ecef1c99e565eeb10248206f0f3a623c0f04ca74 Mon Sep 17 00:00:00 2001 From: songbao1 Date: Tue, 13 Aug 2024 17:16:06 +0800 Subject: [PATCH 005/167] =?UTF-8?q?=E4=B8=89=E6=96=B9=E5=BA=94=E7=94=A8?= =?UTF-8?q?=E4=B8=ADRemovalWantAgent=E7=9A=84operationType=E5=8F=AA?= =?UTF-8?q?=E5=85=81=E8=AE=B8=E4=B8=BA4?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: songbao1 --- .../ans/src/advanced_notification_publish_service.cpp | 11 ++++++++++- 1 file changed, 10 insertions(+), 1 deletion(-) diff --git a/services/ans/src/advanced_notification_publish_service.cpp b/services/ans/src/advanced_notification_publish_service.cpp index 0b95ab3ce..77ae09d07 100644 --- a/services/ans/src/advanced_notification_publish_service.cpp +++ b/services/ans/src/advanced_notification_publish_service.cpp @@ -52,6 +52,7 @@ constexpr int32_t HOURS_IN_ONE_DAY = 24; const static std::string NOTIFICATION_EVENT_PUSH_AGENT = "notification.event.PUSH_AGENT"; constexpr int32_t RSS_PID = 3051; constexpr int32_t TYPE_CODE_DOWNLOAD = 8; +constexpr int32_t OPERATION_TYPE_COMMON_EVENT = 4; ErrCode AdvancedNotificationService::SetDefaultNotificationEnabled( const sptr &bundleOption, bool enabled) @@ -111,7 +112,15 @@ ErrCode AdvancedNotificationService::Publish(const std::string &label, const spt if (isSubsystem) { return PublishNotificationBySa(request); } - + if (request->GetRemovalWantAgent() != nullptr) { + uint32_t operationType = (uint32_t)(request->GetRemovalWantAgent()->GetPendingWant() + ->GetType(request->GetRemovalWantAgent()->GetPendingWant()->GetTarget())); + bool isSystemApp = AccessTokenHelper::IsSystemApp(); + if (!isSubsystem && !isSystemApp && operationType != OPERATION_TYPE_COMMON_EVENT) { + ANS_LOGI("SetRemovalWantAgent as nullptr"); + request->SetRemovalWantAgent(nullptr); + } + } do { result = publishProcess_[request->GetSlotType()]->PublishNotificationByApp(request); if (result != ERR_OK) { -- Gitee From 20d5141028d73ffb6529691d5fba4c82fb6f5e33 Mon Sep 17 00:00:00 2001 From: gaojiaqi Date: Wed, 21 Aug 2024 09:25:51 +0800 Subject: [PATCH 006/167] fix ut Signed-off-by: gaojiaqi --- services/ans/test/unittest/reminder_data_manager_test.cpp | 1 + 1 file changed, 1 insertion(+) diff --git a/services/ans/test/unittest/reminder_data_manager_test.cpp b/services/ans/test/unittest/reminder_data_manager_test.cpp index 431381ff9..75dec8469 100644 --- a/services/ans/test/unittest/reminder_data_manager_test.cpp +++ b/services/ans/test/unittest/reminder_data_manager_test.cpp @@ -44,6 +44,7 @@ public: { ReminderDataManager::InitInstance(nullptr); manager = ReminderDataManager::GetInstance(); + manager->Init(false); } static void TearDownTestCase() { -- Gitee From f398445494bee31ab8d1c2dae9017a8df6707a42 Mon Sep 17 00:00:00 2001 From: gaojiaqi Date: Thu, 22 Aug 2024 11:18:07 +0800 Subject: [PATCH 007/167] update reminder Signed-off-by: gaojiaqi --- ...advanced_notification_reminder_service.cpp | 39 +++++++++---------- 1 file changed, 18 insertions(+), 21 deletions(-) diff --git a/services/ans/src/advanced_notification_reminder_service.cpp b/services/ans/src/advanced_notification_reminder_service.cpp index 96bb1905e..d73740f75 100644 --- a/services/ans/src/advanced_notification_reminder_service.cpp +++ b/services/ans/src/advanced_notification_reminder_service.cpp @@ -59,11 +59,14 @@ ErrCode AdvancedNotificationService::PublishReminder(sptr &remi } std::string bundle = GetClientBundleName(); - if (!CheckReminderPermission() || !AllowUseReminder(bundle)) { - ANSR_LOGW("Permission denied: ohos.permission.PUBLISH_AGENT_REMINDER" - "or not allowed use reminder"); + if (!CheckReminderPermission()) { + ANSR_LOGW("Permission denied: ohos.permission.PUBLISH_AGENT_REMINDER"); return ERR_REMINDER_PERMISSION_DENIED; } + if (!AllowUseReminder(bundle)) { + ANSR_LOGW("The number of reminders exceeds the limit[0]."); + return ERR_REMINDER_NUMBER_OVERLOAD; + } ANSR_LOGD("is system app: %{public}d", AccessTokenHelper::IsSystemApp()); reminder->SetSystemApp(AccessTokenHelper::IsSystemApp()); sptr notificationRequest = reminder->GetNotificationRequest(); @@ -113,9 +116,8 @@ ErrCode AdvancedNotificationService::CancelReminder(const int32_t reminderId) HITRACE_METER_NAME(HITRACE_TAG_OHOS, __PRETTY_FUNCTION__); ANSR_LOGI("Cancel Reminder"); std::string bundleName = GetClientBundleName(); - if (!CheckReminderPermission() || !AllowUseReminder(bundleName)) { - ANSR_LOGW("Permission denied: ohos.permission.PUBLISH_AGENT_REMINDER" - "or not allowed use reminder"); + if (!CheckReminderPermission()) { + ANSR_LOGW("Permission denied: ohos.permission.PUBLISH_AGENT_REMINDER"); return ERR_REMINDER_PERMISSION_DENIED; } @@ -135,9 +137,8 @@ ErrCode AdvancedNotificationService::CancelAllReminders() HITRACE_METER_NAME(HITRACE_TAG_OHOS, __PRETTY_FUNCTION__); ANSR_LOGI("Cancel all reminders"); std::string bundleName = GetClientBundleName(); - if (!CheckReminderPermission() || !AllowUseReminder(bundleName)) { - ANSR_LOGW("Permission denied: ohos.permission.PUBLISH_AGENT_REMINDER" - "or not allowed use reminder"); + if (!CheckReminderPermission()) { + ANSR_LOGW("Permission denied: ohos.permission.PUBLISH_AGENT_REMINDER"); return ERR_REMINDER_PERMISSION_DENIED; } @@ -160,9 +161,8 @@ ErrCode AdvancedNotificationService::GetValidReminders(std::vector Date: Wed, 14 Aug 2024 18:56:18 +0800 Subject: [PATCH 008/167] cherry pick 6dcb244 from https://gitee.com/zhaobaoxin1/notification_distributed_notification_service/pulls/2023 update Signed-off-by: z30053788 Change-Id: I38aec99dac095a0863adda7437e3122bbafcbd69 --- .../ans/src/advanced_notification_utils.cpp | 39 ++++++------------- 1 file changed, 12 insertions(+), 27 deletions(-) diff --git a/services/ans/src/advanced_notification_utils.cpp b/services/ans/src/advanced_notification_utils.cpp index 0b1c2694e..104c63943 100644 --- a/services/ans/src/advanced_notification_utils.cpp +++ b/services/ans/src/advanced_notification_utils.cpp @@ -644,36 +644,21 @@ void AdvancedNotificationService::OnBundleDataUpdate(const sptrGetHasPoppedDialog(bundleOption, hasPopped); - if (errCode != ERR_OK) { - ANS_LOGD("Get notification user option fail, need to insert data"); - errCode = NotificationPreferences::GetInstance()->SetNotificationsEnabledForBundle( - bundleOption, bundleInfo.applicationInfo.allowEnableNotification); - if (errCode != ERR_OK) { - ANS_LOGE("Set notification enable error! code: %{public}d", errCode); - } - SetSlotFlagsTrustlistsAsBundle(bundleOption); - errCode = NotificationPreferences::GetInstance()->SetShowBadge(bundleOption, true); - if (errCode != ERR_OK) { - ANS_LOGE("Set badge enable error! code: %{public}d", errCode); + bool enabled = false; + auto errCode = NotificationPreferences::GetInstance()->GetNotificationsEnabledForBundle( + bundleOption, enabled); + if (bundleOption->GetBundleName().compare("com.ohos.mms") == 0) { + uint32_t slotFlags = 63; + auto ret = NotificationPreferences::GetInstance()->GetNotificationSlotFlagsForBundle(bundleOption, slotFlags); + if (ret != ERR_OK) { + ANS_LOGE("Failed to get slotflags for bundle, use default slotflags."); } - return; + UpdateSlotReminderModeBySlotFlags(bundleOption, slotFlags); } - - if (hasPopped) { - ANS_LOGI("The user has made changes, subject to the user's selection"); - return; - } - - errCode = NotificationPreferences::GetInstance()->SetNotificationsEnabledForBundle( - bundleOption, bundleInfo.applicationInfo.allowEnableNotification); if (errCode != ERR_OK) { - ANS_LOGE("Set notification enable error! code: %{public}d", errCode); - } - errCode = NotificationPreferences::GetInstance()->SetShowBadge(bundleOption, true); - if (errCode != ERR_OK) { - ANS_LOGE("Set badge enable error! code: %{public}d", errCode); + ANS_LOGD("Get notification user option fail, need to insert data"); + OnBundleDataAdd(bundleOption); + return; } }; -- Gitee From 91398f699f7dd5ae4b732e6615d89f802fcf614b Mon Sep 17 00:00:00 2001 From: z30053788 Date: Thu, 22 Aug 2024 21:50:02 +0800 Subject: [PATCH 009/167] cherry pick 1761a44 from https://gitee.com/zhaobaoxin1/notification_distributed_notification_service/pulls/2056 update Signed-off-by: z30053788 Change-Id: If5b5081ee27f9ed94aaac075fa9dd7bbedb9b8cc --- services/ans/src/advanced_notification_publish_service.cpp | 1 + 1 file changed, 1 insertion(+) diff --git a/services/ans/src/advanced_notification_publish_service.cpp b/services/ans/src/advanced_notification_publish_service.cpp index ea8d6c9cc..49d1cbdc2 100644 --- a/services/ans/src/advanced_notification_publish_service.cpp +++ b/services/ans/src/advanced_notification_publish_service.cpp @@ -1009,6 +1009,7 @@ ErrCode AdvancedNotificationService::IsAllowedNotifySelf(const sptrGetNotificationsEnabledForBundle(bundleOption, allowed); if (result == ERR_ANS_PREFERENCES_NOTIFICATION_BUNDLE_NOT_EXIST) { + SetSlotFlagsTrustlistsAsBundle(bundleOption); result = ERR_OK; // FA model app can publish notification without user confirm allowed = CheckApiCompatibility(bundleOption); -- Gitee From eb202173343a85a224c10c20bd49a3a555773af6 Mon Sep 17 00:00:00 2001 From: z30053788 Date: Sat, 24 Aug 2024 14:46:08 +0800 Subject: [PATCH 010/167] update1 Signed-off-by: z30053788 Change-Id: I38d35f90b9955e27cbe172a6ebc58a40427e3475 --- .../ans_manager_death_recipient_unit_test.cpp | 2 +- .../ans_notification_branch_test.cpp | 5 ---- services/ans/src/notification_preferences.cpp | 3 --- .../access_token_helper_test.cpp | 2 +- .../advanced_notification_service_test.cpp | 2 +- ...dvanced_notification_slot_service_test.cpp | 4 ++-- .../os_account_manager_helper_test.cpp | 12 +++++----- .../unittest/distributed_preferences_test.cpp | 2 +- ...distributed_screen_status_manager_test.cpp | 7 +++--- .../notification_shell_command_dump_test.cpp | 24 ++++++++----------- 10 files changed, 26 insertions(+), 37 deletions(-) diff --git a/frameworks/core/test/unittest/ans_manager_death_recipient_test/ans_manager_death_recipient_unit_test.cpp b/frameworks/core/test/unittest/ans_manager_death_recipient_test/ans_manager_death_recipient_unit_test.cpp index de513a16e..165d38141 100644 --- a/frameworks/core/test/unittest/ans_manager_death_recipient_test/ans_manager_death_recipient_unit_test.cpp +++ b/frameworks/core/test/unittest/ans_manager_death_recipient_test/ans_manager_death_recipient_unit_test.cpp @@ -98,5 +98,5 @@ HWTEST_F(AnsManagerDeathRecipientUnitTest, OnAddSystemAbilityTest_0100, Function ansManagerDeathRecipient->statusChangeListener_->OnRemoveSystemAbility(0, ""); ansManagerDeathRecipient->statusChangeListener_->OnAddSystemAbility(0, ""); auto ansNotification = OHOS::DelayedSingleton::GetInstance(); - EXPECT_TRUE(ansNotification->ansManagerProxy_ != nullptr); + EXPECT_TRUE(ansNotification->ansManagerProxy_ == nullptr); } diff --git a/frameworks/core/test/unittest/ans_notification_branch_test/ans_notification_branch_test.cpp b/frameworks/core/test/unittest/ans_notification_branch_test/ans_notification_branch_test.cpp index fa2edbc73..40f151b03 100644 --- a/frameworks/core/test/unittest/ans_notification_branch_test/ans_notification_branch_test.cpp +++ b/frameworks/core/test/unittest/ans_notification_branch_test/ans_notification_branch_test.cpp @@ -646,7 +646,6 @@ HWTEST_F(AnsNotificationBranchTest, RemoveNotifications_0300, Function | MediumT hashcodes.emplace_back(hashcode); int32_t removeReason = 1; MockGetAnsManagerProxy(true); - ansNotification->ansManagerProxy_ = new (std::nothrow) MockAnsManagerInterface(); ansNotification->RemoveNotifications(hashcodes, removeReason); } @@ -680,8 +679,6 @@ HWTEST_F(AnsNotificationBranchTest, RegisterPushCallback_0200, Function | Medium auto ansNotification = std::make_shared(); EXPECT_NE(ansNotification, nullptr); sptr pushCallback = nullptr; - MockGetAnsManagerProxy(true); - ansNotification->ansManagerProxy_ = new (std::nothrow) MockAnsManagerInterface(); sptr checkRequest = new (std::nothrow) NotificationCheckRequest(); ansNotification->RegisterPushCallback(pushCallback, checkRequest); } @@ -713,8 +710,6 @@ HWTEST_F(AnsNotificationBranchTest, UnregisterPushCallback_0200, Function | Medi { auto ansNotification = std::make_shared(); EXPECT_NE(ansNotification, nullptr); - MockGetAnsManagerProxy(true); - ansNotification->ansManagerProxy_ = new (std::nothrow) MockAnsManagerInterface(); ansNotification->UnregisterPushCallback(); } diff --git a/services/ans/src/notification_preferences.cpp b/services/ans/src/notification_preferences.cpp index 2907cda30..90812c771 100644 --- a/services/ans/src/notification_preferences.cpp +++ b/services/ans/src/notification_preferences.cpp @@ -72,9 +72,6 @@ ErrCode NotificationPreferences::AddNotificationSlots( for (auto slot : slots) { result = CheckSlotForCreateSlot(bundleOption, slot, preferencesInfo); if (result != ERR_OK) { - message.SlotType(static_cast(slot->GetType())); - message.Message("Check slot for create failed." + std::to_string(result)); - NotificationAnalyticsUtil::ReportModifyEvent(message); return result; } } diff --git a/services/ans/test/unittest/access_token_helper_test/access_token_helper_test.cpp b/services/ans/test/unittest/access_token_helper_test/access_token_helper_test.cpp index 7ab64e542..7cd61c13c 100644 --- a/services/ans/test/unittest/access_token_helper_test/access_token_helper_test.cpp +++ b/services/ans/test/unittest/access_token_helper_test/access_token_helper_test.cpp @@ -141,7 +141,7 @@ HWTEST_F(AccessTokenHelperTest, CheckPermission_00100, Function | SmallTest | Le { std::string permission = ""; MockGetTokenTypeFlag(ATokenTypeEnum::TOKEN_HAP); - ASSERT_EQ(stub_->CheckPermission(permission), false); + ASSERT_EQ(stub_->CheckPermission(permission), true); } } // 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 38c03b4fb..f26937a28 100644 --- a/services/ans/test/unittest/advanced_notification_service_test.cpp +++ b/services/ans/test/unittest/advanced_notification_service_test.cpp @@ -361,7 +361,7 @@ HWTEST_F(AdvancedNotificationServiceTest, AdvancedNotificationServiceTest_03500, int32_t id = 0; sptr bundleOption = new (std::nothrow) NotificationBundleOption(); auto ret = advancedNotificationService_->CancelAsBundleWithAgent(bundleOption, id); - ASSERT_EQ(ret, (int)ERR_ANS_NO_AGENT_SETTING); + ASSERT_EQ(ret, (int)ERR_ANS_NOTIFICATION_NOT_EXISTS); } /** diff --git a/services/ans/test/unittest/advanced_notification_slot_service_test.cpp b/services/ans/test/unittest/advanced_notification_slot_service_test.cpp index 129dfbc3c..04fe6a44a 100644 --- a/services/ans/test/unittest/advanced_notification_slot_service_test.cpp +++ b/services/ans/test/unittest/advanced_notification_slot_service_test.cpp @@ -506,7 +506,7 @@ HWTEST_F(AnsSlotServiceTest, GenerateSlotReminderMode_00001, Function | SmallTes sptr bundle = nullptr; sptr slot = new (std::nothrow) NotificationSlot(NotificationConstant::SlotType::SERVICE_REMINDER); advancedNotificationService_->GenerateSlotReminderMode(slot, bundle); - ASSERT_EQ(slot->GetReminderMode(), (int)0b111011); + ASSERT_EQ(slot->GetReminderMode(), (int)0b111111); } /** @@ -520,7 +520,7 @@ HWTEST_F(AnsSlotServiceTest, GenerateSlotReminderMode_00002, Function | SmallTes sptr bundle = nullptr; sptr slot = new (std::nothrow) NotificationSlot(NotificationConstant::SlotType::SERVICE_REMINDER); advancedNotificationService_->GenerateSlotReminderMode(slot, bundle, true); - ASSERT_EQ(slot->GetReminderMode(), (int)0b111011); + ASSERT_EQ(slot->GetReminderMode(), (int)0b111111); } /** diff --git a/services/ans/test/unittest/os_account_manager_helper_test.cpp b/services/ans/test/unittest/os_account_manager_helper_test.cpp index 092c5d746..a13607524 100644 --- a/services/ans/test/unittest/os_account_manager_helper_test.cpp +++ b/services/ans/test/unittest/os_account_manager_helper_test.cpp @@ -90,7 +90,7 @@ HWTEST_F(OsAccountManagerHelperTest, CheckUserExists_00200, Function | SmallTest /** * @tc.number : IsSystemAccount_0100 * @tc.name : IsSystemAccount_0100 - * @tc.desc : test IsSystemAccount function, 100 is true(100 <= userId <= 1099) + * @tc.desc : test IsSystemAccount function, 100 is true(100 <= userId <= 10736) */ HWTEST_F(OsAccountManagerHelperTest, IsSystemAccount_0100, Function | SmallTest | Level1) { @@ -101,18 +101,18 @@ HWTEST_F(OsAccountManagerHelperTest, IsSystemAccount_0100, Function | SmallTest /** * @tc.number : IsSystemAccount_0200 * @tc.name : IsSystemAccount_0200 - * @tc.desc : test IsSystemAccount function, 1100 is false(100 <= userId <= 1099) + * @tc.desc : test IsSystemAccount function, 1100 is false(100 <= userId <= 10736) */ HWTEST_F(OsAccountManagerHelperTest, IsSystemAccount_0200, Function | SmallTest | Level1) { - int32_t userId = 1100; + int32_t userId = 10737; ASSERT_EQ(false, OsAccountManagerHelper::IsSystemAccount(userId)); } /** * @tc.number : IsSystemAccount_0300 * @tc.name : IsSystemAccount_0300 - * @tc.desc : test IsSystemAccount function, 0 is false(100 <= userId <= 1099) + * @tc.desc : test IsSystemAccount function, 0 is false(100 <= userId <= 10736) */ HWTEST_F(OsAccountManagerHelperTest, IsSystemAccount_0300, Function | SmallTest | Level1) { @@ -123,11 +123,11 @@ HWTEST_F(OsAccountManagerHelperTest, IsSystemAccount_0300, Function | SmallTest /** * @tc.number : IsSystemAccount_0400 * @tc.name : IsSystemAccount_0400 - * @tc.desc : test IsSystemAccount function, 1099 is true(100 <= userId <= 1099) + * @tc.desc : test IsSystemAccount function, 1099 is true(100 <= userId <= 10736) */ HWTEST_F(OsAccountManagerHelperTest, IsSystemAccount_0400, Function | SmallTest | Level1) { - int32_t userId = 1099; + int32_t userId = 10736; ASSERT_EQ(true, OsAccountManagerHelper::IsSystemAccount(userId)); } } diff --git a/services/distributed/test/unittest/distributed_preferences_test.cpp b/services/distributed/test/unittest/distributed_preferences_test.cpp index 22504c93e..b2d15d12b 100644 --- a/services/distributed/test/unittest/distributed_preferences_test.cpp +++ b/services/distributed/test/unittest/distributed_preferences_test.cpp @@ -101,7 +101,7 @@ HWTEST_F(DistributedPreferencesTest, SetDistributedBundleEnable_00200, Function */ HWTEST_F(DistributedPreferencesTest, ClearDataInRestoreFactorySettings_00100, Function | SmallTest | Level1) { - EXPECT_EQ(distributedPreferences_->ClearDataInRestoreFactorySettings(), ERR_ANS_DISTRIBUTED_OPERATION_FAILED); + EXPECT_EQ(distributedPreferences_->ClearDataInRestoreFactorySettings(), ERR_OK); } /** diff --git a/services/distributed/test/unittest/distributed_screen_status_manager_test.cpp b/services/distributed/test/unittest/distributed_screen_status_manager_test.cpp index 448b497db..dc1eb3649 100644 --- a/services/distributed/test/unittest/distributed_screen_status_manager_test.cpp +++ b/services/distributed/test/unittest/distributed_screen_status_manager_test.cpp @@ -14,7 +14,7 @@ */ #include - +#include "ans_inner_errors.h" #include "gtest/gtest.h" #define private public #include "distributed_screen_status_manager.h" @@ -52,7 +52,8 @@ HWTEST_F(DistributedScreenStatusManagerTest, CheckRemoteDevicesIsUsing_00100, Fu { bool isUsing = true; - EXPECT_EQ(distributedScreenStatusManager_->CheckRemoteDevicesIsUsing(isUsing), ERR_OK); + EXPECT_EQ(distributedScreenStatusManager_->CheckRemoteDevicesIsUsing(isUsing), + ERR_ANS_DISTRIBUTED_OPERATION_FAILED); } /** @@ -64,7 +65,7 @@ HWTEST_F(DistributedScreenStatusManagerTest, SetLocalScreenStatus_00100, Functio { bool screenOn = false; - EXPECT_EQ(distributedScreenStatusManager_->SetLocalScreenStatus(screenOn), ERR_OK); + EXPECT_EQ(distributedScreenStatusManager_->SetLocalScreenStatus(screenOn), ERR_ANS_DISTRIBUTED_OPERATION_FAILED); } } // namespace Notification } // namespace OHOS \ No newline at end of file diff --git a/tools/test/unittest/dump/notification_shell_command_dump_test.cpp b/tools/test/unittest/dump/notification_shell_command_dump_test.cpp index 1c626f469..76db6405c 100644 --- a/tools/test/unittest/dump/notification_shell_command_dump_test.cpp +++ b/tools/test/unittest/dump/notification_shell_command_dump_test.cpp @@ -123,10 +123,6 @@ static char g_helpMsg[] = " --user-id, -u dump the info filter by the specified userId\n" " --receiver, -r dump the info filter by the specified receiver userId\n"; -static char g_bundleName[] = "example"; -static char g_commandActive[] = "active"; -static char g_commandRecent[] = "recent"; - class AnmManagerDumpTest : public testing::Test { public: static void SetUpTestCase(); @@ -213,7 +209,7 @@ HWTEST_F(AnmManagerDumpTest, Anm_Notification_Shell_Dump_0200, Function | Medium cmd.ExecCommand(); - EXPECT_EQ(stubPtr_->GetCmd(), g_commandActive); + EXPECT_EQ(stubPtr_->GetCmd(), ""); } /** @@ -235,7 +231,7 @@ HWTEST_F(AnmManagerDumpTest, Anm_Notification_Shell_Dump_0300, Function | Medium cmd.ExecCommand(); - EXPECT_EQ(stubPtr_->GetCmd(), g_commandRecent); + EXPECT_EQ(stubPtr_->GetCmd(), ""); } /** @@ -280,8 +276,8 @@ HWTEST_F(AnmManagerDumpTest, Anm_Notification_Shell_Dump_0500, Function | Medium cmd.ExecCommand(); - EXPECT_EQ(stubPtr_->GetCmd(), g_commandActive); - EXPECT_EQ(stubPtr_->GetBundle(), g_bundleName); + EXPECT_EQ(stubPtr_->GetCmd(), ""); + EXPECT_EQ(stubPtr_->GetBundle(), ""); } /** @@ -326,8 +322,8 @@ HWTEST_F(AnmManagerDumpTest, Anm_Notification_Shell_Dump_0700, Function | Medium cmd.ExecCommand(); - EXPECT_EQ(stubPtr_->GetCmd(), g_commandRecent); - EXPECT_EQ(stubPtr_->GetBundle(), g_bundleName); + EXPECT_EQ(stubPtr_->GetCmd(), ""); + EXPECT_EQ(stubPtr_->GetBundle(), ""); } /** @@ -393,8 +389,8 @@ HWTEST_F(AnmManagerDumpTest, Anm_Notification_Shell_Dump_1000, Function | Medium cmd.ExecCommand(); - EXPECT_EQ(stubPtr_->GetCmd(), g_commandActive); - EXPECT_EQ(stubPtr_->GetUserId(), 33); + EXPECT_EQ(stubPtr_->GetCmd(), ""); + EXPECT_EQ(stubPtr_->GetUserId(), 0); } /** @@ -418,8 +414,8 @@ HWTEST_F(AnmManagerDumpTest, Anm_Notification_Shell_Dump_1100, Function | Medium cmd.ExecCommand(); - EXPECT_EQ(stubPtr_->GetCmd(), g_commandRecent); - EXPECT_EQ(stubPtr_->GetUserId(), 33); + EXPECT_EQ(stubPtr_->GetCmd(), ""); + EXPECT_EQ(stubPtr_->GetUserId(), 0); } /** -- Gitee From 250f16d2472b652da651fb1c95cc23fbee74ef5b Mon Sep 17 00:00:00 2001 From: xdongs Date: Tue, 20 Aug 2024 18:24:18 +0800 Subject: [PATCH 011/167] =?UTF-8?q?=E5=85=AC=E7=A4=BA=20Signed-off-by:=20x?= =?UTF-8?q?dongs=20?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../enable_notification_dialog/publicity.xml | 28 +++++++++---------- 1 file changed, 14 insertions(+), 14 deletions(-) diff --git a/services/dialog_ui/enable_notification_dialog/publicity.xml b/services/dialog_ui/enable_notification_dialog/publicity.xml index ba2e4eea9..e65a1ccf4 100644 --- a/services/dialog_ui/enable_notification_dialog/publicity.xml +++ b/services/dialog_ui/enable_notification_dialog/publicity.xml @@ -1,18 +1,18 @@ -/* - * Copyright (c) 2023 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ + \ No newline at end of file -- Gitee From 073daa24a20ab649dc8914e295ed022d29b690ad Mon Sep 17 00:00:00 2001 From: xdongs Date: Mon, 26 Aug 2024 11:10:29 +0800 Subject: [PATCH 012/167] =?UTF-8?q?=E5=BA=94=E7=94=A8=E5=90=8D=E7=A7=B0?= =?UTF-8?q?=E8=B7=9F=E9=9A=8F=E7=B3=BB=E7=BB=9F=E8=AF=AD=E8=A8=80=E5=8F=98?= =?UTF-8?q?=E5=8C=96?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: xdongs --- .../AppScope/app.json | 4 +-- .../NotificationServiceExtAbility.ts | 25 ++++++++++++++++++- .../src/main/ets/pages/notificationDialog.ets | 2 +- .../src/main/resources/ug/element/string.json | 2 +- 4 files changed, 28 insertions(+), 5 deletions(-) diff --git a/services/dialog_ui/enable_notification_dialog/AppScope/app.json b/services/dialog_ui/enable_notification_dialog/AppScope/app.json index b99cc6593..e343d1803 100644 --- a/services/dialog_ui/enable_notification_dialog/AppScope/app.json +++ b/services/dialog_ui/enable_notification_dialog/AppScope/app.json @@ -2,8 +2,8 @@ "app": { "bundleName": "com.ohos.notificationdialog", "vendor": "example", - "versionCode": 1000008, - "versionName": "1.0.8", + "versionCode": 1000010, + "versionName": "1.1.0", "icon": "$media:app_icon", "label": "$string:app_name", "distributedNotificationEnabled": true, diff --git a/services/dialog_ui/enable_notification_dialog/entry/src/main/ets/ServiceExtAbility/NotificationServiceExtAbility.ts b/services/dialog_ui/enable_notification_dialog/entry/src/main/ets/ServiceExtAbility/NotificationServiceExtAbility.ts index 64f1bfba4..904bbe33d 100644 --- a/services/dialog_ui/enable_notification_dialog/entry/src/main/ets/ServiceExtAbility/NotificationServiceExtAbility.ts +++ b/services/dialog_ui/enable_notification_dialog/entry/src/main/ets/ServiceExtAbility/NotificationServiceExtAbility.ts @@ -28,6 +28,13 @@ import StartOptions from '@ohos.app.ability.StartOptions'; const TAG = 'NotificationDialog_Service '; +const UPDATE_INIT = -1; +const UPDATE_NUM = 1; +const UPDATE_BOUNDARY = 100; + + +let systemLanguage: string; + const enableNotificationDialogDestroyedEvent = { eventId: 1, priority: emitter.EventPriority.LOW @@ -202,10 +209,26 @@ export class EnableNotificationDialog { class NotificationDialogServiceExtensionAbility extends UIExtensionAbility { + onConfigurationUpdate(newConfig) { + console.log(TAG, 'onConfigurationUpdate'); + if (systemLanguage !== newConfig.language) { + console.log(TAG, `onConfigurationUpdate newConfig is ${JSON.stringify(newConfig)}`); + systemLanguage = newConfig.language; + let isUpdate:number = AppStorage.get('isUpdate'); + if (isUpdate === undefined || isUpdate > UPDATE_BOUNDARY) { + AppStorage.setOrCreate('isUpdate', UPDATE_NUM); + } else { + AppStorage.setOrCreate('isUpdate', ++isUpdate); + } + } + } + + onCreate() { console.log(TAG, `UIExtAbility onCreate`); AppStorage.setOrCreate('context', this.context); - + AppStorage.setOrCreate('isUpdate', UPDATE_INIT); + systemLanguage = this.context.config.language; } async onSessionCreate(want: Want, session: UIExtensionContentSession) { diff --git a/services/dialog_ui/enable_notification_dialog/entry/src/main/ets/pages/notificationDialog.ets b/services/dialog_ui/enable_notification_dialog/entry/src/main/ets/pages/notificationDialog.ets index 55c303f5d..179a29dfc 100644 --- a/services/dialog_ui/enable_notification_dialog/entry/src/main/ets/pages/notificationDialog.ets +++ b/services/dialog_ui/enable_notification_dialog/entry/src/main/ets/pages/notificationDialog.ets @@ -61,7 +61,7 @@ let storage = LocalStorage.getShared(); @Entry(storage) @Component struct NotificationDialogPage { - @State isUpdate: number = -1; + @StorageLink('isUpdate') isUpdate: number = -1; privacyDialogController: CustomDialogController = new CustomDialogController({ builder: PermissionDialog({ isUpdate: $isUpdate }), diff --git a/services/dialog_ui/enable_notification_dialog/entry/src/main/resources/ug/element/string.json b/services/dialog_ui/enable_notification_dialog/entry/src/main/resources/ug/element/string.json index 221c6c600..2bc9b3ed1 100644 --- a/services/dialog_ui/enable_notification_dialog/entry/src/main/resources/ug/element/string.json +++ b/services/dialog_ui/enable_notification_dialog/entry/src/main/resources/ug/element/string.json @@ -26,7 +26,7 @@ }, { "name": "group_label_notification", - "value": "\\u200f«%s» نىڭ ئۇقتۇرۇش يوللىشىغا رۇخسەتمۇ؟" + "value": "\u200f«%s» نىڭ ئۇقتۇرۇش يوللىشىغا رۇخسەتمۇ؟" } ] } -- Gitee From 11646457979e0e1390241b3b03a12665458ee7f7 Mon Sep 17 00:00:00 2001 From: xdongs Date: Wed, 21 Aug 2024 14:58:23 +0800 Subject: [PATCH 013/167] =?UTF-8?q?=E6=B7=B1=E8=89=B2=E6=A8=A1=E5=BC=8F=20?= =?UTF-8?q?Signed-off-by:=20xdongs=20?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../src/main/ets/pages/notificationDialog.ets | 16 +++++++-------- .../main/resources/base/element/color.json | 16 +++++++++++++++ .../main/resources/dark/element/color.json | 20 +++++++++++++++++++ 3 files changed, 44 insertions(+), 8 deletions(-) create mode 100644 services/dialog_ui/enable_notification_dialog/entry/src/main/resources/dark/element/color.json diff --git a/services/dialog_ui/enable_notification_dialog/entry/src/main/ets/pages/notificationDialog.ets b/services/dialog_ui/enable_notification_dialog/entry/src/main/ets/pages/notificationDialog.ets index 55c303f5d..86243fc5f 100644 --- a/services/dialog_ui/enable_notification_dialog/entry/src/main/ets/pages/notificationDialog.ets +++ b/services/dialog_ui/enable_notification_dialog/entry/src/main/ets/pages/notificationDialog.ets @@ -35,8 +35,8 @@ const bottomPopoverTypes = ['default', 'phone']; let storage = LocalStorage.getShared(); @Extend(Button) function rightCustomizeButton() { - .backgroundColor($r('sys.color.ohos_id_color_dialog_bg')) - .fontColor($r('sys.color.font_emphasize')) + .backgroundColor($r('app.color.dialog_bg')) + .fontColor($r('app.color.button_text')) .fontSize(Constants.TEXT_MIDDLE_FONT_SIZE) .fontWeight(FontWeight.Medium) .height(Constants.BUTTON_HEIGHT) @@ -47,8 +47,8 @@ let storage = LocalStorage.getShared(); } @Extend(Button) function leftCustomizeButton() { - .backgroundColor($r('sys.color.ohos_id_color_dialog_bg')) - .fontColor($r('sys.color.font_emphasize')) + .backgroundColor($r('app.color.dialog_bg')) + .fontColor($r('app.color.button_text')) .fontSize(Constants.TEXT_MIDDLE_FONT_SIZE) .fontWeight(FontWeight.Medium) .height(Constants.BUTTON_HEIGHT) @@ -119,7 +119,7 @@ struct PermissionDialog { Span(getContext(this).resourceManager.getStringSync(permission.label.id).replace('%s', this.appName)) } .fontSize($r('sys.float.ohos_id_text_size_headline8')) - .fontColor($r('sys.color.ohos_id_color_text_primary')) + .fontColor($r('app.color.text_primary')) .fontWeight(FontWeight.Bold) .lineHeight(Constants.DIALOG_REQ_LINE_HEIGHT) .margin({ @@ -138,7 +138,7 @@ struct PermissionDialog { } .fontSize(Constants.DIALOG_DESP_FONT_SIZE) .fontWeight(FontWeight.Regular) - .fontColor($r('sys.color.ohos_id_color_text_primary')) + .fontColor($r('app.color.text_primary')) .lineHeight(Constants.DIALOG_DESP_LINE_HEIGHT) .margin({ top: Constants.DIALOG_DESP_MARGIN_TOP, @@ -159,7 +159,7 @@ struct PermissionDialog { }) .leftCustomizeButton() Divider() - .color($r('sys.color.comp_divider')) + .color($r('app.color.comp_divider')) .vertical(true) .height(Constants.DIVIDER_HEIGHT) .strokeWidth(Constants.DIVIDER_WIDTH) @@ -172,7 +172,7 @@ struct PermissionDialog { .margin({ left: Constants.BUTTON_MARGIN_LEFT, right: Constants.BUTTON_MARGIN_RIGHT }) } } - .backgroundColor($r('sys.color.ohos_id_color_dialog_bg')) + .backgroundColor($r('app.color.dialog_bg')) .borderRadius(Constants.DIALOG_PRIVACY_BORDER_RADIUS) .width(Constants.FULL_WIDTH) .padding({ bottom: Constants.DIALOG_PADDING_BOTTOM }) diff --git a/services/dialog_ui/enable_notification_dialog/entry/src/main/resources/base/element/color.json b/services/dialog_ui/enable_notification_dialog/entry/src/main/resources/base/element/color.json index 95f6870e2..33aaa77dc 100644 --- a/services/dialog_ui/enable_notification_dialog/entry/src/main/resources/base/element/color.json +++ b/services/dialog_ui/enable_notification_dialog/entry/src/main/resources/base/element/color.json @@ -15,6 +15,22 @@ { "name": "button_color", "value": "#007DFF" + }, + { + "name": "text_primary", + "value": "#E5000000" + }, + { + "name": "comp_divider", + "value": "#33000000" + }, + { + "name": "dialog_bg", + "value": "#FFFFFF" + }, + { + "name": "button_text", + "value": "#0A59F7" } ] } \ No newline at end of file diff --git a/services/dialog_ui/enable_notification_dialog/entry/src/main/resources/dark/element/color.json b/services/dialog_ui/enable_notification_dialog/entry/src/main/resources/dark/element/color.json new file mode 100644 index 000000000..d5a8a1436 --- /dev/null +++ b/services/dialog_ui/enable_notification_dialog/entry/src/main/resources/dark/element/color.json @@ -0,0 +1,20 @@ +{ + "color": [ + { + "name": "text_primary", + "value": "#DBFFFFFF" + }, + { + "name": "comp_divider", + "value": "#33FFFFFF" + }, + { + "name": "dialog_bg", + "value": "#202224" + }, + { + "name": "button_text", + "value": "#5291FF" + } + ] + } \ No newline at end of file -- Gitee From 0541cc9390d94c5afc635d83f10b489f9944a01a Mon Sep 17 00:00:00 2001 From: xdongs Date: Tue, 20 Aug 2024 17:32:07 +0800 Subject: [PATCH 014/167] liveview Signed-off-by: xdongs --- frameworks/js/napi/src/subscribe.cpp | 11 ++++++----- services/ans/include/notification_trust_list.h | 2 ++ .../ans/src/advanced_notification_slot_service.cpp | 5 ++++- ...otification_local_live_view_subscriber_manager.cpp | 2 +- services/ans/src/notification_subscriber_manager.cpp | 2 +- services/ans/src/notification_trust_list.cpp | 9 +++++++++ 6 files changed, 23 insertions(+), 8 deletions(-) diff --git a/frameworks/js/napi/src/subscribe.cpp b/frameworks/js/napi/src/subscribe.cpp index 043c7549a..696116d17 100644 --- a/frameworks/js/napi/src/subscribe.cpp +++ b/frameworks/js/napi/src/subscribe.cpp @@ -207,9 +207,8 @@ void SubscriberInstance::OnCanceled(const std::shared_ptrGetNotificationRequest().GetNotificationId()); - ANS_LOGI("OnCanceled sortingMap size = %{public}zu", sortingMap->GetKey().size()); - ANS_LOGI("OnCanceled deleteReason = %{public}d", deleteReason); + ANS_LOGI("OnCanceled NotificationKey = %{public}s. sortingMap size = %{public}zu. deleteReason = %{public}d", + request->GetKey().c_str(),sortingMap->GetKey().size(), deleteReason); NotificationReceiveDataWorker *dataWorker = new (std::nothrow) NotificationReceiveDataWorker(); if (dataWorker == nullptr) { @@ -377,8 +376,10 @@ void SubscriberInstance::OnConsumed(const std::shared_ptrGetKey().c_str(), sortingMap->GetKey().size()); + auto notificationFlags = request->GetNotificationRequest().GetFlags(); + ANS_LOGI("OnConsumed Notification key = %{public}s, sortingMap size = %{public}zu, notificationFlag = %{public}s", + request->GetKey().c_str(), sortingMap->GetKey().size(), + notificationFlags == nullptr ? "null" : notificationFlags->Dump().c_str()); ANS_LOGD("OnConsumed Notification info is %{public}s", request->GetNotificationRequest().Dump().c_str()); NotificationReceiveDataWorker *dataWorker = new (std::nothrow) NotificationReceiveDataWorker(); diff --git a/services/ans/include/notification_trust_list.h b/services/ans/include/notification_trust_list.h index f7b1083c0..12ab1d1ee 100644 --- a/services/ans/include/notification_trust_list.h +++ b/services/ans/include/notification_trust_list.h @@ -34,9 +34,11 @@ public: void GetCcmPrivilegesConfig(); + bool IsLiveViewTrtust(const std::string bundleName); bool IsSlotFlagsTrustlistAsBundle(const sptr &bundleOption); bool IsReminderTrustList(const std::string& bundleName); private: + std::set liveViewTrustlist_; std::set reminderTrustlist_; std::set notificationSlotFlagsTrustlist_; constexpr static inline const uint32_t PRIVILEGES_CONFIG_MIN_LEN = 2; diff --git a/services/ans/src/advanced_notification_slot_service.cpp b/services/ans/src/advanced_notification_slot_service.cpp index d90d2828d..2f972b974 100644 --- a/services/ans/src/advanced_notification_slot_service.cpp +++ b/services/ans/src/advanced_notification_slot_service.cpp @@ -36,6 +36,7 @@ #include "advanced_notification_inline.cpp" #include "notification_extension_wrapper.h" #include "notification_analytics_util.h" +#include "notification_trust_list.h" namespace OHOS { namespace Notification { @@ -474,7 +475,9 @@ ErrCode AdvancedNotificationService::AssignValidNotificationSlot(const std::shar if (result == ERR_OK) { if (slot != nullptr && (bundleOption->GetBundleName() == CALL_UI_BUNDLE || slot->GetEnable() || - (record->request->IsAgentNotification() && record->request->IsSystemLiveView()))) { + (record->request->GetAgentBundle() != nullptr && record->request->IsSystemLiveView()) || + (slot->GetType() == NotificationConstant::SlotType::LIVE_VIEW && + DelayedSingleton::GetInstance()->IsLiveViewTrtust(bundleOption->GetBundleName())))) { record->slot = slot; } else { result = ERR_ANS_PREFERENCES_NOTIFICATION_SLOT_ENABLED; diff --git a/services/ans/src/notification_local_live_view_subscriber_manager.cpp b/services/ans/src/notification_local_live_view_subscriber_manager.cpp index d345f091d..12640235f 100644 --- a/services/ans/src/notification_local_live_view_subscriber_manager.cpp +++ b/services/ans/src/notification_local_live_view_subscriber_manager.cpp @@ -156,7 +156,7 @@ void NotificationLocalLiveViewSubscriberManager::OnRemoteDied(const wptr record = FindSubscriberRecord(object); if (record != nullptr) { - ANS_LOGW("subscriber removed."); + ANS_LOGI("subscriber removed . userId = %{public}d", record->userId); AdvancedNotificationService::GetInstance()->RemoveSystemLiveViewNotifications( record->bundleName, record->userId); buttonRecordList_.remove(record); diff --git a/services/ans/src/notification_subscriber_manager.cpp b/services/ans/src/notification_subscriber_manager.cpp index 6550c583b..b5d7d25e3 100644 --- a/services/ans/src/notification_subscriber_manager.cpp +++ b/services/ans/src/notification_subscriber_manager.cpp @@ -280,7 +280,7 @@ void NotificationSubscriberManager::OnRemoteDied(const wptr &obje std::shared_ptr record = FindSubscriberRecord(object); if (record != nullptr) { auto subscriberUid = record->subscriberUid; - ANS_LOGW("subscriber removed."); + ANS_LOGI("subscriber removed . subscriberUid = %{public}d", record->subscriberUid); subscriberRecordList_.remove(record); AdvancedNotificationService::GetInstance()->RemoveSystemLiveViewNotificationsOfSa(record->subscriberUid); } diff --git a/services/ans/src/notification_trust_list.cpp b/services/ans/src/notification_trust_list.cpp index ce1b0c136..3d4193d09 100644 --- a/services/ans/src/notification_trust_list.cpp +++ b/services/ans/src/notification_trust_list.cpp @@ -17,6 +17,7 @@ namespace OHOS { namespace Notification { +constexpr static uint32_t LIVE_VIEW_INDEX = 0; constexpr static uint32_t REMINDER_LIST_INDEX = 2; NotificationTrustList::NotificationTrustList() { @@ -45,6 +46,9 @@ void NotificationTrustList::GetCcmPrivilegesConfig() } for (auto &affect : affects.items()) { std::string affects_value = affect.value().get(); + if (affects_value[LIVE_VIEW_INDEX] != PRIVILEGES_BANNER_NOT_ALLOW) { + liveViewTrustlist_.insert(affect.key()); + } if (affects_value.length() >= PRIVILEGES_CONFIG_MIN_LEN && affects_value[PRIVILEGES_BANNER_INDEX] != PRIVILEGES_BANNER_NOT_ALLOW) { notificationSlotFlagsTrustlist_.insert(affect.key()); @@ -58,6 +62,11 @@ void NotificationTrustList::GetCcmPrivilegesConfig() return; } +bool NotificationTrustList::IsLiveViewTrtust(const std::string bundleName) +{ + return liveViewTrustlist_.count(bundleName); +} + bool NotificationTrustList::IsReminderTrustList(const std::string& bundleName) { return reminderTrustlist_.count(bundleName); -- Gitee From 8c215cd3d47d45fdc2404e9fa70ba986c7c61abe Mon Sep 17 00:00:00 2001 From: baozeyu Date: Thu, 22 Aug 2024 15:02:25 +0800 Subject: [PATCH 015/167] =?UTF-8?q?cherry=20pick=20f18cf17=20from=20https:?= =?UTF-8?q?//gitee.com/baozeyu/notification=5Fdistributed=5Fnotification?= =?UTF-8?q?=5Fservice/pulls/2049=20=E4=BC=98=E5=8C=96=E7=94=A8=E6=88=B7?= =?UTF-8?q?=E5=88=87=E6=8D=A2=E6=9F=A5=E8=AF=A2=E7=94=A8=E6=88=B7=E9=80=BB?= =?UTF-8?q?=E8=BE=91?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: baozeyu Change-Id: I0d177ce6f529a251de630249fc07f777d5d29654 --- frameworks/core/include/ans_notification.h | 2 +- interfaces/inner_api/notification_helper.h | 2 +- .../ans/include/advanced_notification_service.h | 5 +++-- services/ans/include/notification_preferences.h | 2 +- .../include/notification_preferences_database.h | 2 +- .../advanced_notification_live_view_service.cpp | 17 ++++++++++++----- .../advanced_notification_publish_service.cpp | 1 + .../ans/src/advanced_notification_service.cpp | 3 ++- services/ans/src/notification_preferences.cpp | 6 +++--- .../src/notification_preferences_database.cpp | 9 +++++++-- services/ans/src/system_event_observer.cpp | 11 ++++++++--- 11 files changed, 40 insertions(+), 20 deletions(-) diff --git a/frameworks/core/include/ans_notification.h b/frameworks/core/include/ans_notification.h index 691c08642..1e2b6a64e 100644 --- a/frameworks/core/include/ans_notification.h +++ b/frameworks/core/include/ans_notification.h @@ -168,7 +168,7 @@ public: /** * @brief Cancels all the published notifications. - * @note To cancel a specified notification, see CancelNotification(int_32). + * @note To cancel a specified notification, see CancelNotification(int32_t). * * @return Returns cancel all notifications result. */ diff --git a/interfaces/inner_api/notification_helper.h b/interfaces/inner_api/notification_helper.h index 6838448b2..b1345029b 100644 --- a/interfaces/inner_api/notification_helper.h +++ b/interfaces/inner_api/notification_helper.h @@ -169,7 +169,7 @@ public: /** * @brief Cancels all the published notifications. * - * @note To cancel a specified notification, see CancelNotification(int_32). + * @note To cancel a specified notification, see CancelNotification(int32_t). * @return Returns cancel all notifications result. */ static ErrCode CancelAllNotifications(); diff --git a/services/ans/include/advanced_notification_service.h b/services/ans/include/advanced_notification_service.h index 864046222..c7b509233 100644 --- a/services/ans/include/advanced_notification_service.h +++ b/services/ans/include/advanced_notification_service.h @@ -1100,7 +1100,7 @@ public: /** * @brief Recover LiveView from DB. */ - void RecoverLiveViewFromDb(); + void RecoverLiveViewFromDb(int32_t userId = -1); #ifdef NOTIFICATION_SMART_REMINDER_SUPPORTED /** @@ -1286,7 +1286,8 @@ private: std::shared_ptr record); static int32_t SetNotificationRequestToDb(const NotificationRequestDb &requestDb); static int32_t GetNotificationRequestFromDb(const std::string &key, NotificationRequestDb &requestDb); - static int32_t GetBatchNotificationRequestsFromDb(std::vector &requests); + static int32_t GetBatchNotificationRequestsFromDb(std::vector &requests, + int32_t userId = -1); static int32_t DeleteNotificationRequestFromDb(const std::string &key, const int32_t userId); void CancelTimer(uint64_t timerId); ErrCode UpdateNotificationTimerInfo(const std::shared_ptr &record); diff --git a/services/ans/include/notification_preferences.h b/services/ans/include/notification_preferences.h index 2f75ed6e2..1ffce83c8 100644 --- a/services/ans/include/notification_preferences.h +++ b/services/ans/include/notification_preferences.h @@ -359,7 +359,7 @@ public: */ bool GetBundleSoundPermission(bool &allPackage, std::set &bundleNames); - void InitSettingFromDisturbDB(); + void InitSettingFromDisturbDB(int32_t userId = -1); void RemoveSettings(int32_t userId); void RemoveAnsBundleDbInfo(const sptr &bundleOption); void RemoveEnabledDbByBundle(const sptr &bundleOption); diff --git a/services/ans/include/notification_preferences_database.h b/services/ans/include/notification_preferences_database.h index f4ecb94f3..aafa057b2 100644 --- a/services/ans/include/notification_preferences_database.h +++ b/services/ans/include/notification_preferences_database.h @@ -161,7 +161,7 @@ public: * @param info Indicates notification info. * @return Return true on success, false on failure. */ - bool ParseFromDisturbeDB(NotificationPreferencesInfo &info); + bool ParseFromDisturbeDB(NotificationPreferencesInfo &info, int32_t userId = -1); /** * @brief Delete all data from disturbe DB. diff --git a/services/ans/src/advanced_notification_live_view_service.cpp b/services/ans/src/advanced_notification_live_view_service.cpp index e5d7810c0..0f4d0d40e 100644 --- a/services/ans/src/advanced_notification_live_view_service.cpp +++ b/services/ans/src/advanced_notification_live_view_service.cpp @@ -37,12 +37,12 @@ namespace OHOS { namespace Notification { const std::string LOCK_SCREEN_PICTURE_TAG = "lock_screen_picture"; const std::string PROGRESS_VALUE = "progressValue"; -void AdvancedNotificationService::RecoverLiveViewFromDb() +void AdvancedNotificationService::RecoverLiveViewFromDb(int32_t userId) { - ANS_LOGI("Start recover live view from db."); + ANS_LOGI("Start recover live view from db. userId:%{public}d", userId); std::vector requestsdb; - if (GetBatchNotificationRequestsFromDb(requestsdb) != ERR_OK) { + if (GetBatchNotificationRequestsFromDb(requestsdb, userId) != ERR_OK) { ANS_LOGE("Get liveView from db failed."); return; } @@ -290,11 +290,18 @@ int32_t AdvancedNotificationService::GetNotificationRequestFromDb( return ERR_OK; } -int32_t AdvancedNotificationService::GetBatchNotificationRequestsFromDb(std::vector &requests) +int32_t AdvancedNotificationService::GetBatchNotificationRequestsFromDb( + std::vector &requests, int32_t userId) { std::unordered_map dbRecords; std::vector userIds; - int32_t ret = OsAccountManagerHelper::GetInstance().GetAllActiveOsAccount(userIds); + int ret = ERR_OK; + if (userId == -1) { + ret = OsAccountManagerHelper::GetInstance().GetAllActiveOsAccount(userIds); + } else { + userIds.push_back(userId); + } + if (ret != ERR_OK) { ANS_LOGE("Get all os account failed."); return ret; diff --git a/services/ans/src/advanced_notification_publish_service.cpp b/services/ans/src/advanced_notification_publish_service.cpp index ea8d6c9cc..ebf7a1c5e 100644 --- a/services/ans/src/advanced_notification_publish_service.cpp +++ b/services/ans/src/advanced_notification_publish_service.cpp @@ -789,6 +789,7 @@ ErrCode AdvancedNotificationService::RequestEnableNotification(const std::string if (!CreateDialogManager()) { return ERROR_INTERNAL_ERROR; } + result = dialogManager_->RequestEnableNotificationDailog(bundleOption, callback, callerToken); if (result == ERR_OK) { result = ERR_ANS_DIALOG_POP_SUCCEEDED; diff --git a/services/ans/src/advanced_notification_service.cpp b/services/ans/src/advanced_notification_service.cpp index 5da77206f..b9ca6c3dc 100644 --- a/services/ans/src/advanced_notification_service.cpp +++ b/services/ans/src/advanced_notification_service.cpp @@ -301,7 +301,8 @@ AdvancedNotificationService::AdvancedNotificationService() std::bind(&AdvancedNotificationService::OnSubscriberAdd, this, std::placeholders::_1); NotificationSubscriberManager::GetInstance()->RegisterOnSubscriberAddCallback(callback); - std::function recoverFunc = std::bind(&AdvancedNotificationService::RecoverLiveViewFromDb, this); + std::function recoverFunc = std::bind( + &AdvancedNotificationService::RecoverLiveViewFromDb, this, SUBSCRIBE_USER_INIT); notificationSvrQueue_->submit(recoverFunc); ISystemEvent iSystemEvent = { diff --git a/services/ans/src/notification_preferences.cpp b/services/ans/src/notification_preferences.cpp index 2907cda30..d73ed36ab 100644 --- a/services/ans/src/notification_preferences.cpp +++ b/services/ans/src/notification_preferences.cpp @@ -926,12 +926,12 @@ ErrCode NotificationPreferences::IsSmartReminderEnabled(const std::string &devic return storeDBResult ? ERR_OK : ERR_ANS_PREFERENCES_NOTIFICATION_DB_OPERATION_FAILED; } -void NotificationPreferences::InitSettingFromDisturbDB() +void NotificationPreferences::InitSettingFromDisturbDB(int32_t userId) { - ANS_LOGD("%{public}s", __FUNCTION__); + ANS_LOGI("%{public}s userId is %{public}d", __FUNCTION__, userId); std::lock_guard lock(preferenceMutex_); if (preferncesDB_ != nullptr) { - preferncesDB_->ParseFromDisturbeDB(preferencesInfo_); + preferncesDB_->ParseFromDisturbeDB(preferencesInfo_, userId); } } diff --git a/services/ans/src/notification_preferences_database.cpp b/services/ans/src/notification_preferences_database.cpp index e80541632..1b5629041 100644 --- a/services/ans/src/notification_preferences_database.cpp +++ b/services/ans/src/notification_preferences_database.cpp @@ -644,7 +644,7 @@ bool NotificationPreferencesDatabase::PutBundlePropertyValueToDisturbeDB( return true; } -bool NotificationPreferencesDatabase::ParseFromDisturbeDB(NotificationPreferencesInfo &info) +bool NotificationPreferencesDatabase::ParseFromDisturbeDB(NotificationPreferencesInfo &info, int32_t userId) { ANS_LOGD("%{public}s", __FUNCTION__); if (!CheckRdbStore()) { @@ -652,7 +652,12 @@ bool NotificationPreferencesDatabase::ParseFromDisturbeDB(NotificationPreference return false; } std::vector activeUserId; - OsAccountManagerHelper::GetInstance().GetAllActiveOsAccount(activeUserId); + if (userId == -1) { + OsAccountManagerHelper::GetInstance().GetAllActiveOsAccount(activeUserId); + } else { + activeUserId.push_back(userId); + } + for (auto iter : activeUserId) { GetDoNotDisturbType(info, iter); GetDoNotDisturbBeginDate(info, iter); diff --git a/services/ans/src/system_event_observer.cpp b/services/ans/src/system_event_observer.cpp index f382a5891..973fb914b 100644 --- a/services/ans/src/system_event_observer.cpp +++ b/services/ans/src/system_event_observer.cpp @@ -92,11 +92,16 @@ void SystemEventObserver::OnReceiveEvent(const EventFwk::CommonEventData &data) } #endif } else if (action == EventFwk::CommonEventSupport::COMMON_EVENT_USER_SWITCHED) { - NotificationPreferences::GetInstance()->InitSettingFromDisturbDB(); - AdvancedNotificationService::GetInstance()->RecoverLiveViewFromDb(); + int32_t userId = data.GetCode(); + if (userId <= SUBSCRIBE_USER_INIT) { + ANS_LOGE("Illegal userId, userId[%{public}d].", userId); + return; + } + NotificationPreferences::GetInstance()->InitSettingFromDisturbDB(userId); + AdvancedNotificationService::GetInstance()->RecoverLiveViewFromDb(userId); } else if (action == EventFwk::CommonEventSupport::COMMON_EVENT_USER_REMOVED) { int32_t userId = data.GetCode(); - if (userId <= DEFAULT_USER_ID) { + if (userId <= SUBSCRIBE_USER_INIT) { ANS_LOGE("Illegal userId, userId[%{public}d].", userId); return; } -- Gitee From 090729db6e534e1d35f96b4bbac1207bbe9d8e81 Mon Sep 17 00:00:00 2001 From: xdongs2009 Date: Mon, 26 Aug 2024 07:00:21 +0000 Subject: [PATCH 016/167] update frameworks/js/napi/src/subscribe.cpp. code check Signed-off-by: xdongs2009 --- frameworks/js/napi/src/subscribe.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/frameworks/js/napi/src/subscribe.cpp b/frameworks/js/napi/src/subscribe.cpp index 696116d17..58047c256 100644 --- a/frameworks/js/napi/src/subscribe.cpp +++ b/frameworks/js/napi/src/subscribe.cpp @@ -208,7 +208,7 @@ void SubscriberInstance::OnCanceled(const std::shared_ptrGetKey().c_str(),sortingMap->GetKey().size(), deleteReason); + request->GetKey().c_str(), sortingMap->GetKey().size(), deleteReason); NotificationReceiveDataWorker *dataWorker = new (std::nothrow) NotificationReceiveDataWorker(); if (dataWorker == nullptr) { -- Gitee From 8475ce0c6896a07f5925a3df2fa11cc1cfeaf4f0 Mon Sep 17 00:00:00 2001 From: wufarong1 Date: Wed, 21 Aug 2024 11:27:08 +0800 Subject: [PATCH 017/167] =?UTF-8?q?ANS/CES=E4=BD=BF=E7=94=A8JsonCpp?= =?UTF-8?q?=E8=BF=9B=E8=A1=8C=E5=AD=97=E7=AC=A6=E4=B8=B2=E5=BA=8F=E5=88=97?= =?UTF-8?q?=E5=8C=96=E4=B8=8E=E5=8F=8D=E5=BA=8F=E5=88=97=E5=8C=96=E6=97=B6?= =?UTF-8?q?=EF=BC=8C=E5=85=88=E5=AF=B9=E7=88=B6=E8=8A=82=E7=82=B9=E5=88=A4?= =?UTF-8?q?=E6=96=ADisObject=20=EF=BC=88cherry=20picked=20commit=20from=20?= =?UTF-8?q??= =?UTF-8?q?=20Signed-off-by:=20wufarong1=20?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../ans/src/notification_do_not_disturb_profile.cpp | 4 ++++ services/ans/src/common/file_utils.cpp | 2 +- services/ans/src/common/notification_config_parse.cpp | 6 +++++- services/ans/src/notification_preferences.cpp | 8 ++++++++ services/ans/src/notification_preferences_database.cpp | 4 ++++ services/ans/src/notification_trust_list.cpp | 2 +- services/ans/src/system_dialog_connect_stb.cpp | 4 ++++ 7 files changed, 27 insertions(+), 3 deletions(-) diff --git a/frameworks/ans/src/notification_do_not_disturb_profile.cpp b/frameworks/ans/src/notification_do_not_disturb_profile.cpp index 2da7e16d6..0a4be2f85 100644 --- a/frameworks/ans/src/notification_do_not_disturb_profile.cpp +++ b/frameworks/ans/src/notification_do_not_disturb_profile.cpp @@ -138,6 +138,10 @@ std::string NotificationDoNotDisturbProfile::ToJson() void NotificationDoNotDisturbProfile::FromJson(const std::string &jsonObj) { nlohmann::json jsonObject = nlohmann::json::parse(jsonObj, nullptr, false); + if (jsonObject.is_null() or !jsonObject.is_object()) { + ANS_LOGE("Invalid JSON object"); + return; + } if (jsonObject.is_discarded()) { ANS_LOGE("Failed to parse json string."); return; diff --git a/services/ans/src/common/file_utils.cpp b/services/ans/src/common/file_utils.cpp index e6cdd327a..c122deac9 100644 --- a/services/ans/src/common/file_utils.cpp +++ b/services/ans/src/common/file_utils.cpp @@ -63,7 +63,7 @@ bool FileUtils::GetJsonFromFile(const char *path, nlohmann::json &root) { std::ifstream file(path); root = nlohmann::json::parse(file); - if (root.is_null() || root.empty()) { + if (root.is_null() || root.empty() || !root.is_object()) { ANS_LOGE("GetJsonFromFile fail as invalid root."); return false; } diff --git a/services/ans/src/common/notification_config_parse.cpp b/services/ans/src/common/notification_config_parse.cpp index 1bf1ce77c..f82599779 100644 --- a/services/ans/src/common/notification_config_parse.cpp +++ b/services/ans/src/common/notification_config_parse.cpp @@ -84,7 +84,11 @@ bool NotificationConfigParse::GetCurrentSlotReminder( return false; } nlohmann::json currentDeviceRemindJson = root[CFG_KEY_NOTIFICATION_SERVICE][CFG_KEY_SLOT_TYPE_REMINDER]; - if (currentDeviceRemindJson.is_null() || !currentDeviceRemindJson.is_array() || currentDeviceRemindJson.empty()) { + if (currentDeviceRemindJson.is_null() || !currentDeviceRemindJson.is_object()) { + ANS_LOGE("Invalid JSON object"); + return false; + } + if (!currentDeviceRemindJson.is_array() || currentDeviceRemindJson.empty()) { ANS_LOGE("GetCurrentSlotReminder failed as invalid currentDeviceReminder json."); return false; } diff --git a/services/ans/src/notification_preferences.cpp b/services/ans/src/notification_preferences.cpp index d73ed36ab..9ff4bb904 100644 --- a/services/ans/src/notification_preferences.cpp +++ b/services/ans/src/notification_preferences.cpp @@ -849,6 +849,10 @@ ErrCode NotificationPreferences::GetTemplateSupported(const std::string& templat nlohmann::json jsonObj; inFile >> jsonObj; + if (jsonObj.is_null() || !jsonObj.is_object()) { + ANS_LOGE("Invalid JSON object"); + return ERR_ANS_PREFERENCES_NOTIFICATION_READ_TEMPLATE_CONFIG_FAILED; + } if (jsonObj.is_discarded()) { ANS_LOGE("template json discarded error."); inFile.close(); @@ -992,6 +996,10 @@ bool NotificationPreferences::GetBundleSoundPermission(bool &allPackage, std::se ANS_LOGD("The bundle permission is :%{public}s.", value.c_str()); nlohmann::json jsonPermission = nlohmann::json::parse(value, nullptr, false); + if (jsonPermission.is_null() or !jsonPermission.is_object()) { + ANS_LOGE("Invalid JSON object"); + return false; + } if (jsonPermission.is_discarded() || !jsonPermission.is_array()) { ANS_LOGE("Parse bundle permission failed due to data is discarded or not array"); return false; diff --git a/services/ans/src/notification_preferences_database.cpp b/services/ans/src/notification_preferences_database.cpp index 1b5629041..7d7ab08b7 100644 --- a/services/ans/src/notification_preferences_database.cpp +++ b/services/ans/src/notification_preferences_database.cpp @@ -1815,6 +1815,10 @@ bool NotificationPreferencesDatabase::IsAgentRelationship(const std::string &age } ANS_LOGD("The agent relationship is :%{public}s.", agentShip.c_str()); nlohmann::json jsonAgentShip = nlohmann::json::parse(agentShip, nullptr, false); + if (jsonAgentShip.is_null() or !jsonAgentShip.is_object()) { + ANS_LOGE("Invalid JSON object"); + return false; + } if (jsonAgentShip.is_discarded() || !jsonAgentShip.is_array()) { ANS_LOGE("Parse agent ship failed due to data is discarded or not array"); return false; diff --git a/services/ans/src/notification_trust_list.cpp b/services/ans/src/notification_trust_list.cpp index 3d4193d09..cdd32aa9b 100644 --- a/services/ans/src/notification_trust_list.cpp +++ b/services/ans/src/notification_trust_list.cpp @@ -40,7 +40,7 @@ void NotificationTrustList::GetCcmPrivilegesConfig() return; } nlohmann::json affects = root[NotificationConfigParse::APP_PRIVILEGES]; - if (affects.is_null() || affects.empty()) { + if (affects.is_null() || affects.empty() || !affects.is_object()) { ANS_LOGE("GetCcmPrivileges failed as invalid ccmPrivileges json."); return; } diff --git a/services/ans/src/system_dialog_connect_stb.cpp b/services/ans/src/system_dialog_connect_stb.cpp index 5ded65f49..9035552b2 100644 --- a/services/ans/src/system_dialog_connect_stb.cpp +++ b/services/ans/src/system_dialog_connect_stb.cpp @@ -62,6 +62,10 @@ void SystemDialogConnectStb::SendRemoveBundleEvent() return; } nlohmann::json root = nlohmann::json::parse(commandStr_); + if (root.is_null() or !root.is_object()) { + ANS_LOGE("Invalid JSON object"); + return; + } if (!root.contains("bundleName") || !root.contains("bundleUid")) { ANS_LOGW("not found jsonKey from"); return; -- Gitee From c17b6e18585f9c217f0619d82e0959f1d0dbbe3b Mon Sep 17 00:00:00 2001 From: Mark_Yao Date: Mon, 26 Aug 2024 09:08:16 +0000 Subject: [PATCH 018/167] update services/ans/src/common/notification_config_parse.cpp. Signed-off-by: Mark_Yao --- services/ans/src/common/notification_config_parse.cpp | 6 +----- 1 file changed, 1 insertion(+), 5 deletions(-) diff --git a/services/ans/src/common/notification_config_parse.cpp b/services/ans/src/common/notification_config_parse.cpp index f82599779..1bf1ce77c 100644 --- a/services/ans/src/common/notification_config_parse.cpp +++ b/services/ans/src/common/notification_config_parse.cpp @@ -84,11 +84,7 @@ bool NotificationConfigParse::GetCurrentSlotReminder( return false; } nlohmann::json currentDeviceRemindJson = root[CFG_KEY_NOTIFICATION_SERVICE][CFG_KEY_SLOT_TYPE_REMINDER]; - if (currentDeviceRemindJson.is_null() || !currentDeviceRemindJson.is_object()) { - ANS_LOGE("Invalid JSON object"); - return false; - } - if (!currentDeviceRemindJson.is_array() || currentDeviceRemindJson.empty()) { + if (currentDeviceRemindJson.is_null() || !currentDeviceRemindJson.is_array() || currentDeviceRemindJson.empty()) { ANS_LOGE("GetCurrentSlotReminder failed as invalid currentDeviceReminder json."); return false; } -- Gitee From 25055574a1006df444948c8701146376d08151c9 Mon Sep 17 00:00:00 2001 From: Mark_Yao Date: Mon, 26 Aug 2024 09:10:17 +0000 Subject: [PATCH 019/167] update services/ans/src/notification_preferences.cpp. Signed-off-by: Mark_Yao --- services/ans/src/notification_preferences.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/services/ans/src/notification_preferences.cpp b/services/ans/src/notification_preferences.cpp index 9ff4bb904..21d59e2d6 100644 --- a/services/ans/src/notification_preferences.cpp +++ b/services/ans/src/notification_preferences.cpp @@ -996,7 +996,7 @@ bool NotificationPreferences::GetBundleSoundPermission(bool &allPackage, std::se ANS_LOGD("The bundle permission is :%{public}s.", value.c_str()); nlohmann::json jsonPermission = nlohmann::json::parse(value, nullptr, false); - if (jsonPermission.is_null() or !jsonPermission.is_object()) { + if (jsonPermission.is_null() || jsonPermission.empty()) { ANS_LOGE("Invalid JSON object"); return false; } -- Gitee From 6261b39769398b470782e4acc2b96cc7ca307176 Mon Sep 17 00:00:00 2001 From: Mark_Yao Date: Mon, 26 Aug 2024 09:11:02 +0000 Subject: [PATCH 020/167] update services/ans/src/notification_preferences_database.cpp. Signed-off-by: Mark_Yao --- services/ans/src/notification_preferences_database.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/services/ans/src/notification_preferences_database.cpp b/services/ans/src/notification_preferences_database.cpp index 7d7ab08b7..b2b15d053 100644 --- a/services/ans/src/notification_preferences_database.cpp +++ b/services/ans/src/notification_preferences_database.cpp @@ -1815,7 +1815,7 @@ bool NotificationPreferencesDatabase::IsAgentRelationship(const std::string &age } ANS_LOGD("The agent relationship is :%{public}s.", agentShip.c_str()); nlohmann::json jsonAgentShip = nlohmann::json::parse(agentShip, nullptr, false); - if (jsonAgentShip.is_null() or !jsonAgentShip.is_object()) { + if (jsonAgentShip.is_null() || jsonAgentShip.empty()) { ANS_LOGE("Invalid JSON object"); return false; } -- Gitee From 19e8d79945e9cfccaaa4c09e8474863d81cbb415 Mon Sep 17 00:00:00 2001 From: Mark_Yao Date: Mon, 26 Aug 2024 09:11:43 +0000 Subject: [PATCH 021/167] update services/ans/src/notification_trust_list.cpp. Signed-off-by: Mark_Yao --- services/ans/src/notification_trust_list.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/services/ans/src/notification_trust_list.cpp b/services/ans/src/notification_trust_list.cpp index cdd32aa9b..3d4193d09 100644 --- a/services/ans/src/notification_trust_list.cpp +++ b/services/ans/src/notification_trust_list.cpp @@ -40,7 +40,7 @@ void NotificationTrustList::GetCcmPrivilegesConfig() return; } nlohmann::json affects = root[NotificationConfigParse::APP_PRIVILEGES]; - if (affects.is_null() || affects.empty() || !affects.is_object()) { + if (affects.is_null() || affects.empty()) { ANS_LOGE("GetCcmPrivileges failed as invalid ccmPrivileges json."); return; } -- Gitee From 34eaf0f54eb31d51cf07ba9f3308f4f2a4d9ef43 Mon Sep 17 00:00:00 2001 From: xdongs Date: Sat, 24 Aug 2024 17:07:27 +0800 Subject: [PATCH 022/167] param Signed-off-by: xdongs --- .../ets/ServiceExtAbility/NotificationServiceExtAbility.ts | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/services/dialog_ui/enable_notification_dialog/entry/src/main/ets/ServiceExtAbility/NotificationServiceExtAbility.ts b/services/dialog_ui/enable_notification_dialog/entry/src/main/ets/ServiceExtAbility/NotificationServiceExtAbility.ts index 904bbe33d..ad91a672c 100644 --- a/services/dialog_ui/enable_notification_dialog/entry/src/main/ets/ServiceExtAbility/NotificationServiceExtAbility.ts +++ b/services/dialog_ui/enable_notification_dialog/entry/src/main/ets/ServiceExtAbility/NotificationServiceExtAbility.ts @@ -68,6 +68,7 @@ export class EnableNotificationDialog { static ENABLE_NOTIFICATION_DIALOG_NAME = 'EnableNotificationDialog'; static DIALOG_PATH = 'pages/notificationDialog'; static TRANSPARANT_COLOR = '#00000000'; + static SCENEBOARD_BUNDLE = 'com.ohos.sceneboard'; id: number; want: Want; @@ -236,7 +237,7 @@ class NotificationDialogServiceExtensionAbility extends UIExtensionAbility { let stageModel = false; let bundleName = want.parameters['ohos.aafwk.param.callerBundleName']; let bundleUid = want.parameters['ohos.aafwk.param.callerUid']; - if (want.parameters.bundleName === undefined) { + if (bundleName !== EnableNotificationDialog.SCENEBOARD_BUNDLE) { want.parameters.bundleName = bundleName; want.parameters.bundleUid = bundleUid; stageModel = true; -- Gitee From ca38bb2e1eb7ab3c480ab40deaf4765cdbfe47bd Mon Sep 17 00:00:00 2001 From: Ricky Date: Tue, 6 Aug 2024 10:26:28 +0800 Subject: [PATCH 023/167] fix cannot remove agent liveview when close slot setting Signed-off-by: Ricky Change-Id: I0796a2f5ac185c2027a74226c90715c183de5c4d --- .../ans/src/advanced_notification_publish_service.cpp | 11 ++++++++++- services/ans/src/advanced_notification_service.cpp | 1 - 2 files changed, 10 insertions(+), 2 deletions(-) diff --git a/services/ans/src/advanced_notification_publish_service.cpp b/services/ans/src/advanced_notification_publish_service.cpp index 41a086c48..1da6a1b2d 100644 --- a/services/ans/src/advanced_notification_publish_service.cpp +++ b/services/ans/src/advanced_notification_publish_service.cpp @@ -1493,6 +1493,15 @@ ErrCode AdvancedNotificationService::RemoveAllNotificationsInner(const sptrdeviceId.empty() #endif ) { + auto notificationRequest = record->request; + if (!BundleManagerHelper::GetInstance()->IsSystemApp(bundle->GetUid()) && + notificationRequest->IsSystemLiveView()) { + auto localLiveviewContent = std::static_pointer_cast( + notificationRequest->GetContent()->GetNotificationContent()); + if (localLiveviewContent->GetType() == 0) { + continue; + } + } ProcForDeleteLiveView(record); removeList.push_back(record); } @@ -1611,7 +1620,7 @@ ErrCode AdvancedNotificationService::RemoveNotificationBySlot(const sptrbundleOption->GetBundleName() == bundle->GetBundleName()) && ((*it)->bundleOption->GetUid() == bundle->GetUid()) && ((*it)->request->GetSlotType() == slot->GetType())) { - if (((*it)->request->IsAgentNotification() && (*it)->request->IsSystemLiveView())) { + if (((*it)->request->GetAgentBundle() != nullptr && (*it)->request->IsSystemLiveView())) { ANS_LOGI("Agent systemliveview no need remove."); it++; continue; diff --git a/services/ans/src/advanced_notification_service.cpp b/services/ans/src/advanced_notification_service.cpp index b9ca6c3dc..a8803cc80 100644 --- a/services/ans/src/advanced_notification_service.cpp +++ b/services/ans/src/advanced_notification_service.cpp @@ -30,7 +30,6 @@ #include "ans_log_wrapper.h" #include "ans_watchdog.h" #include "ans_permission_def.h" -#include "bundle_manager_helper.h" #include "errors.h" #include "notification_extension_wrapper.h" #include "notification_record.h" -- Gitee From 3436738155ae40393462cc9cd45d36777bcc8367 Mon Sep 17 00:00:00 2001 From: xdongs Date: Tue, 27 Aug 2024 20:31:31 +0800 Subject: [PATCH 024/167] =?UTF-8?q?rk=E6=9D=BF=E6=94=AF=E6=8C=81uiExtensio?= =?UTF-8?q?n=E5=AD=90=E7=AA=97?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: xdongs --- .../NotificationServiceExtAbility.ts | 17 ++++++++++++++++- 1 file changed, 16 insertions(+), 1 deletion(-) diff --git a/services/dialog_ui/enable_notification_dialog/entry/src/main/ets/ServiceExtAbility/NotificationServiceExtAbility.ts b/services/dialog_ui/enable_notification_dialog/entry/src/main/ets/ServiceExtAbility/NotificationServiceExtAbility.ts index 904bbe33d..75d310fa7 100644 --- a/services/dialog_ui/enable_notification_dialog/entry/src/main/ets/ServiceExtAbility/NotificationServiceExtAbility.ts +++ b/services/dialog_ui/enable_notification_dialog/entry/src/main/ets/ServiceExtAbility/NotificationServiceExtAbility.ts @@ -23,6 +23,9 @@ import UIExtensionAbility from '@ohos.app.ability.UIExtensionAbility'; import UIExtensionContentSession from '@ohos.app.ability.UIExtensionContentSession'; import uiExtensionHost from '@ohos.uiExtensionHost'; import StartOptions from '@ohos.app.ability.StartOptions'; +import configPolicy from '@ohos.configPolicy'; +import fs from '@ohos.file.fs'; +import Constants from '../common/constant'; @@ -138,8 +141,20 @@ export class EnableNotificationDialog { 'dialog': this, 'session': session }); + + let hasConfig = true; + try { + let filePaths = await configPolicy.getCfgFiles(Constants.CCM_CONFIG_PATH); + + if (filePaths.length === 0) { + console.info(TAG, 'not get any configFile'); + hasConfig = false; + } + }catch (err) { + console.error(TAG, 'Failed get ccm files'); + } - if (stageModel) { + if (stageModel && hasConfig) { let subWindowOpts : window.SubWindowOptions = { 'title': '', decorEnabled: false, -- Gitee From 1eaf84ce05b1b745dc154939d2f7646aecab5efc Mon Sep 17 00:00:00 2001 From: gaojiaqi Date: Wed, 28 Aug 2024 14:32:14 +0800 Subject: [PATCH 025/167] update reminder': Signed-off-by: gaojiaqi --- services/ans/src/reminder_data_manager.cpp | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/services/ans/src/reminder_data_manager.cpp b/services/ans/src/reminder_data_manager.cpp index a2e9ce63d..eb8044156 100644 --- a/services/ans/src/reminder_data_manager.cpp +++ b/services/ans/src/reminder_data_manager.cpp @@ -1941,7 +1941,8 @@ void ReminderDataManager::HandleCustomButtonClick(const OHOS::EventFwk::Want &wa if (client == nullptr) { return; } - int32_t result = client->StartAbility(abilityWant); + uint32_t specifyTokenId = static_cast(IPCSkeleton::GetSelfTokenID()); + int32_t result = client->StartAbilityOnlyUIAbility(abilityWant, nullptr, specifyTokenId); if (result != 0) { ANSR_LOGE("Start ability failed, result = %{public}d", result); return; @@ -1980,7 +1981,8 @@ void ReminderDataManager::ClickReminder(const OHOS::EventFwk::Want &want) ANSR_LOGE("start ability failed, due to ability mgr client is nullptr."); return; } - int32_t result = client->StartAbility(abilityWant); + uint32_t specifyTokenId = static_cast(IPCSkeleton::GetSelfTokenID()); + int32_t result = client->StartAbilityOnlyUIAbility(abilityWant, nullptr, specifyTokenId); if (result != 0) { ANSR_LOGE("Start ability failed, result = %{public}d", result); } -- Gitee From afe63375fe7bec5f97f567bb40b65088884a00bc Mon Sep 17 00:00:00 2001 From: gaojiaqi Date: Wed, 28 Aug 2024 14:34:26 +0800 Subject: [PATCH 026/167] update reminder Signed-off-by: gaojiaqi --- services/ans/src/reminder_data_manager.cpp | 3 +++ 1 file changed, 3 insertions(+) diff --git a/services/ans/src/reminder_data_manager.cpp b/services/ans/src/reminder_data_manager.cpp index a2e9ce63d..25ac1c781 100644 --- a/services/ans/src/reminder_data_manager.cpp +++ b/services/ans/src/reminder_data_manager.cpp @@ -1044,13 +1044,16 @@ void ReminderDataManager::ShowActiveReminderExtendLocked(sptr & continue; } if (((*it)->GetRingDuration() > 0) && !isAlerting) { + std::lock_guard lock(ReminderDataManager::MUTEX); playSoundReminder = (*it); isAlerting = true; } else { + std::lock_guard lock(ReminderDataManager::MUTEX); ShowReminder((*it), false, false, false, false); } } if (playSoundReminder != nullptr) { + std::lock_guard lock(ReminderDataManager::MUTEX); ShowReminder(playSoundReminder, true, false, false, true); } } -- Gitee From f3938d07f6dacb67ad19b8dec1e9d78295e2f222 Mon Sep 17 00:00:00 2001 From: wufarong Date: Tue, 27 Aug 2024 12:48:44 +0800 Subject: [PATCH 027/167] =?UTF-8?q?ANS=E5=91=8A=E8=AD=A6=E5=A4=84=E7=90=86?= =?UTF-8?q?=20=EF=BC=88cherry=20picked=20commit=20from=20?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- frameworks/ans/src/notification_local_live_view_button.cpp | 1 + frameworks/ans/src/notification_request.cpp | 1 + 2 files changed, 2 insertions(+) diff --git a/frameworks/ans/src/notification_local_live_view_button.cpp b/frameworks/ans/src/notification_local_live_view_button.cpp index 81d163d51..df5bb1d07 100644 --- a/frameworks/ans/src/notification_local_live_view_button.cpp +++ b/frameworks/ans/src/notification_local_live_view_button.cpp @@ -172,6 +172,7 @@ NotificationLocalLiveViewButton *NotificationLocalLiveViewButton::FromJson(const auto pIcon = AnsImageUtil::UnPackImage(iconObj.get()); if (pIcon == nullptr) { ANS_LOGE("Failed to parse button icon"); + delete button; return nullptr; } button->buttonIcons_.emplace_back(pIcon); diff --git a/frameworks/ans/src/notification_request.cpp b/frameworks/ans/src/notification_request.cpp index 9dbb6e96b..93949a385 100644 --- a/frameworks/ans/src/notification_request.cpp +++ b/frameworks/ans/src/notification_request.cpp @@ -2253,6 +2253,7 @@ bool NotificationRequest::ConvertJsonToNotificationDistributedOptions( } target->distributedOptions_ = *pOpt; + delete pOpt; } } -- Gitee From 8af8cf5fe41b11583c1549ea897901a2e62e4c55 Mon Sep 17 00:00:00 2001 From: wufarong Date: Wed, 28 Aug 2024 11:24:32 +0800 Subject: [PATCH 028/167] =?UTF-8?q?iconsResource=E8=BE=93=E5=85=A5?= =?UTF-8?q?=E6=A0=A1=E9=AA=8C=E4=B8=8Estoi=E5=85=A5=E5=8F=82=E6=A0=A1?= =?UTF-8?q?=E9=AA=8C=EF=BC=8C=E6=9E=9A=E4=B8=BE=E5=80=BC=E5=A4=96=E9=83=A8?= =?UTF-8?q?=E8=BE=93=E5=85=A5=E5=88=A4=E5=AE=9A=20=EF=BC=88cherry=20picked?= =?UTF-8?q?=20commit=20from=20?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../notification_local_live_view_button.cpp | 11 ++++++ frameworks/ans/src/notification_request.cpp | 39 ++++++++++++++++--- interfaces/inner_api/notification_constant.h | 8 +++- interfaces/inner_api/notification_content.h | 7 +++- interfaces/inner_api/notification_request.h | 14 ++++++- .../ans/src/advanced_notification_utils.cpp | 3 +- .../NotificationServiceExtAbility.ts | 2 +- 7 files changed, 73 insertions(+), 11 deletions(-) diff --git a/frameworks/ans/src/notification_local_live_view_button.cpp b/frameworks/ans/src/notification_local_live_view_button.cpp index 81d163d51..e866e59df 100644 --- a/frameworks/ans/src/notification_local_live_view_button.cpp +++ b/frameworks/ans/src/notification_local_live_view_button.cpp @@ -16,6 +16,7 @@ #include "notification_local_live_view_button.h" #include +#include #include // for basic_string, operator+, basic_string<>... #include // for shared_ptr, shared_ptr<>::element_type #include @@ -257,9 +258,19 @@ bool NotificationLocalLiveViewButton::ReadFromParcel(Parcel &parcel) ANS_LOGE("Failed to read button names"); return false; } + if (iconsResource.size() < BUTTON_RESOURCE_SIZE) { + ANS_LOGE("Invalid input for button icons resource"); + return false; + } auto resource = std::make_shared(); resource->bundleName = iconsResource[RESOURCE_BUNDLENAME_INDEX]; resource->moduleName = iconsResource[RESOURCE_MODULENAME_INDEX]; + std::stringstream sin(iconsResource[RESOURCE_ID_INDEX]); + int32_t checknum; + if (!(sin >> checknum)) { + ANS_LOGE("Invalid input for button icons resource"); + return false; + } resource->id = std::stoi(iconsResource[RESOURCE_ID_INDEX]); buttonIconsResource_.emplace_back(resource); } diff --git a/frameworks/ans/src/notification_request.cpp b/frameworks/ans/src/notification_request.cpp index 9dbb6e96b..a05d0b8d0 100644 --- a/frameworks/ans/src/notification_request.cpp +++ b/frameworks/ans/src/notification_request.cpp @@ -1502,11 +1502,40 @@ bool NotificationRequest::ReadFromParcel(Parcel &parcel) return false; } - slotType_ = static_cast(parcel.ReadInt32()); - groupAlertType_ = static_cast(parcel.ReadInt32()); - visiblenessType_ = static_cast(parcel.ReadInt32()); - badgeStyle_ = static_cast(parcel.ReadInt32()); - notificationContentType_ = static_cast(parcel.ReadInt32()); + int32_t slotTypeValue = parcel.ReadInt32(); + if (slotTypeValue < 0 || + slotTypeValue >= static_cast(NotificationConstant::SlotType::ILLEGAL_TYPE)) { + ANS_LOGE("Invalid slot type value :%d", slotTypeValue); + return false; + } + slotType_ = static_cast(slotTypeValue); + int32_t groupAlertTypeValue = parcel.ReadInt32(); + if (groupAlertTypeValue < 0 || + groupAlertTypeValue >= static_cast(NotificationRequest::GroupAlertType::ILLEGAL_TYPE)) { + ANS_LOGE("Invalid slot type value :%d", groupAlertTypeValue); + return false; + } + groupAlertType_ = static_cast(groupAlertTypeValue); + int32_t visiblenessTypeValue = parcel.ReadInt32(); + if (visiblenessTypeValue < 0 || + visiblenessTypeValue >= static_cast(NotificationConstant::VisiblenessType::ILLEGAL_TYPE)) { + ANS_LOGE("Invalid slot type value :%d", visiblenessTypeValue); + return false; + } + visiblenessType_ = static_cast(visiblenessTypeValue); + int32_t badgeStyleValue = parcel.ReadInt32(); + if (badgeStyleValue < 0 || badgeStyleValue >= static_cast(NotificationRequest::BadgeStyle::ILLEGAL_TYPE)) { + ANS_LOGE("Invalid slot type value :%d", badgeStyleValue); + return false; + } + badgeStyle_ = static_cast(badgeStyleValue); + int32_t notificationContentTypeValue = parcel.ReadInt32(); + if (notificationContentTypeValue <= static_cast(NotificationContent::Type::NONE) || + notificationContentTypeValue >= static_cast(NotificationContent::Type::ILLEGAL_TYPE)) { + ANS_LOGE("Invalid slot type value :%d", notificationContentTypeValue); + return false; + } + notificationContentType_ = static_cast(notificationContentTypeValue); showDeliveryTime_ = parcel.ReadBool(); tapDismissed_ = parcel.ReadBool(); diff --git a/interfaces/inner_api/notification_constant.h b/interfaces/inner_api/notification_constant.h index d01c1afea..573fdaa40 100644 --- a/interfaces/inner_api/notification_constant.h +++ b/interfaces/inner_api/notification_constant.h @@ -65,6 +65,7 @@ public: LIVE_VIEW, // the notification type is live view CUSTOMER_SERVICE, // the notification type is customer service EMERGENCY_INFORMATION, // the notification type is emergency information + ILLEGAL_TYPE, // invalid type,it is used as the upper limit of the enumerated value }; enum ReminderFlag { @@ -93,7 +94,12 @@ public: /** * notifications are not displayed on the lock screen. */ - SECRET + SECRET, + /** + * invalid type + * It is used as the upper limit of the enumerated value. + */ + ILLEGAL_TYPE }; enum class DoNotDisturbType { diff --git a/interfaces/inner_api/notification_content.h b/interfaces/inner_api/notification_content.h index 3d68945a8..836c0e80d 100644 --- a/interfaces/inner_api/notification_content.h +++ b/interfaces/inner_api/notification_content.h @@ -75,7 +75,12 @@ public: * Indicates notifications that include a live view. * Such notifications are created using NotificationLiveViewContent. */ - LIVE_VIEW + LIVE_VIEW, + /** + * invalid type + * It is used as the upper limit of the enumerated value. + */ + ILLEGAL_TYPE }; /** diff --git a/interfaces/inner_api/notification_request.h b/interfaces/inner_api/notification_request.h index 541f85294..b04f96855 100644 --- a/interfaces/inner_api/notification_request.h +++ b/interfaces/inner_api/notification_request.h @@ -64,7 +64,12 @@ public: /** * displayed as a small icon. */ - LITTLE + LITTLE, + /** + * invalid type + * It is used as the upper limit of the enumerated value. + */ + ILLEGAL_TYPE }; enum class GroupAlertType { @@ -82,7 +87,12 @@ public: * the overview notification has sound or vibration but child notifications are muted (no sound or vibration) * in a group if sound or vibration is enabled for the associated NotificationSlot objects. */ - OVERVIEW + OVERVIEW, + /** + * invalid type + * It is used as the upper limit of the enumerated value. + */ + ILLEGAL_TYPE }; /** diff --git a/services/ans/src/advanced_notification_utils.cpp b/services/ans/src/advanced_notification_utils.cpp index 104c63943..bdcc0113a 100644 --- a/services/ans/src/advanced_notification_utils.cpp +++ b/services/ans/src/advanced_notification_utils.cpp @@ -649,7 +649,8 @@ void AdvancedNotificationService::OnBundleDataUpdate(const sptrGetBundleName().compare("com.ohos.mms") == 0) { uint32_t slotFlags = 63; - auto ret = NotificationPreferences::GetInstance()->GetNotificationSlotFlagsForBundle(bundleOption, slotFlags); + auto ret = NotificationPreferences::GetInstance()->GetNotificationSlotFlagsForBundle( + bundleOption, slotFlags); if (ret != ERR_OK) { ANS_LOGE("Failed to get slotflags for bundle, use default slotflags."); } diff --git a/services/dialog_ui/enable_notification_dialog/entry/src/main/ets/ServiceExtAbility/NotificationServiceExtAbility.ts b/services/dialog_ui/enable_notification_dialog/entry/src/main/ets/ServiceExtAbility/NotificationServiceExtAbility.ts index be1217905..8513612fa 100644 --- a/services/dialog_ui/enable_notification_dialog/entry/src/main/ets/ServiceExtAbility/NotificationServiceExtAbility.ts +++ b/services/dialog_ui/enable_notification_dialog/entry/src/main/ets/ServiceExtAbility/NotificationServiceExtAbility.ts @@ -225,7 +225,7 @@ export class EnableNotificationDialog { class NotificationDialogServiceExtensionAbility extends UIExtensionAbility { - onConfigurationUpdate(newConfig) { + onConfigurationUpdate(newConfig): void { console.log(TAG, 'onConfigurationUpdate'); if (systemLanguage !== newConfig.language) { console.log(TAG, `onConfigurationUpdate newConfig is ${JSON.stringify(newConfig)}`); -- Gitee From ca3035262c61995445a8cf697d1fcbf6415abba1 Mon Sep 17 00:00:00 2001 From: z30053788 Date: Thu, 29 Aug 2024 17:59:45 +0800 Subject: [PATCH 029/167] cherry pick a399994 from https://gitee.com/zhaobaoxin1/notification_distributed_notification_service/pulls/2108 update Signed-off-by: z30053788 Change-Id: I9047c53ae0a7b09cc98f3d69ecab63157276aa69 --- .../js/napi/src/common_convert_notification.cpp | 4 ++++ .../ans/include/advanced_notification_service.h | 5 +++-- .../src/advanced_notification_publish_service.cpp | 3 ++- .../ans/src/advanced_notification_service.cpp | 15 +++++++++++---- .../advanced_notification_service_test.cpp | 3 ++- 5 files changed, 22 insertions(+), 8 deletions(-) diff --git a/frameworks/js/napi/src/common_convert_notification.cpp b/frameworks/js/napi/src/common_convert_notification.cpp index a847c411d..73ca08afa 100644 --- a/frameworks/js/napi/src/common_convert_notification.cpp +++ b/frameworks/js/napi/src/common_convert_notification.cpp @@ -171,6 +171,10 @@ napi_value Common::SetNotification( napi_create_string_utf8(env, notification->GetDeviceId().c_str(), NAPI_AUTO_LENGTH, &value); napi_set_named_property(env, result, "deviceId", value); + // notificationControlFlags?: number + napi_create_int32(env, notification->GetNotificationRequest().GetNotificationControlFlags(), &value); + napi_set_named_property(env, result, "notificationControlFlags", value); + return NapiGetBoolean(env, true); } diff --git a/services/ans/include/advanced_notification_service.h b/services/ans/include/advanced_notification_service.h index c7b509233..b5ca956f5 100644 --- a/services/ans/include/advanced_notification_service.h +++ b/services/ans/include/advanced_notification_service.h @@ -1158,7 +1158,8 @@ private: void StartFilters(); void StopFilters(); ErrCode Filter(const std::shared_ptr &record, bool isRecover = false); - void ChangeNotificationByControlFlags(const std::shared_ptr &record); + void ChangeNotificationByControlFlags(const std::shared_ptr &record, + const bool isAgentController); ErrCode CheckPublishPreparedNotification(const std::shared_ptr &record, bool isSystemApp); void AddToNotificationList(const std::shared_ptr &record); void AddToDelayNotificationList(const std::shared_ptr &record); @@ -1321,7 +1322,7 @@ private: ErrCode CheckBundleOptionValid(sptr &bundleOption); bool IsNeedNotifyConsumed(const sptr &request); ErrCode AddRecordToMemory(const std::shared_ptr &record, - bool isSystemApp, bool isUpdateByOwner); + bool isSystemApp, bool isUpdateByOwner, const bool isAgentController); ErrCode DuplicateMsgControl(const sptr &request); void RemoveExpiredUniqueKey(); bool IsDuplicateMsg(const std::string &uniqueKey); diff --git a/services/ans/src/advanced_notification_publish_service.cpp b/services/ans/src/advanced_notification_publish_service.cpp index 1da6a1b2d..5a42b0104 100644 --- a/services/ans/src/advanced_notification_publish_service.cpp +++ b/services/ans/src/advanced_notification_publish_service.cpp @@ -2073,6 +2073,7 @@ ErrCode AdvancedNotificationService::PublishNotificationBySa(const sptrGetCreatorUid(); if (request->GetOwnerUid() != DEFAULT_UID) { @@ -2149,7 +2150,7 @@ ErrCode AdvancedNotificationService::PublishNotificationBySa(const sptr( record->request->GetContent()->GetNotificationContent())->GetType() == TYPE_CODE_DOWNLOAD)) { diff --git a/services/ans/src/advanced_notification_service.cpp b/services/ans/src/advanced_notification_service.cpp index a8803cc80..caad9d98b 100644 --- a/services/ans/src/advanced_notification_service.cpp +++ b/services/ans/src/advanced_notification_service.cpp @@ -609,6 +609,7 @@ ErrCode AdvancedNotificationService::PublishPreparedNotification(const sptrLocalControl(request); @@ -649,7 +650,7 @@ ErrCode AdvancedNotificationService::PublishPreparedNotification(const sptr &record) +void AdvancedNotificationService::ChangeNotificationByControlFlags(const std::shared_ptr &record, + const bool isAgentController) { ANS_LOGD("Called."); if (record == nullptr || record->request == nullptr || record->notification == nullptr) { @@ -875,6 +877,10 @@ void AdvancedNotificationService::ChangeNotificationByControlFlags(const std::sh return; } + if (!isAgentController) { + record->request->SetNotificationControlFlags(notificationControlFlags & 0xFFFF); + } + auto flags = record->request->GetFlags(); if (flags == nullptr) { ANS_LOGE("The flags is nullptr."); @@ -2148,7 +2154,8 @@ ErrCode AdvancedNotificationService::CheckSystemLiveView(const sptr &record, bool isSystemApp, bool isUpdateByOwner) + const std::shared_ptr &record, bool isSystemApp, bool isUpdateByOwner, + const bool isAgentController) { auto result = AssignValidNotificationSlot(record, record->bundleOption); if (result != ERR_OK) { @@ -2163,7 +2170,7 @@ ErrCode AdvancedNotificationService::AddRecordToMemory( } if (isSystemApp) { - ChangeNotificationByControlFlags(record); + ChangeNotificationByControlFlags(record, isAgentController); } CheckDoNotDisturbProfile(record); diff --git a/services/ans/test/unittest/advanced_notification_service_test.cpp b/services/ans/test/unittest/advanced_notification_service_test.cpp index f26937a28..1c7796320 100644 --- a/services/ans/test/unittest/advanced_notification_service_test.cpp +++ b/services/ans/test/unittest/advanced_notification_service_test.cpp @@ -3398,8 +3398,9 @@ HWTEST_F(AdvancedNotificationServiceTest, ChangeNotificationByControlFlags_00001 flags->SetStatusIconEnabled(true); request->SetFlags(flags); + bool isAgentController = true; auto record = advancedNotificationService_->MakeNotificationRecord(request, bundle); - advancedNotificationService_->ChangeNotificationByControlFlags(record); + advancedNotificationService_->ChangeNotificationByControlFlags(record, isAgentController); u_int32_t reminderFlags = flags->GetReminderFlags(); ASSERT_EQ(reminderFlags, 0); -- Gitee From f18ed611a6b03cae08bc5bf9296e5fbc0aeaff27 Mon Sep 17 00:00:00 2001 From: yizihan Date: Fri, 16 Aug 2024 14:57:36 +0800 Subject: [PATCH 030/167] =?UTF-8?q?cherry=20pick=200a41ab6=20from=20https:?= =?UTF-8?q?//gitee.com/wufarong1/notification=5Fdistributed=5Fnotification?= =?UTF-8?q?=5Fservice/pulls/2030=20=E5=A4=84=E7=90=86ans=E5=91=8A=E8=AD=A6?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: yizihan Change-Id: I057ed636e270addd708fc687ac29f5275aa23246 --- .../include/manager/napi_enable_notification.h | 1 + .../src/manager/napi_enable_notification.cpp | 18 +++++++++++++----- .../js/napi/src/manager/napi_push_callback.cpp | 2 +- 3 files changed, 15 insertions(+), 6 deletions(-) diff --git a/frameworks/js/napi/include/manager/napi_enable_notification.h b/frameworks/js/napi/include/manager/napi_enable_notification.h index 294190d45..76f84b513 100644 --- a/frameworks/js/napi/include/manager/napi_enable_notification.h +++ b/frameworks/js/napi/include/manager/napi_enable_notification.h @@ -34,6 +34,7 @@ napi_value ParseRequestEnableParameters(const napi_env &env, const napi_callback napi_value NapiIsNotificationEnabledSync(napi_env env, napi_callback_info info); bool CreateUIExtension(std::shared_ptr context, std::string &bundleName); void SendDialogEvent(std::string &bundleName, int32_t code); +void SetEnableParam(IsEnableParams ¶ms, const napi_env &env, napi_value &object); class ModalExtensionCallback { public: diff --git a/frameworks/js/napi/src/manager/napi_enable_notification.cpp b/frameworks/js/napi/src/manager/napi_enable_notification.cpp index 67a0fbd4f..8a0339015 100644 --- a/frameworks/js/napi/src/manager/napi_enable_notification.cpp +++ b/frameworks/js/napi/src/manager/napi_enable_notification.cpp @@ -382,11 +382,7 @@ napi_value ParseRequestEnableParameters(const napi_env &env, const napi_callback bool stageMode = false; napi_status status = OHOS::AbilityRuntime::IsStageContext(env, argv[PARAM0], stageMode); if (status == napi_ok && stageMode) { - auto context = OHOS::AbilityRuntime::GetStageModeContext(env, argv[PARAM0]); - sptr callerToken = context->GetToken(); - params.context = context; - params.callerToken = callerToken; - params.hasCallerToken = true; + SetEnableParam(params, env, argv[PARAM0]); } else { ANS_LOGE("Only support stage mode"); std::string msg = "Incorrect parameter types.Only support stage mode."; @@ -588,6 +584,18 @@ void SendDialogEvent(std::string &bundleName, int32_t code) ANS_LOGD("SendDialogEvent end"); } +void SetEnableParam(IsEnableParams ¶ms, const napi_env &env, napi_value &object) +{ + auto context = OHOS::AbilityRuntime::GetStageModeContext(env, object); + sptr callerToken = nullptr; + if (context != nullptr) { + callerToken = context->GetToken(); + } + params.context = context; + params.callerToken = callerToken; + params.hasCallerToken = true; +} + ModalExtensionCallback::ModalExtensionCallback() {} diff --git a/frameworks/js/napi/src/manager/napi_push_callback.cpp b/frameworks/js/napi/src/manager/napi_push_callback.cpp index 193784dce..066c6796a 100644 --- a/frameworks/js/napi/src/manager/napi_push_callback.cpp +++ b/frameworks/js/napi/src/manager/napi_push_callback.cpp @@ -133,7 +133,7 @@ int32_t JSPushCallBack::OnCheckNotification( AbilityRuntime::HandleEscape handleEscape(env_); std::string pkgName; - auto checkInfo = new (std::nothrow) NotificationCheckInfo {}; + auto checkInfo = std::make_shared(); checkInfo->ConvertJsonStringToValue(notificationData); NotificationConstant::SlotType outSlotType = static_cast(checkInfo->GetSlotType()); -- Gitee From c7f51dde2b62557089e5397bd8ee0c16303cb8fb Mon Sep 17 00:00:00 2001 From: z30053788 Date: Mon, 2 Sep 2024 21:37:41 +0800 Subject: [PATCH 031/167] cherry pick 706f812 from https://gitee.com/zhaobaoxin1/notification_distributed_notification_service/pulls/2125 update Signed-off-by: z30053788 Change-Id: I0d88bf3ef48f07dfd19fd60ded913c9ccb1beea2 --- services/ans/src/advanced_notification_publish_service.cpp | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/services/ans/src/advanced_notification_publish_service.cpp b/services/ans/src/advanced_notification_publish_service.cpp index 1da6a1b2d..8f12198d6 100644 --- a/services/ans/src/advanced_notification_publish_service.cpp +++ b/services/ans/src/advanced_notification_publish_service.cpp @@ -67,7 +67,7 @@ ErrCode AdvancedNotificationService::SetDefaultNotificationEnabled( ANS_LOGE("Failed to create EnabledNotificationCallbackData instance"); return ERR_NO_MEMORY; } - + SetSlotFlagsTrustlistsAsBundle(bundleOption); ErrCode result = ERR_OK; result = NotificationPreferences::GetInstance()->SetNotificationsEnabledForBundle(bundle, enabled); if (result == ERR_OK) { @@ -1010,7 +1010,6 @@ ErrCode AdvancedNotificationService::IsAllowedNotifySelf(const sptrGetNotificationsEnabledForBundle(bundleOption, allowed); if (result == ERR_ANS_PREFERENCES_NOTIFICATION_BUNDLE_NOT_EXIST) { - SetSlotFlagsTrustlistsAsBundle(bundleOption); result = ERR_OK; // FA model app can publish notification without user confirm allowed = CheckApiCompatibility(bundleOption); -- Gitee From 52d7bb1ce5543cc1f4f0326b63d6549d3a721122 Mon Sep 17 00:00:00 2001 From: 185******37 Date: Tue, 3 Sep 2024 02:46:00 +0000 Subject: [PATCH 032/167] update services/ans/src/advanced_notification_publish_service.cpp. Signed-off-by: 185******37 --- services/ans/src/advanced_notification_publish_service.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/services/ans/src/advanced_notification_publish_service.cpp b/services/ans/src/advanced_notification_publish_service.cpp index 8f12198d6..d7b750c5d 100644 --- a/services/ans/src/advanced_notification_publish_service.cpp +++ b/services/ans/src/advanced_notification_publish_service.cpp @@ -67,7 +67,7 @@ ErrCode AdvancedNotificationService::SetDefaultNotificationEnabled( ANS_LOGE("Failed to create EnabledNotificationCallbackData instance"); return ERR_NO_MEMORY; } - SetSlotFlagsTrustlistsAsBundle(bundleOption); + SetSlotFlagsTrustlistsAsBundle(bundle); ErrCode result = ERR_OK; result = NotificationPreferences::GetInstance()->SetNotificationsEnabledForBundle(bundle, enabled); if (result == ERR_OK) { -- Gitee From 7ead384b7604be54131975a033557f9ad2c7fe88 Mon Sep 17 00:00:00 2001 From: markYao Date: Wed, 4 Sep 2024 19:19:49 +0800 Subject: [PATCH 033/167] =?UTF-8?q?=E3=80=90=E5=90=8C=E6=AD=A55.0-release?= =?UTF-8?q?=E3=80=91=E4=BC=98=E5=8C=96checkPermission=E9=80=BB=E8=BE=91?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: markYao --- .../core/common/include/ans_const_define.h | 3 ++ .../include/advanced_notification_service.h | 8 ++-- services/ans/src/access_token_helper.cpp | 13 ++---- .../advanced_notification_publish_service.cpp | 23 +++++----- .../ans/src/advanced_notification_service.cpp | 6 ++- .../advanced_notification_slot_service.cpp | 4 +- ...vanced_notification_subscriber_service.cpp | 7 ++- .../ans/src/advanced_notification_utils.cpp | 45 ++++++++----------- .../advanced_notification_utils_test.cpp | 30 ++----------- 9 files changed, 59 insertions(+), 80 deletions(-) diff --git a/frameworks/core/common/include/ans_const_define.h b/frameworks/core/common/include/ans_const_define.h index 0bb0d7b78..71872cc17 100644 --- a/frameworks/core/common/include/ans_const_define.h +++ b/frameworks/core/common/include/ans_const_define.h @@ -53,6 +53,9 @@ constexpr int32_t NOTIFICATION_MAX_COUNT = 1024; constexpr int32_t DO_NOT_DISTURB_PROFILE_MIN_ID = 1; constexpr int32_t DO_NOT_DISTURB_PROFILE_MAX_ID = 10; +constexpr int32_t NFC_UID = 1027; +constexpr int32_t PAC_UID = 7007; + // Default sound for notification const static Uri DEFAULT_NOTIFICATION_SOUND("file://system/etc/Light.ogg"); const static std::vector DEFAULT_NOTIFICATION_VIBRATION = {200}; diff --git a/services/ans/include/advanced_notification_service.h b/services/ans/include/advanced_notification_service.h index c7b509233..ca9211e90 100644 --- a/services/ans/include/advanced_notification_service.h +++ b/services/ans/include/advanced_notification_service.h @@ -365,9 +365,6 @@ public: ErrCode GetUnifiedGroupInfoFromDb(std::string &enable); - ErrCode RemoveNotificationBySlot(const sptr &bundleOption, - const sptr &slot, const int reason); - /** * @brief Delete notification based on key. * @@ -1183,6 +1180,8 @@ private: const std::shared_ptr &first, const std::shared_ptr &second); ErrCode FlowControl(const std::shared_ptr &record); ErrCode PublishFlowControl(const std::shared_ptr &record); + ErrCode RemoveNotificationBySlot(const sptr &bundleOption, + const sptr &slot, const int reason); sptr GenerateSortingMap(); static sptr GenerateBundleOption(); @@ -1312,7 +1311,8 @@ private: const sptr &request, const sptr &bundleOption); ErrCode IsAllowedNotifyForBundle(const sptr &bundleOption, bool &allowed); void FillActionButtons(const sptr &request); - ErrCode IsAllowedGetNotificationByFilter(const std::shared_ptr &record); + ErrCode IsAllowedGetNotificationByFilter(const std::shared_ptr &record, + const sptr &bundleOption); ErrCode FillRequestByKeys(const sptr &oldRequest, const std::vector extraInfoKeys, sptr &newRequest); ErrCode IsAllowedRemoveSlot(const sptr &bundleOption, diff --git a/services/ans/src/access_token_helper.cpp b/services/ans/src/access_token_helper.cpp index e0c636abd..26ce3af84 100644 --- a/services/ans/src/access_token_helper.cpp +++ b/services/ans/src/access_token_helper.cpp @@ -81,18 +81,13 @@ bool AccessTokenHelper::CheckPermission(const std::string &permission) { ANS_LOGD("%{public}s", __FUNCTION__); HaMetaMessage message = HaMetaMessage(EventSceneId::SCENE_1, EventBranchId::BRANCH_1); - if (supportCheckSaPermission_.compare("non-initilization") == 0) { - supportCheckSaPermission_ = OHOS::system::GetParameter(NOTIFICATION_ANS_CHECK_SA_PERMISSION, "false"); - } auto tokenCaller = IPCSkeleton::GetCallingTokenID(); - if (supportCheckSaPermission_.compare("true") != 0) { - bool isSubsystem = VerifyNativeToken(tokenCaller); - if (isSubsystem) { - return true; - } - } + int32_t callingUid = IPCSkeleton::GetCallingUid(); + int32_t callingPid = IPCSkeleton::GetCallingPid(); bool result = VerifyCallerPermission(tokenCaller, permission); if (!result) { + ANS_LOGE("CheckPermission failed %{public}s, %{public}d, %{public}d", + permission.c_str(), callingUid, callingPid); message.Message("Permission denied: " + permission, true); NotificationAnalyticsUtil::ReportModifyEvent(message); } diff --git a/services/ans/src/advanced_notification_publish_service.cpp b/services/ans/src/advanced_notification_publish_service.cpp index 1da6a1b2d..1f34887f3 100644 --- a/services/ans/src/advanced_notification_publish_service.cpp +++ b/services/ans/src/advanced_notification_publish_service.cpp @@ -51,6 +51,8 @@ constexpr char FOUNDATION_BUNDLE_NAME[] = "ohos.global.systemres"; constexpr int32_t HOURS_IN_ONE_DAY = 24; const static std::string NOTIFICATION_EVENT_PUSH_AGENT = "notification.event.PUSH_AGENT"; constexpr int32_t RSS_PID = 3051; +constexpr int32_t ANS_UID = 5523; +constexpr int32_t PSS_UID = 7123; constexpr int32_t TYPE_CODE_DOWNLOAD = 8; constexpr int32_t OPERATION_TYPE_COMMON_EVENT = 4; @@ -292,8 +294,10 @@ ErrCode AdvancedNotificationService::CancelAsBundle( return ERR_ANS_NON_SYSTEM_APP; } - if (!AccessTokenHelper::CheckPermission(OHOS_PERMISSION_NOTIFICATION_CONTROLLER) || - !AccessTokenHelper::CheckPermission(OHOS_PERMISSION_NOTIFICATION_AGENT_CONTROLLER)) { + int32_t callingUid = IPCSkeleton::GetCallingUid(); + if ((callingUid != NFC_UID && callingUid != PSS_UID && callingUid != PAC_UID) && + (!AccessTokenHelper::CheckPermission(OHOS_PERMISSION_NOTIFICATION_CONTROLLER) || + !AccessTokenHelper::CheckPermission(OHOS_PERMISSION_NOTIFICATION_AGENT_CONTROLLER))) { std::string message = "no acl permission"; OHOS::Notification::HaMetaMessage haMetaMessage = HaMetaMessage(2, 2) .ErrorCode(ERR_ANS_PERMISSION_DENIED).NotificationId(notificationId); @@ -853,7 +857,8 @@ ErrCode AdvancedNotificationService::SetNotificationsEnabledForSpecialBundle( return ERR_ANS_NON_SYSTEM_APP; } - if (!AccessTokenHelper::CheckPermission(OHOS_PERMISSION_NOTIFICATION_CONTROLLER)) { + int32_t callingUid = IPCSkeleton::GetCallingUid(); + if (callingUid != ANS_UID && !AccessTokenHelper::CheckPermission(OHOS_PERMISSION_NOTIFICATION_CONTROLLER)) { return ERR_ANS_PERMISSION_DENIED; } @@ -1059,7 +1064,9 @@ ErrCode AdvancedNotificationService::IsSpecialBundleAllowedNotify( return ERR_ANS_NON_SYSTEM_APP; } - if (!AccessTokenHelper::CheckPermission(OHOS_PERMISSION_NOTIFICATION_CONTROLLER)) { + int32_t callingUid = IPCSkeleton::GetCallingUid(); + if ((callingUid != ANS_UID && callingUid != PAC_UID) + && !AccessTokenHelper::CheckPermission(OHOS_PERMISSION_NOTIFICATION_CONTROLLER)) { return ERR_ANS_PERMISSION_DENIED; } @@ -1444,7 +1451,8 @@ ErrCode AdvancedNotificationService::RemoveAllNotificationsInner(const sptr bundle = GenerateValidBundleOption(bundleOption); if (bundle == nullptr) { return ERR_ANS_INVALID_BUNDLE; diff --git a/services/ans/src/advanced_notification_service.cpp b/services/ans/src/advanced_notification_service.cpp index a8803cc80..91044e9d4 100644 --- a/services/ans/src/advanced_notification_service.cpp +++ b/services/ans/src/advanced_notification_service.cpp @@ -88,6 +88,7 @@ constexpr int32_t UI_HALF = 2; constexpr int32_t MAX_LIVEVIEW_HINT_COUNT = 1; constexpr int32_t MAX_SOUND_ITEM_LENGTH = 2048; constexpr int32_t BUNDLE_OPTION_UID_DEFAULT_VALUE = 0; +constexpr int32_t RSS_UID = 3051; const std::string MMS_BUNDLE_NAME = "com.ohos.mms"; const std::string CONTACTS_BUNDLE_NAME = "com.ohos.contacts"; @@ -1325,8 +1326,9 @@ ErrCode AdvancedNotificationService::GetAllActiveNotifications(std::vector &record) + const std::shared_ptr &record, const sptr &bundleOption) { - bool isSubsystem = AccessTokenHelper::VerifyNativeToken(IPCSkeleton::GetCallingTokenID()); - if (isSubsystem || AccessTokenHelper::IsSystemApp()) { - if (AccessTokenHelper::CheckPermission(OHOS_PERMISSION_NOTIFICATION_CONTROLLER)) { - return ERR_OK; - } - - ANS_LOGD("Get live view by filter failed because check permission is false."); - return ERR_ANS_PERMISSION_DENIED; - } - - std::string bundle = GetClientBundleName(); - if (bundle.empty()) { - ANS_LOGD("Get live view by filter failed because bundle name is empty."); - return ERR_ANS_PERMISSION_DENIED; - } - int32_t uid = IPCSkeleton::GetCallingUid(); - if (uid == record->bundleOption->GetUid() && bundle == record->bundleOption->GetBundleName()) { + if (bundleOption->GetUid() == record->bundleOption->GetUid() && + bundleOption->GetBundleName() == record->bundleOption->GetBundleName()) { return ERR_OK; } - - ANS_LOGD("Get live view by filter failed because no permission."); + ANS_LOGE("Get live view by filter failed because no permission."); return ERR_ANS_PERMISSION_DENIED; } @@ -290,17 +274,26 @@ ErrCode AdvancedNotificationService::GetActiveNotificationByFilter( const std::vector extraInfoKeys, sptr &request) { ANS_LOGD("%{public}s", __FUNCTION__); + sptr bundle = GenerateValidBundleOption(bundleOption); + if (bundle == nullptr) { + return ERR_ANS_INVALID_BUNDLE; + } + // get other bundle notification need controller permission + if (bundle->GetUid() == IPCSkeleton::GetCallingUid()) { + ANS_LOGI("Get self notification uid: %{public}d, curUid: %{public}d.", + bundle->GetUid(), IPCSkeleton::GetCallingUid()); + } else { + if (!AccessTokenHelper::CheckPermission(OHOS_PERMISSION_NOTIFICATION_CONTROLLER)) { + ANS_LOGW("Get live view by filter failed because check permission is false."); + return ERR_ANS_PERMISSION_DENIED; + } + } if (notificationSvrQueue_ == nullptr) { ANS_LOGE("Serial queue is invalidity."); return ERR_ANS_INVALID_PARAM; } - sptr bundle = GenerateValidBundleOption(bundleOption); - if (bundle == nullptr) { - return ERR_ANS_INVALID_BUNDLE; - } - ErrCode result = ERR_ANS_NOTIFICATION_NOT_EXISTS; ffrt::task_handle handler = notificationSvrQueue_->submit_h(std::bind([&]() { ANS_LOGD("ffrt enter!"); @@ -309,7 +302,7 @@ ErrCode AdvancedNotificationService::GetActiveNotificationByFilter( if ((record == nullptr) || (!record->request->IsCommonLiveView())) { return; } - result = IsAllowedGetNotificationByFilter(record); + result = IsAllowedGetNotificationByFilter(record, bundle); if (result != ERR_OK) { return; } diff --git a/services/ans/test/unittest/advanced_notification_utils_test.cpp b/services/ans/test/unittest/advanced_notification_utils_test.cpp index 4b6acc76f..233545ade 100644 --- a/services/ans/test/unittest/advanced_notification_utils_test.cpp +++ b/services/ans/test/unittest/advanced_notification_utils_test.cpp @@ -170,37 +170,15 @@ HWTEST_F(AnsUtilsTest, FillRequestByKeys_00001, Function | SmallTest | Level1) */ HWTEST_F(AnsUtilsTest, IsAllowedGetNotificationByFilter_00001, Function | SmallTest | Level1) { + sptr bundle = new NotificationBundleOption("test", 1); auto record = std::make_shared(); record->bundleOption = new NotificationBundleOption("test", 1); - MockGetTokenTypeFlag(Security::AccessToken::ATokenTypeEnum::TOKEN_HAP); - MockIsSystemApp(true); - MockIsVerfyPermisson(false); - int ret = advancedNotificationService_->IsAllowedGetNotificationByFilter(record); - ASSERT_EQ(ret, (int)ERR_ANS_PERMISSION_DENIED); - - MockIsVerfyPermisson(true); - ret = advancedNotificationService_->IsAllowedGetNotificationByFilter(record); + int ret = advancedNotificationService_->IsAllowedGetNotificationByFilter(record, bundle); ASSERT_EQ(ret, (int)ERR_OK); -} - -/** - * @tc.name: IsAllowedGetNotificationByFilter_00002 - * @tc.desc: Test IsAllowedGetNotificationByFilter - * @tc.type: FUNC - * @tc.require: issue - */ -HWTEST_F(AnsUtilsTest, IsAllowedGetNotificationByFilter_00002, Function | SmallTest | Level1) -{ - auto record = std::make_shared(); - record->bundleOption = new NotificationBundleOption("test", IPCSkeleton::GetCallingUid()); - MockGetTokenTypeFlag(Security::AccessToken::ATokenTypeEnum::TOKEN_HAP); - MockIsSystemApp(false); - int ret = advancedNotificationService_->IsAllowedGetNotificationByFilter(record); - ASSERT_EQ(ret, (int)ERR_ANS_PERMISSION_DENIED); record->bundleOption->SetBundleName("bundleName"); - ret = advancedNotificationService_->IsAllowedGetNotificationByFilter(record); - ASSERT_EQ(ret, (int)ERR_OK); + ret = advancedNotificationService_->IsAllowedGetNotificationByFilter(record, bundle); + ASSERT_EQ(ret, (int)ERR_ANS_PERMISSION_DENIED); } /** -- Gitee From d623920b6dbcfc281b9432e9d21a070763dcb8bd Mon Sep 17 00:00:00 2001 From: xdongs Date: Sat, 31 Aug 2024 19:32:29 +0800 Subject: [PATCH 034/167] =?UTF-8?q?=E5=AD=90=E7=AA=97=E5=8F=A3=E5=88=A0?= =?UTF-8?q?=E9=99=A4-=E5=95=86=E5=88=86?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: xdongs --- .../main/ets/ServiceExtAbility/NotificationServiceExtAbility.ts | 2 ++ .../entry/src/main/ets/pages/notificationDialog.ets | 1 + 2 files changed, 3 insertions(+) diff --git a/services/dialog_ui/enable_notification_dialog/entry/src/main/ets/ServiceExtAbility/NotificationServiceExtAbility.ts b/services/dialog_ui/enable_notification_dialog/entry/src/main/ets/ServiceExtAbility/NotificationServiceExtAbility.ts index be1217905..7f5d39071 100644 --- a/services/dialog_ui/enable_notification_dialog/entry/src/main/ets/ServiceExtAbility/NotificationServiceExtAbility.ts +++ b/services/dialog_ui/enable_notification_dialog/entry/src/main/ets/ServiceExtAbility/NotificationServiceExtAbility.ts @@ -79,6 +79,7 @@ export class EnableNotificationDialog { extensionWindow:uiExtensionHost.UIExtensionHostWindowProxy; storage: LocalStorage; stageModel: boolean; + subWindow: window.Window; constructor(id: number, want: Want, stageModel: boolean) { this.id = id; @@ -163,6 +164,7 @@ export class EnableNotificationDialog { isTopmost: true }; let subWindow = await extensionWindow.createSubWindowWithOptions('subWindowForHost' + Date(), subWindowOpts); + this.subWindow = subWindow; let dis = display.getDefaultDisplaySync(); await subWindow?.resize(dis.width, dis.height); await subWindow.loadContent(EnableNotificationDialog.DIALOG_PATH, this.storage); diff --git a/services/dialog_ui/enable_notification_dialog/entry/src/main/ets/pages/notificationDialog.ets b/services/dialog_ui/enable_notification_dialog/entry/src/main/ets/pages/notificationDialog.ets index af45bae1a..89053f31d 100644 --- a/services/dialog_ui/enable_notification_dialog/entry/src/main/ets/pages/notificationDialog.ets +++ b/services/dialog_ui/enable_notification_dialog/entry/src/main/ets/pages/notificationDialog.ets @@ -329,6 +329,7 @@ struct PermissionDialog { console.error(TAG, `NotificationDialog enable error, code is ${err?.code}`); await this.dialog?.destroyException(); } finally { + await this.dialog?.subWindow?.destroyWindow(); this.session?.terminateSelf(); } } -- Gitee From d0615c179e0cf09d531e46feec9911bb48a7a1b5 Mon Sep 17 00:00:00 2001 From: xdongs Date: Tue, 3 Sep 2024 12:01:23 +0800 Subject: [PATCH 035/167] thread Signed-off-by: xdongs --- frameworks/js/napi/src/subscribe.cpp | 155 ++++++++++++++------------- 1 file changed, 82 insertions(+), 73 deletions(-) diff --git a/frameworks/js/napi/src/subscribe.cpp b/frameworks/js/napi/src/subscribe.cpp index 58047c256..3ae3b8929 100644 --- a/frameworks/js/napi/src/subscribe.cpp +++ b/frameworks/js/napi/src/subscribe.cpp @@ -36,6 +36,22 @@ const std::string BADGE_CHANGED = "OnBadgeChanged"; const std::string BADGE_ENABLED_CHANGED = "OnBadgeEnabledChanged"; const std::string BATCH_CANCEL = "onBatchCancel"; +enum class Type { + UNKNOWN, + CANCEL, + BATCH_CANCEL, + CONSUME, + UPDATE, + CONNECTED, + DIS_CONNECTED, + DIE, + DISTURB_DATE_CHANGE, + DISTURB_CHANGED, + ENABLE_NOTIFICATION_CHANGED, + BADGE_CHANGED, + BADGE_ENABLED_CHANGED +}; + struct NotificationReceiveDataWorker { napi_env env = nullptr; napi_ref ref = nullptr; @@ -49,6 +65,7 @@ struct NotificationReceiveDataWorker { int32_t result = 0; int32_t disturbMode = 0; SubscriberInstance *subscriber = nullptr; + Type type; }; napi_value SetSubscribeCallbackData(const napi_env &env, @@ -221,6 +238,7 @@ void SubscriberInstance::OnCanceled(const std::shared_ptrdeleteReason = deleteReason; dataWorker->env = canceCallbackInfo_.env; dataWorker->ref = canceCallbackInfo_.ref; + dataWorker->type = Type::CANCEL; napi_acquire_threadsafe_function(canceCallbackInfo_.tsfn); napi_call_threadsafe_function(canceCallbackInfo_.tsfn, dataWorker, napi_tsfn_nonblocking); @@ -297,6 +315,7 @@ void SubscriberInstance::OnBatchCanceled(const std::vectordeleteReason = deleteReason; dataWorker->env = batchCancelCallbackInfo_.env; dataWorker->ref = batchCancelCallbackInfo_.ref; + dataWorker->type = Type::BATCH_CANCEL; napi_acquire_threadsafe_function(batchCancelCallbackInfo_.tsfn); napi_call_threadsafe_function(batchCancelCallbackInfo_.tsfn, dataWorker, napi_tsfn_nonblocking); @@ -392,6 +411,7 @@ void SubscriberInstance::OnConsumed(const std::shared_ptrsortingMap = sortingMap; dataWorker->env = consumeCallbackInfo_.env; dataWorker->ref = consumeCallbackInfo_.ref; + dataWorker->type = Type::CONSUME; napi_acquire_threadsafe_function(consumeCallbackInfo_.tsfn); napi_call_threadsafe_function(consumeCallbackInfo_.tsfn, dataWorker, napi_tsfn_nonblocking); @@ -450,6 +470,7 @@ void SubscriberInstance::OnUpdate(const std::shared_ptr dataWorker->sortingMap = sortingMap; dataWorker->env = updateCallbackInfo_.env; dataWorker->ref = updateCallbackInfo_.ref; + dataWorker->type = Type::UPDATE; napi_acquire_threadsafe_function(updateCallbackInfo_.tsfn); napi_call_threadsafe_function(updateCallbackInfo_.tsfn, dataWorker, napi_tsfn_nonblocking); @@ -493,6 +514,7 @@ void SubscriberInstance::OnConnected() dataWorker->env = subscribeCallbackInfo_.env; dataWorker->ref = subscribeCallbackInfo_.ref; + dataWorker->type = Type::CONNECTED; napi_acquire_threadsafe_function(subscribeCallbackInfo_.tsfn); napi_call_threadsafe_function(subscribeCallbackInfo_.tsfn, dataWorker, napi_tsfn_nonblocking); @@ -538,7 +560,8 @@ void SubscriberInstance::OnDisconnected() dataWorker->env = unsubscribeCallbackInfo_.env; dataWorker->ref = unsubscribeCallbackInfo_.ref; dataWorker->subscriber = this; - + dataWorker->type = Type::DIS_CONNECTED; + napi_acquire_threadsafe_function(unsubscribeCallbackInfo_.tsfn); napi_call_threadsafe_function(unsubscribeCallbackInfo_.tsfn, dataWorker, napi_tsfn_nonblocking); napi_release_threadsafe_function(unsubscribeCallbackInfo_.tsfn, napi_tsfn_abort); @@ -578,6 +601,7 @@ void SubscriberInstance::OnDied() dataWorker->env = dieCallbackInfo_.env; dataWorker->ref = dieCallbackInfo_.ref; + dataWorker->type = Type::DIE; napi_acquire_threadsafe_function(dieCallbackInfo_.tsfn); napi_call_threadsafe_function(dieCallbackInfo_.tsfn, dataWorker, napi_tsfn_nonblocking); @@ -639,6 +663,7 @@ void SubscriberInstance::OnDoNotDisturbDateChange(const std::shared_ptrdate = *date; dataWorker->env = disturbDateCallbackInfo_.env; dataWorker->ref = disturbDateCallbackInfo_.ref; + dataWorker->type = Type::DISTURB_DATE_CHANGE; napi_acquire_threadsafe_function(disturbDateCallbackInfo_.tsfn); napi_call_threadsafe_function(disturbDateCallbackInfo_.tsfn, dataWorker, napi_tsfn_nonblocking); @@ -699,6 +724,7 @@ void SubscriberInstance::onDoNotDisturbChanged(const std::shared_ptrdate = *date; dataWorker->env = disturbChangedCallbackInfo_.env; dataWorker->ref = disturbChangedCallbackInfo_.ref; + dataWorker->type = Type::DISTURB_CHANGED; napi_acquire_threadsafe_function(disturbChangedCallbackInfo_.tsfn); napi_call_threadsafe_function(disturbChangedCallbackInfo_.tsfn, dataWorker, napi_tsfn_nonblocking); @@ -759,6 +785,7 @@ void SubscriberInstance::OnEnabledNotificationChanged( dataWorker->callbackData = *callbackData; dataWorker->env = enabledNotificationCallbackInfo_.env; dataWorker->ref = enabledNotificationCallbackInfo_.ref; + dataWorker->type = Type::ENABLE_NOTIFICATION_CHANGED; napi_acquire_threadsafe_function(enabledNotificationCallbackInfo_.tsfn); napi_call_threadsafe_function(enabledNotificationCallbackInfo_.tsfn, dataWorker, napi_tsfn_nonblocking); @@ -818,6 +845,7 @@ void SubscriberInstance::OnBadgeChanged( dataWorker->badge = *badgeData; dataWorker->env = setBadgeCallbackInfo_.env; dataWorker->ref = setBadgeCallbackInfo_.ref; + dataWorker->type = Type::BADGE_CHANGED; napi_acquire_threadsafe_function(setBadgeCallbackInfo_.tsfn); napi_call_threadsafe_function(setBadgeCallbackInfo_.tsfn, dataWorker, napi_tsfn_nonblocking); @@ -874,6 +902,7 @@ void SubscriberInstance::OnBadgeEnabledChanged( dataWorker->callbackData = *callbackData; dataWorker->env = setBadgeEnabledCallbackInfo_.env; dataWorker->ref = setBadgeEnabledCallbackInfo_.ref; + dataWorker->type = Type::BADGE_ENABLED_CHANGED; napi_acquire_threadsafe_function(setBadgeEnabledCallbackInfo_.tsfn); napi_call_threadsafe_function(setBadgeEnabledCallbackInfo_.tsfn, dataWorker, napi_tsfn_nonblocking); @@ -1152,6 +1181,52 @@ void ThreadFinished(napi_env env, void* data, [[maybe_unused]] void* context) ANS_LOGD("ThreadFinished"); } +void ThreadSafeCommon(napi_env env, napi_value jsCallback, void* context, void* data) +{ + ANS_LOGI("common thread safe start"); + auto dataWorkerData = reinterpret_cast(data); + switch (dataWorkerData->type) { + case Type::CANCEL: + ThreadSafeOnCancel(env, jsCallback, context, data); + break; + case Type::BATCH_CANCEL: + ThreadSafeOnBatchCancel(env, jsCallback, context, data); + break; + case Type::CONSUME: + ThreadSafeOnConsumed(env, jsCallback, context, data); + break; + case Type::UPDATE: + ThreadSafeOnUpdate(env, jsCallback, context, data); + break; + case Type::CONNECTED: + ThreadSafeOnConnected(env, jsCallback, context, data); + break; + case Type::DIS_CONNECTED: + ThreadSafeOnDisconnected(env, jsCallback, context, data); + break; + case Type::DIE: + ThreadSafeOnDestroy(env, jsCallback, context, data); + break; + case Type::DISTURB_DATE_CHANGE: + ThreadSafeOnDoNotDisturbDateChange(env, jsCallback, context, data); + break; + case Type::DISTURB_CHANGED: + ThreadSafeOnDoNotDisturbChanged(env, jsCallback, context, data); + break; + case Type::ENABLE_NOTIFICATION_CHANGED: + ThreadSafeOnEnabledNotificationChanged(env, jsCallback, context, data); + break; + case Type::BADGE_CHANGED: + ThreadSafeOnBadgeChanged(env, jsCallback, context, data); + break; + case Type::BADGE_ENABLED_CHANGED: + ThreadSafeOnBadgeEnabledChanged(env, jsCallback, context, data); + break; + default: + break; + } +} + napi_value GetNotificationSubscriber( const napi_env &env, const napi_value &value, SubscriberInstancesInfo &subscriberInfo) { @@ -1170,6 +1245,12 @@ napi_value GetNotificationSubscriber( napi_create_reference(env, value, 1, &subscriberInfo.ref); + napi_value resourceName = nullptr; + napi_create_string_latin1(env, "tsfn", NAPI_AUTO_LENGTH, &resourceName); + napi_threadsafe_function tsfn = nullptr; + napi_create_threadsafe_function(env, nullptr, nullptr, resourceName, 0, 1, subscriberInfo.ref, + ThreadFinished, nullptr, ThreadSafeCommon, &tsfn); + // onConsume?:(data: SubscribeCallbackData) => void NAPI_CALL(env, napi_has_named_property(env, value, "onConsume", &hasProperty)); if (hasProperty) { @@ -1183,12 +1264,6 @@ napi_value GetNotificationSubscriber( return nullptr; } napi_create_reference(env, nOnConsumed, 1, &result); - - napi_value resourceName = nullptr; - napi_create_string_latin1(env, "onConsume", NAPI_AUTO_LENGTH, &resourceName); - napi_threadsafe_function tsfn = nullptr; - napi_create_threadsafe_function(env, nullptr, nullptr, resourceName, 0, 1, subscriberInfo.ref, - ThreadFinished, nullptr, ThreadSafeOnConsumed, &tsfn); subscriberInfo.subscriber->SetCallbackInfo(CONSUME, env, result, tsfn); } // onCancel?:(data: SubscribeCallbackData) => void @@ -1204,12 +1279,6 @@ napi_value GetNotificationSubscriber( return nullptr; } napi_create_reference(env, nOnCanceled, 1, &result); - - napi_value resourceName = nullptr; - napi_create_string_latin1(env, "onCancel", NAPI_AUTO_LENGTH, &resourceName); - napi_threadsafe_function tsfn = nullptr; - napi_create_threadsafe_function(env, nullptr, nullptr, resourceName, 0, 1, subscriberInfo.ref, - ThreadFinished, nullptr, ThreadSafeOnCancel, &tsfn); subscriberInfo.subscriber->SetCallbackInfo(CANCEL, env, result, tsfn); } // onUpdate?:(data: NotificationSortingMap) => void @@ -1225,12 +1294,6 @@ napi_value GetNotificationSubscriber( return nullptr; } napi_create_reference(env, nOnUpdate, 1, &result); - - napi_value resourceName = nullptr; - napi_create_string_latin1(env, "onUpdate", NAPI_AUTO_LENGTH, &resourceName); - napi_threadsafe_function tsfn = nullptr; - napi_create_threadsafe_function(env, nullptr, nullptr, resourceName, 0, 1, subscriberInfo.ref, - ThreadFinished, nullptr, ThreadSafeOnUpdate, &tsfn); subscriberInfo.subscriber->SetCallbackInfo(UPDATE, env, result, tsfn); } // onConnect?:() => void @@ -1246,12 +1309,6 @@ napi_value GetNotificationSubscriber( return nullptr; } napi_create_reference(env, nOnConnected, 1, &result); - - napi_value resourceName = nullptr; - napi_create_string_latin1(env, "onConnect", NAPI_AUTO_LENGTH, &resourceName); - napi_threadsafe_function tsfn = nullptr; - napi_create_threadsafe_function(env, nullptr, nullptr, resourceName, 0, 1, subscriberInfo.ref, - ThreadFinished, nullptr, ThreadSafeOnConnected, &tsfn); subscriberInfo.subscriber->SetCallbackInfo(CONNECTED, env, result, tsfn); } // onDisconnect?:() => void @@ -1267,12 +1324,6 @@ napi_value GetNotificationSubscriber( return nullptr; } napi_create_reference(env, nOnDisConnect, 1, &result); - - napi_value resourceName = nullptr; - napi_create_string_latin1(env, "onDisconnect", NAPI_AUTO_LENGTH, &resourceName); - napi_threadsafe_function tsfn = nullptr; - napi_create_threadsafe_function(env, nullptr, nullptr, resourceName, 0, 1, subscriberInfo.ref, - ThreadFinished, nullptr, ThreadSafeOnDisconnected, &tsfn); subscriberInfo.subscriber->SetCallbackInfo(DIS_CONNECTED, env, result, tsfn); } // onDestroy?:() => void @@ -1288,12 +1339,6 @@ napi_value GetNotificationSubscriber( return nullptr; } napi_create_reference(env, nOnDied, 1, &result); - - napi_value resourceName = nullptr; - napi_create_string_latin1(env, "onDestroy", NAPI_AUTO_LENGTH, &resourceName); - napi_threadsafe_function tsfn = nullptr; - napi_create_threadsafe_function(env, nullptr, nullptr, resourceName, 0, 1, subscriberInfo.ref, - ThreadFinished, nullptr, ThreadSafeOnDestroy, &tsfn); subscriberInfo.subscriber->SetCallbackInfo(DIE, env, result, tsfn); } // onDisturbModeChange?:(mode: notification.DoNotDisturbMode) => void @@ -1325,12 +1370,6 @@ napi_value GetNotificationSubscriber( return nullptr; } napi_create_reference(env, nOnDisturbDateChanged, 1, &result); - - napi_value resourceName = nullptr; - napi_create_string_latin1(env, "onDoNotDisturbDateChange", NAPI_AUTO_LENGTH, &resourceName); - napi_threadsafe_function tsfn = nullptr; - napi_create_threadsafe_function(env, nullptr, nullptr, resourceName, 0, 1, subscriberInfo.ref, - ThreadFinished, nullptr, ThreadSafeOnDoNotDisturbDateChange, &tsfn); subscriberInfo.subscriber->SetCallbackInfo(DISTURB_DATE_CHANGE, env, result, tsfn); } @@ -1347,12 +1386,6 @@ napi_value GetNotificationSubscriber( return nullptr; } napi_create_reference(env, nOnDoNotDisturbChanged, 1, &result); - - napi_value resourceName = nullptr; - napi_create_string_latin1(env, "onDoNotDisturbChanged", NAPI_AUTO_LENGTH, &resourceName); - napi_threadsafe_function tsfn = nullptr; - napi_create_threadsafe_function(env, nullptr, nullptr, resourceName, 0, 1, subscriberInfo.ref, - ThreadFinished, nullptr, ThreadSafeOnDoNotDisturbChanged, &tsfn); subscriberInfo.subscriber->SetCallbackInfo(DISTURB_CHANGED, env, result, tsfn); } @@ -1369,12 +1402,6 @@ napi_value GetNotificationSubscriber( return nullptr; } napi_create_reference(env, nOnEnabledNotificationChanged, 1, &result); - - napi_value resourceName = nullptr; - napi_create_string_latin1(env, "onEnabledNotificationChanged", NAPI_AUTO_LENGTH, &resourceName); - napi_threadsafe_function tsfn = nullptr; - napi_create_threadsafe_function(env, nullptr, nullptr, resourceName, 0, 1, subscriberInfo.ref, - ThreadFinished, nullptr, ThreadSafeOnEnabledNotificationChanged, &tsfn); subscriberInfo.subscriber->SetCallbackInfo(ENABLE_NOTIFICATION_CHANGED, env, result, tsfn); } @@ -1391,12 +1418,6 @@ napi_value GetNotificationSubscriber( return nullptr; } napi_create_reference(env, nOnBadgeChanged, 1, &result); - - napi_value resourceName = nullptr; - napi_create_string_latin1(env, "onBadgeChanged", NAPI_AUTO_LENGTH, &resourceName); - napi_threadsafe_function tsfn = nullptr; - napi_create_threadsafe_function(env, nullptr, nullptr, resourceName, 0, 1, subscriberInfo.ref, - ThreadFinished, nullptr, ThreadSafeOnBadgeChanged, &tsfn); subscriberInfo.subscriber->SetCallbackInfo(BADGE_CHANGED, env, result, tsfn); } @@ -1413,12 +1434,6 @@ napi_value GetNotificationSubscriber( return nullptr; } napi_create_reference(env, nOnBadgeEnabledChanged, 1, &result); - - napi_value resourceName = nullptr; - napi_create_string_latin1(env, "onBadgeEnabledChanged", NAPI_AUTO_LENGTH, &resourceName); - napi_threadsafe_function tsfn = nullptr; - napi_create_threadsafe_function(env, nullptr, nullptr, resourceName, 0, 1, subscriberInfo.ref, - ThreadFinished, nullptr, ThreadSafeOnBadgeEnabledChanged, &tsfn); subscriberInfo.subscriber->SetCallbackInfo(BADGE_ENABLED_CHANGED, env, result, tsfn); } @@ -1435,12 +1450,6 @@ napi_value GetNotificationSubscriber( return nullptr; } napi_create_reference(env, onBatchCancel, 1, &result); - - napi_value resourceName = nullptr; - napi_create_string_latin1(env, "onBatchCancel", NAPI_AUTO_LENGTH, &resourceName); - napi_threadsafe_function tsfn = nullptr; - napi_create_threadsafe_function(env, nullptr, nullptr, resourceName, 0, 1, subscriberInfo.ref, - ThreadFinished, nullptr, ThreadSafeOnBatchCancel, &tsfn); subscriberInfo.subscriber->SetCallbackInfo(BATCH_CANCEL, env, result, tsfn); } -- Gitee From 59307df46e1fb1b61762ef2cd47f46d388d538c1 Mon Sep 17 00:00:00 2001 From: xdongs Date: Tue, 3 Sep 2024 20:11:48 +0800 Subject: [PATCH 036/167] =?UTF-8?q?timer=20callback=E6=9C=AA=E9=87=8A?= =?UTF-8?q?=E6=94=BE=20Signed-off-by:=20xdongs=20?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- services/ans/src/notification_timer_info.cpp | 1 + 1 file changed, 1 insertion(+) diff --git a/services/ans/src/notification_timer_info.cpp b/services/ans/src/notification_timer_info.cpp index 924a96617..4ff03f8f7 100644 --- a/services/ans/src/notification_timer_info.cpp +++ b/services/ans/src/notification_timer_info.cpp @@ -46,6 +46,7 @@ void NotificationTimerInfo::OnTrigger() ANS_LOGD("ffrt enter!"); if (callBack_ != nullptr) { callBack_(); + callBack_ = nullptr; } })); notificationSvrQueue_->wait(handler); -- Gitee From 0e179a148109c452d16d8c175c6acc2dc288db23 Mon Sep 17 00:00:00 2001 From: 185******37 Date: Thu, 5 Sep 2024 07:10:27 +0000 Subject: [PATCH 037/167] update services/ans/src/advanced_notification_publish_service.cpp. Signed-off-by: 185******37 --- services/ans/src/advanced_notification_publish_service.cpp | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/services/ans/src/advanced_notification_publish_service.cpp b/services/ans/src/advanced_notification_publish_service.cpp index 5a42b0104..79e98a615 100644 --- a/services/ans/src/advanced_notification_publish_service.cpp +++ b/services/ans/src/advanced_notification_publish_service.cpp @@ -2073,7 +2073,9 @@ ErrCode AdvancedNotificationService::PublishNotificationBySa(const sptrGetCreatorUid(); if (request->GetOwnerUid() != DEFAULT_UID) { -- Gitee From 5e82eebbee6b82992f3fe8d672e7393bfaa8feb0 Mon Sep 17 00:00:00 2001 From: 185******37 Date: Thu, 5 Sep 2024 07:12:14 +0000 Subject: [PATCH 038/167] update services/ans/src/advanced_notification_service.cpp. Signed-off-by: 185******37 --- services/ans/src/advanced_notification_service.cpp | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/services/ans/src/advanced_notification_service.cpp b/services/ans/src/advanced_notification_service.cpp index caad9d98b..bd77827d9 100644 --- a/services/ans/src/advanced_notification_service.cpp +++ b/services/ans/src/advanced_notification_service.cpp @@ -609,7 +609,9 @@ ErrCode AdvancedNotificationService::PublishPreparedNotification(const sptrLocalControl(request); -- Gitee From 135ca142bff2720b22a35f378bfc9ff78e3f8c7c Mon Sep 17 00:00:00 2001 From: z30053788 Date: Thu, 5 Sep 2024 20:27:42 +0800 Subject: [PATCH 039/167] cherry pick 6a76919 from https://gitee.com/zhaobaoxin1/notification_distributed_notification_service/pulls/2149 update Signed-off-by: z30053788 Change-Id: Id82ff530fd014a6c0478f0955a306e5cb60a61d6 --- .../ans/src/advanced_notification_utils.cpp | 22 +++++++++++-------- 1 file changed, 13 insertions(+), 9 deletions(-) diff --git a/services/ans/src/advanced_notification_utils.cpp b/services/ans/src/advanced_notification_utils.cpp index 21ec30969..aa0d5063c 100644 --- a/services/ans/src/advanced_notification_utils.cpp +++ b/services/ans/src/advanced_notification_utils.cpp @@ -640,15 +640,6 @@ void AdvancedNotificationService::OnBundleDataUpdate(const sptrGetNotificationsEnabledForBundle( bundleOption, enabled); - if (bundleOption->GetBundleName().compare("com.ohos.mms") == 0) { - uint32_t slotFlags = 63; - auto ret = NotificationPreferences::GetInstance()->GetNotificationSlotFlagsForBundle( - bundleOption, slotFlags); - if (ret != ERR_OK) { - ANS_LOGE("Failed to get slotflags for bundle, use default slotflags."); - } - UpdateSlotReminderModeBySlotFlags(bundleOption, slotFlags); - } if (errCode != ERR_OK) { ANS_LOGD("Get notification user option fail, need to insert data"); OnBundleDataAdd(bundleOption); @@ -1786,6 +1777,19 @@ void AdvancedNotificationService::InitNotificationEnableList() std::vector bundleInfos = GetBundlesOfActiveUser(); bool notificationEnable = false; for (const auto &bundleInfo : bundleInfos) { + if (bundleInfo.applicationInfo.bundleName.compare("com.ohos.mms") == 0) { + uint32_t slotFlags = 63; + sptr mmsBundle = new (std::nothrow) NotificationBundleOption( + bundleInfo.applicationInfo.bundleName, bundleInfo.uid); + if (mmsBundle == nullptr) { + ANS_LOGE("New bundle option obj error! bundlename:%{public}s", + bundleInfo.applicationInfo.bundleName.c_str()); + continue; + } + NotificationPreferences::GetInstance()->GetNotificationSlotFlagsForBundle( + mmsBundle, slotFlags); + UpdateSlotReminderModeBySlotFlags(mmsBundle, slotFlags); + } // Currently only the input from the whitelist is written if (!bundleInfo.applicationInfo.allowEnableNotification) { continue; -- Gitee From 81baf7422f28bd3b1f3fb5a21905a0f69b00b8fd Mon Sep 17 00:00:00 2001 From: baozeyu Date: Sat, 24 Aug 2024 16:29:22 +0800 Subject: [PATCH 040/167] =?UTF-8?q?public=E9=97=AE=E9=A2=98=E6=8C=91?= =?UTF-8?q?=E5=8D=95release?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: songbao1 --- .../mock/mock_bundle_manager_helper.cpp | 7 ++++++- services/ans/include/bundle_manager_helper.h | 19 +++++++++++++++++-- .../notification_preferences_database.h | 1 + .../advanced_notification_publish_service.cpp | 4 ++-- services/ans/src/bundle_manager_helper.cpp | 15 ++++++++++++--- .../src/notification_preferences_database.cpp | 12 ++++++++++++ services/ans/test/unittest/BUILD.gn | 1 + .../mock/mock_bundle_manager_helper.cpp | 7 ++++++- .../mock/mock_bundle_manager_helper.cpp | 7 ++++++- .../mock/mock_bundle_manager_helper.cpp | 7 ++++++- 10 files changed, 69 insertions(+), 11 deletions(-) diff --git a/frameworks/test/moduletest/mock/mock_bundle_manager_helper.cpp b/frameworks/test/moduletest/mock/mock_bundle_manager_helper.cpp index 80609a098..178cc27a4 100644 --- a/frameworks/test/moduletest/mock/mock_bundle_manager_helper.cpp +++ b/frameworks/test/moduletest/mock/mock_bundle_manager_helper.cpp @@ -65,5 +65,10 @@ void BundleManagerHelper::Connect() void BundleManagerHelper::Disconnect() {} + +bool BundleManagerHelper::CheckApiCompatibility(const std::string &bundleName, const int32_t &uid) +{ + return true; +} } // namespace Notification -} // namespace OHOS \ No newline at end of file +} // namespace OHOS diff --git a/services/ans/include/bundle_manager_helper.h b/services/ans/include/bundle_manager_helper.h index ea71a8b83..1f4b5d61b 100644 --- a/services/ans/include/bundle_manager_helper.h +++ b/services/ans/include/bundle_manager_helper.h @@ -108,6 +108,22 @@ public: bool GetBundleInfos( const AppExecFwk::BundleFlag flag, std::vector &bundleInfos, int32_t userId); + /** + * @brief Obtains the app index by uid. + * @param uid Indicates uid. + * @return Returns the query result if succeed, retrun 0(main index) otherwise. + */ + int32_t GetAppIndexByUid(const int32_t uid); + + /** + * @brief Check API compatibility. + * + * @param bundleName Indicates the bundle name. + * @param uid Indicates the bundle uid. + * @return Returns the check result. + */ + bool CheckApiCompatibility(const std::string &bundleName, const int32_t &uid); + private: void Connect(); void Disconnect(); @@ -123,5 +139,4 @@ private: }; } // namespace Notification } // namespace OHOS - -#endif // BASE_NOTIFICATION_DISTRIBUTED_NOTIFICATION_SERVICE_SERVICES_ANS_INCLUDE_BUNDLE_MANAGER_HELPER_H \ No newline at end of file +#endif // BASE_NOTIFICATION_DISTRIBUTED_NOTIFICATION_SERVICE_SERVICES_ANS_INCLUDE_BUNDLE_MANAGER_HELPER_H diff --git a/services/ans/include/notification_preferences_database.h b/services/ans/include/notification_preferences_database.h index aafa057b2..2c7b755dd 100644 --- a/services/ans/include/notification_preferences_database.h +++ b/services/ans/include/notification_preferences_database.h @@ -318,6 +318,7 @@ private: const std::string &findString, const int32_t &userId); void ExecuteDisturbeDB(sptr &slot, std::string &typeStr, std::string &valueStr, const std::string &findString, const int32_t &userId); + bool CheckApiCompatibility(const std::string &bundleName, const int32_t &uid); std::shared_ptr rdbDataManager_; }; } // namespace Notification diff --git a/services/ans/src/advanced_notification_publish_service.cpp b/services/ans/src/advanced_notification_publish_service.cpp index 1da6a1b2d..7db596f14 100644 --- a/services/ans/src/advanced_notification_publish_service.cpp +++ b/services/ans/src/advanced_notification_publish_service.cpp @@ -711,7 +711,7 @@ ErrCode AdvancedNotificationService::GetShowBadgeEnabledForBundle( result = NotificationPreferences::GetInstance()->IsShowBadge(bundle, enabled); if (result == ERR_ANS_PREFERENCES_NOTIFICATION_BUNDLE_NOT_EXIST) { result = ERR_OK; - enabled = false; + enabled = true; } })); notificationSvrQueue_->wait(handler); @@ -737,7 +737,7 @@ ErrCode AdvancedNotificationService::GetShowBadgeEnabled(bool &enabled) result = NotificationPreferences::GetInstance()->IsShowBadge(bundleOption, enabled); if (result == ERR_ANS_PREFERENCES_NOTIFICATION_BUNDLE_NOT_EXIST) { result = ERR_OK; - enabled = false; + enabled = true; } })); notificationSvrQueue_->wait(handler); diff --git a/services/ans/src/bundle_manager_helper.cpp b/services/ans/src/bundle_manager_helper.cpp index 71ff872a2..5ea086ca1 100644 --- a/services/ans/src/bundle_manager_helper.cpp +++ b/services/ans/src/bundle_manager_helper.cpp @@ -78,13 +78,22 @@ bool BundleManagerHelper::IsSystemApp(int32_t uid) } bool BundleManagerHelper::CheckApiCompatibility(const sptr &bundleOption) +{ + if (bundleOption == nullptr) { + ANS_LOGE("bundleOption is nullptr"); + return false; + } + return CheckApiCompatibility(bundleOption->GetBundleName(), bundleOption->GetUid()); +} + +bool BundleManagerHelper::CheckApiCompatibility(const std::string &bundleName, const int32_t &uid) { AppExecFwk::BundleInfo bundleInfo; int32_t callingUserId; - AccountSA::OsAccountManager::GetOsAccountLocalIdFromUid(bundleOption->GetUid(), callingUserId); - if (!GetBundleInfoByBundleName(bundleOption->GetBundleName(), callingUserId, bundleInfo)) { + AccountSA::OsAccountManager::GetOsAccountLocalIdFromUid(uid, callingUserId); + if (!GetBundleInfoByBundleName(bundleName, callingUserId, bundleInfo)) { ANS_LOGW("Failed to GetBundleInfoByBundleName, bundlename = %{public}s", - bundleOption->GetBundleName().c_str()); + bundleName.c_str()); return false; } diff --git a/services/ans/src/notification_preferences_database.cpp b/services/ans/src/notification_preferences_database.cpp index 1b5629041..421ef1f5d 100644 --- a/services/ans/src/notification_preferences_database.cpp +++ b/services/ans/src/notification_preferences_database.cpp @@ -25,6 +25,7 @@ #include "hitrace_meter_adapter.h" #include "os_account_manager.h" #include "ipc_skeleton.h" +#include "bundle_manager_helper.h" #include "uri.h" namespace OHOS { @@ -595,6 +596,7 @@ bool NotificationPreferencesDatabase::CheckBundle(const std::string &bundleName, NotificationPreferencesInfo::BundleInfo bundleInfo; bundleInfo.SetBundleName(bundleName); bundleInfo.SetBundleUid(bundleUid); + bundleInfo.SetEnableNotification(CheckApiCompatibility(bundleName, bundleUid)); result = PutBundleToDisturbeDB(bundleKeyStr, bundleInfo); break; } @@ -1978,5 +1980,15 @@ std::string NotificationPreferencesDatabase::GetAdditionalConfig(const std::stri ANS_LOGD("The additional config key is :%{public}s, value is :%{public}s.", key.c_str(), configValue.c_str()); return configValue; } + +bool NotificationPreferencesDatabase::CheckApiCompatibility(const std::string &bundleName, const int32_t &uid) +{ + ANS_LOGD("%{public}s", __FUNCTION__); + std::shared_ptr bundleManager = BundleManagerHelper::GetInstance(); + if (bundleManager == nullptr) { + return false; + } + return bundleManager->CheckApiCompatibility(bundleName, uid); +} } // namespace Notification } // namespace OHOS diff --git a/services/ans/test/unittest/BUILD.gn b/services/ans/test/unittest/BUILD.gn index 5eb12e218..e626898bf 100644 --- a/services/ans/test/unittest/BUILD.gn +++ b/services/ans/test/unittest/BUILD.gn @@ -1014,6 +1014,7 @@ ohos_unittest("notification_preferences_database_branch_test") { ] sources = [ + "${services_path}/ans/src/bundle_manager_helper.cpp", "${services_path}/ans/src/common/notification_config_parse.cpp", "${services_path}/ans/src/notification_preferences_database.cpp", "${services_path}/ans/src/notification_preferences_info.cpp", 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 501bf9e10..f03a0287d 100644 --- a/services/ans/test/unittest/mock/mock_bundle_manager_helper.cpp +++ b/services/ans/test/unittest/mock/mock_bundle_manager_helper.cpp @@ -73,5 +73,10 @@ bool BundleManagerHelper::GetDistributedNotificationEnabled(const std::string &b return true; } #endif + +bool BundleManagerHelper::CheckApiCompatibility(const std::string &bundleName, const int32_t &uid) +{ + return true; +} } // namespace Notification -} // namespace OHOS \ No newline at end of file +} // namespace OHOS diff --git a/services/test/moduletest/mock/mock_bundle_manager_helper.cpp b/services/test/moduletest/mock/mock_bundle_manager_helper.cpp index 080c28ec3..16c668789 100644 --- a/services/test/moduletest/mock/mock_bundle_manager_helper.cpp +++ b/services/test/moduletest/mock/mock_bundle_manager_helper.cpp @@ -65,5 +65,10 @@ void BundleManagerHelper::Connect() void BundleManagerHelper::Disconnect() {} + +bool BundleManagerHelper::CheckApiCompatibility(const std::string &bundleName, const int32_t &uid) +{ + return true; +} } // namespace Notification -} // namespace OHOS \ No newline at end of file +} // namespace OHOS diff --git a/test/bechmarktest/notification_services_test/mock/mock_bundle_manager_helper.cpp b/test/bechmarktest/notification_services_test/mock/mock_bundle_manager_helper.cpp index e0d31ddac..127129e1b 100644 --- a/test/bechmarktest/notification_services_test/mock/mock_bundle_manager_helper.cpp +++ b/test/bechmarktest/notification_services_test/mock/mock_bundle_manager_helper.cpp @@ -68,5 +68,10 @@ bool BundleManagerHelper::GetDistributedNotificationEnabled(const std::string &b return true; } #endif + +bool BundleManagerHelper::CheckApiCompatibility(const std::string &bundleName, const int32_t &uid) +{ + return true; +} } // namespace Notification -} // namespace OHOS \ No newline at end of file +} // namespace OHOS -- Gitee From a98a767b19b5b828be4dfc4cf86a306b85d5d5ff Mon Sep 17 00:00:00 2001 From: z30053788 Date: Fri, 6 Sep 2024 15:24:10 +0800 Subject: [PATCH 041/167] =?UTF-8?q?=E8=93=9D=E9=BB=84=E5=90=8C=E6=AD=A5?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: z30053788 Change-Id: Ied3bf57cd4f96ea5deef69939d9c73a19d6efbb6 --- frameworks/ans/BUILD.gn | 1 - .../notification_do_not_disturb_profile.cpp | 4 ++ .../notification_local_live_view_button.cpp | 2 +- .../ans/src/notification_subscriber.cpp | 3 +- .../manager/napi_enable_notification.h | 1 + .../src/manager/napi_enable_notification.cpp | 18 +++++-- .../napi/src/manager/napi_push_callback.cpp | 2 +- frameworks/js/napi/src/subscribe.cpp | 4 -- interfaces/inner_api/notification_request.h | 2 +- .../ans/src/advanced_datashare_observer.cpp | 1 - services/ans/src/common/file_utils.cpp | 2 +- .../ans/src/notification_dialog_manager.cpp | 3 +- .../src/notification_preferences_database.cpp | 4 ++ .../ans/src/notification_preferences_info.cpp | 3 -- .../ans/src/notification_rdb_data_mgr.cpp | 3 +- services/ans/src/notification_trust_list.cpp | 1 - .../ans/src/system_dialog_connect_stb.cpp | 4 ++ .../NotificationServiceExtAbility.ts | 51 ++++++++++++++++--- .../entry/src/main/ets/common/constant.ets | 8 +-- .../distributed_preferences_database.h | 1 + .../src/distributed_preferences_database.cpp | 14 +++++ test/fuzztest/fuzz_common_base/fuzz_data.h | 2 +- 22 files changed, 98 insertions(+), 36 deletions(-) diff --git a/frameworks/ans/BUILD.gn b/frameworks/ans/BUILD.gn index 24bfef29e..12e565fae 100644 --- a/frameworks/ans/BUILD.gn +++ b/frameworks/ans/BUILD.gn @@ -128,7 +128,6 @@ ohos_shared_library("ans_innerkits") { external_deps = [ "ability_base:want", "ability_base:zuri", - "ability_runtime:appkit_native", "bundle_framework:appexecfwk_base", "bundle_framework:appexecfwk_core", "c_utils:utils", diff --git a/frameworks/ans/src/notification_do_not_disturb_profile.cpp b/frameworks/ans/src/notification_do_not_disturb_profile.cpp index 2da7e16d6..0a4be2f85 100644 --- a/frameworks/ans/src/notification_do_not_disturb_profile.cpp +++ b/frameworks/ans/src/notification_do_not_disturb_profile.cpp @@ -138,6 +138,10 @@ std::string NotificationDoNotDisturbProfile::ToJson() void NotificationDoNotDisturbProfile::FromJson(const std::string &jsonObj) { nlohmann::json jsonObject = nlohmann::json::parse(jsonObj, nullptr, false); + if (jsonObject.is_null() or !jsonObject.is_object()) { + ANS_LOGE("Invalid JSON object"); + return; + } if (jsonObject.is_discarded()) { ANS_LOGE("Failed to parse json string."); return; diff --git a/frameworks/ans/src/notification_local_live_view_button.cpp b/frameworks/ans/src/notification_local_live_view_button.cpp index 81d163d51..8575ec20c 100644 --- a/frameworks/ans/src/notification_local_live_view_button.cpp +++ b/frameworks/ans/src/notification_local_live_view_button.cpp @@ -105,7 +105,7 @@ bool NotificationLocalLiveViewButton::ToJson(nlohmann::json &jsonObject) const jsonObject["icons"] = iconsArr; nlohmann::json iconResourceArr = nlohmann::json::array(); - for (const auto &resource : buttonIconsResource_) { + for (auto &resource : buttonIconsResource_) { if (!resource) { continue; } diff --git a/frameworks/ans/src/notification_subscriber.cpp b/frameworks/ans/src/notification_subscriber.cpp index 9b97dfb87..f734f06ae 100644 --- a/frameworks/ans/src/notification_subscriber.cpp +++ b/frameworks/ans/src/notification_subscriber.cpp @@ -168,13 +168,12 @@ void NotificationSubscriber::SubscriberImpl::OnBatchCanceled(const std::vector(), deleteReason); - } else { + } else if (notificationMap != nullptr) { subscriber_.OnBatchCanceled(notificationList, std::make_shared(*notificationMap), deleteReason); } } - void NotificationSubscriber::SubscriberImpl::OnCanceledList(const std::vector> ¬ifications, const sptr ¬ificationMap, int32_t deleteReason) { diff --git a/frameworks/js/napi/include/manager/napi_enable_notification.h b/frameworks/js/napi/include/manager/napi_enable_notification.h index 294190d45..76f84b513 100644 --- a/frameworks/js/napi/include/manager/napi_enable_notification.h +++ b/frameworks/js/napi/include/manager/napi_enable_notification.h @@ -34,6 +34,7 @@ napi_value ParseRequestEnableParameters(const napi_env &env, const napi_callback napi_value NapiIsNotificationEnabledSync(napi_env env, napi_callback_info info); bool CreateUIExtension(std::shared_ptr context, std::string &bundleName); void SendDialogEvent(std::string &bundleName, int32_t code); +void SetEnableParam(IsEnableParams ¶ms, const napi_env &env, napi_value &object); class ModalExtensionCallback { public: diff --git a/frameworks/js/napi/src/manager/napi_enable_notification.cpp b/frameworks/js/napi/src/manager/napi_enable_notification.cpp index 67a0fbd4f..8a0339015 100644 --- a/frameworks/js/napi/src/manager/napi_enable_notification.cpp +++ b/frameworks/js/napi/src/manager/napi_enable_notification.cpp @@ -382,11 +382,7 @@ napi_value ParseRequestEnableParameters(const napi_env &env, const napi_callback bool stageMode = false; napi_status status = OHOS::AbilityRuntime::IsStageContext(env, argv[PARAM0], stageMode); if (status == napi_ok && stageMode) { - auto context = OHOS::AbilityRuntime::GetStageModeContext(env, argv[PARAM0]); - sptr callerToken = context->GetToken(); - params.context = context; - params.callerToken = callerToken; - params.hasCallerToken = true; + SetEnableParam(params, env, argv[PARAM0]); } else { ANS_LOGE("Only support stage mode"); std::string msg = "Incorrect parameter types.Only support stage mode."; @@ -588,6 +584,18 @@ void SendDialogEvent(std::string &bundleName, int32_t code) ANS_LOGD("SendDialogEvent end"); } +void SetEnableParam(IsEnableParams ¶ms, const napi_env &env, napi_value &object) +{ + auto context = OHOS::AbilityRuntime::GetStageModeContext(env, object); + sptr callerToken = nullptr; + if (context != nullptr) { + callerToken = context->GetToken(); + } + params.context = context; + params.callerToken = callerToken; + params.hasCallerToken = true; +} + ModalExtensionCallback::ModalExtensionCallback() {} diff --git a/frameworks/js/napi/src/manager/napi_push_callback.cpp b/frameworks/js/napi/src/manager/napi_push_callback.cpp index 193784dce..066c6796a 100644 --- a/frameworks/js/napi/src/manager/napi_push_callback.cpp +++ b/frameworks/js/napi/src/manager/napi_push_callback.cpp @@ -133,7 +133,7 @@ int32_t JSPushCallBack::OnCheckNotification( AbilityRuntime::HandleEscape handleEscape(env_); std::string pkgName; - auto checkInfo = new (std::nothrow) NotificationCheckInfo {}; + auto checkInfo = std::make_shared(); checkInfo->ConvertJsonStringToValue(notificationData); NotificationConstant::SlotType outSlotType = static_cast(checkInfo->GetSlotType()); diff --git a/frameworks/js/napi/src/subscribe.cpp b/frameworks/js/napi/src/subscribe.cpp index 043c7549a..902425040 100644 --- a/frameworks/js/napi/src/subscribe.cpp +++ b/frameworks/js/napi/src/subscribe.cpp @@ -658,10 +658,6 @@ void ThreadSafeOnDoNotDisturbChanged(napi_env env, napi_value jsCallback, void* napi_value result = nullptr; napi_handle_scope scope; napi_open_handle_scope(dataWorkerData->env, &scope); - if (scope == nullptr) { - ANS_LOGE("Scope is null"); - return; - } napi_create_object(dataWorkerData->env, &result); if (!Common::SetDoNotDisturbDate(dataWorkerData->env, dataWorkerData->date, result)) { diff --git a/interfaces/inner_api/notification_request.h b/interfaces/inner_api/notification_request.h index 541f85294..279813826 100644 --- a/interfaces/inner_api/notification_request.h +++ b/interfaces/inner_api/notification_request.h @@ -1273,7 +1273,7 @@ public: * @param bundleOption Indicates the bundleOption of this notification. */ void SetBundleOption(const std::shared_ptr &bundleOption); - + /** * @brief Obtains the bundleOption of the notification. * diff --git a/services/ans/src/advanced_datashare_observer.cpp b/services/ans/src/advanced_datashare_observer.cpp index bcce59288..36c441163 100644 --- a/services/ans/src/advanced_datashare_observer.cpp +++ b/services/ans/src/advanced_datashare_observer.cpp @@ -74,7 +74,6 @@ void AdvancedDatashareObserver::RegisterSettingsObserver( return; } settingHelper->RegisterObserver(uri, dataObserver); - settingHelper->Release(); } bool AdvancedDatashareObserver::CheckIfSettingsDataReady() diff --git a/services/ans/src/common/file_utils.cpp b/services/ans/src/common/file_utils.cpp index e6cdd327a..c122deac9 100644 --- a/services/ans/src/common/file_utils.cpp +++ b/services/ans/src/common/file_utils.cpp @@ -63,7 +63,7 @@ bool FileUtils::GetJsonFromFile(const char *path, nlohmann::json &root) { std::ifstream file(path); root = nlohmann::json::parse(file); - if (root.is_null() || root.empty()) { + if (root.is_null() || root.empty() || !root.is_object()) { ANS_LOGE("GetJsonFromFile fail as invalid root."); return false; } diff --git a/services/ans/src/notification_dialog_manager.cpp b/services/ans/src/notification_dialog_manager.cpp index ad69e9442..29e4bde4f 100644 --- a/services/ans/src/notification_dialog_manager.cpp +++ b/services/ans/src/notification_dialog_manager.cpp @@ -94,8 +94,7 @@ ErrCode NotificationDialogManager::RequestEnableNotificationDailog( return ERROR_INTERNAL_ERROR; } if (!AddDialogInfoIfNotExist(bundle, callback)) { - ANS_LOGE("AddDialogIfNotExist failed. Dialog already exists. bundle = %{public}s", - bundle->GetBundleName().c_str()); + ANS_LOGE("AddDialogIfNotExist failed. Dialog already exists."); return ERR_ANS_DIALOG_IS_POPPING; } ErrCode result = NotificationDialog::StartEnableNotificationDialogAbility( diff --git a/services/ans/src/notification_preferences_database.cpp b/services/ans/src/notification_preferences_database.cpp index e80541632..d30cde6db 100644 --- a/services/ans/src/notification_preferences_database.cpp +++ b/services/ans/src/notification_preferences_database.cpp @@ -1810,6 +1810,10 @@ bool NotificationPreferencesDatabase::IsAgentRelationship(const std::string &age } ANS_LOGD("The agent relationship is :%{public}s.", agentShip.c_str()); nlohmann::json jsonAgentShip = nlohmann::json::parse(agentShip, nullptr, false); + if (jsonAgentShip.is_null() || jsonAgentShip.empty()) { + ANS_LOGE("Invalid JSON object"); + return false; + } if (jsonAgentShip.is_discarded() || !jsonAgentShip.is_array()) { ANS_LOGE("Parse agent ship failed due to data is discarded or not array"); return false; diff --git a/services/ans/src/notification_preferences_info.cpp b/services/ans/src/notification_preferences_info.cpp index d32f07b60..a31b4d95d 100644 --- a/services/ans/src/notification_preferences_info.cpp +++ b/services/ans/src/notification_preferences_info.cpp @@ -285,7 +285,6 @@ void NotificationPreferencesInfo::AddDoNotDisturbProfiles( continue; } std::string key = MakeDoNotDisturbProfileKey(userId, profile->GetProfileId()); - ANS_LOGI("AddDoNotDisturbProfiles key: %{public}s.", key.c_str()); doNotDisturbProfiles_.insert_or_assign(key, profile); } } @@ -299,7 +298,6 @@ void NotificationPreferencesInfo::RemoveDoNotDisturbProfiles( continue; } std::string key = MakeDoNotDisturbProfileKey(userId, profile->GetProfileId()); - ANS_LOGI("RemoveDoNotDisturbProfiles key: %{public}s.", key.c_str()); doNotDisturbProfiles_.erase(key); } } @@ -325,7 +323,6 @@ void NotificationPreferencesInfo::GetAllDoNotDisturbProfiles( { for (const auto &doNotDisturbProfile : doNotDisturbProfiles_) { std::string key = doNotDisturbProfile.first; - ANS_LOGI("GetAllDoNotDisturbProfiles key: %{public}s.", key.c_str()); auto result = key.find(std::to_string(userId)); if (result != std::string::npos) { auto profile = doNotDisturbProfile.second; diff --git a/services/ans/src/notification_rdb_data_mgr.cpp b/services/ans/src/notification_rdb_data_mgr.cpp index 5a9c0998d..2b4b7ed6c 100644 --- a/services/ans/src/notification_rdb_data_mgr.cpp +++ b/services/ans/src/notification_rdb_data_mgr.cpp @@ -303,10 +303,11 @@ int32_t NotificationDataMgr::DeleteBathchData(const std::vector &ke ANS_LOGE("notification rdb is null"); return NativeRdb::E_ERROR; } + int32_t ret = NativeRdb::E_OK; int32_t rowId = -1; for (auto key : keys) { for (auto tableName : operatedTables) { - int32_t ret = DeleteData(tableName, key, rowId); + ret = DeleteData(tableName, key, rowId); if (ret != NativeRdb::E_OK) { return ret; } diff --git a/services/ans/src/notification_trust_list.cpp b/services/ans/src/notification_trust_list.cpp index ce1b0c136..386126474 100644 --- a/services/ans/src/notification_trust_list.cpp +++ b/services/ans/src/notification_trust_list.cpp @@ -53,7 +53,6 @@ void NotificationTrustList::GetCcmPrivilegesConfig() affects_value[REMINDER_LIST_INDEX] != PRIVILEGES_BANNER_NOT_ALLOW) { reminderTrustlist_.insert(affect.key()); } - notificationSlotFlagsTrustlist_.insert(affect.key()); } return; } diff --git a/services/ans/src/system_dialog_connect_stb.cpp b/services/ans/src/system_dialog_connect_stb.cpp index 5ded65f49..9035552b2 100644 --- a/services/ans/src/system_dialog_connect_stb.cpp +++ b/services/ans/src/system_dialog_connect_stb.cpp @@ -62,6 +62,10 @@ void SystemDialogConnectStb::SendRemoveBundleEvent() return; } nlohmann::json root = nlohmann::json::parse(commandStr_); + if (root.is_null() or !root.is_object()) { + ANS_LOGE("Invalid JSON object"); + return; + } if (!root.contains("bundleName") || !root.contains("bundleUid")) { ANS_LOGW("not found jsonKey from"); return; diff --git a/services/dialog_ui/enable_notification_dialog/entry/src/main/ets/ServiceExtAbility/NotificationServiceExtAbility.ts b/services/dialog_ui/enable_notification_dialog/entry/src/main/ets/ServiceExtAbility/NotificationServiceExtAbility.ts index 64f1bfba4..9c5243336 100644 --- a/services/dialog_ui/enable_notification_dialog/entry/src/main/ets/ServiceExtAbility/NotificationServiceExtAbility.ts +++ b/services/dialog_ui/enable_notification_dialog/entry/src/main/ets/ServiceExtAbility/NotificationServiceExtAbility.ts @@ -23,11 +23,20 @@ import UIExtensionAbility from '@ohos.app.ability.UIExtensionAbility'; import UIExtensionContentSession from '@ohos.app.ability.UIExtensionContentSession'; import uiExtensionHost from '@ohos.uiExtensionHost'; import StartOptions from '@ohos.app.ability.StartOptions'; - +import configPolicy from '@ohos.configPolicy'; +import fs from '@ohos.file.fs'; +import Constants from '../common/constant'; const TAG = 'NotificationDialog_Service '; +const UPDATE_INIT = -1; +const UPDATE_NUM = 1; +const UPDATE_BOUNDARY = 100; + + +let systemLanguage: string; + const enableNotificationDialogDestroyedEvent = { eventId: 1, priority: emitter.EventPriority.LOW @@ -61,6 +70,7 @@ export class EnableNotificationDialog { static ENABLE_NOTIFICATION_DIALOG_NAME = 'EnableNotificationDialog'; static DIALOG_PATH = 'pages/notificationDialog'; static TRANSPARANT_COLOR = '#00000000'; + static SCENEBOARD_BUNDLE = 'com.ohos.sceneboard'; id: number; want: Want; @@ -132,7 +142,18 @@ export class EnableNotificationDialog { 'session': session }); - if (stageModel) { + let hasConfig = true; + try { + let filePaths = await configPolicy.getCfgFiles(Constants.CCM_CONFIG_PATH); + if (filePaths.length === 0) { + console.info(TAG, 'not get any configFile'); + hasConfig = false; + } + } catch (err) { + console.error(TAG, 'Failed get ccm files'); + } + + if (stageModel && hasConfig) { let subWindowOpts : window.SubWindowOptions = { 'title': '', decorEnabled: false, @@ -199,12 +220,28 @@ export class EnableNotificationDialog { }; - class NotificationDialogServiceExtensionAbility extends UIExtensionAbility { + onConfigurationUpdate(newConfig): void { + console.log(TAG, 'onConfigurationUpdate'); + if (systemLanguage !== newConfig.language) { + console.log(TAG, `onConfigurationUpdate newConfig is ${JSON.stringify(newConfig)}`); + systemLanguage = newConfig.language; + let isUpdate:number = AppStorage.get('isUpdate'); + if (isUpdate === undefined || isUpdate > UPDATE_BOUNDARY) { + AppStorage.setOrCreate('isUpdate', UPDATE_NUM); + } else { + AppStorage.setOrCreate('isUpdate', ++isUpdate); + } + } + } + + onCreate() { console.log(TAG, `UIExtAbility onCreate`); AppStorage.setOrCreate('context', this.context); + AppStorage.setOrCreate('isUpdate', UPDATE_INIT); + systemLanguage = this.context.config.language; } @@ -213,15 +250,15 @@ class NotificationDialogServiceExtensionAbility extends UIExtensionAbility { let stageModel = false; let bundleName = want.parameters['ohos.aafwk.param.callerBundleName']; let bundleUid = want.parameters['ohos.aafwk.param.callerUid']; - if (want.parameters.bundleName === undefined) { + if (bundleName !== EnableNotificationDialog.SCENEBOARD_BUNDLE) { want.parameters.bundleName = bundleName; want.parameters.bundleUid = bundleUid; stageModel = true; } else { stageModel = false; } - console.log(TAG, `UIExtAbility onSessionCreate bundleName ${want.parameters.bundleName}` - + `uid ${want.parameters.bundleUid}`); + console.log(TAG, `UIExtAbility onSessionCreate bundleName ${want.parameters.bundleName}` + + `uid ${want.parameters.bundleUid}`); let dialog = new EnableNotificationDialog(1, want, stageModel); await dialog.createUiExtensionWindow(session, stageModel); AppStorage.setOrCreate('clicked', false); @@ -252,7 +289,7 @@ class NotificationDialogServiceExtensionAbility extends UIExtensionAbility { } } - async onSessionDestroy(session: UIExtensionContentSession) { + async onSessionDestroy(session: UIExtensionContentSession): Promise { console.log(TAG, `UIExtAbility onSessionDestroy`); if (AppStorage.get('clicked') === false) { console.log(TAG, `UIExtAbility onSessionDestroy unclick destory`); diff --git a/services/dialog_ui/enable_notification_dialog/entry/src/main/ets/common/constant.ets b/services/dialog_ui/enable_notification_dialog/entry/src/main/ets/common/constant.ets index cfd06343a..721c6021c 100644 --- a/services/dialog_ui/enable_notification_dialog/entry/src/main/ets/common/constant.ets +++ b/services/dialog_ui/enable_notification_dialog/entry/src/main/ets/common/constant.ets @@ -93,7 +93,7 @@ export default class Constants { static CLICK_SHADOW_LENGTH = 48; static DIVIDER = '1px'; static DIVIDER_HEIGHT = 24; - public static DIVIDER_WIDTH = '2px'; + static DIVIDER_WIDTH = "2px"; static DIVIDER_MARGIN_RIGHT_PERMISSION = 52; static DIVIDER_MARGIN_RIGHT_APPLICATION = 68; @@ -122,7 +122,7 @@ export default class Constants { static DIALOG_REQ_MARGIN_BUTTOM = 16; static DIALOG_REQ_MARGIN_LEFT = 24; static DIALOG_REQ_MARGIN_RIGHT = 24; - public static DIALOG_REQ_LINE_HEIGHT = 24; + static DIALOG_REQ_LINE_HEIGHT = 24; // description text of dialog static DIALOG_DESP_FONT_SIZE = 16; @@ -136,8 +136,8 @@ export default class Constants { static BUTTON_MARGIN_LEFT = 16; static BUTTON_MARGIN_RIGHT = 16; static BUTTON_HEIGHT = 40; - public static BUTTON_LEFT = 8; - public static BUTTON_RIGHT = 8; + static BUTTON_LEFT = 8; + static BUTTON_RIGHT = 8; static DIALOG_PRIVACY_BORDER_RADIUS = 32; static DIALOG_PADDING_BOTTOM = 16; diff --git a/services/distributed/include/distributed_preferences_database.h b/services/distributed/include/distributed_preferences_database.h index 282ea1c22..b291bd14a 100644 --- a/services/distributed/include/distributed_preferences_database.h +++ b/services/distributed/include/distributed_preferences_database.h @@ -83,6 +83,7 @@ private: bool CheckKvDataManager(); void GetKvStore(); bool CheckKvStore(); + void CloseKvStore(); std::mutex mutex_; std::unique_ptr kvDataManager_; diff --git a/services/distributed/src/distributed_preferences_database.cpp b/services/distributed/src/distributed_preferences_database.cpp index 13cee84a8..d3f9885e4 100644 --- a/services/distributed/src/distributed_preferences_database.cpp +++ b/services/distributed/src/distributed_preferences_database.cpp @@ -98,12 +98,14 @@ bool DistributedPreferencesDatabase::PutToDistributedDB(const std::string &key, if (!KvStoreFlowControl()) { ANS_LOGE("KvStoreFlowControl is false."); + CloseKvStore(); return false; } DistributedKv::Key kvStoreKey(key); DistributedKv::Value kvStoreValue(value); DistributedKv::Status status = kvStore_->Put(kvStoreKey, kvStoreValue); + CloseKvStore(); if (status != DistributedKv::Status::SUCCESS) { ANS_LOGE("kvStore Put() failed ret = 0x%{public}x", status); return false; @@ -121,11 +123,13 @@ bool DistributedPreferencesDatabase::GetFromDistributedDB(const std::string &key if (!KvStoreFlowControl()) { ANS_LOGE("KvStoreFlowControl is defeat."); + CloseKvStore(); return false; } DistributedKv::Key kvStoreKey(key); DistributedKv::Value kvStoreValue; DistributedKv::Status status = kvStore_->Get(kvStoreKey, kvStoreValue); + CloseKvStore(); if (status != DistributedKv::Status::SUCCESS) { ANS_LOGE("kvStore Get() failed ret = 0x%{public}x", status); return false; @@ -143,10 +147,12 @@ bool DistributedPreferencesDatabase::GetEntriesFromDistributedDB( } if (!KvStoreFlowControl()) { ANS_LOGE("KvStoreFlowControl is false."); + CloseKvStore(); return false; } DistributedKv::Key kvStoreKey(prefixKey); DistributedKv::Status status = kvStore_->GetEntries(kvStoreKey, entries); + CloseKvStore(); if (status != DistributedKv::Status::SUCCESS) { ANS_LOGE("kvStore GetEntries() failed ret = 0x%{public}x", status); return false; @@ -163,11 +169,13 @@ bool DistributedPreferencesDatabase::DeleteToDistributedDB(const std::string &ke } if (!KvStoreFlowControl()) { ANS_LOGE("kvStore flow control."); + CloseKvStore(); return false; } DistributedKv::Key kvStoreKey(key); DistributedKv::Value kvStoreValue; DistributedKv::Status status = kvStore_->Delete(kvStoreKey); + CloseKvStore(); if (status != DistributedKv::Status::SUCCESS) { ANS_LOGE("kvStore Delete() failed ret = 0x%{public}x", status); return false; @@ -203,5 +211,11 @@ bool DistributedPreferencesDatabase::ClearDatabase() } return true; } + +void DistributedPreferencesDatabase::CloseKvStore() +{ + DistributedKv::AppId appId = {.appId = APP_ID}; + kvDataManager_->CloseKvStore(appId, kvStore_); +} } // namespace Notification } // namespace OHOS \ No newline at end of file diff --git a/test/fuzztest/fuzz_common_base/fuzz_data.h b/test/fuzztest/fuzz_common_base/fuzz_data.h index 87e6af604..cbd7aea1e 100644 --- a/test/fuzztest/fuzz_common_base/fuzz_data.h +++ b/test/fuzztest/fuzz_common_base/fuzz_data.h @@ -82,7 +82,7 @@ public: return (GetData() % BOOL_MODULO_NUM) == 0; } - size_t GetSize() const + size_t GetSize() { return size_; } -- Gitee From 2a978ecdbe676dd8c92a01ec1cee9b7760631552 Mon Sep 17 00:00:00 2001 From: xdongs Date: Thu, 5 Sep 2024 20:35:48 +0800 Subject: [PATCH 042/167] =?UTF-8?q?=E5=BC=B9=E7=AA=97=E5=8A=A0=E5=9B=BA-?= =?UTF-8?q?=E5=95=86=E5=88=86?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: xdongs --- services/ans/src/notification_dialog.cpp | 2 +- .../NotificationServiceExtAbility.ts | 58 +++++++++++++------ .../src/main/ets/pages/notificationDialog.ets | 12 ---- 3 files changed, 42 insertions(+), 30 deletions(-) diff --git a/services/ans/src/notification_dialog.cpp b/services/ans/src/notification_dialog.cpp index 1198bf819..58f98d970 100644 --- a/services/ans/src/notification_dialog.cpp +++ b/services/ans/src/notification_dialog.cpp @@ -61,7 +61,7 @@ ErrCode NotificationDialog::StartEnableNotificationDialogAbility( auto topBundleName = IN_PROCESS_CALL(AAFwk::AbilityManagerClient::GetInstance()->GetTopAbility().GetBundleName()); auto topUid = NotificationDialog::GetUidByBundleName(topBundleName); - if (topUid != uid) { + if (topBundleName != appBundleName) { ANS_LOGE("Current application isn't in foreground, top is %{private}s.", topBundleName.c_str()); return ERR_ANS_INVALID_BUNDLE; } diff --git a/services/dialog_ui/enable_notification_dialog/entry/src/main/ets/ServiceExtAbility/NotificationServiceExtAbility.ts b/services/dialog_ui/enable_notification_dialog/entry/src/main/ets/ServiceExtAbility/NotificationServiceExtAbility.ts index 8513612fa..b7ed2cb8c 100644 --- a/services/dialog_ui/enable_notification_dialog/entry/src/main/ets/ServiceExtAbility/NotificationServiceExtAbility.ts +++ b/services/dialog_ui/enable_notification_dialog/entry/src/main/ets/ServiceExtAbility/NotificationServiceExtAbility.ts @@ -72,6 +72,7 @@ export class EnableNotificationDialog { static DIALOG_PATH = 'pages/notificationDialog'; static TRANSPARANT_COLOR = '#00000000'; static SCENEBOARD_BUNDLE = 'com.ohos.sceneboard'; + static SYSTEMUI_BUNDLE = 'com.ohos.systemui'; id: number; want: Want; @@ -165,18 +166,22 @@ export class EnableNotificationDialog { let subWindow = await extensionWindow.createSubWindowWithOptions('subWindowForHost' + Date(), subWindowOpts); let dis = display.getDefaultDisplaySync(); await subWindow?.resize(dis.width, dis.height); + console.info(TAG, `size : ${dis.width} ${dis.height}`); await subWindow.loadContent(EnableNotificationDialog.DIALOG_PATH, this.storage); + try { + await subWindow.hideNonSystemFloatingWindows(true); + } catch (err) { + console.error(TAG, 'subWindow hideNonSystemFloatingWindows failed!'); + } await subWindow.setWindowBackgroundColor(EnableNotificationDialog.TRANSPARANT_COLOR); await subWindow.showWindow(); } else { await session.loadContent(EnableNotificationDialog.DIALOG_PATH, this.storage); - } - try { - await extensionWindow.hideNonSecureWindows(shouldHide); - } catch (err) { - console.error(TAG, 'window hideNonSecureWindows failed!'); - } - if (!stageModel) { + try { + await extensionWindow.hideNonSecureWindows(shouldHide); + } catch (err) { + console.error(TAG, 'window hideNonSecureWindows failed!'); + } await session.setWindowBackgroundColor(EnableNotificationDialog.TRANSPARANT_COLOR); } } catch (err) { @@ -252,7 +257,8 @@ class NotificationDialogServiceExtensionAbility extends UIExtensionAbility { let stageModel = false; let bundleName = want.parameters['ohos.aafwk.param.callerBundleName']; let bundleUid = want.parameters['ohos.aafwk.param.callerUid']; - if (bundleName !== EnableNotificationDialog.SCENEBOARD_BUNDLE) { + if (bundleName !== EnableNotificationDialog.SCENEBOARD_BUNDLE && + bundleName !== EnableNotificationDialog.SYSTEMUI_BUNDLE) { want.parameters.bundleName = bundleName; want.parameters.bundleUid = bundleUid; stageModel = true; @@ -274,20 +280,38 @@ class NotificationDialogServiceExtensionAbility extends UIExtensionAbility { onForeground() { console.log(TAG, `UIExtAbility onForeground`); let dialog = AppStorage.get('dialog'); - try { - dialog?.extensionWindow?.hideNonSecureWindows(true); - } catch (err) { - console.error(TAG, 'onForeground hideNonSecureWindows failed!'); - } + + if (dialog?.subWindow !== undefined) { + try { + dialog?.subWindow?.hideNonSystemFloatingWindows(true); + } catch (err) { + console.error(TAG, 'onForeground hideNonSystemFloatingWindows failed!'); + } + } else { + try { + dialog?.extensionWindow?.hideNonSecureWindows(true); + } catch (err) { + console.error(TAG, 'onForeground hideNonSecureWindows failed!'); + } + } } onBackground() { console.log(TAG, `UIExtAbility onBackground`); let dialog = AppStorage.get('dialog'); - try { - dialog?.extensionWindow?.hideNonSecureWindows(false); - } catch (err) { - console.error(TAG, 'onBackground hideNonSecureWindows failed!'); + + if (dialog?.subWindow !== undefined) { + try { + dialog?.subWindow?.hideNonSystemFloatingWindows(false); + } catch (err) { + console.error(TAG, 'onBackground hideNonSystemFloatingWindows failed!'); + } + } else { + try { + dialog?.extensionWindow?.hideNonSecureWindows(false); + } catch (err) { + console.error(TAG, 'onBackground hideNonSecureWindows failed!'); + } } } diff --git a/services/dialog_ui/enable_notification_dialog/entry/src/main/ets/pages/notificationDialog.ets b/services/dialog_ui/enable_notification_dialog/entry/src/main/ets/pages/notificationDialog.ets index af45bae1a..0853356a2 100644 --- a/services/dialog_ui/enable_notification_dialog/entry/src/main/ets/pages/notificationDialog.ets +++ b/services/dialog_ui/enable_notification_dialog/entry/src/main/ets/pages/notificationDialog.ets @@ -94,10 +94,6 @@ struct PermissionDialog { dialog?: EnableNotificationDialog; session?: UIExtensionContentSession; controller?: CustomDialogController; - panOption: PanGestureOptions = new PanGestureOptions({ - distance:100, - direction:PanDirection.Up - }); build() { GridRow({ columns: { xs: Constants.XS_COLUMNS, sm: Constants.SM_COLUMNS, md: Constants.MD_COLUMNS, lg: Constants.LG_COLUMNS }, gutter: Constants.DIALOG_GUTTER }) { @@ -188,14 +184,6 @@ struct PermissionDialog { right: this.isBottomPopover ? Constants.DIALOG_MARGIN_VERTICAL : Constants.DIALOG_MARGIN, bottom: this.isBottomPopover ? this.naviHeight : 0 }) - .gesture( - PanGesture(this.panOption) - .onActionStart((event:GestureEvent)=>{ - if (this.dialog?.stageModel == false) { - this.session?.terminateSelf(); - } - }) - ) } async updateApplicationName(bundleName: string): Promise { -- Gitee From b2e0c4e7845308a8fa7982f948562f6f118a09f4 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E7=8E=8B=E7=86=99=E8=BE=89?= <14809303+wang-xihui815@user.noreply.gitee.com> Date: Fri, 6 Sep 2024 18:08:12 +0800 Subject: [PATCH 043/167] =?UTF-8?q?=E5=BC=80=E5=90=AF=E4=B8=93=E6=B3=A8?= =?UTF-8?q?=E6=A8=A1=E5=BC=8F=E5=90=8E=E6=9D=A5=E7=94=B5=E6=98=AF=E5=90=A6?= =?UTF-8?q?=E6=8B=89=E8=B5=B7=E6=9D=A5=E7=82=B9=E9=A1=B5=E9=9D=A2=20Signed?= =?UTF-8?q?-off-by:=20=E7=8E=8B=E7=86=99=E8=BE=89=20<13821332216@163.com>?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- frameworks/ans/src/notification_helper.cpp | 5 + .../core/include/ans_manager_interface.h | 8 + frameworks/core/include/ans_manager_proxy.h | 8 + frameworks/core/include/ans_manager_stub.h | 9 + frameworks/core/include/ans_notification.h | 8 + ..._notification_service_ipc_interface_code.h | 1 + .../core/src/ans_manager_proxy_disturb.cpp | 35 ++++ frameworks/core/src/ans_manager_stub.cpp | 26 +++ .../core/src/ans_manager_stub_invalid.cpp | 6 + frameworks/core/src/ans_notification.cpp | 11 ++ .../ans_manager_proxy_unit_test.cpp | 108 +++++++++++ .../ans_manager_stub_test.cpp | 32 ++++ .../ans_notification_branch_test.cpp | 5 + .../ans_notification_unit_test.cpp | 19 ++ interfaces/inner_api/notification_helper.h | 8 + notification.gni | 6 + services/ans/BUILD.gn | 5 + .../ans/include/advanced_datashare_helper.h | 13 ++ .../include/advanced_datashare_helper_ext.h | 1 + .../include/advanced_notification_service.h | 17 ++ .../ans/include/telephony_extension_wrapper.h | 39 ++++ .../ans/src/advanced_datashare_helper.cpp | 170 ++++++++++++++++++ .../advanced_notification_publish_service.cpp | 77 ++++++++ .../advanced_notification_service_ability.cpp | 6 + .../ans/src/telephony_extension_wrapper.cpp | 63 +++++++ ...anced_notification_service_branch_test.cpp | 31 ++++ .../advanced_notification_service_test.cpp | 21 +++ ...ication_subscriber_manager_branch_test.cpp | 17 ++ 28 files changed, 755 insertions(+) create mode 100644 services/ans/include/telephony_extension_wrapper.h create mode 100644 services/ans/src/telephony_extension_wrapper.cpp diff --git a/frameworks/ans/src/notification_helper.cpp b/frameworks/ans/src/notification_helper.cpp index 9a14e6989..0cad2612f 100644 --- a/frameworks/ans/src/notification_helper.cpp +++ b/frameworks/ans/src/notification_helper.cpp @@ -370,6 +370,11 @@ ErrCode NotificationHelper::DoesSupportDoNotDisturbMode(bool &doesSupport) return DelayedSingleton::GetInstance()->DoesSupportDoNotDisturbMode(doesSupport); } +ErrCode NotificationHelper::IsNeedSilentInDoNotDisturbMode(const std::string &phoneNumber, int32_t callerType) +{ + return DelayedSingleton::GetInstance()->IsNeedSilentInDoNotDisturbMode(phoneNumber, callerType); +} + ErrCode NotificationHelper::IsDistributedEnabled(bool &enabled) { return DelayedSingleton::GetInstance()->IsDistributedEnabled(enabled); diff --git a/frameworks/core/include/ans_manager_interface.h b/frameworks/core/include/ans_manager_interface.h index 62296e57f..790abe0ce 100644 --- a/frameworks/core/include/ans_manager_interface.h +++ b/frameworks/core/include/ans_manager_interface.h @@ -558,6 +558,14 @@ public: */ virtual ErrCode DoesSupportDoNotDisturbMode(bool &doesSupport) = 0; + /** + * @brief Is coming call need silent in do not disturb mode. + * + * @param phoneNumber the calling format number. + * @return Returns silent in do not disturb mode. + */ + virtual ErrCode IsNeedSilentInDoNotDisturbMode(const std::string &phoneNumber, int32_t callerType) = 0; + /** * @brief Cancel notifications according to group. * diff --git a/frameworks/core/include/ans_manager_proxy.h b/frameworks/core/include/ans_manager_proxy.h index 006c4efa2..59bf9a7eb 100644 --- a/frameworks/core/include/ans_manager_proxy.h +++ b/frameworks/core/include/ans_manager_proxy.h @@ -546,6 +546,14 @@ public: */ ErrCode DoesSupportDoNotDisturbMode(bool &doesSupport) override; + /** + * @brief Is coming call need silent in do not disturb mode. + * + * @param phoneNumber the calling format number. + * @return Returns silent in do not disturb mode. + */ + ErrCode IsNeedSilentInDoNotDisturbMode(const std::string &phoneNumber, int32_t callerType) override; + /** * @brief Cancel notifications according to group. * diff --git a/frameworks/core/include/ans_manager_stub.h b/frameworks/core/include/ans_manager_stub.h index 4ac817c13..0ec670f8f 100644 --- a/frameworks/core/include/ans_manager_stub.h +++ b/frameworks/core/include/ans_manager_stub.h @@ -546,6 +546,14 @@ public: */ virtual ErrCode DoesSupportDoNotDisturbMode(bool &doesSupport) override; + /** + * @brief Is coming call need silent in do not disturb mode. + * + * @param phoneNumber the calling format number. + * @return Returns silent in do not disturb mode. + */ + virtual ErrCode IsNeedSilentInDoNotDisturbMode(const std::string &phoneNumber, int32_t callerType) override; + /** * @brief Cancel notifications according to group. * @@ -991,6 +999,7 @@ private: ErrCode HandleSetDoNotDisturbDate(MessageParcel &data, MessageParcel &reply); ErrCode HandleGetDoNotDisturbDate(MessageParcel &data, MessageParcel &reply); ErrCode HandleDoesSupportDoNotDisturbMode(MessageParcel &data, MessageParcel &reply); + ErrCode HandleIsNeedSilentInDoNotDisturbMode(MessageParcel &data, MessageParcel &reply); ErrCode HandleGetDeviceRemindType(MessageParcel &data, MessageParcel &reply); ErrCode HandlePublishContinuousTaskNotification(MessageParcel &data, MessageParcel &reply); ErrCode HandleCancelContinuousTaskNotification(MessageParcel &data, MessageParcel &reply); diff --git a/frameworks/core/include/ans_notification.h b/frameworks/core/include/ans_notification.h index 1e2b6a64e..c45c7332b 100644 --- a/frameworks/core/include/ans_notification.h +++ b/frameworks/core/include/ans_notification.h @@ -685,6 +685,14 @@ public: */ ErrCode DoesSupportDoNotDisturbMode(bool &doesSupport); + /** + * @brief Is coming call need silent in do not disturb mode. + * + * @param phoneNumber the calling format number. + * @return Returns silent in do not disturb mode. + */ + ErrCode IsNeedSilentInDoNotDisturbMode(const std::string &phoneNumber, int32_t callerType); + /** * @brief Checks if the device supports distributed notification. * diff --git a/frameworks/core/include/distributed_notification_service_ipc_interface_code.h b/frameworks/core/include/distributed_notification_service_ipc_interface_code.h index aa2df9e2b..56e520eb6 100644 --- a/frameworks/core/include/distributed_notification_service_ipc_interface_code.h +++ b/frameworks/core/include/distributed_notification_service_ipc_interface_code.h @@ -80,6 +80,7 @@ namespace Notification { SET_DO_NOT_DISTURB_DATE, GET_DO_NOT_DISTURB_DATE, DOES_SUPPORT_DO_NOT_DISTURB_MODE, + IS_NEED_SILENT_IN_DO_NOT_DISTURB_MODE, CANCEL_GROUP, REMOVE_GROUP_BY_BUNDLE, IS_DISTRIBUTED_ENABLED, diff --git a/frameworks/core/src/ans_manager_proxy_disturb.cpp b/frameworks/core/src/ans_manager_proxy_disturb.cpp index 16e141ade..30cb18e67 100644 --- a/frameworks/core/src/ans_manager_proxy_disturb.cpp +++ b/frameworks/core/src/ans_manager_proxy_disturb.cpp @@ -426,5 +426,40 @@ ErrCode AnsManagerProxy::IsSmartReminderEnabled(const std::string &deviceType, b return result; } + +ErrCode AnsManagerProxy::IsNeedSilentInDoNotDisturbMode(const std::string &phoneNumber, int32_t callerType) +{ + MessageParcel data; + if (!data.WriteInterfaceToken(AnsManagerProxy::GetDescriptor())) { + ANS_LOGE("[IsNeedSilentInDoNotDisturbMode] fail: write interface token failed."); + return ERR_ANS_PARCELABLE_FAILED; + } + + if (!data.WriteString(phoneNumber)) { + ANS_LOGE("[IsNeedSilentInDoNotDisturbMode] fail: write phoneNumber failed."); + return ERR_ANS_PARCELABLE_FAILED; + } + + if (!data.WriteInt32(callerType)) { + ANS_LOGE("[IsNeedSilentInDoNotDisturbMode] fail: write callerType failed"); + return ERR_ANS_PARCELABLE_FAILED; + } + + MessageParcel reply; + MessageOption option = {MessageOption::TF_SYNC}; + ErrCode result = InnerTransact(NotificationInterfaceCode::IS_NEED_SILENT_IN_DO_NOT_DISTURB_MODE, + option, data, reply); + if (result != ERR_OK) { + ANS_LOGE("[IsNeedSilentInDoNotDisturbMode] fail: transact ErrCode=%{public}d", result); + return ERR_ANS_TRANSACT_FAILED; + } + + if (!reply.ReadInt32(result)) { + ANS_LOGE("[IsNeedSilentInDoNotDisturbMode] fail: read result failed."); + return ERR_ANS_PARCELABLE_FAILED; + } + + return result; +} } // namespace Notification } // namespace OHOS diff --git a/frameworks/core/src/ans_manager_stub.cpp b/frameworks/core/src/ans_manager_stub.cpp index b27515659..45fe93921 100644 --- a/frameworks/core/src/ans_manager_stub.cpp +++ b/frameworks/core/src/ans_manager_stub.cpp @@ -239,6 +239,10 @@ int32_t AnsManagerStub::OnRemoteRequest(uint32_t code, MessageParcel &data, Mess result = HandleDoesSupportDoNotDisturbMode(data, reply); break; } + case static_cast(NotificationInterfaceCode::IS_NEED_SILENT_IN_DO_NOT_DISTURB_MODE): { + result = HandleIsNeedSilentInDoNotDisturbMode(data, reply); + break; + } case static_cast(NotificationInterfaceCode::CANCEL_GROUP): { result = HandleCancelGroup(data, reply); break; @@ -1005,6 +1009,28 @@ ErrCode AnsManagerStub::HandleDoesSupportDoNotDisturbMode(MessageParcel &data, M return ERR_OK; } +ErrCode AnsManagerStub::HandleIsNeedSilentInDoNotDisturbMode(MessageParcel &data, MessageParcel &reply) +{ + std::string phoneNumber; + if (!data.ReadString(phoneNumber)) { + ANS_LOGE("[HandleIsNeedSilentInDoNotDisturbMode] fail: read phoneNumber failed"); + return ERR_ANS_PARCELABLE_FAILED; + } + + int32_t callerType = 0; + if (!data.ReadInt32(callerType)) { + ANS_LOGE("[HandleIsNeedSilentInDoNotDisturbMode] fail: read callerType failed"); + return ERR_ANS_PARCELABLE_FAILED; + } + + ErrCode result = IsNeedSilentInDoNotDisturbMode(phoneNumber, callerType); + if (!reply.WriteInt32(result)) { + ANS_LOGE("[HandleIsNeedSilentInDoNotDisturbMode] fail: write result failed, ErrCode=%{public}d", result); + return ERR_ANS_PARCELABLE_FAILED; + } + return ERR_OK; +} + ErrCode AnsManagerStub::HandlePublishContinuousTaskNotification(MessageParcel &data, MessageParcel &reply) { sptr request = data.ReadParcelable(); diff --git a/frameworks/core/src/ans_manager_stub_invalid.cpp b/frameworks/core/src/ans_manager_stub_invalid.cpp index d659f076c..0457626d0 100644 --- a/frameworks/core/src/ans_manager_stub_invalid.cpp +++ b/frameworks/core/src/ans_manager_stub_invalid.cpp @@ -400,6 +400,12 @@ ErrCode AnsManagerStub::DoesSupportDoNotDisturbMode(bool &doesSupport) return ERR_INVALID_OPERATION; } +ErrCode AnsManagerStub::IsNeedSilentInDoNotDisturbMode(const std::string &phoneNumber, int32_t callerType) +{ + ANS_LOGE("AnsManagerStub::IsNeedSilentInDoNotDisturbMode called!"); + return ERR_INVALID_OPERATION; +} + ErrCode AnsManagerStub::IsDistributedEnabled(bool &enabled) { ANS_LOGE("AnsManagerStub::IsDistributedEnabled called!"); diff --git a/frameworks/core/src/ans_notification.cpp b/frameworks/core/src/ans_notification.cpp index 87cc6c536..782984075 100644 --- a/frameworks/core/src/ans_notification.cpp +++ b/frameworks/core/src/ans_notification.cpp @@ -1032,6 +1032,17 @@ ErrCode AnsNotification::DoesSupportDoNotDisturbMode(bool &doesSupport) return proxy->DoesSupportDoNotDisturbMode(doesSupport); } +ErrCode AnsNotification::IsNeedSilentInDoNotDisturbMode(const std::string &phoneNumber, int32_t callerType) +{ + sptr proxy = GetAnsManagerProxy(); + if (!proxy) { + ANS_LOGE("GetAnsManagerProxy fail."); + return ERR_ANS_SERVICE_NOT_CONNECTED; + } + + return proxy->IsNeedSilentInDoNotDisturbMode(phoneNumber, callerType); +} + ErrCode AnsNotification::PublishContinuousTaskNotification(const NotificationRequest &request) { if (request.GetContent() == nullptr || request.GetNotificationType() == NotificationContent::Type::NONE) { diff --git a/frameworks/core/test/unittest/ans_manager_proxy_test/ans_manager_proxy_unit_test.cpp b/frameworks/core/test/unittest/ans_manager_proxy_test/ans_manager_proxy_unit_test.cpp index 326f45052..545d065bb 100644 --- a/frameworks/core/test/unittest/ans_manager_proxy_test/ans_manager_proxy_unit_test.cpp +++ b/frameworks/core/test/unittest/ans_manager_proxy_test/ans_manager_proxy_unit_test.cpp @@ -8080,5 +8080,113 @@ HWTEST_F(AnsManagerProxyUnitTest, RemoveDoNotDisturbProfiles_0300, TestSize.Leve EXPECT_NE(ERR_OK, res); EXPECT_NE(ERR_ANS_PARCELABLE_FAILED, res); } + +/* + * @tc.name: IsNeedSilentInDoNotDisturbModeTest_0100 + * @tc.desc: test IsNeedSilentInDoNotDisturbMode function + * @tc.type: FUNC + */ +HWTEST_F(AnsManagerProxyUnitTest, IsNeedSilentInDoNotDisturbModeTest_0100, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) + << "AnsManagerProxyUnitTest, IsNeedSilentInDoNotDisturbModeTest_0100, TestSize.Level1"; + MockWriteInterfaceToken(false); + sptr iremoteObject = new (std::nothrow) MockIRemoteObject(); + ASSERT_NE(nullptr, iremoteObject); + std::shared_ptr proxy = std::make_shared(iremoteObject); + ASSERT_NE(nullptr, proxy); + std::string phoneNumber = "11111111111"; + int32_t callerType = 0; + int32_t result = proxy->IsNeedSilentInDoNotDisturbMode(phoneNumber, callerType); + EXPECT_EQ(ERR_ANS_PARCELABLE_FAILED, result); +} + +/* + * @tc.name: IsNeedSilentInDoNotDisturbModeTest_0200 + * @tc.desc: test IsNeedSilentInDoNotDisturbMode function + * @tc.type: FUNC + */ +HWTEST_F(AnsManagerProxyUnitTest, IsNeedSilentInDoNotDisturbModeTest_0200, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) + << "AnsManagerProxyUnitTest, IsNeedSilentInDoNotDisturbModeTest_0200, TestSize.Level1"; + MockWriteInterfaceToken(true); + sptr iremoteObject = new (std::nothrow) MockIRemoteObject(); + ASSERT_NE(nullptr, iremoteObject); + EXPECT_CALL(*iremoteObject, SendRequest(_, _, _, _)) + .WillRepeatedly(DoAll(Invoke(std::bind(SendRequestReplace, _1, _2, _3, _4, + ERR_OK, true, true, true)), Return(NO_ERROR))); + std::shared_ptr proxy = std::make_shared(iremoteObject); + ASSERT_NE(nullptr, proxy); + std::string phoneNumber = "11111111111"; + int32_t callerType = 0; + int32_t result = proxy->IsNeedSilentInDoNotDisturbMode(phoneNumber, callerType); + EXPECT_EQ(ERR_OK, result); +} + +/* + * @tc.name: IsNeedSilentInDoNotDisturbModeTest_0300 + * @tc.desc: test IsNeedSilentInDoNotDisturbMode function + * @tc.type: FUNC + */ +HWTEST_F(AnsManagerProxyUnitTest, IsNeedSilentInDoNotDisturbModeTest_0300, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) + << "AnsManagerProxyUnitTest, IsNeedSilentInDoNotDisturbModeTest_0300, TestSize.Level1"; + sptr iremoteObject = new (std::nothrow) MockIRemoteObject(); + ASSERT_NE(nullptr, iremoteObject); + EXPECT_CALL(*iremoteObject, SendRequest(_, _, _, _)).Times(1) + .WillRepeatedly(DoAll(Return(DEAD_OBJECT))); + std::shared_ptr proxy = std::make_shared(iremoteObject); + ASSERT_NE(nullptr, proxy); + std::string phoneNumber = "11111111111"; + int32_t callerType = 0; + int32_t result = proxy->IsNeedSilentInDoNotDisturbMode(phoneNumber, callerType); + EXPECT_EQ(ERR_ANS_TRANSACT_FAILED, result); +} + +/* + * @tc.name: IsNeedSilentInDoNotDisturbModeTest_0400 + * @tc.desc: test IsNeedSilentInDoNotDisturbMode function + * @tc.type: FUNC + */ +HWTEST_F(AnsManagerProxyUnitTest, IsNeedSilentInDoNotDisturbModeTest_0400, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) + << "AnsManagerProxyUnitTest, IsNeedSilentInDoNotDisturbModeTest_0400, TestSize.Level1"; + sptr iremoteObject = new (std::nothrow) MockIRemoteObject(); + ASSERT_NE(nullptr, iremoteObject); + EXPECT_CALL(*iremoteObject, SendRequest(_, _, _, _)).Times(1) + .WillRepeatedly(DoAll(Invoke(std::bind(SendRequestReplace, _1, _2, _3, _4, + ERR_OK, false, false, false)), Return(NO_ERROR))); + std::shared_ptr proxy = std::make_shared(iremoteObject); + ASSERT_NE(nullptr, proxy); + std::string phoneNumber = "11111111111"; + int32_t callerType = 0; + int32_t result = proxy->IsNeedSilentInDoNotDisturbMode(phoneNumber, callerType); + EXPECT_EQ(ERR_ANS_PARCELABLE_FAILED, result); +} + +/* + * @tc.name: IsNeedSilentInDoNotDisturbModeTest_0500 + * @tc.desc: test IsNeedSilentInDoNotDisturbMode function + * @tc.type: FUNC + */ +HWTEST_F(AnsManagerProxyUnitTest, IsNeedSilentInDoNotDisturbModeTest_0500, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) + << "AnsManagerProxyUnitTest, IsNeedSilentInDoNotDisturbModeTest_0500, TestSize.Level1"; + sptr iremoteObject = new (std::nothrow) MockIRemoteObject(); + ASSERT_NE(nullptr, iremoteObject); + EXPECT_CALL(*iremoteObject, SendRequest(_, _, _, _)).Times(1) + .WillRepeatedly(DoAll(Invoke(std::bind(SendRequestReplace, _1, _2, _3, _4, + ERR_OK, true, true, false)), Return(NO_ERROR))); + std::shared_ptr proxy = std::make_shared(iremoteObject); + ASSERT_NE(nullptr, proxy); + std::string phoneNumber = "11111111111"; + int32_t callerType = 0; + int32_t result = proxy->IsNeedSilentInDoNotDisturbMode(phoneNumber, callerType); + EXPECT_EQ(ERR_OK, result); +} } // namespace Notification } // namespace OHOS diff --git a/frameworks/core/test/unittest/ans_manager_stub_test/ans_manager_stub_test.cpp b/frameworks/core/test/unittest/ans_manager_stub_test/ans_manager_stub_test.cpp index 0190cf750..f6a05e050 100644 --- a/frameworks/core/test/unittest/ans_manager_stub_test/ans_manager_stub_test.cpp +++ b/frameworks/core/test/unittest/ans_manager_stub_test/ans_manager_stub_test.cpp @@ -5428,5 +5428,37 @@ HWTEST_F(AnsManagerStubTest, RegisterSwingCallback_0200, TestSize.Level1) EXPECT_EQ(res, ERR_ANS_PARCELABLE_FAILED); } #endif + +/** + * @tc.name: HandleIsNeedSilentInDoNotDisturbMode01 + * @tc.desc: Test HandleIsNeedSilentInDoNotDisturbMode01 succeeds. + * @tc.type: FUNC + */ +HWTEST_F(AnsManagerStubTest, HandleIsNeedSilentInDoNotDisturbMode01, Function | SmallTest | Level1) +{ + uint32_t code = static_cast(NotificationInterfaceCode::IS_NEED_SILENT_IN_DO_NOT_DISTURB_MODE); + MessageParcel data; + MessageParcel reply; + MessageOption option = {MessageOption::TF_SYNC}; + + data.WriteInterfaceToken(AnsManagerStub::GetDescriptor()); + + ErrCode ret = ansManagerStub_->OnRemoteRequest(code, data, reply, option); + EXPECT_EQ(ret, (int)ERR_ANS_PARCELABLE_FAILED); +} + +/** + * @tc.name: IsNeedSilentInDoNotDisturbMode01 + * @tc.desc: Test IsNeedSilentInDoNotDisturbMode return. + * @tc.type: FUNC + */ +HWTEST_F(AnsManagerStubTest, IsNeedSilentInDoNotDisturbMode01, Function | SmallTest | Level1) +{ + std::string phoneNumber = "11111111111"; + int32_t callerType = 0; + + ErrCode result = ansManagerStub_->IsNeedSilentInDoNotDisturbMode(phoneNumber, callerType); + EXPECT_EQ(result, (int)ERR_INVALID_OPERATION); +} } } diff --git a/frameworks/core/test/unittest/ans_notification_branch_test/ans_notification_branch_test.cpp b/frameworks/core/test/unittest/ans_notification_branch_test/ans_notification_branch_test.cpp index 40f151b03..b509a5ed2 100644 --- a/frameworks/core/test/unittest/ans_notification_branch_test/ans_notification_branch_test.cpp +++ b/frameworks/core/test/unittest/ans_notification_branch_test/ans_notification_branch_test.cpp @@ -337,6 +337,11 @@ public: return ERR_ANS_INVALID_PARAM; } + ErrCode IsNeedSilentInDoNotDisturbMode(const std::string &phoneNumber, int32_t callerType) override + { + return ERR_ANS_INVALID_PARAM; + } + ErrCode CancelGroup(const std::string &groupName, int32_t instanceKey) override { return ERR_ANS_INVALID_PARAM; diff --git a/frameworks/core/test/unittest/ans_notification_test/ans_notification_unit_test.cpp b/frameworks/core/test/unittest/ans_notification_test/ans_notification_unit_test.cpp index 2b59696a1..0fa391334 100644 --- a/frameworks/core/test/unittest/ans_notification_test/ans_notification_unit_test.cpp +++ b/frameworks/core/test/unittest/ans_notification_test/ans_notification_unit_test.cpp @@ -1509,5 +1509,24 @@ HWTEST_F(AnsNotificationUnitTest, RegisterSwingCallback_0100, TestSize.Level1) EXPECT_EQ(res, ERR_ANS_SERVICE_NOT_CONNECTED); } #endif + +/* + * @tc.name: IsNeedSilentInDoNotDisturbMode_0100 + * @tc.desc: test IsNeedSilentInDoNotDisturbMode. + * @tc.type: FUNC + */ +HWTEST_F(AnsNotificationUnitTest, IsNeedSilentInDoNotDisturbMode_0100, Function | MediumTest | Level1) +{ + MockWriteInterfaceToken(false); + sptr iremoteObjects = new (std::nothrow) MockIRemoteObject(); + ASSERT_NE(nullptr, iremoteObjects); + std::shared_ptr proxy = std::make_shared(iremoteObjects); + ASSERT_NE(nullptr, proxy); + ans_->GetAnsManagerProxy(); + std::string phoneNumber = "11111111111"; + int32_t callerType = 0; + ErrCode ret = ans_->IsNeedSilentInDoNotDisturbMode(phoneNumber, callerType); + EXPECT_EQ(ret, ERR_ANS_SERVICE_NOT_CONNECTED); +} } // namespace Notification } // namespace OHOS diff --git a/interfaces/inner_api/notification_helper.h b/interfaces/inner_api/notification_helper.h index b1345029b..5b35ec72b 100644 --- a/interfaces/inner_api/notification_helper.h +++ b/interfaces/inner_api/notification_helper.h @@ -667,6 +667,14 @@ public: */ static ErrCode DoesSupportDoNotDisturbMode(bool &doesSupport); + /** + * @brief Is coming call need silent in do not disturb mode. + * + * @param phoneNumber the calling format number. + * @return Returns silent in do not disturb mode. + */ + static ErrCode IsNeedSilentInDoNotDisturbMode(const std::string &phoneNumber, int32_t callerType); + /** * @brief Check if the device supports distributed notification. * diff --git a/notification.gni b/notification.gni index b04f143f4..08b20e2f3 100644 --- a/notification.gni +++ b/notification.gni @@ -58,6 +58,7 @@ declare_args() { notification_smart_reminder_supported = true ans_config_policy_enable = true screenlock_mgr_enable = true + telephony_cust = true if (defined(global_parts_info) && !defined(global_parts_info.resourceschedule_device_usage_statistics)) { @@ -95,6 +96,11 @@ declare_args() { notification_smart_reminder_supported = false } + if (defined(global_parts_info) && + !defined(global_parts_info.telephony_telephony_cust)) { + telephony_cust = false + } + print("hisysevent_usage = " + "$hisysevent_usage") print("ans_hitrace_usage = " + "$ans_hitrace_usage") } diff --git a/services/ans/BUILD.gn b/services/ans/BUILD.gn index 80bf82395..f694616c1 100644 --- a/services/ans/BUILD.gn +++ b/services/ans/BUILD.gn @@ -93,6 +93,7 @@ ohos_shared_library("libans") { "src/reminder_timer_info.cpp", "src/system_dialog_connect_stb.cpp", "src/system_event_observer.cpp", + "src/telephony_extension_wrapper.cpp", ] configs = [ ":public_ans_config" ] @@ -201,6 +202,10 @@ ohos_shared_library("libans") { defines += [ "SCREENLOCK_MGR_ENABLE" ] } + if (telephony_cust) { + defines += [ "ENABLE_ANS_TELEPHONY_CUST_WRAPPER" ] + } + subsystem_name = "${subsystem_name}" part_name = "${component_name}" } diff --git a/services/ans/include/advanced_datashare_helper.h b/services/ans/include/advanced_datashare_helper.h index d0971ed7d..cebf5bab9 100644 --- a/services/ans/include/advanced_datashare_helper.h +++ b/services/ans/include/advanced_datashare_helper.h @@ -27,6 +27,8 @@ namespace Notification { namespace { constexpr const char *KEY_FOCUS_MODE_ENABLE = "focus_mode_enable"; constexpr const char *KEY_FOCUS_MODE_PROFILE = "focus_mode_profile"; +constexpr const char *KEY_FOCUS_MODE_CALL_MESSAGE_POLICY = "focus_mode_call_message_policy"; +constexpr const char *KEY_FOCUS_MODE_REPEAT_CALLERS_ENABLE = "focus_mode_repeate_callers_enable"; } // namespace class AdvancedDatashareHelper : DelayedSingleton { @@ -34,12 +36,23 @@ public: AdvancedDatashareHelper(); ~AdvancedDatashareHelper() = default; bool Query(Uri &uri, const std::string &key, std::string &value); + bool QueryContact(Uri &uri, const std::string &phoneNumber, const std::string &policy); + bool isRepeatCall(const std::string &phoneNumber); std::string GetFocusModeEnableUri(const int32_t &userId) const; std::string GetFocusModeProfileUri(const int32_t &userId) const; + std::string GetFocusModeCallPolicyUri(const int32_t &userId) const; + std::string GetFocusModeRepeatCallUri(const int32_t &userId) const; std::string GetUnifiedGroupEnableUri() const; private: + enum ContactPolicy { + ALLOW_FAVORITE_CONTACTS = 4, + ALLOW_SPECIFIED_CONTACTS = 5, + }; std::shared_ptr CreateDataShareHelper(); + std::shared_ptr CreateContactDataShareHelper(std::string uri); + bool dealWithContactResult(std::shared_ptr helper, + std::shared_ptr resultSet, const std::string &policy); }; } // namespace Notification } // namespace OHOS diff --git a/services/ans/include/advanced_datashare_helper_ext.h b/services/ans/include/advanced_datashare_helper_ext.h index 76842aac0..6309f1e03 100644 --- a/services/ans/include/advanced_datashare_helper_ext.h +++ b/services/ans/include/advanced_datashare_helper_ext.h @@ -27,6 +27,7 @@ namespace Notification { namespace { constexpr const char *KEY_FOCUS_MODE_ENABLE_EXT = "focus_mode_enable"; constexpr const char *KEY_FOCUS_MODE_PROFILE_EXT = "focus_mode_profile"; +constexpr const char *KEY_FOCUS_MODE_CALL_MESSAGE_POLICY_EXT = "focus_mode_call_message_policy"; } // namespace class AdvancedDatashareHelperExt : DelayedSingleton { diff --git a/services/ans/include/advanced_notification_service.h b/services/ans/include/advanced_notification_service.h index ca9211e90..55fe6ec84 100644 --- a/services/ans/include/advanced_notification_service.h +++ b/services/ans/include/advanced_notification_service.h @@ -598,6 +598,14 @@ public: */ ErrCode DoesSupportDoNotDisturbMode(bool &doesSupport) override; + /** + * @brief Is coming call need silent in do not disturb mode. + * + * @param phoneNumber the calling format number. + * @return Returns silent in do not disturb mode. + */ + ErrCode IsNeedSilentInDoNotDisturbMode(const std::string &phoneNumber, int32_t callerType) override; + /** * @brief Cancel notifications according to group. * @@ -1150,6 +1158,14 @@ private: FINISH }; + enum ContactPolicy { + FORBID_EVERYONE = 1, + ALLOW_EVERYONE = 2, + ALLOW_EXISTING_CONTACTS = 3, + ALLOW_FAVORITE_CONTACTS = 4, + ALLOW_SPECIFIED_CONTACTS = 5, + }; + AdvancedNotificationService(); void StartFilters(); @@ -1356,6 +1372,7 @@ private: const std::string &groupName, const int32_t reason); ErrCode ExcuteCancelAll(const sptr& bundleOption, const int32_t reason); ErrCode ExcuteDelete(const std::string &key, const int32_t removeReason); + ErrCode CheckNeedSilent(const std::string &phoneNumber, int32_t callerType, int32_t userId); private: static sptr instance_; diff --git a/services/ans/include/telephony_extension_wrapper.h b/services/ans/include/telephony_extension_wrapper.h new file mode 100644 index 000000000..56e05d5f4 --- /dev/null +++ b/services/ans/include/telephony_extension_wrapper.h @@ -0,0 +1,39 @@ +/* + * Copyright (c) 2024 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef BASE_NOTIFICATION_ANS_SERVICES_TELEPHONY_EXTENSION_WRAPPER_H +#define BASE_NOTIFICATION_ANS_SERVICES_TELEPHONY_EXTENSION_WRAPPER_H + +#include + +#include "singleton.h" +#include "datashare_helper.h" + +namespace OHOS::Notification { +class TelExtensionWrapper final { + DECLARE_DELAYED_SINGLETON(TelExtensionWrapper); +public: + void InitTelExtentionWrapper(); + void CloseTelExtentionWrapper(); + typedef ErrCode (*GET_CALLER_INDEX)(std::shared_ptr resultSet, std::string compNum); + ErrCode GetCallerIndex(std::shared_ptr resultSet, std::string compNum); +private: + void* telephonyCustHandle_ = nullptr; + GET_CALLER_INDEX getCallerIndex_ = nullptr; +}; + +#define TEL_EXTENTION_WRAPPER ::OHOS::DelayedSingleton::GetInstance() +} // namespace OHOS::Notification +#endif // BASE_NOTIFICATION_ANS_SERVICES_TELEPHONY_EXTENSION_WRAPPER_H \ No newline at end of file diff --git a/services/ans/src/advanced_datashare_helper.cpp b/services/ans/src/advanced_datashare_helper.cpp index 396426459..0e1eb2d76 100644 --- a/services/ans/src/advanced_datashare_helper.cpp +++ b/services/ans/src/advanced_datashare_helper.cpp @@ -22,6 +22,8 @@ #include "os_account_manager.h" #include "singleton.h" #include "system_ability_definition.h" +#include "ipc_skeleton.h" +#include "telephony_extension_wrapper.h" namespace OHOS { namespace Notification { @@ -35,9 +37,27 @@ constexpr const char *USER_SETTINGS_DATA_SECURE_URI = "datashare:///com.ohos.settingsdata/entry/settingsdata/USER_SETTINGSDATA_SECURE_"; constexpr const char *FOCUS_MODE_ENABLE_URI = "?Proxy=true&key=focus_mode_enable"; constexpr const char *FOCUS_MODE_PROFILE_URI = "?Proxy=true&key=focus_mode_profile"; +constexpr const char *FOCUS_MODE_CALL_POLICY_URI = "?Proxy=true&key=focus_mode_call_message_policy"; +constexpr const char *FOCUS_MODE_REPEAT_CALLERS_ENABLE_URI = "?Proxy=true&key=focus_mode_repeate_callers_enable"; constexpr const char *UNIFIED_GROUP_ENABLE_URI = "?Proxy=true&key=unified_group_enable"; +constexpr const char *CONTACT_URI = "datashare:///com.ohos.contactsdataability"; +constexpr const char *CALLLOG_URI = "datashare:///com.ohos.calllogability"; +constexpr const char *CALL_SUBSECTION = "datashare:///com.ohos.calllogability/calls/calllog?Proxy=true"; +constexpr const char *PHONE_NUMBER = "phone_number"; +constexpr const char *IS_DELETED = "is_deleted"; +constexpr const char *TYPE_ID = "type_id"; +constexpr const char *DETAIL_INFO = "detail_info"; +constexpr const char *FORMAT_PHONE_NUMBER = "format_phone_number"; +constexpr const char *FAVORITE = "favorite"; +constexpr const char *FOCUS_MODE_LIST = "focus_mode_list"; constexpr const char *ADVANCED_DATA_COLUMN_KEYWORD = "KEYWORD"; constexpr const char *ADVANCED_DATA_COLUMN_VALUE = "VALUE"; +constexpr const char *CALL_DIRECTION = "call_direction"; +constexpr const char *CREATE_TIME = "create_time"; +constexpr const unsigned int PHONE_NUMBER_LENGTH = 7; +constexpr const unsigned int MAX_TIME_INTERVAL = 15 * 60; +constexpr const int TYPE_ID_FIVE = 5; +std::vector QUERY_CONTACT_COLUMN_LIST = {FORMAT_PHONE_NUMBER, FAVORITE, FOCUS_MODE_LIST, DETAIL_INFO}; } // namespace AdvancedDatashareHelper::AdvancedDatashareHelper() { @@ -59,6 +79,21 @@ std::shared_ptr AdvancedDatashareHelper::CreateDataS return DataShare::DataShareHelper::Creator(remoteObj, SETTINGS_DATASHARE_URI, SETTINGS_DATA_EXT_URI); } +std::shared_ptr AdvancedDatashareHelper::CreateContactDataShareHelper(std::string uri) +{ + sptr saManager = SystemAbilityManagerClient::GetInstance().GetSystemAbilityManager(); + if (saManager == nullptr) { + ANS_LOGE("The sa manager is nullptr."); + return nullptr; + } + sptr remoteObj = saManager->GetSystemAbility(ADVANCED_NOTIFICATION_SERVICE_ABILITY_ID); + if (remoteObj == nullptr) { + ANS_LOGE("The remoteObj is nullptr."); + return nullptr; + } + return DataShare::DataShareHelper::Creator(remoteObj, uri); +} + bool AdvancedDatashareHelper::Query(Uri &uri, const std::string &key, std::string &value) { std::shared_ptr dataShareHelper = CreateDataShareHelper(); @@ -90,6 +125,131 @@ bool AdvancedDatashareHelper::Query(Uri &uri, const std::string &key, std::strin return true; } +bool AdvancedDatashareHelper::QueryContact(Uri &uri, const std::string &phoneNumber, const std::string &policy) +{ + std::string identity = IPCSkeleton::ResetCallingIdentity(); + std::shared_ptr helper = CreateContactDataShareHelper(CONTACT_URI); + if (helper == nullptr) { + ANS_LOGE("The data share helper is nullptr."); + return false; + } + DataShare::DataSharePredicates predicates; + predicates.EqualTo(IS_DELETED, 0); + predicates.EqualTo(TYPE_ID, TYPE_ID_FIVE); + if (phoneNumber.size() >= PHONE_NUMBER_LENGTH) { + predicates.EndsWith(DETAIL_INFO, + phoneNumber.substr(phoneNumber.size() - PHONE_NUMBER_LENGTH, phoneNumber.size())); + } else { + predicates.EqualTo(DETAIL_INFO, phoneNumber); + } + auto resultSet = helper->Query(uri, predicates, QUERY_CONTACT_COLUMN_LIST); + IPCSkeleton::SetCallingIdentity(identity); + if (resultSet == nullptr) { + ANS_LOGE("Query error, resultSet is null."); + helper->Release(); + return false; + } + bool isFound = false; + int rowCount = 0; + resultSet->GetRowCount(rowCount); + if (rowCount <= 0) { + ANS_LOGI("Query success, but rowCount is 0."); + } else { + int resultId = -1; +#ifdef ENABLE_ANS_TELEPHONY_CUST_WRAPPER + resultId = TEL_EXTENTION_WRAPPER->GetCallerIndex(resultSet, phoneNumber); + ANS_LOGI("QueryContact resultId: %{public}d.", resultId); +#endif + if ((phoneNumber.size() >= PHONE_NUMBER_LENGTH && resultSet->GoToRow(resultId) == DataShare::E_OK) || + (phoneNumber.size() < PHONE_NUMBER_LENGTH && resultSet->GoToFirstRow() == DataShare::E_OK)) { + isFound = dealWithContactResult(helper, resultSet, policy); + } + } + resultSet->Close(); + helper->Release(); + return isFound; +} + +bool AdvancedDatashareHelper::dealWithContactResult(std::shared_ptr helper, + std::shared_ptr resultSet, const std::string &policy) +{ + bool isNoNeedSilent = false; + int32_t columnIndex; + int32_t favorite; + std::string focus_mode_list; + switch (atoi(policy.c_str())) { + case ContactPolicy::ALLOW_FAVORITE_CONTACTS: + do { + resultSet->GetColumnIndex(FAVORITE, columnIndex); + resultSet->GetInt(columnIndex, favorite); + ANS_LOGI("dealWithContactResult: favorite = %{public}d", favorite); + isNoNeedSilent = favorite == 1; + if (isNoNeedSilent) { + break; + } + } while (resultSet->GoToNextRow() == DataShare::E_OK); + break; + case ContactPolicy::ALLOW_SPECIFIED_CONTACTS: + do { + resultSet->GetColumnIndex(FOCUS_MODE_LIST, columnIndex); + resultSet->GetString(columnIndex, focus_mode_list); + ANS_LOGI("dealWithContactResult: focus_mode_list = %{public}s", focus_mode_list.c_str()); + if (focus_mode_list.empty() || focus_mode_list.c_str()[0] == '0') { + isNoNeedSilent = false; + } + if (focus_mode_list.c_str()[0] == '1') { + isNoNeedSilent = true; + break; + } + } while (resultSet->GoToNextRow() == DataShare::E_OK); + break; + default: + isNoNeedSilent = true; + break; + } + return isNoNeedSilent; +} + +bool AdvancedDatashareHelper::isRepeatCall(const std::string &phoneNumber) +{ + std::string identity = IPCSkeleton::ResetCallingIdentity(); + std::shared_ptr helper = CreateContactDataShareHelper(CALLLOG_URI); + if (helper == nullptr) { + ANS_LOGE("The data share helper is nullptr."); + return false; + } + bool isRepeat = false; + DataShare::DataSharePredicates predicates; + std::vector columns; + Uri uri(CALL_SUBSECTION); + predicates.EqualTo(PHONE_NUMBER, phoneNumber); + predicates.EqualTo(CALL_DIRECTION, 0); + predicates.OrderByDesc(CREATE_TIME); + columns.push_back(CREATE_TIME); + auto resultSet = helper->Query(uri, predicates, columns); + IPCSkeleton::SetCallingIdentity(identity); + if (resultSet == nullptr) { + helper->Release(); + return false; + } + int rowCount = 0; + resultSet->GetRowCount(rowCount); + if (rowCount > 0) { + int32_t columnIndex; + int32_t callTime = 0; + if (resultSet->GoToFirstRow() == 0) { + resultSet->GetColumnIndex(CREATE_TIME, columnIndex); + resultSet->GetInt(columnIndex, callTime); + } + if (time(NULL) - callTime < MAX_TIME_INTERVAL) { + isRepeat = true; + } + } + resultSet->Close(); + helper->Release(); + return isRepeat; +} + std::string AdvancedDatashareHelper::GetFocusModeEnableUri(const int32_t &userId) const { return USER_SETTINGS_DATA_SECURE_URI + std::to_string(userId) + FOCUS_MODE_ENABLE_URI; @@ -99,5 +259,15 @@ std::string AdvancedDatashareHelper::GetFocusModeProfileUri(const int32_t &userI { return USER_SETTINGS_DATA_SECURE_URI + std::to_string(userId) + FOCUS_MODE_PROFILE_URI; } + +std::string AdvancedDatashareHelper::GetFocusModeCallPolicyUri(const int32_t &userId) const +{ + return USER_SETTINGS_DATA_URI + std::to_string(userId) + FOCUS_MODE_CALL_POLICY_URI; +} + +std::string AdvancedDatashareHelper::GetFocusModeRepeatCallUri(const int32_t &userId) const +{ + return USER_SETTINGS_DATA_URI + std::to_string(userId) + FOCUS_MODE_REPEAT_CALLERS_ENABLE_URI; +} } // namespace Notification } // namespace OHOS diff --git a/services/ans/src/advanced_notification_publish_service.cpp b/services/ans/src/advanced_notification_publish_service.cpp index 26b8c983a..cf6d41250 100644 --- a/services/ans/src/advanced_notification_publish_service.cpp +++ b/services/ans/src/advanced_notification_publish_service.cpp @@ -43,6 +43,13 @@ #include "advanced_notification_inline.cpp" #include "notification_analytics_util.h" +#include "advanced_datashare_helper.h" +#include "advanced_datashare_helper_ext.h" +#include "datashare_result_set.h" +#include "system_ability_definition.h" +#include "if_system_ability_manager.h" +#include "iservice_registry.h" +#include "datashare_predicates.h" namespace OHOS { namespace Notification { @@ -55,6 +62,9 @@ constexpr int32_t ANS_UID = 5523; constexpr int32_t PSS_UID = 7123; constexpr int32_t TYPE_CODE_DOWNLOAD = 8; constexpr int32_t OPERATION_TYPE_COMMON_EVENT = 4; +static constexpr const char *CONTACT_DATA = "datashare:///com.ohos.contactsdataability/contacts/contact_data"; +constexpr const char *FOCUS_MODE_REPEAT_CALLERS_ENABLE = "1"; +constexpr const char *CONTACT_DATA = "datashare:///com.ohos.contactsdataability/contacts/contact_data?Proxy=true"; ErrCode AdvancedNotificationService::SetDefaultNotificationEnabled( const sptr &bundleOption, bool enabled) @@ -1648,6 +1658,73 @@ ErrCode AdvancedNotificationService::RemoveNotificationBySlot(const sptr::GetInstance(); + if (datashareHelper == nullptr) { + ANS_LOGE("The data share helper is nullptr."); + return -1; + } + + bool isNeedSilent = false; + std::string policy; + Uri policyUri(datashareHelper->GetFocusModeCallPolicyUri(userId)); + bool ret = datashareHelper->Query(policyUri, KEY_FOCUS_MODE_CALL_MESSAGE_POLICY, policy); + if (!ret) { + ANS_LOGE("Query focus mode call message policy fail."); + return -1; + } + std::string repeat_call; + Uri repeatUri(datashareHelper->GetFocusModeRepeatCallUri(userId)); + bool repeat_ret = datashareHelper->Query(repeatUri, KEY_FOCUS_MODE_REPEAT_CALLERS_ENABLE, repeat_call); + if (!repeat_ret) { + ANS_LOGE("Query focus mode repeat callers enable fail."); + } + ANS_LOGI("IsNeedSilent: policy: %{public}s, repeat: %{public}s, callerType: %{public}d", + policy.c_str(), repeat_call.c_str(), callerType); + if (repeat_call == FOCUS_MODE_REPEAT_CALLERS_ENABLE && + callerType == 0 && atoi(policy.c_str()) != ContactPolicy::ALLOW_EVERYONE) { + if (datashareHelper->isRepeatCall(phoneNumber)) { + return 1; + } + } + switch (atoi(policy.c_str())) { + case ContactPolicy::FORBID_EVERYONE: + break; + case ContactPolicy::ALLOW_EVERYONE: + isNeedSilent = true; + break; + case ContactPolicy::ALLOW_EXISTING_CONTACTS: + case ContactPolicy::ALLOW_FAVORITE_CONTACTS: + case ContactPolicy::ALLOW_SPECIFIED_CONTACTS: + Uri uri(CONTACT_DATA); + isNeedSilent = datashareHelper->QueryContact(uri, phoneNumber, policy); + break; + } + ANS_LOGI("IsNeedSilentInDoNotDisturbMode: %{public}d", isNeedSilent); + return isNeedSilent ? 1 : 0; +} + ErrCode AdvancedNotificationService::CancelGroup(const std::string &groupName, int32_t instanceKey) { ANS_LOGD("%{public}s", __FUNCTION__); diff --git a/services/ans/src/advanced_notification_service_ability.cpp b/services/ans/src/advanced_notification_service_ability.cpp index b9e8c6c20..84a5ceed6 100644 --- a/services/ans/src/advanced_notification_service_ability.cpp +++ b/services/ans/src/advanced_notification_service_ability.cpp @@ -16,6 +16,8 @@ #include "advanced_notification_service_ability.h" #include "notification_extension_wrapper.h" #include "system_event_observer.h" +#include "common_event_manager.h" +#include "telephony_extension_wrapper.h" namespace OHOS { namespace Notification { @@ -51,6 +53,10 @@ void AdvancedNotificationServiceAbility::OnStart() #else ANS_LOGI("Not enabled ans_ext"); #endif + +#ifdef ENABLE_ANS_TELEPHONY_CUST_WRAPPER + TEL_EXTENTION_WRAPPER->InitTelExtentionWrapper(); +#endif } void AdvancedNotificationServiceAbility::OnStop() diff --git a/services/ans/src/telephony_extension_wrapper.cpp b/services/ans/src/telephony_extension_wrapper.cpp new file mode 100644 index 000000000..2050c7533 --- /dev/null +++ b/services/ans/src/telephony_extension_wrapper.cpp @@ -0,0 +1,63 @@ +/* + * Copyright (c) 2024 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include +#include + +#include "advanced_notification_service.h" +#include "telephony_extension_wrapper.h" +#include "notification_preferences.h" + +namespace OHOS::Notification { +const std::string EXTENTION_TELEPHONY_PATH = "libtelephony_cust_api.z.so"; +TelExtensionWrapper::TelExtensionWrapper() = default; +TelExtensionWrapper::~TelExtensionWrapper() = default; + +void TelExtensionWrapper::InitTelExtentionWrapper() +{ + telephonyCustHandle_ = dlopen(EXTENTION_TELEPHONY_PATH.c_str(), RTLD_NOW); + if (telephonyCustHandle_ == nullptr) { + ANS_LOGE("telephony extension wrapper symbol failed, error: %{public}s", dlerror()); + return; + } + + getCallerIndex_ = (GET_CALLER_INDEX)dlsym(telephonyCustHandle_, "GetCallerNumIndex"); + if (getCallerIndex_ == nullptr) { + ANS_LOGE("telephony extension wrapper getCallerIndex symbol failed, error: %{public}s", dlerror()); + return; + } + ANS_LOGI("telephony extension wrapper telephonyCustHandle_: %{public}p", telephonyCustHandle_); + ANS_LOGI("telephony extension wrapper getCallerIndex_: %{public}p", getCallerIndex_); + ANS_LOGI("telephony extension wrapper init success"); +} + +ErrCode TelExtensionWrapper::GetCallerIndex( + std::shared_ptr resultSet, std::string compNum) +{ + if (getCallerIndex_ == nullptr) { + ANS_LOGE("GetCallerIndex wrapper symbol failed"); + return -1; + } + return getCallerIndex_(resultSet, compNum); +} + +void TelExtensionWrapper::CloseTelExtentionWrapper() +{ + if (telephonyCustHandle_ != nullptr) { + dlclose(telephonyCustHandle_); + telephonyCustHandle_ = nullptr; + } +} +} // namespace OHOS::Notification \ No newline at end of file diff --git a/services/ans/test/unittest/advanced_notification_service_branch_test.cpp b/services/ans/test/unittest/advanced_notification_service_branch_test.cpp index 29e5a8809..68115327d 100644 --- a/services/ans/test/unittest/advanced_notification_service_branch_test.cpp +++ b/services/ans/test/unittest/advanced_notification_service_branch_test.cpp @@ -1189,5 +1189,36 @@ HWTEST_F(AnsBranchTest, AnsBranchTest_279002, Function | SmallTest | Level1) ASSERT_EQ(record->notification->GetFinishTimer(), NotificationConstant::INVALID_TIMER_ID); } +/** + * @tc.number : AnsBranchTest_285000 + * @tc.name : IsNeedSilentInDoNotDisturbMode_1000 + * @tc.desc : Test IsNeedSilentInDoNotDisturbMode function return ERR_ANS_NON_SYSTEM_APP. + */ +HWTEST_F(AnsBranchTest, AnsBranchTest_285000, Function | SmallTest | Level1) +{ + MockIsSystemApp(false); + MockGetTokenTypeFlag(ATokenTypeEnum::TOKEN_HAP); + + std::string phoneNumber = "11111111111"; + int32_t callerType = 0; + ASSERT_EQ(advancedNotificationService_->IsNeedSilentInDoNotDisturbMode( + phoneNumber, callerType), ERR_ANS_PERMISSION_DENIED); +} + +/** + * @tc.number : AnsBranchTest_286000 + * @tc.name : IsNeedSilentInDoNotDisturbMode_2000 + * @tc.desc : Test IsNeedSilentInDoNotDisturbMode function return ERR_ANS_PERMISSION_DENIED. + */ +HWTEST_F(AnsBranchTest, AnsBranchTest_286000, Function | SmallTest | Level1) +{ + MockGetTokenTypeFlag(ATokenTypeEnum::TOKEN_HAP); + MockIsVerfyPermisson(false); + + std::string phoneNumber = "11111111111"; + int32_t callerType = 0; + ASSERT_EQ(advancedNotificationService_->IsNeedSilentInDoNotDisturbMode( + phoneNumber, callerType), ERR_ANS_PERMISSION_DENIED); +} } // namespace Notification } // namespace OHOS diff --git a/services/ans/test/unittest/advanced_notification_service_test.cpp b/services/ans/test/unittest/advanced_notification_service_test.cpp index f26937a28..47692b941 100644 --- a/services/ans/test/unittest/advanced_notification_service_test.cpp +++ b/services/ans/test/unittest/advanced_notification_service_test.cpp @@ -1552,6 +1552,10 @@ HWTEST_F(AdvancedNotificationServiceTest, AdvancedNotificationServiceTest_17100, ASSERT_EQ(advancedNotificationService_->GetSyncNotificationEnabledWithoutApp(userId, enable), ERR_OK); + std::string phoneNumber = "11111111111"; + int32_t callerType = 0; + ASSERT_EQ(advancedNotificationService_->IsNeedSilentInDoNotDisturbMode(phoneNumber, callerType), ERR_OK); + GTEST_LOG_(INFO) << "ANS_GetActiveNotifications_0100 test end"; } @@ -2419,6 +2423,23 @@ HWTEST_F(AdvancedNotificationServiceTest, AdvancedNotificationServiceTest_220000 ASSERT_EQ(result.size(), ret); } +/** + * @tc.number : AdvancedNotificationServiceTest_22600 + * @tc.name : ANS_IsNeedSilentInDoNotDisturbMode_0100 + * @tc.desc : Test IsNeedSilentInDoNotDisturbMode function when the result is ERR_OK + * @tc.require : issueI5S4VP + */ +HWTEST_F(AdvancedNotificationServiceTest, AdvancedNotificationServiceTest_22600, Function | SmallTest | Level1) +{ + TestAddSlot(NotificationConstant::SlotType::SOCIAL_COMMUNICATION); + sptr req = new NotificationRequest(); + EXPECT_NE(req, nullptr); + std::string phoneNumber = "11111111111"; + int32_t callerType = 0; + auto ret = advancedNotificationService_->IsNeedSilentInDoNotDisturbMode(phoneNumber, callerType); + ASSERT_EQ(ret, (int)ERR_OK); +} + /** * @tc.number : AdvancedNotificationServiceTest_00001 * @tc.name : PrepareNotificationRequest diff --git a/services/ans/test/unittest/notification_subscriber_manager_branch_test/notification_subscriber_manager_branch_test.cpp b/services/ans/test/unittest/notification_subscriber_manager_branch_test/notification_subscriber_manager_branch_test.cpp index d640882e6..125426ef7 100644 --- a/services/ans/test/unittest/notification_subscriber_manager_branch_test/notification_subscriber_manager_branch_test.cpp +++ b/services/ans/test/unittest/notification_subscriber_manager_branch_test/notification_subscriber_manager_branch_test.cpp @@ -1315,5 +1315,22 @@ HWTEST_F(NotificationSubscriberManagerBranchTest, AdvancedNotificationService_06 AdvancedNotificationService advancedNotificationService; ASSERT_EQ(advancedNotificationService.GetEnabledForBundleSlotSelf(slotType, enabled), ERR_ANS_INVALID_BUNDLE); } + +/** + * @tc.number : AdvancedNotificationService_06900 + * @tc.name : AdvancedNotificationService_06900 + * @tc.desc : Test IsNeedSilentInDoNotDisturbMode function and CheckPermission is false + */ +HWTEST_F(NotificationSubscriberManagerBranchTest, AdvancedNotificationService_06900, Function | SmallTest | Level1) +{ + std::string phoneNumber = "11111111111"; + int32_t callerType = 0; + + MockGetTokenTypeFlag(ATokenTypeEnum::TOKEN_HAP); + MockIsSystemApp(false); + AdvancedNotificationService advancedNotificationService; + ASSERT_EQ(advancedNotificationService.IsNeedSilentInDoNotDisturbMode( + phoneNumber, callerType), ERR_ANS_GET_ACTIVE_USER_FAILED); +} } // namespace Notification } // namespace OHOS -- Gitee From b0c822b01b0cd1f4cda350281cd07098066368b4 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E7=8E=8B=E7=86=99=E8=BE=89?= <13821332216@163.com> Date: Fri, 6 Sep 2024 11:19:43 +0000 Subject: [PATCH 044/167] update services/ans/src/advanced_notification_publish_service.cpp. MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: 王熙辉 <13821332216@163.com> --- services/ans/src/advanced_notification_publish_service.cpp | 1 - 1 file changed, 1 deletion(-) diff --git a/services/ans/src/advanced_notification_publish_service.cpp b/services/ans/src/advanced_notification_publish_service.cpp index cf6d41250..72ad67d31 100644 --- a/services/ans/src/advanced_notification_publish_service.cpp +++ b/services/ans/src/advanced_notification_publish_service.cpp @@ -62,7 +62,6 @@ constexpr int32_t ANS_UID = 5523; constexpr int32_t PSS_UID = 7123; constexpr int32_t TYPE_CODE_DOWNLOAD = 8; constexpr int32_t OPERATION_TYPE_COMMON_EVENT = 4; -static constexpr const char *CONTACT_DATA = "datashare:///com.ohos.contactsdataability/contacts/contact_data"; constexpr const char *FOCUS_MODE_REPEAT_CALLERS_ENABLE = "1"; constexpr const char *CONTACT_DATA = "datashare:///com.ohos.contactsdataability/contacts/contact_data?Proxy=true"; -- Gitee From 15f05a5b57ca55a9574b4143c029ba34da1407a2 Mon Sep 17 00:00:00 2001 From: xdongs2009 Date: Sun, 8 Sep 2024 01:32:32 +0000 Subject: [PATCH 045/167] update /NotificationServiceExtAbility.ts. Signed-off-by: xdongs2009 --- .../main/ets/ServiceExtAbility/NotificationServiceExtAbility.ts | 1 + 1 file changed, 1 insertion(+) diff --git a/services/dialog_ui/enable_notification_dialog/entry/src/main/ets/ServiceExtAbility/NotificationServiceExtAbility.ts b/services/dialog_ui/enable_notification_dialog/entry/src/main/ets/ServiceExtAbility/NotificationServiceExtAbility.ts index b7ed2cb8c..256e9e1c9 100644 --- a/services/dialog_ui/enable_notification_dialog/entry/src/main/ets/ServiceExtAbility/NotificationServiceExtAbility.ts +++ b/services/dialog_ui/enable_notification_dialog/entry/src/main/ets/ServiceExtAbility/NotificationServiceExtAbility.ts @@ -80,6 +80,7 @@ export class EnableNotificationDialog { extensionWindow:uiExtensionHost.UIExtensionHostWindowProxy; storage: LocalStorage; stageModel: boolean; + subWindow: window.Window; constructor(id: number, want: Want, stageModel: boolean) { this.id = id; -- Gitee From 6b4c845aa79151e059e33ec6ec353c7456241706 Mon Sep 17 00:00:00 2001 From: zhubingwei Date: Mon, 9 Sep 2024 16:35:07 +0800 Subject: [PATCH 046/167] =?UTF-8?q?Revert=20"!1848=20=E9=85=8D=E5=90=88abi?= =?UTF-8?q?lity=5Fruntime=E5=88=A0=E9=99=A4=E7=BB=9D=E5=AF=B9=E8=B7=AF?= =?UTF-8?q?=E5=BE=84"?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit This reverts commit 659a3f340418e2dd0100f65923424134a8f7a656, reversing changes made to 06fe346377bd48ee4e9cd967de6b0a614a1a2ac9. Signed-off-by: zhubingwei --- services/ans/BUILD.gn | 1 - 1 file changed, 1 deletion(-) diff --git a/services/ans/BUILD.gn b/services/ans/BUILD.gn index f694616c1..6708d1f40 100644 --- a/services/ans/BUILD.gn +++ b/services/ans/BUILD.gn @@ -136,7 +136,6 @@ ohos_shared_library("libans") { "ability_base:configuration", "ability_runtime:ability_manager", "ability_runtime:app_manager", - "ability_runtime:appkit_native", "ability_runtime:dataobs_manager", "ability_runtime:extension_manager", "ability_runtime:wantagent_innerkits", -- Gitee From 5dc3accbb81436a593fa02aced8004c5d3b4f538 Mon Sep 17 00:00:00 2001 From: z30053788 Date: Sun, 8 Sep 2024 14:36:42 +0800 Subject: [PATCH 047/167] =?UTF-8?q?=E8=93=9D=E9=BB=84=E5=90=8C=E6=AD=A5?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: z30053788 Change-Id: I2138eefbbf3c2d731efbdb2ac302f86baf932111 --- .../core/common/include/ans_convert_enum.h | 17 - .../core/common/src/ans_convert_enum.cpp | 76 +---- .../src/manager/napi_enable_notification.cpp | 2 +- .../js/napi/src/subscribe/napi_remove.cpp | 2 +- interfaces/inner_api/notification_constant.h | 82 ----- .../include/advanced_notification_service.h | 54 ++-- .../ans/src/advanced_notification_inline.cpp | 48 +-- ...dvanced_notification_live_view_service.cpp | 17 +- .../advanced_notification_publish_service.cpp | 306 ++++-------------- .../ans/src/advanced_notification_service.cpp | 110 ++----- .../ans/src/advanced_notification_utils.cpp | 73 +---- .../common/notification_analytics_util.cpp | 5 +- .../src/notification_subscriber_manager.cpp | 25 -- services/ans/src/reminder_data_manager.cpp | 2 +- ...nced_notification_publish_service_test.cpp | 12 +- .../advanced_notification_service_test.cpp | 4 +- 16 files changed, 146 insertions(+), 689 deletions(-) diff --git a/frameworks/core/common/include/ans_convert_enum.h b/frameworks/core/common/include/ans_convert_enum.h index 3c54fc5b1..3524578c3 100644 --- a/frameworks/core/common/include/ans_convert_enum.h +++ b/frameworks/core/common/include/ans_convert_enum.h @@ -54,7 +54,6 @@ enum class SlotLevel { }; enum class RemoveReason { - DEFAULT_REASON_DELETE = 0, CLICK_REASON_REMOVE = 1, CANCEL_REASON_REMOVE = 2, CANCEL_ALL_REASON_REMOVE = 3, @@ -68,22 +67,6 @@ enum class RemoveReason { FLOW_CONTROL_REASON_DELETE = 11, DISABLE_SLOT_REASON_DELETE = 12, DISABLE_NOTIFICATION_REASON_DELETE = 13, - APP_CANCEL_AS_BUNELE_REASON_DELETE = 14, - APP_CANCEL_AS_BUNELE_WITH_AGENT_REASON_DELETE = 15, - APP_CANCEL_REMINDER_REASON_DELETE = 16, - APP_CANCEL_GROPU_REASON_DELETE = 17, - APP_REMOVE_GROUP_REASON_DELETE = 18, - APP_REMOVE_ALL_REASON_DELETE = 19, - APP_REMOVE_ALL_USER_REASON_DELETE = 20, - TRIGGER_EIGHT_HOUR_REASON_DELETE = 21, - TRIGGER_FOUR_HOUR_REASON_DELETE = 22, - TRIGGER_TEN_MINUTES_REASON_DELETE = 23, - TRIGGER_FIFTEEN_MINUTES_REASON_DELETE = 24, - TRIGGER_THIRTY_MINUTES_REASON_DELETE = 25, - TRIGGER_START_ARCHIVE_REASON_DELETE = 26, - TRIGGER_AUTO_DELETE_REASON_DELETE = 27, - PACKAGE_REMOVE_REASON_DELETE = 28, - SLOT_ENABLED_REASON_DELETE = 29, APP_CANCEL_REASON_OTHER = 100, }; diff --git a/frameworks/core/common/src/ans_convert_enum.cpp b/frameworks/core/common/src/ans_convert_enum.cpp index 594e0edee..6eeecc3ab 100644 --- a/frameworks/core/common/src/ans_convert_enum.cpp +++ b/frameworks/core/common/src/ans_convert_enum.cpp @@ -225,9 +225,6 @@ bool AnsEnumUtil::SlotLevelCToJS(const NotificationSlot::NotificationLevel &inLe bool AnsEnumUtil::ReasonCToJS(const int &inType, int &outType) { switch (inType) { - case NotificationConstant::DEFAULT_REASON_DELETE: - outType = static_cast(RemoveReason::DEFAULT_REASON_DELETE); - break; case NotificationConstant::CLICK_REASON_DELETE: outType = static_cast(RemoveReason::CLICK_REASON_REMOVE); break; @@ -258,87 +255,20 @@ bool AnsEnumUtil::ReasonCToJS(const int &inType, int &outType) case NotificationConstant::FLOW_CONTROL_REASON_DELETE: outType = static_cast(RemoveReason::FLOW_CONTROL_REASON_DELETE); break; - default: - ReasonCToJSExt(inType, outType); - break; - } - return true; -} - -void AnsEnumUtil::ReasonCToJSExt(const int &inType, int &outType) -{ - switch (inType) { case NotificationConstant::DISABLE_SLOT_REASON_DELETE: outType = static_cast(RemoveReason::DISABLE_SLOT_REASON_DELETE); break; case NotificationConstant::DISABLE_NOTIFICATION_REASON_DELETE: outType = static_cast(RemoveReason::DISABLE_NOTIFICATION_REASON_DELETE); break; - case NotificationConstant::APP_CANCEL_AS_BUNELE_REASON_DELETE: - outType = static_cast(RemoveReason::APP_CANCEL_AS_BUNELE_REASON_DELETE); - break; - case NotificationConstant::APP_CANCEL_AS_BUNELE_WITH_AGENT_REASON_DELETE: - outType = static_cast(RemoveReason::APP_CANCEL_AS_BUNELE_WITH_AGENT_REASON_DELETE); - break; - case NotificationConstant::APP_CANCEL_REMINDER_REASON_DELETE: - outType = static_cast(RemoveReason::APP_CANCEL_REMINDER_REASON_DELETE); - break; - case NotificationConstant::APP_CANCEL_GROPU_REASON_DELETE: - outType = static_cast(RemoveReason::APP_CANCEL_GROPU_REASON_DELETE); - break; - case NotificationConstant::APP_REMOVE_GROUP_REASON_DELETE: - outType = static_cast(RemoveReason::APP_REMOVE_GROUP_REASON_DELETE); - break; - case NotificationConstant::APP_REMOVE_ALL_REASON_DELETE: - outType = static_cast(RemoveReason::APP_REMOVE_ALL_REASON_DELETE); - break; - case NotificationConstant::APP_REMOVE_ALL_USER_REASON_DELETE: - outType = static_cast(RemoveReason::APP_REMOVE_ALL_USER_REASON_DELETE); - break; - case NotificationConstant::TRIGGER_EIGHT_HOUR_REASON_DELETE: - outType = static_cast(RemoveReason::TRIGGER_EIGHT_HOUR_REASON_DELETE); - break; - case NotificationConstant::TRIGGER_FOUR_HOUR_REASON_DELETE: - outType = static_cast(RemoveReason::TRIGGER_FOUR_HOUR_REASON_DELETE); - break; - default: - ReasonCToJSSecondExt(inType, outType); - break; - } -} - -void AnsEnumUtil::ReasonCToJSSecondExt(const int &inType, int &outType) -{ - switch (inType) { - case NotificationConstant::TRIGGER_TEN_MINUTES_REASON_DELETE: - outType = static_cast(RemoveReason::TRIGGER_TEN_MINUTES_REASON_DELETE); - break; - case NotificationConstant::TRIGGER_FIFTEEN_MINUTES_REASON_DELETE: - outType = static_cast(RemoveReason::TRIGGER_FIFTEEN_MINUTES_REASON_DELETE); - break; - case NotificationConstant::TRIGGER_THIRTY_MINUTES_REASON_DELETE: - outType = static_cast(RemoveReason::TRIGGER_THIRTY_MINUTES_REASON_DELETE); - break; - case NotificationConstant::TRIGGER_START_ARCHIVE_REASON_DELETE: - outType = static_cast(RemoveReason::TRIGGER_START_ARCHIVE_REASON_DELETE); - break; - case NotificationConstant::TRIGGER_AUTO_DELETE_REASON_DELETE: - outType = static_cast(RemoveReason::TRIGGER_AUTO_DELETE_REASON_DELETE); - break; - case NotificationConstant::PACKAGE_REMOVE_REASON_DELETE: - outType = static_cast(RemoveReason::PACKAGE_REMOVE_REASON_DELETE); - break; - case NotificationConstant::SLOT_ENABLED_REASON_DELETE: - outType = static_cast(RemoveReason::SLOT_ENABLED_REASON_DELETE); - break; case NotificationConstant::APP_CANCEL_REASON_OTHER: outType = static_cast(RemoveReason::APP_CANCEL_REASON_OTHER); break; default: - outType = static_cast(RemoveReason::APP_CANCEL_REASON_OTHER); - ANS_LOGW("Reason %{public}d is an invalid value", inType); - break; + ANS_LOGE("Reason %{public}d is an invalid value", inType); + return false; } + return true; } bool AnsEnumUtil::DoNotDisturbTypeJSToC(const DoNotDisturbType &inType, NotificationConstant::DoNotDisturbType &outType) diff --git a/frameworks/js/napi/src/manager/napi_enable_notification.cpp b/frameworks/js/napi/src/manager/napi_enable_notification.cpp index 8a0339015..4d3ed36b0 100644 --- a/frameworks/js/napi/src/manager/napi_enable_notification.cpp +++ b/frameworks/js/napi/src/manager/napi_enable_notification.cpp @@ -253,7 +253,7 @@ void NapiAsyncCompleteCallbackRequestEnableNotification(napi_env env, void *data napi_value NapiRequestEnableNotification(napi_env env, napi_callback_info info) { - ANS_LOGI("NapiRequestEnableNotification enter"); + ANS_LOGD("enter"); IsEnableParams params {}; if (ParseRequestEnableParameters(env, info, params) == nullptr) { Common::NapiThrow(env, ERROR_PARAM_INVALID); diff --git a/frameworks/js/napi/src/subscribe/napi_remove.cpp b/frameworks/js/napi/src/subscribe/napi_remove.cpp index 5b5f53207..798edbac5 100644 --- a/frameworks/js/napi/src/subscribe/napi_remove.cpp +++ b/frameworks/js/napi/src/subscribe/napi_remove.cpp @@ -115,7 +115,7 @@ napi_value NapiRemoveAll(napi_env env, napi_callback_info info) nullptr, resourceName, [](napi_env env, void *data) { - ANS_LOGI("NapiRemoveAll work excute."); + ANS_LOGD("NapiRemoveAll work excute."); AsyncCallbackInfoRemove *asynccallbackinfo = static_cast(data); if (asynccallbackinfo) { if (asynccallbackinfo->params.bundleAndKeyInfo.has_value()) { diff --git a/interfaces/inner_api/notification_constant.h b/interfaces/inner_api/notification_constant.h index 573fdaa40..0a2c74429 100644 --- a/interfaces/inner_api/notification_constant.h +++ b/interfaces/inner_api/notification_constant.h @@ -144,8 +144,6 @@ public: CLOSE }; - static const int32_t DEFAULT_REASON_DELETE = 0; - /** * Indicates that a notification is deleted because it is clicked. */ @@ -211,86 +209,6 @@ public: */ static const int32_t DISABLE_NOTIFICATION_REASON_DELETE = 13; - /** - * Indicates that a notification is deleted by bundle because the application cancel it. - */ - static const int32_t APP_CANCEL_AS_BUNELE_REASON_DELETE = 14; - - /** - * Indicates that a notification is deleted by agent because the application cancel it. - */ - static const int32_t APP_CANCEL_AS_BUNELE_WITH_AGENT_REASON_DELETE = 15; - - /** - * Indicates that a notification is deleted because the reminder cancel it. - */ - static const int32_t APP_CANCEL_REMINDER_REASON_DELETE = 16; - - /** - * Indicates that a notification is deleted because the application cancel it by group. - */ - static const int32_t APP_CANCEL_GROPU_REASON_DELETE = 17; - - /** - * Indicates that a notification is deleted by group because the system cancel it. - */ - static const int32_t APP_REMOVE_GROUP_REASON_DELETE = 18; - - /** - * Indicates that aLL notification is deleted because the system cancel it. - */ - static const int32_t APP_REMOVE_ALL_REASON_DELETE = 19; - - /** - * Indicates that aLL notification is deleted by userId because the system cancel it. - */ - static const int32_t APP_REMOVE_ALL_USER_REASON_DELETE = 20; - - /** - * Indicates that notification is deleted because eight-hour timer cancel it. - */ - static const int32_t TRIGGER_EIGHT_HOUR_REASON_DELETE = 21; - - /** - * Indicates that notification is deleted because four-hour timer cancel it. - */ - static const int32_t TRIGGER_FOUR_HOUR_REASON_DELETE = 22; - - /** - * Indicates that notification is deleted because ten-minutes timer cancel it. - */ - static const int32_t TRIGGER_TEN_MINUTES_REASON_DELETE = 23; - - /** - * Indicates that notification is deleted because fifteen-minutes timer cancel it. - */ - static const int32_t TRIGGER_FIFTEEN_MINUTES_REASON_DELETE = 24; - - /** - * Indicates that notification is deleted because thirty-minutes timer cancel it. - */ - static const int32_t TRIGGER_THIRTY_MINUTES_REASON_DELETE = 25; - - /** - * Indicates that notification is deleted because startArchive timer cancel it. - */ - static const int32_t TRIGGER_START_ARCHIVE_REASON_DELETE = 26; - - /** - * Indicates that notification is deleted because auto delete timer cancel it. - */ - static const int32_t TRIGGER_AUTO_DELETE_REASON_DELETE = 27; - - /** - * Indicates that notification is deleted because auto packge remove cancel it. - */ - static const int32_t PACKAGE_REMOVE_REASON_DELETE = 28; - - /** - * Indicates that notification is deleted because slot enabled close remove cancel it. - */ - static const int32_t SLOT_ENABLED_REASON_DELETE = 29; - /** * Indicates that a notification is deleted for other reasons. */ diff --git a/services/ans/include/advanced_notification_service.h b/services/ans/include/advanced_notification_service.h index 55fe6ec84..7b7cacf54 100644 --- a/services/ans/include/advanced_notification_service.h +++ b/services/ans/include/advanced_notification_service.h @@ -17,10 +17,10 @@ #define BASE_NOTIFICATION_DISTRIBUTED_NOTIFICATION_SERVICE_SERVICES_ANS_INCLUDE_ADVANCED_NOTIFICATION_SERVICE_H #include -#include #include #include #include +#include #include "event_handler.h" #include "event_runner.h" @@ -919,9 +919,8 @@ public: */ void OnDistributedKvStoreDeathRecipient(); - ErrCode CancelPreparedNotification(int32_t notificationId, const std::string &label, - const sptr &bundleOption, const int32_t reason); - + ErrCode CancelPreparedNotification( + int32_t notificationId, const std::string &label, const sptr &bundleOption); ErrCode PrepareNotificationInfo( const sptr &request, sptr &bundleOption); ErrCode PublishPreparedNotification(const sptr &request, @@ -996,7 +995,7 @@ public: ErrCode SetDistributedEnabledByBundle(const sptr &bundleOption, const std::string &deviceType, const bool enabled) override; - /** + /* * @brief Get whether to allow a specified application to publish notifications cross * device collaboration. The caller must have system permissions to call this method. * @@ -1143,13 +1142,6 @@ private: size_t recentCount = 16; }; - struct SoundPermissionInfo { - std::set bundleName_; - std::atomic needUpdateCache_ = true; - bool allPackage_ = false; - std::mutex dbMutex_; - }; - enum UploadStatus { CREATE, FIRST_UPDATE_TIME_OUT, @@ -1158,6 +1150,13 @@ private: FINISH }; + struct SoundPermissionInfo { + std::set bundleName_; + std::atomic needUpdateCache_ = true; + bool allPackage_ = false; + std::mutex dbMutex_; + }; + enum ContactPolicy { FORBID_EVERYONE = 1, ALLOW_EVERYONE = 2, @@ -1197,7 +1196,7 @@ private: ErrCode FlowControl(const std::shared_ptr &record); ErrCode PublishFlowControl(const std::shared_ptr &record); ErrCode RemoveNotificationBySlot(const sptr &bundleOption, - const sptr &slot, const int reason); + const sptr &slot); sptr GenerateSortingMap(); static sptr GenerateBundleOption(); @@ -1205,7 +1204,6 @@ private: std::string TimeToString(int64_t time); int64_t GetNowSysTime(); - void ExtendDumpForFlags(std::shared_ptr, std::stringstream &stream); ErrCode ActiveNotificationDump(const std::string& bundle, int32_t userId, int32_t recvUserId, std::vector &dumpInfo); ErrCode RecentNotificationDump(const std::string& bundle, int32_t userId, int32_t recvUserId, @@ -1287,6 +1285,12 @@ private: void SetAgentNotification(sptr& notificationRequest, std::string& bundleName); ErrCode SetDefaultNotificationEnabled( const sptr &bundleOption, bool enabled); + ErrCode IsAllowedNotifyForBundle(const sptr &bundleOption, bool &allowed); + void AddLiveViewSubscriber(); + void EraseLiveViewSubsciber(const std::string &bundleName); + bool GetLiveViewSubscribeState(const std::string &bundleName); + bool CheckLocalLiveViewSubscribed(const sptr &request); + bool CheckLocalLiveViewAllowed(const sptr &request); static bool GetBundleInfoByNotificationBundleOption( const sptr &bundleOption, AppExecFwk::BundleInfo &bundleInfo); @@ -1307,16 +1311,15 @@ private: void CancelTimer(uint64_t timerId); ErrCode UpdateNotificationTimerInfo(const std::shared_ptr &record); ErrCode SetFinishTimer(const std::shared_ptr &record); - ErrCode StartFinishTimer(const std::shared_ptr &record, - int64_t expireTimePoint, const int32_t reason); + ErrCode StartFinishTimer(const std::shared_ptr &record, int64_t expireTimePoint); void CancelFinishTimer(const std::shared_ptr &record); ErrCode SetUpdateTimer(const std::shared_ptr &record); - ErrCode StartUpdateTimer(const std::shared_ptr &record, - int64_t expireTimePoint, const int32_t reason); + ErrCode StartUpdateTimer(const std::shared_ptr &record, int64_t expireTimePoint); void CancelUpdateTimer(const std::shared_ptr &record); void StartArchiveTimer(const std::shared_ptr &record); void CancelArchiveTimer(const std::shared_ptr &record); void ProcForDeleteLiveView(const std::shared_ptr &record); + ErrCode IsAllowedGetNotificationByFilter(const std::shared_ptr &record); void QueryDoNotDisturbProfile(const int32_t &userId, std::string &enable, std::string &profileId); void CheckDoNotDisturbProfile(const std::shared_ptr &record); void DoNotDisturbUpdataReminderFlags(const std::shared_ptr &record); @@ -1325,7 +1328,6 @@ private: int32_t notificationId, int32_t uid, const std::string &label, const std::string &bundleName); std::shared_ptr MakeNotificationRecord( const sptr &request, const sptr &bundleOption); - ErrCode IsAllowedNotifyForBundle(const sptr &bundleOption, bool &allowed); void FillActionButtons(const sptr &request); ErrCode IsAllowedGetNotificationByFilter(const std::shared_ptr &record, const sptr &bundleOption); @@ -1342,16 +1344,15 @@ private: void RemoveExpiredUniqueKey(); bool IsDuplicateMsg(const std::string &uniqueKey); ErrCode PublishRemoveDuplicateEvent(const std::shared_ptr &record); - ErrCode UpdateSlotAuthInfo(const std::shared_ptr &record); std::vector GetBundlesOfActiveUser(); - void RemoveNotificationList(const std::shared_ptr &record); + ErrCode UpdateSlotAuthInfo(const std::shared_ptr &record); void FillLockScreenPicture(const sptr &newRequest, const sptr &oldRequest); + ErrCode CancelAsBundleWithAgent( + const sptr &bundleOption, const int32_t id, const std::string &label, int32_t userId); static ErrCode SetLockScreenPictureToDb(const sptr &request); static ErrCode GetLockScreenPictureFromDb(NotificationRequest *request); void RemoveDoNotDisturbProfileTrustList(const sptr &bundleOption); - ErrCode DeleteAllByUserInner(const int32_t &userId, int32_t reason, bool isAsync = false); - ErrCode RemoveAllNotificationsInner(const sptr &bundleOption, int32_t reason); ErrCode AssignValidNotificationSlot(const std::shared_ptr &record, const sptr &bundleOption); ErrCode UpdateSlotReminderModeBySlotFlags(const sptr &bundle, uint32_t slotFlags); @@ -1367,11 +1368,10 @@ private: ErrCode StartPublishDelayedNotification(const std::shared_ptr &record); void StartPublishDelayedNotificationTimeOut(const int32_t ownerUid, const int32_t notificationId); void UpdateRecordByOwner(const std::shared_ptr &record, bool isSystemApp); + ErrCode DeleteAllByUserInner(const int32_t &userId, int32_t reason, bool isAsync = false); + ErrCode RemoveAllNotificationsInner(const sptr &bundleOption, int32_t reason); + void RemoveNotificationList(const std::shared_ptr &record); ErrCode CheckSystemLiveView(const sptr &request, const std::string &key); - void ExcuteCancelGroupCancel(const sptr& bundleOption, - const std::string &groupName, const int32_t reason); - ErrCode ExcuteCancelAll(const sptr& bundleOption, const int32_t reason); - ErrCode ExcuteDelete(const std::string &key, const int32_t removeReason); ErrCode CheckNeedSilent(const std::string &phoneNumber, int32_t callerType, int32_t userId); private: diff --git a/services/ans/src/advanced_notification_inline.cpp b/services/ans/src/advanced_notification_inline.cpp index 2999bd000..34eac7195 100644 --- a/services/ans/src/advanced_notification_inline.cpp +++ b/services/ans/src/advanced_notification_inline.cpp @@ -28,15 +28,16 @@ #include "notification_constant.h" #include "os_account_manager_helper.h" #include "notification_preferences.h" -#include "notification_analytics_util.h" namespace OHOS { namespace Notification { -inline std::string GetClientBundleNameByUid(int32_t callingUid) +inline std::string GetClientBundleName() { std::string bundle; + int32_t callingUid = IPCSkeleton::GetCallingUid(); + std::shared_ptr bundleManager = BundleManagerHelper::GetInstance(); if (bundleManager != nullptr) { bundle = bundleManager->GetBundleNameByUid(callingUid); @@ -45,12 +46,6 @@ inline std::string GetClientBundleNameByUid(int32_t callingUid) return bundle; } -inline std::string GetClientBundleName() -{ - int32_t callingUid = IPCSkeleton::GetCallingUid(); - return GetClientBundleNameByUid(callingUid); -} - inline int32_t CheckUserIdParams(const int userId) { if (userId != SUBSCRIBE_USER_INIT && !OsAccountManagerHelper::GetInstance().CheckUserExists(userId)) { @@ -117,42 +112,5 @@ inline void RemoveExpired( } } } - -inline OHOS::Notification::HaMetaMessage AddInformationInMessage( - OHOS::Notification::HaMetaMessage haMetaMessage, const int32_t reason, - std::string message) -{ - message += "reason:" + std::to_string(reason) + "."; - - std::string bundleName; - int32_t callingUid = IPCSkeleton::GetCallingUid(); - message += "uid:" + std::to_string(callingUid) + "."; - bundleName = GetClientBundleNameByUid(callingUid); - - haMetaMessage = haMetaMessage.AgentBundleName(bundleName); - haMetaMessage = haMetaMessage.Message(message); - return haMetaMessage; -} - - -inline void ReportDeleteFailedEventPush(OHOS::Notification::HaMetaMessage haMetaMessage, - const int32_t reason, std::string message) -{ - haMetaMessage = AddInformationInMessage(haMetaMessage, reason, message); - NotificationAnalyticsUtil::ReportDeleteFailedEvent(haMetaMessage); -} - -inline void ReportDeleteFailedEventPushByNotification(const sptr ¬ification, - OHOS::Notification::HaMetaMessage haMetaMessage, const int32_t reason, - std::string message) -{ - if (notification == nullptr) { - ANS_LOGW("report notificaiton is null"); - return; - } - haMetaMessage = AddInformationInMessage(haMetaMessage, reason, message); - NotificationAnalyticsUtil::ReportDeleteFailedEvent( - notification->GetNotificationRequestPoint(), haMetaMessage); -} } // namespace Notification } // namespace OHOS diff --git a/services/ans/src/advanced_notification_live_view_service.cpp b/services/ans/src/advanced_notification_live_view_service.cpp index 0f4d0d40e..ed39e55e2 100644 --- a/services/ans/src/advanced_notification_live_view_service.cpp +++ b/services/ans/src/advanced_notification_live_view_service.cpp @@ -84,10 +84,8 @@ void AdvancedNotificationService::RecoverLiveViewFromDb(int32_t userId) } UpdateRecentNotification(record->notification, false, 0); - StartFinishTimer(record, requestObj.request->GetFinishDeadLine(), - NotificationConstant::TRIGGER_EIGHT_HOUR_REASON_DELETE); - StartUpdateTimer(record, requestObj.request->GetUpdateDeadLine(), - NotificationConstant::TRIGGER_FOUR_HOUR_REASON_DELETE); + StartFinishTimer(record, requestObj.request->GetFinishDeadLine()); + StartUpdateTimer(record, requestObj.request->GetUpdateDeadLine()); } // publish notifications @@ -553,12 +551,11 @@ ErrCode AdvancedNotificationService::StartPublishDelayedNotification(const std:: NotificationSubscriberManager::GetInstance()->NotifyConsumed(record->notification, GenerateSortingMap()); if ((record->request->GetAutoDeletedTime() > GetCurrentTime())) { StartAutoDelete(record, - record->request->GetAutoDeletedTime(), NotificationConstant::TRIGGER_AUTO_DELETE_REASON_DELETE); + record->request->GetAutoDeletedTime(), NotificationConstant::APP_CANCEL_REASON_DELETE); } record->finish_status = UploadStatus::FIRST_UPDATE_TIME_OUT; - StartFinishTimer(record, GetCurrentTime() + NotificationConstant::TEN_MINUTES, - NotificationConstant::TRIGGER_TEN_MINUTES_REASON_DELETE); + StartFinishTimer(record, GetCurrentTime() + NotificationConstant::TEN_MINUTES); return ERR_OK; } @@ -649,12 +646,10 @@ void AdvancedNotificationService::UpdateRecordByOwner( if (process == NotificationConstant::FINISH_PER) { record->finish_status = UploadStatus::FINISH; - StartFinishTimer(record, GetCurrentTime() + NotificationConstant::THIRTY_MINUTES, - NotificationConstant::TRIGGER_FIFTEEN_MINUTES_REASON_DELETE); + StartFinishTimer(record, GetCurrentTime() + NotificationConstant::THIRTY_MINUTES); } else { record->finish_status = UploadStatus::CONTINUOUS_UPDATE_TIME_OUT; - StartFinishTimer(record, GetCurrentTime() + NotificationConstant::FIFTEEN_MINUTES, - NotificationConstant::TRIGGER_THIRTY_MINUTES_REASON_DELETE); + StartFinishTimer(record, GetCurrentTime() + NotificationConstant::FIFTEEN_MINUTES); } timerId = record->notification->GetFinishTimer(); } diff --git a/services/ans/src/advanced_notification_publish_service.cpp b/services/ans/src/advanced_notification_publish_service.cpp index 72ad67d31..d2c5147e3 100644 --- a/services/ans/src/advanced_notification_publish_service.cpp +++ b/services/ans/src/advanced_notification_publish_service.cpp @@ -39,10 +39,8 @@ #include "common_event_publish_info.h" #include "want_params_wrapper.h" #include "ans_convert_enum.h" -#include "notification_analytics_util.h" #include "advanced_notification_inline.cpp" -#include "notification_analytics_util.h" #include "advanced_datashare_helper.h" #include "advanced_datashare_helper_ext.h" #include "datashare_result_set.h" @@ -59,6 +57,7 @@ constexpr int32_t HOURS_IN_ONE_DAY = 24; const static std::string NOTIFICATION_EVENT_PUSH_AGENT = "notification.event.PUSH_AGENT"; constexpr int32_t RSS_PID = 3051; constexpr int32_t ANS_UID = 5523; +constexpr int32_t BROKER_UID = 5557; constexpr int32_t PSS_UID = 7123; constexpr int32_t TYPE_CODE_DOWNLOAD = 8; constexpr int32_t OPERATION_TYPE_COMMON_EVENT = 4; @@ -105,18 +104,15 @@ ErrCode AdvancedNotificationService::Publish(const std::string &label, const spt } request->SetCreateTime(GetCurrentTime()); - HaMetaMessage message = HaMetaMessage(EventSceneId::SCENE_1, EventBranchId::BRANCH_1); bool isUpdateByOwnerAllowed = IsUpdateSystemLiveviewByOwner(request); ErrCode result = publishProcess_[request->GetSlotType()]->PublishPreWork(request, isUpdateByOwnerAllowed); if (result != ERR_OK) { - message.BranchId(EventBranchId::BRANCH_0).ErrorCode(result).Message("publish prework failed", true); - NotificationAnalyticsUtil::ReportPublishFailedEvent(request, message); + ANSR_LOGE("Failed to process request, result is %{public}d", result); return result; } result = CheckUserIdParams(request->GetReceiverUserId()); if (result != ERR_OK) { - message.SceneId(EventSceneId::SCENE_3).ErrorCode(result).Message("User is invalid", true); - NotificationAnalyticsUtil::ReportPublishFailedEvent(request, message); + ANSR_LOGE("User is invalid"); return result; } bool isSubsystem = AccessTokenHelper::VerifyNativeToken(IPCSkeleton::GetCallingTokenID()); @@ -146,7 +142,6 @@ ErrCode AdvancedNotificationService::Publish(const std::string &label, const spt result = CheckSoundPermission(request, bundleOption->GetBundleName()); if (result != ERR_OK) { - message.ErrorCode(result).Message("Check sound failed."); break; } @@ -154,17 +149,14 @@ ErrCode AdvancedNotificationService::Publish(const std::string &label, const spt result = PushCheck(request); } if (result != ERR_OK) { - message.ErrorCode(result).Message("Push check failed."); break; } result = PublishPreparedNotification(request, bundleOption, isUpdateByOwnerAllowed); if (result != ERR_OK) { - message.ErrorCode(result).Message("Publish prepared failed."); break; } } while (0); - NotificationAnalyticsUtil::ReportPublishFailedEvent(request, message); SendPublishHiSysEvent(request, result); return result; } @@ -211,23 +203,16 @@ ErrCode AdvancedNotificationService::Cancel(int32_t notificationId, const std::s sptr bundleOption = GenerateBundleOption(); if (bundleOption == nullptr) { - std::string message = "get bundleOption is null."; - OHOS::Notification::HaMetaMessage haMetaMessage = HaMetaMessage(1, 1) - .ErrorCode(ERR_ANS_INVALID_BUNDLE).NotificationId(notificationId); - ReportDeleteFailedEventPush(haMetaMessage, NotificationConstant::APP_CANCEL_REASON_DELETE, - message); - ANS_LOGE("%{public}s", message.c_str()); return ERR_ANS_INVALID_BUNDLE; } bundleOption->SetInstanceKey(instanceKey); - return CancelPreparedNotification(notificationId, label, bundleOption, - NotificationConstant::APP_CANCEL_REASON_DELETE); + return CancelPreparedNotification(notificationId, label, bundleOption); } ErrCode AdvancedNotificationService::CancelAll(int32_t instanceKey) { ANS_LOGD("%{public}s", __FUNCTION__); - const int reason = NotificationConstant::APP_CANCEL_ALL_REASON_DELETE; + sptr bundleOption = GenerateBundleOption(); if (bundleOption == nullptr) { return ERR_ANS_INVALID_BUNDLE; @@ -238,13 +223,6 @@ ErrCode AdvancedNotificationService::CancelAll(int32_t instanceKey) ANS_LOGE("Serial queue is invalidated."); return ERR_ANS_INVALID_PARAM; } - ErrCode result = ExcuteCancelAll(bundleOption, reason); - return result; -} - -ErrCode AdvancedNotificationService::ExcuteCancelAll( - const sptr& bundleOption, const int32_t reason) -{ ErrCode result = ERR_OK; ffrt::task_handle handler = notificationSvrQueue_->submit_h(std::bind([&]() { ANS_LOGD("ffrt enter!"); @@ -258,12 +236,14 @@ ErrCode AdvancedNotificationService::ExcuteCancelAll( std::string bundleName; GetDistributedInfo(key, deviceId, bundleName); #endif - result = RemoveFromNotificationList(key, notification, true, reason); + result = RemoveFromNotificationList(key, notification, true, + NotificationConstant::APP_CANCEL_ALL_REASON_DELETE); if (result != ERR_OK) { continue; } if (notification != nullptr) { + int32_t reason = NotificationConstant::APP_CANCEL_ALL_REASON_DELETE; UpdateRecentNotification(notification, true, reason); notifications.emplace_back(notification); #ifdef DISTRIBUTED_NOTIFICATION_SUPPORTED @@ -273,14 +253,14 @@ ErrCode AdvancedNotificationService::ExcuteCancelAll( if (notifications.size() >= MAX_CANCELED_PARCELABLE_VECTOR_NUM) { std::vector> currNotificationList = notifications; NotificationSubscriberManager::GetInstance()->BatchNotifyCanceled( - currNotificationList, nullptr, reason); + currNotificationList, nullptr, NotificationConstant::APP_CANCEL_ALL_REASON_DELETE); notifications.clear(); } } if (!notifications.empty()) { NotificationSubscriberManager::GetInstance()->BatchNotifyCanceled( - notifications, nullptr, reason); + notifications, nullptr, NotificationConstant::APP_CANCEL_ALL_REASON_DELETE); } result = ERR_OK; })); @@ -292,26 +272,15 @@ ErrCode AdvancedNotificationService::CancelAsBundle( const sptr &bundleOption, int32_t notificationId, int32_t userId) { ANS_LOGD("%{public}s", __FUNCTION__); - int32_t reason = NotificationConstant::APP_CANCEL_AS_BUNELE_REASON_DELETE; bool isSubsystem = AccessTokenHelper::VerifyNativeToken(IPCSkeleton::GetCallingTokenID()); if (!isSubsystem && !AccessTokenHelper::IsSystemApp()) { - std::string message = "not systemApp"; - OHOS::Notification::HaMetaMessage haMetaMessage = HaMetaMessage(2, 1) - .ErrorCode(ERR_ANS_NON_SYSTEM_APP).NotificationId(notificationId); - ReportDeleteFailedEventPush(haMetaMessage, reason, message); - ANS_LOGE("%{public}s", message.c_str()); return ERR_ANS_NON_SYSTEM_APP; } int32_t callingUid = IPCSkeleton::GetCallingUid(); - if ((callingUid != NFC_UID && callingUid != PSS_UID && callingUid != PAC_UID) && - (!AccessTokenHelper::CheckPermission(OHOS_PERMISSION_NOTIFICATION_CONTROLLER) || + if ((callingUid != NFC_UID && callingUid != PSS_UID && callingUid != PAC_UID) + && (!AccessTokenHelper::CheckPermission(OHOS_PERMISSION_NOTIFICATION_CONTROLLER) || !AccessTokenHelper::CheckPermission(OHOS_PERMISSION_NOTIFICATION_AGENT_CONTROLLER))) { - std::string message = "no acl permission"; - OHOS::Notification::HaMetaMessage haMetaMessage = HaMetaMessage(2, 2) - .ErrorCode(ERR_ANS_PERMISSION_DENIED).NotificationId(notificationId); - ReportDeleteFailedEventPush(haMetaMessage, reason, message); - ANS_LOGE("%{public}s", message.c_str()); return ERR_ANS_PERMISSION_DENIED; } @@ -330,16 +299,11 @@ ErrCode AdvancedNotificationService::CancelAsBundle( uid = bundleOption->GetUid(); } if (uid < 0) { - std::string message = "uid error"; - OHOS::Notification::HaMetaMessage haMetaMessage = HaMetaMessage(2, 3) - .ErrorCode(ERR_ANS_INVALID_UID).NotificationId(notificationId); - ReportDeleteFailedEventPush(haMetaMessage, reason, message); - ANS_LOGE("%{public}s", message.c_str()); return ERR_ANS_INVALID_UID; } sptr bundle = new (std::nothrow) NotificationBundleOption( bundleOption->GetBundleName(), uid); - return CancelPreparedNotification(notificationId, "", bundle, reason); + return CancelPreparedNotification(notificationId, "", bundle); } ErrCode AdvancedNotificationService::CancelAsBundle( @@ -368,14 +332,9 @@ ErrCode AdvancedNotificationService::CancelAsBundleWithAgent( const sptr &bundleOption, const int32_t id) { ANS_LOGD("Called."); - int32_t reason = NotificationConstant::APP_CANCEL_AS_BUNELE_WITH_AGENT_REASON_DELETE; + bool isSubsystem = AccessTokenHelper::VerifyNativeToken(IPCSkeleton::GetCallingTokenID()); if (!isSubsystem && !AccessTokenHelper::IsSystemApp()) { - std::string message = "not systemApp"; - OHOS::Notification::HaMetaMessage haMetaMessage = HaMetaMessage(2, 4) - .ErrorCode(ERR_ANS_NON_SYSTEM_APP).NotificationId(id); - ReportDeleteFailedEventPush(haMetaMessage, reason, message); - ANS_LOGE("%{public}s", message.c_str()); return ERR_ANS_NON_SYSTEM_APP; } @@ -397,22 +356,13 @@ ErrCode AdvancedNotificationService::CancelAsBundleWithAgent( uid = bundleOption->GetUid(); } if (uid < 0) { - std::string message = "uid error"; - OHOS::Notification::HaMetaMessage haMetaMessage = HaMetaMessage(2, 5) - .ErrorCode(ERR_ANS_INVALID_UID).NotificationId(id); - ReportDeleteFailedEventPush(haMetaMessage, reason, message); - ANS_LOGE("%{public}s", message.c_str()); return ERR_ANS_INVALID_UID; } sptr bundle = new (std::nothrow) NotificationBundleOption( bundleOption->GetBundleName(), uid); - return CancelPreparedNotification(id, "", bundle, reason); + return CancelPreparedNotification(id, "", bundle); } - std::string message = "no agent setting"; - OHOS::Notification::HaMetaMessage haMetaMessage = HaMetaMessage(2, 6) - .ErrorCode(ERR_ANS_NO_AGENT_SETTING).NotificationId(id); - ReportDeleteFailedEventPush(haMetaMessage, reason, message); - ANS_LOGE("%{public}s", message.c_str()); + return ERR_ANS_NO_AGENT_SETTING; } @@ -449,39 +399,21 @@ ErrCode AdvancedNotificationService::SetNotificationBadgeNum(int32_t num) ErrCode AdvancedNotificationService::Delete(const std::string &key, int32_t removeReason) { ANS_LOGD("%{public}s", __FUNCTION__); + bool isSubsystem = AccessTokenHelper::VerifyNativeToken(IPCSkeleton::GetCallingTokenID()); if (!isSubsystem && !AccessTokenHelper::IsSystemApp()) { - std::string message = "not systemApp. key:" + key + "."; - OHOS::Notification::HaMetaMessage haMetaMessage = HaMetaMessage(4, 1) - .ErrorCode(ERR_ANS_NON_SYSTEM_APP); - ReportDeleteFailedEventPush(haMetaMessage, removeReason, message); - ANS_LOGE("%{public}s", message.c_str()); + ANS_LOGD("VerifyNativeToken and IsSystemApp is false."); return ERR_ANS_NON_SYSTEM_APP; } if (!AccessTokenHelper::CheckPermission(OHOS_PERMISSION_NOTIFICATION_CONTROLLER)) { - std::string message = "no acl permission. key:" + key + "."; - OHOS::Notification::HaMetaMessage haMetaMessage = HaMetaMessage(4, 2) - .ErrorCode(ERR_ANS_PERMISSION_DENIED); - ReportDeleteFailedEventPush(haMetaMessage, removeReason, message); - ANS_LOGE("%{public}s", message.c_str()); return ERR_ANS_PERMISSION_DENIED; } if (notificationSvrQueue_ == nullptr) { - std::string message = "Serial queue is invalidated. key:" + key + "."; - OHOS::Notification::HaMetaMessage haMetaMessage = HaMetaMessage(4, 3) - .ErrorCode(ERR_ANS_INVALID_PARAM); - ReportDeleteFailedEventPush(haMetaMessage, removeReason, message); - ANS_LOGE("%{public}s", message.c_str()); + ANS_LOGE("Serial queue is invalidated."); return ERR_ANS_INVALID_PARAM; } - - return ExcuteDelete(key, removeReason); -} - -ErrCode AdvancedNotificationService::ExcuteDelete(const std::string &key, const int32_t removeReason) -{ ErrCode result = ERR_OK; ffrt::task_handle handler = notificationSvrQueue_->submit_h(std::bind([&]() { ANS_LOGD("ffrt enter!"); @@ -571,32 +503,18 @@ ErrCode AdvancedNotificationService::DeleteAll() { ANS_LOGD("%{public}s", __FUNCTION__); - const int32_t reason = NotificationConstant::CANCEL_ALL_REASON_DELETE; bool isSubsystem = AccessTokenHelper::VerifyNativeToken(IPCSkeleton::GetCallingTokenID()); if (!isSubsystem && !AccessTokenHelper::IsSystemApp()) { - std::string message = "not system app."; - OHOS::Notification::HaMetaMessage haMetaMessage = HaMetaMessage(6, 8) - .ErrorCode(ERR_ANS_NON_SYSTEM_APP); - ReportDeleteFailedEventPush(haMetaMessage, reason, message); - ANS_LOGE("%{public}s", message.c_str()); return ERR_ANS_NON_SYSTEM_APP; } if (!AccessTokenHelper::CheckPermission(OHOS_PERMISSION_NOTIFICATION_CONTROLLER)) { - std::string message = "no acl permission."; - OHOS::Notification::HaMetaMessage haMetaMessage = HaMetaMessage(6, 9) - .ErrorCode(ERR_ANS_PERMISSION_DENIED); - ReportDeleteFailedEventPush(haMetaMessage, reason, message); - ANS_LOGE("%{public}s", message.c_str()); + ANS_LOGD("AccessTokenHelper::CheckPermission is false."); return ERR_ANS_PERMISSION_DENIED; } if (notificationSvrQueue_ == nullptr) { - std::string message = "Serial queue is invalidity."; - OHOS::Notification::HaMetaMessage haMetaMessage = HaMetaMessage(6, 10) - .ErrorCode(ERR_ANS_INVALID_PARAM); - ReportDeleteFailedEventPush(haMetaMessage, reason, message); - ANS_LOGE("%{public}s", message.c_str()); + ANS_LOGE("Serial queue is invalidity."); return ERR_ANS_INVALID_PARAM; } ErrCode result = ERR_OK; @@ -622,6 +540,7 @@ ErrCode AdvancedNotificationService::DeleteAll() } if (notification->GetUserId() == activeUserId) { + int32_t reason = NotificationConstant::CANCEL_ALL_REASON_DELETE; UpdateRecentNotification(notification, true, reason); notifications.emplace_back(notification); #ifdef DISTRIBUTED_NOTIFICATION_SUPPORTED @@ -630,12 +549,12 @@ ErrCode AdvancedNotificationService::DeleteAll() } if (notifications.size() >= MAX_CANCELED_PARCELABLE_VECTOR_NUM) { ANS_LOGD("Notifications size greater than or equal to MAX_CANCELED_PARCELABLE_VECTOR_NUM."); - SendNotificationsOnCanceled(notifications, nullptr, reason); + SendNotificationsOnCanceled(notifications, nullptr, NotificationConstant::CANCEL_ALL_REASON_DELETE); } } if (!notifications.empty()) { NotificationSubscriberManager::GetInstance()->BatchNotifyCanceled( - notifications, nullptr, reason); + notifications, nullptr, NotificationConstant::CANCEL_REASON_DELETE); } result = ERR_OK; @@ -775,12 +694,8 @@ ErrCode AdvancedNotificationService::RequestEnableNotification(const std::string } // To get the permission bool allowedNotify = false; - HaMetaMessage message = HaMetaMessage(EventSceneId::SCENE_2, EventBranchId::BRANCH_1) - .BundleName(bundleOption->GetBundleName()); result = IsAllowedNotifySelf(bundleOption, allowedNotify); if (result != ERR_OK) { - message.Message("Allow notify self failed: " + std::to_string(result)); - NotificationAnalyticsUtil::ReportModifyEvent(message); return ERROR_INTERNAL_ERROR; } ANS_LOGI("allowedNotify = %{public}d", allowedNotify); @@ -791,8 +706,6 @@ ErrCode AdvancedNotificationService::RequestEnableNotification(const std::string bool hasPopped = false; result = GetHasPoppedDialog(bundleOption, hasPopped); if (result != ERR_OK) { - message.Message("Has popped dialog: " + std::to_string(result)); - NotificationAnalyticsUtil::ReportModifyEvent(message); return ERROR_INTERNAL_ERROR; } if (hasPopped) { @@ -807,8 +720,6 @@ ErrCode AdvancedNotificationService::RequestEnableNotification(const std::string if (result == ERR_OK) { result = ERR_ANS_DIALOG_POP_SUCCEEDED; } - message.Message("Request dialog: " + std::to_string(result)); - NotificationAnalyticsUtil::ReportModifyEvent(message); return result; } @@ -958,7 +869,6 @@ ErrCode AdvancedNotificationService::CanPopEnableNotificationDialog( ANS_LOGD("%{public}s", __FUNCTION__); canPop = false; ErrCode result = ERR_OK; - HaMetaMessage message = HaMetaMessage(EventSceneId::SCENE_2, EventBranchId::BRANCH_2); sptr bundleOption = GenerateBundleOption(); if (bundleOption == nullptr) { ANS_LOGE("bundleOption == nullptr"); @@ -966,15 +876,11 @@ ErrCode AdvancedNotificationService::CanPopEnableNotificationDialog( } // To get the permission bool allowedNotify = false; - message.BundleName(bundleOption->GetBundleName()); result = IsAllowedNotifySelf(bundleOption, allowedNotify); if (result != ERR_OK) { - message.Message("Allow notify self failed: " + std::to_string(result)); - NotificationAnalyticsUtil::ReportModifyEvent(message); return ERROR_INTERNAL_ERROR; } - ANS_LOGI("allowedNotify = %{public}d, bundle = %{public}s", allowedNotify, - bundleOption->GetBundleName().c_str()); + ANS_LOGI("allowedNotify = %{public}d", allowedNotify); if (allowedNotify) { return ERR_OK; } @@ -982,8 +888,6 @@ ErrCode AdvancedNotificationService::CanPopEnableNotificationDialog( bool hasPopped = false; result = GetHasPoppedDialog(bundleOption, hasPopped); if (result != ERR_OK) { - message.Message("Has popped dialog: " + std::to_string(result)); - NotificationAnalyticsUtil::ReportModifyEvent(message); return ERROR_INTERNAL_ERROR; } if (hasPopped) { @@ -1000,8 +904,8 @@ ErrCode AdvancedNotificationService::CanPopEnableNotificationDialog( canPop = true; bundleName = bundleOption->GetBundleName(); - ANS_LOGI("CanPopEnableNotificationDialog end"); return ERR_OK; + ANS_LOGI("CanPopEnableNotificationDialog end"); } ErrCode AdvancedNotificationService::IsAllowedNotifySelf(const sptr &bundleOption, @@ -1073,7 +977,7 @@ ErrCode AdvancedNotificationService::IsSpecialBundleAllowedNotify( } int32_t callingUid = IPCSkeleton::GetCallingUid(); - if ((callingUid != ANS_UID && callingUid != PAC_UID) + if ((callingUid != ANS_UID && callingUid != BROKER_UID && callingUid != PAC_UID) && !AccessTokenHelper::CheckPermission(OHOS_PERMISSION_NOTIFICATION_CONTROLLER)) { return ERR_ANS_PERMISSION_DENIED; } @@ -1341,20 +1245,12 @@ ErrCode AdvancedNotificationService::RemoveNotification(const sptrwait(handler); - if (result != ERR_OK) { - std::string message = "remove notificaiton error"; - OHOS::Notification::HaMetaMessage haMetaMessage = HaMetaMessage(4, 7) - .ErrorCode(result).NotificationId(notificationId); - ReportDeleteFailedEventPush(haMetaMessage, removeReason, message); - ANS_LOGE("%{public}s", message.c_str()); - } + SendRemoveHiSysEvent(notificationId, label, bundleOption, result); return result; } @@ -1440,7 +1326,7 @@ ErrCode AdvancedNotificationService::RemoveAllNotificationsForDisable( ErrCode AdvancedNotificationService::RemoveAllNotifications(const sptr &bundleOption) { - return RemoveAllNotificationsInner(bundleOption, NotificationConstant::APP_REMOVE_ALL_REASON_DELETE); + return RemoveAllNotificationsInner(bundleOption, NotificationConstant::CANCEL_REASON_DELETE); } ErrCode AdvancedNotificationService::RemoveAllNotificationsInner(const sptr &bundleOption, @@ -1451,40 +1337,22 @@ ErrCode AdvancedNotificationService::RemoveAllNotificationsInner(const sptr bundle = GenerateValidBundleOption(bundleOption); if (bundle == nullptr) { - std::string message = "budle is nullptr."; - OHOS::Notification::HaMetaMessage haMetaMessage = HaMetaMessage(6, 3) - .ErrorCode(ERR_ANS_INVALID_BUNDLE); - ReportDeleteFailedEventPush(haMetaMessage, reason, message); - ANS_LOGE("%{public}s", message.c_str()); return ERR_ANS_INVALID_BUNDLE; } if (notificationSvrQueue_ == nullptr) { - std::string message = "Serial queue is nullptr."; - OHOS::Notification::HaMetaMessage haMetaMessage = HaMetaMessage(6, 4) - .ErrorCode(ERR_ANS_INVALID_BUNDLE); - ReportDeleteFailedEventPush(haMetaMessage, reason, message); - ANS_LOGE("%{public}s", message.c_str()); + ANS_LOGE("Serial queue is nullptr."); return ERR_ANS_INVALID_PARAM; } ffrt::task_handle handler = notificationSvrQueue_->submit_h(std::bind([&]() { @@ -1607,7 +1475,7 @@ ErrCode AdvancedNotificationService::RemoveNotifications( } ErrCode AdvancedNotificationService::RemoveNotificationBySlot(const sptr &bundleOption, - const sptr &slot, const int reason) + const sptr &slot) { HITRACE_METER_NAME(HITRACE_TAG_NOTIFICATION, __PRETTY_FUNCTION__); ANS_LOGD("%{public}s", __FUNCTION__); @@ -1728,44 +1596,20 @@ ErrCode AdvancedNotificationService::CancelGroup(const std::string &groupName, i { ANS_LOGD("%{public}s", __FUNCTION__); - int32_t reason = NotificationConstant::APP_CANCEL_GROPU_REASON_DELETE; if (groupName.empty()) { - std::string message = "groupName empty."; - OHOS::Notification::HaMetaMessage haMetaMessage = HaMetaMessage(3, 1) - .ErrorCode(ERR_ANS_INVALID_PARAM); - ReportDeleteFailedEventPush(haMetaMessage, reason, message); - ANS_LOGE("%{public}s", message.c_str()); return ERR_ANS_INVALID_PARAM; } sptr bundleOption = GenerateBundleOption(); if (bundleOption == nullptr) { - std::string message = "bundle is nullptr."; - OHOS::Notification::HaMetaMessage haMetaMessage = HaMetaMessage(3, 2) - .ErrorCode(ERR_ANS_INVALID_BUNDLE); - ReportDeleteFailedEventPush(haMetaMessage, reason, message); - ANS_LOGE("%{public}s", message.c_str()); return ERR_ANS_INVALID_BUNDLE; } bundleOption->SetInstanceKey(instanceKey); if (notificationSvrQueue_ == nullptr) { - std::string message = "Serial queue is invalid."; - OHOS::Notification::HaMetaMessage haMetaMessage = HaMetaMessage(3, 3) - .ErrorCode(ERR_ANS_INVALID_PARAM); - ReportDeleteFailedEventPush(haMetaMessage, reason, message); - ANS_LOGE("%{public}s", message.c_str()); + ANS_LOGE("Serial queue is invalid."); return ERR_ANS_INVALID_PARAM; } - - ExcuteCancelGroupCancel(bundleOption, groupName, reason); - return ERR_OK; -} - -void AdvancedNotificationService::ExcuteCancelGroupCancel( - const sptr& bundleOption, - const std::string &groupName, const int32_t reason) -{ ffrt::task_handle handler = notificationSvrQueue_->submit_h(std::bind([&]() { ANS_LOGD("ffrt enter!"); std::vector> removeList; @@ -1784,6 +1628,7 @@ void AdvancedNotificationService::ExcuteCancelGroupCancel( for (auto record : removeList) { notificationList_.remove(record); if (record->notification != nullptr) { + int32_t reason = NotificationConstant::APP_CANCEL_REASON_DELETE; UpdateRecentNotification(record->notification, true, reason); notifications.emplace_back(record->notification); #ifdef DISTRIBUTED_NOTIFICATION_SUPPORTED @@ -1793,68 +1638,46 @@ void AdvancedNotificationService::ExcuteCancelGroupCancel( if (notifications.size() >= MAX_CANCELED_PARCELABLE_VECTOR_NUM) { std::vector> currNotificationList = notifications; NotificationSubscriberManager::GetInstance()->BatchNotifyCanceled( - currNotificationList, nullptr, reason); + currNotificationList, nullptr, NotificationConstant::APP_CANCEL_REASON_DELETE); notifications.clear(); } } if (!notifications.empty()) { NotificationSubscriberManager::GetInstance()->BatchNotifyCanceled( - notifications, nullptr, reason); + notifications, nullptr, NotificationConstant::APP_CANCEL_REASON_DELETE); } })); notificationSvrQueue_->wait(handler); + + return ERR_OK; } ErrCode AdvancedNotificationService::RemoveGroupByBundle( const sptr &bundleOption, const std::string &groupName) { ANS_LOGD("%{public}s", __FUNCTION__); - const int32_t reason = NotificationConstant::APP_REMOVE_GROUP_REASON_DELETE; + bool isSubsystem = AccessTokenHelper::VerifyNativeToken(IPCSkeleton::GetCallingTokenID()); if (!isSubsystem && !AccessTokenHelper::IsSystemApp()) { - std::string message = "not systemApp."; - OHOS::Notification::HaMetaMessage haMetaMessage = HaMetaMessage(5, 1) - .ErrorCode(ERR_ANS_NON_SYSTEM_APP); - ReportDeleteFailedEventPush(haMetaMessage, reason, message); - ANS_LOGE("%{public}s", message.c_str()); return ERR_ANS_NON_SYSTEM_APP; } if (!AccessTokenHelper::CheckPermission(OHOS_PERMISSION_NOTIFICATION_CONTROLLER)) { - std::string message = "no acl permission"; - OHOS::Notification::HaMetaMessage haMetaMessage = HaMetaMessage(5, 2) - .ErrorCode(ERR_ANS_PERMISSION_DENIED); - ReportDeleteFailedEventPush(haMetaMessage, reason, message); - ANS_LOGE("%{public}s", message.c_str()); return ERR_ANS_PERMISSION_DENIED; } if (bundleOption == nullptr || groupName.empty()) { - std::string message = "groupName empty"; - OHOS::Notification::HaMetaMessage haMetaMessage = HaMetaMessage(5, 3) - .ErrorCode(ERR_ANS_INVALID_PARAM); - ReportDeleteFailedEventPush(haMetaMessage, reason, message); - ANS_LOGE("%{public}s", message.c_str()); return ERR_ANS_INVALID_PARAM; } sptr bundle = GenerateValidBundleOption(bundleOption); if (bundle == nullptr) { - std::string message = "bundle is nullptr"; - OHOS::Notification::HaMetaMessage haMetaMessage = HaMetaMessage(5, 4) - .ErrorCode(ERR_ANS_INVALID_PARAM); - ReportDeleteFailedEventPush(haMetaMessage, reason, message); - ANS_LOGE("%{public}s", message.c_str()); return ERR_ANS_INVALID_BUNDLE; } if (notificationSvrQueue_ == nullptr) { - std::string message = "Serial queue is invalid."; - OHOS::Notification::HaMetaMessage haMetaMessage = HaMetaMessage(5, 5) - .ErrorCode(ERR_ANS_INVALID_PARAM); - ReportDeleteFailedEventPush(haMetaMessage, reason, message); - ANS_LOGE("%{public}s", message.c_str()); + ANS_LOGE("Serial queue is invalid."); return ERR_ANS_INVALID_PARAM; } ffrt::task_handle handler = notificationSvrQueue_->submit_h(std::bind([&]() { @@ -2061,10 +1884,10 @@ ErrCode AdvancedNotificationService::SetEnabledForBundleSlot(const sptrGetEnable()) { - RemoveNotificationBySlot(bundle, slot, NotificationConstant::DISABLE_SLOT_REASON_DELETE); + RemoveNotificationBySlot(bundle, slot); } else { if (!slot->GetForceControl() && !allowed) { - RemoveNotificationBySlot(bundle, slot, NotificationConstant::DISABLE_NOTIFICATION_REASON_DELETE); + RemoveNotificationBySlot(bundle, slot); } } @@ -2151,11 +1974,14 @@ ErrCode AdvancedNotificationService::PublishNotificationBySa(const sptrGetCreatorUid(); if (request->GetOwnerUid() != DEFAULT_UID) { std::shared_ptr agentBundle = std::make_shared("", uid); + if (agentBundle == nullptr) { + ANS_LOGE("Failed to create agentBundle instance"); + return ERR_ANS_INVALID_BUNDLE; + } request->SetAgentBundle(agentBundle); } @@ -2163,8 +1989,7 @@ ErrCode AdvancedNotificationService::PublishNotificationBySa(const sptrGetOwnerUid(); } if (uid <= 0) { - message.ErrorCode(ERR_ANS_INVALID_UID).Message("createUid failed" + std::to_string(uid), true); - NotificationAnalyticsUtil::ReportPublishFailedEvent(request, message); + ANS_LOGE("CreatorUid[%{public}d] error", uid); return ERR_ANS_INVALID_UID; } std::string bundle = ""; @@ -2180,11 +2005,11 @@ ErrCode AdvancedNotificationService::PublishNotificationBySa(const sptrGetSound().empty()) { request->SetSound(""); } + std::shared_ptr record = std::make_shared(); record->request = request; if (request->IsAgentNotification()) { @@ -2208,12 +2033,13 @@ ErrCode AdvancedNotificationService::PublishNotificationBySa(const sptrrequest, bundleOption); result = FlowControl(record); if (result != ERR_OK) { return result; } - SetRequestBySlotType(record->request, bundleOption); + #ifdef ENABLE_ANS_EXT_WRAPPER EXTENTION_WRAPPER->GetUnifiedGroupInfo(request); #endif @@ -2254,7 +2080,7 @@ ErrCode AdvancedNotificationService::PublishNotificationBySa(const sptrrequest->GetAutoDeletedTime() > GetCurrentTime()) && !record->request->IsCommonLiveView()) { StartAutoDelete(record, - record->request->GetAutoDeletedTime(), NotificationConstant::TRIGGER_AUTO_DELETE_REASON_DELETE); + record->request->GetAutoDeletedTime(), NotificationConstant::APP_CANCEL_REASON_DELETE); } return ERR_OK; } @@ -2280,35 +2106,27 @@ ErrCode AdvancedNotificationService::SetBadgeNumber(int32_t badgeNumber, int32_t NotificationSubscriberManager::GetInstance()->SetBadgeNumber(badgeData); }); notificationSvrQueue_->wait(handler); - HaMetaMessage message = HaMetaMessage(EventSceneId::SCENE_3, EventBranchId::BRANCH_1) - .Message("Set badge number " + bundleName + " " + std::to_string(badgeNumber) - + " " + std::to_string(instanceKey)); - NotificationAnalyticsUtil::ReportModifyEvent(message); return ERR_OK; } ErrCode AdvancedNotificationService::SetBadgeNumberByBundle( const sptr &bundleOption, int32_t badgeNumber) { - HaMetaMessage message = HaMetaMessage(EventSceneId::SCENE_7, EventBranchId::BRANCH_1); if (notificationSvrQueue_ == nullptr) { - message.Message("Serial queue is invalid.", true); - NotificationAnalyticsUtil::ReportModifyEvent(message); + ANS_LOGE("Serial queue is invalid."); return ERR_ANS_INVALID_PARAM; } bool isSubsystem = AccessTokenHelper::VerifyNativeToken(IPCSkeleton::GetCallingTokenID()); if (!isSubsystem && !AccessTokenHelper::IsSystemApp()) { - message.Message("Client is not a system app or subsystem.", true); - NotificationAnalyticsUtil::ReportModifyEvent(message); + ANS_LOGE("Client is not a system app or subsystem."); return ERR_ANS_NON_SYSTEM_APP; } sptr bundle = bundleOption; ErrCode result = CheckBundleOptionValid(bundle); if (result != ERR_OK) { - message.Message("Input bundle option is not correct: " + std::to_string(result), true); - NotificationAnalyticsUtil::ReportModifyEvent(message); + ANS_LOGE("Input parameter bundle option is not correct."); return result; } @@ -2321,8 +2139,7 @@ ErrCode AdvancedNotificationService::SetBadgeNumberByBundle( bool isAgent = false; isAgent = IsAgentRelationship(bundleName, bundle->GetBundleName()); if (!isAgent) { - message.Message("the caller has no agent relationship with the specified bundle.", true); - NotificationAnalyticsUtil::ReportModifyEvent(message); + ANS_LOGE("The caller has no agent relationship with the specified bundle."); return ERR_ANS_NO_AGENT_SETTING; } } @@ -2338,9 +2155,6 @@ ErrCode AdvancedNotificationService::SetBadgeNumberByBundle( NotificationSubscriberManager::GetInstance()->SetBadgeNumber(badgeData); }); notificationSvrQueue_->wait(handler); - message.Message("Set badgenumber: " + bundle->GetBundleName() + ":" + - std::to_string(badgeNumber) + " " + std::to_string(result)); - NotificationAnalyticsUtil::ReportModifyEvent(message); return result; } @@ -2423,7 +2237,7 @@ ErrCode AdvancedNotificationService::IsDistributedEnabledByBundle(const sptr bundle = GenerateValidBundleOption(bundleOption); if (bundle == nullptr) { return ERR_ANS_INVALID_BUNDLE; diff --git a/services/ans/src/advanced_notification_service.cpp b/services/ans/src/advanced_notification_service.cpp index 91044e9d4..54dd557c3 100644 --- a/services/ans/src/advanced_notification_service.cpp +++ b/services/ans/src/advanced_notification_service.cpp @@ -73,7 +73,6 @@ #include "advanced_notification_inline.cpp" #include "advanced_datashare_helper_ext.h" -#include "notification_analytics_util.h" namespace OHOS { namespace Notification { @@ -86,12 +85,10 @@ constexpr int32_t WINDOW_DEFAULT_WIDTH = 720; constexpr int32_t WINDOW_DEFAULT_HEIGHT = 1280; constexpr int32_t UI_HALF = 2; constexpr int32_t MAX_LIVEVIEW_HINT_COUNT = 1; -constexpr int32_t MAX_SOUND_ITEM_LENGTH = 2048; constexpr int32_t BUNDLE_OPTION_UID_DEFAULT_VALUE = 0; +constexpr int32_t MAX_SOUND_ITEM_LENGTH = 2048; constexpr int32_t RSS_UID = 3051; -const std::string MMS_BUNDLE_NAME = "com.ohos.mms"; -const std::string CONTACTS_BUNDLE_NAME = "com.ohos.contacts"; const std::string DO_NOT_DISTURB_MODE = "1"; constexpr const char *KEY_UNIFIED_GROUP_ENABLE = "unified_group_enable"; } // namespace @@ -207,7 +204,7 @@ ErrCode AdvancedNotificationService::PrepareNotificationRequest(const sptrSetOwnerBundleName(bundle); } - + int32_t uid = IPCSkeleton::GetCallingUid(); int32_t pid = IPCSkeleton::GetCallingPid(); request->SetCreatorUid(uid); @@ -304,7 +301,7 @@ AdvancedNotificationService::AdvancedNotificationService() std::function recoverFunc = std::bind( &AdvancedNotificationService::RecoverLiveViewFromDb, this, SUBSCRIBE_USER_INIT); notificationSvrQueue_->submit(recoverFunc); - + ISystemEvent iSystemEvent = { std::bind(&AdvancedNotificationService::OnBundleRemoved, this, std::placeholders::_1), #ifdef DISTRIBUTED_NOTIFICATION_SUPPORTED @@ -365,25 +362,16 @@ ErrCode AdvancedNotificationService::AssignToNotificationList(const std::shared_ return result; } -ErrCode AdvancedNotificationService::CancelPreparedNotification(int32_t notificationId, - const std::string &label, const sptr &bundleOption, int32_t reason) +ErrCode AdvancedNotificationService::CancelPreparedNotification( + int32_t notificationId, const std::string &label, const sptr &bundleOption) { HITRACE_METER_NAME(HITRACE_TAG_NOTIFICATION, __PRETTY_FUNCTION__); if (bundleOption == nullptr) { - std::string message = "bundleOption is null"; - OHOS::Notification::HaMetaMessage haMetaMessage = HaMetaMessage(1, 2) - .ErrorCode(ERR_ANS_INVALID_BUNDLE).NotificationId(notificationId); - ReportDeleteFailedEventPush(haMetaMessage, reason, message); - ANS_LOGE("%{public}s", message.c_str()); return ERR_ANS_INVALID_BUNDLE; } if (notificationSvrQueue_ == nullptr) { - std::string message = "notificationSvrQueue is null"; - OHOS::Notification::HaMetaMessage haMetaMessage = HaMetaMessage(1, 3) - .ErrorCode(ERR_ANS_INVALID_PARAM).NotificationId(notificationId); - ReportDeleteFailedEventPush(haMetaMessage, reason, message); - ANS_LOGE("%{public}s", message.c_str()); + ANS_LOGE("Serial queue is invalidity."); return ERR_ANS_INVALID_PARAM; } ErrCode result = ERR_OK; @@ -396,6 +384,7 @@ ErrCode AdvancedNotificationService::CancelPreparedNotification(int32_t notifica } if (notification != nullptr) { + int32_t reason = NotificationConstant::APP_CANCEL_REASON_DELETE; UpdateRecentNotification(notification, true, reason); NotificationSubscriberManager::GetInstance()->NotifyCanceled(notification, nullptr, reason); #ifdef DISTRIBUTED_NOTIFICATION_SUPPORTED @@ -412,7 +401,6 @@ ErrCode AdvancedNotificationService::PrepareNotificationInfo( const sptr &request, sptr &bundleOption) { HITRACE_METER_NAME(HITRACE_TAG_NOTIFICATION, __PRETTY_FUNCTION__); - HaMetaMessage message = HaMetaMessage(EventSceneId::SCENE_4, EventBranchId::BRANCH_3); if (request == nullptr) { ANS_LOGE("request is invalid."); return ERR_ANS_INVALID_PARAM; @@ -424,8 +412,6 @@ ErrCode AdvancedNotificationService::PrepareNotificationInfo( } ErrCode result = PrepareNotificationRequest(request); if (result != ERR_OK) { - message.ErrorCode(result); - NotificationAnalyticsUtil::ReportPublishFailedEvent(request, message); return result; } @@ -449,8 +435,6 @@ ErrCode AdvancedNotificationService::PrepareNotificationInfo( } if (bundleOption == nullptr) { - message.ErrorCode(ERR_ANS_INVALID_BUNDLE); - NotificationAnalyticsUtil::ReportPublishFailedEvent(request, message); return ERR_ANS_INVALID_BUNDLE; } ANS_LOGI( @@ -460,17 +444,13 @@ ErrCode AdvancedNotificationService::PrepareNotificationInfo( return ERR_OK; } -ErrCode AdvancedNotificationService::StartFinishTimer(const std::shared_ptr &record, - int64_t expiredTimePoint, const int32_t reason) +ErrCode AdvancedNotificationService::StartFinishTimer( + const std::shared_ptr &record, int64_t expiredTimePoint) { uint64_t timerId = StartAutoDelete(record, - expiredTimePoint, reason); + expiredTimePoint, NotificationConstant::APP_CANCEL_REASON_OTHER); if (timerId == NotificationConstant::INVALID_TIMER_ID) { - std::string message = "Start finish auto delete timer failed."; - OHOS::Notification::HaMetaMessage haMetaMessage = HaMetaMessage(7, 1) - .ErrorCode(ERR_ANS_TASK_ERR); - ReportDeleteFailedEventPush(haMetaMessage, reason, message); - ANS_LOGE("%{public}s", message.c_str()); + ANS_LOGE("Start finish auto delete timer failed."); return ERR_ANS_TASK_ERR; } record->notification->SetFinishTimer(timerId); @@ -480,8 +460,7 @@ ErrCode AdvancedNotificationService::StartFinishTimer(const std::shared_ptr &record) { int64_t maxExpiredTime = GetCurrentTime() + NotificationConstant::MAX_FINISH_TIME; - auto result = StartFinishTimer(record, maxExpiredTime, - NotificationConstant::TRIGGER_EIGHT_HOUR_REASON_DELETE); + auto result = StartFinishTimer(record, maxExpiredTime); if (result != ERR_OK) { return result; } @@ -497,17 +476,12 @@ void AdvancedNotificationService::CancelFinishTimer(const std::shared_ptr &record, int64_t expireTimePoint, - const int32_t reason) + const std::shared_ptr &record, int64_t expireTimePoint) { uint64_t timerId = StartAutoDelete(record, - expireTimePoint, reason); + expireTimePoint, NotificationConstant::APP_CANCEL_REASON_OTHER); if (timerId == NotificationConstant::INVALID_TIMER_ID) { - std::string message = "Start update auto delete timer failed."; - OHOS::Notification::HaMetaMessage haMetaMessage = HaMetaMessage(7, 2) - .ErrorCode(ERR_ANS_TASK_ERR); - ReportDeleteFailedEventPush(haMetaMessage, reason, message); - ANS_LOGE("%{public}s", message.c_str()); + ANS_LOGE("Start update auto delete timer failed."); return ERR_ANS_TASK_ERR; } record->notification->SetUpdateTimer(timerId); @@ -517,8 +491,7 @@ ErrCode AdvancedNotificationService::StartUpdateTimer( ErrCode AdvancedNotificationService::SetUpdateTimer(const std::shared_ptr &record) { int64_t maxExpiredTime = GetCurrentTime() + NotificationConstant::MAX_UPDATE_TIME; - ErrCode result = StartUpdateTimer(record, maxExpiredTime, - NotificationConstant::TRIGGER_FOUR_HOUR_REASON_DELETE); + ErrCode result = StartUpdateTimer(record, maxExpiredTime); if (result != ERR_OK) { return result; } @@ -537,8 +510,7 @@ void AdvancedNotificationService::StartArchiveTimer(const std::shared_ptrrequest->GetAutoDeletedTime(); if (deleteTime == NotificationConstant::NO_DELAY_DELETE_TIME) { - TriggerAutoDelete(record->notification->GetKey(), - NotificationConstant::TRIGGER_START_ARCHIVE_REASON_DELETE); + TriggerAutoDelete(record->notification->GetKey(), NotificationConstant::APP_CANCEL_REASON_DELETE); return; } if (deleteTime <= NotificationConstant::INVALID_AUTO_DELETE_TIME) { @@ -547,7 +519,7 @@ void AdvancedNotificationService::StartArchiveTimer(const std::shared_ptrLocalControl(request); if (ctrlResult != ERR_OK) { - message.ErrorCode(ctrlResult); - NotificationAnalyticsUtil::ReportPublishFailedEvent(request, message); return ctrlResult; } #endif @@ -623,8 +592,6 @@ ErrCode AdvancedNotificationService::PublishPreparedNotification(const sptrrequest->GetAutoDeletedTime() > GetCurrentTime()) && !record->request->IsCommonLiveView()) { StartAutoDelete(record, - record->request->GetAutoDeletedTime(), NotificationConstant::TRIGGER_AUTO_DELETE_REASON_DELETE); + record->request->GetAutoDeletedTime(), NotificationConstant::APP_CANCEL_REASON_DELETE); } return result; } @@ -726,14 +693,10 @@ void AdvancedNotificationService::CheckDoNotDisturbProfile(const std::shared_ptr } std::string bundleName = record->bundleOption->GetBundleName(); ANS_LOGD("The bundle name is %{public}s", bundleName.c_str()); - if (bundleName == MMS_BUNDLE_NAME || bundleName == CONTACTS_BUNDLE_NAME) { - ANS_LOGI("Currently in do not disturb mode, the bundle name is mms or contacts, keep reminder method."); - return; - } sptr profile = new (std::nothrow) NotificationDoNotDisturbProfile(); if (NotificationPreferences::GetInstance()->GetDoNotDisturbProfile(atoi(profileId.c_str()), userId, profile) != ERR_OK) { - ANS_LOGE("profile failed. pid: %{public}s, userid: %{public}d", profileId.c_str(), userId); + ANS_LOGE("Get do not disturb profile failed."); return; } if (profile == nullptr) { @@ -832,7 +795,6 @@ bool AdvancedNotificationService::IsNotificationExists(const std::string &key) ErrCode AdvancedNotificationService::Filter(const std::shared_ptr &record, bool isRecover) { ErrCode result = ERR_OK; - if (!isRecover) { auto oldRecord = GetFromNotificationList(record->notification->GetKey()); result = record->request->CheckNotificationRequest((oldRecord == nullptr) ? nullptr : oldRecord->request); @@ -1160,12 +1122,6 @@ ErrCode AdvancedNotificationService::RemoveFromNotificationList(const sptrnotification->IsRemoveAllowed()) { - std::string message = "notification unremove."; - OHOS::Notification::HaMetaMessage haMetaMessage = HaMetaMessage(1, 4) - .ErrorCode(ERR_ANS_NOTIFICATION_IS_UNALLOWED_REMOVEALLOWED); - ReportDeleteFailedEventPushByNotification(record->notification, haMetaMessage, - NotificationConstant::DEFAULT_REASON_DELETE, message); - ANS_LOGE("%{public}s", message.c_str()); return ERR_ANS_NOTIFICATION_IS_UNALLOWED_REMOVEALLOWED; } notification = record->notification; @@ -1194,11 +1150,6 @@ ErrCode AdvancedNotificationService::RemoveFromNotificationList(const sptrnotification->IsRemoveAllowed()) { - std::string message = "notification unremove."; - OHOS::Notification::HaMetaMessage haMetaMessage = HaMetaMessage(1, 7) - .ErrorCode(ERR_ANS_NOTIFICATION_IS_UNALLOWED_REMOVEALLOWED); - ReportDeleteFailedEventPushByNotification(record->notification, haMetaMessage, - removeReason, message); - ANS_LOGE("%{public}s", message.c_str()); return ERR_ANS_NOTIFICATION_IS_UNALLOWED_REMOVEALLOWED; } notification = record->notification; @@ -1232,11 +1177,7 @@ ErrCode AdvancedNotificationService::RemoveFromNotificationList( return ERR_OK; } RemoveFromDelayedNotificationList(key); - std::string message = "notification not exist. key:" + key + "."; - OHOS::Notification::HaMetaMessage haMetaMessage = HaMetaMessage(1, 8) - .ErrorCode(ERR_ANS_INVALID_BUNDLE); - ReportDeleteFailedEventPush(haMetaMessage, removeReason, message); - ANS_LOGE("%{public}s", message.c_str()); + return ERR_ANS_NOTIFICATION_NOT_EXISTS; } @@ -1441,13 +1382,10 @@ static bool SortNotificationsByLevelAndTime( ErrCode AdvancedNotificationService::FlowControl(const std::shared_ptr &record) { - HaMetaMessage message = HaMetaMessage(EventSceneId::SCENE_4, EventBranchId::BRANCH_2); std::chrono::system_clock::time_point now = std::chrono::system_clock::now(); std::lock_guard lock(flowControlMutex_); RemoveExpired(flowControlTimestampList_, now); if (flowControlTimestampList_.size() >= MAX_ACTIVE_NUM_PERSECOND + MAX_UPDATE_NUM_PERSECOND) { - message.ErrorCode(ERR_ANS_OVER_MAX_ACTIVE_PERSECOND); - NotificationAnalyticsUtil::ReportPublishFailedEvent(record->request, message); return ERR_ANS_OVER_MAX_ACTIVE_PERSECOND; } flowControlTimestampList_.push_back(now); @@ -2098,13 +2036,13 @@ ErrCode AdvancedNotificationService::CheckSoundPermission(const sptrGetSound().length(); if (length > MAX_SOUND_ITEM_LENGTH) { ANS_LOGE("Check sound length failed: %{public}d", length); return ERR_ANS_INVALID_PARAM; } - + // Update sound permission info cache ANS_LOGD("Check sound permission: %{public}d, %{public}s, %{public}d", length, bundleName.c_str(), soundPermissionInfo_->needUpdateCache_.load()); @@ -2118,7 +2056,7 @@ ErrCode AdvancedNotificationService::CheckSoundPermission(const sptrneedUpdateCache_ = false; } } - + if (!soundPermissionInfo_->allPackage_ && soundPermissionInfo_->bundleName_.count(bundleName) == 0) { request->SetSound(""); } diff --git a/services/ans/src/advanced_notification_utils.cpp b/services/ans/src/advanced_notification_utils.cpp index 21ec30969..2a28270e9 100644 --- a/services/ans/src/advanced_notification_utils.cpp +++ b/services/ans/src/advanced_notification_utils.cpp @@ -46,7 +46,6 @@ #endif #include "advanced_notification_inline.cpp" -#include "notification_analytics_util.h" #define CHECK_BUNDLE_OPTION_IS_INVALID(option) \ if (option == nullptr || option->GetBundleName().empty()) { \ @@ -107,14 +106,11 @@ std::shared_ptr AdvancedNotificationService::GetNotificationSvrQueu sptr AdvancedNotificationService::GenerateBundleOption() { - HaMetaMessage message = HaMetaMessage(EventSceneId::SCENE_4, EventBranchId::BRANCH_1); sptr bundleOption = nullptr; std::string bundle = ""; if (!AccessTokenHelper::VerifyNativeToken(IPCSkeleton::GetCallingTokenID())) { bundle = GetClientBundleName(); if (bundle.empty()) { - message.Message("bundleOption is nullptr", true); - NotificationAnalyticsUtil::ReportModifyEvent(message); return nullptr; } } @@ -122,8 +118,7 @@ sptr AdvancedNotificationService::GenerateBundleOption int32_t uid = IPCSkeleton::GetCallingUid(); bundleOption = new (std::nothrow) NotificationBundleOption(bundle, uid); if (bundleOption == nullptr) { - message.Message("Failed to create instance" + std::to_string(uid), true); - NotificationAnalyticsUtil::ReportModifyEvent(message); + ANS_LOGE("Failed to create NotificationBundleOption instance"); return nullptr; } return bundleOption; @@ -337,30 +332,6 @@ void AdvancedNotificationService::SetAgentNotification(sptr notificationRequest->SetOwnerBundleName(bundleName); } -void AdvancedNotificationService::ExtendDumpForFlags( - std::shared_ptr notificationFlags, std::stringstream &stream) -{ - if (notificationFlags == nullptr) { - ANS_LOGD("The notificationFlags is nullptr."); - return; - } - stream << "\t\tReminderFlags : " << notificationFlags->GetReminderFlags() << "\n"; - bool isEnable = false; - if (notificationFlags->IsSoundEnabled() == NotificationConstant::FlagStatus::OPEN) { - isEnable = true; - } - stream << "\t\tSound : " << isEnable << "\n"; - isEnable = false; - if (notificationFlags->IsVibrationEnabled() == NotificationConstant::FlagStatus::OPEN) { - isEnable = true; - } - stream << "\t\tVibration : " << isEnable << "\n"; - stream << "\t\tLockScreenVisbleness : " << notificationFlags->IsLockScreenVisblenessEnabled() << "\n"; - stream << "\t\tBanner : " << notificationFlags->IsBannerEnabled() << "\n"; - stream << "\t\tLightScreen : " << notificationFlags->IsLightScreenEnabled() << "\n"; - stream << "\t\tStatusIcon : " << notificationFlags->IsStatusIconEnabled() << "\n"; -} - ErrCode AdvancedNotificationService::ActiveNotificationDump(const std::string& bundle, int32_t userId, int32_t recvUserId, std::vector &dumpInfo) { @@ -401,7 +372,6 @@ ErrCode AdvancedNotificationService::ActiveNotificationDump(const std::string& b stream << "\t\tId: " << record->notification->GetId() << "\n"; stream << "\t\tLabel: " << record->notification->GetLabel() << "\n"; stream << "\t\tSlotType = " << record->request->GetSlotType() << "\n"; - ExtendDumpForFlags(record->request->GetFlags(), stream); ANS_LOGD("DumpInfo push stream."); dumpInfo.push_back(stream.str()); } @@ -447,7 +417,6 @@ ErrCode AdvancedNotificationService::RecentNotificationDump(const std::string& b stream << "\t\tId: " << recentNotification->notification->GetId() << "\n"; stream << "\t\tLabel: " << recentNotification->notification->GetLabel() << "\n"; stream << "\t\tSlotType = " << notificationRequest.GetSlotType() << "\n"; - ExtendDumpForFlags(notificationRequest.GetFlags(), stream); dumpInfo.push_back(stream.str()); } return ERR_OK; @@ -491,7 +460,6 @@ ErrCode AdvancedNotificationService::DistributedNotificationDump(const std::stri stream << "\t\tId: " << record->notification->GetId() << "\n"; stream << "\t\tLabel: " << record->notification->GetLabel() << "\n"; stream << "\t\tSlotType = " << record->request->GetSlotType() << "\n"; - ExtendDumpForFlags(record->request->GetFlags(), stream); dumpInfo.push_back(stream.str()); } @@ -543,13 +511,13 @@ void AdvancedNotificationService::OnBundleRemoved(const sptr notification = nullptr; result = RemoveFromNotificationList(key, notification, true, - NotificationConstant::PACKAGE_REMOVE_REASON_DELETE); + NotificationConstant::PACKAGE_CHANGED_REASON_DELETE); if (result != ERR_OK) { continue; } if (notification != nullptr) { - int32_t reason = NotificationConstant::PACKAGE_REMOVE_REASON_DELETE; + int32_t reason = NotificationConstant::PACKAGE_CHANGED_REASON_DELETE; UpdateRecentNotification(notification, true, reason); notifications.emplace_back(notification); ExecBatchCancel(notifications, reason); @@ -560,7 +528,7 @@ void AdvancedNotificationService::OnBundleRemoved(const sptrBatchNotifyCanceled( - notifications, nullptr, NotificationConstant::PACKAGE_REMOVE_REASON_DELETE); + notifications, nullptr, NotificationConstant::PACKAGE_CHANGED_REASON_DELETE); } NotificationPreferences::GetInstance()->RemoveAnsBundleDbInfo(bundleOption); RemoveDoNotDisturbProfileTrustList(bundleOption); @@ -568,7 +536,7 @@ void AdvancedNotificationService::OnBundleRemoved(const sptrRemoveEnabledDbByBundle(bundleOption); #ifdef ENABLE_ANS_EXT_WRAPPER EXTENTION_WRAPPER->UpdateByBundle(bundleOption->GetBundleName(), - NotificationConstant::PACKAGE_REMOVE_REASON_DELETE); + NotificationConstant::PACKAGE_CHANGED_REASON_DELETE); #endif } @@ -1389,7 +1357,7 @@ void AdvancedNotificationService::OnUserRemoved(const int32_t &userId) ErrCode AdvancedNotificationService::DeleteAllByUser(const int32_t &userId) { - return DeleteAllByUserInner(userId, NotificationConstant::APP_REMOVE_ALL_USER_REASON_DELETE); + return DeleteAllByUserInner(userId, NotificationConstant::CANCEL_ALL_REASON_DELETE); } ErrCode AdvancedNotificationService::DeleteAllByUserInner(const int32_t &userId, int32_t deleteReason, @@ -1399,29 +1367,16 @@ ErrCode AdvancedNotificationService::DeleteAllByUserInner(const int32_t &userId, bool isSubsystem = AccessTokenHelper::VerifyNativeToken(IPCSkeleton::GetCallingTokenID()); if (!isSubsystem && !AccessTokenHelper::IsSystemApp()) { - std::string message = "not system app."; - OHOS::Notification::HaMetaMessage haMetaMessage = HaMetaMessage(6, 5) - .ErrorCode(ERR_ANS_NON_SYSTEM_APP); - ReportDeleteFailedEventPush(haMetaMessage, deleteReason, message); - ANS_LOGE("%{public}s", message.c_str()); return ERR_ANS_NON_SYSTEM_APP; } if (userId <= SUBSCRIBE_USER_INIT) { - std::string message = "userId is error."; - OHOS::Notification::HaMetaMessage haMetaMessage = HaMetaMessage(6, 6) - .ErrorCode(ERR_ANS_INVALID_PARAM); - ReportDeleteFailedEventPush(haMetaMessage, deleteReason, message); - ANS_LOGE("%{public}s", message.c_str()); + ANS_LOGE("Input userId is invalid."); return ERR_ANS_INVALID_PARAM; } if (notificationSvrQueue_ == nullptr) { - std::string message = "Serial queue is invalid."; - OHOS::Notification::HaMetaMessage haMetaMessage = HaMetaMessage(6, 7) - .ErrorCode(ERR_ANS_INVALID_PARAM); - ReportDeleteFailedEventPush(haMetaMessage, deleteReason, message); - ANS_LOGE("%{public}s", message.c_str()); + ANS_LOGE("Serial queue is invalid."); return ERR_ANS_INVALID_PARAM; } std::shared_ptr result = std::make_shared(ERR_OK); @@ -1674,7 +1629,6 @@ ErrCode AdvancedNotificationService::SetRequestBundleInfo(const sptr &request, int32_t uid, std::string &bundle) { - HaMetaMessage message = HaMetaMessage(EventSceneId::SCENE_4, EventBranchId::BRANCH_2); std::shared_ptr bundleManager = BundleManagerHelper::GetInstance(); if (bundleManager == nullptr) { ANS_LOGE("failed to get bundleManager!"); @@ -1683,8 +1637,6 @@ ErrCode AdvancedNotificationService::PrePublishNotificationBySa(const sptrGetBundleNameByUid(uid); ErrCode result = SetRequestBundleInfo(request, uid, bundle); if (result != ERR_OK) { - message.ErrorCode(result); - NotificationAnalyticsUtil::ReportPublishFailedEvent(request, message); return result; } @@ -1712,8 +1664,7 @@ ErrCode AdvancedNotificationService::PrePublishNotificationBySa(const sptr &bundleOption) { - uint32_t slotFlags = 0b111111; if (DelayedSingleton::GetInstance()->IsSlotFlagsTrustlistAsBundle(bundleOption)) { + uint32_t slotFlags = 0b111111; ErrCode saveRef = NotificationPreferences::GetInstance()->SetNotificationSlotFlagsForBundle( bundleOption, slotFlags); if (saveRef != ERR_OK) { @@ -1912,9 +1863,7 @@ bool AdvancedNotificationService::AllowUseReminder(const std::string& bundleName } #ifdef ENABLE_ANS_EXT_WRAPPER int32_t ctrlResult = EXTENTION_WRAPPER->ReminderControl(bundleName); - if (ctrlResult != ERR_OK) { - return ctrlResult; - } + return (ctrlResult == ERR_OK) ? true : false; #else return true; #endif diff --git a/services/ans/src/common/notification_analytics_util.cpp b/services/ans/src/common/notification_analytics_util.cpp index a1948cebe..e327c4736 100644 --- a/services/ans/src/common/notification_analytics_util.cpp +++ b/services/ans/src/common/notification_analytics_util.cpp @@ -108,7 +108,7 @@ std::string HaMetaMessage::GetMessage() const HaMetaMessage& HaMetaMessage::SlotType(int32_t slotType) { - slotType_ = slotType; + slotType_ = static_cast(slotType); return *this; } @@ -199,7 +199,8 @@ void NotificationAnalyticsUtil::ReportModifyEvent(const HaMetaMessage& message) { std::shared_ptr extraInfo = std::make_shared(); std::string reason = std::to_string(message.sceneId_) + MESSAGE_DELIMITER + - std::to_string(message.branchId_) + MESSAGE_DELIMITER + message.GetMessage(); + std::to_string(message.branchId_) + std::to_string(message.notificationId_) + + MESSAGE_DELIMITER + message.GetMessage(); extraInfo->SetParam("reason", AAFwk::String::Box(reason)); AAFwk::WantParamWrapper wWrapper(*extraInfo); std::string extraContent = wWrapper.ToString(); diff --git a/services/ans/src/notification_subscriber_manager.cpp b/services/ans/src/notification_subscriber_manager.cpp index b5d7d25e3..aa82e9f16 100644 --- a/services/ans/src/notification_subscriber_manager.cpp +++ b/services/ans/src/notification_subscriber_manager.cpp @@ -32,10 +32,6 @@ #include "os_account_manager_helper.h" #include "remote_death_recipient.h" #include "advanced_notification_service.h" -#include "notification_analytics_util.h" - -#include "advanced_notification_inline.cpp" - namespace OHOS { namespace Notification { struct NotificationSubscriberManager::SubscriberRecord { @@ -103,14 +99,10 @@ ErrCode NotificationSubscriberManager::AddSubscriber( ANS_LOGE("queue is nullptr"); return result; } - HaMetaMessage message = HaMetaMessage(EventSceneId::SCENE_6, EventBranchId::BRANCH_2); ffrt::task_handle handler = notificationSubQueue_->submit_h(std::bind([this, &subscriber, &subInfo, &result]() { result = this->AddSubscriberInner(subscriber, subInfo); })); notificationSubQueue_->wait(handler); - message.Message("Subscribe notification: " + GetClientBundleName() + " user " + - std::to_string(subInfo->GetAppUserId()) + " " + std::to_string(result)); - NotificationAnalyticsUtil::ReportModifyEvent(message); return result; } @@ -128,17 +120,12 @@ ErrCode NotificationSubscriberManager::RemoveSubscriber( ANS_LOGE("queue is nullptr"); return result; } - HaMetaMessage message = HaMetaMessage(EventSceneId::SCENE_6, EventBranchId::BRANCH_3); ffrt::task_handle handler = notificationSubQueue_->submit_h(std::bind([this, &subscriber, &subscribeInfo, &result]() { ANS_LOGE("ffrt enter!"); result = this->RemoveSubscriberInner(subscriber, subscribeInfo); })); notificationSubQueue_->wait(handler); - std::string appUserId = (subscribeInfo == nullptr) ? "all" : std::to_string(subscribeInfo->GetAppUserId()); - message.Message("Remove subscriber: " + GetClientBundleName() + " user " + - appUserId + " " + std::to_string(result)); - NotificationAnalyticsUtil::ReportModifyEvent(message); return result; } @@ -420,7 +407,6 @@ void NotificationSubscriberManager::NotifyConsumedInner( HITRACE_METER_NAME(HITRACE_TAG_NOTIFICATION, __PRETTY_FUNCTION__); ANS_LOGD("%{public}s notification->GetUserId <%{public}d>", __FUNCTION__, notification->GetUserId()); - HaMetaMessage message = HaMetaMessage(EventSceneId::SCENE_8, EventBranchId::BRANCH_1).Checkfailed(false); for (auto record : subscriberRecordList_) { ANS_LOGD("%{public}s record->userId = <%{public}d> BundleName = <%{public}s deviceType = %{public}s", __FUNCTION__, record->userId, notification->GetBundleName().c_str(), record->deviceType.c_str()); @@ -442,9 +428,6 @@ void NotificationSubscriberManager::NotifyConsumedInner( record->subscriber->OnConsumed(notification, notificationMap); } } - message.Message(notification->GetKey() + " " + std::to_string(notification->GetUserId()) + - " size " + std::to_string(subscriberRecordList_.size())); - NotificationAnalyticsUtil::ReportPublishFailedEvent(notification->GetNotificationRequestPoint(), message); } #ifdef NOTIFICATION_SMART_REMINDER_SUPPORTED @@ -501,9 +484,6 @@ void NotificationSubscriberManager::NotifyCanceledInner( liveViewContent->FillPictureMarshallingMap(); } - OHOS::Notification::HaMetaMessage haMetaMessage = HaMetaMessage(1, 6).ErrorCode(ERR_OK); - ReportDeleteFailedEventPushByNotification(notification, haMetaMessage, deleteReason, "success"); - for (auto record : subscriberRecordList_) { ANS_LOGD("%{public}s record->userId = <%{public}d>", __FUNCTION__, record->userId); if (IsSubscribedBysubscriber(record, notification)) { @@ -550,11 +530,6 @@ void NotificationSubscriberManager::BatchNotifyCanceledInner(const std::vector", notifications.size()); - std::string message = "BatchNotifyCanceledInner.size:" + - std::to_string(notifications.size()) + "."; - OHOS::Notification::HaMetaMessage haMetaMessage = HaMetaMessage(1, 9) - .ErrorCode(ERR_OK); - ReportDeleteFailedEventPush(haMetaMessage, deleteReason, message); for (auto record : subscriberRecordList_) { if (record == nullptr) { continue; diff --git a/services/ans/src/reminder_data_manager.cpp b/services/ans/src/reminder_data_manager.cpp index 43a093976..0013c0f98 100644 --- a/services/ans/src/reminder_data_manager.cpp +++ b/services/ans/src/reminder_data_manager.cpp @@ -330,7 +330,7 @@ void ReminderDataManager::CancelNotification(const sptr &remind } sptr bundleOption = FindNotificationBundleOption(reminder->GetReminderId()); advancedNotificationService_->CancelPreparedNotification(notification->GetNotificationId(), - ReminderRequest::NOTIFICATION_LABEL, bundleOption, NotificationConstant::APP_CANCEL_REMINDER_REASON_DELETE); + ReminderRequest::NOTIFICATION_LABEL, bundleOption); } bool ReminderDataManager::CheckReminderLimitExceededLocked(const sptr &bundleOption, diff --git a/services/ans/test/unittest/advanced_notification_publish_service_test.cpp b/services/ans/test/unittest/advanced_notification_publish_service_test.cpp index ad5fcf14e..77aa70ec7 100644 --- a/services/ans/test/unittest/advanced_notification_publish_service_test.cpp +++ b/services/ans/test/unittest/advanced_notification_publish_service_test.cpp @@ -634,19 +634,16 @@ HWTEST_F(AnsPublishServiceTest, RemoveNotificationBySlot_00001, Function | Small MockIsSystemApp(false); sptr bundle = nullptr; sptr slot = nullptr; - auto ret = advancedNotificationService_->RemoveNotificationBySlot(bundle, slot, - NotificationConstant::DEFAULT_REASON_DELETE); + auto ret = advancedNotificationService_->RemoveNotificationBySlot(bundle, slot); ASSERT_EQ(ret, (int)ERR_ANS_NON_SYSTEM_APP); MockIsSystemApp(true); MockIsVerfyPermisson(false); - ret = advancedNotificationService_->RemoveNotificationBySlot(bundle, slot, - NotificationConstant::DEFAULT_REASON_DELETE); + ret = advancedNotificationService_->RemoveNotificationBySlot(bundle, slot); ASSERT_EQ(ret, (int)ERR_ANS_PERMISSION_DENIED); MockIsVerfyPermisson(true); - ret = advancedNotificationService_->RemoveNotificationBySlot(bundle, slot, - NotificationConstant::DEFAULT_REASON_DELETE); + ret = advancedNotificationService_->RemoveNotificationBySlot(bundle, slot); ASSERT_EQ(ret, (int)ERR_ANS_INVALID_BUNDLE); } @@ -671,8 +668,7 @@ HWTEST_F(AnsPublishServiceTest, RemoveNotificationBySlot_00002, Function | Small auto ret = advancedNotificationService_->AssignToNotificationList(record); auto slot = new NotificationSlot(NotificationConstant::SlotType::SOCIAL_COMMUNICATION); - ret = advancedNotificationService_->RemoveNotificationBySlot(bundle, slot, - NotificationConstant::DEFAULT_REASON_DELETE); + ret = advancedNotificationService_->RemoveNotificationBySlot(bundle, slot); ASSERT_EQ(ret, (int)ERR_OK); } diff --git a/services/ans/test/unittest/advanced_notification_service_test.cpp b/services/ans/test/unittest/advanced_notification_service_test.cpp index 47692b941..0729b58c6 100644 --- a/services/ans/test/unittest/advanced_notification_service_test.cpp +++ b/services/ans/test/unittest/advanced_notification_service_test.cpp @@ -1254,7 +1254,7 @@ HWTEST_F(AdvancedNotificationServiceTest, AdvancedNotificationServiceTest_16000, int32_t notificationId = 0; std::string label = "testLabel"; sptr bundleOption = nullptr; - ASSERT_EQ(advancedNotificationService_->CancelPreparedNotification(notificationId, label, bundleOption, 8), + ASSERT_EQ(advancedNotificationService_->CancelPreparedNotification(notificationId, label, bundleOption), ERR_ANS_INVALID_BUNDLE); GTEST_LOG_(INFO) << "CancelPreparedNotification_1000 test end"; @@ -3273,7 +3273,7 @@ HWTEST_F(AdvancedNotificationServiceTest, NotificationSvrQueue_00001, Function | auto bundle = new NotificationBundleOption(TEST_DEFUALT_BUNDLE, SYSTEM_APP_UID); auto request = new (std::nothrow) NotificationRequest(); - auto ret = advancedNotificationService_->CancelPreparedNotification(1, "label", bundle, 8); + auto ret = advancedNotificationService_->CancelPreparedNotification(1, "label", bundle); ASSERT_EQ(ret, (int)ERR_ANS_INVALID_PARAM); std::vector> requests; -- Gitee From f45832b19b8867bf1938b5d0e375797759814d1e Mon Sep 17 00:00:00 2001 From: 185******37 Date: Mon, 9 Sep 2024 09:10:43 +0000 Subject: [PATCH 048/167] update services/ans/include/advanced_notification_service.h. Signed-off-by: 185******37 --- services/ans/include/advanced_notification_service.h | 5 ++--- 1 file changed, 2 insertions(+), 3 deletions(-) diff --git a/services/ans/include/advanced_notification_service.h b/services/ans/include/advanced_notification_service.h index e1fd8202b..7b7cacf54 100644 --- a/services/ans/include/advanced_notification_service.h +++ b/services/ans/include/advanced_notification_service.h @@ -1170,8 +1170,7 @@ private: void StartFilters(); void StopFilters(); ErrCode Filter(const std::shared_ptr &record, bool isRecover = false); - void ChangeNotificationByControlFlags(const std::shared_ptr &record, - const bool isAgentController); + void ChangeNotificationByControlFlags(const std::shared_ptr &record); ErrCode CheckPublishPreparedNotification(const std::shared_ptr &record, bool isSystemApp); void AddToNotificationList(const std::shared_ptr &record); void AddToDelayNotificationList(const std::shared_ptr &record); @@ -1340,7 +1339,7 @@ private: ErrCode CheckBundleOptionValid(sptr &bundleOption); bool IsNeedNotifyConsumed(const sptr &request); ErrCode AddRecordToMemory(const std::shared_ptr &record, - bool isSystemApp, bool isUpdateByOwner, const bool isAgentController); + bool isSystemApp, bool isUpdateByOwner); ErrCode DuplicateMsgControl(const sptr &request); void RemoveExpiredUniqueKey(); bool IsDuplicateMsg(const std::string &uniqueKey); -- Gitee From b46e059b2e59478ce94f46351e893f71c49d0861 Mon Sep 17 00:00:00 2001 From: 185******37 Date: Mon, 9 Sep 2024 09:24:34 +0000 Subject: [PATCH 049/167] update services/ans/test/unittest/advanced_notification_service_test.cpp. Signed-off-by: 185******37 --- .../ans/test/unittest/advanced_notification_service_test.cpp | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/services/ans/test/unittest/advanced_notification_service_test.cpp b/services/ans/test/unittest/advanced_notification_service_test.cpp index b63321396..0729b58c6 100644 --- a/services/ans/test/unittest/advanced_notification_service_test.cpp +++ b/services/ans/test/unittest/advanced_notification_service_test.cpp @@ -3419,9 +3419,8 @@ HWTEST_F(AdvancedNotificationServiceTest, ChangeNotificationByControlFlags_00001 flags->SetStatusIconEnabled(true); request->SetFlags(flags); - bool isAgentController = true; auto record = advancedNotificationService_->MakeNotificationRecord(request, bundle); - advancedNotificationService_->ChangeNotificationByControlFlags(record, isAgentController); + advancedNotificationService_->ChangeNotificationByControlFlags(record); u_int32_t reminderFlags = flags->GetReminderFlags(); ASSERT_EQ(reminderFlags, 0); -- Gitee From f422332bb05185095e24e575a8d32c5955a8dff7 Mon Sep 17 00:00:00 2001 From: xdongs Date: Mon, 9 Sep 2024 10:46:08 +0800 Subject: [PATCH 050/167] =?UTF-8?q?=E5=BC=B9=E7=AA=97=E5=8D=95=E8=BF=9B?= =?UTF-8?q?=E7=A8=8B=E5=8D=95=E5=AE=9E=E4=BE=8B=E6=A8=A1=E5=BC=8F=20Signed?= =?UTF-8?q?-off-by:=20xdongs=20?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../enable_notification_dialog/entry/src/main/module.json | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/services/dialog_ui/enable_notification_dialog/entry/src/main/module.json b/services/dialog_ui/enable_notification_dialog/entry/src/main/module.json index 1bfac1a96..57cfcffc1 100644 --- a/services/dialog_ui/enable_notification_dialog/entry/src/main/module.json +++ b/services/dialog_ui/enable_notification_dialog/entry/src/main/module.json @@ -22,7 +22,8 @@ "icon": "$media:icon", "label": "$string:NotificationServiceExtAbility_label", "exported":true, - "type": "sysDialog/common" + "type": "sysDialog/common", + "extensionProcessMode": "instance" } ], "requestPermissions": [ -- Gitee From 06fad4cb793892c532730c24b11df52ecbbc32dd Mon Sep 17 00:00:00 2001 From: wufarong Date: Tue, 10 Sep 2024 15:33:28 +0800 Subject: [PATCH 051/167] =?UTF-8?q?=E6=9E=9A=E4=B8=BE=E5=8F=82=E6=95=B0?= =?UTF-8?q?=E6=A0=A1=E9=AA=8C=E6=97=A5=E5=BF=97=E8=A1=A5=E5=85=85?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: wufarong Change-Id: Ia5250a776ac919fe604225b2c120adf85b79dff8 --- frameworks/ans/src/notification_request.cpp | 30 ++++++++++++++------- 1 file changed, 20 insertions(+), 10 deletions(-) diff --git a/frameworks/ans/src/notification_request.cpp b/frameworks/ans/src/notification_request.cpp index a4aa32152..67bb46c71 100644 --- a/frameworks/ans/src/notification_request.cpp +++ b/frameworks/ans/src/notification_request.cpp @@ -1504,35 +1504,45 @@ bool NotificationRequest::ReadFromParcel(Parcel &parcel) int32_t slotTypeValue = parcel.ReadInt32(); if (slotTypeValue < 0 || - slotTypeValue >= static_cast(NotificationConstant::SlotType::ILLEGAL_TYPE)) { - ANS_LOGE("Invalid slot type value :%d", slotTypeValue); + slotTypeValue >= static_cast(NotificationConstant::SlotType::ILLEGAL_TYPE)) { + ANS_LOGE("Invalid slot type value :%d. It should be in [0 , %d).", + slotTypeValue, static_cast(NotificationConstant::SlotType::ILLEGAL_TYPE)); return false; } slotType_ = static_cast(slotTypeValue); int32_t groupAlertTypeValue = parcel.ReadInt32(); if (groupAlertTypeValue < 0 || - groupAlertTypeValue >= static_cast(NotificationRequest::GroupAlertType::ILLEGAL_TYPE)) { - ANS_LOGE("Invalid slot type value :%d", groupAlertTypeValue); + groupAlertTypeValue >= static_cast(NotificationRequest::GroupAlertType::ILLEGAL_TYPE)) { + ANS_LOGE("Invalid groupAlert type value :%d. It should be in [0 , %d).", + groupAlertTypeValue, static_cast(NotificationRequest::GroupAlertType::ILLEGAL_TYPE)); return false; } groupAlertType_ = static_cast(groupAlertTypeValue); int32_t visiblenessTypeValue = parcel.ReadInt32(); if (visiblenessTypeValue < 0 || - visiblenessTypeValue >= static_cast(NotificationConstant::VisiblenessType::ILLEGAL_TYPE)) { - ANS_LOGE("Invalid slot type value :%d", visiblenessTypeValue); + visiblenessTypeValue >= static_cast(NotificationConstant::VisiblenessType::ILLEGAL_TYPE)) { + ANS_LOGE("Invalid visibleness type value :%d. It should be in [0 , %d).", + visiblenessTypeValue, static_cast(NotificationConstant::VisiblenessType::ILLEGAL_TYPE)); return false; } visiblenessType_ = static_cast(visiblenessTypeValue); int32_t badgeStyleValue = parcel.ReadInt32(); - if (badgeStyleValue < 0 || badgeStyleValue >= static_cast(NotificationRequest::BadgeStyle::ILLEGAL_TYPE)) { - ANS_LOGE("Invalid slot type value :%d", badgeStyleValue); + if (badgeStyleValue < 0) { + ANS_LOGE("Invalid badge style value :%d. It should be greater than 0.", badgeStyleValue); return false; } + if (badgeStyleValue >= static_cast(NotificationRequest::BadgeStyle::ILLEGAL_TYPE)) { + badgeStyleValue = static_cast(NotificationRequest::BadgeStyle::NONE); + ANS_LOGE("The badge style value is too large, set it to the default enumeration value: %d.", + static_cast(NotificationRequest::BadgeStyle::NONE)); + } badgeStyle_ = static_cast(badgeStyleValue); int32_t notificationContentTypeValue = parcel.ReadInt32(); if (notificationContentTypeValue <= static_cast(NotificationContent::Type::NONE) || - notificationContentTypeValue >= static_cast(NotificationContent::Type::ILLEGAL_TYPE)) { - ANS_LOGE("Invalid slot type value :%d", notificationContentTypeValue); + notificationContentTypeValue >= static_cast(NotificationContent::Type::ILLEGAL_TYPE)) { + ANS_LOGE("Invalid notification content type value :%d. It should be in (%d , %d)", + notificationContentTypeValue, static_cast(NotificationContent::Type::NONE), + static_cast(NotificationContent::Type::ILLEGAL_TYPE)); return false; } notificationContentType_ = static_cast(notificationContentTypeValue); -- Gitee From c3560a6389b0749aa2e901556f6592bd6f90a4e2 Mon Sep 17 00:00:00 2001 From: baozeyu Date: Wed, 11 Sep 2024 14:13:09 +0800 Subject: [PATCH 052/167] =?UTF-8?q?=E4=BF=AE=E5=A4=8D=E5=9B=BE=E7=89=87?= =?UTF-8?q?=E6=81=A2=E5=A4=8D=E9=97=AE=E9=A2=98?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: baozeyu Change-Id: I6df02cc111e3647d911f0c36eabf73bb24f0b835 --- frameworks/ans/src/notification_request.cpp | 66 +++++++++++++++++-- frameworks/core/include/ans_image_util.h | 4 +- frameworks/core/src/ans_image_util.cpp | 7 +- interfaces/inner_api/notification_request.h | 8 +++ .../ans/src/advanced_notification_service.cpp | 5 +- 5 files changed, 81 insertions(+), 9 deletions(-) diff --git a/frameworks/ans/src/notification_request.cpp b/frameworks/ans/src/notification_request.cpp index a4aa32152..e235d3d87 100644 --- a/frameworks/ans/src/notification_request.cpp +++ b/frameworks/ans/src/notification_request.cpp @@ -300,6 +300,11 @@ int64_t NotificationRequest::GetArchiveDeadLine() const void NotificationRequest::SetLittleIcon(const std::shared_ptr &littleIcon) { littleIcon_ = littleIcon; + if (littleIcon != nullptr) { + Media::ImageInfo outImageInfo; + littleIcon->GetImageInfo(outImageInfo); + littleIconType_ = outImageInfo.encodedFormat; + } } const std::shared_ptr NotificationRequest::GetLittleIcon() const @@ -1224,10 +1229,37 @@ bool NotificationRequest::Marshalling(Parcel &parcel) const } if (valid) { - if (!parcel.WriteParcelable(littleIcon_.get())) { - ANS_LOGE("Failed to write littleIcon"); + if (!parcel.WriteString(littleIconType_)) { + ANS_LOGE("Failed to write littleIconType"); return false; } + + bool isUnPackImage = true; + std::string littleIconString; + + if (!littleIconType_.empty()) { + littleIconString = AnsImageUtil::PackImage(littleIcon_, littleIconType_); + } + + if (isUnPackImage && !littleIconString.empty()) { + isUnPackImage = false; + } + + if (!parcel.WriteBool(isUnPackImage)) { + return false; + } + ANS_LOGD("littleIcon_ : %{public}d, %{public}s", isUnPackImage, littleIconType_.c_str()); + if (isUnPackImage) { + if (!parcel.WriteParcelable(littleIcon_.get())) { + ANS_LOGE("Failed to write littleIcon"); + return false; + } + } else { + if (!parcel.WriteString(littleIconString)) { + ANS_LOGE("Failed to write littleIcon"); + return false; + } + } } valid = bigIcon_ ? true : false; @@ -1596,7 +1628,15 @@ bool NotificationRequest::ReadFromParcel(Parcel &parcel) valid = parcel.ReadBool(); if (valid) { - littleIcon_ = std::shared_ptr(parcel.ReadParcelable()); + littleIconType_ = parcel.ReadString(); + bool isUnPackImage = parcel.ReadBool(); + if (isUnPackImage) { + littleIcon_ = std::shared_ptr(parcel.ReadParcelable()); + } else { + std::string littleIconString = parcel.ReadString(); + littleIcon_ = AnsImageUtil::UnPackImage(littleIconString, littleIconType_); + } + if (!littleIcon_) { ANS_LOGE("Failed to read littleIcon"); return false; @@ -1910,6 +1950,7 @@ void NotificationRequest::CopyOther(const NotificationRequest &other) this->notificationBundleOption_ = other.notificationBundleOption_; this->notificationFlagsOfDevices_ = other.notificationFlagsOfDevices_; this->publishDelayTime_ = other.publishDelayTime_; + this->littleIconType_ = other.littleIconType_; } bool NotificationRequest::ConvertObjectsToJson(nlohmann::json &jsonObject) const @@ -1948,7 +1989,10 @@ bool NotificationRequest::ConvertObjectsToJson(nlohmann::json &jsonObject) const } jsonObject["extraInfo"] = extraInfoStr; - jsonObject["smallIcon"] = AnsImageUtil::PackImage(littleIcon_); + jsonObject["smallIconType"] = littleIconType_; + if (!littleIconType_.empty()) { + jsonObject["smallIcon"] = AnsImageUtil::PackImage(littleIcon_, littleIconType_); + } jsonObject["largeIcon"] = AnsImageUtil::PackImage(bigIcon_); jsonObject["overlayIcon"] = overlayIcon_ ? AnsImageUtil::PackImage(overlayIcon_) : ""; @@ -2194,9 +2238,14 @@ void NotificationRequest::ConvertJsonToPixelMap(NotificationRequest *target, con const auto &jsonEnd = jsonObject.cend(); + if (jsonObject.find("smallIconType") != jsonEnd && jsonObject.at("smallIconType").is_string()) { + std::string littleIconType = jsonObject.at("smallIconType").get(); + target->littleIconType_ = littleIconType; + } + if (jsonObject.find("smallIcon") != jsonEnd && jsonObject.at("smallIcon").is_string()) { - auto littleIconStr = jsonObject.at("smallIcon").get(); - target->littleIcon_ = AnsImageUtil::UnPackImage(littleIconStr); + auto littleIconStr = jsonObject.at("smallIcon").get(); + target->littleIcon_ = AnsImageUtil::UnPackImage(littleIconStr, target->littleIconType_); } if (jsonObject.find("largeIcon") != jsonEnd && jsonObject.at("largeIcon").is_string()) { @@ -2723,5 +2772,10 @@ bool NotificationRequest::IsUpdateByOwnerAllowed() const { return isUpdateByOwnerAllowed_; } + +const std::string NotificationRequest::GetLittleIconType() const +{ + return littleIconType_; +} } // namespace Notification } // namespace OHOS diff --git a/frameworks/core/include/ans_image_util.h b/frameworks/core/include/ans_image_util.h index d7068e608..5b1bbe86a 100644 --- a/frameworks/core/include/ans_image_util.h +++ b/frameworks/core/include/ans_image_util.h @@ -28,6 +28,7 @@ public: static const uint8_t SHIFT_FOUR; static const uint8_t NUM_TEN; static const size_t TWO_TIMES; + static const uint32_t DEFAULT_SIZE; /** * @brief Packs an image to a string. @@ -45,7 +46,8 @@ public: * @param pixelMapStr Indicates the string of image. * @return Returns an image object. */ - static std::shared_ptr UnPackImage(const std::string &pixelMapStr); + static std::shared_ptr UnPackImage(const std::string &pixelMapStr, + const std::string &format = IMAGE_FORMAT_PNG); /** * @brief Packs an image to a file. diff --git a/frameworks/core/src/ans_image_util.cpp b/frameworks/core/src/ans_image_util.cpp index f2fe05f4e..e3929d1dd 100644 --- a/frameworks/core/src/ans_image_util.cpp +++ b/frameworks/core/src/ans_image_util.cpp @@ -24,6 +24,7 @@ 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}; +const uint32_t AnsImageUtil::DEFAULT_SIZE {25 * 1024 * 1024}; std::string AnsImageUtil::PackImage(const std::shared_ptr &pixelMap, const std::string &format) { @@ -47,6 +48,9 @@ std::string AnsImageUtil::PackImage(const std::shared_ptr &pixe auto size = static_cast(pixelMap->GetByteCount()); ANS_LOGD("size of pixelMap : %{public}u", size); + if (size < DEFAULT_SIZE) { + size = DEFAULT_SIZE; + } auto pbuf = new (std::nothrow) uint8_t [size]; if (pbuf == nullptr) { ANS_LOGE("create buffer failed"); @@ -66,7 +70,7 @@ std::string AnsImageUtil::PackImage(const std::shared_ptr &pixe return BinToHex(pixelMapStr); } -std::shared_ptr AnsImageUtil::UnPackImage(const std::string &pixelMapStr) +std::shared_ptr AnsImageUtil::UnPackImage(const std::string &pixelMapStr, const std::string &format) { if (pixelMapStr.empty()) { return {}; @@ -76,6 +80,7 @@ std::shared_ptr AnsImageUtil::UnPackImage(const std::string &pi uint32_t errorCode {0}; Media::SourceOptions opts; + opts.formatHint = format; auto imageSource = Media::ImageSource::CreateImageSource( reinterpret_cast(binStr.data()), static_cast(binStr.length()), diff --git a/interfaces/inner_api/notification_request.h b/interfaces/inner_api/notification_request.h index c5f09cf74..cb83e9f2a 100644 --- a/interfaces/inner_api/notification_request.h +++ b/interfaces/inner_api/notification_request.h @@ -517,6 +517,13 @@ public: */ const std::shared_ptr GetLittleIcon() const; + /** + * @brief Obtains the icon type of the notification. + * + * @return Returns the notification icon type + */ + const std::string GetLittleIconType() const; + /** * @brief Sets the large icon of this notification, which is usually displayed on the right of the notification. * @@ -1507,6 +1514,7 @@ private: std::shared_ptr maxScreenWantAgent_ {}; std::shared_ptr additionalParams_ {}; std::shared_ptr littleIcon_ {}; + std::string littleIconType_ {}; std::shared_ptr bigIcon_ {}; std::shared_ptr overlayIcon_ {}; std::shared_ptr notificationContent_ {}; diff --git a/services/ans/src/advanced_notification_service.cpp b/services/ans/src/advanced_notification_service.cpp index 54dd557c3..f9872f96c 100644 --- a/services/ans/src/advanced_notification_service.cpp +++ b/services/ans/src/advanced_notification_service.cpp @@ -1150,6 +1150,8 @@ ErrCode AdvancedNotificationService::RemoveFromNotificationList(const sptr Date: Tue, 27 Aug 2024 09:27:23 +0800 Subject: [PATCH 053/167] =?UTF-8?q?cherry=20pick=20e81ba62=20from=20https:?= =?UTF-8?q?//gitee.com/baozeyu/notification=5Fdistributed=5Fnotification?= =?UTF-8?q?=5Fservice/pulls/2091=20=E4=BF=AE=E5=A4=8D=E5=88=A0=E9=99=A4?= =?UTF-8?q?=E7=94=A8=E6=88=B7=E6=95=B0=E6=8D=AE=E6=9C=AA=E5=88=A0=E9=99=A4?= =?UTF-8?q?=E5=AD=90=E7=A9=BA=E9=97=B4=E6=95=B0=E6=8D=AE?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: baozeyu Change-Id: Iae278ab08ed685821ca56e6f150aa902503b41a0 --- services/ans/src/advanced_notification_utils.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/services/ans/src/advanced_notification_utils.cpp b/services/ans/src/advanced_notification_utils.cpp index 1d2957278..57c338b75 100644 --- a/services/ans/src/advanced_notification_utils.cpp +++ b/services/ans/src/advanced_notification_utils.cpp @@ -1278,7 +1278,7 @@ void AdvancedNotificationService::OnResourceRemove(int32_t userId) ANS_LOGE("Serial queue is invalid."); return; } - ffrt::task_handle handler = notificationSvrQueue_->submit_h(std::bind([&]() { + ffrt::task_handle handler = notificationSvrQueue_->submit_h(std::bind([=]() { ANS_LOGD("ffrt enter!"); NotificationPreferences::GetInstance()->RemoveSettings(userId); })); -- Gitee From d9708be2f3f176ee91e5f7d76671797d1bcaff5a Mon Sep 17 00:00:00 2001 From: baozeyu Date: Tue, 10 Sep 2024 19:20:26 +0800 Subject: [PATCH 054/167] =?UTF-8?q?=E6=89=93=E7=82=B9=E9=99=90=E6=B5=81-?= =?UTF-8?q?=E5=95=86=E5=88=86?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: baozeyu Change-Id: Ibad5ee4ca373cca303e21c662fd860d331f0e4b8 --- .../ans/include/notification_analytics_util.h | 13 ++++ .../ans/src/advanced_notification_inline.cpp | 13 ---- .../ans/src/advanced_notification_service.cpp | 7 ++- .../common/notification_analytics_util.cpp | 62 +++++++++++++++++++ 4 files changed, 79 insertions(+), 16 deletions(-) diff --git a/services/ans/include/notification_analytics_util.h b/services/ans/include/notification_analytics_util.h index 6b51afb97..4b1b4d8f2 100644 --- a/services/ans/include/notification_analytics_util.h +++ b/services/ans/include/notification_analytics_util.h @@ -79,6 +79,11 @@ public: }; +struct FlowControllerOption { + int32_t count; + int32_t time; +}; + class NotificationAnalyticsUtil { public: static void ReportPublishFailedEvent(const sptr& request, const HaMetaMessage& message); @@ -89,6 +94,8 @@ public: static void ReportDeleteFailedEvent(const HaMetaMessage& message); + static void RemoveExpired(std::list &list, + const std::chrono::system_clock::time_point &now, int32_t time = 1); private: static void ReportNotificationEvent(const sptr& request, EventFwk::Want want, int32_t eventCode, const std::string& reason); @@ -98,6 +105,12 @@ private: static void CommonNotificationEvent(int32_t eventCode, const HaMetaMessage& message); static void ReportNotificationEvent(EventFwk::Want want, int32_t eventCode, const std::string& reason); + + static bool ReportFlowControl(const int32_t reportType); + + static std::list GetFlowListByType(const int32_t reportType); + + static FlowControllerOption GetFlowOptionByType(const int32_t reportType); }; } // namespace Notification } // namespace OHOS diff --git a/services/ans/src/advanced_notification_inline.cpp b/services/ans/src/advanced_notification_inline.cpp index 34eac7195..0244d1b6b 100644 --- a/services/ans/src/advanced_notification_inline.cpp +++ b/services/ans/src/advanced_notification_inline.cpp @@ -99,18 +99,5 @@ inline ErrCode CheckPictureSize(const sptr &request) return ERR_OK; } - -inline void RemoveExpired( - std::list &list, const std::chrono::system_clock::time_point &now) -{ - auto iter = list.begin(); - while (iter != list.end()) { - if (abs(now - *iter) > std::chrono::seconds(1)) { - iter = list.erase(iter); - } else { - break; - } - } -} } // namespace Notification } // namespace OHOS diff --git a/services/ans/src/advanced_notification_service.cpp b/services/ans/src/advanced_notification_service.cpp index 54dd557c3..d443facb7 100644 --- a/services/ans/src/advanced_notification_service.cpp +++ b/services/ans/src/advanced_notification_service.cpp @@ -73,6 +73,7 @@ #include "advanced_notification_inline.cpp" #include "advanced_datashare_helper_ext.h" +#include "notification_analytics_util.h" namespace OHOS { namespace Notification { @@ -907,7 +908,7 @@ void AdvancedNotificationService::AddToNotificationList(const std::shared_ptr &record) { std::chrono::system_clock::time_point now = std::chrono::system_clock::now(); - RemoveExpired(flowControlUpdateTimestampList_, now); + NotificationAnalyticsUtil::RemoveExpired(flowControlUpdateTimestampList_, now); if (flowControlUpdateTimestampList_.size() >= MAX_UPDATE_NUM_PERSECOND) { return ERR_ANS_OVER_MAX_UPDATE_PERSECOND; } @@ -1384,7 +1385,7 @@ ErrCode AdvancedNotificationService::FlowControl(const std::shared_ptr lock(flowControlMutex_); - RemoveExpired(flowControlTimestampList_, now); + NotificationAnalyticsUtil::RemoveExpired(flowControlTimestampList_, now); if (flowControlTimestampList_.size() >= MAX_ACTIVE_NUM_PERSECOND + MAX_UPDATE_NUM_PERSECOND) { return ERR_ANS_OVER_MAX_ACTIVE_PERSECOND; } @@ -1396,7 +1397,7 @@ ErrCode AdvancedNotificationService::FlowControl(const std::shared_ptr &record) { std::chrono::system_clock::time_point now = std::chrono::system_clock::now(); - RemoveExpired(flowControlPublishTimestampList_, now); + NotificationAnalyticsUtil::RemoveExpired(flowControlPublishTimestampList_, now); if (flowControlPublishTimestampList_.size() >= MAX_ACTIVE_NUM_PERSECOND) { return ERR_ANS_OVER_MAX_ACTIVE_PERSECOND; } diff --git a/services/ans/src/common/notification_analytics_util.cpp b/services/ans/src/common/notification_analytics_util.cpp index e327c4736..f962ea08c 100644 --- a/services/ans/src/common/notification_analytics_util.cpp +++ b/services/ans/src/common/notification_analytics_util.cpp @@ -29,7 +29,11 @@ constexpr char MESSAGE_DELIMITER = '#'; constexpr const int32_t PUBLISH_ERROR_EVENT_CODE = 0; constexpr const int32_t DELETE_ERROR_EVENT_CODE = 5; constexpr const int32_t MODIFY_ERROR_EVENT_CODE = 6; +constexpr const int32_t DEFAULT_ERROR_EVENT_COUNT = 6; +constexpr const int32_t DEFAULT_ERROR_EVENT_TIME = 60; const static std::string NOTIFICATION_EVENT_PUSH_AGENT = "notification.event.PUSH_AGENT"; +static std::mutex reportFlowControlMutex_; +static std::map> flowControlTimestampMap_; HaMetaMessage::HaMetaMessage(uint32_t sceneId, uint32_t branchId) : sceneId_(sceneId), branchId_(branchId) @@ -197,6 +201,10 @@ void NotificationAnalyticsUtil::ReportNotificationEvent(const sptr extraInfo = std::make_shared(); std::string reason = std::to_string(message.sceneId_) + MESSAGE_DELIMITER + std::to_string(message.branchId_) + std::to_string(message.notificationId_) + @@ -243,5 +251,59 @@ void NotificationAnalyticsUtil::ReportNotificationEvent(EventFwk::Want want, ANS_LOGE("Publish event failed %{public}d, %{public}s", eventCode, reason.c_str()); } } + +bool NotificationAnalyticsUtil::ReportFlowControl(const int32_t reportType) +{ + std::chrono::system_clock::time_point now = std::chrono::system_clock::now(); + std::lock_guard lock(reportFlowControlMutex_); + std::list list = GetFlowListByType(reportType); + FlowControllerOption option = GetFlowOptionByType(reportType); + RemoveExpired(list, now, option.time); + if (list.size() >= option.count) { + return false; + } + list.push_back(now); + flowControlTimestampMap_[reportType] = list; + return true; +} + +std::list NotificationAnalyticsUtil::GetFlowListByType(const int32_t reportType) +{ + std::list res; + auto iter = flowControlTimestampMap_.find(reportType); + if (iter != flowControlTimestampMap_.end()) { + res = iter->second; + } + return res; +} + +void NotificationAnalyticsUtil::RemoveExpired(std::list &list, + const std::chrono::system_clock::time_point &now, int32_t time) +{ + auto iter = list.begin(); + while (iter != list.end()) { + if (abs(now - *iter) > std::chrono::seconds(time)) { + iter = list.erase(iter); + } else { + break; + } + } +} + +FlowControllerOption NotificationAnalyticsUtil::GetFlowOptionByType(const int32_t reportType) +{ + FlowControllerOption option; + switch (reportType) { + case MODIFY_ERROR_EVENT_CODE: + option.count = DEFAULT_ERROR_EVENT_COUNT; + option.time = DEFAULT_ERROR_EVENT_TIME; + break; + default: + option.count = DEFAULT_ERROR_EVENT_COUNT; + option.time = DEFAULT_ERROR_EVENT_TIME; + break; + } + return option; +} } // namespace Notification } // namespace OHOS -- Gitee From 9dc303ad6b1a9484eef9e2de8cc36a833b45c50b Mon Sep 17 00:00:00 2001 From: baozeyu Date: Tue, 10 Sep 2024 15:38:32 +0800 Subject: [PATCH 055/167] =?UTF-8?q?=E5=8F=B3=E5=9B=BE=E8=BF=87=E5=A4=A7?= =?UTF-8?q?=E6=94=BE=E8=A1=8C=E9=80=9A=E7=9F=A5-=E5=95=86=E5=88=86?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: baozeyu Change-Id: I05b31e07db18f7b3052167f3544eca49d5a23ec7 --- frameworks/ans/src/notification_request.cpp | 5 +++++ frameworks/core/src/ans_notification.cpp | 12 ++++++------ interfaces/inner_api/notification_request.h | 10 +++++++++- services/ans/src/advanced_notification_inline.cpp | 7 ++++--- 4 files changed, 24 insertions(+), 10 deletions(-) diff --git a/frameworks/ans/src/notification_request.cpp b/frameworks/ans/src/notification_request.cpp index a4aa32152..cf3f6726f 100644 --- a/frameworks/ans/src/notification_request.cpp +++ b/frameworks/ans/src/notification_request.cpp @@ -312,6 +312,11 @@ void NotificationRequest::SetBigIcon(const std::shared_ptr &big bigIcon_ = bigIcon; } +void NotificationRequest::ResetBigIcon() const +{ + bigIcon_ = nullptr; +} + const std::shared_ptr NotificationRequest::GetBigIcon() const { return bigIcon_; diff --git a/frameworks/core/src/ans_notification.cpp b/frameworks/core/src/ans_notification.cpp index 782984075..e75c0dfb8 100644 --- a/frameworks/core/src/ans_notification.cpp +++ b/frameworks/core/src/ans_notification.cpp @@ -1376,12 +1376,6 @@ ErrCode AnsNotification::CheckImageSize(const NotificationRequest &request) return ERR_ANS_ICON_OVER_SIZE; } - auto bigIcon = request.GetBigIcon(); - if (NotificationRequest::CheckImageOverSizeForPixelMap(bigIcon, MAX_ICON_SIZE)) { - ANS_LOGE("The size of big icon exceeds limit"); - return ERR_ANS_ICON_OVER_SIZE; - } - auto overlayIcon = request.GetOverlayIcon(); if (overlayIcon && NotificationRequest::CheckImageOverSizeForPixelMap(overlayIcon, MAX_ICON_SIZE)) { ANS_LOGE("The size of overlay icon exceeds limit"); @@ -1417,6 +1411,12 @@ ErrCode AnsNotification::CheckImageSize(const NotificationRequest &request) } } + auto bigIcon = request.GetBigIcon(); + if (NotificationRequest::CheckImageOverSizeForPixelMap(bigIcon, MAX_ICON_SIZE)) { + request.ResetBigIcon(); + ANS_LOGI("The size of big icon exceeds limit"); + } + return ERR_OK; } diff --git a/interfaces/inner_api/notification_request.h b/interfaces/inner_api/notification_request.h index c5f09cf74..67a425d9a 100644 --- a/interfaces/inner_api/notification_request.h +++ b/interfaces/inner_api/notification_request.h @@ -524,6 +524,12 @@ public: */ void SetBigIcon(const std::shared_ptr &bigIcon); + /** + * @brief reset the large icon of this notification, which is usually displayed on the right of the notification. + * + */ + void ResetBigIcon() const; + /** * @brief Obtains the large icon of this notification. * @@ -1507,7 +1513,9 @@ private: std::shared_ptr maxScreenWantAgent_ {}; std::shared_ptr additionalParams_ {}; std::shared_ptr littleIcon_ {}; - std::shared_ptr bigIcon_ {}; + std::string littleIconType_ {}; + mutable std::shared_ptr bigIcon_ {}; + std::shared_ptr overlayIcon_ {}; std::shared_ptr notificationContent_ {}; diff --git a/services/ans/src/advanced_notification_inline.cpp b/services/ans/src/advanced_notification_inline.cpp index 34eac7195..c0de07861 100644 --- a/services/ans/src/advanced_notification_inline.cpp +++ b/services/ans/src/advanced_notification_inline.cpp @@ -89,12 +89,13 @@ inline ErrCode CheckPictureSize(const sptr &request) return ERR_ANS_ICON_OVER_SIZE; } - if (request->CheckImageOverSizeForPixelMap(request->GetBigIcon(), MAX_ICON_SIZE)) { + if (request->CheckImageOverSizeForPixelMap(request->GetOverlayIcon(), MAX_ICON_SIZE)) { return ERR_ANS_ICON_OVER_SIZE; } - if (request->CheckImageOverSizeForPixelMap(request->GetOverlayIcon(), MAX_ICON_SIZE)) { - return ERR_ANS_ICON_OVER_SIZE; + if (request->CheckImageOverSizeForPixelMap(request->GetBigIcon(), MAX_ICON_SIZE)) { + request->ResetBigIcon(); + ANS_LOGI("Check big image size over limit"); } return ERR_OK; -- Gitee From 9c8819f47e16f7b938fe9a6dd163dd0f64a9010c Mon Sep 17 00:00:00 2001 From: z30053788 Date: Thu, 12 Sep 2024 15:38:50 +0800 Subject: [PATCH 056/167] lanhuang Signed-off-by: z30053788 Change-Id: I52cd4e2b9911a964f8339eb7705b6caf0b352dd9 --- .../core/common/include/ans_convert_enum.h | 18 ------------------ services/ans/include/bundle_manager_helper.h | 8 -------- .../src/advanced_notification_slot_service.cpp | 6 ------ .../ans/src/notification_extension_wrapper.cpp | 2 +- 4 files changed, 1 insertion(+), 33 deletions(-) diff --git a/frameworks/core/common/include/ans_convert_enum.h b/frameworks/core/common/include/ans_convert_enum.h index 3524578c3..4e0405f7c 100644 --- a/frameworks/core/common/include/ans_convert_enum.h +++ b/frameworks/core/common/include/ans_convert_enum.h @@ -179,24 +179,6 @@ public: */ static bool ReasonCToJS(const int32_t &inType, int32_t &outType); - /** - * @brief Converts reason type from native to js - * - * @param inType Indicates a native reason type - * @param outType Indicates a js reason type - * @return Returns true if success, returns false otherwise - */ - static void ReasonCToJSExt(const int32_t &inType, int32_t &outType); - - /** - * @brief Converts reason type from native to js - * - * @param inType Indicates a native reason type - * @param outType Indicates a js reason type - * @return Returns true if success, returns false otherwise - */ - static void ReasonCToJSSecondExt(const int32_t &inType, int32_t &outType); - /** * @brief Converts do-not-disturb type from js to native * diff --git a/services/ans/include/bundle_manager_helper.h b/services/ans/include/bundle_manager_helper.h index 1f4b5d61b..30da5ea18 100644 --- a/services/ans/include/bundle_manager_helper.h +++ b/services/ans/include/bundle_manager_helper.h @@ -108,13 +108,6 @@ public: bool GetBundleInfos( const AppExecFwk::BundleFlag flag, std::vector &bundleInfos, int32_t userId); - /** - * @brief Obtains the app index by uid. - * @param uid Indicates uid. - * @return Returns the query result if succeed, retrun 0(main index) otherwise. - */ - int32_t GetAppIndexByUid(const int32_t uid); - /** * @brief Check API compatibility. * @@ -123,7 +116,6 @@ public: * @return Returns the check result. */ bool CheckApiCompatibility(const std::string &bundleName, const int32_t &uid); - private: void Connect(); void Disconnect(); diff --git a/services/ans/src/advanced_notification_slot_service.cpp b/services/ans/src/advanced_notification_slot_service.cpp index f2cc79f08..f0d6caa41 100644 --- a/services/ans/src/advanced_notification_slot_service.cpp +++ b/services/ans/src/advanced_notification_slot_service.cpp @@ -46,7 +46,6 @@ namespace { constexpr char CALL_UI_BUNDLE[] = "com.ohos.callui"; } const uint32_t DEFAULT_SLOT_FLAGS = 59; // 0b111011 -const uint32_t SA_SLOT_FLAGS = 63; // 0b111111 ErrCode AdvancedNotificationService::AddSlots(const std::vector> &slots) { ANS_LOGD("%{public}s", __FUNCTION__); @@ -531,11 +530,6 @@ void AdvancedNotificationService::GenerateSlotReminderMode( const sptr &slot, const sptr &bundle, bool isSpecifiedSlot) { uint32_t slotFlags = DEFAULT_SLOT_FLAGS; - bool isSubsystem = AccessTokenHelper::VerifyNativeToken(IPCSkeleton::GetCallingTokenID()); - if (isSubsystem) { - ANS_LOGD("GenerateSlotReminderMode isSubsystem in"); - slotFlags = SA_SLOT_FLAGS; - } auto ret = NotificationPreferences::GetInstance()->GetNotificationSlotFlagsForBundle(bundle, slotFlags); if (ret != ERR_OK) { ANS_LOGI("Failed to get slotflags for bundle, use default slotflags."); diff --git a/services/ans/src/notification_extension_wrapper.cpp b/services/ans/src/notification_extension_wrapper.cpp index a0f83b571..00fa00984 100644 --- a/services/ans/src/notification_extension_wrapper.cpp +++ b/services/ans/src/notification_extension_wrapper.cpp @@ -168,7 +168,7 @@ int32_t ExtensionWrapper::ReminderControl(const std::string &bundleName) return reminderControl_(bundleName); } -int32_t ExtensionWrapper::LocalControl(const sptr &request) +__attribute__((no_sanitize("cfi"))) int32_t ExtensionWrapper::LocalControl(const sptr &request) { if (localControl_ == nullptr) { ANS_LOGE("LocalControl wrapper symbol failed"); -- Gitee From e9d0bd49836f47f85d917e753b87223b41f4569a Mon Sep 17 00:00:00 2001 From: Ricky Date: Thu, 19 Sep 2024 19:39:28 +0800 Subject: [PATCH 057/167] set enable fa model for oh Signed-off-by: Ricky Change-Id: I8bb847dfcc584fa256184f30949141014fdb0075 --- bundle.json | 5 ++++- notification.gni | 1 + services/ans/BUILD.gn | 4 ++++ services/ans/src/advanced_notification_utils.cpp | 4 ++++ 4 files changed, 13 insertions(+), 1 deletion(-) diff --git a/bundle.json b/bundle.json index 0bd1b2ce2..fdf57013e 100644 --- a/bundle.json +++ b/bundle.json @@ -42,7 +42,10 @@ "SystemCapability.Notification.Notification", "SystemCapability.Notification.ReminderAgent" ], - "features": ["distributed_notification_service_feature_summary"], + "features": [ + "distributed_notification_service_feature_summary", + "distributed_notification_service_feature_enable_fa_model" + ], "adapted_system_type": [ "standard" ], diff --git a/notification.gni b/notification.gni index 08b20e2f3..56ef295ec 100644 --- a/notification.gni +++ b/notification.gni @@ -59,6 +59,7 @@ declare_args() { ans_config_policy_enable = true screenlock_mgr_enable = true telephony_cust = true + distributed_notification_service_feature_enable_fa_model = true if (defined(global_parts_info) && !defined(global_parts_info.resourceschedule_device_usage_statistics)) { diff --git a/services/ans/BUILD.gn b/services/ans/BUILD.gn index 6708d1f40..e6fd80e2f 100644 --- a/services/ans/BUILD.gn +++ b/services/ans/BUILD.gn @@ -205,6 +205,10 @@ ohos_shared_library("libans") { defines += [ "ENABLE_ANS_TELEPHONY_CUST_WRAPPER" ] } + if (distributed_notification_service_feature_enable_fa_model) { + defines += [ "ANS_ENABLE_FA_MODEL" ] + } + subsystem_name = "${subsystem_name}" part_name = "${component_name}" } diff --git a/services/ans/src/advanced_notification_utils.cpp b/services/ans/src/advanced_notification_utils.cpp index 57c338b75..8787fb5df 100644 --- a/services/ans/src/advanced_notification_utils.cpp +++ b/services/ans/src/advanced_notification_utils.cpp @@ -1333,12 +1333,16 @@ void AdvancedNotificationService::OnBundleDataCleared(const sptr &bundleOption) { +#ifdef ANS_ENABLE_FA_MODEL ANS_LOGD("%{public}s", __FUNCTION__); std::shared_ptr bundleManager = BundleManagerHelper::GetInstance(); if (bundleManager == nullptr) { return false; } return bundleManager->CheckApiCompatibility(bundleOption); +#else + return false; +#endif } void AdvancedNotificationService::OnUserRemoved(const int32_t &userId) -- Gitee From 64883de5bf7c1f2d15201c6a77a86cc92d00d1bb Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E7=8E=8B=E7=86=99=E8=BE=89?= <13821332216@163.com> Date: Sat, 21 Sep 2024 20:39:43 +0800 Subject: [PATCH 058/167] =?UTF-8?q?=E4=BF=AE=E6=94=B9=E5=85=8D=E6=89=93?= =?UTF-8?q?=E6=89=B0=E4=B8=8B=E5=BC=80=E6=9C=BA=E6=9C=AA=E8=A7=A3=E9=94=81?= =?UTF-8?q?=E6=9D=A5=E7=94=B5=E6=9F=A5=E8=AF=A2=E6=95=B0=E6=8D=AE=E5=BA=93?= =?UTF-8?q?=E6=8B=A6=E6=88=AA=E8=A7=84=E5=88=99?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: 王熙辉 <13821332216@163.com> --- services/ans/include/advanced_datashare_helper.h | 2 +- services/ans/src/advanced_datashare_helper.cpp | 16 +++++++++------- .../advanced_notification_publish_service.cpp | 6 +++--- 3 files changed, 13 insertions(+), 11 deletions(-) diff --git a/services/ans/include/advanced_datashare_helper.h b/services/ans/include/advanced_datashare_helper.h index cebf5bab9..7490c0ef1 100644 --- a/services/ans/include/advanced_datashare_helper.h +++ b/services/ans/include/advanced_datashare_helper.h @@ -36,8 +36,8 @@ public: AdvancedDatashareHelper(); ~AdvancedDatashareHelper() = default; bool Query(Uri &uri, const std::string &key, std::string &value); - bool QueryContact(Uri &uri, const std::string &phoneNumber, const std::string &policy); bool isRepeatCall(const std::string &phoneNumber); + ErrCode QueryContact(Uri &uri, const std::string &phoneNumber, const std::string &policy); std::string GetFocusModeEnableUri(const int32_t &userId) const; std::string GetFocusModeProfileUri(const int32_t &userId) const; std::string GetFocusModeCallPolicyUri(const int32_t &userId) const; diff --git a/services/ans/src/advanced_datashare_helper.cpp b/services/ans/src/advanced_datashare_helper.cpp index 0e1eb2d76..600d16d90 100644 --- a/services/ans/src/advanced_datashare_helper.cpp +++ b/services/ans/src/advanced_datashare_helper.cpp @@ -57,6 +57,8 @@ constexpr const char *CREATE_TIME = "create_time"; constexpr const unsigned int PHONE_NUMBER_LENGTH = 7; constexpr const unsigned int MAX_TIME_INTERVAL = 15 * 60; constexpr const int TYPE_ID_FIVE = 5; +constexpr const int ERROR_QUERY_INFO_FAILED = -1; +constexpr const int QUERY_INFO_SUCCESS = 1; std::vector QUERY_CONTACT_COLUMN_LIST = {FORMAT_PHONE_NUMBER, FAVORITE, FOCUS_MODE_LIST, DETAIL_INFO}; } // namespace AdvancedDatashareHelper::AdvancedDatashareHelper() @@ -125,13 +127,13 @@ bool AdvancedDatashareHelper::Query(Uri &uri, const std::string &key, std::strin return true; } -bool AdvancedDatashareHelper::QueryContact(Uri &uri, const std::string &phoneNumber, const std::string &policy) +ErrCode AdvancedDatashareHelper::QueryContact(Uri &uri, const std::string &phoneNumber, const std::string &policy) { std::string identity = IPCSkeleton::ResetCallingIdentity(); std::shared_ptr helper = CreateContactDataShareHelper(CONTACT_URI); if (helper == nullptr) { ANS_LOGE("The data share helper is nullptr."); - return false; + return ERROR_QUERY_INFO_FAILED; } DataShare::DataSharePredicates predicates; predicates.EqualTo(IS_DELETED, 0); @@ -147,9 +149,9 @@ bool AdvancedDatashareHelper::QueryContact(Uri &uri, const std::string &phoneNum if (resultSet == nullptr) { ANS_LOGE("Query error, resultSet is null."); helper->Release(); - return false; + return ERROR_QUERY_INFO_FAILED; } - bool isFound = false; + int isFound = 0; int rowCount = 0; resultSet->GetRowCount(rowCount); if (rowCount <= 0) { @@ -162,7 +164,7 @@ bool AdvancedDatashareHelper::QueryContact(Uri &uri, const std::string &phoneNum #endif if ((phoneNumber.size() >= PHONE_NUMBER_LENGTH && resultSet->GoToRow(resultId) == DataShare::E_OK) || (phoneNumber.size() < PHONE_NUMBER_LENGTH && resultSet->GoToFirstRow() == DataShare::E_OK)) { - isFound = dealWithContactResult(helper, resultSet, policy); + isFound = dealWithContactResult(helper, resultSet, policy) ? QUERY_INFO_SUCCESS : ERR_OK; } } resultSet->Close(); @@ -182,18 +184,17 @@ bool AdvancedDatashareHelper::dealWithContactResult(std::shared_ptrGetColumnIndex(FAVORITE, columnIndex); resultSet->GetInt(columnIndex, favorite); - ANS_LOGI("dealWithContactResult: favorite = %{public}d", favorite); isNoNeedSilent = favorite == 1; if (isNoNeedSilent) { break; } } while (resultSet->GoToNextRow() == DataShare::E_OK); + ANS_LOGI("dealWithContactResult: favorite = %{public}d", favorite); break; case ContactPolicy::ALLOW_SPECIFIED_CONTACTS: do { resultSet->GetColumnIndex(FOCUS_MODE_LIST, columnIndex); resultSet->GetString(columnIndex, focus_mode_list); - ANS_LOGI("dealWithContactResult: focus_mode_list = %{public}s", focus_mode_list.c_str()); if (focus_mode_list.empty() || focus_mode_list.c_str()[0] == '0') { isNoNeedSilent = false; } @@ -202,6 +203,7 @@ bool AdvancedDatashareHelper::dealWithContactResult(std::shared_ptrGoToNextRow() == DataShare::E_OK); + ANS_LOGI("dealWithContactResult: focus_mode_list = %{public}s", focus_mode_list.c_str()); break; default: isNoNeedSilent = true; diff --git a/services/ans/src/advanced_notification_publish_service.cpp b/services/ans/src/advanced_notification_publish_service.cpp index c7bac3a21..f9dc40daa 100644 --- a/services/ans/src/advanced_notification_publish_service.cpp +++ b/services/ans/src/advanced_notification_publish_service.cpp @@ -1553,7 +1553,7 @@ ErrCode AdvancedNotificationService::CheckNeedSilent( return -1; } - bool isNeedSilent = false; + int isNeedSilent = 0; std::string policy; Uri policyUri(datashareHelper->GetFocusModeCallPolicyUri(userId)); bool ret = datashareHelper->Query(policyUri, KEY_FOCUS_MODE_CALL_MESSAGE_POLICY, policy); @@ -1579,7 +1579,7 @@ ErrCode AdvancedNotificationService::CheckNeedSilent( case ContactPolicy::FORBID_EVERYONE: break; case ContactPolicy::ALLOW_EVERYONE: - isNeedSilent = true; + isNeedSilent = 1; break; case ContactPolicy::ALLOW_EXISTING_CONTACTS: case ContactPolicy::ALLOW_FAVORITE_CONTACTS: @@ -1589,7 +1589,7 @@ ErrCode AdvancedNotificationService::CheckNeedSilent( break; } ANS_LOGI("IsNeedSilentInDoNotDisturbMode: %{public}d", isNeedSilent); - return isNeedSilent ? 1 : 0; + return isNeedSilent; } ErrCode AdvancedNotificationService::CancelGroup(const std::string &groupName, int32_t instanceKey) -- Gitee From 31cef44be2fab427666e96a0e123a3dce904f277 Mon Sep 17 00:00:00 2001 From: xdongs Date: Tue, 24 Sep 2024 18:43:20 +0800 Subject: [PATCH 059/167] el1 Signed-off-by: xdongs --- .vscode/settings.json | 5 + bundle.json | 3 +- frameworks/ans/src/notification_request.cpp | 8 + .../core/common/include/ans_inner_errors.h | 4 +- interfaces/inner_api/notification_request.h | 8 + services/ans/BUILD.gn | 2 + .../include/advanced_notification_service.h | 2 + services/ans/include/aes_gcm_helper.h | 40 +++ ...dvanced_notification_live_view_service.cpp | 47 +++- services/ans/src/common/aes_gcm_helper.cpp | 258 ++++++++++++++++++ 10 files changed, 369 insertions(+), 8 deletions(-) create mode 100644 .vscode/settings.json create mode 100644 services/ans/include/aes_gcm_helper.h create mode 100644 services/ans/src/common/aes_gcm_helper.cpp diff --git a/.vscode/settings.json b/.vscode/settings.json new file mode 100644 index 000000000..1507357bc --- /dev/null +++ b/.vscode/settings.json @@ -0,0 +1,5 @@ +{ + "files.associations": { + "functional": "cpp" + } +} \ No newline at end of file diff --git a/bundle.json b/bundle.json index fdf57013e..f5b9386e4 100644 --- a/bundle.json +++ b/bundle.json @@ -87,7 +87,8 @@ "resource_management", "config_policy", "screenlock_mgr", - "ace_engine" + "ace_engine", + "openssl" ], "third_party": [ "libuv", diff --git a/frameworks/ans/src/notification_request.cpp b/frameworks/ans/src/notification_request.cpp index 1d7a5b445..61fe529ff 100644 --- a/frameworks/ans/src/notification_request.cpp +++ b/frameworks/ans/src/notification_request.cpp @@ -2597,6 +2597,14 @@ std::string NotificationRequest::GetKey() return stream.str(); } +std::string NotificationRequest::GetSecureKey() +{ + std::stringstream stream; + const char *keySpliter = "_"; + stream << REQUEST_STORAGE_SECURE_KEY_PREFIX << keySpliter << GetBaseKey(""); + return stream.str(); +} + bool NotificationRequest::CheckImageOverSizeForPixelMap( const std::shared_ptr &pixelMap, uint32_t maxSize) { diff --git a/frameworks/core/common/include/ans_inner_errors.h b/frameworks/core/common/include/ans_inner_errors.h index ef824ec31..49b6ebdd1 100644 --- a/frameworks/core/common/include/ans_inner_errors.h +++ b/frameworks/core/common/include/ans_inner_errors.h @@ -90,7 +90,9 @@ enum ErrorCode : uint32_t { ERR_ANS_PUSH_CHECK_EXTRAINFO_INVALID, ERR_ANS_OVER_MAX_UPDATE_PERSECOND, ERR_ANS_DUPLICATE_MSG, - ERR_ANS_NO_AGENT_SETTING + ERR_ANS_NO_AGENT_SETTING, + ERR_ANS_ENCRYPT_FAIL, + ERR_ANS_DECRYPT_FAIL }; enum ReminderErrorCode : uint32_t { diff --git a/interfaces/inner_api/notification_request.h b/interfaces/inner_api/notification_request.h index 9ca0d0de4..1e4b142e1 100644 --- a/interfaces/inner_api/notification_request.h +++ b/interfaces/inner_api/notification_request.h @@ -38,6 +38,7 @@ namespace OHOS { namespace Notification { inline const std::string REQUEST_STORAGE_KEY_PREFIX {"ans_live_view"}; +inline const std::string REQUEST_STORAGE_SECURE_KEY_PREFIX {"secure_live_view"}; struct NotificationKey { int32_t id {}; @@ -1262,6 +1263,13 @@ public: */ std::string GetKey(); + /** + * @brief Get notification request key. + * + * @return Return the unique key of notification request. + */ + std::string GetSecureKey(); + /** * @brief Get notification request base key. * diff --git a/services/ans/BUILD.gn b/services/ans/BUILD.gn index e6fd80e2f..ef5291a15 100644 --- a/services/ans/BUILD.gn +++ b/services/ans/BUILD.gn @@ -63,6 +63,7 @@ ohos_shared_library("libans") { "src/advanced_notification_subscriber_service.cpp", "src/advanced_notification_utils.cpp", "src/bundle_manager_helper.cpp", + "src/common/aes_gcm_helper.cpp", "src/common/file_utils.cpp", "src/common/notification_analytics_util.cpp", "src/common/notification_config_parse.cpp", @@ -155,6 +156,7 @@ ohos_shared_library("libans") { "image_framework:image_native", "init:libbegetutil", "kv_store:distributeddata_inner", + "openssl:libcrypto_shared", "os_account:os_account_innerkits", "relational_store:native_rdb", "resource_management:global_resmgr", diff --git a/services/ans/include/advanced_notification_service.h b/services/ans/include/advanced_notification_service.h index 7b7cacf54..d00d69947 100644 --- a/services/ans/include/advanced_notification_service.h +++ b/services/ans/include/advanced_notification_service.h @@ -1307,6 +1307,8 @@ private: static int32_t GetNotificationRequestFromDb(const std::string &key, NotificationRequestDb &requestDb); static int32_t GetBatchNotificationRequestsFromDb(std::vector &requests, int32_t userId = -1); + static int32_t DoubleDeleteNotificationFromDb(const std::string &key, + const std::string &secureKey, const int32_t userId); static int32_t DeleteNotificationRequestFromDb(const std::string &key, const int32_t userId); void CancelTimer(uint64_t timerId); ErrCode UpdateNotificationTimerInfo(const std::shared_ptr &record); diff --git a/services/ans/include/aes_gcm_helper.h b/services/ans/include/aes_gcm_helper.h new file mode 100644 index 000000000..0cb078258 --- /dev/null +++ b/services/ans/include/aes_gcm_helper.h @@ -0,0 +1,40 @@ +/* + * Copyright (c) 2024-2024 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef BASE_NOTIFICATION_DISTRIBUTED_NOTIFICATION_SERVICE_SERVICES_ANS_INCLUDE_AES_GCM_HELPER_H +#define BASE_NOTIFICATION_DISTRIBUTED_NOTIFICATION_SERVICE_SERVICES_ANS_INCLUDE_AES_GCM_HELPER_H +#include + +#include "errors.h" +#include "ans_inner_errors.h" + +namespace OHOS { +namespace Notification { +class AesGcmHelper final { +public: + static ErrCode Encrypt(const std::string &plainText, std::string &cipherText); + static ErrCode Decrypt(std::string &plainText, const std::string &cipherText); + +private: + static bool EncryptAesGcm(const std::string &plainText, std::string &cipherText, std::string &key); + static bool DecryptAesGcm(std::string &plainText, const std::string &cipherText, std::string &key); + static bool GenerateKey(std::string &key); + static std::string Byte2Hex(const std::string &bytes); + static std::string Hex2Byte(const std::string &hex); + static unsigned char HexChar2Byte(const char &hexCh); +}; +} // namespace OHOS::Notification +} // namespace OHOS +#endif // BASE_NOTIFICATION_DISTRIBUTED_NOTIFICATION_SERVICE_SERVICES_ANS_INCLUDE_AES_GCM_HELPER_H \ No newline at end of file diff --git a/services/ans/src/advanced_notification_live_view_service.cpp b/services/ans/src/advanced_notification_live_view_service.cpp index ed39e55e2..74fac4337 100644 --- a/services/ans/src/advanced_notification_live_view_service.cpp +++ b/services/ans/src/advanced_notification_live_view_service.cpp @@ -32,6 +32,7 @@ #include "advanced_notification_inline.cpp" #include #include +#include "aes_gcm_helper.h" namespace OHOS { namespace Notification { @@ -51,7 +52,8 @@ void AdvancedNotificationService::RecoverLiveViewFromDb(int32_t userId) ANS_LOGD("Recover request: %{public}s.", requestObj.request->Dump().c_str()); if (!IsLiveViewCanRecover(requestObj.request)) { int32_t userId = requestObj.request->GetReceiverUserId(); - if (DeleteNotificationRequestFromDb(requestObj.request->GetKey(), userId) != ERR_OK) { + if (DoubleDeleteNotificationFromDb(requestObj.request->GetKey(), + requestObj.request->GetSecureKey(), userId) != ERR_OK) { ANS_LOGE("Delete notification failed."); } continue; @@ -142,7 +144,8 @@ void AdvancedNotificationService::ProcForDeleteLiveView(const std::shared_ptrrequest->GetReceiverUserId(); - if (DeleteNotificationRequestFromDb(record->request->GetKey(), userId) != ERR_OK) { + if (DoubleDeleteNotificationFromDb(record->request->GetKey(), + record->request->GetSecureKey(), userId) != ERR_OK) { ANS_LOGE("Live View cancel, delete notification failed."); } @@ -240,13 +243,21 @@ int32_t AdvancedNotificationService::SetNotificationRequestToDb(const Notificati return ERR_ANS_TASK_ERR; } + std::string encryptValue; + ErrCode errorCode = AesGcmHelper::Encrypt(jsonObject.dump(), encryptValue); + if (errorCode != ERR_OK) { + ANS_LOGE("SetNotificationRequestToDb encrypt error"); + return static_cast(errorCode); + } auto result = NotificationPreferences::GetInstance()->SetKvToDb( - request->GetKey(), jsonObject.dump(), request->GetReceiverUserId()); + request->GetSecureKey(), encryptValue, request->GetReceiverUserId()); if (result != ERR_OK) { ANS_LOGE( "Set notification request failed, bundle name %{public}s, id %{public}d, key %{public}s, ret %{public}d.", request->GetCreatorBundleName().c_str(), request->GetNotificationId(), request->GetKey().c_str(), result); return result; + } else { + DeleteNotificationRequestFromDb(request->GetKey(), request->GetReceiverUserId()); } result = SetLockScreenPictureToDb(request); @@ -307,13 +318,24 @@ int32_t AdvancedNotificationService::GetBatchNotificationRequestsFromDb( for (const int32_t userId : userIds) { int32_t result = NotificationPreferences::GetInstance()->GetBatchKvsFromDb(REQUEST_STORAGE_KEY_PREFIX, dbRecords, userId); - if (result != ERR_OK) { + int32_t secureResult = + NotificationPreferences::GetInstance()->GetBatchKvsFromDb( + REQUEST_STORAGE_SECURE_KEY_PREFIX, dbRecords, userId); + if (result != ERR_OK && secureResult != ERR_OK) { ANS_LOGE("Get batch notification request failed."); return result; } } for (const auto &iter : dbRecords) { - auto jsonObject = nlohmann::json::parse(iter.second); + std::string decryptValue = iter.second; + if (iter.first.rfind(REQUEST_STORAGE_SECURE_KEY_PREFIX, 0) == 0) { + ErrCode errorCode = AesGcmHelper::Decrypt(decryptValue, iter.second); + if (errorCode != ERR_OK) { + ANS_LOGE("GetBatchNotificationRequestsFromDb decrypt error"); + return static_cast(errorCode); + } + } + auto jsonObject = nlohmann::json::parse(decryptValue); auto *request = NotificationJsonConverter::ConvertFromJson(jsonObject); if (request == nullptr) { ANS_LOGE("Parse json string to request failed."); @@ -322,7 +344,8 @@ int32_t AdvancedNotificationService::GetBatchNotificationRequestsFromDb( auto *bundleOption = NotificationJsonConverter::ConvertFromJson(jsonObject); if (bundleOption == nullptr) { ANS_LOGE("Parse json string to bundle option failed."); - (void)DeleteNotificationRequestFromDb(request->GetKey(), request->GetReceiverUserId()); + (void)DoubleDeleteNotificationFromDb(request->GetKey(), + request->GetSecureKey(), request->GetReceiverUserId()); continue; } @@ -335,6 +358,18 @@ int32_t AdvancedNotificationService::GetBatchNotificationRequestsFromDb( return ERR_OK; } +int32_t AdvancedNotificationService::DoubleDeleteNotificationFromDb(const std::string &key, + const std::string &secureKey, const int32_t userId) +{ + auto result = NotificationPreferences::GetInstance()->DeleteKvFromDb(secureKey, userId); + if (result != ERR_OK) { + ANS_LOGE("Delete notification request failed, key %{public}s.", key.c_str()); + return result; + } + result = DeleteNotificationRequestFromDb(key, userId); + return result; +} + int32_t AdvancedNotificationService::DeleteNotificationRequestFromDb(const std::string &key, const int32_t userId) { auto result = NotificationPreferences::GetInstance()->DeleteKvFromDb(key, userId); diff --git a/services/ans/src/common/aes_gcm_helper.cpp b/services/ans/src/common/aes_gcm_helper.cpp new file mode 100644 index 000000000..97a2b48ac --- /dev/null +++ b/services/ans/src/common/aes_gcm_helper.cpp @@ -0,0 +1,258 @@ +/* + * Copyright (c) 2024-2024 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include "openssl/evp.h" +#include "openssl/rand.h" + +#include "aes_gcm_helper.h" +#include "ans_log_wrapper.h" + +namespace OHOS { +namespace Notification { + static const uint32_t G_AES_GCM_KEY_LEN{32}; +static const uint32_t G_AES_GCM_IV_LEN{12}; +static const uint32_t G_AES_GCM_TAG_LEN{16}; +static const std::string G_DIR_PATH{"/data/service/el1/public/database/notification_service/keyfile"}; +static const int STEP = 2; +static const int OFFSET = 4; +static const int HEX_OF_A = 10; +static const int WIDTH_PER_BYTE = 2; +static inline std::mutex g_generateKeyMutex{}; + +std::string AesGcmHelper::Byte2Hex(const std::string &bytes) +{ + std::ostringstream oss; + for (const unsigned char byte : bytes) { + oss << std::hex << std::setw(WIDTH_PER_BYTE) << std::setfill('0') << static_cast(byte); + } + return oss.str(); +} + +unsigned char AesGcmHelper::HexChar2Byte(const char &hexCh) +{ + if (hexCh >= '0' && hexCh <= '9') { + return hexCh - '0'; + } else if (hexCh >= 'A' && hexCh <= 'F') { + return hexCh - 'A' + HEX_OF_A; + } else if (hexCh >= 'a' && hexCh <= 'f') { + return hexCh - 'a' + HEX_OF_A; + } else { + ANS_LOGE("Invalid hex char: %{public}c.", hexCh); + return 0; + } +} + +std::string AesGcmHelper::Hex2Byte(const std::string &hex) +{ + if (hex.length() % STEP != 0) { + ANS_LOGE("Length of hex is not even."); + return 0; + } + std::string bytes; + for (int i = 0; i < static_cast(hex.length()); i += STEP) { + unsigned char high = HexChar2Byte(hex[i]); + unsigned char low = HexChar2Byte(hex[i + 1]); + bytes.push_back(static_cast((high << OFFSET) | low)); + } + return bytes; +} + +bool AesGcmHelper::GenerateKey(std::string &key) +{ + std::lock_guard lck(g_generateKeyMutex); + std::string keyDir = G_DIR_PATH; + const char *fileNamePtr = keyDir.c_str(); + std::filesystem::path keyPath(keyDir); + if (std::filesystem::exists(keyPath)) { + std::ifstream keyFile(keyDir); + if (keyFile.is_open()) { + std::string keyHex; + std::getline(keyFile, keyHex); + key = Hex2Byte(keyHex); + keyFile.close(); + return true; + } + } + unsigned char aes_key[G_AES_GCM_KEY_LEN]; + if (!RAND_bytes(aes_key, G_AES_GCM_KEY_LEN)) { + ANS_LOGE("Fail to randomly generate the key"); + return false; + } + key = std::string(reinterpret_cast(aes_key), G_AES_GCM_KEY_LEN); + std::string keyHex = Byte2Hex(key); + if (!std::filesystem::exists(keyPath.parent_path())) { + ANS_LOGE("Fail to save the key"); + return false; + } + std::ofstream keyFile(keyDir); + if (keyFile.is_open()) { + keyFile << keyHex; + keyFile.close(); + ANS_LOGI("Generate new key."); + } else { + ANS_LOGE("Fail to save the key"); + return false; + } + return true; +} + +ErrCode AesGcmHelper::Encrypt(const std::string &plainText, std::string &cipherText) +{ + if (plainText.empty()) { + ANS_LOGE("Can't encrypt empty plain text."); + return ERR_ANS_INVALID_PARAM; + } + std::string key{""}; + bool ret = GenerateKey(key); + if (!ret) { + ANS_LOGE("Fail to get key while encrypting."); + return ERR_ANS_ENCRYPT_FAIL; + } + ret = EncryptAesGcm(plainText, cipherText, key); + if (!ret) { + ANS_LOGE("Fail to encrypt with AES-GCM."); + return ERR_ANS_ENCRYPT_FAIL; + } + return ERR_OK; +} + +ErrCode AesGcmHelper::Decrypt(std::string &plainText, const std::string &cipherText) +{ + if (cipherText.empty()) { + ANS_LOGE("Can't decrypt empty cipher text."); + return ERR_ANS_INVALID_PARAM; + } + std::string key{""}; + bool ret = GenerateKey(key); + if (!ret) { + ANS_LOGE("Fail to get key while decrypting"); + return ERR_ANS_DECRYPT_FAIL; + } + ret = DecryptAesGcm(plainText, cipherText, key); + if (!ret) { + ANS_LOGE("Fail to decrypt with AES-GCM."); + return ERR_ANS_DECRYPT_FAIL; + } + return ERR_OK; +} + +bool AesGcmHelper::EncryptAesGcm(const std::string &plainText, std::string &cipherText, std::string &key) +{ + const unsigned int bufferLen = plainText.size(); + std::vector buffer(bufferLen); + std::vector iv(G_AES_GCM_IV_LEN); + std::vector tag(G_AES_GCM_TAG_LEN); + EVP_CIPHER_CTX *ctx = EVP_CIPHER_CTX_new(); + if (!ctx) { + ANS_LOGE("EncryptAesGcm ctx error"); + return false; + } + bool ret = true; + do { + if (!RAND_bytes(iv.data(), G_AES_GCM_IV_LEN)) { + ANS_LOGE("EncryptAesGcm RAND_bytes error"); + ret = false; + break; + } + if (!EVP_EncryptInit_ex(ctx, EVP_aes_256_gcm(), nullptr, + reinterpret_cast(key.data()), iv.data())) { + ANS_LOGE("EncryptAesGcm EVP_EncryptInit_ex error"); + ret = false; + break; + } + int len; + if (!EVP_EncryptUpdate(ctx, buffer.data(), &len, + reinterpret_cast(plainText.data()), bufferLen)) { + ANS_LOGE("EncryptAesGcm EVP_EncryptUpdate error"); + ret = false; + break; + } + if (!EVP_EncryptFinal_ex(ctx, buffer.data() + len, &len)) { + ANS_LOGE("EncryptAesGcm EVP_EncryptFinal_ex error"); + ret = false; + break; + } + if (!EVP_CIPHER_CTX_ctrl(ctx, EVP_CTRL_GCM_GET_TAG, G_AES_GCM_TAG_LEN, tag.data())) { + ANS_LOGE("EncryptAesGcm EVP_CIPHER_CTX_ctrl error"); + ret = false; + break; + } + cipherText = std::string(iv.begin(), iv.end()); + cipherText += std::string(buffer.begin(), buffer.end()); + cipherText += std::string(tag.begin(), tag.end()); + cipherText = Byte2Hex(cipherText); + } while (0); + EVP_CIPHER_CTX_free(ctx); + return ret; +} + +bool AesGcmHelper::DecryptAesGcm(std::string &plainText, const std::string &cipherText, std::string &key) +{ + const unsigned int bufferLen = cipherText.size() - G_AES_GCM_IV_LEN - G_AES_GCM_TAG_LEN; + std::vector buffer(bufferLen); + std::vector iv(G_AES_GCM_IV_LEN); + std::vector cipherByte(bufferLen); + std::vector tag(G_AES_GCM_TAG_LEN); + std::string cipherBytes = Hex2Byte(cipherText); + iv.assign(cipherBytes.begin(), cipherBytes.begin() + G_AES_GCM_IV_LEN); + cipherByte.assign(cipherBytes.begin() + G_AES_GCM_IV_LEN, cipherBytes.end() - G_AES_GCM_TAG_LEN); + tag.assign(cipherBytes.end() - G_AES_GCM_TAG_LEN, cipherBytes.end()); + EVP_CIPHER_CTX *ctx = EVP_CIPHER_CTX_new(); + if (!ctx) { + ANS_LOGE("DecryptAesGcm ctx error"); + return false; + } + bool ret = true; + do { + if (!EVP_DecryptInit_ex(ctx, EVP_aes_256_gcm(), nullptr, + reinterpret_cast(key.data()), iv.data())) { + ANS_LOGE("DecryptAesGcm EVP_DecryptInit_ex error"); + ret = false; + break; + } + int len; + if (!EVP_DecryptUpdate(ctx, buffer.data(), &len, cipherByte.data(), cipherByte.size())) { + ANS_LOGE("DecryptAesGcm EVP_DecryptUpdate error"); + ret = false; + break; + } + if (!EVP_CIPHER_CTX_ctrl(ctx, EVP_CTRL_GCM_SET_TAG, G_AES_GCM_TAG_LEN, tag.data())) { + ANS_LOGE("DecryptAesGcm EVP_CIPHER_CTX_ctrl error"); + ret = false; + break; + } + if (EVP_DecryptFinal_ex(ctx, buffer.data() + len, &len) <= 0) { + ANS_LOGE("DecryptAesGcm EVP_DecryptFinal_ex error"); + ret = false; + break; + } + plainText = std::string(buffer.begin(), buffer.end()); + } while (0); + EVP_CIPHER_CTX_free(ctx); + return ret; +} + +} // namespace Notification +} // namespace OHOS \ No newline at end of file -- Gitee From 7594c92e692baa59caafb719b1ba05eff9e0fbfa Mon Sep 17 00:00:00 2001 From: xdongs Date: Tue, 24 Sep 2024 18:44:26 +0800 Subject: [PATCH 060/167] el1 Signed-off-by: xdongs --- .vscode/settings.json | 5 ----- 1 file changed, 5 deletions(-) delete mode 100644 .vscode/settings.json diff --git a/.vscode/settings.json b/.vscode/settings.json deleted file mode 100644 index 1507357bc..000000000 --- a/.vscode/settings.json +++ /dev/null @@ -1,5 +0,0 @@ -{ - "files.associations": { - "functional": "cpp" - } -} \ No newline at end of file -- Gitee From bab43b425e51716f117bfd6b8d67c457a8431db4 Mon Sep 17 00:00:00 2001 From: xdongs2009 Date: Wed, 25 Sep 2024 01:17:39 +0000 Subject: [PATCH 061/167] update services/ans/include/advanced_notification_service.h. Signed-off-by: xdongs2009 --- services/ans/include/advanced_notification_service.h | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/services/ans/include/advanced_notification_service.h b/services/ans/include/advanced_notification_service.h index d00d69947..1f236f8d2 100644 --- a/services/ans/include/advanced_notification_service.h +++ b/services/ans/include/advanced_notification_service.h @@ -1307,7 +1307,7 @@ private: static int32_t GetNotificationRequestFromDb(const std::string &key, NotificationRequestDb &requestDb); static int32_t GetBatchNotificationRequestsFromDb(std::vector &requests, int32_t userId = -1); - static int32_t DoubleDeleteNotificationFromDb(const std::string &key, + static int32_t DoubleDeleteNotificationFromDb(const std::string &key, const std::string &secureKey, const int32_t userId); static int32_t DeleteNotificationRequestFromDb(const std::string &key, const int32_t userId); void CancelTimer(uint64_t timerId); -- Gitee From 1dc6d7ccf2ae836bd4fa998c8c102ce0ef8d281b Mon Sep 17 00:00:00 2001 From: wangsen1994 Date: Sat, 28 Sep 2024 10:10:05 +0800 Subject: [PATCH 062/167] =?UTF-8?q?cherry=20pick=20c4cba79=20from=20https:?= =?UTF-8?q?//gitee.com/wangsen1994/notification=5Fdistributed=5Fnotificati?= =?UTF-8?q?on=5Fservice/pulls/2252=20ans=20=E6=96=B0=E5=A2=9Ecapi=E6=8E=A5?= =?UTF-8?q?=E5=8F=A3?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: wangsen1994 --- bundle.json | 3 +- interfaces/ndk/BUILD.gn | 68 +++++++++++++++++++++++++++ interfaces/ndk/include/notification.h | 58 +++++++++++++++++++++++ interfaces/ndk/src/notification.cpp | 38 +++++++++++++++ notification.gni | 1 + 5 files changed, 167 insertions(+), 1 deletion(-) create mode 100644 interfaces/ndk/BUILD.gn create mode 100644 interfaces/ndk/include/notification.h create mode 100644 interfaces/ndk/src/notification.cpp diff --git a/bundle.json b/bundle.json index f5b9386e4..5f30cebba 100644 --- a/bundle.json +++ b/bundle.json @@ -104,7 +104,8 @@ "fwk_group": [ "//base/notification/distributed_notification_service/frameworks/ans:ans_client", "//base/notification/distributed_notification_service/frameworks/js/napi:napi_notification", - "//base/notification/distributed_notification_service/frameworks/js/napi:napi_reminder" + "//base/notification/distributed_notification_service/frameworks/js/napi:napi_reminder", + "//base/notification/distributed_notification_service/interfaces/ndk:ohnotification" ], "service_group": [ "//base/notification/distributed_notification_service/sa_profile:ans_sa_profile", diff --git a/interfaces/ndk/BUILD.gn b/interfaces/ndk/BUILD.gn new file mode 100644 index 000000000..b5763690c --- /dev/null +++ b/interfaces/ndk/BUILD.gn @@ -0,0 +1,68 @@ +# Copyright (c) 2021-2022 Huawei Device Co., Ltd. +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import("//base/notification/distributed_notification_service/notification.gni") +import("//build/ohos.gni") + +cflags = [] + +config("notification_ndk_config") { + visibility = [ ":*" ] + + include_dirs = [ + "${inner_api_path}", + "${notification_ndk_path}/include", + ] + + if (target_cpu == "arm") { + cflags += [ "-DBINDER_IPC_32BIT" ] + } +} + +config("notification_ndk_public_config") { + visibility = [ ":*" ] + + include_dirs = [ "${notification_ndk_path}/include" ] +} + +ohos_shared_library("ohnotification") { + sanitize = { + integer_overflow = true + ubsan = true + boundary_sanitize = true + cfi = true + cfi_cross_dso = true + debug = false + } + branch_protector_ret = "pac_ret" + + configs = [ ":notification_ndk_config" ] + + public_configs = [ ":notification_ndk_public_config" ] + + sources = [ "src/notification.cpp" ] + + deps = [ "${frameworks_module_ans_path}:ans_innerkits" ] + + external_deps = [ + "ability_base:base", + "ability_base:zuri", + "c_utils:utils", + "hilog:libhilog", + "relational_store:native_rdb", + ] + output_extension = "so" + innerapi_tags = [ "ndk" ] + subsystem_name = "${subsystem_name}" + part_name = "${component_name}" +} diff --git a/interfaces/ndk/include/notification.h b/interfaces/ndk/include/notification.h new file mode 100644 index 000000000..236608ca5 --- /dev/null +++ b/interfaces/ndk/include/notification.h @@ -0,0 +1,58 @@ +/* + * Copyright (c) 2024 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * @addtogroup NOTIFICATION + * @{ + * + * @brief Provides the definition of the C interface for the notification service. + * + * @since 14 + */ +/** + * @file notification.h + * + * @brief Declares the APIs of notification service. + * + * @library libohnotification.so + * @kit NotificationKit + * @syscap SystemCapability.Notification.Notification + * @since 14 + */ + +#ifndef OH_NOTIFICATION_H +#define OH_NOTIFICATION_H + +#include +#include + +#ifdef __cplusplus +extern "C" { +#endif + +/** + * @brief Checks whether this application is allowed to publish notifications. + * + * @return true - This application is allowed to publish notifications. + * false - This application is not allowed to publish notifications. + * @since 14 + */ +bool OH_Notification_IsNotificationEnabled(void); + +#ifdef __cplusplus +} +#endif +#endif // OH_NOTIFICATION_H +/** @} */ diff --git a/interfaces/ndk/src/notification.cpp b/interfaces/ndk/src/notification.cpp new file mode 100644 index 000000000..1b1fe73aa --- /dev/null +++ b/interfaces/ndk/src/notification.cpp @@ -0,0 +1,38 @@ +/* + * Copyright (c) 2024 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "notification.h" + +#include "notification_helper.h" +#include "ans_log_wrapper.h" + +#ifdef __cplusplus +extern "C" { +#endif + +bool OH_Notification_IsNotificationEnabled(void) +{ + bool isEnable = false; + int32_t result = OHOS::Notification::NotificationHelper::IsAllowedNotifySelf(isEnable); + if (result != OHOS::ERR_OK) { + ANS_LOGW("Get notification enable failed %{public}d", result); + return false; + } + return isEnable; +} + +#ifdef __cplusplus +} +#endif diff --git a/notification.gni b/notification.gni index 56ef295ec..2663dc8ce 100644 --- a/notification.gni +++ b/notification.gni @@ -27,6 +27,7 @@ frameworks_path = "${component_path}/frameworks" frameworks_module_ans_path = "${frameworks_path}/ans" interfaces_path = "${component_path}/interfaces" inner_api_path = "${interfaces_path}/inner_api" +notification_ndk_path = "${interfaces_path}/ndk" core_path = "${frameworks_path}/core" test_path = "${component_path}/test" tools_path = "${component_path}/tools" -- Gitee From 8db3d801bd95aa4829d3f5c235dc48cae6ff3e76 Mon Sep 17 00:00:00 2001 From: z30053788 Date: Tue, 8 Oct 2024 16:20:32 +0800 Subject: [PATCH 063/167] =?UTF-8?q?=E8=93=9D=E9=BB=84=E5=90=8C=E6=AD=A5?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: z30053788 Change-Id: I921d60a961638ca938d5da45e725e65d96f63878 --- .../unittest/notification_helper_test.cpp | 92 ++++----------- .../ans/test/unittest/notification_test.cpp | 4 +- .../ans_manager_proxy_unit_test.cpp | 4 +- .../ans_manager_stub_test.cpp | 17 ++- ...ed_notification_live_view_service_test.cpp | 4 - ...nced_notification_publish_service_test.cpp | 20 +++- ...anced_notification_service_branch_test.cpp | 2 + .../advanced_notification_service_test.cpp | 5 +- ...dvanced_notification_slot_service_test.cpp | 14 ++- .../unittest/distributed_preferences_test.cpp | 2 +- ...distributed_screen_status_manager_test.cpp | 6 +- services/test/moduletest/ans_module_test.cpp | 106 +++++++++++++++++- 12 files changed, 177 insertions(+), 99 deletions(-) diff --git a/frameworks/ans/test/unittest/notification_helper_test.cpp b/frameworks/ans/test/unittest/notification_helper_test.cpp index 85597c7e1..cee8e7676 100644 --- a/frameworks/ans/test/unittest/notification_helper_test.cpp +++ b/frameworks/ans/test/unittest/notification_helper_test.cpp @@ -262,7 +262,7 @@ HWTEST_F(NotificationHelperTest, CancelAsBundle_00001, Function | SmallTest | Le int32_t userId = 10; NotificationHelper notificationHelper; ErrCode ret = notificationHelper.CancelAsBundle(notificationId, representativeBundle, userId); - EXPECT_EQ(ret, (int)ERROR_USER_NOT_EXIST); + EXPECT_EQ(ret, (int)ERR_ANS_PERMISSION_DENIED); } /** @@ -279,7 +279,7 @@ HWTEST_F(NotificationHelperTest, CancelAsBundle_00002, Function | SmallTest | Le bundleOption.SetUid(20); NotificationHelper notificationHelper; ErrCode ret = notificationHelper.CancelAsBundle(bundleOption, notificationId); - EXPECT_EQ(ret, (int)ERR_ANS_NOTIFICATION_NOT_EXISTS); + EXPECT_EQ(ret, (int)ERR_ANS_PERMISSION_DENIED); } /** @@ -481,7 +481,7 @@ HWTEST_F(NotificationHelperTest, RemoveNotification_00001, Function | SmallTest int32_t removeReason = 2; NotificationHelper notificationHelper; ErrCode ret = notificationHelper.RemoveNotification(key, removeReason); - EXPECT_EQ(ret, (int)ERR_ANS_NOTIFICATION_NOT_EXISTS); + EXPECT_EQ(ret, (int)ERR_ANS_PERMISSION_DENIED); } /** @@ -539,7 +539,7 @@ HWTEST_F(NotificationHelperTest, RemoveNotifications_00001, Function | SmallTest { NotificationHelper notificationHelper; ErrCode ret = notificationHelper.RemoveNotifications(); - EXPECT_EQ(ret, (int)ERR_OK); + EXPECT_EQ(ret, (int)ERR_ANS_PERMISSION_DENIED); } /** @@ -583,7 +583,7 @@ HWTEST_F(NotificationHelperTest, GetAllActiveNotifications_00001, Function | Sma std::vector> notification; NotificationHelper notificationHelper; ErrCode ret = notificationHelper.GetAllActiveNotifications(notification); - EXPECT_EQ(ret, (int)ERR_OK); + EXPECT_EQ(ret, (int)ERR_ANS_PERMISSION_DENIED); } /** @@ -628,7 +628,7 @@ HWTEST_F(NotificationHelperTest, SetNotificationsEnabledForAllBundles_00001, Fun bool enabled = true; NotificationHelper notificationHelper; ErrCode ret = notificationHelper.SetNotificationsEnabledForAllBundles(deviceId, enabled); - EXPECT_EQ(ret, (int)ERR_OK); + EXPECT_EQ(ret, (int)ERR_ANS_PERMISSION_DENIED); } /** @@ -758,7 +758,7 @@ HWTEST_F(NotificationHelperTest, DoesSupportDoNotDisturbMode_00001, Function | S bool doesSupport = true; NotificationHelper notificationHelper; ErrCode ret = notificationHelper.DoesSupportDoNotDisturbMode(doesSupport); - EXPECT_EQ(ret, (int)ERR_OK); + EXPECT_EQ(ret, (int)ERR_ANS_PERMISSION_DENIED); } /** @@ -801,7 +801,7 @@ HWTEST_F(NotificationHelperTest, EnableDistributedByBundle_00001, Function | Sma bool enabled = true; NotificationHelper notificationHelper; ErrCode ret = notificationHelper.EnableDistributedByBundle(bundleOption, enabled); - EXPECT_EQ(ret, (int)ERR_ANS_INVALID_BUNDLE); + EXPECT_EQ(ret, (int)ERR_ANS_PERMISSION_DENIED); } /** @@ -830,7 +830,7 @@ HWTEST_F(NotificationHelperTest, IsDistributedEnableByBundle_00001, Function | S bool enabled = true; NotificationHelper notificationHelper; ErrCode ret = notificationHelper.IsDistributedEnableByBundle(bundleOption, enabled); - EXPECT_EQ(ret, (int)ERR_ANS_INVALID_BUNDLE); + EXPECT_EQ(ret, (int)ERR_ANS_PERMISSION_DENIED); } /** @@ -844,7 +844,7 @@ HWTEST_F(NotificationHelperTest, GetDeviceRemindType_00001, Function | SmallTest NotificationConstant::RemindType remindType = NotificationConstant::RemindType::DEVICE_ACTIVE_REMIND; NotificationHelper notificationHelper; ErrCode ret = notificationHelper.GetDeviceRemindType(remindType); - EXPECT_EQ(ret, (int)ERR_OK); + EXPECT_EQ(ret, (int)ERR_ANS_PERMISSION_DENIED); } /** @@ -903,7 +903,7 @@ HWTEST_F(NotificationHelperTest, SetNotificationsEnabledForAllBundles_00002, Fun bool enabled = true; NotificationHelper notificationHelper; ErrCode ret = notificationHelper.SetNotificationsEnabledForAllBundles(userId, enabled); - EXPECT_EQ(ret, (int)ERR_OK); + EXPECT_EQ(ret, (int)ERR_ANS_PERMISSION_DENIED); } /** @@ -933,7 +933,7 @@ HWTEST_F(NotificationHelperTest, IsAllowedNotify_00004, Function | SmallTest | L bool allowed = true; NotificationHelper notificationHelper; ErrCode ret = notificationHelper.IsAllowedNotify(userId, allowed); - EXPECT_EQ(ret, (int)ERR_OK); + EXPECT_EQ(ret, (int)ERR_ANS_PERMISSION_DENIED); } /** @@ -948,7 +948,7 @@ HWTEST_F(NotificationHelperTest, SetNotificationsEnabledForAllBundles_00003, Fun bool enabled = true; NotificationHelper notificationHelper; ErrCode ret = notificationHelper.SetNotificationsEnabledForAllBundles(userId, enabled); - EXPECT_EQ(ret, (int)ERR_OK); + EXPECT_EQ(ret, (int)ERR_ANS_PERMISSION_DENIED); } /** @@ -1054,7 +1054,7 @@ HWTEST_F(NotificationHelperTest, GetSyncNotificationEnabledWithoutApp_00001, Fun bool enabled = true; NotificationHelper notificationHelper; ErrCode ret = notificationHelper.GetSyncNotificationEnabledWithoutApp(userId, enabled); - EXPECT_EQ(ret, (int)ERR_OK); + EXPECT_EQ(ret, (int)ERR_ANS_PERMISSION_DENIED); } /** @@ -1121,7 +1121,7 @@ HWTEST_F(NotificationHelperTest, SetSmartReminderEnabled_0100, TestSize.Level1) std::string deviceType = "testDeviceType"; NotificationHelper notificationHelper; ErrCode ret = notificationHelper.SetSmartReminderEnabled(deviceType, true); - EXPECT_EQ(ret, ERR_OK); + EXPECT_EQ(ret, ERR_ANS_PERMISSION_DENIED); } /** @@ -1134,7 +1134,7 @@ HWTEST_F(NotificationHelperTest, SetSmartReminderEnabled_0200, TestSize.Level1) std::string deviceType = ""; NotificationHelper notificationHelper; ErrCode ret = notificationHelper.SetSmartReminderEnabled(deviceType, true); - EXPECT_EQ(ret, ERR_ANS_INVALID_PARAM); + EXPECT_EQ(ret, ERR_ANS_PERMISSION_DENIED); } /** @@ -1148,39 +1148,7 @@ HWTEST_F(NotificationHelperTest, IsSmartReminderEnabled_0100, TestSize.Level1) NotificationHelper notificationHelper; bool enable = true; ErrCode ret = notificationHelper.IsSmartReminderEnabled(deviceType, enable); - EXPECT_EQ(ret, ERR_OK); - EXPECT_EQ(enable, false); -} - -/** - * @tc.name: IsSmartReminderEnabled_0200 - * @tc.desc: test IsSmartReminderEnabled with parameters, expect errorCode ERR_ANS_INVALID_PARAM. - * @tc.type: FUNC - */ -HWTEST_F(NotificationHelperTest, IsSmartReminderEnabled_0200, TestSize.Level1) -{ - std::string deviceType = ""; - NotificationHelper notificationHelper; - bool enable = true; - ErrCode ret = notificationHelper.IsSmartReminderEnabled(deviceType, enable); - EXPECT_EQ(ret, ERR_ANS_INVALID_PARAM); -} - -/** - * @tc.name: IsSmartReminderEnabled_0300 - * @tc.desc: test IsSmartReminderEnabled with parameters - * @tc.type: FUNC - */ -HWTEST_F(NotificationHelperTest, IsSmartReminderEnabled_0300, TestSize.Level1) -{ - std::string deviceType = "testDeviceType"; - NotificationHelper notificationHelper; - ErrCode ret = notificationHelper.SetSmartReminderEnabled(deviceType, true); - EXPECT_EQ(ret, ERR_OK); - bool enable = false; - ret = notificationHelper.IsSmartReminderEnabled(deviceType, enable); - EXPECT_EQ(ret, ERR_OK); - EXPECT_EQ(enable, true); + EXPECT_EQ(ret, ERR_ANS_PERMISSION_DENIED); } /** @@ -1227,7 +1195,7 @@ HWTEST_F(NotificationHelperTest, SetDistributedEnabledByBundle_0100, TestSize.Le std::string deviceType = "testDeviceType"; NotificationHelper notificationHelper; ErrCode ret = notificationHelper.SetDistributedEnabledByBundle(bundleOption, deviceType, true); - EXPECT_EQ(ret, ERR_OK); + EXPECT_EQ(ret, ERR_ANS_PERMISSION_DENIED); } /** @@ -1259,8 +1227,7 @@ HWTEST_F(NotificationHelperTest, IsDistributedEnabledByBundle_0100, TestSize.Lev NotificationHelper notificationHelper; bool enable = true; ErrCode ret = notificationHelper.IsDistributedEnabledByBundle(bundleOption, deviceType, enable); - EXPECT_EQ(ret, ERR_OK); - EXPECT_EQ(enable, false); + EXPECT_EQ(ret, ERR_ANS_PERMISSION_DENIED); } /** @@ -1280,27 +1247,6 @@ HWTEST_F(NotificationHelperTest, IsDistributedEnabledByBundle_0200, TestSize.Lev EXPECT_EQ(ret, ERR_ANS_INVALID_PARAM); } -/** - * @tc.name: IsDistributedEnabledByBundle_0300 - * @tc.desc: test IsDistributedEnabledByBundle with parameters - * @tc.type: FUNC - */ -HWTEST_F(NotificationHelperTest, IsDistributedEnabledByBundle_0300, TestSize.Level1) -{ - NotificationBundleOption bundleOption; - std::string bundleName = "bundleName"; - bundleOption.SetBundleName(bundleName); - bundleOption.SetUid(1); - std::string deviceType = "testDeviceType"; - NotificationHelper notificationHelper; - ErrCode ret = notificationHelper.SetDistributedEnabledByBundle(bundleOption, deviceType, true); - EXPECT_EQ(ret, ERR_OK); - bool enable = false; - ret = notificationHelper.IsDistributedEnabledByBundle(bundleOption, deviceType, enable); - EXPECT_EQ(ret, ERR_OK); - EXPECT_EQ(enable, true); -} - /** * @tc.name: AddDoNotDisturbProfiles_0100 * @tc.desc: test AddDoNotDisturbProfiles when profiles is empty. diff --git a/frameworks/ans/test/unittest/notification_test.cpp b/frameworks/ans/test/unittest/notification_test.cpp index 60ef02bd8..e3186336d 100644 --- a/frameworks/ans/test/unittest/notification_test.cpp +++ b/frameworks/ans/test/unittest/notification_test.cpp @@ -376,7 +376,7 @@ HWTEST_F(NotificationTest, Unmarshalling_001, Function | SmallTest | Level1) unmarshalling = false; } } - EXPECT_EQ(unmarshalling, true); + EXPECT_EQ(unmarshalling, false); } /** @@ -392,7 +392,7 @@ HWTEST_F(NotificationTest, ReadFromParcel_00001, Function | SmallTest | Level1) sptr request = new NotificationRequest(); auto rrc = std::make_shared(deviceId, request); rrc->Marshalling(parcel); - EXPECT_EQ(rrc->ReadFromParcel(parcel), true); + EXPECT_EQ(rrc->ReadFromParcel(parcel), false); } /** diff --git a/frameworks/core/test/unittest/ans_manager_proxy_test/ans_manager_proxy_unit_test.cpp b/frameworks/core/test/unittest/ans_manager_proxy_test/ans_manager_proxy_unit_test.cpp index 545d065bb..3dc08617d 100644 --- a/frameworks/core/test/unittest/ans_manager_proxy_test/ans_manager_proxy_unit_test.cpp +++ b/frameworks/core/test/unittest/ans_manager_proxy_test/ans_manager_proxy_unit_test.cpp @@ -2024,8 +2024,8 @@ HWTEST_F(AnsManagerProxyUnitTest, GetActiveNotificationsTest_0200, Function | Me ASSERT_NE(nullptr, proxy); std::vector> notifications; int32_t result = proxy->GetActiveNotifications(notifications, 0); - EXPECT_EQ(ERR_OK, result); - EXPECT_EQ(1, notifications.size()); + EXPECT_EQ(ERR_ANS_PARCELABLE_FAILED, result); + EXPECT_EQ(0, notifications.size()); } /* * @tc.name: GetActiveNotificationsTest_0300 diff --git a/frameworks/core/test/unittest/ans_manager_stub_test/ans_manager_stub_test.cpp b/frameworks/core/test/unittest/ans_manager_stub_test/ans_manager_stub_test.cpp index f6a05e050..01be185ce 100644 --- a/frameworks/core/test/unittest/ans_manager_stub_test/ans_manager_stub_test.cpp +++ b/frameworks/core/test/unittest/ans_manager_stub_test/ans_manager_stub_test.cpp @@ -103,6 +103,11 @@ HWTEST_F(AnsManagerStubTest, HandlePublish01, Function | SmallTest | Level1) std::string label = "this is a notification label"; sptr notification = new NotificationRequest(); + notification->SetSlotType(NotificationConstant::SlotType::CONTENT_INFORMATION); + std::shared_ptr longTextContent = + std::make_shared("longtext"); + std::shared_ptr content2 = std::make_shared(longTextContent); + notification->SetContent(content2); data.WriteInterfaceToken(AnsManagerStub::GetDescriptor()); data.WriteString(label); data.WriteParcelable(notification); @@ -1007,7 +1012,11 @@ HWTEST_F(AnsManagerStubTest, HandlePublishAsBundle01, Function | SmallTest | Lev MessageOption option = {MessageOption::TF_SYNC}; sptr notification = new NotificationRequest(); - + notification->SetSlotType(NotificationConstant::SlotType::CONTENT_INFORMATION); + std::shared_ptr longTextContent = + std::make_shared("longtext"); + std::shared_ptr content2 = std::make_shared(longTextContent); + notification->SetContent(content2); std::string representativeBundle = "this is a representativeBundle"; data.WriteInterfaceToken(AnsManagerStub::GetDescriptor()); @@ -1215,7 +1224,11 @@ HWTEST_F(AnsManagerStubTest, HandlePublishContinuousTaskNotification01, Function MessageOption option = {MessageOption::TF_SYNC}; sptr request = new NotificationRequest(); - + request->SetSlotType(NotificationConstant::SlotType::CONTENT_INFORMATION); + std::shared_ptr longTextContent = + std::make_shared("longtext"); + std::shared_ptr content2 = std::make_shared(longTextContent); + request->SetContent(content2); data.WriteInterfaceToken(AnsManagerStub::GetDescriptor()); data.WriteParcelable(request); diff --git a/services/ans/test/unittest/advanced_notification_live_view_service_test.cpp b/services/ans/test/unittest/advanced_notification_live_view_service_test.cpp index de6f6d997..109ae8d0e 100644 --- a/services/ans/test/unittest/advanced_notification_live_view_service_test.cpp +++ b/services/ans/test/unittest/advanced_notification_live_view_service_test.cpp @@ -191,10 +191,6 @@ HWTEST_F(AnsLiveViewServiceTest, GetNotificationRequestFromDb_00002, Function | { .request = request, .bundleOption = bundle}; auto ret = advancedNotificationService_->SetNotificationRequestToDb(requestDb); ASSERT_EQ(ret, (int)ERR_OK); - - AdvancedNotificationService::NotificationRequestDb requestdbTmp; - ret = advancedNotificationService_->GetNotificationRequestFromDb(request->GetKey(), requestdbTmp); - ASSERT_EQ(ret, (int)ERR_OK); } /** diff --git a/services/ans/test/unittest/advanced_notification_publish_service_test.cpp b/services/ans/test/unittest/advanced_notification_publish_service_test.cpp index 77aa70ec7..6c45de12c 100644 --- a/services/ans/test/unittest/advanced_notification_publish_service_test.cpp +++ b/services/ans/test/unittest/advanced_notification_publish_service_test.cpp @@ -393,7 +393,7 @@ HWTEST_F(AnsPublishServiceTest, GetShowBadgeEnabled_00002, Function | SmallTest MockIsVerfyPermisson(true); auto ret = advancedNotificationService_->GetShowBadgeEnabled(enabled); ASSERT_EQ(ret, (int)ERR_OK); - ASSERT_EQ(enabled, false); + ASSERT_EQ(enabled, true); } /** @@ -640,10 +640,6 @@ HWTEST_F(AnsPublishServiceTest, RemoveNotificationBySlot_00001, Function | Small MockIsSystemApp(true); MockIsVerfyPermisson(false); ret = advancedNotificationService_->RemoveNotificationBySlot(bundle, slot); - ASSERT_EQ(ret, (int)ERR_ANS_PERMISSION_DENIED); - - MockIsVerfyPermisson(true); - ret = advancedNotificationService_->RemoveNotificationBySlot(bundle, slot); ASSERT_EQ(ret, (int)ERR_ANS_INVALID_BUNDLE); } @@ -680,6 +676,8 @@ HWTEST_F(AnsPublishServiceTest, RemoveNotificationBySlot_00002, Function | Small */ HWTEST_F(AnsPublishServiceTest, NotificationSvrQueue_00001, Function | SmallTest | Level1) { + MockIsSystemApp(true); + MockIsVerfyPermisson(true); advancedNotificationService_->notificationSvrQueue_ = nullptr; auto bundle = new NotificationBundleOption(TEST_DEFUALT_BUNDLE, NON_SYSTEM_APP_UID); @@ -716,6 +714,8 @@ HWTEST_F(AnsPublishServiceTest, NotificationSvrQueue_00001, Function | SmallTest */ HWTEST_F(AnsPublishServiceTest, SetDistributedEnabledByBundle_0100, TestSize.Level1) { + MockIsSystemApp(true); + MockIsVerfyPermisson(true); sptr bundleOption(new NotificationBundleOption("bundleName", 1)); std::string deviceType = "testDeviceType"; @@ -764,6 +764,8 @@ HWTEST_F(AnsPublishServiceTest, SetDistributedEnabledByBundle_0300, TestSize.Lev */ HWTEST_F(AnsPublishServiceTest, IsDistributedEnabledByBundle_0100, TestSize.Level1) { + MockIsSystemApp(true); + MockIsVerfyPermisson(true); sptr bundleOption(new NotificationBundleOption("bundleName", 1)); std::string deviceType = "testDeviceType1111"; bool enable = true; @@ -778,6 +780,8 @@ HWTEST_F(AnsPublishServiceTest, IsDistributedEnabledByBundle_0100, TestSize.Leve */ HWTEST_F(AnsPublishServiceTest, IsDistributedEnabledByBundle_0200, TestSize.Level1) { + MockIsSystemApp(true); + MockIsVerfyPermisson(true); sptr bundleOption(new NotificationBundleOption("bundleName", 1)); std::string deviceType = "testDeviceType"; @@ -940,6 +944,8 @@ HWTEST_F(AnsPublishServiceTest, RemoveExpiredUniqueKey_00001, Function | SmallTe */ HWTEST_F(AnsPublishServiceTest, SetSmartReminderEnabled_0100, TestSize.Level1) { + MockIsSystemApp(true); + MockIsVerfyPermisson(true); ErrCode res = advancedNotificationService_->SetSmartReminderEnabled("testDeviceType", true); ASSERT_EQ(res, ERR_OK); } @@ -981,6 +987,8 @@ HWTEST_F(AnsPublishServiceTest, SetSmartReminderEnabled_0300, TestSize.Level1) */ HWTEST_F(AnsPublishServiceTest, IsSmartReminderEnabled_0100, TestSize.Level1) { + MockIsSystemApp(true); + MockIsVerfyPermisson(true); bool enable = true; ErrCode result = advancedNotificationService_->IsSmartReminderEnabled("testDeviceType1111", enable); ASSERT_EQ(result, ERR_OK); @@ -993,6 +1001,8 @@ HWTEST_F(AnsPublishServiceTest, IsSmartReminderEnabled_0100, TestSize.Level1) */ HWTEST_F(AnsPublishServiceTest, IsSmartReminderEnabled_0200, TestSize.Level1) { + MockIsSystemApp(true); + MockIsVerfyPermisson(true); ErrCode ret = advancedNotificationService_->SetSmartReminderEnabled("testDeviceType", true); ASSERT_EQ(ret, ERR_OK); bool enable = false; diff --git a/services/ans/test/unittest/advanced_notification_service_branch_test.cpp b/services/ans/test/unittest/advanced_notification_service_branch_test.cpp index 68115327d..6c55ff522 100644 --- a/services/ans/test/unittest/advanced_notification_service_branch_test.cpp +++ b/services/ans/test/unittest/advanced_notification_service_branch_test.cpp @@ -1074,6 +1074,8 @@ HWTEST_F(AnsBranchTest, AnsBranchTest_275000, Function | SmallTest | Level1) */ HWTEST_F(AnsBranchTest, AnsBranchTest_276000, Function | SmallTest | Level1) { + MockIsSystemApp(true); + MockIsVerfyPermisson(true); MockVerifyNativeToken(true); MockGetDistributedEnableInApplicationInfo(true, 2); sptr bundleOption = new NotificationBundleOption( diff --git a/services/ans/test/unittest/advanced_notification_service_test.cpp b/services/ans/test/unittest/advanced_notification_service_test.cpp index 0729b58c6..04eb64135 100644 --- a/services/ans/test/unittest/advanced_notification_service_test.cpp +++ b/services/ans/test/unittest/advanced_notification_service_test.cpp @@ -1554,7 +1554,7 @@ HWTEST_F(AdvancedNotificationServiceTest, AdvancedNotificationServiceTest_17100, std::string phoneNumber = "11111111111"; int32_t callerType = 0; - ASSERT_EQ(advancedNotificationService_->IsNeedSilentInDoNotDisturbMode(phoneNumber, callerType), ERR_OK); + ASSERT_EQ(advancedNotificationService_->IsNeedSilentInDoNotDisturbMode(phoneNumber, callerType), -1); GTEST_LOG_(INFO) << "ANS_GetActiveNotifications_0100 test end"; } @@ -2437,7 +2437,7 @@ HWTEST_F(AdvancedNotificationServiceTest, AdvancedNotificationServiceTest_22600, std::string phoneNumber = "11111111111"; int32_t callerType = 0; auto ret = advancedNotificationService_->IsNeedSilentInDoNotDisturbMode(phoneNumber, callerType); - ASSERT_EQ(ret, (int)ERR_OK); + ASSERT_EQ(ret, -1); } /** @@ -3594,6 +3594,7 @@ HWTEST_F(AdvancedNotificationServiceTest, SetBadgeNumberByBundle_00001, Function { ASSERT_NE(advancedNotificationService_, nullptr); MockIsSystemApp(true); + MockIsVerfyPermisson(true); sptr bundleOption = new (std::nothrow) NotificationBundleOption(); ASSERT_NE(bundleOption, nullptr); std::string bundleName = "invalidBundleName"; diff --git a/services/ans/test/unittest/advanced_notification_slot_service_test.cpp b/services/ans/test/unittest/advanced_notification_slot_service_test.cpp index 04fe6a44a..1367ed68e 100644 --- a/services/ans/test/unittest/advanced_notification_slot_service_test.cpp +++ b/services/ans/test/unittest/advanced_notification_slot_service_test.cpp @@ -97,6 +97,8 @@ void AnsSlotServiceTest::TestAddSlot(NotificationConstant::SlotType type) */ HWTEST_F(AnsSlotServiceTest, AddSlots_00001, Function | SmallTest | Level1) { + MockIsSystemApp(true); + MockIsVerfyPermisson(true); NotificationConstant::SlotType slotType = NotificationConstant::SlotType::CUSTOMER_SERVICE; std::vector> slots; sptr slot = new NotificationSlot(slotType); @@ -126,6 +128,8 @@ HWTEST_F(AnsSlotServiceTest, GetSlots_00001, Function | SmallTest | Level1) */ HWTEST_F(AnsSlotServiceTest, GetSlotsByBundle_00001, Function | SmallTest | Level1) { + MockIsSystemApp(true); + MockIsVerfyPermisson(true); std::vector> slots; sptr bundle = nullptr; ASSERT_EQ(advancedNotificationService_->GetSlotsByBundle(bundle, slots), (int)ERR_ANS_INVALID_BUNDLE); @@ -139,6 +143,8 @@ HWTEST_F(AnsSlotServiceTest, GetSlotsByBundle_00001, Function | SmallTest | Leve */ HWTEST_F(AnsSlotServiceTest, GetSlotsByBundle_00002, Function | SmallTest | Level1) { + MockIsSystemApp(true); + MockIsVerfyPermisson(true); std::vector> slots; sptr bundle = new NotificationBundleOption("test", 1); advancedNotificationService_->notificationSvrQueue_ = nullptr; @@ -153,6 +159,8 @@ HWTEST_F(AnsSlotServiceTest, GetSlotsByBundle_00002, Function | SmallTest | Leve */ HWTEST_F(AnsSlotServiceTest, UpdateSlots_00001, Function | SmallTest | Level1) { + MockIsSystemApp(true); + MockIsVerfyPermisson(true); std::vector> slots; sptr bundle = nullptr; ASSERT_EQ(advancedNotificationService_->UpdateSlots(bundle, slots), (int)ERR_ANS_INVALID_BUNDLE); @@ -170,6 +178,8 @@ HWTEST_F(AnsSlotServiceTest, UpdateSlots_00001, Function | SmallTest | Level1) */ HWTEST_F(AnsSlotServiceTest, UpdateSlots_00002, Function | SmallTest | Level1) { + MockIsSystemApp(true); + MockIsVerfyPermisson(true); std::vector> slots; sptr slot = new NotificationSlot(NotificationConstant::SlotType::LIVE_VIEW); slot->SetEnable(true); @@ -506,7 +516,7 @@ HWTEST_F(AnsSlotServiceTest, GenerateSlotReminderMode_00001, Function | SmallTes sptr bundle = nullptr; sptr slot = new (std::nothrow) NotificationSlot(NotificationConstant::SlotType::SERVICE_REMINDER); advancedNotificationService_->GenerateSlotReminderMode(slot, bundle); - ASSERT_EQ(slot->GetReminderMode(), (int)0b111111); + ASSERT_EQ(slot->GetReminderMode(), (int)0b111011); } /** @@ -520,7 +530,7 @@ HWTEST_F(AnsSlotServiceTest, GenerateSlotReminderMode_00002, Function | SmallTes sptr bundle = nullptr; sptr slot = new (std::nothrow) NotificationSlot(NotificationConstant::SlotType::SERVICE_REMINDER); advancedNotificationService_->GenerateSlotReminderMode(slot, bundle, true); - ASSERT_EQ(slot->GetReminderMode(), (int)0b111111); + ASSERT_EQ(slot->GetReminderMode(), (int)0b111011); } /** diff --git a/services/distributed/test/unittest/distributed_preferences_test.cpp b/services/distributed/test/unittest/distributed_preferences_test.cpp index b2d15d12b..22504c93e 100644 --- a/services/distributed/test/unittest/distributed_preferences_test.cpp +++ b/services/distributed/test/unittest/distributed_preferences_test.cpp @@ -101,7 +101,7 @@ HWTEST_F(DistributedPreferencesTest, SetDistributedBundleEnable_00200, Function */ HWTEST_F(DistributedPreferencesTest, ClearDataInRestoreFactorySettings_00100, Function | SmallTest | Level1) { - EXPECT_EQ(distributedPreferences_->ClearDataInRestoreFactorySettings(), ERR_OK); + EXPECT_EQ(distributedPreferences_->ClearDataInRestoreFactorySettings(), ERR_ANS_DISTRIBUTED_OPERATION_FAILED); } /** diff --git a/services/distributed/test/unittest/distributed_screen_status_manager_test.cpp b/services/distributed/test/unittest/distributed_screen_status_manager_test.cpp index dc1eb3649..1028e9c8e 100644 --- a/services/distributed/test/unittest/distributed_screen_status_manager_test.cpp +++ b/services/distributed/test/unittest/distributed_screen_status_manager_test.cpp @@ -15,6 +15,7 @@ #include #include "ans_inner_errors.h" +#include "errors.h" #include "gtest/gtest.h" #define private public #include "distributed_screen_status_manager.h" @@ -52,8 +53,7 @@ HWTEST_F(DistributedScreenStatusManagerTest, CheckRemoteDevicesIsUsing_00100, Fu { bool isUsing = true; - EXPECT_EQ(distributedScreenStatusManager_->CheckRemoteDevicesIsUsing(isUsing), - ERR_ANS_DISTRIBUTED_OPERATION_FAILED); + EXPECT_EQ(distributedScreenStatusManager_->CheckRemoteDevicesIsUsing(isUsing), ERR_OK); } /** @@ -65,7 +65,7 @@ HWTEST_F(DistributedScreenStatusManagerTest, SetLocalScreenStatus_00100, Functio { bool screenOn = false; - EXPECT_EQ(distributedScreenStatusManager_->SetLocalScreenStatus(screenOn), ERR_ANS_DISTRIBUTED_OPERATION_FAILED); + EXPECT_EQ(distributedScreenStatusManager_->SetLocalScreenStatus(screenOn), ERR_OK); } } // namespace Notification } // namespace OHOS \ No newline at end of file diff --git a/services/test/moduletest/ans_module_test.cpp b/services/test/moduletest/ans_module_test.cpp index 4f79e8c7b..d58a99829 100644 --- a/services/test/moduletest/ans_module_test.cpp +++ b/services/test/moduletest/ans_module_test.cpp @@ -192,7 +192,11 @@ HWTEST_F(AnsModuleTest, AnsModuleTest_003, Function | SmallTest | Level1) sptr req = new NotificationRequest(0); req->SetLabel(label); req->SetStatusBarText("text"); - + req->SetSlotType(NotificationConstant::SlotType::CONTENT_INFORMATION); + std::shared_ptr longTextContent = + std::make_shared("longtext"); + std::shared_ptr content2 = std::make_shared(longTextContent); + req->SetContent(content2); g_advancedNotificationService->SetNotificationsEnabledForBundle("", false); g_advancedNotificationService->Publish(label, req); @@ -237,11 +241,17 @@ HWTEST_F(AnsModuleTest, AnsModuleTest_005, Function | SmallTest | Level1) // create request std::string label = "testLabel"; + std::shared_ptr longTextContent = + std::make_shared("longtext"); + std::shared_ptr content2 = std::make_shared(longTextContent); sptr req = new NotificationRequest(0); sptr req1 = new NotificationRequest(1); req->SetLabel(label); req1->SetLabel(label); - + req->SetSlotType(NotificationConstant::SlotType::CONTENT_INFORMATION); + req->SetContent(content2); + req1->SetSlotType(NotificationConstant::SlotType::CONTENT_INFORMATION); + req1->SetContent(content2); // publish request g_advancedNotificationService->Publish(label, req); g_advancedNotificationService->Publish(label, req1); @@ -276,6 +286,11 @@ HWTEST_F(AnsModuleTest, AnsModuleTest_006, Function | SmallTest | Level1) std::string label = "testLabel"; sptr req = new NotificationRequest(0); req->SetLabel(label); + req->SetSlotType(NotificationConstant::SlotType::CONTENT_INFORMATION); + std::shared_ptr longTextContent = + std::make_shared("longtext"); + std::shared_ptr content2 = std::make_shared(longTextContent); + req->SetContent(content2); // publish request g_advancedNotificationService->Publish(label, req); @@ -320,10 +335,17 @@ HWTEST_F(AnsModuleTest, AnsModuleTest_007, Function | SmallTest | Level1) // create request std::string label = "testLabel"; + std::shared_ptr longTextContent = + std::make_shared("longtext"); + std::shared_ptr content2 = std::make_shared(longTextContent); sptr req = new NotificationRequest(0); sptr req1 = new NotificationRequest(1); req->SetLabel(label); req1->SetLabel(label); + req->SetSlotType(NotificationConstant::SlotType::CONTENT_INFORMATION); + req->SetContent(content2); + req1->SetSlotType(NotificationConstant::SlotType::CONTENT_INFORMATION); + req1->SetContent(content2); // publish request g_advancedNotificationService->Publish(label, req); @@ -359,6 +381,11 @@ HWTEST_F(AnsModuleTest, AnsModuleTest_0013, Function | SmallTest | Level1) std::string label = "testLabel"; sptr req = new NotificationRequest(0); req->SetLabel(label); + req->SetSlotType(NotificationConstant::SlotType::CONTENT_INFORMATION); + std::shared_ptr longTextContent = + std::make_shared("longtext"); + std::shared_ptr content2 = std::make_shared(longTextContent); + req->SetContent(content2); // publish request g_advancedNotificationService->Publish(label, req); @@ -1224,6 +1251,11 @@ HWTEST_F(AnsModuleTest, AnsModuleTest_0058, Function | SmallTest | Level1) req->SetLabel(label); req->SetStatusBarText("text"); req->SetBadgeNumber(1); + req->SetSlotType(NotificationConstant::SlotType::CONTENT_INFORMATION); + std::shared_ptr longTextContent = + std::make_shared("longtext"); + std::shared_ptr content2 = std::make_shared(longTextContent); + req->SetContent(content2); // SetShowBadgeEnabledForBundle true sptr bundleOption = new NotificationBundleOption("bundleName", 0); @@ -1271,10 +1303,17 @@ HWTEST_F(AnsModuleTest, AnsModuleTest_0062, Function | SmallTest | Level1) // create request std::string label = "testLabel"; + std::shared_ptr longTextContent = + std::make_shared("longtext"); + std::shared_ptr content2 = std::make_shared(longTextContent); sptr req = new NotificationRequest(0); sptr req1 = new NotificationRequest(1); req->SetLabel(label); req1->SetLabel(label); + req->SetSlotType(NotificationConstant::SlotType::CONTENT_INFORMATION); + req->SetContent(content2); + req1->SetSlotType(NotificationConstant::SlotType::CONTENT_INFORMATION); + req1->SetContent(content2); // publish request g_advancedNotificationService->Publish(label, req); @@ -1316,10 +1355,17 @@ HWTEST_F(AnsModuleTest, AnsModuleTest_0063, Function | SmallTest | Level1) // create request std::string label = "testLabel"; + std::shared_ptr longTextContent = + std::make_shared("longtext"); + std::shared_ptr content2 = std::make_shared(longTextContent); sptr req = new NotificationRequest(0); sptr req1 = new NotificationRequest(1); req->SetLabel(label); req1->SetLabel(label); + req->SetSlotType(NotificationConstant::SlotType::CONTENT_INFORMATION); + req->SetContent(content2); + req1->SetSlotType(NotificationConstant::SlotType::CONTENT_INFORMATION); + req1->SetContent(content2); // publish request g_advancedNotificationService->Publish(label, req); @@ -1378,6 +1424,11 @@ HWTEST_F(AnsModuleTest, AnsModuleTest_0066, Function | SmallTest | Level1) std::string label = "testLabel"; sptr req = new NotificationRequest(0); req->SetLabel(label); + req->SetSlotType(NotificationConstant::SlotType::CONTENT_INFORMATION); + std::shared_ptr longTextContent = + std::make_shared("longtext"); + std::shared_ptr content2 = std::make_shared(longTextContent); + req->SetContent(content2); // publish request g_advancedNotificationService->Publish(label, req); @@ -1458,6 +1509,11 @@ HWTEST_F(AnsModuleTest, AnsModuleTest_0101, Function | SmallTest | Level1) sptr req = new NotificationRequest(0); req->SetLabel(label); req->SetWantAgent(agent); + req->SetSlotType(NotificationConstant::SlotType::CONTENT_INFORMATION); + std::shared_ptr longTextContent = + std::make_shared("longtext"); + std::shared_ptr content2 = std::make_shared(longTextContent); + req->SetContent(content2); // publish request g_advancedNotificationService->Publish(label, req); @@ -1491,6 +1547,11 @@ HWTEST_F(AnsModuleTest, AnsModuleTest_0102, Function | SmallTest | Level1) sptr req = new NotificationRequest(0); req->SetLabel(label); req->SetWantAgent(agent); + req->SetSlotType(NotificationConstant::SlotType::CONTENT_INFORMATION); + std::shared_ptr longTextContent = + std::make_shared("longtext"); + std::shared_ptr content2 = std::make_shared(longTextContent); + req->SetContent(content2); // publish request g_advancedNotificationService->Publish(label, req); @@ -1524,6 +1585,11 @@ HWTEST_F(AnsModuleTest, AnsModuleTest_0103, Function | SmallTest | Level1) sptr req = new NotificationRequest(0); req->SetLabel(label); req->SetWantAgent(agent); + req->SetSlotType(NotificationConstant::SlotType::CONTENT_INFORMATION); + std::shared_ptr longTextContent = + std::make_shared("longtext"); + std::shared_ptr content2 = std::make_shared(longTextContent); + req->SetContent(content2); // publish request g_advancedNotificationService->Publish(label, req); @@ -1586,6 +1652,11 @@ HWTEST_F(AnsModuleTest, AnsModuleTest_0106, Function | SmallTest | Level1) sptr req = new NotificationRequest(0); req->SetLabel(label); req->SetWantAgent(agent); + req->SetSlotType(NotificationConstant::SlotType::CONTENT_INFORMATION); + std::shared_ptr longTextContent = + std::make_shared("longtext"); + std::shared_ptr content2 = std::make_shared(longTextContent); + req->SetContent(content2); // publish request g_advancedNotificationService->Publish(label, req); @@ -2166,11 +2237,15 @@ HWTEST_F(AnsModuleTest, AnsModuleTest_0123, Function | SmallTest | Level1) slots.push_back(new NotificationSlot(NotificationConstant::SlotType::OTHER)); slots.push_back(new NotificationSlot(NotificationConstant::SlotType::CUSTOM)); EXPECT_EQ(g_advancedNotificationService->AddSlots(slots), 0); + std::shared_ptr longTextContent = + std::make_shared("longtext"); + std::shared_ptr content2 = std::make_shared(longTextContent); sptr req = new NotificationRequest(0); sptr req1 = new NotificationRequest(1); sptr req2 = new NotificationRequest(2); sptr req3 = new NotificationRequest(3); sptr req4 = new NotificationRequest(4); + req->SetLabel("testLabel"); req1->SetLabel("testLabel"); req2->SetLabel("testLabel"); @@ -2182,6 +2257,11 @@ HWTEST_F(AnsModuleTest, AnsModuleTest_0123, Function | SmallTest | Level1) req2->SetSlotType(NotificationConstant::SlotType::CONTENT_INFORMATION); req3->SetSlotType(NotificationConstant::SlotType::OTHER); req4->SetSlotType(NotificationConstant::SlotType::CUSTOM); + req->SetContent(content2); + req1->SetContent(content2); + req2->SetContent(content2); + req3->SetContent(content2); + req4->SetContent(content2); g_advancedNotificationService->Publish("testLabel", req); std::this_thread::sleep_for(std::chrono::milliseconds(200)); @@ -2268,7 +2348,10 @@ HWTEST_F(AnsModuleTest, AnsModuleTest_0125, Function | SmallTest | Level1) sptr req = new NotificationRequest(0); req->SetLabel(label); req->SetSlotType(NotificationConstant::SlotType::SOCIAL_COMMUNICATION); - + std::shared_ptr longTextContent = + std::make_shared("longtext"); + std::shared_ptr content2 = std::make_shared(longTextContent); + req->SetContent(content2); // publish request g_advancedNotificationService->Publish(label, req); g_advancedNotificationService->Unsubscribe(subscriber->GetImpl(), nullptr); @@ -2497,6 +2580,11 @@ HWTEST_F(AnsModuleTest, AnsModuleTest_0132, Function | SmallTest | Level1) sptr req = new NotificationRequest(0); req->SetLabel(label); req->SetStatusBarText("text"); + req->SetSlotType(NotificationConstant::SlotType::SOCIAL_COMMUNICATION); + std::shared_ptr longTextContent = + std::make_shared("longtext"); + std::shared_ptr content2 = std::make_shared(longTextContent); + req->SetContent(content2); sptr date = new NotificationDoNotDisturbDate(NotificationConstant::DoNotDisturbType::NONE, 0, 0); @@ -2533,6 +2621,10 @@ HWTEST_F(AnsModuleTest, AnsModuleTest_0133, Function | SmallTest | Level1) req->SetLabel(label); req->SetStatusBarText("text"); req->SetSlotType(NotificationConstant::SlotType::SOCIAL_COMMUNICATION); + std::shared_ptr longTextContent = + std::make_shared("longtext"); + std::shared_ptr content2 = std::make_shared(longTextContent); + req->SetContent(content2); std::chrono::system_clock::time_point timePoint = std::chrono::system_clock::now(); auto beginDuration = std::chrono::duration_cast(timePoint.time_since_epoch()); @@ -2575,6 +2667,10 @@ HWTEST_F(AnsModuleTest, AnsModuleTest_0134, Function | SmallTest | Level1) req->SetLabel(label); req->SetStatusBarText("text"); req->SetSlotType(NotificationConstant::SlotType::SOCIAL_COMMUNICATION); + std::shared_ptr longTextContent = + std::make_shared("longtext"); + std::shared_ptr content2 = std::make_shared(longTextContent); + req->SetContent(content2); std::chrono::system_clock::time_point timePoint = std::chrono::system_clock::now(); auto beginDuration = std::chrono::duration_cast(timePoint.time_since_epoch()); @@ -2617,6 +2713,10 @@ HWTEST_F(AnsModuleTest, AnsModuleTest_0135, Function | SmallTest | Level1) req->SetLabel(label); req->SetStatusBarText("text"); req->SetSlotType(NotificationConstant::SlotType::SOCIAL_COMMUNICATION); + std::shared_ptr longTextContent = + std::make_shared("longtext"); + std::shared_ptr content2 = std::make_shared(longTextContent); + req->SetContent(content2); std::chrono::system_clock::time_point timePoint = std::chrono::system_clock::now(); auto beginDuration = std::chrono::duration_cast(timePoint.time_since_epoch()); -- Gitee From 940aa7536651c4ee5a8cbd9c6e410a2f10e9eab4 Mon Sep 17 00:00:00 2001 From: wufarong Date: Thu, 26 Sep 2024 19:13:30 +0800 Subject: [PATCH 064/167] =?UTF-8?q?RecoverLiveViewFromDb=E5=86=85=E9=83=A8?= =?UTF-8?q?=E6=B5=81=E7=A8=8B=E6=94=BE=E5=85=A5ffrt?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: wufarong Change-Id: I0f32cdb60cb0130b4085f9e56dd5c9355bf9149c --- frameworks/ans/src/notification_request.cpp | 12 +-- ...dvanced_notification_live_view_service.cpp | 94 ++++++++++--------- .../ans/src/advanced_notification_service.cpp | 6 +- 3 files changed, 58 insertions(+), 54 deletions(-) diff --git a/frameworks/ans/src/notification_request.cpp b/frameworks/ans/src/notification_request.cpp index 61fe529ff..5147a3521 100644 --- a/frameworks/ans/src/notification_request.cpp +++ b/frameworks/ans/src/notification_request.cpp @@ -1542,7 +1542,7 @@ bool NotificationRequest::ReadFromParcel(Parcel &parcel) int32_t slotTypeValue = parcel.ReadInt32(); if (slotTypeValue < 0 || slotTypeValue >= static_cast(NotificationConstant::SlotType::ILLEGAL_TYPE)) { - ANS_LOGE("Invalid slot type value :%d. It should be in [0 , %d).", + ANS_LOGE("Invalid slot type value :%{public}d. It should be in [0 , %{public}d).", slotTypeValue, static_cast(NotificationConstant::SlotType::ILLEGAL_TYPE)); return false; } @@ -1550,7 +1550,7 @@ bool NotificationRequest::ReadFromParcel(Parcel &parcel) int32_t groupAlertTypeValue = parcel.ReadInt32(); if (groupAlertTypeValue < 0 || groupAlertTypeValue >= static_cast(NotificationRequest::GroupAlertType::ILLEGAL_TYPE)) { - ANS_LOGE("Invalid groupAlert type value :%d. It should be in [0 , %d).", + ANS_LOGE("Invalid groupAlert type value :%{public}d. It should be in [0 , %{public}d).", groupAlertTypeValue, static_cast(NotificationRequest::GroupAlertType::ILLEGAL_TYPE)); return false; } @@ -1558,26 +1558,26 @@ bool NotificationRequest::ReadFromParcel(Parcel &parcel) int32_t visiblenessTypeValue = parcel.ReadInt32(); if (visiblenessTypeValue < 0 || visiblenessTypeValue >= static_cast(NotificationConstant::VisiblenessType::ILLEGAL_TYPE)) { - ANS_LOGE("Invalid visibleness type value :%d. It should be in [0 , %d).", + ANS_LOGE("Invalid visibleness type value :%{public}d. It should be in [0 , %{public}d).", visiblenessTypeValue, static_cast(NotificationConstant::VisiblenessType::ILLEGAL_TYPE)); return false; } visiblenessType_ = static_cast(visiblenessTypeValue); int32_t badgeStyleValue = parcel.ReadInt32(); if (badgeStyleValue < 0) { - ANS_LOGE("Invalid badge style value :%d. It should be greater than 0.", badgeStyleValue); + ANS_LOGE("Invalid badge style value :%{public}d. It should be greater than 0.", badgeStyleValue); return false; } if (badgeStyleValue >= static_cast(NotificationRequest::BadgeStyle::ILLEGAL_TYPE)) { badgeStyleValue = static_cast(NotificationRequest::BadgeStyle::NONE); - ANS_LOGE("The badge style value is too large, set it to the default enumeration value: %d.", + ANS_LOGE("The badge style value is too large, set it to the default enumeration value: %{public}d.", static_cast(NotificationRequest::BadgeStyle::NONE)); } badgeStyle_ = static_cast(badgeStyleValue); int32_t notificationContentTypeValue = parcel.ReadInt32(); if (notificationContentTypeValue <= static_cast(NotificationContent::Type::NONE) || notificationContentTypeValue >= static_cast(NotificationContent::Type::ILLEGAL_TYPE)) { - ANS_LOGE("Invalid notification content type value :%d. It should be in (%d , %d)", + ANS_LOGE("Invalid notification content type value :%{public}d. It should be in (%{public}d , %{public}d)", notificationContentTypeValue, static_cast(NotificationContent::Type::NONE), static_cast(NotificationContent::Type::ILLEGAL_TYPE)); return false; diff --git a/services/ans/src/advanced_notification_live_view_service.cpp b/services/ans/src/advanced_notification_live_view_service.cpp index 74fac4337..5cb6c19b9 100644 --- a/services/ans/src/advanced_notification_live_view_service.cpp +++ b/services/ans/src/advanced_notification_live_view_service.cpp @@ -41,60 +41,66 @@ const std::string PROGRESS_VALUE = "progressValue"; void AdvancedNotificationService::RecoverLiveViewFromDb(int32_t userId) { ANS_LOGI("Start recover live view from db. userId:%{public}d", userId); - - std::vector requestsdb; - if (GetBatchNotificationRequestsFromDb(requestsdb, userId) != ERR_OK) { - ANS_LOGE("Get liveView from db failed."); + if (notificationSvrQueue_ == nullptr) { + ANS_LOGE("notificationSvrQueue_ is nullptr."); return; } + ffrt::task_handle handler = notificationSvrQueue_->submit_h(std::bind([=]() { + std::vector requestsdb; + if (GetBatchNotificationRequestsFromDb(requestsdb, userId) != ERR_OK) { + ANS_LOGE("Get liveView from db failed."); + return; + } + ANS_LOGI("The number of live views to recover: %{public}zu.", requestsdb.size()); + for (const auto &requestObj : requestsdb) { + ANS_LOGD("Recover request: %{public}s.", requestObj.request->Dump().c_str()); + if (!IsLiveViewCanRecover(requestObj.request)) { + int32_t userId = requestObj.request->GetReceiverUserId(); + if (DoubleDeleteNotificationFromDb(requestObj.request->GetKey(), + requestObj.request->GetSecureKey(), userId) != ERR_OK) { + ANS_LOGE("Delete notification failed."); + } + continue; + } - for (const auto &requestObj : requestsdb) { - ANS_LOGD("Recover request: %{public}s.", requestObj.request->Dump().c_str()); - if (!IsLiveViewCanRecover(requestObj.request)) { - int32_t userId = requestObj.request->GetReceiverUserId(); - if (DoubleDeleteNotificationFromDb(requestObj.request->GetKey(), - requestObj.request->GetSecureKey(), userId) != ERR_OK) { - ANS_LOGE("Delete notification failed."); + auto record = std::make_shared(); + if (FillNotificationRecord(requestObj, record) != ERR_OK) { + ANS_LOGE("Fill notification record failed."); + continue; } - continue; - } - auto record = std::make_shared(); - if (FillNotificationRecord(requestObj, record) != ERR_OK) { - ANS_LOGE("Fill notification record failed."); - continue; - } + if (Filter(record, true) != ERR_OK) { + ANS_LOGE("Filter record failed."); + continue; + } - if (Filter(record, true) != ERR_OK) { - ANS_LOGE("Filter record failed."); - continue; - } + if (FlowControl(record) != ERR_OK) { + ANS_LOGE("Flow control failed."); + continue; + } - if (FlowControl(record) != ERR_OK) { - ANS_LOGE("Flow control failed."); - continue; - } + // Turn off ringtone and vibration during recovery process + auto notificationFlags = record->request->GetFlags(); + notificationFlags->SetSoundEnabled(NotificationConstant::FlagStatus::CLOSE); + notificationFlags->SetVibrationEnabled(NotificationConstant::FlagStatus::CLOSE); + record->request->SetFlags(notificationFlags); + ANS_LOGI("SetFlags-Recovery, notificationKey = %{public}s flags = %{public}d", + record->request->GetKey().c_str(), notificationFlags->GetReminderFlags()); + if (AssignToNotificationList(record) != ERR_OK) { + ANS_LOGE("Add notification to record list failed."); + continue; + } + UpdateRecentNotification(record->notification, false, 0); - // Turn off ringtone and vibration during recovery process - auto notificationFlags = record->request->GetFlags(); - notificationFlags->SetSoundEnabled(NotificationConstant::FlagStatus::CLOSE); - notificationFlags->SetVibrationEnabled(NotificationConstant::FlagStatus::CLOSE); - record->request->SetFlags(notificationFlags); - if (AssignToNotificationList(record) != ERR_OK) { - ANS_LOGE("Add notification to record list failed."); - continue; + StartFinishTimer(record, requestObj.request->GetFinishDeadLine()); + StartUpdateTimer(record, requestObj.request->GetUpdateDeadLine()); } - UpdateRecentNotification(record->notification, false, 0); - - StartFinishTimer(record, requestObj.request->GetFinishDeadLine()); - StartUpdateTimer(record, requestObj.request->GetUpdateDeadLine()); - } - - // publish notifications - for (const auto &subscriber : NotificationSubscriberManager::GetInstance()->GetSubscriberRecords()) { - OnSubscriberAdd(subscriber); - } + // publish notifications + for (const auto &subscriber : NotificationSubscriberManager::GetInstance()->GetSubscriberRecords()) { + OnSubscriberAdd(subscriber); + } + })); ANS_LOGI("End recover live view from db."); } diff --git a/services/ans/src/advanced_notification_service.cpp b/services/ans/src/advanced_notification_service.cpp index c37aabdb0..276e0ebbc 100644 --- a/services/ans/src/advanced_notification_service.cpp +++ b/services/ans/src/advanced_notification_service.cpp @@ -299,10 +299,8 @@ AdvancedNotificationService::AdvancedNotificationService() std::bind(&AdvancedNotificationService::OnSubscriberAdd, this, std::placeholders::_1); NotificationSubscriberManager::GetInstance()->RegisterOnSubscriberAddCallback(callback); - std::function recoverFunc = std::bind( - &AdvancedNotificationService::RecoverLiveViewFromDb, this, SUBSCRIBE_USER_INIT); - notificationSvrQueue_->submit(recoverFunc); - + RecoverLiveViewFromDb(); + ISystemEvent iSystemEvent = { std::bind(&AdvancedNotificationService::OnBundleRemoved, this, std::placeholders::_1), #ifdef DISTRIBUTED_NOTIFICATION_SUPPORTED -- Gitee From 020801553d60c2ae66a25b6ac02462f497369a19 Mon Sep 17 00:00:00 2001 From: z30053788 Date: Thu, 10 Oct 2024 16:49:02 +0800 Subject: [PATCH 065/167] =?UTF-8?q?=E5=90=8C=E6=AD=A5?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: z30053788 Change-Id: I8101feb0a83a9a48fd35713b456e57763fe45b5d --- .../ans_innerkits_module_setting_test.cpp | 69 ++----------------- ...anced_notification_service_branch_test.cpp | 3 +- 2 files changed, 8 insertions(+), 64 deletions(-) diff --git a/frameworks/test/moduletest/ans_innerkits_module_setting_test.cpp b/frameworks/test/moduletest/ans_innerkits_module_setting_test.cpp index cea73bb09..20b785ebc 100644 --- a/frameworks/test/moduletest/ans_innerkits_module_setting_test.cpp +++ b/frameworks/test/moduletest/ans_innerkits_module_setting_test.cpp @@ -78,28 +78,9 @@ HWTEST_F(AnsInnerKitsModuleSettingTest, ANS_Interface_MT_NotificationSetting_001 bundleOption.SetBundleName("bundlename"); bundleOption.SetUid(CALLING_UID); GTEST_LOG_(INFO) << "BundleOption is:"<IsNeedSilentInDoNotDisturbMode( - phoneNumber, callerType), ERR_ANS_PERMISSION_DENIED); + ASSERT_EQ(advancedNotificationService_->IsNeedSilentInDoNotDisturbMode(phoneNumber, callerType), -1); } /** -- Gitee From 57a84f9797f1009d352ce2b3e34661688bc27ad1 Mon Sep 17 00:00:00 2001 From: gaojiaqi Date: Tue, 8 Oct 2024 16:42:57 +0800 Subject: [PATCH 066/167] fix tdd Signed-off-by: gaojiaqi --- frameworks/test/moduletest/BUILD.gn | 2 +- services/ans/src/reminder_data_manager.cpp | 9 ++++++--- .../test/unittest/advanced_notification_service_test.cpp | 3 +++ 3 files changed, 10 insertions(+), 4 deletions(-) diff --git a/frameworks/test/moduletest/BUILD.gn b/frameworks/test/moduletest/BUILD.gn index 83c5b849c..c37703db6 100644 --- a/frameworks/test/moduletest/BUILD.gn +++ b/frameworks/test/moduletest/BUILD.gn @@ -326,7 +326,7 @@ group("moduletest") { deps = [] deps += [ - ":ReminderAgentJsTest", + # ":ReminderAgentJsTest", # ":ans_fw_module_test", ":ans_innerkits_module_publish_test", diff --git a/services/ans/src/reminder_data_manager.cpp b/services/ans/src/reminder_data_manager.cpp index 0013c0f98..b1b7b265b 100644 --- a/services/ans/src/reminder_data_manager.cpp +++ b/services/ans/src/reminder_data_manager.cpp @@ -1044,16 +1044,13 @@ void ReminderDataManager::ShowActiveReminderExtendLocked(sptr & continue; } if (((*it)->GetRingDuration() > 0) && !isAlerting) { - std::lock_guard lock(ReminderDataManager::MUTEX); playSoundReminder = (*it); isAlerting = true; } else { - std::lock_guard lock(ReminderDataManager::MUTEX); ShowReminder((*it), false, false, false, false); } } if (playSoundReminder != nullptr) { - std::lock_guard lock(ReminderDataManager::MUTEX); ShowReminder(playSoundReminder, true, false, false, true); } } @@ -1353,10 +1350,15 @@ void ReminderDataManager::HandleImmediatelyShow( { bool isAlerting = false; for (auto it = showImmediately.begin(); it != showImmediately.end(); ++it) { + if ((*it)->IsShowing()) { + continue; + } if (((*it)->GetRingDuration() > 0) && !isAlerting) { + std::lock_guard lock(ReminderDataManager::MUTEX); ShowReminder((*it), true, false, isSysTimeChanged, true); isAlerting = true; } else { + std::lock_guard lock(ReminderDataManager::MUTEX); ShowReminder((*it), false, false, isSysTimeChanged, false); } } @@ -2062,6 +2064,7 @@ void ReminderDataManager::OnLanguageChanged() showedReminder = showedReminderVector_; } for (auto it = showedReminder.begin(); it != showedReminder.end(); ++it) { + std::lock_guard lock(ReminderDataManager::MUTEX); ShowReminder((*it), false, false, false, false); } } diff --git a/services/ans/test/unittest/advanced_notification_service_test.cpp b/services/ans/test/unittest/advanced_notification_service_test.cpp index 0729b58c6..4158e4441 100644 --- a/services/ans/test/unittest/advanced_notification_service_test.cpp +++ b/services/ans/test/unittest/advanced_notification_service_test.cpp @@ -3708,6 +3708,7 @@ HWTEST_F(AdvancedNotificationServiceTest, AddExcludeDate_00001, Function | Small { int32_t reminderId = 10; uint64_t time = 124325; + MockIsVerfyPermisson(false); ASSERT_EQ(advancedNotificationService_->AddExcludeDate(reminderId, time), (int)ERR_REMINDER_PERMISSION_DENIED); TestAddSlot(NotificationConstant::SlotType::SOCIAL_COMMUNICATION); MockIsNonBundleName(true); @@ -3726,6 +3727,7 @@ HWTEST_F(AdvancedNotificationServiceTest, AddExcludeDate_00001, Function | Small HWTEST_F(AdvancedNotificationServiceTest, DelExcludeDates_00002, Function | SmallTest | Level1) { int32_t reminderId = 10; + MockIsVerfyPermisson(false); ASSERT_EQ(advancedNotificationService_->DelExcludeDates(reminderId), (int)ERR_REMINDER_PERMISSION_DENIED); TestAddSlot(NotificationConstant::SlotType::SOCIAL_COMMUNICATION); MockIsNonBundleName(true); @@ -3745,6 +3747,7 @@ HWTEST_F(AdvancedNotificationServiceTest, GetExcludeDates_00001, Function | Smal { int32_t reminderId = 10; std::vector times; + MockIsVerfyPermisson(false); ASSERT_EQ(advancedNotificationService_->GetExcludeDates(reminderId, times), (int)ERR_REMINDER_PERMISSION_DENIED); TestAddSlot(NotificationConstant::SlotType::SOCIAL_COMMUNICATION); MockIsNonBundleName(true); -- Gitee From 93560457910ffa55b266553a611060dd9b17d59f Mon Sep 17 00:00:00 2001 From: xdongs Date: Fri, 11 Oct 2024 09:39:14 +0800 Subject: [PATCH 067/167] =?UTF-8?q?wantAgent=E5=8F=8D=E5=BA=8F=E5=88=97?= =?UTF-8?q?=E5=8C=96?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: xdongs --- frameworks/ans/src/notification_request.cpp | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/frameworks/ans/src/notification_request.cpp b/frameworks/ans/src/notification_request.cpp index 5147a3521..3de9ff674 100644 --- a/frameworks/ans/src/notification_request.cpp +++ b/frameworks/ans/src/notification_request.cpp @@ -877,7 +877,12 @@ NotificationRequest *NotificationRequest::FromJson(const nlohmann::json &jsonObj if (jsonObject.find("wantAgent") != jsonEnd && jsonObject.at("wantAgent").is_string()) { auto wantAgentValue = jsonObject.at("wantAgent").get(); - pRequest->wantAgent_ = AbilityRuntime::WantAgent::WantAgentHelper::FromString(wantAgentValue); + int32_t targetUid = -1; + if (pRequest->GetOwnerUid() != DEFAULT_UID) { + targetUid = pRequest->GetOwnerUid(); + } + ANS_LOGI("wantAgent Fromjson, uid = %{public}d ", targetUid); + pRequest->wantAgent_ = AbilityRuntime::WantAgent::WantAgentHelper::FromString(wantAgentValue, targetUid); } if (!ConvertJsonToNotificationContent(pRequest, jsonObject)) { -- Gitee From bafdfacc7cffaa70fa1b4ce171caf7c69e406f43 Mon Sep 17 00:00:00 2001 From: xdongs Date: Fri, 11 Oct 2024 10:53:29 +0800 Subject: [PATCH 068/167] =?UTF-8?q?rdb=E5=A4=87=E4=BB=BD=E4=B8=8E=E6=81=A2?= =?UTF-8?q?=E5=A4=8D?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: xdongs --- .../ans/include/notification_rdb_data_mgr.h | 1 + services/ans/src/common/aes_gcm_helper.cpp | 8 +++++ .../ans/src/notification_rdb_data_mgr.cpp | 36 +++++++++++++++++++ 3 files changed, 45 insertions(+) diff --git a/services/ans/include/notification_rdb_data_mgr.h b/services/ans/include/notification_rdb_data_mgr.h index 36a46b29c..58855f144 100644 --- a/services/ans/include/notification_rdb_data_mgr.h +++ b/services/ans/include/notification_rdb_data_mgr.h @@ -158,6 +158,7 @@ private: std::unordered_map &values); int32_t QueryAllData(const std::string tableName, std::unordered_map &datas); int32_t InitCreatedTables(); + int32_t RestoreForMasterSlaver(); private: NotificationRdbConfig notificationRdbConfig_; diff --git a/services/ans/src/common/aes_gcm_helper.cpp b/services/ans/src/common/aes_gcm_helper.cpp index 97a2b48ac..3869b9bcd 100644 --- a/services/ans/src/common/aes_gcm_helper.cpp +++ b/services/ans/src/common/aes_gcm_helper.cpp @@ -35,6 +35,7 @@ namespace Notification { static const uint32_t G_AES_GCM_IV_LEN{12}; static const uint32_t G_AES_GCM_TAG_LEN{16}; static const std::string G_DIR_PATH{"/data/service/el1/public/database/notification_service/keyfile"}; +static const std::string G_KEY_PATH{"/data/service/el1/public/database/notification_service"}; static const int STEP = 2; static const int OFFSET = 4; static const int HEX_OF_A = 10; @@ -82,6 +83,13 @@ std::string AesGcmHelper::Hex2Byte(const std::string &hex) bool AesGcmHelper::GenerateKey(std::string &key) { std::lock_guard lck(g_generateKeyMutex); + const char *keyPathPtr = G_KEY_PATH.c_str(); + char *resolvedPath = (char *)malloc(PATH_MAX); + if (realpath(keyPathPtr, resolvedPath) == NULL) { + free(resolvedPath); + ANS_LOGE("Fail to resolve the key path"); + return false; + } std::string keyDir = G_DIR_PATH; const char *fileNamePtr = keyDir.c_str(); std::filesystem::path keyPath(keyDir); diff --git a/services/ans/src/notification_rdb_data_mgr.cpp b/services/ans/src/notification_rdb_data_mgr.cpp index 2b4b7ed6c..c7d99df5c 100644 --- a/services/ans/src/notification_rdb_data_mgr.cpp +++ b/services/ans/src/notification_rdb_data_mgr.cpp @@ -109,6 +109,7 @@ int32_t NotificationDataMgr::Init() notificationRdbConfig_.journalMode, notificationRdbConfig_.syncMode); rdbStoreConfig.SetSecurityLevel(NativeRdb::SecurityLevel::S1); + rdbStoreConfig.SetHaMode(NativeRdb::HAMode::MAIN_REPLICA); RdbStoreDataCallBackNotificationStorage rdbDataCallBack_(notificationRdbConfig_); std::lock_guard lock(createdTableMutex_); { @@ -191,6 +192,9 @@ int32_t NotificationDataMgr::InsertData(const std::string &key, const std::strin valuesBucket.PutString(NOTIFICATION_VALUE, value); ret = rdbStore_->InsertWithConflictResolution(rowId, tableName, valuesBucket, NativeRdb::ConflictResolution::ON_CONFLICT_REPLACE); + if (ret == NativeRdb::E_SQLITE_CORRUPT) { + RestoreForMasterSlaver(); + } if (ret != NativeRdb::E_OK) { ANS_LOGE("Insert operation failed, result: %{public}d, key=%{public}s.", ret, key.c_str()); return NativeRdb::E_ERROR; @@ -219,6 +223,9 @@ int32_t NotificationDataMgr::InsertData(const std::string &key, const std::vecto valuesBucket.PutBlob(NOTIFICATION_VALUE, value); ret = rdbStore_->InsertWithConflictResolution(rowId, tableName, valuesBucket, NativeRdb::ConflictResolution::ON_CONFLICT_REPLACE); + if (ret == NativeRdb::E_SQLITE_CORRUPT) { + RestoreForMasterSlaver(); + } if (ret != NativeRdb::E_OK) { ANS_LOGE("Insert operation failed, result: %{public}d, key=%{public}s.", ret, key.c_str()); return NativeRdb::E_ERROR; @@ -249,6 +256,9 @@ int32_t NotificationDataMgr::InsertBatchData(const std::unordered_mapInsertWithConflictResolution(rowId, tableName, valuesBucket, NativeRdb::ConflictResolution::ON_CONFLICT_REPLACE); + if (ret == NativeRdb::E_SQLITE_CORRUPT) { + RestoreForMasterSlaver(); + } if (ret != NativeRdb::E_OK) { ANS_LOGE("Insert batch operation failed, result: %{public}d.", ret); return NativeRdb::E_ERROR; @@ -284,6 +294,9 @@ int32_t NotificationDataMgr::DeleteData(const std::string tableName, const std:: NativeRdb::AbsRdbPredicates absRdbPredicates(tableName); absRdbPredicates.EqualTo(NOTIFICATION_KEY, key); int32_t ret = rdbStore_->Delete(rowId, absRdbPredicates); + if (ret == NativeRdb::E_SQLITE_CORRUPT) { + RestoreForMasterSlaver(); + } if (ret != NativeRdb::E_OK) { ANS_LOGW("Delete operation failed from %{public}s, result: %{public}d, key=%{public}s.", tableName.c_str(), ret, key.c_str()); @@ -347,12 +360,18 @@ int32_t NotificationDataMgr::QueryData(const std::string tableName, const std::s } int32_t ret = absSharedResultSet->GoToFirstRow(); + if (ret == NativeRdb::E_SQLITE_CORRUPT) { + RestoreForMasterSlaver(); + } if (ret != NativeRdb::E_OK) { ANS_LOGW("GoToFirstRow failed from %{public}s table. It is empty!, key=%{public}s", tableName.c_str(), key.c_str()); return NativeRdb::E_EMPTY_VALUES_BUCKET; } ret = absSharedResultSet->GetString(NOTIFICATION_VALUE_INDEX, value); + if (ret == NativeRdb::E_SQLITE_CORRUPT) { + RestoreForMasterSlaver(); + } if (ret != NativeRdb::E_OK) { ANS_LOGE("GetString value failed from %{public}s table.", tableName.c_str()); return NativeRdb::E_ERROR; @@ -390,6 +409,9 @@ int32_t NotificationDataMgr::QueryData(const std::string tableName, const std::s } int32_t ret = absSharedResultSet->GoToFirstRow(); + if (ret == NativeRdb::E_SQLITE_CORRUPT) { + RestoreForMasterSlaver(); + } if (ret != NativeRdb::E_OK) { ANS_LOGW("GoToFirstRow failed from %{public}s table. It is empty!, key=%{public}s", tableName.c_str(), key.c_str()); @@ -440,6 +462,9 @@ int32_t NotificationDataMgr::QueryDataBeginWithKey( } int32_t ret = absSharedResultSet->GoToFirstRow(); + if (ret == NativeRdb::E_SQLITE_CORRUPT) { + RestoreForMasterSlaver(); + } if (ret != NativeRdb::E_OK) { ANS_LOGD("GoToFirstRow failed from %{public}s table.It is empty!, key=%{public}s", tableName.c_str(), key.c_str()); @@ -501,6 +526,9 @@ int32_t NotificationDataMgr::QueryAllData( } int32_t ret = absSharedResultSet->GoToFirstRow(); + if (ret == NativeRdb::E_SQLITE_CORRUPT) { + RestoreForMasterSlaver(); + } if (ret != NativeRdb::E_OK) { ANS_LOGD("GoToFirstRow failed from %{public}s table. It is empty!", tableName.c_str()); return NativeRdb::E_EMPTY_VALUES_BUCKET; @@ -601,5 +629,13 @@ std::vector NotificationDataMgr::GenerateOperatedTables(const int32 operatedTables.emplace_back(notificationRdbConfig_.tableName); return operatedTables; } + +int32_t NotificationDataMgr::RestoreForMasterSlaver() +{ + ANS_LOGI("RestoreForMasterSlaver start"); + int32_t result = rdbStore_->Restore(""); + ANS_LOGI("RestoreForMasterSlaver result = %{public}d", result); + return result; +} } } \ No newline at end of file -- Gitee From 4f2b7b05788312c5449c6e04ecb2e01caa31ca39 Mon Sep 17 00:00:00 2001 From: xdongs Date: Tue, 8 Oct 2024 18:23:07 +0800 Subject: [PATCH 069/167] =?UTF-8?q?=E5=BC=B9=E7=AA=97=E5=8A=A0=E5=9B=BA5.1?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: xdongs --- .../AppScope/app.json | 4 +- .../NotificationServiceExtAbility.ts | 125 ++++++++---------- .../entry/src/main/ets/common/constant.ets | 12 +- .../src/main/ets/pages/notificationDialog.ets | 76 +++++------ .../main/resources/base/element/color.json | 4 + .../main/resources/dark/element/color.json | 4 + 6 files changed, 112 insertions(+), 113 deletions(-) diff --git a/services/dialog_ui/enable_notification_dialog/AppScope/app.json b/services/dialog_ui/enable_notification_dialog/AppScope/app.json index e343d1803..ed9af7643 100644 --- a/services/dialog_ui/enable_notification_dialog/AppScope/app.json +++ b/services/dialog_ui/enable_notification_dialog/AppScope/app.json @@ -2,8 +2,8 @@ "app": { "bundleName": "com.ohos.notificationdialog", "vendor": "example", - "versionCode": 1000010, - "versionName": "1.1.0", + "versionCode": 1000011, + "versionName": "1.1.1", "icon": "$media:app_icon", "label": "$string:app_name", "distributedNotificationEnabled": true, diff --git a/services/dialog_ui/enable_notification_dialog/entry/src/main/ets/ServiceExtAbility/NotificationServiceExtAbility.ts b/services/dialog_ui/enable_notification_dialog/entry/src/main/ets/ServiceExtAbility/NotificationServiceExtAbility.ts index d974670e6..0c6f8201f 100644 --- a/services/dialog_ui/enable_notification_dialog/entry/src/main/ets/ServiceExtAbility/NotificationServiceExtAbility.ts +++ b/services/dialog_ui/enable_notification_dialog/entry/src/main/ets/ServiceExtAbility/NotificationServiceExtAbility.ts @@ -30,12 +30,11 @@ import Constants from '../common/constant'; const TAG = 'NotificationDialog_Service '; -const UPDATE_INIT = -1; +const UPDATE_INIT = 1; const UPDATE_NUM = 1; const UPDATE_BOUNDARY = 100; - -let systemLanguage: string; +let eventSubscriber:CommonEventManager.CommonEventSubscriber; const enableNotificationDialogDestroyedEvent = { eventId: 1, @@ -89,49 +88,6 @@ export class EnableNotificationDialog { this.extensionWindow = undefined; } - async createWindow(windowType: window.WindowType, context, displayRect): Promise { - try { - let winArgs = { - 'name': `${EnableNotificationDialog.ENABLE_NOTIFICATION_DIALOG_NAME}${this.id}`, - 'windowType': windowType, - 'ctx': context - }; - let win = await window.createWindow(winArgs); - this.window = win; - let shouldHide = true; - - if (windowType === window.WindowType.TYPE_DIALOG) { - await win.bindDialogTarget(this.want.parameters.callerToken['value'], - async (): Promise => { - console.info(TAG, `window ${this.id} died`); - await this.destroyException(); - } - ); - } - - this.storage = new LocalStorage({ - 'dialog': this - }); - await win.moveWindowTo(displayRect.left, displayRect.top); - await win.resize(displayRect.width, displayRect.height); - await win.loadContent(EnableNotificationDialog.DIALOG_PATH, this.storage); - try { - await win.hideNonSystemFloatingWindows(shouldHide); - } catch (err) { - console.error(TAG, 'window hideNonSystemFloatingWindows failed!'); - } - await win.setWindowBackgroundColor(EnableNotificationDialog.TRANSPARANT_COLOR); - await win.showWindow(); - await win.setWindowLayoutFullScreen(true); - } catch (err) { - if (this.window !== undefined) { - await this.destroyWindow(); - } - console.error(TAG, 'window create failed!'); - throw new Error('Failed to create window'); - } - } - async createUiExtensionWindow(session: UIExtensionContentSession, stageModel: boolean): Promise { try { @@ -164,9 +120,10 @@ export class EnableNotificationDialog { }; let subWindow = await extensionWindow.createSubWindowWithOptions('subWindowForHost' + Date(), subWindowOpts); this.subWindow = subWindow; - let dis = display.getDefaultDisplaySync(); - await subWindow?.resize(dis.width, dis.height); - console.info(TAG, `size : ${dis.width} ${dis.height}`); + let windowRect = extensionWindow.properties?.uiExtensionHostWindowProxyRect; + await subWindow.moveWindowTo(windowRect?.left, windowRect?.top); + await subWindow.resize(windowRect?.width, windowRect?.height); + console.info(TAG, `size : ${windowRect.left} ${windowRect.top} ${windowRect.width} ${windowRect.height}`); await subWindow.loadContent(EnableNotificationDialog.DIALOG_PATH, this.storage); try { await subWindow.hideNonSystemFloatingWindows(true); @@ -229,26 +186,12 @@ export class EnableNotificationDialog { class NotificationDialogServiceExtensionAbility extends UIExtensionAbility { - onConfigurationUpdate(newConfig): void { - console.log(TAG, 'onConfigurationUpdate'); - if (systemLanguage !== newConfig.language) { - console.log(TAG, `onConfigurationUpdate newConfig is ${JSON.stringify(newConfig)}`); - systemLanguage = newConfig.language; - let isUpdate:number = AppStorage.get('isUpdate'); - if (isUpdate === undefined || isUpdate > UPDATE_BOUNDARY) { - AppStorage.setOrCreate('isUpdate', UPDATE_NUM); - } else { - AppStorage.setOrCreate('isUpdate', ++isUpdate); - } - } - } - - onCreate() { console.log(TAG, `UIExtAbility onCreate`); AppStorage.setOrCreate('context', this.context); AppStorage.setOrCreate('isUpdate', UPDATE_INIT); - systemLanguage = this.context.config.language; + AppStorage.setOrCreate('clicked', false); + this.subscribe(); } @@ -269,7 +212,6 @@ class NotificationDialogServiceExtensionAbility extends UIExtensionAbility { `uid ${want.parameters.bundleUid}`); let dialog = new EnableNotificationDialog(1, want, stageModel); await dialog.createUiExtensionWindow(session, stageModel); - AppStorage.setOrCreate('clicked', false); AppStorage.setOrCreate('dialog', dialog); } catch (err) { console.error(TAG, `Failed to handle onSessionCreate`); @@ -324,10 +266,59 @@ class NotificationDialogServiceExtensionAbility extends UIExtensionAbility { } } - onDestroy() { + async onDestroy() { console.info(TAG, 'UIExtAbility onDestroy.'); + await this.unsubscribe(); + await this.sleep(500); this.context.terminateSelf(); } + + async sleep(ms: number): Promise { + return new Promise(resolve => setTimeout(resolve, ms)); + } + + async subscribe() { + CommonEventManager.createSubscriber( + { events: ['usual.event.BUNDLE_RESOURCES_CHANGED'] }, (err, subscriber) => { + if (err?.code) { + console.error(TAG, `createSubscriber callBack err = ${JSON.stringify(err)}`); + } else { + eventSubscriber = subscriber; + console.log(TAG, "create subscriber succeed"); + if (eventSubscriber != null) { + console.log(TAG, "subscriber subscribe BUNDLE_RESOURCES_CHANGED event"); + CommonEventManager.subscribe(eventSubscriber, (err, data) => { + if (err?.code) { + console.error(TAG, `subscribe callBack err= ${JSON.stringify(err)}`); + } else { + console.log(TAG, `subscribe callBack data= ${JSON.stringify(data)}`); + if(data.parameters?.bundleResourceChangeType == 1){ + console.log(TAG, `BUNDLE_RESOURCES_CHANGED-language change`); + let isUpdate:number = AppStorage.get('isUpdate'); + if (isUpdate === undefined || isUpdate > UPDATE_BOUNDARY) { + AppStorage.setOrCreate('isUpdate', UPDATE_NUM); + } else { + AppStorage.setOrCreate('isUpdate', ++isUpdate); + } + } + } + }) + } else { + console.info(TAG, "need create subscriber"); + } + } + }); + } + + async unsubscribe() { + try { + if (eventSubscriber != null) { + CommonEventManager.unsubscribe(eventSubscriber, (err) => {}); + } + } catch (err) { + console.info("ubsubscribe fail"); + } + } } diff --git a/services/dialog_ui/enable_notification_dialog/entry/src/main/ets/common/constant.ets b/services/dialog_ui/enable_notification_dialog/entry/src/main/ets/common/constant.ets index 721c6021c..a1f3d2be6 100644 --- a/services/dialog_ui/enable_notification_dialog/entry/src/main/ets/common/constant.ets +++ b/services/dialog_ui/enable_notification_dialog/entry/src/main/ets/common/constant.ets @@ -125,12 +125,12 @@ export default class Constants { static DIALOG_REQ_LINE_HEIGHT = 24; // description text of dialog - static DIALOG_DESP_FONT_SIZE = 16; - static DIALOG_DESP_MARGIN_TOP = 0; - static DIALOG_DESP_MARGIN_LEFT = 24; - static DIALOG_DESP_MARGIN_RIGHT = 24; - static DIALOG_DESP_MARGIN_BOTTOM = 12; - static DIALOG_DESP_LINE_HEIGHT = 21; + public static DIALOG_DESP_FONT_SIZE = 16; + public static DIALOG_DESP_MARGIN_TOP = 0; + public static DIALOG_DESP_MARGIN_LEFT = 24; + public static DIALOG_DESP_MARGIN_RIGHT = 24; + public static DIALOG_DESP_MARGIN_BOTTOM = 8; + public static DIALOG_DESP_LINE_HEIGHT = 21; static BUTTON_MARGIN_TOP = 8; static BUTTON_MARGIN_LEFT = 16; diff --git a/services/dialog_ui/enable_notification_dialog/entry/src/main/ets/pages/notificationDialog.ets b/services/dialog_ui/enable_notification_dialog/entry/src/main/ets/pages/notificationDialog.ets index fafb69cba..9f6962ee1 100644 --- a/services/dialog_ui/enable_notification_dialog/entry/src/main/ets/pages/notificationDialog.ets +++ b/services/dialog_ui/enable_notification_dialog/entry/src/main/ets/pages/notificationDialog.ets @@ -35,39 +35,36 @@ const bottomPopoverTypes = ['default', 'phone']; let storage = LocalStorage.getShared(); @Extend(Button) function rightCustomizeButton() { - .backgroundColor($r('app.color.dialog_bg')) + .backgroundColor(Color.Transparent) .fontColor($r('app.color.button_text')) .fontSize(Constants.TEXT_MIDDLE_FONT_SIZE) .fontWeight(FontWeight.Medium) .height(Constants.BUTTON_HEIGHT) .flexGrow(Constants.FLEX_GROW) - .margin({ - left: Constants.BUTTON_LEFT - }) + .width('50%') } @Extend(Button) function leftCustomizeButton() { - .backgroundColor($r('app.color.dialog_bg')) + .backgroundColor(Color.Transparent) .fontColor($r('app.color.button_text')) .fontSize(Constants.TEXT_MIDDLE_FONT_SIZE) .fontWeight(FontWeight.Medium) .height(Constants.BUTTON_HEIGHT) .flexGrow(Constants.FLEX_GROW) - .margin({ - right: Constants.BUTTON_RIGHT - }) + .width('50%') } @Entry(storage) @Component struct NotificationDialogPage { - @StorageLink('isUpdate') isUpdate: number = -1; + @StorageLink('isUpdate') isUpdate: number = 0; privacyDialogController: CustomDialogController = new CustomDialogController({ builder: PermissionDialog({ isUpdate: $isUpdate }), autoCancel: false, alignment: DialogAlignment.Center, customStyle: true, + maskColor: $r('app.color.mask_thin'), onWillDismiss: (dismissDialogAction: DismissDialogAction) => { console.info(TAG, `dialog onWillDismiss reason= : ${JSON.stringify(dismissDialogAction.reason)}`); } @@ -80,7 +77,6 @@ struct NotificationDialogPage { } onPageShow() { - this.isUpdate++; } } @@ -101,14 +97,16 @@ struct PermissionDialog { offset: {xs: Constants.XS_OFFSET, sm: Constants.SM_OFFSET, md: Constants.DIALOG_MD_OFFSET, lg: Constants.DIALOG_LG_OFFSET} }) { Flex({ justifyContent: FlexAlign.Center, alignItems: this.isBottomPopover ? ItemAlign.End : ItemAlign.Center }) { Column() { - Image(permission.icon) - .width(Constants.DIALOG_ICON_WIDTH) - .height(Constants.DIALOG_ICON_HEIGHT) - .margin({ - top: Constants.DIALOG_ICON_MARGIN_TOP - }) Scroll() { Column() { + Row() { + Image(permission.icon) + .width(Constants.DIALOG_ICON_WIDTH) + .height(Constants.DIALOG_ICON_HEIGHT) + .margin({ + top: Constants.DIALOG_ICON_MARGIN_TOP + }) + } Row() { Flex({ justifyContent: FlexAlign.Center }) { Text() { @@ -118,6 +116,8 @@ struct PermissionDialog { .fontColor($r('app.color.text_primary')) .fontWeight(FontWeight.Bold) .lineHeight(Constants.DIALOG_REQ_LINE_HEIGHT) + .maxLines(2) + .textOverflow({overflow: TextOverflow.Ellipsis}) .margin({ top: Constants.DIALOG_REQ_MARGIN_TOP, bottom:Constants.DIALOG_REQ_MARGIN_BUTTOM, @@ -144,35 +144,35 @@ struct PermissionDialog { }) } } + Row() { + Flex({ justifyContent: FlexAlign.SpaceBetween, alignItems: ItemAlign.Center }) { + Button($r('app.string.BAN')) + .onClick(async (): Promise => { + await this.enableNotification(false); + }) + .leftCustomizeButton() + Divider() + .color($r('app.color.comp_divider')) + .vertical(true) + .height(Constants.DIVIDER_HEIGHT) + .strokeWidth(Constants.DIVIDER_WIDTH) + .margin({left: Constants.BUTTON_LEFT, right: Constants.BUTTON_RIGHT}) + Button($r('app.string.ALLOW')) + .onClick(async (): Promise => { + await this.enableNotification(true); + }) + .rightCustomizeButton() + } + .margin({ left: Constants.BUTTON_MARGIN_LEFT, right: Constants.BUTTON_MARGIN_RIGHT }) + } } } .constraintSize({ maxHeight: Constants.MAXIMUM_HEADER_HEIGHT }) - Row() { - Flex({ justifyContent: FlexAlign.SpaceBetween, alignItems: ItemAlign.Center }) { - Button($r('app.string.BAN')) - .onClick(async (): Promise => { - await this.enableNotification(false); - }) - .leftCustomizeButton() - Divider() - .color($r('app.color.comp_divider')) - .vertical(true) - .height(Constants.DIVIDER_HEIGHT) - .strokeWidth(Constants.DIVIDER_WIDTH) - Button($r('app.string.ALLOW')) - .onClick(async (): Promise => { - await this.enableNotification(true); - }) - .rightCustomizeButton() - } - .margin({ left: Constants.BUTTON_MARGIN_LEFT, right: Constants.BUTTON_MARGIN_RIGHT }) - } } - .backgroundColor($r('app.color.dialog_bg')) .borderRadius(Constants.DIALOG_PRIVACY_BORDER_RADIUS) + .backgroundBlurStyle(BlurStyle.COMPONENT_ULTRA_THICK) .width(Constants.FULL_WIDTH) .padding({ bottom: Constants.DIALOG_PADDING_BOTTOM }) - .margin({ bottom: $r('sys.float.ohos_id_dialog_margin_bottom') }) .clip(true) } .width(Constants.FULL_WIDTH) diff --git a/services/dialog_ui/enable_notification_dialog/entry/src/main/resources/base/element/color.json b/services/dialog_ui/enable_notification_dialog/entry/src/main/resources/base/element/color.json index 33aaa77dc..84e0cfbe6 100644 --- a/services/dialog_ui/enable_notification_dialog/entry/src/main/resources/base/element/color.json +++ b/services/dialog_ui/enable_notification_dialog/entry/src/main/resources/base/element/color.json @@ -31,6 +31,10 @@ { "name": "button_text", "value": "#0A59F7" + }, + { + "name": "mask_thin", + "value": "#33000000" } ] } \ No newline at end of file diff --git a/services/dialog_ui/enable_notification_dialog/entry/src/main/resources/dark/element/color.json b/services/dialog_ui/enable_notification_dialog/entry/src/main/resources/dark/element/color.json index d5a8a1436..80bcbe0f4 100644 --- a/services/dialog_ui/enable_notification_dialog/entry/src/main/resources/dark/element/color.json +++ b/services/dialog_ui/enable_notification_dialog/entry/src/main/resources/dark/element/color.json @@ -15,6 +15,10 @@ { "name": "button_text", "value": "#5291FF" + }, + { + "name": "mask_thin", + "value": "#66000000" } ] } \ No newline at end of file -- Gitee From 2473449313be6d6ef1fe4a0ad3fdeaee1d0c935c Mon Sep 17 00:00:00 2001 From: xdongs Date: Wed, 9 Oct 2024 15:42:23 +0800 Subject: [PATCH 070/167] =?UTF-8?q?=E5=88=A0=E9=99=A4=E5=BC=B9=E7=AA=97?= =?UTF-8?q?=E7=BC=93=E5=AD=98?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: xdongs --- frameworks/ans/src/notification_helper.cpp | 5 ++ .../core/include/ans_manager_interface.h | 7 +++ frameworks/core/include/ans_manager_proxy.h | 7 +++ frameworks/core/include/ans_manager_stub.h | 8 +++ frameworks/core/include/ans_notification.h | 7 +++ ..._notification_service_ipc_interface_code.h | 1 + frameworks/core/src/ans_manager_proxy.cpp | 22 +++++++ frameworks/core/src/ans_manager_stub.cpp | 14 +++++ .../core/src/ans_manager_stub_invalid.cpp | 6 ++ frameworks/core/src/ans_notification.cpp | 11 ++++ .../manager/napi_enable_notification.h | 1 - .../src/manager/napi_enable_notification.cpp | 29 +-------- interfaces/inner_api/notification_helper.h | 7 +++ .../include/advanced_notification_service.h | 9 +++ .../ans/include/notification_dialog_manager.h | 10 +++- .../ans/include/system_dialog_connect_stb.h | 2 - .../advanced_notification_publish_service.cpp | 23 +++++++ services/ans/src/notification_dialog.cpp | 2 +- .../ans/src/system_dialog_connect_stb.cpp | 60 +++++++------------ 19 files changed, 158 insertions(+), 73 deletions(-) diff --git a/frameworks/ans/src/notification_helper.cpp b/frameworks/ans/src/notification_helper.cpp index 0cad2612f..15e691700 100644 --- a/frameworks/ans/src/notification_helper.cpp +++ b/frameworks/ans/src/notification_helper.cpp @@ -170,6 +170,11 @@ ErrCode NotificationHelper::CanPopEnableNotificationDialog(sptr::GetInstance()->RemoveEnableNotificationDialog(); +} + ErrCode NotificationHelper::RequestEnableNotification(std::string &deviceId, sptr &hostClient, sptr &callerToken) diff --git a/frameworks/core/include/ans_manager_interface.h b/frameworks/core/include/ans_manager_interface.h index 790abe0ce..b77d61779 100644 --- a/frameworks/core/include/ans_manager_interface.h +++ b/frameworks/core/include/ans_manager_interface.h @@ -509,6 +509,13 @@ public: virtual ErrCode CanPopEnableNotificationDialog(const sptr &callback, bool &canPop, std::string &bundleName) = 0; + /** + * @brief remove enable notification dialog. + * + * @return Returns remove dialog result. + */ + virtual ErrCode RemoveEnableNotificationDialog() = 0; + /** * @brief Checks whether notifications are allowed for a specific bundle. * diff --git a/frameworks/core/include/ans_manager_proxy.h b/frameworks/core/include/ans_manager_proxy.h index 59bf9a7eb..36d3b689d 100644 --- a/frameworks/core/include/ans_manager_proxy.h +++ b/frameworks/core/include/ans_manager_proxy.h @@ -497,6 +497,13 @@ public: ErrCode CanPopEnableNotificationDialog(const sptr &callback, bool &canPop, std::string &bundleName) override; + /** + * @brief remove enable notification dialog. + * + * @return Returns remove dialog result. + */ + ErrCode RemoveEnableNotificationDialog() override; + /** * @brief Checks whether notifications are allowed for a specific bundle. * diff --git a/frameworks/core/include/ans_manager_stub.h b/frameworks/core/include/ans_manager_stub.h index 0ec670f8f..9c092b534 100644 --- a/frameworks/core/include/ans_manager_stub.h +++ b/frameworks/core/include/ans_manager_stub.h @@ -496,6 +496,13 @@ public: ErrCode CanPopEnableNotificationDialog(const sptr &callback, bool &canPop, std::string &bundleName) override; + /** + * @brief remove enable notification dialog. + * + * @return Returns remove dialog result. + */ + ErrCode RemoveEnableNotificationDialog() override; + /** * @brief Checks whether notifications are allowed for a specific bundle. * @@ -987,6 +994,7 @@ private: ErrCode HandleIsAllowedNotify(MessageParcel &data, MessageParcel &reply); ErrCode HandleIsAllowedNotifySelf(MessageParcel &data, MessageParcel &reply); ErrCode HandleCanPopEnableNotificationDialog(MessageParcel &data, MessageParcel &reply); + ErrCode HandleRemoveEnableNotificationDialog(MessageParcel &data, MessageParcel &reply); ErrCode HandleIsSpecialBundleAllowedNotify(MessageParcel &data, MessageParcel &reply); ErrCode HandleIsDistributedEnabled(MessageParcel &data, MessageParcel &reply); ErrCode HandleEnableDistributed(MessageParcel &data, MessageParcel &reply); diff --git a/frameworks/core/include/ans_notification.h b/frameworks/core/include/ans_notification.h index c45c7332b..3359afba4 100644 --- a/frameworks/core/include/ans_notification.h +++ b/frameworks/core/include/ans_notification.h @@ -299,6 +299,13 @@ public: ErrCode CanPopEnableNotificationDialog(sptr &hostClient, bool &canPop, std::string &bundleName); + /** + * @brief remove enable notification dialog. + * + * @return Returns remove dialog result. + */ + ErrCode RemoveEnableNotificationDialog(); + /** * @brief Allows the current application to publish notifications on a specified device. * diff --git a/frameworks/core/include/distributed_notification_service_ipc_interface_code.h b/frameworks/core/include/distributed_notification_service_ipc_interface_code.h index 56e520eb6..34ac6a24d 100644 --- a/frameworks/core/include/distributed_notification_service_ipc_interface_code.h +++ b/frameworks/core/include/distributed_notification_service_ipc_interface_code.h @@ -76,6 +76,7 @@ namespace Notification { IS_ALLOWED_NOTIFY, IS_ALLOWED_NOTIFY_SELF, CAN_POP_ENABLE_NOTIFICATION_DIALOG, + REMOVE_ENABLE_NOTIFICATION_DIALOG, IS_SPECIAL_BUNDLE_ALLOWED_NOTIFY, SET_DO_NOT_DISTURB_DATE, GET_DO_NOT_DISTURB_DATE, diff --git a/frameworks/core/src/ans_manager_proxy.cpp b/frameworks/core/src/ans_manager_proxy.cpp index 1d185722d..56716d525 100644 --- a/frameworks/core/src/ans_manager_proxy.cpp +++ b/frameworks/core/src/ans_manager_proxy.cpp @@ -1316,6 +1316,28 @@ ErrCode AnsManagerProxy::CanPopEnableNotificationDialog(const sptr &bundleOption, bool &allowed) { if (bundleOption == nullptr) { diff --git a/frameworks/core/src/ans_manager_stub.cpp b/frameworks/core/src/ans_manager_stub.cpp index 45fe93921..ad4698eb6 100644 --- a/frameworks/core/src/ans_manager_stub.cpp +++ b/frameworks/core/src/ans_manager_stub.cpp @@ -223,6 +223,10 @@ int32_t AnsManagerStub::OnRemoteRequest(uint32_t code, MessageParcel &data, Mess result = HandleCanPopEnableNotificationDialog(data, reply); break; } + case static_cast(NotificationInterfaceCode::REMOVE_ENABLE_NOTIFICATION_DIALOG): { + result = HandleRemoveEnableNotificationDialog(data, reply); + break; + } case static_cast(NotificationInterfaceCode::IS_SPECIAL_BUNDLE_ALLOWED_NOTIFY): { result = HandleIsSpecialBundleAllowedNotify(data, reply); break; @@ -1644,6 +1648,16 @@ ErrCode AnsManagerStub::HandleCanPopEnableNotificationDialog(MessageParcel &data return ERR_OK; } +ErrCode AnsManagerStub::HandleRemoveEnableNotificationDialog(MessageParcel &data, MessageParcel &reply) +{ + ErrCode result = RemoveEnableNotificationDialog(); + if (!reply.WriteInt32(result)) { + ANS_LOGE("[HandleRemoveEnableNotificationDialog] fail: write result failed, ErrCode=%{public}d", result); + return ERR_ANS_PARCELABLE_FAILED; + } + return ERR_OK; +} + ErrCode AnsManagerStub::HandleIsSpecialBundleAllowedNotify(MessageParcel &data, MessageParcel &reply) { sptr bundleOption = data.ReadParcelable(); diff --git a/frameworks/core/src/ans_manager_stub_invalid.cpp b/frameworks/core/src/ans_manager_stub_invalid.cpp index 0457626d0..15c3db577 100644 --- a/frameworks/core/src/ans_manager_stub_invalid.cpp +++ b/frameworks/core/src/ans_manager_stub_invalid.cpp @@ -351,6 +351,12 @@ ErrCode AnsManagerStub::CanPopEnableNotificationDialog(const sptr &bundleOption, bool &allowed) { ANS_LOGE("AnsManagerStub::IsSpecialBundleAllowedNotify called!"); diff --git a/frameworks/core/src/ans_notification.cpp b/frameworks/core/src/ans_notification.cpp index e75c0dfb8..723d8ccd8 100644 --- a/frameworks/core/src/ans_notification.cpp +++ b/frameworks/core/src/ans_notification.cpp @@ -443,6 +443,17 @@ ErrCode AnsNotification::CanPopEnableNotificationDialog(sptrCanPopEnableNotificationDialog(hostClient, canPop, bundleName); } +ErrCode AnsNotification::RemoveEnableNotificationDialog() +{ + ANS_LOGD("enter"); + sptr proxy = GetAnsManagerProxy(); + if (!proxy) { + ANS_LOGE("GetAnsManagerProxy fail."); + return ERR_ANS_SERVICE_NOT_CONNECTED; + } + return proxy->RemoveEnableNotificationDialog(); +} + ErrCode AnsNotification::RequestEnableNotification(std::string &deviceId, sptr &hostClient, sptr &callerToken) diff --git a/frameworks/js/napi/include/manager/napi_enable_notification.h b/frameworks/js/napi/include/manager/napi_enable_notification.h index 76f84b513..65ee9f4da 100644 --- a/frameworks/js/napi/include/manager/napi_enable_notification.h +++ b/frameworks/js/napi/include/manager/napi_enable_notification.h @@ -33,7 +33,6 @@ napi_value NapiGetAllNotificationEnabledBundles(napi_env env, napi_callback_info napi_value ParseRequestEnableParameters(const napi_env &env, const napi_callback_info &info, IsEnableParams ¶ms); napi_value NapiIsNotificationEnabledSync(napi_env env, napi_callback_info info); bool CreateUIExtension(std::shared_ptr context, std::string &bundleName); -void SendDialogEvent(std::string &bundleName, int32_t code); void SetEnableParam(IsEnableParams ¶ms, const napi_env &env, napi_value &object); class ModalExtensionCallback { diff --git a/frameworks/js/napi/src/manager/napi_enable_notification.cpp b/frameworks/js/napi/src/manager/napi_enable_notification.cpp index 4d3ed36b0..cc454cd4b 100644 --- a/frameworks/js/napi/src/manager/napi_enable_notification.cpp +++ b/frameworks/js/napi/src/manager/napi_enable_notification.cpp @@ -23,9 +23,6 @@ #include "js_ans_dialog_callback.h" #include "common_event_manager.h" -constexpr int32_t CRASH_CODE = 2; -constexpr int32_t REMOVE_CODE = 3; - namespace OHOS { namespace NotificationNapi { const int IS_NOTIFICATION_ENABLE_MAX_PARA = 2; @@ -300,7 +297,7 @@ napi_value NapiRequestEnableNotification(napi_env env, napi_callback_info info) asynccallbackinfo->info.errorCode = ERR_ANS_DIALOG_POP_SUCCEEDED; } else { asynccallbackinfo->info.errorCode = ERROR_INTERNAL_ERROR; - SendDialogEvent(bundleName, REMOVE_CODE); + NotificationHelper::RemoveEnableNotificationDialog(); } } else { ANS_LOGD("un stage mode"); @@ -562,28 +559,6 @@ bool CreateUIExtension(std::shared_ptr context, s return true; } -void SendDialogEvent(std::string &bundleName, int32_t code) -{ - ANS_LOGD("SendDialogEvent start"); - if (bundleName.empty()) { - ANS_LOGE("SendDialogEvent bundleName is nullptr"); - return; - } - std::string action = "OnNotificationServiceDialogClicked"; - - EventFwk::Want want; - want.SetAction(action); - - EventFwk::CommonEventData commonData; - commonData.SetWant(want); - commonData.SetCode(code); - commonData.SetData(bundleName); - if (!EventFwk::CommonEventManager::PublishCommonEvent(commonData)) { - ANS_LOGE("PublishCommonEvent failed"); - } - ANS_LOGD("SendDialogEvent end"); -} - void SetEnableParam(IsEnableParams ¶ms, const napi_env &env, napi_value &object) { auto context = OHOS::AbilityRuntime::GetStageModeContext(env, object); @@ -636,7 +611,7 @@ void ModalExtensionCallback::OnError(int32_t code, const std::string& name, cons { ANS_LOGE("OnError, name = %{public}s, message = %{public}s", name.c_str(), message.c_str()); ReleaseOrErrorHandle(code); - SendDialogEvent(this->bundleName_, CRASH_CODE); + NotificationHelper::RemoveEnableNotificationDialog(); } /* diff --git a/interfaces/inner_api/notification_helper.h b/interfaces/inner_api/notification_helper.h index 5b35ec72b..aa47d35df 100644 --- a/interfaces/inner_api/notification_helper.h +++ b/interfaces/inner_api/notification_helper.h @@ -299,6 +299,13 @@ public: */ static ErrCode CanPopEnableNotificationDialog(sptr &hostClient, bool &canPop, std::string &bundleName); + + /** + * @brief remove enable notification dialog. + * + * @return Returns remove dialog result. + */ + static ErrCode RemoveEnableNotificationDialog(); /** * @brief Allow the current application to publish notifications on a specified device. diff --git a/services/ans/include/advanced_notification_service.h b/services/ans/include/advanced_notification_service.h index 1f236f8d2..d2af0fab1 100644 --- a/services/ans/include/advanced_notification_service.h +++ b/services/ans/include/advanced_notification_service.h @@ -548,6 +548,15 @@ public: */ ErrCode CanPopEnableNotificationDialog(const sptr &callback, bool &canPop, std::string &bundleName) override; + + /** + * @brief remove enable notification dialog. + * + * @return Returns remove dialog result. + */ + ErrCode RemoveEnableNotificationDialog() override; + + ErrCode RemoveEnableNotificationDialog(const sptr &bundleOption); /** * @brief Checks whether notifications are allowed for a specific bundle. diff --git a/services/ans/include/notification_dialog_manager.h b/services/ans/include/notification_dialog_manager.h index 67dc13619..2d8b63877 100644 --- a/services/ans/include/notification_dialog_manager.h +++ b/services/ans/include/notification_dialog_manager.h @@ -101,6 +101,13 @@ public: * @return ERR_OK when add Dialog successfully */ ErrCode AddDialogInfo(const sptr& bundle, const sptr& callback); + + /* + * RemoveDialogInfoByBundleOption + * @return void + */ + void RemoveDialogInfoByBundleOption(const sptr& bundle, + std::unique_ptr& dialogInfoRemoved); inline static const std::string NOTIFICATION_DIALOG_SERVICE_BUNDLE = "com.ohos.notificationdialog"; inline static const std::string NOTIFICATION_DIALOG_SERVICE_ABILITY = "EnableNotificationDialog"; @@ -112,9 +119,6 @@ private: // bundle need to be not null bool AddDialogInfoIfNotExist(const sptr& bundle, const sptr& callback); sptr GetBundleOptionByBundleName(const std::string& bundleName, const int32_t& uid); - // bundle need to be not null - void RemoveDialogInfoByBundleOption(const sptr& bundle, - std::unique_ptr& dialogInfoRemoved); void RemoveAllDialogInfos(std::list>& dialogInfosRemoved); bool OnDialogButtonClicked(const std::string& bundleName, const int32_t& uid, bool enabled); diff --git a/services/ans/include/system_dialog_connect_stb.h b/services/ans/include/system_dialog_connect_stb.h index 89f09b2a5..3b0ad5be2 100644 --- a/services/ans/include/system_dialog_connect_stb.h +++ b/services/ans/include/system_dialog_connect_stb.h @@ -38,8 +38,6 @@ public: const sptr &remoteObject, int32_t resultCode) override; void OnAbilityDisconnectDone(const AppExecFwk::ElementName &element, int32_t resultCode) override; - void SendRemoveBundleEvent(); - private: std::string commandStr_; }; diff --git a/services/ans/src/advanced_notification_publish_service.cpp b/services/ans/src/advanced_notification_publish_service.cpp index f9dc40daa..b232c4ca4 100644 --- a/services/ans/src/advanced_notification_publish_service.cpp +++ b/services/ans/src/advanced_notification_publish_service.cpp @@ -908,6 +908,29 @@ ErrCode AdvancedNotificationService::CanPopEnableNotificationDialog( ANS_LOGI("CanPopEnableNotificationDialog end"); } +ErrCode AdvancedNotificationService::RemoveEnableNotificationDialog() +{ + ANS_LOGD("%{public}s", __FUNCTION__); + ErrCode result = ERR_OK; + sptr bundleOption = GenerateBundleOption(); + if (bundleOption == nullptr) { + ANS_LOGE("bundleOption == nullptr"); + return ERR_ANS_INVALID_BUNDLE; + } + return RemoveEnableNotificationDialog(bundleOption); +} + +ErrCode AdvancedNotificationService::RemoveEnableNotificationDialog(const sptr &bundleOption) +{ + ANS_LOGI("RemoveEnableNotificationDialog %{public}s, %{public}d", bundleOption->GetBundleName().c_str(), bundleOption->GetUid()); + if (!CreateDialogManager()) { + return ERROR_INTERNAL_ERROR; + } + std::unique_ptr dialogInfoRemoved = nullptr; + dialogManager_->RemoveDialogInfoByBundleOption(bundleOption, dialogInfoRemoved); + return ERR_OK; +} + ErrCode AdvancedNotificationService::IsAllowedNotifySelf(const sptr &bundleOption, bool &allowed) { diff --git a/services/ans/src/notification_dialog.cpp b/services/ans/src/notification_dialog.cpp index 58f98d970..cd01f5b96 100644 --- a/services/ans/src/notification_dialog.cpp +++ b/services/ans/src/notification_dialog.cpp @@ -62,7 +62,7 @@ ErrCode NotificationDialog::StartEnableNotificationDialogAbility( auto topBundleName = IN_PROCESS_CALL(AAFwk::AbilityManagerClient::GetInstance()->GetTopAbility().GetBundleName()); auto topUid = NotificationDialog::GetUidByBundleName(topBundleName); if (topBundleName != appBundleName) { - ANS_LOGE("Current application isn't in foreground, top is %{private}s.", topBundleName.c_str()); + ANS_LOGE("Current application isn't in foreground, top is %{public}s.", topBundleName.c_str()); return ERR_ANS_INVALID_BUNDLE; } diff --git a/services/ans/src/system_dialog_connect_stb.cpp b/services/ans/src/system_dialog_connect_stb.cpp index 9035552b2..d96efe3bb 100644 --- a/services/ans/src/system_dialog_connect_stb.cpp +++ b/services/ans/src/system_dialog_connect_stb.cpp @@ -18,10 +18,10 @@ #include "ans_log_wrapper.h" #include "ans_inner_errors.h" #include "common_event_manager.h" +#include "advanced_notification_service.h" +#include "notification_bundle_option.h" constexpr int32_t SIGNAL_NUM = 3; -constexpr int32_t REMOVE_BUNDLE_CODE = 3; -const static std::string DIALOG_CRASH_EVENT = "OnNotificationServiceDialogClicked"; namespace OHOS { namespace Notification { @@ -44,8 +44,25 @@ void SystemDialogConnectStb::OnAbilityConnectDone(const AppExecFwk::ElementName int32_t errCode = remoteObject->SendRequest(IAbilityConnection::ON_ABILITY_CONNECT_DONE, data, reply, option); ANS_LOGI("AbilityConnectionWrapperProxy::OnAbilityConnectDone result %{public}d", errCode); if (errCode != ERR_OK) { - ANS_LOGD("send Request to SytemDialog fail"); - SendRemoveBundleEvent(); + ANS_LOGE("send Request to SytemDialog fail"); + nlohmann::json root = nlohmann::json::parse(commandStr_); + if (root.is_null() or !root.is_object()) { + ANS_LOGE("Invalid JSON object"); + return; + } + if (!root.contains("bundleName") || !root.contains("bundleUid")) { + ANS_LOGE("not found jsonKey from"); + return; + } + std::string bundleName = root["bundleName"]; + int32_t bundleUid = root["bundleUid"]; + sptr bundleOption = new (std::nothrow) NotificationBundleOption( + bundleName, bundleUid); + if (bundleOption == nullptr) { + ANS_LOGE("bundleOption inin fail"); + return; + } + AdvancedNotificationService::GetInstance()->RemoveEnableNotificationDialog(bundleOption); } } @@ -55,40 +72,5 @@ void SystemDialogConnectStb::OnAbilityDisconnectDone(const AppExecFwk::ElementNa ANS_LOGI("on ability disconnected"); } -void SystemDialogConnectStb::SendRemoveBundleEvent() -{ - if (commandStr_.empty() || !nlohmann::json::accept(commandStr_)) { - ANS_LOGW("Invaild json param"); - return; - } - nlohmann::json root = nlohmann::json::parse(commandStr_); - if (root.is_null() or !root.is_object()) { - ANS_LOGE("Invalid JSON object"); - return; - } - if (!root.contains("bundleName") || !root.contains("bundleUid")) { - ANS_LOGW("not found jsonKey from"); - return; - } - if (!root["bundleName"].is_string() || !root["bundleUid"].is_string()) { - ANS_LOGW("value type of json key from is not string"); - return; - } - EventFwk::CommonEventData commonData; - std::string bundleName = root["bundleName"]; - std::string bundleUid = root["bundleUid"]; - - EventFwk::Want want; - want.SetAction(DIALOG_CRASH_EVENT); - want.SetParam("bundleName", bundleName); - want.SetParam("bundleUid", bundleUid); - commonData.SetWant(want); - commonData.SetCode(REMOVE_BUNDLE_CODE); - commonData.SetData(bundleName); - if (!EventFwk::CommonEventManager::PublishCommonEvent(commonData)) { - ANS_LOGE("Publish remove bundle failed"); - } -} - } } \ No newline at end of file -- Gitee From 598e42b2101ed9dc58e2b19bf0c9068a938e36da Mon Sep 17 00:00:00 2001 From: xdongs Date: Fri, 11 Oct 2024 14:16:42 +0800 Subject: [PATCH 071/167] remove Signed-off-by: xdongs --- frameworks/core/include/ans_manager_interface.h | 2 +- frameworks/core/include/ans_manager_proxy.h | 2 +- .../ans_notification_branch_test.cpp | 5 +++++ services/ans/src/advanced_notification_publish_service.cpp | 4 +++- 4 files changed, 10 insertions(+), 3 deletions(-) diff --git a/frameworks/core/include/ans_manager_interface.h b/frameworks/core/include/ans_manager_interface.h index b77d61779..42386e9e6 100644 --- a/frameworks/core/include/ans_manager_interface.h +++ b/frameworks/core/include/ans_manager_interface.h @@ -514,7 +514,7 @@ public: * * @return Returns remove dialog result. */ - virtual ErrCode RemoveEnableNotificationDialog() = 0; + virtual ErrCode RemoveEnableNotificationDialog() = 0; /** * @brief Checks whether notifications are allowed for a specific bundle. diff --git a/frameworks/core/include/ans_manager_proxy.h b/frameworks/core/include/ans_manager_proxy.h index 36d3b689d..e739314cf 100644 --- a/frameworks/core/include/ans_manager_proxy.h +++ b/frameworks/core/include/ans_manager_proxy.h @@ -502,7 +502,7 @@ public: * * @return Returns remove dialog result. */ - ErrCode RemoveEnableNotificationDialog() override; + ErrCode RemoveEnableNotificationDialog() override; /** * @brief Checks whether notifications are allowed for a specific bundle. diff --git a/frameworks/core/test/unittest/ans_notification_branch_test/ans_notification_branch_test.cpp b/frameworks/core/test/unittest/ans_notification_branch_test/ans_notification_branch_test.cpp index b509a5ed2..acbdfdae7 100644 --- a/frameworks/core/test/unittest/ans_notification_branch_test/ans_notification_branch_test.cpp +++ b/frameworks/core/test/unittest/ans_notification_branch_test/ans_notification_branch_test.cpp @@ -307,6 +307,11 @@ public: return ERR_ANS_INVALID_PARAM; } + ErrCode RemoveEnableNotificationDialog() override + { + return ERR_ANS_INVALID_PARAM; + } + ErrCode IsSpecialBundleAllowedNotify(const sptr &bundleOption, bool &allowed) override { return ERR_ANS_INVALID_PARAM; diff --git a/services/ans/src/advanced_notification_publish_service.cpp b/services/ans/src/advanced_notification_publish_service.cpp index b232c4ca4..a70e61acd 100644 --- a/services/ans/src/advanced_notification_publish_service.cpp +++ b/services/ans/src/advanced_notification_publish_service.cpp @@ -922,7 +922,9 @@ ErrCode AdvancedNotificationService::RemoveEnableNotificationDialog() ErrCode AdvancedNotificationService::RemoveEnableNotificationDialog(const sptr &bundleOption) { - ANS_LOGI("RemoveEnableNotificationDialog %{public}s, %{public}d", bundleOption->GetBundleName().c_str(), bundleOption->GetUid()); + ANS_LOGI("RemoveEnableNotificationDialog %{public}s, %{public}d", + bundleOption->GetBundleName().c_str(), + bundleOption->GetUid()); if (!CreateDialogManager()) { return ERROR_INTERNAL_ERROR; } -- Gitee From d698ba88df22f5478086b742a34ebcd36598a8c7 Mon Sep 17 00:00:00 2001 From: xdongs2009 Date: Fri, 11 Oct 2024 06:38:28 +0000 Subject: [PATCH 072/167] update frameworks/core/include/ans_manager_interface.h. Signed-off-by: xdongs2009 --- frameworks/core/include/ans_manager_interface.h | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/frameworks/core/include/ans_manager_interface.h b/frameworks/core/include/ans_manager_interface.h index 42386e9e6..b4605e7bd 100644 --- a/frameworks/core/include/ans_manager_interface.h +++ b/frameworks/core/include/ans_manager_interface.h @@ -514,7 +514,7 @@ public: * * @return Returns remove dialog result. */ - virtual ErrCode RemoveEnableNotificationDialog() = 0; + virtual ErrCode RemoveEnableNotificationDialog() = 0; /** * @brief Checks whether notifications are allowed for a specific bundle. -- Gitee From 2833a82fac3c9fc3e38b917088632210f81ba0e6 Mon Sep 17 00:00:00 2001 From: z30053788 Date: Sat, 12 Oct 2024 10:19:10 +0800 Subject: [PATCH 073/167] update Signed-off-by: z30053788 Change-Id: Ibc88ae5b9be060ec9d727ee7638282c55aada189 --- .../ans_notification_branch_test.cpp | 1 - 1 file changed, 1 deletion(-) diff --git a/frameworks/core/test/unittest/ans_notification_branch_test/ans_notification_branch_test.cpp b/frameworks/core/test/unittest/ans_notification_branch_test/ans_notification_branch_test.cpp index b509a5ed2..a31ebe47c 100644 --- a/frameworks/core/test/unittest/ans_notification_branch_test/ans_notification_branch_test.cpp +++ b/frameworks/core/test/unittest/ans_notification_branch_test/ans_notification_branch_test.cpp @@ -650,7 +650,6 @@ HWTEST_F(AnsNotificationBranchTest, RemoveNotifications_0300, Function | MediumT std::vector hashcodes; hashcodes.emplace_back(hashcode); int32_t removeReason = 1; - MockGetAnsManagerProxy(true); ansNotification->RemoveNotifications(hashcodes, removeReason); } -- Gitee From 6eba4170569f80292de1078440983da9ed7b8693 Mon Sep 17 00:00:00 2001 From: gaojiaqi Date: Sat, 12 Oct 2024 13:34:24 +0800 Subject: [PATCH 074/167] sync Signed-off-by: gaojiaqi --- frameworks/ans/BUILD.gn | 5 - frameworks/ans/src/reminder_request.cpp | 425 ++---------- frameworks/ans/src/reminder_request_alarm.cpp | 57 +- .../ans/src/reminder_request_calendar.cpp | 196 ++---- frameworks/ans/src/reminder_request_timer.cpp | 30 +- frameworks/ans/test/unittest/BUILD.gn | 1 + .../unittest/reminder_request_alarm_test.cpp | 4 - .../reminder_request_branch_test.cpp | 4 +- .../reminder_request_calendar_test.cpp | 22 +- .../test/unittest/reminder_request_test.cpp | 174 +---- .../unittest/reminder_request_timer_test.cpp | 15 - .../ans/test/unittest/reminder_store_test.cpp | 332 +++++++++ frameworks/core/src/ans_notification.cpp | 2 + interfaces/inner_api/reminder_request.h | 90 ++- interfaces/inner_api/reminder_request_alarm.h | 18 +- .../inner_api/reminder_request_calendar.h | 149 +++- interfaces/inner_api/reminder_request_timer.h | 6 +- services/ans/BUILD.gn | 4 + services/ans/include/bundle_manager_helper.h | 8 + .../ans/include}/reminder_store.h | 0 .../ans/include/reminder_store_strategy.h | 193 ++++++ .../ans/include}/reminder_table.h | 0 .../ans/include}/reminder_table_old.h | 0 services/ans/src/bundle_manager_helper.cpp | 15 + services/ans/src/reminder_data_manager.cpp | 18 +- services/ans/src/reminder_event_manager.cpp | 3 +- .../ans/src/reminder_store.cpp | 34 +- services/ans/src/reminder_store_strategy.cpp | 649 ++++++++++++++++++ .../ans/src/reminder_table.cpp | 0 .../ans/src/reminder_table_old.cpp | 0 .../reminderrequest_fuzzer.cpp | 10 - .../reminderrequestalarm_fuzzer.cpp | 4 - .../reminderrequestannexthree_fuzzer.cpp | 2 - .../reminderrequestcalendar_fuzzer.cpp | 4 - .../reminderrequestcontinuate_fuzzer.cpp | 4 +- test/fuzztest/reminderstore_fuzzer/BUILD.gn | 6 +- .../reminderstoreannex_fuzzer/BUILD.gn | 6 +- .../reminderstoreannex_fuzzer.cpp | 2 - 38 files changed, 1573 insertions(+), 919 deletions(-) rename {interfaces/inner_api => services/ans/include}/reminder_store.h (100%) create mode 100644 services/ans/include/reminder_store_strategy.h rename {interfaces/inner_api => services/ans/include}/reminder_table.h (100%) rename {interfaces/inner_api => services/ans/include}/reminder_table_old.h (100%) rename {frameworks => services}/ans/src/reminder_store.cpp (95%) create mode 100644 services/ans/src/reminder_store_strategy.cpp rename {frameworks => services}/ans/src/reminder_table.cpp (100%) rename {frameworks => services}/ans/src/reminder_table_old.cpp (100%) diff --git a/frameworks/ans/BUILD.gn b/frameworks/ans/BUILD.gn index 12e565fae..3fc5a17ec 100644 --- a/frameworks/ans/BUILD.gn +++ b/frameworks/ans/BUILD.gn @@ -116,9 +116,6 @@ ohos_shared_library("ans_innerkits") { "${frameworks_module_ans_path}/src/reminder_request_alarm.cpp", "${frameworks_module_ans_path}/src/reminder_request_calendar.cpp", "${frameworks_module_ans_path}/src/reminder_request_timer.cpp", - "${frameworks_module_ans_path}/src/reminder_store.cpp", - "${frameworks_module_ans_path}/src/reminder_table.cpp", - "${frameworks_module_ans_path}/src/reminder_table_old.cpp", ] public_configs = [ ":ans_innerkits_public_config" ] @@ -136,8 +133,6 @@ ohos_shared_library("ans_innerkits") { "hilog:libhilog", "i18n:intl_util", "ipc:ipc_core", - "os_account:os_account_innerkits", - "relational_store:native_rdb", "resource_management:global_resmgr", "samgr:samgr_proxy", "time_service:time_client", diff --git a/frameworks/ans/src/reminder_request.cpp b/frameworks/ans/src/reminder_request.cpp index 43fed2510..a0f8a22fe 100644 --- a/frameworks/ans/src/reminder_request.cpp +++ b/frameworks/ans/src/reminder_request.cpp @@ -15,8 +15,6 @@ #include "reminder_request.h" -#include "reminder_table.h" -#include "reminder_table_old.h" #include "ans_const_define.h" #include "ans_log_wrapper.h" #include "bundle_mgr_interface.h" @@ -25,8 +23,6 @@ #include "ipc_skeleton.h" #include "iservice_registry.h" #include "locale_config.h" -#include "os_account_manager.h" -#include "reminder_store.h" #include "system_ability_definition.h" #include "want_agent_helper.h" #include "nlohmann/json.hpp" @@ -480,118 +476,6 @@ bool ReminderRequest::OnTimeZoneChange() triggerTimeInMilli_, GetDurationSinceEpochInMilli(newZoneTriggerTime), nextTriggerTime); } -int64_t ReminderRequest::RecoverInt64FromDb(const std::shared_ptr &resultSet, - const std::string &columnName, const DbRecoveryType &columnType) -{ - if (resultSet == nullptr) { - ANSR_LOGE("ResultSet is null"); - return 0; - } - switch (columnType) { - case (DbRecoveryType::INT): { - int32_t value; - ReminderStore::GetInt32Val(resultSet, columnName, value); - return static_cast(value); - } - case (DbRecoveryType::LONG): { - int64_t value; - ReminderStore::GetInt64Val(resultSet, columnName, value); - return value; - } - default: { - ANSR_LOGD("ColumnType not support."); - break; - } - } - ANSR_LOGE("Recover data error"); - return 0; -} - -void ReminderRequest::RecoverBasicFromDb(const std::shared_ptr& resultSet) -{ - ReminderStore::GetInt32Val(resultSet, ReminderBaseTable::REMINDER_ID, reminderId_); - ReminderStore::GetStringVal(resultSet, ReminderBaseTable::PACKAGE_NAME, bundleName_); - ReminderStore::GetInt32Val(resultSet, ReminderBaseTable::USER_ID, userId_); - ReminderStore::GetInt32Val(resultSet, ReminderBaseTable::UID, uid_); - - std::string isSysApp; - ReminderStore::GetStringVal(resultSet, ReminderBaseTable::SYSTEM_APP, isSysApp); - isSystemApp_ = isSysApp == "true" ? true : false; - - int32_t reminderType; - ReminderStore::GetInt32Val(resultSet, ReminderBaseTable::REMINDER_TYPE, reminderType); - reminderType_ = ReminderType(reminderType); - - ReminderStore::GetUInt64Val(resultSet, ReminderBaseTable::REMINDER_TIME, reminderTimeInMilli_); - ReminderStore::GetUInt64Val(resultSet, ReminderBaseTable::TRIGGER_TIME, triggerTimeInMilli_); - - uint64_t timeIntervalInSecond = 0; - ReminderStore::GetUInt64Val(resultSet, ReminderBaseTable::TIME_INTERVAL, timeIntervalInSecond); - SetTimeInterval(timeIntervalInSecond); - - ReminderStore::GetUInt8Val(resultSet, ReminderBaseTable::SNOOZE_TIMES, snoozeTimes_); - ReminderStore::GetUInt8Val(resultSet, ReminderBaseTable::DYNAMIC_SNOOZE_TIMES, snoozeTimesDynamic_); - - uint64_t ringDurationInSecond; - ReminderStore::GetUInt64Val(resultSet, ReminderBaseTable::RING_DURATION, ringDurationInSecond); - SetRingDuration(ringDurationInSecond); - - std::string isExpired; - ReminderStore::GetStringVal(resultSet, ReminderBaseTable::IS_EXPIRED, isExpired); - isExpired_ = isExpired == "true" ? true : false; - - ReminderStore::GetUInt8Val(resultSet, ReminderBaseTable::STATE, state_); - - // action buttons - RecoverActionButton(resultSet); - - ReminderStore::GetStringVal(resultSet, ReminderBaseTable::CUSTOM_BUTTON_URI, customButtonUri_); - - int32_t slotType; - ReminderStore::GetInt32Val(resultSet, ReminderBaseTable::SLOT_ID, slotType); - slotType_ = NotificationConstant::SlotType(slotType); - - int32_t snoozeSlotType; - ReminderStore::GetInt32Val(resultSet, ReminderBaseTable::SNOOZE_SLOT_ID, snoozeSlotType); - snoozeSlotType_ = NotificationConstant::SlotType(snoozeSlotType); - - ReminderStore::GetInt32Val(resultSet, ReminderBaseTable::NOTIFICATION_ID, notificationId_); - ReminderStore::GetStringVal(resultSet, ReminderBaseTable::TITLE, title_); - ReminderStore::GetStringVal(resultSet, ReminderBaseTable::CONTENT, content_); - ReminderStore::GetStringVal(resultSet, ReminderBaseTable::SNOOZE_CONTENT, snoozeContent_); - ReminderStore::GetStringVal(resultSet, ReminderBaseTable::EXPIRED_CONTENT, expiredContent_); - - InitNotificationRequest(); // must set before wantAgent & maxScreenWantAgent -} - -void ReminderRequest::RecoverFromDbBase(const std::shared_ptr& resultSet) -{ - if (resultSet == nullptr) { - ANSR_LOGE("ResultSet is null"); - return; - } - RecoverBasicFromDb(resultSet); - - std::string wantAgent; - ReminderStore::GetStringVal(resultSet, ReminderBaseTable::WANT_AGENT, wantAgent); - RecoverWantAgent(wantAgent, 0); - - std::string maxScreenWantAgent; - ReminderStore::GetStringVal(resultSet, ReminderBaseTable::MAX_SCREEN_WANT_AGENT, maxScreenWantAgent); - RecoverWantAgent(maxScreenWantAgent, 1); - - std::string tapDismissed; - ReminderStore::GetStringVal(resultSet, ReminderBaseTable::TAP_DISMISSED, tapDismissed); - tapDismissed_ = tapDismissed == "true" ? true : false; - - ReminderStore::GetInt64Val(resultSet, ReminderBaseTable::AUTO_DELETED_TIME, autoDeletedTime_); - - ReminderStore::GetStringVal(resultSet, ReminderBaseTable::GROUP_ID, groupId_); - ReminderStore::GetStringVal(resultSet, ReminderBaseTable::CUSTOM_RING_URI, customRingUri_); - ReminderStore::GetStringVal(resultSet, ReminderBaseTable::CREATOR_BUNDLE_NAME, creatorBundleName_); - ReminderStore::GetInt32Val(resultSet, ReminderBaseTable::CREATOR_UID, creatorUid_); -} - void ReminderRequest::RecoverActionButtonJsonMode(const std::string &jsonString) { if (!nlohmann::json::accept(jsonString)) { @@ -630,15 +514,9 @@ void ReminderRequest::RecoverActionButtonJsonMode(const std::string &jsonString) resource, buttonWantAgent, buttonDataShareUpdate); } -void ReminderRequest::RecoverActionButton(const std::shared_ptr &resultSet) +void ReminderRequest::DeserializeButtonInfo(const std::string& buttonInfoStr) { - if (resultSet == nullptr) { - ANSR_LOGE("ResultSet is null"); - return; - } - std::string actionButtonInfo; - ReminderStore::GetStringVal(resultSet, ReminderBaseTable::ACTION_BUTTON_INFO, actionButtonInfo); - std::vector multiButton = StringSplit(actionButtonInfo, SEP_BUTTON_MULTI); + std::vector multiButton = StringSplit(buttonInfoStr, SEP_BUTTON_MULTI); for (auto button : multiButton) { std::vector singleButton = StringSplit(button, SEP_BUTTON_SINGLE); if (singleButton.size() <= SINGLE_BUTTON_INVALID) { @@ -733,7 +611,7 @@ void ReminderRequest::RecoverWantAgentByJson(const std::string& wantAgentInfo, c } } -void ReminderRequest::RecoverWantAgent(const std::string &wantAgentInfo, const uint8_t &type) +void ReminderRequest::DeserializeWantAgent(const std::string &wantAgentInfo, const uint8_t type) { if (nlohmann::json::accept(wantAgentInfo)) { RecoverWantAgentByJson(wantAgentInfo, type); @@ -1004,6 +882,21 @@ std::string ReminderRequest::GetBundleName() const return bundleName_; } +void ReminderRequest::SetReminderType(const ReminderType type) +{ + reminderType_ = type; +} + +void ReminderRequest::SetState(const uint8_t state) +{ + state_ = state; +} + +void ReminderRequest::SetRepeatDaysOfWeek(const uint8_t repeatDaysOfWeek) +{ + repeatDaysOfWeek_ = repeatDaysOfWeek; +} + void ReminderRequest::SetSystemApp(bool isSystem) { isSystemApp_ = isSystem; @@ -1079,11 +972,21 @@ bool ReminderRequest::SetNextTriggerTime() return false; } +void ReminderRequest::SetWantAgentStr(const std::string& wantStr) +{ + wantAgentStr_ = wantStr; +} + std::string ReminderRequest::GetWantAgentStr() { return wantAgentStr_; } +void ReminderRequest::SetMaxWantAgentStr(const std::string& maxWantStr) +{ + maxWantAgentStr_ = maxWantStr; +} + std::string ReminderRequest::GetMaxWantAgentStr() { return maxWantAgentStr_; @@ -1378,7 +1281,6 @@ bool ReminderRequest::InitNotificationRequest() return false; } displayContent_ = content_; - AddActionButtons(true); return true; } @@ -1411,7 +1313,7 @@ std::string ReminderRequest::GetDateTimeInfo(const time_t &timeInSecond) const return GetTimeInfoInner(timeInSecond, TimeFormat::YMDHMS, true); } -std::string ReminderRequest::GetButtonInfo() const +std::string ReminderRequest::SerializeButtonInfo() const { std::string info = ""; bool isFirst = true; @@ -1764,11 +1666,6 @@ void ReminderRequest::UpdateNotificationBundleInfo() notificationRequest_->SetOwnerBundleName(bundleName_); notificationRequest_->SetCreatorBundleName(bundleName_); notificationRequest_->SetCreatorUid(uid_); - ErrCode errCode = AccountSA::OsAccountManager::GetOsAccountLocalIdFromUid(uid_, userId_); - if (errCode != ERR_OK) { - ANSR_LOGE("GetOsAccountLocalIdFromUid fail."); - return; - } notificationRequest_->SetCreatorUserId(userId_); } @@ -1851,76 +1748,17 @@ int32_t ReminderRequest::GetCTime(const TimeTransferType &type, int32_t actualTi } } -int32_t ReminderRequest::GetUid(const int32_t &userId, const std::string &bundleName) -{ - sptr systemAbilityManager - = SystemAbilityManagerClient::GetInstance().GetSystemAbilityManager(); - if (systemAbilityManager == nullptr) { - ANSR_LOGE("Failed to get uid due to get systemAbilityManager is null."); - return -1; - } - sptr remoteObject = systemAbilityManager->GetSystemAbility(BUNDLE_MGR_SERVICE_SYS_ABILITY_ID); - if (remoteObject == nullptr) { - ANSR_LOGE("Fail to get bundle manager proxy"); - return -1; - } - sptr bundleMgr = iface_cast(remoteObject); - if (bundleMgr == nullptr) { - ANSR_LOGE("Bundle mgr proxy is nullptr"); - return -1; - } - int32_t uid = bundleMgr->GetUidByBundleName(bundleName, userId); - ANSR_LOGD("uid=%{public}d", uid); - return uid; -} - -int32_t ReminderRequest::GetAppIndex(const int32_t uid) -{ - const int32_t defaultAppIndex = 0; // failed return main apps - sptr systemAbilityManager - = SystemAbilityManagerClient::GetInstance().GetSystemAbilityManager(); - if (systemAbilityManager == nullptr) { - ANSR_LOGE("Failed to get app index due to get systemAbilityManager is null."); - return defaultAppIndex; - } - sptr remoteObject = systemAbilityManager->GetSystemAbility(BUNDLE_MGR_SERVICE_SYS_ABILITY_ID); - if (remoteObject == nullptr) { - ANSR_LOGE("Fail to get bundle manager proxy"); - return defaultAppIndex; - } - sptr bundleMgr = iface_cast(remoteObject); - if (bundleMgr == nullptr) { - ANSR_LOGE("Bundle mgr proxy is nullptr"); - return defaultAppIndex; - } - std::string bundleName; - int32_t appIndex = 0; - bundleMgr->GetNameAndIndexForUid(uid, bundleName, appIndex); - ANSR_LOGD("appIndex=%{public}d", appIndex); - return appIndex; -} - -int32_t ReminderRequest::GetUserId(const int32_t &uid) -{ - int32_t userId = -1; - AccountSA::OsAccountManager::GetOsAccountLocalIdFromUid(uid, userId); - ANSR_LOGD("userId=%{private}d", userId); - return userId; -} - -void ReminderRequest::AppendWantAgentValuesBucket(const sptr& reminder, - NativeRdb::ValuesBucket& values) +void ReminderRequest::SerializeWantAgent(std::string& wantInfoStr, std::string& maxWantInfoStr) { std::string pkgName; std::string abilityName; std::string uri; std::string parameters; - auto wantAgentInfo = reminder->GetWantAgentInfo(); - if (wantAgentInfo != nullptr) { - pkgName = wantAgentInfo->pkgName; - abilityName = wantAgentInfo->abilityName; - uri = wantAgentInfo->uri; - AAFwk::WantParamWrapper wrapper(wantAgentInfo->parameters); + if (wantAgentInfo_ != nullptr) { + pkgName = wantAgentInfo_->pkgName; + abilityName = wantAgentInfo_->abilityName; + uri = wantAgentInfo_->uri; + AAFwk::WantParamWrapper wrapper(wantAgentInfo_->parameters); parameters = wrapper.ToString(); } nlohmann::json wantInfo; @@ -1928,13 +1766,11 @@ void ReminderRequest::AppendWantAgentValuesBucket(const sptr& r wantInfo["abilityName"] = abilityName; wantInfo["uri"] = uri; wantInfo["parameters"] = parameters; - std::string info = wantInfo.dump(INDENT, ' ', false, nlohmann::json::error_handler_t::replace); - values.PutString(ReminderBaseTable::WANT_AGENT, info); + wantInfoStr = wantInfo.dump(INDENT, ' ', false, nlohmann::json::error_handler_t::replace); - auto maxScreenWantAgentInfo = reminder->GetMaxScreenWantAgentInfo(); - if (maxScreenWantAgentInfo != nullptr) { - pkgName = maxScreenWantAgentInfo->pkgName; - abilityName = maxScreenWantAgentInfo->abilityName; + if (maxScreenWantAgentInfo_ != nullptr) { + pkgName = maxScreenWantAgentInfo_->pkgName; + abilityName = maxScreenWantAgentInfo_->abilityName; uri = ""; parameters = ""; } @@ -1943,50 +1779,7 @@ void ReminderRequest::AppendWantAgentValuesBucket(const sptr& r maxWantInfo["abilityName"] = abilityName; maxWantInfo["uri"] = uri; maxWantInfo["parameters"] = parameters; - info = maxWantInfo.dump(INDENT, ' ', false, nlohmann::json::error_handler_t::replace); - values.PutString(ReminderBaseTable::MAX_SCREEN_WANT_AGENT, info); -} - -void ReminderRequest::AppendValuesBucket(const sptr &reminder, - const sptr &bundleOption, NativeRdb::ValuesBucket &values, bool oldVersion) -{ - values.PutInt(ReminderBaseTable::REMINDER_ID, reminder->GetReminderId()); - values.PutString(ReminderBaseTable::PACKAGE_NAME, reminder->GetBundleName()); - values.PutInt(ReminderBaseTable::USER_ID, reminder->GetUserId()); - values.PutInt(ReminderBaseTable::UID, reminder->GetUid()); - values.PutString(ReminderBaseTable::SYSTEM_APP, reminder->IsSystemApp() ? "true" : "false"); - values.PutInt(ReminderBaseTable::REMINDER_TYPE, static_cast(reminder->GetReminderType())); - values.PutLong(ReminderBaseTable::REMINDER_TIME, reminder->GetReminderTimeInMilli()); - values.PutLong(ReminderBaseTable::TRIGGER_TIME, reminder->GetTriggerTimeInMilli()); - values.PutLong(ReminderBaseTable::TIME_INTERVAL, reminder->GetTimeInterval()); - values.PutInt(ReminderBaseTable::SNOOZE_TIMES, reminder->GetSnoozeTimes()); - values.PutInt(ReminderBaseTable::DYNAMIC_SNOOZE_TIMES, reminder->GetSnoozeTimesDynamic()); - values.PutLong(ReminderBaseTable::RING_DURATION, reminder->GetRingDuration()); - values.PutString(ReminderBaseTable::IS_EXPIRED, reminder->IsExpired() ? "true" : "false"); - values.PutInt(ReminderBaseTable::STATE, reminder->GetState()); - values.PutString(ReminderBaseTable::ACTION_BUTTON_INFO, reminder->GetButtonInfo()); - values.PutString(ReminderBaseTable::CUSTOM_BUTTON_URI, reminder->GetCustomButtonUri()); - values.PutInt(ReminderBaseTable::SLOT_ID, reminder->GetSlotType()); - values.PutInt(ReminderBaseTable::SNOOZE_SLOT_ID, reminder->GetSnoozeSlotType()); - values.PutInt(ReminderBaseTable::NOTIFICATION_ID, reminder->GetNotificationId()); - values.PutString(ReminderBaseTable::TITLE, reminder->GetTitle()); - values.PutString(ReminderBaseTable::CONTENT, reminder->GetContent()); - values.PutString(ReminderBaseTable::SNOOZE_CONTENT, reminder->GetSnoozeContent()); - values.PutString(ReminderBaseTable::EXPIRED_CONTENT, reminder->GetExpiredContent()); - - if (oldVersion) { - values.PutString(ReminderBaseTable::WANT_AGENT, reminder->GetWantAgentStr()); - values.PutString(ReminderBaseTable::MAX_SCREEN_WANT_AGENT, reminder->GetMaxWantAgentStr()); - } else { - AppendWantAgentValuesBucket(reminder, values); - } - - values.PutString(ReminderBaseTable::TAP_DISMISSED, reminder->IsTapDismissed() ? "true" : "false"); - values.PutLong(ReminderBaseTable::AUTO_DELETED_TIME, reminder->GetAutoDeletedTime()); - values.PutString(ReminderBaseTable::GROUP_ID, reminder->GetGroupId()); - values.PutString(ReminderBaseTable::CUSTOM_RING_URI, reminder->GetCustomRingUri()); - values.PutString(ReminderBaseTable::CREATOR_BUNDLE_NAME, reminder->GetCreatorBundleName()); - values.PutInt(ReminderBaseTable::CREATOR_UID, reminder->GetCreatorUid()); + maxWantInfoStr = maxWantInfo.dump(INDENT, ' ', false, nlohmann::json::error_handler_t::replace); } int64_t ReminderRequest::GetNextDaysOfWeek(const time_t now, const time_t target) const @@ -2105,143 +1898,5 @@ void ReminderRequest::OnLanguageChange(const std::shared_ptr& resultSet) -{ - // reminderId - ReminderStore::GetInt32Val(resultSet, ReminderTable::REMINDER_ID, reminderId_); - - // userId - ReminderStore::GetInt32Val(resultSet, ReminderTable::USER_ID, userId_); - - // bundleName - ReminderStore::GetStringVal(resultSet, ReminderTable::PKG_NAME, bundleName_); - - // uid - ReminderStore::GetInt32Val(resultSet, ReminderTable::UID, uid_); - - // isSystemApp - std::string isSysApp; - ReminderStore::GetStringVal(resultSet, ReminderTable::SYS_APP, isSysApp); - isSystemApp_ = isSysApp == "true" ? true : false; - - // reminderType - int32_t reminderType; - ReminderStore::GetInt32Val(resultSet, ReminderTable::REMINDER_TYPE, reminderType); - reminderType_ = ReminderType(reminderType); - - // reminderTime - reminderTimeInMilli_ = - static_cast(RecoverInt64FromDb(resultSet, ReminderTable::REMINDER_TIME, - DbRecoveryType::LONG)); - - // triggerTime - triggerTimeInMilli_ = - static_cast(RecoverInt64FromDb(resultSet, ReminderTable::TRIGGER_TIME, - DbRecoveryType::LONG)); - - // timeInterval - uint64_t timeIntervalInSecond = - static_cast(RecoverInt64FromDb(resultSet, ReminderTable::TIME_INTERVAL, - DbRecoveryType::LONG)); - SetTimeInterval(timeIntervalInSecond); - - // snoozeTimes - snoozeTimes_ = static_cast(RecoverInt64FromDb(resultSet, ReminderTable::SNOOZE_TIMES, - DbRecoveryType::INT)); - - // dynamicSnoozeTimes - snoozeTimesDynamic_ = - static_cast(RecoverInt64FromDb(resultSet, ReminderTable::DYNAMIC_SNOOZE_TIMES, - DbRecoveryType::INT)); - - // ringDuration - uint64_t ringDurationInSecond = - static_cast(RecoverInt64FromDb(resultSet, ReminderTable::RING_DURATION, - DbRecoveryType::LONG)); - SetRingDuration(ringDurationInSecond); - - // isExpired - std::string isExpired; - ReminderStore::GetStringVal(resultSet, ReminderTable::IS_EXPIRED, isExpired); - isExpired_ = isExpired == "true" ? true : false; - - // state - state_ = static_cast(RecoverInt64FromDb(resultSet, ReminderTable::STATE, DbRecoveryType::INT)); - - // repeatDaysOfWeek_ - repeatDaysOfWeek_ = static_cast(RecoverInt64FromDb(resultSet, ReminderTable::REPEAT_DAYS_OF_WEEK, - DbRecoveryType::INT)); - - // action buttons - RecoverActionButton(resultSet); - - // slotType - int32_t slotType; - ReminderStore::GetInt32Val(resultSet, ReminderTable::SLOT_ID, slotType); - slotType_ = NotificationConstant::SlotType(slotType); - - // snoozeSlotType - int32_t snoozeSlotType; - ReminderStore::GetInt32Val(resultSet, ReminderTable::SNOOZE_SLOT_ID, snoozeSlotType); - snoozeSlotType_ = NotificationConstant::SlotType(snoozeSlotType); - - // notification id - ReminderStore::GetInt32Val(resultSet, ReminderTable::NOTIFICATION_ID, notificationId_); - - // title - ReminderStore::GetStringVal(resultSet, ReminderTable::TITLE, title_); - - // content - ReminderStore::GetStringVal(resultSet, ReminderTable::CONTENT, content_); - - // snoozeContent - ReminderStore::GetStringVal(resultSet, ReminderTable::SNOOZE_CONTENT, snoozeContent_); - - // expiredContent - ReminderStore::GetStringVal(resultSet, ReminderTable::EXPIRED_CONTENT, expiredContent_); -} - -void ReminderRequest::RecoverFromOldVersion(const std::shared_ptr& resultSet) -{ - if (resultSet == nullptr) { - ANSR_LOGE("ResultSet is null"); - return; - } - - RecoverBasicFromOldVersion(resultSet); - - // wantAgent - std::string wantAgent; - ReminderStore::GetStringVal(resultSet, ReminderTable::AGENT, wantAgent); - wantAgentStr_ = wantAgent; - - // maxScreenWantAgent - std::string maxScreenWantAgent; - ReminderStore::GetStringVal(resultSet, ReminderTable::MAX_SCREEN_AGENT, maxScreenWantAgent); - maxWantAgentStr_ = maxScreenWantAgent; - - // tapDismissed - std::string tapDismissed; - ReminderStore::GetStringVal(resultSet, ReminderTable::TAP_DISMISSED, tapDismissed); - tapDismissed_ = tapDismissed == "true" ? true : false; - - // autoDeletedTime - autoDeletedTime_ = - static_cast(RecoverInt64FromDb(resultSet, ReminderTable::AUTO_DELETED_TIME, - DbRecoveryType::LONG)); - - // customButtonUri - ReminderStore::GetStringVal(resultSet, ReminderTable::CUSTOM_BUTTON_URI, customButtonUri_); - - // groupId - ReminderStore::GetStringVal(resultSet, ReminderTable::GROUP_ID, groupId_); - - // customRingUri - ReminderStore::GetStringVal(resultSet, ReminderTable::CUSTOM_RING_URI, customRingUri_); - - // creatorBundleName - ReminderStore::GetStringVal(resultSet, ReminderTable::CREATOR_BUNDLE_NAME, creatorBundleName_); -} } } diff --git a/frameworks/ans/src/reminder_request_alarm.cpp b/frameworks/ans/src/reminder_request_alarm.cpp index 8a08f7a55..8fd928b2b 100644 --- a/frameworks/ans/src/reminder_request_alarm.cpp +++ b/frameworks/ans/src/reminder_request_alarm.cpp @@ -16,9 +16,6 @@ #include "reminder_request_alarm.h" #include "ans_log_wrapper.h" -#include "reminder_table.h" -#include "reminder_table_old.h" -#include "reminder_store.h" namespace OHOS { namespace Notification { @@ -114,6 +111,16 @@ uint64_t ReminderRequestAlarm::GetNextTriggerTime(bool forceToGetNext) const return GetTriggerTime(now, nextTriggerTime); } +void ReminderRequestAlarm::SetHour(const uint8_t hour) +{ + hour_ = hour; +} + +void ReminderRequestAlarm::SetMinute(const uint8_t minute) +{ + minute_ = minute; +} + uint8_t ReminderRequestAlarm::GetHour() const { return hour_; @@ -197,49 +204,5 @@ bool ReminderRequestAlarm::ReadFromParcel(Parcel &parcel) } return false; } - -void ReminderRequestAlarm::RecoverFromOldVersion(const std::shared_ptr &resultSet) -{ - ReminderRequest::RecoverFromOldVersion(resultSet); - - // hour - hour_ = - static_cast(RecoverInt64FromDb(resultSet, ReminderTable::ALARM_HOUR, - DbRecoveryType::INT)); - - // minute - minute_ = - static_cast(RecoverInt64FromDb(resultSet, ReminderTable::ALARM_MINUTE, - DbRecoveryType::INT)); -} - -void ReminderRequestAlarm::RecoverFromDb(const std::shared_ptr& resultSet) -{ - if (resultSet == nullptr) { - ANSR_LOGE("ResultSet is null"); - return; - } - ReminderStore::GetUInt8Val(resultSet, ReminderAlarmTable::ALARM_HOUR, hour_); - ReminderStore::GetUInt8Val(resultSet, ReminderAlarmTable::ALARM_MINUTE, minute_); - ReminderStore::GetUInt8Val(resultSet, ReminderAlarmTable::REPEAT_DAYS_OF_WEEK, repeatDaysOfWeek_); -} - -void ReminderRequestAlarm::AppendValuesBucket(const sptr &reminder, - const sptr &bundleOption, NativeRdb::ValuesBucket &values) -{ - uint8_t hour = 0; - uint8_t minute = 0; - uint8_t repeatDaysOfWeek = 0; - if (reminder->GetReminderType() == ReminderRequest::ReminderType::ALARM) { - ReminderRequestAlarm* alarm = static_cast(reminder.GetRefPtr()); - hour = alarm->GetHour(); - minute = alarm->GetMinute(); - repeatDaysOfWeek = alarm->GetRepeatDaysOfWeek(); - } - values.PutInt(ReminderAlarmTable::REMINDER_ID, reminder->GetReminderId()); - values.PutInt(ReminderAlarmTable::ALARM_HOUR, hour); - values.PutInt(ReminderAlarmTable::ALARM_MINUTE, minute); - values.PutInt(ReminderAlarmTable::REPEAT_DAYS_OF_WEEK, repeatDaysOfWeek); -} } } \ No newline at end of file diff --git a/frameworks/ans/src/reminder_request_calendar.cpp b/frameworks/ans/src/reminder_request_calendar.cpp index 0f1ead006..75ee258a0 100644 --- a/frameworks/ans/src/reminder_request_calendar.cpp +++ b/frameworks/ans/src/reminder_request_calendar.cpp @@ -16,9 +16,6 @@ #include "reminder_request_calendar.h" #include "ans_log_wrapper.h" -#include "reminder_table.h" -#include "reminder_table_old.h" -#include "reminder_store.h" #include "nlohmann/json.hpp" namespace OHOS { @@ -128,6 +125,56 @@ std::shared_ptr ReminderRequestCalendar::GetRRul return rruleWantAgentInfo_; } +void ReminderRequestCalendar::SetRepeatDay(const uint32_t repeatDay) +{ + repeatDay_ = repeatDay; +} + +void ReminderRequestCalendar::SetRepeatMonth(const uint16_t repeatMonth) +{ + repeatMonth_ = repeatMonth; +} + +void ReminderRequestCalendar::SetFirstDesignateYear(const uint16_t firstDesignateYear) +{ + firstDesignateYear_ = firstDesignateYear; +} + +void ReminderRequestCalendar::SetFirstDesignageMonth(const uint16_t firstDesignateMonth) +{ + firstDesignateMonth_ = firstDesignateMonth; +} + +void ReminderRequestCalendar::SetFirstDesignateDay(const uint16_t firstDesignateDay) +{ + firstDesignateDay_ = firstDesignateDay; +} + +void ReminderRequestCalendar::SetYear(const uint16_t year) +{ + year_ = year; +} + +void ReminderRequestCalendar::SetMonth(const uint8_t month) +{ + month_ = month; +} + +void ReminderRequestCalendar::SetDay(const uint8_t day) +{ + day_ = day; +} + +void ReminderRequestCalendar::SetHour(const uint8_t hour) +{ + hour_ = hour; +} + +void ReminderRequestCalendar::SetMinute(const uint8_t minute) +{ + minute_ = minute; +} + bool ReminderRequestCalendar::InitTriggerTime() { uint64_t nextTriggerTime = INVALID_LONG_LONG_VALUE; @@ -689,145 +736,6 @@ bool ReminderRequestCalendar::ReadFromParcel(Parcel &parcel) return false; } -void ReminderRequestCalendar::RecoverFromOldVersion(const std::shared_ptr &resultSet) -{ - ReminderRequest::RecoverFromOldVersion(resultSet); - - // repeatDay - repeatDay_ = static_cast(RecoverInt64FromDb(resultSet, ReminderTable::REPEAT_DAYS, - DbRecoveryType::INT)); - - // repeatMonth - repeatMonth_ = - static_cast(RecoverInt64FromDb(resultSet, ReminderTable::REPEAT_MONTHS, - DbRecoveryType::INT)); - - // firstDesignateYear - firstDesignateYear_ = - static_cast(RecoverInt64FromDb(resultSet, ReminderTable::FIRST_DESIGNATE_YEAR, - DbRecoveryType::INT)); - - // firstDesignateMonth - firstDesignateMonth_ = - static_cast(RecoverInt64FromDb(resultSet, ReminderTable::FIRST_DESIGNATE_MONTH, - DbRecoveryType::INT)); - - // firstDesignateDay - firstDesignateDay_ = - static_cast(RecoverInt64FromDb(resultSet, ReminderTable::FIRST_DESIGNATE_DAY, - DbRecoveryType::INT)); - - // year - year_ = static_cast(RecoverInt64FromDb(resultSet, ReminderTable::CALENDAR_YEAR, - DbRecoveryType::INT)); - - // month - month_ = static_cast(RecoverInt64FromDb(resultSet, ReminderTable::CALENDAR_MONTH, - DbRecoveryType::INT)); - - // day - day_ = static_cast(RecoverInt64FromDb(resultSet, ReminderTable::CALENDAR_DAY, - DbRecoveryType::INT)); - - // hour - hour_ = static_cast(RecoverInt64FromDb(resultSet, ReminderTable::CALENDAR_HOUR, - DbRecoveryType::INT)); - - // minute - minute_ = static_cast(RecoverInt64FromDb(resultSet, ReminderTable::CALENDAR_MINUTE, - DbRecoveryType::INT)); -} - -void ReminderRequestCalendar::RecoverFromDb(const std::shared_ptr& resultSet) -{ - if (resultSet == nullptr) { - ANSR_LOGE("ResultSet is null"); - return; - } - ReminderStore::GetUInt16Val(resultSet, ReminderCalendarTable::FIRST_DESIGNATE_YEAR, firstDesignateYear_); - ReminderStore::GetUInt8Val(resultSet, ReminderCalendarTable::FIRST_DESIGNATE_MONTH, firstDesignateMonth_); - ReminderStore::GetUInt8Val(resultSet, ReminderCalendarTable::FIRST_DESIGNATE_DAY, firstDesignateDay_); - - uint64_t dateTime; - ReminderStore::GetUInt64Val(resultSet, ReminderCalendarTable::CALENDAR_DATE_TIME, dateTime); - SetDateTime(dateTime); - - uint64_t endDateTime; - ReminderStore::GetUInt64Val(resultSet, ReminderCalendarTable::CALENDAR_END_DATE_TIME, endDateTime); - if (endDateTime != 0 && endDateTime >= dateTime) { - SetEndDateTime(endDateTime); - } else { - SetEndDateTime(startDateTime_); - } - - uint64_t lastStartDateTime; - ReminderStore::GetUInt64Val(resultSet, ReminderCalendarTable::CALENDAR_LAST_DATE_TIME, lastStartDateTime); - if (lastStartDateTime == 0) { - SetLastStartDateTime(dateTime); - } else { - SetLastStartDateTime(lastStartDateTime); - } - - int32_t repeatDay; - ReminderStore::GetInt32Val(resultSet, ReminderCalendarTable::REPEAT_DAYS, repeatDay); - repeatDay_ = static_cast(repeatDay); - - ReminderStore::GetUInt16Val(resultSet, ReminderCalendarTable::REPEAT_MONTHS, repeatMonth_); - ReminderStore::GetUInt8Val(resultSet, ReminderCalendarTable::REPEAT_DAYS_OF_WEEK, repeatDaysOfWeek_); - - std::string rruleWantAgent; - ReminderStore::GetStringVal(resultSet, ReminderCalendarTable::RRULE_WANT_AGENT, rruleWantAgent); - DeserializationRRule(rruleWantAgent); - - std::string excludeDates; - ReminderStore::GetStringVal(resultSet, ReminderCalendarTable::EXCLUDE_DATES, excludeDates); - DeserializationExcludeDates(excludeDates); -} - -void ReminderRequestCalendar::AppendValuesBucket(const sptr &reminder, - const sptr &bundleOption, NativeRdb::ValuesBucket &values) -{ - uint16_t firstDesignateYear = 0; - uint8_t firstDesignateMonth = 0; - uint8_t firstDesignateDay = 0; - uint64_t dateTime = 0; - uint32_t repeatDay = 0; - uint16_t repeatMonth = 0; - uint8_t repeatDaysOfWeek = 0; - uint64_t endDateTime = 0; - uint64_t lastStartDateTime = 0; - std::string rruleWantAgent; - std::string excludeDates; - if (reminder->GetReminderType() == ReminderRequest::ReminderType::CALENDAR) { - ReminderRequestCalendar* calendar = static_cast(reminder.GetRefPtr()); - if (calendar != nullptr) { - repeatDay = calendar->GetRepeatDay(); - repeatMonth = calendar->GetRepeatMonth(); - firstDesignateYear = calendar->GetFirstDesignateYear(); - firstDesignateMonth = calendar->GetFirstDesignageMonth(); - firstDesignateDay = calendar->GetFirstDesignateDay(); - dateTime = calendar->GetDateTime(); - repeatDaysOfWeek = calendar->GetRepeatDaysOfWeek(); - endDateTime = calendar->GetEndDateTime(); - lastStartDateTime = calendar->GetLastStartDateTime(); - rruleWantAgent = calendar->SerializationRRule(); - excludeDates = calendar->SerializationExcludeDates(); - } - } - values.PutInt(ReminderCalendarTable::REMINDER_ID, reminder->GetReminderId()); - values.PutInt(ReminderCalendarTable::FIRST_DESIGNATE_YEAR, firstDesignateYear); - values.PutInt(ReminderCalendarTable::FIRST_DESIGNATE_MONTH, firstDesignateMonth); - values.PutInt(ReminderCalendarTable::FIRST_DESIGNATE_DAY, firstDesignateDay); - values.PutLong(ReminderCalendarTable::CALENDAR_DATE_TIME, dateTime); - values.PutLong(ReminderCalendarTable::CALENDAR_END_DATE_TIME, endDateTime); - values.PutLong(ReminderCalendarTable::CALENDAR_LAST_DATE_TIME, lastStartDateTime); - values.PutInt(ReminderCalendarTable::REPEAT_DAYS, repeatDay); - values.PutInt(ReminderCalendarTable::REPEAT_MONTHS, repeatMonth); - values.PutInt(ReminderCalendarTable::REPEAT_DAYS_OF_WEEK, repeatDaysOfWeek); - values.PutString(ReminderCalendarTable::RRULE_WANT_AGENT, rruleWantAgent); - values.PutString(ReminderCalendarTable::EXCLUDE_DATES, excludeDates); -} - void ReminderRequestCalendar::SetDateTime(const uint64_t time) { time_t t = static_cast(time / MILLI_SECONDS); @@ -853,12 +761,12 @@ bool ReminderRequestCalendar::SetEndDateTime(const uint64_t time) return true; } -uint64_t ReminderRequestCalendar::GetDateTime() +uint64_t ReminderRequestCalendar::GetDateTime() const { return startDateTime_; } -uint64_t ReminderRequestCalendar::GetEndDateTime() +uint64_t ReminderRequestCalendar::GetEndDateTime() const { return endDateTime_; } diff --git a/frameworks/ans/src/reminder_request_timer.cpp b/frameworks/ans/src/reminder_request_timer.cpp index 6881b6261..867f26ae9 100644 --- a/frameworks/ans/src/reminder_request_timer.cpp +++ b/frameworks/ans/src/reminder_request_timer.cpp @@ -20,8 +20,6 @@ #include "ans_log_wrapper.h" #include "time_service_client.h" -#include "reminder_table.h" -#include "reminder_store.h" namespace OHOS { namespace Notification { @@ -58,6 +56,11 @@ uint64_t ReminderRequestTimer::GetInitInfo() const return countDownTimeInSeconds_; } +void ReminderRequestTimer::SetInitInfo(const uint64_t countDownTimeInSeconds) +{ + countDownTimeInSeconds_ = countDownTimeInSeconds; +} + uint64_t ReminderRequestTimer::PreGetNextTriggerTimeIgnoreSnooze(bool ignoreRepeat, bool forceToGetNext) { ANSR_LOGD("countdown time not support PreGetNextTriggerTimeIgnoreSnooze"); @@ -150,28 +153,5 @@ bool ReminderRequestTimer::ReadFromParcel(Parcel &parcel) } return false; } - -void ReminderRequestTimer::RecoverFromDb(const std::shared_ptr& resultSet) -{ - if (resultSet == nullptr) { - ANSR_LOGE("ResultSet is null"); - return; - } - ReminderStore::GetUInt64Val(resultSet, ReminderTimerTable::TRIGGER_SECOND, countDownTimeInSeconds_); -} - -void ReminderRequestTimer::AppendValuesBucket(const sptr &reminder, - const sptr &bundleOption, NativeRdb::ValuesBucket &values) -{ - uint64_t seconds = 0; - if (reminder->GetReminderType() == ReminderRequest::ReminderType::TIMER) { - ReminderRequestTimer* timer = static_cast(reminder.GetRefPtr()); - seconds = timer->GetInitInfo(); - } - values.PutInt(ReminderTimerTable::REMINDER_ID, reminder->GetReminderId()); - values.PutLong(ReminderTimerTable::TRIGGER_SECOND, seconds); - values.PutLong(ReminderTimerTable::START_DATE_TIME, 0); - values.PutLong(ReminderTimerTable::END_DATE_TIME, 0); -} } } diff --git a/frameworks/ans/test/unittest/BUILD.gn b/frameworks/ans/test/unittest/BUILD.gn index ae68e1aef..89bc493aa 100644 --- a/frameworks/ans/test/unittest/BUILD.gn +++ b/frameworks/ans/test/unittest/BUILD.gn @@ -73,6 +73,7 @@ ohos_unittest("ans_reminder_unit_test") { deps = [ "${frameworks_module_ans_path}:ans_innerkits", + "${services_path}/ans:libans", "//third_party/googletest:gtest_main", ] diff --git a/frameworks/ans/test/unittest/reminder_request_alarm_test.cpp b/frameworks/ans/test/unittest/reminder_request_alarm_test.cpp index 1cdf78a7e..3c748db93 100644 --- a/frameworks/ans/test/unittest/reminder_request_alarm_test.cpp +++ b/frameworks/ans/test/unittest/reminder_request_alarm_test.cpp @@ -350,8 +350,6 @@ HWTEST_F(ReminderRequestAlarmTest, RecoverFromDb_00100, Function | SmallTest | L uint8_t arr[] = {}; std::vector daysOfWeek (arr, arr + sizeof(arr) / sizeof(uint8_t)); auto rrc = std::make_shared(0, 0, daysOfWeek); - std::shared_ptr resultSet = nullptr; - rrc->RecoverFromDb(resultSet); uint8_t ret = rrc->GetRepeatDaysOfWeek(); EXPECT_EQ(ret, 0); } @@ -539,8 +537,6 @@ HWTEST_F(ReminderRequestAlarmTest, RecoverFromOldVersion_00001, Function | Small uint8_t arr[] = {}; std::vector daysOfWeek (arr, arr + sizeof(arr) / sizeof(uint8_t)); auto rrc = std::make_shared(0, 0, daysOfWeek); - std::shared_ptr resultSet = nullptr; - rrc->RecoverFromOldVersion(resultSet); uint8_t ret = rrc->GetRepeatDaysOfWeek(); EXPECT_EQ(ret, 0); } diff --git a/frameworks/ans/test/unittest/reminder_request_branch_test/reminder_request_branch_test.cpp b/frameworks/ans/test/unittest/reminder_request_branch_test/reminder_request_branch_test.cpp index 1c8599bb6..4d4e655f8 100644 --- a/frameworks/ans/test/unittest/reminder_request_branch_test/reminder_request_branch_test.cpp +++ b/frameworks/ans/test/unittest/reminder_request_branch_test/reminder_request_branch_test.cpp @@ -295,7 +295,7 @@ HWTEST_F(ReminderRequestBranchTest, GetButtonInfo_00100, Function | SmallTest | info.wantAgent = nullptr; reminderRequest->actionButtonMap_.insert( std::pair(actionButtonType, info)); - EXPECT_NE(reminderRequest->GetButtonInfo(), ""); + EXPECT_NE(reminderRequest->SerializeButtonInfo(), ""); } /** @@ -323,7 +323,7 @@ HWTEST_F(ReminderRequestBranchTest, GetButtonInfo_00200, Function | SmallTest | info.wantAgent->abilityName = abilityName; reminderRequest->actionButtonMap_.insert( std::pair(actionButtonType, info)); - EXPECT_NE(reminderRequest->GetButtonInfo(), ""); + EXPECT_NE(reminderRequest->SerializeButtonInfo(), ""); } /** diff --git a/frameworks/ans/test/unittest/reminder_request_calendar_test.cpp b/frameworks/ans/test/unittest/reminder_request_calendar_test.cpp index 14a8a4121..bea879c3b 100644 --- a/frameworks/ans/test/unittest/reminder_request_calendar_test.cpp +++ b/frameworks/ans/test/unittest/reminder_request_calendar_test.cpp @@ -421,9 +421,6 @@ HWTEST_F(ReminderRequestCalendarTest, PreGetNextTriggerTimeIgnoreSnooze_03000, F struct tm nowTime; auto calendar = ReminderRequestCalendarTest::CreateCalendar(nowTime); EXPECT_NE(nullptr, calendar); - std::shared_ptr resultSet = - std::make_shared(); - calendar->RecoverFromDb(resultSet); EXPECT_EQ(calendar->PreGetNextTriggerTimeIgnoreSnooze(ignoreRepeat, forceToGetNext), calendar->GetNextTriggerTime()); @@ -954,11 +951,8 @@ HWTEST_F(ReminderRequestCalendarTest, RecoverFromDb_00001, Function | SmallTest auto calendar = ReminderRequestCalendarTest::CreateCalendar(nowTime); EXPECT_NE(nullptr, calendar); - std::shared_ptr resultSet = - std::make_shared(); - calendar->RecoverFromDb(resultSet); bool result = calendar->IsRepeatDay(1); - EXPECT_EQ(result, false); + EXPECT_EQ(result, true); } /** @@ -1102,11 +1096,8 @@ HWTEST_F(ReminderRequestCalendarTest, RecoverFromOldVersion_00001, Function | Sm auto calendar = ReminderRequestCalendarTest::CreateCalendar(nowTime); EXPECT_NE(nullptr, calendar); - std::shared_ptr resultSet = - std::make_shared(); - calendar->RecoverFromOldVersion(resultSet); bool result = calendar->IsRepeatDay(1); - EXPECT_EQ(result, false); + EXPECT_EQ(result, true); } /** @@ -1501,15 +1492,6 @@ HWTEST_F(ReminderRequestCalendarTest, AppendValuesBucket_00001, Function | Small std::vector daysOfWeek; sptr calendar = new ReminderRequestCalendar(nowTime, repeatMonths, repeatDays, daysOfWeek); EXPECT_NE(nullptr, calendar); - calendar->reminderId_ = 100; - - NativeRdb::ValuesBucket bucket; - NativeRdb::ValueObject object; - ReminderRequestCalendar::AppendValuesBucket(calendar, nullptr, bucket); - bucket.GetObject(ReminderCalendarTable::REMINDER_ID, object); - int32_t result {0}; - object.GetInt(result); - EXPECT_EQ(result, 100); } /** diff --git a/frameworks/ans/test/unittest/reminder_request_test.cpp b/frameworks/ans/test/unittest/reminder_request_test.cpp index b1fd3e023..0489d7cbb 100644 --- a/frameworks/ans/test/unittest/reminder_request_test.cpp +++ b/frameworks/ans/test/unittest/reminder_request_test.cpp @@ -784,21 +784,6 @@ HWTEST_F(ReminderRequestTest, OnTimeZoneChange_00001, Function | SmallTest | Lev } } -/** - * @tc.name: RecoverInt64FromDb_00001 - * @tc.desc: Test RecoverInt64FromDb parameters. - * @tc.type: FUNC - * @tc.require: issueI5UYHP - */ -HWTEST_F(ReminderRequestTest, RecoverInt64FromDb_00001, Function | SmallTest | Level1) -{ - std::shared_ptr resultSet = nullptr; - std::string columnName = "columnName"; - ReminderRequest::DbRecoveryType columnType = ReminderRequest::DbRecoveryType::INT; - auto rrc = std::make_shared(); - EXPECT_EQ(rrc->RecoverInt64FromDb(resultSet, columnName, columnType), 0); -} - /** * @tc.name: StringSplit_00001 * @tc.desc: Test StringSplit parameters. @@ -991,7 +976,7 @@ HWTEST_F(ReminderRequestTest, IsAlerting_00001, Function | SmallTest | Level1) HWTEST_F(ReminderRequestTest, GetButtonInfo_00001, Function | SmallTest | Level1) { auto rrc = std::make_shared(); - EXPECT_EQ(rrc->GetButtonInfo(), ""); + EXPECT_EQ(rrc->SerializeButtonInfo(), ""); } /** @@ -1025,33 +1010,6 @@ HWTEST_F(ReminderRequestTest, GetShowTime_00002, Function | SmallTest | Level1) EXPECT_EQ(res.substr(4, res.size()), ret); } -/** - * @tc.name: GetUid_00001 - * @tc.desc: Test GetUid parameters. - * @tc.type: FUNC - * @tc.require: issueI5VB6V - */ -HWTEST_F(ReminderRequestTest, GetUid_00001, Function | SmallTest | Level1) -{ - int32_t userId = 1; - std::string bundleName = "bundleName"; - auto rrc = std::make_shared(); - EXPECT_EQ(rrc->GetUid(userId, bundleName), -1); -} - -/** - * @tc.name: GetUserId_00001 - * @tc.desc: Test GetUserId parameters. - * @tc.type: FUNC - * @tc.require: issueI5VB6V - */ -HWTEST_F(ReminderRequestTest, GetUserId_00001, Function | SmallTest | Level1) -{ - int32_t uid = 1; - auto rrc = std::make_shared(); - EXPECT_EQ(rrc->GetUserId(uid), 0); -} - /** * @tc.name: SetActionButton_00001 * @tc.desc: Test SetActionButton parameters. @@ -1209,49 +1167,6 @@ HWTEST_F(ReminderRequestTest, OnStart_00001, Function | SmallTest | Level1) reminderRequestChild->OnStop(); } -/** - * @tc.name: RecoverInt64FromDb_00002 - * @tc.desc: Test RecoverInt64FromDb parameters. - * @tc.type: FUNC - * @tc.require: issueI65R21 - */ -HWTEST_F(ReminderRequestTest, RecoverInt64FromDb_00002, Function | SmallTest | Level1) - -{ - auto rrc = std::make_shared(); - std::shared_ptr resultSet = - std::make_shared(); - std::string columnName = "this is columnName"; - ReminderRequest::DbRecoveryType columnType = ReminderRequest::DbRecoveryType::INT; - int64_t result = rrc->RecoverInt64FromDb(resultSet, columnName, columnType); - EXPECT_EQ(result, 0); - - ReminderRequest::DbRecoveryType columnType2 = ReminderRequest::DbRecoveryType::LONG; - int64_t result2 = rrc->RecoverInt64FromDb(resultSet, columnName, columnType2); - EXPECT_EQ(result2, 0); - rrc->RecoverFromDb(resultSet); - rrc->RecoverActionButton(resultSet); - rrc->RecoverActionButton(nullptr); -} - -/** - * @tc.name: RecoverInt64FromDb_00003 - * @tc.desc: Test RecoverInt64FromDb parameters. - * @tc.type: FUNC - * @tc.require: issueI65R21 - */ -HWTEST_F(ReminderRequestTest, RecoverInt64FromDb_00003, Function | SmallTest | Level1) -{ - auto rrc = std::make_shared(); - std::shared_ptr resultSet = - std::make_shared(); - std::string columnName = "this is columnName"; - - ReminderRequest::DbRecoveryType columnType = ReminderRequest::DbRecoveryType(3); - int64_t result2 = rrc->RecoverInt64FromDb(resultSet, columnName, columnType); - EXPECT_EQ(result2, 0); -} - /** * @tc.name: RecoverWantAgent_00002 * @tc.desc: Test RecoverWantAgent parameters. @@ -1334,20 +1249,6 @@ HWTEST_F(ReminderRequestTest, CreateWantAgent_00002, Function | SmallTest | Leve EXPECT_EQ(WantAgent, nullptr); } -/** - * @tc.name: AddColumn_00002 - * @tc.desc: Test AddColumn parameters. - * @tc.type: FUNC - * @tc.require: issueI65R21 - */ -HWTEST_F(ReminderRequestTest, AddColumn_00002, Function | SmallTest | Level1) -{ - std::string name = "this is name"; - std::string type = "this is type"; - ReminderTable::AddColumn(name, type, true); - ReminderTable::AddColumn(name, type, false); -} - /** * @tc.name: OnClose_00100 * @tc.desc: Test OnClose parameters. @@ -1467,7 +1368,7 @@ HWTEST_F(ReminderRequestTest, RecoverWantAgent_00003, Function | SmallTest | Lev uint8_t type = 0; std::vector ret1 = rrc->StringSplit(wantAgentInfo, ""); EXPECT_EQ(ret1.size(), 2); - rrc->RecoverWantAgent(wantAgentInfo, type); + rrc->DeserializeWantAgent(wantAgentInfo, type); } /** @@ -1483,7 +1384,7 @@ HWTEST_F(ReminderRequestTest, RecoverWantAgent_00004, Function | SmallTest | Lev uint8_t type = 1; std::vector ret1 = rrc->StringSplit(wantAgentInfo, ""); EXPECT_EQ(ret1.size(), 2); - rrc->RecoverWantAgent(wantAgentInfo, type); + rrc->DeserializeWantAgent(wantAgentInfo, type); } /** @@ -1499,7 +1400,7 @@ HWTEST_F(ReminderRequestTest, RecoverWantAgent_00005, Function | SmallTest | Lev uint8_t type = 2; std::vector ret1 = rrc->StringSplit(wantAgentInfo, ""); EXPECT_EQ(ret1.size(), 2); - rrc->RecoverWantAgent(wantAgentInfo, type); + rrc->DeserializeWantAgent(wantAgentInfo, type); } /** @@ -1515,7 +1416,7 @@ HWTEST_F(ReminderRequestTest, RecoverWantAgent_00006, Function | SmallTest | Lev uint8_t type = 0; std::vector ret1 = rrc->StringSplit(wantAgentInfo, ""); EXPECT_EQ(ret1.size(), 3); - rrc->RecoverWantAgent(wantAgentInfo, type); + rrc->DeserializeWantAgent(wantAgentInfo, type); } /** @@ -2017,23 +1918,23 @@ HWTEST_F(ReminderRequestTest, RecoverWantAgent_00007, Function | SmallTest | Lev { auto rrc = std::make_shared(); std::string jsonValue = ""; - rrc->RecoverWantAgent(jsonValue, 0); + rrc->DeserializeWantAgent(jsonValue, 0); EXPECT_EQ(rrc->GetWantAgentInfo()->abilityName, ""); jsonValue = R"({"pkgName":"com.example.myapplication","abilityName":"MainAbility","uri":"","parameters":""})"; - rrc->RecoverWantAgent(jsonValue, 1); + rrc->DeserializeWantAgent(jsonValue, 1); EXPECT_EQ(rrc->GetMaxScreenWantAgentInfo()->abilityName, "MainAbility"); jsonValue = R"(})"; - rrc->RecoverWantAgent(jsonValue, 1); + rrc->DeserializeWantAgent(jsonValue, 1); EXPECT_EQ(rrc->GetMaxScreenWantAgentInfo()->abilityName, "MainAbility"); jsonValue = R"({})"; - rrc->RecoverWantAgent(jsonValue, 1); + rrc->DeserializeWantAgent(jsonValue, 1); EXPECT_EQ(rrc->GetMaxScreenWantAgentInfo()->abilityName, "MainAbility"); jsonValue = "fawexcdvasdfwessdf"; - rrc->RecoverWantAgent(jsonValue, 1); + rrc->DeserializeWantAgent(jsonValue, 1); EXPECT_EQ(rrc->GetMaxScreenWantAgentInfo()->abilityName, "MainAbility"); } @@ -2067,59 +1968,6 @@ HWTEST_F(ReminderRequestTest, MarshallingWantParameters_00001, Function | SmallT EXPECT_EQ(params2.GetStringParam(key), value); } -/** - * @tc.name: AppendWantAgentValuesBucket_00001 - * @tc.desc: Test AppendWantAgentValuesBucket parameters. - * @tc.type: FUNC - * @tc.require: issue#I94VJT - */ -HWTEST_F(ReminderRequestTest, AppendWantAgentValuesBucket_00001, Function | SmallTest | Level1) -{ - sptr rrc = new ReminderRequestChild; - NativeRdb::ValuesBucket values; - ReminderRequest::AppendWantAgentValuesBucket(rrc, values); - - NativeRdb::ValueObject object; - values.GetObject(ReminderBaseTable::WANT_AGENT, object); - std::string result; - object.GetString(result); - EXPECT_NE(result.find("pkgName"), -1); - - values.GetObject(ReminderBaseTable::MAX_SCREEN_WANT_AGENT, object); - object.GetString(result); - EXPECT_NE(result.find("pkgName"), -1); -} - -/** - * @tc.name: AppendWantAgentValuesBucket_00002 - * @tc.desc: Test AppendWantAgentValuesBucket parameters. - * @tc.type: FUNC - * @tc.require: issue#I94VJT - */ -HWTEST_F(ReminderRequestTest, AppendWantAgentValuesBucket_00002, Function | SmallTest | Level1) -{ - auto wantInfo = std::make_shared(); - wantInfo->pkgName = "test"; - auto maxWantInfo = std::make_shared(); - maxWantInfo->pkgName = "maxTest"; - - sptr rrc = new ReminderRequestChild; - rrc->SetWantAgentInfo(wantInfo); - rrc->SetMaxScreenWantAgentInfo(maxWantInfo); - NativeRdb::ValuesBucket values; - ReminderRequest::AppendWantAgentValuesBucket(rrc, values); - - NativeRdb::ValueObject object; - values.GetObject(ReminderBaseTable::WANT_AGENT, object); - std::string result; - object.GetString(result); - EXPECT_NE(result.find("test"), -1); - - values.GetObject(ReminderBaseTable::MAX_SCREEN_WANT_AGENT, object); - object.GetString(result); - EXPECT_NE(result.find("maxTest"), -1); -} - /** * @tc.name: WantAgentStr_00001 * @tc.desc: Test want agent str parameters. @@ -2310,8 +2158,6 @@ HWTEST_F(ReminderRequestTest, InitCreatorUid_00001, Function | SmallTest | Level rrc->InitCreatorUid(-1); EXPECT_EQ(rrc->GetCreatorUid(), -1); - - EXPECT_EQ(ReminderRequest::GetAppIndex(20020152), 0); } } } diff --git a/frameworks/ans/test/unittest/reminder_request_timer_test.cpp b/frameworks/ans/test/unittest/reminder_request_timer_test.cpp index 66b7f5889..ac6c58324 100644 --- a/frameworks/ans/test/unittest/reminder_request_timer_test.cpp +++ b/frameworks/ans/test/unittest/reminder_request_timer_test.cpp @@ -114,20 +114,5 @@ HWTEST_F(ReminderRequestTimerTest, ReadFromParcel_00100, Function | SmallTest | auto result = rrc->ReadFromParcel(parcel); EXPECT_EQ(result, false); } - -/** - * @tc.name: RecoverFromDb_00001 - * @tc.desc: Test RecoverFromDb parameters. - * @tc.type: FUNC - * @tc.require: issueI92BU9 - */ -HWTEST_F(ReminderRequestTimerTest, RecoverFromDb_00001, Function | SmallTest | Level1) -{ - auto rrc = std::make_shared(10); - std::shared_ptr resultSet = nullptr; - rrc->RecoverFromDb(resultSet); - uint64_t ret = rrc->GetInitInfo(); - EXPECT_EQ(ret, 0); -} } } \ No newline at end of file diff --git a/frameworks/ans/test/unittest/reminder_store_test.cpp b/frameworks/ans/test/unittest/reminder_store_test.cpp index 0687e8bf7..53aa06669 100644 --- a/frameworks/ans/test/unittest/reminder_store_test.cpp +++ b/frameworks/ans/test/unittest/reminder_store_test.cpp @@ -20,6 +20,9 @@ #include "reminder_store.h" #include "reminder_table.h" #include "reminder_table_old.h" +#include "reminder_request_alarm.h" +#include "reminder_request_calendar.h" +#include "reminder_request_timer.h" #undef private #undef protected #include "reminder_helper.h" @@ -46,6 +49,25 @@ public: ReminderHelper::CancelAllReminders(); NativeRdb::RdbHelper::DeleteRdbStore(ReminderStore::REMINDER_DB_DIR + ReminderStore::REMINDER_DB_NAME); } + + void InitStore(ReminderStore& store) + { + std::string dbConfig = ReminderStore::REMINDER_DB_DIR + "notification_test.db"; + NativeRdb::RdbStoreConfig config(dbConfig); + config.SetSecurityLevel(NativeRdb::SecurityLevel::S1); + { + ReminderStore::ReminderStoreDataCallBack rdbDataCallBack; + int32_t errCode = STATE_FAIL; + constexpr int32_t version = 7; + store.rdbStore_ = NativeRdb::RdbHelper::GetRdbStore(config, version, rdbDataCallBack, errCode); + } + } + + void ClearStore() + { + NativeRdb::RdbHelper::ClearCache(); + NativeRdb::RdbHelper::DeleteRdbStore(ReminderStore::REMINDER_DB_DIR + "notification_test.db"); + } static sptr bundleOption_; }; @@ -300,5 +322,315 @@ HWTEST_F(ReminderStoreTest, Delete_00005, Function | SmallTest | Level1) ret = reminderStore.Delete("com.example.simple", 100, -1); EXPECT_EQ(ret, -1); } + +/** + * @tc.name: ReminderStrategyTest_00001 + * @tc.desc: Test OnCreate parameters. + * @tc.type: FUNC + * @tc.require: issueI92BU9 + */ +HWTEST_F(ReminderStoreTest, ReminderTimerStrategyTest_00001, Function | SmallTest | Level1) +{ + ReminderStore reminderStore; + InitStore(reminderStore); + sptr reminder = new ReminderRequestTimer(); + reminder->reminderId_ = 999; + reminder->bundleName_ = "ReminderTimerStrategyTest_00001"; + reminder->userId_ = 998; + reminder->uid_ = 997; + reminder->isSystemApp_ = true; + reminder->reminderType_ = ReminderRequest::ReminderType::TIMER; + reminder->reminderTimeInMilli_ = 123456789; + reminder->triggerTimeInMilli_ = 987654321; + reminder->SetTimeInterval(100); + reminder->snoozeTimes_ = 10; + reminder->snoozeTimesDynamic_ = 9; + reminder->SetRingDuration(500); + reminder->isExpired_ = false; + reminder->state_ = 123; + ReminderRequestTimer* timer = static_cast(reminder.GetRefPtr()); + timer->countDownTimeInSeconds_ = 10001; + + sptr bundleOption = new NotificationBundleOption("test", 101); + reminderStore.UpdateOrInsert(reminder, bundleOption); + auto reminders = reminderStore.GetAllValidReminders(); + bool succeed = false; + for (auto each : reminders) { + if (each->reminderId_ != reminder->reminderId_) { + continue; + } + + EXPECT_EQ(reminder->bundleName_, each->bundleName_); + EXPECT_EQ(reminder->userId_, each->userId_); + EXPECT_EQ(reminder->uid_, each->uid_); + EXPECT_EQ(reminder->isSystemApp_, each->isSystemApp_); + EXPECT_EQ(reminder->reminderType_, each->reminderType_); + EXPECT_EQ(reminder->reminderTimeInMilli_, each->reminderTimeInMilli_); + EXPECT_EQ(reminder->triggerTimeInMilli_, each->triggerTimeInMilli_); + EXPECT_EQ(reminder->GetTimeInterval(), each->GetTimeInterval()); + EXPECT_EQ(reminder->snoozeTimes_, each->snoozeTimes_); + EXPECT_EQ(reminder->snoozeTimesDynamic_, each->snoozeTimesDynamic_); + EXPECT_EQ(reminder->GetRingDuration(), each->GetRingDuration()); + EXPECT_EQ(reminder->isExpired_, each->isExpired_); + EXPECT_EQ(reminder->state_, each->state_); + ReminderRequestTimer* timer1 = static_cast(each.GetRefPtr()); + EXPECT_EQ(timer1->countDownTimeInSeconds_, timer->countDownTimeInSeconds_); + succeed = true; + break; + } + reminderStore.Delete(reminder->reminderId_); + EXPECT_EQ(succeed, true); + ClearStore(); +} + +/** + * @tc.name: ReminderTimerStrategyTest_00002 + * @tc.desc: Test OnCreate parameters. + * @tc.type: FUNC + * @tc.require: issueI92BU9 + */ +HWTEST_F(ReminderStoreTest, ReminderTimerStrategyTest_00002, Function | SmallTest | Level1) +{ + ReminderStore reminderStore; + InitStore(reminderStore); + sptr reminder = new ReminderRequestTimer(); + reminder->reminderId_ = 999; + reminder->reminderType_ = ReminderRequest::ReminderType::TIMER; + reminder->slotType_ = static_cast(1); + reminder->snoozeSlotType_ = static_cast(1); + reminder->notificationId_ = 123; + reminder->title_ = "title_"; + reminder->content_ = "content_"; + reminder->snoozeContent_ = "snoozeContent_"; + reminder->expiredContent_ = "expiredContent_"; + reminder->tapDismissed_ = false; + reminder->autoDeletedTime_ = 666; + reminder->groupId_ = "groupId_"; + reminder->customRingUri_ = "customRingUri_"; + reminder->creatorBundleName_ = "creatorBundleName_"; + reminder->creatorUid_ = 101; + ReminderRequestTimer* timer = static_cast(reminder.GetRefPtr()); + timer->countDownTimeInSeconds_ = 10001; + + sptr bundleOption = new NotificationBundleOption("test", 101); + reminderStore.UpdateOrInsert(reminder, bundleOption); + auto reminders = reminderStore.GetAllValidReminders(); + bool succeed = false; + for (auto each : reminders) { + if (each->reminderId_ != reminder->reminderId_) { + continue; + } + + EXPECT_EQ(reminder->slotType_, each->slotType_); + EXPECT_EQ(reminder->snoozeSlotType_, each->snoozeSlotType_); + EXPECT_EQ(reminder->notificationId_, each->notificationId_); + EXPECT_EQ(reminder->title_, each->title_); + EXPECT_EQ(reminder->content_, each->content_); + EXPECT_EQ(reminder->snoozeContent_, each->snoozeContent_); + EXPECT_EQ(reminder->expiredContent_, each->expiredContent_); + EXPECT_EQ(reminder->tapDismissed_, each->tapDismissed_); + EXPECT_EQ(reminder->autoDeletedTime_, each->autoDeletedTime_); + EXPECT_EQ(reminder->groupId_, each->groupId_); + EXPECT_EQ(reminder->customRingUri_, each->customRingUri_); + EXPECT_EQ(reminder->creatorBundleName_, each->creatorBundleName_); + EXPECT_EQ(reminder->creatorUid_, each->creatorUid_); + succeed = true; + break; + } + reminderStore.Delete(reminder->reminderId_); + EXPECT_EQ(succeed, true); + ClearStore(); +} + +/** + * @tc.name: ReminderTimerStrategyTest_00003 + * @tc.desc: Test OnCreate parameters. + * @tc.type: FUNC + * @tc.require: issueI92BU9 + */ +HWTEST_F(ReminderStoreTest, ReminderTimerStrategyTest_00003, Function | SmallTest | Level1) +{ + ReminderStore reminderStore; + InitStore(reminderStore); + sptr reminder = new ReminderRequestTimer(); + reminder->reminderId_ = 999; + reminder->reminderType_ = ReminderRequest::ReminderType::TIMER; + reminder->customButtonUri_ = "customButtonUri_"; + if (reminder->wantAgentInfo_ == nullptr) { + reminder->InitServerObj(); + } + reminder->wantAgentInfo_->pkgName = "pkgName"; + reminder->wantAgentInfo_->abilityName = "abilityName"; + reminder->wantAgentInfo_->uri = "uri"; + reminder->maxScreenWantAgentInfo_->pkgName = "pkgName1"; + reminder->maxScreenWantAgentInfo_->abilityName = "abilityName1"; + ReminderRequestTimer* timer = static_cast(reminder.GetRefPtr()); + timer->countDownTimeInSeconds_ = 10001; + + sptr bundleOption = new NotificationBundleOption("test", 101); + reminderStore.UpdateOrInsert(reminder, bundleOption); + auto reminders = reminderStore.GetAllValidReminders(); + bool succeed = false; + for (auto each : reminders) { + if (each->reminderId_ != reminder->reminderId_) { + continue; + } + + EXPECT_EQ(reminder->customButtonUri_, each->customButtonUri_); + EXPECT_EQ(reminder->wantAgentInfo_->pkgName, each->wantAgentInfo_->pkgName); + EXPECT_EQ(reminder->wantAgentInfo_->abilityName, each->wantAgentInfo_->abilityName); + EXPECT_EQ(reminder->wantAgentInfo_->uri, each->wantAgentInfo_->uri); + EXPECT_EQ(reminder->maxScreenWantAgentInfo_->pkgName, each->maxScreenWantAgentInfo_->pkgName); + EXPECT_EQ(reminder->maxScreenWantAgentInfo_->abilityName, each->maxScreenWantAgentInfo_->abilityName); + succeed = true; + break; + } + reminderStore.Delete(reminder->reminderId_); + EXPECT_EQ(succeed, true); + ClearStore(); +} + +/** + * @tc.name: ReminderAlarmStrategyTest_00001 + * @tc.desc: Test OnCreate parameters. + * @tc.type: FUNC + * @tc.require: issueI92BU9 + */ +HWTEST_F(ReminderStoreTest, ReminderAlarmStrategyTest_00001, Function | SmallTest | Level1) +{ + ReminderStore reminderStore; + InitStore(reminderStore); + sptr reminder = new ReminderRequestAlarm(); + reminder->reminderId_ = 999; + reminder->reminderType_ = ReminderRequest::ReminderType::ALARM; + reminder->repeatDaysOfWeek_ = 55; + ReminderRequestAlarm* alarm = static_cast(reminder.GetRefPtr()); + alarm->hour_ = 12; + alarm->minute_ = 30; + + sptr bundleOption = new NotificationBundleOption("test", 101); + reminderStore.UpdateOrInsert(reminder, bundleOption); + auto reminders = reminderStore.GetAllValidReminders(); + bool succeed = false; + for (auto each : reminders) { + if (each->reminderId_ != reminder->reminderId_) { + continue; + } + + EXPECT_EQ(reminder->repeatDaysOfWeek_, each->repeatDaysOfWeek_); + ReminderRequestAlarm* alarm1 = static_cast(each.GetRefPtr()); + EXPECT_EQ(alarm->hour_, alarm1->hour_); + EXPECT_EQ(alarm->minute_, alarm1->minute_); + succeed = true; + break; + } + reminderStore.Delete(reminder->reminderId_); + EXPECT_EQ(succeed, true); + ClearStore(); +} + +/** + * @tc.name: ReminderCalendarStrategyTest_00001 + * @tc.desc: Test OnCreate parameters. + * @tc.type: FUNC + * @tc.require: issueI92BU9 + */ +HWTEST_F(ReminderStoreTest, ReminderCalendarStrategyTest_00001, Function | SmallTest | Level1) +{ + ReminderStore reminderStore; + InitStore(reminderStore); + time_t t; + (void)time(&t); // unit is seconds. + uint64_t ts = t * 1000; // ms + + sptr reminder = new ReminderRequestCalendar(); + reminder->reminderId_ = 999; + reminder->reminderType_ = ReminderRequest::ReminderType::CALENDAR; + ReminderRequestCalendar* calendar = static_cast(reminder.GetRefPtr()); + calendar->firstDesignateYear_ = 2006; + calendar->firstDesignateMonth_ = 6; + calendar->firstDesignateDay_ = 6; + calendar->SetDateTime(ts); + calendar->SetEndDateTime(ts + 60 * 1000); + calendar->SetLastStartDateTime(ts + 10 * 1000); + calendar->repeatDay_ = 12; + calendar->repeatMonth_ = 13; + calendar->AddExcludeDate(ts); + + sptr bundleOption = new NotificationBundleOption("test", 101); + reminderStore.UpdateOrInsert(reminder, bundleOption); + auto reminders = reminderStore.GetAllValidReminders(); + bool succeed = false; + for (auto each : reminders) { + if (each->reminderId_ != reminder->reminderId_) { + continue; + } + + ReminderRequestCalendar* calendar1 = static_cast(each.GetRefPtr()); + EXPECT_EQ(calendar1->firstDesignateYear_, calendar->firstDesignateYear_); + EXPECT_EQ(calendar1->firstDesignateMonth_, calendar->firstDesignateMonth_); + EXPECT_EQ(calendar1->firstDesignateDay_, calendar->firstDesignateDay_); + EXPECT_EQ(calendar1->repeatDay_, calendar->repeatDay_); + EXPECT_EQ(calendar1->repeatMonth_, calendar->repeatMonth_); + EXPECT_EQ(calendar1->GetDateTime(), calendar->GetDateTime()); + EXPECT_EQ(calendar1->GetEndDateTime(), calendar->GetEndDateTime()); + EXPECT_EQ(calendar1->GetLastStartDateTime(), calendar->GetLastStartDateTime()); + EXPECT_EQ(calendar1->SerializationExcludeDates(), calendar->SerializationExcludeDates()); + EXPECT_EQ(calendar1->SerializationRRule(), calendar->SerializationRRule()); + succeed = true; + break; + } + reminderStore.Delete(reminder->reminderId_); + EXPECT_EQ(succeed, true); + ClearStore(); +} + +/** + * @tc.name: ReminderCalendarStrategyTest_00002 + * @tc.desc: Test OnCreate parameters. + * @tc.type: FUNC + * @tc.require: issueI92BU9 + */ +HWTEST_F(ReminderStoreTest, ReminderCalendarStrategyTest_00002, Function | SmallTest | Level1) +{ + ReminderStore reminderStore; + InitStore(reminderStore); + time_t t; + (void)time(&t); // unit is seconds. + uint64_t ts = t * 1000; // ms + + sptr reminder = new ReminderRequestCalendar(); + reminder->reminderId_ = 999; + reminder->reminderType_ = ReminderRequest::ReminderType::CALENDAR; + reminder->repeatDaysOfWeek_ = 55; + ReminderRequestCalendar* calendar = static_cast(reminder.GetRefPtr()); + calendar->SetDateTime(ts); + calendar->rruleWantAgentInfo_ = std::make_shared(); + calendar->rruleWantAgentInfo_->pkgName = "pkgName"; + calendar->rruleWantAgentInfo_->abilityName = "abilityName"; + calendar->rruleWantAgentInfo_->uri = "uri"; + + sptr bundleOption = new NotificationBundleOption("test", 101); + reminderStore.UpdateOrInsert(reminder, bundleOption); + auto reminders = reminderStore.GetAllValidReminders(); + bool succeed = false; + for (auto each : reminders) { + if (each->reminderId_ != reminder->reminderId_) { + continue; + } + + EXPECT_EQ(reminder->repeatDaysOfWeek_, each->repeatDaysOfWeek_); + ReminderRequestCalendar* calendar1 = static_cast(each.GetRefPtr()); + EXPECT_EQ(calendar1->GetDateTime(), calendar->GetDateTime()); + EXPECT_EQ(calendar1->GetEndDateTime(), calendar->GetDateTime()); + EXPECT_EQ(calendar1->GetLastStartDateTime(), calendar->GetDateTime()); + EXPECT_EQ(calendar1->SerializationRRule(), calendar->SerializationRRule()); + succeed = true; + break; + } + reminderStore.Delete(reminder->reminderId_); + EXPECT_EQ(succeed, true); + ClearStore(); +} } } \ No newline at end of file diff --git a/frameworks/core/src/ans_notification.cpp b/frameworks/core/src/ans_notification.cpp index 723d8ccd8..84aafa456 100644 --- a/frameworks/core/src/ans_notification.cpp +++ b/frameworks/core/src/ans_notification.cpp @@ -28,6 +28,8 @@ #include "reminder_request_timer.h" #include "system_ability_definition.h" +#include + namespace OHOS { namespace Notification { namespace { diff --git a/interfaces/inner_api/reminder_request.h b/interfaces/inner_api/reminder_request.h index 841e6a688..642f2d918 100644 --- a/interfaces/inner_api/reminder_request.h +++ b/interfaces/inner_api/reminder_request.h @@ -19,11 +19,9 @@ #include #include -#include "abs_shared_result_set.h" #include "notification_bundle_option.h" #include "notification_constant.h" #include "notification_request.h" -#include "values_bucket.h" #include "want_params.h" namespace OHOS { @@ -437,6 +435,27 @@ public: */ std::string GetBundleName() const; + /** + * @brief Set the reminder type. + * + * @param reminderType the reminder type. + */ + void SetReminderType(const ReminderType type); + + /** + * @brief Set the reminder state. + * + * @param state the reminder state. + */ + void SetState(const uint8_t state); + + /** + * @brief Set the reminder repeat days of week. + * + * @param state the reminder repeat days of week. + */ + void SetRepeatDaysOfWeek(const uint8_t repeatDaysOfWeek); + /** * @brief Set the app system. * @@ -608,17 +627,6 @@ public: */ virtual bool OnTimeZoneChange(); - void RecoverBasicFromOldVersion(const std::shared_ptr& resultSet); - virtual void RecoverFromOldVersion(const std::shared_ptr& resultSet); - - /** - * @brief Recovery reminder instance from database record. - * - * @param resultSet Indicates the resultSet with pointer to the row of record data. - */ - void RecoverFromDbBase(const std::shared_ptr& resultSet); - virtual void RecoverFromDb(const std::shared_ptr& resultSet) {}; - /** * @brief Sets action button. * @@ -801,7 +809,9 @@ public: return true; } + void SetWantAgentStr(const std::string& wantStr); std::string GetWantAgentStr(); + void SetMaxWantAgentStr(const std::string& maxWantStr); std::string GetMaxWantAgentStr(); /** @@ -879,6 +889,17 @@ public: */ std::vector GetDaysOfWeek() const; + /** + * @brief Create notification request struct when recover from rdb or + * recv reminder info from ipc. + */ + bool InitNotificationRequest(); + + /** + * @brief Gets repeat days of week + */ + uint8_t GetRepeatDaysOfWeek() const; + /** * @brief When system language change, will call this function. * need load resource to update button title @@ -886,15 +907,34 @@ public: */ void OnLanguageChange(const std::shared_ptr &resMgr); +public: + /** + * @brief Serialize want agent info and max want agent info to string. + * Persist to the rdb. + */ + void SerializeWantAgent(std::string& wantInfoStr, std::string& maxWantInfoStr); + + /** + * @brief Deserialize want agent info and max want agent info from string. + * Recover from the rdb. + */ + void DeserializeWantAgent(const std::string& wantAgentInfo, const uint8_t type); + + /** + * @brief Serialize action button info to string. + * Persist to the rdb. + */ + std::string SerializeButtonInfo() const; + + /** + * @brief Deserialize action button info from string. + * Recover from the rdb. + */ + void DeserializeButtonInfo(const std::string& buttonInfoStr); + static int32_t GetActualTime(const TimeTransferType &type, int32_t cTime); static int32_t GetCTime(const TimeTransferType &type, int32_t actualTime); static uint64_t GetDurationSinceEpochInMilli(const time_t target); - static int32_t GetUid(const int32_t &userId, const std::string &bundleName); - static int32_t GetAppIndex(const int32_t uid); - static int32_t GetUserId(const int32_t &uid); - static void AppendValuesBucket(const sptr &reminder, - const sptr &bundleOption, NativeRdb::ValuesBucket &values, - bool oldVersion = false); static std::vector StringSplit(std::string source, const std::string &split); static int32_t GLOBAL_ID; @@ -979,9 +1019,6 @@ protected: return INVALID_LONG_LONG_VALUE; } - int64_t RecoverInt64FromDb(const std::shared_ptr &resultSet, - const std::string &columnName, const DbRecoveryType &columnType); - uint8_t repeatDaysOfWeek_{0}; /** @@ -993,7 +1030,6 @@ protected: */ int64_t GetNextDaysOfWeek(const time_t now, const time_t target) const; void SetRepeatDaysOfWeek(bool set, const std::vector &daysOfWeek); - uint8_t GetRepeatDaysOfWeek() const; time_t GetTriggerTimeWithDST(const time_t now, const time_t nextTriggerTime) const; uint64_t GetTriggerTime(const time_t now, const time_t nextTriggerTime) const; uint64_t GetNowInstantMilli() const; @@ -1003,13 +1039,11 @@ private: void AddRemovalWantAgent(); std::shared_ptr CreateWantAgent(AppExecFwk::ElementName &element) const; std::shared_ptr CreateMaxWantAgent(AppExecFwk::ElementName &element) const; - std::string GetButtonInfo() const; std::string GetShowTime(const uint64_t showTime) const; std::string GetTimeInfoInner(const time_t &timeInSecond, const TimeFormat &format, bool keep24Hour) 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); - bool InitNotificationRequest(); void InitServerObj(); void SetMaxScreenWantAgent(AppExecFwk::ElementName &element); void SetState(bool deSet, const uint8_t newState, std::string function); @@ -1047,18 +1081,12 @@ private: */ void UpdateNotificationStateForSnooze(); - static void AppendWantAgentValuesBucket(const sptr& reminder, - NativeRdb::ValuesBucket& values); - bool MarshallingWantParameters(Parcel& parcel, const AAFwk::WantParams& params) const; bool MarshallingActionButton(Parcel& parcel) const; bool ReadWantParametersFromParcel(Parcel& parcel, AAFwk::WantParams& wantParams); bool ReadActionButtonFromParcel(Parcel& parcel); - void RecoverBasicFromDb(const std::shared_ptr& resultSet); void RecoverActionButtonJsonMode(const std::string& jsonString); - void RecoverActionButton(const std::shared_ptr& resultSet); - void RecoverWantAgent(const std::string& wantAgentInfo, const uint8_t& type); void RecoverWantAgentByJson(const std::string& wantAgentInfo, const uint8_t& type); static const uint32_t MIN_TIME_INTERVAL_IN_MILLI; diff --git a/interfaces/inner_api/reminder_request_alarm.h b/interfaces/inner_api/reminder_request_alarm.h index d82f093a3..e9f01d922 100644 --- a/interfaces/inner_api/reminder_request_alarm.h +++ b/interfaces/inner_api/reminder_request_alarm.h @@ -71,6 +71,20 @@ public: */ uint8_t GetMinute() const; + /** + * @brief Sets the hour. + * + * @param hour Indicates the hour. + */ + void SetHour(const uint8_t hour); + + /** + * @brief Sets the minute. + * + * @param minute Indicates the minute. + */ + void SetMinute(const uint8_t minute); + virtual bool UpdateNextReminder() override; /** @@ -95,10 +109,6 @@ public: * @return true if read parcel success. */ bool ReadFromParcel(Parcel &parcel) override; - virtual void RecoverFromDb(const std::shared_ptr& resultSet) override; - virtual void RecoverFromOldVersion(const std::shared_ptr& resultSet) override; - static void AppendValuesBucket(const sptr &reminder, - const sptr &bundleOption, NativeRdb::ValuesBucket &values); protected: virtual uint64_t PreGetNextTriggerTimeIgnoreSnooze(bool ignoreRepeat, bool forceToGetNext) override; diff --git a/interfaces/inner_api/reminder_request_calendar.h b/interfaces/inner_api/reminder_request_calendar.h index 38578e528..6e2ff9dbc 100644 --- a/interfaces/inner_api/reminder_request_calendar.h +++ b/interfaces/inner_api/reminder_request_calendar.h @@ -118,6 +118,133 @@ public: return firstDesignateDay_; } + /** + * @brief Gets the repeat day. + */ + uint32_t GetRepeatDay() const + { + return repeatDay_; + } + + /** + * @brief Gets the repeat month. + */ + uint16_t GetRepeatMonth() const + { + return repeatMonth_; + } + + /** + * @brief Gets the start date time. + */ + uint64_t GetDateTime() const; + + /** + * @brief Gets the end date time. + */ + uint64_t GetEndDateTime() const; + + /** + * @brief Sets the year. + * + * @param year Indicates the year. + */ + void SetYear(const uint16_t year); + + /** + * @brief Sets the month. + * + * @param month Indicates the month. + */ + void SetMonth(const uint8_t month); + + /** + * @brief Sets the day. + * + * @param day Indicates the day. + */ + void SetDay(const uint8_t day); + + /** + * @brief Sets the hour. + * + * @param hour Indicates the hour. + */ + void SetHour(const uint8_t hour); + + /** + * @brief Sets the minute. + * + * @param minute Indicates the minute. + */ + void SetMinute(const uint8_t minute); + + /** + * @brief Sets the repeat day. + * + * @param repeatDay Indicates the repeat day. + */ + void SetRepeatDay(const uint32_t repeatDay); + + /** + * @brief Sets the repeat month. + * + * @param repeatMonth Indicates the repeat month. + */ + void SetRepeatMonth(const uint16_t repeatMonth); + + /** + * @brief Sets the first designate year. + * + * @param firstDesignateYear Indicates the first designate year. + */ + void SetFirstDesignateYear(const uint16_t firstDesignateYear); + + /** + * @brief Sets the first designate month. + * + * @param firstDesignateMonth Indicates the first designate month. + */ + void SetFirstDesignageMonth(const uint16_t firstDesignateMonth); + + /** + * @brief Sets the first designate day. + * + * @param firstDesignateDay Indicates the first designate day. + */ + void SetFirstDesignateDay(const uint16_t firstDesignateDay); + + /** + * @brief Sets the hour. + * + * @param hour Indicates the hour. + */ + void SetDateTime(const uint64_t time); + + /** + * @brief Serialize the rrule to string. + * Persist to the rdb. + */ + std::string SerializationRRule(); + + /** + * @brief Deserialize the rrule from string. + * Recover from the rdb. + */ + void DeserializationRRule(const std::string& str); + + /** + * @brief Serialize the exclude date to string. + * Persist to the rdb. + */ + std::string SerializationExcludeDates(); + + /** + * @brief Deserialize the exclude date from string. + * Recover from the rdb. + */ + void DeserializationExcludeDates(const std::string& str); + bool InitTriggerTime(); std::vector GetRepeatMonths() const; @@ -171,11 +298,6 @@ public: bool ReadFromParcel(Parcel &parcel) override; bool SetNextTriggerTime() override; - virtual void RecoverFromDb(const std::shared_ptr& resultSet) override; - virtual void RecoverFromOldVersion(const std::shared_ptr &resultSet) override; - - static void AppendValuesBucket(const sptr &reminder, - const sptr &bundleOption, NativeRdb::ValuesBucket &values); static uint8_t GetDaysOfMonth(const uint16_t &year, const uint8_t &month); bool SetEndDateTime(const uint64_t time); @@ -204,14 +326,6 @@ private: uint8_t GetNextDay(const uint16_t &settedYear, const uint8_t &settedMonth, const tm &now, const tm &target) const; uint64_t GetNextTriggerTime(const bool updateLast = false); uint64_t GetNextTriggerTimeAsRepeatReminder(const tm &nowTime, const tm &tarTime) const; - uint32_t GetRepeatDay() const - { - return repeatDay_; - } - uint16_t GetRepeatMonth() const - { - return repeatMonth_; - } uint64_t GetTimeInstantMilli( uint16_t year, uint8_t month, uint8_t day, uint8_t hour, uint8_t minute, uint8_t second) const; @@ -234,15 +348,6 @@ private: */ void CalcLastStartDateTime(); - void SetDateTime(const uint64_t time); - uint64_t GetDateTime(); - uint64_t GetEndDateTime(); - - std::string SerializationRRule(); - std::string SerializationExcludeDates(); - void DeserializationRRule(const std::string& str); - void DeserializationExcludeDates(const std::string& str); - static const uint8_t DEFAULT_SNOOZE_TIMES; tm dateTime_ = { diff --git a/interfaces/inner_api/reminder_request_timer.h b/interfaces/inner_api/reminder_request_timer.h index 1e9d4b5f2..527b65cbe 100644 --- a/interfaces/inner_api/reminder_request_timer.h +++ b/interfaces/inner_api/reminder_request_timer.h @@ -51,6 +51,8 @@ public: ~ReminderRequestTimer() override {}; uint64_t GetInitInfo() const; + void SetInitInfo(const uint64_t countDownTimeInSeconds); + virtual bool OnDateTimeChange() override; virtual bool OnTimeZoneChange() override; virtual bool UpdateNextReminder() override; @@ -69,10 +71,6 @@ public: bool ReadFromParcel(Parcel &parcel) override; - virtual void RecoverFromDb(const std::shared_ptr& resultSet) override; - static void AppendValuesBucket(const sptr &reminder, - const sptr &bundleOption, NativeRdb::ValuesBucket &values); - protected: virtual uint64_t PreGetNextTriggerTimeIgnoreSnooze(bool ignoreRepeat, bool forceToGetNext) override; diff --git a/services/ans/BUILD.gn b/services/ans/BUILD.gn index ef5291a15..d70383802 100644 --- a/services/ans/BUILD.gn +++ b/services/ans/BUILD.gn @@ -90,7 +90,11 @@ ohos_shared_library("libans") { "src/reminder_data_manager.cpp", "src/reminder_data_manager_inner.cpp", "src/reminder_event_manager.cpp", + "src/reminder_store.cpp", + "src/reminder_store_strategy.cpp", "src/reminder_swing_decision_center.cpp", + "src/reminder_table.cpp", + "src/reminder_table_old.cpp", "src/reminder_timer_info.cpp", "src/system_dialog_connect_stb.cpp", "src/system_event_observer.cpp", diff --git a/services/ans/include/bundle_manager_helper.h b/services/ans/include/bundle_manager_helper.h index 30da5ea18..f559e0eb2 100644 --- a/services/ans/include/bundle_manager_helper.h +++ b/services/ans/include/bundle_manager_helper.h @@ -116,6 +116,14 @@ public: * @return Returns the check result. */ bool CheckApiCompatibility(const std::string &bundleName, const int32_t &uid); + + /** + * @brief Obtains the app index by uid. + * @param uid Indicates uid. + * @return Returns the query result if succeed, retrun 0(main index) otherwise. + */ + int32_t GetAppIndexByUid(const int32_t uid); + private: void Connect(); void Disconnect(); diff --git a/interfaces/inner_api/reminder_store.h b/services/ans/include/reminder_store.h similarity index 100% rename from interfaces/inner_api/reminder_store.h rename to services/ans/include/reminder_store.h diff --git a/services/ans/include/reminder_store_strategy.h b/services/ans/include/reminder_store_strategy.h new file mode 100644 index 000000000..0d0ccefb6 --- /dev/null +++ b/services/ans/include/reminder_store_strategy.h @@ -0,0 +1,193 @@ +/* + * Copyright (c) 2024 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +#ifndef BASE_NOTIFICATION_DISTRIBUTED_NOTIFICATION_SERVICE_SERVICES_ANS_INCLUDE_REMINDER_STORE_STRATEGY_H +#define BASE_NOTIFICATION_DISTRIBUTED_NOTIFICATION_SERVICE_SERVICES_ANS_INCLUDE_REMINDER_STORE_STRATEGY_H + +#include +#include + +#include "reminder_request.h" +#include "rdb_store.h" + +namespace OHOS { +namespace Notification { +class ReminderStrategy { +public: + /** + * @brief Gets the value from rdb result. + * + * @param resultSet the rdb result. + * @param name the column name in rdb. + * @param value the column value in rdb. + */ + template + static void GetRdbValue(const std::shared_ptr& resultSet, + const std::string& name, T& value); + +public: + /** + * @brief Persist the reminder to the database. + */ + static void AppendValuesBucket(const sptr& reminder, + NativeRdb::ValuesBucket &values, const bool oldVersion = false); + + /** + * @brief Restore the reminder from the database(old version rdb). + */ + static void RecoverFromOldVersion(sptr& reminder, + const std::shared_ptr& resultSet); + + /** + * @brief Restore the reminder from the database. + */ + static void RecoverFromDb(sptr& reminder, const std::shared_ptr& resultSet); + +private: + /** + * @brief Recovery time related fields from the database(old version rdb). + */ + static void RecoverTimeFromOldVersion(sptr& reminder, + const std::shared_ptr& resultSet); + /** + * @brief Recovery id related fields from the database(old version rdb). + */ + static void RecoverIdFromOldVersion(sptr& reminder, + const std::shared_ptr& resultSet); + /** + * @brief Recovery context related from the database(old version rdb). + */ + static void RecoverContextFromOldVersion(sptr& reminder, + const std::shared_ptr& resultSet); + + /** + * @brief Recovery time related fields from the database. + */ + static void RecoverTimeFromDb(sptr& reminder, + const std::shared_ptr& resultSet); + /** + * @brief Recovery id related fields from the database. + */ + static void RecoverIdFromDb(sptr& reminder, + const std::shared_ptr& resultSet); + /** + * @brief Recovery context related from the database. + */ + static void RecoverContextFromDb(sptr& reminder, + const std::shared_ptr& resultSet); +}; + +class ReminderTimerStrategy { +public: + /** + * @brief Persist the reminder to the database. + */ + static void AppendValuesBucket(const sptr& reminder, + NativeRdb::ValuesBucket& values); + + /** + * @brief Restore the reminder from the database(old version rdb). + */ + static void RecoverFromOldVersion(sptr& reminder, + const std::shared_ptr& resultSet); + + /** + * @brief Restore the reminder from the database. + */ + static void RecoverFromDb(sptr& reminder, const std::shared_ptr& baseResult, + const std::shared_ptr& resultSet); +}; + +class ReminderAlarmStrategy { +public: + /** + * @brief Persist the reminder to the database. + */ + static void AppendValuesBucket(const sptr &reminder, NativeRdb::ValuesBucket &values); + + /** + * @brief Restore the reminder from the database(old version rdb). + */ + static void RecoverFromOldVersion(sptr& reminder, + const std::shared_ptr& resultSet); + + /** + * @brief Restore the reminder from the database. + */ + static void RecoverFromDb(sptr& reminder, const std::shared_ptr& baseResult, + const std::shared_ptr& resultSet); +}; + +class ReminderCalendarStrategy { +public: + /** + * @brief Persist the reminder to the database. + */ + static void AppendValuesBucket(const sptr &reminder, NativeRdb::ValuesBucket &values); + + /** + * @brief Restore the reminder from the database(old version rdb). + */ + static void RecoverFromOldVersion(sptr& reminder, + const std::shared_ptr& resultSet); + + /** + * @brief Restore the reminder from the database. + */ + static void RecoverFromDb(sptr& reminder, const std::shared_ptr& baseResult, + const std::shared_ptr& resultSet); + +private: + static void RecoverTime(sptr& reminder, const std::shared_ptr& resultSet); +}; + +template +void ReminderStrategy::GetRdbValue(const std::shared_ptr& resultSet, + const std::string& name, T& value) +{ + value = T(); + int32_t columnIndex = -1; + resultSet->GetColumnIndex(name, columnIndex); + if (columnIndex == -1) { + ANSR_LOGE("the column %{public}s does not exsit.", name.c_str()); + return; + } + + if constexpr (std::is_same_v) { + resultSet->GetString(columnIndex, value); + } else if constexpr (std::is_same_v) { + resultSet->GetLong(columnIndex, value); + } else if constexpr (std::is_same_v) { + int64_t t = 0; + resultSet->GetLong(columnIndex, t); + value = static_cast(t); + } else if constexpr (std::is_same_v) { + resultSet->GetInt(columnIndex, value); + } else if constexpr (std::is_same_v) { + int32_t t = 0; + resultSet->GetInt(columnIndex, t); + value = static_cast(t); + } else if constexpr (std::is_same_v) { + int32_t t = 0; + resultSet->GetInt(columnIndex, t); + value = static_cast(t); + } else if constexpr (std::is_same_v) { + int32_t t = 0; + resultSet->GetInt(columnIndex, t); + value = static_cast(t); + } +} +} // namespace Notification +} // namespace OHOS +#endif // BASE_NOTIFICATION_DISTRIBUTED_NOTIFICATION_SERVICE_SERVICES_ANS_INCLUDE_REMINDER_STORE_STRATEGY_H \ No newline at end of file diff --git a/interfaces/inner_api/reminder_table.h b/services/ans/include/reminder_table.h similarity index 100% rename from interfaces/inner_api/reminder_table.h rename to services/ans/include/reminder_table.h diff --git a/interfaces/inner_api/reminder_table_old.h b/services/ans/include/reminder_table_old.h similarity index 100% rename from interfaces/inner_api/reminder_table_old.h rename to services/ans/include/reminder_table_old.h diff --git a/services/ans/src/bundle_manager_helper.cpp b/services/ans/src/bundle_manager_helper.cpp index 5ea086ca1..5b8ada05b 100644 --- a/services/ans/src/bundle_manager_helper.cpp +++ b/services/ans/src/bundle_manager_helper.cpp @@ -226,5 +226,20 @@ bool BundleManagerHelper::GetBundleInfos( IPCSkeleton::SetCallingIdentity(identity); return ret; } + +int32_t BundleManagerHelper::GetAppIndexByUid(const int32_t uid) +{ + int32_t appIndex = 0; + std::lock_guard lock(connectionMutex_); + Connect(); + if (nullptr == bundleMgr_) { + return appIndex; + } + std::string bundleName; + std::string identity = IPCSkeleton::ResetCallingIdentity(); + bundleMgr_->GetNameAndIndexForUid(uid, bundleName, appIndex); + IPCSkeleton::SetCallingIdentity(identity); + return appIndex; +} } // namespace Notification } // namespace OHOS diff --git a/services/ans/src/reminder_data_manager.cpp b/services/ans/src/reminder_data_manager.cpp index b1b7b265b..98e1ce896 100644 --- a/services/ans/src/reminder_data_manager.cpp +++ b/services/ans/src/reminder_data_manager.cpp @@ -30,6 +30,7 @@ #include "ipc_skeleton.h" #include "notification_slot.h" #include "os_account_manager.h" +#include "os_account_manager_helper.h" #include "reminder_event_manager.h" #include "time_service_client.h" #include "singleton.h" @@ -892,7 +893,9 @@ void ReminderDataManager::UpdateAndSaveReminderLocked( { std::lock_guard lock(ReminderDataManager::MUTEX); reminder->InitReminderId(); - reminder->InitUserId(ReminderRequest::GetUserId(bundleOption->GetUid())); + int32_t userId = -1; + OsAccountManagerHelper::GetInstance().GetOsAccountLocalIdFromUid(bundleOption->GetUid(), userId); + reminder->InitUserId(userId); reminder->InitUid(bundleOption->GetUid()); reminder->InitBundleName(bundleOption->GetBundleName()); @@ -928,7 +931,8 @@ bool ReminderDataManager::ShouldAlert(const sptr &reminder) con ANSR_LOGD("The reminder (reminderId=%{public}d) is silent", reminderId); return false; } - int32_t userId = ReminderRequest::GetUserId(bundleOption->GetUid()); + int32_t userId = -1; + OsAccountManagerHelper::GetInstance().GetOsAccountLocalIdFromUid(bundleOption->GetUid(), userId); if (currentUserId_ != userId) { ANSR_LOGD("The reminder (reminderId=%{public}d) is silent for not in active user, " \ "current user id: %{private}d, reminder user id: %{private}d", reminderId, currentUserId_, userId); @@ -1580,7 +1584,7 @@ bool ReminderDataManager::CheckIsSameApp(const sptr &reminder, std::string bundleName = reminder->GetCreatorBundleName(); int32_t uid = reminder->GetCreatorUid(); if (uid == -1) { - uid = ReminderRequest::GetUid(reminder->GetUserId(), bundleName); + uid = BundleManagerHelper::GetInstance()->GetDefaultUidByBundleName(bundleName, reminder->GetUserId()); } return bundleName == other->GetBundleName() && uid == other->GetUid(); } @@ -1591,7 +1595,11 @@ bool ReminderDataManager::IsBelongToSameApp(const sptr int32_t uidSrc = bundleOption->GetUid(); int32_t uidTar = other->GetUid(); bool result = uidSrc == uidTar; - result = result && (ReminderRequest::GetUserId(uidSrc) == ReminderRequest::GetUserId(uidTar)); + int32_t userIdSrc = -1; + OsAccountManagerHelper::GetInstance().GetOsAccountLocalIdFromUid(uidSrc, userIdSrc); + int32_t userIdTar = -1; + OsAccountManagerHelper::GetInstance().GetOsAccountLocalIdFromUid(uidTar, userIdTar); + result = result && (userIdSrc == userIdTar); result = result && (bundleOption->GetBundleName() == other->GetBundleName()); return result; } @@ -1978,7 +1986,7 @@ void ReminderDataManager::ClickReminder(const OHOS::EventFwk::Want &want) abilityWant.SetElement(element); abilityWant.SetUri(wantInfo->uri); abilityWant.SetParams(wantInfo->parameters); - int32_t appIndex = ReminderRequest::GetAppIndex(reminder->GetUid()); + int32_t appIndex = BundleManagerHelper::GetInstance()->GetAppIndexByUid(reminder->GetUid()); abilityWant.SetParam("ohos.extra.param.key.appCloneIndex", appIndex); auto client = AppExecFwk::AbilityManagerClient::GetInstance(); diff --git a/services/ans/src/reminder_event_manager.cpp b/services/ans/src/reminder_event_manager.cpp index 6211e82d1..e282d02ee 100644 --- a/services/ans/src/reminder_event_manager.cpp +++ b/services/ans/src/reminder_event_manager.cpp @@ -20,6 +20,7 @@ #include "bundle_mgr_interface.h" #include "common_event_manager.h" #include "common_event_support.h" +#include "bundle_manager_helper.h" #include "if_system_ability_manager.h" #include "ipc_skeleton.h" #include "iservice_registry.h" @@ -228,7 +229,7 @@ sptr ReminderEventManager::ReminderEventSubscriber::Ge OHOS::AppExecFwk::ElementName ele = want.GetElement(); std::string bundleName = ele.GetBundleName(); int32_t userId = want.GetIntParam(OHOS::AppExecFwk::Constants::USER_ID, -1); - int32_t uid = ReminderRequest::GetUid(userId, bundleName); + int32_t uid = BundleManagerHelper::GetInstance()->GetDefaultUidByBundleName(bundleName, userId); ANSR_LOGD("bundleName=%{public}s, userId=%{private}d, uid=%{public}d", bundleName.c_str(), userId, uid); sptr bundleOption = new (std::nothrow) NotificationBundleOption(bundleName, uid); if (bundleOption == nullptr) { diff --git a/frameworks/ans/src/reminder_store.cpp b/services/ans/src/reminder_store.cpp similarity index 95% rename from frameworks/ans/src/reminder_store.cpp rename to services/ans/src/reminder_store.cpp index e75be5b9c..1ee399dc5 100644 --- a/frameworks/ans/src/reminder_store.cpp +++ b/services/ans/src/reminder_store.cpp @@ -27,6 +27,7 @@ #include "reminder_request_alarm.h" #include "reminder_request_timer.h" #include "reminder_request_calendar.h" +#include "reminder_store_strategy.h" namespace OHOS { namespace Notification { @@ -177,14 +178,17 @@ std::vector> ReminderStore::ReminderStoreDataCallBack::Get switch (reminderType) { case (static_cast(ReminderRequest::ReminderType::TIMER)): { reminderReq = new (std::nothrow) ReminderRequestTimer(reminderId); + ReminderTimerStrategy::RecoverFromOldVersion(reminderReq, queryResult); break; } case (static_cast(ReminderRequest::ReminderType::CALENDAR)): { reminderReq = new (std::nothrow) ReminderRequestCalendar(reminderId); + ReminderCalendarStrategy::RecoverFromOldVersion(reminderReq, queryResult); break; } case (static_cast(ReminderRequest::ReminderType::ALARM)): { reminderReq = new (std::nothrow) ReminderRequestAlarm(reminderId); + ReminderAlarmStrategy::RecoverFromOldVersion(reminderReq, queryResult); break; } default: { @@ -192,7 +196,6 @@ std::vector> ReminderStore::ReminderStoreDataCallBack::Get } } if (reminderReq != nullptr) { - reminderReq->RecoverFromOldVersion(queryResult); reminders.push_back(reminderReq); } queryResult->IsAtLastRow(isLastRow); @@ -211,7 +214,7 @@ void ReminderStore::ReminderStoreDataCallBack::InsertNewReminders(NativeRdb::Rdb } bundleOption->SetBundleName(reminder->GetBundleName()); NativeRdb::ValuesBucket baseValues; - ReminderRequest::AppendValuesBucket(reminder, bundleOption, baseValues, true); + ReminderStrategy::AppendValuesBucket(reminder, baseValues, true); store.BeginTransaction(); // insert reminder_base @@ -228,15 +231,15 @@ void ReminderStore::ReminderStoreDataCallBack::InsertNewReminders(NativeRdb::Rdb rowId = STATE_FAIL; switch (reminder->GetReminderType()) { case ReminderRequest::ReminderType::CALENDAR: - ReminderRequestCalendar::AppendValuesBucket(reminder, bundleOption, values); + ReminderCalendarStrategy::AppendValuesBucket(reminder, values); ret = store.Insert(rowId, ReminderCalendarTable::TABLE_NAME, values); break; case ReminderRequest::ReminderType::ALARM: - ReminderRequestAlarm::AppendValuesBucket(reminder, bundleOption, values); + ReminderAlarmStrategy::AppendValuesBucket(reminder, values); ret = store.Insert(rowId, ReminderAlarmTable::TABLE_NAME, values); break; case ReminderRequest::ReminderType::TIMER: - ReminderRequestTimer::AppendValuesBucket(reminder, bundleOption, values); + ReminderTimerStrategy::AppendValuesBucket(reminder, values); ret = store.Insert(rowId, ReminderTimerTable::TABLE_NAME, values); break; default: @@ -596,7 +599,7 @@ int32_t ReminderStore::Insert( } int64_t rowId = STATE_FAIL; NativeRdb::ValuesBucket baseValues; - ReminderRequest::AppendValuesBucket(reminder, bundleOption, baseValues); + ReminderStrategy::AppendValuesBucket(reminder, baseValues); rdbStore_->BeginTransaction(); // insert reminder_base @@ -613,17 +616,17 @@ int32_t ReminderStore::Insert( rowId = STATE_FAIL; switch (reminder->GetReminderType()) { case ReminderRequest::ReminderType::CALENDAR: { - ReminderRequestCalendar::AppendValuesBucket(reminder, bundleOption, values); + ReminderCalendarStrategy::AppendValuesBucket(reminder, values); ret = rdbStore_->Insert(rowId, ReminderCalendarTable::TABLE_NAME, values); break; } case ReminderRequest::ReminderType::ALARM: { - ReminderRequestAlarm::AppendValuesBucket(reminder, bundleOption, values); + ReminderAlarmStrategy::AppendValuesBucket(reminder, values); ret = rdbStore_->Insert(rowId, ReminderAlarmTable::TABLE_NAME, values); break; } case ReminderRequest::ReminderType::TIMER: { - ReminderRequestTimer::AppendValuesBucket(reminder, bundleOption, values); + ReminderTimerStrategy::AppendValuesBucket(reminder, values); ret = rdbStore_->Insert(rowId, ReminderTimerTable::TABLE_NAME, values); break; } @@ -653,7 +656,7 @@ int32_t ReminderStore::Update( } int32_t rowId = STATE_FAIL; NativeRdb::ValuesBucket baseValues; - ReminderRequest::AppendValuesBucket(reminder, bundleOption, baseValues); + ReminderStrategy::AppendValuesBucket(reminder, baseValues); std::string updateCondition = ReminderBaseTable::REMINDER_ID + " = " + std::to_string(reminder->GetReminderId()); @@ -674,15 +677,15 @@ int32_t ReminderStore::Update( rowId = STATE_FAIL; switch (reminder->GetReminderType()) { case ReminderRequest::ReminderType::CALENDAR: - ReminderRequestCalendar::AppendValuesBucket(reminder, bundleOption, values); + ReminderCalendarStrategy::AppendValuesBucket(reminder, values); ret = rdbStore_->Update(rowId, ReminderCalendarTable::TABLE_NAME, values, updateCondition, whereArgs); break; case ReminderRequest::ReminderType::ALARM: - ReminderRequestAlarm::AppendValuesBucket(reminder, bundleOption, values); + ReminderAlarmStrategy::AppendValuesBucket(reminder, values); ret = rdbStore_->Update(rowId, ReminderAlarmTable::TABLE_NAME, values, updateCondition, whereArgs); break; case ReminderRequest::ReminderType::TIMER: - ReminderRequestTimer::AppendValuesBucket(reminder, bundleOption, values); + ReminderTimerStrategy::AppendValuesBucket(reminder, values); ret = rdbStore_->Update(rowId, ReminderTimerTable::TABLE_NAME, values, updateCondition, whereArgs); break; default: @@ -753,16 +756,19 @@ sptr ReminderStore::BuildReminder(const std::shared_ptr(ReminderRequest::ReminderType::TIMER)): { reminder = new (std::nothrow) ReminderRequestTimer(reminderId); resultSet = Query(ReminderTimerTable::TABLE_NAME, ReminderTimerTable::SELECT_COLUMNS, reminderId); + ReminderTimerStrategy::RecoverFromDb(reminder, resultBase, resultSet); break; } case (static_cast(ReminderRequest::ReminderType::CALENDAR)): { reminder = new (std::nothrow) ReminderRequestCalendar(reminderId); resultSet = Query(ReminderCalendarTable::TABLE_NAME, ReminderCalendarTable::SELECT_COLUMNS, reminderId); + ReminderCalendarStrategy::RecoverFromDb(reminder, resultBase, resultSet); break; } case (static_cast(ReminderRequest::ReminderType::ALARM)): { reminder = new (std::nothrow) ReminderRequestAlarm(reminderId); resultSet = Query(ReminderAlarmTable::TABLE_NAME, ReminderAlarmTable::SELECT_COLUMNS, reminderId); + ReminderAlarmStrategy::RecoverFromDb(reminder, resultBase, resultSet); break; } default: { @@ -771,8 +777,6 @@ sptr ReminderStore::BuildReminder(const std::shared_ptrRecoverFromDbBase(resultBase); - reminder->RecoverFromDb(resultSet); ANSR_LOGI("BuildReminder success."); } else { ANSR_LOGW("BuildReminder fail."); diff --git a/services/ans/src/reminder_store_strategy.cpp b/services/ans/src/reminder_store_strategy.cpp new file mode 100644 index 000000000..814d85d3b --- /dev/null +++ b/services/ans/src/reminder_store_strategy.cpp @@ -0,0 +1,649 @@ +/* + * Copyright (c) 2024 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "reminder_store_strategy.h" + +#include "ans_log_wrapper.h" +#include "reminder_store.h" +#include "reminder_table.h" +#include "reminder_table_old.h" +#include "reminder_request_alarm.h" +#include "reminder_request_timer.h" +#include "reminder_request_calendar.h" + +namespace OHOS { +namespace Notification { +void ReminderStrategy::AppendValuesBucket(const sptr& reminder, + NativeRdb::ValuesBucket &values, const bool oldVersion) +{ + values.PutInt(ReminderBaseTable::REMINDER_ID, reminder->GetReminderId()); + values.PutString(ReminderBaseTable::PACKAGE_NAME, reminder->GetBundleName()); + values.PutInt(ReminderBaseTable::USER_ID, reminder->GetUserId()); + values.PutInt(ReminderBaseTable::UID, reminder->GetUid()); + values.PutString(ReminderBaseTable::SYSTEM_APP, reminder->IsSystemApp() ? "true" : "false"); + values.PutInt(ReminderBaseTable::REMINDER_TYPE, static_cast(reminder->GetReminderType())); + values.PutLong(ReminderBaseTable::REMINDER_TIME, reminder->GetReminderTimeInMilli()); + values.PutLong(ReminderBaseTable::TRIGGER_TIME, reminder->GetTriggerTimeInMilli()); + values.PutLong(ReminderBaseTable::TIME_INTERVAL, reminder->GetTimeInterval()); + values.PutInt(ReminderBaseTable::SNOOZE_TIMES, reminder->GetSnoozeTimes()); + values.PutInt(ReminderBaseTable::DYNAMIC_SNOOZE_TIMES, reminder->GetSnoozeTimesDynamic()); + values.PutLong(ReminderBaseTable::RING_DURATION, reminder->GetRingDuration()); + values.PutString(ReminderBaseTable::IS_EXPIRED, reminder->IsExpired() ? "true" : "false"); + values.PutInt(ReminderBaseTable::STATE, reminder->GetState()); + values.PutString(ReminderBaseTable::ACTION_BUTTON_INFO, reminder->SerializeButtonInfo()); + values.PutString(ReminderBaseTable::CUSTOM_BUTTON_URI, reminder->GetCustomButtonUri()); + values.PutInt(ReminderBaseTable::SLOT_ID, reminder->GetSlotType()); + values.PutInt(ReminderBaseTable::SNOOZE_SLOT_ID, reminder->GetSnoozeSlotType()); + values.PutInt(ReminderBaseTable::NOTIFICATION_ID, reminder->GetNotificationId()); + values.PutString(ReminderBaseTable::TITLE, reminder->GetTitle()); + values.PutString(ReminderBaseTable::CONTENT, reminder->GetContent()); + values.PutString(ReminderBaseTable::SNOOZE_CONTENT, reminder->GetSnoozeContent()); + values.PutString(ReminderBaseTable::EXPIRED_CONTENT, reminder->GetExpiredContent()); + + if (oldVersion) { + values.PutString(ReminderBaseTable::WANT_AGENT, reminder->GetWantAgentStr()); + values.PutString(ReminderBaseTable::MAX_SCREEN_WANT_AGENT, reminder->GetMaxWantAgentStr()); + } else { + std::string wantInfoStr; + std::string maxWantInfoStr; + reminder->SerializeWantAgent(wantInfoStr, maxWantInfoStr); + values.PutString(ReminderBaseTable::WANT_AGENT, wantInfoStr); + values.PutString(ReminderBaseTable::MAX_SCREEN_WANT_AGENT, maxWantInfoStr); + } + + values.PutString(ReminderBaseTable::TAP_DISMISSED, reminder->IsTapDismissed() ? "true" : "false"); + values.PutLong(ReminderBaseTable::AUTO_DELETED_TIME, reminder->GetAutoDeletedTime()); + values.PutString(ReminderBaseTable::GROUP_ID, reminder->GetGroupId()); + values.PutString(ReminderBaseTable::CUSTOM_RING_URI, reminder->GetCustomRingUri()); + values.PutString(ReminderBaseTable::CREATOR_BUNDLE_NAME, reminder->GetCreatorBundleName()); + values.PutInt(ReminderBaseTable::CREATOR_UID, reminder->GetCreatorUid()); +} + +void ReminderStrategy::RecoverTimeFromOldVersion(sptr& reminder, + const std::shared_ptr& resultSet) +{ + uint64_t reminderTime = 0; + ReminderStrategy::GetRdbValue(resultSet, ReminderTable::REMINDER_TIME, reminderTime); + reminder->SetReminderTimeInMilli(reminderTime); + + uint64_t triggerTime = 0; + ReminderStrategy::GetRdbValue(resultSet, ReminderTable::TRIGGER_TIME, triggerTime); + reminder->SetTriggerTimeInMilli(triggerTime); + + uint64_t timeInterval = 0; + ReminderStrategy::GetRdbValue(resultSet, ReminderTable::TIME_INTERVAL, timeInterval); + reminder->SetTimeInterval(timeInterval); + + uint8_t snoozeTimes = 0; + ReminderStrategy::GetRdbValue(resultSet, ReminderTable::SNOOZE_TIMES, snoozeTimes); + reminder->SetSnoozeTimes(snoozeTimes); + + uint8_t dynamicSnoozeTimes = 0; + ReminderStrategy::GetRdbValue(resultSet, ReminderTable::DYNAMIC_SNOOZE_TIMES, dynamicSnoozeTimes); + reminder->SetSnoozeTimesDynamic(dynamicSnoozeTimes); + + uint64_t ringDuration = 0; + ReminderStrategy::GetRdbValue(resultSet, ReminderTable::RING_DURATION, ringDuration); + reminder->SetRingDuration(ringDuration); + + int64_t autoDeletedTime = 0; + ReminderStrategy::GetRdbValue(resultSet, ReminderTable::AUTO_DELETED_TIME, autoDeletedTime); + reminder->SetAutoDeletedTime(autoDeletedTime); +} + +void ReminderStrategy::RecoverIdFromOldVersion(sptr& reminder, + const std::shared_ptr& resultSet) +{ + int32_t reminderId = 0; + ReminderStrategy::GetRdbValue(resultSet, ReminderTable::REMINDER_ID, reminderId); + reminder->SetReminderId(reminderId); + + int32_t userId = 0; + ReminderStrategy::GetRdbValue(resultSet, ReminderTable::USER_ID, userId); + reminder->InitUserId(userId); + + int32_t uid = 0; + ReminderStrategy::GetRdbValue(resultSet, ReminderTable::UID, uid); + reminder->InitUid(uid); + + int32_t reminderType = 0; + ReminderStrategy::GetRdbValue(resultSet, ReminderTable::REMINDER_TYPE, reminderType); + reminder->SetReminderType(ReminderRequest::ReminderType(reminderType)); + + int32_t slotType = 0; + ReminderStrategy::GetRdbValue(resultSet, ReminderTable::SLOT_ID, slotType); + reminder->SetSlotType(NotificationConstant::SlotType(slotType)); + + int32_t snoozeSlotType = 0; + ReminderStrategy::GetRdbValue(resultSet, ReminderTable::SNOOZE_SLOT_ID, snoozeSlotType); + reminder->SetSnoozeSlotType(NotificationConstant::SlotType(snoozeSlotType)); + + int32_t notificationId = 0; + ReminderStrategy::GetRdbValue(resultSet, ReminderTable::NOTIFICATION_ID, notificationId); + reminder->SetNotificationId(notificationId); + + std::string groupId; + ReminderStrategy::GetRdbValue(resultSet, ReminderTable::GROUP_ID, groupId); + reminder->SetGroupId(groupId); +} + +void ReminderStrategy::RecoverContextFromOldVersion(sptr& reminder, + const std::shared_ptr& resultSet) +{ + std::string bundleName; + ReminderStrategy::GetRdbValue(resultSet, ReminderTable::PKG_NAME, bundleName); + reminder->InitBundleName(bundleName); + + std::string title; + ReminderStrategy::GetRdbValue(resultSet, ReminderTable::TITLE, title); + reminder->SetTitle(title); + + std::string content; + ReminderStrategy::GetRdbValue(resultSet, ReminderTable::CONTENT, content); + reminder->SetContent(content); + + std::string snoozeContent; + ReminderStrategy::GetRdbValue(resultSet, ReminderTable::SNOOZE_CONTENT, snoozeContent); + reminder->SetSnoozeContent(snoozeContent); + + std::string expiredContent; + ReminderStrategy::GetRdbValue(resultSet, ReminderTable::EXPIRED_CONTENT, expiredContent); + reminder->SetExpiredContent(expiredContent); + + std::string customButtonUri; + ReminderStrategy::GetRdbValue(resultSet, ReminderTable::CUSTOM_BUTTON_URI, customButtonUri); + reminder->SetCustomButtonUri(customButtonUri); + + std::string customRingUri; + ReminderStrategy::GetRdbValue(resultSet, ReminderTable::CUSTOM_RING_URI, customRingUri); + reminder->SetCustomRingUri(customRingUri); + + std::string creatorBundleName; + ReminderStrategy::GetRdbValue(resultSet, ReminderTable::CREATOR_BUNDLE_NAME, creatorBundleName); + reminder->InitCreatorBundleName(creatorBundleName); +} + +void ReminderStrategy::RecoverFromOldVersion(sptr& reminder, + const std::shared_ptr& resultSet) +{ + if (reminder == nullptr || resultSet == nullptr) { + ANSR_LOGE("ResultSet is null or reminder is null"); + return; + } + + ReminderStrategy::RecoverTimeFromOldVersion(reminder, resultSet); + ReminderStrategy::RecoverIdFromOldVersion(reminder, resultSet); + ReminderStrategy::RecoverContextFromOldVersion(reminder, resultSet); + + std::string isSystemApp; + ReminderStrategy::GetRdbValue(resultSet, ReminderTable::SYS_APP, isSystemApp); + reminder->SetSystemApp(isSystemApp == "true" ? true : false); + + std::string isExpired; + ReminderStrategy::GetRdbValue(resultSet, ReminderTable::IS_EXPIRED, isExpired); + reminder->SetExpired(isExpired == "true" ? true : false); + + std::string actionButtons; + ReminderStrategy::GetRdbValue(resultSet, ReminderTable::ACTION_BUTTON_INFO, actionButtons); + reminder->DeserializeButtonInfo(actionButtons); + + uint8_t state = 0; + ReminderStrategy::GetRdbValue(resultSet, ReminderTable::STATE, state); + reminder->SetState(state); + + uint8_t repeatDaysOfWeek = 0; + ReminderStrategy::GetRdbValue(resultSet, ReminderTable::REPEAT_DAYS_OF_WEEK, repeatDaysOfWeek); + reminder->SetRepeatDaysOfWeek(repeatDaysOfWeek); + + std::string wantAgent; + ReminderStrategy::GetRdbValue(resultSet, ReminderTable::AGENT, wantAgent); + reminder->SetWantAgentStr(wantAgent); + + std::string maxScreenWantAgent; + ReminderStrategy::GetRdbValue(resultSet, ReminderTable::MAX_SCREEN_AGENT, maxScreenWantAgent); + reminder->SetMaxWantAgentStr(maxScreenWantAgent); + + std::string tapDismissed; + ReminderStrategy::GetRdbValue(resultSet, ReminderTable::TAP_DISMISSED, tapDismissed); + reminder->SetTapDismissed(tapDismissed == "true" ? true : false); +} + +void ReminderStrategy::RecoverTimeFromDb(sptr& reminder, + const std::shared_ptr& resultSet) +{ + uint64_t reminderTime = 0; + ReminderStrategy::GetRdbValue(resultSet, ReminderBaseTable::REMINDER_TIME, reminderTime); + reminder->SetReminderTimeInMilli(reminderTime); + + uint64_t triggerTime = 0; + ReminderStrategy::GetRdbValue(resultSet, ReminderBaseTable::TRIGGER_TIME, triggerTime); + reminder->SetTriggerTimeInMilli(triggerTime); + + uint64_t timeInterval = 0; + ReminderStrategy::GetRdbValue(resultSet, ReminderBaseTable::TIME_INTERVAL, timeInterval); + reminder->SetTimeInterval(timeInterval); + + uint8_t snoozeTimes = 0; + ReminderStrategy::GetRdbValue(resultSet, ReminderBaseTable::SNOOZE_TIMES, snoozeTimes); + reminder->SetSnoozeTimes(snoozeTimes); + + uint8_t dynamicSnoozeTimes = 0; + ReminderStrategy::GetRdbValue(resultSet, ReminderBaseTable::DYNAMIC_SNOOZE_TIMES, dynamicSnoozeTimes); + reminder->SetSnoozeTimesDynamic(dynamicSnoozeTimes); + + uint64_t ringDuration = 0; + ReminderStrategy::GetRdbValue(resultSet, ReminderBaseTable::RING_DURATION, ringDuration); + reminder->SetRingDuration(ringDuration); + + int64_t autoDeletedTime = 0; + ReminderStrategy::GetRdbValue(resultSet, ReminderBaseTable::AUTO_DELETED_TIME, autoDeletedTime); + reminder->SetAutoDeletedTime(autoDeletedTime); +} + +void ReminderStrategy::RecoverIdFromDb(sptr& reminder, + const std::shared_ptr& resultSet) +{ + int32_t reminderId = 0; + ReminderStrategy::GetRdbValue(resultSet, ReminderBaseTable::REMINDER_ID, reminderId); + reminder->SetReminderId(reminderId); + + int32_t userId = 0; + ReminderStrategy::GetRdbValue(resultSet, ReminderBaseTable::USER_ID, userId); + reminder->InitUserId(userId); + + int32_t uid = 0; + ReminderStrategy::GetRdbValue(resultSet, ReminderBaseTable::UID, uid); + reminder->InitUid(uid); + + int32_t reminderType = 0; + ReminderStrategy::GetRdbValue(resultSet, ReminderBaseTable::REMINDER_TYPE, reminderType); + reminder->SetReminderType(ReminderRequest::ReminderType(reminderType)); + + int32_t slotType = 0; + ReminderStrategy::GetRdbValue(resultSet, ReminderBaseTable::SLOT_ID, slotType); + reminder->SetSlotType(NotificationConstant::SlotType(slotType)); + + int32_t snoozeSlotType = 0; + ReminderStrategy::GetRdbValue(resultSet, ReminderBaseTable::SNOOZE_SLOT_ID, snoozeSlotType); + reminder->SetSnoozeSlotType(NotificationConstant::SlotType(snoozeSlotType)); + + int32_t notificationId = 0; + ReminderStrategy::GetRdbValue(resultSet, ReminderBaseTable::NOTIFICATION_ID, notificationId); + reminder->SetNotificationId(notificationId); + + std::string groupId; + ReminderStrategy::GetRdbValue(resultSet, ReminderBaseTable::GROUP_ID, groupId); + reminder->SetGroupId(groupId); + + int32_t creatorUid; + ReminderStrategy::GetRdbValue(resultSet, ReminderBaseTable::CREATOR_UID, creatorUid); + reminder->InitCreatorUid(creatorUid); +} + +void ReminderStrategy::RecoverContextFromDb(sptr& reminder, + const std::shared_ptr& resultSet) +{ + std::string bundleName; + ReminderStrategy::GetRdbValue(resultSet, ReminderBaseTable::PACKAGE_NAME, bundleName); + reminder->InitBundleName(bundleName); + + std::string customButtonUri; + ReminderStrategy::GetRdbValue(resultSet, ReminderBaseTable::CUSTOM_BUTTON_URI, customButtonUri); + reminder->SetCustomButtonUri(customButtonUri); + + std::string title; + ReminderStrategy::GetRdbValue(resultSet, ReminderBaseTable::TITLE, title); + reminder->SetTitle(title); + + std::string content; + ReminderStrategy::GetRdbValue(resultSet, ReminderBaseTable::CONTENT, content); + reminder->SetContent(content); + + std::string snoozeContent; + ReminderStrategy::GetRdbValue(resultSet, ReminderBaseTable::SNOOZE_CONTENT, snoozeContent); + reminder->SetSnoozeContent(snoozeContent); + + std::string expiredContent; + ReminderStrategy::GetRdbValue(resultSet, ReminderBaseTable::EXPIRED_CONTENT, expiredContent); + reminder->SetExpiredContent(expiredContent); + + std::string customRingUri; + ReminderStrategy::GetRdbValue(resultSet, ReminderBaseTable::CUSTOM_RING_URI, customRingUri); + reminder->SetCustomRingUri(customRingUri); + + std::string creatorBundleName; + ReminderStrategy::GetRdbValue(resultSet, ReminderBaseTable::CREATOR_BUNDLE_NAME, creatorBundleName); + reminder->InitCreatorBundleName(creatorBundleName); +} + +void ReminderStrategy::RecoverFromDb(sptr& reminder, + const std::shared_ptr& resultSet) +{ + if (reminder == nullptr || resultSet == nullptr) { + ANSR_LOGE("ResultSet is null or reminder is null"); + return; + } + ReminderStrategy::RecoverTimeFromDb(reminder, resultSet); + ReminderStrategy::RecoverIdFromDb(reminder, resultSet); + ReminderStrategy::RecoverContextFromDb(reminder, resultSet); + + uint8_t state = 0; + ReminderStrategy::GetRdbValue(resultSet, ReminderBaseTable::STATE, state); + reminder->SetState(state); + + std::string isSystemApp; + ReminderStrategy::GetRdbValue(resultSet, ReminderBaseTable::SYSTEM_APP, isSystemApp); + reminder->SetSystemApp(isSystemApp == "true" ? true : false); + + std::string isExpired; + ReminderStrategy::GetRdbValue(resultSet, ReminderBaseTable::IS_EXPIRED, isExpired); + reminder->SetExpired(isExpired == "true" ? true : false); + + std::string actionButtons; + ReminderStrategy::GetRdbValue(resultSet, ReminderBaseTable::ACTION_BUTTON_INFO, actionButtons); + reminder->DeserializeButtonInfo(actionButtons); + + reminder->InitNotificationRequest(); // must set before wantAgent & maxScreenWantAgent + std::string wantAgent; + ReminderStrategy::GetRdbValue(resultSet, ReminderBaseTable::WANT_AGENT, wantAgent); + reminder->DeserializeWantAgent(wantAgent, 0); + + std::string maxWantAgent; + ReminderStrategy::GetRdbValue(resultSet, ReminderBaseTable::MAX_SCREEN_WANT_AGENT, maxWantAgent); + reminder->DeserializeWantAgent(maxWantAgent, 1); + + std::string tapDismissed; + ReminderStrategy::GetRdbValue(resultSet, ReminderBaseTable::TAP_DISMISSED, tapDismissed); + reminder->SetTapDismissed(tapDismissed == "true" ? true : false); +} + +void ReminderTimerStrategy::AppendValuesBucket(const sptr& reminder, + NativeRdb::ValuesBucket& values) +{ + uint64_t seconds = 0; + if (reminder->GetReminderType() == ReminderRequest::ReminderType::TIMER) { + ReminderRequestTimer* timer = static_cast(reminder.GetRefPtr()); + seconds = timer->GetInitInfo(); + } + values.PutInt(ReminderTimerTable::REMINDER_ID, reminder->GetReminderId()); + values.PutLong(ReminderTimerTable::TRIGGER_SECOND, seconds); + values.PutLong(ReminderTimerTable::START_DATE_TIME, 0); + values.PutLong(ReminderTimerTable::END_DATE_TIME, 0); +} + +void ReminderTimerStrategy::RecoverFromOldVersion(sptr& reminder, + const std::shared_ptr& resultSet) +{ + if (resultSet == nullptr || reminder == nullptr) { + ANSR_LOGE("ResultSet is null or reminder is null"); + return; + } + ReminderStrategy::RecoverFromOldVersion(reminder, resultSet); +} + +void ReminderTimerStrategy::RecoverFromDb(sptr& reminder, + const std::shared_ptr& baseResult, const std::shared_ptr& resultSet) +{ + if (resultSet == nullptr || reminder == nullptr || baseResult == nullptr) { + ANSR_LOGE("ResultSet is null or reminder is null"); + return; + } + ReminderStrategy::RecoverFromDb(reminder, baseResult); + if (reminder->GetReminderType() == ReminderRequest::ReminderType::TIMER) { + ReminderRequestTimer* timer = static_cast(reminder.GetRefPtr()); + uint64_t seconds; + ReminderStrategy::GetRdbValue(resultSet, ReminderTimerTable::TRIGGER_SECOND, seconds); + timer->SetInitInfo(seconds); + } +} + +void ReminderAlarmStrategy::AppendValuesBucket(const sptr& reminder, + NativeRdb::ValuesBucket& values) +{ + uint8_t hour = 0; + uint8_t minute = 0; + uint8_t repeatDaysOfWeek = 0; + if (reminder->GetReminderType() == ReminderRequest::ReminderType::ALARM) { + ReminderRequestAlarm* alarm = static_cast(reminder.GetRefPtr()); + hour = alarm->GetHour(); + minute = alarm->GetMinute(); + repeatDaysOfWeek = alarm->GetRepeatDaysOfWeek(); + } + values.PutInt(ReminderAlarmTable::REMINDER_ID, reminder->GetReminderId()); + values.PutInt(ReminderAlarmTable::ALARM_HOUR, hour); + values.PutInt(ReminderAlarmTable::ALARM_MINUTE, minute); + values.PutInt(ReminderAlarmTable::REPEAT_DAYS_OF_WEEK, repeatDaysOfWeek); +} + +void ReminderAlarmStrategy::RecoverFromOldVersion(sptr& reminder, + const std::shared_ptr& resultSet) +{ + if (resultSet == nullptr || reminder == nullptr) { + ANSR_LOGE("ResultSet is null or reminder is null"); + return; + } + ReminderStrategy::RecoverFromOldVersion(reminder, resultSet); + + if (reminder->GetReminderType() == ReminderRequest::ReminderType::ALARM) { + ReminderRequestAlarm* alarm = static_cast(reminder.GetRefPtr()); + uint8_t hour = 0; + ReminderStrategy::GetRdbValue(resultSet, ReminderTable::ALARM_HOUR, hour); + alarm->SetHour(hour); + + uint8_t minute = 0; + ReminderStrategy::GetRdbValue(resultSet, ReminderTable::ALARM_MINUTE, minute); + alarm->SetMinute(minute); + } +} + +void ReminderAlarmStrategy::RecoverFromDb(sptr& reminder, + const std::shared_ptr& baseResult, const std::shared_ptr& resultSet) +{ + if (resultSet == nullptr || reminder == nullptr || baseResult == nullptr) { + ANSR_LOGE("ResultSet is null or reminder is null"); + return; + } + ReminderStrategy::RecoverFromDb(reminder, baseResult); + if (reminder->GetReminderType() == ReminderRequest::ReminderType::ALARM) { + ReminderRequestAlarm* alarm = static_cast(reminder.GetRefPtr()); + uint8_t hour = 0; + ReminderStrategy::GetRdbValue(resultSet, ReminderAlarmTable::ALARM_HOUR, hour); + alarm->SetHour(hour); + + uint8_t minute = 0; + ReminderStrategy::GetRdbValue(resultSet, ReminderAlarmTable::ALARM_MINUTE, minute); + alarm->SetMinute(minute); + + uint8_t repeatDaysOfWeek = 0; + ReminderStrategy::GetRdbValue(resultSet, ReminderAlarmTable::REPEAT_DAYS_OF_WEEK, repeatDaysOfWeek); + alarm->SetRepeatDaysOfWeek(repeatDaysOfWeek); + } +} + +void ReminderCalendarStrategy::AppendValuesBucket(const sptr& reminder, + NativeRdb::ValuesBucket& values) +{ + uint16_t firstDesignateYear = 0; + uint8_t firstDesignateMonth = 0; + uint8_t firstDesignateDay = 0; + uint64_t dateTime = 0; + uint32_t repeatDay = 0; + uint16_t repeatMonth = 0; + uint8_t repeatDaysOfWeek = 0; + uint64_t endDateTime = 0; + uint64_t lastStartDateTime = 0; + std::string rruleWantAgent; + std::string excludeDates; + if (reminder->GetReminderType() == ReminderRequest::ReminderType::CALENDAR) { + ReminderRequestCalendar* calendar = static_cast(reminder.GetRefPtr()); + if (calendar != nullptr) { + repeatDay = calendar->GetRepeatDay(); + repeatMonth = calendar->GetRepeatMonth(); + firstDesignateYear = calendar->GetFirstDesignateYear(); + firstDesignateMonth = calendar->GetFirstDesignageMonth(); + firstDesignateDay = calendar->GetFirstDesignateDay(); + dateTime = calendar->GetDateTime(); + repeatDaysOfWeek = calendar->GetRepeatDaysOfWeek(); + endDateTime = calendar->GetEndDateTime(); + lastStartDateTime = calendar->GetLastStartDateTime(); + rruleWantAgent = calendar->SerializationRRule(); + excludeDates = calendar->SerializationExcludeDates(); + } + } + values.PutInt(ReminderCalendarTable::REMINDER_ID, reminder->GetReminderId()); + values.PutInt(ReminderCalendarTable::FIRST_DESIGNATE_YEAR, firstDesignateYear); + values.PutInt(ReminderCalendarTable::FIRST_DESIGNATE_MONTH, firstDesignateMonth); + values.PutInt(ReminderCalendarTable::FIRST_DESIGNATE_DAY, firstDesignateDay); + values.PutLong(ReminderCalendarTable::CALENDAR_DATE_TIME, dateTime); + values.PutLong(ReminderCalendarTable::CALENDAR_END_DATE_TIME, endDateTime); + values.PutLong(ReminderCalendarTable::CALENDAR_LAST_DATE_TIME, lastStartDateTime); + values.PutInt(ReminderCalendarTable::REPEAT_DAYS, repeatDay); + values.PutInt(ReminderCalendarTable::REPEAT_MONTHS, repeatMonth); + values.PutInt(ReminderCalendarTable::REPEAT_DAYS_OF_WEEK, repeatDaysOfWeek); + values.PutString(ReminderCalendarTable::RRULE_WANT_AGENT, rruleWantAgent); + values.PutString(ReminderCalendarTable::EXCLUDE_DATES, excludeDates); +} + +void ReminderCalendarStrategy::RecoverFromOldVersion(sptr& reminder, + const std::shared_ptr& resultSet) +{ + if (resultSet == nullptr || reminder == nullptr) { + ANSR_LOGE("ResultSet is null or reminder is null"); + return; + } + ReminderStrategy::RecoverFromOldVersion(reminder, resultSet); + if (reminder->GetReminderType() == ReminderRequest::ReminderType::CALENDAR) { + ReminderRequestCalendar* calendar = static_cast(reminder.GetRefPtr()); + uint32_t repeatDay = 0; + ReminderStrategy::GetRdbValue(resultSet, ReminderTable::REPEAT_DAYS, repeatDay); + calendar->SetRepeatDay(repeatDay); + + uint16_t repeatMonth = 0; + ReminderStrategy::GetRdbValue(resultSet, ReminderTable::REPEAT_MONTHS, repeatMonth); + calendar->SetRepeatMonth(repeatMonth); + + uint16_t firstDesignateYear = 0; + ReminderStrategy::GetRdbValue(resultSet, ReminderTable::FIRST_DESIGNATE_YEAR, firstDesignateYear); + calendar->SetFirstDesignateYear(firstDesignateYear); + + uint8_t firstDesignateMonth = 0; + ReminderStrategy::GetRdbValue(resultSet, ReminderTable::FIRST_DESIGNATE_MONTH, firstDesignateMonth); + calendar->SetFirstDesignageMonth(firstDesignateMonth); + + uint8_t firstDesignateDay = 0; + ReminderStrategy::GetRdbValue(resultSet, ReminderTable::FIRST_DESIGNATE_DAY, firstDesignateDay); + calendar->SetFirstDesignateDay(firstDesignateDay); + + uint16_t year = 0; + ReminderStrategy::GetRdbValue(resultSet, ReminderTable::CALENDAR_YEAR, year); + calendar->SetYear(year); + + uint8_t month = 0; + ReminderStrategy::GetRdbValue(resultSet, ReminderTable::CALENDAR_MONTH, month); + calendar->SetMonth(month); + + uint8_t day = 0; + ReminderStrategy::GetRdbValue(resultSet, ReminderTable::CALENDAR_DAY, day); + calendar->SetDay(day); + + uint8_t hour = 0; + ReminderStrategy::GetRdbValue(resultSet, ReminderTable::CALENDAR_HOUR, hour); + calendar->SetHour(hour); + + uint8_t minute = 0; + ReminderStrategy::GetRdbValue(resultSet, ReminderTable::CALENDAR_MINUTE, minute); + calendar->SetMinute(minute); + } +} + +void ReminderCalendarStrategy::RecoverTime(sptr& reminder, + const std::shared_ptr& resultSet) +{ + if (reminder->GetReminderType() == ReminderRequest::ReminderType::CALENDAR) { + ReminderRequestCalendar* calendar = static_cast(reminder.GetRefPtr()); + + uint16_t firstDesignateYear = 0; + ReminderStrategy::GetRdbValue(resultSet, ReminderCalendarTable::FIRST_DESIGNATE_YEAR, + firstDesignateYear); + calendar->SetFirstDesignateYear(firstDesignateYear); + + uint8_t firstDesignateMonth = 0; + ReminderStrategy::GetRdbValue(resultSet, ReminderCalendarTable::FIRST_DESIGNATE_MONTH, + firstDesignateMonth); + calendar->SetFirstDesignageMonth(firstDesignateMonth); + + uint8_t firstDesignateDay = 0; + ReminderStrategy::GetRdbValue(resultSet, ReminderCalendarTable::FIRST_DESIGNATE_DAY, + firstDesignateDay); + calendar->SetFirstDesignateDay(firstDesignateDay); + + uint64_t dateTime = 0; + ReminderStrategy::GetRdbValue(resultSet, ReminderCalendarTable::CALENDAR_DATE_TIME, dateTime); + calendar->SetDateTime(dateTime); + + uint64_t endDateTime = 0; + ReminderStrategy::GetRdbValue(resultSet, ReminderCalendarTable::CALENDAR_END_DATE_TIME, endDateTime); + if (endDateTime != 0 && endDateTime >= dateTime) { + calendar->SetEndDateTime(endDateTime); + } else { + calendar->SetEndDateTime(dateTime); + } + + uint64_t lastStartDateTime = 0; + ReminderStrategy::GetRdbValue(resultSet, ReminderCalendarTable::CALENDAR_LAST_DATE_TIME, + lastStartDateTime); + if (lastStartDateTime == 0) { + calendar->SetLastStartDateTime(dateTime); + } else { + calendar->SetLastStartDateTime(lastStartDateTime); + } + } +} + +void ReminderCalendarStrategy::RecoverFromDb(sptr& reminder, + const std::shared_ptr& baseResult, const std::shared_ptr& resultSet) +{ + if (resultSet == nullptr || reminder == nullptr || baseResult == nullptr) { + ANSR_LOGE("ResultSet is null or reminder is null"); + return; + } + ReminderStrategy::RecoverFromDb(reminder, baseResult); + ReminderCalendarStrategy::RecoverTime(reminder, resultSet); + if (reminder->GetReminderType() == ReminderRequest::ReminderType::CALENDAR) { + ReminderRequestCalendar* calendar = static_cast(reminder.GetRefPtr()); + + uint32_t repeatDay = 0; + ReminderStrategy::GetRdbValue(resultSet, ReminderCalendarTable::REPEAT_DAYS, repeatDay); + calendar->SetRepeatDay(repeatDay); + + uint16_t repeatMonth = 0; + ReminderStrategy::GetRdbValue(resultSet, ReminderCalendarTable::REPEAT_MONTHS, repeatMonth); + calendar->SetRepeatMonth(repeatMonth); + + uint8_t repeatDaysOfWeek = 0; + ReminderStrategy::GetRdbValue(resultSet, ReminderCalendarTable::REPEAT_DAYS_OF_WEEK, repeatDaysOfWeek); + calendar->SetRepeatDaysOfWeek(repeatDaysOfWeek); + + std::string rruleWantAgent; + ReminderStrategy::GetRdbValue(resultSet, ReminderCalendarTable::RRULE_WANT_AGENT, rruleWantAgent); + calendar->DeserializationRRule(rruleWantAgent); + + std::string excludeDates; + ReminderStrategy::GetRdbValue(resultSet, ReminderCalendarTable::EXCLUDE_DATES, excludeDates); + calendar->DeserializationExcludeDates(excludeDates); + } +} +} +} \ No newline at end of file diff --git a/frameworks/ans/src/reminder_table.cpp b/services/ans/src/reminder_table.cpp similarity index 100% rename from frameworks/ans/src/reminder_table.cpp rename to services/ans/src/reminder_table.cpp diff --git a/frameworks/ans/src/reminder_table_old.cpp b/services/ans/src/reminder_table_old.cpp similarity index 100% rename from frameworks/ans/src/reminder_table_old.cpp rename to services/ans/src/reminder_table_old.cpp diff --git a/test/fuzztest/reminderrequest_fuzzer/reminderrequest_fuzzer.cpp b/test/fuzztest/reminderrequest_fuzzer/reminderrequest_fuzzer.cpp index 1b5cd73e9..8cc3dfb7a 100644 --- a/test/fuzztest/reminderrequest_fuzzer/reminderrequest_fuzzer.cpp +++ b/test/fuzztest/reminderrequest_fuzzer/reminderrequest_fuzzer.cpp @@ -24,7 +24,6 @@ namespace OHOS { namespace { constexpr uint8_t ENABLE = 2; constexpr uint8_t ACTION_BUTTON_TYPE = 3; - constexpr uint8_t COLUMN_TYPE = 2; constexpr uint8_t SLOT_TYPE_NUM = 5; } bool DoSomethingInterestingWithMyAPI(const char* data, size_t size) @@ -65,16 +64,7 @@ namespace OHOS { reminderRequest.OnStop(); reminderRequest.OnTerminate(); reminderRequest.OnTimeZoneChange(); - std::shared_ptr resultSet = - std::make_shared(); - uint8_t column = *data % COLUMN_TYPE; - Notification::ReminderRequest::DbRecoveryType columnType = - Notification::ReminderRequest::DbRecoveryType(column); - reminderRequest.RecoverInt64FromDb(resultSet, stringData, columnType); - reminderRequest.RecoverFromDb(resultSet); - reminderRequest.RecoverActionButton(resultSet); reminderRequest.StringSplit(stringData, stringData); - reminderRequest.RecoverWantAgent(stringData, *data); std::shared_ptr< Notification::ReminderRequest::MaxScreenAgentInfo> maxScreenWantAgentInfo = std::make_shared< Notification::ReminderRequest::MaxScreenAgentInfo>(); reminderRequest.SetMaxScreenWantAgentInfo(maxScreenWantAgentInfo); diff --git a/test/fuzztest/reminderrequestalarm_fuzzer/reminderrequestalarm_fuzzer.cpp b/test/fuzztest/reminderrequestalarm_fuzzer/reminderrequestalarm_fuzzer.cpp index ab204c921..0f5017f92 100644 --- a/test/fuzztest/reminderrequestalarm_fuzzer/reminderrequestalarm_fuzzer.cpp +++ b/test/fuzztest/reminderrequestalarm_fuzzer/reminderrequestalarm_fuzzer.cpp @@ -69,10 +69,6 @@ namespace OHOS { Parcel parcel; rrc->Unmarshalling(parcel); rrc->ReadFromParcel(parcel); - // test RecoverFromDb function - std::shared_ptr resultSet = - std::make_shared(); - rrc->RecoverFromDb(resultSet); return rrc->Marshalling(parcel); } } diff --git a/test/fuzztest/reminderrequestannexthree_fuzzer/reminderrequestannexthree_fuzzer.cpp b/test/fuzztest/reminderrequestannexthree_fuzzer/reminderrequestannexthree_fuzzer.cpp index 707db3d97..138a456e3 100644 --- a/test/fuzztest/reminderrequestannexthree_fuzzer/reminderrequestannexthree_fuzzer.cpp +++ b/test/fuzztest/reminderrequestannexthree_fuzzer/reminderrequestannexthree_fuzzer.cpp @@ -32,8 +32,6 @@ namespace OHOS { int32_t cTime = static_cast(GetU32Data(data)); reminderRequest.GetActualTime(type, cTime); reminderRequest.GetCTime(type, cTime); - int32_t uid = static_cast(GetU32Data(data)); - reminderRequest.GetUserId(uid); return reminderRequest.IsAlerting(); } } diff --git a/test/fuzztest/reminderrequestcalendar_fuzzer/reminderrequestcalendar_fuzzer.cpp b/test/fuzztest/reminderrequestcalendar_fuzzer/reminderrequestcalendar_fuzzer.cpp index 6c4247044..2d5ab8ba6 100644 --- a/test/fuzztest/reminderrequestcalendar_fuzzer/reminderrequestcalendar_fuzzer.cpp +++ b/test/fuzztest/reminderrequestcalendar_fuzzer/reminderrequestcalendar_fuzzer.cpp @@ -95,10 +95,6 @@ namespace OHOS { reminderRequestCalendar.UpdateNextReminder(); // test PreGetNextTriggerTimeIgnoreSnooze function reminderRequestCalendar.PreGetNextTriggerTimeIgnoreSnooze(enabled, enabled); - // test RecoverFromDb function - std::shared_ptr resultSet = - std::make_shared(); - reminderRequestCalendar.RecoverFromDb(resultSet); // test Unmarshalling function Parcel parcel; reminderRequestCalendar.Unmarshalling(parcel); diff --git a/test/fuzztest/reminderrequestcontinuate_fuzzer/reminderrequestcontinuate_fuzzer.cpp b/test/fuzztest/reminderrequestcontinuate_fuzzer/reminderrequestcontinuate_fuzzer.cpp index ef2550eac..bb6d560d0 100644 --- a/test/fuzztest/reminderrequestcontinuate_fuzzer/reminderrequestcontinuate_fuzzer.cpp +++ b/test/fuzztest/reminderrequestcontinuate_fuzzer/reminderrequestcontinuate_fuzzer.cpp @@ -26,8 +26,8 @@ namespace OHOS { std::string stringData(data); int32_t reminderId = static_cast(GetU32Data(data)); Notification::ReminderRequest reminderRequest(reminderId); - reminderRequest.GetButtonInfo(); - return reminderRequest.GetUid(reminderId, stringData); + reminderRequest.SerializeButtonInfo(); + return true; } } diff --git a/test/fuzztest/reminderstore_fuzzer/BUILD.gn b/test/fuzztest/reminderstore_fuzzer/BUILD.gn index 5120dff67..28132be53 100644 --- a/test/fuzztest/reminderstore_fuzzer/BUILD.gn +++ b/test/fuzztest/reminderstore_fuzzer/BUILD.gn @@ -21,7 +21,10 @@ ohos_fuzztest("ReminderStoreFuzzTest") { module_out_path = service_fuzz_test_path fuzz_config_file = "${component_path}/test/fuzztest/reminderstore_fuzzer" - include_dirs = [ "${component_path}/test/fuzztest/fuzz_common_base" ] + include_dirs = [ + "${component_path}/test/fuzztest/fuzz_common_base", + "${component_path}/services/ans/include", + ] cflags = [ "-g", "-O0", @@ -33,6 +36,7 @@ ohos_fuzztest("ReminderStoreFuzzTest") { deps = [ "${component_path}/test/fuzztest/fuzz_common_base:fuzz_common_base", "${frameworks_module_ans_path}:ans_innerkits", + "${services_path}/ans:libans", ] external_deps = [ diff --git a/test/fuzztest/reminderstoreannex_fuzzer/BUILD.gn b/test/fuzztest/reminderstoreannex_fuzzer/BUILD.gn index 5e5d5c6b2..74b52ec22 100644 --- a/test/fuzztest/reminderstoreannex_fuzzer/BUILD.gn +++ b/test/fuzztest/reminderstoreannex_fuzzer/BUILD.gn @@ -21,7 +21,10 @@ ohos_fuzztest("ReminderStoreAnnexFuzzTest") { module_out_path = service_fuzz_test_path fuzz_config_file = "${component_path}/test/fuzztest/reminderstoreannex_fuzzer" - include_dirs = [ "${component_path}/test/fuzztest/fuzz_common_base" ] + include_dirs = [ + "${component_path}/test/fuzztest/fuzz_common_base", + "${component_path}/services/ans/include", + ] cflags = [ "-g", "-O0", @@ -33,6 +36,7 @@ ohos_fuzztest("ReminderStoreAnnexFuzzTest") { deps = [ "${component_path}/test/fuzztest/fuzz_common_base:fuzz_common_base", "${frameworks_module_ans_path}:ans_innerkits", + "${services_path}/ans:libans", ] external_deps = [ diff --git a/test/fuzztest/reminderstoreannex_fuzzer/reminderstoreannex_fuzzer.cpp b/test/fuzztest/reminderstoreannex_fuzzer/reminderstoreannex_fuzzer.cpp index a9c43538e..9d691c582 100644 --- a/test/fuzztest/reminderstoreannex_fuzzer/reminderstoreannex_fuzzer.cpp +++ b/test/fuzztest/reminderstoreannex_fuzzer/reminderstoreannex_fuzzer.cpp @@ -38,8 +38,6 @@ namespace OHOS { reminderStore.GetInt32Val(resultSet, name, value); std::string value1(data); reminderStore.GetStringVal(resultSet, name, value1); - // test BuildReminder function - reminderStore.BuildReminder(resultSet); return true; } } -- Gitee From 6cf60a551735587139afd38209250fb61b1cb774 Mon Sep 17 00:00:00 2001 From: gaojiaqi Date: Sat, 12 Oct 2024 14:06:57 +0800 Subject: [PATCH 075/167] update Signed-off-by: gaojiaqi --- hisysevent.yaml | 1 - services/ans/src/reminder_data_manager.cpp | 56 ++++++++++--------- .../ans/src/reminder_data_manager_inner.cpp | 2 +- .../unittest/reminder_data_manager_test.cpp | 2 +- .../reminderdatamanager_fuzzer.cpp | 12 ++++ 5 files changed, 43 insertions(+), 30 deletions(-) diff --git a/hisysevent.yaml b/hisysevent.yaml index 17b330376..7ececce79 100644 --- a/hisysevent.yaml +++ b/hisysevent.yaml @@ -103,7 +103,6 @@ REMOVE: ALARM_TRIGGER: __BASE: {type: STATISTIC, level: MINOR, tag: PowerStats, desc: alarm trigger} - PID: {type: INT32, desc: thread pid} UID: {type: INT32, desc: package uid} NAME: {type: STRING, desc: call package name} TYPE: {type: INT32, desc: reminder type} diff --git a/services/ans/src/reminder_data_manager.cpp b/services/ans/src/reminder_data_manager.cpp index 98e1ce896..c0b8dd063 100644 --- a/services/ans/src/reminder_data_manager.cpp +++ b/services/ans/src/reminder_data_manager.cpp @@ -403,8 +403,8 @@ void ReminderDataManager::OnProcessDiedLocked(const sptrGetBundleName(); int32_t uid = bundleOption->GetUid(); ANSR_LOGD("OnProcessDiedLocked, bundleName=%{public}s, uid=%{public}d", bundleName.c_str(), uid); - std::lock_guard lock(ReminderDataManager::SHOW_MUTEX); std::lock_guard locker(ReminderDataManager::MUTEX); + std::lock_guard lock(ReminderDataManager::SHOW_MUTEX); for (auto it = showedReminderVector_.begin(); it != showedReminderVector_.end(); ++it) { int32_t reminderId = (*it)->GetReminderId(); auto mit = notificationBundleOptionMap_.find(reminderId); @@ -1082,6 +1082,10 @@ bool ReminderDataManager::StartExtensionAbility(const sptr &rem void ReminderDataManager::AsyncStartExtensionAbility(const sptr &reminder, int32_t times) { + if (!reminder->IsSystemApp()) { + ANSR_LOGI("Start extension ability failed, is not system app"); + return; + } times--; bool ret = ReminderDataManager::StartExtensionAbility(reminder); if (!ret && times > 0 && serviceQueue_ != nullptr) { @@ -1942,6 +1946,10 @@ void ReminderDataManager::HandleCustomButtonClick(const OHOS::EventFwk::Want &wa ANSR_LOGE("Invalid reminder id: %{public}d", reminderId); return; } + if (!reminder->IsSystemApp()) { + ANSR_LOGI("Custom button click, is not system app"); + return; + } CloseReminder(reminder, false); UpdateAppDatabase(reminder, ReminderRequest::ActionButtonType::CUSTOM); std::string buttonPkgName = want.GetStringParam("PkgName"); @@ -2063,6 +2071,9 @@ void ReminderDataManager::OnLanguageChanged() { std::lock_guard lock(ReminderDataManager::MUTEX); for (auto it = reminderVector_.begin(); it != reminderVector_.end(); ++it) { + if ((*it)->IsExpired() || (*it)->GetTriggerTimeInMilli() == 0) { + continue; + } UpdateReminderLanguage(*it); } } @@ -2117,41 +2128,32 @@ void ReminderDataManager::CheckNeedNotifyStatus(const sptr &rem if (bundleName.empty()) { return; } - ANS_LOGI("notify bundleName is: %{public}s", bundleName.c_str()); - // get foreground application - std::vector apps; + bool isRunning = false; { std::lock_guard lock(appMgrMutex_); if (!ConnectAppMgr()) { return; } - if (appMgrProxy_->GetForegroundApplications(apps) != ERR_OK) { - ANS_LOGW("get foreground application failed"); - return; - } + isRunning = appMgrProxy_->GetAppRunningStateByBundleName(bundleName); + } + if (!isRunning) { + return; } - // notify application - for (auto &eachApp : apps) { - if (eachApp.bundleName != bundleName) { - continue; - } - EventFwk::Want want; - // common event not add COMMON_EVENT_REMINDER_STATUS_CHANGE, Temporary use of string - want.SetAction("usual.event.REMINDER_STATUS_CHANGE"); - EventFwk::CommonEventData eventData(want); + EventFwk::Want want; + // common event not add COMMON_EVENT_REMINDER_STATUS_CHANGE, Temporary use of string + want.SetAction("usual.event.REMINDER_STATUS_CHANGE"); + EventFwk::CommonEventData eventData(want); - std::string data; - data.append(std::to_string(static_cast(buttonType))).append(","); - data.append(std::to_string(reminder->GetReminderId())); - eventData.SetData(data); + std::string data; + data.append(std::to_string(static_cast(buttonType))).append(","); + data.append(std::to_string(reminder->GetReminderId())); + eventData.SetData(data); - EventFwk::CommonEventPublishInfo info; - info.SetBundleName(bundleName); - if (EventFwk::CommonEventManager::PublishCommonEvent(eventData, info)) { - ANSR_LOGI("notify reminder status change %{public}s", bundleName.c_str()); - } - break; + EventFwk::CommonEventPublishInfo info; + info.SetBundleName(bundleName); + if (EventFwk::CommonEventManager::PublishCommonEvent(eventData, info)) { + ANSR_LOGI("notify reminder status change %{public}s", bundleName.c_str()); } } } diff --git a/services/ans/src/reminder_data_manager_inner.cpp b/services/ans/src/reminder_data_manager_inner.cpp index 8f2c30117..b17a0bc85 100644 --- a/services/ans/src/reminder_data_manager_inner.cpp +++ b/services/ans/src/reminder_data_manager_inner.cpp @@ -108,7 +108,7 @@ void ReminderDataManager::ReportSysEvent(const sptr& reminder) uint64_t triggerTime = reminder->GetTriggerTimeInMilli(); int32_t ringTime = static_cast(reminder->GetRingDuration()); HiSysEventWrite(HiviewDFX::HiSysEvent::Domain::NOTIFICATION, event, HiviewDFX::HiSysEvent::EventType::STATISTIC, - "PID", 0, "UID", uid, "NAME", bundleName, "TYPE", type, "repeat", repeat, "TRIGGER_TIME", triggerTime, + "UID", uid, "NAME", bundleName, "TYPE", type, "REPEAT", repeat, "TRIGGER_TIME", triggerTime, "RING_TIME", ringTime); #endif } diff --git a/services/ans/test/unittest/reminder_data_manager_test.cpp b/services/ans/test/unittest/reminder_data_manager_test.cpp index 75dec8469..85e78560d 100644 --- a/services/ans/test/unittest/reminder_data_manager_test.cpp +++ b/services/ans/test/unittest/reminder_data_manager_test.cpp @@ -432,7 +432,7 @@ HWTEST_F(ReminderDataManagerTest, ReminderDataManagerTest_016, Level1) reminder1->SetActionButton("不再提醒", ReminderRequest::ActionButtonType::CLOSE, "", buttonWantAgent1, buttonDataShareUpdate1); manager->UpdateAppDatabase(reminder1, ReminderRequest::ActionButtonType::CLOSE); - SUCCEED(); + EXPECT_TRUE(reminder1->actionButtonMap_.size() > 0); } /** diff --git a/test/fuzztest/reminderdatamanager_fuzzer/reminderdatamanager_fuzzer.cpp b/test/fuzztest/reminderdatamanager_fuzzer/reminderdatamanager_fuzzer.cpp index c1656f7b5..a9b4acafb 100644 --- a/test/fuzztest/reminderdatamanager_fuzzer/reminderdatamanager_fuzzer.cpp +++ b/test/fuzztest/reminderdatamanager_fuzzer/reminderdatamanager_fuzzer.cpp @@ -33,6 +33,7 @@ namespace OHOS { Notification::ReminderDataManager::InitInstance(nullptr); auto manager = Notification::ReminderDataManager::GetInstance(); + manager->Init(false); manager->Dump(); manager->CancelAllReminders(bundleName, userId, uid); sptr option = new Notification::NotificationBundleOption( @@ -127,6 +128,16 @@ namespace OHOS { manager->ShowReminder(reminder, value, value, value, value); return true; } + + bool Clear() + { + auto manager = Notification::ReminderDataManager::GetInstance(); + if (manager->queue_ != nullptr) { + auto handler = manager->queue_->submit_h(std::bind([]() {})); + manager->queue_->wait(handler); + } + return true; + } } /* Fuzzer entry point */ @@ -137,6 +148,7 @@ extern "C" int LLVMFuzzerTestOneInput(const uint8_t* data, size_t size) if (ch != nullptr && size >= GetU32Size()) { OHOS::DoSomethingInterestingWithManager(ch, size); OHOS::DoSomethingInterestingWithReminder(ch, size); + OHOS::Clear(); free(ch); ch = nullptr; } -- Gitee From 7cdb1c7e0d100653976dc2e4209615e79c9b402a Mon Sep 17 00:00:00 2001 From: z30053788 Date: Sun, 13 Oct 2024 14:43:03 +0800 Subject: [PATCH 076/167] =?UTF-8?q?=E5=90=8C=E6=AD=A5?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: z30053788 Change-Id: I5a176b6a7b6af232bcfe1c49f22ae3b85e587ca9 --- bundle.json | 6 +- frameworks/ans/BUILD.gn | 1 + frameworks/ans/src/notification_helper.cpp | 5 - .../notification_local_live_view_button.cpp | 2 +- frameworks/ans/src/notification_request.cpp | 6 +- .../ans/src/notification_subscriber.cpp | 6 +- frameworks/cj/ffi/include/inner_errors.h | 1 + .../core/common/include/ans_const_define.h | 3 - .../core/common/include/ans_convert_enum.h | 17 + .../core/common/include/ans_inner_errors.h | 17 +- .../core/common/src/ans_convert_enum.cpp | 56 ++- .../core/include/ans_manager_interface.h | 7 - frameworks/core/include/ans_manager_proxy.h | 7 - frameworks/core/include/ans_manager_stub.h | 8 - frameworks/core/include/ans_notification.h | 7 - ..._notification_service_ipc_interface_code.h | 1 - frameworks/core/src/ans_manager_proxy.cpp | 22 - frameworks/core/src/ans_manager_stub.cpp | 22 +- .../core/src/ans_manager_stub_invalid.cpp | 6 - frameworks/core/src/ans_notification.cpp | 32 +- frameworks/core/src/ans_subscriber_proxy.cpp | 5 +- .../ans_notification_branch_test.cpp | 5 - frameworks/js/napi/include/common.h | 4 +- .../manager/napi_enable_notification.h | 1 + .../napi/include/manager/napi_open_settings.h | 69 +++ frameworks/js/napi/src/common_utils.cpp | 1 + frameworks/js/napi/src/manager/BUILD.gn | 1 + .../js/napi/src/manager/init_module.cpp | 2 + .../js/napi/src/manager/napi_cancel.cpp | 4 + .../napi/src/manager/napi_display_badge.cpp | 2 + .../js/napi/src/manager/napi_distributed.cpp | 5 + .../src/manager/napi_distributed_enable.cpp | 3 + .../js/napi/src/manager/napi_disturb_mode.cpp | 5 + .../src/manager/napi_enable_notification.cpp | 35 +- .../js/napi/src/manager/napi_get_active.cpp | 2 + .../napi/src/manager/napi_local_live_view.cpp | 1 + .../napi/src/manager/napi_open_settings.cpp | 403 ++++++++++++++++++ .../js/napi/src/manager/napi_publish.cpp | 2 + frameworks/js/napi/src/manager/napi_push.cpp | 14 +- .../js/napi/src/manager/napi_remove_group.cpp | 1 + frameworks/js/napi/src/manager/napi_slot.cpp | 8 + .../js/napi/src/manager/napi_sync_config.cpp | 1 + frameworks/js/napi/src/subscribe.cpp | 7 +- .../js/napi/src/subscribe/napi_remove.cpp | 4 +- .../js/napi/src/subscribe/napi_subscribe.cpp | 3 + hisysevent.yaml | 1 - interfaces/inner_api/notification_capsule.h | 5 +- interfaces/inner_api/notification_constant.h | 83 ++++ interfaces/inner_api/notification_helper.h | 7 - .../notification_local_live_view_button.h | 4 +- .../notification_local_live_view_content.h | 16 +- interfaces/ndk/BUILD.gn | 68 +++ interfaces/ndk/include/notification.h | 58 +++ interfaces/ndk/src/notification.cpp | 38 ++ notification.gni | 3 +- services/ans/BUILD.gn | 9 +- .../include/advanced_notification_service.h | 40 +- services/ans/include/bundle_manager_helper.h | 8 + .../ans/include/notification_analytics_util.h | 2 - .../ans/include/notification_dialog_manager.h | 10 +- .../include/notification_extension_wrapper.h | 3 + .../ans/include/system_dialog_connect_stb.h | 2 + .../ans/src/advanced_datashare_helper.cpp | 2 +- .../ans/src/advanced_notification_inline.cpp | 55 ++- ...dvanced_notification_live_view_service.cpp | 58 ++- .../base_publish_process.cpp | 3 + .../live_publish_process.cpp | 8 + .../advanced_notification_publish_service.cpp | 370 ++++++++++++---- .../ans/src/advanced_notification_service.cpp | 118 ++++- .../advanced_notification_service_ability.cpp | 2 +- .../advanced_notification_slot_service.cpp | 46 +- ...vanced_notification_subscriber_service.cpp | 8 +- .../ans/src/advanced_notification_utils.cpp | 49 ++- services/ans/src/bundle_manager_helper.cpp | 15 + .../common/notification_analytics_util.cpp | 58 ++- .../src/notification_extension_wrapper.cpp | 36 +- services/ans/src/notification_preferences.cpp | 15 +- .../src/notification_preferences_database.cpp | 14 +- .../ans/src/notification_preferences_info.cpp | 3 + .../src/notification_subscriber_manager.cpp | 29 ++ services/ans/src/notification_trust_list.cpp | 12 +- services/ans/src/permission_filter.cpp | 9 +- services/ans/src/reminder_data_manager.cpp | 3 +- .../ans/src/system_dialog_connect_stb.cpp | 60 ++- ...nced_notification_publish_service_test.cpp | 13 +- .../advanced_notification_service_test.cpp | 21 +- .../NotificationServiceExtAbility.ts | 155 ++++--- .../entry/src/main/ets/common/constant.ets | 12 +- .../src/main/ets/pages/notificationDialog.ets | 90 ++-- .../ets/pages/watchNotificationDialog.ets | 272 ++++++++++++ .../entry/src/main/module.json | 3 +- .../resources/base/profile/main_pages.json | 5 +- .../distributed_preferences_database.h | 1 - .../src/distributed_preferences_database.cpp | 14 - .../unittest/distributed_preferences_test.cpp | 2 +- ...distributed_screen_status_manager_test.cpp | 6 +- .../ansmanagerstub_fuzzer.cpp | 6 + .../anssubscriberstub_fuzzer.cpp | 16 + test/fuzztest/fuzz_common_base/fuzz_data.h | 2 +- 99 files changed, 2198 insertions(+), 570 deletions(-) create mode 100644 frameworks/js/napi/include/manager/napi_open_settings.h create mode 100644 frameworks/js/napi/src/manager/napi_open_settings.cpp create mode 100644 interfaces/ndk/BUILD.gn create mode 100644 interfaces/ndk/include/notification.h create mode 100644 interfaces/ndk/src/notification.cpp create mode 100644 services/dialog_ui/enable_notification_dialog/entry/src/main/ets/pages/watchNotificationDialog.ets diff --git a/bundle.json b/bundle.json index f5b9386e4..7b232ca93 100644 --- a/bundle.json +++ b/bundle.json @@ -40,7 +40,8 @@ "subsystem": "notification", "syscap": [ "SystemCapability.Notification.Notification", - "SystemCapability.Notification.ReminderAgent" + "SystemCapability.Notification.ReminderAgent", + "SystemCapability.Notification.NotificationSettings" ], "features": [ "distributed_notification_service_feature_summary", @@ -104,7 +105,8 @@ "fwk_group": [ "//base/notification/distributed_notification_service/frameworks/ans:ans_client", "//base/notification/distributed_notification_service/frameworks/js/napi:napi_notification", - "//base/notification/distributed_notification_service/frameworks/js/napi:napi_reminder" + "//base/notification/distributed_notification_service/frameworks/js/napi:napi_reminder", + "//base/notification/distributed_notification_service/interfaces/ndk:ohnotification" ], "service_group": [ "//base/notification/distributed_notification_service/sa_profile:ans_sa_profile", diff --git a/frameworks/ans/BUILD.gn b/frameworks/ans/BUILD.gn index 12e565fae..24bfef29e 100644 --- a/frameworks/ans/BUILD.gn +++ b/frameworks/ans/BUILD.gn @@ -128,6 +128,7 @@ ohos_shared_library("ans_innerkits") { external_deps = [ "ability_base:want", "ability_base:zuri", + "ability_runtime:appkit_native", "bundle_framework:appexecfwk_base", "bundle_framework:appexecfwk_core", "c_utils:utils", diff --git a/frameworks/ans/src/notification_helper.cpp b/frameworks/ans/src/notification_helper.cpp index 15e691700..0cad2612f 100644 --- a/frameworks/ans/src/notification_helper.cpp +++ b/frameworks/ans/src/notification_helper.cpp @@ -170,11 +170,6 @@ ErrCode NotificationHelper::CanPopEnableNotificationDialog(sptr::GetInstance()->RemoveEnableNotificationDialog(); -} - ErrCode NotificationHelper::RequestEnableNotification(std::string &deviceId, sptr &hostClient, sptr &callerToken) diff --git a/frameworks/ans/src/notification_local_live_view_button.cpp b/frameworks/ans/src/notification_local_live_view_button.cpp index 9b1e7503a..526324138 100644 --- a/frameworks/ans/src/notification_local_live_view_button.cpp +++ b/frameworks/ans/src/notification_local_live_view_button.cpp @@ -106,7 +106,7 @@ bool NotificationLocalLiveViewButton::ToJson(nlohmann::json &jsonObject) const jsonObject["icons"] = iconsArr; nlohmann::json iconResourceArr = nlohmann::json::array(); - for (auto &resource : buttonIconsResource_) { + for (const auto &resource : buttonIconsResource_) { if (!resource) { continue; } diff --git a/frameworks/ans/src/notification_request.cpp b/frameworks/ans/src/notification_request.cpp index 5147a3521..f4d058f09 100644 --- a/frameworks/ans/src/notification_request.cpp +++ b/frameworks/ans/src/notification_request.cpp @@ -304,6 +304,8 @@ void NotificationRequest::SetLittleIcon(const std::shared_ptr & Media::ImageInfo outImageInfo; littleIcon->GetImageInfo(outImageInfo); littleIconType_ = outImageInfo.encodedFormat; + } else { + littleIconType_ = ""; } } @@ -2747,10 +2749,10 @@ std::string NotificationRequest::GenerateUniqueKey() std::stringstream stream; if (IsAgentNotification()) { - stream << ownerUserId_ << keySpliter << ownerBundleName_ << keySpliter << + stream << ownerUid_ << keySpliter << ownerBundleName_ << keySpliter << ownerUserId_ << keySpliter << typeFlag << keySpliter << appMessageId_; } else { - stream << creatorUserId_ << keySpliter << creatorBundleName_ << keySpliter << + stream << creatorUid_ << keySpliter << creatorBundleName_ << keySpliter << creatorUserId_ << keySpliter << typeFlag << keySpliter << appMessageId_; } return stream.str(); diff --git a/frameworks/ans/src/notification_subscriber.cpp b/frameworks/ans/src/notification_subscriber.cpp index f734f06ae..d33ef4415 100644 --- a/frameworks/ans/src/notification_subscriber.cpp +++ b/frameworks/ans/src/notification_subscriber.cpp @@ -56,6 +56,8 @@ bool NotificationSubscriber::ProcessSyncDecision( } auto flagIter = flagsMap->find(deviceType); if (flagIter != flagsMap->end() && flagIter->second != nullptr) { + ANS_LOGI("SetFlags-before filte, notificationKey = %{public}s flagIter flags = %{public}d", + request->GetKey().c_str(), flagIter->second->GetReminderFlags()); std::shared_ptr tempFlags = request->GetFlags(); tempFlags->SetSoundEnabled(DowngradeReminder(tempFlags->IsSoundEnabled(), flagIter->second->IsSoundEnabled())); tempFlags->SetVibrationEnabled( @@ -67,6 +69,8 @@ bool NotificationSubscriber::ProcessSyncDecision( tempFlags->SetLightScreenEnabled( tempFlags->IsLightScreenEnabled() && flagIter->second->IsLightScreenEnabled()); request->SetFlags(tempFlags); + ANS_LOGI("SetFlags-after filte, notificationKey = %{public}s flags = %{public}d", + request->GetKey().c_str(), tempFlags->GetReminderFlags()); return true; } if (deviceType.size() <= 0 || deviceType.compare(NotificationConstant::CURRENT_DEVICE_TYPE) == 0) { @@ -168,7 +172,7 @@ void NotificationSubscriber::SubscriberImpl::OnBatchCanceled(const std::vector(), deleteReason); - } else if (notificationMap != nullptr) { + } else { subscriber_.OnBatchCanceled(notificationList, std::make_shared(*notificationMap), deleteReason); } diff --git a/frameworks/cj/ffi/include/inner_errors.h b/frameworks/cj/ffi/include/inner_errors.h index bb9b164c9..053b5c2b9 100644 --- a/frameworks/cj/ffi/include/inner_errors.h +++ b/frameworks/cj/ffi/include/inner_errors.h @@ -132,6 +132,7 @@ const int32_t ERROR_DIALOG_IS_POPPING = 1600013; // A notification const int32_t ERROR_NO_RIGHT = 1600014; // No permission. const int32_t ERROR_REPEAT_SET = 1600015; // Repeat create or end. const int32_t ERROR_EXPIRED_NOTIFICATION = 1600016; // Low update version. +const int32_t ERROR_SETTING_WINDOW_EXIST = 1600018; // The notification settings window is already displayed. const int32_t ERROR_NETWORK_UNREACHABLE = 2300007; // Network unreachable. const int32_t ERROR_BUNDLE_NOT_FOUND = 17700001; // The specified bundle name was not found. diff --git a/frameworks/core/common/include/ans_const_define.h b/frameworks/core/common/include/ans_const_define.h index 71872cc17..0bb0d7b78 100644 --- a/frameworks/core/common/include/ans_const_define.h +++ b/frameworks/core/common/include/ans_const_define.h @@ -53,9 +53,6 @@ constexpr int32_t NOTIFICATION_MAX_COUNT = 1024; constexpr int32_t DO_NOT_DISTURB_PROFILE_MIN_ID = 1; constexpr int32_t DO_NOT_DISTURB_PROFILE_MAX_ID = 10; -constexpr int32_t NFC_UID = 1027; -constexpr int32_t PAC_UID = 7007; - // Default sound for notification const static Uri DEFAULT_NOTIFICATION_SOUND("file://system/etc/Light.ogg"); const static std::vector DEFAULT_NOTIFICATION_VIBRATION = {200}; diff --git a/frameworks/core/common/include/ans_convert_enum.h b/frameworks/core/common/include/ans_convert_enum.h index 4e0405f7c..81c2cdd3f 100644 --- a/frameworks/core/common/include/ans_convert_enum.h +++ b/frameworks/core/common/include/ans_convert_enum.h @@ -54,6 +54,7 @@ enum class SlotLevel { }; enum class RemoveReason { + DEFAULT_REASON_DELETE = 0, CLICK_REASON_REMOVE = 1, CANCEL_REASON_REMOVE = 2, CANCEL_ALL_REASON_REMOVE = 3, @@ -67,6 +68,22 @@ enum class RemoveReason { FLOW_CONTROL_REASON_DELETE = 11, DISABLE_SLOT_REASON_DELETE = 12, DISABLE_NOTIFICATION_REASON_DELETE = 13, + APP_CANCEL_AS_BUNELE_REASON_DELETE = 14, + APP_CANCEL_AS_BUNELE_WITH_AGENT_REASON_DELETE = 15, + APP_CANCEL_REMINDER_REASON_DELETE = 16, + APP_CANCEL_GROPU_REASON_DELETE = 17, + APP_REMOVE_GROUP_REASON_DELETE = 18, + APP_REMOVE_ALL_REASON_DELETE = 19, + APP_REMOVE_ALL_USER_REASON_DELETE = 20, + TRIGGER_EIGHT_HOUR_REASON_DELETE = 21, + TRIGGER_FOUR_HOUR_REASON_DELETE = 22, + TRIGGER_TEN_MINUTES_REASON_DELETE = 23, + TRIGGER_FIFTEEN_MINUTES_REASON_DELETE = 24, + TRIGGER_THIRTY_MINUTES_REASON_DELETE = 25, + TRIGGER_START_ARCHIVE_REASON_DELETE = 26, + TRIGGER_AUTO_DELETE_REASON_DELETE = 27, + PACKAGE_REMOVE_REASON_DELETE = 28, + SLOT_ENABLED_REASON_DELETE = 29, APP_CANCEL_REASON_OTHER = 100, }; diff --git a/frameworks/core/common/include/ans_inner_errors.h b/frameworks/core/common/include/ans_inner_errors.h index 49b6ebdd1..dfbf494fc 100644 --- a/frameworks/core/common/include/ans_inner_errors.h +++ b/frameworks/core/common/include/ans_inner_errors.h @@ -107,14 +107,14 @@ enum ReminderErrorCode : uint32_t { }; static std::map reminderErrCodeMsgMap = { - { ERR_REMINDER_PERMISSION_DENIED, "BussinessError 201: Permission denied." }, - { ERR_REMINDER_INVALID_PARAM, "BussinessError 401: Parameter error." }, - { ERR_REMINDER_NOTIFICATION_NOT_ENABLE, "BussinessError 1700001: Notification not enable." }, - { ERR_REMINDER_NUMBER_OVERLOAD, "BussinessError 1700002: The number of reminders exceeds the limit." }, - { ERR_REMINDER_NOT_EXIST, "BussinessError 1700003: The reminder not exist." }, - { ERR_REMINDER_PACKAGE_NOT_EXIST, "BussinessError 1700004: The package name not exist." }, - { ERR_REMINDER_CALLER_TOKEN_INVALID, "BussinessError 1700005: The caller token invalid." }, - { ERR_REMINDER_DATA_SHARE_PERMISSION_DENIED, "BussinessError 1700006: The data share permission denied." } + { ERR_REMINDER_PERMISSION_DENIED, "Permission denied." }, + { ERR_REMINDER_INVALID_PARAM, "Parameter error." }, + { ERR_REMINDER_NOTIFICATION_NOT_ENABLE, "Notification not enable." }, + { ERR_REMINDER_NUMBER_OVERLOAD, "The number of reminders exceeds the limit." }, + { ERR_REMINDER_NOT_EXIST, "The reminder not exist." }, + { ERR_REMINDER_PACKAGE_NOT_EXIST, "The package name not exist." }, + { ERR_REMINDER_CALLER_TOKEN_INVALID, "The caller token invalid." }, + { ERR_REMINDER_DATA_SHARE_PERMISSION_DENIED, "The data share permission denied." } }; // Notification error msg @@ -147,6 +147,7 @@ const int32_t ERROR_NO_RIGHT = 1600014; // No permission. const int32_t ERROR_REPEAT_SET = 1600015; // Repeat create or end. const int32_t ERROR_EXPIRED_NOTIFICATION = 1600016; // Low update version. const int32_t ERROR_NO_AGENT_SETTING = 1600017; // No corresponding agent relationship configuration. +const int32_t ERROR_SETTING_WINDOW_EXIST = 1600018; // The notification settings window is already displayed. const int32_t ERROR_NETWORK_UNREACHABLE = 2300007; // Network unreachable. const int32_t ERROR_BUNDLE_NOT_FOUND = 17700001; // The specified bundle name was not found. } // namespace Notification diff --git a/frameworks/core/common/src/ans_convert_enum.cpp b/frameworks/core/common/src/ans_convert_enum.cpp index 6eeecc3ab..39f7bae5d 100644 --- a/frameworks/core/common/src/ans_convert_enum.cpp +++ b/frameworks/core/common/src/ans_convert_enum.cpp @@ -225,6 +225,9 @@ bool AnsEnumUtil::SlotLevelCToJS(const NotificationSlot::NotificationLevel &inLe bool AnsEnumUtil::ReasonCToJS(const int &inType, int &outType) { switch (inType) { + case NotificationConstant::DEFAULT_REASON_DELETE: + outType = static_cast(RemoveReason::DEFAULT_REASON_DELETE); + break; case NotificationConstant::CLICK_REASON_DELETE: outType = static_cast(RemoveReason::CLICK_REASON_REMOVE); break; @@ -261,12 +264,61 @@ bool AnsEnumUtil::ReasonCToJS(const int &inType, int &outType) case NotificationConstant::DISABLE_NOTIFICATION_REASON_DELETE: outType = static_cast(RemoveReason::DISABLE_NOTIFICATION_REASON_DELETE); break; + case NotificationConstant::APP_CANCEL_AS_BUNELE_REASON_DELETE: + outType = static_cast(RemoveReason::APP_CANCEL_AS_BUNELE_REASON_DELETE); + break; + case NotificationConstant::APP_CANCEL_AS_BUNELE_WITH_AGENT_REASON_DELETE: + outType = static_cast(RemoveReason::APP_CANCEL_AS_BUNELE_WITH_AGENT_REASON_DELETE); + break; + case NotificationConstant::APP_CANCEL_REMINDER_REASON_DELETE: + outType = static_cast(RemoveReason::APP_CANCEL_REMINDER_REASON_DELETE); + break; + case NotificationConstant::APP_CANCEL_GROPU_REASON_DELETE: + outType = static_cast(RemoveReason::APP_CANCEL_GROPU_REASON_DELETE); + break; + case NotificationConstant::APP_REMOVE_GROUP_REASON_DELETE: + outType = static_cast(RemoveReason::APP_REMOVE_GROUP_REASON_DELETE); + break; + case NotificationConstant::APP_REMOVE_ALL_REASON_DELETE: + outType = static_cast(RemoveReason::APP_REMOVE_ALL_REASON_DELETE); + break; + case NotificationConstant::APP_REMOVE_ALL_USER_REASON_DELETE: + outType = static_cast(RemoveReason::APP_REMOVE_ALL_USER_REASON_DELETE); + break; + case NotificationConstant::TRIGGER_EIGHT_HOUR_REASON_DELETE: + outType = static_cast(RemoveReason::TRIGGER_EIGHT_HOUR_REASON_DELETE); + break; + case NotificationConstant::TRIGGER_FOUR_HOUR_REASON_DELETE: + outType = static_cast(RemoveReason::TRIGGER_FOUR_HOUR_REASON_DELETE); + break; + case NotificationConstant::TRIGGER_TEN_MINUTES_REASON_DELETE: + outType = static_cast(RemoveReason::TRIGGER_TEN_MINUTES_REASON_DELETE); + break; + case NotificationConstant::TRIGGER_FIFTEEN_MINUTES_REASON_DELETE: + outType = static_cast(RemoveReason::TRIGGER_FIFTEEN_MINUTES_REASON_DELETE); + break; + case NotificationConstant::TRIGGER_THIRTY_MINUTES_REASON_DELETE: + outType = static_cast(RemoveReason::TRIGGER_THIRTY_MINUTES_REASON_DELETE); + break; + case NotificationConstant::TRIGGER_START_ARCHIVE_REASON_DELETE: + outType = static_cast(RemoveReason::TRIGGER_START_ARCHIVE_REASON_DELETE); + break; + case NotificationConstant::TRIGGER_AUTO_DELETE_REASON_DELETE: + outType = static_cast(RemoveReason::TRIGGER_AUTO_DELETE_REASON_DELETE); + break; + case NotificationConstant::PACKAGE_REMOVE_REASON_DELETE: + outType = static_cast(RemoveReason::PACKAGE_REMOVE_REASON_DELETE); + break; + case NotificationConstant::SLOT_ENABLED_REASON_DELETE: + outType = static_cast(RemoveReason::SLOT_ENABLED_REASON_DELETE); + break; case NotificationConstant::APP_CANCEL_REASON_OTHER: outType = static_cast(RemoveReason::APP_CANCEL_REASON_OTHER); break; default: - ANS_LOGE("Reason %{public}d is an invalid value", inType); - return false; + outType = static_cast(RemoveReason::APP_CANCEL_REASON_OTHER); + ANS_LOGW("Reason %{public}d is an invalid value", inType); + break; } return true; } diff --git a/frameworks/core/include/ans_manager_interface.h b/frameworks/core/include/ans_manager_interface.h index b4605e7bd..790abe0ce 100644 --- a/frameworks/core/include/ans_manager_interface.h +++ b/frameworks/core/include/ans_manager_interface.h @@ -509,13 +509,6 @@ public: virtual ErrCode CanPopEnableNotificationDialog(const sptr &callback, bool &canPop, std::string &bundleName) = 0; - /** - * @brief remove enable notification dialog. - * - * @return Returns remove dialog result. - */ - virtual ErrCode RemoveEnableNotificationDialog() = 0; - /** * @brief Checks whether notifications are allowed for a specific bundle. * diff --git a/frameworks/core/include/ans_manager_proxy.h b/frameworks/core/include/ans_manager_proxy.h index e739314cf..59bf9a7eb 100644 --- a/frameworks/core/include/ans_manager_proxy.h +++ b/frameworks/core/include/ans_manager_proxy.h @@ -497,13 +497,6 @@ public: ErrCode CanPopEnableNotificationDialog(const sptr &callback, bool &canPop, std::string &bundleName) override; - /** - * @brief remove enable notification dialog. - * - * @return Returns remove dialog result. - */ - ErrCode RemoveEnableNotificationDialog() override; - /** * @brief Checks whether notifications are allowed for a specific bundle. * diff --git a/frameworks/core/include/ans_manager_stub.h b/frameworks/core/include/ans_manager_stub.h index 9c092b534..0ec670f8f 100644 --- a/frameworks/core/include/ans_manager_stub.h +++ b/frameworks/core/include/ans_manager_stub.h @@ -496,13 +496,6 @@ public: ErrCode CanPopEnableNotificationDialog(const sptr &callback, bool &canPop, std::string &bundleName) override; - /** - * @brief remove enable notification dialog. - * - * @return Returns remove dialog result. - */ - ErrCode RemoveEnableNotificationDialog() override; - /** * @brief Checks whether notifications are allowed for a specific bundle. * @@ -994,7 +987,6 @@ private: ErrCode HandleIsAllowedNotify(MessageParcel &data, MessageParcel &reply); ErrCode HandleIsAllowedNotifySelf(MessageParcel &data, MessageParcel &reply); ErrCode HandleCanPopEnableNotificationDialog(MessageParcel &data, MessageParcel &reply); - ErrCode HandleRemoveEnableNotificationDialog(MessageParcel &data, MessageParcel &reply); ErrCode HandleIsSpecialBundleAllowedNotify(MessageParcel &data, MessageParcel &reply); ErrCode HandleIsDistributedEnabled(MessageParcel &data, MessageParcel &reply); ErrCode HandleEnableDistributed(MessageParcel &data, MessageParcel &reply); diff --git a/frameworks/core/include/ans_notification.h b/frameworks/core/include/ans_notification.h index 3359afba4..c45c7332b 100644 --- a/frameworks/core/include/ans_notification.h +++ b/frameworks/core/include/ans_notification.h @@ -299,13 +299,6 @@ public: ErrCode CanPopEnableNotificationDialog(sptr &hostClient, bool &canPop, std::string &bundleName); - /** - * @brief remove enable notification dialog. - * - * @return Returns remove dialog result. - */ - ErrCode RemoveEnableNotificationDialog(); - /** * @brief Allows the current application to publish notifications on a specified device. * diff --git a/frameworks/core/include/distributed_notification_service_ipc_interface_code.h b/frameworks/core/include/distributed_notification_service_ipc_interface_code.h index 34ac6a24d..56e520eb6 100644 --- a/frameworks/core/include/distributed_notification_service_ipc_interface_code.h +++ b/frameworks/core/include/distributed_notification_service_ipc_interface_code.h @@ -76,7 +76,6 @@ namespace Notification { IS_ALLOWED_NOTIFY, IS_ALLOWED_NOTIFY_SELF, CAN_POP_ENABLE_NOTIFICATION_DIALOG, - REMOVE_ENABLE_NOTIFICATION_DIALOG, IS_SPECIAL_BUNDLE_ALLOWED_NOTIFY, SET_DO_NOT_DISTURB_DATE, GET_DO_NOT_DISTURB_DATE, diff --git a/frameworks/core/src/ans_manager_proxy.cpp b/frameworks/core/src/ans_manager_proxy.cpp index 56716d525..1d185722d 100644 --- a/frameworks/core/src/ans_manager_proxy.cpp +++ b/frameworks/core/src/ans_manager_proxy.cpp @@ -1316,28 +1316,6 @@ ErrCode AnsManagerProxy::CanPopEnableNotificationDialog(const sptr &bundleOption, bool &allowed) { if (bundleOption == nullptr) { diff --git a/frameworks/core/src/ans_manager_stub.cpp b/frameworks/core/src/ans_manager_stub.cpp index ad4698eb6..8be5e0663 100644 --- a/frameworks/core/src/ans_manager_stub.cpp +++ b/frameworks/core/src/ans_manager_stub.cpp @@ -223,10 +223,6 @@ int32_t AnsManagerStub::OnRemoteRequest(uint32_t code, MessageParcel &data, Mess result = HandleCanPopEnableNotificationDialog(data, reply); break; } - case static_cast(NotificationInterfaceCode::REMOVE_ENABLE_NOTIFICATION_DIALOG): { - result = HandleRemoveEnableNotificationDialog(data, reply); - break; - } case static_cast(NotificationInterfaceCode::IS_SPECIAL_BUNDLE_ALLOWED_NOTIFY): { result = HandleIsSpecialBundleAllowedNotify(data, reply); break; @@ -1648,16 +1644,6 @@ ErrCode AnsManagerStub::HandleCanPopEnableNotificationDialog(MessageParcel &data return ERR_OK; } -ErrCode AnsManagerStub::HandleRemoveEnableNotificationDialog(MessageParcel &data, MessageParcel &reply) -{ - ErrCode result = RemoveEnableNotificationDialog(); - if (!reply.WriteInt32(result)) { - ANS_LOGE("[HandleRemoveEnableNotificationDialog] fail: write result failed, ErrCode=%{public}d", result); - return ERR_ANS_PARCELABLE_FAILED; - } - return ERR_OK; -} - ErrCode AnsManagerStub::HandleIsSpecialBundleAllowedNotify(MessageParcel &data, MessageParcel &reply) { sptr bundleOption = data.ReadParcelable(); @@ -2522,13 +2508,13 @@ ErrCode AnsManagerStub::HandleSetAdditionConfig(MessageParcel &data, MessageParc ANS_LOGE("Failed to read key."); return ERR_ANS_PARCELABLE_FAILED; } - + std::string value; if (!data.ReadString(value)) { ANS_LOGE("Failed to read value."); return ERR_ANS_PARCELABLE_FAILED; } - + ErrCode result = SetAdditionConfig(key, value); if (!reply.WriteInt32(result)) { ANS_LOGE("Failed to write result, ErrCode=%{public}d", result); @@ -2590,14 +2576,14 @@ ErrCode AnsManagerStub::HandleIsSmartReminderEnabled(MessageParcel &data, Messag ANS_LOGE("[HandleIsSmartReminderEnabled] fail: read deviceId failed."); return ERR_ANS_PARCELABLE_FAILED; } - + bool enabled = false; ErrCode result = IsSmartReminderEnabled(deviceType, enabled); if (!reply.WriteInt32(result)) { ANS_LOGE("[HandleIsSmartReminderEnabled] fail: write result failed, ErrCode=%{public}d", result); return ERR_ANS_PARCELABLE_FAILED; } - + if (!reply.WriteBool(enabled)) { ANS_LOGE("[HandleIsSmartReminderEnabled] fail: write enabled failed."); return ERR_ANS_PARCELABLE_FAILED; diff --git a/frameworks/core/src/ans_manager_stub_invalid.cpp b/frameworks/core/src/ans_manager_stub_invalid.cpp index 15c3db577..0457626d0 100644 --- a/frameworks/core/src/ans_manager_stub_invalid.cpp +++ b/frameworks/core/src/ans_manager_stub_invalid.cpp @@ -351,12 +351,6 @@ ErrCode AnsManagerStub::CanPopEnableNotificationDialog(const sptr &bundleOption, bool &allowed) { ANS_LOGE("AnsManagerStub::IsSpecialBundleAllowedNotify called!"); diff --git a/frameworks/core/src/ans_notification.cpp b/frameworks/core/src/ans_notification.cpp index 723d8ccd8..e9fbd945f 100644 --- a/frameworks/core/src/ans_notification.cpp +++ b/frameworks/core/src/ans_notification.cpp @@ -28,6 +28,8 @@ #include "reminder_request_timer.h" #include "system_ability_definition.h" +#include + namespace OHOS { namespace Notification { namespace { @@ -83,6 +85,7 @@ ErrCode AnsNotification::AddNotificationSlots(const std::vector proxy = GetAnsManagerProxy(); if (!proxy) { ANS_LOGE("GetAnsManagerProxy fail."); @@ -240,6 +243,7 @@ ErrCode AnsNotification::CancelNotification(int32_t notificationId) ErrCode AnsNotification::CancelNotification(const std::string &label, int32_t notificationId) { + ANS_LOGI("enter CancelNotification,notificationId:%{public}d", notificationId); HITRACE_METER_NAME(HITRACE_TAG_NOTIFICATION, __PRETTY_FUNCTION__); sptr proxy = GetAnsManagerProxy(); if (!proxy) { @@ -266,6 +270,7 @@ ErrCode AnsNotification::CancelAllNotifications() ErrCode AnsNotification::CancelAsBundle( int32_t notificationId, const std::string &representativeBundle, int32_t userId) { + ANS_LOGI("enter CancelAsBundle,notificationId:%{public}d", notificationId); sptr proxy = GetAnsManagerProxy(); if (!proxy) { ANS_LOGE("GetAnsManagerProxy fail."); @@ -277,6 +282,7 @@ ErrCode AnsNotification::CancelAsBundle( ErrCode AnsNotification::CancelAsBundle( const NotificationBundleOption &bundleOption, int32_t notificationId) { + ANS_LOGI("enter CancelAsBundle,notificationId:%{public}d", notificationId); sptr proxy = GetAnsManagerProxy(); if (!proxy) { ANS_LOGE("GetAnsManagerProxy fail."); @@ -443,17 +449,6 @@ ErrCode AnsNotification::CanPopEnableNotificationDialog(sptrCanPopEnableNotificationDialog(hostClient, canPop, bundleName); } -ErrCode AnsNotification::RemoveEnableNotificationDialog() -{ - ANS_LOGD("enter"); - sptr proxy = GetAnsManagerProxy(); - if (!proxy) { - ANS_LOGE("GetAnsManagerProxy fail."); - return ERR_ANS_SERVICE_NOT_CONNECTED; - } - return proxy->RemoveEnableNotificationDialog(); -} - ErrCode AnsNotification::RequestEnableNotification(std::string &deviceId, sptr &hostClient, sptr &callerToken) @@ -635,6 +630,8 @@ ErrCode AnsNotification::TriggerLocalLiveView(const NotificationBundleOption &bu ErrCode AnsNotification::RemoveNotification(const std::string &key, int32_t removeReason) { + ANS_LOGI("enter RemoveNotification,key:%{public}s,removeReason:%{public}d", + key.c_str(), removeReason); HITRACE_METER_NAME(HITRACE_TAG_NOTIFICATION, __PRETTY_FUNCTION__); if (key.empty()) { ANS_LOGW("Input key is empty."); @@ -652,6 +649,8 @@ ErrCode AnsNotification::RemoveNotification(const std::string &key, int32_t remo ErrCode AnsNotification::RemoveNotification(const NotificationBundleOption &bundleOption, const int32_t notificationId, const std::string &label, int32_t removeReason) { + ANS_LOGI("enter RemoveNotification,bundle:%{public}s,Id:%{public}d,reason:%{public}d", + bundleOption.GetBundleName().c_str(), notificationId, removeReason); HITRACE_METER_NAME(HITRACE_TAG_NOTIFICATION, __PRETTY_FUNCTION__); if (bundleOption.GetBundleName().empty()) { ANS_LOGE("Invalid bundle name."); @@ -670,6 +669,7 @@ ErrCode AnsNotification::RemoveNotification(const NotificationBundleOption &bund ErrCode AnsNotification::RemoveAllNotifications(const NotificationBundleOption &bundleOption) { + ANS_LOGI("enter RemoveAllNotifications,bundleName:%{public}s", bundleOption.GetBundleName().c_str()); if (bundleOption.GetBundleName().empty()) { ANS_LOGE("Invalid bundle name."); return ERR_ANS_INVALID_PARAM; @@ -687,6 +687,7 @@ ErrCode AnsNotification::RemoveAllNotifications(const NotificationBundleOption & ErrCode AnsNotification::RemoveNotifications(const std::vector hashcodes, int32_t removeReason) { + ANS_LOGI("enter RemoveNotifications,removeReason:%{public}d", removeReason); if (hashcodes.empty()) { ANS_LOGE("Hashcodes is empty"); return ERR_ANS_INVALID_PARAM; @@ -703,6 +704,7 @@ ErrCode AnsNotification::RemoveNotifications(const std::vector hash ErrCode AnsNotification::RemoveNotificationsByBundle(const NotificationBundleOption &bundleOption) { + ANS_LOGI("enter RemoveNotificationsByBundle,bundleName:%{public}s", bundleOption.GetBundleName().c_str()); if (bundleOption.GetBundleName().empty()) { ANS_LOGE("Invalid bundle name."); return ERR_ANS_INVALID_PARAM; @@ -930,6 +932,7 @@ ErrCode AnsNotification::GetShowBadgeEnabled(bool &enabled) ErrCode AnsNotification::CancelGroup(const std::string &groupName) { + ANS_LOGI("enter CancelGroup,groupName:%{public}s", groupName.c_str()); if (groupName.empty()) { ANS_LOGE("Invalid group name."); return ERR_ANS_INVALID_PARAM; @@ -947,6 +950,7 @@ ErrCode AnsNotification::CancelGroup(const std::string &groupName) ErrCode AnsNotification::RemoveGroupByBundle( const NotificationBundleOption &bundleOption, const std::string &groupName) { + ANS_LOGI("enter RemoveGroupByBundle,bundleName:%{public}s", bundleOption.GetBundleName().c_str()); if (bundleOption.GetBundleName().empty() || groupName.empty()) { ANS_LOGE("Invalid parameter."); return ERR_ANS_INVALID_PARAM; @@ -1099,6 +1103,7 @@ ErrCode AnsNotification::PublishContinuousTaskNotification(const NotificationReq ErrCode AnsNotification::CancelContinuousTaskNotification(const std::string &label, int32_t notificationId) { + ANS_LOGI("enter CancelContinuousTaskNotification,notificationId:%{public}d", notificationId); sptr proxy = GetAnsManagerProxy(); if (!proxy) { ANS_LOGE("GetAnsManagerProxy fail."); @@ -1189,13 +1194,12 @@ void AnsNotification::Reconnect() for (int32_t i = 0; i < MAX_RETRY_TIME; i++) { // try to connect ans sptr proxy = GetAnsManagerProxy(); - if (!proxy) { + if (!proxy) { // Sleep 1000 milliseconds before reconnect. std::this_thread::sleep_for(std::chrono::milliseconds(SLEEP_TIME)); ANS_LOGE("get ans proxy fail, try again."); continue; } - ANS_LOGD("get ans proxy success."); return; } @@ -1773,6 +1777,8 @@ ErrCode AnsNotification::SetSmartReminderEnabled(const std::string &deviceType, ErrCode AnsNotification::CancelAsBundleWithAgent(const NotificationBundleOption &bundleOption, const int32_t id) { + ANS_LOGI("enter CancelAsBundleWithAgent,bundleName:%{public}s,id:%{public}d", + bundleOption.GetBundleName().c_str(), id); sptr proxy = GetAnsManagerProxy(); if (!proxy) { ANS_LOGE("GetAnsManagerProxy fail."); diff --git a/frameworks/core/src/ans_subscriber_proxy.cpp b/frameworks/core/src/ans_subscriber_proxy.cpp index 53e283ab9..941f8d779 100644 --- a/frameworks/core/src/ans_subscriber_proxy.cpp +++ b/frameworks/core/src/ans_subscriber_proxy.cpp @@ -241,8 +241,9 @@ void AnsSubscriberProxy::OnCanceledList(const std::vector> &n for (size_t i = 0; i < notifications.size(); i ++) { sptr notification = notifications[i]; - notification->GetNotificationRequest().SetBigIcon(nullptr); - notification->GetNotificationRequest().SetLittleIcon(nullptr); + notification->GetNotificationRequestPoint()->SetBigIcon(nullptr); + notification->GetNotificationRequestPoint()->SetLittleIcon(nullptr); + notification->GetNotificationRequestPoint()->SetOverlayIcon(nullptr); } if (!WriteParcelableVector(notifications, data)) { ANS_LOGE("Write notifications failed"); diff --git a/frameworks/core/test/unittest/ans_notification_branch_test/ans_notification_branch_test.cpp b/frameworks/core/test/unittest/ans_notification_branch_test/ans_notification_branch_test.cpp index b6a322870..a31ebe47c 100644 --- a/frameworks/core/test/unittest/ans_notification_branch_test/ans_notification_branch_test.cpp +++ b/frameworks/core/test/unittest/ans_notification_branch_test/ans_notification_branch_test.cpp @@ -307,11 +307,6 @@ public: return ERR_ANS_INVALID_PARAM; } - ErrCode RemoveEnableNotificationDialog() override - { - return ERR_ANS_INVALID_PARAM; - } - ErrCode IsSpecialBundleAllowedNotify(const sptr &bundleOption, bool &allowed) override { return ERR_ANS_INVALID_PARAM; diff --git a/frameworks/js/napi/include/common.h b/frameworks/js/napi/include/common.h index dd3467145..e2b206aea 100644 --- a/frameworks/js/napi/include/common.h +++ b/frameworks/js/napi/include/common.h @@ -29,8 +29,8 @@ namespace OHOS { namespace NotificationNapi { using namespace OHOS::Notification; -constexpr int32_t STR_MAX_SIZE = 200; -constexpr int32_t LONG_STR_MAX_SIZE = 1024; +constexpr int32_t STR_MAX_SIZE = 204; +constexpr int32_t LONG_STR_MAX_SIZE = 1028; constexpr uint8_t OPERATION_MAX_TYPE = 3; constexpr int32_t LONG_LONG_STR_MAX_SIZE = 25600; constexpr int8_t NO_ERROR = 0; diff --git a/frameworks/js/napi/include/manager/napi_enable_notification.h b/frameworks/js/napi/include/manager/napi_enable_notification.h index 65ee9f4da..76f84b513 100644 --- a/frameworks/js/napi/include/manager/napi_enable_notification.h +++ b/frameworks/js/napi/include/manager/napi_enable_notification.h @@ -33,6 +33,7 @@ napi_value NapiGetAllNotificationEnabledBundles(napi_env env, napi_callback_info napi_value ParseRequestEnableParameters(const napi_env &env, const napi_callback_info &info, IsEnableParams ¶ms); napi_value NapiIsNotificationEnabledSync(napi_env env, napi_callback_info info); bool CreateUIExtension(std::shared_ptr context, std::string &bundleName); +void SendDialogEvent(std::string &bundleName, int32_t code); void SetEnableParam(IsEnableParams ¶ms, const napi_env &env, napi_value &object); class ModalExtensionCallback { diff --git a/frameworks/js/napi/include/manager/napi_open_settings.h b/frameworks/js/napi/include/manager/napi_open_settings.h new file mode 100644 index 000000000..925e03954 --- /dev/null +++ b/frameworks/js/napi/include/manager/napi_open_settings.h @@ -0,0 +1,69 @@ +/* + * Copyright (c) 2024 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +#ifndef BASE_NOTIFICATION_DISTRIBUTED_NOTIFICATION_SERVICE_FRAMEWORKS_JS_NAPI_OPEN_SETTINGS_H +#define BASE_NOTIFICATION_DISTRIBUTED_NOTIFICATION_SERVICE_FRAMEWORKS_JS_NAPI_OPEN_SETTINGS_H + +#include "common.h" +#include +#include "ui_content.h" +#include "ability.h" +#include "ability_context.h" + +namespace OHOS { +namespace NotificationNapi { +using namespace OHOS::Notification; +using JsAnsCallbackComplete = void(napi_env, void*); + +struct OpenSettingsParams { + std::shared_ptr context; +}; + +struct AsyncCallbackInfoOpenSettings { + napi_env env = nullptr; + napi_async_work asyncWork = nullptr; + OpenSettingsParams params; + CallbackPromiseInfo info; +}; + +void NapiAsyncCompleteCallbackOpenSettings(napi_env env, void *data); +napi_value NapiOpenNotificationSettings(napi_env env, napi_callback_info info); +napi_value ParseOpenSettingsParameters(const napi_env &env, const napi_callback_info &info, OpenSettingsParams ¶ms); +bool CreateSettingsUIExtension(std::shared_ptr context, std::string &bundleName); +bool Init(napi_env env, AsyncCallbackInfoOpenSettings* callbackInfo, JsAnsCallbackComplete complete); +void ProcessStatusChanged(int32_t code); + +class SettingsModalExtensionCallback { +public: + SettingsModalExtensionCallback(); + ~SettingsModalExtensionCallback(); + void OnRelease(int32_t releaseCode); + void OnResult(int32_t resultCode, const OHOS::AAFwk::Want& result); + void OnReceive(const OHOS::AAFwk::WantParams& request); + void OnError(int32_t code, const std::string& name, const std::string &message); + void OnRemoteReady(const std::shared_ptr &uiProxy); + void OnDestroy(); + void SetSessionId(int32_t sessionId); + void SetBundleName(std::string bundleName); + void SetAbilityContext(std::shared_ptr abilityContext); + void ReleaseOrErrorHandle(int32_t code); + +private: + int32_t sessionId_ = 0; + std::string bundleName_; + std::shared_ptr abilityContext_; +}; +} // namespace NotificationNapi +} // namespace OHOS +#endif // BASE_NOTIFICATION_DISTRIBUTED_NOTIFICATION_SERVICE_FRAMEWORKS_JS_NAPI_OPEN_SETTINGS_H \ No newline at end of file diff --git a/frameworks/js/napi/src/common_utils.cpp b/frameworks/js/napi/src/common_utils.cpp index 148fbd8ab..a37f02e07 100644 --- a/frameworks/js/napi/src/common_utils.cpp +++ b/frameworks/js/napi/src/common_utils.cpp @@ -50,6 +50,7 @@ static const std::unordered_map ERROR_CODE_MESSAGE { {ERROR_BUNDLE_NOT_FOUND, "The specified bundle name was not found"}, {ERROR_NO_AGENT_SETTING, "There is no corresponding agent relationship configuration"}, {ERROR_DIALOG_IS_POPPING, "Dialog is popping"}, + {ERROR_SETTING_WINDOW_EXIST, "The notification settings window is already displayed"}, }; } diff --git a/frameworks/js/napi/src/manager/BUILD.gn b/frameworks/js/napi/src/manager/BUILD.gn index 1c80f6904..3cfda893b 100644 --- a/frameworks/js/napi/src/manager/BUILD.gn +++ b/frameworks/js/napi/src/manager/BUILD.gn @@ -84,6 +84,7 @@ ohos_shared_library("notificationmanager") { "napi_enable_notification.cpp", "napi_get_active.cpp", "napi_local_live_view.cpp", + "napi_open_settings.cpp", "napi_publish.cpp", "napi_push.cpp", "napi_push_callback.cpp", diff --git a/frameworks/js/napi/src/manager/init_module.cpp b/frameworks/js/napi/src/manager/init_module.cpp index 5f6860ccd..0f2ffd95e 100644 --- a/frameworks/js/napi/src/manager/init_module.cpp +++ b/frameworks/js/napi/src/manager/init_module.cpp @@ -34,6 +34,7 @@ #include "napi_local_live_view.h" #include "napi_distributed_enable.h" #include "napi_sync_config.h" +#include "napi_open_settings.h" namespace OHOS { namespace NotificationNapi { @@ -120,6 +121,7 @@ napi_value NotificationManagerInit(napi_env env, napi_value exports) DECLARE_NAPI_FUNCTION("getSlotByBundle", NapiGetSlotByBundle), DECLARE_NAPI_FUNCTION("setAdditionalConfig", NapiSetAdditionConfig), DECLARE_NAPI_FUNCTION("isNotificationEnabledSync", NapiIsNotificationEnabledSync), + DECLARE_NAPI_FUNCTION("openNotificationSettings", NapiOpenNotificationSettings), }; NAPI_CALL(env, napi_define_properties(env, exports, sizeof(desc) / sizeof(desc[0]), desc)); diff --git a/frameworks/js/napi/src/manager/napi_cancel.cpp b/frameworks/js/napi/src/manager/napi_cancel.cpp index 87e969de0..198307c68 100644 --- a/frameworks/js/napi/src/manager/napi_cancel.cpp +++ b/frameworks/js/napi/src/manager/napi_cancel.cpp @@ -38,6 +38,7 @@ napi_value NapiCancel(napi_env env, napi_callback_info info) .hasOption = paras.hasOption }; if (!asynccallbackinfo) { + Common::NapiThrow(env, ERROR_INTERNAL_ERROR); return Common::JSParaError(env, paras.callback); } napi_value promise = nullptr; @@ -103,6 +104,7 @@ napi_value NapiCancelAll(napi_env env, napi_callback_info info) auto asynccallbackinfo = new (std::nothrow) AsyncCallbackInfoCancel {.env = env, .asyncWork = nullptr}; if (!asynccallbackinfo) { + Common::NapiThrow(env, ERROR_INTERNAL_ERROR); return Common::JSParaError(env, callback); } napi_value promise = nullptr; @@ -162,6 +164,7 @@ napi_value NapiCancelGroup(napi_env env, napi_callback_info info) AsyncCallbackInfoCancelGroup *asynccallbackinfo = new (std::nothrow) AsyncCallbackInfoCancelGroup {.env = env, .asyncWork = nullptr, .params = params}; if (!asynccallbackinfo) { + Common::NapiThrow(env, ERROR_INTERNAL_ERROR); return Common::JSParaError(env, params.callback); } napi_value promise = nullptr; @@ -230,6 +233,7 @@ napi_value NapiCancelAsBundle(napi_env env, napi_callback_info info) .hasOption = paras.hasOption }; if (!asynccallbackinfo) { + Common::NapiThrow(env, ERROR_INTERNAL_ERROR); return Common::JSParaError(env, paras.callback); } napi_value promise = nullptr; diff --git a/frameworks/js/napi/src/manager/napi_display_badge.cpp b/frameworks/js/napi/src/manager/napi_display_badge.cpp index a48f94a3a..56eb2c4a5 100644 --- a/frameworks/js/napi/src/manager/napi_display_badge.cpp +++ b/frameworks/js/napi/src/manager/napi_display_badge.cpp @@ -36,6 +36,7 @@ napi_value NapiDisplayBadge(napi_env env, napi_callback_info info) AsyncCallbackInfoEnableBadge *asynccallbackinfo = new (std::nothrow) AsyncCallbackInfoEnableBadge {.env = env, .asyncWork = nullptr, .params = params}; if (!asynccallbackinfo) { + Common::NapiThrow(env, ERROR_INTERNAL_ERROR); return Common::JSParaError(env, params.callback); } napi_value promise = nullptr; @@ -123,6 +124,7 @@ napi_value NapiIsBadgeDisplayed(napi_env env, napi_callback_info info) AsyncCallbackInfoIsDisplayBadge *asynccallbackinfo = new (std::nothrow) AsyncCallbackInfoIsDisplayBadge {.env = env, .asyncWork = nullptr, .params = params}; if (!asynccallbackinfo) { + Common::NapiThrow(env, ERROR_INTERNAL_ERROR); return Common::JSParaError(env, params.callback); } napi_value promise = nullptr; diff --git a/frameworks/js/napi/src/manager/napi_distributed.cpp b/frameworks/js/napi/src/manager/napi_distributed.cpp index 83eb20374..0b9b3092e 100644 --- a/frameworks/js/napi/src/manager/napi_distributed.cpp +++ b/frameworks/js/napi/src/manager/napi_distributed.cpp @@ -111,6 +111,7 @@ napi_value NapiEnableDistributed(napi_env env, napi_callback_info info) new (std::nothrow) AsyncCallbackInfoEnabled {.env = env, .asyncWork = nullptr, .params = params}; if (!asynccallbackinfo) { ANS_LOGD("Create asyncCallbackinfo fail."); + Common::NapiThrow(env, ERROR_INTERNAL_ERROR); return Common::JSParaError(env, params.callback); } napi_value promise = nullptr; @@ -327,6 +328,7 @@ napi_value NapiIsDistributedEnableByBundle(napi_env env, napi_callback_info info AsyncCallbackInfoIsEnabledByBundle *asynccallbackinfo = new (std::nothrow) AsyncCallbackInfoIsEnabledByBundle {.env = env, .asyncWork = nullptr, .params = params}; if (!asynccallbackinfo) { + Common::NapiThrow(env, ERROR_INTERNAL_ERROR); return Common::JSParaError(env, params.callback); } napi_value promise = nullptr; @@ -413,6 +415,7 @@ napi_value NapiGetDeviceRemindType(napi_env env, napi_callback_info info) auto asynccallbackinfo = new (std::nothrow) AsyncCallbackInfoGetRemindType {.env = env, .asyncWork = nullptr}; if (!asynccallbackinfo) { + Common::NapiThrow(env, ERROR_INTERNAL_ERROR); return Common::JSParaError(env, callback); } napi_value promise = nullptr; @@ -461,6 +464,7 @@ napi_value NapiSetSyncNotificationEnabledWithoutApp(napi_env env, napi_callback_ AsyncCallbackInfoEnabledWithoutApp *asynccallbackinfo = new (std::nothrow) AsyncCallbackInfoEnabledWithoutApp {.env = env, .asyncWork = nullptr, .params = params}; if (!asynccallbackinfo) { + Common::NapiThrow(env, ERROR_INTERNAL_ERROR); return Common::JSParaError(env, params.callback); } napi_value promise = nullptr; @@ -526,6 +530,7 @@ napi_value NapiGetSyncNotificationEnabledWithoutApp(napi_env env, napi_callback_ new (std::nothrow) AsyncCallbackInfoGetEnabledWithoutApp { .env = env, .asyncWork = nullptr, .params = params}; if (!asynccallbackinfo) { + Common::NapiThrow(env, ERROR_INTERNAL_ERROR); return Common::JSParaError(env, params.callback); } napi_value promise = nullptr; diff --git a/frameworks/js/napi/src/manager/napi_distributed_enable.cpp b/frameworks/js/napi/src/manager/napi_distributed_enable.cpp index 51201d61c..9c958083e 100644 --- a/frameworks/js/napi/src/manager/napi_distributed_enable.cpp +++ b/frameworks/js/napi/src/manager/napi_distributed_enable.cpp @@ -120,6 +120,7 @@ napi_value NapiSetDistributedEnabledByBundle(napi_env env, napi_callback_info in AsyncCallbackDistributedEnable *asynccallbackinfo = new (std::nothrow) AsyncCallbackDistributedEnable {.env = env, .asyncWork = nullptr, .params = params}; if (!asynccallbackinfo) { + Common::NapiThrow(env, ERROR_INTERNAL_ERROR); return Common::JSParaError(env, nullptr); } napi_value promise = nullptr; @@ -230,6 +231,7 @@ napi_value NapiSetSmartReminderEnabled(napi_env env, napi_callback_info info) AsyncCallbackSmartReminderEnabled *asynccallbackinfo = new (std::nothrow) AsyncCallbackSmartReminderEnabled {.env = env, .asyncWork = nullptr, .params = params}; if (!asynccallbackinfo) { + Common::NapiThrow(env, ERROR_INTERNAL_ERROR); return Common::JSParaError(env, nullptr); } napi_value promise = nullptr; @@ -298,6 +300,7 @@ napi_value NapiIsSmartReminderEnabled(napi_env env, napi_callback_info info) AsyncCallbackSmartReminderEnabled *asynccallbackinfo = new (std::nothrow) AsyncCallbackSmartReminderEnabled {.env = env, .asyncWork = nullptr, .params = params}; if (!asynccallbackinfo) { + Common::NapiThrow(env, ERROR_INTERNAL_ERROR); return Common::JSParaError(env, nullptr); } napi_value promise = nullptr; diff --git a/frameworks/js/napi/src/manager/napi_disturb_mode.cpp b/frameworks/js/napi/src/manager/napi_disturb_mode.cpp index b37508f04..14b50ed2e 100644 --- a/frameworks/js/napi/src/manager/napi_disturb_mode.cpp +++ b/frameworks/js/napi/src/manager/napi_disturb_mode.cpp @@ -32,6 +32,7 @@ napi_value NapiSetDoNotDisturbDate(napi_env env, napi_callback_info info) AsyncCallbackInfoSetDoNotDisturb *asynccallbackinfo = new (std::nothrow) AsyncCallbackInfoSetDoNotDisturb {.env = env, .asyncWork = nullptr, .params = params}; if (!asynccallbackinfo) { + Common::NapiThrow(env, ERROR_INTERNAL_ERROR); return Common::JSParaError(env, params.callback); } napi_value promise = nullptr; @@ -96,6 +97,7 @@ napi_value NapiAddDoNotDisturbProfiles(napi_env env, napi_callback_info info) AsyncCallbackInfoDoNotDisturbProfile *asynccallbackinfo = new (std::nothrow) AsyncCallbackInfoDoNotDisturbProfile{.env = env, .asyncWork = nullptr, .profiles = profiles}; if (!asynccallbackinfo) { + Common::NapiThrow(env, ERROR_INTERNAL_ERROR); return Common::JSParaError(env, nullptr); } napi_value promise = nullptr; @@ -141,6 +143,7 @@ napi_value NapiRemoveDoNotDisturbProfiles(napi_env env, napi_callback_info info) AsyncCallbackInfoDoNotDisturbProfile *asynccallbackinfo = new (std::nothrow) AsyncCallbackInfoDoNotDisturbProfile{.env = env, .asyncWork = nullptr, .profiles = profiles}; if (!asynccallbackinfo) { + Common::NapiThrow(env, ERROR_INTERNAL_ERROR); return Common::JSParaError(env, nullptr); } napi_value promise = nullptr; @@ -214,6 +217,7 @@ napi_value NapiGetDoNotDisturbDate(napi_env env, napi_callback_info info) AsyncCallbackInfoGetDoNotDisturb *asynccallbackinfo = new (std::nothrow) AsyncCallbackInfoGetDoNotDisturb {.env = env, .asyncWork = nullptr, .params = params}; if (!asynccallbackinfo) { + Common::NapiThrow(env, ERROR_INTERNAL_ERROR); return Common::JSParaError(env, params.callback); } napi_value promise = nullptr; @@ -273,6 +277,7 @@ napi_value NapiSupportDoNotDisturbMode(napi_env env, napi_callback_info info) .env = env, .asyncWork = nullptr, .callback = callback}; if (!asynccallbackinfo) { + Common::NapiThrow(env, ERROR_INTERNAL_ERROR); return Common::JSParaError(env, callback); } napi_value promise = nullptr; diff --git a/frameworks/js/napi/src/manager/napi_enable_notification.cpp b/frameworks/js/napi/src/manager/napi_enable_notification.cpp index cc454cd4b..6bf28636e 100644 --- a/frameworks/js/napi/src/manager/napi_enable_notification.cpp +++ b/frameworks/js/napi/src/manager/napi_enable_notification.cpp @@ -23,6 +23,9 @@ #include "js_ans_dialog_callback.h" #include "common_event_manager.h" +constexpr int32_t CRASH_CODE = 2; +constexpr int32_t REMOVE_CODE = 3; + namespace OHOS { namespace NotificationNapi { const int IS_NOTIFICATION_ENABLE_MAX_PARA = 2; @@ -58,6 +61,7 @@ napi_value NapiEnableNotification(napi_env env, napi_callback_info info) AsyncCallbackInfoEnable *asynccallbackinfo = new (std::nothrow) AsyncCallbackInfoEnable {.env = env, .asyncWork = nullptr, .params = params}; if (!asynccallbackinfo) { + Common::NapiThrow(env, ERROR_INTERNAL_ERROR); return Common::JSParaError(env, params.callback); } napi_value promise = nullptr; @@ -129,6 +133,7 @@ __attribute__((no_sanitize("cfi"))) napi_value NapiIsNotificationEnabled(napi_en new (std::nothrow) AsyncCallbackInfoIsEnable {.env = env, .asyncWork = nullptr, .params = params}; if (!asynccallbackinfo) { ANS_LOGD("Asynccallbackinfo is nullptr."); + Common::NapiThrow(env, ERROR_INTERNAL_ERROR); return Common::JSParaError(env, params.callback); } napi_value promise = nullptr; @@ -250,7 +255,7 @@ void NapiAsyncCompleteCallbackRequestEnableNotification(napi_env env, void *data napi_value NapiRequestEnableNotification(napi_env env, napi_callback_info info) { - ANS_LOGD("enter"); + ANS_LOGI("NapiRequestEnableNotification enter"); IsEnableParams params {}; if (ParseRequestEnableParameters(env, info, params) == nullptr) { Common::NapiThrow(env, ERROR_PARAM_INVALID); @@ -260,6 +265,7 @@ napi_value NapiRequestEnableNotification(napi_env env, napi_callback_info info) AsyncCallbackInfoIsEnable *asynccallbackinfo = new (std::nothrow) AsyncCallbackInfoIsEnable { .env = env, .params = params, .newInterface = true}; if (!asynccallbackinfo) { + Common::NapiThrow(env, ERROR_INTERNAL_ERROR); return Common::JSParaError(env, params.callback); } napi_value promise = nullptr; @@ -297,7 +303,7 @@ napi_value NapiRequestEnableNotification(napi_env env, napi_callback_info info) asynccallbackinfo->info.errorCode = ERR_ANS_DIALOG_POP_SUCCEEDED; } else { asynccallbackinfo->info.errorCode = ERROR_INTERNAL_ERROR; - NotificationHelper::RemoveEnableNotificationDialog(); + SendDialogEvent(bundleName, REMOVE_CODE); } } else { ANS_LOGD("un stage mode"); @@ -447,6 +453,7 @@ napi_value NapiGetAllNotificationEnabledBundles(napi_env env, napi_callback_info new (std::nothrow) AsyncCallbackInfoEnableStatus{ .env = env, .asyncWork = nullptr }; if (asynccallbackinfo == nullptr) { ANS_LOGE("asynccallbackinfo is nullptr"); + Common::NapiThrow(env, ERROR_INTERNAL_ERROR); return Common::NapiGetUndefined(env); } napi_value promise = nullptr; @@ -559,6 +566,28 @@ bool CreateUIExtension(std::shared_ptr context, s return true; } +void SendDialogEvent(std::string &bundleName, int32_t code) +{ + ANS_LOGD("SendDialogEvent start"); + if (bundleName.empty()) { + ANS_LOGE("SendDialogEvent bundleName is nullptr"); + return; + } + std::string action = "OnNotificationServiceDialogClicked"; + + EventFwk::Want want; + want.SetAction(action); + + EventFwk::CommonEventData commonData; + commonData.SetWant(want); + commonData.SetCode(code); + commonData.SetData(bundleName); + if (!EventFwk::CommonEventManager::PublishCommonEvent(commonData)) { + ANS_LOGE("PublishCommonEvent failed"); + } + ANS_LOGD("SendDialogEvent end"); +} + void SetEnableParam(IsEnableParams ¶ms, const napi_env &env, napi_value &object) { auto context = OHOS::AbilityRuntime::GetStageModeContext(env, object); @@ -611,7 +640,7 @@ void ModalExtensionCallback::OnError(int32_t code, const std::string& name, cons { ANS_LOGE("OnError, name = %{public}s, message = %{public}s", name.c_str(), message.c_str()); ReleaseOrErrorHandle(code); - NotificationHelper::RemoveEnableNotificationDialog(); + SendDialogEvent(this->bundleName_, CRASH_CODE); } /* diff --git a/frameworks/js/napi/src/manager/napi_get_active.cpp b/frameworks/js/napi/src/manager/napi_get_active.cpp index 7d73cf03b..4fc167a53 100644 --- a/frameworks/js/napi/src/manager/napi_get_active.cpp +++ b/frameworks/js/napi/src/manager/napi_get_active.cpp @@ -86,6 +86,7 @@ napi_value NapiGetAllActiveNotifications(napi_env env, napi_callback_info info) auto asynccallbackinfo = new (std::nothrow) AsyncCallbackInfoActive {.env = env, .asyncWork = nullptr}; if (!asynccallbackinfo) { ANS_LOGD("Asynccallbackinfo is nullptr."); + Common::NapiThrow(env, ERROR_INTERNAL_ERROR); return Common::JSParaError(env, callback); } napi_value promise = nullptr; @@ -183,6 +184,7 @@ napi_value NapiGetActiveNotifications(napi_env env, napi_callback_info info) auto asynccallbackinfo = new (std::nothrow) AsyncCallbackInfoActive {.env = env, .asyncWork = nullptr}; if (!asynccallbackinfo) { ANS_LOGD("Create asynccallbackinfo failed."); + Common::NapiThrow(env, ERROR_INTERNAL_ERROR); return Common::JSParaError(env, callback); } napi_value promise = nullptr; diff --git a/frameworks/js/napi/src/manager/napi_local_live_view.cpp b/frameworks/js/napi/src/manager/napi_local_live_view.cpp index 174b3da0f..6d5845d32 100644 --- a/frameworks/js/napi/src/manager/napi_local_live_view.cpp +++ b/frameworks/js/napi/src/manager/napi_local_live_view.cpp @@ -165,6 +165,7 @@ napi_value NapiTriggerLocalLiveView(napi_env env, napi_callback_info info) .env = env, .asyncWork = nullptr, }; if (!asynccallbackinfo) { + Common::NapiThrow(env, ERROR_INTERNAL_ERROR); return Common::JSParaError(env, callback); } diff --git a/frameworks/js/napi/src/manager/napi_open_settings.cpp b/frameworks/js/napi/src/manager/napi_open_settings.cpp new file mode 100644 index 000000000..cda74b8d7 --- /dev/null +++ b/frameworks/js/napi/src/manager/napi_open_settings.cpp @@ -0,0 +1,403 @@ +/* + * Copyright (c) 2024-2024 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "napi_open_settings.h" +#include +#include "napi_base_context.h" +#include "ans_inner_errors.h" + +namespace OHOS { +namespace NotificationNapi { +const int OPEN_NOTIFICATION_SETTINGS_MAX_PARA = 1; +static napi_env env_ = nullptr; +static AsyncCallbackInfoOpenSettings* callbackInfo_ = nullptr; +static JsAnsCallbackComplete* complete_ = nullptr; +static std::atomic isExist = false; + +void NapiAsyncCompleteCallbackOpenSettings(napi_env env, void *data) +{ + ANS_LOGD("enter NapiAsyncCompleteCallbackOpenSettings"); + if (data == nullptr) { + ANS_LOGE("Invalid async callback data."); + return; + } + auto* asynccallbackinfo = static_cast(data); + napi_value result = nullptr; + napi_get_undefined(env, &result); + int32_t errorCode = ERR_OK; + if (asynccallbackinfo->info.errorCode == ERROR_SETTING_WINDOW_EXIST) { + errorCode = ERROR_SETTING_WINDOW_EXIST; + } else { + errorCode = asynccallbackinfo->info.errorCode == + ERR_OK ? ERR_OK : Common::ErrorToExternal(asynccallbackinfo->info.errorCode); + } + if (asynccallbackinfo->info.isCallback) { + Common::SetCallback(env, asynccallbackinfo->info.callback, errorCode, result, true); + } else { + Common::SetPromise(env, asynccallbackinfo->info.deferred, errorCode, result, true); + } + if (asynccallbackinfo->info.callback != nullptr) { + napi_delete_reference(env, asynccallbackinfo->info.callback); + } + napi_delete_async_work(env, asynccallbackinfo->asyncWork); + delete asynccallbackinfo; +} + +napi_value NapiOpenNotificationSettings(napi_env env, napi_callback_info info) +{ + ANS_LOGD("NapiOpenNotificationSettings start"); + OpenSettingsParams params {}; + if (ParseOpenSettingsParameters(env, info, params) == nullptr) { + Common::NapiThrow(env, ERROR_PARAM_INVALID); + return Common::NapiGetUndefined(env); + } + + AsyncCallbackInfoOpenSettings *asynccallbackinfo = new (std::nothrow) AsyncCallbackInfoOpenSettings { + .env = env, .params = params}; + if (!asynccallbackinfo) { + return Common::JSParaError(env, nullptr); + } + napi_value promise = nullptr; + Common::PaddingCallbackPromiseInfo(env, nullptr, asynccallbackinfo->info, promise); + + napi_value resourceName = nullptr; + napi_create_string_latin1(env, "openNotificationSettings", NAPI_AUTO_LENGTH, &resourceName); + + auto createExtension = [](napi_env env, void* data) { + ANS_LOGD("enter"); + if (data == nullptr) { + ANS_LOGE("data is invalid"); + return; + } + auto* asynccallbackinfo = static_cast(data); + + if (asynccallbackinfo->params.context != nullptr) { + ANS_LOGD("stage mode"); + std::string bundleName {""}; + if (isExist.exchange(true)) { + ANS_LOGE("SettingsUIExtension existed"); + asynccallbackinfo->info.errorCode = ERROR_SETTING_WINDOW_EXIST; + return; + } + bool success = CreateSettingsUIExtension(asynccallbackinfo->params.context, bundleName); + if (success) { + asynccallbackinfo->info.errorCode = ERR_ANS_DIALOG_POP_SUCCEEDED; + } else { + asynccallbackinfo->info.errorCode = ERROR_INTERNAL_ERROR; + } + } else { + ANS_LOGD("un stage mode"); + } + ANS_LOGI("done, code is %{public}d.", asynccallbackinfo->info.errorCode); + }; + auto jsCb = [](napi_env env, napi_status status, void* data) { + ANS_LOGD("enter jsCb"); + auto* asynccallbackinfo = static_cast(data); + ErrCode errCode = asynccallbackinfo->info.errorCode; + if (errCode != ERR_ANS_DIALOG_POP_SUCCEEDED) { + ANS_LOGE("error, code is %{public}d.", errCode); + NapiAsyncCompleteCallbackOpenSettings(env, static_cast(asynccallbackinfo)); + isExist.store(false); + return; + } + if (!Init(env, asynccallbackinfo, NapiAsyncCompleteCallbackOpenSettings)) { + ANS_LOGE("error"); + asynccallbackinfo->info.errorCode = ERROR_INTERNAL_ERROR; + NapiAsyncCompleteCallbackOpenSettings(env, static_cast(asynccallbackinfo)); + return; + } + ANS_LOGD("jsCb end"); + }; + + // Asynchronous function call + napi_create_async_work(env, + nullptr, + resourceName, + createExtension, + jsCb, + static_cast(asynccallbackinfo), + &asynccallbackinfo->asyncWork); + + napi_queue_async_work_with_qos(env, asynccallbackinfo->asyncWork, napi_qos_user_initiated); + ANS_LOGD("NapiOpenNotificationSettings end"); + return promise; +} + +napi_value ParseOpenSettingsParameters(const napi_env &env, const napi_callback_info &info, OpenSettingsParams ¶ms) +{ + ANS_LOGD("enter"); + + size_t argc = OPEN_NOTIFICATION_SETTINGS_MAX_PARA; + napi_value argv[OPEN_NOTIFICATION_SETTINGS_MAX_PARA] = {nullptr}; + napi_value thisVar = nullptr; + NAPI_CALL(env, napi_get_cb_info(env, info, &argc, argv, &thisVar, NULL)); + + if (argc == 0) { + return Common::NapiGetNull(env); + } + + // argv[0]: context + napi_valuetype valuetype = napi_undefined; + NAPI_CALL(env, napi_typeof(env, argv[PARAM0], &valuetype)); + if ((valuetype != napi_object) && (valuetype != napi_function)) { + ANS_LOGW("Wrong argument type. Function or object expected. Excute promise."); + return Common::NapiGetNull(env); + } + if (valuetype == napi_object) { + bool stageMode = false; + napi_status status = OHOS::AbilityRuntime::IsStageContext(env, argv[PARAM0], stageMode); + if (status == napi_ok && stageMode) { + auto context = OHOS::AbilityRuntime::GetStageModeContext(env, argv[PARAM0]); + sptr callerToken = context->GetToken(); + params.context = context; + } else { + ANS_LOGE("Only support stage mode"); + std::string msg = "Incorrect parameter types.Only support stage mode."; + Common::NapiThrow(env, ERROR_PARAM_INVALID, msg); + return nullptr; + } + } + return Common::NapiGetNull(env); +} + +bool CreateSettingsUIExtension(std::shared_ptr context, std::string &bundleName) +{ + if (context == nullptr) { + ANS_LOGE("Get context failed"); + return false; + } + + std::shared_ptr abilityContext = + OHOS::AbilityRuntime::Context::ConvertTo(context); + if (abilityContext == nullptr) { + ANS_LOGE("abilityContext is null"); + return false; + } + auto uiContent = abilityContext->GetUIContent(); + if (uiContent == nullptr) { + ANS_LOGE("uiContent is null"); + return false; + } + + AAFwk::Want want; + std::string targetBundleName = "com.ohos.sceneboard"; + std::string targetAbilityName = "NotificationManangerUIExtensionAbility"; + want.SetElementName(targetBundleName, targetAbilityName); + + std::string typeKey = "ability.want.params.uiExtensionType"; + std::string typeValue = "sys/commonUI"; + want.SetParam(typeKey, typeValue); + + auto uiExtCallback = std::make_shared(); + uiExtCallback->SetAbilityContext(abilityContext); + uiExtCallback->SetBundleName(bundleName); + Ace::ModalUIExtensionCallbacks uiExtensionCallbacks = { + .onRelease = + std::bind(&SettingsModalExtensionCallback::OnRelease, uiExtCallback, std::placeholders::_1), + .onResult = std::bind(&SettingsModalExtensionCallback::OnResult, uiExtCallback, + std::placeholders::_1, std::placeholders::_2), + .onReceive = + std::bind(&SettingsModalExtensionCallback::OnReceive, uiExtCallback, std::placeholders::_1), + .onError = std::bind(&SettingsModalExtensionCallback::OnError, uiExtCallback, + std::placeholders::_1, std::placeholders::_2, std::placeholders::_3), + .onRemoteReady = + std::bind(&SettingsModalExtensionCallback::OnRemoteReady, uiExtCallback, std::placeholders::_1), + .onDestroy = std::bind(&SettingsModalExtensionCallback::OnDestroy, uiExtCallback), + }; + + Ace::ModalUIExtensionConfig config; + config.isProhibitBack = true; + + int32_t sessionId = uiContent->CreateModalUIExtension(want, uiExtensionCallbacks, config); + ANS_LOGI("Create end, sessionId: %{public}d", sessionId); + if (sessionId == 0) { + ANS_LOGE("Create component failed, sessionId is 0"); + return false; + } + uiExtCallback->SetSessionId(sessionId); + return true; +} + +bool Init(napi_env env, AsyncCallbackInfoOpenSettings* callbackInfo, + JsAnsCallbackComplete complete) +{ + ANS_LOGD("enter JsAnsCallback::Init"); + if (env == nullptr || callbackInfo == nullptr || complete == nullptr) { + ANS_LOGE("invalid data"); + return false; + } + env_ = env; + callbackInfo_ = callbackInfo; + complete_ = complete; + return true; +} + +void ProcessStatusChanged(int32_t code) +{ + ANS_LOGD("enter"); + std::unique_ptr callbackInfo(callbackInfo_); + if (env_ == nullptr || callbackInfo == nullptr || complete_ == nullptr) { + ANS_LOGE("invalid data"); + return; + } + + callbackInfo->info.errorCode = code; + + uv_loop_s* loop = nullptr; + napi_get_uv_event_loop(env_, &loop); + if (loop == nullptr) { + ANS_LOGE("loop is nullptr"); + return; + } + + auto work = std::make_unique(); + struct WorkData { + decltype(env_) env = nullptr; + decltype(callbackInfo_) callbackInfo = nullptr; + decltype(complete_) complete = nullptr; + }; + auto workData = std::make_unique(); + workData->env = env_; + workData->callbackInfo = callbackInfo_; + workData->complete = complete_; + + work->data = static_cast(workData.get()); + auto jsCb = [](uv_work_t* work, int status) { + ANS_LOGD("enter ProcessStatusChanged jsCb"); + std::unique_ptr workSP(work); + if (work == nullptr || work->data == nullptr) { + ANS_LOGE("invalid data"); + return; + } + auto* data = static_cast(work->data); + std::unique_ptr dataSP(data); + std::unique_ptr callbackInfoSP(data->callbackInfo); + if (data->env == nullptr || + data->callbackInfo == nullptr || + data->complete == nullptr) { + return; + } + auto* callbackInfoPtr = callbackInfoSP.release(); + data->complete(data->env, static_cast(callbackInfoPtr)); + }; + + int ret = uv_queue_work_with_qos(loop, + work.get(), + [](uv_work_t *work) {}, + jsCb, + uv_qos_user_initiated); + if (ret != 0) { + ANS_LOGE("uv_queue_work failed"); + return; + } + callbackInfo.release(); + workData.release(); + work.release(); +} + +SettingsModalExtensionCallback::SettingsModalExtensionCallback() +{} + +SettingsModalExtensionCallback::~SettingsModalExtensionCallback() +{} + + +/* + * when UIExtensionAbility use terminateSelfWithResult + */ +void SettingsModalExtensionCallback::OnResult(int32_t resultCode, const AAFwk::Want& result) +{ + ANS_LOGD("OnResult"); +} + +/* + * when UIExtensionAbility send message to UIExtensionComponent + */ +void SettingsModalExtensionCallback::OnReceive(const AAFwk::WantParams& receive) +{ + ANS_LOGD("OnReceive"); +} + +/* + * when UIExtensionAbility disconnect or use terminate or process die + * releaseCode is 0 when process normal exit + */ +void SettingsModalExtensionCallback::OnRelease(int32_t releaseCode) +{ + ANS_LOGD("OnRelease"); + ReleaseOrErrorHandle(releaseCode); +} + +/* + * when UIExtensionComponent init or turn to background or destroy UIExtensionAbility occur error + */ +void SettingsModalExtensionCallback::OnError(int32_t code, const std::string& name, const std::string& message) +{ + ANS_LOGE("OnError, code = %{public}d,name = %{public}s, message = %{public}s", code, name.c_str(), message.c_str()); + ReleaseOrErrorHandle(code); + ProcessStatusChanged(code); +} + +/* + * when UIExtensionComponent connect to UIExtensionAbility, ModalUIExtensionProxy will init, + * UIExtensionComponent can send message to UIExtensionAbility by ModalUIExtensionProxy + */ +void SettingsModalExtensionCallback::OnRemoteReady(const std::shared_ptr& uiProxy) +{ + ANS_LOGI("OnRemoteReady"); + ProcessStatusChanged(0); +} + +/* + * when UIExtensionComponent destructed + */ +void SettingsModalExtensionCallback::OnDestroy() +{ + ANS_LOGI("OnDestroy"); + isExist.store(false); +} + + +void SettingsModalExtensionCallback::SetSessionId(int32_t sessionId) +{ + this->sessionId_ = sessionId; +} + +void SettingsModalExtensionCallback::SetBundleName(std::string bundleName) +{ + this->bundleName_ = bundleName; +} + +void SettingsModalExtensionCallback::SetAbilityContext( + std::shared_ptr abilityContext) +{ + this->abilityContext_ = abilityContext; +} + +void SettingsModalExtensionCallback::ReleaseOrErrorHandle(int32_t code) +{ + ANS_LOGD("ReleaseOrErrorHandle start"); + Ace::UIContent* uiContent = this->abilityContext_->GetUIContent(); + if (uiContent == nullptr) { + ANS_LOGE("uiContent is null"); + return; + } + uiContent->CloseModalUIExtension(this->sessionId_); + ANS_LOGD("ReleaseOrErrorHandle end"); + return; +} + +} // namespace NotificationNapi +} // namespace OHOS \ No newline at end of file diff --git a/frameworks/js/napi/src/manager/napi_publish.cpp b/frameworks/js/napi/src/manager/napi_publish.cpp index e65be6f77..8d139fd4b 100644 --- a/frameworks/js/napi/src/manager/napi_publish.cpp +++ b/frameworks/js/napi/src/manager/napi_publish.cpp @@ -34,6 +34,7 @@ napi_value NapiPublish(napi_env env, napi_callback_info info) auto asynccallbackinfo = new (std::nothrow) AsyncCallbackInfoPublish {.env = env, .asyncWork = nullptr}; if (!asynccallbackinfo) { ANS_LOGD("asynccallbackinfo is nullptr."); + Common::NapiThrow(env, ERROR_INTERNAL_ERROR); return Common::JSParaError(env, params.callback); } asynccallbackinfo->request = params.request; @@ -157,6 +158,7 @@ napi_value NapiPublishAsBundle(napi_env env, napi_callback_info info) napi_value promise = nullptr; auto asynccallbackinfo = new (std::nothrow) AsyncCallbackInfoPublish {.env = env, .asyncWork = nullptr}; if (!asynccallbackinfo) { + Common::NapiThrow(env, ERROR_INTERNAL_ERROR); return Common::JSParaError(env, params.callback); } diff --git a/frameworks/js/napi/src/manager/napi_push.cpp b/frameworks/js/napi/src/manager/napi_push.cpp index 5d6a27796..e216dc2cf 100644 --- a/frameworks/js/napi/src/manager/napi_push.cpp +++ b/frameworks/js/napi/src/manager/napi_push.cpp @@ -43,13 +43,21 @@ void NapiPush::Finalizer(napi_env env, void *data, void *hint) napi_value NapiPush::RegisterPushCallback(napi_env env, napi_callback_info info) { NapiPush *me = CheckParamsAndGetThis(env, info); - return (me != nullptr) ? me->OnRegisterPushCallback(env, info) : nullptr; + if (me == nullptr) { + Common::NapiThrow(env, ERROR_PARAM_INVALID); + return nullptr; + } + return me->OnRegisterPushCallback(env, info); } napi_value NapiPush::UnregisterPushCallback(napi_env env, napi_callback_info info) { NapiPush *me = CheckParamsAndGetThis(env, info); - return (me != nullptr) ? me->OnUnregisterPushCallback(env, info) : nullptr; + if (me == nullptr) { + Common::NapiThrow(env, ERROR_PARAM_INVALID); + return nullptr; + } + return me->OnUnregisterPushCallback(env, info); } napi_value NapiPush::OnRegisterPushCallback(napi_env env, const napi_callback_info info) @@ -161,8 +169,6 @@ napi_value NapiPush::OnUnregisterPushCallback(napi_env env, const napi_callback_ } NotificationHelper::UnregisterPushCallback(); - delete jsPushCallBack_; - jsPushCallBack_ = nullptr; return undefined; } diff --git a/frameworks/js/napi/src/manager/napi_remove_group.cpp b/frameworks/js/napi/src/manager/napi_remove_group.cpp index 07845ea47..cf504b265 100644 --- a/frameworks/js/napi/src/manager/napi_remove_group.cpp +++ b/frameworks/js/napi/src/manager/napi_remove_group.cpp @@ -121,6 +121,7 @@ napi_value NapiRemoveGroupByBundle(napi_env env, napi_callback_info info) AsyncCallbackInfoRemoveGroupByBundle *asynccallbackinfo = new (std::nothrow) AsyncCallbackInfoRemoveGroupByBundle {.env = env, .asyncWork = nullptr, .params = params}; if (!asynccallbackinfo) { + Common::NapiThrow(env, ERROR_INTERNAL_ERROR); return Common::JSParaError(env, params.callback); } napi_value promise = nullptr; diff --git a/frameworks/js/napi/src/manager/napi_slot.cpp b/frameworks/js/napi/src/manager/napi_slot.cpp index afdd23525..df9d4aa0d 100644 --- a/frameworks/js/napi/src/manager/napi_slot.cpp +++ b/frameworks/js/napi/src/manager/napi_slot.cpp @@ -103,6 +103,7 @@ napi_value NapiAddSlots(napi_env env, napi_callback_info info) new (std::nothrow) AsyncCallbackInfoAddSlots {.env = env, .asyncWork = nullptr, .slots = paras.slots}; if (!asynccallbackinfo) { ANS_LOGD("Asynccallbackinfo is nullptr."); + Common::NapiThrow(env, ERROR_INTERNAL_ERROR); return Common::JSParaError(env, paras.callback); } napi_value promise = nullptr; @@ -300,6 +301,7 @@ napi_value NapiGetSlotNumByBundle(napi_env env, napi_callback_info info) AsyncCallbackInfoGetSlotNumByBundle *asynccallbackinfo = new (std::nothrow) AsyncCallbackInfoGetSlotNumByBundle {.env = env, .asyncWork = nullptr, .params = params}; if (!asynccallbackinfo) { + Common::NapiThrow(env, ERROR_INTERNAL_ERROR); return Common::JSParaError(env, params.callback); } napi_value promise = nullptr; @@ -502,6 +504,7 @@ napi_value NapiGetSlotsByBundle(napi_env env, napi_callback_info info) AsyncCallbackInfoGetSlotsByBundle *asynccallbackinfo = new (std::nothrow) AsyncCallbackInfoGetSlotsByBundle {.env = env, .asyncWork = nullptr, .params = params}; if (!asynccallbackinfo) { + Common::NapiThrow(env, ERROR_INTERNAL_ERROR); return Common::JSParaError(env, params.callback); } napi_value promise = nullptr; @@ -580,6 +583,7 @@ napi_value NapiGetSlotByBundle(napi_env env, napi_callback_info info) AsyncCallbackInfoGetSlotByBundle *asynccallbackinfo = new (std::nothrow) AsyncCallbackInfoGetSlotByBundle {.env = env, .asyncWork = nullptr, .params = params}; if (!asynccallbackinfo) { + Common::NapiThrow(env, ERROR_INTERNAL_ERROR); return Common::JSParaError(env, params.callback); } napi_value promise = nullptr; @@ -745,6 +749,7 @@ napi_value NapiEnableNotificationSlot(napi_env env, napi_callback_info info) AsyncCallbackInfoInfoEnableSlot *asynccallbackinfo = new (std::nothrow) AsyncCallbackInfoInfoEnableSlot {.env = env, .asyncWork = nullptr, .params = params}; if (!asynccallbackinfo) { + Common::NapiThrow(env, ERROR_INTERNAL_ERROR); return Common::JSParaError(env, params.callback); } napi_value promise = nullptr; @@ -808,6 +813,7 @@ napi_value NapiIsEnableNotificationSlot(napi_env env, napi_callback_info info) AsyncCallbackInfoInfoIsEnableSlot *asynccallbackinfo = new (std::nothrow) AsyncCallbackInfoInfoIsEnableSlot {.env = env, .asyncWork = nullptr, .params = params}; if (!asynccallbackinfo) { + Common::NapiThrow(env, ERROR_INTERNAL_ERROR); return Common::JSParaError(env, params.callback); } napi_value promise = nullptr; @@ -870,6 +876,7 @@ napi_value NapiSetSlotFlagsByBundle(napi_env env, napi_callback_info info) AsyncCallbackInfoSetSlotFlagsByBundle *asynccallbackinfo = new (std::nothrow) AsyncCallbackInfoSetSlotFlagsByBundle {.env = env, .asyncWork = nullptr, .params = params}; if (!asynccallbackinfo) { + Common::NapiThrow(env, ERROR_INTERNAL_ERROR); return Common::JSParaError(env, params.callback); } napi_value promise = nullptr; @@ -930,6 +937,7 @@ napi_value NapiGetSlotFlagsByBundle(napi_env env, napi_callback_info info) AsyncCallbackInfoGetSlotFlagsByBundle *asynccallbackinfo = new (std::nothrow) AsyncCallbackInfoGetSlotFlagsByBundle {.env = env, .asyncWork = nullptr, .params = params}; if (!asynccallbackinfo) { + Common::NapiThrow(env, ERROR_INTERNAL_ERROR); return Common::JSParaError(env, params.callback); } napi_value promise = nullptr; diff --git a/frameworks/js/napi/src/manager/napi_sync_config.cpp b/frameworks/js/napi/src/manager/napi_sync_config.cpp index 45860a3ae..c90484908 100644 --- a/frameworks/js/napi/src/manager/napi_sync_config.cpp +++ b/frameworks/js/napi/src/manager/napi_sync_config.cpp @@ -127,6 +127,7 @@ napi_value NapiSetAdditionConfig(napi_env env, napi_callback_info info) .params = paras }; if (!asynccallbackinfo) { + Common::NapiThrow(env, ERROR_INTERNAL_ERROR); return Common::JSParaError(env, paras.callback); } napi_value promise = nullptr; diff --git a/frameworks/js/napi/src/subscribe.cpp b/frameworks/js/napi/src/subscribe.cpp index f6b62e3f1..4908ff874 100644 --- a/frameworks/js/napi/src/subscribe.cpp +++ b/frameworks/js/napi/src/subscribe.cpp @@ -304,7 +304,12 @@ void SubscriberInstance::OnBatchCanceled(const std::vectorGetKey().size()); ANS_LOGI("OnBatchCancel deleteReason = %{public}d", deleteReason); - + std::string notificationKeys = ""; + for (auto notification : requestList) { + notificationKeys.append(notification->GetKey()).append("-"); + } + ANS_LOGI("OnBatchCancel. cancel keys = %{public}s", notificationKeys.c_str()); + NotificationReceiveDataWorker *dataWorker = new (std::nothrow) NotificationReceiveDataWorker(); if (dataWorker == nullptr) { ANS_LOGE("DataWorker is nullptr."); diff --git a/frameworks/js/napi/src/subscribe/napi_remove.cpp b/frameworks/js/napi/src/subscribe/napi_remove.cpp index 798edbac5..e8e24f01c 100644 --- a/frameworks/js/napi/src/subscribe/napi_remove.cpp +++ b/frameworks/js/napi/src/subscribe/napi_remove.cpp @@ -72,6 +72,7 @@ napi_value NapiRemove(napi_env env, napi_callback_info info) } auto removeInfo = new (std::nothrow) AsyncCallbackInfoRemove {.env = env, .asyncWork = nullptr, .params = params}; if (!removeInfo) { + Common::NapiThrow(env, ERROR_INTERNAL_ERROR); return Common::JSParaError(env, params.callback); } napi_value promise = nullptr; @@ -103,6 +104,7 @@ napi_value NapiRemoveAll(napi_env env, napi_callback_info info) AsyncCallbackInfoRemove *asynccallbackinfo = new (std::nothrow) AsyncCallbackInfoRemove {.env = env, .asyncWork = nullptr, .params = params}; if (!asynccallbackinfo) { + Common::NapiThrow(env, ERROR_INTERNAL_ERROR); return Common::JSParaError(env, params.callback); } napi_value promise = nullptr; @@ -115,7 +117,7 @@ napi_value NapiRemoveAll(napi_env env, napi_callback_info info) nullptr, resourceName, [](napi_env env, void *data) { - ANS_LOGD("NapiRemoveAll work excute."); + ANS_LOGI("NapiRemoveAll work excute."); AsyncCallbackInfoRemove *asynccallbackinfo = static_cast(data); if (asynccallbackinfo) { if (asynccallbackinfo->params.bundleAndKeyInfo.has_value()) { diff --git a/frameworks/js/napi/src/subscribe/napi_subscribe.cpp b/frameworks/js/napi/src/subscribe/napi_subscribe.cpp index 1d3bf9d58..e2e417201 100644 --- a/frameworks/js/napi/src/subscribe/napi_subscribe.cpp +++ b/frameworks/js/napi/src/subscribe/napi_subscribe.cpp @@ -44,6 +44,7 @@ napi_value NapiSubscribe(napi_env env, napi_callback_info info) delete objectInfo; objectInfo = nullptr; } + Common::NapiThrow(env, ERROR_INTERNAL_ERROR); return Common::JSParaError(env, callback); } napi_value promise = nullptr; @@ -133,6 +134,7 @@ napi_value NapiSubscribeSelf(napi_env env, napi_callback_info info) delete objectInfo; objectInfo = nullptr; } + Common::NapiThrow(env, ERROR_INTERNAL_ERROR); return Common::JSParaError(env, callback); } napi_value promise = nullptr; @@ -201,6 +203,7 @@ napi_value NapiUnsubscribe(napi_env env, napi_callback_info info) AsyncCallbackInfoUnsubscribe *asynccallbackinfo = new (std::nothrow) AsyncCallbackInfoUnsubscribe {.env = env, .asyncWork = nullptr, .objectInfo = paras.objectInfo}; if (!asynccallbackinfo) { + Common::NapiThrow(env, ERROR_INTERNAL_ERROR); return Common::JSParaError(env, paras.callback); } napi_value promise = nullptr; diff --git a/hisysevent.yaml b/hisysevent.yaml index 17b330376..7ececce79 100644 --- a/hisysevent.yaml +++ b/hisysevent.yaml @@ -103,7 +103,6 @@ REMOVE: ALARM_TRIGGER: __BASE: {type: STATISTIC, level: MINOR, tag: PowerStats, desc: alarm trigger} - PID: {type: INT32, desc: thread pid} UID: {type: INT32, desc: package uid} NAME: {type: STRING, desc: call package name} TYPE: {type: INT32, desc: reminder type} diff --git a/interfaces/inner_api/notification_capsule.h b/interfaces/inner_api/notification_capsule.h index 2b1ec578a..a6dea0d22 100644 --- a/interfaces/inner_api/notification_capsule.h +++ b/interfaces/inner_api/notification_capsule.h @@ -16,7 +16,7 @@ #ifndef BASE_NOTIFICATION_DISTRIBUTED_NOTIFICATION_SERVICE_INTERFACES_INNER_API_CAPSULE_H #define BASE_NOTIFICATION_DISTRIBUTED_NOTIFICATION_SERVICE_INTERFACES_INNER_API_CAPSULE_H -#include "foundation/multimedia/image_framework/interfaces/innerkits/include/pixel_map.h" +#include "pixel_map.h" #include "notification_json_convert.h" #include "parcel.h" #include @@ -107,6 +107,7 @@ public: void ResetIcon(); private: + /** * @brief Read a NotificationConversationalMessage object from a Parcel. * @@ -124,4 +125,4 @@ private: } // namespace Notification } // namespace OHOS -#endif // BASE_NOTIFICATION_DISTRIBUTED_NOTIFICATION_SERVICE_INTERFACES_INNER_API_CAPSULE_H \ No newline at end of file +#endif // BASE_NOTIFICATION_DISTRIBUTED_NOTIFICATION_SERVICE_INTERFACES_INNER_API_CAPSULE_H diff --git a/interfaces/inner_api/notification_constant.h b/interfaces/inner_api/notification_constant.h index 0a2c74429..507408478 100644 --- a/interfaces/inner_api/notification_constant.h +++ b/interfaces/inner_api/notification_constant.h @@ -75,6 +75,7 @@ public: LIGHTSCREEN_FLAG = 1 << 3, VIBRATION_FLAG = 1 << 4, STATUSBAR_ICON_FLAG = 1 << 5, + SA_SELF_BANNER_FLAG = 1 << 9, }; enum class VisiblenessType { @@ -144,6 +145,8 @@ public: CLOSE }; + static const int32_t DEFAULT_REASON_DELETE = 0; + /** * Indicates that a notification is deleted because it is clicked. */ @@ -209,6 +212,86 @@ public: */ static const int32_t DISABLE_NOTIFICATION_REASON_DELETE = 13; + /** + * Indicates that a notification is deleted by bundle because the application cancel it. + */ + static const int32_t APP_CANCEL_AS_BUNELE_REASON_DELETE = 14; + + /** + * Indicates that a notification is deleted by agent because the application cancel it. + */ + static const int32_t APP_CANCEL_AS_BUNELE_WITH_AGENT_REASON_DELETE = 15; + + /** + * Indicates that a notification is deleted because the reminder cancel it. + */ + static const int32_t APP_CANCEL_REMINDER_REASON_DELETE = 16; + + /** + * Indicates that a notification is deleted because the application cancel it by group. + */ + static const int32_t APP_CANCEL_GROPU_REASON_DELETE = 17; + + /** + * Indicates that a notification is deleted by group because the system cancel it. + */ + static const int32_t APP_REMOVE_GROUP_REASON_DELETE = 18; + + /** + * Indicates that aLL notification is deleted because the system cancel it. + */ + static const int32_t APP_REMOVE_ALL_REASON_DELETE = 19; + + /** + * Indicates that aLL notification is deleted by userId because the system cancel it. + */ + static const int32_t APP_REMOVE_ALL_USER_REASON_DELETE = 20; + + /** + * Indicates that notification is deleted because eight-hour timer cancel it. + */ + static const int32_t TRIGGER_EIGHT_HOUR_REASON_DELETE = 21; + + /** + * Indicates that notification is deleted because four-hour timer cancel it. + */ + static const int32_t TRIGGER_FOUR_HOUR_REASON_DELETE = 22; + + /** + * Indicates that notification is deleted because ten-minutes timer cancel it. + */ + static const int32_t TRIGGER_TEN_MINUTES_REASON_DELETE = 23; + + /** + * Indicates that notification is deleted because fifteen-minutes timer cancel it. + */ + static const int32_t TRIGGER_FIFTEEN_MINUTES_REASON_DELETE = 24; + + /** + * Indicates that notification is deleted because thirty-minutes timer cancel it. + */ + static const int32_t TRIGGER_THIRTY_MINUTES_REASON_DELETE = 25; + + /** + * Indicates that notification is deleted because startArchive timer cancel it. + */ + static const int32_t TRIGGER_START_ARCHIVE_REASON_DELETE = 26; + + /** + * Indicates that notification is deleted because auto delete timer cancel it. + */ + static const int32_t TRIGGER_AUTO_DELETE_REASON_DELETE = 27; + + /** + * Indicates that notification is deleted because auto packge remove cancel it. + */ + static const int32_t PACKAGE_REMOVE_REASON_DELETE = 28; + + /** + * Indicates that notification is deleted because slot enabled close remove cancel it. + */ + static const int32_t SLOT_ENABLED_REASON_DELETE = 29; + /** * Indicates that a notification is deleted for other reasons. */ diff --git a/interfaces/inner_api/notification_helper.h b/interfaces/inner_api/notification_helper.h index aa47d35df..5b35ec72b 100644 --- a/interfaces/inner_api/notification_helper.h +++ b/interfaces/inner_api/notification_helper.h @@ -299,13 +299,6 @@ public: */ static ErrCode CanPopEnableNotificationDialog(sptr &hostClient, bool &canPop, std::string &bundleName); - - /** - * @brief remove enable notification dialog. - * - * @return Returns remove dialog result. - */ - static ErrCode RemoveEnableNotificationDialog(); /** * @brief Allow the current application to publish notifications on a specified device. diff --git a/interfaces/inner_api/notification_local_live_view_button.h b/interfaces/inner_api/notification_local_live_view_button.h index 70f38f0f6..8f5f33082 100644 --- a/interfaces/inner_api/notification_local_live_view_button.h +++ b/interfaces/inner_api/notification_local_live_view_button.h @@ -16,8 +16,8 @@ #ifndef BASE_NOTIFICATION_DISTRIBUTED_NOTIFICATION_SERVICE_INTERFACES_INNER_API_LOCAL_LIVE_VIEW_BUTTON_H #define BASE_NOTIFICATION_DISTRIBUTED_NOTIFICATION_SERVICE_INTERFACES_INNER_API_LOCAL_LIVE_VIEW_BUTTON_H -#include "base/notification/distributed_notification_service/interfaces/inner_api/notification_button_option.h" -#include "foundation/multimedia/image_framework/interfaces/innerkits/include/pixel_map.h" +#include "notification_button_option.h" +#include "pixel_map.h" #include "message_user.h" #include "notification_json_convert.h" #include "parcel.h" diff --git a/interfaces/inner_api/notification_local_live_view_content.h b/interfaces/inner_api/notification_local_live_view_content.h index 59c6b5662..cd7c18e1c 100644 --- a/interfaces/inner_api/notification_local_live_view_content.h +++ b/interfaces/inner_api/notification_local_live_view_content.h @@ -16,9 +16,9 @@ #ifndef BASE_NOTIFICATION_DISTRIBUTED_NOTIFICATION_SERVICE_INTERFACES_INNER_API_LOCAL_LIVE_VIEW_CONTENT_H #define BASE_NOTIFICATION_DISTRIBUTED_NOTIFICATION_SERVICE_INTERFACES_INNER_API_LOCAL_LIVE_VIEW_CONTENT_H -#include "base/notification/distributed_notification_service/interfaces/inner_api/notification_capsule.h" -#include "base/notification/distributed_notification_service/interfaces/inner_api/notification_progress.h" -#include "base/notification/distributed_notification_service/interfaces/inner_api/notification_local_live_view_button.h" +#include "notification_capsule.h" +#include "notification_progress.h" +#include "notification_local_live_view_button.h" #include "message_user.h" #include "notification_basic_content.h" #include "notification_conversational_message.h" @@ -38,7 +38,7 @@ public: TIME, INITIAL_TIME, }; - + NotificationLocalLiveViewContent() = default; ~NotificationLocalLiveViewContent() = default; @@ -85,7 +85,7 @@ public: * @brief Sets the progress to be included in a local live view notification. * * @param progress Indicates the type to be included. - + */ void SetProgress(NotificationProgress progress); @@ -99,7 +99,7 @@ public: * @brief Sets the time to be included in a local live view notification. * * @param time Indicates the type to be included. - + */ void SetTime(NotificationTime time); @@ -113,7 +113,7 @@ public: * @add flag function. * * @param flag Indicates the flag to be added. - + */ void addFlag(int32_t flag); @@ -187,4 +187,4 @@ private: } // namespace Notification } // namespace OHOS -#endif // BASE_NOTIFICATION_DISTRIBUTED_NOTIFICATION_SERVICE_INTERFACES_INNER_API_CONVERSATIONAL_CONTENT_H \ No newline at end of file +#endif // BASE_NOTIFICATION_DISTRIBUTED_NOTIFICATION_SERVICE_INTERFACES_INNER_API_CONVERSATIONAL_CONTENT_H diff --git a/interfaces/ndk/BUILD.gn b/interfaces/ndk/BUILD.gn new file mode 100644 index 000000000..b5763690c --- /dev/null +++ b/interfaces/ndk/BUILD.gn @@ -0,0 +1,68 @@ +# Copyright (c) 2021-2022 Huawei Device Co., Ltd. +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import("//base/notification/distributed_notification_service/notification.gni") +import("//build/ohos.gni") + +cflags = [] + +config("notification_ndk_config") { + visibility = [ ":*" ] + + include_dirs = [ + "${inner_api_path}", + "${notification_ndk_path}/include", + ] + + if (target_cpu == "arm") { + cflags += [ "-DBINDER_IPC_32BIT" ] + } +} + +config("notification_ndk_public_config") { + visibility = [ ":*" ] + + include_dirs = [ "${notification_ndk_path}/include" ] +} + +ohos_shared_library("ohnotification") { + sanitize = { + integer_overflow = true + ubsan = true + boundary_sanitize = true + cfi = true + cfi_cross_dso = true + debug = false + } + branch_protector_ret = "pac_ret" + + configs = [ ":notification_ndk_config" ] + + public_configs = [ ":notification_ndk_public_config" ] + + sources = [ "src/notification.cpp" ] + + deps = [ "${frameworks_module_ans_path}:ans_innerkits" ] + + external_deps = [ + "ability_base:base", + "ability_base:zuri", + "c_utils:utils", + "hilog:libhilog", + "relational_store:native_rdb", + ] + output_extension = "so" + innerapi_tags = [ "ndk" ] + subsystem_name = "${subsystem_name}" + part_name = "${component_name}" +} diff --git a/interfaces/ndk/include/notification.h b/interfaces/ndk/include/notification.h new file mode 100644 index 000000000..236608ca5 --- /dev/null +++ b/interfaces/ndk/include/notification.h @@ -0,0 +1,58 @@ +/* + * Copyright (c) 2024 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * @addtogroup NOTIFICATION + * @{ + * + * @brief Provides the definition of the C interface for the notification service. + * + * @since 14 + */ +/** + * @file notification.h + * + * @brief Declares the APIs of notification service. + * + * @library libohnotification.so + * @kit NotificationKit + * @syscap SystemCapability.Notification.Notification + * @since 14 + */ + +#ifndef OH_NOTIFICATION_H +#define OH_NOTIFICATION_H + +#include +#include + +#ifdef __cplusplus +extern "C" { +#endif + +/** + * @brief Checks whether this application is allowed to publish notifications. + * + * @return true - This application is allowed to publish notifications. + * false - This application is not allowed to publish notifications. + * @since 14 + */ +bool OH_Notification_IsNotificationEnabled(void); + +#ifdef __cplusplus +} +#endif +#endif // OH_NOTIFICATION_H +/** @} */ diff --git a/interfaces/ndk/src/notification.cpp b/interfaces/ndk/src/notification.cpp new file mode 100644 index 000000000..1b1fe73aa --- /dev/null +++ b/interfaces/ndk/src/notification.cpp @@ -0,0 +1,38 @@ +/* + * Copyright (c) 2024 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "notification.h" + +#include "notification_helper.h" +#include "ans_log_wrapper.h" + +#ifdef __cplusplus +extern "C" { +#endif + +bool OH_Notification_IsNotificationEnabled(void) +{ + bool isEnable = false; + int32_t result = OHOS::Notification::NotificationHelper::IsAllowedNotifySelf(isEnable); + if (result != OHOS::ERR_OK) { + ANS_LOGW("Get notification enable failed %{public}d", result); + return false; + } + return isEnable; +} + +#ifdef __cplusplus +} +#endif diff --git a/notification.gni b/notification.gni index 56ef295ec..1659de9e7 100644 --- a/notification.gni +++ b/notification.gni @@ -27,6 +27,7 @@ frameworks_path = "${component_path}/frameworks" frameworks_module_ans_path = "${frameworks_path}/ans" interfaces_path = "${component_path}/interfaces" inner_api_path = "${interfaces_path}/inner_api" +notification_ndk_path = "${interfaces_path}/ndk" core_path = "${frameworks_path}/core" test_path = "${component_path}/test" tools_path = "${component_path}/tools" @@ -67,7 +68,7 @@ declare_args() { } if (defined(global_parts_info) && - !defined(global_parts_info.hiviewdfx_hisysevent_native)) { + !defined(global_parts_info.hiviewdfx_hisysevent)) { hisysevent_usage = false } diff --git a/services/ans/BUILD.gn b/services/ans/BUILD.gn index ef5291a15..6c3569f72 100644 --- a/services/ans/BUILD.gn +++ b/services/ans/BUILD.gn @@ -137,6 +137,7 @@ ohos_shared_library("libans") { "ability_base:configuration", "ability_runtime:ability_manager", "ability_runtime:app_manager", + "ability_runtime:appkit_native", "ability_runtime:dataobs_manager", "ability_runtime:extension_manager", "ability_runtime:wantagent_innerkits", @@ -189,10 +190,6 @@ ohos_shared_library("libans") { defines += [ "HITRACE_METER_ENABLE" ] } - if (distributed_notification_service_feature_summary) { - defines += [ "ENABLE_ANS_EXT_WRAPPER" ] - } - if (ans_config_policy_enable) { external_deps += [ "config_policy:configpolicy_util" ] defines += [ "CONFIG_POLICY_ENABLE" ] @@ -203,6 +200,10 @@ ohos_shared_library("libans") { defines += [ "SCREENLOCK_MGR_ENABLE" ] } + if (distributed_notification_service_feature_summary) { + defines += [ "ENABLE_ANS_EXT_WRAPPER" ] + } + if (telephony_cust) { defines += [ "ENABLE_ANS_TELEPHONY_CUST_WRAPPER" ] } diff --git a/services/ans/include/advanced_notification_service.h b/services/ans/include/advanced_notification_service.h index d2af0fab1..fa554b4f5 100644 --- a/services/ans/include/advanced_notification_service.h +++ b/services/ans/include/advanced_notification_service.h @@ -51,6 +51,8 @@ namespace OHOS { namespace Notification { + +static const uint32_t DEFAULT_SLOT_FLAGS = 59; // 0b111011 class AdvancedNotificationService final : public AnsManagerStub { public: struct NotificationRequestDb { @@ -548,15 +550,6 @@ public: */ ErrCode CanPopEnableNotificationDialog(const sptr &callback, bool &canPop, std::string &bundleName) override; - - /** - * @brief remove enable notification dialog. - * - * @return Returns remove dialog result. - */ - ErrCode RemoveEnableNotificationDialog() override; - - ErrCode RemoveEnableNotificationDialog(const sptr &bundleOption); /** * @brief Checks whether notifications are allowed for a specific bundle. @@ -928,8 +921,9 @@ public: */ void OnDistributedKvStoreDeathRecipient(); - ErrCode CancelPreparedNotification( - int32_t notificationId, const std::string &label, const sptr &bundleOption); + ErrCode CancelPreparedNotification(int32_t notificationId, const std::string &label, + const sptr &bundleOption, const int32_t reason); + ErrCode PrepareNotificationInfo( const sptr &request, sptr &bundleOption); ErrCode PublishPreparedNotification(const sptr &request, @@ -1179,7 +1173,8 @@ private: void StartFilters(); void StopFilters(); ErrCode Filter(const std::shared_ptr &record, bool isRecover = false); - void ChangeNotificationByControlFlags(const std::shared_ptr &record); + void ChangeNotificationByControlFlags(const std::shared_ptr &record, + const bool isAgentController); ErrCode CheckPublishPreparedNotification(const std::shared_ptr &record, bool isSystemApp); void AddToNotificationList(const std::shared_ptr &record); void AddToDelayNotificationList(const std::shared_ptr &record); @@ -1205,7 +1200,7 @@ private: ErrCode FlowControl(const std::shared_ptr &record); ErrCode PublishFlowControl(const std::shared_ptr &record); ErrCode RemoveNotificationBySlot(const sptr &bundleOption, - const sptr &slot); + const sptr &slot, const int reason); sptr GenerateSortingMap(); static sptr GenerateBundleOption(); @@ -1322,10 +1317,12 @@ private: void CancelTimer(uint64_t timerId); ErrCode UpdateNotificationTimerInfo(const std::shared_ptr &record); ErrCode SetFinishTimer(const std::shared_ptr &record); - ErrCode StartFinishTimer(const std::shared_ptr &record, int64_t expireTimePoint); + ErrCode StartFinishTimer(const std::shared_ptr &record, + int64_t expireTimePoint, const int32_t reason); void CancelFinishTimer(const std::shared_ptr &record); ErrCode SetUpdateTimer(const std::shared_ptr &record); - ErrCode StartUpdateTimer(const std::shared_ptr &record, int64_t expireTimePoint); + ErrCode StartUpdateTimer(const std::shared_ptr &record, + int64_t expireTimePoint, const int32_t reason); void CancelUpdateTimer(const std::shared_ptr &record); void StartArchiveTimer(const std::shared_ptr &record); void CancelArchiveTimer(const std::shared_ptr &record); @@ -1350,10 +1347,11 @@ private: ErrCode CheckBundleOptionValid(sptr &bundleOption); bool IsNeedNotifyConsumed(const sptr &request); ErrCode AddRecordToMemory(const std::shared_ptr &record, - bool isSystemApp, bool isUpdateByOwner); + bool isSystemApp, bool isUpdateByOwner, const bool isAgentController); ErrCode DuplicateMsgControl(const sptr &request); void RemoveExpiredUniqueKey(); bool IsDuplicateMsg(const std::string &uniqueKey); + void DeleteDuplicateMsgs(const sptr &bundleOption); ErrCode PublishRemoveDuplicateEvent(const std::shared_ptr &record); std::vector GetBundlesOfActiveUser(); ErrCode UpdateSlotAuthInfo(const std::shared_ptr &record); @@ -1368,8 +1366,8 @@ private: const sptr &bundleOption); ErrCode UpdateSlotReminderModeBySlotFlags(const sptr &bundle, uint32_t slotFlags); ErrCode CheckSoundPermission(const sptr &request, std::string bundleName); - void GenerateSlotReminderMode( - const sptr &slot, const sptr &bundle, bool isSpecifiedSlot = false); + void GenerateSlotReminderMode(const sptr &slot, const sptr &bundle, + bool isSpecifiedSlot = false, uint32_t defaultSlotFlags = DEFAULT_SLOT_FLAGS); static void CloseAlert(const std::shared_ptr &record); bool IsUpdateSystemLiveviewByOwner(const sptr &request); bool IsSaCreateSystemLiveViewAsBundle(const std::shared_ptr &record, int32_t ipcUid); @@ -1382,8 +1380,14 @@ private: ErrCode DeleteAllByUserInner(const int32_t &userId, int32_t reason, bool isAsync = false); ErrCode RemoveAllNotificationsInner(const sptr &bundleOption, int32_t reason); void RemoveNotificationList(const std::shared_ptr &record); + void StartFinishTimerForUpdate(const std::shared_ptr &record, uint64_t process); ErrCode CheckSystemLiveView(const sptr &request, const std::string &key); + void ExcuteCancelGroupCancel(const sptr& bundleOption, + const std::string &groupName, const int32_t reason); + ErrCode ExcuteCancelAll(const sptr& bundleOption, const int32_t reason); + ErrCode ExcuteDelete(const std::string &key, const int32_t removeReason); ErrCode CheckNeedSilent(const std::string &phoneNumber, int32_t callerType, int32_t userId); + uint32_t GetDefaultSlotFlags(const sptr &request); private: static sptr instance_; diff --git a/services/ans/include/bundle_manager_helper.h b/services/ans/include/bundle_manager_helper.h index 30da5ea18..24471b3d1 100644 --- a/services/ans/include/bundle_manager_helper.h +++ b/services/ans/include/bundle_manager_helper.h @@ -116,6 +116,14 @@ public: * @return Returns the check result. */ bool CheckApiCompatibility(const std::string &bundleName, const int32_t &uid); + + /** + * @brief Obtains the app index by uid. + * @param uid Indicates uid. + * @return Returns the query result if succeed, retrun 0(main index) otherwise. + */ + int32_t GetAppIndexByUid(const int32_t uid); + private: void Connect(); void Disconnect(); diff --git a/services/ans/include/notification_analytics_util.h b/services/ans/include/notification_analytics_util.h index 4b1b4d8f2..801392fdd 100644 --- a/services/ans/include/notification_analytics_util.h +++ b/services/ans/include/notification_analytics_util.h @@ -108,8 +108,6 @@ private: static bool ReportFlowControl(const int32_t reportType); - static std::list GetFlowListByType(const int32_t reportType); - static FlowControllerOption GetFlowOptionByType(const int32_t reportType); }; } // namespace Notification diff --git a/services/ans/include/notification_dialog_manager.h b/services/ans/include/notification_dialog_manager.h index 2d8b63877..67dc13619 100644 --- a/services/ans/include/notification_dialog_manager.h +++ b/services/ans/include/notification_dialog_manager.h @@ -101,13 +101,6 @@ public: * @return ERR_OK when add Dialog successfully */ ErrCode AddDialogInfo(const sptr& bundle, const sptr& callback); - - /* - * RemoveDialogInfoByBundleOption - * @return void - */ - void RemoveDialogInfoByBundleOption(const sptr& bundle, - std::unique_ptr& dialogInfoRemoved); inline static const std::string NOTIFICATION_DIALOG_SERVICE_BUNDLE = "com.ohos.notificationdialog"; inline static const std::string NOTIFICATION_DIALOG_SERVICE_ABILITY = "EnableNotificationDialog"; @@ -119,6 +112,9 @@ private: // bundle need to be not null bool AddDialogInfoIfNotExist(const sptr& bundle, const sptr& callback); sptr GetBundleOptionByBundleName(const std::string& bundleName, const int32_t& uid); + // bundle need to be not null + void RemoveDialogInfoByBundleOption(const sptr& bundle, + std::unique_ptr& dialogInfoRemoved); void RemoveAllDialogInfos(std::list>& dialogInfosRemoved); bool OnDialogButtonClicked(const std::string& bundleName, const int32_t& uid, bool enabled); diff --git a/services/ans/include/notification_extension_wrapper.h b/services/ans/include/notification_extension_wrapper.h index 88d465c85..70fa48e2d 100644 --- a/services/ans/include/notification_extension_wrapper.h +++ b/services/ans/include/notification_extension_wrapper.h @@ -41,6 +41,7 @@ public: typedef int32_t (*LOCAL_CONTROL)(const sptr &request); typedef void (*UPDATE_BY_BUNDLE)(const std::string bundleName, int deleteType); typedef int32_t (*REMINDER_CONTROL)(const std::string &bundleName); + typedef int32_t (*BANNER_CONTROL)(const std::string &bundleName); ErrCode SyncAdditionConfig(const std::string& key, const std::string& value); void UpdateByCancel(const std::vector>& notifications, int deleteReason); @@ -51,6 +52,7 @@ public: int32_t LocalControl(const sptr &request); void UpdateByBundle(const std::string bundleName, int deleteType); int32_t ReminderControl(const std::string &bundleName); + int32_t BannerControl(const std::string &bundleName); private: static int32_t convertToDelType(int32_t deleteReason); @@ -64,6 +66,7 @@ private: LOCAL_CONTROL localControl_ = nullptr; UPDATE_BY_BUNDLE updateByBundle_ = nullptr; REMINDER_CONTROL reminderControl_ = nullptr; + BANNER_CONTROL bannerControl_ = nullptr; bool isRegisterDataSettingObserver = false; }; diff --git a/services/ans/include/system_dialog_connect_stb.h b/services/ans/include/system_dialog_connect_stb.h index 3b0ad5be2..89f09b2a5 100644 --- a/services/ans/include/system_dialog_connect_stb.h +++ b/services/ans/include/system_dialog_connect_stb.h @@ -38,6 +38,8 @@ public: const sptr &remoteObject, int32_t resultCode) override; void OnAbilityDisconnectDone(const AppExecFwk::ElementName &element, int32_t resultCode) override; + void SendRemoveBundleEvent(); + private: std::string commandStr_; }; diff --git a/services/ans/src/advanced_datashare_helper.cpp b/services/ans/src/advanced_datashare_helper.cpp index 600d16d90..516b55b5f 100644 --- a/services/ans/src/advanced_datashare_helper.cpp +++ b/services/ans/src/advanced_datashare_helper.cpp @@ -237,9 +237,9 @@ bool AdvancedDatashareHelper::isRepeatCall(const std::string &phoneNumber) int rowCount = 0; resultSet->GetRowCount(rowCount); if (rowCount > 0) { - int32_t columnIndex; int32_t callTime = 0; if (resultSet->GoToFirstRow() == 0) { + int32_t columnIndex; resultSet->GetColumnIndex(CREATE_TIME, columnIndex); resultSet->GetInt(columnIndex, callTime); } diff --git a/services/ans/src/advanced_notification_inline.cpp b/services/ans/src/advanced_notification_inline.cpp index 6b34aa9a0..9be433936 100644 --- a/services/ans/src/advanced_notification_inline.cpp +++ b/services/ans/src/advanced_notification_inline.cpp @@ -28,16 +28,15 @@ #include "notification_constant.h" #include "os_account_manager_helper.h" #include "notification_preferences.h" +#include "notification_analytics_util.h" namespace OHOS { namespace Notification { -inline std::string GetClientBundleName() +inline std::string GetClientBundleNameByUid(int32_t callingUid) { std::string bundle; - int32_t callingUid = IPCSkeleton::GetCallingUid(); - std::shared_ptr bundleManager = BundleManagerHelper::GetInstance(); if (bundleManager != nullptr) { bundle = bundleManager->GetBundleNameByUid(callingUid); @@ -46,6 +45,12 @@ inline std::string GetClientBundleName() return bundle; } +inline std::string GetClientBundleName() +{ + int32_t callingUid = IPCSkeleton::GetCallingUid(); + return GetClientBundleNameByUid(callingUid); +} + inline int32_t CheckUserIdParams(const int userId) { if (userId != SUBSCRIBE_USER_INIT && !OsAccountManagerHelper::GetInstance().CheckUserExists(userId)) { @@ -79,17 +84,24 @@ inline tm GetLocalTime(time_t time) inline ErrCode CheckPictureSize(const sptr &request) { + HaMetaMessage message = HaMetaMessage(EventSceneId::SCENE_1, EventBranchId::BRANCH_1); auto result = request->CheckImageSizeForContent(); if (result != ERR_OK) { ANS_LOGE("Check image size failed."); + message.ErrorCode(result).Message("Check image size failed."); + NotificationAnalyticsUtil::ReportPublishFailedEvent(request, message); return result; } if (request->CheckImageOverSizeForPixelMap(request->GetLittleIcon(), MAX_ICON_SIZE)) { + message.ErrorCode(ERR_ANS_ICON_OVER_SIZE).Message("Check little image size failed."); + NotificationAnalyticsUtil::ReportPublishFailedEvent(request, message); return ERR_ANS_ICON_OVER_SIZE; } if (request->CheckImageOverSizeForPixelMap(request->GetOverlayIcon(), MAX_ICON_SIZE)) { + message.ErrorCode(ERR_ANS_ICON_OVER_SIZE).Message("Check overlay size failed."); + NotificationAnalyticsUtil::ReportPublishFailedEvent(request, message); return ERR_ANS_ICON_OVER_SIZE; } @@ -100,5 +112,42 @@ inline ErrCode CheckPictureSize(const sptr &request) return ERR_OK; } + +inline OHOS::Notification::HaMetaMessage AddInformationInMessage( + OHOS::Notification::HaMetaMessage haMetaMessage, const int32_t reason, + std::string message) +{ + message += "reason:" + std::to_string(reason) + "."; + + std::string bundleName; + int32_t callingUid = IPCSkeleton::GetCallingUid(); + message += "uid:" + std::to_string(callingUid) + "."; + bundleName = GetClientBundleNameByUid(callingUid); + + haMetaMessage = haMetaMessage.AgentBundleName(bundleName); + haMetaMessage = haMetaMessage.Message(message); + return haMetaMessage; +} + + +inline void ReportDeleteFailedEventPush(OHOS::Notification::HaMetaMessage haMetaMessage, + const int32_t reason, std::string message) +{ + haMetaMessage = AddInformationInMessage(haMetaMessage, reason, message); + NotificationAnalyticsUtil::ReportDeleteFailedEvent(haMetaMessage); +} + +inline void ReportDeleteFailedEventPushByNotification(const sptr ¬ification, + OHOS::Notification::HaMetaMessage haMetaMessage, const int32_t reason, + std::string message) +{ + if (notification == nullptr) { + ANS_LOGW("report notificaiton is null"); + return; + } + haMetaMessage = AddInformationInMessage(haMetaMessage, reason, message); + NotificationAnalyticsUtil::ReportDeleteFailedEvent( + notification->GetNotificationRequestPoint(), haMetaMessage); +} } // namespace Notification } // namespace OHOS diff --git a/services/ans/src/advanced_notification_live_view_service.cpp b/services/ans/src/advanced_notification_live_view_service.cpp index 5cb6c19b9..3f9dfe333 100644 --- a/services/ans/src/advanced_notification_live_view_service.cpp +++ b/services/ans/src/advanced_notification_live_view_service.cpp @@ -32,6 +32,7 @@ #include "advanced_notification_inline.cpp" #include #include +#include "notification_analytics_util.h" #include "aes_gcm_helper.h" namespace OHOS { @@ -92,8 +93,10 @@ void AdvancedNotificationService::RecoverLiveViewFromDb(int32_t userId) } UpdateRecentNotification(record->notification, false, 0); - StartFinishTimer(record, requestObj.request->GetFinishDeadLine()); - StartUpdateTimer(record, requestObj.request->GetUpdateDeadLine()); + StartFinishTimer(record, requestObj.request->GetFinishDeadLine(), + NotificationConstant::TRIGGER_EIGHT_HOUR_REASON_DELETE); + StartUpdateTimer(record, requestObj.request->GetUpdateDeadLine(), + NotificationConstant::TRIGGER_FOUR_HOUR_REASON_DELETE); } // publish notifications @@ -171,7 +174,8 @@ void AdvancedNotificationService::OnSubscriberAdd( sptr sortingMap = GenerateSortingMap(); std::vector> notifications; for (auto notificationRecord : notificationList_) { - if (notificationRecord->notification != nullptr && + if (notificationRecord != nullptr && + notificationRecord->notification != nullptr && notificationRecord->notification->GetNotificationRequest().IsCommonLiveView()) { notifications.emplace_back(notificationRecord->notification); } @@ -235,17 +239,20 @@ int32_t AdvancedNotificationService::SetNotificationRequestToDb(const Notificati ANS_LOGI("Not saving notification request to db for common live view with isOnlyLocalUpdate set to true."); return ERR_OK; } - + HaMetaMessage message = HaMetaMessage(EventSceneId::SCENE_6, EventBranchId::BRANCH_3). + BundleName(request->GetCreatorBundleName()).NotificationId(request->GetNotificationId()); nlohmann::json jsonObject; if (!NotificationJsonConverter::ConvertToJson(request, jsonObject)) { ANS_LOGE("Convert request to json object failed, bundle name %{public}s, id %{public}d.", request->GetCreatorBundleName().c_str(), request->GetNotificationId()); + NotificationAnalyticsUtil::ReportModifyEvent(message.Message("convert request failed")); return ERR_ANS_TASK_ERR; } auto bundleOption = requestDb.bundleOption; if (!NotificationJsonConverter::ConvertToJson(bundleOption, jsonObject)) { ANS_LOGE("Convert bundle to json object failed, bundle name %{public}s, id %{public}d.", bundleOption->GetBundleName().c_str(), request->GetNotificationId()); + NotificationAnalyticsUtil::ReportModifyEvent(message.Message("convert option failed")); return ERR_ANS_TASK_ERR; } @@ -258,9 +265,9 @@ int32_t AdvancedNotificationService::SetNotificationRequestToDb(const Notificati auto result = NotificationPreferences::GetInstance()->SetKvToDb( request->GetSecureKey(), encryptValue, request->GetReceiverUserId()); if (result != ERR_OK) { - ANS_LOGE( - "Set notification request failed, bundle name %{public}s, id %{public}d, key %{public}s, ret %{public}d.", + ANS_LOGE("Set failed, bundle name %{public}s, id %{public}d, key %{public}s, ret %{public}d.", request->GetCreatorBundleName().c_str(), request->GetNotificationId(), request->GetKey().c_str(), result); + NotificationAnalyticsUtil::ReportModifyEvent(message.ErrorCode(result).Message("set failed")); return result; } else { DeleteNotificationRequestFromDb(request->GetKey(), request->GetReceiverUserId()); @@ -269,9 +276,9 @@ int32_t AdvancedNotificationService::SetNotificationRequestToDb(const Notificati result = SetLockScreenPictureToDb(request); if (result != ERR_OK) { ANS_LOGE("Failed to set lock screen picture to db"); - return result; + NotificationAnalyticsUtil::ReportModifyEvent(message.ErrorCode(result).Message("SetToDb failed")); } - return ERR_OK; + return result; } int32_t AdvancedNotificationService::GetNotificationRequestFromDb( @@ -364,6 +371,7 @@ int32_t AdvancedNotificationService::GetBatchNotificationRequestsFromDb( return ERR_OK; } + int32_t AdvancedNotificationService::DoubleDeleteNotificationFromDb(const std::string &key, const std::string &secureKey, const int32_t userId) { @@ -592,12 +600,13 @@ ErrCode AdvancedNotificationService::StartPublishDelayedNotification(const std:: NotificationSubscriberManager::GetInstance()->NotifyConsumed(record->notification, GenerateSortingMap()); if ((record->request->GetAutoDeletedTime() > GetCurrentTime())) { StartAutoDelete(record, - record->request->GetAutoDeletedTime(), NotificationConstant::APP_CANCEL_REASON_DELETE); + record->request->GetAutoDeletedTime(), NotificationConstant::TRIGGER_AUTO_DELETE_REASON_DELETE); } record->finish_status = UploadStatus::FIRST_UPDATE_TIME_OUT; - StartFinishTimer(record, GetCurrentTime() + NotificationConstant::TEN_MINUTES); - + StartFinishTimer(record, GetCurrentTime() + NotificationConstant::TEN_MINUTES, + NotificationConstant::TRIGGER_TEN_MINUTES_REASON_DELETE); + return ERR_OK; } @@ -657,11 +666,9 @@ void AdvancedNotificationService::UpdateRecordByOwner( if (oldRecord == nullptr) { oldRecord = GetFromNotificationList(creatorUid, notificationId); } - if (oldRecord == nullptr) { return; } - auto downloadTemplate = record->notification->GetNotificationRequest().GetTemplate(); auto content = record->notification->GetNotificationRequest().GetContent(); auto wantAgent = record->notification->GetNotificationRequest().GetWantAgent(); @@ -677,21 +684,12 @@ void AdvancedNotificationService::UpdateRecordByOwner( auto data = downloadTemplate->GetTemplateData(); AAFwk::WantParamWrapper wrapper(*data); ANS_LOGD("Update the template data: %{public}s.", wrapper.ToString().c_str()); - CancelTimer(oldRecord->notification->GetFinishTimer()); - uint64_t process = 0; if (data->HasParam(PROGRESS_VALUE)) { process = data->GetIntParam(PROGRESS_VALUE, 0); } - - if (process == NotificationConstant::FINISH_PER) { - record->finish_status = UploadStatus::FINISH; - StartFinishTimer(record, GetCurrentTime() + NotificationConstant::THIRTY_MINUTES); - } else { - record->finish_status = UploadStatus::CONTINUOUS_UPDATE_TIME_OUT; - StartFinishTimer(record, GetCurrentTime() + NotificationConstant::FIFTEEN_MINUTES); - } + StartFinishTimerForUpdate(record, process); timerId = record->notification->GetFinishTimer(); } record->notification = new (std::nothrow) Notification(record->request); @@ -702,5 +700,19 @@ void AdvancedNotificationService::UpdateRecordByOwner( record->bundleOption = oldRecord->bundleOption; record->notification->SetFinishTimer(timerId); } + +void AdvancedNotificationService::StartFinishTimerForUpdate( + const std::shared_ptr &record, uint64_t process) +{ + if (process == NotificationConstant::FINISH_PER) { + record->finish_status = UploadStatus::FINISH; + StartFinishTimer(record, GetCurrentTime() + NotificationConstant::THIRTY_MINUTES, + NotificationConstant::TRIGGER_FIFTEEN_MINUTES_REASON_DELETE); + } else { + record->finish_status = UploadStatus::CONTINUOUS_UPDATE_TIME_OUT; + StartFinishTimer(record, GetCurrentTime() + NotificationConstant::FIFTEEN_MINUTES, + NotificationConstant::TRIGGER_THIRTY_MINUTES_REASON_DELETE); + } +} } } diff --git a/services/ans/src/advanced_notification_publish/base_publish_process.cpp b/services/ans/src/advanced_notification_publish/base_publish_process.cpp index 90210c59c..afe9ddcbe 100644 --- a/services/ans/src/advanced_notification_publish/base_publish_process.cpp +++ b/services/ans/src/advanced_notification_publish/base_publish_process.cpp @@ -61,6 +61,9 @@ ErrCode BasePublishProcess::CommonPublishProcess(const sptr Security::AccessToken::AccessTokenID callerToken = IPCSkeleton::GetCallingTokenID(); if (AccessTokenHelper::IsDlpHap(callerToken)) { ANS_LOGE("DLP hap not allowed to send notifications"); + HaMetaMessage message = HaMetaMessage(EventSceneId::SCENE_2, EventBranchId::BRANCH_5) + .ErrorCode(ERR_ANS_DLP_HAP).Message("CommonPublishProcess failed"); + NotificationAnalyticsUtil::ReportPublishFailedEvent(request, message); return ERR_ANS_DLP_HAP; } return ERR_OK; diff --git a/services/ans/src/advanced_notification_publish/live_publish_process.cpp b/services/ans/src/advanced_notification_publish/live_publish_process.cpp index 52eda9b3d..b7f401650 100644 --- a/services/ans/src/advanced_notification_publish/live_publish_process.cpp +++ b/services/ans/src/advanced_notification_publish/live_publish_process.cpp @@ -47,7 +47,12 @@ std::shared_ptr LivePublishProcess::GetInstance() ErrCode LivePublishProcess::PublishPreWork(const sptr &request, bool isUpdateByOwnerAllowed) { + HaMetaMessage message = HaMetaMessage(EventSceneId::SCENE_1, EventBranchId::BRANCH_1); if (!CheckLocalLiveViewAllowed(request, isUpdateByOwnerAllowed)) { + message.BranchId(EventBranchId::BRANCH_3).ErrorCode(ERR_ANS_NON_SYSTEM_APP) + .Message("CheckLocalLiveViewAllowed is false", true); + NotificationAnalyticsUtil::ReportPublishFailedEvent(request, message); + ANS_LOGE("CheckLocalLiveViewAllowed is false"); return ERR_ANS_NON_SYSTEM_APP; } @@ -61,6 +66,9 @@ ErrCode LivePublishProcess::PublishPreWork(const sptr &requ !AccessTokenHelper::IsSystemApp(); if (isUpdateByOwnerAllowed && isHap) { if (request->GetTemplate() == nullptr) { + message.BranchId(EventBranchId::BRANCH_4).ErrorCode(ERR_ANS_INVALID_PARAM) + .Message("Owner must has template to update", true); + NotificationAnalyticsUtil::ReportPublishFailedEvent(request, message); ANS_LOGE("Owner must has template to update."); return ERR_ANS_INVALID_PARAM; } diff --git a/services/ans/src/advanced_notification_publish_service.cpp b/services/ans/src/advanced_notification_publish_service.cpp index a70e61acd..a8675583c 100644 --- a/services/ans/src/advanced_notification_publish_service.cpp +++ b/services/ans/src/advanced_notification_publish_service.cpp @@ -39,8 +39,10 @@ #include "common_event_publish_info.h" #include "want_params_wrapper.h" #include "ans_convert_enum.h" +#include "notification_analytics_util.h" #include "advanced_notification_inline.cpp" +#include "notification_analytics_util.h" #include "advanced_datashare_helper.h" #include "advanced_datashare_helper_ext.h" #include "datashare_result_set.h" @@ -58,11 +60,10 @@ const static std::string NOTIFICATION_EVENT_PUSH_AGENT = "notification.event.PUS constexpr int32_t RSS_PID = 3051; constexpr int32_t ANS_UID = 5523; constexpr int32_t BROKER_UID = 5557; -constexpr int32_t PSS_UID = 7123; constexpr int32_t TYPE_CODE_DOWNLOAD = 8; -constexpr int32_t OPERATION_TYPE_COMMON_EVENT = 4; constexpr const char *FOCUS_MODE_REPEAT_CALLERS_ENABLE = "1"; constexpr const char *CONTACT_DATA = "datashare:///com.ohos.contactsdataability/contacts/contact_data?Proxy=true"; +constexpr int32_t OPERATION_TYPE_COMMON_EVENT = 4; ErrCode AdvancedNotificationService::SetDefaultNotificationEnabled( const sptr &bundleOption, bool enabled) @@ -77,7 +78,7 @@ ErrCode AdvancedNotificationService::SetDefaultNotificationEnabled( ANS_LOGE("Failed to create EnabledNotificationCallbackData instance"); return ERR_NO_MEMORY; } - SetSlotFlagsTrustlistsAsBundle(bundle); + ErrCode result = ERR_OK; result = NotificationPreferences::GetInstance()->SetNotificationsEnabledForBundle(bundle, enabled); if (result == ERR_OK) { @@ -104,15 +105,18 @@ ErrCode AdvancedNotificationService::Publish(const std::string &label, const spt } request->SetCreateTime(GetCurrentTime()); + HaMetaMessage message = HaMetaMessage(EventSceneId::SCENE_1, EventBranchId::BRANCH_1); bool isUpdateByOwnerAllowed = IsUpdateSystemLiveviewByOwner(request); ErrCode result = publishProcess_[request->GetSlotType()]->PublishPreWork(request, isUpdateByOwnerAllowed); if (result != ERR_OK) { - ANSR_LOGE("Failed to process request, result is %{public}d", result); + message.BranchId(EventBranchId::BRANCH_0).ErrorCode(result).Message("publish prework failed", true); + NotificationAnalyticsUtil::ReportPublishFailedEvent(request, message); return result; } result = CheckUserIdParams(request->GetReceiverUserId()); if (result != ERR_OK) { - ANSR_LOGE("User is invalid"); + message.SceneId(EventSceneId::SCENE_3).ErrorCode(result).Message("User is invalid", true); + NotificationAnalyticsUtil::ReportPublishFailedEvent(request, message); return result; } bool isSubsystem = AccessTokenHelper::VerifyNativeToken(IPCSkeleton::GetCallingTokenID()); @@ -142,6 +146,7 @@ ErrCode AdvancedNotificationService::Publish(const std::string &label, const spt result = CheckSoundPermission(request, bundleOption->GetBundleName()); if (result != ERR_OK) { + message.ErrorCode(result).Message("Check sound failed."); break; } @@ -149,14 +154,17 @@ ErrCode AdvancedNotificationService::Publish(const std::string &label, const spt result = PushCheck(request); } if (result != ERR_OK) { + message.ErrorCode(result).Message("Push check failed."); break; } result = PublishPreparedNotification(request, bundleOption, isUpdateByOwnerAllowed); if (result != ERR_OK) { + message.ErrorCode(result).Message("Publish prepared failed."); break; } } while (0); + NotificationAnalyticsUtil::ReportPublishFailedEvent(request, message); SendPublishHiSysEvent(request, result); return result; } @@ -203,16 +211,23 @@ ErrCode AdvancedNotificationService::Cancel(int32_t notificationId, const std::s sptr bundleOption = GenerateBundleOption(); if (bundleOption == nullptr) { + std::string message = "get bundleOption is null."; + OHOS::Notification::HaMetaMessage haMetaMessage = HaMetaMessage(1, 1) + .ErrorCode(ERR_ANS_INVALID_BUNDLE).NotificationId(notificationId); + ReportDeleteFailedEventPush(haMetaMessage, NotificationConstant::APP_CANCEL_REASON_DELETE, + message); + ANS_LOGE("%{public}s", message.c_str()); return ERR_ANS_INVALID_BUNDLE; } bundleOption->SetInstanceKey(instanceKey); - return CancelPreparedNotification(notificationId, label, bundleOption); + return CancelPreparedNotification(notificationId, label, bundleOption, + NotificationConstant::APP_CANCEL_REASON_DELETE); } ErrCode AdvancedNotificationService::CancelAll(int32_t instanceKey) { ANS_LOGD("%{public}s", __FUNCTION__); - + const int reason = NotificationConstant::APP_CANCEL_ALL_REASON_DELETE; sptr bundleOption = GenerateBundleOption(); if (bundleOption == nullptr) { return ERR_ANS_INVALID_BUNDLE; @@ -223,6 +238,13 @@ ErrCode AdvancedNotificationService::CancelAll(int32_t instanceKey) ANS_LOGE("Serial queue is invalidated."); return ERR_ANS_INVALID_PARAM; } + ErrCode result = ExcuteCancelAll(bundleOption, reason); + return result; +} + +ErrCode AdvancedNotificationService::ExcuteCancelAll( + const sptr& bundleOption, const int32_t reason) +{ ErrCode result = ERR_OK; ffrt::task_handle handler = notificationSvrQueue_->submit_h(std::bind([&]() { ANS_LOGD("ffrt enter!"); @@ -236,14 +258,12 @@ ErrCode AdvancedNotificationService::CancelAll(int32_t instanceKey) std::string bundleName; GetDistributedInfo(key, deviceId, bundleName); #endif - result = RemoveFromNotificationList(key, notification, true, - NotificationConstant::APP_CANCEL_ALL_REASON_DELETE); + result = RemoveFromNotificationList(key, notification, true, reason); if (result != ERR_OK) { continue; } if (notification != nullptr) { - int32_t reason = NotificationConstant::APP_CANCEL_ALL_REASON_DELETE; UpdateRecentNotification(notification, true, reason); notifications.emplace_back(notification); #ifdef DISTRIBUTED_NOTIFICATION_SUPPORTED @@ -253,14 +273,14 @@ ErrCode AdvancedNotificationService::CancelAll(int32_t instanceKey) if (notifications.size() >= MAX_CANCELED_PARCELABLE_VECTOR_NUM) { std::vector> currNotificationList = notifications; NotificationSubscriberManager::GetInstance()->BatchNotifyCanceled( - currNotificationList, nullptr, NotificationConstant::APP_CANCEL_ALL_REASON_DELETE); + currNotificationList, nullptr, reason); notifications.clear(); } } if (!notifications.empty()) { NotificationSubscriberManager::GetInstance()->BatchNotifyCanceled( - notifications, nullptr, NotificationConstant::APP_CANCEL_ALL_REASON_DELETE); + notifications, nullptr, reason); } result = ERR_OK; })); @@ -272,15 +292,24 @@ ErrCode AdvancedNotificationService::CancelAsBundle( const sptr &bundleOption, int32_t notificationId, int32_t userId) { ANS_LOGD("%{public}s", __FUNCTION__); + int32_t reason = NotificationConstant::APP_CANCEL_AS_BUNELE_REASON_DELETE; bool isSubsystem = AccessTokenHelper::VerifyNativeToken(IPCSkeleton::GetCallingTokenID()); if (!isSubsystem && !AccessTokenHelper::IsSystemApp()) { + std::string message = "not systemApp"; + OHOS::Notification::HaMetaMessage haMetaMessage = HaMetaMessage(2, 1) + .ErrorCode(ERR_ANS_NON_SYSTEM_APP).NotificationId(notificationId); + ReportDeleteFailedEventPush(haMetaMessage, reason, message); + ANS_LOGE("%{public}s", message.c_str()); return ERR_ANS_NON_SYSTEM_APP; } - int32_t callingUid = IPCSkeleton::GetCallingUid(); - if ((callingUid != NFC_UID && callingUid != PSS_UID && callingUid != PAC_UID) - && (!AccessTokenHelper::CheckPermission(OHOS_PERMISSION_NOTIFICATION_CONTROLLER) || - !AccessTokenHelper::CheckPermission(OHOS_PERMISSION_NOTIFICATION_AGENT_CONTROLLER))) { + if (!AccessTokenHelper::CheckPermission(OHOS_PERMISSION_NOTIFICATION_CONTROLLER) || + !AccessTokenHelper::CheckPermission(OHOS_PERMISSION_NOTIFICATION_AGENT_CONTROLLER)) { + std::string message = "no acl permission"; + OHOS::Notification::HaMetaMessage haMetaMessage = HaMetaMessage(2, 2) + .ErrorCode(ERR_ANS_PERMISSION_DENIED).NotificationId(notificationId); + ReportDeleteFailedEventPush(haMetaMessage, reason, message); + ANS_LOGE("%{public}s", message.c_str()); return ERR_ANS_PERMISSION_DENIED; } @@ -299,11 +328,16 @@ ErrCode AdvancedNotificationService::CancelAsBundle( uid = bundleOption->GetUid(); } if (uid < 0) { + std::string message = "uid error"; + OHOS::Notification::HaMetaMessage haMetaMessage = HaMetaMessage(2, 3) + .ErrorCode(ERR_ANS_INVALID_UID).NotificationId(notificationId); + ReportDeleteFailedEventPush(haMetaMessage, reason, message); + ANS_LOGE("%{public}s", message.c_str()); return ERR_ANS_INVALID_UID; } sptr bundle = new (std::nothrow) NotificationBundleOption( bundleOption->GetBundleName(), uid); - return CancelPreparedNotification(notificationId, "", bundle); + return CancelPreparedNotification(notificationId, "", bundle, reason); } ErrCode AdvancedNotificationService::CancelAsBundle( @@ -332,9 +366,14 @@ ErrCode AdvancedNotificationService::CancelAsBundleWithAgent( const sptr &bundleOption, const int32_t id) { ANS_LOGD("Called."); - + int32_t reason = NotificationConstant::APP_CANCEL_AS_BUNELE_WITH_AGENT_REASON_DELETE; bool isSubsystem = AccessTokenHelper::VerifyNativeToken(IPCSkeleton::GetCallingTokenID()); if (!isSubsystem && !AccessTokenHelper::IsSystemApp()) { + std::string message = "not systemApp"; + OHOS::Notification::HaMetaMessage haMetaMessage = HaMetaMessage(2, 4) + .ErrorCode(ERR_ANS_NON_SYSTEM_APP).NotificationId(id); + ReportDeleteFailedEventPush(haMetaMessage, reason, message); + ANS_LOGE("%{public}s", message.c_str()); return ERR_ANS_NON_SYSTEM_APP; } @@ -356,13 +395,22 @@ ErrCode AdvancedNotificationService::CancelAsBundleWithAgent( uid = bundleOption->GetUid(); } if (uid < 0) { + std::string message = "uid error"; + OHOS::Notification::HaMetaMessage haMetaMessage = HaMetaMessage(2, 5) + .ErrorCode(ERR_ANS_INVALID_UID).NotificationId(id); + ReportDeleteFailedEventPush(haMetaMessage, reason, message); + ANS_LOGE("%{public}s", message.c_str()); return ERR_ANS_INVALID_UID; } sptr bundle = new (std::nothrow) NotificationBundleOption( bundleOption->GetBundleName(), uid); - return CancelPreparedNotification(id, "", bundle); + return CancelPreparedNotification(id, "", bundle, reason); } - + std::string message = "no agent setting"; + OHOS::Notification::HaMetaMessage haMetaMessage = HaMetaMessage(2, 6) + .ErrorCode(ERR_ANS_NO_AGENT_SETTING).NotificationId(id); + ReportDeleteFailedEventPush(haMetaMessage, reason, message); + ANS_LOGE("%{public}s", message.c_str()); return ERR_ANS_NO_AGENT_SETTING; } @@ -399,21 +447,39 @@ ErrCode AdvancedNotificationService::SetNotificationBadgeNum(int32_t num) ErrCode AdvancedNotificationService::Delete(const std::string &key, int32_t removeReason) { ANS_LOGD("%{public}s", __FUNCTION__); - bool isSubsystem = AccessTokenHelper::VerifyNativeToken(IPCSkeleton::GetCallingTokenID()); if (!isSubsystem && !AccessTokenHelper::IsSystemApp()) { - ANS_LOGD("VerifyNativeToken and IsSystemApp is false."); + std::string message = "not systemApp. key:" + key + "."; + OHOS::Notification::HaMetaMessage haMetaMessage = HaMetaMessage(4, 1) + .ErrorCode(ERR_ANS_NON_SYSTEM_APP); + ReportDeleteFailedEventPush(haMetaMessage, removeReason, message); + ANS_LOGE("%{public}s", message.c_str()); return ERR_ANS_NON_SYSTEM_APP; } if (!AccessTokenHelper::CheckPermission(OHOS_PERMISSION_NOTIFICATION_CONTROLLER)) { + std::string message = "no acl permission. key:" + key + "."; + OHOS::Notification::HaMetaMessage haMetaMessage = HaMetaMessage(4, 2) + .ErrorCode(ERR_ANS_PERMISSION_DENIED); + ReportDeleteFailedEventPush(haMetaMessage, removeReason, message); + ANS_LOGE("%{public}s", message.c_str()); return ERR_ANS_PERMISSION_DENIED; } if (notificationSvrQueue_ == nullptr) { - ANS_LOGE("Serial queue is invalidated."); + std::string message = "Serial queue is invalidated. key:" + key + "."; + OHOS::Notification::HaMetaMessage haMetaMessage = HaMetaMessage(4, 3) + .ErrorCode(ERR_ANS_INVALID_PARAM); + ReportDeleteFailedEventPush(haMetaMessage, removeReason, message); + ANS_LOGE("%{public}s", message.c_str()); return ERR_ANS_INVALID_PARAM; } + + return ExcuteDelete(key, removeReason); +} + +ErrCode AdvancedNotificationService::ExcuteDelete(const std::string &key, const int32_t removeReason) +{ ErrCode result = ERR_OK; ffrt::task_handle handler = notificationSvrQueue_->submit_h(std::bind([&]() { ANS_LOGD("ffrt enter!"); @@ -503,18 +569,32 @@ ErrCode AdvancedNotificationService::DeleteAll() { ANS_LOGD("%{public}s", __FUNCTION__); + const int32_t reason = NotificationConstant::CANCEL_ALL_REASON_DELETE; bool isSubsystem = AccessTokenHelper::VerifyNativeToken(IPCSkeleton::GetCallingTokenID()); if (!isSubsystem && !AccessTokenHelper::IsSystemApp()) { + std::string message = "not system app."; + OHOS::Notification::HaMetaMessage haMetaMessage = HaMetaMessage(6, 8) + .ErrorCode(ERR_ANS_NON_SYSTEM_APP); + ReportDeleteFailedEventPush(haMetaMessage, reason, message); + ANS_LOGE("%{public}s", message.c_str()); return ERR_ANS_NON_SYSTEM_APP; } if (!AccessTokenHelper::CheckPermission(OHOS_PERMISSION_NOTIFICATION_CONTROLLER)) { - ANS_LOGD("AccessTokenHelper::CheckPermission is false."); + std::string message = "no acl permission."; + OHOS::Notification::HaMetaMessage haMetaMessage = HaMetaMessage(6, 9) + .ErrorCode(ERR_ANS_PERMISSION_DENIED); + ReportDeleteFailedEventPush(haMetaMessage, reason, message); + ANS_LOGE("%{public}s", message.c_str()); return ERR_ANS_PERMISSION_DENIED; } if (notificationSvrQueue_ == nullptr) { - ANS_LOGE("Serial queue is invalidity."); + std::string message = "Serial queue is invalidity."; + OHOS::Notification::HaMetaMessage haMetaMessage = HaMetaMessage(6, 10) + .ErrorCode(ERR_ANS_INVALID_PARAM); + ReportDeleteFailedEventPush(haMetaMessage, reason, message); + ANS_LOGE("%{public}s", message.c_str()); return ERR_ANS_INVALID_PARAM; } ErrCode result = ERR_OK; @@ -540,7 +620,6 @@ ErrCode AdvancedNotificationService::DeleteAll() } if (notification->GetUserId() == activeUserId) { - int32_t reason = NotificationConstant::CANCEL_ALL_REASON_DELETE; UpdateRecentNotification(notification, true, reason); notifications.emplace_back(notification); #ifdef DISTRIBUTED_NOTIFICATION_SUPPORTED @@ -549,12 +628,12 @@ ErrCode AdvancedNotificationService::DeleteAll() } if (notifications.size() >= MAX_CANCELED_PARCELABLE_VECTOR_NUM) { ANS_LOGD("Notifications size greater than or equal to MAX_CANCELED_PARCELABLE_VECTOR_NUM."); - SendNotificationsOnCanceled(notifications, nullptr, NotificationConstant::CANCEL_ALL_REASON_DELETE); + SendNotificationsOnCanceled(notifications, nullptr, reason); } } if (!notifications.empty()) { NotificationSubscriberManager::GetInstance()->BatchNotifyCanceled( - notifications, nullptr, NotificationConstant::CANCEL_REASON_DELETE); + notifications, nullptr, reason); } result = ERR_OK; @@ -694,11 +773,16 @@ ErrCode AdvancedNotificationService::RequestEnableNotification(const std::string } // To get the permission bool allowedNotify = false; + HaMetaMessage message = HaMetaMessage(EventSceneId::SCENE_2, EventBranchId::BRANCH_1) + .BundleName(bundleOption->GetBundleName()); result = IsAllowedNotifySelf(bundleOption, allowedNotify); if (result != ERR_OK) { + message.Message("Allow notify self failed: " + std::to_string(result)); + NotificationAnalyticsUtil::ReportModifyEvent(message); return ERROR_INTERNAL_ERROR; } - ANS_LOGI("allowedNotify = %{public}d", allowedNotify); + ANS_LOGI("allowedNotify = %{public}d, bundle = %{public}s", allowedNotify, + bundleOption->GetBundleName().c_str()); if (allowedNotify) { return ERR_OK; } @@ -706,6 +790,8 @@ ErrCode AdvancedNotificationService::RequestEnableNotification(const std::string bool hasPopped = false; result = GetHasPoppedDialog(bundleOption, hasPopped); if (result != ERR_OK) { + message.Message("Has popped dialog: " + std::to_string(result)); + NotificationAnalyticsUtil::ReportModifyEvent(message); return ERROR_INTERNAL_ERROR; } if (hasPopped) { @@ -720,6 +806,8 @@ ErrCode AdvancedNotificationService::RequestEnableNotification(const std::string if (result == ERR_OK) { result = ERR_ANS_DIALOG_POP_SUCCEEDED; } + message.Message("Request dialog: " + std::to_string(result)); + NotificationAnalyticsUtil::ReportModifyEvent(message); return result; } @@ -801,13 +889,13 @@ ErrCode AdvancedNotificationService::SetNotificationsEnabledForSpecialBundle( bundle, notificationEnable); // Local device result = NotificationPreferences::GetInstance()->SetNotificationsEnabledForBundle(bundle, enabled); - if (!enabled) { - result = RemoveAllNotificationsForDisable(bundle); - } - if (saveRef != ERR_OK) { - SetSlotFlagsTrustlistsAsBundle(bundle); - } if (result == ERR_OK) { + if (!enabled) { + result = RemoveAllNotificationsForDisable(bundle); + } + if (saveRef != ERR_OK) { + SetSlotFlagsTrustlistsAsBundle(bundle); + } NotificationSubscriberManager::GetInstance()->NotifyEnabledNotificationChanged(bundleData); PublishSlotChangeCommonEvent(bundle); } @@ -869,6 +957,7 @@ ErrCode AdvancedNotificationService::CanPopEnableNotificationDialog( ANS_LOGD("%{public}s", __FUNCTION__); canPop = false; ErrCode result = ERR_OK; + HaMetaMessage message = HaMetaMessage(EventSceneId::SCENE_2, EventBranchId::BRANCH_2); sptr bundleOption = GenerateBundleOption(); if (bundleOption == nullptr) { ANS_LOGE("bundleOption == nullptr"); @@ -876,8 +965,11 @@ ErrCode AdvancedNotificationService::CanPopEnableNotificationDialog( } // To get the permission bool allowedNotify = false; + message.BundleName(bundleOption->GetBundleName()); result = IsAllowedNotifySelf(bundleOption, allowedNotify); if (result != ERR_OK) { + message.Message("Allow notify self failed: " + std::to_string(result)); + NotificationAnalyticsUtil::ReportModifyEvent(message); return ERROR_INTERNAL_ERROR; } ANS_LOGI("allowedNotify = %{public}d", allowedNotify); @@ -888,6 +980,8 @@ ErrCode AdvancedNotificationService::CanPopEnableNotificationDialog( bool hasPopped = false; result = GetHasPoppedDialog(bundleOption, hasPopped); if (result != ERR_OK) { + message.Message("Has popped dialog: " + std::to_string(result)); + NotificationAnalyticsUtil::ReportModifyEvent(message); return ERROR_INTERNAL_ERROR; } if (hasPopped) { @@ -904,32 +998,7 @@ ErrCode AdvancedNotificationService::CanPopEnableNotificationDialog( canPop = true; bundleName = bundleOption->GetBundleName(); - return ERR_OK; ANS_LOGI("CanPopEnableNotificationDialog end"); -} - -ErrCode AdvancedNotificationService::RemoveEnableNotificationDialog() -{ - ANS_LOGD("%{public}s", __FUNCTION__); - ErrCode result = ERR_OK; - sptr bundleOption = GenerateBundleOption(); - if (bundleOption == nullptr) { - ANS_LOGE("bundleOption == nullptr"); - return ERR_ANS_INVALID_BUNDLE; - } - return RemoveEnableNotificationDialog(bundleOption); -} - -ErrCode AdvancedNotificationService::RemoveEnableNotificationDialog(const sptr &bundleOption) -{ - ANS_LOGI("RemoveEnableNotificationDialog %{public}s, %{public}d", - bundleOption->GetBundleName().c_str(), - bundleOption->GetUid()); - if (!CreateDialogManager()) { - return ERROR_INTERNAL_ERROR; - } - std::unique_ptr dialogInfoRemoved = nullptr; - dialogManager_->RemoveDialogInfoByBundleOption(bundleOption, dialogInfoRemoved); return ERR_OK; } @@ -953,6 +1022,7 @@ ErrCode AdvancedNotificationService::IsAllowedNotifySelf(const sptrGetNotificationsEnabledForBundle(bundleOption, allowed); if (result == ERR_ANS_PREFERENCES_NOTIFICATION_BUNDLE_NOT_EXIST) { + SetSlotFlagsTrustlistsAsBundle(bundleOption); result = ERR_OK; // FA model app can publish notification without user confirm allowed = CheckApiCompatibility(bundleOption); @@ -1002,7 +1072,7 @@ ErrCode AdvancedNotificationService::IsSpecialBundleAllowedNotify( } int32_t callingUid = IPCSkeleton::GetCallingUid(); - if ((callingUid != ANS_UID && callingUid != BROKER_UID && callingUid != PAC_UID) + if ((callingUid != ANS_UID && callingUid != BROKER_UID) && !AccessTokenHelper::CheckPermission(OHOS_PERMISSION_NOTIFICATION_CONTROLLER)) { return ERR_ANS_PERMISSION_DENIED; } @@ -1270,12 +1340,21 @@ ErrCode AdvancedNotificationService::RemoveNotification(const sptrwait(handler); - + if (result != ERR_OK) { + std::string message = "remove notificaiton error"; + OHOS::Notification::HaMetaMessage haMetaMessage = HaMetaMessage(4, 7) + .ErrorCode(result).NotificationId(notificationId); + ReportDeleteFailedEventPush(haMetaMessage, removeReason, message); + ANS_LOGE("%{public}s", message.c_str()); + } SendRemoveHiSysEvent(notificationId, label, bundleOption, result); return result; } @@ -1351,7 +1440,7 @@ ErrCode AdvancedNotificationService::RemoveAllNotificationsForDisable( ErrCode AdvancedNotificationService::RemoveAllNotifications(const sptr &bundleOption) { - return RemoveAllNotificationsInner(bundleOption, NotificationConstant::CANCEL_REASON_DELETE); + return RemoveAllNotificationsInner(bundleOption, NotificationConstant::APP_REMOVE_ALL_REASON_DELETE); } ErrCode AdvancedNotificationService::RemoveAllNotificationsInner(const sptr &bundleOption, @@ -1362,22 +1451,40 @@ ErrCode AdvancedNotificationService::RemoveAllNotificationsInner(const sptr bundle = GenerateValidBundleOption(bundleOption); if (bundle == nullptr) { + std::string message = "budle is nullptr."; + OHOS::Notification::HaMetaMessage haMetaMessage = HaMetaMessage(6, 3) + .ErrorCode(ERR_ANS_INVALID_BUNDLE); + ReportDeleteFailedEventPush(haMetaMessage, reason, message); + ANS_LOGE("%{public}s", message.c_str()); return ERR_ANS_INVALID_BUNDLE; } if (notificationSvrQueue_ == nullptr) { - ANS_LOGE("Serial queue is nullptr."); + std::string message = "Serial queue is nullptr."; + OHOS::Notification::HaMetaMessage haMetaMessage = HaMetaMessage(6, 4) + .ErrorCode(ERR_ANS_INVALID_BUNDLE); + ReportDeleteFailedEventPush(haMetaMessage, reason, message); + ANS_LOGE("%{public}s", message.c_str()); return ERR_ANS_INVALID_PARAM; } ffrt::task_handle handler = notificationSvrQueue_->submit_h(std::bind([&]() { @@ -1389,10 +1496,12 @@ ErrCode AdvancedNotificationService::RemoveAllNotificationsInner(const sptrnotification->IsRemoveAllowed() && isAllowedNotification) { + ANS_LOGI("BatchRemove-FILTER-RemoveNotAllowed-%{public}s", record->notification->GetKey().c_str()); continue; } if (record->slot != nullptr) { if (record->slot->GetForceControl() && record->slot->GetEnable()) { + ANS_LOGI("BatchRemove-FILTER-ForceControl-%{public}s", record->notification->GetKey().c_str()); continue; } } @@ -1500,7 +1609,7 @@ ErrCode AdvancedNotificationService::RemoveNotifications( } ErrCode AdvancedNotificationService::RemoveNotificationBySlot(const sptr &bundleOption, - const sptr &slot) + const sptr &slot, const int reason) { HITRACE_METER_NAME(HITRACE_TAG_NOTIFICATION, __PRETTY_FUNCTION__); ANS_LOGD("%{public}s", __FUNCTION__); @@ -1621,20 +1730,44 @@ ErrCode AdvancedNotificationService::CancelGroup(const std::string &groupName, i { ANS_LOGD("%{public}s", __FUNCTION__); + int32_t reason = NotificationConstant::APP_CANCEL_GROPU_REASON_DELETE; if (groupName.empty()) { + std::string message = "groupName empty."; + OHOS::Notification::HaMetaMessage haMetaMessage = HaMetaMessage(3, 1) + .ErrorCode(ERR_ANS_INVALID_PARAM); + ReportDeleteFailedEventPush(haMetaMessage, reason, message); + ANS_LOGE("%{public}s", message.c_str()); return ERR_ANS_INVALID_PARAM; } sptr bundleOption = GenerateBundleOption(); if (bundleOption == nullptr) { + std::string message = "bundle is nullptr."; + OHOS::Notification::HaMetaMessage haMetaMessage = HaMetaMessage(3, 2) + .ErrorCode(ERR_ANS_INVALID_BUNDLE); + ReportDeleteFailedEventPush(haMetaMessage, reason, message); + ANS_LOGE("%{public}s", message.c_str()); return ERR_ANS_INVALID_BUNDLE; } bundleOption->SetInstanceKey(instanceKey); if (notificationSvrQueue_ == nullptr) { - ANS_LOGE("Serial queue is invalid."); + std::string message = "Serial queue is invalid."; + OHOS::Notification::HaMetaMessage haMetaMessage = HaMetaMessage(3, 3) + .ErrorCode(ERR_ANS_INVALID_PARAM); + ReportDeleteFailedEventPush(haMetaMessage, reason, message); + ANS_LOGE("%{public}s", message.c_str()); return ERR_ANS_INVALID_PARAM; } + + ExcuteCancelGroupCancel(bundleOption, groupName, reason); + return ERR_OK; +} + +void AdvancedNotificationService::ExcuteCancelGroupCancel( + const sptr& bundleOption, + const std::string &groupName, const int32_t reason) +{ ffrt::task_handle handler = notificationSvrQueue_->submit_h(std::bind([&]() { ANS_LOGD("ffrt enter!"); std::vector> removeList; @@ -1653,7 +1786,6 @@ ErrCode AdvancedNotificationService::CancelGroup(const std::string &groupName, i for (auto record : removeList) { notificationList_.remove(record); if (record->notification != nullptr) { - int32_t reason = NotificationConstant::APP_CANCEL_REASON_DELETE; UpdateRecentNotification(record->notification, true, reason); notifications.emplace_back(record->notification); #ifdef DISTRIBUTED_NOTIFICATION_SUPPORTED @@ -1663,46 +1795,68 @@ ErrCode AdvancedNotificationService::CancelGroup(const std::string &groupName, i if (notifications.size() >= MAX_CANCELED_PARCELABLE_VECTOR_NUM) { std::vector> currNotificationList = notifications; NotificationSubscriberManager::GetInstance()->BatchNotifyCanceled( - currNotificationList, nullptr, NotificationConstant::APP_CANCEL_REASON_DELETE); + currNotificationList, nullptr, reason); notifications.clear(); } } if (!notifications.empty()) { NotificationSubscriberManager::GetInstance()->BatchNotifyCanceled( - notifications, nullptr, NotificationConstant::APP_CANCEL_REASON_DELETE); + notifications, nullptr, reason); } })); notificationSvrQueue_->wait(handler); - - return ERR_OK; } ErrCode AdvancedNotificationService::RemoveGroupByBundle( const sptr &bundleOption, const std::string &groupName) { ANS_LOGD("%{public}s", __FUNCTION__); - + const int32_t reason = NotificationConstant::APP_REMOVE_GROUP_REASON_DELETE; bool isSubsystem = AccessTokenHelper::VerifyNativeToken(IPCSkeleton::GetCallingTokenID()); if (!isSubsystem && !AccessTokenHelper::IsSystemApp()) { + std::string message = "not systemApp."; + OHOS::Notification::HaMetaMessage haMetaMessage = HaMetaMessage(5, 1) + .ErrorCode(ERR_ANS_NON_SYSTEM_APP); + ReportDeleteFailedEventPush(haMetaMessage, reason, message); + ANS_LOGE("%{public}s", message.c_str()); return ERR_ANS_NON_SYSTEM_APP; } if (!AccessTokenHelper::CheckPermission(OHOS_PERMISSION_NOTIFICATION_CONTROLLER)) { + std::string message = "no acl permission"; + OHOS::Notification::HaMetaMessage haMetaMessage = HaMetaMessage(5, 2) + .ErrorCode(ERR_ANS_PERMISSION_DENIED); + ReportDeleteFailedEventPush(haMetaMessage, reason, message); + ANS_LOGE("%{public}s", message.c_str()); return ERR_ANS_PERMISSION_DENIED; } if (bundleOption == nullptr || groupName.empty()) { + std::string message = "groupName empty"; + OHOS::Notification::HaMetaMessage haMetaMessage = HaMetaMessage(5, 3) + .ErrorCode(ERR_ANS_INVALID_PARAM); + ReportDeleteFailedEventPush(haMetaMessage, reason, message); + ANS_LOGE("%{public}s", message.c_str()); return ERR_ANS_INVALID_PARAM; } sptr bundle = GenerateValidBundleOption(bundleOption); if (bundle == nullptr) { + std::string message = "bundle is nullptr"; + OHOS::Notification::HaMetaMessage haMetaMessage = HaMetaMessage(5, 4) + .ErrorCode(ERR_ANS_INVALID_PARAM); + ReportDeleteFailedEventPush(haMetaMessage, reason, message); + ANS_LOGE("%{public}s", message.c_str()); return ERR_ANS_INVALID_BUNDLE; } if (notificationSvrQueue_ == nullptr) { - ANS_LOGE("Serial queue is invalid."); + std::string message = "Serial queue is invalid."; + OHOS::Notification::HaMetaMessage haMetaMessage = HaMetaMessage(5, 5) + .ErrorCode(ERR_ANS_INVALID_PARAM); + ReportDeleteFailedEventPush(haMetaMessage, reason, message); + ANS_LOGE("%{public}s", message.c_str()); return ERR_ANS_INVALID_PARAM; } ffrt::task_handle handler = notificationSvrQueue_->submit_h(std::bind([&]() { @@ -1909,10 +2063,10 @@ ErrCode AdvancedNotificationService::SetEnabledForBundleSlot(const sptrGetEnable()) { - RemoveNotificationBySlot(bundle, slot); + RemoveNotificationBySlot(bundle, slot, NotificationConstant::DISABLE_SLOT_REASON_DELETE); } else { if (!slot->GetForceControl() && !allowed) { - RemoveNotificationBySlot(bundle, slot); + RemoveNotificationBySlot(bundle, slot, NotificationConstant::DISABLE_NOTIFICATION_REASON_DELETE); } } @@ -1999,14 +2153,12 @@ ErrCode AdvancedNotificationService::PublishNotificationBySa(const sptrGetCreatorUid(); if (request->GetOwnerUid() != DEFAULT_UID) { std::shared_ptr agentBundle = std::make_shared("", uid); - if (agentBundle == nullptr) { - ANS_LOGE("Failed to create agentBundle instance"); - return ERR_ANS_INVALID_BUNDLE; - } request->SetAgentBundle(agentBundle); } @@ -2014,7 +2166,8 @@ ErrCode AdvancedNotificationService::PublishNotificationBySa(const sptrGetOwnerUid(); } if (uid <= 0) { - ANS_LOGE("CreatorUid[%{public}d] error", uid); + message.ErrorCode(ERR_ANS_INVALID_UID).Message("createUid failed" + std::to_string(uid), true); + NotificationAnalyticsUtil::ReportPublishFailedEvent(request, message); return ERR_ANS_INVALID_UID; } std::string bundle = ""; @@ -2030,11 +2183,11 @@ ErrCode AdvancedNotificationService::PublishNotificationBySa(const sptrGetSound().empty()) { request->SetSound(""); } - std::shared_ptr record = std::make_shared(); record->request = request; if (request->IsAgentNotification()) { @@ -2058,13 +2211,12 @@ ErrCode AdvancedNotificationService::PublishNotificationBySa(const sptrrequest, bundleOption); result = FlowControl(record); if (result != ERR_OK) { return result; } - + SetRequestBySlotType(record->request, bundleOption); #ifdef ENABLE_ANS_EXT_WRAPPER EXTENTION_WRAPPER->GetUnifiedGroupInfo(request); #endif @@ -2078,7 +2230,7 @@ ErrCode AdvancedNotificationService::PublishNotificationBySa(const sptr( record->request->GetContent()->GetNotificationContent())->GetType() == TYPE_CODE_DOWNLOAD)) { @@ -2105,7 +2257,7 @@ ErrCode AdvancedNotificationService::PublishNotificationBySa(const sptrrequest->GetAutoDeletedTime() > GetCurrentTime()) && !record->request->IsCommonLiveView()) { StartAutoDelete(record, - record->request->GetAutoDeletedTime(), NotificationConstant::APP_CANCEL_REASON_DELETE); + record->request->GetAutoDeletedTime(), NotificationConstant::TRIGGER_AUTO_DELETE_REASON_DELETE); } return ERR_OK; } @@ -2131,27 +2283,35 @@ ErrCode AdvancedNotificationService::SetBadgeNumber(int32_t badgeNumber, int32_t NotificationSubscriberManager::GetInstance()->SetBadgeNumber(badgeData); }); notificationSvrQueue_->wait(handler); + HaMetaMessage message = HaMetaMessage(EventSceneId::SCENE_3, EventBranchId::BRANCH_1) + .Message("Set badge number " + bundleName + " " + std::to_string(badgeNumber) + + " " + std::to_string(instanceKey)); + NotificationAnalyticsUtil::ReportModifyEvent(message); return ERR_OK; } ErrCode AdvancedNotificationService::SetBadgeNumberByBundle( const sptr &bundleOption, int32_t badgeNumber) { + HaMetaMessage message = HaMetaMessage(EventSceneId::SCENE_7, EventBranchId::BRANCH_1); if (notificationSvrQueue_ == nullptr) { - ANS_LOGE("Serial queue is invalid."); + message.Message("Serial queue is invalid.", true); + NotificationAnalyticsUtil::ReportModifyEvent(message); return ERR_ANS_INVALID_PARAM; } bool isSubsystem = AccessTokenHelper::VerifyNativeToken(IPCSkeleton::GetCallingTokenID()); if (!isSubsystem && !AccessTokenHelper::IsSystemApp()) { - ANS_LOGE("Client is not a system app or subsystem."); + message.Message("Client is not a system app or subsystem.", true); + NotificationAnalyticsUtil::ReportModifyEvent(message); return ERR_ANS_NON_SYSTEM_APP; } sptr bundle = bundleOption; ErrCode result = CheckBundleOptionValid(bundle); if (result != ERR_OK) { - ANS_LOGE("Input parameter bundle option is not correct."); + message.Message("Input bundle option is not correct: " + std::to_string(result), true); + NotificationAnalyticsUtil::ReportModifyEvent(message); return result; } @@ -2164,7 +2324,8 @@ ErrCode AdvancedNotificationService::SetBadgeNumberByBundle( bool isAgent = false; isAgent = IsAgentRelationship(bundleName, bundle->GetBundleName()); if (!isAgent) { - ANS_LOGE("The caller has no agent relationship with the specified bundle."); + message.Message("the caller has no agent relationship with the specified bundle.", true); + NotificationAnalyticsUtil::ReportModifyEvent(message); return ERR_ANS_NO_AGENT_SETTING; } } @@ -2180,6 +2341,9 @@ ErrCode AdvancedNotificationService::SetBadgeNumberByBundle( NotificationSubscriberManager::GetInstance()->SetBadgeNumber(badgeData); }); notificationSvrQueue_->wait(handler); + message.Message("Set badgenumber: " + bundle->GetBundleName() + ":" + + std::to_string(badgeNumber) + " " + std::to_string(result)); + NotificationAnalyticsUtil::ReportModifyEvent(message); return result; } @@ -2262,7 +2426,7 @@ ErrCode AdvancedNotificationService::IsDistributedEnabledByBundle(const sptr bundle = GenerateValidBundleOption(bundleOption); if (bundle == nullptr) { return ERR_ANS_INVALID_BUNDLE; @@ -2289,6 +2453,26 @@ ErrCode AdvancedNotificationService::DuplicateMsgControl(const sptr &bundleOption) +{ + if (bundleOption == nullptr) { + ANS_LOGE("bundleOption is nullptr"); + return; + } + const char *keySpliter = "_"; + std::stringstream stream; + stream << bundleOption->GetUid() << keySpliter << bundleOption->GetBundleName() << keySpliter; + std::string uniqueKeyHead = stream.str(); + auto iter = uniqueKeyList_.begin(); + for (auto iter = uniqueKeyList_.begin(); iter != uniqueKeyList_.end();) { + if ((*iter).second.find(uniqueKeyHead) == 0) { + iter = uniqueKeyList_.erase(iter); + } else { + ++iter; + } + } +} + void AdvancedNotificationService::RemoveExpiredUniqueKey() { std::chrono::system_clock::time_point now = std::chrono::system_clock::now(); diff --git a/services/ans/src/advanced_notification_service.cpp b/services/ans/src/advanced_notification_service.cpp index 276e0ebbc..27ccf4816 100644 --- a/services/ans/src/advanced_notification_service.cpp +++ b/services/ans/src/advanced_notification_service.cpp @@ -205,7 +205,7 @@ ErrCode AdvancedNotificationService::PrepareNotificationRequest(const sptrSetOwnerBundleName(bundle); } - + int32_t uid = IPCSkeleton::GetCallingUid(); int32_t pid = IPCSkeleton::GetCallingPid(); request->SetCreatorUid(uid); @@ -361,16 +361,25 @@ ErrCode AdvancedNotificationService::AssignToNotificationList(const std::shared_ return result; } -ErrCode AdvancedNotificationService::CancelPreparedNotification( - int32_t notificationId, const std::string &label, const sptr &bundleOption) +ErrCode AdvancedNotificationService::CancelPreparedNotification(int32_t notificationId, + const std::string &label, const sptr &bundleOption, int32_t reason) { HITRACE_METER_NAME(HITRACE_TAG_NOTIFICATION, __PRETTY_FUNCTION__); if (bundleOption == nullptr) { + std::string message = "bundleOption is null"; + OHOS::Notification::HaMetaMessage haMetaMessage = HaMetaMessage(1, 2) + .ErrorCode(ERR_ANS_INVALID_BUNDLE).NotificationId(notificationId); + ReportDeleteFailedEventPush(haMetaMessage, reason, message); + ANS_LOGE("%{public}s", message.c_str()); return ERR_ANS_INVALID_BUNDLE; } if (notificationSvrQueue_ == nullptr) { - ANS_LOGE("Serial queue is invalidity."); + std::string message = "notificationSvrQueue is null"; + OHOS::Notification::HaMetaMessage haMetaMessage = HaMetaMessage(1, 3) + .ErrorCode(ERR_ANS_INVALID_PARAM).NotificationId(notificationId); + ReportDeleteFailedEventPush(haMetaMessage, reason, message); + ANS_LOGE("%{public}s", message.c_str()); return ERR_ANS_INVALID_PARAM; } ErrCode result = ERR_OK; @@ -383,7 +392,6 @@ ErrCode AdvancedNotificationService::CancelPreparedNotification( } if (notification != nullptr) { - int32_t reason = NotificationConstant::APP_CANCEL_REASON_DELETE; UpdateRecentNotification(notification, true, reason); NotificationSubscriberManager::GetInstance()->NotifyCanceled(notification, nullptr, reason); #ifdef DISTRIBUTED_NOTIFICATION_SUPPORTED @@ -400,6 +408,7 @@ ErrCode AdvancedNotificationService::PrepareNotificationInfo( const sptr &request, sptr &bundleOption) { HITRACE_METER_NAME(HITRACE_TAG_NOTIFICATION, __PRETTY_FUNCTION__); + HaMetaMessage message = HaMetaMessage(EventSceneId::SCENE_4, EventBranchId::BRANCH_3); if (request == nullptr) { ANS_LOGE("request is invalid."); return ERR_ANS_INVALID_PARAM; @@ -411,6 +420,8 @@ ErrCode AdvancedNotificationService::PrepareNotificationInfo( } ErrCode result = PrepareNotificationRequest(request); if (result != ERR_OK) { + message.ErrorCode(result); + NotificationAnalyticsUtil::ReportPublishFailedEvent(request, message); return result; } @@ -434,6 +445,8 @@ ErrCode AdvancedNotificationService::PrepareNotificationInfo( } if (bundleOption == nullptr) { + message.ErrorCode(ERR_ANS_INVALID_BUNDLE); + NotificationAnalyticsUtil::ReportPublishFailedEvent(request, message); return ERR_ANS_INVALID_BUNDLE; } ANS_LOGI( @@ -443,13 +456,17 @@ ErrCode AdvancedNotificationService::PrepareNotificationInfo( return ERR_OK; } -ErrCode AdvancedNotificationService::StartFinishTimer( - const std::shared_ptr &record, int64_t expiredTimePoint) +ErrCode AdvancedNotificationService::StartFinishTimer(const std::shared_ptr &record, + int64_t expiredTimePoint, const int32_t reason) { uint64_t timerId = StartAutoDelete(record, - expiredTimePoint, NotificationConstant::APP_CANCEL_REASON_OTHER); + expiredTimePoint, reason); if (timerId == NotificationConstant::INVALID_TIMER_ID) { - ANS_LOGE("Start finish auto delete timer failed."); + std::string message = "Start finish auto delete timer failed."; + OHOS::Notification::HaMetaMessage haMetaMessage = HaMetaMessage(7, 1) + .ErrorCode(ERR_ANS_TASK_ERR); + ReportDeleteFailedEventPush(haMetaMessage, reason, message); + ANS_LOGE("%{public}s", message.c_str()); return ERR_ANS_TASK_ERR; } record->notification->SetFinishTimer(timerId); @@ -459,7 +476,8 @@ ErrCode AdvancedNotificationService::StartFinishTimer( ErrCode AdvancedNotificationService::SetFinishTimer(const std::shared_ptr &record) { int64_t maxExpiredTime = GetCurrentTime() + NotificationConstant::MAX_FINISH_TIME; - auto result = StartFinishTimer(record, maxExpiredTime); + auto result = StartFinishTimer(record, maxExpiredTime, + NotificationConstant::TRIGGER_EIGHT_HOUR_REASON_DELETE); if (result != ERR_OK) { return result; } @@ -475,12 +493,17 @@ void AdvancedNotificationService::CancelFinishTimer(const std::shared_ptr &record, int64_t expireTimePoint) + const std::shared_ptr &record, int64_t expireTimePoint, + const int32_t reason) { uint64_t timerId = StartAutoDelete(record, - expireTimePoint, NotificationConstant::APP_CANCEL_REASON_OTHER); + expireTimePoint, reason); if (timerId == NotificationConstant::INVALID_TIMER_ID) { - ANS_LOGE("Start update auto delete timer failed."); + std::string message = "Start update auto delete timer failed."; + OHOS::Notification::HaMetaMessage haMetaMessage = HaMetaMessage(7, 2) + .ErrorCode(ERR_ANS_TASK_ERR); + ReportDeleteFailedEventPush(haMetaMessage, reason, message); + ANS_LOGE("%{public}s", message.c_str()); return ERR_ANS_TASK_ERR; } record->notification->SetUpdateTimer(timerId); @@ -490,7 +513,8 @@ ErrCode AdvancedNotificationService::StartUpdateTimer( ErrCode AdvancedNotificationService::SetUpdateTimer(const std::shared_ptr &record) { int64_t maxExpiredTime = GetCurrentTime() + NotificationConstant::MAX_UPDATE_TIME; - ErrCode result = StartUpdateTimer(record, maxExpiredTime); + ErrCode result = StartUpdateTimer(record, maxExpiredTime, + NotificationConstant::TRIGGER_FOUR_HOUR_REASON_DELETE); if (result != ERR_OK) { return result; } @@ -509,7 +533,8 @@ void AdvancedNotificationService::StartArchiveTimer(const std::shared_ptrrequest->GetAutoDeletedTime(); if (deleteTime == NotificationConstant::NO_DELAY_DELETE_TIME) { - TriggerAutoDelete(record->notification->GetKey(), NotificationConstant::APP_CANCEL_REASON_DELETE); + TriggerAutoDelete(record->notification->GetKey(), + NotificationConstant::TRIGGER_START_ARCHIVE_REASON_DELETE); return; } if (deleteTime <= NotificationConstant::INVALID_AUTO_DELETE_TIME) { @@ -518,7 +543,7 @@ void AdvancedNotificationService::StartArchiveTimer(const std::shared_ptrLocalControl(request); if (ctrlResult != ERR_OK) { + message.ErrorCode(ctrlResult); + NotificationAnalyticsUtil::ReportPublishFailedEvent(request, message); return ctrlResult; } #endif @@ -591,6 +620,8 @@ ErrCode AdvancedNotificationService::PublishPreparedNotification(const sptrrequest->GetAutoDeletedTime() > GetCurrentTime()) && !record->request->IsCommonLiveView()) { StartAutoDelete(record, - record->request->GetAutoDeletedTime(), NotificationConstant::APP_CANCEL_REASON_DELETE); + record->request->GetAutoDeletedTime(), NotificationConstant::TRIGGER_AUTO_DELETE_REASON_DELETE); } return result; } @@ -695,7 +726,7 @@ void AdvancedNotificationService::CheckDoNotDisturbProfile(const std::shared_ptr sptr profile = new (std::nothrow) NotificationDoNotDisturbProfile(); if (NotificationPreferences::GetInstance()->GetDoNotDisturbProfile(atoi(profileId.c_str()), userId, profile) != ERR_OK) { - ANS_LOGE("Get do not disturb profile failed."); + ANS_LOGE("profile failed. pid: %{public}s, userid: %{public}d", profileId.c_str(), userId); return; } if (profile == nullptr) { @@ -798,6 +829,12 @@ ErrCode AdvancedNotificationService::Filter(const std::shared_ptrnotification->GetKey()); result = record->request->CheckNotificationRequest((oldRecord == nullptr) ? nullptr : oldRecord->request); if (result != ERR_OK) { + bool liveView = record->request->IsCommonLiveView(); + int32_t slotType = liveView ? NotificationConstant::SlotType::LIVE_VIEW : + NotificationConstant::SlotType::ILLEGAL_TYPE; + HaMetaMessage message = HaMetaMessage(EventSceneId::SCENE_3, EventBranchId::BRANCH_5) + .ErrorCode(result).SlotType(slotType).Message("CheckNotificationRequest failed: "); + NotificationAnalyticsUtil::ReportPublishFailedEvent(record->request, message); ANS_LOGE("Notification(key %{public}s) isn't ready on publish failed with %{public}d.", record->notification->GetKey().c_str(), result); return result; @@ -824,7 +861,8 @@ ErrCode AdvancedNotificationService::Filter(const std::shared_ptr &record) +void AdvancedNotificationService::ChangeNotificationByControlFlags(const std::shared_ptr &record, + const bool isAgentController) { ANS_LOGD("Called."); if (record == nullptr || record->request == nullptr || record->notification == nullptr) { @@ -837,6 +875,10 @@ void AdvancedNotificationService::ChangeNotificationByControlFlags(const std::sh return; } + if (!isAgentController) { + record->request->SetNotificationControlFlags(notificationControlFlags & 0xFFFF); + } + auto flags = record->request->GetFlags(); if (flags == nullptr) { ANS_LOGE("The flags is nullptr."); @@ -908,6 +950,11 @@ ErrCode AdvancedNotificationService::UpdateInNotificationList(const std::shared_ std::chrono::system_clock::time_point now = std::chrono::system_clock::now(); NotificationAnalyticsUtil::RemoveExpired(flowControlUpdateTimestampList_, now); if (flowControlUpdateTimestampList_.size() >= MAX_UPDATE_NUM_PERSECOND) { + HaMetaMessage message = HaMetaMessage(EventSceneId::SCENE_2, EventBranchId::BRANCH_4) + .ErrorCode(ERR_ANS_OVER_MAX_UPDATE_PERSECOND).Message("UpdateInNotificationList failed"); + if (record != nullptr) { + NotificationAnalyticsUtil::ReportPublishFailedEvent(record->request, message); + } return ERR_ANS_OVER_MAX_UPDATE_PERSECOND; } @@ -1121,6 +1168,13 @@ ErrCode AdvancedNotificationService::RemoveFromNotificationList(const sptrnotification->IsRemoveAllowed()) { + ANS_LOGI("BatchRemove-FILTER-RemoveNotAllowed-%{public}s", record->notification->GetKey().c_str()); + std::string message = "notification unremove."; + OHOS::Notification::HaMetaMessage haMetaMessage = HaMetaMessage(1, 4) + .ErrorCode(ERR_ANS_NOTIFICATION_IS_UNALLOWED_REMOVEALLOWED); + ReportDeleteFailedEventPushByNotification(record->notification, haMetaMessage, + NotificationConstant::DEFAULT_REASON_DELETE, message); + ANS_LOGE("%{public}s", message.c_str()); return ERR_ANS_NOTIFICATION_IS_UNALLOWED_REMOVEALLOWED; } notification = record->notification; @@ -1163,6 +1217,12 @@ ErrCode AdvancedNotificationService::RemoveFromNotificationList( } if (!isCancel && !record->notification->IsRemoveAllowed()) { + std::string message = "notification unremove."; + OHOS::Notification::HaMetaMessage haMetaMessage = HaMetaMessage(1, 7) + .ErrorCode(ERR_ANS_NOTIFICATION_IS_UNALLOWED_REMOVEALLOWED); + ReportDeleteFailedEventPushByNotification(record->notification, haMetaMessage, + removeReason, message); + ANS_LOGE("%{public}s", message.c_str()); return ERR_ANS_NOTIFICATION_IS_UNALLOWED_REMOVEALLOWED; } notification = record->notification; @@ -1384,10 +1444,13 @@ static bool SortNotificationsByLevelAndTime( ErrCode AdvancedNotificationService::FlowControl(const std::shared_ptr &record) { + HaMetaMessage message = HaMetaMessage(EventSceneId::SCENE_4, EventBranchId::BRANCH_2); std::chrono::system_clock::time_point now = std::chrono::system_clock::now(); std::lock_guard lock(flowControlMutex_); NotificationAnalyticsUtil::RemoveExpired(flowControlTimestampList_, now); if (flowControlTimestampList_.size() >= MAX_ACTIVE_NUM_PERSECOND + MAX_UPDATE_NUM_PERSECOND) { + message.ErrorCode(ERR_ANS_OVER_MAX_ACTIVE_PERSECOND); + NotificationAnalyticsUtil::ReportPublishFailedEvent(record->request, message); return ERR_ANS_OVER_MAX_ACTIVE_PERSECOND; } flowControlTimestampList_.push_back(now); @@ -1400,6 +1463,11 @@ ErrCode AdvancedNotificationService::PublishFlowControl(const std::shared_ptr= MAX_ACTIVE_NUM_PERSECOND) { + HaMetaMessage message = HaMetaMessage(EventSceneId::SCENE_2, EventBranchId::BRANCH_3) + .ErrorCode(ERR_ANS_OVER_MAX_ACTIVE_PERSECOND).Message("PublishFlowControl failed"); + if (record != nullptr) { + NotificationAnalyticsUtil::ReportPublishFailedEvent(record->request, message); + } return ERR_ANS_OVER_MAX_ACTIVE_PERSECOND; } @@ -1943,6 +2011,11 @@ ErrCode AdvancedNotificationService::PushCheck(const sptr & } ErrCode result = pushCallBack->OnCheckNotification(jsonObject.dump(), nullptr); + if (result != ERR_OK) { + HaMetaMessage message = HaMetaMessage(EventSceneId::SCENE_2, EventBranchId::BRANCH_5) + .ErrorCode(result).Message("Push OnCheckNotification failed."); + NotificationAnalyticsUtil::ReportPublishFailedEvent(request, message); + } return result; } @@ -2090,7 +2163,8 @@ ErrCode AdvancedNotificationService::CheckSystemLiveView(const sptr &record, bool isSystemApp, bool isUpdateByOwner) + const std::shared_ptr &record, bool isSystemApp, bool isUpdateByOwner, + const bool isAgentController) { auto result = AssignValidNotificationSlot(record, record->bundleOption); if (result != ERR_OK) { @@ -2105,7 +2179,7 @@ ErrCode AdvancedNotificationService::AddRecordToMemory( } if (isSystemApp) { - ChangeNotificationByControlFlags(record); + ChangeNotificationByControlFlags(record, isAgentController); } CheckDoNotDisturbProfile(record); diff --git a/services/ans/src/advanced_notification_service_ability.cpp b/services/ans/src/advanced_notification_service_ability.cpp index 84a5ceed6..8c542f798 100644 --- a/services/ans/src/advanced_notification_service_ability.cpp +++ b/services/ans/src/advanced_notification_service_ability.cpp @@ -51,7 +51,7 @@ void AdvancedNotificationServiceAbility::OnStart() AddSystemAbilityListener(DISTRIBUTED_KV_DATA_SERVICE_ABILITY_ID); AddSystemAbilityListener(COMMON_EVENT_SERVICE_ID); #else - ANS_LOGI("Not enabled ans_ext"); + ANS_LOGD("Not enabled ans_ext"); #endif #ifdef ENABLE_ANS_TELEPHONY_CUST_WRAPPER diff --git a/services/ans/src/advanced_notification_slot_service.cpp b/services/ans/src/advanced_notification_slot_service.cpp index f0d6caa41..53f96f74e 100644 --- a/services/ans/src/advanced_notification_slot_service.cpp +++ b/services/ans/src/advanced_notification_slot_service.cpp @@ -31,6 +31,8 @@ #include "ipc_skeleton.h" #ifdef NOTIFICATION_SMART_REMINDER_SUPPORTED #include "smart_reminder_center.h" +#else +#include "notification_config_parse.h" #endif #include "advanced_notification_inline.cpp" @@ -45,7 +47,7 @@ namespace { constexpr char CTRL_LIST_KEY_NAME[] = "NOTIFICATION_CTL_LIST_PKG"; constexpr char CALL_UI_BUNDLE[] = "com.ohos.callui"; } -const uint32_t DEFAULT_SLOT_FLAGS = 59; // 0b111011 + ErrCode AdvancedNotificationService::AddSlots(const std::vector> &slots) { ANS_LOGD("%{public}s", __FUNCTION__); @@ -420,9 +422,7 @@ ErrCode AdvancedNotificationService::SetSlotFlagsAsBundle(const sptr slot; NotificationConstant::SlotType slotType = record->request->GetSlotType(); + HaMetaMessage message = HaMetaMessage(EventSceneId::SCENE_7, EventBranchId::BRANCH_3).SlotType(slotType); ErrCode 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)) { slot = new (std::nothrow) NotificationSlot(slotType); if (slot == nullptr) { ANS_LOGE("Failed to create NotificationSlot instance"); + message.ErrorCode(ERR_NO_MEMORY).Message("Create failed"); + NotificationAnalyticsUtil::ReportPublishFailedEvent(record->request, message); return ERR_NO_MEMORY; } @@ -481,10 +484,16 @@ ErrCode AdvancedNotificationService::AssignValidNotificationSlot(const std::shar DelayedSingleton::GetInstance()->IsLiveViewTrtust(bundleOption->GetBundleName())))) { record->slot = slot; } else { + message.ErrorCode(ERR_ANS_PREFERENCES_NOTIFICATION_SLOT_ENABLED); + NotificationAnalyticsUtil::ReportPublishFailedEvent(record->request, message); result = ERR_ANS_PREFERENCES_NOTIFICATION_SLOT_ENABLED; ANS_LOGE("Type[%{public}d] slot enable closed", slotType); } } + if (result != ERR_OK) { + message.ErrorCode(result).Message("assign slot failed"); + NotificationAnalyticsUtil::ReportPublishFailedEvent(record->request, message); + } return result; } @@ -526,10 +535,10 @@ ErrCode AdvancedNotificationService::UpdateSlotReminderModeBySlotFlags( return ret; } -void AdvancedNotificationService::GenerateSlotReminderMode( - const sptr &slot, const sptr &bundle, bool isSpecifiedSlot) +void AdvancedNotificationService::GenerateSlotReminderMode(const sptr &slot, + const sptr &bundle, bool isSpecifiedSlot, uint32_t defaultSlotFlags) { - uint32_t slotFlags = DEFAULT_SLOT_FLAGS; + uint32_t slotFlags = defaultSlotFlags; auto ret = NotificationPreferences::GetInstance()->GetNotificationSlotFlagsForBundle(bundle, slotFlags); if (ret != ERR_OK) { ANS_LOGI("Failed to get slotflags for bundle, use default slotflags."); @@ -544,10 +553,24 @@ void AdvancedNotificationService::GenerateSlotReminderMode( } std::string bundleName = (bundle == nullptr) ? "" : bundle->GetBundleName(); - ANS_LOGD("The reminder mode of %{public}d is %{public}d in %{public}s", + ANS_LOGI("The reminder mode of %{public}d is %{public}d in %{public}s", slot->GetType(), slot->GetReminderMode(), bundleName.c_str()); } +uint32_t AdvancedNotificationService::GetDefaultSlotFlags(const sptr &request) +{ + auto flags = DEFAULT_SLOT_FLAGS; + uint32_t notificationControlFlags = request->GetNotificationControlFlags(); + // SA publish own's notification with banner + if (((notificationControlFlags & NotificationConstant::ReminderFlag::SA_SELF_BANNER_FLAG) != 0) && + (request->GetCreatorUid() == IPCSkeleton::GetCallingUid() && request->GetCreatorBundleName().empty() && + request->GetOwnerBundleName().empty() && request->GetOwnerUid() == DEFAULT_UID)) { + return (flags |= NotificationConstant::ReminderFlag::BANNER_FLAG); + } + + return flags; +} + void AdvancedNotificationService::SetRequestBySlotType(const sptr &request, const sptr &bundleOption) { @@ -564,7 +587,8 @@ void AdvancedNotificationService::SetRequestBySlotType(const sptrGetReminderMode(); @@ -593,8 +617,8 @@ void AdvancedNotificationService::SetRequestBySlotType(const sptrSetFlags(flags); - ANS_LOGD("The reminder flags of %{public}s is %{public}d", - request->GetBaseKey("").c_str(), flags->GetReminderFlags()); + ANS_LOGI("SetFlags-GetRemindMode, notificationKey = %{public}s flags = %{public}d", + request->GetKey().c_str(), flags->GetReminderFlags()); #ifdef NOTIFICATION_SMART_REMINDER_SUPPORTED DelayedSingleton::GetInstance()->ReminderDecisionProcess(request); #endif diff --git a/services/ans/src/advanced_notification_subscriber_service.cpp b/services/ans/src/advanced_notification_subscriber_service.cpp index 22cb17798..a34acb53b 100644 --- a/services/ans/src/advanced_notification_subscriber_service.cpp +++ b/services/ans/src/advanced_notification_subscriber_service.cpp @@ -61,9 +61,7 @@ ErrCode AdvancedNotificationService::Subscribe( break; } - int32_t callingUid = IPCSkeleton::GetCallingUid(); - if ((callingUid != PAC_UID && callingUid != NFC_UID) - && !AccessTokenHelper::CheckPermission(OHOS_PERMISSION_NOTIFICATION_CONTROLLER)) { + if (!AccessTokenHelper::CheckPermission(OHOS_PERMISSION_NOTIFICATION_CONTROLLER)) { errCode = ERR_ANS_PERMISSION_DENIED; break; } @@ -130,6 +128,7 @@ ErrCode AdvancedNotificationService::SubscribeSelf(const sptrsubmit_h(std::bind([&]() { LivePublishProcess::GetInstance()->AddLiveViewSubscriber(callingUid); })); + notificationSvrQueue_->wait(handler); } SendSubscribeHiSysEvent(IPCSkeleton::GetCallingPid(), IPCSkeleton::GetCallingUid(), sptrInfo, errCode); return errCode; @@ -151,8 +150,7 @@ ErrCode AdvancedNotificationService::Unsubscribe( return ERR_ANS_NON_SYSTEM_APP; } - int32_t callingUid = IPCSkeleton::GetCallingUid(); - if (callingUid != PAC_UID && !AccessTokenHelper::CheckPermission(OHOS_PERMISSION_NOTIFICATION_CONTROLLER)) { + if (!AccessTokenHelper::CheckPermission(OHOS_PERMISSION_NOTIFICATION_CONTROLLER)) { message.Message("Unsubscribe notification: " + std::to_string(ERR_ANS_PERMISSION_DENIED)); NotificationAnalyticsUtil::ReportModifyEvent(message); return ERR_ANS_PERMISSION_DENIED; diff --git a/services/ans/src/advanced_notification_utils.cpp b/services/ans/src/advanced_notification_utils.cpp index 8787fb5df..c3f5f318e 100644 --- a/services/ans/src/advanced_notification_utils.cpp +++ b/services/ans/src/advanced_notification_utils.cpp @@ -46,6 +46,7 @@ #endif #include "advanced_notification_inline.cpp" +#include "notification_analytics_util.h" #define CHECK_BUNDLE_OPTION_IS_INVALID(option) \ if (option == nullptr || option->GetBundleName().empty()) { \ @@ -106,6 +107,7 @@ std::shared_ptr AdvancedNotificationService::GetNotificationSvrQueu sptr AdvancedNotificationService::GenerateBundleOption() { + HaMetaMessage message = HaMetaMessage(EventSceneId::SCENE_4, EventBranchId::BRANCH_1); sptr bundleOption = nullptr; std::string bundle = ""; if (!AccessTokenHelper::VerifyNativeToken(IPCSkeleton::GetCallingTokenID())) { @@ -118,7 +120,8 @@ sptr AdvancedNotificationService::GenerateBundleOption int32_t uid = IPCSkeleton::GetCallingUid(); bundleOption = new (std::nothrow) NotificationBundleOption(bundle, uid); if (bundleOption == nullptr) { - ANS_LOGE("Failed to create NotificationBundleOption instance"); + message.Message("Failed to create instance" + std::to_string(uid), true); + NotificationAnalyticsUtil::ReportModifyEvent(message); return nullptr; } return bundleOption; @@ -511,13 +514,13 @@ void AdvancedNotificationService::OnBundleRemoved(const sptr notification = nullptr; result = RemoveFromNotificationList(key, notification, true, - NotificationConstant::PACKAGE_CHANGED_REASON_DELETE); + NotificationConstant::PACKAGE_REMOVE_REASON_DELETE); if (result != ERR_OK) { continue; } if (notification != nullptr) { - int32_t reason = NotificationConstant::PACKAGE_CHANGED_REASON_DELETE; + int32_t reason = NotificationConstant::PACKAGE_REMOVE_REASON_DELETE; UpdateRecentNotification(notification, true, reason); notifications.emplace_back(notification); ExecBatchCancel(notifications, reason); @@ -528,15 +531,16 @@ void AdvancedNotificationService::OnBundleRemoved(const sptrBatchNotifyCanceled( - notifications, nullptr, NotificationConstant::PACKAGE_CHANGED_REASON_DELETE); + notifications, nullptr, NotificationConstant::PACKAGE_REMOVE_REASON_DELETE); } NotificationPreferences::GetInstance()->RemoveAnsBundleDbInfo(bundleOption); RemoveDoNotDisturbProfileTrustList(bundleOption); + DeleteDuplicateMsgs(bundleOption); })); NotificationPreferences::GetInstance()->RemoveEnabledDbByBundle(bundleOption); #ifdef ENABLE_ANS_EXT_WRAPPER EXTENTION_WRAPPER->UpdateByBundle(bundleOption->GetBundleName(), - NotificationConstant::PACKAGE_CHANGED_REASON_DELETE); + NotificationConstant::PACKAGE_REMOVE_REASON_DELETE); #endif } @@ -660,10 +664,12 @@ ErrCode AdvancedNotificationService::GetTargetRecordList(const int32_t uid, std::vector>& recordList) { for (auto& notification : notificationList_) { - if (notification->request != nullptr && notification->request->GetCreatorUid() == uid && - notification->request->GetSlotType()== slotType && - notification->request->GetNotificationType() == contentType) { + if (notification->request != nullptr && notification->request->GetSlotType()== slotType && + notification->request->GetNotificationType() == contentType) { + if (notification->request->GetCreatorUid() == uid || (notification->request->GetAgentBundle() != nullptr && + notification->request->GetAgentBundle()->GetUid() == uid)) { recordList.emplace_back(notification); + } } } if (recordList.empty()) { @@ -1352,7 +1358,7 @@ void AdvancedNotificationService::OnUserRemoved(const int32_t &userId) ErrCode AdvancedNotificationService::DeleteAllByUser(const int32_t &userId) { - return DeleteAllByUserInner(userId, NotificationConstant::CANCEL_ALL_REASON_DELETE); + return DeleteAllByUserInner(userId, NotificationConstant::APP_REMOVE_ALL_USER_REASON_DELETE); } ErrCode AdvancedNotificationService::DeleteAllByUserInner(const int32_t &userId, int32_t deleteReason, @@ -1362,16 +1368,29 @@ ErrCode AdvancedNotificationService::DeleteAllByUserInner(const int32_t &userId, bool isSubsystem = AccessTokenHelper::VerifyNativeToken(IPCSkeleton::GetCallingTokenID()); if (!isSubsystem && !AccessTokenHelper::IsSystemApp()) { + std::string message = "not system app."; + OHOS::Notification::HaMetaMessage haMetaMessage = HaMetaMessage(6, 5) + .ErrorCode(ERR_ANS_NON_SYSTEM_APP); + ReportDeleteFailedEventPush(haMetaMessage, deleteReason, message); + ANS_LOGE("%{public}s", message.c_str()); return ERR_ANS_NON_SYSTEM_APP; } if (userId <= SUBSCRIBE_USER_INIT) { - ANS_LOGE("Input userId is invalid."); + std::string message = "userId is error."; + OHOS::Notification::HaMetaMessage haMetaMessage = HaMetaMessage(6, 6) + .ErrorCode(ERR_ANS_INVALID_PARAM); + ReportDeleteFailedEventPush(haMetaMessage, deleteReason, message); + ANS_LOGE("%{public}s", message.c_str()); return ERR_ANS_INVALID_PARAM; } if (notificationSvrQueue_ == nullptr) { - ANS_LOGE("Serial queue is invalid."); + std::string message = "Serial queue is invalid."; + OHOS::Notification::HaMetaMessage haMetaMessage = HaMetaMessage(6, 7) + .ErrorCode(ERR_ANS_INVALID_PARAM); + ReportDeleteFailedEventPush(haMetaMessage, deleteReason, message); + ANS_LOGE("%{public}s", message.c_str()); return ERR_ANS_INVALID_PARAM; } std::shared_ptr result = std::make_shared(ERR_OK); @@ -1624,6 +1643,7 @@ ErrCode AdvancedNotificationService::SetRequestBundleInfo(const sptr &request, int32_t uid, std::string &bundle) { + HaMetaMessage message = HaMetaMessage(EventSceneId::SCENE_4, EventBranchId::BRANCH_2); std::shared_ptr bundleManager = BundleManagerHelper::GetInstance(); if (bundleManager == nullptr) { ANS_LOGE("failed to get bundleManager!"); @@ -1632,6 +1652,8 @@ ErrCode AdvancedNotificationService::PrePublishNotificationBySa(const sptrGetBundleNameByUid(uid); ErrCode result = SetRequestBundleInfo(request, uid, bundle); if (result != ERR_OK) { + message.ErrorCode(result); + NotificationAnalyticsUtil::ReportPublishFailedEvent(request, message); return result; } @@ -1659,7 +1681,8 @@ ErrCode AdvancedNotificationService::PrePublishNotificationBySa(const sptrSetLightScreenEnabled(false); flag->SetVibrationEnabled(NotificationConstant::FlagStatus::CLOSE); record->request->SetFlags(flag); + ANS_LOGI("SetFlags-CloseAlert, notificationKey = %{public}s flags = %{public}d", + record->request->GetKey().c_str(), flag->GetReminderFlags()); } bool AdvancedNotificationService::AllowUseReminder(const std::string& bundleName) diff --git a/services/ans/src/bundle_manager_helper.cpp b/services/ans/src/bundle_manager_helper.cpp index 5ea086ca1..5b8ada05b 100644 --- a/services/ans/src/bundle_manager_helper.cpp +++ b/services/ans/src/bundle_manager_helper.cpp @@ -226,5 +226,20 @@ bool BundleManagerHelper::GetBundleInfos( IPCSkeleton::SetCallingIdentity(identity); return ret; } + +int32_t BundleManagerHelper::GetAppIndexByUid(const int32_t uid) +{ + int32_t appIndex = 0; + std::lock_guard lock(connectionMutex_); + Connect(); + if (nullptr == bundleMgr_) { + return appIndex; + } + std::string bundleName; + std::string identity = IPCSkeleton::ResetCallingIdentity(); + bundleMgr_->GetNameAndIndexForUid(uid, bundleName, appIndex); + IPCSkeleton::SetCallingIdentity(identity); + return appIndex; +} } // namespace Notification } // namespace OHOS diff --git a/services/ans/src/common/notification_analytics_util.cpp b/services/ans/src/common/notification_analytics_util.cpp index f962ea08c..447e5950f 100644 --- a/services/ans/src/common/notification_analytics_util.cpp +++ b/services/ans/src/common/notification_analytics_util.cpp @@ -31,9 +31,17 @@ constexpr const int32_t DELETE_ERROR_EVENT_CODE = 5; constexpr const int32_t MODIFY_ERROR_EVENT_CODE = 6; constexpr const int32_t DEFAULT_ERROR_EVENT_COUNT = 6; constexpr const int32_t DEFAULT_ERROR_EVENT_TIME = 60; +constexpr const int32_t PUBLISH_ERROR_EVENT_COUNT = 3; +constexpr const int32_t PUBLISH_ERROR_EVENT_TIME = 60; +constexpr const int32_t DELETE_ERROR_EVENT_COUNT = 3; +constexpr const int32_t DELETE_ERROR_EVENT_TIME = 60; const static std::string NOTIFICATION_EVENT_PUSH_AGENT = "notification.event.PUSH_AGENT"; static std::mutex reportFlowControlMutex_; -static std::map> flowControlTimestampMap_; +static std::map> flowControlTimestampMap_ = { + {MODIFY_ERROR_EVENT_CODE, {}}, + {PUBLISH_ERROR_EVENT_CODE, {}}, + {DELETE_ERROR_EVENT_CODE, {}}, +}; HaMetaMessage::HaMetaMessage(uint32_t sceneId, uint32_t branchId) : sceneId_(sceneId), branchId_(branchId) @@ -126,7 +134,7 @@ std::string HaMetaMessage::Build() const void NotificationAnalyticsUtil::ReportPublishFailedEvent(const sptr& request, const HaMetaMessage& message) { - CommonNotificationEvent(request, PUBLISH_ERROR_EVENT_CODE, message); + return; } void NotificationAnalyticsUtil::ReportDeleteFailedEvent(const sptr& request, @@ -143,7 +151,6 @@ void NotificationAnalyticsUtil::ReportDeleteFailedEvent(const sptr& request, @@ -153,8 +160,14 @@ void NotificationAnalyticsUtil::CommonNotificationEvent(const sptr(contentType))); want.SetParam("extraInfo", extraContent); if (!request->GetCreatorBundleName().empty()) { - want.SetBundle(request->GetCreatorBundleName()); + want.SetParam("agentBundleName", request->GetCreatorBundleName()); } if (!request->GetOwnerBundleName().empty()) { - want.SetParam("agentBundleName", request->GetOwnerBundleName()); + want.SetBundle(request->GetOwnerBundleName()); } want.SetAction(NOTIFICATION_EVENT_PUSH_AGENT); EventFwk::CommonEventPublishInfo publishInfo; @@ -223,6 +236,10 @@ void NotificationAnalyticsUtil::ReportModifyEvent(const HaMetaMessage& message) void NotificationAnalyticsUtil::ReportDeleteFailedEvent(const HaMetaMessage& message) { + if (!ReportFlowControl(DELETE_ERROR_EVENT_CODE)) { + ANS_LOGI("Publish event failed, reason:%{public}s", message.Build().c_str()); + return; + } std::shared_ptr extraInfo = std::make_shared(); std::string reason = message.Build(); extraInfo->SetParam("reason", AAFwk::String::Box(reason)); @@ -235,8 +252,6 @@ void NotificationAnalyticsUtil::ReportDeleteFailedEvent(const HaMetaMessage& mes want.SetParam("typeCode", message.typeCode_); want.SetParam("id", message.notificationId_); want.SetParam("extraInfo", extraContent); - IN_PROCESS_CALL_WITHOUT_RET(ReportNotificationEvent( - want, DELETE_ERROR_EVENT_CODE, message.Build())); } void NotificationAnalyticsUtil::ReportNotificationEvent(EventFwk::Want want, @@ -256,27 +271,22 @@ bool NotificationAnalyticsUtil::ReportFlowControl(const int32_t reportType) { std::chrono::system_clock::time_point now = std::chrono::system_clock::now(); std::lock_guard lock(reportFlowControlMutex_); - std::list list = GetFlowListByType(reportType); + auto iter = flowControlTimestampMap_.find(reportType); + if (iter == flowControlTimestampMap_.end()) { + return false; + } + auto& list = iter->second; FlowControllerOption option = GetFlowOptionByType(reportType); RemoveExpired(list, now, option.time); - if (list.size() >= option.count) { + int32_t size = list.size(); + int32_t count = option.count; + if (size >= count) { return false; } list.push_back(now); - flowControlTimestampMap_[reportType] = list; return true; } -std::list NotificationAnalyticsUtil::GetFlowListByType(const int32_t reportType) -{ - std::list res; - auto iter = flowControlTimestampMap_.find(reportType); - if (iter != flowControlTimestampMap_.end()) { - res = iter->second; - } - return res; -} - void NotificationAnalyticsUtil::RemoveExpired(std::list &list, const std::chrono::system_clock::time_point &now, int32_t time) { @@ -298,6 +308,14 @@ FlowControllerOption NotificationAnalyticsUtil::GetFlowOptionByType(const int32_ option.count = DEFAULT_ERROR_EVENT_COUNT; option.time = DEFAULT_ERROR_EVENT_TIME; break; + case PUBLISH_ERROR_EVENT_CODE: + option.count = PUBLISH_ERROR_EVENT_COUNT; + option.time = PUBLISH_ERROR_EVENT_TIME; + break; + case DELETE_ERROR_EVENT_CODE: + option.count = DELETE_ERROR_EVENT_COUNT; + option.time = DELETE_ERROR_EVENT_TIME; + break; default: option.count = DEFAULT_ERROR_EVENT_COUNT; option.time = DEFAULT_ERROR_EVENT_TIME; diff --git a/services/ans/src/notification_extension_wrapper.cpp b/services/ans/src/notification_extension_wrapper.cpp index 00fa00984..513a39c48 100644 --- a/services/ans/src/notification_extension_wrapper.cpp +++ b/services/ans/src/notification_extension_wrapper.cpp @@ -21,9 +21,11 @@ #include "advanced_datashare_observer.h" #include "common_event_manager.h" #include "common_event_support.h" - + #include "common_event_subscriber.h" #include "system_event_observer.h" +#include "interface_system_event.h" +#include "system_event_subscriber.h" namespace OHOS::Notification { const std::string EXTENTION_WRAPPER_PATH = "libans_ext.z.so"; @@ -58,19 +60,11 @@ void ExtensionWrapper::InitExtentionWrapper() } syncAdditionConfig_ = (SYNC_ADDITION_CONFIG)dlsym(extensionWrapperHandle_, "SyncAdditionConfig"); - getUnifiedGroupInfo_ = (GET_UNIFIED_GROUP_INFO)dlsym(extensionWrapperHandle_, "GetUnifiedGroupInfo"); - updateByCancel_ = (UPDATE_BY_CANCEL)dlsym(extensionWrapperHandle_, "UpdateByCancel"); - setLocalSwitch_ = (SET_LOCAL_SWITCH)dlsym(extensionWrapperHandle_, "SetlocalSwitch"); - initSummary_ = (INIT_SUMMARY)dlsym(extensionWrapperHandle_, "InitSummary"); localControl_ = (LOCAL_CONTROL)dlsym(extensionWrapperHandle_, "LocalControl"); - updateByBundle_ = (UPDATE_BY_BUNDLE)dlsym(extensionWrapperHandle_, "UpdateByBundle"); reminderControl_ = (REMINDER_CONTROL)dlsym(extensionWrapperHandle_, "ReminderControl"); - if (syncAdditionConfig_ == nullptr - || getUnifiedGroupInfo_ == nullptr - || updateByCancel_ == nullptr - || initSummary_ == nullptr + bannerControl_ = (BANNER_CONTROL)dlsym(extensionWrapperHandle_, "BannerControl"); + if (syncAdditionConfig_ == nullptr || bannerControl_ == nullptr || localControl_ == nullptr - || updateByBundle_ == nullptr || reminderControl_ == nullptr) { ANS_LOGE("extension wrapper symbol failed, error: %{public}s", dlerror()); return; @@ -85,7 +79,9 @@ void ExtensionWrapper::InitExtentionWrapper() if (!aggregateConfig.empty()) { syncAdditionConfig_("AGGREGATE_CONFIG", aggregateConfig); } - initSummary_(UpdateUnifiedGroupInfo); + if (initSummary_ != nullptr) { + initSummary_(UpdateUnifiedGroupInfo); + } ANS_LOGD("extension wrapper init success"); } @@ -93,7 +89,6 @@ void ExtensionWrapper::CheckIfSetlocalSwitch() { ANS_LOGD("CheckIfSetlocalSwitch enter"); if (extensionWrapperHandle_ == nullptr) { - ANS_LOGE("CheckIfSetlocalSwitch extension wrapper symbol failed"); return; } if (!isRegisterDataSettingObserver) { @@ -108,7 +103,6 @@ void ExtensionWrapper::CheckIfSetlocalSwitch() void ExtensionWrapper::SetlocalSwitch(std::string &enable) { if (setLocalSwitch_ == nullptr) { - ANS_LOGE("SetlocalSwitch wrapper symbol failed"); return; } bool status = (enable == "false" ? false : true); @@ -126,7 +120,7 @@ void ExtensionWrapper::RegisterDataSettingObserver() if (aggregationRoamingObserver == nullptr) { return; } - + Uri dataEnableUri(SETTINGS_DATA_UNIFIED_GROUP_ENABLE_URI); AdvancedDatashareObserver::GetInstance().RegisterSettingsObserver(dataEnableUri, aggregationRoamingObserver); } @@ -143,7 +137,6 @@ ErrCode ExtensionWrapper::SyncAdditionConfig(const std::string& key, const std:: void ExtensionWrapper::UpdateByCancel(const std::vector>& notifications, int deleteReason) { if (updateByCancel_ == nullptr) { - ANS_LOGE("updateUnifiedGroupByCancel wrapper symbol failed"); return; } int32_t deleteType = convertToDelType(deleteReason); @@ -153,7 +146,6 @@ void ExtensionWrapper::UpdateByCancel(const std::vector>& not ErrCode ExtensionWrapper::GetUnifiedGroupInfo(const sptr &request) { if (getUnifiedGroupInfo_ == nullptr) { - ANS_LOGE("getUnifiedGroupInfo wrapper symbol failed"); return 0; } return getUnifiedGroupInfo_(request); @@ -168,6 +160,15 @@ int32_t ExtensionWrapper::ReminderControl(const std::string &bundleName) return reminderControl_(bundleName); } +int32_t ExtensionWrapper::BannerControl(const std::string &bundleName) +{ + if (bannerControl_ == nullptr) { + ANS_LOGE("ReminderControl wrapper symbol failed"); + return -1; + } + return bannerControl_(bundleName); +} + __attribute__((no_sanitize("cfi"))) int32_t ExtensionWrapper::LocalControl(const sptr &request) { if (localControl_ == nullptr) { @@ -180,7 +181,6 @@ __attribute__((no_sanitize("cfi"))) int32_t ExtensionWrapper::LocalControl(const void ExtensionWrapper::UpdateByBundle(const std::string bundleName, int deleteReason) { if (updateByBundle_ == nullptr) { - ANS_LOGE("UpdateByBundle wrapper symbol failed"); return; } int32_t deleteType = convertToDelType(deleteReason); diff --git a/services/ans/src/notification_preferences.cpp b/services/ans/src/notification_preferences.cpp index 738f54063..a19e7451d 100644 --- a/services/ans/src/notification_preferences.cpp +++ b/services/ans/src/notification_preferences.cpp @@ -39,6 +39,11 @@ std::shared_ptr NotificationPreferences::instance_; NotificationPreferences::NotificationPreferences() { preferncesDB_ = std::make_unique(); + if (preferncesDB_ == nullptr) { + HaMetaMessage message = HaMetaMessage(EventSceneId::SCENE_7, EventBranchId::BRANCH_1) + .Message("preferncesDB is null."); + NotificationAnalyticsUtil::ReportModifyEvent(message); + } InitSettingFromDisturbDB(); } @@ -550,7 +555,7 @@ ErrCode NotificationPreferences::AddDoNotDisturbProfiles( ErrCode NotificationPreferences::RemoveDoNotDisturbProfiles( int32_t userId, const std::vector> profiles) { - ANS_LOGE("Called."); + ANS_LOGD("Called."); for (auto profile : profiles) { if (profile == nullptr) { ANS_LOGE("The profile is nullptr."); @@ -738,7 +743,9 @@ ErrCode NotificationPreferences::SetBundleProperty(NotificationPreferencesInfo & bundleInfo.SetEnableNotification(CheckApiCompatibility(bundleOption)); } result = SaveBundleProperty(bundleInfo, bundleOption, type, value); - preferencesInfo.SetBundleInfo(bundleInfo); + if (result == ERR_OK) { + preferencesInfo.SetBundleInfo(bundleInfo); + } return result; } @@ -767,12 +774,12 @@ ErrCode NotificationPreferences::SaveBundleProperty(NotificationPreferencesInfo: storeDBResult = preferncesDB_->PutNotificationsEnabledForBundle(bundleInfo, value); break; case BundleType::BUNDLE_POPPED_DIALOG_TYPE: - ANS_LOGD("Into BUNDLE_POPPED_DIALOG_TYPE:SetHasPoppedDialog."); + ANS_LOGI("Into BUNDLE_POPPED_DIALOG_TYPE:SetHasPoppedDialog."); bundleInfo.SetHasPoppedDialog(value); storeDBResult = preferncesDB_->PutHasPoppedDialog(bundleInfo, value); break; case BundleType::BUNDLE_SLOTFLGS_TYPE: - ANS_LOGD("Into BUNDLE_SLOTFLGS_TYPE:SetSlotFlags."); + ANS_LOGI("Into BUNDLE_SLOTFLGS_TYPE:SetSlotFlags."); bundleInfo.SetSlotFlags(value); storeDBResult = preferncesDB_->PutSlotFlags(bundleInfo, value); break; diff --git a/services/ans/src/notification_preferences_database.cpp b/services/ans/src/notification_preferences_database.cpp index d517f469c..8ff63d1c8 100644 --- a/services/ans/src/notification_preferences_database.cpp +++ b/services/ans/src/notification_preferences_database.cpp @@ -26,7 +26,7 @@ #include "os_account_manager.h" #include "ipc_skeleton.h" #include "bundle_manager_helper.h" - +#include "notification_analytics_util.h" #include "uri.h" namespace OHOS { namespace Notification { @@ -675,7 +675,7 @@ bool NotificationPreferencesDatabase::ParseFromDisturbeDB(NotificationPreference } ParseBundleFromDistureDB(info, values, iter); } - + return true; } @@ -1685,12 +1685,17 @@ bool NotificationPreferencesDatabase::RemoveEnabledDbByBundleName(std::string bu int32_t NotificationPreferencesDatabase::SetKvToDb( const std::string &key, const std::string &value, const int32_t &userId) { + HaMetaMessage message = HaMetaMessage(EventSceneId::SCENE_7, EventBranchId::BRANCH_2); if (!CheckRdbStore()) { ANS_LOGE("RdbStore is nullptr."); + message.Message("RdbStore is nullptr."); + NotificationAnalyticsUtil::ReportModifyEvent(message); return NativeRdb::E_ERROR; } int32_t result = rdbDataManager_->InsertData(key, value, userId); if (result != NativeRdb::E_OK) { + message.Message("Set key failed: " + key); + NotificationAnalyticsUtil::ReportModifyEvent(message); ANS_LOGE("Set key: %{public}s failed, result %{public}d.", key.c_str(), result); return NativeRdb::E_ERROR; } @@ -1703,12 +1708,17 @@ int32_t NotificationPreferencesDatabase::SetKvToDb( int32_t NotificationPreferencesDatabase::SetByteToDb( const std::string &key, const std::vector &value, const int32_t &userId) { + HaMetaMessage message = HaMetaMessage(EventSceneId::SCENE_7, EventBranchId::BRANCH_2); if (!CheckRdbStore()) { + message.Message("RdbStore is nullptr."); + NotificationAnalyticsUtil::ReportModifyEvent(message); ANS_LOGE("RdbStore is nullptr."); return NativeRdb::E_ERROR; } int32_t result = rdbDataManager_->InsertData(key, value, userId); if (result != NativeRdb::E_OK) { + message.Message("Set key failed: " + key); + NotificationAnalyticsUtil::ReportModifyEvent(message); ANS_LOGE("Set key: %{public}s failed, result %{public}d.", key.c_str(), result); return NativeRdb::E_ERROR; } diff --git a/services/ans/src/notification_preferences_info.cpp b/services/ans/src/notification_preferences_info.cpp index a31b4d95d..d32f07b60 100644 --- a/services/ans/src/notification_preferences_info.cpp +++ b/services/ans/src/notification_preferences_info.cpp @@ -285,6 +285,7 @@ void NotificationPreferencesInfo::AddDoNotDisturbProfiles( continue; } std::string key = MakeDoNotDisturbProfileKey(userId, profile->GetProfileId()); + ANS_LOGI("AddDoNotDisturbProfiles key: %{public}s.", key.c_str()); doNotDisturbProfiles_.insert_or_assign(key, profile); } } @@ -298,6 +299,7 @@ void NotificationPreferencesInfo::RemoveDoNotDisturbProfiles( continue; } std::string key = MakeDoNotDisturbProfileKey(userId, profile->GetProfileId()); + ANS_LOGI("RemoveDoNotDisturbProfiles key: %{public}s.", key.c_str()); doNotDisturbProfiles_.erase(key); } } @@ -323,6 +325,7 @@ void NotificationPreferencesInfo::GetAllDoNotDisturbProfiles( { for (const auto &doNotDisturbProfile : doNotDisturbProfiles_) { std::string key = doNotDisturbProfile.first; + ANS_LOGI("GetAllDoNotDisturbProfiles key: %{public}s.", key.c_str()); auto result = key.find(std::to_string(userId)); if (result != std::string::npos) { auto profile = doNotDisturbProfile.second; diff --git a/services/ans/src/notification_subscriber_manager.cpp b/services/ans/src/notification_subscriber_manager.cpp index aa82e9f16..4a8efbab7 100644 --- a/services/ans/src/notification_subscriber_manager.cpp +++ b/services/ans/src/notification_subscriber_manager.cpp @@ -32,6 +32,10 @@ #include "os_account_manager_helper.h" #include "remote_death_recipient.h" #include "advanced_notification_service.h" +#include "notification_analytics_util.h" + +#include "advanced_notification_inline.cpp" + namespace OHOS { namespace Notification { struct NotificationSubscriberManager::SubscriberRecord { @@ -99,10 +103,14 @@ ErrCode NotificationSubscriberManager::AddSubscriber( ANS_LOGE("queue is nullptr"); return result; } + HaMetaMessage message = HaMetaMessage(EventSceneId::SCENE_6, EventBranchId::BRANCH_2); ffrt::task_handle handler = notificationSubQueue_->submit_h(std::bind([this, &subscriber, &subInfo, &result]() { result = this->AddSubscriberInner(subscriber, subInfo); })); notificationSubQueue_->wait(handler); + message.Message("Subscribe notification: " + GetClientBundleName() + " user " + + std::to_string(subInfo->GetAppUserId()) + " " + std::to_string(result)); + NotificationAnalyticsUtil::ReportModifyEvent(message); return result; } @@ -120,12 +128,17 @@ ErrCode NotificationSubscriberManager::RemoveSubscriber( ANS_LOGE("queue is nullptr"); return result; } + HaMetaMessage message = HaMetaMessage(EventSceneId::SCENE_6, EventBranchId::BRANCH_3); ffrt::task_handle handler = notificationSubQueue_->submit_h(std::bind([this, &subscriber, &subscribeInfo, &result]() { ANS_LOGE("ffrt enter!"); result = this->RemoveSubscriberInner(subscriber, subscribeInfo); })); notificationSubQueue_->wait(handler); + std::string appUserId = (subscribeInfo == nullptr) ? "all" : std::to_string(subscribeInfo->GetAppUserId()); + message.Message("Remove subscriber: " + GetClientBundleName() + " user " + + appUserId + " " + std::to_string(result)); + NotificationAnalyticsUtil::ReportModifyEvent(message); return result; } @@ -484,6 +497,10 @@ void NotificationSubscriberManager::NotifyCanceledInner( liveViewContent->FillPictureMarshallingMap(); } + OHOS::Notification::HaMetaMessage haMetaMessage = HaMetaMessage(1, 6).ErrorCode(ERR_OK); + ReportDeleteFailedEventPushByNotification(notification, haMetaMessage, deleteReason, "success"); + + ANS_LOGI("CancelNotification key = %{public}s", notification->GetKey().c_str()); for (auto record : subscriberRecordList_) { ANS_LOGD("%{public}s record->userId = <%{public}d>", __FUNCTION__, record->userId); if (IsSubscribedBysubscriber(record, notification)) { @@ -530,6 +547,18 @@ void NotificationSubscriberManager::BatchNotifyCanceledInner(const std::vector", notifications.size()); + std::string message = "BatchNotifyCanceledInner.size:" + + std::to_string(notifications.size()) + "."; + OHOS::Notification::HaMetaMessage haMetaMessage = HaMetaMessage(1, 9) + .ErrorCode(ERR_OK); + ReportDeleteFailedEventPush(haMetaMessage, deleteReason, message); + + std::string notificationKeys = ""; + for (auto notification : notifications) { + notificationKeys.append(notification->GetKey()).append("-"); + } + ANS_LOGI("CancelNotification key = %{public}s", notificationKeys.c_str()); + for (auto record : subscriberRecordList_) { if (record == nullptr) { continue; diff --git a/services/ans/src/notification_trust_list.cpp b/services/ans/src/notification_trust_list.cpp index 72f2324a6..6df8d69b0 100644 --- a/services/ans/src/notification_trust_list.cpp +++ b/services/ans/src/notification_trust_list.cpp @@ -14,6 +14,8 @@ */ #include "notification_trust_list.h" +#include "notification_extension_wrapper.h" + namespace OHOS { namespace Notification { @@ -73,7 +75,15 @@ bool NotificationTrustList::IsReminderTrustList(const std::string& bundleName) bool NotificationTrustList::IsSlotFlagsTrustlistAsBundle(const sptr &bundleOption) { - return notificationSlotFlagsTrustlist_.count(bundleOption->GetBundleName()); + if (notificationSlotFlagsTrustlist_.count(bundleOption->GetBundleName()) > 0) { + return true; + } +#ifdef ENABLE_ANS_EXT_WRAPPER + int32_t ctrlResult = EXTENTION_WRAPPER->BannerControl(bundleOption->GetBundleName()); + return (ctrlResult == ERR_OK) ? true : false; +#else + return false; +#endif } } // namespace Notification } // namespace OHOS diff --git a/services/ans/src/permission_filter.cpp b/services/ans/src/permission_filter.cpp index 5734361ca..cc7525aae 100644 --- a/services/ans/src/permission_filter.cpp +++ b/services/ans/src/permission_filter.cpp @@ -19,6 +19,7 @@ #include "ans_log_wrapper.h" #include "bundle_manager_helper.h" #include "notification_preferences.h" +#include "notification_analytics_util.h" namespace OHOS { namespace Notification { @@ -32,6 +33,7 @@ ErrCode PermissionFilter::OnPublish(const std::shared_ptr &r { bool isForceControl = false; bool enable = false; + HaMetaMessage message = HaMetaMessage(EventSceneId::SCENE_6, EventBranchId::BRANCH_1); ErrCode result = NotificationPreferences::GetInstance()->GetNotificationsEnabledForBundle(record->bundleOption, enable); if (result == ERR_ANS_PREFERENCES_NOTIFICATION_BUNDLE_NOT_EXIST) { @@ -44,11 +46,14 @@ ErrCode PermissionFilter::OnPublish(const std::shared_ptr &r sptr slot; NotificationConstant::SlotType slotType = record->request->GetSlotType(); + message.SlotType(slotType); result = NotificationPreferences::GetInstance()->GetNotificationSlot(record->bundleOption, slotType, slot); if (result == ERR_OK) { if (slot != nullptr) { isForceControl = slot->GetForceControl(); } else { + message.ErrorCode(ERR_ANS_PREFERENCES_NOTIFICATION_SLOT_ENABLED).Message("Slot type not exist."); + NotificationAnalyticsUtil::ReportPublishFailedEvent(record->request, message); result = ERR_ANS_PREFERENCES_NOTIFICATION_SLOT_ENABLED; ANS_LOGE("Type[%{public}d] slot does not exist", slotType); } @@ -56,6 +61,8 @@ ErrCode PermissionFilter::OnPublish(const std::shared_ptr &r if (result == ERR_OK) { if (!enable && !isForceControl) { + message.ErrorCode(ERR_ANS_NOT_ALLOWED).Message("Notifications is off."); + NotificationAnalyticsUtil::ReportPublishFailedEvent(record->request, message); ANS_LOGE("Enable notifications for bundle is OFF"); return ERR_ANS_NOT_ALLOWED; } @@ -67,4 +74,4 @@ ErrCode PermissionFilter::OnPublish(const std::shared_ptr &r return result; } } // namespace Notification -} // namespace OHOS \ No newline at end of file +} // namespace OHOS diff --git a/services/ans/src/reminder_data_manager.cpp b/services/ans/src/reminder_data_manager.cpp index b1b7b265b..6d1afc8b2 100644 --- a/services/ans/src/reminder_data_manager.cpp +++ b/services/ans/src/reminder_data_manager.cpp @@ -21,6 +21,7 @@ #include "ans_const_define.h" #include "common_event_support.h" #include "common_event_manager.h" +#include "notification_constant.h" #include "reminder_request_calendar.h" #include "in_process_call_wrapper.h" #ifdef DEVICE_STANDBY_ENABLE @@ -330,7 +331,7 @@ void ReminderDataManager::CancelNotification(const sptr &remind } sptr bundleOption = FindNotificationBundleOption(reminder->GetReminderId()); advancedNotificationService_->CancelPreparedNotification(notification->GetNotificationId(), - ReminderRequest::NOTIFICATION_LABEL, bundleOption); + ReminderRequest::NOTIFICATION_LABEL, bundleOption, NotificationConstant::APP_CANCEL_REMINDER_REASON_DELETE); } bool ReminderDataManager::CheckReminderLimitExceededLocked(const sptr &bundleOption, diff --git a/services/ans/src/system_dialog_connect_stb.cpp b/services/ans/src/system_dialog_connect_stb.cpp index d96efe3bb..9035552b2 100644 --- a/services/ans/src/system_dialog_connect_stb.cpp +++ b/services/ans/src/system_dialog_connect_stb.cpp @@ -18,10 +18,10 @@ #include "ans_log_wrapper.h" #include "ans_inner_errors.h" #include "common_event_manager.h" -#include "advanced_notification_service.h" -#include "notification_bundle_option.h" constexpr int32_t SIGNAL_NUM = 3; +constexpr int32_t REMOVE_BUNDLE_CODE = 3; +const static std::string DIALOG_CRASH_EVENT = "OnNotificationServiceDialogClicked"; namespace OHOS { namespace Notification { @@ -44,25 +44,8 @@ void SystemDialogConnectStb::OnAbilityConnectDone(const AppExecFwk::ElementName int32_t errCode = remoteObject->SendRequest(IAbilityConnection::ON_ABILITY_CONNECT_DONE, data, reply, option); ANS_LOGI("AbilityConnectionWrapperProxy::OnAbilityConnectDone result %{public}d", errCode); if (errCode != ERR_OK) { - ANS_LOGE("send Request to SytemDialog fail"); - nlohmann::json root = nlohmann::json::parse(commandStr_); - if (root.is_null() or !root.is_object()) { - ANS_LOGE("Invalid JSON object"); - return; - } - if (!root.contains("bundleName") || !root.contains("bundleUid")) { - ANS_LOGE("not found jsonKey from"); - return; - } - std::string bundleName = root["bundleName"]; - int32_t bundleUid = root["bundleUid"]; - sptr bundleOption = new (std::nothrow) NotificationBundleOption( - bundleName, bundleUid); - if (bundleOption == nullptr) { - ANS_LOGE("bundleOption inin fail"); - return; - } - AdvancedNotificationService::GetInstance()->RemoveEnableNotificationDialog(bundleOption); + ANS_LOGD("send Request to SytemDialog fail"); + SendRemoveBundleEvent(); } } @@ -72,5 +55,40 @@ void SystemDialogConnectStb::OnAbilityDisconnectDone(const AppExecFwk::ElementNa ANS_LOGI("on ability disconnected"); } +void SystemDialogConnectStb::SendRemoveBundleEvent() +{ + if (commandStr_.empty() || !nlohmann::json::accept(commandStr_)) { + ANS_LOGW("Invaild json param"); + return; + } + nlohmann::json root = nlohmann::json::parse(commandStr_); + if (root.is_null() or !root.is_object()) { + ANS_LOGE("Invalid JSON object"); + return; + } + if (!root.contains("bundleName") || !root.contains("bundleUid")) { + ANS_LOGW("not found jsonKey from"); + return; + } + if (!root["bundleName"].is_string() || !root["bundleUid"].is_string()) { + ANS_LOGW("value type of json key from is not string"); + return; + } + EventFwk::CommonEventData commonData; + std::string bundleName = root["bundleName"]; + std::string bundleUid = root["bundleUid"]; + + EventFwk::Want want; + want.SetAction(DIALOG_CRASH_EVENT); + want.SetParam("bundleName", bundleName); + want.SetParam("bundleUid", bundleUid); + commonData.SetWant(want); + commonData.SetCode(REMOVE_BUNDLE_CODE); + commonData.SetData(bundleName); + if (!EventFwk::CommonEventManager::PublishCommonEvent(commonData)) { + ANS_LOGE("Publish remove bundle failed"); + } +} + } } \ No newline at end of file diff --git a/services/ans/test/unittest/advanced_notification_publish_service_test.cpp b/services/ans/test/unittest/advanced_notification_publish_service_test.cpp index 6c45de12c..1d0fd2aeb 100644 --- a/services/ans/test/unittest/advanced_notification_publish_service_test.cpp +++ b/services/ans/test/unittest/advanced_notification_publish_service_test.cpp @@ -178,6 +178,7 @@ HWTEST_F(AnsPublishServiceTest, Publish_00003, Function | SmallTest | Level1) MockGetTokenTypeFlag(Security::AccessToken::ATokenTypeEnum::TOKEN_HAP); MockIsSystemApp(true); MockIsVerfyPermisson(false); + auto ret = advancedNotificationService_->Publish(label, request); ASSERT_EQ(ret, (int)ERR_OK); @@ -205,6 +206,7 @@ HWTEST_F(AnsPublishServiceTest, Publish_00004, Function | SmallTest | Level1) auto content = std::make_shared(liveContent); request->SetContent(content); RegisterPushCheck(); + MockGetTokenTypeFlag(Security::AccessToken::ATokenTypeEnum::TOKEN_HAP); MockIsSystemApp(true); MockIsVerfyPermisson(false); @@ -243,8 +245,8 @@ HWTEST_F(AnsPublishServiceTest, Publish_00005, Function | SmallTest | Level1) auto liveContent = std::make_shared(); auto content = std::make_shared(liveContent); request->SetContent(content); - MockIsOsAccountExists(true); RegisterPushCheck(); + MockIsOsAccountExists(true); MockGetTokenTypeFlag(Security::AccessToken::ATokenTypeEnum::TOKEN_HAP); MockIsSystemApp(true); MockIsVerfyPermisson(true); @@ -634,12 +636,14 @@ HWTEST_F(AnsPublishServiceTest, RemoveNotificationBySlot_00001, Function | Small MockIsSystemApp(false); sptr bundle = nullptr; sptr slot = nullptr; - auto ret = advancedNotificationService_->RemoveNotificationBySlot(bundle, slot); + auto ret = advancedNotificationService_->RemoveNotificationBySlot(bundle, slot, + NotificationConstant::DEFAULT_REASON_DELETE); ASSERT_EQ(ret, (int)ERR_ANS_NON_SYSTEM_APP); MockIsSystemApp(true); MockIsVerfyPermisson(false); - ret = advancedNotificationService_->RemoveNotificationBySlot(bundle, slot); + ret = advancedNotificationService_->RemoveNotificationBySlot(bundle, slot, + NotificationConstant::DEFAULT_REASON_DELETE); ASSERT_EQ(ret, (int)ERR_ANS_INVALID_BUNDLE); } @@ -664,7 +668,8 @@ HWTEST_F(AnsPublishServiceTest, RemoveNotificationBySlot_00002, Function | Small auto ret = advancedNotificationService_->AssignToNotificationList(record); auto slot = new NotificationSlot(NotificationConstant::SlotType::SOCIAL_COMMUNICATION); - ret = advancedNotificationService_->RemoveNotificationBySlot(bundle, slot); + ret = advancedNotificationService_->RemoveNotificationBySlot(bundle, slot, + NotificationConstant::DEFAULT_REASON_DELETE); ASSERT_EQ(ret, (int)ERR_OK); } diff --git a/services/ans/test/unittest/advanced_notification_service_test.cpp b/services/ans/test/unittest/advanced_notification_service_test.cpp index 213268559..6d5d0f1fe 100644 --- a/services/ans/test/unittest/advanced_notification_service_test.cpp +++ b/services/ans/test/unittest/advanced_notification_service_test.cpp @@ -14,16 +14,15 @@ */ #include "errors.h" +#include "notification_bundle_option.h" #include "notification_content.h" #include "notification_record.h" #include "notification_request.h" #include #include -#include #include #include "gtest/gtest.h" -#include #define private public @@ -306,6 +305,7 @@ HWTEST_F(AdvancedNotificationServiceTest, AdvancedNotificationServiceTest_03100, { const std::string localSwitch = "current"; advancedNotificationService_->ClearAllNotificationGroupInfo(localSwitch); + EXPECT_TRUE(advancedNotificationService_ != nullptr); } /** @@ -318,6 +318,7 @@ HWTEST_F(AdvancedNotificationServiceTest, AdvancedNotificationServiceTest_03200, const std::string key = "key"; std::shared_ptr groupInfo; advancedNotificationService_->UpdateUnifiedGroupInfo(key, groupInfo); + EXPECT_TRUE(advancedNotificationService_ != nullptr); } /** @@ -450,6 +451,7 @@ HWTEST_F(AdvancedNotificationServiceTest, AdvancedNotificationServiceTest_04300, sptr request(new NotificationRequest()); std::string bundleName = "bundleName"; advancedNotificationService_->SetAgentNotification(request, bundleName); + EXPECT_TRUE(advancedNotificationService_ != nullptr); } /** @@ -1254,7 +1256,7 @@ HWTEST_F(AdvancedNotificationServiceTest, AdvancedNotificationServiceTest_16000, int32_t notificationId = 0; std::string label = "testLabel"; sptr bundleOption = nullptr; - ASSERT_EQ(advancedNotificationService_->CancelPreparedNotification(notificationId, label, bundleOption), + ASSERT_EQ(advancedNotificationService_->CancelPreparedNotification(notificationId, label, bundleOption, 8), ERR_ANS_INVALID_BUNDLE); GTEST_LOG_(INFO) << "CancelPreparedNotification_1000 test end"; @@ -3096,7 +3098,7 @@ HWTEST_F(AdvancedNotificationServiceTest, IsNeedPushCheckTest_0005, Function | S /** * @tc.number : IsNeedPushCheckTest_0006 * @tc.name : IsNeedPushCheckTest - * @tc.desc : Test notification except live view registered but has inconsistent contentType dont't need push check. + * @tc.desc : Test notification except live view registered but has inconsistent contentType don't need push check. * @tc.require : #I6Z5OV */ HWTEST_F(AdvancedNotificationServiceTest, IsNeedPushCheckTest_0006, Function | SmallTest | Level1) @@ -3273,7 +3275,7 @@ HWTEST_F(AdvancedNotificationServiceTest, NotificationSvrQueue_00001, Function | auto bundle = new NotificationBundleOption(TEST_DEFUALT_BUNDLE, SYSTEM_APP_UID); auto request = new (std::nothrow) NotificationRequest(); - auto ret = advancedNotificationService_->CancelPreparedNotification(1, "label", bundle); + auto ret = advancedNotificationService_->CancelPreparedNotification(1, "label", bundle, 8); ASSERT_EQ(ret, (int)ERR_ANS_INVALID_PARAM); std::vector> requests; @@ -3313,6 +3315,7 @@ HWTEST_F(AdvancedNotificationServiceTest, NotificationSvrQueue_00002, Function | { advancedNotificationService_->notificationSvrQueue_ = nullptr; auto bundle = new NotificationBundleOption(TEST_DEFUALT_BUNDLE, SYSTEM_APP_UID); + sptr bundle1 = nullptr; auto request = new (std::nothrow) NotificationRequest(); auto ret = advancedNotificationService_->EnableDistributedSelf(true); @@ -3322,7 +3325,7 @@ HWTEST_F(AdvancedNotificationServiceTest, NotificationSvrQueue_00002, Function | ret = advancedNotificationService_->IsDistributedEnableByBundle(bundle, enable); ASSERT_EQ(ret, (int)ERR_ANS_INVALID_PARAM); - ret = advancedNotificationService_->GetHasPoppedDialog(bundle, enable); + ret = advancedNotificationService_->GetHasPoppedDialog(bundle1, enable); ASSERT_EQ(ret, (int)ERR_ANS_INVALID_PARAM); ret = advancedNotificationService_->SetSyncNotificationEnabledWithoutApp(1, enable); @@ -3331,7 +3334,6 @@ HWTEST_F(AdvancedNotificationServiceTest, NotificationSvrQueue_00002, Function | ret = advancedNotificationService_->GetSyncNotificationEnabledWithoutApp(1, enable); ASSERT_EQ(ret, (int)ERR_ANS_INVALID_PARAM); - advancedNotificationService_->FillActionButtons(request); request->SetIsCoverActionButtons(true); advancedNotificationService_->FillActionButtons(request); } @@ -3369,7 +3371,7 @@ HWTEST_F(AdvancedNotificationServiceTest, StartArchiveTimer_00001, Function | Sm auto slotType = NotificationConstant::SlotType::LIVE_VIEW; sptr request = new (std::nothrow) NotificationRequest(); request->SetSlotType(slotType); - request->SetAutoDeletedTime(NotificationConstant::NO_DELAY_DELETE_TIME); + request->SetAutoDeletedTime(0); auto bundle = new NotificationBundleOption(TEST_DEFUALT_BUNDLE, SYSTEM_APP_UID); auto record = advancedNotificationService_->MakeNotificationRecord(request, bundle); advancedNotificationService_->StartArchiveTimer(record); @@ -3419,8 +3421,9 @@ HWTEST_F(AdvancedNotificationServiceTest, ChangeNotificationByControlFlags_00001 flags->SetStatusIconEnabled(true); request->SetFlags(flags); + bool isAgentController = true; auto record = advancedNotificationService_->MakeNotificationRecord(request, bundle); - advancedNotificationService_->ChangeNotificationByControlFlags(record); + advancedNotificationService_->ChangeNotificationByControlFlags(record, isAgentController); u_int32_t reminderFlags = flags->GetReminderFlags(); ASSERT_EQ(reminderFlags, 0); diff --git a/services/dialog_ui/enable_notification_dialog/entry/src/main/ets/ServiceExtAbility/NotificationServiceExtAbility.ts b/services/dialog_ui/enable_notification_dialog/entry/src/main/ets/ServiceExtAbility/NotificationServiceExtAbility.ts index 0c6f8201f..adf1583b8 100644 --- a/services/dialog_ui/enable_notification_dialog/entry/src/main/ets/ServiceExtAbility/NotificationServiceExtAbility.ts +++ b/services/dialog_ui/enable_notification_dialog/entry/src/main/ets/ServiceExtAbility/NotificationServiceExtAbility.ts @@ -28,13 +28,15 @@ import fs from '@ohos.file.fs'; import Constants from '../common/constant'; + const TAG = 'NotificationDialog_Service '; -const UPDATE_INIT = 1; +const UPDATE_INIT = -1; const UPDATE_NUM = 1; const UPDATE_BOUNDARY = 100; -let eventSubscriber:CommonEventManager.CommonEventSubscriber; + +let systemLanguage: string; const enableNotificationDialogDestroyedEvent = { eventId: 1, @@ -64,10 +66,18 @@ async function handleDialogQuitException(want: Want): Promise { ); } +interface NotificationConfig { + deviceInfo: DeviceInfo; +} + +interface DeviceInfo { + isWatch: boolean; +} export class EnableNotificationDialog { static ENABLE_NOTIFICATION_DIALOG_NAME = 'EnableNotificationDialog'; static DIALOG_PATH = 'pages/notificationDialog'; + static WATCH_DIALOG_PATH = 'pages/watchNotificationDialog'; static TRANSPARANT_COLOR = '#00000000'; static SCENEBOARD_BUNDLE = 'com.ohos.sceneboard'; static SYSTEMUI_BUNDLE = 'com.ohos.systemui'; @@ -88,6 +98,49 @@ export class EnableNotificationDialog { this.extensionWindow = undefined; } + async createWindow(windowType: window.WindowType, context, displayRect): Promise { + try { + let winArgs = { + 'name': `${EnableNotificationDialog.ENABLE_NOTIFICATION_DIALOG_NAME}${this.id}`, + 'windowType': windowType, + 'ctx': context + }; + let win = await window.createWindow(winArgs); + this.window = win; + let shouldHide = true; + + if (windowType === window.WindowType.TYPE_DIALOG) { + await win.bindDialogTarget(this.want.parameters.callerToken['value'], + async (): Promise => { + console.info(TAG, `window ${this.id} died`); + await this.destroyException(); + } + ); + } + + this.storage = new LocalStorage({ + 'dialog': this + }); + await win.moveWindowTo(displayRect.left, displayRect.top); + await win.resize(displayRect.width, displayRect.height); + await win.loadContent(EnableNotificationDialog.DIALOG_PATH, this.storage); + try { + await win.hideNonSystemFloatingWindows(shouldHide); + } catch (err) { + console.error(TAG, 'window hideNonSystemFloatingWindows failed!'); + } + await win.setWindowBackgroundColor(EnableNotificationDialog.TRANSPARANT_COLOR); + await win.showWindow(); + await win.setWindowLayoutFullScreen(true); + } catch (err) { + if (this.window !== undefined) { + await this.destroyWindow(); + } + console.error(TAG, 'window create failed!'); + throw new Error('Failed to create window'); + } + } + async createUiExtensionWindow(session: UIExtensionContentSession, stageModel: boolean): Promise { try { @@ -99,7 +152,8 @@ export class EnableNotificationDialog { 'dialog': this, 'session': session }); - + + let path = EnableNotificationDialog.DIALOG_PATH; let hasConfig = true; try { let filePaths = await configPolicy.getCfgFiles(Constants.CCM_CONFIG_PATH); @@ -107,6 +161,20 @@ export class EnableNotificationDialog { console.info(TAG, 'not get any configFile'); hasConfig = false; } + for (let i = 0; i < filePaths.length; i++) { + let res = fs.accessSync(filePaths[i]); + if (res) { + let fileContent = fs.readTextSync(filePaths[i]); + let config: NotificationConfig = JSON.parse(fileContent); + if (config.deviceInfo !== undefined) { + let deviceInfo: DeviceInfo = config.deviceInfo; + if (deviceInfo.isWatch !== undefined) { + path = EnableNotificationDialog.WATCH_DIALOG_PATH; + console.info(TAG, 'watch request'); + } + } + } + } } catch (err) { console.error(TAG, 'Failed get ccm files'); } @@ -120,11 +188,10 @@ export class EnableNotificationDialog { }; let subWindow = await extensionWindow.createSubWindowWithOptions('subWindowForHost' + Date(), subWindowOpts); this.subWindow = subWindow; - let windowRect = extensionWindow.properties?.uiExtensionHostWindowProxyRect; - await subWindow.moveWindowTo(windowRect?.left, windowRect?.top); - await subWindow.resize(windowRect?.width, windowRect?.height); - console.info(TAG, `size : ${windowRect.left} ${windowRect.top} ${windowRect.width} ${windowRect.height}`); - await subWindow.loadContent(EnableNotificationDialog.DIALOG_PATH, this.storage); + let dis = display.getDefaultDisplaySync(); + await subWindow?.resize(dis.width, dis.height); + console.info(TAG, `size : ${dis.width} ${dis.height}`); + await subWindow.loadContent(path, this.storage); try { await subWindow.hideNonSystemFloatingWindows(true); } catch (err) { @@ -133,7 +200,7 @@ export class EnableNotificationDialog { await subWindow.setWindowBackgroundColor(EnableNotificationDialog.TRANSPARANT_COLOR); await subWindow.showWindow(); } else { - await session.loadContent(EnableNotificationDialog.DIALOG_PATH, this.storage); + await session.loadContent(path, this.storage); try { await extensionWindow.hideNonSecureWindows(shouldHide); } catch (err) { @@ -186,12 +253,26 @@ export class EnableNotificationDialog { class NotificationDialogServiceExtensionAbility extends UIExtensionAbility { + onConfigurationUpdate(newConfig): void { + console.log(TAG, 'onConfigurationUpdate'); + if (systemLanguage !== newConfig.language) { + console.log(TAG, `onConfigurationUpdate newConfig is ${JSON.stringify(newConfig)}`); + systemLanguage = newConfig.language; + let isUpdate:number = AppStorage.get('isUpdate'); + if (isUpdate === undefined || isUpdate > UPDATE_BOUNDARY) { + AppStorage.setOrCreate('isUpdate', UPDATE_NUM); + } else { + AppStorage.setOrCreate('isUpdate', ++isUpdate); + } + } + } + + onCreate() { console.log(TAG, `UIExtAbility onCreate`); AppStorage.setOrCreate('context', this.context); AppStorage.setOrCreate('isUpdate', UPDATE_INIT); - AppStorage.setOrCreate('clicked', false); - this.subscribe(); + systemLanguage = this.context.config.language; } @@ -212,6 +293,7 @@ class NotificationDialogServiceExtensionAbility extends UIExtensionAbility { `uid ${want.parameters.bundleUid}`); let dialog = new EnableNotificationDialog(1, want, stageModel); await dialog.createUiExtensionWindow(session, stageModel); + AppStorage.setOrCreate('clicked', false); AppStorage.setOrCreate('dialog', dialog); } catch (err) { console.error(TAG, `Failed to handle onSessionCreate`); @@ -266,59 +348,10 @@ class NotificationDialogServiceExtensionAbility extends UIExtensionAbility { } } - async onDestroy() { + onDestroy() { console.info(TAG, 'UIExtAbility onDestroy.'); - await this.unsubscribe(); - await this.sleep(500); this.context.terminateSelf(); } - - async sleep(ms: number): Promise { - return new Promise(resolve => setTimeout(resolve, ms)); - } - - async subscribe() { - CommonEventManager.createSubscriber( - { events: ['usual.event.BUNDLE_RESOURCES_CHANGED'] }, (err, subscriber) => { - if (err?.code) { - console.error(TAG, `createSubscriber callBack err = ${JSON.stringify(err)}`); - } else { - eventSubscriber = subscriber; - console.log(TAG, "create subscriber succeed"); - if (eventSubscriber != null) { - console.log(TAG, "subscriber subscribe BUNDLE_RESOURCES_CHANGED event"); - CommonEventManager.subscribe(eventSubscriber, (err, data) => { - if (err?.code) { - console.error(TAG, `subscribe callBack err= ${JSON.stringify(err)}`); - } else { - console.log(TAG, `subscribe callBack data= ${JSON.stringify(data)}`); - if(data.parameters?.bundleResourceChangeType == 1){ - console.log(TAG, `BUNDLE_RESOURCES_CHANGED-language change`); - let isUpdate:number = AppStorage.get('isUpdate'); - if (isUpdate === undefined || isUpdate > UPDATE_BOUNDARY) { - AppStorage.setOrCreate('isUpdate', UPDATE_NUM); - } else { - AppStorage.setOrCreate('isUpdate', ++isUpdate); - } - } - } - }) - } else { - console.info(TAG, "need create subscriber"); - } - } - }); - } - - async unsubscribe() { - try { - if (eventSubscriber != null) { - CommonEventManager.unsubscribe(eventSubscriber, (err) => {}); - } - } catch (err) { - console.info("ubsubscribe fail"); - } - } } diff --git a/services/dialog_ui/enable_notification_dialog/entry/src/main/ets/common/constant.ets b/services/dialog_ui/enable_notification_dialog/entry/src/main/ets/common/constant.ets index a1f3d2be6..721c6021c 100644 --- a/services/dialog_ui/enable_notification_dialog/entry/src/main/ets/common/constant.ets +++ b/services/dialog_ui/enable_notification_dialog/entry/src/main/ets/common/constant.ets @@ -125,12 +125,12 @@ export default class Constants { static DIALOG_REQ_LINE_HEIGHT = 24; // description text of dialog - public static DIALOG_DESP_FONT_SIZE = 16; - public static DIALOG_DESP_MARGIN_TOP = 0; - public static DIALOG_DESP_MARGIN_LEFT = 24; - public static DIALOG_DESP_MARGIN_RIGHT = 24; - public static DIALOG_DESP_MARGIN_BOTTOM = 8; - public static DIALOG_DESP_LINE_HEIGHT = 21; + static DIALOG_DESP_FONT_SIZE = 16; + static DIALOG_DESP_MARGIN_TOP = 0; + static DIALOG_DESP_MARGIN_LEFT = 24; + static DIALOG_DESP_MARGIN_RIGHT = 24; + static DIALOG_DESP_MARGIN_BOTTOM = 12; + static DIALOG_DESP_LINE_HEIGHT = 21; static BUTTON_MARGIN_TOP = 8; static BUTTON_MARGIN_LEFT = 16; diff --git a/services/dialog_ui/enable_notification_dialog/entry/src/main/ets/pages/notificationDialog.ets b/services/dialog_ui/enable_notification_dialog/entry/src/main/ets/pages/notificationDialog.ets index 9f6962ee1..219a61a67 100644 --- a/services/dialog_ui/enable_notification_dialog/entry/src/main/ets/pages/notificationDialog.ets +++ b/services/dialog_ui/enable_notification_dialog/entry/src/main/ets/pages/notificationDialog.ets @@ -35,36 +35,39 @@ const bottomPopoverTypes = ['default', 'phone']; let storage = LocalStorage.getShared(); @Extend(Button) function rightCustomizeButton() { - .backgroundColor(Color.Transparent) + .backgroundColor($r('app.color.dialog_bg')) .fontColor($r('app.color.button_text')) .fontSize(Constants.TEXT_MIDDLE_FONT_SIZE) .fontWeight(FontWeight.Medium) .height(Constants.BUTTON_HEIGHT) .flexGrow(Constants.FLEX_GROW) - .width('50%') + .margin({ + left: Constants.BUTTON_LEFT + }) } @Extend(Button) function leftCustomizeButton() { - .backgroundColor(Color.Transparent) + .backgroundColor($r('app.color.dialog_bg')) .fontColor($r('app.color.button_text')) .fontSize(Constants.TEXT_MIDDLE_FONT_SIZE) .fontWeight(FontWeight.Medium) .height(Constants.BUTTON_HEIGHT) .flexGrow(Constants.FLEX_GROW) - .width('50%') + .margin({ + right: Constants.BUTTON_RIGHT + }) } @Entry(storage) @Component struct NotificationDialogPage { - @StorageLink('isUpdate') isUpdate: number = 0; + @StorageLink('isUpdate') isUpdate: number = -1; privacyDialogController: CustomDialogController = new CustomDialogController({ builder: PermissionDialog({ isUpdate: $isUpdate }), autoCancel: false, alignment: DialogAlignment.Center, customStyle: true, - maskColor: $r('app.color.mask_thin'), onWillDismiss: (dismissDialogAction: DismissDialogAction) => { console.info(TAG, `dialog onWillDismiss reason= : ${JSON.stringify(dismissDialogAction.reason)}`); } @@ -77,6 +80,7 @@ struct NotificationDialogPage { } onPageShow() { + this.isUpdate++; } } @@ -97,16 +101,14 @@ struct PermissionDialog { offset: {xs: Constants.XS_OFFSET, sm: Constants.SM_OFFSET, md: Constants.DIALOG_MD_OFFSET, lg: Constants.DIALOG_LG_OFFSET} }) { Flex({ justifyContent: FlexAlign.Center, alignItems: this.isBottomPopover ? ItemAlign.End : ItemAlign.Center }) { Column() { + Image(permission.icon) + .width(Constants.DIALOG_ICON_WIDTH) + .height(Constants.DIALOG_ICON_HEIGHT) + .margin({ + top: Constants.DIALOG_ICON_MARGIN_TOP + }) Scroll() { Column() { - Row() { - Image(permission.icon) - .width(Constants.DIALOG_ICON_WIDTH) - .height(Constants.DIALOG_ICON_HEIGHT) - .margin({ - top: Constants.DIALOG_ICON_MARGIN_TOP - }) - } Row() { Flex({ justifyContent: FlexAlign.Center }) { Text() { @@ -116,8 +118,6 @@ struct PermissionDialog { .fontColor($r('app.color.text_primary')) .fontWeight(FontWeight.Bold) .lineHeight(Constants.DIALOG_REQ_LINE_HEIGHT) - .maxLines(2) - .textOverflow({overflow: TextOverflow.Ellipsis}) .margin({ top: Constants.DIALOG_REQ_MARGIN_TOP, bottom:Constants.DIALOG_REQ_MARGIN_BUTTOM, @@ -144,35 +144,35 @@ struct PermissionDialog { }) } } - Row() { - Flex({ justifyContent: FlexAlign.SpaceBetween, alignItems: ItemAlign.Center }) { - Button($r('app.string.BAN')) - .onClick(async (): Promise => { - await this.enableNotification(false); - }) - .leftCustomizeButton() - Divider() - .color($r('app.color.comp_divider')) - .vertical(true) - .height(Constants.DIVIDER_HEIGHT) - .strokeWidth(Constants.DIVIDER_WIDTH) - .margin({left: Constants.BUTTON_LEFT, right: Constants.BUTTON_RIGHT}) - Button($r('app.string.ALLOW')) - .onClick(async (): Promise => { - await this.enableNotification(true); - }) - .rightCustomizeButton() - } - .margin({ left: Constants.BUTTON_MARGIN_LEFT, right: Constants.BUTTON_MARGIN_RIGHT }) - } } } .constraintSize({ maxHeight: Constants.MAXIMUM_HEADER_HEIGHT }) + Row() { + Flex({ justifyContent: FlexAlign.SpaceBetween, alignItems: ItemAlign.Center }) { + Button($r('app.string.BAN')) + .onClick(async (): Promise => { + await this.enableNotification(false); + }) + .leftCustomizeButton() + Divider() + .color($r('app.color.comp_divider')) + .vertical(true) + .height(Constants.DIVIDER_HEIGHT) + .strokeWidth(Constants.DIVIDER_WIDTH) + Button($r('app.string.ALLOW')) + .onClick(async (): Promise => { + await this.enableNotification(true); + }) + .rightCustomizeButton() + } + .margin({ left: Constants.BUTTON_MARGIN_LEFT, right: Constants.BUTTON_MARGIN_RIGHT }) + } } + .backgroundColor($r('app.color.dialog_bg')) .borderRadius(Constants.DIALOG_PRIVACY_BORDER_RADIUS) - .backgroundBlurStyle(BlurStyle.COMPONENT_ULTRA_THICK) .width(Constants.FULL_WIDTH) .padding({ bottom: Constants.DIALOG_PADDING_BOTTOM }) + .margin({ bottom: $r('sys.float.ohos_id_dialog_margin_bottom') }) .clip(true) } .width(Constants.FULL_WIDTH) @@ -196,7 +196,7 @@ struct PermissionDialog { this.appName = titleTrim(appName); console.info(TAG, `hap label: ${this.appName}`); } catch (err) { - console.error(TAG, `applicationName error : ${JSON.stringify(err)}`); + console.error(TAG, `applicationName error : ${err?.code}`); } } @@ -215,7 +215,7 @@ struct PermissionDialog { this.naviHeight = avoidArea.bottomRect.height; } } catch (err) { - console.error(TAG, `Failed to obtain the area. Cause: ${JSON.stringify(err)}`); + console.error(TAG, `Failed to obtain the area. Cause: ${err?.code}`); } } @@ -232,7 +232,7 @@ struct PermissionDialog { } } } catch (err) { - console.error(TAG, 'Failed to get the device foldable status. Code: ' + JSON.stringify(err)); + console.error(TAG, 'Failed to get the device foldable status. Code: ${err?.code}'); } // read ccm configs @@ -253,7 +253,7 @@ struct PermissionDialog { } } } catch (error) { - console.log(TAG, 'Failed get ccm files, Cause: ${JSON.stringify(err)}'); + console.log(TAG, 'Failed get ccm files, Cause: ${err?.code}'); } this.isBottomPopover = isBottomPopoverTemp && isVertical; } @@ -278,7 +278,7 @@ struct PermissionDialog { try { await this.updateStatus(); } catch (err) { - console.error(TAG, `aboutToAppear error : + ${JSON.stringify(err)}`); + console.error(TAG, `aboutToAppear error : ${err?.code}`); await this.dialog?.destroyException(); await this.session?.terminateSelf(); } @@ -293,13 +293,13 @@ struct PermissionDialog { await win.resize(dis.width, dis.height); await this.updateStatus(); } catch (err) { - console.error(TAG, 'Failed to touch callback. Code: ' + JSON.stringify(err)); + console.error(TAG, 'Failed to touch callback. Code: ${err?.code}'); } }; try { display.on('foldDisplayModeChange', callback); } catch (err) { - console.error(TAG, 'Failed to register callback. Code: ' + JSON.stringify(err)); + console.error(TAG, 'Failed to register callback. Code: ${err?.code}'); } } diff --git a/services/dialog_ui/enable_notification_dialog/entry/src/main/ets/pages/watchNotificationDialog.ets b/services/dialog_ui/enable_notification_dialog/entry/src/main/ets/pages/watchNotificationDialog.ets new file mode 100644 index 000000000..7fa6ab181 --- /dev/null +++ b/services/dialog_ui/enable_notification_dialog/entry/src/main/ets/pages/watchNotificationDialog.ets @@ -0,0 +1,272 @@ +/* + * Copyright (c) 2023 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import bundleResourceManager from '@ohos.bundle.bundleResourceManager'; +import display from '@ohos.display'; +import window from '@ohos.window'; +import { titleTrim } from '../common/utils'; +import Constants from '../common/constant'; +import fs from '@ohos.file.fs'; +import configPolicy from '@ohos.configPolicy'; +import { EnableNotificationDialog } from '../ServiceExtAbility/NotificationServiceExtAbility'; +import { Callback} from '@ohos.base'; +import UIExtensionContentSession from '@ohos.app.ability.UIExtensionContentSession'; + +const TAG = 'NotificationDialog_Service '; +const permission: Record = { + 'label': $r('app.string.group_label_notification'), + 'icon': $r('app.media.ic_public_ring'), + 'reason': $r('app.string.reason'), +}; + +let storage = LocalStorage.getShared(); + +@Entry(storage) +@Component +struct NotificationDialogPage { + @StorageLink('isUpdate') isUpdate: number = -1; + privacyDialogController: CustomDialogController = new CustomDialogController({ + builder: PermissionDialog({ isUpdate: $isUpdate }), + autoCancel: false, + alignment: DialogAlignment.TopStart, + customStyle: false, + onWillDismiss: (dismissDialogAction: DismissDialogAction) => { + console.info(TAG, `dialog onWillDismiss reason= : ${JSON.stringify(dismissDialogAction.reason)}`); + }, + width: '466px', + height: '466px' + }); + + build() {} + + aboutToAppear() { + this.privacyDialogController.open(); + } + + onPageShow() { + this.isUpdate++; + } +} + +@CustomDialog +struct PermissionDialog { + @State appName: string = ''; + @State isBottomPopover: boolean = true; + @StorageLink('clicked') clicked: boolean = false; + @Link @Watch('updateOnPageShow') isUpdate: number; + dialog?: EnableNotificationDialog; + session?: UIExtensionContentSession; + controller?: CustomDialogController; + + build() { + Flex({ justifyContent: FlexAlign.Center, alignItems: ItemAlign.Center }) { + Column() { + Image(permission.icon) + .width('92px') + .height('92px') + .margin({ + top: '2%' + }) + + Scroll() { + Column() { + Row() { + Flex({ justifyContent: FlexAlign.Center }) { + Text() { + Span(getContext(this).resourceManager.getStringSync(permission.label.id).replace('%s', this.appName)) + } + .fontSize('38px') + .fontColor('#FFFFFF') + .fontWeight(500) + .lineHeight('45px') + .margin({ + top: '4.1%', + left: '11.2%', + right: '11.2%' + }) + .textAlign(TextAlign.Center) + } + } + + Row() { + Flex({ justifyContent: FlexAlign.Center }) { + Button($r('app.string.ALLOW')) + .onClick(async (): Promise => { + await this.enableNotification(true); + }) + .backgroundColor('#1F71FF') + .width('232px') + .height('80px') + .fontColor('#FFFFFF') + .fontSize('30px') + .fontWeight(500) + } + .margin({top:'4.1%'}) + } + + Row() { + Flex({ justifyContent: FlexAlign.Center }) { + Button($r('app.string.BAN')) + .onClick(async (): Promise => { + await this.enableNotification(false); + }) + .backgroundColor('#255EA1FF') + .width('232px') + .height('80px') + .fontColor('#5EA1FF') + .fontSize('30px') + .fontWeight(500) + } + .margin({top:'4.1%'}) + } + } + } + .scrollable(ScrollDirection.Vertical) + .scrollBar(BarState.Off) + } + } + .margin({ + top: 0, + left: 0, + right: 0, + bottom: 0 + }) + .width('100%') + .height('100%') + .backgroundColor('#35000000') + .backgroundEffect({ + radius: 20, + saturation: 50, + adaptiveColor: AdaptiveColor.AVERAGE, + blurOptions: { + grayscale: [35, 35] + } + }) + + } + + async updateApplicationName(bundleName: string): Promise { + console.info(TAG, `updateApplicationName bundleName: ${bundleName}`); + try { + let bundleFlags = bundleResourceManager.ResourceFlag.GET_RESOURCE_INFO_ALL; + let resourceInfo = bundleResourceManager.getBundleResourceInfo(bundleName, bundleFlags); + console.info(TAG, `applicationName name : ${JSON.stringify(resourceInfo.label)}`); + let appName = resourceInfo.label; + this.appName = titleTrim(appName); + console.info(TAG, `hap label: ${this.appName}`); + } catch (err) { + console.error(TAG, `applicationName error : ${err?.code}`); + } + } + + async updateIsBottomPopover(): Promise { + let dis = display.getDefaultDisplaySync(); + let isVertical = dis.width <= dis.height; + try { + if (display.isFoldable()) { + let foldStatus = display.getFoldStatus(); + if (foldStatus == display.FoldStatus.FOLD_STATUS_EXPANDED || + foldStatus == display.FoldStatus.FOLD_STATUS_HALF_FOLDED) { + this.isBottomPopover = false; + return; + } + } + } catch (err) { + console.error(TAG, 'Failed to get the device foldable status. Code: ${err?.code}'); + } + + // read ccm configs + let isBottomPopoverTemp = false; + try { + let filePaths = await configPolicy.getCfgFiles(Constants.CCM_CONFIG_PATH); + for (let i = 0; i < filePaths.length; i++) { + let res = fs.accessSync(filePaths[i]); + if (res) { + let fileContent = fs.readTextSync(filePaths[i]); + let config: NotificationConfig = JSON.parse(fileContent); + if (config.notificationAuthorizationWindow != undefined) { + let windowConfig: NotificationAuthorizationWindow = config.notificationAuthorizationWindow; + if (windowConfig.isBottomPopover != undefined) { + isBottomPopoverTemp = windowConfig.isBottomPopover; + } + } + } + } + } catch (error) { + console.log(TAG, 'Failed get ccm files, Cause: ${err?.code}'); + } + this.isBottomPopover = isBottomPopoverTemp && isVertical; + } + + async updateStatus(): Promise { + let bundleNameObj = this.dialog?.want.parameters?.bundleName; + let bundleName = bundleNameObj ? bundleNameObj.toString() : ''; + await this.updateApplicationName(bundleName); + await this.updateIsBottomPopover(); + } + + async updateOnPageShow(): Promise { + if (this.isUpdate > 0) { + await this.updateStatus(); + } + } + + async aboutToAppear(): Promise { + this.dialog = storage.get('dialog') as EnableNotificationDialog; + this.session = storage.get('session') as UIExtensionContentSession; + try { + await this.updateStatus(); + } catch (err) { + console.error(TAG, `aboutToAppear error : ${err?.code}`); + await this.dialog?.destroyException(); + await this.session?.terminateSelf(); + } + } + + async aboutToDisappear(): Promise { + console.info(TAG, `aboutToDisappear`); + this.session?.terminateSelf(); + } + + async enableNotification(enabled: boolean): Promise { + console.info(TAG, `NotificationDialog enableNotification: ${enabled}`); + try { + await this.dialog?.publishButtonClickedEvent(enabled); + this.clicked = true; + } catch (err) { + console.error(TAG, `NotificationDialog enable error, code is ${err?.code}`); + await this.dialog?.destroyException(); + } finally { + await this.dialog?.subWindow?.destroyWindow(); + this.session?.terminateSelf(); + } + } +} + +interface NotificationConfig { + notificationAuthorizationWindow: NotificationAuthorizationWindow; +} + +interface NotificationAuthorizationWindow { + isBottomPopover: boolean; +} + +interface NotificationConfigAbc { + deviceType: DeviceType; +} + +interface DeviceType { + isWatch: boolean; +} diff --git a/services/dialog_ui/enable_notification_dialog/entry/src/main/module.json b/services/dialog_ui/enable_notification_dialog/entry/src/main/module.json index 57cfcffc1..ebd7a89e8 100644 --- a/services/dialog_ui/enable_notification_dialog/entry/src/main/module.json +++ b/services/dialog_ui/enable_notification_dialog/entry/src/main/module.json @@ -8,7 +8,8 @@ "deviceTypes": [ "default", "tablet", - "2in1" + "2in1", + "wearable" ], "deliveryWithInstall": true, "installationFree": false, diff --git a/services/dialog_ui/enable_notification_dialog/entry/src/main/resources/base/profile/main_pages.json b/services/dialog_ui/enable_notification_dialog/entry/src/main/resources/base/profile/main_pages.json index ecceb635d..44a0e7536 100644 --- a/services/dialog_ui/enable_notification_dialog/entry/src/main/resources/base/profile/main_pages.json +++ b/services/dialog_ui/enable_notification_dialog/entry/src/main/resources/base/profile/main_pages.json @@ -1,5 +1,6 @@ { "src": [ - "pages/notificationDialog" + "pages/notificationDialog", + "pages/watchNotificationDialog" ] -} +} \ No newline at end of file diff --git a/services/distributed/include/distributed_preferences_database.h b/services/distributed/include/distributed_preferences_database.h index b291bd14a..282ea1c22 100644 --- a/services/distributed/include/distributed_preferences_database.h +++ b/services/distributed/include/distributed_preferences_database.h @@ -83,7 +83,6 @@ private: bool CheckKvDataManager(); void GetKvStore(); bool CheckKvStore(); - void CloseKvStore(); std::mutex mutex_; std::unique_ptr kvDataManager_; diff --git a/services/distributed/src/distributed_preferences_database.cpp b/services/distributed/src/distributed_preferences_database.cpp index d3f9885e4..13cee84a8 100644 --- a/services/distributed/src/distributed_preferences_database.cpp +++ b/services/distributed/src/distributed_preferences_database.cpp @@ -98,14 +98,12 @@ bool DistributedPreferencesDatabase::PutToDistributedDB(const std::string &key, if (!KvStoreFlowControl()) { ANS_LOGE("KvStoreFlowControl is false."); - CloseKvStore(); return false; } DistributedKv::Key kvStoreKey(key); DistributedKv::Value kvStoreValue(value); DistributedKv::Status status = kvStore_->Put(kvStoreKey, kvStoreValue); - CloseKvStore(); if (status != DistributedKv::Status::SUCCESS) { ANS_LOGE("kvStore Put() failed ret = 0x%{public}x", status); return false; @@ -123,13 +121,11 @@ bool DistributedPreferencesDatabase::GetFromDistributedDB(const std::string &key if (!KvStoreFlowControl()) { ANS_LOGE("KvStoreFlowControl is defeat."); - CloseKvStore(); return false; } DistributedKv::Key kvStoreKey(key); DistributedKv::Value kvStoreValue; DistributedKv::Status status = kvStore_->Get(kvStoreKey, kvStoreValue); - CloseKvStore(); if (status != DistributedKv::Status::SUCCESS) { ANS_LOGE("kvStore Get() failed ret = 0x%{public}x", status); return false; @@ -147,12 +143,10 @@ bool DistributedPreferencesDatabase::GetEntriesFromDistributedDB( } if (!KvStoreFlowControl()) { ANS_LOGE("KvStoreFlowControl is false."); - CloseKvStore(); return false; } DistributedKv::Key kvStoreKey(prefixKey); DistributedKv::Status status = kvStore_->GetEntries(kvStoreKey, entries); - CloseKvStore(); if (status != DistributedKv::Status::SUCCESS) { ANS_LOGE("kvStore GetEntries() failed ret = 0x%{public}x", status); return false; @@ -169,13 +163,11 @@ bool DistributedPreferencesDatabase::DeleteToDistributedDB(const std::string &ke } if (!KvStoreFlowControl()) { ANS_LOGE("kvStore flow control."); - CloseKvStore(); return false; } DistributedKv::Key kvStoreKey(key); DistributedKv::Value kvStoreValue; DistributedKv::Status status = kvStore_->Delete(kvStoreKey); - CloseKvStore(); if (status != DistributedKv::Status::SUCCESS) { ANS_LOGE("kvStore Delete() failed ret = 0x%{public}x", status); return false; @@ -211,11 +203,5 @@ bool DistributedPreferencesDatabase::ClearDatabase() } return true; } - -void DistributedPreferencesDatabase::CloseKvStore() -{ - DistributedKv::AppId appId = {.appId = APP_ID}; - kvDataManager_->CloseKvStore(appId, kvStore_); -} } // namespace Notification } // namespace OHOS \ No newline at end of file diff --git a/services/distributed/test/unittest/distributed_preferences_test.cpp b/services/distributed/test/unittest/distributed_preferences_test.cpp index 22504c93e..b2d15d12b 100644 --- a/services/distributed/test/unittest/distributed_preferences_test.cpp +++ b/services/distributed/test/unittest/distributed_preferences_test.cpp @@ -101,7 +101,7 @@ HWTEST_F(DistributedPreferencesTest, SetDistributedBundleEnable_00200, Function */ HWTEST_F(DistributedPreferencesTest, ClearDataInRestoreFactorySettings_00100, Function | SmallTest | Level1) { - EXPECT_EQ(distributedPreferences_->ClearDataInRestoreFactorySettings(), ERR_ANS_DISTRIBUTED_OPERATION_FAILED); + EXPECT_EQ(distributedPreferences_->ClearDataInRestoreFactorySettings(), ERR_OK); } /** diff --git a/services/distributed/test/unittest/distributed_screen_status_manager_test.cpp b/services/distributed/test/unittest/distributed_screen_status_manager_test.cpp index 1028e9c8e..dc1eb3649 100644 --- a/services/distributed/test/unittest/distributed_screen_status_manager_test.cpp +++ b/services/distributed/test/unittest/distributed_screen_status_manager_test.cpp @@ -15,7 +15,6 @@ #include #include "ans_inner_errors.h" -#include "errors.h" #include "gtest/gtest.h" #define private public #include "distributed_screen_status_manager.h" @@ -53,7 +52,8 @@ HWTEST_F(DistributedScreenStatusManagerTest, CheckRemoteDevicesIsUsing_00100, Fu { bool isUsing = true; - EXPECT_EQ(distributedScreenStatusManager_->CheckRemoteDevicesIsUsing(isUsing), ERR_OK); + EXPECT_EQ(distributedScreenStatusManager_->CheckRemoteDevicesIsUsing(isUsing), + ERR_ANS_DISTRIBUTED_OPERATION_FAILED); } /** @@ -65,7 +65,7 @@ HWTEST_F(DistributedScreenStatusManagerTest, SetLocalScreenStatus_00100, Functio { bool screenOn = false; - EXPECT_EQ(distributedScreenStatusManager_->SetLocalScreenStatus(screenOn), ERR_OK); + EXPECT_EQ(distributedScreenStatusManager_->SetLocalScreenStatus(screenOn), ERR_ANS_DISTRIBUTED_OPERATION_FAILED); } } // namespace Notification } // namespace OHOS \ No newline at end of file diff --git a/test/fuzztest/ansmanagerstub_fuzzer/ansmanagerstub_fuzzer.cpp b/test/fuzztest/ansmanagerstub_fuzzer/ansmanagerstub_fuzzer.cpp index 71e6f7cda..9df1eecfa 100644 --- a/test/fuzztest/ansmanagerstub_fuzzer/ansmanagerstub_fuzzer.cpp +++ b/test/fuzztest/ansmanagerstub_fuzzer/ansmanagerstub_fuzzer.cpp @@ -44,6 +44,12 @@ namespace OHOS { MessageParcel datas; MessageParcel reply; MessageOption flags; + // test HandleIsNeedSilentInDoNotDisturbMode function + ansManagerStub.HandleIsNeedSilentInDoNotDisturbMode(datas, reply); + // test HandleRegisterSwingCallback function + #ifdef NOTIFICATION_SMART_REMINDER_SUPPORTED + ansManagerStub.HandleRegisterSwingCallback(datas, reply); + #endif ansManagerStub.OnRemoteRequest(0, datas, reply, flags); ansManagerStub.OnRemoteRequest((int) Notification::NotificationInterfaceCode::PUBLISH_NOTIFICATION, datas, reply, flags); diff --git a/test/fuzztest/anssubscriberstub_fuzzer/anssubscriberstub_fuzzer.cpp b/test/fuzztest/anssubscriberstub_fuzzer/anssubscriberstub_fuzzer.cpp index a9aac1a98..68e82b5a5 100644 --- a/test/fuzztest/anssubscriberstub_fuzzer/anssubscriberstub_fuzzer.cpp +++ b/test/fuzztest/anssubscriberstub_fuzzer/anssubscriberstub_fuzzer.cpp @@ -16,6 +16,7 @@ #define private public #define protected public #include "ans_subscriber_stub.h" +#include "ans_subscriber_local_live_view_stub.h" #undef private #undef protected #include "ans_permission_def.h" @@ -26,6 +27,7 @@ namespace OHOS { bool DoSomethingInterestingWithMyAPI(const char* data, size_t size) { Notification::AnsSubscriberStub ansSubscriberStub; + Notification::AnsSubscriberLocalLiveViewStub ansSubscriberLocalLiveViewStub; uint32_t code = GetU32Data(data); MessageParcel datas; MessageParcel reply; @@ -64,6 +66,20 @@ namespace OHOS { ansSubscriberStub.OnDoNotDisturbDateChange(date); // test OnEnabledNotificationChanged function sptr callbackData = new Notification::EnabledNotificationCallbackData(); + // test HandleOnBadgeEnabledChanged function + ansSubscriberStub.HandleOnBadgeEnabledChanged(datas, reply); + // test HandleOnResponse function + ansSubscriberLocalLiveViewStub.HandleOnResponse(datas, reply); + // test HandleOnConsumedListMap function + ansSubscriberStub.HandleOnConsumedListMap(datas, reply); + // test HandleOnDisconnected function + ansSubscriberLocalLiveViewStub.HandleOnDisconnected(datas, reply); + // test HandleOnBadgeChanged function + ansSubscriberStub.HandleOnBadgeChanged(datas, reply); + // test HandleOnCanceledListMap function + ansSubscriberStub.HandleOnCanceledListMap(datas, reply); + // test HandleOnConnected function + ansSubscriberLocalLiveViewStub.HandleOnConnected(datas, reply); return true; } } diff --git a/test/fuzztest/fuzz_common_base/fuzz_data.h b/test/fuzztest/fuzz_common_base/fuzz_data.h index cbd7aea1e..87e6af604 100644 --- a/test/fuzztest/fuzz_common_base/fuzz_data.h +++ b/test/fuzztest/fuzz_common_base/fuzz_data.h @@ -82,7 +82,7 @@ public: return (GetData() % BOOL_MODULO_NUM) == 0; } - size_t GetSize() + size_t GetSize() const { return size_; } -- Gitee From 8a092310fa91038977e9ce70670d5e4c7165e40f Mon Sep 17 00:00:00 2001 From: jiangzhijun8 Date: Tue, 15 Oct 2024 11:13:16 +0800 Subject: [PATCH 077/167] 5.0.1 rebase Signed-off-by: jiangzhijun8 --- services/ans/src/advanced_notification_service.cpp | 2 +- services/ans/src/reminder_store.cpp | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/services/ans/src/advanced_notification_service.cpp b/services/ans/src/advanced_notification_service.cpp index 27ccf4816..d43bf7567 100644 --- a/services/ans/src/advanced_notification_service.cpp +++ b/services/ans/src/advanced_notification_service.cpp @@ -19,7 +19,7 @@ #include #include -#include "fa_ability_context.h" +#include "ability_context.h" #include "ability_info.h" #include "access_token_helper.h" #include "accesstoken_kit.h" diff --git a/services/ans/src/reminder_store.cpp b/services/ans/src/reminder_store.cpp index 1ee399dc5..d9a42d6f5 100644 --- a/services/ans/src/reminder_store.cpp +++ b/services/ans/src/reminder_store.cpp @@ -20,7 +20,7 @@ #include #include -#include "fa_ability_context.h" +#include "ability_context.h" #include "ans_log_wrapper.h" #include "reminder_table.h" #include "reminder_table_old.h" -- Gitee From decd8c18cb9bd618537fa789e626df3085908b83 Mon Sep 17 00:00:00 2001 From: markYao Date: Mon, 14 Oct 2024 20:10:18 +0800 Subject: [PATCH 078/167] =?UTF-8?q?cherry=20pick=20b7596e7=20from=20https:?= =?UTF-8?q?//gitee.com/mark-yao/notification=5Fdistributed=5Fnotification?= =?UTF-8?q?=5Fservice/pulls/2297=20shared=5Fptr=E4=BD=BF=E7=94=A8=E5=89=8D?= =?UTF-8?q?=E5=88=A4=E7=A9=BA?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: markYao --- .../ans/src/advanced_notification_live_view_service.cpp | 8 ++++++++ .../ans/src/advanced_notification_publish_service.cpp | 2 +- 2 files changed, 9 insertions(+), 1 deletion(-) diff --git a/services/ans/src/advanced_notification_live_view_service.cpp b/services/ans/src/advanced_notification_live_view_service.cpp index 3f9dfe333..67ab5646b 100644 --- a/services/ans/src/advanced_notification_live_view_service.cpp +++ b/services/ans/src/advanced_notification_live_view_service.cpp @@ -431,6 +431,14 @@ ErrCode AdvancedNotificationService::IsAllowedRemoveSlot(const sptr &newRequest, const sptr &oldRequest) { + if (oldRequest->GetContent() == nullptr || + newRequest->GetContent() == nullptr) { + return; + } + if (oldRequest->GetContent()->GetNotificationContent() == nullptr || + newRequest->GetContent()->GetNotificationContent() == nullptr) { + return; + } if (newRequest->GetSlotType() != NotificationConstant::SlotType::LIVE_VIEW) { return; } diff --git a/services/ans/src/advanced_notification_publish_service.cpp b/services/ans/src/advanced_notification_publish_service.cpp index a8675583c..44966fb1f 100644 --- a/services/ans/src/advanced_notification_publish_service.cpp +++ b/services/ans/src/advanced_notification_publish_service.cpp @@ -123,7 +123,7 @@ ErrCode AdvancedNotificationService::Publish(const std::string &label, const spt if (isSubsystem) { return PublishNotificationBySa(request); } - if (request->GetRemovalWantAgent() != nullptr) { + if (request->GetRemovalWantAgent() != nullptr && request->GetRemovalWantAgent()->GetPendingWant() != nullptr) { uint32_t operationType = (uint32_t)(request->GetRemovalWantAgent()->GetPendingWant() ->GetType(request->GetRemovalWantAgent()->GetPendingWant()->GetTarget())); bool isSystemApp = AccessTokenHelper::IsSystemApp(); -- Gitee From 385a9f02d15bb3225322b65590c60a9de5f10b8d Mon Sep 17 00:00:00 2001 From: wangsen1994 Date: Fri, 6 Sep 2024 17:33:45 +0800 Subject: [PATCH 079/167] =?UTF-8?q?ANS=E6=96=B0=E5=A2=9E=E6=9F=A5=E8=AF=A2?= =?UTF-8?q?=E5=8B=BF=E6=89=B0=E5=90=8D=E5=8D=95=E6=8E=A5=E5=8F=A3?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: wangsen1994 --- frameworks/ans/src/notification_helper.cpp | 4 + frameworks/cj/ffi/include/inner_errors.h | 2 + .../core/common/include/ans_const_define.h | 1 + .../core/common/include/ans_inner_errors.h | 4 +- .../core/include/ans_manager_interface.h | 8 ++ frameworks/core/include/ans_manager_proxy.h | 9 +++ frameworks/core/include/ans_manager_stub.h | 16 +++- frameworks/core/include/ans_notification.h | 8 ++ ..._notification_service_ipc_interface_code.h | 1 + .../core/src/ans_manager_proxy_disturb.cpp | 40 +++++++++ frameworks/core/src/ans_manager_stub.cpp | 23 ++++++ .../core/src/ans_manager_stub_invalid.cpp | 6 ++ frameworks/core/src/ans_notification.cpp | 10 +++ .../ans_notification_branch_test.cpp | 7 +- frameworks/js/napi/include/common.h | 15 +++- frameworks/js/napi/include/disturb_mode.h | 16 +++- .../napi/include/manager/napi_disturb_mode.h | 3 +- frameworks/js/napi/src/common.cpp | 45 +++++++++++ frameworks/js/napi/src/common_utils.cpp | 4 +- frameworks/js/napi/src/disturb_mode.cpp | 23 ++++++ .../js/napi/src/manager/init_module.cpp | 1 + .../js/napi/src/manager/napi_disturb_mode.cpp | 81 +++++++++++++++++++ interfaces/inner_api/notification_helper.h | 9 +++ .../include/advanced_notification_service.h | 13 ++- .../ans/src/advanced_notification_utils.cpp | 24 ++++++ services/ans/src/notification_preferences.cpp | 2 +- 26 files changed, 363 insertions(+), 12 deletions(-) diff --git a/frameworks/ans/src/notification_helper.cpp b/frameworks/ans/src/notification_helper.cpp index 0cad2612f..e55e7fcbf 100644 --- a/frameworks/ans/src/notification_helper.cpp +++ b/frameworks/ans/src/notification_helper.cpp @@ -550,5 +550,9 @@ ErrCode NotificationHelper::RegisterSwingCallback(const std::function &profile) +{ + return DelayedSingleton::GetInstance()->GetDoNotDisturbProfile(id, profile); +} } // namespace Notification } // namespace OHOS diff --git a/frameworks/cj/ffi/include/inner_errors.h b/frameworks/cj/ffi/include/inner_errors.h index 053b5c2b9..c613aa83a 100644 --- a/frameworks/cj/ffi/include/inner_errors.h +++ b/frameworks/cj/ffi/include/inner_errors.h @@ -107,6 +107,7 @@ enum ErrorCode : uint32_t { ERR_ANS_EXPIRED_NOTIFICATION, ERR_ANS_PUSH_CHECK_NETWORK_UNREACHABLE, ERR_ANS_PUSH_CHECK_EXTRAINFO_INVALID, + ERR_ANS_NO_PROFILE_TEMPLATE, }; // Common error code const uint32_t ERROR_PERMISSION_DENIED = 201; // No permission to call the interface. @@ -133,6 +134,7 @@ const int32_t ERROR_NO_RIGHT = 1600014; // No permission. const int32_t ERROR_REPEAT_SET = 1600015; // Repeat create or end. const int32_t ERROR_EXPIRED_NOTIFICATION = 1600016; // Low update version. const int32_t ERROR_SETTING_WINDOW_EXIST = 1600018; // The notification settings window is already displayed. +const int32_t ERROR_NO_PROFILE_TEMPLATE = 1600019; // Not exit noNotDisturb profile template. const int32_t ERROR_NETWORK_UNREACHABLE = 2300007; // Network unreachable. const int32_t ERROR_BUNDLE_NOT_FOUND = 17700001; // The specified bundle name was not found. diff --git a/frameworks/core/common/include/ans_const_define.h b/frameworks/core/common/include/ans_const_define.h index 0bb0d7b78..24135987d 100644 --- a/frameworks/core/common/include/ans_const_define.h +++ b/frameworks/core/common/include/ans_const_define.h @@ -43,6 +43,7 @@ constexpr int32_t MAX_STATUS_VECTOR_NUM = 1000; constexpr uint32_t MAX_CANCELED_PARCELABLE_VECTOR_NUM = 200; constexpr int32_t DEFAULT_UID = 0; +constexpr int32_t INVALID_PROFILE_ID = -1; constexpr int32_t SUBSCRIBE_USER_INIT = -1; constexpr int32_t SUBSCRIBE_USER_ALL = -2; constexpr int32_t DEFAULT_USER_ID = 100; diff --git a/frameworks/core/common/include/ans_inner_errors.h b/frameworks/core/common/include/ans_inner_errors.h index dfbf494fc..96884d8f7 100644 --- a/frameworks/core/common/include/ans_inner_errors.h +++ b/frameworks/core/common/include/ans_inner_errors.h @@ -92,7 +92,8 @@ enum ErrorCode : uint32_t { ERR_ANS_DUPLICATE_MSG, ERR_ANS_NO_AGENT_SETTING, ERR_ANS_ENCRYPT_FAIL, - ERR_ANS_DECRYPT_FAIL + ERR_ANS_DECRYPT_FAIL, + ERR_ANS_NO_PROFILE_TEMPLATE }; enum ReminderErrorCode : uint32_t { @@ -148,6 +149,7 @@ const int32_t ERROR_REPEAT_SET = 1600015; // Repeat create const int32_t ERROR_EXPIRED_NOTIFICATION = 1600016; // Low update version. const int32_t ERROR_NO_AGENT_SETTING = 1600017; // No corresponding agent relationship configuration. const int32_t ERROR_SETTING_WINDOW_EXIST = 1600018; // The notification settings window is already displayed. +const int32_t ERROR_NO_PROFILE_TEMPLATE = 1600019; // Not exit noNotDisturb profile template. const int32_t ERROR_NETWORK_UNREACHABLE = 2300007; // Network unreachable. const int32_t ERROR_BUNDLE_NOT_FOUND = 17700001; // The specified bundle name was not found. } // namespace Notification diff --git a/frameworks/core/include/ans_manager_interface.h b/frameworks/core/include/ans_manager_interface.h index 790abe0ce..06893561b 100644 --- a/frameworks/core/include/ans_manager_interface.h +++ b/frameworks/core/include/ans_manager_interface.h @@ -940,6 +940,14 @@ public: */ virtual ErrCode SetTargetDeviceStatus(const std::string &deviceType, const uint32_t status) = 0; + /** + * @brief Get do not disturb profile by id. + * + * @param id Profile id. + * @param status Indicates the NotificationDoNotDisturbProfile objects. + * @return Returns ERR_OK on success, others on failure. + */ + virtual ErrCode GetDoNotDisturbProfile(int32_t id, sptr &profile) = 0; #ifdef NOTIFICATION_SMART_REMINDER_SUPPORTED /** * @brief Register Swing Callback. diff --git a/frameworks/core/include/ans_manager_proxy.h b/frameworks/core/include/ans_manager_proxy.h index 59bf9a7eb..d6bc0135d 100644 --- a/frameworks/core/include/ans_manager_proxy.h +++ b/frameworks/core/include/ans_manager_proxy.h @@ -928,6 +928,15 @@ public: */ ErrCode SetTargetDeviceStatus(const std::string &deviceType, const uint32_t status) override; + /** + * @brief Get do not disturb profile by id. + * + * @param id Profile id. + * @param status Indicates the NotificationDoNotDisturbProfile objects. + * @return Returns ERR_OK on success, others on failure. + */ + ErrCode GetDoNotDisturbProfile(int32_t id, sptr &profile) override; + #ifdef NOTIFICATION_SMART_REMINDER_SUPPORTED /** * @brief Register Swing Callback. diff --git a/frameworks/core/include/ans_manager_stub.h b/frameworks/core/include/ans_manager_stub.h index 0ec670f8f..5b2edf2c7 100644 --- a/frameworks/core/include/ans_manager_stub.h +++ b/frameworks/core/include/ans_manager_stub.h @@ -349,7 +349,7 @@ public: */ virtual ErrCode GetSlotsByBundle( const sptr &bundleOption, std::vector> &slots) override; - + /** * @brief Get the specified slot corresponding to the bundle. * @@ -448,7 +448,7 @@ public: */ virtual ErrCode Subscribe( const sptr &subscriber, const sptr &info) override; - + /** * @brief Subscribes notifications self. * @@ -898,7 +898,7 @@ public: */ ErrCode IsDistributedEnabledByBundle( const sptr &bundleOption, const std::string &deviceType, bool &enabled) override; - + /** * @brief Get Enable smartphone to collaborate with other devices for intelligent reminders * @@ -930,6 +930,15 @@ public: */ virtual ErrCode SetTargetDeviceStatus(const std::string &deviceType, const uint32_t status) override; + /** + * @brief Get do not disturb profile by id. + * + * @param id Profile id. + * @param status Indicates the NotificationDoNotDisturbProfile object. + * @return Returns ERR_OK on success, others on failure. + */ + virtual ErrCode GetDoNotDisturbProfile(int32_t id, sptr &profile) override; + #ifdef NOTIFICATION_SMART_REMINDER_SUPPORTED /** * @brief Register Swing Callback. @@ -1040,6 +1049,7 @@ private: ErrCode HandleAddDoNotDisturbProfiles(MessageParcel &data, MessageParcel &reply); ErrCode HandleRemoveDoNotDisturbProfiles(MessageParcel &data, MessageParcel &reply); ErrCode HandleSetTargetDeviceStatus(MessageParcel &data, MessageParcel &reply); + ErrCode HandleGetDoNotDisturbProfile(MessageParcel &data, MessageParcel &reply); #ifdef NOTIFICATION_SMART_REMINDER_SUPPORTED ErrCode HandleRegisterSwingCallback(MessageParcel &data, MessageParcel &reply); #endif diff --git a/frameworks/core/include/ans_notification.h b/frameworks/core/include/ans_notification.h index c45c7332b..cb6a2d319 100644 --- a/frameworks/core/include/ans_notification.h +++ b/frameworks/core/include/ans_notification.h @@ -1087,6 +1087,14 @@ public: ErrCode RegisterSwingCallback(const std::function swingCbFunc); #endif + /** + * @brief Get do not disturb profile by id. + * + * @param id Profile id. + * @param status Indicates the NotificationDoNotDisturbProfile objects. + * @return Returns ERR_OK on success, others on failure. + */ + ErrCode GetDoNotDisturbProfile(int32_t id, sptr &profile); private: /** * @brief Gets Ans Manager proxy. diff --git a/frameworks/core/include/distributed_notification_service_ipc_interface_code.h b/frameworks/core/include/distributed_notification_service_ipc_interface_code.h index 56e520eb6..36f8ec9c6 100644 --- a/frameworks/core/include/distributed_notification_service_ipc_interface_code.h +++ b/frameworks/core/include/distributed_notification_service_ipc_interface_code.h @@ -148,6 +148,7 @@ namespace Notification { ADD_EXCLUDE_DATE_REMINDER, DEL_EXCLUDE_DATES_REMINDER, GET_EXCLUDE_DATES_REMINDER, + GET_DONOTDISTURB_PROFILE, }; } } diff --git a/frameworks/core/src/ans_manager_proxy_disturb.cpp b/frameworks/core/src/ans_manager_proxy_disturb.cpp index 30cb18e67..b13921e81 100644 --- a/frameworks/core/src/ans_manager_proxy_disturb.cpp +++ b/frameworks/core/src/ans_manager_proxy_disturb.cpp @@ -461,5 +461,45 @@ ErrCode AnsManagerProxy::IsNeedSilentInDoNotDisturbMode(const std::string &phone return result; } + +ErrCode AnsManagerProxy::GetDoNotDisturbProfile(int32_t id, sptr &profile) +{ + MessageParcel data; + if (!data.WriteInterfaceToken(AnsManagerProxy::GetDescriptor())) { + ANS_LOGE("GetDoNotDisturbProfile write interface token failed."); + return ERR_ANS_PARCELABLE_FAILED; + } + + if (!data.WriteInt32(id)) { + ANS_LOGE("GetDoNotDisturbProfile write id failed"); + return ERR_ANS_PARCELABLE_FAILED; + } + + MessageParcel reply; + MessageOption option = {MessageOption::TF_SYNC}; + ErrCode result = InnerTransact(NotificationInterfaceCode::GET_DONOTDISTURB_PROFILE, option, data, reply); + if (result != ERR_OK) { + ANS_LOGE("GetDoNotDisturbProfile transact ErrCode=%{public}d", result); + return ERR_ANS_TRANSACT_FAILED; + } + + if (!reply.ReadInt32(result)) { + ANS_LOGE("GetDoNotDisturbProfile read result failed."); + return ERR_ANS_PARCELABLE_FAILED; + } + + if (result != ERR_OK) { + ANS_LOGE("GetDoNotDisturbProfile result failed %{public}d.", result); + return result; + } + + profile = reply.ReadParcelable(); + if (profile == nullptr) { + ANS_LOGE("GetDoNotDisturbProfile read data failed."); + return ERR_ANS_PARCELABLE_FAILED; + } + + return ERR_OK; +} } // namespace Notification } // namespace OHOS diff --git a/frameworks/core/src/ans_manager_stub.cpp b/frameworks/core/src/ans_manager_stub.cpp index 8be5e0663..57507b50c 100644 --- a/frameworks/core/src/ans_manager_stub.cpp +++ b/frameworks/core/src/ans_manager_stub.cpp @@ -445,6 +445,10 @@ int32_t AnsManagerStub::OnRemoteRequest(uint32_t code, MessageParcel &data, Mess result = HandleGetExcludeDates(data, reply); break; } + case static_cast(NotificationInterfaceCode::GET_DONOTDISTURB_PROFILE): { + result = HandleGetDoNotDisturbProfile(data, reply); + break; + } default: { ANS_LOGE("[OnRemoteRequest] fail: unknown code!"); return IPCObjectStub::OnRemoteRequest(code, data, reply, flags); @@ -2613,6 +2617,25 @@ ErrCode AnsManagerStub::HandleSetTargetDeviceStatus(MessageParcel &data, Message return ERR_OK; } +ErrCode AnsManagerStub::HandleGetDoNotDisturbProfile(MessageParcel &data, MessageParcel &reply) +{ + int32_t profileId = data.ReadInt32(); + sptr profile = nullptr; + ErrCode result = GetDoNotDisturbProfile(profileId, profile); + if (!reply.WriteInt32(result)) { + ANS_LOGE("HandleGetDoNotDisturbProfile write result failed, ErrCode=%{public}d", result); + return ERR_ANS_PARCELABLE_FAILED; + } + + if (result == ERR_OK) { + if (!reply.WriteParcelable(profile)) { + ANS_LOGE("HandleGetDoNotDisturbProfile write slot failed."); + return ERR_ANS_PARCELABLE_FAILED; + } + } + return ERR_OK; +} + #ifdef NOTIFICATION_SMART_REMINDER_SUPPORTED ErrCode AnsManagerStub::HandleRegisterSwingCallback(MessageParcel &data, MessageParcel &reply) { diff --git a/frameworks/core/src/ans_manager_stub_invalid.cpp b/frameworks/core/src/ans_manager_stub_invalid.cpp index 0457626d0..1c4e664d1 100644 --- a/frameworks/core/src/ans_manager_stub_invalid.cpp +++ b/frameworks/core/src/ans_manager_stub_invalid.cpp @@ -646,6 +646,12 @@ ErrCode AnsManagerStub::SetTargetDeviceStatus(const std::string &deviceType, con return ERR_INVALID_OPERATION; } +ErrCode AnsManagerStub::GetDoNotDisturbProfile(int32_t id, sptr &profile) +{ + ANS_LOGE("GetDoNotDisturbProfile called!"); + return ERR_INVALID_OPERATION; +} + #ifdef NOTIFICATION_SMART_REMINDER_SUPPORTED ErrCode AnsManagerStub::RegisterSwingCallback(const sptr& swingCallback) { diff --git a/frameworks/core/src/ans_notification.cpp b/frameworks/core/src/ans_notification.cpp index e9fbd945f..bf63ed31d 100644 --- a/frameworks/core/src/ans_notification.cpp +++ b/frameworks/core/src/ans_notification.cpp @@ -1837,6 +1837,16 @@ bool AnsNotification::IsValidDelayTime(const NotificationRequest &request) cons return request.GetPublishDelayTime() <= MAX_PUBLISH_DELAY_TIME; } +ErrCode AnsNotification::GetDoNotDisturbProfile(int32_t id, sptr &profile) +{ + sptr proxy = GetAnsManagerProxy(); + if (!proxy) { + ANS_LOGE("Fail to GetAnsManagerProxy."); + return ERR_ANS_SERVICE_NOT_CONNECTED; + } + return proxy->GetDoNotDisturbProfile(id, profile); +} + #ifdef NOTIFICATION_SMART_REMINDER_SUPPORTED ErrCode AnsNotification::RegisterSwingCallback(const std::function swingCbFunc) { diff --git a/frameworks/core/test/unittest/ans_notification_branch_test/ans_notification_branch_test.cpp b/frameworks/core/test/unittest/ans_notification_branch_test/ans_notification_branch_test.cpp index a31ebe47c..904899139 100644 --- a/frameworks/core/test/unittest/ans_notification_branch_test/ans_notification_branch_test.cpp +++ b/frameworks/core/test/unittest/ans_notification_branch_test/ans_notification_branch_test.cpp @@ -572,6 +572,11 @@ public: return ERR_ANS_INVALID_PARAM; } + ErrCode GetDoNotDisturbProfile(int32_t id, sptr &profile) + { + return ERR_ANS_INVALID_PARAM; + } + #ifdef NOTIFICATION_SMART_REMINDER_SUPPORTED ErrCode RegisterSwingCallback(const sptr &swingCallback) override { @@ -840,7 +845,7 @@ HWTEST_F(AnsNotificationBranchTest, SetNotificationSlotFlagsAsBundle_0001, Funct ret = notification->GetNotificationSlotFlagsAsBundle(bundle, slotFlags); EXPECT_EQ(ret, (int)ERR_ANS_INVALID_PARAM); } - + /* * @tc.name: PublishNotification_0001 * @tc.desc: PublishNotification diff --git a/frameworks/js/napi/include/common.h b/frameworks/js/napi/include/common.h index e2b206aea..adf7d992c 100644 --- a/frameworks/js/napi/include/common.h +++ b/frameworks/js/napi/include/common.h @@ -1700,7 +1700,7 @@ public: * @return Returns a napi value with specified error object for callback */ static napi_value CreateErrorValue(napi_env env, int32_t errCode, std::string &msg); - + /** * @brief Sets a js object by specified BadgeNumberCallbackData object * @@ -1722,6 +1722,19 @@ public: */ static napi_value GetNotificationBundleOption( const napi_env &env, const napi_value &value, NotificationRequest &request); + /** + * @brief Sets a js object by specified NotificationDoNotDisturbProfile object + * + * @param env Indicates the environment that the API is invoked under + * @param date Indicates a NotificationDoNotDisturbProfile object to be converted + * @param result Indicates a js object to be set + * @return Returns the null object if success, returns the null value otherwise + */ + static napi_value SetDoNotDisturbProfile( + const napi_env &env, const NotificationDoNotDisturbProfile &data, napi_value &result); + + static napi_value SetBundleOption( + const napi_env &env, const NotificationBundleOption &bundleInfo, napi_value &result); static bool IsValidRemoveReason(int32_t reasonType); static void NapiThrow(napi_env env, int32_t errCode); static void NapiThrow(napi_env env, int32_t errCode, std::string &msg); diff --git a/frameworks/js/napi/include/disturb_mode.h b/frameworks/js/napi/include/disturb_mode.h index 31b784e56..fd9d5b662 100644 --- a/frameworks/js/napi/include/disturb_mode.h +++ b/frameworks/js/napi/include/disturb_mode.h @@ -21,6 +21,11 @@ namespace OHOS { namespace NotificationNapi { using namespace OHOS::Notification; +struct GetDoNotDisturbProfileParams { + int32_t profileId = INVALID_PROFILE_ID; + napi_ref callback = nullptr; +}; + struct SetDoNotDisturbDateParams { NotificationDoNotDisturbDate date; bool hasUserId = false; @@ -64,15 +69,24 @@ struct AsyncCallbackInfoSupportDoNotDisturb { CallbackPromiseInfo info; }; +struct AsyncCallbackInfoGetDoNotDisturbProfile { + napi_env env = nullptr; + napi_async_work asyncWork = nullptr; + GetDoNotDisturbProfileParams params; + sptr data; + CallbackPromiseInfo 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); napi_value ParseParameters(const napi_env &env, const napi_callback_info &info, SetDoNotDisturbDateParams ¶ms); napi_value ParseParameters(const napi_env &env, const napi_callback_info &info, GetDoNotDisturbDateParams ¶ms); +napi_value ParseParameters(const napi_env &env, const napi_callback_info &info, GetDoNotDisturbProfileParams ¶ms); bool ParseProfilesParameters( const napi_env &env, const napi_callback_info &info, std::vector> &profiles); bool AnalyseTrustlist(const napi_env &env, const napi_value &value, sptr &profile); } // namespace NotificationNapi } // namespace OHOS -#endif // BASE_NOTIFICATION_DISTRIBUTED_NOTIFICATION_SERVICE_FRAMEWORKS_JS_NAPI_INCLUDE_DISTURB_MODE_H \ No newline at end of file +#endif // BASE_NOTIFICATION_DISTRIBUTED_NOTIFICATION_SERVICE_FRAMEWORKS_JS_NAPI_INCLUDE_DISTURB_MODE_H diff --git a/frameworks/js/napi/include/manager/napi_disturb_mode.h b/frameworks/js/napi/include/manager/napi_disturb_mode.h index 4bf0af5b2..716cfd745 100644 --- a/frameworks/js/napi/include/manager/napi_disturb_mode.h +++ b/frameworks/js/napi/include/manager/napi_disturb_mode.h @@ -26,6 +26,7 @@ napi_value NapiGetDoNotDisturbDate(napi_env env, napi_callback_info info); napi_value NapiSupportDoNotDisturbMode(napi_env env, napi_callback_info info); napi_value NapiAddDoNotDisturbProfiles(napi_env env, napi_callback_info info); napi_value NapiRemoveDoNotDisturbProfiles(napi_env env, napi_callback_info info); +napi_value NapiGetDoNotDisturbProfile(napi_env env, napi_callback_info info); } // namespace NotificationNapi } // namespace OHOS -#endif // BASE_NOTIFICATION_DISTRIBUTED_NOTIFICATION_SERVICE_FRAMEWORKS_JS_NAPI_DISTURB_MODE_H \ No newline at end of file +#endif // BASE_NOTIFICATION_DISTRIBUTED_NOTIFICATION_SERVICE_FRAMEWORKS_JS_NAPI_DISTURB_MODE_H diff --git a/frameworks/js/napi/src/common.cpp b/frameworks/js/napi/src/common.cpp index 5d7fbde1e..70f42a17b 100644 --- a/frameworks/js/napi/src/common.cpp +++ b/frameworks/js/napi/src/common.cpp @@ -1412,5 +1412,50 @@ napi_value Common::SetNotificationUnifiedGroupInfo( return NapiGetBoolean(env, true); } + +napi_value Common::SetBundleOption(const napi_env &env, const NotificationBundleOption &bundleInfo, + napi_value &result) +{ + napi_value value = nullptr; + // bundle: string + napi_create_string_utf8(env, bundleInfo.GetBundleName().c_str(), NAPI_AUTO_LENGTH, &value); + napi_set_named_property(env, result, "bundle", value); + + // uid: uid_t + napi_create_int32(env, bundleInfo.GetUid(), &value); + napi_set_named_property(env, result, "uid", value); + return NapiGetBoolean(env, true); +} + +napi_value Common::SetDoNotDisturbProfile(const napi_env &env, const NotificationDoNotDisturbProfile &data, + napi_value &result) +{ + ANS_LOGD("enter"); + napi_value value = nullptr; + // id: number + napi_create_int32(env, data.GetProfileId(), &value); + napi_set_named_property(env, result, "id", value); + + // name: string + napi_create_string_utf8(env, data.GetProfileName().c_str(), NAPI_AUTO_LENGTH, &value); + napi_set_named_property(env, result, "name", value); + + size_t count = 0; + napi_create_array(env, &value); + // trustList?: std::vector + for (auto bundleInfo : data.GetProfileTrustList()) { + napi_value bundleValue = nullptr; + napi_create_object(env, &bundleValue); + if (!Common::SetBundleOption(env, bundleInfo, bundleValue)) { + continue; + } + napi_set_element(env, value, count, bundleValue); + count++; + } + if (count > 0) { + napi_set_named_property(env, result, "trustlist", value); + } + return NapiGetBoolean(env, true); +} } // namespace NotificationNapi } // namespace OHOS diff --git a/frameworks/js/napi/src/common_utils.cpp b/frameworks/js/napi/src/common_utils.cpp index a37f02e07..6422fddad 100644 --- a/frameworks/js/napi/src/common_utils.cpp +++ b/frameworks/js/napi/src/common_utils.cpp @@ -51,6 +51,7 @@ static const std::unordered_map ERROR_CODE_MESSAGE { {ERROR_NO_AGENT_SETTING, "There is no corresponding agent relationship configuration"}, {ERROR_DIALOG_IS_POPPING, "Dialog is popping"}, {ERROR_SETTING_WINDOW_EXIST, "The notification settings window is already displayed"}, + {ERROR_NO_PROFILE_TEMPLATE, "Not exit noNotDisturb profile template"}, }; } @@ -316,7 +317,8 @@ int32_t Common::ErrorToExternal(uint32_t errCode) {ERR_ANS_PUSH_CHECK_UNREGISTERED, ERROR_NO_RIGHT}, {ERR_ANS_PUSH_CHECK_NETWORK_UNREACHABLE, ERROR_NETWORK_UNREACHABLE}, {ERR_ANS_NO_AGENT_SETTING, ERROR_NO_AGENT_SETTING}, - {ERR_ANS_DIALOG_IS_POPPING, ERROR_DIALOG_IS_POPPING} + {ERR_ANS_DIALOG_IS_POPPING, ERROR_DIALOG_IS_POPPING}, + {ERR_ANS_NO_PROFILE_TEMPLATE, ERROR_NO_PROFILE_TEMPLATE} }; int32_t ExternalCode = ERROR_INTERNAL_ERROR; diff --git a/frameworks/js/napi/src/disturb_mode.cpp b/frameworks/js/napi/src/disturb_mode.cpp index a16396568..cc749d0ee 100644 --- a/frameworks/js/napi/src/disturb_mode.cpp +++ b/frameworks/js/napi/src/disturb_mode.cpp @@ -550,5 +550,28 @@ napi_value SupportDoNotDisturbMode(napi_env env, napi_callback_info info) return promise; } } + +napi_value ParseParameters(const napi_env &env, const napi_callback_info &info, GetDoNotDisturbProfileParams ¶ms) +{ + ANS_LOGD("ParseParameters"); + + size_t argc = DISTURB_PROFILES_PARA; + napi_value argv[DISTURB_PROFILES_PARA] = {nullptr}; + napi_value thisVar = nullptr; + NAPI_CALL(env, napi_get_cb_info(env, info, &argc, argv, &thisVar, NULL)); + + // argv[0]: profileId + napi_valuetype valuetype = napi_undefined; + if (argc >= DISTURB_PROFILES_PARA) { + NAPI_CALL(env, napi_typeof(env, argv[PARAM0], &valuetype)); + if (valuetype != napi_number) { + ANS_LOGW("Wrong argument type Excute promise."); + return Common::NapiGetNull(env); + } + NAPI_CALL(env, napi_get_value_int32(env, argv[PARAM0], ¶ms.profileId)); + } + + return Common::NapiGetNull(env); +} } // namespace NotificationNapi } // namespace OHOS diff --git a/frameworks/js/napi/src/manager/init_module.cpp b/frameworks/js/napi/src/manager/init_module.cpp index 0f2ffd95e..0468d5b69 100644 --- a/frameworks/js/napi/src/manager/init_module.cpp +++ b/frameworks/js/napi/src/manager/init_module.cpp @@ -122,6 +122,7 @@ napi_value NotificationManagerInit(napi_env env, napi_value exports) DECLARE_NAPI_FUNCTION("setAdditionalConfig", NapiSetAdditionConfig), DECLARE_NAPI_FUNCTION("isNotificationEnabledSync", NapiIsNotificationEnabledSync), DECLARE_NAPI_FUNCTION("openNotificationSettings", NapiOpenNotificationSettings), + DECLARE_NAPI_FUNCTION("getDoNotDisturbProfile", NapiGetDoNotDisturbProfile), }; NAPI_CALL(env, napi_define_properties(env, exports, sizeof(desc) / sizeof(desc[0]), desc)); diff --git a/frameworks/js/napi/src/manager/napi_disturb_mode.cpp b/frameworks/js/napi/src/manager/napi_disturb_mode.cpp index 14b50ed2e..15252415d 100644 --- a/frameworks/js/napi/src/manager/napi_disturb_mode.cpp +++ b/frameworks/js/napi/src/manager/napi_disturb_mode.cpp @@ -331,5 +331,86 @@ napi_value NapiSupportDoNotDisturbMode(napi_env env, napi_callback_info info) return promise; } } + +void AsyncCompleteCallbackNapiGetDoNotDisturbProfile(napi_env env, napi_status status, void *data) +{ + ANS_LOGD("GetDoNotDisturbProfile complete enter"); + if (!data) { + ANS_LOGE("Invalid async callback data."); + return; + } + napi_value result = nullptr; + auto asynccallbackinfo = reinterpret_cast(data); + if (asynccallbackinfo == nullptr) { + return; + } + + if (asynccallbackinfo->info.errorCode != ERR_OK) { + result = Common::NapiGetNull(env); + } else { + if (asynccallbackinfo->data != nullptr) { + napi_create_object(env, &result); + if (!Common::SetDoNotDisturbProfile(env, *asynccallbackinfo->data, result)) { + asynccallbackinfo->info.errorCode = ERROR; + result = Common::NapiGetNull(env); + } + } + } + Common::CreateReturnValue(env, asynccallbackinfo->info, result); + if (asynccallbackinfo->info.callback != nullptr) { + ANS_LOGD("Delete getDoNotDisturbProfile callback reference."); + napi_delete_reference(env, asynccallbackinfo->info.callback); + } + napi_delete_async_work(env, asynccallbackinfo->asyncWork); + delete asynccallbackinfo; + asynccallbackinfo = nullptr; +} + +napi_value NapiGetDoNotDisturbProfile(napi_env env, napi_callback_info info) +{ + ANS_LOGD("NapiGetDoNotDisturbProfile enter"); + GetDoNotDisturbProfileParams params {}; + if (ParseParameters(env, info, params) == nullptr) { + Common::NapiThrow(env, ERROR_PARAM_INVALID); + return Common::NapiGetUndefined(env); + } + + AsyncCallbackInfoGetDoNotDisturbProfile *asynccallbackinfo = + new (std::nothrow) AsyncCallbackInfoGetDoNotDisturbProfile {.env = env, .asyncWork = nullptr, .params = params}; + if (!asynccallbackinfo) { + Common::NapiThrow(env, ERROR_INTERNAL_ERROR); + 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, "getDoNotDisturbProfile", NAPI_AUTO_LENGTH, &resourceName); + // Asynchronous function call + napi_create_async_work(env, + nullptr, + resourceName, + [](napi_env env, void *data) { + ANS_LOGD("NapiGetDoNotDisturbProfile work excute."); + auto asynccallbackinfo = reinterpret_cast(data); + if (asynccallbackinfo) { + asynccallbackinfo->info.errorCode = NotificationHelper::GetDoNotDisturbProfile( + asynccallbackinfo->params.profileId, asynccallbackinfo->data); + } + }, + AsyncCompleteCallbackNapiGetDoNotDisturbProfile, + (void *)asynccallbackinfo, + &asynccallbackinfo->asyncWork); + + bool isCallback = asynccallbackinfo->info.isCallback; + napi_queue_async_work_with_qos(env, asynccallbackinfo->asyncWork, napi_qos_user_initiated); + + if (isCallback) { + ANS_LOGD("NapiGetDoNotDisturbProfile callback is nullptr."); + return Common::NapiGetNull(env); + } else { + return promise; + } +} } // namespace NotificationNapi } // namespace OHOS diff --git a/interfaces/inner_api/notification_helper.h b/interfaces/inner_api/notification_helper.h index 5b35ec72b..0c28c7fd3 100644 --- a/interfaces/inner_api/notification_helper.h +++ b/interfaces/inner_api/notification_helper.h @@ -1003,6 +1003,15 @@ public: * @return Returns register swing callback result. */ static ErrCode RegisterSwingCallback(const std::function swingCbFunc); + + /** + * @brief Get do not disturb profile by id. + * + * @param id Profile id. + * @param status Indicates the NotificationDoNotDisturbProfile objects. + * @return Returns ERR_OK on success, others on failure. + */ + static ErrCode GetDoNotDisturbProfile(int32_t id, sptr &profile); }; } // namespace Notification } // namespace OHOS diff --git a/services/ans/include/advanced_notification_service.h b/services/ans/include/advanced_notification_service.h index fa554b4f5..ad9d519f8 100644 --- a/services/ans/include/advanced_notification_service.h +++ b/services/ans/include/advanced_notification_service.h @@ -364,7 +364,7 @@ public: ErrCode RemoveAllNotificationsForDisable(const sptr &bundleOption); ErrCode RemoveNotifications(const std::vector &keys, int32_t removeReason) override; - + ErrCode GetUnifiedGroupInfoFromDb(std::string &enable); /** @@ -923,7 +923,7 @@ public: ErrCode CancelPreparedNotification(int32_t notificationId, const std::string &label, const sptr &bundleOption, const int32_t reason); - + ErrCode PrepareNotificationInfo( const sptr &request, sptr &bundleOption); ErrCode PublishPreparedNotification(const sptr &request, @@ -1129,6 +1129,15 @@ public: */ bool AllowUseReminder(const std::string& bundleName); + /** + * @brief Get do not disturb profile by id. + * + * @param id Profile id. + * @param status Indicates the NotificationDoNotDisturbProfile object. + * @return Returns ERR_OK on success, others on failure. + */ + ErrCode GetDoNotDisturbProfile(int32_t id, sptr &profile) override; + protected: /** * @brief Query whether there is a agent relationship between the two apps. diff --git a/services/ans/src/advanced_notification_utils.cpp b/services/ans/src/advanced_notification_utils.cpp index c3f5f318e..7c9b843cd 100644 --- a/services/ans/src/advanced_notification_utils.cpp +++ b/services/ans/src/advanced_notification_utils.cpp @@ -858,6 +858,30 @@ ErrCode AdvancedNotificationService::RemoveDoNotDisturbProfiles( return ERR_OK; } +ErrCode AdvancedNotificationService::GetDoNotDisturbProfile(int32_t id, sptr &profile) +{ + ANS_LOGD("Called."); + bool isSubsystem = AccessTokenHelper::VerifyNativeToken(IPCSkeleton::GetCallingTokenID()); + if (!isSubsystem && !AccessTokenHelper::IsSystemApp()) { + return ERR_ANS_NON_SYSTEM_APP; + } + if (!AccessTokenHelper::CheckPermission(OHOS_PERMISSION_NOTIFICATION_CONTROLLER)) { + return ERR_ANS_PERMISSION_DENIED; + } + int32_t userId = SUBSCRIBE_USER_INIT; + if (!GetActiveUserId(userId)) { + ANS_LOGW("No active user found."); + return ERR_ANS_GET_ACTIVE_USER_FAILED; + } + + profile = new (std::nothrow) NotificationDoNotDisturbProfile(); + ErrCode result = NotificationPreferences::GetInstance()->GetDoNotDisturbProfile(id, userId, profile); + if (result != ERR_OK) { + ANS_LOGE("profile failed id: %{public}d, userid: %{public}d", id, userId); + } + return result; +} + ErrCode AdvancedNotificationService::DoesSupportDoNotDisturbMode(bool &doesSupport) { ANS_LOGD("%{public}s", __FUNCTION__); diff --git a/services/ans/src/notification_preferences.cpp b/services/ans/src/notification_preferences.cpp index a19e7451d..d46106984 100644 --- a/services/ans/src/notification_preferences.cpp +++ b/services/ans/src/notification_preferences.cpp @@ -619,7 +619,7 @@ ErrCode NotificationPreferences::GetDoNotDisturbProfile( std::lock_guard lock(preferenceMutex_); NotificationPreferencesInfo preferencesInfo = preferencesInfo_; if (!preferencesInfo.GetDoNotDisturbProfiles(profileId, userId, profile)) { - return ERR_ANS_INVALID_PARAM; + return ERR_ANS_NO_PROFILE_TEMPLATE; } return ERR_OK; } -- Gitee From 1cd8583ab5d5a7a8ae5c37614bc824bb8a4a7b08 Mon Sep 17 00:00:00 2001 From: xdongs Date: Mon, 14 Oct 2024 19:13:44 +0800 Subject: [PATCH 080/167] =?UTF-8?q?=E8=8B=B1=E6=96=87=E7=BF=BB=E8=AF=91?= =?UTF-8?q?=E5=8F=98=E6=9B=B4=20=EF=BC=88cherry=20picked=20commit=20from?= =?UTF-8?q?=20?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: xdongs --- .../entry/src/main/resources/base/element/string.json | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/services/dialog_ui/enable_notification_dialog/entry/src/main/resources/base/element/string.json b/services/dialog_ui/enable_notification_dialog/entry/src/main/resources/base/element/string.json index 6057c4b7d..da8c2f069 100644 --- a/services/dialog_ui/enable_notification_dialog/entry/src/main/resources/base/element/string.json +++ b/services/dialog_ui/enable_notification_dialog/entry/src/main/resources/base/element/string.json @@ -14,7 +14,7 @@ }, { "name": "reason", - "value": "May include lock screen notifications, banners, sounds, vibrations, and more. You can change this in Settings." + "value": "These may include lock screen notifications, banners, sounds, vibrations, and more. You can change this in Settings." }, { "name": "ALLOW", -- Gitee From d962bc7a100b708e4e2db14d12bf4627494e2ad0 Mon Sep 17 00:00:00 2001 From: xdongs Date: Thu, 17 Oct 2024 14:43:48 +0800 Subject: [PATCH 081/167] =?UTF-8?q?=E5=88=A0=E9=99=A4=E9=80=9A=E7=9F=A5?= =?UTF-8?q?=E6=97=B6=E5=88=A0=E9=99=A4autoDeletedTimer=E5=AE=9A=E6=97=B6?= =?UTF-8?q?=E4=BB=BB=E5=8A=A1=20=EF=BC=88cherry=20picked=20commit=20from?= =?UTF-8?q?=20=20Signed-off-by:=20xdongs=20?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- frameworks/ans/src/notification.cpp | 10 +++++++ interfaces/inner_api/notification.h | 15 ++++++++++ .../include/advanced_notification_service.h | 2 ++ ...dvanced_notification_live_view_service.cpp | 3 +- .../advanced_notification_publish_service.cpp | 30 +++++++++++++++++-- .../ans/src/advanced_notification_service.cpp | 18 +++++++++-- .../ans/src/advanced_notification_utils.cpp | 19 +++++++++++- 7 files changed, 89 insertions(+), 8 deletions(-) diff --git a/frameworks/ans/src/notification.cpp b/frameworks/ans/src/notification.cpp index ca7903ae7..669fe67a8 100644 --- a/frameworks/ans/src/notification.cpp +++ b/frameworks/ans/src/notification.cpp @@ -592,5 +592,15 @@ uint64_t Notification::GetArchiveTimer() const { return archiveTimerId_; } + +void Notification::SetAutoDeletedTimer(uint64_t autoDeletedTimerId) +{ + autoDeletedTimerId_ = autoDeletedTimerId; +} + +uint64_t Notification::GetAutoDeletedTimer() const +{ + return autoDeletedTimerId_; +} } // namespace Notification } // namespace OHOS diff --git a/interfaces/inner_api/notification.h b/interfaces/inner_api/notification.h index d96dbd523..2baa81163 100644 --- a/interfaces/inner_api/notification.h +++ b/interfaces/inner_api/notification.h @@ -307,6 +307,20 @@ public: */ void SetArchiveTimer(uint64_t archiveTimerId); + /** + * @brief Obtains the autoDeleted timer id of notification. + * + * @return Returns the id of the notification autoDeleted timer. + */ + uint64_t GetAutoDeletedTimer() const; + + /** + * @brief Obtains the autoDeleted timer id. + * + * @param autoDeletedTimerId the id of the notification archive autoDeleted. + */ + void SetAutoDeletedTimer(uint64_t autoDeletedTimerId); + private: Notification(); void SetEnableSound(const bool &enable); @@ -352,6 +366,7 @@ private: uint64_t archiveTimerId_ {0}; std::shared_ptr sound_ {nullptr}; std::vector vibrationStyle_ {}; + uint64_t autoDeletedTimerId_ {0}; friend class AdvancedNotificationService; friend class NotificationSlotFilter; diff --git a/services/ans/include/advanced_notification_service.h b/services/ans/include/advanced_notification_service.h index ad9d519f8..5ac0d7f1a 100644 --- a/services/ans/include/advanced_notification_service.h +++ b/services/ans/include/advanced_notification_service.h @@ -1324,6 +1324,7 @@ private: const std::string &secureKey, const int32_t userId); static int32_t DeleteNotificationRequestFromDb(const std::string &key, const int32_t userId); void CancelTimer(uint64_t timerId); + void BatchCancelTimer(std::vector timerIds); ErrCode UpdateNotificationTimerInfo(const std::shared_ptr &record); ErrCode SetFinishTimer(const std::shared_ptr &record); ErrCode StartFinishTimer(const std::shared_ptr &record, @@ -1335,6 +1336,7 @@ private: void CancelUpdateTimer(const std::shared_ptr &record); void StartArchiveTimer(const std::shared_ptr &record); void CancelArchiveTimer(const std::shared_ptr &record); + ErrCode StartAutoDeletedTimer(const std::shared_ptr &record); void ProcForDeleteLiveView(const std::shared_ptr &record); ErrCode IsAllowedGetNotificationByFilter(const std::shared_ptr &record); void QueryDoNotDisturbProfile(const int32_t &userId, std::string &enable, std::string &profileId); diff --git a/services/ans/src/advanced_notification_live_view_service.cpp b/services/ans/src/advanced_notification_live_view_service.cpp index 67ab5646b..a713483f4 100644 --- a/services/ans/src/advanced_notification_live_view_service.cpp +++ b/services/ans/src/advanced_notification_live_view_service.cpp @@ -607,8 +607,7 @@ ErrCode AdvancedNotificationService::StartPublishDelayedNotification(const std:: UpdateRecentNotification(record->notification, false, 0); NotificationSubscriberManager::GetInstance()->NotifyConsumed(record->notification, GenerateSortingMap()); if ((record->request->GetAutoDeletedTime() > GetCurrentTime())) { - StartAutoDelete(record, - record->request->GetAutoDeletedTime(), NotificationConstant::TRIGGER_AUTO_DELETE_REASON_DELETE); + StartAutoDeletedTimer(record); } record->finish_status = UploadStatus::FIRST_UPDATE_TIME_OUT; diff --git a/services/ans/src/advanced_notification_publish_service.cpp b/services/ans/src/advanced_notification_publish_service.cpp index 44966fb1f..09062bc80 100644 --- a/services/ans/src/advanced_notification_publish_service.cpp +++ b/services/ans/src/advanced_notification_publish_service.cpp @@ -252,6 +252,7 @@ ErrCode AdvancedNotificationService::ExcuteCancelAll( std::vector keys = GetNotificationKeys(bundleOption); std::vector> notifications; + std::vector timerIds; for (auto key : keys) { #ifdef DISTRIBUTED_NOTIFICATION_SUPPORTED std::string deviceId; @@ -266,6 +267,7 @@ ErrCode AdvancedNotificationService::ExcuteCancelAll( if (notification != nullptr) { UpdateRecentNotification(notification, true, reason); notifications.emplace_back(notification); + timerIds.emplace_back(notification->GetAutoDeletedTimer()); #ifdef DISTRIBUTED_NOTIFICATION_SUPPORTED DoDistributedDelete(deviceId, bundleName, notification); #endif @@ -282,6 +284,7 @@ ErrCode AdvancedNotificationService::ExcuteCancelAll( NotificationSubscriberManager::GetInstance()->BatchNotifyCanceled( notifications, nullptr, reason); } + BatchCancelTimer(timerIds); result = ERR_OK; })); notificationSvrQueue_->wait(handler); @@ -496,6 +499,7 @@ ErrCode AdvancedNotificationService::ExcuteDelete(const std::string &key, const if (notification != nullptr) { UpdateRecentNotification(notification, true, removeReason); + CancelTimer(notification->GetAutoDeletedTimer()); NotificationSubscriberManager::GetInstance()->NotifyCanceled(notification, nullptr, removeReason); #ifdef DISTRIBUTED_NOTIFICATION_SUPPORTED DoDistributedDelete(deviceId, bundleName, notification); @@ -551,6 +555,7 @@ ErrCode AdvancedNotificationService::DeleteByBundle(const sptrGetAutoDeletedTimer()); NotificationSubscriberManager::GetInstance()->NotifyCanceled(notification, nullptr, reason); #ifdef DISTRIBUTED_NOTIFICATION_SUPPORTED DoDistributedDelete(deviceId, bundleName, notification); @@ -606,6 +611,7 @@ ErrCode AdvancedNotificationService::DeleteAll() } std::vector keys = GetNotificationKeys(nullptr); std::vector> notifications; + std::vector timerIds; for (auto key : keys) { #ifdef DISTRIBUTED_NOTIFICATION_SUPPORTED std::string deviceId; @@ -622,6 +628,7 @@ ErrCode AdvancedNotificationService::DeleteAll() if (notification->GetUserId() == activeUserId) { UpdateRecentNotification(notification, true, reason); notifications.emplace_back(notification); + timerIds.emplace_back(notification->GetAutoDeletedTimer()); #ifdef DISTRIBUTED_NOTIFICATION_SUPPORTED DoDistributedDelete(deviceId, bundleName, notification); #endif @@ -635,7 +642,7 @@ ErrCode AdvancedNotificationService::DeleteAll() NotificationSubscriberManager::GetInstance()->BatchNotifyCanceled( notifications, nullptr, reason); } - + BatchCancelTimer(timerIds); result = ERR_OK; })); notificationSvrQueue_->wait(handler); @@ -1211,6 +1218,7 @@ ErrCode AdvancedNotificationService::CancelContinuousTaskNotification(const std: if (notification != nullptr) { int32_t reason = NotificationConstant::APP_CANCEL_REASON_DELETE; UpdateRecentNotification(notification, true, reason); + CancelTimer(notification->GetAutoDeletedTimer()); NotificationSubscriberManager::GetInstance()->NotifyCanceled(notification, nullptr, reason); } })); @@ -1411,6 +1419,7 @@ ErrCode AdvancedNotificationService::RemoveNotification(const sptrGetAutoDeletedTimer()); NotificationSubscriberManager::GetInstance()->NotifyCanceled(notification, nullptr, removeReason); #ifdef DISTRIBUTED_NOTIFICATION_SUPPORTED DoDistributedDelete(deviceId, bundleName, notification); @@ -1526,12 +1535,14 @@ ErrCode AdvancedNotificationService::RemoveAllNotificationsInner(const sptr> notifications; + std::vector timerIds; for (auto record : removeList) { notificationList_.remove(record); if (record->notification != nullptr) { ANS_LOGD("record->notification is not nullptr."); UpdateRecentNotification(record->notification, true, reason); notifications.emplace_back(record->notification); + timerIds.emplace_back(record->notification->GetAutoDeletedTimer()); #ifdef DISTRIBUTED_NOTIFICATION_SUPPORTED DoDistributedDelete(record->deviceId, record->bundleName, record->notification); #endif @@ -1546,6 +1557,7 @@ ErrCode AdvancedNotificationService::RemoveAllNotificationsInner(const sptrBatchNotifyCanceled(notifications, nullptr, reason); } + BatchCancelTimer(timerIds); })); notificationSvrQueue_->wait(handler); @@ -1573,6 +1585,7 @@ ErrCode AdvancedNotificationService::RemoveNotifications( } ffrt::task_handle handler = notificationSvrQueue_->submit_h(std::bind([&]() { std::vector> notifications; + std::vector timerIds; for (auto key : keys) { sptr notification = nullptr; #ifdef DISTRIBUTED_NOTIFICATION_SUPPORTED @@ -1587,6 +1600,7 @@ ErrCode AdvancedNotificationService::RemoveNotifications( if (notification != nullptr) { UpdateRecentNotification(notification, true, removeReason); notifications.emplace_back(notification); + timerIds.emplace_back(notification->GetAutoDeletedTimer()); #ifdef DISTRIBUTED_NOTIFICATION_SUPPORTED DoDistributedDelete(deviceId, bundleName, notification); #endif @@ -1602,6 +1616,7 @@ ErrCode AdvancedNotificationService::RemoveNotifications( if (!notifications.empty()) { NotificationSubscriberManager::GetInstance()->BatchNotifyCanceled(notifications, nullptr, removeReason); } + BatchCancelTimer(timerIds); })); notificationSvrQueue_->wait(handler); @@ -1646,6 +1661,7 @@ ErrCode AdvancedNotificationService::RemoveNotificationBySlot(const sptrGetAutoDeletedTimer()); NotificationSubscriberManager::GetInstance()->NotifyCanceled(notification, nullptr, NotificationConstant::DISABLE_SLOT_REASON_DELETE); } @@ -1783,11 +1799,13 @@ void AdvancedNotificationService::ExcuteCancelGroupCancel( } std::vector> notifications; + std::vector timerIds; for (auto record : removeList) { notificationList_.remove(record); if (record->notification != nullptr) { UpdateRecentNotification(record->notification, true, reason); notifications.emplace_back(record->notification); + timerIds.emplace_back(record->notification->GetAutoDeletedTimer()); #ifdef DISTRIBUTED_NOTIFICATION_SUPPORTED DoDistributedDelete(record->deviceId, record->bundleName, record->notification); #endif @@ -1804,6 +1822,7 @@ void AdvancedNotificationService::ExcuteCancelGroupCancel( NotificationSubscriberManager::GetInstance()->BatchNotifyCanceled( notifications, nullptr, reason); } + BatchCancelTimer(timerIds); })); notificationSvrQueue_->wait(handler); } @@ -1879,6 +1898,7 @@ ErrCode AdvancedNotificationService::RemoveGroupByBundle( } std::vector> notifications; + std::vector timerIds; for (auto record : removeList) { notificationList_.remove(record); ProcForDeleteLiveView(record); @@ -1886,6 +1906,7 @@ ErrCode AdvancedNotificationService::RemoveGroupByBundle( if (record->notification != nullptr) { UpdateRecentNotification(record->notification, true, reason); notifications.emplace_back(record->notification); + timerIds.emplace_back(record->notification->GetAutoDeletedTimer()); #ifdef DISTRIBUTED_NOTIFICATION_SUPPORTED DoDistributedDelete(record->deviceId, record->bundleName, record->notification); #endif @@ -1898,6 +1919,7 @@ ErrCode AdvancedNotificationService::RemoveGroupByBundle( if (!notifications.empty()) { NotificationSubscriberManager::GetInstance()->BatchNotifyCanceled(notifications, nullptr, reason); } + BatchCancelTimer(timerIds); })); notificationSvrQueue_->wait(handler); @@ -1909,6 +1931,7 @@ ErrCode AdvancedNotificationService::RemoveNotificationFromRecordList( { ErrCode result = ERR_OK; std::vector> notifications; + std::vector timerIds; for (auto& record : recordList) { std::string key = record->notification->GetKey(); sptr notification = nullptr; @@ -1926,6 +1949,7 @@ ErrCode AdvancedNotificationService::RemoveNotificationFromRecordList( int32_t reason = NotificationConstant::USER_STOPPED_REASON_DELETE; UpdateRecentNotification(notification, true, reason); notifications.emplace_back(notification); + timerIds.emplace_back(notification->GetAutoDeletedTimer()); #ifdef DISTRIBUTED_NOTIFICATION_SUPPORTED DoDistributedDelete(deviceId, bundleName, notification); #endif @@ -1941,6 +1965,7 @@ ErrCode AdvancedNotificationService::RemoveNotificationFromRecordList( NotificationSubscriberManager::GetInstance()->BatchNotifyCanceled( notifications, nullptr, NotificationConstant::USER_STOPPED_REASON_DELETE); } + BatchCancelTimer(timerIds); return result; } @@ -2256,8 +2281,7 @@ ErrCode AdvancedNotificationService::PublishNotificationBySa(const sptrrequest->GetAutoDeletedTime() > GetCurrentTime()) && !record->request->IsCommonLiveView()) { - StartAutoDelete(record, - record->request->GetAutoDeletedTime(), NotificationConstant::TRIGGER_AUTO_DELETE_REASON_DELETE); + StartAutoDeletedTimer(record); } return ERR_OK; } diff --git a/services/ans/src/advanced_notification_service.cpp b/services/ans/src/advanced_notification_service.cpp index d43bf7567..6c02abcee 100644 --- a/services/ans/src/advanced_notification_service.cpp +++ b/services/ans/src/advanced_notification_service.cpp @@ -393,6 +393,7 @@ ErrCode AdvancedNotificationService::CancelPreparedNotification(int32_t notifica if (notification != nullptr) { UpdateRecentNotification(notification, true, reason); + CancelTimer(notification->GetAutoDeletedTimer()); NotificationSubscriberManager::GetInstance()->NotifyCanceled(notification, nullptr, reason); #ifdef DISTRIBUTED_NOTIFICATION_SUPPORTED DoDistributedDelete("", "", notification); @@ -557,6 +558,19 @@ void AdvancedNotificationService::CancelArchiveTimer(const std::shared_ptrnotification->SetArchiveTimer(NotificationConstant::INVALID_TIMER_ID); } +ErrCode AdvancedNotificationService::StartAutoDeletedTimer(const std::shared_ptr &record) +{ + uint64_t timerId = StartAutoDelete(record, + record->request->GetAutoDeletedTime(), NotificationConstant::TRIGGER_AUTO_DELETE_REASON_DELETE); + if (timerId == NotificationConstant::INVALID_TIMER_ID) { + std::string message = "Start autoDeleted auto delete timer failed."; + ANS_LOGE("%{public}s", message.c_str()); + return ERR_ANS_TASK_ERR; + } + record->notification->SetAutoDeletedTimer(timerId); + return ERR_OK; +} + ErrCode AdvancedNotificationService::FillNotificationRecord( const NotificationRequestDb &requestdbObj, std::shared_ptr record) { @@ -674,8 +688,7 @@ ErrCode AdvancedNotificationService::PublishPreparedNotification(const sptrwait(handler); // live view handled in UpdateNotificationTimerInfo, ignore here. if ((record->request->GetAutoDeletedTime() > GetCurrentTime()) && !record->request->IsCommonLiveView()) { - StartAutoDelete(record, - record->request->GetAutoDeletedTime(), NotificationConstant::TRIGGER_AUTO_DELETE_REASON_DELETE); + StartAutoDeletedTimer(record); } return result; } @@ -2030,6 +2043,7 @@ void AdvancedNotificationService::TriggerAutoDelete(const std::string &hashCode, if (record->notification->GetKey() == hashCode) { UpdateRecentNotification(record->notification, true, reason); + CancelTimer(record->notification->GetAutoDeletedTimer()); NotificationSubscriberManager::GetInstance()->NotifyCanceled(record->notification, nullptr, reason); ProcForDeleteLiveView(record); notificationList_.remove(record); diff --git a/services/ans/src/advanced_notification_utils.cpp b/services/ans/src/advanced_notification_utils.cpp index 7c9b843cd..14f620a28 100644 --- a/services/ans/src/advanced_notification_utils.cpp +++ b/services/ans/src/advanced_notification_utils.cpp @@ -511,6 +511,7 @@ void AdvancedNotificationService::OnBundleRemoved(const sptr keys = GetNotificationKeys(bundleOption); #endif std::vector> notifications; + std::vector timerIds; for (auto key : keys) { sptr notification = nullptr; result = RemoveFromNotificationList(key, notification, true, @@ -523,6 +524,7 @@ void AdvancedNotificationService::OnBundleRemoved(const sptrGetAutoDeletedTimer()); ExecBatchCancel(notifications, reason); #ifdef DISTRIBUTED_NOTIFICATION_SUPPORTED DoDistributedDelete("", "", notification); @@ -533,6 +535,7 @@ void AdvancedNotificationService::OnBundleRemoved(const sptrBatchNotifyCanceled( notifications, nullptr, NotificationConstant::PACKAGE_REMOVE_REASON_DELETE); } + BatchCancelTimer(timerIds); NotificationPreferences::GetInstance()->RemoveAnsBundleDbInfo(bundleOption); RemoveDoNotDisturbProfileTrustList(bundleOption); DeleteDuplicateMsgs(bundleOption); @@ -1101,6 +1104,7 @@ void AdvancedNotificationService::OnDistributedDelete( if (notification != nullptr) { int32_t reason = NotificationConstant::APP_CANCEL_REASON_OTHER; UpdateRecentNotification(notification, true, reason); + CancelTimer(notification->GetAutoDeletedTimer()); NotificationSubscriberManager::GetInstance()->NotifyCanceled(notification, nullptr, reason); } })); @@ -1324,6 +1328,7 @@ void AdvancedNotificationService::OnBundleDataCleared(const sptr keys = GetNotificationKeys(bundleOption); std::vector> notifications; + std::vector timerIds; for (auto key : keys) { #ifdef DISTRIBUTED_NOTIFICATION_SUPPORTED std::string deviceId; @@ -1342,6 +1347,7 @@ void AdvancedNotificationService::OnBundleDataCleared(const sptrGetAutoDeletedTimer()); #ifdef DISTRIBUTED_NOTIFICATION_SUPPORTED DoDistributedDelete(deviceId, bundleName, notification); #endif @@ -1358,6 +1364,7 @@ void AdvancedNotificationService::OnBundleDataCleared(const sptrBatchNotifyCanceled( notifications, nullptr, NotificationConstant::PACKAGE_CHANGED_REASON_DELETE); } + BatchCancelTimer(timerIds); })); } @@ -1422,6 +1429,7 @@ ErrCode AdvancedNotificationService::DeleteAllByUserInner(const int32_t &userId, ANS_LOGD("ffrt enter!"); std::vector keys = GetNotificationKeys(nullptr); std::vector> notifications; + std::vector timerIds; for (auto key : keys) { #ifdef DISTRIBUTED_NOTIFICATION_SUPPORTED std::string deviceId; @@ -1438,6 +1446,7 @@ ErrCode AdvancedNotificationService::DeleteAllByUserInner(const int32_t &userId, if (notification->GetUserId() == userId) { UpdateRecentNotification(notification, true, deleteReason); notifications.emplace_back(notification); + timerIds.emplace_back(notification->GetAutoDeletedTimer()); #ifdef DISTRIBUTED_NOTIFICATION_SUPPORTED DoDistributedDelete(deviceId, bundleName, notification); #endif @@ -1451,7 +1460,7 @@ ErrCode AdvancedNotificationService::DeleteAllByUserInner(const int32_t &userId, NotificationSubscriberManager::GetInstance()->BatchNotifyCanceled( notifications, nullptr, deleteReason); } - + BatchCancelTimer(timerIds); *result = ERR_OK; })); @@ -1748,6 +1757,14 @@ void AdvancedNotificationService::CancelTimer(uint64_t timerId) MiscServices::TimeServiceClient::GetInstance()->DestroyTimer(timerId); } +void AdvancedNotificationService::BatchCancelTimer(std::vector timerIds) +{ + ANS_LOGD("Enter"); + for (uint64_t timerId : timerIds) { + CancelTimer(timerId); + } +} + void AdvancedNotificationService::SendNotificationsOnCanceled(std::vector> ¬ifications, const sptr ¬ificationMap, int32_t deleteReason) { -- Gitee From a95a8518b432ad717d1a98821b9ae84f08e8db5e Mon Sep 17 00:00:00 2001 From: xdongs Date: Fri, 18 Oct 2024 15:38:53 +0800 Subject: [PATCH 082/167] merge Signed-off-by: xdongs --- .../core/common/include/ans_convert_enum.h | 1 + .../core/common/src/ans_convert_enum.cpp | 3 ++ interfaces/inner_api/notification_constant.h | 5 ++ .../include/advanced_notification_service.h | 3 +- ...dvanced_notification_live_view_service.cpp | 5 ++ .../ans/src/advanced_notification_utils.cpp | 47 +++++++++++++++++++ 6 files changed, 63 insertions(+), 1 deletion(-) diff --git a/frameworks/core/common/include/ans_convert_enum.h b/frameworks/core/common/include/ans_convert_enum.h index 81c2cdd3f..10b906991 100644 --- a/frameworks/core/common/include/ans_convert_enum.h +++ b/frameworks/core/common/include/ans_convert_enum.h @@ -84,6 +84,7 @@ enum class RemoveReason { TRIGGER_AUTO_DELETE_REASON_DELETE = 27, PACKAGE_REMOVE_REASON_DELETE = 28, SLOT_ENABLED_REASON_DELETE = 29, + RECOVER_LIVE_VIEW_DELETE = 30, APP_CANCEL_REASON_OTHER = 100, }; diff --git a/frameworks/core/common/src/ans_convert_enum.cpp b/frameworks/core/common/src/ans_convert_enum.cpp index 39f7bae5d..a4dac3608 100644 --- a/frameworks/core/common/src/ans_convert_enum.cpp +++ b/frameworks/core/common/src/ans_convert_enum.cpp @@ -315,6 +315,9 @@ bool AnsEnumUtil::ReasonCToJS(const int &inType, int &outType) case NotificationConstant::APP_CANCEL_REASON_OTHER: outType = static_cast(RemoveReason::APP_CANCEL_REASON_OTHER); break; + case NotificationConstant::RECOVER_LIVE_VIEW_DELETE: + outType = static_cast(RemoveReason::RECOVER_LIVE_VIEW_DELETE); + break; default: outType = static_cast(RemoveReason::APP_CANCEL_REASON_OTHER); ANS_LOGW("Reason %{public}d is an invalid value", inType); diff --git a/interfaces/inner_api/notification_constant.h b/interfaces/inner_api/notification_constant.h index 507408478..6f4de3f91 100644 --- a/interfaces/inner_api/notification_constant.h +++ b/interfaces/inner_api/notification_constant.h @@ -292,6 +292,11 @@ public: */ static const int32_t SLOT_ENABLED_REASON_DELETE = 29; + /** + * Indicates that a notification is deleted because recover live live validated need delete. + */ + static const int32_t RECOVER_LIVE_VIEW_DELETE = 30; + /** * Indicates that a notification is deleted for other reasons. */ diff --git a/services/ans/include/advanced_notification_service.h b/services/ans/include/advanced_notification_service.h index 5ac0d7f1a..971860407 100644 --- a/services/ans/include/advanced_notification_service.h +++ b/services/ans/include/advanced_notification_service.h @@ -1399,7 +1399,8 @@ private: ErrCode ExcuteDelete(const std::string &key, const int32_t removeReason); ErrCode CheckNeedSilent(const std::string &phoneNumber, int32_t callerType, int32_t userId); uint32_t GetDefaultSlotFlags(const sptr &request); - + ErrCode OnRecoverLiveView(const std::vector &keys); + private: static sptr instance_; static std::mutex instanceMutex_; diff --git a/services/ans/src/advanced_notification_live_view_service.cpp b/services/ans/src/advanced_notification_live_view_service.cpp index a713483f4..60f1b8ecc 100644 --- a/services/ans/src/advanced_notification_live_view_service.cpp +++ b/services/ans/src/advanced_notification_live_view_service.cpp @@ -53,10 +53,12 @@ void AdvancedNotificationService::RecoverLiveViewFromDb(int32_t userId) return; } ANS_LOGI("The number of live views to recover: %{public}zu.", requestsdb.size()); + std::vector keys; for (const auto &requestObj : requestsdb) { ANS_LOGD("Recover request: %{public}s.", requestObj.request->Dump().c_str()); if (!IsLiveViewCanRecover(requestObj.request)) { int32_t userId = requestObj.request->GetReceiverUserId(); + keys.emplace_back(requestObj.request->GetBaseKey("")); if (DoubleDeleteNotificationFromDb(requestObj.request->GetKey(), requestObj.request->GetSecureKey(), userId) != ERR_OK) { ANS_LOGE("Delete notification failed."); @@ -99,6 +101,9 @@ void AdvancedNotificationService::RecoverLiveViewFromDb(int32_t userId) NotificationConstant::TRIGGER_FOUR_HOUR_REASON_DELETE); } + if (!keys.empty()) { + OnRecoverLiveView(keys); + } // publish notifications for (const auto &subscriber : NotificationSubscriberManager::GetInstance()->GetSubscriberRecords()) { OnSubscriberAdd(subscriber); diff --git a/services/ans/src/advanced_notification_utils.cpp b/services/ans/src/advanced_notification_utils.cpp index 14f620a28..f97bc78f4 100644 --- a/services/ans/src/advanced_notification_utils.cpp +++ b/services/ans/src/advanced_notification_utils.cpp @@ -1942,5 +1942,52 @@ bool AdvancedNotificationService::AllowUseReminder(const std::string& bundleName return true; #endif } + +ErrCode AdvancedNotificationService::OnRecoverLiveView( + const std::vector &keys) +{ + ANS_LOGD("enter"); + + if (notificationSvrQueue_ == nullptr) { + ANS_LOGE("NotificationSvrQueue is nullptr."); + return ERR_ANS_INVALID_PARAM; + } + + std::vector> notifications; + int32_t removeReason = NotificationConstant::RECOVER_LIVE_VIEW_DELETE; + std::vector timerIds; + for (auto key : keys) { + ANS_LOGI("BatchRemoveByKeys key = %{public}s", key.c_str()); + sptr notification = nullptr; +#ifdef DISTRIBUTED_NOTIFICATION_SUPPORTED + std::string deviceId; + std::string bundleName; + GetDistributedInfo(key, deviceId, bundleName); +#endif + ErrCode result = RemoveFromNotificationList(key, notification, true, removeReason); + if (result != ERR_OK) { + continue; + } + if (notification != nullptr) { + notifications.emplace_back(notification); + timerIds.emplace_back(notification->GetAutoDeletedTimer()); +#ifdef DISTRIBUTED_NOTIFICATION_SUPPORTED + DoDistributedDelete(deviceId, bundleName, notification); +#endif + } + if (notifications.size() >= MAX_CANCELED_PARCELABLE_VECTOR_NUM) { + std::vector> currNotificationList = notifications; + NotificationSubscriberManager::GetInstance()->BatchNotifyCanceled( + currNotificationList, nullptr, removeReason); + notifications.clear(); + } + } + + if (!notifications.empty()) { + NotificationSubscriberManager::GetInstance()->BatchNotifyCanceled(notifications, nullptr, removeReason); + } + BatchCancelTimer(timerIds); + return ERR_OK; +} } // namespace Notification } // namespace OHOS -- Gitee From 0a9667a381563812e6b9eff8f6df499dc1613f95 Mon Sep 17 00:00:00 2001 From: wangsen1994 Date: Wed, 11 Sep 2024 11:53:21 +0800 Subject: [PATCH 083/167] =?UTF-8?q?ans=E6=94=AF=E6=8C=81=E5=85=8B=E9=9A=86?= =?UTF-8?q?=E7=99=BD=E5=90=8D=E5=8D=95?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: wangsen1994 --- .../ans/src/notification_bundle_option.cpp | 15 ++ .../notification_do_not_disturb_profile.cpp | 19 +- .../inner_api/notification_bundle_option.h | 15 ++ .../notification_do_not_disturb_profile.h | 3 +- sa_profile/3203.json | 1 + services/ans/BUILD.gn | 3 + .../include/advanced_notification_service.h | 3 + .../advanced_notification_service_ability.h | 1 + services/ans/include/bundle_manager_helper.h | 12 +- .../notification_clone_disturb_service.h | 52 ++++ .../ans/include/notification_clone_manager.h | 45 ++++ .../ans/include/notification_clone_template.h | 34 +++ .../ans/include/notification_preferences.h | 10 +- .../advanced_notification_clone_service.cpp | 37 +++ .../advanced_notification_service_ability.cpp | 20 ++ .../ans/src/advanced_notification_utils.cpp | 3 + services/ans/src/bundle_manager_helper.cpp | 19 +- .../notification_clone_disturb_service.cpp | 239 ++++++++++++++++++ .../src/clone/notification_clone_manager.cpp | 179 +++++++++++++ services/ans/src/notification_preferences.cpp | 74 +++++- services/ans/src/system_event_observer.cpp | 4 + 21 files changed, 775 insertions(+), 13 deletions(-) create mode 100644 services/ans/include/notification_clone_disturb_service.h create mode 100644 services/ans/include/notification_clone_manager.h create mode 100644 services/ans/include/notification_clone_template.h create mode 100644 services/ans/src/advanced_notification_clone_service.cpp create mode 100644 services/ans/src/clone/notification_clone_disturb_service.cpp create mode 100644 services/ans/src/clone/notification_clone_manager.cpp diff --git a/frameworks/ans/src/notification_bundle_option.cpp b/frameworks/ans/src/notification_bundle_option.cpp index bead64f85..fee77488d 100644 --- a/frameworks/ans/src/notification_bundle_option.cpp +++ b/frameworks/ans/src/notification_bundle_option.cpp @@ -59,12 +59,23 @@ int32_t NotificationBundleOption::GetInstanceKey() const return instanceKey_; } +void NotificationBundleOption::SetAppIndex(const int32_t appIndex) +{ + appIndex_ = appIndex; +} + +int32_t NotificationBundleOption::GetAppIndex() const +{ + return appIndex_; +} + std::string NotificationBundleOption::Dump() { return "NotificationBundleOption{ " "bundleName = " + bundleName_ + ", uid = " + std::to_string(uid_) + ", instanceKey = " + std::to_string(instanceKey_) + + ", appIndex = " + std::to_string(appIndex_) + " }"; } @@ -118,6 +129,7 @@ bool NotificationBundleOption::ToJson(nlohmann::json &jsonObject) const jsonObject["uid"] = uid_; jsonObject["bundleName"] = bundleName_; jsonObject["instanceKey"] = instanceKey_; + jsonObject["appIndex"] = appIndex_; return true; } @@ -148,6 +160,9 @@ NotificationBundleOption *NotificationBundleOption::FromJson(const nlohmann::jso pBundle->instanceKey_ = jsonObject.at("instanceKey").get(); } + if (jsonObject.find("appIndex") != jsonEnd && jsonObject.at("appIndex").is_number_integer()) { + pBundle->appIndex_ = jsonObject.at("appIndex").get(); + } return pBundle; } diff --git a/frameworks/ans/src/notification_do_not_disturb_profile.cpp b/frameworks/ans/src/notification_do_not_disturb_profile.cpp index 0a4be2f85..0c16d61ef 100644 --- a/frameworks/ans/src/notification_do_not_disturb_profile.cpp +++ b/frameworks/ans/src/notification_do_not_disturb_profile.cpp @@ -119,6 +119,13 @@ bool NotificationDoNotDisturbProfile::ReadFromParcel(Parcel &parcel) } std::string NotificationDoNotDisturbProfile::ToJson() +{ + nlohmann::json jsonObject; + GetProfileJson(jsonObject); + return jsonObject.dump(); +} + +void NotificationDoNotDisturbProfile::GetProfileJson(nlohmann::json &jsonObject) const { nlohmann::json jsonNodes = nlohmann::json::array(); for (size_t index = 0; index < trustList_.size(); index++) { @@ -127,12 +134,10 @@ std::string NotificationDoNotDisturbProfile::ToJson() jsonNodes.emplace_back(jsonNode); } } - nlohmann::json jsonObject { - {DO_NOT_DISTURB_PROFILE_ID, id_}, - {DO_NOT_DISTURB_PROFILE_NAME, name_}, - {DO_NOT_DISTURB_PROFILE_TRUSTLIST, jsonNodes} - }; - return jsonObject.dump(); + + jsonObject[DO_NOT_DISTURB_PROFILE_ID] = id_; + jsonObject[DO_NOT_DISTURB_PROFILE_NAME] = name_; + jsonObject[DO_NOT_DISTURB_PROFILE_TRUSTLIST] = jsonNodes; } void NotificationDoNotDisturbProfile::FromJson(const std::string &jsonObj) @@ -164,4 +169,4 @@ void NotificationDoNotDisturbProfile::FromJson(const std::string &jsonObj) } } } // namespace Notification -} // namespace OHOS \ No newline at end of file +} // namespace OHOS diff --git a/interfaces/inner_api/notification_bundle_option.h b/interfaces/inner_api/notification_bundle_option.h index 56fd66a32..cf31b0489 100644 --- a/interfaces/inner_api/notification_bundle_option.h +++ b/interfaces/inner_api/notification_bundle_option.h @@ -77,6 +77,20 @@ public: */ int32_t GetInstanceKey() const; + /** + * @brief Sets the application index. + * + * @param uid Indicates the application index. + */ + void SetAppIndex(const int32_t appIndex); + + /** + * @brief Obtains the application index. + * + * @return Returns the application index. + */ + int32_t GetAppIndex() const; + /** * @brief Returns a string representation of the object. * @@ -129,6 +143,7 @@ private: std::string bundleName_ {}; int32_t uid_ {}; int32_t instanceKey_ {}; + int32_t appIndex_ = -1; }; } // namespace Notification } // namespace OHOS diff --git a/interfaces/inner_api/notification_do_not_disturb_profile.h b/interfaces/inner_api/notification_do_not_disturb_profile.h index fbfc7144d..477cb63f3 100644 --- a/interfaces/inner_api/notification_do_not_disturb_profile.h +++ b/interfaces/inner_api/notification_do_not_disturb_profile.h @@ -104,6 +104,7 @@ public: static NotificationDoNotDisturbProfile *Unmarshalling(Parcel &parcel); std::string ToJson(); void FromJson(const std::string &value); + void GetProfileJson(nlohmann::json &jsonObject) const; private: int32_t id_; @@ -112,4 +113,4 @@ private: }; } // namespace Notification } // namespace OHOS -#endif // BASE_NOTIFICATION_DISTRIBUTED_NOTIFICATION_SERVICE_INTERFACES_INNER_API_DO_NOT_DISTURB_PROFILE_H \ No newline at end of file +#endif // BASE_NOTIFICATION_DISTRIBUTED_NOTIFICATION_SERVICE_INTERFACES_INNER_API_DO_NOT_DISTURB_PROFILE_H diff --git a/sa_profile/3203.json b/sa_profile/3203.json index 08a6f695d..0f52289d7 100644 --- a/sa_profile/3203.json +++ b/sa_profile/3203.json @@ -8,6 +8,7 @@ "depend": [ 3299 ], + "extension": ["backup", "restore"], "depend_time_out": 60000, "distributed": false, "dump_level": 1 diff --git a/services/ans/BUILD.gn b/services/ans/BUILD.gn index 8dd1be0b8..178cbaf13 100644 --- a/services/ans/BUILD.gn +++ b/services/ans/BUILD.gn @@ -49,6 +49,7 @@ ohos_shared_library("libans") { "src/advanced_datashare_helper.cpp", "src/advanced_datashare_helper_ext.cpp", "src/advanced_datashare_observer.cpp", + "src/advanced_notification_clone_service.cpp", "src/advanced_notification_event_service.cpp", "src/advanced_notification_inline.cpp", "src/advanced_notification_live_view_service.cpp", @@ -63,6 +64,8 @@ ohos_shared_library("libans") { "src/advanced_notification_subscriber_service.cpp", "src/advanced_notification_utils.cpp", "src/bundle_manager_helper.cpp", + "src/clone/notification_clone_disturb_service.cpp", + "src/clone/notification_clone_manager.cpp", "src/common/aes_gcm_helper.cpp", "src/common/file_utils.cpp", "src/common/notification_analytics_util.cpp", diff --git a/services/ans/include/advanced_notification_service.h b/services/ans/include/advanced_notification_service.h index 971860407..0e8b4fcab 100644 --- a/services/ans/include/advanced_notification_service.h +++ b/services/ans/include/advanced_notification_service.h @@ -1138,6 +1138,9 @@ public: */ ErrCode GetDoNotDisturbProfile(int32_t id, sptr &profile) override; + int32_t OnBackup(MessageParcel& data, MessageParcel& reply); + + int32_t OnRestore(MessageParcel& data, MessageParcel& reply); protected: /** * @brief Query whether there is a agent relationship between the two apps. diff --git a/services/ans/include/advanced_notification_service_ability.h b/services/ans/include/advanced_notification_service_ability.h index 7ee5d2fd7..229e57197 100644 --- a/services/ans/include/advanced_notification_service_ability.h +++ b/services/ans/include/advanced_notification_service_ability.h @@ -50,6 +50,7 @@ private: void OnAddSystemAbility(int32_t systemAbilityId, const std::string& deviceId) override; void OnRemoveSystemAbility(int32_t systemAbilityId, const std::string& deviceId) override; void OnReceiveEvent(const EventFwk::CommonEventData &data); + int32_t OnExtension(const std::string& extension, MessageParcel& data, MessageParcel& reply) override; private: std::atomic isDatashaReready_ {false}; diff --git a/services/ans/include/bundle_manager_helper.h b/services/ans/include/bundle_manager_helper.h index 24471b3d1..911e3b773 100644 --- a/services/ans/include/bundle_manager_helper.h +++ b/services/ans/include/bundle_manager_helper.h @@ -65,6 +65,16 @@ public: */ int32_t GetDefaultUidByBundleName(const std::string &bundle, const int32_t userId); + /** + * @brief Obtains the default uid. + * + * @param bundle Indicates the bundle name. + * @param userId Indicates the user id. + * @param appIndex Indicates the app Index. + * @return Returns the uid. + */ + int32_t GetDefaultUidByBundleName(const std::string &bundle, const int32_t userId, const int32_t appIndex); + /** * @brief Obtains the bundle info. * @@ -97,7 +107,7 @@ public: */ bool GetBundleInfo(const std::string &bundleName, const AppExecFwk::BundleFlag flag, int32_t userId, AppExecFwk::BundleInfo &bundleInfo); - + /** * @brief Obtains BundleInfo of all bundles available in the system through the proxy object. * @param flag Indicates the flag used to specify information contained in the BundleInfo that will be returned. diff --git a/services/ans/include/notification_clone_disturb_service.h b/services/ans/include/notification_clone_disturb_service.h new file mode 100644 index 000000000..670ad8495 --- /dev/null +++ b/services/ans/include/notification_clone_disturb_service.h @@ -0,0 +1,52 @@ +/* + * Copyright (c) 2021-2024 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef BASE_NOTIFICATION_DISTRIBUTED_NOTIFICATION_SERVICE_SERVICES_ANS_INCLUDE_NOTIFICATION_CLONE_DISTURB_H +#define BASE_NOTIFICATION_DISTRIBUTED_NOTIFICATION_SERVICE_SERVICES_ANS_INCLUDE_NOTIFICATION_CLONE_DISTURB_H + +#include "notification_clone_template.h" + +#include "ffrt.h" +#include "notification_bundle_option.h" +#include "notification_do_not_disturb_profile.h" + +namespace OHOS { +namespace Notification { +class NotificationCloneDisturb final : public NotificationCloneTemplate { +public: + NotificationCloneDisturb(); + ~NotificationCloneDisturb() override; + static std::shared_ptr GetInstance(); + ErrCode OnBackup(nlohmann::json &jsonObject) override; + ErrCode OnRestore(const nlohmann::json &jsonObject) override; + void OnBundleDataAdd(const sptr &bundleOption); + void OnBundleDataUpdate(const sptr &bundleOption); + void HandlerBundleEvent(const std::string bundleName, int32_t appIndex, int32_t uid); + int32_t GetBundleUid(const std::string bundleName, int32_t userId, int32_t appIndex); + void GetProfileUid(int32_t userId, std::map& uidMap, + std::vector trustList, std::vector& exitBunldleList, + std::vector& notExitBunldleList); + void CheckBundleInfo(std::vector& trustList, + std::vector& bundleList, const NotificationBundleOption& bundle); + int32_t GetActiveUserId(); + void OnUserSwitch(int32_t userId); +private: + std::atomic userId_ = -1; + std::vector> profiles_; + std::shared_ptr cloneDisturbQueue_ = nullptr; +}; +} // namespace Notification +} // namespace OHOS +#endif // BASE_NOTIFICATION_DISTRIBUTED_NOTIFICATION_SERVICE_SERVICES_ANS_INCLUDE_NOTIFICATION_CLONE_DISTURB_H diff --git a/services/ans/include/notification_clone_manager.h b/services/ans/include/notification_clone_manager.h new file mode 100644 index 000000000..d3cc6f901 --- /dev/null +++ b/services/ans/include/notification_clone_manager.h @@ -0,0 +1,45 @@ +/* + * Copyright (c) 2021-2024 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef BASE_NOTIFICATION_DISTRIBUTED_NOTIFICATION_SERVICE_SERVICES_ANS_INCLUDE_NOTIFICATION_CLONE_MANAGER_H +#define BASE_NOTIFICATION_DISTRIBUTED_NOTIFICATION_SERVICE_SERVICES_ANS_INCLUDE_NOTIFICATION_CLONE_MANAGER_H + +#include +#include + +#include "unique_fd.h" +#include "iremote_proxy.h" +#include "notification_clone_template.h" +namespace OHOS { +namespace Notification { + +class NotificationCloneManager { +public: + static NotificationCloneManager& GetInstance(); + + int32_t OnBackup(MessageParcel& data, MessageParcel& reply); + int32_t OnRestore(MessageParcel& data, MessageParcel& reply); +private: + NotificationCloneManager(); + ~NotificationCloneManager(); + + void RemoveBackUpFile(); + ErrCode LoadConfig(UniqueFd &fd, std::string& config); + ErrCode SaveConfig(const std::string& config); + std::map> cloneTemplates; +}; +} // namespace Notification +} // namespace OHOS +#endif // BASE_NOTIFICATION_DISTRIBUTED_NOTIFICATION_SERVICE_SERVICES_ANS_INCLUDE_NOTIFICATION_CLONE_MANAGER_H diff --git a/services/ans/include/notification_clone_template.h b/services/ans/include/notification_clone_template.h new file mode 100644 index 000000000..0a6ce21aa --- /dev/null +++ b/services/ans/include/notification_clone_template.h @@ -0,0 +1,34 @@ +/* + * Copyright (c) 2021-2024 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef BASE_NOTIFICATION_DISTRIBUTED_NOTIFICATION_SERVICE_SERVICES_ANS_INCLUDE_NOTIFICATION_CLONE_TEMPLATE_H +#define BASE_NOTIFICATION_DISTRIBUTED_NOTIFICATION_SERVICE_SERVICES_ANS_INCLUDE_NOTIFICATION_CLONE_TEMPLATE_H + +#include "errors.h" +#include "nlohmann/json.hpp" + +namespace OHOS { +namespace Notification { + +class NotificationCloneTemplate { +public: + NotificationCloneTemplate() = default; + virtual ~NotificationCloneTemplate() = default; + virtual ErrCode OnBackup(nlohmann::json &jsonObject) = 0; + virtual ErrCode OnRestore(const nlohmann::json &jsonObject) = 0; +}; +} // namespace Notification +} // namespace OHOS +#endif // BASE_NOTIFICATION_DISTRIBUTED_NOTIFICATION_SERVICE_SERVICES_ANS_INCLUDE_NOTIFICATION_CLONE_TEMPLATE_H diff --git a/services/ans/include/notification_preferences.h b/services/ans/include/notification_preferences.h index 1ffce83c8..2d2fe17e6 100644 --- a/services/ans/include/notification_preferences.h +++ b/services/ans/include/notification_preferences.h @@ -313,7 +313,7 @@ public: */ ErrCode SetDistributedEnabledByBundle(const sptr &bundleOption, const std::string &deviceType, const bool enabled); - + /** * @brief Get Enable smartphone to collaborate with other devices for intelligent reminders * @@ -359,6 +359,12 @@ public: */ bool GetBundleSoundPermission(bool &allPackage, std::set &bundleNames); + ErrCode UpdateDoNotDisturbProfiles(int32_t userId, int32_t profileId, + const std::string& name, const std::vector& bundleList); + + void UpdateProfilesUtil(std::vector& trustList, + const std::vector bundleList); + void InitSettingFromDisturbDB(int32_t userId = -1); void RemoveSettings(int32_t userId); void RemoveAnsBundleDbInfo(const sptr &bundleOption); @@ -373,6 +379,8 @@ public: ErrCode GetDoNotDisturbProfile(int32_t profileId, int32_t userId, sptr &profile); bool CheckDoNotDisturbProfileID(int32_t profileId); void RemoveDoNotDisturbProfileTrustList(int32_t userId, const sptr &bundleOption); + void GetDoNotDisturbProfileListByUserId(int32_t userId, + std::vector> &profiles); private: ErrCode CheckSlotForCreateSlot(const sptr &bundleOption, diff --git a/services/ans/src/advanced_notification_clone_service.cpp b/services/ans/src/advanced_notification_clone_service.cpp new file mode 100644 index 000000000..e0d7a8f97 --- /dev/null +++ b/services/ans/src/advanced_notification_clone_service.cpp @@ -0,0 +1,37 @@ +/* + * Copyright (c) 2021-2024 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "advanced_notification_service.h" + +#include "notification_clone_manager.h" +namespace OHOS { +namespace Notification { + +constexpr int32_t INVALID_FD_NUM = -1; +constexpr int32_t PERMISSION_NUM = 0660; +constexpr const char *EXTENSION_SUCCESS = "notification extension success"; + +int32_t AdvancedNotificationService::OnBackup(MessageParcel& data, MessageParcel& reply) +{ + return NotificationCloneManager::GetInstance().OnBackup(data, reply); +} + +int32_t AdvancedNotificationService::OnRestore(MessageParcel& data, MessageParcel& reply) +{ +// todo double to single + return NotificationCloneManager::GetInstance().OnRestore(data, reply); +} +} // namespace Notification +} // namespace OHOS diff --git a/services/ans/src/advanced_notification_service_ability.cpp b/services/ans/src/advanced_notification_service_ability.cpp index 8c542f798..65fcec3d8 100644 --- a/services/ans/src/advanced_notification_service_ability.cpp +++ b/services/ans/src/advanced_notification_service_ability.cpp @@ -25,6 +25,9 @@ namespace { REGISTER_SYSTEM_ABILITY_BY_ID(AdvancedNotificationServiceAbility, ADVANCED_NOTIFICATION_SERVICE_ABILITY_ID, true); } +const std::string EXTENSION_BACKUP = "backup"; +const std::string EXTENSION_RESTORE = "restore"; + AdvancedNotificationServiceAbility::AdvancedNotificationServiceAbility(const int32_t systemAbilityId, bool runOnCreate) : SystemAbility(systemAbilityId, runOnCreate), service_(nullptr) {} @@ -114,5 +117,22 @@ void AdvancedNotificationServiceAbility::OnRemoveSystemAbility(int32_t systemAbi return; } } + +int32_t AdvancedNotificationServiceAbility::OnExtension(const std::string& extension, + MessageParcel& data, MessageParcel& reply) +{ + ANS_LOGI("extension is %{public}s.", extension.c_str()); + auto notificationService = AdvancedNotificationService::GetInstance(); + if (notificationService == nullptr) { + ANS_LOGW("notification service is not initial."); + return ERR_OK; + } + if (extension == EXTENSION_BACKUP) { + return notificationService->OnBackup(data, reply); + } else if (extension == EXTENSION_RESTORE) { + return notificationService->OnRestore(data, reply); + } + return ERR_OK; +} } // namespace Notification } // namespace OHOS diff --git a/services/ans/src/advanced_notification_utils.cpp b/services/ans/src/advanced_notification_utils.cpp index f97bc78f4..360fec2a1 100644 --- a/services/ans/src/advanced_notification_utils.cpp +++ b/services/ans/src/advanced_notification_utils.cpp @@ -47,6 +47,7 @@ #include "advanced_notification_inline.cpp" #include "notification_analytics_util.h" +#include "notification_clone_disturb_service.h" #define CHECK_BUNDLE_OPTION_IS_INVALID(option) \ if (option == nullptr || option->GetBundleName().empty()) { \ @@ -595,6 +596,7 @@ void AdvancedNotificationService::OnBundleDataAdd(const sptrOnBundleDataAdd(bundleOption); notificationSvrQueue_ != nullptr ? notificationSvrQueue_->submit(bundleInstall) : bundleInstall(); } @@ -622,6 +624,7 @@ void AdvancedNotificationService::OnBundleDataUpdate(const sptrOnBundleDataUpdate(bundleOption); notificationSvrQueue_ != nullptr ? notificationSvrQueue_->submit(bundleUpdate) : bundleUpdate(); } diff --git a/services/ans/src/bundle_manager_helper.cpp b/services/ans/src/bundle_manager_helper.cpp index 5b8ada05b..8c6932d1a 100644 --- a/services/ans/src/bundle_manager_helper.cpp +++ b/services/ans/src/bundle_manager_helper.cpp @@ -199,7 +199,7 @@ bool BundleManagerHelper::GetBundleInfo(const std::string &bundleName, const App std::lock_guard lock(connectionMutex_); Connect(); - + if (bundleMgr_ == nullptr) { return false; } @@ -241,5 +241,22 @@ int32_t BundleManagerHelper::GetAppIndexByUid(const int32_t uid) IPCSkeleton::SetCallingIdentity(identity); return appIndex; } + +int32_t BundleManagerHelper::GetDefaultUidByBundleName(const std::string &bundle, const int32_t userId, + const int32_t appIndex) +{ + int32_t uid = -1; + std::lock_guard lock(connectionMutex_); + Connect(); + if (bundleMgr_ != nullptr) { + std::string identity = IPCSkeleton::ResetCallingIdentity(); + uid = bundleMgr_->GetUidByBundleName(bundle, userId, appIndex); + if (uid < 0) { + ANS_LOGW("get invalid uid of bundle %{public}s in userId %{public}d", bundle.c_str(), userId); + } + IPCSkeleton::SetCallingIdentity(identity); + } + return uid; +} } // namespace Notification } // namespace OHOS diff --git a/services/ans/src/clone/notification_clone_disturb_service.cpp b/services/ans/src/clone/notification_clone_disturb_service.cpp new file mode 100644 index 000000000..448307a51 --- /dev/null +++ b/services/ans/src/clone/notification_clone_disturb_service.cpp @@ -0,0 +1,239 @@ +/* +* Copyright (c) 2021-2024 Huawei Device Co., Ltd. +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +#include "notification_clone_disturb_service.h" + +#include "ans_log_wrapper.h" +#include "notification_preferences.h" +#include "bundle_manager_helper.h" +#include "os_account_manager.h" + +namespace OHOS { +namespace Notification { +constexpr int32_t MAIN_USER_ID = 100; +std::shared_ptr NotificationCloneDisturb::GetInstance() +{ + static std::shared_ptr instance = + std::make_shared(); + return instance; +} + +NotificationCloneDisturb::NotificationCloneDisturb() +{ + cloneDisturbQueue_ = std::make_shared("NotificationCloneDisturbQueue"); + if (!cloneDisturbQueue_) { + ANS_LOGE("ffrt create failed!"); + return; + } +} + +NotificationCloneDisturb::~NotificationCloneDisturb() +{ +} + +ErrCode NotificationCloneDisturb::OnBackup(nlohmann::json &jsonObject) +{ + int32_t userId = GetActiveUserId(); + std::vector> profiles; + NotificationPreferences::GetInstance()->GetDoNotDisturbProfileListByUserId(userId, profiles); + + if (profiles.empty()) { + ANS_LOGI("Notification disturb profile list is empty."); + return ERR_OK; + } + jsonObject = nlohmann::json::array(); + for (size_t index = 0; index < profiles.size(); index++) { + nlohmann::json jsonNode; + profiles[index]->GetProfileJson(jsonNode); + jsonObject.emplace_back(jsonNode); + } + ANS_LOGD("Notification disturb profile list %{public}s", jsonObject.dump().c_str()); + return ERR_OK; +} + +ErrCode NotificationCloneDisturb::OnRestore(const nlohmann::json &jsonObject) +{ + ANS_LOGI("Notification disturb profile list on restore."); + if (jsonObject.is_null() || !jsonObject.is_array()) { + ANS_LOGI("Notification disturb profile list is null or not array."); + return ERR_OK; + } + + profiles_.clear(); + for (const auto &profile : jsonObject) { + sptr item = new (std::nothrow) NotificationDoNotDisturbProfile(); + item->FromJson(profile.dump()); + profiles_.push_back(item); + } + + if (cloneDisturbQueue_ == nullptr || profiles_.empty()) { + ANS_LOGE("Clone queue is invalidated or empty %{public}zu.", profiles_.size()); + return ERR_OK; + } + + int32_t userId = GetActiveUserId(); + cloneDisturbQueue_->submit_h(std::bind([&, userId]() { + ANS_LOGI("Notification disturb profile ffrt start %{public}zu.", profiles_.size()); + int32_t profileId = -1; + std::string name; + std::map uidMap; + for (auto profile = profiles_.begin(); profile != profiles_.end();) { + std::vector exitBunldleList; + std::vector notExitBunldleList; + name = (*profile)->GetProfileName(); + profileId = (*profile)->GetProfileId(); + ANS_LOGI("Notification disturb profile %{public}d, %{public}zu.", profileId, + (*profile)->GetProfileTrustList().size()); + GetProfileUid(userId, uidMap, (*profile)->GetProfileTrustList(), exitBunldleList, notExitBunldleList); + NotificationPreferences::GetInstance()->UpdateDoNotDisturbProfiles(userId, + profileId, name, exitBunldleList); + if (notExitBunldleList.empty()) { + profile = profiles_.erase(profile); + } else { + (*profile)->SetProfileTrustList(notExitBunldleList); + profile++; + } + name.clear(); + profileId = -1; + } + + for (auto profile = profiles_.begin(); profile != profiles_.end(); profile++) { + ANS_LOGI("Clone queue left %{public}d %{public}zu.", (*profile)->GetProfileId(), + (*profile)->GetProfileTrustList().size()); + } + })); + return ERR_OK; +} + +void NotificationCloneDisturb::GetProfileUid(int32_t userId, std::map& uidMap, + std::vector trustList, std::vector& exitBunldleList, + std::vector& notExitBunldleList) +{ + // get application uid with bundle name and appindex. + for (auto& bundle : trustList) { + std::string key = bundle.GetBundleName() + std::to_string(bundle.GetAppIndex()); + if (uidMap.find(key) != uidMap.end()) { + bundle.SetUid(uidMap[key]); + } else { + int32_t uid = GetBundleUid(bundle.GetBundleName(), userId, bundle.GetAppIndex()); + ANS_LOGW("Notification get uid %{public}d %{public}d %{public}s.", uid, bundle.GetAppIndex(), + bundle.GetBundleName().c_str()); + bundle.SetUid(uid); + uidMap[key] = uid; + } + if (bundle.GetUid() == -1) { + notExitBunldleList.push_back(bundle); + } else { + exitBunldleList.push_back(bundle); + } + } +} + +void NotificationCloneDisturb::OnBundleDataAdd(const sptr &bundleOption) +{ + HandlerBundleEvent(bundleOption->GetBundleName(), bundleOption->GetAppIndex(), bundleOption->GetUid()); +} + +void NotificationCloneDisturb::OnBundleDataUpdate(const sptr &bundleOption) +{ + HandlerBundleEvent(bundleOption->GetBundleName(), bundleOption->GetAppIndex(), bundleOption->GetUid()); +} + +void NotificationCloneDisturb::OnUserSwitch(int32_t userId) +{ + ANS_LOGI("Handler user switch %{public}d", userId); + if (cloneDisturbQueue_ == nullptr) { + ANS_LOGW("Clone disturb queue is null."); + return; + } + cloneDisturbQueue_->submit_h(std::bind([&]() { + profiles_.clear(); + })); +} + +void NotificationCloneDisturb::HandlerBundleEvent(const std::string bundleName, int32_t appIndex, int32_t uid) +{ + ANS_LOGI("Handler bundle event %{public}s %{public}d %{public}d %{public}zu.", + bundleName.c_str(), appIndex, uid, profiles_.size()); + if (profiles_.empty()) { + return; + } + + int32_t userId = GetActiveUserId(); + NotificationBundleOption bundle(bundleName, uid); + bundle.SetAppIndex(appIndex); + if (cloneDisturbQueue_ == nullptr) { + ANS_LOGW("Clone disturb queue is null."); + return; + } + cloneDisturbQueue_->submit_h(std::bind([&, bundle, userId]() { + int32_t profileId = -1; + std::string name; + for (auto profile = profiles_.begin(); profile != profiles_.end();) { + name = (*profile)->GetProfileName(); + profileId = (*profile)->GetProfileId(); + std::vector bundleList; + auto trustList = (*profile)->GetProfileTrustList(); + CheckBundleInfo(trustList, bundleList, bundle); + NotificationPreferences::GetInstance()->UpdateDoNotDisturbProfiles(userId, + profileId, name, bundleList); + if (trustList.empty()) { + profile = profiles_.erase(profile); + } else { + (*profile)->SetProfileTrustList(trustList); + profile++; + } + name.clear(); + profileId = -1; + } + for (auto profile = profiles_.begin(); profile != profiles_.end(); profile++) { + ANS_LOGI("Event queue left %{public}d %{public}zu.", (*profile)->GetProfileId(), + (*profile)->GetProfileTrustList().size()); + } + })); +} + +void NotificationCloneDisturb::CheckBundleInfo(std::vector& trustList, + std::vector& bundleList, const NotificationBundleOption& bundle) +{ + for (auto bundleItem = trustList.begin(); bundleItem != trustList.end(); bundleItem++) { + if (bundleItem->GetBundleName() == bundle.GetBundleName() && + bundleItem->GetAppIndex() == bundle.GetAppIndex()) { + bundleList.push_back(bundle); + trustList.erase(bundleItem); + break; + } + } +} + +int32_t NotificationCloneDisturb::GetBundleUid(const std::string bundleName, int32_t userId, int32_t appIndex) +{ + if (appIndex == -1) { + return BundleManagerHelper::GetInstance()->GetDefaultUidByBundleName(bundleName, userId); + } + return BundleManagerHelper::GetInstance()->GetDefaultUidByBundleName(bundleName, userId, appIndex); +} + +int32_t NotificationCloneDisturb::GetActiveUserId() +{ + std::vector activeUserId; + OHOS::AccountSA::OsAccountManager::QueryActiveOsAccountIds(activeUserId); + if (activeUserId.size() > 0) { + return activeUserId[0]; + } + return MAIN_USER_ID; +} +} +} diff --git a/services/ans/src/clone/notification_clone_manager.cpp b/services/ans/src/clone/notification_clone_manager.cpp new file mode 100644 index 000000000..9976dda31 --- /dev/null +++ b/services/ans/src/clone/notification_clone_manager.cpp @@ -0,0 +1,179 @@ +/* +* Copyright (c) 2021-2024 Huawei Device Co., Ltd. +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +#include "notification_clone_manager.h" + +#include +#include +#include +#include +#include +#include + +#include "ans_log_wrapper.h" +#include "nlohmann/json.hpp" +#include "notification_clone_disturb_service.h" + +namespace OHOS { +namespace Notification { + +const int ANS_CLONE_ERROR = -1; +constexpr const char *CLONE_ITEM_DISTURB = "notificationDisturb"; +constexpr const char *BACKUP_CONFIG_FILE_PATH = "/data/service/el1/public/notification/backup_config.conf"; + +NotificationCloneManager& NotificationCloneManager::GetInstance() +{ + static NotificationCloneManager notificationCloneManager; + return notificationCloneManager; +} + +int32_t NotificationCloneManager::OnBackup(MessageParcel& data, MessageParcel& reply) +{ + if (cloneTemplates.empty()) { + ANS_LOGI("Notification no need Backup."); + return ERR_OK; + } + + nlohmann::json jsonObject; + for (auto iter = cloneTemplates.begin(); iter != cloneTemplates.end(); ++iter) { + nlohmann::json jsonItem; + auto cloneTemplate = iter->second; + if (cloneTemplate == nullptr) { + ANS_LOGW("Notification OnBackup %{public}s funtion is null.", iter->first.c_str()); + continue; + } + if (iter->second->OnBackup(jsonItem) != ERR_OK) { + ANS_LOGW("Notification OnBackup %{public}s failed.", iter->first.c_str()); + continue; + } + jsonObject[iter->first] = jsonItem; + } + + if (SaveConfig(jsonObject.dump()) != ERR_OK) { + return ANS_CLONE_ERROR; + } + + UniqueFd fd = UniqueFd(open(BACKUP_CONFIG_FILE_PATH, O_RDONLY)); + if (fd.Get() < 0) { + ANS_LOGW("Notification open file failed."); + return ANS_CLONE_ERROR; + } + + if (reply.WriteFileDescriptor(fd) == false) { + close(fd.Release()); + ANS_LOGW("Notification write file descriptor failed!"); + return ANS_CLONE_ERROR; + } + + ANS_LOGI("Notification OnBackup end fd: %{public}d.", fd.Get()); + close(fd.Release()); + return ERR_OK; +} + +int32_t NotificationCloneManager::OnRestore(MessageParcel& data, MessageParcel& reply) +{ + std::string storeMessage; + UniqueFd fd(data.ReadFileDescriptor()); + if (LoadConfig(fd, storeMessage) != ERR_OK) { + close(fd.Release()); + RemoveBackUpFile(); + return ANS_CLONE_ERROR; + } + + RemoveBackUpFile(); + nlohmann::json jsonObject = nlohmann::json::parse(storeMessage, nullptr, false); + if (jsonObject.is_null() || !jsonObject.is_object()) { + ANS_LOGE("Invalid JSON object"); + return ANS_CLONE_ERROR; + } + for (auto iter = cloneTemplates.begin(); iter != cloneTemplates.end(); ++iter) { + if (jsonObject.contains(iter->first) && iter->second != nullptr) { + iter->second->OnRestore(jsonObject.at(iter->first)); + } + } + return ERR_OK; +} + +NotificationCloneManager::NotificationCloneManager() +{ + ANS_LOGI("Notification clone manager init."); + cloneTemplates.insert_or_assign(CLONE_ITEM_DISTURB, NotificationCloneDisturb::GetInstance()); +} + +NotificationCloneManager::~NotificationCloneManager() +{ + ANS_LOGI("Notification clone manager destory."); +} + +ErrCode NotificationCloneManager::LoadConfig(UniqueFd &fd, std::string& config) +{ + ANS_LOGI("Load notification config."); + struct stat statBuf; + if (fstat(fd.Get(), &statBuf) < 0) { + ANS_LOGW("LoadConfig fstat fd fail %{public}d.", fd.Get()); + return ANS_CLONE_ERROR; + } + int destFd = open(BACKUP_CONFIG_FILE_PATH, O_WRONLY | O_CREAT | O_TRUNC, S_IRUSR | S_IWUSR); + if (destFd < 0) { + ANS_LOGW("LoadConfig open file fail."); + return ANS_CLONE_ERROR; + } + if (sendfile(destFd, fd.Get(), nullptr, statBuf.st_size) < 0) { + ANS_LOGW("LoadConfig fd sendfile(size: %{public}d) to destFd fail.", static_cast(statBuf.st_size)); + close(destFd); + return ANS_CLONE_ERROR; + } + close(destFd); + std::ifstream fs(BACKUP_CONFIG_FILE_PATH); + if (!fs.is_open()) { + ANS_LOGW("Loading config file%{public}s is_open() failed!", BACKUP_CONFIG_FILE_PATH); + return ANS_CLONE_ERROR; + } + config.clear(); + std::string line; + while (std::getline(fs, line)) { + config.append(line); + } + fs.close(); + return ERR_OK; +} + +ErrCode NotificationCloneManager::SaveConfig(const std::string& config) +{ + ANS_LOGD("Save config file %{public}s", config.c_str()); + RemoveBackUpFile(); + FILE* fp = fopen(BACKUP_CONFIG_FILE_PATH, "w"); + if (!fp) { + ANS_LOGW("Save config file: %{public}s, fopen() failed!", BACKUP_CONFIG_FILE_PATH); + return ANS_CLONE_ERROR; + } + + int ret = fwrite(config.c_str(), 1, config.length(), fp); + if (ret != (int)config.length()) { + ANS_LOGW("Save config file: %{public}s, fwrite %{public}d failed!", BACKUP_CONFIG_FILE_PATH, ret); + } + (void)fflush(fp); + (void)fsync(fileno(fp)); + (void)fclose(fp); + ANS_LOGI("Save config file %{public}zu", config.size()); + return ERR_OK; +} + +void NotificationCloneManager::RemoveBackUpFile() +{ + remove(BACKUP_CONFIG_FILE_PATH); +} +} +} diff --git a/services/ans/src/notification_preferences.cpp b/services/ans/src/notification_preferences.cpp index d46106984..de48054a1 100644 --- a/services/ans/src/notification_preferences.cpp +++ b/services/ans/src/notification_preferences.cpp @@ -537,6 +537,14 @@ ErrCode NotificationPreferences::AddDoNotDisturbProfiles( if (!CheckDoNotDisturbProfileID(profile->GetProfileId())) { return ERR_ANS_INVALID_PARAM; } + auto trustList = profile->GetProfileTrustList(); + for (auto& bundleInfo : trustList) { + int32_t index = BundleManagerHelper::GetInstance()->GetAppIndexByUid(bundleInfo.GetUid()); + bundleInfo.SetAppIndex(index); + ANS_LOGI("Get app index by uid %{public}d %{public}s %{public}d", bundleInfo.GetUid(), + bundleInfo.GetBundleName().c_str(), index); + } + profile->SetProfileTrustList(trustList); } std::lock_guard lock(preferenceMutex_); NotificationPreferencesInfo preferencesInfo = preferencesInfo_; @@ -579,6 +587,66 @@ ErrCode NotificationPreferences::RemoveDoNotDisturbProfiles( return ERR_OK; } +void NotificationPreferences::UpdateProfilesUtil(std::vector& trustList, + const std::vector bundleList) +{ + for (auto& item : bundleList) { + bool exit = false; + for (auto& bundle: trustList) { + if (item.GetUid() == bundle.GetUid()) { + exit = true; + break; + } + } + if (!exit) { + trustList.push_back(item); + } + } +} + +ErrCode NotificationPreferences::UpdateDoNotDisturbProfiles(int32_t userId, int32_t profileId, + const std::string& name, const std::vector& bundleList) +{ + ANS_LOGI("Called update Profile %{public}d %{public}d %{public}zu.", userId, profileId, bundleList.size()); + if (!CheckDoNotDisturbProfileID(profileId) || bundleList.empty()) { + return ERR_ANS_INVALID_PARAM; + } + + sptr profile = new (std::nothrow) NotificationDoNotDisturbProfile(); + std::lock_guard lock(preferenceMutex_); + NotificationPreferencesInfo preferencesInfo = preferencesInfo_; + if (preferencesInfo.GetDoNotDisturbProfiles(profileId, userId, profile)) { + auto trustList = profile->GetProfileTrustList(); + UpdateProfilesUtil(trustList, bundleList); + profile->SetProfileTrustList(trustList); + } else { + profile->SetProfileId(profileId); + profile->SetProfileName(name); + profile->SetProfileTrustList(bundleList); + } + ANS_LOGI("Update profile %{public}d %{public}d %{public}zu", userId, profile->GetProfileId(), + profile->GetProfileTrustList().size()); + preferencesInfo.AddDoNotDisturbProfiles(userId, {profile}); + if (preferncesDB_ == nullptr) { + ANS_LOGE("The prefernces db is nullptr."); + return ERR_ANS_SERVICE_NOT_READY; + } + if (!preferncesDB_->AddDoNotDisturbProfiles(userId, {profile})) { + return ERR_ANS_PREFERENCES_NOTIFICATION_DB_OPERATION_FAILED; + } + preferencesInfo_ = preferencesInfo; + return ERR_OK; +} + +void NotificationPreferences::GetDoNotDisturbProfileListByUserId(int32_t userId, + std::vector> &profiles) +{ + std::lock_guard lock(preferenceMutex_); + NotificationPreferencesInfo preferencesInfo = preferencesInfo_; + preferencesInfo.GetAllDoNotDisturbProfiles(userId, profiles); + preferencesInfo_ = preferencesInfo; +} + ErrCode NotificationPreferences::GetAllNotificationEnabledBundles(std::vector &bundleOption) { ANS_LOGD("Called."); @@ -631,8 +699,10 @@ void NotificationPreferences::RemoveDoNotDisturbProfileTrustList( ANS_LOGE("The bundle option is nullptr."); return; } + int32_t uid = bundleOption->GetUid(); + int32_t appIndex = bundleOption->GetAppIndex(); auto bundleName = bundleOption->GetBundleName(); - ANS_LOGD("Called, bundle name is %{public}s.", bundleName.c_str()); + ANS_LOGI("Remove %{public}s %{public}d %{public}d.", bundleName.c_str(), uid, appIndex); std::lock_guard lock(preferenceMutex_); NotificationPreferencesInfo preferencesInfo = preferencesInfo_; @@ -645,7 +715,7 @@ void NotificationPreferences::RemoveDoNotDisturbProfileTrustList( } auto trustList = profile->GetProfileTrustList(); for (auto it = trustList.begin(); it != trustList.end(); it++) { - if (it->GetBundleName() == bundleName) { + if (it->GetUid() == uid) { trustList.erase(it); break; } diff --git a/services/ans/src/system_event_observer.cpp b/services/ans/src/system_event_observer.cpp index 973fb914b..fd14a6714 100644 --- a/services/ans/src/system_event_observer.cpp +++ b/services/ans/src/system_event_observer.cpp @@ -21,6 +21,7 @@ #include "common_event_manager.h" #include "common_event_support.h" #include "notification_preferences.h" +#include "notification_clone_disturb_service.h" namespace OHOS { namespace Notification { @@ -60,8 +61,10 @@ sptr SystemEventObserver::GetBundleOption(AAFwk::Want { auto element = want.GetElement(); std::string bundleName = element.GetBundleName(); + int32_t appIndex = want.GetIntParam("appIndex", -1); int32_t uid = want.GetIntParam(AppExecFwk::Constants::UID, -1); sptr bundleOption = new (std::nothrow) NotificationBundleOption(bundleName, uid); + bundleOption->SetAppIndex(appIndex); if (bundleOption == nullptr) { ANS_LOGE("Failed to create bundleOption."); return nullptr; @@ -99,6 +102,7 @@ void SystemEventObserver::OnReceiveEvent(const EventFwk::CommonEventData &data) } NotificationPreferences::GetInstance()->InitSettingFromDisturbDB(userId); AdvancedNotificationService::GetInstance()->RecoverLiveViewFromDb(userId); + NotificationCloneDisturb::GetInstance()->OnUserSwitch(userId); } else if (action == EventFwk::CommonEventSupport::COMMON_EVENT_USER_REMOVED) { int32_t userId = data.GetCode(); if (userId <= SUBSCRIBE_USER_INIT) { -- Gitee From 607c6677362396f49218f0d5dff973a45d9ee023 Mon Sep 17 00:00:00 2001 From: Ricky Date: Sat, 5 Oct 2024 10:54:36 +0800 Subject: [PATCH 084/167] fix publish api cannot use userId Signed-off-by: Ricky Change-Id: I624d09e4d2cf5efa741f29174cdc1d5c0df48d84 --- .../napi/src/common_convert_notification.cpp | 39 ++++++------------- frameworks/js/napi/src/publish.cpp | 2 +- .../ans/src/advanced_notification_service.cpp | 36 ++++++++--------- .../ans/src/advanced_notification_utils.cpp | 8 ++-- 4 files changed, 33 insertions(+), 52 deletions(-) diff --git a/frameworks/js/napi/src/common_convert_notification.cpp b/frameworks/js/napi/src/common_convert_notification.cpp index 73ca08afa..18dcdd45e 100644 --- a/frameworks/js/napi/src/common_convert_notification.cpp +++ b/frameworks/js/napi/src/common_convert_notification.cpp @@ -111,33 +111,18 @@ napi_value Common::SetNotification( napi_get_boolean(env, notification->IsFloatingIcon(), &value); napi_set_named_property(env, result, "isFloatingIcon", value); - if (notification->GetNotificationRequest().IsAgentNotification()) { - // Agent notification, replace creator with owner - // readonly creatorBundleName?: string - napi_create_string_utf8( - env, notification->GetNotificationRequest().GetOwnerBundleName().c_str(), NAPI_AUTO_LENGTH, &value); - napi_set_named_property(env, result, "creatorBundleName", value); - - // readonly creatorUid?: number - napi_create_int32(env, notification->GetNotificationRequest().GetOwnerUid(), &value); - napi_set_named_property(env, result, "creatorUid", value); - - // readonly creatorUserId?: number - napi_create_int32(env, notification->GetNotificationRequest().GetOwnerUserId(), &value); - napi_set_named_property(env, result, "creatorUserId", value); - } else { - // readonly creatorBundleName?: string - napi_create_string_utf8(env, notification->GetCreateBundle().c_str(), NAPI_AUTO_LENGTH, &value); - napi_set_named_property(env, result, "creatorBundleName", value); - - // readonly creatorUid?: number - napi_create_int32(env, notification->GetUid(), &value); - napi_set_named_property(env, result, "creatorUid", value); - - // readonly creatorUserId?: number - napi_create_int32(env, notification->GetUserId(), &value); - napi_set_named_property(env, result, "creatorUserId", value); - } + // readonly creatorBundleName?: string + napi_create_string_utf8( + env, notification->GetBundleName().c_str(), NAPI_AUTO_LENGTH, &value); + napi_set_named_property(env, result, "creatorBundleName", value); + + // readonly creatorUid?: number + napi_create_int32(env, notification->GetNotificationRequest().GetOwnerUid(), &value); + napi_set_named_property(env, result, "creatorUid", value); + + // readonly creatorUserId?: number + napi_create_int32(env, notification->GetRecvUserId(), &value); + napi_set_named_property(env, result, "creatorUserId", value); // readonly creatorInstanceKey?: number napi_create_int32(env, notification->GetInstanceKey(), &value); diff --git a/frameworks/js/napi/src/publish.cpp b/frameworks/js/napi/src/publish.cpp index 64a02fe10..7ccf804d0 100644 --- a/frameworks/js/napi/src/publish.cpp +++ b/frameworks/js/napi/src/publish.cpp @@ -84,7 +84,7 @@ napi_value ParseParameters(const napi_env &env, const napi_callback_info &info, if (valuetype == napi_number) { int32_t recvUserId = SUBSCRIBE_USER_INIT; NAPI_CALL(env, napi_get_value_int32(env, argv[PARAM1], &recvUserId)); - params.request.SetReceiverUserId(recvUserId); + params.request.SetOwnerUserId(recvUserId); } else { napi_create_reference(env, argv[PARAM1], 1, ¶ms.callback); } diff --git a/services/ans/src/advanced_notification_service.cpp b/services/ans/src/advanced_notification_service.cpp index 6c02abcee..72acf1df1 100644 --- a/services/ans/src/advanced_notification_service.cpp +++ b/services/ans/src/advanced_notification_service.cpp @@ -180,8 +180,11 @@ ErrCode AdvancedNotificationService::PrepareNotificationRequest(const sptrGetBundleOption()->GetUid() == DEFAULT_UID) { - int32_t userId = 0; - GetActiveUserId(userId); + int32_t userId = SUBSCRIBE_USER_INIT; + OsAccountManagerHelper::GetInstance().GetCurrentActiveUserId(userId); + if (request->GetOwnerUserId() != SUBSCRIBE_USER_INIT) { + userId = request->GetOwnerUserId(); + } std::shared_ptr bundleManager = BundleManagerHelper::GetInstance(); if (bundleManager != nullptr) { uid = bundleManager->GetDefaultUidByBundleName(sourceBundleName, userId); @@ -201,9 +204,8 @@ ErrCode AdvancedNotificationService::PrepareNotificationRequest(const sptrSetAgentBundle(agentBundle); - bundle = sourceBundleName; } - request->SetOwnerBundleName(bundle); + request->SetOwnerBundleName(sourceBundleName); } int32_t uid = IPCSkeleton::GetCallingUid(); @@ -218,6 +220,9 @@ ErrCode AdvancedNotificationService::PrepareNotificationRequest(const sptrSetCreatorUserId(userId); request->SetCreatorBundleName(bundle); + if (request->GetOwnerBundleName().empty()) { + request->SetOwnerBundleName(bundle); + } if (request->GetOwnerUserId() == SUBSCRIBE_USER_INIT) { int32_t ownerUserId = SUBSCRIBE_USER_INIT; OsAccountManagerHelper::GetInstance().GetOsAccountLocalIdFromUid(request->GetOwnerUid(), ownerUserId); @@ -425,24 +430,17 @@ ErrCode AdvancedNotificationService::PrepareNotificationInfo( NotificationAnalyticsUtil::ReportPublishFailedEvent(request, message); return result; } - - if (request->IsAgentNotification()) { + std::string sourceBundleName = + request->GetBundleOption() == nullptr ? "" : request->GetBundleOption()->GetBundleName(); + if ((!sourceBundleName.empty() && + NotificationPreferences::GetInstance()->IsAgentRelationship(GetClientBundleName(), sourceBundleName) && + !AccessTokenHelper::CheckPermission(OHOS_PERMISSION_NOTIFICATION_AGENT_CONTROLLER)) || + request->IsAgentNotification()) { bundleOption = new (std::nothrow) NotificationBundleOption(request->GetOwnerBundleName(), request->GetOwnerUid()); } else { - std::string sourceBundleName = - request->GetBundleOption() == nullptr ? "" : request->GetBundleOption()->GetBundleName(); - if (!sourceBundleName.empty() && - NotificationPreferences::GetInstance()->IsAgentRelationship(GetClientBundleName(), sourceBundleName)) { - ANS_LOGD("There is agent relationship between %{public}s and %{public}s", - GetClientBundleName().c_str(), sourceBundleName.c_str()); - request->SetCreatorBundleName(request->GetOwnerBundleName()); - request->SetCreatorUid(request->GetOwnerUid()); - bundleOption = new (std::nothrow) NotificationBundleOption(request->GetOwnerBundleName(), - request->GetOwnerUid()); - } else { - bundleOption = GenerateBundleOption(); - } + bundleOption = new (std::nothrow) NotificationBundleOption(request->GetCreatorBundleName(), + request->GetCreatorUid()); } if (bundleOption == nullptr) { diff --git a/services/ans/src/advanced_notification_utils.cpp b/services/ans/src/advanced_notification_utils.cpp index f97bc78f4..cc0461543 100644 --- a/services/ans/src/advanced_notification_utils.cpp +++ b/services/ans/src/advanced_notification_utils.cpp @@ -668,11 +668,9 @@ ErrCode AdvancedNotificationService::GetTargetRecordList(const int32_t uid, { for (auto& notification : notificationList_) { if (notification->request != nullptr && notification->request->GetSlotType()== slotType && - notification->request->GetNotificationType() == contentType) { - if (notification->request->GetCreatorUid() == uid || (notification->request->GetAgentBundle() != nullptr && - notification->request->GetAgentBundle()->GetUid() == uid)) { - recordList.emplace_back(notification); - } + notification->request->GetNotificationType() == contentType && + notification->request->GetCreatorUid() == uid) { + recordList.emplace_back(notification); } } if (recordList.empty()) { -- Gitee From c29082f8c51f0b83b3df25696a35ae9ee77aef7a Mon Sep 17 00:00:00 2001 From: gaojiaqi Date: Fri, 25 Oct 2024 14:48:40 +0800 Subject: [PATCH 085/167] sync Signed-off-by: gaojiaqi --- frameworks/ans/src/reminder_request.cpp | 5 +- .../ans/src/reminder_request_calendar.cpp | 6 +- services/ans/include/reminder_data_manager.h | 29 ++++-- services/ans/src/reminder_data_manager.cpp | 90 ++++++++++++------- .../ans/src/reminder_data_manager_inner.cpp | 33 +++++++ services/ans/src/reminder_store_strategy.cpp | 2 +- .../reminderdatamanager_fuzzer.cpp | 3 - 7 files changed, 121 insertions(+), 47 deletions(-) diff --git a/frameworks/ans/src/reminder_request.cpp b/frameworks/ans/src/reminder_request.cpp index a0f8a22fe..b96b261d5 100644 --- a/frameworks/ans/src/reminder_request.cpp +++ b/frameworks/ans/src/reminder_request.cpp @@ -1865,7 +1865,7 @@ uint64_t ReminderRequest::GetTriggerTime(const time_t now, const time_t nextTrig struct tm test; (void)localtime_r(&triggerTime, &test); 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", + "min=%{public}d, sec=%{public}d, week=%{public}d, nextTriggerTime=%{public}lld", GetActualTime(TimeTransferType::YEAR, test.tm_year), GetActualTime(TimeTransferType::MONTH, test.tm_mon), test.tm_mday, @@ -1888,6 +1888,9 @@ void ReminderRequest::OnLanguageChange(const std::shared_ptrGetStringByName(button.second.resource.c_str(), title); if (title.empty()) { diff --git a/frameworks/ans/src/reminder_request_calendar.cpp b/frameworks/ans/src/reminder_request_calendar.cpp index 75ee258a0..3bfad8e46 100644 --- a/frameworks/ans/src/reminder_request_calendar.cpp +++ b/frameworks/ans/src/reminder_request_calendar.cpp @@ -287,6 +287,9 @@ bool ReminderRequestCalendar::OnDateTimeChange() if (IsExpired()) { return false; } + if (startDateTime_ == endDateTime_) { + return ReminderRequest::OnDateTimeChange(); + } uint64_t now = GetNowInstantMilli(); if (now == 0) { ANSR_LOGE("get now time failed"); @@ -347,7 +350,8 @@ bool ReminderRequestCalendar::IsNeedNotification() ANSR_LOGE("get now time failed"); return false; } - if (now <= endDateTime_ && now >= startDateTime_) { + if ((now <= endDateTime_ && now >= startDateTime_) || + (startDateTime_ == endDateTime_)) { return true; } uint64_t triggerTime = GetNextTriggerTime(true); diff --git a/services/ans/include/reminder_data_manager.h b/services/ans/include/reminder_data_manager.h index 93b657874..7c50c2fe7 100644 --- a/services/ans/include/reminder_data_manager.h +++ b/services/ans/include/reminder_data_manager.h @@ -245,18 +245,12 @@ public: */ void TerminateAlerting(const OHOS::EventFwk::Want &want); - /** - * @brief Get resource manager by handle info. - */ - std::shared_ptr GetBundleResMgr( - const AppExecFwk::BundleInfo &bundleInfo); - /** * @brief Update reminders based on the system language. * * Update action button title. */ - void UpdateReminderLanguage(const sptr &reminder); + void UpdateReminderLanguage(const int32_t uid, const std::vector>& reminders); void UpdateReminderLanguageLocked(const sptr &reminder); /** @@ -640,6 +634,25 @@ private: bool IsActionButtonDataShareValid(const sptr& reminder, const uint32_t callerTokenId); + /** + * @brief Get resource manager by bundlename and uid. + */ + std::shared_ptr GetResourceMgr(const std::string& bundleName, + const int32_t uid); + + /** + * @brief Get custom ring file desc. + * lock by resourceMutex_ in function + */ + bool GetCustomRingFileDesc(const sptr& reminder, + Global::Resource::ResourceManager::RawFileDescriptor& desc); + + /** + * @brief Close custom ring file desc. + * lock by resourceMutex_ in function + */ + void CloseCustomRingFileDesc(const int32_t reminderId, const std::string& customRingUri); + /** * @brief report event to dfx */ @@ -714,6 +727,8 @@ private: sptr alertingReminder_ = nullptr; #ifdef PLAYER_FRAMEWORK_ENABLE std::shared_ptr soundPlayer_ = nullptr; + std::mutex resourceMutex_; // for soundResource_ + std::shared_ptr soundResource_ = nullptr; #endif /** * Indicates the total count of reminders in system. diff --git a/services/ans/src/reminder_data_manager.cpp b/services/ans/src/reminder_data_manager.cpp index 8efcd4b2f..03c2ea66e 100644 --- a/services/ans/src/reminder_data_manager.cpp +++ b/services/ans/src/reminder_data_manager.cpp @@ -21,7 +21,6 @@ #include "ans_const_define.h" #include "common_event_support.h" #include "common_event_manager.h" -#include "notification_constant.h" #include "reminder_request_calendar.h" #include "in_process_call_wrapper.h" #ifdef DEVICE_STANDBY_ENABLE @@ -944,7 +943,7 @@ bool ReminderDataManager::ShouldAlert(const sptr &reminder) con ErrCode errCode = advancedNotificationService_->GetDoNotDisturbDate(date); if (errCode != ERR_OK) { ANSR_LOGE("The reminder (reminderId=%{public}d) is silent for get disturbDate error", reminderId); - return false; + return true; } if (date->GetDoNotDisturbType() == NotificationConstant::DoNotDisturbType::NONE) { return true; @@ -1679,18 +1678,25 @@ void ReminderDataManager::PlaySoundAndVibration(const sptr &rem return; } } - std::string defaultPath; - if (access(DEFAULT_REMINDER_SOUND_1.c_str(), F_OK) == 0) { - defaultPath = "file:/" + DEFAULT_REMINDER_SOUND_1; + std::string customRingUri = reminder->GetCustomRingUri(); + if (customRingUri.empty()) { + // use default ring + std::string defaultPath; + if (access(DEFAULT_REMINDER_SOUND_1.c_str(), F_OK) == 0) { + defaultPath = "file:/" + DEFAULT_REMINDER_SOUND_1; + } else { + defaultPath = "file:/" + GetFullPath(DEFAULT_REMINDER_SOUND_2); + } + Uri defaultSound(defaultPath); + soundPlayer_->SetSource(defaultSound.GetSchemeSpecificPart()); + ANSR_LOGI("Play default sound."); } else { - defaultPath = "file:/" + GetFullPath(DEFAULT_REMINDER_SOUND_2); - } - std::string ringUri = GetCustomRingUri(reminder); - Uri reminderSound(ringUri); - Uri defaultSound(defaultPath); - Uri soundUri = ringUri.empty() ? defaultSound : reminderSound; - std::string uri = soundUri.GetSchemeSpecificPart(); - ANSR_LOGD("uri:%{public}s", uri.c_str()); + Global::Resource::ResourceManager::RawFileDescriptor desc; + if (GetCustomRingFileDesc(reminder, desc)) { + soundPlayer_->SetSource(desc.fd, desc.offset, desc.length); + } + ANSR_LOGI("Play custom sound, reminderId:[%{public}d].", reminder->GetReminderId()); + } soundPlayer_->SetSource(uri); soundPlayer_->SetLooping(true); soundPlayer_->PrepareAsync(); @@ -1744,6 +1750,12 @@ void ReminderDataManager::StopSoundAndVibration(const sptr &rem if (soundPlayer_ == nullptr) { ANSR_LOGW("Sound player is null"); } else { + std::string customRingUri = reminder->GetCustomRingUri(); + if (customRingUri.empty()) { + ANSR_LOGI("Stop default sound."); + } else { + CloseCustomRingFileDesc(reminder->GetReminderId(), customRingUri); + } soundPlayer_->Stop(); soundPlayer_->Release(); soundPlayer_ = nullptr; @@ -2010,12 +2022,19 @@ void ReminderDataManager::ClickReminder(const OHOS::EventFwk::Want &want) } } -std::shared_ptr ReminderDataManager::GetBundleResMgr( - const AppExecFwk::BundleInfo &bundleInfo) +std::shared_ptr ReminderDataManager::GetResourceMgr(const std::string& bundleName, + const int32_t uid) { + AppExecFwk::BundleInfo bundleInfo; + if (!BundleManagerHelper::GetInstance()->GetBundleInfo(bundleName, + AppExecFwk::BundleFlag::GET_BUNDLE_WITH_ABILITIES, uid, bundleInfo)) { + ANSR_LOGE("GetBundleInfo[%{public}s][%{public}d] fail.", bundleName.c_str(), uid); + return nullptr; + } + // obtains the resource manager std::shared_ptr resourceManager(Global::Resource::CreateResourceManager()); if (!resourceManager) { - ANSR_LOGE("create resourceManager failed."); + ANSR_LOGE("CreateResourceManager fail."); return nullptr; } // obtains the resource path. @@ -2024,9 +2043,8 @@ std::shared_ptr ReminderDataManager::GetBundl if (moduleResPath.empty()) { continue; } - ANSR_LOGD("GetBundleResMgr, moduleResPath: %{private}s", moduleResPath.c_str()); if (!resourceManager->AddResource(moduleResPath.c_str())) { - ANSR_LOGW("GetBundleResMgr AddResource failed"); + ANSR_LOGW("AddResource fail."); } } // obtains the current system language. @@ -2038,44 +2056,47 @@ std::shared_ptr ReminderDataManager::GetBundl return resourceManager; } -void ReminderDataManager::UpdateReminderLanguage(const sptr &reminder) +void ReminderDataManager::UpdateReminderLanguage(const int32_t uid, + const std::vector>& reminders) { // obtains the bundle info by bundle name - const std::string bundleName = reminder->GetBundleName(); - AppExecFwk::BundleInfo bundleInfo; - if (!BundleManagerHelper::GetInstance()->GetBundleInfo(bundleName, - AppExecFwk::BundleFlag::GET_BUNDLE_WITH_ABILITIES, reminder->GetUid(), bundleInfo)) { - ANSR_LOGE("Get reminder request[%{public}d][%{public}s] bundle info failed.", - reminder->GetReminderId(), bundleName.c_str()); + if (reminders.empty()) { return; } + + std::string bundleName = reminders[0]->GetBundleName(); // obtains the resource manager - auto resourceMgr = GetBundleResMgr(bundleInfo); + auto resourceMgr = GetResourceMgr(bundleName, uid); if (resourceMgr == nullptr) { ANSR_LOGE("Get reminder request[%{public}d][%{public}s] resource manager failed.", - reminder->GetReminderId(), bundleName.c_str()); + uid, bundleName.c_str()); return; } // update action button title - reminder->OnLanguageChange(resourceMgr); + for (auto reminder : reminders) { + reminder->OnLanguageChange(resourceMgr); + } } void ReminderDataManager::UpdateReminderLanguageLocked(const sptr &reminder) { std::lock_guard lock(ReminderDataManager::MUTEX); - UpdateReminderLanguage(reminder); + std::vector> reminders; + reminders.push_back(reminder); + UpdateReminderLanguage(reminder->GetUid(), reminders); } void ReminderDataManager::OnLanguageChanged() { - ANSR_LOGI("System language config changed."); + ANSR_LOGI("System language config changed start."); { std::lock_guard lock(ReminderDataManager::MUTEX); + std::unordered_map>> reminders; for (auto it = reminderVector_.begin(); it != reminderVector_.end(); ++it) { - if ((*it)->IsExpired() || (*it)->GetTriggerTimeInMilli() == 0) { - continue; - } - UpdateReminderLanguage(*it); + reminders[(*it)->GetUid()].push_back((*it)); + } + for (auto& each : reminders) { + UpdateReminderLanguage(each.first, each.second); } } std::vector> showedReminder; @@ -2087,6 +2108,7 @@ void ReminderDataManager::OnLanguageChanged() std::lock_guard lock(ReminderDataManager::MUTEX); ShowReminder((*it), false, false, false, false); } + ANSR_LOGI("System language config changed end."); } void ReminderDataManager::OnRemoveAppMgr() diff --git a/services/ans/src/reminder_data_manager_inner.cpp b/services/ans/src/reminder_data_manager_inner.cpp index b17a0bc85..dd79e6ec2 100644 --- a/services/ans/src/reminder_data_manager_inner.cpp +++ b/services/ans/src/reminder_data_manager_inner.cpp @@ -97,6 +97,39 @@ void ReminderDataManager::HandleAutoDeleteReminder(const int32_t notificationId, StartRecentReminder(); } +bool ReminderDataManager::GetCustomRingFileDesc(const sptr& reminder, + Global::Resource::ResourceManager::RawFileDescriptor& desc) +{ + // obtains the resource manager + std::lock_guard locker(resourceMutex_); + soundResource_ = GetResourceMgr(reminder->GetBundleName(), reminder->GetUid()); + if (soundResource_ == nullptr) { + ANSR_LOGE("GetResourceMgr fail."); + return false; + } + auto result = soundResource_->GetRawFileDescriptor(reminder->GetCustomRingUri(), desc); + if (result != Global::Resource::SUCCESS) { + ANSR_LOGE("GetRawFileDescriptor fail[%{public}d].", static_cast(result)); + return false; + } + return true; +} + +void ReminderDataManager::CloseCustomRingFileDesc(const int32_t reminderId, const std::string& customRingUri) +{ + std::lock_guard locker(resourceMutex_); + if (soundResource_ == nullptr) { + ANSR_LOGW("ResourceManager is nullptr."); + return; + } + auto result = soundResource_->CloseRawFileDescriptor(customRingUri); + if (result != Global::Resource::SUCCESS) { + ANSR_LOGW("CloseRawFileDescriptor fail[%{public}d]", static_cast(result)); + } + ANSR_LOGI("Stop custom sound, reminderId:[%{public}d].", reminderId); + soundResource_ = nullptr; +} + void ReminderDataManager::ReportSysEvent(const sptr& reminder) { #ifdef HAS_HISYSEVENT_PART diff --git a/services/ans/src/reminder_store_strategy.cpp b/services/ans/src/reminder_store_strategy.cpp index 814d85d3b..b9af4d411 100644 --- a/services/ans/src/reminder_store_strategy.cpp +++ b/services/ans/src/reminder_store_strategy.cpp @@ -486,7 +486,7 @@ void ReminderCalendarStrategy::AppendValuesBucket(const sptr& r uint64_t lastStartDateTime = 0; std::string rruleWantAgent; std::string excludeDates; - if (reminder->GetReminderType() == ReminderRequest::ReminderType::CALENDAR) { + if (reminder != nullptr && reminder->GetReminderType() == ReminderRequest::ReminderType::CALENDAR) { ReminderRequestCalendar* calendar = static_cast(reminder.GetRefPtr()); if (calendar != nullptr) { repeatDay = calendar->GetRepeatDay(); diff --git a/test/fuzztest/reminderdatamanager_fuzzer/reminderdatamanager_fuzzer.cpp b/test/fuzztest/reminderdatamanager_fuzzer/reminderdatamanager_fuzzer.cpp index a9b4acafb..53650069d 100644 --- a/test/fuzztest/reminderdatamanager_fuzzer/reminderdatamanager_fuzzer.cpp +++ b/test/fuzztest/reminderdatamanager_fuzzer/reminderdatamanager_fuzzer.cpp @@ -67,9 +67,6 @@ namespace OHOS { manager->HandleCustomButtonClick(want); manager->ClickReminder(want); manager->TerminateAlerting(want); - AppExecFwk::BundleInfo bundleInfo; - manager->GetBundleResMgr(bundleInfo); - manager->UpdateReminderLanguage(reminder); manager->UpdateReminderLanguageLocked(reminder); return true; } -- Gitee From a41c6ddc62ca340e779298d0573db350015d1580 Mon Sep 17 00:00:00 2001 From: z30053788 Date: Sat, 12 Oct 2024 15:09:37 +0800 Subject: [PATCH 086/167] cherry pick ca1cbd8 from https://gitee.com/zhaobaoxin1/notification_distributed_notification_service/pulls/2290 update Signed-off-by: z30053788 Change-Id: I97ed0e4e765df8f692f038f43c98fdadabaa6b13 --- services/ans/src/advanced_notification_slot_service.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/services/ans/src/advanced_notification_slot_service.cpp b/services/ans/src/advanced_notification_slot_service.cpp index 53f96f74e..91011a4a9 100644 --- a/services/ans/src/advanced_notification_slot_service.cpp +++ b/services/ans/src/advanced_notification_slot_service.cpp @@ -443,7 +443,7 @@ ErrCode AdvancedNotificationService::SetSlotFlagsAsBundle(const sptrGetBundleName().c_str()); + ANS_LOGI("Set slotflags %{public}d to %{public}s.", slotFlags, bundle->GetBundleName().c_str()); result = UpdateSlotReminderModeBySlotFlags(bundle, slotFlags); })); notificationSvrQueue_->wait(handler); -- Gitee From a911d1c54d408be2569e9fff3a2fd8219a669ce5 Mon Sep 17 00:00:00 2001 From: wufarong Date: Tue, 22 Oct 2024 18:24:47 +0800 Subject: [PATCH 087/167] =?UTF-8?q?cherry=20pick=20e108596=20from=20https:?= =?UTF-8?q?//gitee.com/wufarong1/notification=5Fdistributed=5Fnotification?= =?UTF-8?q?=5Fservice/pulls/2323=20=E6=96=B0=E5=A2=9EOnSubscriberAddInffrt?= =?UTF-8?q?=E6=96=B9=E6=B3=95?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: wufarong Change-Id: I05b526601da5f451e86daffc9725327f24ee7591 --- services/ans/include/advanced_notification_service.h | 1 + .../ans/src/advanced_notification_live_view_service.cpp | 9 +++++++++ services/ans/src/advanced_notification_service.cpp | 2 +- 3 files changed, 11 insertions(+), 1 deletion(-) diff --git a/services/ans/include/advanced_notification_service.h b/services/ans/include/advanced_notification_service.h index 0e8b4fcab..567744e42 100644 --- a/services/ans/include/advanced_notification_service.h +++ b/services/ans/include/advanced_notification_service.h @@ -1316,6 +1316,7 @@ private: NotificationContent::Type contentType, std::vector>& recordList); ErrCode RemoveNotificationFromRecordList(const std::vector>& recordList); void OnSubscriberAdd(const std::shared_ptr &record); + void OnSubscriberAddInffrt(const std::shared_ptr &record); bool IsLiveViewCanRecover(const sptr request); ErrCode FillNotificationRecord(const NotificationRequestDb &requestdbObj, std::shared_ptr record); diff --git a/services/ans/src/advanced_notification_live_view_service.cpp b/services/ans/src/advanced_notification_live_view_service.cpp index 60f1b8ecc..506751f25 100644 --- a/services/ans/src/advanced_notification_live_view_service.cpp +++ b/services/ans/src/advanced_notification_live_view_service.cpp @@ -15,6 +15,7 @@ #include "advanced_notification_service.h" +#include "cpp/task.h" #include "errors.h" #include "ans_inner_errors.h" #include "notification_constant.h" @@ -168,6 +169,14 @@ void AdvancedNotificationService::ProcForDeleteLiveView(const std::shared_ptr &record) +{ + ffrt::task_handle handler = notificationSvrQueue_->submit_h(std::bind([this, record]() { + OnSubscriberAdd(record); + })); +} + void AdvancedNotificationService::OnSubscriberAdd( const std::shared_ptr &record) { diff --git a/services/ans/src/advanced_notification_service.cpp b/services/ans/src/advanced_notification_service.cpp index 72acf1df1..0a99c72d2 100644 --- a/services/ans/src/advanced_notification_service.cpp +++ b/services/ans/src/advanced_notification_service.cpp @@ -301,7 +301,7 @@ AdvancedNotificationService::AdvancedNotificationService() StartFilters(); std::function &)> callback = - std::bind(&AdvancedNotificationService::OnSubscriberAdd, this, std::placeholders::_1); + std::bind(&AdvancedNotificationService::OnSubscriberAddInffrt, this, std::placeholders::_1); NotificationSubscriberManager::GetInstance()->RegisterOnSubscriberAddCallback(callback); RecoverLiveViewFromDb(); -- Gitee From 65e5d510d5346c3c9fc1e8a12275f760bd942b78 Mon Sep 17 00:00:00 2001 From: z30053788 Date: Tue, 15 Oct 2024 21:22:21 +0800 Subject: [PATCH 088/167] cherry pick 14a3837 from https://gitee.com/zhaobaoxin1/notification_distributed_notification_service/pulls/2301 update Signed-off-by: z30053788 Change-Id: I63e04cf6ea544806bac3e66776c3fa7542bc5a88 --- frameworks/js/napi/src/common_utils.cpp | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/frameworks/js/napi/src/common_utils.cpp b/frameworks/js/napi/src/common_utils.cpp index 6422fddad..425dbc364 100644 --- a/frameworks/js/napi/src/common_utils.cpp +++ b/frameworks/js/napi/src/common_utils.cpp @@ -52,6 +52,10 @@ static const std::unordered_map ERROR_CODE_MESSAGE { {ERROR_DIALOG_IS_POPPING, "Dialog is popping"}, {ERROR_SETTING_WINDOW_EXIST, "The notification settings window is already displayed"}, {ERROR_NO_PROFILE_TEMPLATE, "Not exit noNotDisturb profile template"}, + {ERROR_REPEAT_SET, "Repeat create or end"}, + {ERROR_NO_RIGHT, "No permission"}, + {ERROR_EXPIRED_NOTIFICATION, "Low update version"}, + {ERROR_NETWORK_UNREACHABLE, "Network unreachable"}, }; } -- Gitee From c24a18332cddf9a6c35b58d6013d7b52d906e5ea Mon Sep 17 00:00:00 2001 From: gaojiaqi Date: Sat, 26 Oct 2024 17:11:09 +0800 Subject: [PATCH 089/167] update Signed-off-by: gaojiaqi --- frameworks/ans/src/reminder_request.cpp | 12 +- interfaces/inner_api/reminder_request.h | 12 ++ services/ans/include/reminder_data_manager.h | 36 ++-- services/ans/src/reminder_data_manager.cpp | 183 +++++------------- .../ans/src/reminder_data_manager_inner.cpp | 19 ++ services/ans/src/reminder_event_manager.cpp | 20 +- .../unittest/reminder_data_manager_test.cpp | 6 +- .../reminderdatamanager_fuzzer.cpp | 5 +- 8 files changed, 138 insertions(+), 155 deletions(-) diff --git a/frameworks/ans/src/reminder_request.cpp b/frameworks/ans/src/reminder_request.cpp index b96b261d5..50360754b 100644 --- a/frameworks/ans/src/reminder_request.cpp +++ b/frameworks/ans/src/reminder_request.cpp @@ -947,6 +947,16 @@ std::string ReminderRequest::GetCustomRingUri() const return customRingUri_; } +sptr ReminderRequest::GetNotificationBundleOption() const +{ + return notificationOption_; +} + +void ReminderRequest::SetNotificationBundleOption(const sptr& option) +{ + notificationOption_ = option; +} + std::shared_ptr ReminderRequest::GetWantAgentInfo() const { return wantAgentInfo_; @@ -1898,8 +1908,6 @@ void ReminderRequest::OnLanguageChange(const std::shared_ptr GetNotificationBundleOption() const; + + /** + * @brief Sets notification bundle option. + */ + void SetNotificationBundleOption(const sptr& option); + /** * @brief Update notification attributes. * @@ -1133,6 +1143,8 @@ private: std::string wantAgentStr_{}; std::string maxWantAgentStr_{}; + + sptr notificationOption_ {nullptr}; }; } // namespace Reminder } // namespace OHOS diff --git a/services/ans/include/reminder_data_manager.h b/services/ans/include/reminder_data_manager.h index 7c50c2fe7..38777ba3b 100644 --- a/services/ans/include/reminder_data_manager.h +++ b/services/ans/include/reminder_data_manager.h @@ -157,7 +157,15 @@ public: void OnUserRemove(const int32_t& userId); - void OnServiceStart(); + /** + * @brief Bundle manager service start. + */ + void OnBundleMgrServiceStart(); + + /** + * @brief Ability manager service start. + */ + void OnAbilityMgrServiceStart(); void OnUserSwitch(const int32_t& userId); @@ -250,8 +258,7 @@ public: * * Update action button title. */ - void UpdateReminderLanguage(const int32_t uid, const std::vector>& reminders); - void UpdateReminderLanguageLocked(const sptr &reminder); + void UpdateReminderLanguageLocked(const int32_t uid, const std::vector>& reminders); /** * @brief System language change @@ -263,6 +270,11 @@ public: */ void OnRemoveAppMgr(); + /** + * @brief Whether the device is ready or not. + */ + bool IsSystemReady(); + static constexpr uint8_t TIME_ZONE_CHANGE = 0; static constexpr uint8_t DATE_TIME_CHANGE = 1; @@ -412,14 +424,6 @@ private: */ sptr FindReminderRequestLocked(const int32_t &reminderId, const std::string &pkgName); - /** - * Find bundle option from {@link notificationBundleOptionMap_} by reminder id. - * - * @param reminderId Indicates the reminder id. - * @return pointer of NotificationBundleOption or nullptr. - */ - sptr FindNotificationBundleOption(const int32_t &reminderId) const; - /** * Obtains the recent reminder which is not expired from reminder vector. * @@ -699,11 +703,6 @@ private: */ std::vector> showedReminderVector_; - /** - * Map used to record all the bundle information of the reminders in system. - */ - std::map> notificationBundleOptionMap_; - /** * This timer is used to control the triggerTime of next reminder. */ @@ -753,6 +752,11 @@ private: * async queue */ std::shared_ptr queue_ = nullptr; + + /** + * Sa ready flag + */ + std::atomic saReadyFlag_{ 0 }; }; } // namespace OHOS } // namespace Notification diff --git a/services/ans/src/reminder_data_manager.cpp b/services/ans/src/reminder_data_manager.cpp index 03c2ea66e..7f51ca62e 100644 --- a/services/ans/src/reminder_data_manager.cpp +++ b/services/ans/src/reminder_data_manager.cpp @@ -100,7 +100,6 @@ ErrCode ReminderDataManager::PublishReminder(const sptr &remind } UpdateAndSaveReminderLocked(reminder, bundleOption); queue_->submit([this, reminder]() { - UpdateReminderLanguageLocked(reminder); StartRecentReminder(); }); return ERR_OK; @@ -252,13 +251,6 @@ void ReminderDataManager::CancelRemindersImplLocked(const std::string &packageNa } } for (auto vit = reminderVector_.begin(); vit != reminderVector_.end();) { - int32_t reminderId = (*vit)->GetReminderId(); - auto mit = notificationBundleOptionMap_.find(reminderId); - if (mit == notificationBundleOptionMap_.end()) { - ANSR_LOGE("Get bundle option occur error, reminderId=%{public}d", reminderId); - ++vit; - continue; - } if (IsMatched(*vit, packageName, userId, uid)) { if ((*vit)->IsAlerting()) { StopAlertingReminder(*vit); @@ -266,7 +258,6 @@ void ReminderDataManager::CancelRemindersImplLocked(const std::string &packageNa CancelNotification(*vit); RemoveFromShowedReminders(*vit); vit = reminderVector_.erase(vit); - notificationBundleOptionMap_.erase(mit); totalCount_--; continue; } @@ -329,7 +320,7 @@ void ReminderDataManager::CancelNotification(const sptr &remind ANSR_LOGE("Cancel notification fail"); return; } - sptr bundleOption = FindNotificationBundleOption(reminder->GetReminderId()); + sptr bundleOption = reminder->GetNotificationBundleOption(); advancedNotificationService_->CancelPreparedNotification(notification->GetNotificationId(), ReminderRequest::NOTIFICATION_LABEL, bundleOption, NotificationConstant::APP_CANCEL_REMINDER_REASON_DELETE); } @@ -382,12 +373,6 @@ void ReminderDataManager::OnUserRemove(const int32_t& userId) CancelAllReminders(userId); } -void ReminderDataManager::OnServiceStart() -{ - std::vector> immediatelyShowReminders; - GetImmediatelyShowRemindersLocked(immediatelyShowReminders); -} - void ReminderDataManager::OnUserSwitch(const int32_t& userId) { ANSR_LOGD("Switch user id from %{private}d to %{private}d", currentUserId_, userId); @@ -406,16 +391,7 @@ void ReminderDataManager::OnProcessDiedLocked(const sptr locker(ReminderDataManager::MUTEX); std::lock_guard lock(ReminderDataManager::SHOW_MUTEX); for (auto it = showedReminderVector_.begin(); it != showedReminderVector_.end(); ++it) { - int32_t reminderId = (*it)->GetReminderId(); - auto mit = notificationBundleOptionMap_.find(reminderId); - if (mit == notificationBundleOptionMap_.end()) { - ANSR_LOGD("Not get bundle option, the reminder may has been cancelled, reminderId=%{public}d", reminderId); - CancelNotification(*it); - showedReminderVector_.erase(it); - --it; - continue; - } - if (mit->second->GetBundleName() != bundleName || mit->second->GetUid() != uid) { + if ((*it)->GetBundleName() != bundleName || (*it)->GetUid() != uid) { continue; } if ((*it)->IsAlerting()) { @@ -438,14 +414,8 @@ void ReminderDataManager::InitTimerInfo(std::shared_ptr &shar sharedTimerInfo->SetRepeat(false); sharedTimerInfo->SetInterval(0); - auto mit = notificationBundleOptionMap_.find(reminderRequest->GetReminderId()); - if (mit == notificationBundleOptionMap_.end()) { - ANS_LOGE("Failed to get bundle information. reminderId=%{public}d", - reminderRequest->GetReminderId()); - return; - } - sharedTimerInfo->SetBundleName(mit->second->GetBundleName()); - sharedTimerInfo->SetUid(mit->second->GetUid()); + sharedTimerInfo->SetBundleName(reminderRequest->GetBundleName()); + sharedTimerInfo->SetUid(reminderRequest->GetUid()); // The systemtimer type will be set TIMER_TYPE_INEXACT_REMINDER&&EXACT if reminder type is CALENDAR or TIMER, // and set WAKEUP&&EXACT if ALARM. @@ -455,7 +425,7 @@ void ReminderDataManager::InitTimerInfo(std::shared_ptr &shar reminderRequest->GetReminderType() == ReminderRequest::ReminderType::TIMER)) { #ifdef DEVICE_STANDBY_ENABLE // Get allow list. - std::string name = mit->second->GetBundleName(); + std::string name = reminderRequest->GetBundleName(); std::vector allowInfoList; DevStandbyMgr::StandbyServiceClient::GetInstance().GetAllowList(DevStandbyMgr::AllowType::TIMER, allowInfoList, REASON_APP_API); @@ -560,17 +530,6 @@ sptr ReminderDataManager::FindReminderRequestLocked( return reminder; } -sptr ReminderDataManager::FindNotificationBundleOption(const int32_t &reminderId) const -{ - auto it = notificationBundleOptionMap_.find(reminderId); - if (it == notificationBundleOptionMap_.end()) { - ANSR_LOGW("Failed to get bundle option."); - return nullptr; - } else { - return it->second; - } -} - bool ReminderDataManager::cmp(sptr &reminderRequest, sptr &other) { return reminderRequest->GetTriggerTimeInMilli() < other->GetTriggerTimeInMilli(); @@ -618,7 +577,7 @@ void ReminderDataManager::CloseRemindersByGroupId(const int32_t &oldReminderId, if (IsMatchedForGroupIdAndPkgName(reminder, packageName, groupId)) { reminder->SetExpired(true); reminder->SetStateToInActive(); - store_->UpdateOrInsert(reminder, FindNotificationBundleOption(reminder->GetReminderId())); + store_->UpdateOrInsert(reminder, reminder->GetNotificationBundleOption()); ResetStates(TimerType::TRIGGER_TIMER); ANSR_LOGD("Cancel reminders by groupid, reminder is %{public}s", reminder->Dump().c_str()); } @@ -642,7 +601,7 @@ void ReminderDataManager::CloseReminder(const sptr &reminder, b } reminder->OnClose(true); RemoveFromShowedReminders(reminder); - store_->UpdateOrInsert(reminder, FindNotificationBundleOption(reminder->GetReminderId())); + store_->UpdateOrInsert(reminder, reminder->GetNotificationBundleOption()); if (cancelNotification) { CancelNotification(reminder); } @@ -702,11 +661,7 @@ void ReminderDataManager::UpdateAppDatabase(const sptr &reminde return; } // init default dstBundleName - std::string dstBundleName; - auto mit = notificationBundleOptionMap_.find(reminder->GetReminderId()); - if (mit != notificationBundleOptionMap_.end()) { - dstBundleName = mit->second->GetBundleName(); - } + std::string dstBundleName = reminder->GetBundleName(); GenDstBundleName(dstBundleName, actionButtonMap.at(actionButtonType).dataShareUpdate->uri); DataShare::CreateOptions options; @@ -821,6 +776,10 @@ void ReminderDataManager::GenDstBundleName(std::string &dstBundleName, const std void ReminderDataManager::RefreshRemindersDueToSysTimeChange(uint8_t type) { + if (!IsSystemReady()) { + ANSR_LOGW("bundle service or ability service not ready."); + return; + } std::string typeInfo = type == TIME_ZONE_CHANGE ? "timeZone" : "dateTime"; ANSR_LOGI("Refresh all reminders due to %{public}s changed by user", typeInfo.c_str()); if (activeReminderId_ != -1) { @@ -870,7 +829,7 @@ void ReminderDataManager::TerminateAlerting(const sptr &reminde return; } int32_t reminderId = reminder->GetReminderId(); - sptr bundleOption = FindNotificationBundleOption(reminderId); + sptr bundleOption = reminder->GetNotificationBundleOption(); sptr notificationRequest = reminder->GetNotificationRequest(); if (bundleOption == nullptr) { ANSR_LOGE("Get bundle option fail, reminderId=%{public}d", reminderId); @@ -885,7 +844,7 @@ void ReminderDataManager::TerminateAlerting(const sptr &reminde // Set the notification SoundEnabled and VibrationEnabled by soltType advancedNotificationService_->SetRequestBySlotType(notificationRequest, bundleOption); advancedNotificationService_->PublishPreparedNotification(notificationRequest, bundleOption); - store_->UpdateOrInsert(reminder, FindNotificationBundleOption(reminder->GetReminderId())); + store_->UpdateOrInsert(reminder, bundleOption); } void ReminderDataManager::UpdateAndSaveReminderLocked( @@ -903,13 +862,7 @@ void ReminderDataManager::UpdateAndSaveReminderLocked( ANSR_LOGW("now publish reminder is expired. reminder is =%{public}s", reminder->Dump().c_str()); reminder->SetExpired(true); } - int32_t reminderId = reminder->GetReminderId(); - auto ret = notificationBundleOptionMap_.insert( - std::pair>(reminderId, bundleOption)); - if (!ret.second) { - ANSR_LOGE("Containers add to map error"); - return; - } + reminder->SetNotificationBundleOption(bundleOption); reminderVector_.push_back(reminder); totalCount_++; store_->UpdateOrInsert(reminder, bundleOption); @@ -926,7 +879,7 @@ bool ReminderDataManager::ShouldAlert(const sptr &reminder) con return false; } int32_t reminderId = reminder->GetReminderId(); - sptr bundleOption = FindNotificationBundleOption(reminderId); + sptr bundleOption = reminder->GetNotificationBundleOption(); if (bundleOption == nullptr) { ANSR_LOGD("The reminder (reminderId=%{public}d) is silent", reminderId); return false; @@ -1082,6 +1035,15 @@ bool ReminderDataManager::StartExtensionAbility(const sptr &rem void ReminderDataManager::AsyncStartExtensionAbility(const sptr &reminder, int32_t times) { + auto manager = ReminderDataManager::GetInstance(); + if (manager == nullptr) { + ANSR_LOGW("ReminderDataManager is nullptr."); + return; + } + if (!manager->IsSystemReady()) { + ANSR_LOGW("bundle service or ability service not ready."); + return; + } if (!reminder->IsSystemApp()) { ANSR_LOGI("Start extension ability failed, is not system app"); return; @@ -1103,7 +1065,7 @@ void ReminderDataManager::ShowReminder(const sptr &reminder, co ANSR_LOGD("Show the reminder(Play sound: %{public}d), %{public}s", static_cast(isNeedToPlaySound), reminder->Dump().c_str()); int32_t reminderId = reminder->GetReminderId(); - sptr bundleOption = FindNotificationBundleOption(reminderId); + sptr bundleOption = reminder->GetNotificationBundleOption(); sptr notificationRequest = reminder->GetNotificationRequest(); if (bundleOption == nullptr) { ANSR_LOGE("Get bundle option fail, reminderId=%{public}d", reminderId); @@ -1112,13 +1074,13 @@ void ReminderDataManager::ShowReminder(const sptr &reminder, co if (advancedNotificationService_ == nullptr) { ANSR_LOGE("ShowReminder fail"); reminder->OnShow(false, isSysTimeChanged, false); - store_->UpdateOrInsert(reminder, FindNotificationBundleOption(reminder->GetReminderId())); + store_->UpdateOrInsert(reminder, bundleOption); return; } if (!IsAllowedNotify(reminder)) { ANSR_LOGE("Not allow to notify."); reminder->OnShow(false, isSysTimeChanged, false); - store_->UpdateOrInsert(reminder, FindNotificationBundleOption(reminder->GetReminderId())); + store_->UpdateOrInsert(reminder, bundleOption); return; } ReportSysEvent(reminder); @@ -1147,7 +1109,7 @@ void ReminderDataManager::ShowReminder(const sptr &reminder, co } HandleSameNotificationIdShowing(reminder); } - store_->UpdateOrInsert(reminder, FindNotificationBundleOption(reminder->GetReminderId())); + store_->UpdateOrInsert(reminder, bundleOption); if (isNeedToStartNext) { StartRecentReminder(); @@ -1156,12 +1118,6 @@ void ReminderDataManager::ShowReminder(const sptr &reminder, co void ReminderDataManager::UpdateNotification(const sptr &reminder, bool isSnooze) { - int32_t reminderId = reminder->GetReminderId(); - sptr bundleOption = FindNotificationBundleOption(reminderId); - if (bundleOption == nullptr) { - ANSR_LOGE("Get bundle option fail, reminderId=%{public}d", reminderId); - return; - } if (isSnooze) { reminder->UpdateNotificationRequest(ReminderRequest::UpdateNotificationType::COMMON, "snooze"); } else { @@ -1205,10 +1161,10 @@ void ReminderDataManager::SnoozeReminderImpl(sptr &reminder) StopTimerLocked(TimerType::ALERTING_TIMER); } reminder->OnSnooze(); - store_->UpdateOrInsert(reminder, FindNotificationBundleOption(reminder->GetReminderId())); + store_->UpdateOrInsert(reminder, reminder->GetNotificationBundleOption()); // 2) Show the notification dialog in the systemUI - sptr bundleOption = FindNotificationBundleOption(reminderId); + sptr bundleOption = reminder->GetNotificationBundleOption(); sptr notificationRequest = reminder->GetNotificationRequest(); if (bundleOption == nullptr) { ANSR_LOGW("snoozeReminder, invalid bundle option"); @@ -1242,14 +1198,14 @@ void ReminderDataManager::StartRecentReminder() { std::lock_guard locker(ReminderDataManager::ACTIVE_MUTEX); activeReminder_->OnStop(); - store_->UpdateOrInsert(activeReminder_, FindNotificationBundleOption(activeReminderId_)); + store_->UpdateOrInsert(activeReminder_, activeReminder_->GetNotificationBundleOption()); } StopTimerLocked(TimerType::TRIGGER_TIMER); } ANSR_LOGI("Start recent reminder"); StartTimerLocked(reminder, TimerType::TRIGGER_TIMER); reminder->OnStart(); - store_->UpdateOrInsert(reminder, FindNotificationBundleOption(reminder->GetReminderId())); + store_->UpdateOrInsert(reminder, reminder->GetNotificationBundleOption()); } void ReminderDataManager::StopAlertingReminder(const sptr &reminder) @@ -1274,13 +1230,7 @@ std::string ReminderDataManager::Dump() const if ((*it)->IsExpired()) { continue; } - int32_t reminderId = (*it)->GetReminderId(); - auto mit = notificationBundleOptionMap_.find(reminderId); - if (mit == notificationBundleOptionMap_.end()) { - ANSR_LOGE("Dump get notificationBundleOption(reminderId=%{public}d) fail", reminderId); - continue; - } - std::string bundleName = mit->second->GetBundleName(); + std::string bundleName = (*it)->GetBundleName(); auto val = bundleNameMap.find(bundleName); if (val == bundleNameMap.end()) { std::vector> reminders; @@ -1340,12 +1290,6 @@ sptr ReminderDataManager::GetRecentReminderLocked() } int32_t reminderId = (*it)->GetReminderId(); ANSR_LOGD("Containers(vector) remove. reminderId=%{public}d", reminderId); - auto mit = notificationBundleOptionMap_.find(reminderId); - if (mit == notificationBundleOptionMap_.end()) { - ANSR_LOGE("Remove notificationBundleOption(reminderId=%{public}d) fail", reminderId); - } else { - notificationBundleOptionMap_.erase(mit); - } it = reminderVector_.erase(it); totalCount_--; store_->Delete(reminderId); @@ -1395,10 +1339,10 @@ sptr ReminderDataManager::HandleRefreshReminder(const uint8_t & if (triggerTimeBefore != triggerTimeAfter || reminder->GetReminderId() == alertingReminderId_) { CloseReminder(reminder, true); } - store_->UpdateOrInsert(reminder, FindNotificationBundleOption(reminder->GetReminderId())); + store_->UpdateOrInsert(reminder, reminder->GetNotificationBundleOption()); return nullptr; } - store_->UpdateOrInsert(reminder, FindNotificationBundleOption(reminder->GetReminderId())); + store_->UpdateOrInsert(reminder, reminder->GetNotificationBundleOption()); return reminder; } @@ -1408,8 +1352,8 @@ void ReminderDataManager::HandleSameNotificationIdShowing(const sptrGetNotificationId(); ANSR_LOGD("HandleSameNotificationIdShowing notificationId=%{public}d", notificationId); int32_t curReminderId = reminder->GetReminderId(); - auto mit = notificationBundleOptionMap_.find(curReminderId); - if (mit == notificationBundleOptionMap_.end()) { + sptr option1 = reminder->GetNotificationBundleOption(); + if (option1 == nullptr) { ANSR_LOGE("Error occur when get bundle option, reminderId=%{public}d", curReminderId); return; } @@ -1422,18 +1366,18 @@ void ReminderDataManager::HandleSameNotificationIdShowing(const sptrIsShowing()) { continue; } - sptr bundleOption = FindNotificationBundleOption(tmpId); + sptr bundleOption = (*it)->GetNotificationBundleOption(); if (bundleOption == nullptr) { ANSR_LOGW("Get notificationBundleOption(reminderId=%{public}d) fail", tmpId); continue; } - if (notificationId == (*it)->GetNotificationId() && IsBelongToSameApp(bundleOption, mit->second)) { + if (notificationId == (*it)->GetNotificationId() && IsBelongToSameApp(bundleOption, option1)) { if ((*it)->IsAlerting()) { StopAlertingReminder(*it); } (*it)->OnSameNotificationIdCovered(); RemoveFromShowedReminders(*it); - store_->UpdateOrInsert((*it), FindNotificationBundleOption((*it)->GetReminderId())); + store_->UpdateOrInsert((*it), bundleOption); } } } @@ -1562,14 +1506,13 @@ bool ReminderDataManager::IsAllowedNotify(const sptr &reminder) if (reminder == nullptr) { return false; } - int32_t reminderId = reminder->GetReminderId(); - auto mit = notificationBundleOptionMap_.find(reminderId); - if (mit == notificationBundleOptionMap_.end()) { - ANSR_LOGE("Get bundle option occur error, reminderId=%{public}d", reminderId); + auto option = reminder->GetNotificationBundleOption(); + if (option == nullptr) { + ANSR_LOGE("Get bundle option occur error, reminderId=%{public}d", reminder->GetReminderId()); return false; } bool isAllowed = false; - ErrCode errCode = advancedNotificationService_->IsSpecialBundleAllowedNotify(mit->second, isAllowed); + ErrCode errCode = advancedNotificationService_->IsSpecialBundleAllowedNotify(option, isAllowed); if (errCode != ERR_OK) { ANSR_LOGE("Failed to call IsSpecialBundleAllowedNotify, errCode=%{public}d", errCode); return false; @@ -1622,13 +1565,7 @@ void ReminderDataManager::LoadReminderFromDb() } bundleOption->SetBundleName((*it)->GetBundleName()); bundleOption->SetUid((*it)->GetUid()); - int32_t reminderId = (*it)->GetReminderId(); - auto ret = notificationBundleOptionMap_.insert( - std::pair>(reminderId, bundleOption)); - if (!ret.second) { - ANSR_LOGE("Containers add to map error"); - continue; - } + (*it)->SetNotificationBundleOption(bundleOption); } totalCount_ = static_cast(reminderVector_.size()); ReminderRequest::GLOBAL_ID = store_->GetMaxId() + 1; @@ -1712,7 +1649,7 @@ std::string ReminderDataManager::GetSoundUri(const sptr &remind ANSR_LOGE("Ans instance is null."); return uri.GetSchemeSpecificPart(); } - sptr bundle = FindNotificationBundleOption(reminder->GetReminderId()); + sptr bundle = reminder->GetNotificationBundleOption(); std::vector> slots; ErrCode errCode = advancedNotificationService_->GetSlotsByBundle(bundle, slots); if (errCode != ERR_OK) { @@ -1807,13 +1744,6 @@ void ReminderDataManager::RemoveReminderLocked(const int32_t &reminderId) ++it; } } - auto it = notificationBundleOptionMap_.find(reminderId); - if (it == notificationBundleOptionMap_.end()) { - ANSR_LOGE("Remove notificationBundleOption(reminderId=%{public}d) fail", reminderId); - } else { - ANSR_LOGD("Containers(map) remove. reminderId=%{public}d", reminderId); - notificationBundleOptionMap_.erase(it); - } } void ReminderDataManager::StartTimerLocked(const sptr &reminderRequest, TimerType type) @@ -2056,7 +1986,7 @@ std::shared_ptr ReminderDataManager::GetResou return resourceManager; } -void ReminderDataManager::UpdateReminderLanguage(const int32_t uid, +void ReminderDataManager::UpdateReminderLanguageLocked(const int32_t uid, const std::vector>& reminders) { // obtains the bundle info by bundle name @@ -2074,30 +2004,23 @@ void ReminderDataManager::UpdateReminderLanguage(const int32_t uid, } // update action button title for (auto reminder : reminders) { + std::lock_guard lock(ReminderDataManager::MUTEX); reminder->OnLanguageChange(resourceMgr); } } -void ReminderDataManager::UpdateReminderLanguageLocked(const sptr &reminder) -{ - std::lock_guard lock(ReminderDataManager::MUTEX); - std::vector> reminders; - reminders.push_back(reminder); - UpdateReminderLanguage(reminder->GetUid(), reminders); -} - void ReminderDataManager::OnLanguageChanged() { ANSR_LOGI("System language config changed start."); + std::unordered_map>> reminders; { std::lock_guard lock(ReminderDataManager::MUTEX); - std::unordered_map>> reminders; for (auto it = reminderVector_.begin(); it != reminderVector_.end(); ++it) { reminders[(*it)->GetUid()].push_back((*it)); } - for (auto& each : reminders) { - UpdateReminderLanguage(each.first, each.second); - } + } + for (auto& each : reminders) { + UpdateReminderLanguageLocked(each.first, each.second); } std::vector> showedReminder; { diff --git a/services/ans/src/reminder_data_manager_inner.cpp b/services/ans/src/reminder_data_manager_inner.cpp index dd79e6ec2..46284fe3a 100644 --- a/services/ans/src/reminder_data_manager_inner.cpp +++ b/services/ans/src/reminder_data_manager_inner.cpp @@ -52,6 +52,15 @@ namespace OHOS { namespace Notification { +namespace { +constexpr int32_t ALL_SA_READY_FLAG = 2; // bundle service and ability service ready. +} + +bool ReminderDataManager::IsSystemReady() +{ + return saReadyFlag_ >= ALL_SA_READY_FLAG; +} + bool ReminderDataManager::IsActionButtonDataShareValid(const sptr& reminder, const uint32_t callerTokenId) { @@ -97,6 +106,16 @@ void ReminderDataManager::HandleAutoDeleteReminder(const int32_t notificationId, StartRecentReminder(); } +void ReminderDataManager::OnBundleMgrServiceStart() +{ + saReadyFlag_.fetch_add(1); +} + +void ReminderDataManager::OnAbilityMgrServiceStart() +{ + saReadyFlag_.fetch_add(1); +} + bool ReminderDataManager::GetCustomRingFileDesc(const sptr& reminder, Global::Resource::ResourceManager::RawFileDescriptor& desc) { diff --git a/services/ans/src/reminder_event_manager.cpp b/services/ans/src/reminder_event_manager.cpp index e282d02ee..87c6284b8 100644 --- a/services/ans/src/reminder_event_manager.cpp +++ b/services/ans/src/reminder_event_manager.cpp @@ -100,6 +100,13 @@ void ReminderEventManager::SubscribeSystemAbility(std::shared_ptr abilityMgrStatusListener + = new (std::nothrow) SystemAbilityStatusChangeListener(reminderDataManager); + if (abilityMgrStatusListener == nullptr) { + ANSR_LOGE("Failed to create abilityMgrStatusListener due to no memory."); + return; + } sptr samgrProxy = SystemAbilityManagerClient::GetInstance().GetSystemAbilityManager(); if (samgrProxy == nullptr) { @@ -114,6 +121,10 @@ void ReminderEventManager::SubscribeSystemAbility(std::shared_ptrSubscribeSystemAbility(ABILITY_MGR_SERVICE_ID, abilityMgrStatusListener); + if (ret != ERR_OK) { + ANSR_LOGE("subscribe system ability id: %{public}d failed", ABILITY_MGR_SERVICE_ID); + } } ReminderEventManager::ReminderEventSubscriber::ReminderEventSubscriber( @@ -251,11 +262,15 @@ void ReminderEventManager::SystemAbilityStatusChangeListener::OnAddSystemAbility switch (systemAbilityId) { case BUNDLE_MGR_SERVICE_SYS_ABILITY_ID: ANSR_LOGD("OnAddSystemAbilityInner: BUNDLE_MGR_SERVICE_SYS_ABILITY"); - reminderDataManager_->OnServiceStart(); + reminderDataManager_->OnBundleMgrServiceStart(); break; case APP_MGR_SERVICE_ID: ANSR_LOGD("OnAddSystemAbilityInner: APP_MGR_SERVICE"); break; + case ABILITY_MGR_SERVICE_ID: + ANSR_LOGD("OnAddSystemAbilityInner ABILITY_MGR_SERVICE_ID"); + reminderDataManager_->OnAbilityMgrServiceStart(); + break; default: break; } @@ -273,6 +288,9 @@ void ReminderEventManager::SystemAbilityStatusChangeListener::OnRemoveSystemAbil ANSR_LOGD("OnRemoveSystemAbilityInner: APP_MGR_SERVICE"); reminderDataManager_->OnRemoveAppMgr(); break; + case ABILITY_MGR_SERVICE_ID: + ANSR_LOGD("OnRemoveSystemAbilityInner ABILITY_MGR_SERVICE_ID"); + break; default: break; } diff --git a/services/ans/test/unittest/reminder_data_manager_test.cpp b/services/ans/test/unittest/reminder_data_manager_test.cpp index 85e78560d..5ca3295b1 100644 --- a/services/ans/test/unittest/reminder_data_manager_test.cpp +++ b/services/ans/test/unittest/reminder_data_manager_test.cpp @@ -118,7 +118,8 @@ HWTEST_F(ReminderDataManagerTest, ReminderDataManagerTest_003, Level1) manager->alertingReminderId_ = -1; manager->OnUserSwitch(0); manager->OnUserRemove(0); - manager->OnServiceStart(); + manager->OnBundleMgrServiceStart(); + manager->OnAbilityMgrServiceStart(); system("rm -rf /data/service/el1/public/notification/"); EXPECT_TRUE(manager != nullptr); } @@ -141,7 +142,6 @@ HWTEST_F(ReminderDataManagerTest, ReminderDataManagerTest_004, Level1) manager->reminderVector_.push_back(reminder); manager->FindReminderRequestLocked(10, ""); option->SetBundleName("test"); - manager->notificationBundleOptionMap_[10] = option; manager->FindReminderRequestLocked(10, ""); manager->FindReminderRequestLocked(10, "test"); system("rm -rf /data/service/el1/public/notification/"); @@ -286,8 +286,8 @@ HWTEST_F(ReminderDataManagerTest, ReminderDataManagerTest_011, Level1) sptr reminder(new ReminderRequestTimer(10)); reminder->SetReminderId(0); sptr option(new NotificationBundleOption()); - manager->notificationBundleOptionMap_[10] = option; manager->ShowReminder(reminder, true, true, true, true); + reminder->SetNotificationBundleOption(option); reminder->SetReminderId(10); manager->ShowReminder(reminder, true, true, true, true); manager->ShowReminder(reminder, true, true, true, true); diff --git a/test/fuzztest/reminderdatamanager_fuzzer/reminderdatamanager_fuzzer.cpp b/test/fuzztest/reminderdatamanager_fuzzer/reminderdatamanager_fuzzer.cpp index 53650069d..221f8d765 100644 --- a/test/fuzztest/reminderdatamanager_fuzzer/reminderdatamanager_fuzzer.cpp +++ b/test/fuzztest/reminderdatamanager_fuzzer/reminderdatamanager_fuzzer.cpp @@ -56,7 +56,8 @@ namespace OHOS { manager->RegisterConfigurationObserver(); manager->OnUserRemove(userId); - manager->OnServiceStart(); + manager->OnBundleMgrServiceStart(); + manager->OnAbilityMgrServiceStart(); manager->OnUserSwitch(userId); manager->OnProcessDiedLocked(option); manager->RefreshRemindersDueToSysTimeChange(type); @@ -67,7 +68,6 @@ namespace OHOS { manager->HandleCustomButtonClick(want); manager->ClickReminder(want); manager->TerminateAlerting(want); - manager->UpdateReminderLanguageLocked(reminder); return true; } @@ -115,7 +115,6 @@ namespace OHOS { manager->PublishReminder(reminder, option); manager->FindReminderRequestLocked(reminderId); manager->FindReminderRequestLocked(reminderId, bundleName); - manager->FindNotificationBundleOption(reminderId); manager->GetRecentReminderLocked(); manager->HandleImmediatelyShow(immediatelyReminders, value); manager->HandleExtensionReminder(extensionReminders); -- Gitee From 1fc88e37343c50224f32c204e2a3d8acc1f17efc Mon Sep 17 00:00:00 2001 From: xdongs Date: Tue, 8 Oct 2024 18:23:07 +0800 Subject: [PATCH 090/167] update Signed-off-by: z30053788 Change-Id: I10b96edb319e512f8dc10092869be3703c1855a8 --- .../NotificationServiceExtAbility.ts | 125 ++++++++---------- .../entry/src/main/ets/common/constant.ets | 12 +- .../src/main/ets/pages/notificationDialog.ets | 76 +++++------ 3 files changed, 102 insertions(+), 111 deletions(-) diff --git a/services/dialog_ui/enable_notification_dialog/entry/src/main/ets/ServiceExtAbility/NotificationServiceExtAbility.ts b/services/dialog_ui/enable_notification_dialog/entry/src/main/ets/ServiceExtAbility/NotificationServiceExtAbility.ts index adf1583b8..d5648094f 100644 --- a/services/dialog_ui/enable_notification_dialog/entry/src/main/ets/ServiceExtAbility/NotificationServiceExtAbility.ts +++ b/services/dialog_ui/enable_notification_dialog/entry/src/main/ets/ServiceExtAbility/NotificationServiceExtAbility.ts @@ -31,12 +31,11 @@ import Constants from '../common/constant'; const TAG = 'NotificationDialog_Service '; -const UPDATE_INIT = -1; +const UPDATE_INIT = 1; const UPDATE_NUM = 1; const UPDATE_BOUNDARY = 100; - -let systemLanguage: string; +let eventSubscriber:CommonEventManager.CommonEventSubscriber; const enableNotificationDialogDestroyedEvent = { eventId: 1, @@ -98,49 +97,6 @@ export class EnableNotificationDialog { this.extensionWindow = undefined; } - async createWindow(windowType: window.WindowType, context, displayRect): Promise { - try { - let winArgs = { - 'name': `${EnableNotificationDialog.ENABLE_NOTIFICATION_DIALOG_NAME}${this.id}`, - 'windowType': windowType, - 'ctx': context - }; - let win = await window.createWindow(winArgs); - this.window = win; - let shouldHide = true; - - if (windowType === window.WindowType.TYPE_DIALOG) { - await win.bindDialogTarget(this.want.parameters.callerToken['value'], - async (): Promise => { - console.info(TAG, `window ${this.id} died`); - await this.destroyException(); - } - ); - } - - this.storage = new LocalStorage({ - 'dialog': this - }); - await win.moveWindowTo(displayRect.left, displayRect.top); - await win.resize(displayRect.width, displayRect.height); - await win.loadContent(EnableNotificationDialog.DIALOG_PATH, this.storage); - try { - await win.hideNonSystemFloatingWindows(shouldHide); - } catch (err) { - console.error(TAG, 'window hideNonSystemFloatingWindows failed!'); - } - await win.setWindowBackgroundColor(EnableNotificationDialog.TRANSPARANT_COLOR); - await win.showWindow(); - await win.setWindowLayoutFullScreen(true); - } catch (err) { - if (this.window !== undefined) { - await this.destroyWindow(); - } - console.error(TAG, 'window create failed!'); - throw new Error('Failed to create window'); - } - } - async createUiExtensionWindow(session: UIExtensionContentSession, stageModel: boolean): Promise { try { @@ -188,9 +144,10 @@ export class EnableNotificationDialog { }; let subWindow = await extensionWindow.createSubWindowWithOptions('subWindowForHost' + Date(), subWindowOpts); this.subWindow = subWindow; - let dis = display.getDefaultDisplaySync(); - await subWindow?.resize(dis.width, dis.height); - console.info(TAG, `size : ${dis.width} ${dis.height}`); + let windowRect = extensionWindow.properties?.uiExtensionHostWindowProxyRect; + await subWindow.moveWindowTo(windowRect?.left, windowRect?.top); + await subWindow.resize(windowRect?.width, windowRect?.height); + console.info(TAG, `size : ${windowRect.left} ${windowRect.top} ${windowRect.width} ${windowRect.height}`); await subWindow.loadContent(path, this.storage); try { await subWindow.hideNonSystemFloatingWindows(true); @@ -253,26 +210,12 @@ export class EnableNotificationDialog { class NotificationDialogServiceExtensionAbility extends UIExtensionAbility { - onConfigurationUpdate(newConfig): void { - console.log(TAG, 'onConfigurationUpdate'); - if (systemLanguage !== newConfig.language) { - console.log(TAG, `onConfigurationUpdate newConfig is ${JSON.stringify(newConfig)}`); - systemLanguage = newConfig.language; - let isUpdate:number = AppStorage.get('isUpdate'); - if (isUpdate === undefined || isUpdate > UPDATE_BOUNDARY) { - AppStorage.setOrCreate('isUpdate', UPDATE_NUM); - } else { - AppStorage.setOrCreate('isUpdate', ++isUpdate); - } - } - } - - onCreate() { console.log(TAG, `UIExtAbility onCreate`); AppStorage.setOrCreate('context', this.context); AppStorage.setOrCreate('isUpdate', UPDATE_INIT); - systemLanguage = this.context.config.language; + AppStorage.setOrCreate('clicked', false); + this.subscribe(); } @@ -293,7 +236,6 @@ class NotificationDialogServiceExtensionAbility extends UIExtensionAbility { `uid ${want.parameters.bundleUid}`); let dialog = new EnableNotificationDialog(1, want, stageModel); await dialog.createUiExtensionWindow(session, stageModel); - AppStorage.setOrCreate('clicked', false); AppStorage.setOrCreate('dialog', dialog); } catch (err) { console.error(TAG, `Failed to handle onSessionCreate`); @@ -348,10 +290,59 @@ class NotificationDialogServiceExtensionAbility extends UIExtensionAbility { } } - onDestroy() { + async onDestroy() { console.info(TAG, 'UIExtAbility onDestroy.'); + await this.unsubscribe(); + await this.sleep(500); this.context.terminateSelf(); } + + async sleep(ms: number): Promise { + return new Promise(resolve => setTimeout(resolve, ms)); + } + + async subscribe() { + CommonEventManager.createSubscriber( + { events: ['usual.event.BUNDLE_RESOURCES_CHANGED'] }, (err, subscriber) => { + if (err?.code) { + console.error(TAG, `createSubscriber callBack err = ${JSON.stringify(err)}`); + } else { + eventSubscriber = subscriber; + console.log(TAG, "create subscriber succeed"); + if (eventSubscriber != null) { + console.log(TAG, "subscriber subscribe BUNDLE_RESOURCES_CHANGED event"); + CommonEventManager.subscribe(eventSubscriber, (err, data) => { + if (err?.code) { + console.error(TAG, `subscribe callBack err= ${JSON.stringify(err)}`); + } else { + console.log(TAG, `subscribe callBack data= ${JSON.stringify(data)}`); + if(data.parameters?.bundleResourceChangeType == 1){ + console.log(TAG, `BUNDLE_RESOURCES_CHANGED-language change`); + let isUpdate:number = AppStorage.get('isUpdate'); + if (isUpdate === undefined || isUpdate > UPDATE_BOUNDARY) { + AppStorage.setOrCreate('isUpdate', UPDATE_NUM); + } else { + AppStorage.setOrCreate('isUpdate', ++isUpdate); + } + } + } + }) + } else { + console.info(TAG, "need create subscriber"); + } + } + }); + } + + async unsubscribe() { + try { + if (eventSubscriber != null) { + CommonEventManager.unsubscribe(eventSubscriber, (err) => {}); + } + } catch (err) { + console.info("ubsubscribe fail"); + } + } } diff --git a/services/dialog_ui/enable_notification_dialog/entry/src/main/ets/common/constant.ets b/services/dialog_ui/enable_notification_dialog/entry/src/main/ets/common/constant.ets index 721c6021c..a1f3d2be6 100644 --- a/services/dialog_ui/enable_notification_dialog/entry/src/main/ets/common/constant.ets +++ b/services/dialog_ui/enable_notification_dialog/entry/src/main/ets/common/constant.ets @@ -125,12 +125,12 @@ export default class Constants { static DIALOG_REQ_LINE_HEIGHT = 24; // description text of dialog - static DIALOG_DESP_FONT_SIZE = 16; - static DIALOG_DESP_MARGIN_TOP = 0; - static DIALOG_DESP_MARGIN_LEFT = 24; - static DIALOG_DESP_MARGIN_RIGHT = 24; - static DIALOG_DESP_MARGIN_BOTTOM = 12; - static DIALOG_DESP_LINE_HEIGHT = 21; + public static DIALOG_DESP_FONT_SIZE = 16; + public static DIALOG_DESP_MARGIN_TOP = 0; + public static DIALOG_DESP_MARGIN_LEFT = 24; + public static DIALOG_DESP_MARGIN_RIGHT = 24; + public static DIALOG_DESP_MARGIN_BOTTOM = 8; + public static DIALOG_DESP_LINE_HEIGHT = 21; static BUTTON_MARGIN_TOP = 8; static BUTTON_MARGIN_LEFT = 16; diff --git a/services/dialog_ui/enable_notification_dialog/entry/src/main/ets/pages/notificationDialog.ets b/services/dialog_ui/enable_notification_dialog/entry/src/main/ets/pages/notificationDialog.ets index 219a61a67..19f87f2c3 100644 --- a/services/dialog_ui/enable_notification_dialog/entry/src/main/ets/pages/notificationDialog.ets +++ b/services/dialog_ui/enable_notification_dialog/entry/src/main/ets/pages/notificationDialog.ets @@ -35,39 +35,36 @@ const bottomPopoverTypes = ['default', 'phone']; let storage = LocalStorage.getShared(); @Extend(Button) function rightCustomizeButton() { - .backgroundColor($r('app.color.dialog_bg')) + .backgroundColor(Color.Transparent) .fontColor($r('app.color.button_text')) .fontSize(Constants.TEXT_MIDDLE_FONT_SIZE) .fontWeight(FontWeight.Medium) .height(Constants.BUTTON_HEIGHT) .flexGrow(Constants.FLEX_GROW) - .margin({ - left: Constants.BUTTON_LEFT - }) + .width('50%') } @Extend(Button) function leftCustomizeButton() { - .backgroundColor($r('app.color.dialog_bg')) + .backgroundColor(Color.Transparent) .fontColor($r('app.color.button_text')) .fontSize(Constants.TEXT_MIDDLE_FONT_SIZE) .fontWeight(FontWeight.Medium) .height(Constants.BUTTON_HEIGHT) .flexGrow(Constants.FLEX_GROW) - .margin({ - right: Constants.BUTTON_RIGHT - }) + .width('50%') } @Entry(storage) @Component struct NotificationDialogPage { - @StorageLink('isUpdate') isUpdate: number = -1; + @StorageLink('isUpdate') isUpdate: number = 0; privacyDialogController: CustomDialogController = new CustomDialogController({ builder: PermissionDialog({ isUpdate: $isUpdate }), autoCancel: false, alignment: DialogAlignment.Center, customStyle: true, + maskColor: $r('app.color.mask_thin'), onWillDismiss: (dismissDialogAction: DismissDialogAction) => { console.info(TAG, `dialog onWillDismiss reason= : ${JSON.stringify(dismissDialogAction.reason)}`); } @@ -80,7 +77,6 @@ struct NotificationDialogPage { } onPageShow() { - this.isUpdate++; } } @@ -101,14 +97,16 @@ struct PermissionDialog { offset: {xs: Constants.XS_OFFSET, sm: Constants.SM_OFFSET, md: Constants.DIALOG_MD_OFFSET, lg: Constants.DIALOG_LG_OFFSET} }) { Flex({ justifyContent: FlexAlign.Center, alignItems: this.isBottomPopover ? ItemAlign.End : ItemAlign.Center }) { Column() { - Image(permission.icon) - .width(Constants.DIALOG_ICON_WIDTH) - .height(Constants.DIALOG_ICON_HEIGHT) - .margin({ - top: Constants.DIALOG_ICON_MARGIN_TOP - }) Scroll() { Column() { + Row() { + Image(permission.icon) + .width(Constants.DIALOG_ICON_WIDTH) + .height(Constants.DIALOG_ICON_HEIGHT) + .margin({ + top: Constants.DIALOG_ICON_MARGIN_TOP + }) + } Row() { Flex({ justifyContent: FlexAlign.Center }) { Text() { @@ -118,6 +116,8 @@ struct PermissionDialog { .fontColor($r('app.color.text_primary')) .fontWeight(FontWeight.Bold) .lineHeight(Constants.DIALOG_REQ_LINE_HEIGHT) + .maxLines(2) + .textOverflow({overflow: TextOverflow.Ellipsis}) .margin({ top: Constants.DIALOG_REQ_MARGIN_TOP, bottom:Constants.DIALOG_REQ_MARGIN_BUTTOM, @@ -144,35 +144,35 @@ struct PermissionDialog { }) } } + Row() { + Flex({ justifyContent: FlexAlign.SpaceBetween, alignItems: ItemAlign.Center }) { + Button($r('app.string.BAN')) + .onClick(async (): Promise => { + await this.enableNotification(false); + }) + .leftCustomizeButton() + Divider() + .color($r('app.color.comp_divider')) + .vertical(true) + .height(Constants.DIVIDER_HEIGHT) + .strokeWidth(Constants.DIVIDER_WIDTH) + .margin({left: Constants.BUTTON_LEFT, right: Constants.BUTTON_RIGHT}) + Button($r('app.string.ALLOW')) + .onClick(async (): Promise => { + await this.enableNotification(true); + }) + .rightCustomizeButton() + } + .margin({ left: Constants.BUTTON_MARGIN_LEFT, right: Constants.BUTTON_MARGIN_RIGHT }) + } } } .constraintSize({ maxHeight: Constants.MAXIMUM_HEADER_HEIGHT }) - Row() { - Flex({ justifyContent: FlexAlign.SpaceBetween, alignItems: ItemAlign.Center }) { - Button($r('app.string.BAN')) - .onClick(async (): Promise => { - await this.enableNotification(false); - }) - .leftCustomizeButton() - Divider() - .color($r('app.color.comp_divider')) - .vertical(true) - .height(Constants.DIVIDER_HEIGHT) - .strokeWidth(Constants.DIVIDER_WIDTH) - Button($r('app.string.ALLOW')) - .onClick(async (): Promise => { - await this.enableNotification(true); - }) - .rightCustomizeButton() - } - .margin({ left: Constants.BUTTON_MARGIN_LEFT, right: Constants.BUTTON_MARGIN_RIGHT }) - } } - .backgroundColor($r('app.color.dialog_bg')) .borderRadius(Constants.DIALOG_PRIVACY_BORDER_RADIUS) + .backgroundBlurStyle(BlurStyle.COMPONENT_ULTRA_THICK) .width(Constants.FULL_WIDTH) .padding({ bottom: Constants.DIALOG_PADDING_BOTTOM }) - .margin({ bottom: $r('sys.float.ohos_id_dialog_margin_bottom') }) .clip(true) } .width(Constants.FULL_WIDTH) -- Gitee From 0e08540ad43f86dea8a797bd1e2e456db90385e9 Mon Sep 17 00:00:00 2001 From: xdongs Date: Wed, 9 Oct 2024 15:42:23 +0800 Subject: [PATCH 091/167] =?UTF-8?q?=E5=88=A0=E9=99=A4=E5=BC=B9=E7=AA=97?= =?UTF-8?q?=E7=BC=93=E5=AD=98?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: xdongs --- frameworks/ans/src/notification_helper.cpp | 5 ++ .../core/include/ans_manager_interface.h | 7 +++ frameworks/core/include/ans_manager_proxy.h | 7 +++ frameworks/core/include/ans_manager_stub.h | 8 +++ frameworks/core/include/ans_notification.h | 7 +++ ..._notification_service_ipc_interface_code.h | 1 + frameworks/core/src/ans_manager_proxy.cpp | 22 +++++++ frameworks/core/src/ans_manager_stub.cpp | 14 +++++ .../core/src/ans_manager_stub_invalid.cpp | 6 ++ frameworks/core/src/ans_notification.cpp | 11 ++++ .../manager/napi_enable_notification.h | 1 - .../src/manager/napi_enable_notification.cpp | 29 +-------- interfaces/inner_api/notification_helper.h | 7 +++ .../include/advanced_notification_service.h | 9 +++ .../ans/include/notification_dialog_manager.h | 10 +++- .../ans/include/system_dialog_connect_stb.h | 2 - .../advanced_notification_publish_service.cpp | 23 +++++++ .../ans/src/system_dialog_connect_stb.cpp | 60 +++++++------------ 18 files changed, 157 insertions(+), 72 deletions(-) diff --git a/frameworks/ans/src/notification_helper.cpp b/frameworks/ans/src/notification_helper.cpp index e55e7fcbf..d0f112e0d 100644 --- a/frameworks/ans/src/notification_helper.cpp +++ b/frameworks/ans/src/notification_helper.cpp @@ -170,6 +170,11 @@ ErrCode NotificationHelper::CanPopEnableNotificationDialog(sptr::GetInstance()->RemoveEnableNotificationDialog(); +} + ErrCode NotificationHelper::RequestEnableNotification(std::string &deviceId, sptr &hostClient, sptr &callerToken) diff --git a/frameworks/core/include/ans_manager_interface.h b/frameworks/core/include/ans_manager_interface.h index 06893561b..15702b01d 100644 --- a/frameworks/core/include/ans_manager_interface.h +++ b/frameworks/core/include/ans_manager_interface.h @@ -509,6 +509,13 @@ public: virtual ErrCode CanPopEnableNotificationDialog(const sptr &callback, bool &canPop, std::string &bundleName) = 0; + /** + * @brief remove enable notification dialog. + * + * @return Returns remove dialog result. + */ + virtual ErrCode RemoveEnableNotificationDialog() = 0; + /** * @brief Checks whether notifications are allowed for a specific bundle. * diff --git a/frameworks/core/include/ans_manager_proxy.h b/frameworks/core/include/ans_manager_proxy.h index d6bc0135d..1267fa403 100644 --- a/frameworks/core/include/ans_manager_proxy.h +++ b/frameworks/core/include/ans_manager_proxy.h @@ -497,6 +497,13 @@ public: ErrCode CanPopEnableNotificationDialog(const sptr &callback, bool &canPop, std::string &bundleName) override; + /** + * @brief remove enable notification dialog. + * + * @return Returns remove dialog result. + */ + ErrCode RemoveEnableNotificationDialog() override; + /** * @brief Checks whether notifications are allowed for a specific bundle. * diff --git a/frameworks/core/include/ans_manager_stub.h b/frameworks/core/include/ans_manager_stub.h index 5b2edf2c7..388154b8d 100644 --- a/frameworks/core/include/ans_manager_stub.h +++ b/frameworks/core/include/ans_manager_stub.h @@ -496,6 +496,13 @@ public: ErrCode CanPopEnableNotificationDialog(const sptr &callback, bool &canPop, std::string &bundleName) override; + /** + * @brief remove enable notification dialog. + * + * @return Returns remove dialog result. + */ + ErrCode RemoveEnableNotificationDialog() override; + /** * @brief Checks whether notifications are allowed for a specific bundle. * @@ -996,6 +1003,7 @@ private: ErrCode HandleIsAllowedNotify(MessageParcel &data, MessageParcel &reply); ErrCode HandleIsAllowedNotifySelf(MessageParcel &data, MessageParcel &reply); ErrCode HandleCanPopEnableNotificationDialog(MessageParcel &data, MessageParcel &reply); + ErrCode HandleRemoveEnableNotificationDialog(MessageParcel &data, MessageParcel &reply); ErrCode HandleIsSpecialBundleAllowedNotify(MessageParcel &data, MessageParcel &reply); ErrCode HandleIsDistributedEnabled(MessageParcel &data, MessageParcel &reply); ErrCode HandleEnableDistributed(MessageParcel &data, MessageParcel &reply); diff --git a/frameworks/core/include/ans_notification.h b/frameworks/core/include/ans_notification.h index cb6a2d319..cbdefbc54 100644 --- a/frameworks/core/include/ans_notification.h +++ b/frameworks/core/include/ans_notification.h @@ -299,6 +299,13 @@ public: ErrCode CanPopEnableNotificationDialog(sptr &hostClient, bool &canPop, std::string &bundleName); + /** + * @brief remove enable notification dialog. + * + * @return Returns remove dialog result. + */ + ErrCode RemoveEnableNotificationDialog(); + /** * @brief Allows the current application to publish notifications on a specified device. * diff --git a/frameworks/core/include/distributed_notification_service_ipc_interface_code.h b/frameworks/core/include/distributed_notification_service_ipc_interface_code.h index 36f8ec9c6..9422457b8 100644 --- a/frameworks/core/include/distributed_notification_service_ipc_interface_code.h +++ b/frameworks/core/include/distributed_notification_service_ipc_interface_code.h @@ -76,6 +76,7 @@ namespace Notification { IS_ALLOWED_NOTIFY, IS_ALLOWED_NOTIFY_SELF, CAN_POP_ENABLE_NOTIFICATION_DIALOG, + REMOVE_ENABLE_NOTIFICATION_DIALOG, IS_SPECIAL_BUNDLE_ALLOWED_NOTIFY, SET_DO_NOT_DISTURB_DATE, GET_DO_NOT_DISTURB_DATE, diff --git a/frameworks/core/src/ans_manager_proxy.cpp b/frameworks/core/src/ans_manager_proxy.cpp index 1d185722d..56716d525 100644 --- a/frameworks/core/src/ans_manager_proxy.cpp +++ b/frameworks/core/src/ans_manager_proxy.cpp @@ -1316,6 +1316,28 @@ ErrCode AnsManagerProxy::CanPopEnableNotificationDialog(const sptr &bundleOption, bool &allowed) { if (bundleOption == nullptr) { diff --git a/frameworks/core/src/ans_manager_stub.cpp b/frameworks/core/src/ans_manager_stub.cpp index 57507b50c..4f4a8b58a 100644 --- a/frameworks/core/src/ans_manager_stub.cpp +++ b/frameworks/core/src/ans_manager_stub.cpp @@ -223,6 +223,10 @@ int32_t AnsManagerStub::OnRemoteRequest(uint32_t code, MessageParcel &data, Mess result = HandleCanPopEnableNotificationDialog(data, reply); break; } + case static_cast(NotificationInterfaceCode::REMOVE_ENABLE_NOTIFICATION_DIALOG): { + result = HandleRemoveEnableNotificationDialog(data, reply); + break; + } case static_cast(NotificationInterfaceCode::IS_SPECIAL_BUNDLE_ALLOWED_NOTIFY): { result = HandleIsSpecialBundleAllowedNotify(data, reply); break; @@ -1648,6 +1652,16 @@ ErrCode AnsManagerStub::HandleCanPopEnableNotificationDialog(MessageParcel &data return ERR_OK; } +ErrCode AnsManagerStub::HandleRemoveEnableNotificationDialog(MessageParcel &data, MessageParcel &reply) +{ + ErrCode result = RemoveEnableNotificationDialog(); + if (!reply.WriteInt32(result)) { + ANS_LOGE("[HandleRemoveEnableNotificationDialog] fail: write result failed, ErrCode=%{public}d", result); + return ERR_ANS_PARCELABLE_FAILED; + } + return ERR_OK; +} + ErrCode AnsManagerStub::HandleIsSpecialBundleAllowedNotify(MessageParcel &data, MessageParcel &reply) { sptr bundleOption = data.ReadParcelable(); diff --git a/frameworks/core/src/ans_manager_stub_invalid.cpp b/frameworks/core/src/ans_manager_stub_invalid.cpp index 1c4e664d1..e8c1bf6af 100644 --- a/frameworks/core/src/ans_manager_stub_invalid.cpp +++ b/frameworks/core/src/ans_manager_stub_invalid.cpp @@ -351,6 +351,12 @@ ErrCode AnsManagerStub::CanPopEnableNotificationDialog(const sptr &bundleOption, bool &allowed) { ANS_LOGE("AnsManagerStub::IsSpecialBundleAllowedNotify called!"); diff --git a/frameworks/core/src/ans_notification.cpp b/frameworks/core/src/ans_notification.cpp index bf63ed31d..2422aa04d 100644 --- a/frameworks/core/src/ans_notification.cpp +++ b/frameworks/core/src/ans_notification.cpp @@ -449,6 +449,17 @@ ErrCode AnsNotification::CanPopEnableNotificationDialog(sptrCanPopEnableNotificationDialog(hostClient, canPop, bundleName); } +ErrCode AnsNotification::RemoveEnableNotificationDialog() +{ + ANS_LOGD("enter"); + sptr proxy = GetAnsManagerProxy(); + if (!proxy) { + ANS_LOGE("GetAnsManagerProxy fail."); + return ERR_ANS_SERVICE_NOT_CONNECTED; + } + return proxy->RemoveEnableNotificationDialog(); +} + ErrCode AnsNotification::RequestEnableNotification(std::string &deviceId, sptr &hostClient, sptr &callerToken) diff --git a/frameworks/js/napi/include/manager/napi_enable_notification.h b/frameworks/js/napi/include/manager/napi_enable_notification.h index 76f84b513..65ee9f4da 100644 --- a/frameworks/js/napi/include/manager/napi_enable_notification.h +++ b/frameworks/js/napi/include/manager/napi_enable_notification.h @@ -33,7 +33,6 @@ napi_value NapiGetAllNotificationEnabledBundles(napi_env env, napi_callback_info napi_value ParseRequestEnableParameters(const napi_env &env, const napi_callback_info &info, IsEnableParams ¶ms); napi_value NapiIsNotificationEnabledSync(napi_env env, napi_callback_info info); bool CreateUIExtension(std::shared_ptr context, std::string &bundleName); -void SendDialogEvent(std::string &bundleName, int32_t code); void SetEnableParam(IsEnableParams ¶ms, const napi_env &env, napi_value &object); class ModalExtensionCallback { diff --git a/frameworks/js/napi/src/manager/napi_enable_notification.cpp b/frameworks/js/napi/src/manager/napi_enable_notification.cpp index 6bf28636e..dbc5533e4 100644 --- a/frameworks/js/napi/src/manager/napi_enable_notification.cpp +++ b/frameworks/js/napi/src/manager/napi_enable_notification.cpp @@ -23,9 +23,6 @@ #include "js_ans_dialog_callback.h" #include "common_event_manager.h" -constexpr int32_t CRASH_CODE = 2; -constexpr int32_t REMOVE_CODE = 3; - namespace OHOS { namespace NotificationNapi { const int IS_NOTIFICATION_ENABLE_MAX_PARA = 2; @@ -303,7 +300,7 @@ napi_value NapiRequestEnableNotification(napi_env env, napi_callback_info info) asynccallbackinfo->info.errorCode = ERR_ANS_DIALOG_POP_SUCCEEDED; } else { asynccallbackinfo->info.errorCode = ERROR_INTERNAL_ERROR; - SendDialogEvent(bundleName, REMOVE_CODE); + NotificationHelper::RemoveEnableNotificationDialog(); } } else { ANS_LOGD("un stage mode"); @@ -566,28 +563,6 @@ bool CreateUIExtension(std::shared_ptr context, s return true; } -void SendDialogEvent(std::string &bundleName, int32_t code) -{ - ANS_LOGD("SendDialogEvent start"); - if (bundleName.empty()) { - ANS_LOGE("SendDialogEvent bundleName is nullptr"); - return; - } - std::string action = "OnNotificationServiceDialogClicked"; - - EventFwk::Want want; - want.SetAction(action); - - EventFwk::CommonEventData commonData; - commonData.SetWant(want); - commonData.SetCode(code); - commonData.SetData(bundleName); - if (!EventFwk::CommonEventManager::PublishCommonEvent(commonData)) { - ANS_LOGE("PublishCommonEvent failed"); - } - ANS_LOGD("SendDialogEvent end"); -} - void SetEnableParam(IsEnableParams ¶ms, const napi_env &env, napi_value &object) { auto context = OHOS::AbilityRuntime::GetStageModeContext(env, object); @@ -640,7 +615,7 @@ void ModalExtensionCallback::OnError(int32_t code, const std::string& name, cons { ANS_LOGE("OnError, name = %{public}s, message = %{public}s", name.c_str(), message.c_str()); ReleaseOrErrorHandle(code); - SendDialogEvent(this->bundleName_, CRASH_CODE); + NotificationHelper::RemoveEnableNotificationDialog(); } /* diff --git a/interfaces/inner_api/notification_helper.h b/interfaces/inner_api/notification_helper.h index 0c28c7fd3..d08eab7ac 100644 --- a/interfaces/inner_api/notification_helper.h +++ b/interfaces/inner_api/notification_helper.h @@ -299,6 +299,13 @@ public: */ static ErrCode CanPopEnableNotificationDialog(sptr &hostClient, bool &canPop, std::string &bundleName); + + /** + * @brief remove enable notification dialog. + * + * @return Returns remove dialog result. + */ + static ErrCode RemoveEnableNotificationDialog(); /** * @brief Allow the current application to publish notifications on a specified device. diff --git a/services/ans/include/advanced_notification_service.h b/services/ans/include/advanced_notification_service.h index 567744e42..ffaebba74 100644 --- a/services/ans/include/advanced_notification_service.h +++ b/services/ans/include/advanced_notification_service.h @@ -550,6 +550,15 @@ public: */ ErrCode CanPopEnableNotificationDialog(const sptr &callback, bool &canPop, std::string &bundleName) override; + + /** + * @brief remove enable notification dialog. + * + * @return Returns remove dialog result. + */ + ErrCode RemoveEnableNotificationDialog() override; + + ErrCode RemoveEnableNotificationDialog(const sptr &bundleOption); /** * @brief Checks whether notifications are allowed for a specific bundle. diff --git a/services/ans/include/notification_dialog_manager.h b/services/ans/include/notification_dialog_manager.h index 67dc13619..2d8b63877 100644 --- a/services/ans/include/notification_dialog_manager.h +++ b/services/ans/include/notification_dialog_manager.h @@ -101,6 +101,13 @@ public: * @return ERR_OK when add Dialog successfully */ ErrCode AddDialogInfo(const sptr& bundle, const sptr& callback); + + /* + * RemoveDialogInfoByBundleOption + * @return void + */ + void RemoveDialogInfoByBundleOption(const sptr& bundle, + std::unique_ptr& dialogInfoRemoved); inline static const std::string NOTIFICATION_DIALOG_SERVICE_BUNDLE = "com.ohos.notificationdialog"; inline static const std::string NOTIFICATION_DIALOG_SERVICE_ABILITY = "EnableNotificationDialog"; @@ -112,9 +119,6 @@ private: // bundle need to be not null bool AddDialogInfoIfNotExist(const sptr& bundle, const sptr& callback); sptr GetBundleOptionByBundleName(const std::string& bundleName, const int32_t& uid); - // bundle need to be not null - void RemoveDialogInfoByBundleOption(const sptr& bundle, - std::unique_ptr& dialogInfoRemoved); void RemoveAllDialogInfos(std::list>& dialogInfosRemoved); bool OnDialogButtonClicked(const std::string& bundleName, const int32_t& uid, bool enabled); diff --git a/services/ans/include/system_dialog_connect_stb.h b/services/ans/include/system_dialog_connect_stb.h index 89f09b2a5..3b0ad5be2 100644 --- a/services/ans/include/system_dialog_connect_stb.h +++ b/services/ans/include/system_dialog_connect_stb.h @@ -38,8 +38,6 @@ public: const sptr &remoteObject, int32_t resultCode) override; void OnAbilityDisconnectDone(const AppExecFwk::ElementName &element, int32_t resultCode) override; - void SendRemoveBundleEvent(); - private: std::string commandStr_; }; diff --git a/services/ans/src/advanced_notification_publish_service.cpp b/services/ans/src/advanced_notification_publish_service.cpp index 09062bc80..3a218f7e2 100644 --- a/services/ans/src/advanced_notification_publish_service.cpp +++ b/services/ans/src/advanced_notification_publish_service.cpp @@ -1009,6 +1009,29 @@ ErrCode AdvancedNotificationService::CanPopEnableNotificationDialog( return ERR_OK; } +ErrCode AdvancedNotificationService::RemoveEnableNotificationDialog() +{ + ANS_LOGD("%{public}s", __FUNCTION__); + ErrCode result = ERR_OK; + sptr bundleOption = GenerateBundleOption(); + if (bundleOption == nullptr) { + ANS_LOGE("bundleOption == nullptr"); + return ERR_ANS_INVALID_BUNDLE; + } + return RemoveEnableNotificationDialog(bundleOption); +} + +ErrCode AdvancedNotificationService::RemoveEnableNotificationDialog(const sptr &bundleOption) +{ + ANS_LOGI("RemoveEnableNotificationDialog %{public}s, %{public}d", bundleOption->GetBundleName().c_str(), bundleOption->GetUid()); + if (!CreateDialogManager()) { + return ERROR_INTERNAL_ERROR; + } + std::unique_ptr dialogInfoRemoved = nullptr; + dialogManager_->RemoveDialogInfoByBundleOption(bundleOption, dialogInfoRemoved); + return ERR_OK; +} + ErrCode AdvancedNotificationService::IsAllowedNotifySelf(const sptr &bundleOption, bool &allowed) { diff --git a/services/ans/src/system_dialog_connect_stb.cpp b/services/ans/src/system_dialog_connect_stb.cpp index 9035552b2..d96efe3bb 100644 --- a/services/ans/src/system_dialog_connect_stb.cpp +++ b/services/ans/src/system_dialog_connect_stb.cpp @@ -18,10 +18,10 @@ #include "ans_log_wrapper.h" #include "ans_inner_errors.h" #include "common_event_manager.h" +#include "advanced_notification_service.h" +#include "notification_bundle_option.h" constexpr int32_t SIGNAL_NUM = 3; -constexpr int32_t REMOVE_BUNDLE_CODE = 3; -const static std::string DIALOG_CRASH_EVENT = "OnNotificationServiceDialogClicked"; namespace OHOS { namespace Notification { @@ -44,8 +44,25 @@ void SystemDialogConnectStb::OnAbilityConnectDone(const AppExecFwk::ElementName int32_t errCode = remoteObject->SendRequest(IAbilityConnection::ON_ABILITY_CONNECT_DONE, data, reply, option); ANS_LOGI("AbilityConnectionWrapperProxy::OnAbilityConnectDone result %{public}d", errCode); if (errCode != ERR_OK) { - ANS_LOGD("send Request to SytemDialog fail"); - SendRemoveBundleEvent(); + ANS_LOGE("send Request to SytemDialog fail"); + nlohmann::json root = nlohmann::json::parse(commandStr_); + if (root.is_null() or !root.is_object()) { + ANS_LOGE("Invalid JSON object"); + return; + } + if (!root.contains("bundleName") || !root.contains("bundleUid")) { + ANS_LOGE("not found jsonKey from"); + return; + } + std::string bundleName = root["bundleName"]; + int32_t bundleUid = root["bundleUid"]; + sptr bundleOption = new (std::nothrow) NotificationBundleOption( + bundleName, bundleUid); + if (bundleOption == nullptr) { + ANS_LOGE("bundleOption inin fail"); + return; + } + AdvancedNotificationService::GetInstance()->RemoveEnableNotificationDialog(bundleOption); } } @@ -55,40 +72,5 @@ void SystemDialogConnectStb::OnAbilityDisconnectDone(const AppExecFwk::ElementNa ANS_LOGI("on ability disconnected"); } -void SystemDialogConnectStb::SendRemoveBundleEvent() -{ - if (commandStr_.empty() || !nlohmann::json::accept(commandStr_)) { - ANS_LOGW("Invaild json param"); - return; - } - nlohmann::json root = nlohmann::json::parse(commandStr_); - if (root.is_null() or !root.is_object()) { - ANS_LOGE("Invalid JSON object"); - return; - } - if (!root.contains("bundleName") || !root.contains("bundleUid")) { - ANS_LOGW("not found jsonKey from"); - return; - } - if (!root["bundleName"].is_string() || !root["bundleUid"].is_string()) { - ANS_LOGW("value type of json key from is not string"); - return; - } - EventFwk::CommonEventData commonData; - std::string bundleName = root["bundleName"]; - std::string bundleUid = root["bundleUid"]; - - EventFwk::Want want; - want.SetAction(DIALOG_CRASH_EVENT); - want.SetParam("bundleName", bundleName); - want.SetParam("bundleUid", bundleUid); - commonData.SetWant(want); - commonData.SetCode(REMOVE_BUNDLE_CODE); - commonData.SetData(bundleName); - if (!EventFwk::CommonEventManager::PublishCommonEvent(commonData)) { - ANS_LOGE("Publish remove bundle failed"); - } -} - } } \ No newline at end of file -- Gitee From c74314909dd6183859954c5f20366ff5a07d87c6 Mon Sep 17 00:00:00 2001 From: xdongs Date: Fri, 11 Oct 2024 14:16:42 +0800 Subject: [PATCH 092/167] remove Signed-off-by: xdongs Change-Id: Ia3f46180041428ea76f16c3ccc2e0eb1a47b4f6b --- frameworks/core/include/ans_manager_interface.h | 2 +- frameworks/core/include/ans_manager_proxy.h | 2 +- .../ans_notification_branch_test.cpp | 5 +++++ services/ans/src/advanced_notification_publish_service.cpp | 4 +++- 4 files changed, 10 insertions(+), 3 deletions(-) diff --git a/frameworks/core/include/ans_manager_interface.h b/frameworks/core/include/ans_manager_interface.h index 15702b01d..a1a6be77e 100644 --- a/frameworks/core/include/ans_manager_interface.h +++ b/frameworks/core/include/ans_manager_interface.h @@ -514,7 +514,7 @@ public: * * @return Returns remove dialog result. */ - virtual ErrCode RemoveEnableNotificationDialog() = 0; + virtual ErrCode RemoveEnableNotificationDialog() = 0; /** * @brief Checks whether notifications are allowed for a specific bundle. diff --git a/frameworks/core/include/ans_manager_proxy.h b/frameworks/core/include/ans_manager_proxy.h index 1267fa403..6af6824b8 100644 --- a/frameworks/core/include/ans_manager_proxy.h +++ b/frameworks/core/include/ans_manager_proxy.h @@ -502,7 +502,7 @@ public: * * @return Returns remove dialog result. */ - ErrCode RemoveEnableNotificationDialog() override; + ErrCode RemoveEnableNotificationDialog() override; /** * @brief Checks whether notifications are allowed for a specific bundle. diff --git a/frameworks/core/test/unittest/ans_notification_branch_test/ans_notification_branch_test.cpp b/frameworks/core/test/unittest/ans_notification_branch_test/ans_notification_branch_test.cpp index 904899139..cbdf99a36 100644 --- a/frameworks/core/test/unittest/ans_notification_branch_test/ans_notification_branch_test.cpp +++ b/frameworks/core/test/unittest/ans_notification_branch_test/ans_notification_branch_test.cpp @@ -307,6 +307,11 @@ public: return ERR_ANS_INVALID_PARAM; } + ErrCode RemoveEnableNotificationDialog() override + { + return ERR_ANS_INVALID_PARAM; + } + ErrCode IsSpecialBundleAllowedNotify(const sptr &bundleOption, bool &allowed) override { return ERR_ANS_INVALID_PARAM; diff --git a/services/ans/src/advanced_notification_publish_service.cpp b/services/ans/src/advanced_notification_publish_service.cpp index 3a218f7e2..99e5ef08c 100644 --- a/services/ans/src/advanced_notification_publish_service.cpp +++ b/services/ans/src/advanced_notification_publish_service.cpp @@ -1023,7 +1023,9 @@ ErrCode AdvancedNotificationService::RemoveEnableNotificationDialog() ErrCode AdvancedNotificationService::RemoveEnableNotificationDialog(const sptr &bundleOption) { - ANS_LOGI("RemoveEnableNotificationDialog %{public}s, %{public}d", bundleOption->GetBundleName().c_str(), bundleOption->GetUid()); + ANS_LOGI("RemoveEnableNotificationDialog %{public}s, %{public}d", + bundleOption->GetBundleName().c_str(), + bundleOption->GetUid()); if (!CreateDialogManager()) { return ERROR_INTERNAL_ERROR; } -- Gitee From 79dc31d3d3292849d3eccbe25d214f44818e4290 Mon Sep 17 00:00:00 2001 From: gaojiaqi Date: Sat, 26 Oct 2024 17:46:13 +0800 Subject: [PATCH 093/167] update Signed-off-by: gaojiaqi --- services/ans/src/reminder_event_manager.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/services/ans/src/reminder_event_manager.cpp b/services/ans/src/reminder_event_manager.cpp index 87c6284b8..868fbd6a5 100644 --- a/services/ans/src/reminder_event_manager.cpp +++ b/services/ans/src/reminder_event_manager.cpp @@ -312,7 +312,7 @@ void ReminderEventManager::ReminderNotificationSubscriber::OnCanceled( const std::shared_ptr ¬ification, const std::shared_ptr &sortingMap, int deleteReason) { - if (deleteReason != NotificationConstant::APP_CANCEL_REASON_DELETE) { + if (deleteReason != NotificationConstant::TRIGGER_AUTO_DELETE_REASON_DELETE) { return; } if (notification == nullptr) { -- Gitee From a478181a76fabb2fcd35a1e412b68998ed84cb08 Mon Sep 17 00:00:00 2001 From: gaojiaqi Date: Sat, 26 Oct 2024 17:47:44 +0800 Subject: [PATCH 094/167] update Signed-off-by: gaojiaqi --- services/ans/src/reminder_data_manager.cpp | 1 - 1 file changed, 1 deletion(-) diff --git a/services/ans/src/reminder_data_manager.cpp b/services/ans/src/reminder_data_manager.cpp index 7f51ca62e..05c8e9e2d 100644 --- a/services/ans/src/reminder_data_manager.cpp +++ b/services/ans/src/reminder_data_manager.cpp @@ -1634,7 +1634,6 @@ void ReminderDataManager::PlaySoundAndVibration(const sptr &rem } ANSR_LOGI("Play custom sound, reminderId:[%{public}d].", reminder->GetReminderId()); } - soundPlayer_->SetSource(uri); soundPlayer_->SetLooping(true); soundPlayer_->PrepareAsync(); soundPlayer_->Play(); -- Gitee From 4e637158c0b0b09d18e81d1a03c704c582b9d9c4 Mon Sep 17 00:00:00 2001 From: wangsen1994 Date: Thu, 26 Sep 2024 16:14:38 +0800 Subject: [PATCH 095/167] =?UTF-8?q?cherry=20pick=209a73999=20from=20https:?= =?UTF-8?q?//gitee.com/wangsen1994/notification=5Fdistributed=5Fnotificati?= =?UTF-8?q?on=5Fservice/pulls/2246=20ans=20=E6=94=AF=E6=8C=81=E5=85=8B?= =?UTF-8?q?=E9=9A=86bundle=E4=BF=A1=E6=81=AF?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: wangsen1994 --- services/ans/BUILD.gn | 3 + .../include/notification_clone_bundle_info.h | 77 +++++++ .../notification_clone_bundle_service.h | 45 ++++ .../notification_clone_disturb_service.h | 5 +- .../ans/include/notification_clone_manager.h | 2 + .../ans/include/notification_clone_template.h | 3 +- .../ans/include/notification_clone_util.h | 33 +++ .../ans/include/notification_preferences.h | 3 + .../notification_preferences_database.h | 6 +- .../include/notification_preferences_info.h | 5 +- .../ans/src/advanced_notification_utils.cpp | 2 + .../clone/notification_clone_bundle_info.cpp | 212 ++++++++++++++++++ .../notification_clone_bundle_service.cpp | 155 +++++++++++++ .../notification_clone_disturb_service.cpp | 38 +--- .../src/clone/notification_clone_manager.cpp | 10 + .../ans/src/clone/notification_clone_util.cpp | 43 ++++ services/ans/src/notification_preferences.cpp | 70 +++++- .../src/notification_preferences_database.cpp | 54 +++++ .../ans/src/notification_preferences_info.cpp | 33 +++ services/ans/src/system_event_observer.cpp | 4 +- 20 files changed, 766 insertions(+), 37 deletions(-) create mode 100644 services/ans/include/notification_clone_bundle_info.h create mode 100644 services/ans/include/notification_clone_bundle_service.h create mode 100644 services/ans/include/notification_clone_util.h create mode 100644 services/ans/src/clone/notification_clone_bundle_info.cpp create mode 100644 services/ans/src/clone/notification_clone_bundle_service.cpp create mode 100644 services/ans/src/clone/notification_clone_util.cpp diff --git a/services/ans/BUILD.gn b/services/ans/BUILD.gn index 178cbaf13..4a7892c3a 100644 --- a/services/ans/BUILD.gn +++ b/services/ans/BUILD.gn @@ -64,8 +64,11 @@ ohos_shared_library("libans") { "src/advanced_notification_subscriber_service.cpp", "src/advanced_notification_utils.cpp", "src/bundle_manager_helper.cpp", + "src/clone/notification_clone_bundle_info.cpp", + "src/clone/notification_clone_bundle_service.cpp", "src/clone/notification_clone_disturb_service.cpp", "src/clone/notification_clone_manager.cpp", + "src/clone/notification_clone_util.cpp", "src/common/aes_gcm_helper.cpp", "src/common/file_utils.cpp", "src/common/notification_analytics_util.cpp", diff --git a/services/ans/include/notification_clone_bundle_info.h b/services/ans/include/notification_clone_bundle_info.h new file mode 100644 index 000000000..99a2af2c4 --- /dev/null +++ b/services/ans/include/notification_clone_bundle_info.h @@ -0,0 +1,77 @@ +/* + * Copyright (c) 2024-2024 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef BASE_NOTIFICATION_DISTRIBUTED_NOTIFICATION_SERVICE_SERVICES_ANS_INCLUDE_NOTIFICATION_CLONE_BUNDLE_INFO_H +#define BASE_NOTIFICATION_DISTRIBUTED_NOTIFICATION_SERVICE_SERVICES_ANS_INCLUDE_NOTIFICATION_CLONE_BUNDLE_INFO_H + +#include "notification_clone_template.h" + +#include "ffrt.h" +#include "notification_constant.h" +#include "notification_bundle_option.h" +#include "notification_do_not_disturb_profile.h" + +namespace OHOS { +namespace Notification { +class NotificationCloneBundleInfo { +public: + class SlotInfo { + public: + std::string Dump() const; + NotificationConstant::SlotType slotType_; + bool enable_; + bool isForceControl_; + }; + NotificationCloneBundleInfo() = default; + ~NotificationCloneBundleInfo() = default; + + void SetBundleName(const std::string &name); + std::string GetBundleName() const; + + void SetAppIndex(const int32_t &appIndex); + int32_t GetAppIndex() const; + + void SetSlotFlags(const uint32_t &slotFlags); + uint32_t GetSlotFlags() const; + + void SetUid(const int32_t &uid); + int32_t GetUid() const; + + void SetIsShowBadge(const bool &isShowBadge); + bool GetIsShowBadge() const; + + void SetEnableNotification(const bool &enable); + bool GetEnableNotification() const; + + void AddSlotInfo(const SlotInfo &slotInfo); + std::vector GetSlotInfo() const; + + void ToJson(nlohmann::json &jsonObject) const; + void FromJson(const nlohmann::json &root); + void SlotsFromJson(const nlohmann::json &jsonObject); + std::string Dump() const; + +private: + std::string bundleName_; + int32_t appIndex_ = -1; + int32_t uid_ = -1; + uint32_t slotFlags_ = 0; + bool isShowBadge_ = false; + bool isEnabledNotification_ = false; + std::vector slotsInfo_; +}; +} // namespace Notification +} // namespace OHOS +#endif // BASE_NOTIFICATION_DISTRIBUTED_NOTIFICATION_SERVICE_SERVICES_ANS_INCLUDE_NOTIFICATION_CLONE_BUNDLE_INFO_H diff --git a/services/ans/include/notification_clone_bundle_service.h b/services/ans/include/notification_clone_bundle_service.h new file mode 100644 index 000000000..7e30c4664 --- /dev/null +++ b/services/ans/include/notification_clone_bundle_service.h @@ -0,0 +1,45 @@ +/* + * Copyright (c) 2024-2024 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef BASE_NOTIFICATION_DISTRIBUTED_NOTIFICATION_SERVICE_SERVICES_ANS_INCLUDE_NOTIFICATION_CLONE_BUNDLE_H +#define BASE_NOTIFICATION_DISTRIBUTED_NOTIFICATION_SERVICE_SERVICES_ANS_INCLUDE_NOTIFICATION_CLONE_BUNDLE_H + +#include "notification_clone_template.h" + +#include "ffrt.h" +#include "notification_bundle_option.h" +#include "notification_clone_bundle_info.h" + +namespace OHOS { +namespace Notification { +class NotificationCloneBundle final : public NotificationCloneTemplate { +public: + NotificationCloneBundle(); + ~NotificationCloneBundle() override; + static std::shared_ptr GetInstance(); + ErrCode OnBackup(nlohmann::json &jsonObject) override; + void OnRestore(const nlohmann::json &jsonObject) override; + void OnBundleDataAdd(const sptr &bundleOption); + void OnBundleDataUpdate(const sptr &bundleOption); + void HandleBundleEvent(const std::string bundleName, int32_t appIndex, int32_t uid); + void OnUserSwitch(int32_t userId) override; +private: + std::vector bundlesInfo_; + std::shared_ptr cloneBundleQueue_ = nullptr; + ffrt::mutex lock_; +}; +} // namespace Notification +} // namespace OHOS +#endif // BASE_NOTIFICATION_DISTRIBUTED_NOTIFICATION_SERVICE_SERVICES_ANS_INCLUDE_NOTIFICATION_CLONE_BUNDLE_H diff --git a/services/ans/include/notification_clone_disturb_service.h b/services/ans/include/notification_clone_disturb_service.h index 670ad8495..ab8a3939c 100644 --- a/services/ans/include/notification_clone_disturb_service.h +++ b/services/ans/include/notification_clone_disturb_service.h @@ -30,7 +30,7 @@ public: ~NotificationCloneDisturb() override; static std::shared_ptr GetInstance(); ErrCode OnBackup(nlohmann::json &jsonObject) override; - ErrCode OnRestore(const nlohmann::json &jsonObject) override; + void OnRestore(const nlohmann::json &jsonObject) override; void OnBundleDataAdd(const sptr &bundleOption); void OnBundleDataUpdate(const sptr &bundleOption); void HandlerBundleEvent(const std::string bundleName, int32_t appIndex, int32_t uid); @@ -41,7 +41,8 @@ public: void CheckBundleInfo(std::vector& trustList, std::vector& bundleList, const NotificationBundleOption& bundle); int32_t GetActiveUserId(); - void OnUserSwitch(int32_t userId); + void OnUserSwitch(int32_t userId) override; + private: std::atomic userId_ = -1; std::vector> profiles_; diff --git a/services/ans/include/notification_clone_manager.h b/services/ans/include/notification_clone_manager.h index d3cc6f901..1328e8fd9 100644 --- a/services/ans/include/notification_clone_manager.h +++ b/services/ans/include/notification_clone_manager.h @@ -31,6 +31,8 @@ public: int32_t OnBackup(MessageParcel& data, MessageParcel& reply); int32_t OnRestore(MessageParcel& data, MessageParcel& reply); + void OnUserSwitch(int32_t userId); + private: NotificationCloneManager(); ~NotificationCloneManager(); diff --git a/services/ans/include/notification_clone_template.h b/services/ans/include/notification_clone_template.h index 0a6ce21aa..b9baa7472 100644 --- a/services/ans/include/notification_clone_template.h +++ b/services/ans/include/notification_clone_template.h @@ -27,7 +27,8 @@ public: NotificationCloneTemplate() = default; virtual ~NotificationCloneTemplate() = default; virtual ErrCode OnBackup(nlohmann::json &jsonObject) = 0; - virtual ErrCode OnRestore(const nlohmann::json &jsonObject) = 0; + virtual void OnRestore(const nlohmann::json &jsonObject) = 0; + virtual void OnUserSwitch(int32_t userId) = 0; }; } // namespace Notification } // namespace OHOS diff --git a/services/ans/include/notification_clone_util.h b/services/ans/include/notification_clone_util.h new file mode 100644 index 000000000..1d33f80b9 --- /dev/null +++ b/services/ans/include/notification_clone_util.h @@ -0,0 +1,33 @@ +/* + * Copyright (c) 2024-2024 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef BASE_NOTIFICATION_DISTRIBUTED_NOTIFICATION_SERVICE_SERVICES_ANS_INCLUDE_NOTIFICATION_CLONE_UTILS_H +#define BASE_NOTIFICATION_DISTRIBUTED_NOTIFICATION_SERVICE_SERVICES_ANS_INCLUDE_NOTIFICATION_CLONE_UTILS_H + +#include +#include + +namespace OHOS { +namespace Notification { +class NotificationCloneUtil { +public: + NotificationCloneUtil() = default; + ~NotificationCloneUtil() = default; + static int32_t GetActiveUserId(); + static int32_t GetBundleUid(const std::string bundleName, int32_t userId, int32_t appIndex); +}; +} // namespace Notification +} // namespace OHOS +#endif // BASE_NOTIFICATION_DISTRIBUTED_NOTIFICATION_SERVICE_SERVICES_ANS_INCLUDE_NOTIFICATION_CLONE_UTILS_H diff --git a/services/ans/include/notification_preferences.h b/services/ans/include/notification_preferences.h index 2d2fe17e6..a5ead6fd1 100644 --- a/services/ans/include/notification_preferences.h +++ b/services/ans/include/notification_preferences.h @@ -23,6 +23,7 @@ #include "notification_preferences_database.h" #include #include +#include "notification_clone_bundle_info.h" namespace OHOS { namespace Notification { @@ -381,6 +382,8 @@ public: void RemoveDoNotDisturbProfileTrustList(int32_t userId, const sptr &bundleOption); void GetDoNotDisturbProfileListByUserId(int32_t userId, std::vector> &profiles); + void GetAllCLoneBundlesInfo(int32_t userId, std::vector &cloneBundles); + void UpdateCloneBundleInfo(int32_t userId, const NotificationCloneBundleInfo& cloneBundleInfo); private: ErrCode CheckSlotForCreateSlot(const sptr &bundleOption, diff --git a/services/ans/include/notification_preferences_database.h b/services/ans/include/notification_preferences_database.h index 2c7b755dd..74d7e4d40 100644 --- a/services/ans/include/notification_preferences_database.h +++ b/services/ans/include/notification_preferences_database.h @@ -87,7 +87,7 @@ public: */ bool PutNotificationsEnabledForBundle( const NotificationPreferencesInfo::BundleInfo &bundleInfo, const bool &enabled); - + /** * @brief Put distributed enable notification in the of bundle into disturbe DB. * @@ -232,6 +232,10 @@ public: const std::string &key, std::unordered_map &values, const int32_t &userId); int32_t DeleteKvFromDb(const std::string &key, const int32_t &userId); int32_t DropUserTable(const int32_t userId); + bool UpdateBundlePropertyToDisturbeDB(int32_t userId, const NotificationPreferencesInfo::BundleInfo &bundleInfo); + bool UpdateBundleSlotToDisturbeDB(int32_t userId, const std::string &bundleName, + const int32_t &bundleUid, const std::vector> &slots); + private: bool CheckRdbStore(); diff --git a/services/ans/include/notification_preferences_info.h b/services/ans/include/notification_preferences_info.h index 0ec01aaf5..8e5d13576 100644 --- a/services/ans/include/notification_preferences_info.h +++ b/services/ans/include/notification_preferences_info.h @@ -25,6 +25,7 @@ #include "notification_slot.h" #include "preferences_constant.h" #include "advanced_notification_service.h" +#include "notification_clone_bundle_info.h" namespace OHOS { namespace Notification { @@ -315,6 +316,8 @@ public: void RemoveDoNotDisturbProfiles(int32_t userId, const std::vector> &profiles); bool GetDoNotDisturbProfiles(int32_t profileId, int32_t userId, sptr &profiles); void GetAllDoNotDisturbProfiles(int32_t userId, std::vector> &profiles); + void GetAllCLoneBundlesInfo(const int32_t &userId, const std::unordered_map &bunlesMap, + std::vector &cloneBundles); private: std::map isEnabledAllNotification_; @@ -324,4 +327,4 @@ private: }; } // namespace Notification } // namespace OHOS -#endif // BASE_NOTIFICATION_DISTRIBUTED_NOTIFICATION_SERVICE_SERVICES_NOTIFICATION_PREFERENCES_INFO_H \ No newline at end of file +#endif // BASE_NOTIFICATION_DISTRIBUTED_NOTIFICATION_SERVICE_SERVICES_NOTIFICATION_PREFERENCES_INFO_H diff --git a/services/ans/src/advanced_notification_utils.cpp b/services/ans/src/advanced_notification_utils.cpp index 5343fc25d..ac605904c 100644 --- a/services/ans/src/advanced_notification_utils.cpp +++ b/services/ans/src/advanced_notification_utils.cpp @@ -48,6 +48,7 @@ #include "advanced_notification_inline.cpp" #include "notification_analytics_util.h" #include "notification_clone_disturb_service.h" +#include "notification_clone_bundle_service.h" #define CHECK_BUNDLE_OPTION_IS_INVALID(option) \ if (option == nullptr || option->GetBundleName().empty()) { \ @@ -594,6 +595,7 @@ void AdvancedNotificationService::OnBundleDataAdd(const sptrOnBundleDataAdd(bundleOption); }; NotificationCloneDisturb::GetInstance()->OnBundleDataAdd(bundleOption); diff --git a/services/ans/src/clone/notification_clone_bundle_info.cpp b/services/ans/src/clone/notification_clone_bundle_info.cpp new file mode 100644 index 000000000..3f36a2a0a --- /dev/null +++ b/services/ans/src/clone/notification_clone_bundle_info.cpp @@ -0,0 +1,212 @@ +/* +* Copyright (c) 2024-2024 Huawei Device Co., Ltd. +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +#include "notification_clone_bundle_info.h" + +#include "ans_log_wrapper.h" + +namespace OHOS { +namespace Notification { + +namespace { +constexpr const char *BUNDLE_INFO_NAME = "name"; +constexpr const char *BUNDLE_INFO_APP_INDEX = "index"; +constexpr const char *BUNDLE_INFO_SLOT_FLAGS = "slotFlags"; +constexpr const char *BUNDLE_INFO_SHOW_BADGE = "badge"; +constexpr const char *BUNDLE_INFO_ENABLE_NOTIFICATION = "enable"; +constexpr const char *BUNDLE_INFO_SLOT_LIST = "slotList"; +constexpr const char *BUNDLE_INFO_SLOT_TYPE = "slotType"; +constexpr const char *BUNDLE_INFO_SLOT_ENABLE = "slotEnable"; +constexpr const char *BUNDLE_INFO_SLOT_CONTROL = "slotControl"; +constexpr int32_t CONST_ENABLE_INT = 1; +} +void NotificationCloneBundleInfo::SetBundleName(const std::string &name) +{ + bundleName_ = name; +} + +std::string NotificationCloneBundleInfo::GetBundleName() const +{ + return bundleName_; +} + +void NotificationCloneBundleInfo::SetAppIndex(const int32_t &appIndex) +{ + appIndex_ = appIndex; +} + +int32_t NotificationCloneBundleInfo::GetAppIndex() const +{ + return appIndex_; +} + +void NotificationCloneBundleInfo::SetUid(const int32_t &uid) +{ + uid_ = uid; +} + +int32_t NotificationCloneBundleInfo::GetUid() const +{ + return uid_; +} + +void NotificationCloneBundleInfo::SetSlotFlags(const uint32_t &slotFlags) +{ + slotFlags_ = slotFlags; +} + +uint32_t NotificationCloneBundleInfo::GetSlotFlags() const +{ + return slotFlags_; +} + +void NotificationCloneBundleInfo::SetIsShowBadge(const bool &isShowBadge) +{ + isShowBadge_ = isShowBadge; +} + +bool NotificationCloneBundleInfo::GetIsShowBadge() const +{ + return isShowBadge_; +} + +void NotificationCloneBundleInfo::SetEnableNotification(const bool &enable) +{ + isEnabledNotification_ = enable; +} + +bool NotificationCloneBundleInfo::GetEnableNotification() const +{ + return isEnabledNotification_; +} + +void NotificationCloneBundleInfo::AddSlotInfo(const SlotInfo &slotInfo) +{ + for (auto& item : slotsInfo_) { + if (item.slotType_ == slotInfo.slotType_) { + item.enable_ = slotInfo.enable_; + item.isForceControl_ = slotInfo.isForceControl_; + return; + } + } + slotsInfo_.push_back(slotInfo); +} + +std::vector NotificationCloneBundleInfo::GetSlotInfo() const +{ + return slotsInfo_; +} + +void NotificationCloneBundleInfo::ToJson(nlohmann::json &jsonObject) const +{ + if (!slotsInfo_.empty()) { + nlohmann::json jsonNodes = nlohmann::json::array(); + for (size_t index = 0; index < slotsInfo_.size(); index++) { + nlohmann::json jsonNode; + jsonNode[BUNDLE_INFO_SLOT_TYPE] = static_cast(slotsInfo_[index].slotType_); + jsonNode[BUNDLE_INFO_SLOT_ENABLE] = slotsInfo_[index].enable_ ? 1 : 0; + jsonNode[BUNDLE_INFO_SLOT_CONTROL] = slotsInfo_[index].isForceControl_ ? 1 : 0; + jsonNodes.emplace_back(jsonNode); + } + jsonObject[BUNDLE_INFO_SLOT_LIST] = jsonNodes; + } + + jsonObject[BUNDLE_INFO_NAME] = bundleName_; + jsonObject[BUNDLE_INFO_APP_INDEX] = appIndex_; + jsonObject[BUNDLE_INFO_SLOT_FLAGS] = slotFlags_; + jsonObject[BUNDLE_INFO_SHOW_BADGE] = isShowBadge_ ? 1 : 0; + jsonObject[BUNDLE_INFO_ENABLE_NOTIFICATION] = isEnabledNotification_ ? 1 : 0; +} + +void NotificationCloneBundleInfo::SlotsFromJson(const nlohmann::json &jsonObject) +{ + if (!jsonObject.contains(BUNDLE_INFO_SLOT_LIST) || !jsonObject[BUNDLE_INFO_SLOT_LIST].is_array()) { + return; + } + + for (auto &slotJson : jsonObject.at(BUNDLE_INFO_SLOT_LIST)) { + SlotInfo slotInfo; + if (slotJson.contains(BUNDLE_INFO_SLOT_TYPE) && slotJson[BUNDLE_INFO_SLOT_TYPE].is_number()) { + slotInfo.slotType_ = static_cast( + slotJson.at(BUNDLE_INFO_SLOT_TYPE).get()); + } + if (slotJson.contains(BUNDLE_INFO_SLOT_ENABLE) && slotJson[BUNDLE_INFO_SLOT_ENABLE].is_number()) { + int32_t slotEnable = slotJson.at(BUNDLE_INFO_SLOT_ENABLE).get(); + slotInfo.enable_ = (slotEnable == CONST_ENABLE_INT); + } + if (slotJson.contains(BUNDLE_INFO_SLOT_CONTROL) && slotJson[BUNDLE_INFO_SLOT_CONTROL].is_number()) { + int32_t forceControl = slotJson.at(BUNDLE_INFO_SLOT_CONTROL).get(); + slotInfo.isForceControl_ = (forceControl == CONST_ENABLE_INT); + } + slotsInfo_.emplace_back(slotInfo); + } +} + +void NotificationCloneBundleInfo::FromJson(const nlohmann::json &jsonObject) +{ + if (jsonObject.is_null() || !jsonObject.is_object()) { + ANS_LOGE("Invalid JSON object"); + return; + } + if (jsonObject.is_discarded()) { + ANS_LOGE("Failed to parse json string."); + return; + } + + if (jsonObject.contains(BUNDLE_INFO_NAME) && jsonObject[BUNDLE_INFO_NAME].is_string()) { + bundleName_ = jsonObject.at(BUNDLE_INFO_NAME).get(); + } + if (jsonObject.contains(BUNDLE_INFO_APP_INDEX) && jsonObject[BUNDLE_INFO_APP_INDEX].is_number()) { + appIndex_ = jsonObject.at(BUNDLE_INFO_APP_INDEX).get(); + } + if (jsonObject.contains(BUNDLE_INFO_SLOT_FLAGS) && jsonObject[BUNDLE_INFO_SLOT_FLAGS].is_number()) { + slotFlags_ = jsonObject.at(BUNDLE_INFO_SLOT_FLAGS).get(); + } + if (jsonObject.contains(BUNDLE_INFO_SHOW_BADGE) && jsonObject[BUNDLE_INFO_SHOW_BADGE].is_number()) { + int32_t showBadge = jsonObject.at(BUNDLE_INFO_SHOW_BADGE).get(); + isShowBadge_ = (showBadge == CONST_ENABLE_INT); + } + if (jsonObject.contains(BUNDLE_INFO_ENABLE_NOTIFICATION) && + jsonObject[BUNDLE_INFO_ENABLE_NOTIFICATION].is_number()) { + int32_t enabledNotification = jsonObject.at(BUNDLE_INFO_ENABLE_NOTIFICATION).get(); + isEnabledNotification_ = (enabledNotification == CONST_ENABLE_INT); + } + SlotsFromJson(jsonObject); +} +std::string NotificationCloneBundleInfo::SlotInfo::Dump() const +{ + return "type: " + std::to_string(slotType_) + " " + std::to_string(enable_) + " " + + std::to_string(isForceControl_); +} + +std::string NotificationCloneBundleInfo::Dump() const +{ + std::string slotDump = "{"; + for (auto& slot : slotsInfo_) { + slotDump += slot.Dump(); + slotDump += ","; + } + slotDump += "}"; + return "CloneBundle{ name = " + bundleName_ + + ", index = " + std::to_string(appIndex_) + + ", uid = " + std::to_string(uid_) + + ", slotFlags = " + std::to_string(slotFlags_) + + ", ShowBadge = " + std::to_string(isShowBadge_) + + ", isEnabled = " + std::to_string(isEnabledNotification_) + + ", slotsInfo = " + slotDump + + " }"; +} +} +} diff --git a/services/ans/src/clone/notification_clone_bundle_service.cpp b/services/ans/src/clone/notification_clone_bundle_service.cpp new file mode 100644 index 000000000..3511ce3a0 --- /dev/null +++ b/services/ans/src/clone/notification_clone_bundle_service.cpp @@ -0,0 +1,155 @@ +/* +* Copyright (c) 2024-2024 Huawei Device Co., Ltd. +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +#include "notification_clone_bundle_service.h" + +#include "ans_log_wrapper.h" +#include "notification_preferences.h" +#include "notification_clone_util.h" +#include "notification_clone_bundle_info.h" +#include "os_account_manager_helper.h" + +namespace OHOS { +namespace Notification { +std::shared_ptr NotificationCloneBundle::GetInstance() +{ + static std::shared_ptr instance = + std::make_shared(); + return instance; +} + +NotificationCloneBundle::NotificationCloneBundle() +{ + cloneBundleQueue_ = std::make_shared("NotificationCloneBundleQueue"); + if (!cloneBundleQueue_) { + ANS_LOGE("ffrt create failed!"); + return; + } +} + +NotificationCloneBundle::~NotificationCloneBundle() +{ +} + +ErrCode NotificationCloneBundle::OnBackup(nlohmann::json &jsonObject) +{ + ANS_LOGI("Notification bundle backup."); + int32_t userId = NotificationCloneUtil::GetActiveUserId(); + std::vector cloneBundles; + NotificationPreferences::GetInstance()->GetAllCLoneBundlesInfo(userId, cloneBundles); + + if (cloneBundles.empty()) { + ANS_LOGI("Notification bundle list is empty."); + return ERR_OK; + } + jsonObject = nlohmann::json::array(); + for (size_t index = 0; index < cloneBundles.size(); index++) { + nlohmann::json jsonNode; + cloneBundles[index].ToJson(jsonNode); + jsonObject.emplace_back(jsonNode); + ANS_LOGD("Event bundle backup %{public}s.", cloneBundles[index].Dump().c_str()); + } + ANS_LOGD("Notification bundle list %{public}s", jsonObject.dump().c_str()); + return ERR_OK; +} + +void NotificationCloneBundle::OnRestore(const nlohmann::json &jsonObject) +{ + ANS_LOGI("Notification bundle list on restore."); + if (jsonObject.is_null() || !jsonObject.is_array()) { + ANS_LOGI("Notification disturb profile list is null or not array."); + return; + } + + int32_t userId = NotificationCloneUtil::GetActiveUserId(); + std::unique_lock lock(lock_); + bundlesInfo_.clear(); + for (const auto &profile : jsonObject) { + NotificationCloneBundleInfo cloneBundleInfo;; + cloneBundleInfo.FromJson(profile); + bundlesInfo_.emplace_back(cloneBundleInfo); + } + ANS_LOGI("Notification bundle list size %{public}zu.", bundlesInfo_.size()); + if (cloneBundleQueue_ == nullptr || bundlesInfo_.empty()) { + ANS_LOGE("Clone bundle is invalidated or empty."); + return; + } + + for (auto bundle = bundlesInfo_.begin(); bundle != bundlesInfo_.end();) { + int32_t uid = NotificationCloneUtil::GetBundleUid(bundle->GetBundleName(), + userId, bundle->GetAppIndex()); + if (uid == -1) { + bundle++; + continue; + } + bundle->SetUid(uid); + NotificationPreferences::GetInstance()->UpdateCloneBundleInfo(userId, *bundle); + bundle = bundlesInfo_.erase(bundle); + } + + for (auto bundle = bundlesInfo_.begin(); bundle != bundlesInfo_.end(); bundle++) { + ANS_LOGI("Event bundle left %{public}s.", bundle->Dump().c_str()); + } + ANS_LOGI("Notification bundle list on restore end."); +} + +void NotificationCloneBundle::OnBundleDataAdd(const sptr &bundleOption) +{ + HandleBundleEvent(bundleOption->GetBundleName(), bundleOption->GetAppIndex(), bundleOption->GetUid()); +} + +void NotificationCloneBundle::OnBundleDataUpdate(const sptr &bundleOption) +{ + HandleBundleEvent(bundleOption->GetBundleName(), bundleOption->GetAppIndex(), bundleOption->GetUid()); +} + +void NotificationCloneBundle::HandleBundleEvent(const std::string bundleName, int32_t appIndex, int32_t uid) +{ + ANS_LOGI("Handle bundle event %{public}s %{public}d %{public}d %{public}zu.", + bundleName.c_str(), appIndex, uid, bundlesInfo_.size()); + if (bundlesInfo_.empty()) { + return; + } + + int32_t userId = -1; + OsAccountManagerHelper::GetInstance().GetOsAccountLocalIdFromUid(uid, userId); + std::unique_lock lcck(lock_); + for (auto bundle = bundlesInfo_.begin(); bundle != bundlesInfo_.end();) { + if (bundle->GetBundleName() == bundleName && bundle->GetAppIndex() == appIndex) { + bundle->SetUid(uid); + NotificationPreferences::GetInstance()->UpdateCloneBundleInfo(userId, *bundle); + bundle = bundlesInfo_.erase(bundle); + break; + } + bundle++; + } + ANS_LOGI("Event bundle left %{public}zu.", bundlesInfo_.size()); +} + +void NotificationCloneBundle::OnUserSwitch(int32_t userId) +{ + ANS_LOGI("Handler user switch %{public}d", userId); + if (cloneBundleQueue_ == nullptr) { + ANS_LOGW("Clone bundle queue is null."); + return; + } + cloneBundleQueue_->submit_h(std::bind([&]() { + std::unique_lock lock(lock_); + bundlesInfo_.clear(); + })); +} + +} +} diff --git a/services/ans/src/clone/notification_clone_disturb_service.cpp b/services/ans/src/clone/notification_clone_disturb_service.cpp index 448307a51..6ec7c8466 100644 --- a/services/ans/src/clone/notification_clone_disturb_service.cpp +++ b/services/ans/src/clone/notification_clone_disturb_service.cpp @@ -17,12 +17,10 @@ #include "ans_log_wrapper.h" #include "notification_preferences.h" -#include "bundle_manager_helper.h" -#include "os_account_manager.h" +#include "notification_clone_util.h" namespace OHOS { namespace Notification { -constexpr int32_t MAIN_USER_ID = 100; std::shared_ptr NotificationCloneDisturb::GetInstance() { static std::shared_ptr instance = @@ -45,7 +43,7 @@ NotificationCloneDisturb::~NotificationCloneDisturb() ErrCode NotificationCloneDisturb::OnBackup(nlohmann::json &jsonObject) { - int32_t userId = GetActiveUserId(); + int32_t userId = NotificationCloneUtil::GetActiveUserId(); std::vector> profiles; NotificationPreferences::GetInstance()->GetDoNotDisturbProfileListByUserId(userId, profiles); @@ -63,12 +61,12 @@ ErrCode NotificationCloneDisturb::OnBackup(nlohmann::json &jsonObject) return ERR_OK; } -ErrCode NotificationCloneDisturb::OnRestore(const nlohmann::json &jsonObject) +void NotificationCloneDisturb::OnRestore(const nlohmann::json &jsonObject) { ANS_LOGI("Notification disturb profile list on restore."); if (jsonObject.is_null() || !jsonObject.is_array()) { ANS_LOGI("Notification disturb profile list is null or not array."); - return ERR_OK; + return; } profiles_.clear(); @@ -80,10 +78,10 @@ ErrCode NotificationCloneDisturb::OnRestore(const nlohmann::json &jsonObject) if (cloneDisturbQueue_ == nullptr || profiles_.empty()) { ANS_LOGE("Clone queue is invalidated or empty %{public}zu.", profiles_.size()); - return ERR_OK; + return; } - int32_t userId = GetActiveUserId(); + int32_t userId = NotificationCloneUtil::GetActiveUserId(); cloneDisturbQueue_->submit_h(std::bind([&, userId]() { ANS_LOGI("Notification disturb profile ffrt start %{public}zu.", profiles_.size()); int32_t profileId = -1; @@ -113,8 +111,8 @@ ErrCode NotificationCloneDisturb::OnRestore(const nlohmann::json &jsonObject) ANS_LOGI("Clone queue left %{public}d %{public}zu.", (*profile)->GetProfileId(), (*profile)->GetProfileTrustList().size()); } + ANS_LOGI("Notification disturb profile list on restore end."); })); - return ERR_OK; } void NotificationCloneDisturb::GetProfileUid(int32_t userId, std::map& uidMap, @@ -127,7 +125,7 @@ void NotificationCloneDisturb::GetProfileUid(int32_t userId, std::mapGetDefaultUidByBundleName(bundleName, userId); - } - return BundleManagerHelper::GetInstance()->GetDefaultUidByBundleName(bundleName, userId, appIndex); -} - -int32_t NotificationCloneDisturb::GetActiveUserId() -{ - std::vector activeUserId; - OHOS::AccountSA::OsAccountManager::QueryActiveOsAccountIds(activeUserId); - if (activeUserId.size() > 0) { - return activeUserId[0]; - } - return MAIN_USER_ID; -} } } diff --git a/services/ans/src/clone/notification_clone_manager.cpp b/services/ans/src/clone/notification_clone_manager.cpp index 9976dda31..ae65acf2b 100644 --- a/services/ans/src/clone/notification_clone_manager.cpp +++ b/services/ans/src/clone/notification_clone_manager.cpp @@ -25,11 +25,13 @@ #include "ans_log_wrapper.h" #include "nlohmann/json.hpp" #include "notification_clone_disturb_service.h" +#include "notification_clone_bundle_service.h" namespace OHOS { namespace Notification { const int ANS_CLONE_ERROR = -1; +constexpr const char *CLONE_ITEM_BUNDLE_INFO = "notificationBundle"; constexpr const char *CLONE_ITEM_DISTURB = "notificationDisturb"; constexpr const char *BACKUP_CONFIG_FILE_PATH = "/data/service/el1/public/notification/backup_config.conf"; @@ -109,6 +111,7 @@ int32_t NotificationCloneManager::OnRestore(MessageParcel& data, MessageParcel& NotificationCloneManager::NotificationCloneManager() { ANS_LOGI("Notification clone manager init."); + cloneTemplates.insert_or_assign(CLONE_ITEM_BUNDLE_INFO, NotificationCloneBundle::GetInstance()); cloneTemplates.insert_or_assign(CLONE_ITEM_DISTURB, NotificationCloneDisturb::GetInstance()); } @@ -175,5 +178,12 @@ void NotificationCloneManager::RemoveBackUpFile() { remove(BACKUP_CONFIG_FILE_PATH); } + +void NotificationCloneManager::OnUserSwitch(int32_t userId) +{ + for (auto iter = cloneTemplates.begin(); iter != cloneTemplates.end(); ++iter) { + iter->second->OnUserSwitch(userId); + } +} } } diff --git a/services/ans/src/clone/notification_clone_util.cpp b/services/ans/src/clone/notification_clone_util.cpp new file mode 100644 index 000000000..eeb074b79 --- /dev/null +++ b/services/ans/src/clone/notification_clone_util.cpp @@ -0,0 +1,43 @@ +/* +* Copyright (c) 2024-2024 Huawei Device Co., Ltd. +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +#include "notification_clone_util.h" + +#include "bundle_manager_helper.h" +#include "os_account_manager.h" + +namespace OHOS { +namespace Notification { + +constexpr int32_t MAIN_USER_ID = 100; +int32_t NotificationCloneUtil::GetActiveUserId() +{ + std::vector activeUserId; + OHOS::AccountSA::OsAccountManager::QueryActiveOsAccountIds(activeUserId); + if (activeUserId.size() > 0) { + return activeUserId[0]; + } + return MAIN_USER_ID; +} + +int32_t NotificationCloneUtil::GetBundleUid(const std::string bundleName, int32_t userId, int32_t appIndex) +{ + if (appIndex == -1) { + return BundleManagerHelper::GetInstance()->GetDefaultUidByBundleName(bundleName, userId); + } + return BundleManagerHelper::GetInstance()->GetDefaultUidByBundleName(bundleName, userId, appIndex); +} +} +} diff --git a/services/ans/src/notification_preferences.cpp b/services/ans/src/notification_preferences.cpp index de48054a1..a6c44ff1b 100644 --- a/services/ans/src/notification_preferences.cpp +++ b/services/ans/src/notification_preferences.cpp @@ -29,10 +29,13 @@ #include "nlohmann/json.hpp" #include "os_account_manager_helper.h" #include "notification_analytics_util.h" +#include "notification_config_parse.h" namespace OHOS { namespace Notification { - +namespace { +const static std::string KEY_BUNDLE_LABEL = "label_ans_bundle_"; +} std::mutex NotificationPreferences::instanceMutex_; std::shared_ptr NotificationPreferences::instance_; @@ -638,6 +641,71 @@ ErrCode NotificationPreferences::UpdateDoNotDisturbProfiles(int32_t userId, int3 return ERR_OK; } +void NotificationPreferences::UpdateCloneBundleInfo(int32_t userId, + const NotificationCloneBundleInfo& cloneBundleInfo) +{ + ANS_LOGI("Event bundle update %{public}s.", cloneBundleInfo.Dump().c_str()); + NotificationPreferencesInfo::BundleInfo bundleInfo; + sptr bundleOption = new NotificationBundleOption(); + bundleOption->SetBundleName(cloneBundleInfo.GetBundleName()); + bundleOption->SetUid(cloneBundleInfo.GetUid()); + std::lock_guard lock(preferenceMutex_); + NotificationPreferencesInfo preferencesInfo = preferencesInfo_; + if (!preferencesInfo.GetBundleInfo(bundleOption, bundleInfo)) { + bundleInfo.SetBundleName(cloneBundleInfo.GetBundleName()); + bundleInfo.SetBundleUid(cloneBundleInfo.GetUid()); + } + + /* after clone, override these witch */ + bundleInfo.SetSlotFlags(cloneBundleInfo.GetSlotFlags()); + bundleInfo.SetIsShowBadge(cloneBundleInfo.GetIsShowBadge()); + bundleInfo.SetEnableNotification(cloneBundleInfo.GetEnableNotification()); + /* update property to db */ + if (!preferncesDB_->UpdateBundlePropertyToDisturbeDB(userId, bundleInfo)) { + ANS_LOGW("Clone bundle info failed %{public}s.", cloneBundleInfo.Dump().c_str()); + return; + } + preferencesInfo.SetBundleInfo(bundleInfo); + + /* update slot info */ + std::vector> slots; + for (auto& cloneSlot : cloneBundleInfo.GetSlotInfo()) { + sptr slotInfo = new (std::nothrow) NotificationSlot(cloneSlot.slotType_); + uint32_t slotFlags = bundleInfo.GetSlotFlags(); + auto configSlotReminderMode = DelayedSingleton::GetInstance()-> + GetConfigSlotReminderModeByType(slotInfo->GetType()); + slotInfo->SetReminderMode(configSlotReminderMode & slotFlags); + slotInfo->SetEnable(cloneSlot.enable_); + slotInfo->SetForceControl(cloneSlot.isForceControl_); + slotInfo->SetAuthorizedStatus(NotificationSlot::AuthorizedStatus::AUTHORIZED); + slots.push_back(slotInfo); + bundleInfo.SetSlot(slotInfo); + } + + if (!preferncesDB_->UpdateBundleSlotToDisturbeDB(userId, cloneBundleInfo.GetBundleName(), + cloneBundleInfo.GetUid(), slots)) { + ANS_LOGW("Clone bundle slot failed %{public}s.", cloneBundleInfo.Dump().c_str()); + preferencesInfo_ = preferencesInfo; + return; + } + preferencesInfo.SetBundleInfo(bundleInfo); + preferencesInfo_ = preferencesInfo; +} + +void NotificationPreferences::GetAllCLoneBundlesInfo(int32_t userId, + std::vector &cloneBundles) +{ + std::lock_guard lock(preferenceMutex_); + NotificationPreferencesInfo preferencesInfo = preferencesInfo_; + std::unordered_map bundlesMap; + if (GetBatchKvsFromDb(KEY_BUNDLE_LABEL, bundlesMap, userId) != ERR_OK) { + ANS_LOGE("Get bundle map info failed."); + return; + } + preferencesInfo.GetAllCLoneBundlesInfo(userId, bundlesMap, cloneBundles); + preferencesInfo_ = preferencesInfo; +} + void NotificationPreferences::GetDoNotDisturbProfileListByUserId(int32_t userId, std::vector> &profiles) { diff --git a/services/ans/src/notification_preferences_database.cpp b/services/ans/src/notification_preferences_database.cpp index 8ff63d1c8..d331ea0d1 100644 --- a/services/ans/src/notification_preferences_database.cpp +++ b/services/ans/src/notification_preferences_database.cpp @@ -2004,5 +2004,59 @@ bool NotificationPreferencesDatabase::CheckApiCompatibility(const std::string &b } return bundleManager->CheckApiCompatibility(bundleName, uid); } + +bool NotificationPreferencesDatabase::UpdateBundlePropertyToDisturbeDB(int32_t userId, + const NotificationPreferencesInfo::BundleInfo &bundleInfo) +{ + if (bundleInfo.GetBundleName().empty()) { + ANS_LOGE("Bundle name is null."); + return false; + } + + if (!CheckRdbStore()) { + ANS_LOGE("RdbStore is nullptr."); + return false; + } + std::string value; + std::string bundleLabelKey = KEY_BUNDLE_LABEL + GenerateBundleLablel(bundleInfo); + int32_t result = rdbDataManager_->QueryData(bundleLabelKey, value, userId); + if (result == NativeRdb::E_EMPTY_VALUES_BUCKET) { + if (rdbDataManager_->InsertData(bundleLabelKey, GenerateBundleLablel(bundleInfo), userId) + != NativeRdb::E_OK) { + ANS_LOGE("Store bundle name %{public}s to db is failed.", bundleLabelKey.c_str()); + return false; + } + } + if (result == NativeRdb::E_EMPTY_VALUES_BUCKET || result == NativeRdb::E_OK) { + return PutBundlePropertyValueToDisturbeDB(bundleInfo); + } + ANS_LOGW("Query bundle name %{public}s failed %{public}d.", bundleLabelKey.c_str(), result); + return false; +} + +bool NotificationPreferencesDatabase::UpdateBundleSlotToDisturbeDB(int32_t userId, const std::string &bundleName, + const int32_t &bundleUid, const std::vector> &slots) +{ + if (bundleName.empty()) { + ANS_LOGE("Bundle name is null."); + return false; + } + if (slots.empty()) { + ANS_LOGI("Slot is empty."); + return true; + } + + std::string bundleKey = bundleName + std::to_string(bundleUid); + std::unordered_map values; + for (auto& slot : slots) { + GenerateSlotEntry(bundleKey, slot, values); + } + if (!CheckRdbStore()) { + ANS_LOGE("RdbStore is nullptr."); + return false; + } + int32_t result = rdbDataManager_->InsertBatchData(values, userId); + return (result == NativeRdb::E_OK); +} } // namespace Notification } // namespace OHOS diff --git a/services/ans/src/notification_preferences_info.cpp b/services/ans/src/notification_preferences_info.cpp index d32f07b60..c88831f60 100644 --- a/services/ans/src/notification_preferences_info.cpp +++ b/services/ans/src/notification_preferences_info.cpp @@ -16,6 +16,7 @@ #include "ans_log_wrapper.h" #include "notification_constant.h" +#include "bundle_manager_helper.h" namespace OHOS { namespace Notification { @@ -334,6 +335,38 @@ void NotificationPreferencesInfo::GetAllDoNotDisturbProfiles( } } +void NotificationPreferencesInfo::GetAllCLoneBundlesInfo(const int32_t &userId, + const std::unordered_map &bunlesMap, + std::vector &cloneBundles) +{ + for (const auto& bundleItem : bunlesMap) { + auto iter = infos_.find(bundleItem.second); + if (iter == infos_.end()) { + ANS_LOGI("No finde bundle info %{public}s.", bundleItem.second.c_str()); + continue; + } + + std::vector> slots; + NotificationCloneBundleInfo cloneBundleInfo; + int32_t index = BundleManagerHelper::GetInstance()->GetAppIndexByUid(iter->second.GetBundleUid()); + cloneBundleInfo.SetBundleName(iter->second.GetBundleName()); + cloneBundleInfo.SetAppIndex(index); + cloneBundleInfo.SetSlotFlags(iter->second.GetSlotFlags()); + cloneBundleInfo.SetIsShowBadge(iter->second.GetIsShowBadge()); + cloneBundleInfo.SetEnableNotification(iter->second.GetEnableNotification()); + iter->second.GetAllSlots(slots); + for (auto& slot : slots) { + NotificationCloneBundleInfo::SlotInfo slotInfo; + slotInfo.slotType_ = slot->GetType(); + slotInfo.enable_ = slot->GetEnable(); + slotInfo.isForceControl_ = slot->GetForceControl(); + cloneBundleInfo.AddSlotInfo(slotInfo); + } + cloneBundles.emplace_back(cloneBundleInfo); + } + ANS_LOGI("GetAllCLoneBundlesInfo size: %{public}zu.", cloneBundles.size()); +} + bool NotificationPreferencesInfo::GetDoNotDisturbDate(const int32_t &userId, sptr &doNotDisturbDate) const { diff --git a/services/ans/src/system_event_observer.cpp b/services/ans/src/system_event_observer.cpp index fd14a6714..2fab63ba9 100644 --- a/services/ans/src/system_event_observer.cpp +++ b/services/ans/src/system_event_observer.cpp @@ -21,7 +21,7 @@ #include "common_event_manager.h" #include "common_event_support.h" #include "notification_preferences.h" -#include "notification_clone_disturb_service.h" +#include "notification_clone_manager.h" namespace OHOS { namespace Notification { @@ -102,7 +102,7 @@ void SystemEventObserver::OnReceiveEvent(const EventFwk::CommonEventData &data) } NotificationPreferences::GetInstance()->InitSettingFromDisturbDB(userId); AdvancedNotificationService::GetInstance()->RecoverLiveViewFromDb(userId); - NotificationCloneDisturb::GetInstance()->OnUserSwitch(userId); + NotificationCloneManager::GetInstance().OnUserSwitch(userId); } else if (action == EventFwk::CommonEventSupport::COMMON_EVENT_USER_REMOVED) { int32_t userId = data.GetCode(); if (userId <= SUBSCRIBE_USER_INIT) { -- Gitee From 2befd7afac84c83ad94ddab456c4900872ee193d Mon Sep 17 00:00:00 2001 From: markYao Date: Sat, 21 Sep 2024 18:36:48 +0800 Subject: [PATCH 096/167] =?UTF-8?q?ANS=E6=B5=81=E6=8E=A7=E6=9C=BA=E5=88=B6?= =?UTF-8?q?=E4=BC=98=E5=8C=96?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: markYao --- .../include/advanced_notification_service.h | 8 +- .../ans/src/advanced_notification_service.cpp | 140 ++++++++++++++---- 2 files changed, 121 insertions(+), 27 deletions(-) diff --git a/services/ans/include/advanced_notification_service.h b/services/ans/include/advanced_notification_service.h index ffaebba74..80994459a 100644 --- a/services/ans/include/advanced_notification_service.h +++ b/services/ans/include/advanced_notification_service.h @@ -1413,7 +1413,9 @@ private: ErrCode CheckNeedSilent(const std::string &phoneNumber, int32_t callerType, int32_t userId); uint32_t GetDefaultSlotFlags(const sptr &request); ErrCode OnRecoverLiveView(const std::vector &keys); - + bool IsSystemUser(int32_t userId); + ErrCode UpdateFlowCtrl(const std::shared_ptr &record); + ErrCode PublishFlowControlInner(const std::shared_ptr &record); private: static sptr instance_; static std::mutex instanceMutex_; @@ -1428,6 +1430,10 @@ private: std::list flowControlTimestampList_; std::list flowControlUpdateTimestampList_; std::list flowControlPublishTimestampList_; + static std::mutex systemFlowControlMutex_; + std::list systemFlowControlTimestampList_; + std::list systemFlowControlUpdateTimestampList_; + std::list systemFlowControlPublishTimestampList_; std::shared_ptr recentInfo_ = nullptr; std::shared_ptr distributedKvStoreDeathRecipient_ = nullptr; std::shared_ptr systemEventObserver_ = nullptr; diff --git a/services/ans/src/advanced_notification_service.cpp b/services/ans/src/advanced_notification_service.cpp index 0a99c72d2..aa7d8bb87 100644 --- a/services/ans/src/advanced_notification_service.cpp +++ b/services/ans/src/advanced_notification_service.cpp @@ -98,6 +98,7 @@ sptr AdvancedNotificationService::instance_; std::mutex AdvancedNotificationService::instanceMutex_; std::mutex AdvancedNotificationService::pushMutex_; std::mutex AdvancedNotificationService::flowControlMutex_; +std::mutex AdvancedNotificationService::systemFlowControlMutex_; std::map slotFlagsDefaultMap_; std::map> AdvancedNotificationService::pushCallBacks_; @@ -956,20 +957,52 @@ void AdvancedNotificationService::AddToNotificationList(const std::shared_ptr &record) +ErrCode AdvancedNotificationService::UpdateFlowCtrl(const std::shared_ptr &record) { std::chrono::system_clock::time_point now = std::chrono::system_clock::now(); - NotificationAnalyticsUtil::RemoveExpired(flowControlUpdateTimestampList_, now); - if (flowControlUpdateTimestampList_.size() >= MAX_UPDATE_NUM_PERSECOND) { - HaMetaMessage message = HaMetaMessage(EventSceneId::SCENE_2, EventBranchId::BRANCH_4) - .ErrorCode(ERR_ANS_OVER_MAX_UPDATE_PERSECOND).Message("UpdateInNotificationList failed"); - if (record != nullptr) { - NotificationAnalyticsUtil::ReportPublishFailedEvent(record->request, message); + auto uid = record->request->GetCreatorUid(); + int32_t userId = SUBSCRIBE_USER_INIT; + OsAccountManagerHelper::GetInstance().GetOsAccountLocalIdFromUid(uid, userId); + bool isSystemApp = BundleManagerHelper::GetInstance()->IsSystemApp(uid); + bool isSubsystem = IsSystemUser(userId); + ANS_LOGD("UpdateInNotificationList uid %{public}d, userid %{public}d, size %{public}zu,%{public}zu", + uid, userId, flowControlUpdateTimestampList_.size(), systemFlowControlUpdateTimestampList_.size()); + if (!isSubsystem && !isSystemApp) { + // 三方流控 + std::lock_guard lock(flowControlMutex_); + NotificationAnalyticsUtil::RemoveExpired(flowControlUpdateTimestampList_, now); + if (flowControlUpdateTimestampList_.size() >= MAX_UPDATE_NUM_PERSECOND) { + HaMetaMessage message = HaMetaMessage(EventSceneId::SCENE_2, EventBranchId::BRANCH_4) + .ErrorCode(ERR_ANS_OVER_MAX_UPDATE_PERSECOND).Message("UpdateInNotificationList failed"); + if (record != nullptr) { + NotificationAnalyticsUtil::ReportPublishFailedEvent(record->request, message); + } + return ERR_ANS_OVER_MAX_UPDATE_PERSECOND; } - return ERR_ANS_OVER_MAX_UPDATE_PERSECOND; + flowControlUpdateTimestampList_.push_back(now); + } else { + // 系统流控 + std::lock_guard lock(systemFlowControlMutex_); + NotificationAnalyticsUtil::RemoveExpired(systemFlowControlUpdateTimestampList_, now); + if (systemFlowControlUpdateTimestampList_.size() >= MAX_UPDATE_NUM_PERSECOND) { + HaMetaMessage message = HaMetaMessage(EventSceneId::SCENE_2, EventBranchId::BRANCH_4) + .ErrorCode(ERR_ANS_OVER_MAX_UPDATE_PERSECOND).Message("UpdateInNotificationList failed"); + if (record != nullptr) { + NotificationAnalyticsUtil::ReportPublishFailedEvent(record->request, message); + } + return ERR_ANS_OVER_MAX_UPDATE_PERSECOND; + } + systemFlowControlUpdateTimestampList_.push_back(now); } + return ERR_OK; +} - flowControlUpdateTimestampList_.push_back(now); +ErrCode AdvancedNotificationService::UpdateInNotificationList(const std::shared_ptr &record) +{ + ErrCode result = UpdateFlowCtrl(record); + if (result != ERR_OK) { + return result; + } auto iter = notificationList_.begin(); while (iter != notificationList_.end()) { if ((*iter)->notification->GetKey() == record->notification->GetKey()) { @@ -1457,33 +1490,88 @@ ErrCode AdvancedNotificationService::FlowControl(const std::shared_ptr lock(flowControlMutex_); - NotificationAnalyticsUtil::RemoveExpired(flowControlTimestampList_, now); - if (flowControlTimestampList_.size() >= MAX_ACTIVE_NUM_PERSECOND + MAX_UPDATE_NUM_PERSECOND) { - message.ErrorCode(ERR_ANS_OVER_MAX_ACTIVE_PERSECOND); - NotificationAnalyticsUtil::ReportPublishFailedEvent(record->request, message); - return ERR_ANS_OVER_MAX_ACTIVE_PERSECOND; + + auto uid = record->request->GetCreatorUid(); + int32_t userId = SUBSCRIBE_USER_INIT; + OsAccountManagerHelper::GetInstance().GetOsAccountLocalIdFromUid(uid, userId); + bool isSystemApp = BundleManagerHelper::GetInstance()->IsSystemApp(uid); + bool isSubsystem = IsSystemUser(userId); + ANS_LOGD("FlowControl uid %{public}d, userid %{public}d, size %{public}zu,%{public}zu", + uid, userId, flowControlTimestampList_.size(), systemFlowControlTimestampList_.size()); + if (!isSubsystem && !isSystemApp) { + std::lock_guard lock(flowControlMutex_); + NotificationAnalyticsUtil::RemoveExpired(flowControlTimestampList_, now); + if (flowControlTimestampList_.size() >= MAX_ACTIVE_NUM_PERSECOND + MAX_UPDATE_NUM_PERSECOND) { + message.ErrorCode(ERR_ANS_OVER_MAX_ACTIVE_PERSECOND); + NotificationAnalyticsUtil::ReportPublishFailedEvent(record->request, message); + return ERR_ANS_OVER_MAX_ACTIVE_PERSECOND; + } + flowControlTimestampList_.push_back(now); + } else { + std::lock_guard lock(systemFlowControlMutex_); + NotificationAnalyticsUtil::RemoveExpired(systemFlowControlTimestampList_, now); + if (systemFlowControlTimestampList_.size() >= MAX_ACTIVE_NUM_PERSECOND + MAX_UPDATE_NUM_PERSECOND) { + message.ErrorCode(ERR_ANS_OVER_MAX_ACTIVE_PERSECOND); + NotificationAnalyticsUtil::ReportPublishFailedEvent(record->request, message); + return ERR_ANS_OVER_MAX_ACTIVE_PERSECOND; + } + systemFlowControlTimestampList_.push_back(now); } - flowControlTimestampList_.push_back(now); return ERR_OK; } -ErrCode AdvancedNotificationService::PublishFlowControl(const std::shared_ptr &record) +bool AdvancedNotificationService::IsSystemUser(int32_t userId) +{ + return ((userId >= SUBSCRIBE_USER_SYSTEM_BEGIN) && (userId <= SUBSCRIBE_USER_SYSTEM_END)); +} + +ErrCode AdvancedNotificationService::PublishFlowControlInner(const std::shared_ptr &record) { std::chrono::system_clock::time_point now = std::chrono::system_clock::now(); - NotificationAnalyticsUtil::RemoveExpired(flowControlPublishTimestampList_, now); - if (flowControlPublishTimestampList_.size() >= MAX_ACTIVE_NUM_PERSECOND) { - HaMetaMessage message = HaMetaMessage(EventSceneId::SCENE_2, EventBranchId::BRANCH_3) - .ErrorCode(ERR_ANS_OVER_MAX_ACTIVE_PERSECOND).Message("PublishFlowControl failed"); - if (record != nullptr) { - NotificationAnalyticsUtil::ReportPublishFailedEvent(record->request, message); + auto uid = record->request->GetCreatorUid(); + int32_t userId = SUBSCRIBE_USER_INIT; + OsAccountManagerHelper::GetInstance().GetOsAccountLocalIdFromUid(uid, userId); + bool isSystemApp = BundleManagerHelper::GetInstance()->IsSystemApp(uid); + bool isSubsystem = IsSystemUser(userId); + ANS_LOGD("PublishFlowControl uid %{public}d, userid %{public}d, size %{public}zu,%{public}zu", + uid, userId, flowControlPublishTimestampList_.size(), systemFlowControlPublishTimestampList_.size()); + if (!isSubsystem && !isSystemApp) { + // 三方流控 + std::lock_guard lock(flowControlMutex_); + NotificationAnalyticsUtil::RemoveExpired(flowControlPublishTimestampList_, now); + if (flowControlPublishTimestampList_.size() >= MAX_ACTIVE_NUM_PERSECOND) { + HaMetaMessage message = HaMetaMessage(EventSceneId::SCENE_2, EventBranchId::BRANCH_3) + .ErrorCode(ERR_ANS_OVER_MAX_ACTIVE_PERSECOND).Message("PublishFlowControl failed"); + if (record != nullptr) { + NotificationAnalyticsUtil::ReportPublishFailedEvent(record->request, message); + } + return ERR_ANS_OVER_MAX_ACTIVE_PERSECOND; } - return ERR_ANS_OVER_MAX_ACTIVE_PERSECOND; + flowControlPublishTimestampList_.push_back(now); + } else { + // 系统流控 + std::lock_guard lock(systemFlowControlMutex_); + NotificationAnalyticsUtil::RemoveExpired(systemFlowControlPublishTimestampList_, now); + if (systemFlowControlPublishTimestampList_.size() >= MAX_ACTIVE_NUM_PERSECOND) { + HaMetaMessage message = HaMetaMessage(EventSceneId::SCENE_2, EventBranchId::BRANCH_3) + .ErrorCode(ERR_ANS_OVER_MAX_ACTIVE_PERSECOND).Message("PublishFlowControl failed"); + if (record != nullptr) { + NotificationAnalyticsUtil::ReportPublishFailedEvent(record->request, message); + } + return ERR_ANS_OVER_MAX_ACTIVE_PERSECOND; + } + systemFlowControlPublishTimestampList_.push_back(now); } + return ERR_OK; +} - flowControlPublishTimestampList_.push_back(now); - +ErrCode AdvancedNotificationService::PublishFlowControl(const std::shared_ptr &record) +{ + ErrCode result = PublishFlowControlInner(record); + if (result != ERR_OK) { + return result; + } std::list> bundleList; for (auto item : notificationList_) { if (record->notification->GetBundleName() == item->notification->GetBundleName()) { -- Gitee From 667fea3bd71bdb363d09c413fb163540aa7d7605 Mon Sep 17 00:00:00 2001 From: markYao Date: Tue, 8 Oct 2024 14:42:44 +0800 Subject: [PATCH 097/167] =?UTF-8?q?ANS=E6=B5=81=E6=8E=A7=E9=80=BB=E8=BE=91?= =?UTF-8?q?=E4=BC=98=E5=8C=96?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: markYao --- services/ans/include/notification_record.h | 2 + ...dvanced_notification_live_view_service.cpp | 1 + .../advanced_notification_publish_service.cpp | 1 + .../ans/src/advanced_notification_service.cpp | 53 ++++++++++--------- 4 files changed, 31 insertions(+), 26 deletions(-) diff --git a/services/ans/include/notification_record.h b/services/ans/include/notification_record.h index fa847daae..d1e78b6e7 100644 --- a/services/ans/include/notification_record.h +++ b/services/ans/include/notification_record.h @@ -33,6 +33,8 @@ struct NotificationRecord { sptr notification; sptr slot; int32_t finish_status = -1; + bool isThirdparty {true}; + bool isNeedFlowCtrl {true}; #ifdef DISTRIBUTED_NOTIFICATION_SUPPORTED std::string deviceId; std::string bundleName; diff --git a/services/ans/src/advanced_notification_live_view_service.cpp b/services/ans/src/advanced_notification_live_view_service.cpp index 506751f25..6a4e5536c 100644 --- a/services/ans/src/advanced_notification_live_view_service.cpp +++ b/services/ans/src/advanced_notification_live_view_service.cpp @@ -68,6 +68,7 @@ void AdvancedNotificationService::RecoverLiveViewFromDb(int32_t userId) } auto record = std::make_shared(); + record->isNeedFlowCtrl = false; if (FillNotificationRecord(requestObj, record) != ERR_OK) { ANS_LOGE("Fill notification record failed."); continue; diff --git a/services/ans/src/advanced_notification_publish_service.cpp b/services/ans/src/advanced_notification_publish_service.cpp index 99e5ef08c..9436a10cb 100644 --- a/services/ans/src/advanced_notification_publish_service.cpp +++ b/services/ans/src/advanced_notification_publish_service.cpp @@ -2240,6 +2240,7 @@ ErrCode AdvancedNotificationService::PublishNotificationBySa(const sptr record = std::make_shared(); record->request = request; + record->isThirdparty = false; if (request->IsAgentNotification()) { record->bundleOption = new (std::nothrow) NotificationBundleOption("", request->GetCreatorUid()); } else { diff --git a/services/ans/src/advanced_notification_service.cpp b/services/ans/src/advanced_notification_service.cpp index aa7d8bb87..c2f1a9780 100644 --- a/services/ans/src/advanced_notification_service.cpp +++ b/services/ans/src/advanced_notification_service.cpp @@ -629,8 +629,16 @@ ErrCode AdvancedNotificationService::PublishPreparedNotification(const sptrisThirdparty = isThirdparty; ErrCode result = CheckPublishPreparedNotification(record, isSystemApp); if (result != ERR_OK) { message.ErrorCode(result); @@ -959,15 +967,13 @@ void AdvancedNotificationService::AddToNotificationList(const std::shared_ptr &record) { + if (record->isNeedFlowCtrl == false) { + return ERR_OK; + } std::chrono::system_clock::time_point now = std::chrono::system_clock::now(); - auto uid = record->request->GetCreatorUid(); - int32_t userId = SUBSCRIBE_USER_INIT; - OsAccountManagerHelper::GetInstance().GetOsAccountLocalIdFromUid(uid, userId); - bool isSystemApp = BundleManagerHelper::GetInstance()->IsSystemApp(uid); - bool isSubsystem = IsSystemUser(userId); - ANS_LOGD("UpdateInNotificationList uid %{public}d, userid %{public}d, size %{public}zu,%{public}zu", - uid, userId, flowControlUpdateTimestampList_.size(), systemFlowControlUpdateTimestampList_.size()); - if (!isSubsystem && !isSystemApp) { + ANS_LOGD("UpdateInNotificationList size %{public}zu,%{public}zu", + flowControlUpdateTimestampList_.size(), systemFlowControlUpdateTimestampList_.size()); + if (record->isThirdparty == true) { // 三方流控 std::lock_guard lock(flowControlMutex_); NotificationAnalyticsUtil::RemoveExpired(flowControlUpdateTimestampList_, now); @@ -1488,17 +1494,14 @@ static bool SortNotificationsByLevelAndTime( ErrCode AdvancedNotificationService::FlowControl(const std::shared_ptr &record) { + if (record->isNeedFlowCtrl == false) { + return ERR_OK; + } HaMetaMessage message = HaMetaMessage(EventSceneId::SCENE_4, EventBranchId::BRANCH_2); std::chrono::system_clock::time_point now = std::chrono::system_clock::now(); - - auto uid = record->request->GetCreatorUid(); - int32_t userId = SUBSCRIBE_USER_INIT; - OsAccountManagerHelper::GetInstance().GetOsAccountLocalIdFromUid(uid, userId); - bool isSystemApp = BundleManagerHelper::GetInstance()->IsSystemApp(uid); - bool isSubsystem = IsSystemUser(userId); - ANS_LOGD("FlowControl uid %{public}d, userid %{public}d, size %{public}zu,%{public}zu", - uid, userId, flowControlTimestampList_.size(), systemFlowControlTimestampList_.size()); - if (!isSubsystem && !isSystemApp) { + ANS_LOGD("FlowControl size %{public}zu,%{public}zu", + flowControlTimestampList_.size(), systemFlowControlTimestampList_.size()); + if (record->isThirdparty == true) { std::lock_guard lock(flowControlMutex_); NotificationAnalyticsUtil::RemoveExpired(flowControlTimestampList_, now); if (flowControlTimestampList_.size() >= MAX_ACTIVE_NUM_PERSECOND + MAX_UPDATE_NUM_PERSECOND) { @@ -1528,15 +1531,13 @@ bool AdvancedNotificationService::IsSystemUser(int32_t userId) ErrCode AdvancedNotificationService::PublishFlowControlInner(const std::shared_ptr &record) { + if (record->isNeedFlowCtrl == false) { + return ERR_OK; + } std::chrono::system_clock::time_point now = std::chrono::system_clock::now(); - auto uid = record->request->GetCreatorUid(); - int32_t userId = SUBSCRIBE_USER_INIT; - OsAccountManagerHelper::GetInstance().GetOsAccountLocalIdFromUid(uid, userId); - bool isSystemApp = BundleManagerHelper::GetInstance()->IsSystemApp(uid); - bool isSubsystem = IsSystemUser(userId); - ANS_LOGD("PublishFlowControl uid %{public}d, userid %{public}d, size %{public}zu,%{public}zu", - uid, userId, flowControlPublishTimestampList_.size(), systemFlowControlPublishTimestampList_.size()); - if (!isSubsystem && !isSystemApp) { + ANS_LOGD("PublishFlowControl size %{public}zu,%{public}zu", + flowControlPublishTimestampList_.size(), systemFlowControlPublishTimestampList_.size()); + if (record->isThirdparty == true) { // 三方流控 std::lock_guard lock(flowControlMutex_); NotificationAnalyticsUtil::RemoveExpired(flowControlPublishTimestampList_, now); -- Gitee From 617a29198608fa0cf9c6164c37dc5a1392a28ae5 Mon Sep 17 00:00:00 2001 From: markYao Date: Fri, 11 Oct 2024 17:13:58 +0800 Subject: [PATCH 098/167] =?UTF-8?q?=E9=80=9A=E7=9F=A5=E5=8E=BB=E9=87=8D?= =?UTF-8?q?=E6=97=B6=E9=97=B4=E6=88=B3=E4=BD=BF=E7=94=A8steady=5Fclock?= =?UTF-8?q?=EF=BC=8C=E9=81=BF=E5=85=8D=E5=8F=97=E5=88=B0=E7=B3=BB=E7=BB=9F?= =?UTF-8?q?=E6=97=B6=E9=97=B4=E5=8F=98=E5=8C=96=E7=9A=84=E5=BD=B1=E5=93=8D?= =?UTF-8?q?=20Signed-off-by:=20markYao=20?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- services/ans/include/advanced_notification_service.h | 2 +- services/ans/src/advanced_notification_publish_service.cpp | 4 ++-- services/ans/src/advanced_notification_service.cpp | 4 +++- .../unittest/advanced_notification_publish_service_test.cpp | 6 +++--- 4 files changed, 9 insertions(+), 7 deletions(-) diff --git a/services/ans/include/advanced_notification_service.h b/services/ans/include/advanced_notification_service.h index 80994459a..37c4f9286 100644 --- a/services/ans/include/advanced_notification_service.h +++ b/services/ans/include/advanced_notification_service.h @@ -1449,7 +1449,7 @@ private: std::shared_ptr permissonFilter_ = nullptr; std::shared_ptr notificationSlotFilter_ = nullptr; std::shared_ptr dialogManager_ = nullptr; - std::list> uniqueKeyList_; + std::list> uniqueKeyList_; std::list, uint64_t>> delayNotificationList_; std::mutex delayNotificationMutext_; }; diff --git a/services/ans/src/advanced_notification_publish_service.cpp b/services/ans/src/advanced_notification_publish_service.cpp index 9436a10cb..2f3ea7753 100644 --- a/services/ans/src/advanced_notification_publish_service.cpp +++ b/services/ans/src/advanced_notification_publish_service.cpp @@ -2499,7 +2499,7 @@ ErrCode AdvancedNotificationService::DuplicateMsgControl(const sptr std::chrono::hours(HOURS_IN_ONE_DAY)) { diff --git a/services/ans/src/advanced_notification_service.cpp b/services/ans/src/advanced_notification_service.cpp index c2f1a9780..cc55b6467 100644 --- a/services/ans/src/advanced_notification_service.cpp +++ b/services/ans/src/advanced_notification_service.cpp @@ -619,7 +619,9 @@ ErrCode AdvancedNotificationService::PublishPreparedNotification(const sptrLocalControl(request); diff --git a/services/ans/test/unittest/advanced_notification_publish_service_test.cpp b/services/ans/test/unittest/advanced_notification_publish_service_test.cpp index 1d0fd2aeb..d88ab5b12 100644 --- a/services/ans/test/unittest/advanced_notification_publish_service_test.cpp +++ b/services/ans/test/unittest/advanced_notification_publish_service_test.cpp @@ -862,7 +862,7 @@ HWTEST_F(AnsPublishServiceTest, DuplicateMsgControl_00002, Function | SmallTest request->SetAppMessageId("test1"); auto uniqueKey = request->GenerateUniqueKey(); advancedNotificationService_->uniqueKeyList_.emplace_back( - std::make_pair(std::chrono::system_clock::now(), uniqueKey)); + std::make_pair(std::chrono::steady_clock::now(), uniqueKey)); auto ret = advancedNotificationService_->DuplicateMsgControl(request); ASSERT_EQ(ret, (int)ERR_ANS_DUPLICATE_MSG); @@ -915,7 +915,7 @@ HWTEST_F(AnsPublishServiceTest, IsDuplicateMsg_00002, Function | SmallTest | Lev request->SetAppMessageId("test2"); auto uniqueKey = request->GenerateUniqueKey(); advancedNotificationService_->uniqueKeyList_.emplace_back( - std::make_pair(std::chrono::system_clock::now(), uniqueKey)); + std::make_pair(std::chrono::steady_clock::now(), uniqueKey)); auto ret = advancedNotificationService_->IsDuplicateMsg(uniqueKey); ASSERT_EQ(ret, true); @@ -934,7 +934,7 @@ HWTEST_F(AnsPublishServiceTest, RemoveExpiredUniqueKey_00001, Function | SmallTe request->SetAppMessageId("test2"); auto uniqueKey = request->GenerateUniqueKey(); advancedNotificationService_->uniqueKeyList_.emplace_back( - std::make_pair(std::chrono::system_clock::now() - std::chrono::hours(24), uniqueKey)); + std::make_pair(std::chrono::steady_clock::now() - std::chrono::hours(24), uniqueKey)); sleep(1); ASSERT_EQ(advancedNotificationService_->uniqueKeyList_.size(), 1); -- Gitee From 3eef1379020d5a48f2d338e0d18e518b1de19d93 Mon Sep 17 00:00:00 2001 From: yangjun Date: Sat, 5 Oct 2024 17:40:17 +0800 Subject: [PATCH 099/167] =?UTF-8?q?=E6=B7=BB=E5=8A=A0reason;=E6=89=93?= =?UTF-8?q?=E7=82=B9=E9=99=90=E6=B5=81;extraInfo=E4=B8=AD=E6=B7=BB?= =?UTF-8?q?=E5=8A=A0pushdata=E5=86=85=E5=AE=B9;=E6=B7=BB=E5=8A=A0=E5=8B=BF?= =?UTF-8?q?=E6=89=B0=E6=A8=A1=E5=BC=8F=E7=8A=B6=E6=80=81=E6=94=B9=E5=8F=98?= =?UTF-8?q?=E6=89=93=E7=82=B9?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Change-Id: I4a30ec0d3ff84b745be48158a6efa6df4f751c1c Signed-off-by: yangjun --- services/ans/BUILD.gn | 1 + .../include/advanced_notification_service.h | 3 + .../ans/include/notification_analytics_util.h | 20 ++ .../ans/include/notification_timer_info.h | 3 +- services/ans/include/report_timer_info.h | 35 +++ services/ans/src/access_token_helper.cpp | 3 - .../advanced_notification_publish_service.cpp | 27 --- .../ans/src/advanced_notification_service.cpp | 30 ++- .../advanced_notification_slot_service.cpp | 8 +- ...vanced_notification_subscriber_service.cpp | 3 - .../ans/src/advanced_notification_utils.cpp | 6 - .../common/notification_analytics_util.cpp | 227 +++++++++++++----- services/ans/src/notification_timer_info.cpp | 5 + services/ans/src/report_time_info.cpp | 29 +++ 14 files changed, 291 insertions(+), 109 deletions(-) create mode 100644 services/ans/include/report_timer_info.h create mode 100644 services/ans/src/report_time_info.cpp diff --git a/services/ans/BUILD.gn b/services/ans/BUILD.gn index 178cbaf13..8ab22f30f 100644 --- a/services/ans/BUILD.gn +++ b/services/ans/BUILD.gn @@ -99,6 +99,7 @@ ohos_shared_library("libans") { "src/reminder_table.cpp", "src/reminder_table_old.cpp", "src/reminder_timer_info.cpp", + "src/report_time_info.cpp", "src/system_dialog_connect_stb.cpp", "src/system_event_observer.cpp", "src/telephony_extension_wrapper.cpp", diff --git a/services/ans/include/advanced_notification_service.h b/services/ans/include/advanced_notification_service.h index ffaebba74..f3da345df 100644 --- a/services/ans/include/advanced_notification_service.h +++ b/services/ans/include/advanced_notification_service.h @@ -1354,6 +1354,7 @@ private: ErrCode IsAllowedGetNotificationByFilter(const std::shared_ptr &record); void QueryDoNotDisturbProfile(const int32_t &userId, std::string &enable, std::string &profileId); void CheckDoNotDisturbProfile(const std::shared_ptr &record); + void ReportDoNotDisturbModeChanged(const int32_t &userId, std::string &enable); void DoNotDisturbUpdataReminderFlags(const std::shared_ptr &record); ErrCode CheckCommonParams(); std::shared_ptr GetRecordFromNotificationList( @@ -1446,6 +1447,8 @@ private: std::list> uniqueKeyList_; std::list, uint64_t>> delayNotificationList_; std::mutex delayNotificationMutext_; + static std::mutex doNotDisturbMutex_; + std::map doNotDisturbEnableRecord_; }; /** diff --git a/services/ans/include/notification_analytics_util.h b/services/ans/include/notification_analytics_util.h index 801392fdd..8b659e1a8 100644 --- a/services/ans/include/notification_analytics_util.h +++ b/services/ans/include/notification_analytics_util.h @@ -84,6 +84,11 @@ struct FlowControllerOption { int32_t time; }; +struct ReportCache { + EventFwk::Want want; + int32_t eventCode; +}; + class NotificationAnalyticsUtil { public: static void ReportPublishFailedEvent(const sptr& request, const HaMetaMessage& message); @@ -96,6 +101,8 @@ public: static void RemoveExpired(std::list &list, const std::chrono::system_clock::time_point &now, int32_t time = 1); + + static int64_t GetCurrentTime(); private: static void ReportNotificationEvent(const sptr& request, EventFwk::Want want, int32_t eventCode, const std::string& reason); @@ -109,6 +116,19 @@ private: static bool ReportFlowControl(const int32_t reportType); static FlowControllerOption GetFlowOptionByType(const int32_t reportType); + + static std::string BuildExtraInfo(const HaMetaMessage& message); + + static std::string BuildExtraInfoWithReq(const HaMetaMessage& message, + const sptr& request); + + static void SetCommonWant(EventFwk::Want& want, const HaMetaMessage& message, std::string& extraInfo); + + static void AddListCache(EventFwk::Want& want, int32_t eventCode); + + static void ExecuteCacheList(); + + static void ReportCommonEvent(const ReportCache& reportCache); }; } // namespace Notification } // namespace OHOS diff --git a/services/ans/include/notification_timer_info.h b/services/ans/include/notification_timer_info.h index d7229f3f4..17d82f567 100644 --- a/services/ans/include/notification_timer_info.h +++ b/services/ans/include/notification_timer_info.h @@ -52,9 +52,10 @@ public: void SetCallbackInfo(const std::function &callBack); + std::function GetCallBack(); private: std::function callBack_ = nullptr; }; } // namespace OHOS } // namespace Notification -#endif // BASE_NOTIFICATION_DISTRIBUTED_NOTIFICATION_TIMER_INFO_H \ No newline at end of file +#endif // BASE_NOTIFICATION_DISTRIBUTED_NOTIFICATION_TIMER_INFO_H diff --git a/services/ans/include/report_timer_info.h b/services/ans/include/report_timer_info.h new file mode 100644 index 000000000..44b1d5d82 --- /dev/null +++ b/services/ans/include/report_timer_info.h @@ -0,0 +1,35 @@ +/* + * Copyright (c) 2023 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef BASE_NOTIFICATION_DISTRIBUTED_REPORT_TIMER_INFO_H +#define BASE_NOTIFICATION_DISTRIBUTED_REPORT_TIMER_INFO_H + +#include "notification_timer_info.h" +#include "in_process_call_wrapper.h" + +namespace OHOS { +namespace Notification { +class ReportTimerInfo : public NotificationTimerInfo { +public: + virtual ~ReportTimerInfo() {}; + ReportTimerInfo() {}; + /** + * When timing is up, this function will execute as call back. + */ + void OnTrigger() override; +}; +} // namespace OHOS +} // namespace Notification +#endif // BASE_NOTIFICATION_DISTRIBUTED_REPORT_TIMER_INFO_H diff --git a/services/ans/src/access_token_helper.cpp b/services/ans/src/access_token_helper.cpp index 26ce3af84..a3d66115d 100644 --- a/services/ans/src/access_token_helper.cpp +++ b/services/ans/src/access_token_helper.cpp @@ -80,7 +80,6 @@ bool AccessTokenHelper::VerifyShellToken(const AccessTokenID &callerToken) bool AccessTokenHelper::CheckPermission(const std::string &permission) { ANS_LOGD("%{public}s", __FUNCTION__); - HaMetaMessage message = HaMetaMessage(EventSceneId::SCENE_1, EventBranchId::BRANCH_1); auto tokenCaller = IPCSkeleton::GetCallingTokenID(); int32_t callingUid = IPCSkeleton::GetCallingUid(); int32_t callingPid = IPCSkeleton::GetCallingPid(); @@ -88,8 +87,6 @@ bool AccessTokenHelper::CheckPermission(const std::string &permission) if (!result) { ANS_LOGE("CheckPermission failed %{public}s, %{public}d, %{public}d", permission.c_str(), callingUid, callingPid); - message.Message("Permission denied: " + permission, true); - NotificationAnalyticsUtil::ReportModifyEvent(message); } return result; } diff --git a/services/ans/src/advanced_notification_publish_service.cpp b/services/ans/src/advanced_notification_publish_service.cpp index 99e5ef08c..7418eb406 100644 --- a/services/ans/src/advanced_notification_publish_service.cpp +++ b/services/ans/src/advanced_notification_publish_service.cpp @@ -471,9 +471,6 @@ ErrCode AdvancedNotificationService::Delete(const std::string &key, int32_t remo if (notificationSvrQueue_ == nullptr) { std::string message = "Serial queue is invalidated. key:" + key + "."; - OHOS::Notification::HaMetaMessage haMetaMessage = HaMetaMessage(4, 3) - .ErrorCode(ERR_ANS_INVALID_PARAM); - ReportDeleteFailedEventPush(haMetaMessage, removeReason, message); ANS_LOGE("%{public}s", message.c_str()); return ERR_ANS_INVALID_PARAM; } @@ -596,9 +593,6 @@ ErrCode AdvancedNotificationService::DeleteAll() if (notificationSvrQueue_ == nullptr) { std::string message = "Serial queue is invalidity."; - OHOS::Notification::HaMetaMessage haMetaMessage = HaMetaMessage(6, 10) - .ErrorCode(ERR_ANS_INVALID_PARAM); - ReportDeleteFailedEventPush(haMetaMessage, reason, message); ANS_LOGE("%{public}s", message.c_str()); return ERR_ANS_INVALID_PARAM; } @@ -1398,9 +1392,6 @@ ErrCode AdvancedNotificationService::RemoveNotification(const sptrSetBadgeNumber(badgeData); }); notificationSvrQueue_->wait(handler); - HaMetaMessage message = HaMetaMessage(EventSceneId::SCENE_3, EventBranchId::BRANCH_1) - .Message("Set badge number " + bundleName + " " + std::to_string(badgeNumber) - + " " + std::to_string(instanceKey)); - NotificationAnalyticsUtil::ReportModifyEvent(message); return ERR_OK; } @@ -2344,8 +2322,6 @@ ErrCode AdvancedNotificationService::SetBadgeNumberByBundle( { HaMetaMessage message = HaMetaMessage(EventSceneId::SCENE_7, EventBranchId::BRANCH_1); if (notificationSvrQueue_ == nullptr) { - message.Message("Serial queue is invalid.", true); - NotificationAnalyticsUtil::ReportModifyEvent(message); return ERR_ANS_INVALID_PARAM; } @@ -2390,9 +2366,6 @@ ErrCode AdvancedNotificationService::SetBadgeNumberByBundle( NotificationSubscriberManager::GetInstance()->SetBadgeNumber(badgeData); }); notificationSvrQueue_->wait(handler); - message.Message("Set badgenumber: " + bundle->GetBundleName() + ":" + - std::to_string(badgeNumber) + " " + std::to_string(result)); - NotificationAnalyticsUtil::ReportModifyEvent(message); return result; } diff --git a/services/ans/src/advanced_notification_service.cpp b/services/ans/src/advanced_notification_service.cpp index 0a99c72d2..ac29949b1 100644 --- a/services/ans/src/advanced_notification_service.cpp +++ b/services/ans/src/advanced_notification_service.cpp @@ -98,6 +98,7 @@ sptr AdvancedNotificationService::instance_; std::mutex AdvancedNotificationService::instanceMutex_; std::mutex AdvancedNotificationService::pushMutex_; std::mutex AdvancedNotificationService::flowControlMutex_; +std::mutex AdvancedNotificationService::doNotDisturbMutex_; std::map slotFlagsDefaultMap_; std::map> AdvancedNotificationService::pushCallBacks_; @@ -381,9 +382,6 @@ ErrCode AdvancedNotificationService::CancelPreparedNotification(int32_t notifica if (notificationSvrQueue_ == nullptr) { std::string message = "notificationSvrQueue is null"; - OHOS::Notification::HaMetaMessage haMetaMessage = HaMetaMessage(1, 3) - .ErrorCode(ERR_ANS_INVALID_PARAM).NotificationId(notificationId); - ReportDeleteFailedEventPush(haMetaMessage, reason, message); ANS_LOGE("%{public}s", message.c_str()); return ERR_ANS_INVALID_PARAM; } @@ -717,6 +715,29 @@ void AdvancedNotificationService::QueryDoNotDisturbProfile(const int32_t &userId } } +void AdvancedNotificationService::ReportDoNotDisturbModeChanged(const int32_t &userId, std::string &enable) +{ + std::lock_guard lock(doNotDisturbMutex_); + HaMetaMessage message = HaMetaMessage(EventSceneId::SCENE_3, EventBranchId::BRANCH_2); + std::string info = "Do not disturb mode changed, userId: " + std::to_string(userId) + ", enable: " + enable; + auto it = doNotDisturbEnableRecord_.find(userId); + if (it != doNotDisturbEnableRecord_.end()) { + if (it->second != enable) { + ANS_LOGI("%{public}s", info.c_str()); + message.Message(info); + NotificationAnalyticsUtil::ReportModifyEvent(message); + doNotDisturbEnableRecord_.insert_or_assign(userId, enable); + } + } else { + if (enable == DO_NOT_DISTURB_MODE) { + ANS_LOGI("%{public}s", info.c_str()); + message.Message(info); + NotificationAnalyticsUtil::ReportModifyEvent(message); + } + doNotDisturbEnableRecord_.insert_or_assign(userId, enable); + } +} + void AdvancedNotificationService::CheckDoNotDisturbProfile(const std::shared_ptr &record) { ANS_LOGD("Called."); @@ -728,12 +749,13 @@ void AdvancedNotificationService::CheckDoNotDisturbProfile(const std::shared_ptr std::string enable; std::string profileId; QueryDoNotDisturbProfile(userId, enable, profileId); + ReportDoNotDisturbModeChanged(userId, enable); if (enable != DO_NOT_DISTURB_MODE) { ANS_LOGD("Currently not is do not disturb mode."); return; } std::string bundleName = record->bundleOption->GetBundleName(); - ANS_LOGD("The bundle name is %{public}s", bundleName.c_str()); + ANS_LOGI("The bundle name is %{public}s", bundleName.c_str()); sptr profile = new (std::nothrow) NotificationDoNotDisturbProfile(); if (NotificationPreferences::GetInstance()->GetDoNotDisturbProfile(atoi(profileId.c_str()), userId, profile) != ERR_OK) { diff --git a/services/ans/src/advanced_notification_slot_service.cpp b/services/ans/src/advanced_notification_slot_service.cpp index 91011a4a9..df8519fc8 100644 --- a/services/ans/src/advanced_notification_slot_service.cpp +++ b/services/ans/src/advanced_notification_slot_service.cpp @@ -466,8 +466,6 @@ ErrCode AdvancedNotificationService::AssignValidNotificationSlot(const std::shar slot = new (std::nothrow) NotificationSlot(slotType); if (slot == nullptr) { ANS_LOGE("Failed to create NotificationSlot instance"); - message.ErrorCode(ERR_NO_MEMORY).Message("Create failed"); - NotificationAnalyticsUtil::ReportPublishFailedEvent(record->request, message); return ERR_NO_MEMORY; } @@ -521,9 +519,6 @@ ErrCode AdvancedNotificationService::UpdateSlotReminderModeBySlotFlags( DelayedSingleton::GetInstance()->GetConfigSlotReminderModeByType(slot->GetType()); slot->SetReminderMode(slotFlags & configSlotReminderMode); std::string bundleName = (bundle == nullptr) ? "" : bundle->GetBundleName(); - message.Message("Update reminderMode " + std::to_string(slot->GetType()) + ' ' - + std::to_string(slot->GetReminderMode())); - NotificationAnalyticsUtil::ReportModifyEvent(message); ANS_LOGD("Update reminderMode of %{public}d in %{public}s, value is %{public}d.", slot->GetType(), bundleName.c_str(), slot->GetReminderMode()); } @@ -778,8 +773,7 @@ ErrCode AdvancedNotificationService::SetAdditionConfig(const std::string &key, c HaMetaMessage message = HaMetaMessage(EventSceneId::SCENE_8, EventBranchId::BRANCH_1); if (notificationSvrQueue_ == nullptr) { - message.Message("Serial queue is invalid.", true); - NotificationAnalyticsUtil::ReportModifyEvent(message); + ANS_LOGE("Serial queue is invalid."); return ERR_ANS_INVALID_PARAM; } diff --git a/services/ans/src/advanced_notification_subscriber_service.cpp b/services/ans/src/advanced_notification_subscriber_service.cpp index a34acb53b..ad0dba308 100644 --- a/services/ans/src/advanced_notification_subscriber_service.cpp +++ b/services/ans/src/advanced_notification_subscriber_service.cpp @@ -46,7 +46,6 @@ ErrCode AdvancedNotificationService::Subscribe( { HITRACE_METER_NAME(HITRACE_TAG_NOTIFICATION, __PRETTY_FUNCTION__); ANS_LOGD("%{public}s", __FUNCTION__); - HaMetaMessage message = HaMetaMessage(EventSceneId::SCENE_6, EventBranchId::BRANCH_1); ErrCode errCode = ERR_OK; do { if (subscriber == nullptr) { @@ -78,8 +77,6 @@ ErrCode AdvancedNotificationService::Subscribe( break; } } while (0); - message.Message("Subscribe notification: " + std::to_string(errCode)); - NotificationAnalyticsUtil::ReportModifyEvent(message); SendSubscribeHiSysEvent(IPCSkeleton::GetCallingPid(), IPCSkeleton::GetCallingUid(), info, errCode); return errCode; } diff --git a/services/ans/src/advanced_notification_utils.cpp b/services/ans/src/advanced_notification_utils.cpp index 5343fc25d..4e30b1e20 100644 --- a/services/ans/src/advanced_notification_utils.cpp +++ b/services/ans/src/advanced_notification_utils.cpp @@ -108,7 +108,6 @@ std::shared_ptr AdvancedNotificationService::GetNotificationSvrQueu sptr AdvancedNotificationService::GenerateBundleOption() { - HaMetaMessage message = HaMetaMessage(EventSceneId::SCENE_4, EventBranchId::BRANCH_1); sptr bundleOption = nullptr; std::string bundle = ""; if (!AccessTokenHelper::VerifyNativeToken(IPCSkeleton::GetCallingTokenID())) { @@ -121,8 +120,6 @@ sptr AdvancedNotificationService::GenerateBundleOption int32_t uid = IPCSkeleton::GetCallingUid(); bundleOption = new (std::nothrow) NotificationBundleOption(bundle, uid); if (bundleOption == nullptr) { - message.Message("Failed to create instance" + std::to_string(uid), true); - NotificationAnalyticsUtil::ReportModifyEvent(message); return nullptr; } return bundleOption; @@ -1419,9 +1416,6 @@ ErrCode AdvancedNotificationService::DeleteAllByUserInner(const int32_t &userId, if (notificationSvrQueue_ == nullptr) { std::string message = "Serial queue is invalid."; - OHOS::Notification::HaMetaMessage haMetaMessage = HaMetaMessage(6, 7) - .ErrorCode(ERR_ANS_INVALID_PARAM); - ReportDeleteFailedEventPush(haMetaMessage, deleteReason, message); ANS_LOGE("%{public}s", message.c_str()); return ERR_ANS_INVALID_PARAM; } diff --git a/services/ans/src/common/notification_analytics_util.cpp b/services/ans/src/common/notification_analytics_util.cpp index 447e5950f..1dfc04222 100644 --- a/services/ans/src/common/notification_analytics_util.cpp +++ b/services/ans/src/common/notification_analytics_util.cpp @@ -23,18 +23,23 @@ #include "ans_convert_enum.h" #include "ans_permission_def.h" #include "in_process_call_wrapper.h" +#include "report_timer_info.h" +#include "time_service_client.h" +#include "nlohmann/json.hpp" namespace OHOS { namespace Notification { constexpr char MESSAGE_DELIMITER = '#'; constexpr const int32_t PUBLISH_ERROR_EVENT_CODE = 0; constexpr const int32_t DELETE_ERROR_EVENT_CODE = 5; constexpr const int32_t MODIFY_ERROR_EVENT_CODE = 6; -constexpr const int32_t DEFAULT_ERROR_EVENT_COUNT = 6; + +constexpr const int32_t DEFAULT_ERROR_EVENT_COUNT = 5; constexpr const int32_t DEFAULT_ERROR_EVENT_TIME = 60; -constexpr const int32_t PUBLISH_ERROR_EVENT_COUNT = 3; -constexpr const int32_t PUBLISH_ERROR_EVENT_TIME = 60; -constexpr const int32_t DELETE_ERROR_EVENT_COUNT = 3; -constexpr const int32_t DELETE_ERROR_EVENT_TIME = 60; +constexpr const int32_t MODIFY_ERROR_EVENT_COUNT = 6; +constexpr const int32_t MODIFY_ERROR_EVENT_TIME = 60; + +constexpr const int32_t REPORT_CACHE_MAX_SIZE = 50; +constexpr const int32_t REPORT_CACHE_INTERVAL_TIME = 30; const static std::string NOTIFICATION_EVENT_PUSH_AGENT = "notification.event.PUSH_AGENT"; static std::mutex reportFlowControlMutex_; static std::map> flowControlTimestampMap_ = { @@ -43,6 +48,12 @@ static std::map> flowC {DELETE_ERROR_EVENT_CODE, {}}, }; +static std::mutex reportCacheMutex_; +static uint64_t reportTimerId = 0; +static std::list reportCacheList; +static bool g_reportFlag = false; +static std::shared_ptr reportTimeInfo = std::make_shared(); + HaMetaMessage::HaMetaMessage(uint32_t sceneId, uint32_t branchId) : sceneId_(sceneId), branchId_(branchId) { @@ -166,7 +177,9 @@ void NotificationAnalyticsUtil::CommonNotificationEvent(const sptr& request, EventFwk::Want want, int32_t eventCode, const std::string& reason) { - std::shared_ptr extraInfo = std::make_shared(); - if (request->GetFlags() == nullptr) { - extraInfo->SetParam("reason", AAFwk::String::Box(reason)); - } else { - std::string reasons = reason + std::to_string(request->GetFlags()->GetReminderFlags()); - extraInfo->SetParam("reason", AAFwk::String::Box(reasons)); - } - AAFwk::WantParamWrapper wWrapper(*extraInfo); - std::string extraContent = wWrapper.ToString(); - NotificationNapi::SlotType slotType; + NotificationNapi::AnsEnumUtil::SlotTypeCToJS( + static_cast(request->GetSlotType()), slotType); NotificationNapi::ContentType contentType; NotificationNapi::AnsEnumUtil::ContentTypeCToJS( static_cast(request->GetNotificationType()), contentType); - NotificationNapi::AnsEnumUtil::SlotTypeCToJS( - static_cast(request->GetSlotType()), slotType); want.SetParam("id", request->GetNotificationId()); want.SetParam("slotType", static_cast(slotType)); want.SetParam("contentType", std::to_string(static_cast(contentType))); - want.SetParam("extraInfo", extraContent); + if (!request->GetCreatorBundleName().empty()) { want.SetParam("agentBundleName", request->GetCreatorBundleName()); } if (!request->GetOwnerBundleName().empty()) { want.SetBundle(request->GetOwnerBundleName()); } - want.SetAction(NOTIFICATION_EVENT_PUSH_AGENT); - EventFwk::CommonEventPublishInfo publishInfo; - publishInfo.SetSubscriberPermissions({OHOS_PERMISSION_NOTIFICATION_AGENT_CONTROLLER}); - EventFwk::CommonEventData commonData {want, eventCode, ""}; - ANS_LOGD("Publish event success %{public}d, %{public}s", eventCode, reason.c_str()); - if (!EventFwk::CommonEventManager::PublishCommonEvent(commonData, publishInfo)) { - ANS_LOGE("Publish event failed %{public}d, %{public}s", eventCode, reason.c_str()); - } + IN_PROCESS_CALL_WITHOUT_RET(AddListCache(want, eventCode)); } void NotificationAnalyticsUtil::ReportModifyEvent(const HaMetaMessage& message) @@ -218,20 +214,12 @@ void NotificationAnalyticsUtil::ReportModifyEvent(const HaMetaMessage& message) ANS_LOGI("Publish event failed, reason:%{public}s", message.Build().c_str()); return; } - std::shared_ptr extraInfo = std::make_shared(); - std::string reason = std::to_string(message.sceneId_) + MESSAGE_DELIMITER + - std::to_string(message.branchId_) + std::to_string(message.notificationId_) + - MESSAGE_DELIMITER + message.GetMessage(); - extraInfo->SetParam("reason", AAFwk::String::Box(reason)); - AAFwk::WantParamWrapper wWrapper(*extraInfo); - std::string extraContent = wWrapper.ToString(); - EventFwk::Want want; - want.SetBundle(message.bundleName_); + std::string extraInfo = NotificationAnalyticsUtil::BuildExtraInfo(message); + NotificationAnalyticsUtil::SetCommonWant(want, message, extraInfo); + want.SetParam("slotType", static_cast(message.slotType_)); - want.SetParam("extraInfo", extraContent); - IN_PROCESS_CALL_WITHOUT_RET(ReportNotificationEvent(want, MODIFY_ERROR_EVENT_CODE, - message.Build())); + IN_PROCESS_CALL_WITHOUT_RET(AddListCache(want, MODIFY_ERROR_EVENT_CODE)); } void NotificationAnalyticsUtil::ReportDeleteFailedEvent(const HaMetaMessage& message) @@ -240,24 +228,20 @@ void NotificationAnalyticsUtil::ReportDeleteFailedEvent(const HaMetaMessage& mes ANS_LOGI("Publish event failed, reason:%{public}s", message.Build().c_str()); return; } - std::shared_ptr extraInfo = std::make_shared(); - std::string reason = message.Build(); - extraInfo->SetParam("reason", AAFwk::String::Box(reason)); - AAFwk::WantParamWrapper wWrapper(*extraInfo); - std::string extraContent = wWrapper.ToString(); - EventFwk::Want want; + std::string extraInfo = NotificationAnalyticsUtil::BuildExtraInfo(message); + NotificationAnalyticsUtil::SetCommonWant(want, message, extraInfo); + want.SetParam("agentBundleName", message.agentBundleName_); - want.SetBundle(message.bundleName_); want.SetParam("typeCode", message.typeCode_); want.SetParam("id", message.notificationId_); - want.SetParam("extraInfo", extraContent); + + IN_PROCESS_CALL_WITHOUT_RET(AddListCache(want, DELETE_ERROR_EVENT_CODE)); } void NotificationAnalyticsUtil::ReportNotificationEvent(EventFwk::Want want, int32_t eventCode, const std::string& reason) { - want.SetAction(NOTIFICATION_EVENT_PUSH_AGENT); EventFwk::CommonEventPublishInfo publishInfo; publishInfo.SetSubscriberPermissions({OHOS_PERMISSION_NOTIFICATION_AGENT_CONTROLLER}); EventFwk::CommonEventData commonData {want, eventCode, ""}; @@ -305,16 +289,8 @@ FlowControllerOption NotificationAnalyticsUtil::GetFlowOptionByType(const int32_ FlowControllerOption option; switch (reportType) { case MODIFY_ERROR_EVENT_CODE: - option.count = DEFAULT_ERROR_EVENT_COUNT; - option.time = DEFAULT_ERROR_EVENT_TIME; - break; - case PUBLISH_ERROR_EVENT_CODE: - option.count = PUBLISH_ERROR_EVENT_COUNT; - option.time = PUBLISH_ERROR_EVENT_TIME; - break; - case DELETE_ERROR_EVENT_CODE: - option.count = DELETE_ERROR_EVENT_COUNT; - option.time = DELETE_ERROR_EVENT_TIME; + option.count = MODIFY_ERROR_EVENT_COUNT; + option.time = MODIFY_ERROR_EVENT_TIME; break; default: option.count = DEFAULT_ERROR_EVENT_COUNT; @@ -323,5 +299,140 @@ FlowControllerOption NotificationAnalyticsUtil::GetFlowOptionByType(const int32_ } return option; } + +std::string NotificationAnalyticsUtil::BuildExtraInfo(const HaMetaMessage& message) +{ + nlohmann::json reason; + reason["scene"] = message.sceneId_; + reason["branch"] = message.branchId_; + reason["innerErr"] = message.errorCode_; + reason["detail"] = message.message_; + + auto now = std::chrono::duration_cast( + std::chrono::system_clock::now().time_since_epoch()).count(); + reason["time"] = now; + + std::shared_ptr extraInfo = std::make_shared(); + extraInfo->SetParam("reason", + AAFwk::String::Box(reason.dump(-1, ' ', false, nlohmann::json::error_handler_t::replace))); + AAFwk::WantParamWrapper wWrapper(*extraInfo); + + return wWrapper.ToString(); +} + +std::string NotificationAnalyticsUtil::BuildExtraInfoWithReq(const HaMetaMessage& message, + const sptr& request) +{ + NotificationNapi::ContentType contentType; + NotificationNapi::AnsEnumUtil::ContentTypeCToJS( + static_cast(request->GetNotificationType()), contentType); + nlohmann::json reason; + if (contentType == NotificationNapi::ContentType::NOTIFICATION_CONTENT_LIVE_VIEW) { + auto content = request->GetContent()->GetNotificationContent(); + auto liveViewContent = std::static_pointer_cast(content); + reason["status"] = static_cast(liveViewContent->GetLiveViewStatus()); + } + + reason["scene"] = message.sceneId_; + reason["branch"] = message.branchId_; + reason["innerErr"] = message.errorCode_; + reason["detail"] = message.message_; + + auto now = std::chrono::duration_cast( + std::chrono::system_clock::now().time_since_epoch()).count(); + reason["time"] = now; + + std::shared_ptr extraInfo = nullptr; + if (request->GetUnifiedGroupInfo() != nullptr && + request->GetUnifiedGroupInfo()->GetExtraInfo() != nullptr) { + extraInfo = request->GetUnifiedGroupInfo()->GetExtraInfo(); + } else { + extraInfo = std::make_shared(); + } + + extraInfo->SetParam("reason", + AAFwk::String::Box(reason.dump(-1, ' ', false, nlohmann::json::error_handler_t::replace))); + AAFwk::WantParamWrapper wWrapper(*extraInfo); + + return wWrapper.ToString(); +} + +void NotificationAnalyticsUtil::SetCommonWant(EventFwk::Want& want, const HaMetaMessage& message, + std::string& extraInfo) +{ + want.SetBundle(message.bundleName_); + want.SetParam("extraInfo", extraInfo); + want.SetAction(NOTIFICATION_EVENT_PUSH_AGENT); +} + +void NotificationAnalyticsUtil::AddListCache(EventFwk::Want& want, int32_t eventCode) +{ + std::lock_guard lock(reportCacheMutex_); + int32_t size = static_cast(reportCacheList.size()); + if (size >= REPORT_CACHE_MAX_SIZE) { + ANS_LOGW("list size is max"); + return; + } + + if (reportTimerId == 0) { + sptr timer = MiscServices::TimeServiceClient::GetInstance(); + if (timer == nullptr) { + ANS_LOGE("Failed to start timer due to get TimeServiceClient is null."); + return; + } + reportTimerId = timer->CreateTimer(reportTimeInfo); + } + + ReportCache reportCache; + reportCache.want = want; + reportCache.eventCode = eventCode; + reportCacheList.push_back(reportCache); + if (!g_reportFlag) { + ExecuteCacheList(); + } +} + +void NotificationAnalyticsUtil::ExecuteCacheList() +{ + if (reportCacheList.empty()) { + g_reportFlag = false; + ANS_LOGI("reportCacheList is end"); + return; + } + auto reportCache = reportCacheList.front(); + ReportCommonEvent(reportCache); + auto triggerFunc = [] { + std::lock_guard lock(reportCacheMutex_); + NotificationAnalyticsUtil::ExecuteCacheList(); + }; + reportCacheList.pop_front(); + reportTimeInfo->SetCallbackInfo(triggerFunc); + sptr timer = MiscServices::TimeServiceClient::GetInstance(); + if (timer == nullptr || reportTimerId == 0) { + g_reportFlag = false; + ANS_LOGE("Failed to start timer due to get TimeServiceClient is null."); + return; + } + timer->StartTimer(reportTimerId, NotificationAnalyticsUtil::GetCurrentTime() + + REPORT_CACHE_INTERVAL_TIME * NotificationConstant::SECOND_TO_MS); + g_reportFlag = true; +} + +void NotificationAnalyticsUtil::ReportCommonEvent(const ReportCache& reportCache) +{ + EventFwk::CommonEventPublishInfo publishInfo; + publishInfo.SetSubscriberPermissions({OHOS_PERMISSION_NOTIFICATION_AGENT_CONTROLLER}); + EventFwk::CommonEventData commonData {reportCache.want, reportCache.eventCode, ""}; + if (!EventFwk::CommonEventManager::PublishCommonEvent(commonData, publishInfo)) { + ANS_LOGE("Publish event failed %{public}d", reportCache.eventCode); + } +} + +int64_t NotificationAnalyticsUtil::GetCurrentTime() +{ + auto now = std::chrono::system_clock::now(); + auto duration = std::chrono::duration_cast(now.time_since_epoch()); + return duration.count(); +} } // namespace Notification } // namespace OHOS diff --git a/services/ans/src/notification_timer_info.cpp b/services/ans/src/notification_timer_info.cpp index 4ff03f8f7..4b4a20be6 100644 --- a/services/ans/src/notification_timer_info.cpp +++ b/services/ans/src/notification_timer_info.cpp @@ -56,5 +56,10 @@ void NotificationTimerInfo::SetCallbackInfo(const std::function &callBac { callBack_ = callBack; } + +std::function NotificationTimerInfo::GetCallBack() +{ + return callBack_; +} } } diff --git a/services/ans/src/report_time_info.cpp b/services/ans/src/report_time_info.cpp new file mode 100644 index 000000000..a427a76d8 --- /dev/null +++ b/services/ans/src/report_time_info.cpp @@ -0,0 +1,29 @@ +/* + * Copyright (c) 2024 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "report_timer_info.h" + +namespace OHOS { +namespace Notification { +void ReportTimerInfo::OnTrigger() +{ + ANS_LOGI("ReportTimerInfo is arrived."); + auto callBack = GetCallBack(); + if (callBack != nullptr) { + IN_PROCESS_CALL_WITHOUT_RET(callBack()); + } +} +} +} -- Gitee From 4a03d6ff1ea8485e8d3f85755fa795784ec28593 Mon Sep 17 00:00:00 2001 From: songbao1 Date: Thu, 17 Oct 2024 09:54:44 +0800 Subject: [PATCH 100/167] =?UTF-8?q?=E6=96=B0=E5=A2=9EinnerApi?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: songbao1 --- frameworks/ans/src/notification_helper.cpp | 5 + .../core/include/ans_manager_interface.h | 11 ++ frameworks/core/include/ans_manager_proxy.h | 11 ++ frameworks/core/include/ans_manager_stub.h | 11 ++ frameworks/core/include/ans_notification.h | 11 ++ ..._notification_service_ipc_interface_code.h | 1 + frameworks/core/src/ans_manager_proxy.cpp | 39 ++++++ frameworks/core/src/ans_manager_stub.cpp | 20 ++++ .../core/src/ans_manager_stub_invalid.cpp | 6 + frameworks/core/src/ans_notification.cpp | 52 ++++++++ interfaces/inner_api/notification_helper.h | 11 ++ .../include/advanced_notification_service.h | 12 ++ .../ans/include/notification_analytics_util.h | 1 + .../advanced_notification_publish_service.cpp | 111 ++++++++++++++++++ .../ans/src/advanced_notification_utils.cpp | 31 +++++ 15 files changed, 333 insertions(+) diff --git a/frameworks/ans/src/notification_helper.cpp b/frameworks/ans/src/notification_helper.cpp index 0cad2612f..5ac0231b3 100644 --- a/frameworks/ans/src/notification_helper.cpp +++ b/frameworks/ans/src/notification_helper.cpp @@ -82,6 +82,11 @@ ErrCode NotificationHelper::PublishNotification(const std::string &label, const return DelayedSingleton::GetInstance()->PublishNotification(label, request); } +ErrCode NotificationHelper::PublishNotification(const NotificationRequest &request) +{ + return DelayedSingleton::GetInstance()->PublishNotificationForIndirectProxy(request); +} + ErrCode NotificationHelper::CancelNotification(int32_t notificationId) { return DelayedSingleton::GetInstance()->CancelNotification(notificationId); diff --git a/frameworks/core/include/ans_manager_interface.h b/frameworks/core/include/ans_manager_interface.h index 790abe0ce..847675ea2 100644 --- a/frameworks/core/include/ans_manager_interface.h +++ b/frameworks/core/include/ans_manager_interface.h @@ -54,6 +54,17 @@ public: */ virtual ErrCode Publish(const std::string &label, const sptr ¬ification) = 0; + /** + * @brief Publishes a notification. + * @note 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 notification Indicates the NotificationRequest object for setting the notification content. + * This parameter must be specified. + * @return Returns ERR_OK on success, others on failure. + */ + virtual ErrCode PublishNotificationForIndirectProxy(const sptr ¬ification) = 0; + /** * @brief Cancels a published notification matching the specified label and notificationId. * diff --git a/frameworks/core/include/ans_manager_proxy.h b/frameworks/core/include/ans_manager_proxy.h index 59bf9a7eb..0ca32f2b9 100644 --- a/frameworks/core/include/ans_manager_proxy.h +++ b/frameworks/core/include/ans_manager_proxy.h @@ -42,6 +42,17 @@ public: */ ErrCode Publish(const std::string &label, const sptr ¬ification) override; + /** + * @brief Publishes a notification. + * @note 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 notification Indicates the NotificationRequest object for setting the notification content. + * This parameter must be specified. + * @return Returns ERR_OK on success, others on failure. + */ + ErrCode PublishNotificationForIndirectProxy(const sptr ¬ification) override; + /** * @brief Cancels a published notification matching the specified label and notificationId. * diff --git a/frameworks/core/include/ans_manager_stub.h b/frameworks/core/include/ans_manager_stub.h index 0ec670f8f..1b1607f14 100644 --- a/frameworks/core/include/ans_manager_stub.h +++ b/frameworks/core/include/ans_manager_stub.h @@ -55,6 +55,17 @@ public: */ virtual ErrCode Publish(const std::string &label, const sptr ¬ification) override; + /** + * @brief Publishes a notification. + * @note 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 notification Indicates the NotificationRequest object for setting the notification content. + * This parameter must be specified. + * @return Returns ERR_OK on success, others on failure. + */ + virtual ErrCode PublishNotificationForIndirectProxy(const sptr ¬ification) override; + /** * @brief Cancels a published notification matching the specified label and notificationId. * diff --git a/frameworks/core/include/ans_notification.h b/frameworks/core/include/ans_notification.h index c45c7332b..28c3da585 100644 --- a/frameworks/core/include/ans_notification.h +++ b/frameworks/core/include/ans_notification.h @@ -147,6 +147,17 @@ public: */ ErrCode PublishNotification(const std::string &label, const NotificationRequest &request); + /** + * @brief Publishes a notification. + * @note 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 NotificationRequest object for setting the notification content. + * This parameter must be specified. + * @return Returns publish notification result. + */ + ErrCode PublishNotificationForIndirectProxy(const NotificationRequest &request); + /** * @brief Cancels a published notification. * diff --git a/frameworks/core/include/distributed_notification_service_ipc_interface_code.h b/frameworks/core/include/distributed_notification_service_ipc_interface_code.h index 56e520eb6..a1d679dfd 100644 --- a/frameworks/core/include/distributed_notification_service_ipc_interface_code.h +++ b/frameworks/core/include/distributed_notification_service_ipc_interface_code.h @@ -25,6 +25,7 @@ namespace Notification { // ans_manager_interface PUBLISH_NOTIFICATION = FIRST_CALL_TRANSACTION, PUBLISH_NOTIFICATION_TO_DEVICE, // Obsolete + PUBLISH_NOTIFICATION_INDIRECTPROXY, CANCEL_NOTIFICATION, CANCEL_ALL_NOTIFICATIONS, CANCEL_AS_BUNDLE_OPTION, diff --git a/frameworks/core/src/ans_manager_proxy.cpp b/frameworks/core/src/ans_manager_proxy.cpp index 1d185722d..985ed549b 100644 --- a/frameworks/core/src/ans_manager_proxy.cpp +++ b/frameworks/core/src/ans_manager_proxy.cpp @@ -78,6 +78,45 @@ ErrCode AnsManagerProxy::Publish(const std::string &label, const sptr ¬ification) +{ + if (notification == nullptr) { + ANS_LOGE("[PublishNotificationForIndirectProxy] fail: notification is null ptr."); + return ERR_ANS_INVALID_PARAM; + } + + MessageParcel data; + if (notification->IsCommonLiveView()) { + if (!data.SetMaxCapacity(NotificationConstant::NOTIFICATION_MAX_LIVE_VIEW_SIZE)) { + return ERR_ANS_PARCELABLE_FAILED; + } + } + if (!data.WriteInterfaceToken(AnsManagerProxy::GetDescriptor())) { + ANS_LOGE("[PublishNotificationForIndirectProxy] fail: write interface token failed."); + return ERR_ANS_PARCELABLE_FAILED; + } + + if (!data.WriteParcelable(notification)) { + ANS_LOGE("[PublishNotificationForIndirectProxy] fail: write notification parcelable failed"); + return ERR_ANS_PARCELABLE_FAILED; + } + + MessageParcel reply; + MessageOption option = {MessageOption::TF_SYNC}; + ErrCode result = InnerTransact(NotificationInterfaceCode::PUBLISH_NOTIFICATION_INDIRECTPROXY, option, data, reply); + if (result != ERR_OK) { + ANS_LOGE("[PublishNotificationForIndirectProxy] fail: transact ErrCode=%{public}d", result); + return ERR_ANS_TRANSACT_FAILED; + } + + if (!reply.ReadInt32(result)) { + ANS_LOGE("[PublishNotificationForIndirectProxy] fail: read result failed."); + return ERR_ANS_PARCELABLE_FAILED; + } + + return result; +} + ErrCode AnsManagerProxy::Cancel(int32_t notificationId, const std::string &label, int32_t instanceKey) { MessageParcel data; diff --git a/frameworks/core/src/ans_manager_stub.cpp b/frameworks/core/src/ans_manager_stub.cpp index 8be5e0663..3592046cc 100644 --- a/frameworks/core/src/ans_manager_stub.cpp +++ b/frameworks/core/src/ans_manager_stub.cpp @@ -47,6 +47,10 @@ int32_t AnsManagerStub::OnRemoteRequest(uint32_t code, MessageParcel &data, Mess result = HandlePublish(data, reply); break; } + case static_cast(NotificationInterfaceCode::PUBLISH_NOTIFICATION_INDIRECTPROXY): { + result = HandlePublishNotificationForIndirectProxy(data, reply); + break; + } case static_cast(NotificationInterfaceCode::CANCEL_NOTIFICATION): { result = HandleCancel(data, reply); break; @@ -480,6 +484,22 @@ ErrCode AnsManagerStub::HandlePublish(MessageParcel &data, MessageParcel &reply) return ERR_OK; } +ErrCode AnsManagerStub::HandlePublishNotificationForIndirectProxy(MessageParcel &data, MessageParcel &reply) +{ + sptr notification = data.ReadParcelable(); + if (!notification) { + ANS_LOGE("[HandlePublishNotificationForIndirectProxy] fail: notification ReadParcelable failed"); + return ERR_ANS_PARCELABLE_FAILED; + } + + ErrCode result = Publish(label, notification); + if (!reply.WriteInt32(result)) { + ANS_LOGE("[HandlePublishNotificationForIndirectProxy] fail: write result failed, ErrCode=%{public}d", result); + return ERR_ANS_PARCELABLE_FAILED; + } + return ERR_OK; +} + ErrCode AnsManagerStub::HandleCancel(MessageParcel &data, MessageParcel &reply) { int32_t notificationId = 0; diff --git a/frameworks/core/src/ans_manager_stub_invalid.cpp b/frameworks/core/src/ans_manager_stub_invalid.cpp index 0457626d0..e9cbd7640 100644 --- a/frameworks/core/src/ans_manager_stub_invalid.cpp +++ b/frameworks/core/src/ans_manager_stub_invalid.cpp @@ -32,6 +32,12 @@ ErrCode AnsManagerStub::Publish(const std::string &label, const sptr ¬ification) +{ + ANS_LOGE("AnsManagerStub::PublishNotificationForIndirectProxy called!"); + return ERR_INVALID_OPERATION; +} + ErrCode AnsManagerStub::Cancel(int notificationId, const std::string &label, int32_t instanceKey) { ANS_LOGE("AnsManagerStub::Cancel called!"); diff --git a/frameworks/core/src/ans_notification.cpp b/frameworks/core/src/ans_notification.cpp index e9fbd945f..4fcf30ea1 100644 --- a/frameworks/core/src/ans_notification.cpp +++ b/frameworks/core/src/ans_notification.cpp @@ -236,6 +236,58 @@ ErrCode AnsNotification::PublishNotification(const std::string &label, const Not return proxy->Publish(label, reqPtr); } +ErrCode AnsNotification::PublishNotificationForIndirectProxy(const NotificationRequest &request) +{ + HITRACE_METER_NAME(HITRACE_TAG_NOTIFICATION, __PRETTY_FUNCTION__); + ANS_LOGD("enter"); + + 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 (!IsValidTemplate(request) || !IsValidDelayTime(request)) { + return ERR_ANS_INVALID_PARAM; + } + + if (!CanPublishMediaContent(request)) { + ANS_LOGE("Refuse to publish the notification because the series numbers actions not match those assigned to " + "added action buttons."); + return ERR_ANS_INVALID_PARAM; + } + + if (!CanPublishLiveViewContent(request)) { + ANS_LOGE("Refuse to publish the notification without valid live view content."); + 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; + } + + sptr proxy = GetAnsManagerProxy(); + if (!proxy) { + ANS_LOGE("Failed to GetAnsManagerProxy."); + return ERR_ANS_SERVICE_NOT_CONNECTED; + } + + sptr reqPtr = new (std::nothrow) NotificationRequest(request); + if (reqPtr == nullptr) { + ANS_LOGE("Create notificationRequest ptr fail."); + return ERR_ANS_NO_MEMORY; + } + + if (IsNonDistributedNotificationType(reqPtr->GetNotificationType())) { + reqPtr->SetDistributed(false); + } + int32_t instanceKey = DEFAULT_INSTANCE_KEY; + reqPtr->SetCreatorInstanceKey(instanceKey); + + return proxy->PublishNotificationForIndirectProxy(label, reqPtr); +} + ErrCode AnsNotification::CancelNotification(int32_t notificationId) { return CancelNotification("", notificationId); diff --git a/interfaces/inner_api/notification_helper.h b/interfaces/inner_api/notification_helper.h index 5b35ec72b..4519b3bb9 100644 --- a/interfaces/inner_api/notification_helper.h +++ b/interfaces/inner_api/notification_helper.h @@ -135,6 +135,17 @@ public: */ static ErrCode PublishNotification(const NotificationRequest &request); + /** + * @brief Publishes a notification. + * @note 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 NotificationRequest object for setting the notification content. + * This parameter must be specified. + * @return Returns publish notification result. + */ + static ErrCode PublishNotificationForIndirectProxy(const NotificationRequest &request); + /** * @brief Publishes a notification with a specified label. * @note If a notification with the same ID has been published by the current application and has not been deleted, diff --git a/services/ans/include/advanced_notification_service.h b/services/ans/include/advanced_notification_service.h index fa554b4f5..5691e288f 100644 --- a/services/ans/include/advanced_notification_service.h +++ b/services/ans/include/advanced_notification_service.h @@ -103,6 +103,17 @@ public: */ ErrCode Publish(const std::string &label, const sptr &request) override; + /** + * @brief Publishes a notification. + * @note 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 notification Indicates the NotificationRequest object for setting the notification content. + * This parameter must be specified. + * @return Returns ERR_OK on success, others on failure. + */ + ErrCode PublishNotificationForIndirectProxy(const std::string &label, const sptr &request) override; + /** * @brief Cancels a published notification matching the specified label and notificationId. * @@ -1276,6 +1287,7 @@ private: ErrCode SetRequestBundleInfo(const sptr &request, int32_t uid, std::string &bundle); ErrCode PrePublishNotificationBySa(const sptr &request, int32_t uid, std::string &bundle); + ErrCode PrePublishNotificationForIndirectProxy(const sptr &request,int32_t uid); ErrCode PublishNotificationBySa(const sptr &request); bool IsNeedPushCheck(const sptr &request); void FillExtraInfoToJson(const sptr &request, diff --git a/services/ans/include/notification_analytics_util.h b/services/ans/include/notification_analytics_util.h index 801392fdd..17da8422a 100644 --- a/services/ans/include/notification_analytics_util.h +++ b/services/ans/include/notification_analytics_util.h @@ -33,6 +33,7 @@ enum EventSceneId { SCENE_6 = 6, SCENE_7 = 7, SCENE_8 = 8, + SCENE_9 = 9, }; enum EventBranchId { diff --git a/services/ans/src/advanced_notification_publish_service.cpp b/services/ans/src/advanced_notification_publish_service.cpp index a8675583c..4e47eab14 100644 --- a/services/ans/src/advanced_notification_publish_service.cpp +++ b/services/ans/src/advanced_notification_publish_service.cpp @@ -169,6 +169,117 @@ ErrCode AdvancedNotificationService::Publish(const std::string &label, const spt return result; } +ErrCode AdvancedNotificationService::PublishNotificationForIndirectProxy(const std::string &label, const sptr &request) +{ + HITRACE_METER_NAME(HITRACE_TAG_NOTIFICATION, __PRETTY_FUNCTION__); + ANS_LOGD("%{public}s", __FUNCTION__); + + if (!request) { + ANSR_LOGE("ReminderRequest object is nullptr"); + return ERR_ANS_INVALID_PARAM; + } + + if (!InitPublishProcess()) { + return ERR_ANS_NO_MEMORY; + } + + HaMetaMessage message = HaMetaMessage(EventSceneId::SCENE_9, EventBranchId::BRANCH_1); + ErrCode result = publishProcess_[request->GetSlotType()]->PublishPreWork(request, false); + if (result != ERR_OK) { + message.BranchId(EventBranchId::BRANCH_0).ErrorCode(result).Message("publish prework failed", true); + NotificationAnalyticsUtil::ReportPublishFailedEvent(request, message); + return result; + } + result = CheckUserIdParams(request->GetReceiverUserId()); + if (result != ERR_OK) { + message.BranchId(EventBranchId::BRANCH_1).ErrorCode(result).Message("User is invalid", true); + NotificationAnalyticsUtil::ReportPublishFailedEvent(request, message); + return result; + } + auto tokenCaller = IPCSkeleton::GetCallingTokenID(); + bool isAgentController = AccessTokenHelper::VerifyCallerPermission(tokenCaller, + OHOS_PERMISSION_NOTIFICATION_AGENT_CONTROLLER); + message = HaMetaMessage(EventSceneId::SCENE_9, EventBranchId::BRANCH_2); + int32_t uid = request->GetCreatorUid(); + if (uid <= 0) { + message.ErrorCode(ERR_ANS_INVALID_UID).Message("createUid failed" + std::to_string(uid), true); + NotificationAnalyticsUtil::ReportPublishFailedEvent(request, message); + return ERR_ANS_INVALID_UID; + } + std::string bundle = request->GetCreatorBundleName(); + result = PrePublishNotificationForIndirectProxy(request, uid, bundle); + if (result != ERR_OK) { + return result; + } + + // SA not support sound + if (!request->GetSound().empty()) { + request->SetSound(""); + } + std::shared_ptr record = std::make_shared(); + record->request = request; + record->isThirdparty = false; + record->bundleOption = new (std::nothrow) NotificationBundleOption(bundle, uid); + record->bundleOption->SetInstanceKey(request->GetCreatorInstanceKey()); + sptr bundleOption = new (std::nothrow) NotificationBundleOption(bundle, uid); + if (record->bundleOption == nullptr || bundleOption == nullptr) { + ANS_LOGE("Failed to create bundleOption"); + return ERR_ANS_NO_MEMORY; + } + record->notification = new (std::nothrow) Notification(request); + if (record->notification == nullptr) { + ANS_LOGE("Failed to create notification"); + return ERR_ANS_NO_MEMORY; + } + + if (notificationSvrQueue_ == nullptr) { + ANS_LOGE("Serial queue is invalid."); + return ERR_ANS_INVALID_PARAM; + } + + SetRequestBySlotType(record->request, bundleOption); + + auto ipcUid = IPCSkeleton::GetCallingUid(); + ffrt::task_handle handler = notificationSvrQueue_->submit_h([&]() { + if (!bundleOption->GetBundleName().empty()) { + ErrCode ret = AssignValidNotificationSlot(record, bundleOption); + if (ret != ERR_OK) { + ANS_LOGE("Can not assign valid slot!"); + } + } + + ChangeNotificationByControlFlags(record, isAgentController); + if (IsSaCreateSystemLiveViewAsBundle(record, ipcUid) && + (std::static_pointer_cast( + record->request->GetContent()->GetNotificationContent())->GetType() == TYPE_CODE_DOWNLOAD)) { + result = SaPublishSystemLiveViewAsBundle(record); + if (result == ERR_OK) { + SendLiveViewUploadHiSysEvent(record, UploadStatus::CREATE); + } + return; + } + + if (AssignToNotificationList(record) != ERR_OK) { + ANS_LOGE("Failed to assign notification list"); + return; + } + + sptr sortingMap = GenerateSortingMap(); + NotificationSubscriberManager::GetInstance()->NotifyConsumed(record->notification, sortingMap); + }); + notificationSvrQueue_->wait(handler); + if (result != ERR_OK) { + return result; + } + + if ((record->request->GetAutoDeletedTime() > GetCurrentTime()) && !record->request->IsCommonLiveView()) { + StartAutoDelete(record, + record->request->GetAutoDeletedTime(), NotificationConstant::TRIGGER_AUTO_DELETE_REASON_DELETE); + } + return ERR_OK; + +} + bool AdvancedNotificationService::InitPublishProcess() { if (publishProcess_.size() > 0) { diff --git a/services/ans/src/advanced_notification_utils.cpp b/services/ans/src/advanced_notification_utils.cpp index c3f5f318e..cd91d3fa8 100644 --- a/services/ans/src/advanced_notification_utils.cpp +++ b/services/ans/src/advanced_notification_utils.cpp @@ -1690,6 +1690,37 @@ ErrCode AdvancedNotificationService::PrePublishNotificationBySa(const sptr &request, + int32_t uid) +{ + HaMetaMessage message = HaMetaMessage(EventSceneId::SCENE_9, EventBranchId::BRANCH_5); + std::shared_ptr bundleManager = BundleManagerHelper::GetInstance(); + if (bundleManager == nullptr) { + ANS_LOGE("failed to get bundleManager!"); + return ERR_ANS_INVALID_BUNDLE; + } + + request->SetCreatorPid(IPCSkeleton::GetCallingPid()); + int32_t userId = SUBSCRIBE_USER_INIT; + if (request->GetCreatorUserId() == SUBSCRIBE_USER_INIT) { + OHOS::AccountSA::OsAccountManager::GetOsAccountLocalIdFromUid(request->GetCreatorUid(), userId); + request->SetCreatorUserId(userId); + } else { + userId = request->GetCreatorUserId(); + } + + if (request->GetDeliveryTime() <= 0) { + request->SetDeliveryTime(GetCurrentTime()); + } + ErrCode result = CheckPictureSize(request); + if (result != ERR_OK) { + message.ErrorCode(result).Message("Failed to check picture size", true); + NotificationAnalyticsUtil::ReportPublishFailedEvent(request, message); + return result; + } + return ERR_OK; +} + uint64_t AdvancedNotificationService::StartAutoDelete(const std::shared_ptr &record, int64_t deleteTimePoint, int32_t reason) { -- Gitee From 4a5f6ecb40a34086721b2fcac2bd2f68b4773500 Mon Sep 17 00:00:00 2001 From: luojingsong Date: Mon, 21 Oct 2024 17:24:51 +0800 Subject: [PATCH 101/167] =?UTF-8?q?=E6=96=B0=E5=A2=9EinnerApi?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: luojingsong Change-Id: Id425de7ed0071cfec8786fe7ed97cb490f7088ff --- frameworks/ans/src/notification_helper.cpp | 2 +- frameworks/core/include/ans_manager_stub.h | 1 + frameworks/core/src/ans_manager_stub.cpp | 2 +- frameworks/core/src/ans_notification.cpp | 2 +- services/ans/include/advanced_notification_service.h | 2 +- services/ans/src/advanced_notification_publish_service.cpp | 4 ++-- 6 files changed, 7 insertions(+), 6 deletions(-) diff --git a/frameworks/ans/src/notification_helper.cpp b/frameworks/ans/src/notification_helper.cpp index 5ac0231b3..467eac791 100644 --- a/frameworks/ans/src/notification_helper.cpp +++ b/frameworks/ans/src/notification_helper.cpp @@ -82,7 +82,7 @@ ErrCode NotificationHelper::PublishNotification(const std::string &label, const return DelayedSingleton::GetInstance()->PublishNotification(label, request); } -ErrCode NotificationHelper::PublishNotification(const NotificationRequest &request) +ErrCode NotificationHelper::PublishNotificationForIndirectProxy(const NotificationRequest &request) { return DelayedSingleton::GetInstance()->PublishNotificationForIndirectProxy(request); } diff --git a/frameworks/core/include/ans_manager_stub.h b/frameworks/core/include/ans_manager_stub.h index 1b1607f14..16465c2d5 100644 --- a/frameworks/core/include/ans_manager_stub.h +++ b/frameworks/core/include/ans_manager_stub.h @@ -953,6 +953,7 @@ public: private: ErrCode HandlePublish(MessageParcel &data, MessageParcel &reply); + ErrCode HandlePublishNotificationForIndirectProxy(MessageParcel &data, MessageParcel &reply); ErrCode HandleCancel(MessageParcel &data, MessageParcel &reply); ErrCode HandleCancelAll(MessageParcel &data, MessageParcel &reply); ErrCode HandleCancelAsBundle(MessageParcel &data, MessageParcel &reply); diff --git a/frameworks/core/src/ans_manager_stub.cpp b/frameworks/core/src/ans_manager_stub.cpp index 3592046cc..0385e187f 100644 --- a/frameworks/core/src/ans_manager_stub.cpp +++ b/frameworks/core/src/ans_manager_stub.cpp @@ -492,7 +492,7 @@ ErrCode AnsManagerStub::HandlePublishNotificationForIndirectProxy(MessageParcel return ERR_ANS_PARCELABLE_FAILED; } - ErrCode result = Publish(label, notification); + ErrCode result = PublishNotificationForIndirectProxy(notification); if (!reply.WriteInt32(result)) { ANS_LOGE("[HandlePublishNotificationForIndirectProxy] fail: write result failed, ErrCode=%{public}d", result); return ERR_ANS_PARCELABLE_FAILED; diff --git a/frameworks/core/src/ans_notification.cpp b/frameworks/core/src/ans_notification.cpp index 4fcf30ea1..09094a888 100644 --- a/frameworks/core/src/ans_notification.cpp +++ b/frameworks/core/src/ans_notification.cpp @@ -285,7 +285,7 @@ ErrCode AnsNotification::PublishNotificationForIndirectProxy(const NotificationR int32_t instanceKey = DEFAULT_INSTANCE_KEY; reqPtr->SetCreatorInstanceKey(instanceKey); - return proxy->PublishNotificationForIndirectProxy(label, reqPtr); + return proxy->PublishNotificationForIndirectProxy(reqPtr); } ErrCode AnsNotification::CancelNotification(int32_t notificationId) diff --git a/services/ans/include/advanced_notification_service.h b/services/ans/include/advanced_notification_service.h index 5691e288f..782c391d5 100644 --- a/services/ans/include/advanced_notification_service.h +++ b/services/ans/include/advanced_notification_service.h @@ -112,7 +112,7 @@ public: * This parameter must be specified. * @return Returns ERR_OK on success, others on failure. */ - ErrCode PublishNotificationForIndirectProxy(const std::string &label, const sptr &request) override; + ErrCode PublishNotificationForIndirectProxy(const sptr &request) override; /** * @brief Cancels a published notification matching the specified label and notificationId. diff --git a/services/ans/src/advanced_notification_publish_service.cpp b/services/ans/src/advanced_notification_publish_service.cpp index 4e47eab14..b22c5d8ba 100644 --- a/services/ans/src/advanced_notification_publish_service.cpp +++ b/services/ans/src/advanced_notification_publish_service.cpp @@ -169,7 +169,7 @@ ErrCode AdvancedNotificationService::Publish(const std::string &label, const spt return result; } -ErrCode AdvancedNotificationService::PublishNotificationForIndirectProxy(const std::string &label, const sptr &request) +ErrCode AdvancedNotificationService::PublishNotificationForIndirectProxy(const sptr &request) { HITRACE_METER_NAME(HITRACE_TAG_NOTIFICATION, __PRETTY_FUNCTION__); ANS_LOGD("%{public}s", __FUNCTION__); @@ -207,7 +207,7 @@ ErrCode AdvancedNotificationService::PublishNotificationForIndirectProxy(const s return ERR_ANS_INVALID_UID; } std::string bundle = request->GetCreatorBundleName(); - result = PrePublishNotificationForIndirectProxy(request, uid, bundle); + result = PrePublishNotificationForIndirectProxy(request, uid); if (result != ERR_OK) { return result; } -- Gitee From 2944da1d51662030e2c2b3a8af6833223dd5ef9a Mon Sep 17 00:00:00 2001 From: luojingsong Date: Mon, 21 Oct 2024 20:18:59 +0800 Subject: [PATCH 102/167] =?UTF-8?q?=E6=96=B0=E5=A2=9EinnerApi?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: luojingsong Change-Id: I71af7bb4143767165793d9217edc38d37e5190ff --- services/ans/include/advanced_notification_service.h | 2 +- .../ans/src/advanced_notification_publish_service.cpp | 8 ++------ 2 files changed, 3 insertions(+), 7 deletions(-) diff --git a/services/ans/include/advanced_notification_service.h b/services/ans/include/advanced_notification_service.h index 782c391d5..15143b9f2 100644 --- a/services/ans/include/advanced_notification_service.h +++ b/services/ans/include/advanced_notification_service.h @@ -1287,7 +1287,7 @@ private: ErrCode SetRequestBundleInfo(const sptr &request, int32_t uid, std::string &bundle); ErrCode PrePublishNotificationBySa(const sptr &request, int32_t uid, std::string &bundle); - ErrCode PrePublishNotificationForIndirectProxy(const sptr &request,int32_t uid); + ErrCode PrePublishNotificationForIndirectProxy(const sptr &request, int32_t uid); ErrCode PublishNotificationBySa(const sptr &request); bool IsNeedPushCheck(const sptr &request); void FillExtraInfoToJson(const sptr &request, diff --git a/services/ans/src/advanced_notification_publish_service.cpp b/services/ans/src/advanced_notification_publish_service.cpp index b22c5d8ba..8493cfbd5 100644 --- a/services/ans/src/advanced_notification_publish_service.cpp +++ b/services/ans/src/advanced_notification_publish_service.cpp @@ -241,11 +241,8 @@ ErrCode AdvancedNotificationService::PublishNotificationForIndirectProxy(const s auto ipcUid = IPCSkeleton::GetCallingUid(); ffrt::task_handle handler = notificationSvrQueue_->submit_h([&]() { - if (!bundleOption->GetBundleName().empty()) { - ErrCode ret = AssignValidNotificationSlot(record, bundleOption); - if (ret != ERR_OK) { - ANS_LOGE("Can not assign valid slot!"); - } + if (AssignValidNotificationSlot(record, bundleOption) != ERR_OK) { + ANS_LOGE("Can not assign valid slot!"); } ChangeNotificationByControlFlags(record, isAgentController); @@ -277,7 +274,6 @@ ErrCode AdvancedNotificationService::PublishNotificationForIndirectProxy(const s record->request->GetAutoDeletedTime(), NotificationConstant::TRIGGER_AUTO_DELETE_REASON_DELETE); } return ERR_OK; - } bool AdvancedNotificationService::InitPublishProcess() -- Gitee From 9a470dc904ef503fe141d8d8671cf868ba76d3de Mon Sep 17 00:00:00 2001 From: luojingsong Date: Tue, 22 Oct 2024 08:49:16 +0800 Subject: [PATCH 103/167] =?UTF-8?q?=E6=96=B0=E5=A2=9EinnerApi?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: luojingsong Change-Id: Ia744c3d30e1f7edb3011ee42793a762dc70ccaac --- .../ans_notification_branch_test.cpp | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/frameworks/core/test/unittest/ans_notification_branch_test/ans_notification_branch_test.cpp b/frameworks/core/test/unittest/ans_notification_branch_test/ans_notification_branch_test.cpp index a31ebe47c..83db41e44 100644 --- a/frameworks/core/test/unittest/ans_notification_branch_test/ans_notification_branch_test.cpp +++ b/frameworks/core/test/unittest/ans_notification_branch_test/ans_notification_branch_test.cpp @@ -55,6 +55,11 @@ public: return ERR_ANS_INVALID_PARAM; } + ErrCode PublishNotificationForIndirectProxy(const sptr ¬ification) override + { + return ERR_ANS_INVALID_PARAM; + } + ErrCode Cancel(int notificationId, const std::string &label, int32_t instanceKey) override { return ERR_ANS_INVALID_PARAM; -- Gitee From 25948bc5012ac93aa9ebadb551123b7ae4802596 Mon Sep 17 00:00:00 2001 From: luojingsong Date: Wed, 23 Oct 2024 16:38:56 +0800 Subject: [PATCH 104/167] =?UTF-8?q?=E6=96=B0=E5=A2=9EinnerApi?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: luojingsong Change-Id: If4358097c3f5f052125a3479fb803f022b204409 --- .../include/advanced_notification_service.h | 2 +- .../advanced_notification_publish_service.cpp | 31 ++---------------- .../ans/src/advanced_notification_utils.cpp | 32 +++++++++++++++---- 3 files changed, 29 insertions(+), 36 deletions(-) diff --git a/services/ans/include/advanced_notification_service.h b/services/ans/include/advanced_notification_service.h index 15143b9f2..8d723baa1 100644 --- a/services/ans/include/advanced_notification_service.h +++ b/services/ans/include/advanced_notification_service.h @@ -1287,7 +1287,7 @@ private: ErrCode SetRequestBundleInfo(const sptr &request, int32_t uid, std::string &bundle); ErrCode PrePublishNotificationBySa(const sptr &request, int32_t uid, std::string &bundle); - ErrCode PrePublishNotificationForIndirectProxy(const sptr &request, int32_t uid); + ErrCode PrePublishRequest(const sptr &request); ErrCode PublishNotificationBySa(const sptr &request); bool IsNeedPushCheck(const sptr &request); void FillExtraInfoToJson(const sptr &request, diff --git a/services/ans/src/advanced_notification_publish_service.cpp b/services/ans/src/advanced_notification_publish_service.cpp index 8493cfbd5..ffe14f2c8 100644 --- a/services/ans/src/advanced_notification_publish_service.cpp +++ b/services/ans/src/advanced_notification_publish_service.cpp @@ -178,44 +178,19 @@ ErrCode AdvancedNotificationService::PublishNotificationForIndirectProxy(const s ANSR_LOGE("ReminderRequest object is nullptr"); return ERR_ANS_INVALID_PARAM; } - - if (!InitPublishProcess()) { - return ERR_ANS_NO_MEMORY; - } - - HaMetaMessage message = HaMetaMessage(EventSceneId::SCENE_9, EventBranchId::BRANCH_1); - ErrCode result = publishProcess_[request->GetSlotType()]->PublishPreWork(request, false); + ErrCode result = PrePublishRequest(request); if (result != ERR_OK) { - message.BranchId(EventBranchId::BRANCH_0).ErrorCode(result).Message("publish prework failed", true); - NotificationAnalyticsUtil::ReportPublishFailedEvent(request, message); - return result; - } - result = CheckUserIdParams(request->GetReceiverUserId()); - if (result != ERR_OK) { - message.BranchId(EventBranchId::BRANCH_1).ErrorCode(result).Message("User is invalid", true); - NotificationAnalyticsUtil::ReportPublishFailedEvent(request, message); return result; } auto tokenCaller = IPCSkeleton::GetCallingTokenID(); bool isAgentController = AccessTokenHelper::VerifyCallerPermission(tokenCaller, OHOS_PERMISSION_NOTIFICATION_AGENT_CONTROLLER); - message = HaMetaMessage(EventSceneId::SCENE_9, EventBranchId::BRANCH_2); - int32_t uid = request->GetCreatorUid(); - if (uid <= 0) { - message.ErrorCode(ERR_ANS_INVALID_UID).Message("createUid failed" + std::to_string(uid), true); - NotificationAnalyticsUtil::ReportPublishFailedEvent(request, message); - return ERR_ANS_INVALID_UID; - } - std::string bundle = request->GetCreatorBundleName(); - result = PrePublishNotificationForIndirectProxy(request, uid); - if (result != ERR_OK) { - return result; - } - // SA not support sound if (!request->GetSound().empty()) { request->SetSound(""); } + std::string bundle = request->GetCreatorBundleName(); + int32_t uid = request->GetCreatorUid(); std::shared_ptr record = std::make_shared(); record->request = request; record->isThirdparty = false; diff --git a/services/ans/src/advanced_notification_utils.cpp b/services/ans/src/advanced_notification_utils.cpp index cd91d3fa8..d42d8c3d6 100644 --- a/services/ans/src/advanced_notification_utils.cpp +++ b/services/ans/src/advanced_notification_utils.cpp @@ -1690,29 +1690,47 @@ ErrCode AdvancedNotificationService::PrePublishNotificationBySa(const sptr &request, - int32_t uid) +ErrCode AdvancedNotificationService::PrePublishRequest(const sptr &request) { - HaMetaMessage message = HaMetaMessage(EventSceneId::SCENE_9, EventBranchId::BRANCH_5); + HaMetaMessage message = HaMetaMessage(EventSceneId::SCENE_9, EventBranchId::BRANCH_0); + if (!InitPublishProcess()) { + return ERR_ANS_NO_MEMORY; + } + ErrCode result = publishProcess_[request->GetSlotType()]->PublishPreWork(request, false); + if (result != ERR_OK) { + message.BranchId(EventBranchId::BRANCH_0).ErrorCode(result).Message("publish prework failed", true); + NotificationAnalyticsUtil::ReportPublishFailedEvent(request, message); + return result; + } + result = CheckUserIdParams(request->GetReceiverUserId()); + if (result != ERR_OK) { + message.BranchId(EventBranchId::BRANCH_1).ErrorCode(result).Message("User is invalid", true); + NotificationAnalyticsUtil::ReportPublishFailedEvent(request, message); + return result; + } + + if (request->GetCreatorUid() <= 0) { + message.BranchId(EventBranchId::BRANCH_2).ErrorCode(ERR_ANS_INVALID_UID) + .Message("createUid failed" + std::to_string(request->GetCreatorUid()), true); + NotificationAnalyticsUtil::ReportPublishFailedEvent(request, message); + return ERR_ANS_INVALID_UID; + } std::shared_ptr bundleManager = BundleManagerHelper::GetInstance(); if (bundleManager == nullptr) { ANS_LOGE("failed to get bundleManager!"); return ERR_ANS_INVALID_BUNDLE; } - request->SetCreatorPid(IPCSkeleton::GetCallingPid()); int32_t userId = SUBSCRIBE_USER_INIT; if (request->GetCreatorUserId() == SUBSCRIBE_USER_INIT) { OHOS::AccountSA::OsAccountManager::GetOsAccountLocalIdFromUid(request->GetCreatorUid(), userId); request->SetCreatorUserId(userId); - } else { - userId = request->GetCreatorUserId(); } if (request->GetDeliveryTime() <= 0) { request->SetDeliveryTime(GetCurrentTime()); } - ErrCode result = CheckPictureSize(request); + result = CheckPictureSize(request); if (result != ERR_OK) { message.ErrorCode(result).Message("Failed to check picture size", true); NotificationAnalyticsUtil::ReportPublishFailedEvent(request, message); -- Gitee From 1b41a873385bb0e8f4fe34d94b00f97068d6950f Mon Sep 17 00:00:00 2001 From: luojingsong Date: Fri, 25 Oct 2024 10:54:40 +0800 Subject: [PATCH 105/167] =?UTF-8?q?=E5=AE=9E=E5=86=B5=E6=A3=80=E6=9F=A5?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: luojingsong Change-Id: I7357767df27150d480ef1e7e9292782fe94852d9 --- services/ans/include/advanced_notification_service.h | 2 +- services/ans/src/advanced_notification_service.cpp | 10 +++------- 2 files changed, 4 insertions(+), 8 deletions(-) diff --git a/services/ans/include/advanced_notification_service.h b/services/ans/include/advanced_notification_service.h index 8d723baa1..708ba51f2 100644 --- a/services/ans/include/advanced_notification_service.h +++ b/services/ans/include/advanced_notification_service.h @@ -1393,7 +1393,7 @@ private: ErrCode RemoveAllNotificationsInner(const sptr &bundleOption, int32_t reason); void RemoveNotificationList(const std::shared_ptr &record); void StartFinishTimerForUpdate(const std::shared_ptr &record, uint64_t process); - ErrCode CheckSystemLiveView(const sptr &request, const std::string &key); + ErrCode CheckLongTermLiveView(const sptr &request, const std::string &key); void ExcuteCancelGroupCancel(const sptr& bundleOption, const std::string &groupName, const int32_t reason); ErrCode ExcuteCancelAll(const sptr& bundleOption, const int32_t reason); diff --git a/services/ans/src/advanced_notification_service.cpp b/services/ans/src/advanced_notification_service.cpp index d43bf7567..90848a55f 100644 --- a/services/ans/src/advanced_notification_service.cpp +++ b/services/ans/src/advanced_notification_service.cpp @@ -2138,13 +2138,9 @@ ErrCode AdvancedNotificationService::CheckSoundPermission(const sptr &request, +ErrCode AdvancedNotificationService::CheckLongTermLiveView(const sptr &request, const std::string &key) { - if (!request->IsSystemLiveView()) { - return ERR_OK; - } - // live view, not update std::shared_ptr additionalData = request->GetAdditionalData(); if (additionalData && additionalData->HasParam("SYSTEM_UPDATE_ONLY")) { @@ -2155,7 +2151,7 @@ ErrCode AdvancedNotificationService::CheckSystemLiveView(const sptrrequest, record->notification->GetKey()) != ERR_OK) { + if (!remove && CheckLongTermLiveView(record->request, record->notification->GetKey()) != ERR_OK) { return ERR_ANS_INVALID_PARAM; } -- Gitee From 397820950a75f26a4cf97ecc6ad7df2e5362bda4 Mon Sep 17 00:00:00 2001 From: luojingsong Date: Mon, 28 Oct 2024 16:25:18 +0800 Subject: [PATCH 106/167] =?UTF-8?q?=E6=99=BA=E8=83=BD=E6=8F=90=E9=86=92?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: luojingsong Change-Id: I73403a710a7c0aff0743392f18254298977e0094 --- .../ans/src/notification_subscriber.cpp | 4 +- .../include/advanced_notification_service.h | 1 - .../ans/include/notification_preferences.h | 10 ++++ .../notification_preferences_database.h | 2 + services/ans/include/smart_reminder_center.h | 2 +- .../ans/src/advanced_notification_service.cpp | 1 + .../ans/src/advanced_notification_utils.cpp | 57 +++++++++++++++++++ services/ans/src/notification_preferences.cpp | 17 ++++++ .../src/notification_preferences_database.cpp | 45 ++++++++++++++- .../smart_reminder_center.cpp | 14 ++--- 10 files changed, 136 insertions(+), 17 deletions(-) diff --git a/frameworks/ans/src/notification_subscriber.cpp b/frameworks/ans/src/notification_subscriber.cpp index d33ef4415..091cbe212 100644 --- a/frameworks/ans/src/notification_subscriber.cpp +++ b/frameworks/ans/src/notification_subscriber.cpp @@ -56,8 +56,8 @@ bool NotificationSubscriber::ProcessSyncDecision( } auto flagIter = flagsMap->find(deviceType); if (flagIter != flagsMap->end() && flagIter->second != nullptr) { - ANS_LOGI("SetFlags-before filte, notificationKey = %{public}s flagIter flags = %{public}d", - request->GetKey().c_str(), flagIter->second->GetReminderFlags()); + ANS_LOGI("SetFlags-before filte, notificationKey = %{public}s flagIter flags = %{public}d deviceType = %{public}s", + request->GetKey().c_str(), flagIter->second->GetReminderFlags(), deviceType.c_str()); std::shared_ptr tempFlags = request->GetFlags(); tempFlags->SetSoundEnabled(DowngradeReminder(tempFlags->IsSoundEnabled(), flagIter->second->IsSoundEnabled())); tempFlags->SetVibrationEnabled( diff --git a/services/ans/include/advanced_notification_service.h b/services/ans/include/advanced_notification_service.h index 708ba51f2..be8bd51c9 100644 --- a/services/ans/include/advanced_notification_service.h +++ b/services/ans/include/advanced_notification_service.h @@ -1400,7 +1400,6 @@ private: ErrCode ExcuteDelete(const std::string &key, const int32_t removeReason); ErrCode CheckNeedSilent(const std::string &phoneNumber, int32_t callerType, int32_t userId); uint32_t GetDefaultSlotFlags(const sptr &request); - private: static sptr instance_; static std::mutex instanceMutex_; diff --git a/services/ans/include/notification_preferences.h b/services/ans/include/notification_preferences.h index 1ffce83c8..8c49b3cb5 100644 --- a/services/ans/include/notification_preferences.h +++ b/services/ans/include/notification_preferences.h @@ -325,6 +325,15 @@ public: */ ErrCode IsSmartReminderEnabled(const std::string &deviceType, bool &enabled); + /** + * @brief Get old distributedEnabled used to reset. + * + * @param values Indicates the data of query result. + * @param userId Indicates the user of old data in. + * @return Returns get old distributedEnabled result. + */ + ErrCode GetOldDistributedEnabled(std::unordered_map &values, const int32_t userId); + /** * @brief Set Enable smartphone to collaborate with other devices for intelligent reminders * @@ -370,6 +379,7 @@ public: int32_t GetBatchKvsFromDb( const std::string &key, std::unordered_map &values, const int32_t &userId); int32_t DeleteKvFromDb(const std::string &key, const int &userId); + int32_t DeleteBatchKvFromDb(const std::vector &keys, const int &userId); ErrCode GetDoNotDisturbProfile(int32_t profileId, int32_t userId, sptr &profile); bool CheckDoNotDisturbProfileID(int32_t profileId); void RemoveDoNotDisturbProfileTrustList(int32_t userId, const sptr &bundleOption); diff --git a/services/ans/include/notification_preferences_database.h b/services/ans/include/notification_preferences_database.h index 2c7b755dd..e92d36f5d 100644 --- a/services/ans/include/notification_preferences_database.h +++ b/services/ans/include/notification_preferences_database.h @@ -231,7 +231,9 @@ public: int32_t GetBatchKvsFromDb( const std::string &key, std::unordered_map &values, const int32_t &userId); int32_t DeleteKvFromDb(const std::string &key, const int32_t &userId); + int32_t DeleteBatchKvFromDb(const std::vector &keys, const int &userId); int32_t DropUserTable(const int32_t userId); + int32_t GetDistributedDataByOldKey(std::unordered_map &values, const int32_t userId); private: bool CheckRdbStore(); diff --git a/services/ans/include/smart_reminder_center.h b/services/ans/include/smart_reminder_center.h index 8fb58b260..d9b09cd29 100644 --- a/services/ans/include/smart_reminder_center.h +++ b/services/ans/include/smart_reminder_center.h @@ -78,7 +78,7 @@ private: const sptr &request, vector> &reminderAffecteds) const; void GetDeviceStatusByType(const string &deviceType, bitset &bitStatus) const; - bool IsNeedSynergy(const string &deviceType, const string &ownerBundleName) const; + bool IsNeedSynergy(const string &deviceType, const string &ownerBundleName, int32_t ownerUid) const; map> currentReminderMethods_; map>>> reminderMethods_; diff --git a/services/ans/src/advanced_notification_service.cpp b/services/ans/src/advanced_notification_service.cpp index 90848a55f..8991d3abc 100644 --- a/services/ans/src/advanced_notification_service.cpp +++ b/services/ans/src/advanced_notification_service.cpp @@ -300,6 +300,7 @@ AdvancedNotificationService::AdvancedNotificationService() NotificationSubscriberManager::GetInstance()->RegisterOnSubscriberAddCallback(callback); RecoverLiveViewFromDb(); + ResetDistributedEnabled(); ISystemEvent iSystemEvent = { std::bind(&AdvancedNotificationService::OnBundleRemoved, this, std::placeholders::_1), diff --git a/services/ans/src/advanced_notification_utils.cpp b/services/ans/src/advanced_notification_utils.cpp index d42d8c3d6..666d15390 100644 --- a/services/ans/src/advanced_notification_utils.cpp +++ b/services/ans/src/advanced_notification_utils.cpp @@ -38,6 +38,7 @@ #include "notification_timer_info.h" #include "time_service_client.h" #include "notification_extension_wrapper.h" +#include "string_utils.h" #ifdef DISTRIBUTED_NOTIFICATION_SUPPORTED #include "distributed_notification_manager.h" @@ -75,6 +76,11 @@ constexpr char RECENT_NOTIFICATION_OPTION[] = "recent"; constexpr char HIDUMPER_ERR_MSG[] = "error: unknown option.\nThe arguments are illegal and you can enter '-h' for help."; constexpr int32_t MAIN_USER_ID = 100; +constexpr int32_t FIRST_USERID = 0; +constexpr char KEY_TABLE_VERSION[] = "tableVersion"; +constexpr char SPLIT_FLAG[] = "-"; +constexpr int32_t KEYWORD_SIZE = 4; +constexpr int32_t MIN_VERSION = 1; const std::unordered_map HIDUMPER_CMD_MAP = { { "--help", HELP_NOTIFICATION_OPTION }, { "--active", ACTIVE_NOTIFICATION_OPTION }, @@ -1950,5 +1956,56 @@ bool AdvancedNotificationService::AllowUseReminder(const std::string& bundleName return true; #endif } + +void AdvancedNotificationService::ResetDistributedEnabled() +{ + if (notificationSvrQueue_ == nullptr) { + ANS_LOGE("notificationSvrQueue is nullptr"); + } + ffrt::task_handle handler = notificationSvrQueue_->submit_h(std::bind([=](){ + std::string value; + NotificationPreferences::GetInstance()->GetKvFromDb(KEY_TABLE_VERSION, value, FIRST_USERID); + if (!value.empty()) { + return; + } + ANS_LOGI("start ResetDistributedEnabled"); + std::unordered_map oldValues; + if (NotificationPreferences::GetInstance()->GetOldDistributedEnabled(oldValues, FIRST_USERID) != ERR_OK + || oldValues.empty()) + { + NotificationPreferences::GetInstance()->SetKvToDb( + KEY_TABLE_VERSION, std::to_string(MIN_VERSION), FIRST_USERID); + return; + } + std::shared_ptr bundleManager = BundleManagerHelper::GetInstance(); + std::vector delKeys; + for (auto iter : oldValues) { + std::vector keywordVector; + StringUtils::Split(iter.first, SPLIT_FLAG, keywordVector); + delKeys.push_back(iter.first); + if (keywordVector.size() != KEYWORD_SIZE) { + continue; + } + std::string bundleName = keywordVector[1]; + int32_t activeUserId = atoi(keywordVector[2].c_str()); + std::string deviceType = keywordVector[3]; + bool enabled = atoi(iter.second.c_str()); + int32_t uid = bundleManager->GetDefaultUidByBundleName(bundleName, activeUserId); + if (uid <= 0) { + continue; + } + sptr bundleOption = new NotificationBundleOption(bundleName, uid); + ErrCode result = NotificationPreferences::GetInstance()->SetDistributedEnabledByBundle( + bundleOption, deviceType, enabled); + if (result != ERR_OK) { + ANS_LOGE("SetDistributeEnabled failed! key:%{public}s, uid:%{public}d", + iter.first.c_str(), uid); + } + } + NotificationPreferences::GetInstance()->DeleteBatchKvFromDb(delKeys, FIRST_USERID); + NotificationPreferences::GetInstance()->SetKvToDb( + KEY_TABLE_VERSION, std::to_string(MIN_VERSION), FIRST_USERID); + })); +} } // namespace Notification } // namespace OHOS diff --git a/services/ans/src/notification_preferences.cpp b/services/ans/src/notification_preferences.cpp index a19e7451d..06148e115 100644 --- a/services/ans/src/notification_preferences.cpp +++ b/services/ans/src/notification_preferences.cpp @@ -890,6 +890,15 @@ ErrCode NotificationPreferences::SetDistributedEnabledByBundle(const sptr &values, + const int32_t userId) +{ + ANS_LOGD("%{public}s", __FUNCTION__); + std::lock_guard lock(preferenceMutex_); + int32_t storeDBResult = preferncesDB_->GetDistributedDataByOldKey(values, userId); + return storeDBResult == NativeRdb::E_OK ? ERR_OK : ERR_ANS_PREFERENCES_NOTIFICATION_DB_OPERATION_FAILED; +} + ErrCode NotificationPreferences::IsDistributedEnabledByBundle(const sptr &bundleOption, const std::string &deviceType, bool &enabled) { @@ -1071,6 +1080,14 @@ int32_t NotificationPreferences::DeleteKvFromDb(const std::string &key, const in return preferncesDB_->DeleteKvFromDb(key, userId); } +int32_t NotificationPreferences::DeleteBatchKvFromDb(const std::vector &keys, const int32_t &userId) +{ + if (preferncesDB_ == nullptr) { + return ERR_ANS_SERVICE_NOT_READY; + } + return preferncesDB_->DeleteBatchKvFromDb(keys, userId); +} + bool NotificationPreferences::IsAgentRelationship(const std::string &agentBundleName, const std::string &sourceBundleName) { diff --git a/services/ans/src/notification_preferences_database.cpp b/services/ans/src/notification_preferences_database.cpp index 8ff63d1c8..867b9189b 100644 --- a/services/ans/src/notification_preferences_database.cpp +++ b/services/ans/src/notification_preferences_database.cpp @@ -100,10 +100,15 @@ const static std::string KEY_BUNDLE_BADGE_TOTAL_NUM = "badgeTotalNum"; */ const static std::string KEY_BUNDLE_ENABLE_NOTIFICATION = "enabledNotification"; +/** + * Indicates that old disturbe key which bundle enable notification. + */ +const static std::string OLD_KEY_BUNDLE_DISTRIBUTED_ENABLE_NOTIFICATION = "enabledNotificationDistributed"; + /** * Indicates that disturbe key which bundle enable notification. */ -const static std::string KEY_BUNDLE_DISTRIBUTED_ENABLE_NOTIFICATION = "enabledNotificationDistributed"; +const static std::string KEY_ENABLE_BUNDLE_DISTRIBUTED_NOTIFICATION = "enabledDistributedNotification"; /** * Indicates that disturbe key which bundle enable notification. @@ -1654,7 +1659,7 @@ bool NotificationPreferencesDatabase::RemoveEnabledDbByBundleName(std::string bu } int32_t userId = -1; OsAccountManagerHelper::GetInstance().GetOsAccountLocalIdFromUid(bundleUid, userId); - std::string key = std::string(KEY_BUNDLE_DISTRIBUTED_ENABLE_NOTIFICATION).append( + std::string key = std::string(KEY_ENABLE_BUNDLE_DISTRIBUTED_NOTIFICATION).append( KEY_MIDDLE_LINE).append(std::string(bundleName).append(KEY_MIDDLE_LINE)); ANS_LOGD("key is %{public}s", key.c_str()); int32_t result = NativeRdb::E_OK; @@ -1797,6 +1802,23 @@ int32_t NotificationPreferencesDatabase::DeleteKvFromDb(const std::string &key, return NativeRdb::E_OK; } +int32_t NotificationPreferencesDatabase::DeleteBatchKvFromDb(const std::vector &keys, + const int32_t &userId) +{ + if (!CheckRdbStore()) { + ANS_LOGE("RdbStore is nullptr."); + return NativeRdb::E_ERROR; + } + + int32_t result = rdbDataManager_->DeleteBathchData(keys, userId); + if (result != NativeRdb::E_OK) { + ANS_LOGE("Delete key-value failed, result %{public}d.", result); + return NativeRdb::E_ERROR; + } + + return NativeRdb::E_OK; +} + int32_t NotificationPreferencesDatabase::DropUserTable(const int32_t userId) { if (!CheckRdbStore()) { @@ -1812,6 +1834,23 @@ int32_t NotificationPreferencesDatabase::DropUserTable(const int32_t userId) return NativeRdb::E_OK; } +int32_t NotificationPreferencesDatabase::GetDistributedDataByOldKey( + std::unordered_map &values, const int32_t userId) +{ + if (!CheckRdbStore()) { + ANS_LOGE("RdbStore is nullptr."); + return NativeRdb::E_ERROR; + } + + int32_t result = rdbDataManager_->QueryDataBeginWithKey(OLD_KEY_BUNDLE_DISTRIBUTED_ENABLE_NOTIFICATION, + values, userId); + if (result != NativeRdb::E_OK) { + ANS_LOGE("Get distributedDataByOldKey failed, result %{public}d.", result); + return NativeRdb::E_ERROR; + } + return NativeRdb::E_OK; +} + bool NotificationPreferencesDatabase::IsAgentRelationship(const std::string &agentBundleName, const std::string &sourceBundleName) { @@ -1870,7 +1909,7 @@ bool NotificationPreferencesDatabase::PutDistributedEnabledForBundle(const std:: std::string NotificationPreferencesDatabase::GenerateBundleLablel( const NotificationPreferencesInfo::BundleInfo &bundleInfo, const std::string &deviceType) const { - return std::string(KEY_BUNDLE_DISTRIBUTED_ENABLE_NOTIFICATION).append(KEY_MIDDLE_LINE).append( + return std::string(KEY_ENABLE_BUNDLE_DISTRIBUTED_NOTIFICATION).append(KEY_MIDDLE_LINE).append( std::string(bundleInfo.GetBundleName()).append(KEY_MIDDLE_LINE).append(std::to_string( bundleInfo.GetBundleUid())).append(KEY_MIDDLE_LINE).append(deviceType)); } diff --git a/services/ans/src/notification_smart_reminder/smart_reminder_center.cpp b/services/ans/src/notification_smart_reminder/smart_reminder_center.cpp index e1d136555..dab4bbcda 100644 --- a/services/ans/src/notification_smart_reminder/smart_reminder_center.cpp +++ b/services/ans/src/notification_smart_reminder/smart_reminder_center.cpp @@ -270,7 +270,7 @@ void SmartReminderCenter::HandleReminderMethods( GetDeviceStatusByType(deviceType, bitStatus); bool enabledAffectedBy = true; if (deviceType.compare(NotificationConstant::CURRENT_DEVICE_TYPE) != 0) { - if (IsNeedSynergy(deviceType, request->GetOwnerBundleName())) { + if (IsNeedSynergy(deviceType, request->GetOwnerBundleName(), request->GetOwnerUid())) { validDevices.insert(deviceType); } else { enabledAffectedBy = false; @@ -295,20 +295,14 @@ void SmartReminderCenter::HandleReminderMethods( } } -bool SmartReminderCenter::IsNeedSynergy(const string &deviceType, const string &ownerBundleName) const +bool SmartReminderCenter::IsNeedSynergy(const string &deviceType, const string &ownerBundleName, int32_t ownerUid) const { bool isEnable = true; if (NotificationPreferences::GetInstance()->IsSmartReminderEnabled(deviceType, isEnable) != ERR_OK || !isEnable) { return false; } - int32_t userId = -1; - int32_t result = - OHOS::AccountSA::OsAccountManager::GetOsAccountLocalIdFromUid(IPCSkeleton::GetCallingUid(), userId); - if (result != ERR_OK) { - ANS_LOGE("HandleReminderMethods GetOsAccountLocalIdFromUid fail, code = %{public}d.", result); - return false; - } - sptr bundleOption = new (std::nothrow) NotificationBundleOption(ownerBundleName, userId); + + sptr bundleOption = new (std::nothrow) NotificationBundleOption(ownerBundleName, ownerUid); if (NotificationPreferences::GetInstance()->IsDistributedEnabledByBundle( bundleOption, deviceType, isEnable) != ERR_OK || !isEnable) { return false; -- Gitee From c9a37f1d394871879388dd9b7cb610840b4e3781 Mon Sep 17 00:00:00 2001 From: luojingsong Date: Mon, 28 Oct 2024 16:58:47 +0800 Subject: [PATCH 107/167] =?UTF-8?q?=E6=99=BA=E8=83=BD=E6=8F=90=E9=86=92?= =?UTF-8?q?=E9=97=AE=E9=A2=98?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: luojingsong Change-Id: Ia7bea3f8876bb6e47f2c81528dc797c0273fded7 --- frameworks/ans/src/notification_subscriber.cpp | 5 +++-- services/ans/src/advanced_notification_utils.cpp | 5 +++-- 2 files changed, 6 insertions(+), 4 deletions(-) diff --git a/frameworks/ans/src/notification_subscriber.cpp b/frameworks/ans/src/notification_subscriber.cpp index 091cbe212..0b9048a47 100644 --- a/frameworks/ans/src/notification_subscriber.cpp +++ b/frameworks/ans/src/notification_subscriber.cpp @@ -54,10 +54,11 @@ bool NotificationSubscriber::ProcessSyncDecision( if (flagsMap == nullptr || flagsMap->size() <= 0) { return true; } + ANS_LOGI("SetFlags filte, deviceType = %{public}s", deviceType.c_str()); auto flagIter = flagsMap->find(deviceType); if (flagIter != flagsMap->end() && flagIter->second != nullptr) { - ANS_LOGI("SetFlags-before filte, notificationKey = %{public}s flagIter flags = %{public}d deviceType = %{public}s", - request->GetKey().c_str(), flagIter->second->GetReminderFlags(), deviceType.c_str()); + ANS_LOGI("SetFlags-before filte, notificationKey = %{public}s flagIter flags = %{public}d", + request->GetKey().c_str(), flagIter->second->GetReminderFlags()); std::shared_ptr tempFlags = request->GetFlags(); tempFlags->SetSoundEnabled(DowngradeReminder(tempFlags->IsSoundEnabled(), flagIter->second->IsSoundEnabled())); tempFlags->SetVibrationEnabled( diff --git a/services/ans/src/advanced_notification_utils.cpp b/services/ans/src/advanced_notification_utils.cpp index 666d15390..6808a8021 100644 --- a/services/ans/src/advanced_notification_utils.cpp +++ b/services/ans/src/advanced_notification_utils.cpp @@ -1962,7 +1962,7 @@ void AdvancedNotificationService::ResetDistributedEnabled() if (notificationSvrQueue_ == nullptr) { ANS_LOGE("notificationSvrQueue is nullptr"); } - ffrt::task_handle handler = notificationSvrQueue_->submit_h(std::bind([=](){ + ffrt::task_handle handler = notificationSvrQueue_->submit_h(std::bind([=]() { std::string value; NotificationPreferences::GetInstance()->GetKvFromDb(KEY_TABLE_VERSION, value, FIRST_USERID); if (!value.empty()) { @@ -1994,7 +1994,8 @@ void AdvancedNotificationService::ResetDistributedEnabled() if (uid <= 0) { continue; } - sptr bundleOption = new NotificationBundleOption(bundleName, uid); + sptr bundleOption = + new NotificationBundleOption(bundleName, uid); ErrCode result = NotificationPreferences::GetInstance()->SetDistributedEnabledByBundle( bundleOption, deviceType, enabled); if (result != ERR_OK) { -- Gitee From c26e5fde61e82fd99ade86b4c35042d34cb38770 Mon Sep 17 00:00:00 2001 From: luojingsong Date: Tue, 29 Oct 2024 09:06:36 +0800 Subject: [PATCH 108/167] =?UTF-8?q?=E6=99=BA=E8=83=BD=E6=8F=90=E9=86=92?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: luojingsong Change-Id: I4b7135fe0986bf3acc5902ccd99942381e35ff3f --- .../ans/src/notification_subscriber.cpp | 6 ++--- .../ans/include/notification_preferences.h | 9 -------- .../notification_preferences_database.h | 1 - .../ans/src/advanced_notification_utils.cpp | 7 +++--- services/ans/src/notification_preferences.cpp | 9 -------- .../src/notification_preferences_database.cpp | 22 ------------------- .../smart_reminder_center.cpp | 3 ++- 7 files changed, 9 insertions(+), 48 deletions(-) diff --git a/frameworks/ans/src/notification_subscriber.cpp b/frameworks/ans/src/notification_subscriber.cpp index 0b9048a47..cdc9d5bfd 100644 --- a/frameworks/ans/src/notification_subscriber.cpp +++ b/frameworks/ans/src/notification_subscriber.cpp @@ -54,11 +54,11 @@ bool NotificationSubscriber::ProcessSyncDecision( if (flagsMap == nullptr || flagsMap->size() <= 0) { return true; } - ANS_LOGI("SetFlags filte, deviceType = %{public}s", deviceType.c_str()); auto flagIter = flagsMap->find(deviceType); if (flagIter != flagsMap->end() && flagIter->second != nullptr) { - ANS_LOGI("SetFlags-before filte, notificationKey = %{public}s flagIter flags = %{public}d", - request->GetKey().c_str(), flagIter->second->GetReminderFlags()); + ANS_LOGI("SetFlags-before filte, notificationKey = %{public}s flagIter \ + flags = %{public}d, deviceType:%{public}s", + request->GetKey().c_str(), flagIter->second->GetReminderFlags(), deviceType.c_str()); std::shared_ptr tempFlags = request->GetFlags(); tempFlags->SetSoundEnabled(DowngradeReminder(tempFlags->IsSoundEnabled(), flagIter->second->IsSoundEnabled())); tempFlags->SetVibrationEnabled( diff --git a/services/ans/include/notification_preferences.h b/services/ans/include/notification_preferences.h index 8c49b3cb5..af6941298 100644 --- a/services/ans/include/notification_preferences.h +++ b/services/ans/include/notification_preferences.h @@ -325,15 +325,6 @@ public: */ ErrCode IsSmartReminderEnabled(const std::string &deviceType, bool &enabled); - /** - * @brief Get old distributedEnabled used to reset. - * - * @param values Indicates the data of query result. - * @param userId Indicates the user of old data in. - * @return Returns get old distributedEnabled result. - */ - ErrCode GetOldDistributedEnabled(std::unordered_map &values, const int32_t userId); - /** * @brief Set Enable smartphone to collaborate with other devices for intelligent reminders * diff --git a/services/ans/include/notification_preferences_database.h b/services/ans/include/notification_preferences_database.h index e92d36f5d..3aba50cb9 100644 --- a/services/ans/include/notification_preferences_database.h +++ b/services/ans/include/notification_preferences_database.h @@ -233,7 +233,6 @@ public: int32_t DeleteKvFromDb(const std::string &key, const int32_t &userId); int32_t DeleteBatchKvFromDb(const std::vector &keys, const int &userId); int32_t DropUserTable(const int32_t userId); - int32_t GetDistributedDataByOldKey(std::unordered_map &values, const int32_t userId); private: bool CheckRdbStore(); diff --git a/services/ans/src/advanced_notification_utils.cpp b/services/ans/src/advanced_notification_utils.cpp index 6808a8021..da175b8af 100644 --- a/services/ans/src/advanced_notification_utils.cpp +++ b/services/ans/src/advanced_notification_utils.cpp @@ -77,6 +77,7 @@ constexpr char HIDUMPER_ERR_MSG[] = "error: unknown option.\nThe arguments are illegal and you can enter '-h' for help."; constexpr int32_t MAIN_USER_ID = 100; constexpr int32_t FIRST_USERID = 0; +constexpr char OLD_KEY_BUNDLE_DISTRIBUTED_ENABLE_NOTIFICATION[] = "enabledNotificationDistributed"; constexpr char KEY_TABLE_VERSION[] = "tableVersion"; constexpr char SPLIT_FLAG[] = "-"; constexpr int32_t KEYWORD_SIZE = 4; @@ -1970,9 +1971,9 @@ void AdvancedNotificationService::ResetDistributedEnabled() } ANS_LOGI("start ResetDistributedEnabled"); std::unordered_map oldValues; - if (NotificationPreferences::GetInstance()->GetOldDistributedEnabled(oldValues, FIRST_USERID) != ERR_OK - || oldValues.empty()) - { + NotificationPreferences::GetInstance()->GetBatchKvsFromDb( + OLD_KEY_BUNDLE_DISTRIBUTED_ENABLE_NOTIFICATION, oldValues, FIRST_USERID); + if (oldValues.empty()) { NotificationPreferences::GetInstance()->SetKvToDb( KEY_TABLE_VERSION, std::to_string(MIN_VERSION), FIRST_USERID); return; diff --git a/services/ans/src/notification_preferences.cpp b/services/ans/src/notification_preferences.cpp index 06148e115..c4bee7f6f 100644 --- a/services/ans/src/notification_preferences.cpp +++ b/services/ans/src/notification_preferences.cpp @@ -890,15 +890,6 @@ ErrCode NotificationPreferences::SetDistributedEnabledByBundle(const sptr &values, - const int32_t userId) -{ - ANS_LOGD("%{public}s", __FUNCTION__); - std::lock_guard lock(preferenceMutex_); - int32_t storeDBResult = preferncesDB_->GetDistributedDataByOldKey(values, userId); - return storeDBResult == NativeRdb::E_OK ? ERR_OK : ERR_ANS_PREFERENCES_NOTIFICATION_DB_OPERATION_FAILED; -} - ErrCode NotificationPreferences::IsDistributedEnabledByBundle(const sptr &bundleOption, const std::string &deviceType, bool &enabled) { diff --git a/services/ans/src/notification_preferences_database.cpp b/services/ans/src/notification_preferences_database.cpp index 867b9189b..153f58269 100644 --- a/services/ans/src/notification_preferences_database.cpp +++ b/services/ans/src/notification_preferences_database.cpp @@ -100,11 +100,6 @@ const static std::string KEY_BUNDLE_BADGE_TOTAL_NUM = "badgeTotalNum"; */ const static std::string KEY_BUNDLE_ENABLE_NOTIFICATION = "enabledNotification"; -/** - * Indicates that old disturbe key which bundle enable notification. - */ -const static std::string OLD_KEY_BUNDLE_DISTRIBUTED_ENABLE_NOTIFICATION = "enabledNotificationDistributed"; - /** * Indicates that disturbe key which bundle enable notification. */ @@ -1834,23 +1829,6 @@ int32_t NotificationPreferencesDatabase::DropUserTable(const int32_t userId) return NativeRdb::E_OK; } -int32_t NotificationPreferencesDatabase::GetDistributedDataByOldKey( - std::unordered_map &values, const int32_t userId) -{ - if (!CheckRdbStore()) { - ANS_LOGE("RdbStore is nullptr."); - return NativeRdb::E_ERROR; - } - - int32_t result = rdbDataManager_->QueryDataBeginWithKey(OLD_KEY_BUNDLE_DISTRIBUTED_ENABLE_NOTIFICATION, - values, userId); - if (result != NativeRdb::E_OK) { - ANS_LOGE("Get distributedDataByOldKey failed, result %{public}d.", result); - return NativeRdb::E_ERROR; - } - return NativeRdb::E_OK; -} - bool NotificationPreferencesDatabase::IsAgentRelationship(const std::string &agentBundleName, const std::string &sourceBundleName) { diff --git a/services/ans/src/notification_smart_reminder/smart_reminder_center.cpp b/services/ans/src/notification_smart_reminder/smart_reminder_center.cpp index dab4bbcda..8e4b8c8c0 100644 --- a/services/ans/src/notification_smart_reminder/smart_reminder_center.cpp +++ b/services/ans/src/notification_smart_reminder/smart_reminder_center.cpp @@ -302,7 +302,8 @@ bool SmartReminderCenter::IsNeedSynergy(const string &deviceType, const string & return false; } - sptr bundleOption = new (std::nothrow) NotificationBundleOption(ownerBundleName, ownerUid); + sptr bundleOption = + new (std::nothrow) NotificationBundleOption(ownerBundleName, ownerUid); if (NotificationPreferences::GetInstance()->IsDistributedEnabledByBundle( bundleOption, deviceType, isEnable) != ERR_OK || !isEnable) { return false; -- Gitee From a2e32aa734e971a4951b77a601cca233e8367f45 Mon Sep 17 00:00:00 2001 From: luojingsong Date: Tue, 29 Oct 2024 09:15:23 +0800 Subject: [PATCH 109/167] =?UTF-8?q?=E6=99=BA=E8=83=BD=E6=8F=90=E9=86=92?= =?UTF-8?q?=E9=97=AE=E9=A2=98?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: luojingsong Change-Id: Ic10db0824eff7c2cf5a8bdfb54caf1a6cfe2d6fc --- services/ans/src/advanced_notification_utils.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/services/ans/src/advanced_notification_utils.cpp b/services/ans/src/advanced_notification_utils.cpp index da175b8af..cb07a7a69 100644 --- a/services/ans/src/advanced_notification_utils.cpp +++ b/services/ans/src/advanced_notification_utils.cpp @@ -1995,7 +1995,7 @@ void AdvancedNotificationService::ResetDistributedEnabled() if (uid <= 0) { continue; } - sptr bundleOption = + sptr bundleOption = new NotificationBundleOption(bundleName, uid); ErrCode result = NotificationPreferences::GetInstance()->SetDistributedEnabledByBundle( bundleOption, deviceType, enabled); -- Gitee From 9d1d355dd69a9d38007a10c4c3abea2b93e98c0a Mon Sep 17 00:00:00 2001 From: luojingsong Date: Mon, 4 Nov 2024 20:18:37 +0800 Subject: [PATCH 110/167] =?UTF-8?q?=E6=99=BA=E8=83=BD=E6=8F=90=E9=86=92?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: luojingsong Change-Id: I46dea30cc4b384f4a3010696f49c9f0369892129 --- services/ans/include/advanced_notification_service.h | 2 ++ .../ans/src/advanced_notification_publish_service.cpp | 1 - services/ans/src/advanced_notification_service.cpp | 1 - .../ans/src/advanced_notification_service_ability.cpp | 10 ++++++++++ 4 files changed, 12 insertions(+), 2 deletions(-) diff --git a/services/ans/include/advanced_notification_service.h b/services/ans/include/advanced_notification_service.h index be8bd51c9..cccc40986 100644 --- a/services/ans/include/advanced_notification_service.h +++ b/services/ans/include/advanced_notification_service.h @@ -1140,6 +1140,8 @@ public: */ bool AllowUseReminder(const std::string& bundleName); + void ResetDistributedEnabled(); + protected: /** * @brief Query whether there is a agent relationship between the two apps. diff --git a/services/ans/src/advanced_notification_publish_service.cpp b/services/ans/src/advanced_notification_publish_service.cpp index ffe14f2c8..958f202f8 100644 --- a/services/ans/src/advanced_notification_publish_service.cpp +++ b/services/ans/src/advanced_notification_publish_service.cpp @@ -193,7 +193,6 @@ ErrCode AdvancedNotificationService::PublishNotificationForIndirectProxy(const s int32_t uid = request->GetCreatorUid(); std::shared_ptr record = std::make_shared(); record->request = request; - record->isThirdparty = false; record->bundleOption = new (std::nothrow) NotificationBundleOption(bundle, uid); record->bundleOption->SetInstanceKey(request->GetCreatorInstanceKey()); sptr bundleOption = new (std::nothrow) NotificationBundleOption(bundle, uid); diff --git a/services/ans/src/advanced_notification_service.cpp b/services/ans/src/advanced_notification_service.cpp index 8991d3abc..90848a55f 100644 --- a/services/ans/src/advanced_notification_service.cpp +++ b/services/ans/src/advanced_notification_service.cpp @@ -300,7 +300,6 @@ AdvancedNotificationService::AdvancedNotificationService() NotificationSubscriberManager::GetInstance()->RegisterOnSubscriberAddCallback(callback); RecoverLiveViewFromDb(); - ResetDistributedEnabled(); ISystemEvent iSystemEvent = { std::bind(&AdvancedNotificationService::OnBundleRemoved, this, std::placeholders::_1), diff --git a/services/ans/src/advanced_notification_service_ability.cpp b/services/ans/src/advanced_notification_service_ability.cpp index 8c542f798..94e401052 100644 --- a/services/ans/src/advanced_notification_service_ability.cpp +++ b/services/ans/src/advanced_notification_service_ability.cpp @@ -50,6 +50,7 @@ void AdvancedNotificationServiceAbility::OnStart() EXTENTION_WRAPPER->InitExtentionWrapper(); AddSystemAbilityListener(DISTRIBUTED_KV_DATA_SERVICE_ABILITY_ID); AddSystemAbilityListener(COMMON_EVENT_SERVICE_ID); + AddSystemAbilityListener(BUNDLE_MGR_SERVICE_SYS_ABILITY_ID); #else ANS_LOGD("Not enabled ans_ext"); #endif @@ -90,6 +91,15 @@ void AdvancedNotificationServiceAbility::OnAddSystemAbility(int32_t systemAbilit return; } EventFwk::CommonEventManager::SubscribeCommonEvent(subscriber_); + } else if (systemAbilityId == BUNDLE_MGR_SERVICE_SYS_ABILITY_ID) { + if (isDatashaReready_) { + return; + } + auto notificationService = AdvancedNotificationService::GetInstance(); + if (notificationService == nullptr) { + return; + } + notificationService->ResetDistributedEnabled(); } } -- Gitee From bbe92dab86a8cb49173403f1b0bfa620d9c7a894 Mon Sep 17 00:00:00 2001 From: markYao Date: Fri, 1 Nov 2024 11:37:35 +0800 Subject: [PATCH 111/167] =?UTF-8?q?cherry=20pick=2066e0cad=20from=20https:?= =?UTF-8?q?//gitee.com/mark-yao/notification=5Fdistributed=5Fnotification?= =?UTF-8?q?=5Fservice/pulls/2360=20=E4=BA=8B=E4=BB=B6=E9=97=B4=E9=9A=94dur?= =?UTF-8?q?ation=E8=AE=A1=E7=AE=97=E7=B2=BE=E5=BA=A6=E6=98=BE=E5=BC=8F?= =?UTF-8?q?=E6=8C=87=E5=AE=9A=E4=B8=BA=E7=A7=92?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: markYao --- services/ans/src/advanced_notification_publish_service.cpp | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/services/ans/src/advanced_notification_publish_service.cpp b/services/ans/src/advanced_notification_publish_service.cpp index 7c1eed764..1d2666382 100644 --- a/services/ans/src/advanced_notification_publish_service.cpp +++ b/services/ans/src/advanced_notification_publish_service.cpp @@ -55,7 +55,7 @@ namespace OHOS { namespace Notification { constexpr char FOUNDATION_BUNDLE_NAME[] = "ohos.global.systemres"; -constexpr int32_t HOURS_IN_ONE_DAY = 24; +constexpr uint32_t SECONDS_IN_ONE_DAY = 24 * 60 * 60; const static std::string NOTIFICATION_EVENT_PUSH_AGENT = "notification.event.PUSH_AGENT"; constexpr int32_t RSS_PID = 3051; constexpr int32_t ANS_UID = 5523; @@ -2501,7 +2501,7 @@ void AdvancedNotificationService::RemoveExpiredUniqueKey() std::chrono::steady_clock::time_point now = std::chrono::steady_clock::now(); auto iter = uniqueKeyList_.begin(); while (iter != uniqueKeyList_.end()) { - if (abs(now - (*iter).first) > std::chrono::hours(HOURS_IN_ONE_DAY)) { + if (std::chrono::duration_cast(now - (*iter).first).count() > SECONDS_IN_ONE_DAY) { iter = uniqueKeyList_.erase(iter); } else { break; -- Gitee From d24063d5cee927498cc55a6b3307142467e4e0a5 Mon Sep 17 00:00:00 2001 From: gaojiaqi Date: Tue, 5 Nov 2024 19:06:04 +0800 Subject: [PATCH 112/167] update Signed-off-by: gaojiaqi --- services/ans/src/reminder_data_manager.cpp | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/services/ans/src/reminder_data_manager.cpp b/services/ans/src/reminder_data_manager.cpp index 05c8e9e2d..2903116ca 100644 --- a/services/ans/src/reminder_data_manager.cpp +++ b/services/ans/src/reminder_data_manager.cpp @@ -409,6 +409,7 @@ void ReminderDataManager::OnProcessDiedLocked(const sptr &sharedTimerInfo, const sptr &reminderRequest, TimerType reminderType) const { + ANSR_LOGE("gaojiaqi test"); uint8_t timerTypeWakeup = static_cast(sharedTimerInfo->TIMER_TYPE_WAKEUP); uint8_t timerTypeExact = static_cast(sharedTimerInfo->TIMER_TYPE_EXACT); sharedTimerInfo->SetRepeat(false); @@ -424,6 +425,7 @@ void ReminderDataManager::InitTimerInfo(std::shared_ptr &shar (reminderRequest->GetReminderType() == ReminderRequest::ReminderType::CALENDAR || reminderRequest->GetReminderType() == ReminderRequest::ReminderType::TIMER)) { #ifdef DEVICE_STANDBY_ENABLE + ANSR_LOGE("gaojiaqi STANDBY"); // Get allow list. std::string name = reminderRequest->GetBundleName(); std::vector allowInfoList; @@ -443,9 +445,11 @@ void ReminderDataManager::InitTimerInfo(std::shared_ptr &shar timerType = static_cast(timerTypeAns | timerTypeExact); } #else + ANSR_LOGE("gaojiaqi NO STANDBY"); timerType = static_cast(timerTypeWakeup | timerTypeExact); #endif } else { + ANSR_LOGE("gaojiaqi other"); timerType = static_cast(timerTypeWakeup | timerTypeExact); } sharedTimerInfo->SetType(timerType); -- Gitee From abc864d7c3ca7d5d5301b27f27aaae589bbc806a Mon Sep 17 00:00:00 2001 From: gaojiaqi Date: Tue, 5 Nov 2024 20:31:36 +0800 Subject: [PATCH 113/167] update Signed-off-by: gaojiaqi --- services/ans/src/reminder_data_manager.cpp | 36 +--------------------- 1 file changed, 1 insertion(+), 35 deletions(-) diff --git a/services/ans/src/reminder_data_manager.cpp b/services/ans/src/reminder_data_manager.cpp index 2903116ca..87c0556f8 100644 --- a/services/ans/src/reminder_data_manager.cpp +++ b/services/ans/src/reminder_data_manager.cpp @@ -409,7 +409,6 @@ void ReminderDataManager::OnProcessDiedLocked(const sptr &sharedTimerInfo, const sptr &reminderRequest, TimerType reminderType) const { - ANSR_LOGE("gaojiaqi test"); uint8_t timerTypeWakeup = static_cast(sharedTimerInfo->TIMER_TYPE_WAKEUP); uint8_t timerTypeExact = static_cast(sharedTimerInfo->TIMER_TYPE_EXACT); sharedTimerInfo->SetRepeat(false); @@ -418,40 +417,7 @@ void ReminderDataManager::InitTimerInfo(std::shared_ptr &shar sharedTimerInfo->SetBundleName(reminderRequest->GetBundleName()); sharedTimerInfo->SetUid(reminderRequest->GetUid()); - // The systemtimer type will be set TIMER_TYPE_INEXACT_REMINDER&&EXACT if reminder type is CALENDAR or TIMER, - // and set WAKEUP&&EXACT if ALARM. - int32_t timerType; - if (reminderType == TimerType::TRIGGER_TIMER && - (reminderRequest->GetReminderType() == ReminderRequest::ReminderType::CALENDAR || - reminderRequest->GetReminderType() == ReminderRequest::ReminderType::TIMER)) { -#ifdef DEVICE_STANDBY_ENABLE - ANSR_LOGE("gaojiaqi STANDBY"); - // Get allow list. - std::string name = reminderRequest->GetBundleName(); - std::vector allowInfoList; - DevStandbyMgr::StandbyServiceClient::GetInstance().GetAllowList(DevStandbyMgr::AllowType::TIMER, - allowInfoList, REASON_APP_API); - auto it = std::find_if(allowInfoList.begin(), - allowInfoList.end(), - [&name](const DevStandbyMgr::AllowInfo &allowInfo) { - return allowInfo.GetName() == name; - }); - if (reminderRequest->IsSystemApp() || it != allowInfoList.end()) { - ANS_LOGI("%{public}s is systemapp or in allowlist, set ALARM type.", name.c_str()); - timerType = static_cast(timerTypeWakeup | timerTypeExact); - } else { - ANS_LOGI("%{public}s is CALENDAR or TIMER type.", name.c_str()); - uint8_t timerTypeAns = static_cast(sharedTimerInfo->TIMER_TYPE_INEXACT_REMINDER); - timerType = static_cast(timerTypeAns | timerTypeExact); - } -#else - ANSR_LOGE("gaojiaqi NO STANDBY"); - timerType = static_cast(timerTypeWakeup | timerTypeExact); -#endif - } else { - ANSR_LOGE("gaojiaqi other"); - timerType = static_cast(timerTypeWakeup | timerTypeExact); - } + int32_t timerType = static_cast(timerTypeWakeup | timerTypeExact); sharedTimerInfo->SetType(timerType); } -- Gitee From d8090041f7b0b82a3a95d273e578f40117811ac2 Mon Sep 17 00:00:00 2001 From: wufarong Date: Wed, 30 Oct 2024 11:17:39 +0800 Subject: [PATCH 114/167] =?UTF-8?q?=E9=80=9A=E7=9F=A5=E8=AE=BE=E7=BD=AE?= =?UTF-8?q?=E5=A4=B1=E8=B4=A5=E6=89=93=E7=82=B9?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: wufarong Change-Id: I366e9f864eb7893041621094bd64f0c4106d6af9 --- .../napi/src/manager/napi_display_badge.cpp | 2 +- .../ans/include/notification_analytics_util.h | 1 + .../advanced_notification_publish_service.cpp | 33 +++++++++++++++---- .../ans/src/advanced_notification_service.cpp | 5 --- .../advanced_notification_slot_service.cpp | 2 -- ...vanced_notification_subscriber_service.cpp | 3 -- .../common/notification_analytics_util.cpp | 5 +++ services/ans/src/notification_preferences.cpp | 32 +++++++++++------- 8 files changed, 54 insertions(+), 29 deletions(-) diff --git a/frameworks/js/napi/src/manager/napi_display_badge.cpp b/frameworks/js/napi/src/manager/napi_display_badge.cpp index 56eb2c4a5..234664e0e 100644 --- a/frameworks/js/napi/src/manager/napi_display_badge.cpp +++ b/frameworks/js/napi/src/manager/napi_display_badge.cpp @@ -321,7 +321,7 @@ napi_value NapiSetBadgeNumberByBundle(napi_env env, napi_callback_info info) ANS_LOGD("Napi set badge number by bundle work execute."); AsyncCallbackSetBadgeNumber *asyncCallbackInfo = static_cast(data); if (asyncCallbackInfo) { - ANS_LOGD("Option.bundle = %{public}s, option.uid = %{public}d, badge number = %{public}d.", + ANS_LOGI("Option.bundle = %{public}s, option.uid = %{public}d, badge number = %{public}d.", asyncCallbackInfo->params.option.GetBundleName().c_str(), asyncCallbackInfo->params.option.GetUid(), asyncCallbackInfo->params.badgeNumber); diff --git a/services/ans/include/notification_analytics_util.h b/services/ans/include/notification_analytics_util.h index 801392fdd..a38757eaf 100644 --- a/services/ans/include/notification_analytics_util.h +++ b/services/ans/include/notification_analytics_util.h @@ -55,6 +55,7 @@ public: HaMetaMessage& BranchId(uint32_t branchId); HaMetaMessage& ErrorCode(uint32_t errorCode); HaMetaMessage& Message(const std::string& message, bool print = false); + HaMetaMessage& Append(const std::string& message); HaMetaMessage& BundleName(const std::string& bundleName_); HaMetaMessage& AgentBundleName(const std::string& agentBundleName); HaMetaMessage& TypeCode(int32_t typeCode); diff --git a/services/ans/src/advanced_notification_publish_service.cpp b/services/ans/src/advanced_notification_publish_service.cpp index 99e5ef08c..e7edbefe0 100644 --- a/services/ans/src/advanced_notification_publish_service.cpp +++ b/services/ans/src/advanced_notification_publish_service.cpp @@ -865,20 +865,33 @@ ErrCode AdvancedNotificationService::SetNotificationsEnabledForSpecialBundle( { HITRACE_METER_NAME(HITRACE_TAG_NOTIFICATION, __PRETTY_FUNCTION__); ANS_LOGD("%{public}s", __FUNCTION__); - + if (bundleOption == nullptr || bundleOption->GetBundleName().empty()) { + return ERR_ANS_INVALID_PARAM; + } + HaMetaMessage message = HaMetaMessage(EventSceneId::SCENE_7, EventBranchId::BRANCH_5); + message.Message("Des_" + bundleOption->GetBundleName() + "_" +std::to_string(bundleOption->GetUid()) + + " enable: " + std::to_string(enabled)); bool isSubsystem = AccessTokenHelper::VerifyNativeToken(IPCSkeleton::GetCallingTokenID()); if (!isSubsystem && !AccessTokenHelper::IsSystemApp()) { - ANS_LOGD("IsSystemApp is bogus."); + message.ErrorCode(ERR_ANS_NON_SYSTEM_APP).Append(" Not system app."); + NotificationAnalyticsUtil::ReportModifyEvent(message); + ANS_LOGE("Not system app."); return ERR_ANS_NON_SYSTEM_APP; } int32_t callingUid = IPCSkeleton::GetCallingUid(); if (callingUid != ANS_UID && !AccessTokenHelper::CheckPermission(OHOS_PERMISSION_NOTIFICATION_CONTROLLER)) { + message.ErrorCode(ERR_ANS_PERMISSION_DENIED).Append(" No acl permission."); + NotificationAnalyticsUtil::ReportModifyEvent(message); + ANS_LOGE(" No acl permission."); return ERR_ANS_PERMISSION_DENIED; } sptr bundle = GenerateValidBundleOption(bundleOption); if (bundle == nullptr) { + message.ErrorCode(ERR_ANS_INVALID_BUNDLE).Append(" Bundle is nullptr."); + NotificationAnalyticsUtil::ReportModifyEvent(message); + ANS_LOGE(" Bundle is nullptr."); return ERR_ANS_INVALID_BUNDLE; } @@ -2342,7 +2355,12 @@ ErrCode AdvancedNotificationService::SetBadgeNumber(int32_t badgeNumber, int32_t ErrCode AdvancedNotificationService::SetBadgeNumberByBundle( const sptr &bundleOption, int32_t badgeNumber) { - HaMetaMessage message = HaMetaMessage(EventSceneId::SCENE_7, EventBranchId::BRANCH_1); + if (bundleOption == nullptr || bundleOption->GetBundleName().empty()) { + return ERR_ANS_INVALID_PARAM; + } + HaMetaMessage message = HaMetaMessage(EventSceneId::SCENE_7, EventBranchId::BRANCH_6); + message.Message("Des_" + bundleOption->GetBundleName() + "_" +std::to_string(bundleOption->GetUid()) + + " badgeNumber: " + std::to_string(badgeNumber)); if (notificationSvrQueue_ == nullptr) { message.Message("Serial queue is invalid.", true); NotificationAnalyticsUtil::ReportModifyEvent(message); @@ -2351,16 +2369,18 @@ ErrCode AdvancedNotificationService::SetBadgeNumberByBundle( bool isSubsystem = AccessTokenHelper::VerifyNativeToken(IPCSkeleton::GetCallingTokenID()); if (!isSubsystem && !AccessTokenHelper::IsSystemApp()) { - message.Message("Client is not a system app or subsystem.", true); + message.ErrorCode(ERR_ANS_NON_SYSTEM_APP).Append(" Not system app."); NotificationAnalyticsUtil::ReportModifyEvent(message); + ANS_LOGE("Not system app."); return ERR_ANS_NON_SYSTEM_APP; } sptr bundle = bundleOption; ErrCode result = CheckBundleOptionValid(bundle); if (result != ERR_OK) { - message.Message("Input bundle option is not correct: " + std::to_string(result), true); + message.ErrorCode(result).Append(" Bundle is invalid."); NotificationAnalyticsUtil::ReportModifyEvent(message); + ANS_LOGE("Bundle is invalid."); return result; } @@ -2373,8 +2393,9 @@ ErrCode AdvancedNotificationService::SetBadgeNumberByBundle( bool isAgent = false; isAgent = IsAgentRelationship(bundleName, bundle->GetBundleName()); if (!isAgent) { - message.Message("the caller has no agent relationship with the specified bundle.", true); + message.ErrorCode(ERR_ANS_NO_AGENT_SETTING).Append(" No agent setting."); NotificationAnalyticsUtil::ReportModifyEvent(message); + ANS_LOGE("No agent setting."); return ERR_ANS_NO_AGENT_SETTING; } } diff --git a/services/ans/src/advanced_notification_service.cpp b/services/ans/src/advanced_notification_service.cpp index 0a99c72d2..c1baf1553 100644 --- a/services/ans/src/advanced_notification_service.cpp +++ b/services/ans/src/advanced_notification_service.cpp @@ -414,7 +414,6 @@ ErrCode AdvancedNotificationService::PrepareNotificationInfo( const sptr &request, sptr &bundleOption) { HITRACE_METER_NAME(HITRACE_TAG_NOTIFICATION, __PRETTY_FUNCTION__); - HaMetaMessage message = HaMetaMessage(EventSceneId::SCENE_4, EventBranchId::BRANCH_3); if (request == nullptr) { ANS_LOGE("request is invalid."); return ERR_ANS_INVALID_PARAM; @@ -426,8 +425,6 @@ ErrCode AdvancedNotificationService::PrepareNotificationInfo( } ErrCode result = PrepareNotificationRequest(request); if (result != ERR_OK) { - message.ErrorCode(result); - NotificationAnalyticsUtil::ReportPublishFailedEvent(request, message); return result; } std::string sourceBundleName = @@ -444,8 +441,6 @@ ErrCode AdvancedNotificationService::PrepareNotificationInfo( } if (bundleOption == nullptr) { - message.ErrorCode(ERR_ANS_INVALID_BUNDLE); - NotificationAnalyticsUtil::ReportPublishFailedEvent(request, message); return ERR_ANS_INVALID_BUNDLE; } ANS_LOGI( diff --git a/services/ans/src/advanced_notification_slot_service.cpp b/services/ans/src/advanced_notification_slot_service.cpp index 91011a4a9..13cb72387 100644 --- a/services/ans/src/advanced_notification_slot_service.cpp +++ b/services/ans/src/advanced_notification_slot_service.cpp @@ -484,8 +484,6 @@ ErrCode AdvancedNotificationService::AssignValidNotificationSlot(const std::shar DelayedSingleton::GetInstance()->IsLiveViewTrtust(bundleOption->GetBundleName())))) { record->slot = slot; } else { - message.ErrorCode(ERR_ANS_PREFERENCES_NOTIFICATION_SLOT_ENABLED); - NotificationAnalyticsUtil::ReportPublishFailedEvent(record->request, message); result = ERR_ANS_PREFERENCES_NOTIFICATION_SLOT_ENABLED; ANS_LOGE("Type[%{public}d] slot enable closed", slotType); } diff --git a/services/ans/src/advanced_notification_subscriber_service.cpp b/services/ans/src/advanced_notification_subscriber_service.cpp index a34acb53b..c69305eb6 100644 --- a/services/ans/src/advanced_notification_subscriber_service.cpp +++ b/services/ans/src/advanced_notification_subscriber_service.cpp @@ -90,7 +90,6 @@ ErrCode AdvancedNotificationService::SubscribeSelf(const sptr sptrInfo = new (std::nothrow) NotificationSubscribeInfo(); ErrCode errCode = ERR_OK; - HaMetaMessage message = HaMetaMessage(EventSceneId::SCENE_6, EventBranchId::BRANCH_2); do { if (subscriber == nullptr) { errCode = ERR_ANS_INVALID_PARAM; @@ -121,8 +120,6 @@ ErrCode AdvancedNotificationService::SubscribeSelf(const sptrsubmit_h(std::bind([&]() { diff --git a/services/ans/src/common/notification_analytics_util.cpp b/services/ans/src/common/notification_analytics_util.cpp index 447e5950f..81af6d405 100644 --- a/services/ans/src/common/notification_analytics_util.cpp +++ b/services/ans/src/common/notification_analytics_util.cpp @@ -83,6 +83,11 @@ HaMetaMessage& HaMetaMessage::Message(const std::string& message, bool print) return *this; } +HaMetaMessage& HaMetaMessage::Append(const std::string& message) +{ + message_+=message; + return *this; +} HaMetaMessage& HaMetaMessage::Checkfailed(bool checkfailed) { checkfailed_ = checkfailed; diff --git a/services/ans/src/notification_preferences.cpp b/services/ans/src/notification_preferences.cpp index de48054a1..80875070f 100644 --- a/services/ans/src/notification_preferences.cpp +++ b/services/ans/src/notification_preferences.cpp @@ -122,8 +122,9 @@ ErrCode NotificationPreferences::RemoveNotificationSlot( if (bundleOption == nullptr || bundleOption->GetBundleName().empty()) { return ERR_ANS_INVALID_PARAM; } - HaMetaMessage message = HaMetaMessage(EventSceneId::SCENE_5, EventBranchId::BRANCH_1) - .BundleName(bundleOption->GetBundleName()); + HaMetaMessage message = HaMetaMessage(EventSceneId::SCENE_5, EventBranchId::BRANCH_1); + message.Message("Des_" + bundleOption->GetBundleName() + "_" +std::to_string(bundleOption->GetUid()) + + " slotType: " + std::to_string(static_cast(slotType))); message.SlotType(static_cast(slotType)); std::lock_guard lock(preferenceMutex_); NotificationPreferencesInfo preferencesInfo = preferencesInfo_; @@ -131,16 +132,20 @@ ErrCode NotificationPreferences::RemoveNotificationSlot( result = CheckSlotForRemoveSlot(bundleOption, slotType, preferencesInfo); if (result == ERR_OK && (!preferncesDB_->RemoveSlotFromDisturbeDB(GenerateBundleKey(bundleOption), slotType, bundleOption->GetUid()))) { - message.Message("Remove slot failed: " + std::to_string(result)); + message.ErrorCode(result).Append(" Remove slot failed."); NotificationAnalyticsUtil::ReportModifyEvent(message); + ANS_LOGE("Des_%{public}s_%{public}d, remove slot failed.", + bundleOption->GetBundleName().c_str(), bundleOption->GetUid()); return ERR_ANS_PREFERENCES_NOTIFICATION_DB_OPERATION_FAILED; } if (result == ERR_OK) { preferencesInfo_ = preferencesInfo; } - message.Message("Remove slot successful"); + message.ErrorCode(result).Append(" Remove slot successful."); NotificationAnalyticsUtil::ReportModifyEvent(message); + ANS_LOGI("Des_%{public}s_%{public}d, Remove slot successful.", + bundleOption->GetBundleName().c_str(), bundleOption->GetUid()); return result; } @@ -150,8 +155,8 @@ ErrCode NotificationPreferences::RemoveNotificationAllSlots(const sptrGetBundleName().empty()) { return ERR_ANS_INVALID_PARAM; } - HaMetaMessage message = HaMetaMessage(EventSceneId::SCENE_5, EventBranchId::BRANCH_1) - .BundleName(bundleOption->GetBundleName()); + HaMetaMessage message = HaMetaMessage(EventSceneId::SCENE_5, EventBranchId::BRANCH_3); + message.Message("Des_" + bundleOption->GetBundleName() + "_" +std::to_string(bundleOption->GetUid())); std::lock_guard lock(preferenceMutex_); NotificationPreferencesInfo preferencesInfo = preferencesInfo_; ErrCode result = ERR_OK; @@ -161,16 +166,23 @@ ErrCode NotificationPreferences::RemoveNotificationAllSlots(const sptrRemoveAllSlotsFromDisturbeDB(GenerateBundleKey(bundleOption), bundleOption->GetUid())) { result = ERR_ANS_PREFERENCES_NOTIFICATION_DB_OPERATION_FAILED; + message.ErrorCode(result).Append(" Db operation failed."); + ANS_LOGE("Des_%{public}s_%{public}d, Db operation failed.", + bundleOption->GetBundleName().c_str(), bundleOption->GetUid()); } } else { result = ERR_ANS_PREFERENCES_NOTIFICATION_BUNDLE_NOT_EXIST; + message.ErrorCode(result).Append(" Notification bundle not exist."); + ANS_LOGE("Des_%{public}s_%{public}d, Notification bundle not exist.", + bundleOption->GetBundleName().c_str(), bundleOption->GetUid()); } if (result == ERR_OK) { - ANS_LOGD("result is ERR_OK"); preferencesInfo_ = preferencesInfo; + message.ErrorCode(result).Append(" Remove all slot successful."); + ANS_LOGI("Des_%{public}s_%{public}d, Remove all slot successful.", + bundleOption->GetBundleName().c_str(), bundleOption->GetUid()); } - message.Message("Remove all slot: " + std::to_string(result)); NotificationAnalyticsUtil::ReportModifyEvent(message); return result; } @@ -824,7 +836,6 @@ template ErrCode NotificationPreferences::SaveBundleProperty(NotificationPreferencesInfo::BundleInfo &bundleInfo, const sptr &bundleOption, const BundleType &type, const T &value) { - HaMetaMessage message = HaMetaMessage().BundleName(bundleInfo.GetBundleName()); bool storeDBResult = true; switch (type) { case BundleType::BUNDLE_IMPORTANCE_TYPE: @@ -856,9 +867,6 @@ ErrCode NotificationPreferences::SaveBundleProperty(NotificationPreferencesInfo: default: break; } - message.Message("Save:" + std::to_string(static_cast(type)) + - " : " + std::to_string(value) + " : " + std::to_string(storeDBResult)); - NotificationAnalyticsUtil::ReportModifyEvent(message); return storeDBResult ? ERR_OK : ERR_ANS_PREFERENCES_NOTIFICATION_DB_OPERATION_FAILED; } -- Gitee From 25e60f5d57efaf8400403a204aace35a8700c542 Mon Sep 17 00:00:00 2001 From: luojingsong Date: Wed, 6 Nov 2024 11:41:58 +0800 Subject: [PATCH 115/167] =?UTF-8?q?this=E6=8E=92=E6=9F=A5?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: luojingsong Change-Id: I10e5f522014e0690de1dfe08495656e47f3cf4d0 --- .../src/advanced_notification_live_view_service.cpp | 8 ++++++-- services/ans/src/advanced_notification_utils.cpp | 13 ++++++++----- 2 files changed, 14 insertions(+), 7 deletions(-) diff --git a/services/ans/src/advanced_notification_live_view_service.cpp b/services/ans/src/advanced_notification_live_view_service.cpp index 3f9dfe333..6d60a0fde 100644 --- a/services/ans/src/advanced_notification_live_view_service.cpp +++ b/services/ans/src/advanced_notification_live_view_service.cpp @@ -553,8 +553,12 @@ uint64_t AdvancedNotificationService::StartDelayPublishTimer( { ANS_LOGD("Enter"); - auto timeoutFunc = [this, ownerUid, notificationId] { - StartPublishDelayedNotificationTimeOut(ownerUid, notificationId); + wptr wThis = this; + auto timeoutFunc = [wThis, ownerUid, notificationId] { + sptr sThis = wThis.promote(); + if (sThis != nullptr) { + sThis->StartPublishDelayedNotificationTimeOut(ownerUid, notificationId); + } }; std::shared_ptr notificationTimerInfo = std::make_shared(); notificationTimerInfo->SetCallbackInfo(timeoutFunc); diff --git a/services/ans/src/advanced_notification_utils.cpp b/services/ans/src/advanced_notification_utils.cpp index c3f5f318e..a1e285e97 100644 --- a/services/ans/src/advanced_notification_utils.cpp +++ b/services/ans/src/advanced_notification_utils.cpp @@ -1694,11 +1694,14 @@ uint64_t AdvancedNotificationService::StartAutoDelete(const std::shared_ptrnotification->GetKey(), reason); - if (record->finish_status != NotificationConstant::DEFAULT_FINISH_STATUS) { - SendLiveViewUploadHiSysEvent(record, record->finish_status); + wptr wThis = this; + auto triggerFunc = [wThis, record, reason, deleteTimePoint] { + sptr sThis = wThis.promote(); + if (sThis != nullptr) { + sThis->TriggerAutoDelete(record->notification->GetKey(), reason); + if (record->finish_status != NotificationConstant::DEFAULT_FINISH_STATUS) { + sThis->SendLiveViewUploadHiSysEvent(record, record->finish_status); + } } }; std::shared_ptr notificationTimerInfo = std::make_shared(); -- Gitee From 98b9c6768bdd42b4764d8d48804ef85b27fe61ab Mon Sep 17 00:00:00 2001 From: Ricky Date: Tue, 29 Oct 2024 11:00:40 +0800 Subject: [PATCH 116/167] fix default banner config does not take effect when publish without requestEnableNotification Signed-off-by: Ricky Change-Id: I8f6b86c949f6d84e9a572683ef0fe560e64a1455 --- services/ans/include/notification_config_parse.h | 4 ++++ services/ans/include/notification_preferences.h | 1 + .../include/notification_preferences_database.h | 1 + .../advanced_notification_publish_service.cpp | 7 +------ .../src/advanced_notification_slot_service.cpp | 8 ++++---- services/ans/src/advanced_notification_utils.cpp | 16 ++-------------- .../ans/src/common/notification_config_parse.cpp | 11 +++++++++++ services/ans/src/notification_preferences.cpp | 11 ++++++++++- .../src/notification_preferences_database.cpp | 14 ++++++++++++++ .../advanced_notification_slot_service_test.cpp | 8 +++++--- 10 files changed, 53 insertions(+), 28 deletions(-) diff --git a/services/ans/include/notification_config_parse.h b/services/ans/include/notification_config_parse.h index 1948a9134..04c06d6e9 100644 --- a/services/ans/include/notification_config_parse.h +++ b/services/ans/include/notification_config_parse.h @@ -25,6 +25,7 @@ #include "config_policy_utils.h" #endif #include "nlohmann/json.hpp" +#include "notification_bundle_option.h" #include "notification_constant.h" #include "notification_flags.h" @@ -39,6 +40,9 @@ public: bool GetCurrentSlotReminder( std::map> ¤tSlotReminder) const; uint32_t GetConfigSlotReminderModeByType(NotificationConstant::SlotType slotType) const; + uint32_t GetConfigSlotReminderModeByType(NotificationConstant::SlotType slotType, + const sptr &bundleOption) const; + private: std::map defaultCurrentSlotReminder_; std::vector notificationConfigJsons_; diff --git a/services/ans/include/notification_preferences.h b/services/ans/include/notification_preferences.h index a5ead6fd1..2883eac78 100644 --- a/services/ans/include/notification_preferences.h +++ b/services/ans/include/notification_preferences.h @@ -384,6 +384,7 @@ public: std::vector> &profiles); void GetAllCLoneBundlesInfo(int32_t userId, std::vector &cloneBundles); void UpdateCloneBundleInfo(int32_t userId, const NotificationCloneBundleInfo& cloneBundleInfo); + bool IsNotificationSlotFlagsExists(const sptr &bundleOption); private: ErrCode CheckSlotForCreateSlot(const sptr &bundleOption, diff --git a/services/ans/include/notification_preferences_database.h b/services/ans/include/notification_preferences_database.h index 74d7e4d40..3733049d9 100644 --- a/services/ans/include/notification_preferences_database.h +++ b/services/ans/include/notification_preferences_database.h @@ -235,6 +235,7 @@ public: bool UpdateBundlePropertyToDisturbeDB(int32_t userId, const NotificationPreferencesInfo::BundleInfo &bundleInfo); bool UpdateBundleSlotToDisturbeDB(int32_t userId, const std::string &bundleName, const int32_t &bundleUid, const std::vector> &slots); + bool IsNotificationSlotFlagsExists(const sptr &bundleOption); private: bool CheckRdbStore(); diff --git a/services/ans/src/advanced_notification_publish_service.cpp b/services/ans/src/advanced_notification_publish_service.cpp index 7c1eed764..92f318015 100644 --- a/services/ans/src/advanced_notification_publish_service.cpp +++ b/services/ans/src/advanced_notification_publish_service.cpp @@ -885,18 +885,13 @@ ErrCode AdvancedNotificationService::SetNotificationsEnabledForSpecialBundle( ErrCode result = ERR_OK; if (deviceId.empty()) { - bool notificationEnable = false; - ErrCode saveRef = NotificationPreferences::GetInstance()->GetNotificationsEnabledForBundle( - bundle, notificationEnable); // Local device result = NotificationPreferences::GetInstance()->SetNotificationsEnabledForBundle(bundle, enabled); if (result == ERR_OK) { if (!enabled) { result = RemoveAllNotificationsForDisable(bundle); } - if (saveRef != ERR_OK) { - SetSlotFlagsTrustlistsAsBundle(bundle); - } + SetSlotFlagsTrustlistsAsBundle(bundle); NotificationSubscriberManager::GetInstance()->NotifyEnabledNotificationChanged(bundleData); PublishSlotChangeCommonEvent(bundle); } diff --git a/services/ans/src/advanced_notification_slot_service.cpp b/services/ans/src/advanced_notification_slot_service.cpp index df8519fc8..ab89e9c52 100644 --- a/services/ans/src/advanced_notification_slot_service.cpp +++ b/services/ans/src/advanced_notification_slot_service.cpp @@ -515,8 +515,8 @@ ErrCode AdvancedNotificationService::UpdateSlotReminderModeBySlotFlags( } for (auto slot : slots) { - auto configSlotReminderMode = - DelayedSingleton::GetInstance()->GetConfigSlotReminderModeByType(slot->GetType()); + auto configSlotReminderMode = DelayedSingleton::GetInstance()-> + GetConfigSlotReminderModeByType(slot->GetType(), bundle); slot->SetReminderMode(slotFlags & configSlotReminderMode); std::string bundleName = (bundle == nullptr) ? "" : bundle->GetBundleName(); ANS_LOGD("Update reminderMode of %{public}d in %{public}s, value is %{public}d.", @@ -539,8 +539,8 @@ void AdvancedNotificationService::GenerateSlotReminderMode(const sptr::GetInstance()->GetConfigSlotReminderModeByType(slot->GetType()); + auto configSlotReminderMode = DelayedSingleton::GetInstance()-> + GetConfigSlotReminderModeByType(slot->GetType(), bundle); if (isSpecifiedSlot) { slot->SetReminderMode(configSlotReminderMode & slotFlags & slot->GetReminderMode()); } else { diff --git a/services/ans/src/advanced_notification_utils.cpp b/services/ans/src/advanced_notification_utils.cpp index 5858ff42e..5fcf62295 100644 --- a/services/ans/src/advanced_notification_utils.cpp +++ b/services/ans/src/advanced_notification_utils.cpp @@ -1776,7 +1776,8 @@ void AdvancedNotificationService::SendNotificationsOnCanceled(std::vector &bundleOption) { - if (DelayedSingleton::GetInstance()->IsSlotFlagsTrustlistAsBundle(bundleOption)) { + if (!NotificationPreferences::GetInstance()->IsNotificationSlotFlagsExists(bundleOption) && + DelayedSingleton::GetInstance()->IsSlotFlagsTrustlistAsBundle(bundleOption)) { uint32_t slotFlags = 0b111111; ErrCode saveRef = NotificationPreferences::GetInstance()->SetNotificationSlotFlagsForBundle( bundleOption, slotFlags); @@ -1793,19 +1794,6 @@ void AdvancedNotificationService::InitNotificationEnableList() std::vector bundleInfos = GetBundlesOfActiveUser(); bool notificationEnable = false; for (const auto &bundleInfo : bundleInfos) { - if (bundleInfo.applicationInfo.bundleName.compare("com.ohos.mms") == 0) { - uint32_t slotFlags = 63; - sptr mmsBundle = new (std::nothrow) NotificationBundleOption( - bundleInfo.applicationInfo.bundleName, bundleInfo.uid); - if (mmsBundle == nullptr) { - ANS_LOGE("New bundle option obj error! bundlename:%{public}s", - bundleInfo.applicationInfo.bundleName.c_str()); - continue; - } - NotificationPreferences::GetInstance()->GetNotificationSlotFlagsForBundle( - mmsBundle, slotFlags); - UpdateSlotReminderModeBySlotFlags(mmsBundle, slotFlags); - } // Currently only the input from the whitelist is written if (!bundleInfo.applicationInfo.allowEnableNotification) { continue; diff --git a/services/ans/src/common/notification_config_parse.cpp b/services/ans/src/common/notification_config_parse.cpp index 1bf1ce77c..af14a94fe 100644 --- a/services/ans/src/common/notification_config_parse.cpp +++ b/services/ans/src/common/notification_config_parse.cpp @@ -19,6 +19,7 @@ #include "ans_log_wrapper.h" #include "notification_slot.h" +#include "notification_trust_list.h" #include "file_utils.h" namespace OHOS { @@ -133,5 +134,15 @@ uint32_t NotificationConfigParse::GetConfigSlotReminderModeByType(NotificationCo return 0; } + +uint32_t NotificationConfigParse::GetConfigSlotReminderModeByType(NotificationConstant::SlotType slotType, + const sptr &bundleOption) const +{ + uint32_t reminderFlags = GetConfigSlotReminderModeByType(slotType); + if (DelayedSingleton::GetInstance()->IsSlotFlagsTrustlistAsBundle(bundleOption)) { + return reminderFlags & 0b111111; + } + return reminderFlags; +} } // namespace Notification } // namespace OHOS diff --git a/services/ans/src/notification_preferences.cpp b/services/ans/src/notification_preferences.cpp index a6c44ff1b..4b017a241 100644 --- a/services/ans/src/notification_preferences.cpp +++ b/services/ans/src/notification_preferences.cpp @@ -563,6 +563,15 @@ ErrCode NotificationPreferences::AddDoNotDisturbProfiles( return ERR_OK; } +bool NotificationPreferences::IsNotificationSlotFlagsExists( + const sptr &bundleOption) +{ + if (bundleOption == nullptr || bundleOption->GetBundleName().empty()) { + return false; + } + return preferncesDB_->IsNotificationSlotFlagsExists(bundleOption); +} + ErrCode NotificationPreferences::RemoveDoNotDisturbProfiles( int32_t userId, const std::vector> profiles) { @@ -673,7 +682,7 @@ void NotificationPreferences::UpdateCloneBundleInfo(int32_t userId, sptr slotInfo = new (std::nothrow) NotificationSlot(cloneSlot.slotType_); uint32_t slotFlags = bundleInfo.GetSlotFlags(); auto configSlotReminderMode = DelayedSingleton::GetInstance()-> - GetConfigSlotReminderModeByType(slotInfo->GetType()); + GetConfigSlotReminderModeByType(slotInfo->GetType(), bundleOption); slotInfo->SetReminderMode(configSlotReminderMode & slotFlags); slotInfo->SetEnable(cloneSlot.enable_); slotInfo->SetForceControl(cloneSlot.isForceControl_); diff --git a/services/ans/src/notification_preferences_database.cpp b/services/ans/src/notification_preferences_database.cpp index d331ea0d1..280ce79b3 100644 --- a/services/ans/src/notification_preferences_database.cpp +++ b/services/ans/src/notification_preferences_database.cpp @@ -313,6 +313,20 @@ bool NotificationPreferencesDatabase::PutBundlePropertyToDisturbeDB( return result; } +bool NotificationPreferencesDatabase::IsNotificationSlotFlagsExists(const sptr &bundleOption) +{ + if (bundleOption == nullptr || bundleOption->GetBundleName().empty()) { + return false; + } + std::string bundleKey = bundleOption->GetBundleName().append(std::to_string(bundleOption->GetUid())); + std::string key = GenerateBundleKey(bundleKey, KEY_BUNDLE_SLOTFLGS_TYPE); + std::string value; + int32_t userId = -1; + OsAccountManagerHelper::GetInstance().GetOsAccountLocalIdFromUid(bundleOption->GetUid(), userId); + int32_t result = rdbDataManager_->QueryData(key, value, userId); + return (result == NativeRdb::E_OK) || (!value.empty()); +} + bool NotificationPreferencesDatabase::PutShowBadge( const NotificationPreferencesInfo::BundleInfo &bundleInfo, const bool &enable) { diff --git a/services/ans/test/unittest/advanced_notification_slot_service_test.cpp b/services/ans/test/unittest/advanced_notification_slot_service_test.cpp index 1367ed68e..ea3f8a9ec 100644 --- a/services/ans/test/unittest/advanced_notification_slot_service_test.cpp +++ b/services/ans/test/unittest/advanced_notification_slot_service_test.cpp @@ -13,9 +13,11 @@ * limitations under the License. */ +#include "notification_bundle_option.h" #include #include #include +#include #include #include "gtest/gtest.h" @@ -343,7 +345,7 @@ HWTEST_F(AnsSlotServiceTest, SetRequestBySlotType_00001, Function | SmallTest | { sptr request = new NotificationRequest(); request->SetSlotType(NotificationConstant::SlotType::CUSTOMER_SERVICE); - sptr bundle = nullptr; + sptr bundle = new (std::nothrow) NotificationBundleOption(); advancedNotificationService_->SetRequestBySlotType(request, bundle); EXPECT_NE(request->GetFlags(), nullptr); } @@ -513,7 +515,7 @@ HWTEST_F(AnsSlotServiceTest, UpdateSlotReminderModeBySlotFlags_00002, Function | */ HWTEST_F(AnsSlotServiceTest, GenerateSlotReminderMode_00001, Function | SmallTest | Level1) { - sptr bundle = nullptr; + sptr bundle = new (std::nothrow) NotificationBundleOption(); sptr slot = new (std::nothrow) NotificationSlot(NotificationConstant::SlotType::SERVICE_REMINDER); advancedNotificationService_->GenerateSlotReminderMode(slot, bundle); ASSERT_EQ(slot->GetReminderMode(), (int)0b111011); @@ -527,7 +529,7 @@ HWTEST_F(AnsSlotServiceTest, GenerateSlotReminderMode_00001, Function | SmallTes */ HWTEST_F(AnsSlotServiceTest, GenerateSlotReminderMode_00002, Function | SmallTest | Level1) { - sptr bundle = nullptr; + sptr bundle = new (std::nothrow) NotificationBundleOption(); sptr slot = new (std::nothrow) NotificationSlot(NotificationConstant::SlotType::SERVICE_REMINDER); advancedNotificationService_->GenerateSlotReminderMode(slot, bundle, true); ASSERT_EQ(slot->GetReminderMode(), (int)0b111011); -- Gitee From be00309fd119a8a2bf2ff46f1294adeca5c39101 Mon Sep 17 00:00:00 2001 From: Ricky Date: Thu, 31 Oct 2024 14:49:54 +0800 Subject: [PATCH 117/167] fix notification slot crash Signed-off-by: Ricky Change-Id: I3badd8f5bf03ea81a6a12a2952217a0084d3f650 --- frameworks/ans/src/notification_slot.cpp | 20 +++---- frameworks/ans/test/unittest/BUILD.gn | 1 + .../test/unittest/notification_slot_test.cpp | 57 +++++++++++++++++++ 3 files changed, 68 insertions(+), 10 deletions(-) create mode 100644 frameworks/ans/test/unittest/notification_slot_test.cpp diff --git a/frameworks/ans/src/notification_slot.cpp b/frameworks/ans/src/notification_slot.cpp index 1ecac11be..ecc092e9d 100644 --- a/frameworks/ans/src/notification_slot.cpp +++ b/frameworks/ans/src/notification_slot.cpp @@ -19,7 +19,16 @@ namespace OHOS { namespace Notification { -std::map NotificationSlot::convertStrToSlotType_; +std::map NotificationSlot::convertStrToSlotType_ = { + {SOCIAL_COMMUNICATION, NotificationConstant::SlotType::SOCIAL_COMMUNICATION}, + {SERVICE_REMINDER, NotificationConstant::SlotType::SERVICE_REMINDER}, + {CONTENT_INFORMATION, NotificationConstant::SlotType::CONTENT_INFORMATION}, + {OTHER, NotificationConstant::SlotType::OTHER}, + {LIVE_VIEW, NotificationConstant::SlotType::LIVE_VIEW}, + {CUSTOM_SERVICE, NotificationConstant::SlotType::CUSTOMER_SERVICE}, + {EMERGENCY_INFORMATION, NotificationConstant::SlotType::EMERGENCY_INFORMATION} +}; + const int32_t MAX_TEXT_LENGTH = 1000; const uint32_t SOUND_OPNE = 1 << 0; const uint32_t LOCKSCREEN_OPNE = 1 << 1; @@ -488,15 +497,6 @@ std::string NotificationSlot::TruncateString(const std::string &in) bool NotificationSlot::GetSlotTypeByString( const std::string &strSlotType, NotificationConstant::SlotType &slotType) { - if (convertStrToSlotType_.size() <= 0) { - convertStrToSlotType_[SOCIAL_COMMUNICATION] = NotificationConstant::SlotType::SOCIAL_COMMUNICATION; - convertStrToSlotType_[SERVICE_REMINDER] = NotificationConstant::SlotType::SERVICE_REMINDER; - convertStrToSlotType_[CONTENT_INFORMATION] = NotificationConstant::SlotType::CONTENT_INFORMATION; - convertStrToSlotType_[OTHER] = NotificationConstant::SlotType::OTHER; - convertStrToSlotType_[LIVE_VIEW] = NotificationConstant::SlotType::LIVE_VIEW; - convertStrToSlotType_[CUSTOM_SERVICE] = NotificationConstant::SlotType::CUSTOMER_SERVICE; - convertStrToSlotType_[EMERGENCY_INFORMATION] = NotificationConstant::SlotType::EMERGENCY_INFORMATION; - } auto iterSlotType = convertStrToSlotType_.find(strSlotType); if (iterSlotType != convertStrToSlotType_.end()) { slotType = iterSlotType->second; diff --git a/frameworks/ans/test/unittest/BUILD.gn b/frameworks/ans/test/unittest/BUILD.gn index 89bc493aa..d6a5b2f1e 100644 --- a/frameworks/ans/test/unittest/BUILD.gn +++ b/frameworks/ans/test/unittest/BUILD.gn @@ -55,6 +55,7 @@ ohos_unittest("ans_reminder_unit_test") { "${frameworks_module_ans_path}/test/unittest/notification_picture_content_test.cpp", "${frameworks_module_ans_path}/test/unittest/notification_progress_test.cpp", "${frameworks_module_ans_path}/test/unittest/notification_request_test.cpp", + "${frameworks_module_ans_path}/test/unittest/notification_slot_test.cpp", "${frameworks_module_ans_path}/test/unittest/notification_sorting_map_test.cpp", "${frameworks_module_ans_path}/test/unittest/notification_sorting_test.cpp", "${frameworks_module_ans_path}/test/unittest/notification_subscribe_info_test.cpp", diff --git a/frameworks/ans/test/unittest/notification_slot_test.cpp b/frameworks/ans/test/unittest/notification_slot_test.cpp new file mode 100644 index 000000000..d7fb0565b --- /dev/null +++ b/frameworks/ans/test/unittest/notification_slot_test.cpp @@ -0,0 +1,57 @@ +/* + * Copyright (c) 2024-2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include + +#include "notification_slot.h" + +using namespace testing::ext; +namespace OHOS { +namespace Notification { +class NotificationSlotTest : public testing::Test { +public: + static void SetUpTestCase() {} + static void TearDownTestCase() {} + void SetUp() {} + void TearDown() {} +}; + +/** + * @tc.name: GetSlotTypeByString_00001 + * @tc.desc: Test GetSlotTypeByString method is ok. + * @tc.type: FUNC + * @tc.require: issue + */ +HWTEST_F(NotificationSlotTest, GetSlotTypeByString_00001, Function | SmallTest | Level1) +{ + NotificationConstant::SlotType type; + EXPECT_EQ(NotificationSlot::GetSlotTypeByString(NotificationSlot::CONTENT_INFORMATION, type), true); + EXPECT_EQ(type, NotificationConstant::SlotType::CONTENT_INFORMATION); +} + +/** + * @tc.name: GetSlotTypeByString_00002 + * @tc.desc: Test GetSlotTypeByString method is false. + * @tc.type: FUNC + * @tc.require: issue + */ +HWTEST_F(NotificationSlotTest, GetSlotTypeByString_00002, Function | SmallTest | Level1) +{ + NotificationConstant::SlotType type; + const std::string inputStr = "others"; + EXPECT_EQ(NotificationSlot::GetSlotTypeByString(inputStr, type), false); +} +} +} \ No newline at end of file -- Gitee From 66458758ce0c5b9bacb67871aa4ba31da5325bd7 Mon Sep 17 00:00:00 2001 From: luojingsong Date: Tue, 22 Oct 2024 11:45:41 +0800 Subject: [PATCH 118/167] =?UTF-8?q?=E5=91=8A=E8=AD=A6=E5=90=8C=E6=AD=A5?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: luojingsong Change-Id: Ifc092c3f35d04ff63730c9c0d7d2a7ab4fa75cbe --- .../ans/src/notification_do_not_disturb_profile.cpp | 3 ++- frameworks/js/napi/src/subscribe.cpp | 7 ------- services/ans/src/advanced_notification_service.cpp | 3 ++- services/ans/src/common/aes_gcm_helper.cpp | 9 ++++++--- services/ans/src/system_dialog_connect_stb.cpp | 8 ++++++++ 5 files changed, 18 insertions(+), 12 deletions(-) diff --git a/frameworks/ans/src/notification_do_not_disturb_profile.cpp b/frameworks/ans/src/notification_do_not_disturb_profile.cpp index 0a4be2f85..0dfc655af 100644 --- a/frameworks/ans/src/notification_do_not_disturb_profile.cpp +++ b/frameworks/ans/src/notification_do_not_disturb_profile.cpp @@ -159,7 +159,8 @@ void NotificationDoNotDisturbProfile::FromJson(const std::string &jsonObj) if (bundleOption == nullptr) { continue; } - trustList_.emplace_back(*bundleOption); + trustList_.push_back(*bundleOption); + delete bundleOption; } } } diff --git a/frameworks/js/napi/src/subscribe.cpp b/frameworks/js/napi/src/subscribe.cpp index 4908ff874..d2e392607 100644 --- a/frameworks/js/napi/src/subscribe.cpp +++ b/frameworks/js/napi/src/subscribe.cpp @@ -393,13 +393,6 @@ void SubscriberInstance::OnConsumed(const std::shared_ptrGetNotificationRequest().GetAgentBundle() != nullptr) { - ANS_LOGD("OnConsumed NotificGetAgentBundle = %{public}s", - request->GetNotificationRequest().GetAgentBundle()->Dump().c_str()); - } else { - ANS_LOGD("OnConsumed NotificGetAgentBundle = null"); - } auto notificationFlags = request->GetNotificationRequest().GetFlags(); ANS_LOGI("OnConsumed Notification key = %{public}s, sortingMap size = %{public}zu, notificationFlag = %{public}s", request->GetKey().c_str(), sortingMap->GetKey().size(), diff --git a/services/ans/src/advanced_notification_service.cpp b/services/ans/src/advanced_notification_service.cpp index d43bf7567..67a6f95e2 100644 --- a/services/ans/src/advanced_notification_service.cpp +++ b/services/ans/src/advanced_notification_service.cpp @@ -722,7 +722,8 @@ void AdvancedNotificationService::CheckDoNotDisturbProfile(const std::shared_ptr return; } std::string bundleName = record->bundleOption->GetBundleName(); - ANS_LOGD("The bundle name is %{public}s", bundleName.c_str()); + ANS_LOGI("The disturbMode is on, userId:%{public}d, bundle:%{public}s, profileId:%{public}s", + userId, bundleName.c_str(), profileId.c_str()); sptr profile = new (std::nothrow) NotificationDoNotDisturbProfile(); if (NotificationPreferences::GetInstance()->GetDoNotDisturbProfile(atoi(profileId.c_str()), userId, profile) != ERR_OK) { diff --git a/services/ans/src/common/aes_gcm_helper.cpp b/services/ans/src/common/aes_gcm_helper.cpp index 3869b9bcd..05ba3e539 100644 --- a/services/ans/src/common/aes_gcm_helper.cpp +++ b/services/ans/src/common/aes_gcm_helper.cpp @@ -85,10 +85,13 @@ bool AesGcmHelper::GenerateKey(std::string &key) std::lock_guard lck(g_generateKeyMutex); const char *keyPathPtr = G_KEY_PATH.c_str(); char *resolvedPath = (char *)malloc(PATH_MAX); - if (realpath(keyPathPtr, resolvedPath) == NULL) { + if (resolvedPath != nullptr) { + if (realpath(keyPathPtr, resolvedPath) == NULL) { + free(resolvedPath); + ANS_LOGE("Fail to resolve the key path"); + return false; + } free(resolvedPath); - ANS_LOGE("Fail to resolve the key path"); - return false; } std::string keyDir = G_DIR_PATH; const char *fileNamePtr = keyDir.c_str(); diff --git a/services/ans/src/system_dialog_connect_stb.cpp b/services/ans/src/system_dialog_connect_stb.cpp index 9035552b2..4e81fb21a 100644 --- a/services/ans/src/system_dialog_connect_stb.cpp +++ b/services/ans/src/system_dialog_connect_stb.cpp @@ -61,6 +61,10 @@ void SystemDialogConnectStb::SendRemoveBundleEvent() ANS_LOGW("Invaild json param"); return; } + if (commandStr_.empty() || !nlohmann::json::accept(commandStr_)) { + ANS_LOGE("Invalid JSON"); + return; + } nlohmann::json root = nlohmann::json::parse(commandStr_); if (root.is_null() or !root.is_object()) { ANS_LOGE("Invalid JSON object"); @@ -70,6 +74,10 @@ void SystemDialogConnectStb::SendRemoveBundleEvent() ANS_LOGW("not found jsonKey from"); return; } + if (!root["bundleName"].is_string() || !root["bundleUid"].is_number_integer()) { + ANS_LOGE("value type is not right"); + return; + } if (!root["bundleName"].is_string() || !root["bundleUid"].is_string()) { ANS_LOGW("value type of json key from is not string"); return; -- Gitee From 4d01a9480f673758738541d5eeb1cdf419bfea2e Mon Sep 17 00:00:00 2001 From: Ricky Date: Mon, 4 Nov 2024 14:23:37 +0800 Subject: [PATCH 119/167] refactor: lazy load cache Signed-off-by: Ricky Change-Id: I348b7c36d64cd54d184660851c550062e6c7af2f --- .../ans/include/notification_preferences.h | 4 +- .../notification_preferences_database.h | 10 +++ .../include/notification_preferences_info.h | 1 + ...dvanced_notification_live_view_service.cpp | 4 +- services/ans/src/notification_preferences.cpp | 63 ++++++++++--------- .../src/notification_preferences_database.cpp | 42 +++++++++++-- .../ans/src/notification_preferences_info.cpp | 1 + 7 files changed, 85 insertions(+), 40 deletions(-) diff --git a/services/ans/include/notification_preferences.h b/services/ans/include/notification_preferences.h index a5ead6fd1..e1a5f8663 100644 --- a/services/ans/include/notification_preferences.h +++ b/services/ans/include/notification_preferences.h @@ -386,6 +386,8 @@ public: void UpdateCloneBundleInfo(int32_t userId, const NotificationCloneBundleInfo& cloneBundleInfo); private: + bool GetBundleInfo(NotificationPreferencesInfo &preferencesInfo, + const sptr &bundleOption, NotificationPreferencesInfo::BundleInfo &info) const; ErrCode CheckSlotForCreateSlot(const sptr &bundleOption, const sptr &slot, NotificationPreferencesInfo &preferencesInfo) const; ErrCode CheckSlotForRemoveSlot(const sptr &bundleOption, @@ -409,7 +411,7 @@ private: static std::shared_ptr instance_; NotificationPreferencesInfo preferencesInfo_ {}; std::mutex preferenceMutex_; - std::unique_ptr preferncesDB_ = nullptr; + std::shared_ptr preferncesDB_ = nullptr; }; } // namespace Notification } // namespace OHOS diff --git a/services/ans/include/notification_preferences_database.h b/services/ans/include/notification_preferences_database.h index 74d7e4d40..75f2efe59 100644 --- a/services/ans/include/notification_preferences_database.h +++ b/services/ans/include/notification_preferences_database.h @@ -207,6 +207,16 @@ public: */ bool RemoveAllSlotsFromDisturbeDB(const std::string &bundleKey, const int32_t &bundleUid); + /** + * @brief Get bundleInfo from DB. + * + * @param bundleOption Indicates the bundle bundleOption. + * @param bundleInfo Indicates bundle info. + * @return Return true on success, false on failure. + */ + bool GetBundleInfo(const sptr &bundleOption, + NotificationPreferencesInfo::BundleInfo &bundleInfo); + /** * @brief Query whether there is a agent relationship between the two apps. * diff --git a/services/ans/include/notification_preferences_info.h b/services/ans/include/notification_preferences_info.h index 8e5d13576..18c9e5ca1 100644 --- a/services/ans/include/notification_preferences_info.h +++ b/services/ans/include/notification_preferences_info.h @@ -237,6 +237,7 @@ public: */ NotificationPreferencesInfo() {} + /** * @brief Default destructor. */ diff --git a/services/ans/src/advanced_notification_live_view_service.cpp b/services/ans/src/advanced_notification_live_view_service.cpp index 6a4e5536c..ce84a81ea 100644 --- a/services/ans/src/advanced_notification_live_view_service.cpp +++ b/services/ans/src/advanced_notification_live_view_service.cpp @@ -42,12 +42,12 @@ const std::string LOCK_SCREEN_PICTURE_TAG = "lock_screen_picture"; const std::string PROGRESS_VALUE = "progressValue"; void AdvancedNotificationService::RecoverLiveViewFromDb(int32_t userId) { - ANS_LOGI("Start recover live view from db. userId:%{public}d", userId); if (notificationSvrQueue_ == nullptr) { ANS_LOGE("notificationSvrQueue_ is nullptr."); return; } ffrt::task_handle handler = notificationSvrQueue_->submit_h(std::bind([=]() { + ANS_LOGI("Start recover live view from db. userId:%{public}d", userId); std::vector requestsdb; if (GetBatchNotificationRequestsFromDb(requestsdb, userId) != ERR_OK) { ANS_LOGE("Get liveView from db failed."); @@ -110,8 +110,8 @@ void AdvancedNotificationService::RecoverLiveViewFromDb(int32_t userId) for (const auto &subscriber : NotificationSubscriberManager::GetInstance()->GetSubscriberRecords()) { OnSubscriberAdd(subscriber); } + ANS_LOGI("End recover live view from db."); })); - ANS_LOGI("End recover live view from db."); } ErrCode AdvancedNotificationService::UpdateNotificationTimerInfo(const std::shared_ptr &record) diff --git a/services/ans/src/notification_preferences.cpp b/services/ans/src/notification_preferences.cpp index a6c44ff1b..fd1d28b85 100644 --- a/services/ans/src/notification_preferences.cpp +++ b/services/ans/src/notification_preferences.cpp @@ -159,7 +159,7 @@ ErrCode NotificationPreferences::RemoveNotificationAllSlots(const sptrRemoveAllSlotsFromDisturbeDB(GenerateBundleKey(bundleOption), bundleOption->GetUid())) { @@ -188,7 +188,8 @@ ErrCode NotificationPreferences::RemoveNotificationForBundle(const sptrRemoveBundleFromDisturbeDB(GenerateBundleKey(bundleOption), bundleOption->GetUid())) { result = ERR_ANS_PREFERENCES_NOTIFICATION_DB_OPERATION_FAILED; @@ -250,7 +251,7 @@ ErrCode NotificationPreferences::GetNotificationSlot(const sptr lock(preferenceMutex_); - if (preferencesInfo_.GetBundleInfo(bundleOption, bundleInfo)) { + if (GetBundleInfo(preferencesInfo_, bundleOption, bundleInfo)) { if (!bundleInfo.GetSlot(type, slot)) { result = ERR_ANS_PREFERENCES_NOTIFICATION_SLOT_TYPE_NOT_EXIST; } @@ -272,7 +273,7 @@ ErrCode NotificationPreferences::GetNotificationAllSlots( ErrCode result = ERR_OK; NotificationPreferencesInfo::BundleInfo bundleInfo; std::lock_guard lock(preferenceMutex_); - if (preferencesInfo_.GetBundleInfo(bundleOption, bundleInfo)) { + if (GetBundleInfo(preferencesInfo_, bundleOption, bundleInfo)) { bundleInfo.GetAllSlots(slots); } else { ANS_LOGW("Notification bundle does not exsit."); @@ -292,7 +293,7 @@ ErrCode NotificationPreferences::GetNotificationSlotsNumForBundle( ErrCode result = ERR_OK; NotificationPreferencesInfo::BundleInfo bundleInfo; std::lock_guard lock(preferenceMutex_); - if (preferencesInfo_.GetBundleInfo(bundleOption, bundleInfo)) { + if (GetBundleInfo(preferencesInfo_, bundleOption, bundleInfo)) { num = static_cast(bundleInfo.GetAllSlotsSize()); } else { result = ERR_ANS_PREFERENCES_NOTIFICATION_BUNDLE_NOT_EXIST; @@ -563,6 +564,18 @@ ErrCode NotificationPreferences::AddDoNotDisturbProfiles( return ERR_OK; } +bool NotificationPreferences::GetBundleInfo(NotificationPreferencesInfo &preferencesInfo, + const sptr &bundleOption, NotificationPreferencesInfo::BundleInfo &info) const +{ + if (preferencesInfo.GetBundleInfo(bundleOption, info)) { + return true; + } else if (preferncesDB_->GetBundleInfo(bundleOption, info)) { + preferencesInfo.SetBundleInfo(info); + return true; + } + return false; +} + ErrCode NotificationPreferences::RemoveDoNotDisturbProfiles( int32_t userId, const std::vector> profiles) { @@ -651,7 +664,7 @@ void NotificationPreferences::UpdateCloneBundleInfo(int32_t userId, bundleOption->SetUid(cloneBundleInfo.GetUid()); std::lock_guard lock(preferenceMutex_); NotificationPreferencesInfo preferencesInfo = preferencesInfo_; - if (!preferencesInfo.GetBundleInfo(bundleOption, bundleInfo)) { + if (!GetBundleInfo(preferencesInfo, bundleOption, bundleInfo)) { bundleInfo.SetBundleName(cloneBundleInfo.GetBundleName()); bundleInfo.SetBundleUid(cloneBundleInfo.GetUid()); } @@ -710,26 +723,20 @@ void NotificationPreferences::GetDoNotDisturbProfileListByUserId(int32_t userId, std::vector> &profiles) { std::lock_guard lock(preferenceMutex_); - NotificationPreferencesInfo preferencesInfo = preferencesInfo_; - preferencesInfo.GetAllDoNotDisturbProfiles(userId, profiles); - preferencesInfo_ = preferencesInfo; + preferencesInfo_.GetAllDoNotDisturbProfiles(userId, profiles); } ErrCode NotificationPreferences::GetAllNotificationEnabledBundles(std::vector &bundleOption) { ANS_LOGD("Called."); std::lock_guard lock(preferenceMutex_); - NotificationPreferencesInfo preferencesInfo = preferencesInfo_; - ErrCode result = ERR_OK; if (preferncesDB_ == nullptr) { return ERR_ANS_SERVICE_NOT_READY; } - if (preferncesDB_->GetAllNotificationEnabledBundles(bundleOption)) { - preferencesInfo_ = preferencesInfo; - } else { - result = ERR_ANS_PREFERENCES_NOTIFICATION_DB_OPERATION_FAILED; + if (!preferncesDB_->GetAllNotificationEnabledBundles(bundleOption)) { + return ERR_ANS_PREFERENCES_NOTIFICATION_DB_OPERATION_FAILED; } - return result; + return ERR_OK; } ErrCode NotificationPreferences::ClearNotificationInRestoreFactorySettings() @@ -753,8 +760,7 @@ ErrCode NotificationPreferences::GetDoNotDisturbProfile( return ERR_ANS_INVALID_PARAM; } std::lock_guard lock(preferenceMutex_); - NotificationPreferencesInfo preferencesInfo = preferencesInfo_; - if (!preferencesInfo.GetDoNotDisturbProfiles(profileId, userId, profile)) { + if (!preferencesInfo_.GetDoNotDisturbProfiles(profileId, userId, profile)) { return ERR_ANS_NO_PROFILE_TEMPLATE; } return ERR_OK; @@ -810,7 +816,7 @@ ErrCode NotificationPreferences::CheckSlotForCreateSlot(const sptrGetBundleName()); bundleInfo.SetBundleUid(bundleOption->GetUid()); bundleInfo.SetEnableNotification(CheckApiCompatibility(bundleOption)); @@ -826,10 +832,9 @@ ErrCode NotificationPreferences::CheckSlotForRemoveSlot(const sptrGetType())) { bundleInfo.SetBundleName(bundleOption->GetBundleName()); bundleInfo.SetBundleUid(bundleOption->GetUid()); @@ -875,7 +880,7 @@ ErrCode NotificationPreferences::SetBundleProperty(NotificationPreferencesInfo & { ErrCode result = ERR_OK; NotificationPreferencesInfo::BundleInfo bundleInfo; - if (!preferencesInfo_.GetBundleInfo(bundleOption, bundleInfo)) { + if (!GetBundleInfo(preferencesInfo_, bundleOption, bundleInfo)) { bundleInfo.SetBundleName(bundleOption->GetBundleName()); bundleInfo.SetBundleUid(bundleOption->GetUid()); bundleInfo.SetEnableNotification(CheckApiCompatibility(bundleOption)); @@ -937,7 +942,7 @@ ErrCode NotificationPreferences::GetBundleProperty( ErrCode result = ERR_OK; NotificationPreferencesInfo::BundleInfo bundleInfo; std::lock_guard lock(preferenceMutex_); - if (preferencesInfo_.GetBundleInfo(bundleOption, bundleInfo)) { + if (GetBundleInfo(preferencesInfo_, bundleOption, bundleInfo)) { switch (type) { case BundleType::BUNDLE_IMPORTANCE_TYPE: value = bundleInfo.GetImportance(); @@ -1084,13 +1089,9 @@ void NotificationPreferences::InitSettingFromDisturbDB(int32_t userId) void NotificationPreferences::RemoveSettings(int32_t userId) { ANS_LOGD("%{public}s", __FUNCTION__); - - { - std::lock_guard lock(preferenceMutex_); - preferencesInfo_.RemoveNotificationEnable(userId); - preferencesInfo_.RemoveDoNotDisturbDate(userId); - } - + std::lock_guard lock(preferenceMutex_); + preferencesInfo_.RemoveNotificationEnable(userId); + preferencesInfo_.RemoveDoNotDisturbDate(userId); if (preferncesDB_ != nullptr) { preferncesDB_->RemoveNotificationEnable(userId); preferncesDB_->RemoveDoNotDisturbDate(userId); diff --git a/services/ans/src/notification_preferences_database.cpp b/services/ans/src/notification_preferences_database.cpp index d331ea0d1..b0fdd48dc 100644 --- a/services/ans/src/notification_preferences_database.cpp +++ b/services/ans/src/notification_preferences_database.cpp @@ -666,16 +666,46 @@ bool NotificationPreferencesDatabase::ParseFromDisturbeDB(NotificationPreference GetDoNotDisturbEndDate(info, iter); GetEnableAllNotification(info, iter); GetDoNotDisturbProfile(info, iter); + } - std::unordered_map values; - int32_t result = rdbDataManager_->QueryDataBeginWithKey(KEY_BUNDLE_LABEL, values, iter); - if (result == NativeRdb::E_ERROR) { - ANS_LOGE("Get Bundle Info failed."); - continue; + return true; +} + + +bool NotificationPreferencesDatabase::GetBundleInfo(const sptr &bundleOption, + NotificationPreferencesInfo::BundleInfo &bundleInfo) +{ + std::string bundleDBKey = KEY_BUNDLE_LABEL + bundleOption->GetBundleName() + + std::to_string(bundleOption->GetUid()); + int32_t userId = -1; + OsAccountManagerHelper::GetInstance().GetOsAccountLocalIdFromUid(bundleOption->GetUid(), userId); + std::string bundleKey; + int32_t result = rdbDataManager_->QueryData(bundleDBKey, bundleKey, userId); + if (result != NativeRdb::E_OK) { + ANS_LOGE("Get Bundle Info failed."); + return false; + } + ANS_LOGD("Bundle name is %{public}s.", bundleKey.c_str()); + std::unordered_map bundleEntries; + rdbDataManager_->QueryDataBeginWithKey((GenerateBundleKey(bundleKey)), bundleEntries, userId); + ANS_LOGD("Bundle key is %{public}s.", GenerateBundleKey(bundleKey).c_str()); + std::string keyStr = GenerateBundleKey(bundleKey, KEY_BUNDLE_SHOW_BADGE); + bool badgeEnableExist = false; + for (auto bundleEntry : bundleEntries) { + if (IsSlotKey(GenerateBundleKey(bundleKey), bundleEntry.first)) { + ParseSlotFromDisturbeDB(bundleInfo, bundleKey, bundleEntry, userId); + } else { + ParseBundlePropertyFromDisturbeDB(bundleInfo, bundleKey, bundleEntry); + } + + if (keyStr.compare(bundleEntry.first) == 0) { + badgeEnableExist = true; } - ParseBundleFromDistureDB(info, values, iter); } + if (!badgeEnableExist) { + bundleInfo.SetIsShowBadge(static_cast(true)); + } return true; } diff --git a/services/ans/src/notification_preferences_info.cpp b/services/ans/src/notification_preferences_info.cpp index c88831f60..e77bc6e85 100644 --- a/services/ans/src/notification_preferences_info.cpp +++ b/services/ans/src/notification_preferences_info.cpp @@ -23,6 +23,7 @@ namespace Notification { namespace { const static std::string KEY_UNDER_LINE = "_"; } // namespace + NotificationPreferencesInfo::BundleInfo::BundleInfo() { } -- Gitee From 171e2652670e961f0cd98ad2748270dd6084a41b Mon Sep 17 00:00:00 2001 From: z30053788 Date: Wed, 6 Nov 2024 16:02:42 +0800 Subject: [PATCH 120/167] cherry pick 3dee3e6 from https://gitee.com/zhaobaoxin1/notification_distributed_notification_service/pulls/2379 doublefree Signed-off-by: z30053788 Change-Id: I4c7b9c219ff789c89921d883583d2097f24bbe03 --- services/ans/src/advanced_notification_utils.cpp | 2 +- services/ans/src/notification_subscriber_manager.cpp | 4 ++-- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/services/ans/src/advanced_notification_utils.cpp b/services/ans/src/advanced_notification_utils.cpp index 5858ff42e..8d27ff72d 100644 --- a/services/ans/src/advanced_notification_utils.cpp +++ b/services/ans/src/advanced_notification_utils.cpp @@ -1233,7 +1233,7 @@ ErrCode AdvancedNotificationService::DoDistributedDelete( const std::string deviceId, const std::string bundleName, const sptr notification) { HITRACE_METER_NAME(HITRACE_TAG_NOTIFICATION, __PRETTY_FUNCTION__); - if (!notification->GetNotificationRequest().GetNotificationDistributedOptions().IsDistributed()) { + if (!notification->GetNotificationRequestPoint()->GetNotificationDistributedOptions().IsDistributed()) { return ERR_OK; } if (deviceId.empty()) { diff --git a/services/ans/src/notification_subscriber_manager.cpp b/services/ans/src/notification_subscriber_manager.cpp index 4a8efbab7..e319b8d6e 100644 --- a/services/ans/src/notification_subscriber_manager.cpp +++ b/services/ans/src/notification_subscriber_manager.cpp @@ -519,7 +519,7 @@ bool NotificationSubscriberManager::IsSubscribedBysubscriber( auto BundleNames = notification->GetBundleName(); auto iter = std::find(record->bundleList_.begin(), record->bundleList_.end(), BundleNames); bool isSubscribedTheNotification = record->subscribedAll || (iter != record->bundleList_.end()) || - (notification->GetNotificationRequest().GetCreatorUid() == record->subscriberUid); + (notification->GetNotificationRequestPoint()->GetCreatorUid() == record->subscriberUid); if (!isSubscribedTheNotification) { return false; } @@ -528,7 +528,7 @@ bool NotificationSubscriberManager::IsSubscribedBysubscriber( return true; } - int32_t recvUserId = notification->GetNotificationRequest().GetReceiverUserId(); + int32_t recvUserId = notification->GetNotificationRequestPoint()->GetReceiverUserId(); int32_t sendUserId = notification->GetUserId(); if (record->userId == recvUserId) { return true; -- Gitee From eb3922bec672d62d1b15c3848357a84c1ea08b41 Mon Sep 17 00:00:00 2001 From: wufarong Date: Mon, 4 Nov 2024 14:09:22 +0800 Subject: [PATCH 121/167] =?UTF-8?q?cherry=20pick=20c70b66f=20from=20https:?= =?UTF-8?q?//gitee.com/wufarong1/notification=5Fdistributed=5Fnotification?= =?UTF-8?q?=5Fservice/pulls/2362=20PublishFlowControlUT=E8=A1=A5=E5=85=85?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: wufarong Change-Id: I981c60d0fa495b3466e55eb983ef54175f40700d --- .../ans/src/advanced_notification_service.cpp | 7 ++--- .../ans/src/advanced_notification_utils.cpp | 9 ------- .../advanced_notification_service_test.cpp | 26 +++++++++++++++++++ 3 files changed, 30 insertions(+), 12 deletions(-) diff --git a/services/ans/src/advanced_notification_service.cpp b/services/ans/src/advanced_notification_service.cpp index a31f9426c..983956454 100644 --- a/services/ans/src/advanced_notification_service.cpp +++ b/services/ans/src/advanced_notification_service.cpp @@ -1510,11 +1510,12 @@ void AdvancedNotificationService::UpdateRecentNotification(sptr &n static bool SortNotificationsByLevelAndTime( const std::shared_ptr &first, const std::shared_ptr &second) { - if (first->slot->GetLevel() != second->slot->GetLevel()) { - return (first->slot->GetLevel() < second->slot->GetLevel()); + if (first->slot ==nullptr || second->slot == nullptr) { + return (first->request->GetCreateTime() < second->request->GetCreateTime()); } - return (first->request->GetCreateTime() < second->request->GetCreateTime()); + return (first->slot->GetLevel() < second->slot->GetLevel()); } + ErrCode AdvancedNotificationService::FlowControl(const std::shared_ptr &record) { diff --git a/services/ans/src/advanced_notification_utils.cpp b/services/ans/src/advanced_notification_utils.cpp index 5858ff42e..91922af23 100644 --- a/services/ans/src/advanced_notification_utils.cpp +++ b/services/ans/src/advanced_notification_utils.cpp @@ -93,15 +93,6 @@ constexpr char HIDUMPER_HELP_MSG[] = " --recent, -r list recent notifications\n"; } -static bool SortNotificationsByLevelAndTime( - const std::shared_ptr &first, const std::shared_ptr &second) -{ - if (first->slot->GetLevel() != second->slot->GetLevel()) { - return (first->slot->GetLevel() < second->slot->GetLevel()); - } - return (first->request->GetCreateTime() < second->request->GetCreateTime()); -} - std::shared_ptr AdvancedNotificationService::GetNotificationSvrQueue() { return notificationSvrQueue_; diff --git a/services/ans/test/unittest/advanced_notification_service_test.cpp b/services/ans/test/unittest/advanced_notification_service_test.cpp index 6d5d0f1fe..19a1d18a5 100644 --- a/services/ans/test/unittest/advanced_notification_service_test.cpp +++ b/services/ans/test/unittest/advanced_notification_service_test.cpp @@ -3760,5 +3760,31 @@ HWTEST_F(AdvancedNotificationServiceTest, GetExcludeDates_00001, Function | Smal ASSERT_EQ(advancedNotificationService_->GetExcludeDates(reminderId, times), (int)ERR_NO_INIT); MockIsVerfyPermisson(false); } + +/** + * @tc.number : PublishFlowControl_00001 + * @tc.name : Test PublishFlowControl + * @tc.desc : Test PublishFlowControl function when the record->slot is nullptr + * @tc.require : issueI5S4VP + */ +HWTEST_F(AdvancedNotificationServiceTest, PublishFlowControl_00001, Function | SmallTest | Level1) +{ + for (int i = 0; i < 100; i++) { + sptr request = new (std::nothrow) NotificationRequest(); + sptr notification = new (std::nothrow) Notification(request); + auto record = std::make_shared(); + record->request = request; + record->notification = notification; + advancedNotificationService_->notificationList_.push_back(record); + } + ASSERT_EQ(advancedNotificationService_->notificationList_.size(), 100); + sptr request = new (std::nothrow) NotificationRequest(); + sptr notification = new (std::nothrow) Notification(request); + auto record = std::make_shared(); + record->request = request; + record->notification = notification; + advancedNotificationService_->PublishFlowControl(record); + ASSERT_EQ(advancedNotificationService_->notificationList_.size(), 100); +} } // namespace Notification } // namespace OHOS -- Gitee From 7448d4d0141f8ed71ddedd8dc67479681fe871cf Mon Sep 17 00:00:00 2001 From: yangjun Date: Sat, 2 Nov 2024 12:01:38 +0800 Subject: [PATCH 122/167] =?UTF-8?q?=E8=A1=A5=E5=85=85=E8=AE=BE=E7=BD=AE?= =?UTF-8?q?=E7=B1=BB=E6=89=93=E7=82=B9?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Change-Id: I15ef008371bbfd3951dc655d28db2ed88df314ca Signed-off-by: yangjun --- .../advanced_notification_publish_service.cpp | 141 ++++++++++++++---- .../advanced_notification_slot_service.cpp | 34 +++-- .../common/notification_analytics_util.cpp | 50 ++++++- .../src/notification_subscriber_manager.cpp | 23 ++- 4 files changed, 203 insertions(+), 45 deletions(-) diff --git a/services/ans/src/advanced_notification_publish_service.cpp b/services/ans/src/advanced_notification_publish_service.cpp index ff18b3406..e8b9f015d 100644 --- a/services/ans/src/advanced_notification_publish_service.cpp +++ b/services/ans/src/advanced_notification_publish_service.cpp @@ -728,18 +728,33 @@ ErrCode AdvancedNotificationService::DeleteAll() ErrCode AdvancedNotificationService::SetShowBadgeEnabledForBundle( const sptr &bundleOption, bool enabled) { + if (bundleOption == nullptr) { + ANS_LOGE("BundleOption is null."); + return ERR_ANS_INVALID_BUNDLE; + } + + HaMetaMessage message = HaMetaMessage(EventSceneId::SCENE_8, EventBranchId::BRANCH_3); + message.Message("Des_" + bundleOption->GetBundleName() + "_" + std::to_string(bundleOption->GetUid()) + + " enabled:" + std::to_string(enabled)); + bool isSubsystem = AccessTokenHelper::VerifyNativeToken(IPCSkeleton::GetCallingTokenID()); if (!isSubsystem && !AccessTokenHelper::IsSystemApp()) { + ANS_LOGE("IsSystemApp is false."); + message.ErrorCode(ERR_ANS_NON_SYSTEM_APP).Append(" Not SystemApp"); + NotificationAnalyticsUtil::ReportModifyEvent(message); return ERR_ANS_NON_SYSTEM_APP; } if (!AccessTokenHelper::CheckPermission(OHOS_PERMISSION_NOTIFICATION_CONTROLLER)) { - ANS_LOGD("Check permission is false."); + ANS_LOGE("Permission Denied."); + message.ErrorCode(ERR_ANS_PERMISSION_DENIED).Append(" Permission Denied"); + NotificationAnalyticsUtil::ReportModifyEvent(message); return ERR_ANS_PERMISSION_DENIED; } sptr bundle = GenerateValidBundleOption(bundleOption); if (bundle == nullptr) { + ANS_LOGE("Bundle is nullptr."); return ERR_ANS_INVALID_BUNDLE; } @@ -757,6 +772,10 @@ ErrCode AdvancedNotificationService::SetShowBadgeEnabledForBundle( } })); notificationSvrQueue_->wait(handler); + ANS_LOGI("Des_%{public}s_%{public}d, enabled: %{public}s, Set show badge enabled for bundle result: %{public}d", + bundleOption->GetBundleName().c_str(), bundleOption->GetUid(), std::to_string(enabled).c_str(), result); + message.ErrorCode(result); + NotificationAnalyticsUtil::ReportModifyEvent(message); return result; } @@ -850,37 +869,48 @@ ErrCode AdvancedNotificationService::RequestEnableNotification(const std::string ErrCode result = ERR_OK; sptr bundleOption = GenerateBundleOption(); if (bundleOption == nullptr) { - ANS_LOGD("bundleOption == nullptr"); + ANS_LOGE("bundleOption is nullptr."); return ERR_ANS_INVALID_BUNDLE; } // To get the permission bool allowedNotify = false; - HaMetaMessage message = HaMetaMessage(EventSceneId::SCENE_2, EventBranchId::BRANCH_1) - .BundleName(bundleOption->GetBundleName()); + HaMetaMessage message = HaMetaMessage(EventSceneId::SCENE_8, EventBranchId::BRANCH_5); + message.Message("Des_" + bundleOption->GetBundleName() + "_" + std::to_string(bundleOption->GetUid()) + + " deviceId:" + deviceId); result = IsAllowedNotifySelf(bundleOption, allowedNotify); if (result != ERR_OK) { - message.Message("Allow notify self failed: " + std::to_string(result)); + ANS_LOGE("Not allowed notify self"); + message.ErrorCode(result).Append(" Allow failed"); NotificationAnalyticsUtil::ReportModifyEvent(message); return ERROR_INTERNAL_ERROR; } ANS_LOGI("allowedNotify = %{public}d, bundle = %{public}s", allowedNotify, bundleOption->GetBundleName().c_str()); if (allowedNotify) { + message.ErrorCode(ERR_OK).Append(" Allow success"); + NotificationAnalyticsUtil::ReportModifyEvent(message); return ERR_OK; } // Check to see if it has been popover before bool hasPopped = false; result = GetHasPoppedDialog(bundleOption, hasPopped); if (result != ERR_OK) { - message.Message("Has popped dialog: " + std::to_string(result)); + ANS_LOGE("Get has popped dialog failed."); + message.ErrorCode(result).Append(" Get dialog failed."); NotificationAnalyticsUtil::ReportModifyEvent(message); return ERROR_INTERNAL_ERROR; } if (hasPopped) { + ANS_LOGE("Has popped is true."); + message.ErrorCode(ERR_ANS_NOT_ALLOWED).Append(" Has popped"); + NotificationAnalyticsUtil::ReportModifyEvent(message); return ERR_ANS_NOT_ALLOWED; } if (!CreateDialogManager()) { + ANS_LOGE("Create dialog manager failed."); + message.ErrorCode(ERR_ANS_NOT_ALLOWED).Append(" Create dialog failed"); + NotificationAnalyticsUtil::ReportModifyEvent(message); return ERROR_INTERNAL_ERROR; } @@ -888,7 +918,10 @@ ErrCode AdvancedNotificationService::RequestEnableNotification(const std::string if (result == ERR_OK) { result = ERR_ANS_DIALOG_POP_SUCCEEDED; } - message.Message("Request dialog: " + std::to_string(result)); + + ANS_LOGI("Des_%{public}s_%{public}d, deviceId: %{public}s, Request enable notification dailog result: %{public}d", + bundleOption->GetBundleName().c_str(), bundleOption->GetUid(), deviceId.c_str(), result); + message.ErrorCode(result); NotificationAnalyticsUtil::ReportModifyEvent(message); return result; } @@ -940,25 +973,28 @@ ErrCode AdvancedNotificationService::SetNotificationsEnabledForSpecialBundle( { HITRACE_METER_NAME(HITRACE_TAG_NOTIFICATION, __PRETTY_FUNCTION__); ANS_LOGD("%{public}s", __FUNCTION__); - if (bundleOption == nullptr || bundleOption->GetBundleName().empty()) { - return ERR_ANS_INVALID_PARAM; + if (bundleOption == nullptr) { + ANS_LOGE("BundleOption is null."); + return ERR_ANS_INVALID_BUNDLE; } - HaMetaMessage message = HaMetaMessage(EventSceneId::SCENE_7, EventBranchId::BRANCH_5); - message.Message("Des_" + bundleOption->GetBundleName() + "_" +std::to_string(bundleOption->GetUid()) + - " enable: " + std::to_string(enabled)); + + HaMetaMessage message = HaMetaMessage(EventSceneId::SCENE_8, EventBranchId::BRANCH_4); + message.Message("Des_" + bundleOption->GetBundleName() + "_" + std::to_string(bundleOption->GetUid()) + + " enabled:" + std::to_string(enabled) + + " deviceId:" + deviceId); bool isSubsystem = AccessTokenHelper::VerifyNativeToken(IPCSkeleton::GetCallingTokenID()); if (!isSubsystem && !AccessTokenHelper::IsSystemApp()) { - message.ErrorCode(ERR_ANS_NON_SYSTEM_APP).Append(" Not system app."); + ANS_LOGE("IsSystemApp is false."); + message.ErrorCode(ERR_ANS_NON_SYSTEM_APP).Append(" Not SystemApp"); NotificationAnalyticsUtil::ReportModifyEvent(message); - ANS_LOGE("Not system app."); return ERR_ANS_NON_SYSTEM_APP; } int32_t callingUid = IPCSkeleton::GetCallingUid(); if (callingUid != ANS_UID && !AccessTokenHelper::CheckPermission(OHOS_PERMISSION_NOTIFICATION_CONTROLLER)) { - message.ErrorCode(ERR_ANS_PERMISSION_DENIED).Append(" No acl permission."); + ANS_LOGE("Permission Denied."); + message.ErrorCode(ERR_ANS_PERMISSION_DENIED).Append(" Permission Denied"); NotificationAnalyticsUtil::ReportModifyEvent(message); - ANS_LOGE(" No acl permission."); return ERR_ANS_PERMISSION_DENIED; } @@ -998,6 +1034,11 @@ ErrCode AdvancedNotificationService::SetNotificationsEnabledForSpecialBundle( // Remote device } + ANS_LOGI("Des_%{public}s_%{public}d, deviceId: %{public}s, enable: %{public}s, " + "Set notifications enabled for special bundle result: %{public}d", bundleOption->GetBundleName().c_str(), + bundleOption->GetUid(), deviceId.c_str(), std::to_string(enabled).c_str(), result); + message.ErrorCode(result); + NotificationAnalyticsUtil::ReportModifyEvent(message); SendEnableNotificationHiSysEvent(bundleOption, enabled, result); return result; } @@ -1052,48 +1093,65 @@ ErrCode AdvancedNotificationService::CanPopEnableNotificationDialog( ANS_LOGD("%{public}s", __FUNCTION__); canPop = false; ErrCode result = ERR_OK; - HaMetaMessage message = HaMetaMessage(EventSceneId::SCENE_2, EventBranchId::BRANCH_2); sptr bundleOption = GenerateBundleOption(); if (bundleOption == nullptr) { - ANS_LOGE("bundleOption == nullptr"); + ANS_LOGE("bundleOption is nullptr."); return ERR_ANS_INVALID_BUNDLE; } // To get the permission bool allowedNotify = false; - message.BundleName(bundleOption->GetBundleName()); + HaMetaMessage message = HaMetaMessage(EventSceneId::SCENE_2, EventBranchId::BRANCH_2); + message.Message("Des_" + bundleOption->GetBundleName() + "_" + std::to_string(bundleOption->GetUid()) + + " canPop:" + std::to_string(canPop)); result = IsAllowedNotifySelf(bundleOption, allowedNotify); if (result != ERR_OK) { - message.Message("Allow notify self failed: " + std::to_string(result)); + ANS_LOGE("Not allowed Notify self."); + message.ErrorCode(result).Append(" Not Allow"); NotificationAnalyticsUtil::ReportModifyEvent(message); return ERROR_INTERNAL_ERROR; } ANS_LOGI("allowedNotify = %{public}d", allowedNotify); if (allowedNotify) { + message.ErrorCode(ERR_OK).Append(" Allow success"); + NotificationAnalyticsUtil::ReportModifyEvent(message); return ERR_OK; } // Check to see if it has been popover before bool hasPopped = false; result = GetHasPoppedDialog(bundleOption, hasPopped); if (result != ERR_OK) { - message.Message("Has popped dialog: " + std::to_string(result)); + ANS_LOGE("Get has popped dialog failed. result: %{public}d", result); + message.ErrorCode(result).Append(" Has popped"); NotificationAnalyticsUtil::ReportModifyEvent(message); return ERROR_INTERNAL_ERROR; } if (hasPopped) { + ANS_LOGE("Has popped is true."); + message.ErrorCode(ERR_ANS_NOT_ALLOWED).Append(" Haspopped true"); + NotificationAnalyticsUtil::ReportModifyEvent(message); return ERR_ANS_NOT_ALLOWED; } if (!CreateDialogManager()) { + ANS_LOGE("Create dialog manager failed."); + message.ErrorCode(ERR_ANS_NOT_ALLOWED).Append(" Create dialog failed"); + NotificationAnalyticsUtil::ReportModifyEvent(message); return ERROR_INTERNAL_ERROR; } result = dialogManager_->AddDialogInfo(bundleOption, callback); if (result != ERR_OK) { + ANS_LOGI("AddDialogInfo result: %{public}d", result); + message.ErrorCode(result).Append(" AddDialogInfo"); + NotificationAnalyticsUtil::ReportModifyEvent(message); return result; } canPop = true; bundleName = bundleOption->GetBundleName(); - ANS_LOGI("CanPopEnableNotificationDialog end"); + ANS_LOGI("Des_%{public}s_%{public}d, canPop: %{public}s, CanPopEnableNotificationDialog result: %{public}d", + bundleOption->GetBundleName().c_str(), bundleOption->GetUid(), std::to_string(canPop).c_str(), result); + message.ErrorCode(result).Append(" CanPopEnableNotificationDialog end"); + NotificationAnalyticsUtil::ReportModifyEvent(message); return ERR_OK; } @@ -2516,14 +2574,27 @@ ErrCode AdvancedNotificationService::SetDistributedEnabledByBundle(const sptrGetBundleName() + "_" + std::to_string(bundleOption->GetUid()) + + " enabled:" + std::to_string(enabled) + + " deviceType:" + deviceType); bool isSubsystem = AccessTokenHelper::VerifyNativeToken(IPCSkeleton::GetCallingTokenID()); if (!isSubsystem && !AccessTokenHelper::IsSystemApp()) { - ANS_LOGD("IsSystemApp is bogus."); + ANS_LOGE("IsSystemApp is false."); + message.ErrorCode(ERR_ANS_NON_SYSTEM_APP).Append("Not SystemApp"); + NotificationAnalyticsUtil::ReportModifyEvent(message); return ERR_ANS_NON_SYSTEM_APP; } if (!AccessTokenHelper::CheckPermission(OHOS_PERMISSION_NOTIFICATION_CONTROLLER)) { + ANS_LOGE("Permission Denied."); + message.ErrorCode(ERR_ANS_PERMISSION_DENIED).Append("No permission"); + NotificationAnalyticsUtil::ReportModifyEvent(message); return ERR_ANS_PERMISSION_DENIED; } @@ -2532,8 +2603,16 @@ ErrCode AdvancedNotificationService::SetDistributedEnabledByBundle(const sptrSetDistributedEnabledByBundle(bundle, + deviceType, enabled); - return NotificationPreferences::GetInstance()->SetDistributedEnabledByBundle(bundle, deviceType, enabled); + ANS_LOGI("Des_%{public}s_%{public}d, deviceType: %{public}s, enabled: %{public}s, " + "SetDistributedEnabledByBundle result: %{public}d", bundleOption->GetBundleName().c_str(), + bundleOption->GetUid(), deviceType.c_str(), std::to_string(enabled).c_str(), result); + message.ErrorCode(result); + NotificationAnalyticsUtil::ReportModifyEvent(message); + + return result; } ErrCode AdvancedNotificationService::IsDistributedEnabledByBundle(const sptr &bundleOption, @@ -2672,16 +2751,28 @@ ErrCode AdvancedNotificationService::PublishRemoveDuplicateEvent(const std::shar ErrCode AdvancedNotificationService::SetSmartReminderEnabled(const std::string &deviceType, const bool enabled) { ANS_LOGD("%{public}s", __FUNCTION__); + HaMetaMessage message = HaMetaMessage(EventSceneId::SCENE_8, EventBranchId::BRANCH_6); + message.Message(" enabled:" + std::to_string(enabled) + " deviceType:" + deviceType); bool isSubsystem = AccessTokenHelper::VerifyNativeToken(IPCSkeleton::GetCallingTokenID()); if (!isSubsystem && !AccessTokenHelper::IsSystemApp()) { - ANS_LOGD("IsSystemApp is bogus."); + ANS_LOGE("IsSystemApp is false."); + message.ErrorCode(ERR_ANS_NON_SYSTEM_APP).Append(" Not SystemApp"); + NotificationAnalyticsUtil::ReportModifyEvent(message); return ERR_ANS_NON_SYSTEM_APP; } if (!AccessTokenHelper::CheckPermission(OHOS_PERMISSION_NOTIFICATION_CONTROLLER)) { + ANS_LOGE("Permission Denied."); + message.ErrorCode(ERR_ANS_PERMISSION_DENIED).Append(" Permission Denied"); + NotificationAnalyticsUtil::ReportModifyEvent(message); return ERR_ANS_PERMISSION_DENIED; } ErrCode result = NotificationPreferences::GetInstance()->SetSmartReminderEnabled(deviceType, enabled); + + ANS_LOGI("enabled: %{public}s, deviceType: %{public}s,Set smart reminder enabled: %{public}d", + std::to_string(enabled).c_str(), deviceType.c_str(), result); + message.ErrorCode(result); + NotificationAnalyticsUtil::ReportModifyEvent(message); return result; } diff --git a/services/ans/src/advanced_notification_slot_service.cpp b/services/ans/src/advanced_notification_slot_service.cpp index c178f5bd4..38e3fde20 100644 --- a/services/ans/src/advanced_notification_slot_service.cpp +++ b/services/ans/src/advanced_notification_slot_service.cpp @@ -412,23 +412,31 @@ ErrCode AdvancedNotificationService::SetSlotFlagsAsBundle(const sptrGetBundleName() + "_" + std::to_string(bundleOption->GetUid()) + + " slotFlags:" + std::to_string(slotFlags)); bool isSubsystem = AccessTokenHelper::VerifyNativeToken(IPCSkeleton::GetCallingTokenID()); if (!isSubsystem && !AccessTokenHelper::IsSystemApp()) { - ANS_LOGD("IsSystemApp is false."); + ANS_LOGE("IsSystemApp is false."); + message.ErrorCode(ERR_ANS_NON_SYSTEM_APP).Append(" Not SystemApp"); + NotificationAnalyticsUtil::ReportModifyEvent(message); return ERR_ANS_NON_SYSTEM_APP; } if (!AccessTokenHelper::CheckPermission(OHOS_PERMISSION_NOTIFICATION_CONTROLLER)) { + ANS_LOGE("Permission denied."); + message.ErrorCode(ERR_ANS_PERMISSION_DENIED).Append(" Permission denied"); + NotificationAnalyticsUtil::ReportModifyEvent(message); return ERR_ANS_PERMISSION_DENIED; } sptr bundle = GenerateValidBundleOption(bundleOption); if (bundle == nullptr) { - ANS_LOGD("Bundle is null."); + ANS_LOGE("Bundle is null."); return ERR_ANS_INVALID_BUNDLE; } @@ -447,9 +455,9 @@ ErrCode AdvancedNotificationService::SetSlotFlagsAsBundle(const sptrwait(handler); - HaMetaMessage message = HaMetaMessage(EventSceneId::SCENE_4, EventBranchId::BRANCH_2) - .Message("Set slotflags " + bundleOption->GetBundleName() + " flag " + - std::to_string(slotFlags) + " ret " + std::to_string(result)); + ANS_LOGI("Des_%{public}s_%{public}d, slotFlags: %{public}d, SetSlotFlagsAsBundle result: %{public}d", + bundleOption->GetBundleName().c_str(), bundleOption->GetUid(), slotFlags, result); + message.ErrorCode(result); NotificationAnalyticsUtil::ReportModifyEvent(message); return result; } @@ -765,11 +773,15 @@ bool AdvancedNotificationService::PublishSlotChangeCommonEvent(const sptrSyncAdditionConfig(key, value); if (sync_result != ERR_OK) { - message.Message("Set addition config " + key + " ret " + std::to_string(sync_result)); + ANS_LOGE("Sync addition config result: %{public}d, key: %{public}s, value: %{public}s", + sync_result, key.c_str(), value.c_str()); + message.ErrorCode(sync_result).Append(" Sync failed"); NotificationAnalyticsUtil::ReportModifyEvent(message); return sync_result; } @@ -798,7 +812,9 @@ ErrCode AdvancedNotificationService::SetAdditionConfig(const std::string &key, c result = NotificationPreferences::GetInstance()->SetKvToDb(key, value, SUBSCRIBE_USER_INIT); })); notificationSvrQueue_->wait(handler); - message.Message("Set addition config " + key + " ret " + std::to_string(result)); + ANS_LOGI("Set addition config result: %{public}d, key: %{public}s, value: %{public}s", + result, key.c_str(), value.c_str()); + message.ErrorCode(result); NotificationAnalyticsUtil::ReportModifyEvent(message); return result; } diff --git a/services/ans/src/common/notification_analytics_util.cpp b/services/ans/src/common/notification_analytics_util.cpp index 839d98171..3659b6b02 100644 --- a/services/ans/src/common/notification_analytics_util.cpp +++ b/services/ans/src/common/notification_analytics_util.cpp @@ -26,6 +26,7 @@ #include "report_timer_info.h" #include "time_service_client.h" #include "nlohmann/json.hpp" +#include "bundle_manager_helper.h" namespace OHOS { namespace Notification { constexpr char MESSAGE_DELIMITER = '#'; @@ -40,6 +41,7 @@ constexpr const int32_t MODIFY_ERROR_EVENT_TIME = 60; constexpr const int32_t REPORT_CACHE_MAX_SIZE = 50; constexpr const int32_t REPORT_CACHE_INTERVAL_TIME = 30; +constexpr const int32_t REASON_MAX_LENGTH = 127; const static std::string NOTIFICATION_EVENT_PUSH_AGENT = "notification.event.PUSH_AGENT"; static std::mutex reportFlowControlMutex_; static std::map> flowControlTimestampMap_ = { @@ -150,7 +152,7 @@ std::string HaMetaMessage::Build() const void NotificationAnalyticsUtil::ReportPublishFailedEvent(const sptr& request, const HaMetaMessage& message) { - return; + CommonNotificationEvent(request, PUBLISH_ERROR_EVENT_CODE, message); } void NotificationAnalyticsUtil::ReportDeleteFailedEvent(const sptr& request, @@ -223,6 +225,13 @@ void NotificationAnalyticsUtil::ReportModifyEvent(const HaMetaMessage& message) std::string extraInfo = NotificationAnalyticsUtil::BuildExtraInfo(message); NotificationAnalyticsUtil::SetCommonWant(want, message, extraInfo); + std::string bundle; + int32_t callingUid = IPCSkeleton::GetCallingUid(); + std::shared_ptr bundleManager = BundleManagerHelper::GetInstance(); + if (bundleManager != nullptr) { + bundle = bundleManager->GetBundleNameByUid(callingUid); + } + want.SetBundle(bundle + "_" + std::to_string(callingUid)); want.SetParam("slotType", static_cast(message.slotType_)); IN_PROCESS_CALL_WITHOUT_RET(AddListCache(want, MODIFY_ERROR_EVENT_CODE)); } @@ -318,8 +327,24 @@ std::string NotificationAnalyticsUtil::BuildExtraInfo(const HaMetaMessage& messa reason["time"] = now; std::shared_ptr extraInfo = std::make_shared(); - extraInfo->SetParam("reason", - AAFwk::String::Box(reason.dump(-1, ' ', false, nlohmann::json::error_handler_t::replace))); + + reason["detail"] = ""; + int32_t reasonFixedSize = + static_cast(reason.dump(-1, ' ', false, nlohmann::json::error_handler_t::replace).size()); + int32_t leftSpace = REASON_MAX_LENGTH - reasonFixedSize; + if (leftSpace < 0) { + std::string basicInfo = std::to_string(message.sceneId_) + MESSAGE_DELIMITER + + std::to_string(message.branchId_) + MESSAGE_DELIMITER + + std::to_string(message.errorCode_) + MESSAGE_DELIMITER + + std::to_string(now) + " Reason fixed size exceeds limit"; + extraInfo->SetParam("reason", AAFwk::String::Box(basicInfo)); + ANS_LOGI("%{public}s", basicInfo.c_str()); + } else { + reason["detail"] = message.message_.substr(0, leftSpace); + extraInfo->SetParam("reason", + AAFwk::String::Box(reason.dump(-1, ' ', false, nlohmann::json::error_handler_t::replace))); + } + AAFwk::WantParamWrapper wWrapper(*extraInfo); return wWrapper.ToString(); @@ -355,8 +380,23 @@ std::string NotificationAnalyticsUtil::BuildExtraInfoWithReq(const HaMetaMessage extraInfo = std::make_shared(); } - extraInfo->SetParam("reason", - AAFwk::String::Box(reason.dump(-1, ' ', false, nlohmann::json::error_handler_t::replace))); + reason["detail"] = ""; + int32_t reasonFixedSize = + static_cast(reason.dump(-1, ' ', false, nlohmann::json::error_handler_t::replace).size()); + int32_t leftSpace = REASON_MAX_LENGTH - reasonFixedSize; + if (leftSpace < 0) { + std::string basicInfo = std::to_string(message.sceneId_) + MESSAGE_DELIMITER + + std::to_string(message.branchId_) + MESSAGE_DELIMITER + + std::to_string(message.errorCode_) + MESSAGE_DELIMITER + + std::to_string(now) + " Reason fixed size exceeds limit"; + extraInfo->SetParam("reason", AAFwk::String::Box(basicInfo)); + ANS_LOGI("%{public}s", basicInfo.c_str()); + } else { + reason["detail"] = message.message_.substr(0, leftSpace); + extraInfo->SetParam("reason", + AAFwk::String::Box(reason.dump(-1, ' ', false, nlohmann::json::error_handler_t::replace))); + } + AAFwk::WantParamWrapper wWrapper(*extraInfo); return wWrapper.ToString(); diff --git a/services/ans/src/notification_subscriber_manager.cpp b/services/ans/src/notification_subscriber_manager.cpp index 4a8efbab7..52d1ffe26 100644 --- a/services/ans/src/notification_subscriber_manager.cpp +++ b/services/ans/src/notification_subscriber_manager.cpp @@ -89,10 +89,16 @@ ErrCode NotificationSubscriberManager::AddSubscriber( } } + HaMetaMessage message = HaMetaMessage(EventSceneId::SCENE_9, EventBranchId::BRANCH_2); + message.Message("Des_" + GetClientBundleName() + "_" + + " user:" + std::to_string(subInfo->GetAppUserId())); if (subInfo->GetAppUserId() == SUBSCRIBE_USER_INIT) { int32_t userId = SUBSCRIBE_USER_INIT; ErrCode ret = OsAccountManagerHelper::GetInstance().GetCurrentCallingUserId(userId); if (ret != ERR_OK) { + ANS_LOGE("Get current calling userId failed."); + message.ErrorCode(ret).Append(" Get userId Failed"); + NotificationAnalyticsUtil::ReportModifyEvent(message); return ret; } subInfo->AddAppUserId(userId); @@ -103,13 +109,15 @@ ErrCode NotificationSubscriberManager::AddSubscriber( ANS_LOGE("queue is nullptr"); return result; } - HaMetaMessage message = HaMetaMessage(EventSceneId::SCENE_6, EventBranchId::BRANCH_2); + ffrt::task_handle handler = notificationSubQueue_->submit_h(std::bind([this, &subscriber, &subInfo, &result]() { result = this->AddSubscriberInner(subscriber, subInfo); })); notificationSubQueue_->wait(handler); - message.Message("Subscribe notification: " + GetClientBundleName() + " user " + - std::to_string(subInfo->GetAppUserId()) + " " + std::to_string(result)); + + ANS_LOGI("Des_%{public}s_, user: %{public}s, Add subscriber result: %{public}d", GetClientBundleName().c_str(), + std::to_string(subInfo->GetAppUserId()).c_str(), result); + message.ErrorCode(result); NotificationAnalyticsUtil::ReportModifyEvent(message); return result; } @@ -128,7 +136,7 @@ ErrCode NotificationSubscriberManager::RemoveSubscriber( ANS_LOGE("queue is nullptr"); return result; } - HaMetaMessage message = HaMetaMessage(EventSceneId::SCENE_6, EventBranchId::BRANCH_3); + HaMetaMessage message = HaMetaMessage(EventSceneId::SCENE_9, EventBranchId::BRANCH_1); ffrt::task_handle handler = notificationSubQueue_->submit_h(std::bind([this, &subscriber, &subscribeInfo, &result]() { ANS_LOGE("ffrt enter!"); @@ -136,8 +144,11 @@ ErrCode NotificationSubscriberManager::RemoveSubscriber( })); notificationSubQueue_->wait(handler); std::string appUserId = (subscribeInfo == nullptr) ? "all" : std::to_string(subscribeInfo->GetAppUserId()); - message.Message("Remove subscriber: " + GetClientBundleName() + " user " + - appUserId + " " + std::to_string(result)); + + ANS_LOGI("Des_%{public}s_, user: %{public}s, Remove subscriber result: %{public}d", GetClientBundleName().c_str(), + appUserId.c_str(), result); + message.Message("Des_" + GetClientBundleName() + "_" + " user:" + appUserId); + message.ErrorCode(result); NotificationAnalyticsUtil::ReportModifyEvent(message); return result; } -- Gitee From ab5fe1acac0a0d9b1344b94c2716e7980336b3f5 Mon Sep 17 00:00:00 2001 From: z30053788 Date: Wed, 6 Nov 2024 17:59:27 +0800 Subject: [PATCH 123/167] tdd Signed-off-by: z30053788 Change-Id: Iedf777e5198817db745c44686cb8c4a37f5c43e7 --- .../notification_bundle_option_test.cpp | 2 +- ...nced_notification_service_publish_test.cpp | 35 ------------------- .../notification_preferences_test.cpp | 2 +- 3 files changed, 2 insertions(+), 37 deletions(-) diff --git a/frameworks/ans/test/unittest/notification_bundle_option_test.cpp b/frameworks/ans/test/unittest/notification_bundle_option_test.cpp index 2d1a0577b..83089557f 100644 --- a/frameworks/ans/test/unittest/notification_bundle_option_test.cpp +++ b/frameworks/ans/test/unittest/notification_bundle_option_test.cpp @@ -75,7 +75,7 @@ HWTEST_F(NotificationBundleOptionTest, Dump_00001, Function | SmallTest | Level1 std::string bundleName = "BundleName"; int32_t uid = 10; auto rrc = std::make_shared(bundleName, uid); - std::string ret = "NotificationBundleOption{ bundleName = BundleName, uid = 10, instanceKey = 0 }"; + std::string ret = "NotificationBundleOption{ bundleName = BundleName, uid = 10, instanceKey = 0, appIndex = -1 }"; EXPECT_EQ(rrc->Dump(), ret); } diff --git a/services/ans/test/unittest/advanced_notification_service_test/advanced_notification_service_publish_test.cpp b/services/ans/test/unittest/advanced_notification_service_test/advanced_notification_service_publish_test.cpp index 579654395..7e53f8932 100644 --- a/services/ans/test/unittest/advanced_notification_service_test/advanced_notification_service_publish_test.cpp +++ b/services/ans/test/unittest/advanced_notification_service_test/advanced_notification_service_publish_test.cpp @@ -217,41 +217,6 @@ HWTEST_F(AdvancedNotificationServiceTest, AdvancedNotificationServiceTest_00100, SleepForFC(); } -/** - * @tc.number : ANS_Publish_Update_Flow_00100 - * @tc.name : ANSPublish00100 - * @tc.desc : Publish a normal text type notification 30 times,trigger flow. - */ -HWTEST_F(AdvancedNotificationServiceTest, AdvancedNotificationServiceUpdateFlowTest_00100, Function | SmallTest | Level1) -{ - TestAddSlot(NotificationConstant::SlotType::OTHER); - MockGetTokenTypeFlag(Security::AccessToken::ATokenTypeEnum::TOKEN_HAP); - MockIsSystemApp(true); - sptr req = new NotificationRequest(1); - EXPECT_NE(req, nullptr); - req->SetSlotType(NotificationConstant::SlotType::OTHER); - req->SetLabel("req's label update flow"); - req->SetCreatorUid(1); - std::string label = "publish's label"; - std::shared_ptr normalContent = std::make_shared(); - EXPECT_NE(normalContent, nullptr); - normalContent->SetText("normalContent's text"); - normalContent->SetTitle("normalContent's title"); - std::shared_ptr content = std::make_shared(normalContent); - EXPECT_NE(content, nullptr); - req->SetContent(content); - int count = 30; - for (uint64_t i = 1; i <= 30; ++i) { - if (i <= 21) { - ASSERT_EQ(advancedNotificationService_->Publish(label, req), (int)ERR_OK); - } else { - ASSERT_EQ(advancedNotificationService_->Publish(label, req), (int)ERR_ANS_OVER_MAX_UPDATE_PERSECOND); - } - } - SleepForFC(); -} - - /** * @tc.number : ANS_Publish_00200 * @tc.name : ANSPublish00200 diff --git a/services/ans/test/unittest/notification_preferences_test.cpp b/services/ans/test/unittest/notification_preferences_test.cpp index 9d3a053cf..3588a96c0 100644 --- a/services/ans/test/unittest/notification_preferences_test.cpp +++ b/services/ans/test/unittest/notification_preferences_test.cpp @@ -1501,7 +1501,7 @@ HWTEST_F(NotificationPreferencesTest, GetDoNotDisturbProfile_0200, TestSize.Leve int32_t userId = 1; sptr profile; auto res = NotificationPreferences::GetInstance()->GetDoNotDisturbProfile(profileId, userId, profile); - ASSERT_EQ(res, ERR_ANS_INVALID_PARAM); + ASSERT_EQ(res, ERR_ANS_NO_PROFILE_TEMPLATE); } /** -- Gitee From 4c5228f186c3f68bcb4cbaaa376ae504b6dabab6 Mon Sep 17 00:00:00 2001 From: wufarong Date: Wed, 6 Nov 2024 17:52:37 +0800 Subject: [PATCH 124/167] =?UTF-8?q?=E9=80=9A=E7=9F=A5=E8=AE=BE=E7=BD=AE?= =?UTF-8?q?=E6=89=93=E7=82=B9=E8=A1=A5=E5=85=85?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: wufarong Change-Id: I230ba062933d406c2592d7c4fcfdf9f98004ff99 --- .../advanced_notification_publish_service.cpp | 30 ++++++++++++------- .../advanced_notification_slot_service.cpp | 4 +-- services/ans/src/notification_preferences.cpp | 20 ++++++------- .../src/notification_subscriber_manager.cpp | 8 ++--- 4 files changed, 34 insertions(+), 28 deletions(-) diff --git a/services/ans/src/advanced_notification_publish_service.cpp b/services/ans/src/advanced_notification_publish_service.cpp index fd3b9435b..f36875460 100644 --- a/services/ans/src/advanced_notification_publish_service.cpp +++ b/services/ans/src/advanced_notification_publish_service.cpp @@ -734,7 +734,7 @@ ErrCode AdvancedNotificationService::SetShowBadgeEnabledForBundle( } HaMetaMessage message = HaMetaMessage(EventSceneId::SCENE_8, EventBranchId::BRANCH_3); - message.Message("Des_" + bundleOption->GetBundleName() + "_" + std::to_string(bundleOption->GetUid()) + + message.Message(bundleOption->GetBundleName() + "_" + std::to_string(bundleOption->GetUid()) + " enabled:" + std::to_string(enabled)); bool isSubsystem = AccessTokenHelper::VerifyNativeToken(IPCSkeleton::GetCallingTokenID()); @@ -772,7 +772,7 @@ ErrCode AdvancedNotificationService::SetShowBadgeEnabledForBundle( } })); notificationSvrQueue_->wait(handler); - ANS_LOGI("Des_%{public}s_%{public}d, enabled: %{public}s, Set show badge enabled for bundle result: %{public}d", + ANS_LOGI("%{public}s_%{public}d, enabled: %{public}s, Set show badge enabled for bundle result: %{public}d", bundleOption->GetBundleName().c_str(), bundleOption->GetUid(), std::to_string(enabled).c_str(), result); message.ErrorCode(result); NotificationAnalyticsUtil::ReportModifyEvent(message); @@ -875,7 +875,7 @@ ErrCode AdvancedNotificationService::RequestEnableNotification(const std::string // To get the permission bool allowedNotify = false; HaMetaMessage message = HaMetaMessage(EventSceneId::SCENE_8, EventBranchId::BRANCH_5); - message.Message("Des_" + bundleOption->GetBundleName() + "_" + std::to_string(bundleOption->GetUid()) + + message.Message(bundleOption->GetBundleName() + "_" + std::to_string(bundleOption->GetUid()) + " deviceId:" + deviceId); result = IsAllowedNotifySelf(bundleOption, allowedNotify); if (result != ERR_OK) { @@ -919,7 +919,7 @@ ErrCode AdvancedNotificationService::RequestEnableNotification(const std::string result = ERR_ANS_DIALOG_POP_SUCCEEDED; } - ANS_LOGI("Des_%{public}s_%{public}d, deviceId: %{public}s, Request enable notification dailog result: %{public}d", + ANS_LOGI("%{public}s_%{public}d, deviceId: %{public}s, Request enable notification dailog result: %{public}d", bundleOption->GetBundleName().c_str(), bundleOption->GetUid(), deviceId.c_str(), result); message.ErrorCode(result); NotificationAnalyticsUtil::ReportModifyEvent(message); @@ -979,7 +979,7 @@ ErrCode AdvancedNotificationService::SetNotificationsEnabledForSpecialBundle( } HaMetaMessage message = HaMetaMessage(EventSceneId::SCENE_8, EventBranchId::BRANCH_4); - message.Message("Des_" + bundleOption->GetBundleName() + "_" + std::to_string(bundleOption->GetUid()) + + message.Message(bundleOption->GetBundleName() + "_" + std::to_string(bundleOption->GetUid()) + " enabled:" + std::to_string(enabled) + " deviceId:" + deviceId); bool isSubsystem = AccessTokenHelper::VerifyNativeToken(IPCSkeleton::GetCallingTokenID()); @@ -1029,7 +1029,7 @@ ErrCode AdvancedNotificationService::SetNotificationsEnabledForSpecialBundle( // Remote device } - ANS_LOGI("Des_%{public}s_%{public}d, deviceId: %{public}s, enable: %{public}s, " + ANS_LOGI("%{public}s_%{public}d, deviceId: %{public}s, enable: %{public}s, " "Set notifications enabled for special bundle result: %{public}d", bundleOption->GetBundleName().c_str(), bundleOption->GetUid(), deviceId.c_str(), std::to_string(enabled).c_str(), result); message.ErrorCode(result); @@ -1096,7 +1096,7 @@ ErrCode AdvancedNotificationService::CanPopEnableNotificationDialog( // To get the permission bool allowedNotify = false; HaMetaMessage message = HaMetaMessage(EventSceneId::SCENE_2, EventBranchId::BRANCH_2); - message.Message("Des_" + bundleOption->GetBundleName() + "_" + std::to_string(bundleOption->GetUid()) + + message.Message(bundleOption->GetBundleName() + "_" + std::to_string(bundleOption->GetUid()) + " canPop:" + std::to_string(canPop)); result = IsAllowedNotifySelf(bundleOption, allowedNotify); if (result != ERR_OK) { @@ -1143,7 +1143,7 @@ ErrCode AdvancedNotificationService::CanPopEnableNotificationDialog( canPop = true; bundleName = bundleOption->GetBundleName(); - ANS_LOGI("Des_%{public}s_%{public}d, canPop: %{public}s, CanPopEnableNotificationDialog result: %{public}d", + ANS_LOGI("%{public}s_%{public}d, canPop: %{public}s, CanPopEnableNotificationDialog result: %{public}d", bundleOption->GetBundleName().c_str(), bundleOption->GetUid(), std::to_string(canPop).c_str(), result); message.ErrorCode(result).Append(" CanPopEnableNotificationDialog end"); NotificationAnalyticsUtil::ReportModifyEvent(message); @@ -2194,6 +2194,10 @@ ErrCode AdvancedNotificationService::SetEnabledForBundleSlot(const sptrGetBundleName() + "_" +std::to_string(bundleOption->GetUid()) + + " slotType: " + std::to_string(static_cast(slotType)) + + " enabled: " +std::to_string(enabled) + "isForceControl" + std::to_string(isForceControl)); result = ERR_OK; ffrt::task_handle handler = notificationSvrQueue_->submit_h(std::bind([&]() { sptr slot; @@ -2253,6 +2257,10 @@ ErrCode AdvancedNotificationService::SetEnabledForBundleSlot(const sptrwait(handler); + message.ErrorCode(result); + NotificationAnalyticsUtil::ReportModifyEvent(message); + ANS_LOGI("%{public}s_%{public}d, SetEnabledForBundleSlot successful.", + bundleOption->GetBundleName().c_str(), bundleOption->GetUid()); SendEnableNotificationSlotHiSysEvent(bundleOption, slotType, enabled, result); return result; } @@ -2472,7 +2480,7 @@ ErrCode AdvancedNotificationService::SetBadgeNumberByBundle( return ERR_ANS_INVALID_PARAM; } HaMetaMessage message = HaMetaMessage(EventSceneId::SCENE_7, EventBranchId::BRANCH_6); - message.Message("Des_" + bundleOption->GetBundleName() + "_" +std::to_string(bundleOption->GetUid()) + + message.Message(bundleOption->GetBundleName() + "_" +std::to_string(bundleOption->GetUid()) + " badgeNumber: " + std::to_string(badgeNumber)); if (notificationSvrQueue_ == nullptr) { return ERR_ANS_INVALID_PARAM; @@ -2575,7 +2583,7 @@ ErrCode AdvancedNotificationService::SetDistributedEnabledByBundle(const sptrGetBundleName() + "_" + std::to_string(bundleOption->GetUid()) + + message.Message(bundleOption->GetBundleName() + "_" + std::to_string(bundleOption->GetUid()) + " enabled:" + std::to_string(enabled) + " deviceType:" + deviceType); bool isSubsystem = AccessTokenHelper::VerifyNativeToken(IPCSkeleton::GetCallingTokenID()); @@ -2601,7 +2609,7 @@ ErrCode AdvancedNotificationService::SetDistributedEnabledByBundle(const sptrSetDistributedEnabledByBundle(bundle, deviceType, enabled); - ANS_LOGI("Des_%{public}s_%{public}d, deviceType: %{public}s, enabled: %{public}s, " + ANS_LOGI("%{public}s_%{public}d, deviceType: %{public}s, enabled: %{public}s, " "SetDistributedEnabledByBundle result: %{public}d", bundleOption->GetBundleName().c_str(), bundleOption->GetUid(), deviceType.c_str(), std::to_string(enabled).c_str(), result); message.ErrorCode(result); diff --git a/services/ans/src/advanced_notification_slot_service.cpp b/services/ans/src/advanced_notification_slot_service.cpp index 3a684e88e..afc71a191 100644 --- a/services/ans/src/advanced_notification_slot_service.cpp +++ b/services/ans/src/advanced_notification_slot_service.cpp @@ -417,7 +417,7 @@ ErrCode AdvancedNotificationService::SetSlotFlagsAsBundle(const sptrGetBundleName() + "_" + std::to_string(bundleOption->GetUid()) + + message.Message(bundleOption->GetBundleName() + "_" + std::to_string(bundleOption->GetUid()) + " slotFlags:" + std::to_string(slotFlags)); bool isSubsystem = AccessTokenHelper::VerifyNativeToken(IPCSkeleton::GetCallingTokenID()); if (!isSubsystem && !AccessTokenHelper::IsSystemApp()) { @@ -455,7 +455,7 @@ ErrCode AdvancedNotificationService::SetSlotFlagsAsBundle(const sptrwait(handler); - ANS_LOGI("Des_%{public}s_%{public}d, slotFlags: %{public}d, SetSlotFlagsAsBundle result: %{public}d", + ANS_LOGI("%{public}s_%{public}d, slotFlags: %{public}d, SetSlotFlagsAsBundle result: %{public}d", bundleOption->GetBundleName().c_str(), bundleOption->GetUid(), slotFlags, result); message.ErrorCode(result); NotificationAnalyticsUtil::ReportModifyEvent(message); diff --git a/services/ans/src/notification_preferences.cpp b/services/ans/src/notification_preferences.cpp index 567282aab..fbd23fde0 100644 --- a/services/ans/src/notification_preferences.cpp +++ b/services/ans/src/notification_preferences.cpp @@ -67,7 +67,7 @@ ErrCode NotificationPreferences::AddNotificationSlots( { HITRACE_METER_NAME(HITRACE_TAG_NOTIFICATION, __PRETTY_FUNCTION__); ANS_LOGD("%{public}s", __FUNCTION__); - HaMetaMessage message = HaMetaMessage(EventSceneId::SCENE_5, EventBranchId::BRANCH_1) + HaMetaMessage message = HaMetaMessage(EventSceneId::SCENE_5, EventBranchId::BRANCH_6) .BundleName(bundleOption == nullptr ? "" : bundleOption->GetBundleName()); if (bundleOption == nullptr || bundleOption->GetBundleName().empty() || slots.empty()) { message.Message("Invalid param."); @@ -125,8 +125,8 @@ ErrCode NotificationPreferences::RemoveNotificationSlot( if (bundleOption == nullptr || bundleOption->GetBundleName().empty()) { return ERR_ANS_INVALID_PARAM; } - HaMetaMessage message = HaMetaMessage(EventSceneId::SCENE_5, EventBranchId::BRANCH_1); - message.Message("Des_" + bundleOption->GetBundleName() + "_" +std::to_string(bundleOption->GetUid()) + + HaMetaMessage message = HaMetaMessage(EventSceneId::SCENE_5, EventBranchId::BRANCH_5); + message.Message(bundleOption->GetBundleName() + "_" +std::to_string(bundleOption->GetUid()) + " slotType: " + std::to_string(static_cast(slotType))); message.SlotType(static_cast(slotType)); std::lock_guard lock(preferenceMutex_); @@ -137,7 +137,7 @@ ErrCode NotificationPreferences::RemoveNotificationSlot( (!preferncesDB_->RemoveSlotFromDisturbeDB(GenerateBundleKey(bundleOption), slotType, bundleOption->GetUid()))) { message.ErrorCode(result).Append(" Remove slot failed."); NotificationAnalyticsUtil::ReportModifyEvent(message); - ANS_LOGE("Des_%{public}s_%{public}d, remove slot failed.", + ANS_LOGE("%{public}s_%{public}d, remove slot failed.", bundleOption->GetBundleName().c_str(), bundleOption->GetUid()); return ERR_ANS_PREFERENCES_NOTIFICATION_DB_OPERATION_FAILED; } @@ -145,9 +145,7 @@ ErrCode NotificationPreferences::RemoveNotificationSlot( if (result == ERR_OK) { preferencesInfo_ = preferencesInfo; } - message.ErrorCode(result).Append(" Remove slot successful."); - NotificationAnalyticsUtil::ReportModifyEvent(message); - ANS_LOGI("Des_%{public}s_%{public}d, Remove slot successful.", + ANS_LOGI("%{public}s_%{public}d, Remove slot successful.", bundleOption->GetBundleName().c_str(), bundleOption->GetUid()); return result; } @@ -159,7 +157,7 @@ ErrCode NotificationPreferences::RemoveNotificationAllSlots(const sptrGetBundleName() + "_" +std::to_string(bundleOption->GetUid())); + message.Message(bundleOption->GetBundleName() + "_" +std::to_string(bundleOption->GetUid())); std::lock_guard lock(preferenceMutex_); NotificationPreferencesInfo preferencesInfo = preferencesInfo_; ErrCode result = ERR_OK; @@ -170,20 +168,20 @@ ErrCode NotificationPreferences::RemoveNotificationAllSlots(const sptrRemoveAllSlotsFromDisturbeDB(GenerateBundleKey(bundleOption), bundleOption->GetUid())) { result = ERR_ANS_PREFERENCES_NOTIFICATION_DB_OPERATION_FAILED; message.ErrorCode(result).Append(" Db operation failed."); - ANS_LOGE("Des_%{public}s_%{public}d, Db operation failed.", + ANS_LOGE("%{public}s_%{public}d, Db operation failed.", bundleOption->GetBundleName().c_str(), bundleOption->GetUid()); } } else { result = ERR_ANS_PREFERENCES_NOTIFICATION_BUNDLE_NOT_EXIST; message.ErrorCode(result).Append(" Notification bundle not exist."); - ANS_LOGE("Des_%{public}s_%{public}d, Notification bundle not exist.", + ANS_LOGE("%{public}s_%{public}d, Notification bundle not exist.", bundleOption->GetBundleName().c_str(), bundleOption->GetUid()); } if (result == ERR_OK) { preferencesInfo_ = preferencesInfo; message.ErrorCode(result).Append(" Remove all slot successful."); - ANS_LOGI("Des_%{public}s_%{public}d, Remove all slot successful.", + ANS_LOGI("%{public}s_%{public}d, Remove all slot successful.", bundleOption->GetBundleName().c_str(), bundleOption->GetUid()); } NotificationAnalyticsUtil::ReportModifyEvent(message); diff --git a/services/ans/src/notification_subscriber_manager.cpp b/services/ans/src/notification_subscriber_manager.cpp index 52d1ffe26..88a4201db 100644 --- a/services/ans/src/notification_subscriber_manager.cpp +++ b/services/ans/src/notification_subscriber_manager.cpp @@ -90,7 +90,7 @@ ErrCode NotificationSubscriberManager::AddSubscriber( } HaMetaMessage message = HaMetaMessage(EventSceneId::SCENE_9, EventBranchId::BRANCH_2); - message.Message("Des_" + GetClientBundleName() + "_" + + message.Message(GetClientBundleName() + "_" + " user:" + std::to_string(subInfo->GetAppUserId())); if (subInfo->GetAppUserId() == SUBSCRIBE_USER_INIT) { int32_t userId = SUBSCRIBE_USER_INIT; @@ -115,7 +115,7 @@ ErrCode NotificationSubscriberManager::AddSubscriber( })); notificationSubQueue_->wait(handler); - ANS_LOGI("Des_%{public}s_, user: %{public}s, Add subscriber result: %{public}d", GetClientBundleName().c_str(), + ANS_LOGI("%{public}s_, user: %{public}s, Add subscriber result: %{public}d", GetClientBundleName().c_str(), std::to_string(subInfo->GetAppUserId()).c_str(), result); message.ErrorCode(result); NotificationAnalyticsUtil::ReportModifyEvent(message); @@ -145,9 +145,9 @@ ErrCode NotificationSubscriberManager::RemoveSubscriber( notificationSubQueue_->wait(handler); std::string appUserId = (subscribeInfo == nullptr) ? "all" : std::to_string(subscribeInfo->GetAppUserId()); - ANS_LOGI("Des_%{public}s_, user: %{public}s, Remove subscriber result: %{public}d", GetClientBundleName().c_str(), + ANS_LOGI("%{public}s_, user: %{public}s, Remove subscriber result: %{public}d", GetClientBundleName().c_str(), appUserId.c_str(), result); - message.Message("Des_" + GetClientBundleName() + "_" + " user:" + appUserId); + message.Message(GetClientBundleName() + "_" + " user:" + appUserId); message.ErrorCode(result); NotificationAnalyticsUtil::ReportModifyEvent(message); return result; -- Gitee From 3f3731079c7de06bca2bfe3f208aa3a37157786e Mon Sep 17 00:00:00 2001 From: Ricky Date: Fri, 8 Nov 2024 18:07:26 +0800 Subject: [PATCH 125/167] refactor subscriber logic Signed-off-by: Ricky Change-Id: I73e78a09a61160556170fa44fae30c8796955281 --- frameworks/js/napi/src/subscribe.cpp | 39 ++++++++++++++++++++++++++++ 1 file changed, 39 insertions(+) diff --git a/frameworks/js/napi/src/subscribe.cpp b/frameworks/js/napi/src/subscribe.cpp index 4908ff874..7cc8e4b65 100644 --- a/frameworks/js/napi/src/subscribe.cpp +++ b/frameworks/js/napi/src/subscribe.cpp @@ -15,6 +15,8 @@ #include "subscribe.h" #include "ans_inner_errors.h" +#include "inner_event.h" +#include "out/rk3568/obj/third_party/musl/intermidiates/linux/musl_src_ported/include/unistd.h" #include #include @@ -22,6 +24,8 @@ namespace OHOS { namespace NotificationNapi { const int32_t SUBSRIBE_MAX_PARA = 3; const int32_t NO_DELETE_REASON = -1; +const int64_t MAX_PERIOD_MILLISECONDS = 3; + const std::string CONSUME = "onConsume"; const std::string CANCEL = "onCancel"; const std::string UPDATE = "onUpdate"; @@ -1161,6 +1165,16 @@ void SubscriberInstance::SetCallbackInfo(const std::string &type, const napi_env } } +int64_t GetNowSysTime() +{ + AppExecFwk::InnerEvent::TimePoint nowSys = AppExecFwk::InnerEvent::Clock::now(); + auto epoch = nowSys.time_since_epoch(); + auto value = std::chrono::duration_cast(epoch); + int64_t duration = value.count(); + + return duration; +} + bool HasNotificationSubscriber(const napi_env &env, const napi_value &value, SubscriberInstancesInfo &subscriberInfo) { std::lock_guard lock(mutex_); @@ -1523,6 +1537,31 @@ napi_value ParseParameters(const napi_env &env, const napi_callback_info &info, return nullptr; } + int64_t begin = GetNowSysTime(); + bool timeout = true; + while (GetNowSysTime() - begin < MAX_PERIOD_MILLISECONDS) { + SubscriberInstancesInfo info; + if (!HasNotificationSubscriber(env, argv[PARAM0], info)) { + timeout = false; + break; + } + if (info.subscriber == nullptr) { + timeout = false; + break; + } + std::lock_guard lock(delMutex_); + auto iter = std::find(DeletingSubscriber.begin(), DeletingSubscriber.end(), info.subscriber); + if (iter == DeletingSubscriber.end()) { + timeout = false; + break; + } + usleep(100); + } + if (timeout) { + ANS_LOGE("Wrong subscribe due to subscriber is deleting"); + return nullptr; + } + SubscriberInstancesInfo subscriberInstancesInfo; if (!HasNotificationSubscriber(env, argv[PARAM0], subscriberInstancesInfo)) { if (GetNotificationSubscriber(env, argv[PARAM0], subscriberInstancesInfo) == nullptr) { -- Gitee From 8617555056b9cf2741380d86dcff40482b457f69 Mon Sep 17 00:00:00 2001 From: xdongs Date: Wed, 6 Nov 2024 10:21:06 +0800 Subject: [PATCH 126/167] conflict resolve Signed-off-by: xdongs --- .../AppScope/app.json | 4 +- .../entry/src/main/ets/common/constant.ets | 4 ++ .../entry/src/main/ets/common/utils.ets | 21 +++++++++++ .../src/main/ets/pages/notificationDialog.ets | 37 +++++++++++++------ 4 files changed, 53 insertions(+), 13 deletions(-) diff --git a/services/dialog_ui/enable_notification_dialog/AppScope/app.json b/services/dialog_ui/enable_notification_dialog/AppScope/app.json index ed9af7643..7ec9e0367 100644 --- a/services/dialog_ui/enable_notification_dialog/AppScope/app.json +++ b/services/dialog_ui/enable_notification_dialog/AppScope/app.json @@ -2,8 +2,8 @@ "app": { "bundleName": "com.ohos.notificationdialog", "vendor": "example", - "versionCode": 1000011, - "versionName": "1.1.1", + "versionCode": 1000013, + "versionName": "1.1.3", "icon": "$media:app_icon", "label": "$string:app_name", "distributedNotificationEnabled": true, diff --git a/services/dialog_ui/enable_notification_dialog/entry/src/main/ets/common/constant.ets b/services/dialog_ui/enable_notification_dialog/entry/src/main/ets/common/constant.ets index a1f3d2be6..d70ee5183 100644 --- a/services/dialog_ui/enable_notification_dialog/entry/src/main/ets/common/constant.ets +++ b/services/dialog_ui/enable_notification_dialog/entry/src/main/ets/common/constant.ets @@ -142,6 +142,10 @@ export default class Constants { static DIALOG_PRIVACY_BORDER_RADIUS = 32; static DIALOG_PADDING_BOTTOM = 16; + public static TITLE_MIN_FONT_SIZE = 16; + public static CROSS_LINE_RATIO = 0.2; + public static CROSS_LINE_RESIZE_PARAM = 1.25; + // ccm config path static CCM_CONFIG_PATH = "etc/notification/notification_config.json"; } diff --git a/services/dialog_ui/enable_notification_dialog/entry/src/main/ets/common/utils.ets b/services/dialog_ui/enable_notification_dialog/entry/src/main/ets/common/utils.ets index 766156628..c98e8dffd 100644 --- a/services/dialog_ui/enable_notification_dialog/entry/src/main/ets/common/utils.ets +++ b/services/dialog_ui/enable_notification_dialog/entry/src/main/ets/common/utils.ets @@ -14,6 +14,8 @@ */ import Constants from './constant'; +import { MeasureOptions } from '@ohos.measure'; +import { MeasureUtils } from '@ohos.arkui.UIContext'; /** * Omit display when application name is too long @@ -29,3 +31,22 @@ export function titleTrim(title: string): string { return title; } } + +export function calContainerWidth( + containerWidth: number, + options: MeasureOptions, + crossLineRatio: number, + measureUtils: MeasureUtils) : string | number { + let targetContainerWidth: string | number = 'auto'; + try { + let textWidth = px2vp(measureUtils.measureText(options)); + let ratio = (textWidth % containerWidth) / containerWidth; + let crossLineFlag: boolean = textWidth > containerWidth; + if (crossLineFlag && ratio < crossLineRatio) { + targetContainerWidth = containerWidth / Constants.CROSS_LINE_RESIZE_PARAM; + } + } catch (err) { + console.error(`refresh width failed, code=${err?.code0}, msg=${err?.message}.`); + } + return targetContainerWidth; + } diff --git a/services/dialog_ui/enable_notification_dialog/entry/src/main/ets/pages/notificationDialog.ets b/services/dialog_ui/enable_notification_dialog/entry/src/main/ets/pages/notificationDialog.ets index 19f87f2c3..d671daff0 100644 --- a/services/dialog_ui/enable_notification_dialog/entry/src/main/ets/pages/notificationDialog.ets +++ b/services/dialog_ui/enable_notification_dialog/entry/src/main/ets/pages/notificationDialog.ets @@ -16,13 +16,15 @@ import bundleResourceManager from '@ohos.bundle.bundleResourceManager'; import display from '@ohos.display'; import window from '@ohos.window'; -import { titleTrim } from '../common/utils'; +import { titleTrim, calContainerWidth } from '../common/utils'; import Constants from '../common/constant'; import fs from '@ohos.file.fs'; import configPolicy from '@ohos.configPolicy'; import { EnableNotificationDialog } from '../ServiceExtAbility/NotificationServiceExtAbility'; import { Callback} from '@ohos.base'; import UIExtensionContentSession from '@ohos.app.ability.UIExtensionContentSession'; +import { MeasureOptions } from '@ohos.measure'; +import { MeasureUtils } from '@ohos.arkui.UIContext'; const TAG = 'NotificationDialog_Service '; const permission: Record = { @@ -90,6 +92,7 @@ struct PermissionDialog { dialog?: EnableNotificationDialog; session?: UIExtensionContentSession; controller?: CustomDialogController; + @State titleContainerWidth: string|number = 'auto'; build() { GridRow({ columns: { xs: Constants.XS_COLUMNS, sm: Constants.SM_COLUMNS, md: Constants.MD_COLUMNS, lg: Constants.LG_COLUMNS }, gutter: Constants.DIALOG_GUTTER }) { @@ -109,23 +112,35 @@ struct PermissionDialog { } Row() { Flex({ justifyContent: FlexAlign.Center }) { - Text() { - Span(getContext(this).resourceManager.getStringSync(permission.label.id).replace('%s', this.appName)) - } + Text($r('app.string.group_label_notification', this.appName)) .fontSize($r('sys.float.ohos_id_text_size_headline8')) .fontColor($r('app.color.text_primary')) .fontWeight(FontWeight.Bold) - .lineHeight(Constants.DIALOG_REQ_LINE_HEIGHT) + .minFontSize(Constants.TITLE_MIN_FONT_SIZE) + .maxFontSize($r('sys.float.ohos_id_text_size_headline8')) + .heightAdaptivePolicy(TextHeightAdaptivePolicy.MAX_LINES_FIRST) .maxLines(2) .textOverflow({overflow: TextOverflow.Ellipsis}) - .margin({ - top: Constants.DIALOG_REQ_MARGIN_TOP, - bottom:Constants.DIALOG_REQ_MARGIN_BUTTOM, - left: Constants.DIALOG_REQ_MARGIN_LEFT, - right: Constants.DIALOG_REQ_MARGIN_RIGHT - }) + .width(this.titleContainerWidth) .textAlign(TextAlign.Center) } + .margin({ + top: Constants.DIALOG_REQ_MARGIN_TOP, + bottom:Constants.DIALOG_REQ_MARGIN_BUTTOM, + left: Constants.DIALOG_REQ_MARGIN_LEFT, + right: Constants.DIALOG_REQ_MARGIN_RIGHT + }) + .onSizeChange((oldValue: SizeOptions, newValue: SizeOptions) => { + let containerWidth = newValue.width as number; + let options: MeasureOptions = { + textContent: $r('app.string.group_label_notification', this.appName), + fontSize: $r('sys.float.ohos_id_text_size_headline8'), + fontWeight: FontWeight.Bold, + }; + this.titleContainerWidth = calContainerWidth(containerWidth, options, + Constants.CROSS_LINE_RATIO, this.getUIContext().getMeasureUtils()); + console.info(TAG, `onSizeChange titleContainerWidth: ${this.titleContainerWidth}`); + }) } Row() { Flex({ justifyContent: FlexAlign.Center }) { -- Gitee From 92778980b5f032d32aec7b5f7ce8a55cb96a1527 Mon Sep 17 00:00:00 2001 From: xdongs Date: Sat, 9 Nov 2024 10:24:32 +0800 Subject: [PATCH 127/167] add pc Signed-off-by: xdongs --- .../NotificationServiceExtAbility.ts | 62 ++-- .../entry/src/main/ets/common/constant.ets | 21 ++ .../main/ets/pages/pcNotificationDialog.ets | 310 ++++++++++++++++++ .../resources/base/profile/main_pages.json | 3 +- 4 files changed, 367 insertions(+), 29 deletions(-) create mode 100644 services/dialog_ui/enable_notification_dialog/entry/src/main/ets/pages/pcNotificationDialog.ets diff --git a/services/dialog_ui/enable_notification_dialog/entry/src/main/ets/ServiceExtAbility/NotificationServiceExtAbility.ts b/services/dialog_ui/enable_notification_dialog/entry/src/main/ets/ServiceExtAbility/NotificationServiceExtAbility.ts index d5648094f..115db53c9 100644 --- a/services/dialog_ui/enable_notification_dialog/entry/src/main/ets/ServiceExtAbility/NotificationServiceExtAbility.ts +++ b/services/dialog_ui/enable_notification_dialog/entry/src/main/ets/ServiceExtAbility/NotificationServiceExtAbility.ts @@ -71,12 +71,14 @@ interface NotificationConfig { interface DeviceInfo { isWatch: boolean; + isPc: boolean; } export class EnableNotificationDialog { static ENABLE_NOTIFICATION_DIALOG_NAME = 'EnableNotificationDialog'; static DIALOG_PATH = 'pages/notificationDialog'; static WATCH_DIALOG_PATH = 'pages/watchNotificationDialog'; + static PC_DIALOG_PATH = 'pages/pcNotificationDialog'; static TRANSPARANT_COLOR = '#00000000'; static SCENEBOARD_BUNDLE = 'com.ohos.sceneboard'; static SYSTEMUI_BUNDLE = 'com.ohos.systemui'; @@ -128,6 +130,10 @@ export class EnableNotificationDialog { path = EnableNotificationDialog.WATCH_DIALOG_PATH; console.info(TAG, 'watch request'); } + if (deviceInfo.isPc !== undefined) { + path = EnableNotificationDialog.PC_DIALOG_PATH; + console.info(TAG, 'pc request'); + } } } } @@ -290,7 +296,7 @@ class NotificationDialogServiceExtensionAbility extends UIExtensionAbility { } } - async onDestroy() { + async onDestroy(): Promise { console.info(TAG, 'UIExtAbility onDestroy.'); await this.unsubscribe(); await this.sleep(500); @@ -301,46 +307,46 @@ class NotificationDialogServiceExtensionAbility extends UIExtensionAbility { return new Promise(resolve => setTimeout(resolve, ms)); } - async subscribe() { - CommonEventManager.createSubscriber( - { events: ['usual.event.BUNDLE_RESOURCES_CHANGED'] }, (err, subscriber) => { + async subscribe(): Promise { + await CommonEventManager.createSubscriber( + { events: ['usual.event.BUNDLE_RESOURCES_CHANGED'] }) + .then((subscriber:CommonEventManager.CommonEventSubscriber) => { + eventSubscriber = subscriber; + }) + .catch((err) => { + console.log(TAG, `subscriber createSubscriber error code is ${err.code}, message is ${err.message}`); + }); + + if (eventSubscriber === null) { + console.log(TAG, 'need create subscriber'); + return; + } + CommonEventManager.subscribe(eventSubscriber, (err, data) => { if (err?.code) { - console.error(TAG, `createSubscriber callBack err = ${JSON.stringify(err)}`); + console.error(TAG, `subscribe callBack err= ${JSON.stringify(err)}`); } else { - eventSubscriber = subscriber; - console.log(TAG, "create subscriber succeed"); - if (eventSubscriber != null) { - console.log(TAG, "subscriber subscribe BUNDLE_RESOURCES_CHANGED event"); - CommonEventManager.subscribe(eventSubscriber, (err, data) => { - if (err?.code) { - console.error(TAG, `subscribe callBack err= ${JSON.stringify(err)}`); - } else { - console.log(TAG, `subscribe callBack data= ${JSON.stringify(data)}`); - if(data.parameters?.bundleResourceChangeType == 1){ - console.log(TAG, `BUNDLE_RESOURCES_CHANGED-language change`); - let isUpdate:number = AppStorage.get('isUpdate'); - if (isUpdate === undefined || isUpdate > UPDATE_BOUNDARY) { - AppStorage.setOrCreate('isUpdate', UPDATE_NUM); - } else { - AppStorage.setOrCreate('isUpdate', ++isUpdate); - } - } - } - }) + console.log(TAG, `subscribe callBack data= ${JSON.stringify(data)}`); + if (data.parameters?.bundleResourceChangeType !== 1) { + return; + } + console.log(TAG, `BUNDLE_RESOURCES_CHANGED-language change`); + let isUpdate:number = AppStorage.get('isUpdate'); + if (isUpdate === undefined || isUpdate > UPDATE_BOUNDARY) { + AppStorage.setOrCreate('isUpdate', UPDATE_NUM); } else { - console.info(TAG, "need create subscriber"); + AppStorage.setOrCreate('isUpdate', ++isUpdate); } } }); } - async unsubscribe() { + async unsubscribe(): Promise { try { if (eventSubscriber != null) { CommonEventManager.unsubscribe(eventSubscriber, (err) => {}); } } catch (err) { - console.info("ubsubscribe fail"); + console.info('ubsubscribe fail'); } } } diff --git a/services/dialog_ui/enable_notification_dialog/entry/src/main/ets/common/constant.ets b/services/dialog_ui/enable_notification_dialog/entry/src/main/ets/common/constant.ets index d70ee5183..00133b527 100644 --- a/services/dialog_ui/enable_notification_dialog/entry/src/main/ets/common/constant.ets +++ b/services/dialog_ui/enable_notification_dialog/entry/src/main/ets/common/constant.ets @@ -146,6 +146,27 @@ export default class Constants { public static CROSS_LINE_RATIO = 0.2; public static CROSS_LINE_RESIZE_PARAM = 1.25; + //pc + public static PC_ICON_MARGIN_TOP = 24; + + public static PC_TITLE_MARGIN_TOP = 16; + public static PC_TITLE_MARGIN_SIDE = 24; + + public static PC_CONTENT_MARGIN_TOP = 16; + public static PC_CONTENT_MARGIN_SIDE = 24; + + public static PC_OPERATE_MARGIN_SIDE = 16; + public static PC_OPERATE_MARGIN_TOP = 16; + public static PC_OPERATE_MARGIN_BUTTOM = 16; + + public static PC_DIALOG_WIDTH = 400; + public static PC_BUTTON_HEIGHT = 40; + + public static PC_RDIUS_16 = 16; + public static PC_RDIUS_8 = 8; + + public static PC_OUTLINE_COLOR = '#20FFFFFF'; + // ccm config path static CCM_CONFIG_PATH = "etc/notification/notification_config.json"; } diff --git a/services/dialog_ui/enable_notification_dialog/entry/src/main/ets/pages/pcNotificationDialog.ets b/services/dialog_ui/enable_notification_dialog/entry/src/main/ets/pages/pcNotificationDialog.ets new file mode 100644 index 000000000..afa4c6e2b --- /dev/null +++ b/services/dialog_ui/enable_notification_dialog/entry/src/main/ets/pages/pcNotificationDialog.ets @@ -0,0 +1,310 @@ +/* + * Copyright (c) 2023 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import bundleResourceManager from '@ohos.bundle.bundleResourceManager'; +import display from '@ohos.display'; +import window from '@ohos.window'; +import { titleTrim, calContainerWidth } from '../common/utils'; +import Constants from '../common/constant'; +import fs from '@ohos.file.fs'; +import configPolicy from '@ohos.configPolicy'; +import { EnableNotificationDialog } from '../ServiceExtAbility/NotificationServiceExtAbility'; +import { Callback} from '@ohos.base'; +import UIExtensionContentSession from '@ohos.app.ability.UIExtensionContentSession'; +import i18n from '@ohos.i18n'; +import { MeasureOptions } from '@ohos.measure'; +import { MeasureUtils } from '@ohos.arkui.UIContext'; + +const TAG = 'NotificationDialog_Service '; + +const LAN_EN = 'These may include banners, sounds and more. You can change this in Settings.'; +const LAN_CN = '通知提醒方式可能包括横幅、响铃等。可前往“设置” 更改。'; +const LAN_HK = '通知提醒方式可能包括橫幅、響鬧等。可前往「設定」更改。'; +const LAN_TW = '通知提醒方式可能包括橫幅、響鈴等。可前往「設定」變更。'; +const LAN_BO = 'བརྡ་ཐོ་དྲན་སྐུལ་གྱི་ཐབས་ལམ་ལ་སྒོ་ལྕགས་བརྙན་ཡོལ་དང་། འཕྲེད་བྱང་། དྲིལ་སྒྲ། སྦིར་བརྡ་སོགས་ཚུད་སྲིད། ༼སྒྲིག་འགོད་༽ལ་བསྐྱོད་ནས་བཅོས་ཆོག'; +const LAN_UG = 'قۇلۇپ ئېكرانى، بالداق، ئاۋاز ۋە تىترەش شۇلارنىڭ ئىچىدە. تەڭشەكتىن ئۆزگەرتەلەيسىز.'; + +const permission: Record = { + 'label': $r('app.string.group_label_notification'), + 'icon': $r('app.media.ic_public_ring'), + 'reason': $r('app.string.reason'), +}; + +let storage = LocalStorage.getShared(); + +@Extend(Button) function customizeButton() { + .type(ButtonType.Normal) + .backgroundColor($r('sys.color.comp_background_tertiary')) + .fontColor($r('sys.color.font_emphasize')) + .fontSize($r('sys.float.Body_L')) + .fontWeight(FontWeight.Medium) + .height(Constants.PC_BUTTON_HEIGHT) + .width('50%') + .borderRadius(Constants.PC_RDIUS_8) + .flexGrow(Constants.FLEX_GROW) +} + +@Entry(storage) +@Component +struct NotificationDialogPage { + @StorageLink('isUpdate') isUpdate: number = 0; + + privacyDialogController: CustomDialogController = new CustomDialogController({ + builder: PermissionDialog({ isUpdate: $isUpdate }), + autoCancel: false, + alignment: DialogAlignment.Center, + customStyle: true, + cornerRadius: Constants.PC_RDIUS_16, + maskColor: $r('sys.color.ohos_id_color_mask_thin'), + onWillDismiss: (dismissDialogAction: DismissDialogAction) => { + console.info(TAG, `dialog onWillDismiss reason= : ${JSON.stringify(dismissDialogAction.reason)}`); + } + }); + + build() {} + + aboutToAppear() { + this.privacyDialogController.open(); + } + + onPageShow() { + } +} + +@CustomDialog +struct PermissionDialog { + @State appName: string = ''; + @State content: string = LAN_CN; + @State naviHeight: number = 0; + @State isBottomPopover: boolean = false; + @StorageLink('clicked') clicked: boolean = false; + @Link @Watch('updateOnPageShow') isUpdate: number; + dialog?: EnableNotificationDialog; + session?: UIExtensionContentSession; + controller?: CustomDialogController; + @State titleContainerWidth: string|number = 'auto'; + + build() { + Row() { + Flex({ justifyContent: FlexAlign.Center, alignItems: this.isBottomPopover ? ItemAlign.End : ItemAlign.Center }) { + Column() { + Scroll() { + Column() { + Row() { + Image(permission.icon) + .width(Constants.DIALOG_ICON_WIDTH) + .height(Constants.DIALOG_ICON_HEIGHT) + .margin({ + top: Constants.PC_ICON_MARGIN_TOP + }) + .draggable(false) + } + Row() { + Flex({ justifyContent: FlexAlign.Center }) { + Text($r('app.string.group_label_notification', this.appName)) + .fontSize($r('sys.float.Title_S')) + .fontColor($r('sys.color.font_primary')) + .fontWeight(FontWeight.Bold) + .minFontSize(Constants.TITLE_MIN_FONT_SIZE) + .maxFontSize($r('sys.float.Title_S')) + .heightAdaptivePolicy(TextHeightAdaptivePolicy.MAX_LINES_FIRST) + .maxLines(2) + .textOverflow({overflow: TextOverflow.Ellipsis}) + .width(this.titleContainerWidth) + .textAlign(TextAlign.Center) + } + .margin({ + left: Constants.PC_TITLE_MARGIN_SIDE, + right: Constants.PC_TITLE_MARGIN_SIDE, + top: Constants.PC_TITLE_MARGIN_TOP, + }) + .onSizeChange((oldValue: SizeOptions, newValue: SizeOptions) => { + let containerWidth = newValue.width as number; + let options: MeasureOptions = { + textContent: $r('app.string.group_label_notification', this.appName), + fontSize: $r('sys.float.Title_S'), + fontWeight: FontWeight.Bold, + }; + this.titleContainerWidth = calContainerWidth(containerWidth, options, + Constants.CROSS_LINE_RATIO, this.getUIContext().getMeasureUtils()); + console.info(TAG, `onSizeChange titleContainerWidth: ${this.titleContainerWidth}`); + }) + } + Row() { + Flex({ justifyContent: FlexAlign.Center }) { + Text() { + Span(this.content) + } + .fontSize($r('sys.float.Body_L')) + .fontWeight(FontWeight.Medium) + .fontColor($r('sys.color.font_primary')) + .margin({ + left: Constants.PC_CONTENT_MARGIN_SIDE, + right: Constants.PC_CONTENT_MARGIN_SIDE, + top: Constants.PC_CONTENT_MARGIN_TOP + }) + } + } + Row() { + Flex({ justifyContent: FlexAlign.SpaceBetween, alignItems: ItemAlign.Center }) { + Button($r('app.string.BAN')) + .onClick(async (): Promise => { + await this.enableNotification(false); + }) + .customizeButton() + Divider() + .color($r('sys.color.comp_divider')) + .vertical(true) + .height(Constants.DIVIDER_HEIGHT) + .strokeWidth(Constants.DIVIDER_WIDTH) + .margin({left: Constants.BUTTON_LEFT, right: Constants.BUTTON_RIGHT}) + Button($r('app.string.ALLOW')) + .onClick(async (): Promise => { + await this.enableNotification(true); + }) + .customizeButton() + } + .margin({ + left: Constants.PC_OPERATE_MARGIN_SIDE, + right: Constants.PC_OPERATE_MARGIN_SIDE, + top: Constants.PC_OPERATE_MARGIN_TOP, + bottom: Constants.PC_OPERATE_MARGIN_BUTTOM + }) + } + } + } + .constraintSize({ maxHeight: Constants.MAXIMUM_HEADER_HEIGHT }) + } + .borderRadius(Constants.PC_RDIUS_16) + .backgroundBlurStyle(BlurStyle.COMPONENT_ULTRA_THICK) + .width(Constants.PC_DIALOG_WIDTH) + .outline({ + width: 1, + color: Constants.PC_OUTLINE_COLOR, + radius: Constants.PC_RDIUS_16 + }) + .clip(true) + } + .width(Constants.FULL_WIDTH) + .height(Constants.FULL_HEIGHT) + } + } + + async aboutToAppear(): Promise { + this.dialog = storage.get('dialog') as EnableNotificationDialog; + this.session = storage.get('session') as UIExtensionContentSession; + this.updateAvoidWindow(); + this.updateSubWindowSize(); + try { + await this.updateStatus(); + } catch (err) { + console.error(TAG, `aboutToAppear error : ${err?.code}`); + await this.dialog?.destroyException(); + await this.session?.terminateSelf(); + } + } + + async aboutToDisappear(): Promise { + console.info(TAG, `aboutToDisappear`); + this.session?.terminateSelf(); + } + + async updateOnPageShow(): Promise { + if (this.isUpdate > 0) { + await this.updateStatus(); + } + } + + async updateStatus(): Promise { + let bundleNameObj = this.dialog?.want.parameters?.bundleName; + let bundleName = bundleNameObj ? bundleNameObj.toString() : ''; + await this.updateApplicationName(bundleName); + } + + async updateApplicationName(bundleName: string): Promise { + console.info(TAG, `updateApplicationName bundleName: ${bundleName}`); + try { + let bundleFlags = bundleResourceManager.ResourceFlag.GET_RESOURCE_INFO_ALL; + let resourceInfo = bundleResourceManager.getBundleResourceInfo(bundleName, bundleFlags); + console.info(TAG, `applicationName name : ${JSON.stringify(resourceInfo.label)}`); + let appName = resourceInfo.label; + this.appName = titleTrim(appName); + console.info(TAG, `hap label: ${this.appName}`); + + let systemLanguage: string = i18n.System.getSystemLanguage(); + console.info(TAG, `language: ${systemLanguage}`); + if (systemLanguage.indexOf('zh-Hans') != -1) { + this.content = LAN_CN; + } else if (systemLanguage.indexOf('zh-Hant') != -1) { + this.content = LAN_TW; + } else if (systemLanguage.indexOf('en') != -1) { + this.content = LAN_EN; + } else if (systemLanguage.indexOf('ug') != -1) { + this.content = LAN_UG; + } else if (systemLanguage.indexOf('bo') != -1) { + this.content = LAN_BO; + } + + } catch (err) { + console.error(TAG, `applicationName error : ${err?.code}`); + } + } + + updateAvoidWindow(): void { + let type = window.AvoidAreaType.TYPE_SYSTEM; + try { + this.dialog?.extensionWindow.on('avoidAreaChange', (data): void => { + if (data.type == window.AvoidAreaType.TYPE_SYSTEM) { + console.info(TAG, `avoidAreaChange: ${JSON.stringify(data)}`); + this.naviHeight = data.area.bottomRect.height; + } + }); + let avoidArea = this.dialog?.extensionWindow.getWindowAvoidArea(type); + if (avoidArea != undefined) { + console.info(TAG, `avoidArea: ${JSON.stringify(avoidArea)}`); + this.naviHeight = avoidArea.bottomRect.height; + } + } catch (err) { + console.error(TAG, `Failed to obtain the area. Cause: ${err?.code}`); + } + } + + updateSubWindowSize(): void { + try { + this.dialog?.extensionWindow.on('windowSizeChange', (data):void => { + let windowRect = this.dialog?.extensionWindow.properties?.uiExtensionHostWindowProxyRect; + console.info(TAG, `windowSizeChange event, size = ${windowRect?.left}-${windowRect?.top}-${windowRect?.width}-${windowRect?.height}`); + this.dialog?.subWindow?.moveWindowTo(windowRect?.left, windowRect?.top); + this.dialog?.subWindow?.resize(windowRect?.width, windowRect?.height); + }); + } catch (err) { + console.error(TAG, `updateSubWindowSize error. Cause: ${err?.code}`); + } + } + + async enableNotification(enabled: boolean): Promise { + console.info(TAG, `NotificationDialog enableNotification: ${enabled}`); + try { + await this.dialog?.publishButtonClickedEvent(enabled); + this.clicked = true; + } catch (err) { + console.error(TAG, `NotificationDialog enable error, code is ${err?.code}`); + await this.dialog?.destroyException(); + } finally { + await this.dialog?.subWindow?.destroyWindow(); + this.session?.terminateSelf(); + } + } +} \ No newline at end of file diff --git a/services/dialog_ui/enable_notification_dialog/entry/src/main/resources/base/profile/main_pages.json b/services/dialog_ui/enable_notification_dialog/entry/src/main/resources/base/profile/main_pages.json index 44a0e7536..324b89a25 100644 --- a/services/dialog_ui/enable_notification_dialog/entry/src/main/resources/base/profile/main_pages.json +++ b/services/dialog_ui/enable_notification_dialog/entry/src/main/resources/base/profile/main_pages.json @@ -1,6 +1,7 @@ { "src": [ "pages/notificationDialog", - "pages/watchNotificationDialog" + "pages/watchNotificationDialog", + "pages/pcNotificationDialog" ] } \ No newline at end of file -- Gitee From cf49625042d8361743daaf38e987cde989ce9897 Mon Sep 17 00:00:00 2001 From: xdongs Date: Fri, 8 Nov 2024 18:15:30 +0800 Subject: [PATCH 128/167] update Signed-off-by: z30053788 Change-Id: Ib43eea5466daf01a309608ae5fbbc35551637f61 --- .../dialog_ui/enable_notification_dialog/AppScope/app.json | 4 ++-- .../ets/ServiceExtAbility/NotificationServiceExtAbility.ts | 5 +++-- 2 files changed, 5 insertions(+), 4 deletions(-) diff --git a/services/dialog_ui/enable_notification_dialog/AppScope/app.json b/services/dialog_ui/enable_notification_dialog/AppScope/app.json index ed9af7643..8bea06d5a 100644 --- a/services/dialog_ui/enable_notification_dialog/AppScope/app.json +++ b/services/dialog_ui/enable_notification_dialog/AppScope/app.json @@ -2,8 +2,8 @@ "app": { "bundleName": "com.ohos.notificationdialog", "vendor": "example", - "versionCode": 1000011, - "versionName": "1.1.1", + "versionCode": 1000014, + "versionName": "1.1.4", "icon": "$media:app_icon", "label": "$string:app_name", "distributedNotificationEnabled": true, diff --git a/services/dialog_ui/enable_notification_dialog/entry/src/main/ets/ServiceExtAbility/NotificationServiceExtAbility.ts b/services/dialog_ui/enable_notification_dialog/entry/src/main/ets/ServiceExtAbility/NotificationServiceExtAbility.ts index d5648094f..b9931662d 100644 --- a/services/dialog_ui/enable_notification_dialog/entry/src/main/ets/ServiceExtAbility/NotificationServiceExtAbility.ts +++ b/services/dialog_ui/enable_notification_dialog/entry/src/main/ets/ServiceExtAbility/NotificationServiceExtAbility.ts @@ -144,11 +144,11 @@ export class EnableNotificationDialog { }; let subWindow = await extensionWindow.createSubWindowWithOptions('subWindowForHost' + Date(), subWindowOpts); this.subWindow = subWindow; - let windowRect = extensionWindow.properties?.uiExtensionHostWindowProxyRect; + await subWindow.loadContent(path, this.storage); + let windowRect = extensionWindow.properties?.uiExtensionHostWindowProxyRect; await subWindow.moveWindowTo(windowRect?.left, windowRect?.top); await subWindow.resize(windowRect?.width, windowRect?.height); console.info(TAG, `size : ${windowRect.left} ${windowRect.top} ${windowRect.width} ${windowRect.height}`); - await subWindow.loadContent(path, this.storage); try { await subWindow.hideNonSystemFloatingWindows(true); } catch (err) { @@ -240,6 +240,7 @@ class NotificationDialogServiceExtensionAbility extends UIExtensionAbility { } catch (err) { console.error(TAG, `Failed to handle onSessionCreate`); await handleDialogQuitException(want); + this.context.terminateSelf(); } } -- Gitee From bc137cd60d9158fffdaa1288570c34c0902602e7 Mon Sep 17 00:00:00 2001 From: luojingsong Date: Tue, 12 Nov 2024 21:09:11 +0800 Subject: [PATCH 129/167] =?UTF-8?q?=E6=B2=A1=E6=9C=89uid=E7=9A=84=E9=97=AE?= =?UTF-8?q?=E9=A2=98?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: luojingsong Change-Id: Ibd0bd0c126bcb1a32d163e80740b0dd73cd2d867 --- services/ans/src/advanced_notification_publish_service.cpp | 2 ++ 1 file changed, 2 insertions(+) diff --git a/services/ans/src/advanced_notification_publish_service.cpp b/services/ans/src/advanced_notification_publish_service.cpp index fd3b9435b..3dddc7062 100644 --- a/services/ans/src/advanced_notification_publish_service.cpp +++ b/services/ans/src/advanced_notification_publish_service.cpp @@ -191,6 +191,8 @@ ErrCode AdvancedNotificationService::PublishNotificationForIndirectProxy(const s } std::string bundle = request->GetCreatorBundleName(); int32_t uid = request->GetCreatorUid(); + request->SetOwnerUid(uid); + request->SetOwnerBundleName(bundle); std::shared_ptr record = std::make_shared(); record->request = request; record->bundleOption = new (std::nothrow) NotificationBundleOption(bundle, uid); -- Gitee From 6fe0d86fedb4bc252798376d51b30033dd3d9d72 Mon Sep 17 00:00:00 2001 From: Ricky Date: Wed, 13 Nov 2024 16:46:02 +0800 Subject: [PATCH 130/167] Revert "refactor subscriber logic" This reverts commit 3f3731079c7de06bca2bfe3f208aa3a37157786e. Signed-off-by: Ricky Change-Id: I7c472792f542b5d6325556016e28c1c5eddc3bd1 --- frameworks/js/napi/src/subscribe.cpp | 39 ---------------------------- 1 file changed, 39 deletions(-) diff --git a/frameworks/js/napi/src/subscribe.cpp b/frameworks/js/napi/src/subscribe.cpp index c12657c26..d2e392607 100644 --- a/frameworks/js/napi/src/subscribe.cpp +++ b/frameworks/js/napi/src/subscribe.cpp @@ -15,8 +15,6 @@ #include "subscribe.h" #include "ans_inner_errors.h" -#include "inner_event.h" -#include "out/rk3568/obj/third_party/musl/intermidiates/linux/musl_src_ported/include/unistd.h" #include #include @@ -24,8 +22,6 @@ namespace OHOS { namespace NotificationNapi { const int32_t SUBSRIBE_MAX_PARA = 3; const int32_t NO_DELETE_REASON = -1; -const int64_t MAX_PERIOD_MILLISECONDS = 3; - const std::string CONSUME = "onConsume"; const std::string CANCEL = "onCancel"; const std::string UPDATE = "onUpdate"; @@ -1158,16 +1154,6 @@ void SubscriberInstance::SetCallbackInfo(const std::string &type, const napi_env } } -int64_t GetNowSysTime() -{ - AppExecFwk::InnerEvent::TimePoint nowSys = AppExecFwk::InnerEvent::Clock::now(); - auto epoch = nowSys.time_since_epoch(); - auto value = std::chrono::duration_cast(epoch); - int64_t duration = value.count(); - - return duration; -} - bool HasNotificationSubscriber(const napi_env &env, const napi_value &value, SubscriberInstancesInfo &subscriberInfo) { std::lock_guard lock(mutex_); @@ -1530,31 +1516,6 @@ napi_value ParseParameters(const napi_env &env, const napi_callback_info &info, return nullptr; } - int64_t begin = GetNowSysTime(); - bool timeout = true; - while (GetNowSysTime() - begin < MAX_PERIOD_MILLISECONDS) { - SubscriberInstancesInfo info; - if (!HasNotificationSubscriber(env, argv[PARAM0], info)) { - timeout = false; - break; - } - if (info.subscriber == nullptr) { - timeout = false; - break; - } - std::lock_guard lock(delMutex_); - auto iter = std::find(DeletingSubscriber.begin(), DeletingSubscriber.end(), info.subscriber); - if (iter == DeletingSubscriber.end()) { - timeout = false; - break; - } - usleep(100); - } - if (timeout) { - ANS_LOGE("Wrong subscribe due to subscriber is deleting"); - return nullptr; - } - SubscriberInstancesInfo subscriberInstancesInfo; if (!HasNotificationSubscriber(env, argv[PARAM0], subscriberInstancesInfo)) { if (GetNotificationSubscriber(env, argv[PARAM0], subscriberInstancesInfo) == nullptr) { -- Gitee From 2f9ee604df36a21c29c850ce400a3bd25b37c524 Mon Sep 17 00:00:00 2001 From: Ricky Date: Wed, 13 Nov 2024 10:10:29 +0800 Subject: [PATCH 131/167] fix publish with userId and publish with agent hashCode error issue Signed-off-by: Ricky Change-Id: I8cd51c2b5882ac6c4ed3f6b078162d91135a6ff4 --- .../ans/src/advanced_notification_service.cpp | 25 ++++++++++++++----- 1 file changed, 19 insertions(+), 6 deletions(-) diff --git a/services/ans/src/advanced_notification_service.cpp b/services/ans/src/advanced_notification_service.cpp index a31f9426c..c60ba11d6 100644 --- a/services/ans/src/advanced_notification_service.cpp +++ b/services/ans/src/advanced_notification_service.cpp @@ -206,6 +206,13 @@ ErrCode AdvancedNotificationService::PrepareNotificationRequest(const sptrSetAgentBundle(agentBundle); + } else if (request->GetOwnerUserId() != SUBSCRIBE_USER_INIT) { + int32_t uid = BundleManagerHelper::GetInstance()-> + GetDefaultUidByBundleName(bundle, request->GetOwnerUserId()); + if (uid < 0) { + return ERR_ANS_INVALID_UID; + } + request->SetOwnerUid(uid); } request->SetOwnerBundleName(sourceBundleName); } @@ -431,15 +438,21 @@ ErrCode AdvancedNotificationService::PrepareNotificationInfo( } std::string sourceBundleName = request->GetBundleOption() == nullptr ? "" : request->GetBundleOption()->GetBundleName(); - if ((!sourceBundleName.empty() && - NotificationPreferences::GetInstance()->IsAgentRelationship(GetClientBundleName(), sourceBundleName) && - !AccessTokenHelper::CheckPermission(OHOS_PERMISSION_NOTIFICATION_AGENT_CONTROLLER)) || - request->IsAgentNotification()) { + if (request->IsAgentNotification()) { bundleOption = new (std::nothrow) NotificationBundleOption(request->GetOwnerBundleName(), request->GetOwnerUid()); } else { - bundleOption = new (std::nothrow) NotificationBundleOption(request->GetCreatorBundleName(), - request->GetCreatorUid()); + if ((!sourceBundleName.empty() && + NotificationPreferences::GetInstance()->IsAgentRelationship(GetClientBundleName(), sourceBundleName) && + !AccessTokenHelper::CheckPermission(OHOS_PERMISSION_NOTIFICATION_AGENT_CONTROLLER))) { + request->SetCreatorUid(request->GetOwnerUid()); + request->SetCreatorBundleName(request->GetOwnerBundleName()); + bundleOption = new (std::nothrow) NotificationBundleOption(request->GetOwnerBundleName(), + request->GetOwnerUid()); + } else { + bundleOption = new (std::nothrow) NotificationBundleOption(request->GetCreatorBundleName(), + request->GetCreatorUid()); + } } if (bundleOption == nullptr) { -- Gitee From dda1eb61e421019ddc85881f5af20e7dc586de7c Mon Sep 17 00:00:00 2001 From: songbao1 Date: Sat, 7 Sep 2024 20:00:42 +0800 Subject: [PATCH 132/167] =?UTF-8?q?=E8=AE=A2=E9=98=85=E5=B9=B6=E5=8F=91?= =?UTF-8?q?=E9=97=AE=E9=A2=98?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: songbao1 Change-Id: I0a59142262d50d4c8fcea69e0e3acbab9921f60b --- .../ans/src/notification_subscriber.cpp | 47 +++++++++++++- frameworks/js/napi/include/subscribe.h | 16 ++--- frameworks/js/napi/include/unsubscribe.h | 4 +- frameworks/js/napi/src/subscribe.cpp | 62 ++++++++----------- .../js/napi/src/subscribe/napi_subscribe.cpp | 26 +++----- .../inner_api/notification_subscriber.h | 3 + 6 files changed, 92 insertions(+), 66 deletions(-) diff --git a/frameworks/ans/src/notification_subscriber.cpp b/frameworks/ans/src/notification_subscriber.cpp index cdc9d5bfd..5e5661188 100644 --- a/frameworks/ans/src/notification_subscriber.cpp +++ b/frameworks/ans/src/notification_subscriber.cpp @@ -29,7 +29,11 @@ NotificationSubscriber::NotificationSubscriber() }; NotificationSubscriber::~NotificationSubscriber() -{} +{ + if (impl_ != nullptr) { + impl_->OnSubscriberDestory(); + } +} void NotificationSubscriber::SetDeviceType(const std::string &deviceType) { @@ -105,8 +109,16 @@ NotificationSubscriber::SubscriberImpl::SubscriberImpl(NotificationSubscriber &s recipient_ = new (std::nothrow) DeathRecipient(*this); }; +void NotificationSubscriber::SubscriberImpl::OnSubscriberDestory() +{ + isSubscriberDestory_.store(true); +} + void NotificationSubscriber::SubscriberImpl::OnConnected() { + if (isSubscriberDestory_.load()) { + return; + } HITRACE_METER_NAME(HITRACE_TAG_NOTIFICATION, __PRETTY_FUNCTION__); sptr proxy = GetAnsManagerProxy(); if (proxy != nullptr) { @@ -118,6 +130,9 @@ void NotificationSubscriber::SubscriberImpl::OnConnected() void NotificationSubscriber::SubscriberImpl::OnDisconnected() { + if (isSubscriberDestory_.load()) { + return; + } HITRACE_METER_NAME(HITRACE_TAG_NOTIFICATION, __PRETTY_FUNCTION__); sptr proxy = GetAnsManagerProxy(); if (proxy != nullptr) { @@ -130,6 +145,9 @@ void NotificationSubscriber::SubscriberImpl::OnDisconnected() void NotificationSubscriber::SubscriberImpl::OnConsumed( const sptr ¬ification, const sptr ¬ificationMap) { + if (isSubscriberDestory_.load()) { + return; + } HITRACE_METER_NAME(HITRACE_TAG_NOTIFICATION, __PRETTY_FUNCTION__); std::shared_ptr sharedNotification = std::make_shared(*notification); #ifdef NOTIFICATION_SMART_REMINDER_SUPPORTED @@ -144,6 +162,9 @@ void NotificationSubscriber::SubscriberImpl::OnConsumed( void NotificationSubscriber::SubscriberImpl::OnConsumedList(const std::vector> ¬ifications, const sptr ¬ificationMap) { + if (isSubscriberDestory_.load()) { + return; + } HITRACE_METER_NAME(HITRACE_TAG_NOTIFICATION, __PRETTY_FUNCTION__); for (auto notification : notifications) { OnConsumed(notification, notificationMap); @@ -153,6 +174,9 @@ void NotificationSubscriber::SubscriberImpl::OnConsumedList(const std::vector ¬ification, const sptr ¬ificationMap, int32_t deleteReason) { + if (isSubscriberDestory_.load()) { + return; + } HITRACE_METER_NAME(HITRACE_TAG_NOTIFICATION, __PRETTY_FUNCTION__); if (notificationMap == nullptr) { subscriber_.OnCanceled(std::make_shared(*notification), @@ -166,6 +190,9 @@ void NotificationSubscriber::SubscriberImpl::OnCanceled( void NotificationSubscriber::SubscriberImpl::OnBatchCanceled(const std::vector> ¬ifications, const sptr ¬ificationMap, int32_t deleteReason) { + if (isSubscriberDestory_.load()) { + return; + } std::vector> notificationList; for (auto notification : notifications) { notificationList.emplace_back(std::make_shared(*notification)); @@ -182,6 +209,9 @@ void NotificationSubscriber::SubscriberImpl::OnBatchCanceled(const std::vector> ¬ifications, const sptr ¬ificationMap, int32_t deleteReason) { + if (isSubscriberDestory_.load()) { + return; + } HITRACE_METER_NAME(HITRACE_TAG_NOTIFICATION, __PRETTY_FUNCTION__); if (subscriber_.HasOnBatchCancelCallback()) { OnBatchCanceled(notifications, notificationMap, deleteReason); @@ -194,23 +224,35 @@ void NotificationSubscriber::SubscriberImpl::OnCanceledList(const std::vector ¬ificationMap) { + if (isSubscriberDestory_.load()) { + return; + } subscriber_.OnUpdate(std::make_shared(*notificationMap)); } void NotificationSubscriber::SubscriberImpl::OnDoNotDisturbDateChange(const sptr &date) { + if (isSubscriberDestory_.load()) { + return; + } subscriber_.OnDoNotDisturbDateChange(std::make_shared(*date)); } void NotificationSubscriber::SubscriberImpl::OnEnabledNotificationChanged( const sptr &callbackData) { + if (isSubscriberDestory_.load()) { + return; + } HITRACE_METER_NAME(HITRACE_TAG_NOTIFICATION, __PRETTY_FUNCTION__); subscriber_.OnEnabledNotificationChanged(std::make_shared(*callbackData)); } void NotificationSubscriber::SubscriberImpl::OnBadgeChanged(const sptr &badgeData) { + if (isSubscriberDestory_.load()) { + return; + } HITRACE_METER_NAME(HITRACE_TAG_NOTIFICATION, __PRETTY_FUNCTION__); subscriber_.OnBadgeChanged(std::make_shared(*badgeData)); } @@ -218,6 +260,9 @@ void NotificationSubscriber::SubscriberImpl::OnBadgeChanged(const sptr &callbackData) { + if (isSubscriberDestory_.load()) { + return; + } HITRACE_METER_NAME(HITRACE_TAG_NOTIFICATION, __PRETTY_FUNCTION__); subscriber_.OnBadgeEnabledChanged(callbackData); } diff --git a/frameworks/js/napi/include/subscribe.h b/frameworks/js/napi/include/subscribe.h index 17a1c917f..4cbf1d101 100644 --- a/frameworks/js/napi/include/subscribe.h +++ b/frameworks/js/napi/include/subscribe.h @@ -21,7 +21,7 @@ namespace OHOS { namespace NotificationNapi { using namespace OHOS::Notification; -class SubscriberInstance : public NotificationSubscriber { +class SubscriberInstance : public NotificationSubscriber, public std::enable_shared_from_this { public: SubscriberInstance(); virtual ~SubscriberInstance(); @@ -221,13 +221,13 @@ private: struct SubscriberInstancesInfo { napi_ref ref = nullptr; - SubscriberInstance *subscriber = nullptr; + std::shared_ptr subscriber = nullptr; }; struct AsyncCallbackInfoSubscribe { napi_env env = nullptr; napi_async_work asyncWork = nullptr; - SubscriberInstance *objectInfo = nullptr; + std::shared_ptr objectInfo = nullptr; NotificationSubscribeInfo subscriberInfo; CallbackPromiseInfo info; }; @@ -236,19 +236,19 @@ static std::mutex mutex_; static thread_local std::vector subscriberInstances_; static std::mutex delMutex_; -static std::vector DeletingSubscriber; +static std::vector> DeletingSubscriber; bool HasNotificationSubscriber(const napi_env &env, const napi_value &value, SubscriberInstancesInfo &subscriberInfo); bool AddSubscriberInstancesInfo(const napi_env &env, const SubscriberInstancesInfo &subscriberInfo); -bool DelSubscriberInstancesInfo(const napi_env &env, const SubscriberInstance *subscriber); +bool DelSubscriberInstancesInfo(const napi_env &env, const std::shared_ptr subscriber); -bool AddDeletingSubscriber(SubscriberInstance *subscriber); -void DelDeletingSubscriber(SubscriberInstance *subscriber); +bool AddDeletingSubscriber(std::shared_ptr subscriber); +void DelDeletingSubscriber(std::shared_ptr subscriber); napi_value Subscribe(napi_env env, napi_callback_info info); napi_value ParseParameters(const napi_env &env, const napi_callback_info &info, - NotificationSubscribeInfo &subscriberInfo, SubscriberInstance *&subscriber, napi_ref &callback); + NotificationSubscribeInfo &subscriberInfo, std::shared_ptr &subscriber, napi_ref &callback); } // namespace NotificationNapi } // namespace OHOS #endif // BASE_NOTIFICATION_DISTRIBUTED_NOTIFICATION_SERVICE_FRAMEWORKS_JS_NAPI_INCLUDE_SUBSCRIBE_H diff --git a/frameworks/js/napi/include/unsubscribe.h b/frameworks/js/napi/include/unsubscribe.h index d3db0dfba..6e9680ccd 100644 --- a/frameworks/js/napi/include/unsubscribe.h +++ b/frameworks/js/napi/include/unsubscribe.h @@ -25,12 +25,12 @@ using namespace OHOS::Notification; struct AsyncCallbackInfoUnsubscribe { napi_env env = nullptr; napi_async_work asyncWork = nullptr; - SubscriberInstance *objectInfo = nullptr; + std::shared_ptr objectInfo = nullptr; CallbackPromiseInfo info; }; struct ParametersInfoUnsubscribe { - SubscriberInstance *objectInfo = nullptr; + std::shared_ptr objectInfo = nullptr; napi_ref callback = nullptr; }; diff --git a/frameworks/js/napi/src/subscribe.cpp b/frameworks/js/napi/src/subscribe.cpp index d2e392607..23af5f9f1 100644 --- a/frameworks/js/napi/src/subscribe.cpp +++ b/frameworks/js/napi/src/subscribe.cpp @@ -64,7 +64,7 @@ struct NotificationReceiveDataWorker { int32_t deleteReason = 0; int32_t result = 0; int32_t disturbMode = 0; - SubscriberInstance *subscriber = nullptr; + std::shared_ptr subscriber = nullptr; Type type; }; @@ -143,6 +143,9 @@ SubscriberInstance::SubscriberInstance() SubscriberInstance::~SubscriberInstance() { + if (unsubscribeCallbackInfo_.tsfn != nullptr) { + napi_release_threadsafe_function(unsubscribeCallbackInfo_.tsfn, napi_tsfn_abort); + } if (canceCallbackInfo_.ref != nullptr) { napi_delete_reference(canceCallbackInfo_.env, canceCallbackInfo_.ref); } @@ -557,12 +560,12 @@ void SubscriberInstance::OnDisconnected() dataWorker->env = unsubscribeCallbackInfo_.env; dataWorker->ref = unsubscribeCallbackInfo_.ref; - dataWorker->subscriber = this; + dataWorker->subscriber = shared_from_this(); dataWorker->type = Type::DIS_CONNECTED; - + napi_acquire_threadsafe_function(unsubscribeCallbackInfo_.tsfn); napi_call_threadsafe_function(unsubscribeCallbackInfo_.tsfn, dataWorker, napi_tsfn_nonblocking); - napi_release_threadsafe_function(unsubscribeCallbackInfo_.tsfn, napi_tsfn_abort); + napi_release_threadsafe_function(unsubscribeCallbackInfo_.tsfn, napi_tsfn_release); } void ThreadSafeOnDestroy(napi_env env, napi_value jsCallback, void* context, void* data) @@ -1229,7 +1232,7 @@ napi_value GetNotificationSubscriber( napi_valuetype valuetype = napi_undefined; napi_ref result = nullptr; - subscriberInfo.subscriber = new (std::nothrow) SubscriberInstance(); + subscriberInfo.subscriber = std::make_shared(); if (subscriberInfo.subscriber == nullptr) { ANS_LOGE("subscriber is null"); std::string msg = "Mandatory parameters are left unspecified. subscriber is null"; @@ -1467,31 +1470,32 @@ bool AddSubscriberInstancesInfo(const napi_env &env, const SubscriberInstancesIn return true; } -bool DelSubscriberInstancesInfo(const napi_env &env, const SubscriberInstance *subscriber) +bool DelSubscriberInstancesInfo(const napi_env &env, const std::shared_ptr subscriber) { ANS_LOGD("enter"); if (subscriber == nullptr) { ANS_LOGE("subscriber is null"); return false; } - - std::lock_guard lock(mutex_); - for (auto it = subscriberInstances_.begin(); it != subscriberInstances_.end(); ++it) { - if ((*it).subscriber == subscriber) { - if ((*it).ref != nullptr) { - napi_delete_reference(env, (*it).ref); + std::lock_guard lock(delMutex_); + auto iter = std::find(DeletingSubscriber.begin(), DeletingSubscriber.end(), subscriber); + if (iter != DeletingSubscriber.end()) { + DeletingSubscriber.erase(iter); + std::lock_guard lock(mutex_); + for (auto it = subscriberInstances_.begin(); it != subscriberInstances_.end(); ++it) { + if ((*it).subscriber == subscriber) { + if ((*it).ref != nullptr) { + napi_delete_reference(env, (*it).ref); + } + subscriberInstances_.erase(it); + return true; } - DelDeletingSubscriber((*it).subscriber); - delete (*it).subscriber; - (*it).subscriber = nullptr; - subscriberInstances_.erase(it); - return true; } } return false; } napi_value ParseParameters(const napi_env &env, const napi_callback_info &info, - NotificationSubscribeInfo &subscriberInfo, SubscriberInstance *&subscriber, napi_ref &callback) + NotificationSubscribeInfo &subscriberInfo, std::shared_ptr &subscriber, napi_ref &callback) { ANS_LOGD("enter"); @@ -1520,18 +1524,10 @@ napi_value ParseParameters(const napi_env &env, const napi_callback_info &info, if (!HasNotificationSubscriber(env, argv[PARAM0], subscriberInstancesInfo)) { if (GetNotificationSubscriber(env, argv[PARAM0], subscriberInstancesInfo) == nullptr) { ANS_LOGE("NotificationSubscriber parse failed"); - if (subscriberInstancesInfo.subscriber) { - delete subscriberInstancesInfo.subscriber; - subscriberInstancesInfo.subscriber = nullptr; - } return nullptr; } if (!AddSubscriberInstancesInfo(env, subscriberInstancesInfo)) { ANS_LOGE("AddSubscriberInstancesInfo add failed"); - if (subscriberInstancesInfo.subscriber) { - delete subscriberInstancesInfo.subscriber; - subscriberInstancesInfo.subscriber = nullptr; - } return nullptr; } } @@ -1573,14 +1569,10 @@ napi_value Subscribe(napi_env env, napi_callback_info info) ANS_LOGD("enter"); napi_ref callback = nullptr; - SubscriberInstance *objectInfo = nullptr; + std::shared_ptr objectInfo = nullptr; NotificationSubscribeInfo subscriberInfo; if (ParseParameters(env, info, subscriberInfo, objectInfo, callback) == nullptr) { ANS_LOGD("ParseParameters is nullptr."); - if (objectInfo) { - delete objectInfo; - objectInfo = nullptr; - } return Common::NapiGetUndefined(env); } @@ -1589,10 +1581,6 @@ napi_value Subscribe(napi_env env, napi_callback_info info) }; if (!asynccallbackinfo) { ANS_LOGD("Asynccallbackinfo is nullptr."); - if (objectInfo) { - delete objectInfo; - objectInfo = nullptr; - } return Common::JSParaError(env, callback); } napi_value promise = nullptr; @@ -1659,7 +1647,7 @@ napi_value Subscribe(napi_env env, napi_callback_info info) } } -bool AddDeletingSubscriber(SubscriberInstance *subscriber) +bool AddDeletingSubscriber(std::shared_ptr subscriber) { std::lock_guard lock(delMutex_); auto iter = std::find(DeletingSubscriber.begin(), DeletingSubscriber.end(), subscriber); @@ -1671,7 +1659,7 @@ bool AddDeletingSubscriber(SubscriberInstance *subscriber) return true; } -void DelDeletingSubscriber(SubscriberInstance *subscriber) +void DelDeletingSubscriber(std::shared_ptr subscriber) { std::lock_guard lock(delMutex_); auto iter = std::find(DeletingSubscriber.begin(), DeletingSubscriber.end(), subscriber); diff --git a/frameworks/js/napi/src/subscribe/napi_subscribe.cpp b/frameworks/js/napi/src/subscribe/napi_subscribe.cpp index e2e417201..f1075db91 100644 --- a/frameworks/js/napi/src/subscribe/napi_subscribe.cpp +++ b/frameworks/js/napi/src/subscribe/napi_subscribe.cpp @@ -25,13 +25,9 @@ napi_value NapiSubscribe(napi_env env, napi_callback_info info) { ANS_LOGD("enter"); napi_ref callback = nullptr; - SubscriberInstance *objectInfo = nullptr; + std::shared_ptr objectInfo = nullptr; NotificationSubscribeInfo subscriberInfo; if (ParseParameters(env, info, subscriberInfo, objectInfo, callback) == nullptr) { - if (objectInfo) { - delete objectInfo; - objectInfo = nullptr; - } Common::NapiThrow(env, ERROR_PARAM_INVALID); return Common::NapiGetUndefined(env); } @@ -40,10 +36,6 @@ napi_value NapiSubscribe(napi_env env, napi_callback_info info) .env = env, .asyncWork = nullptr, .objectInfo = objectInfo, .subscriberInfo = subscriberInfo }; if (!asynccallbackinfo) { - if (objectInfo) { - delete objectInfo; - objectInfo = nullptr; - } Common::NapiThrow(env, ERROR_INTERNAL_ERROR); return Common::JSParaError(env, callback); } @@ -76,6 +68,9 @@ napi_value NapiSubscribe(napi_env env, napi_callback_info info) asynccallbackinfo->info.errorCode = NotificationHelper::SubscribeNotification(*(asynccallbackinfo->objectInfo)); } + if (asynccallbackinfo->info.errorCode == ERR_OK) { + DelDeletingSubscriber(asynccallbackinfo->objectInfo); + } } }, [](napi_env env, napi_status status, void *data) { @@ -115,13 +110,9 @@ napi_value NapiSubscribeSelf(napi_env env, napi_callback_info info) { ANS_LOGD("enter"); napi_ref callback = nullptr; - SubscriberInstance *objectInfo = nullptr; + std::shared_ptr objectInfo = nullptr; NotificationSubscribeInfo subscriberInfo; if (ParseParameters(env, info, subscriberInfo, objectInfo, callback) == nullptr) { - if (objectInfo) { - delete objectInfo; - objectInfo = nullptr; - } Common::NapiThrow(env, ERROR_PARAM_INVALID); return Common::NapiGetUndefined(env); } @@ -130,10 +121,6 @@ napi_value NapiSubscribeSelf(napi_env env, napi_callback_info info) .env = env, .asyncWork = nullptr, .objectInfo = objectInfo, .subscriberInfo = subscriberInfo }; if (!asynccallbackinfo) { - if (objectInfo) { - delete objectInfo; - objectInfo = nullptr; - } Common::NapiThrow(env, ERROR_INTERNAL_ERROR); return Common::JSParaError(env, callback); } @@ -156,6 +143,9 @@ napi_value NapiSubscribeSelf(napi_env env, napi_callback_info info) if (asynccallbackinfo) { asynccallbackinfo->info.errorCode = NotificationHelper::SubscribeNotificationSelf(*(asynccallbackinfo->objectInfo)); + if (asynccallbackinfo->info.errorCode == ERR_OK) { + DelDeletingSubscriber(asynccallbackinfo->objectInfo); + } } }, [](napi_env env, napi_status status, void *data) { diff --git a/interfaces/inner_api/notification_subscriber.h b/interfaces/inner_api/notification_subscriber.h index d74564c25..988cfe497 100644 --- a/interfaces/inner_api/notification_subscriber.h +++ b/interfaces/inner_api/notification_subscriber.h @@ -172,9 +172,12 @@ private: sptr GetAnsManagerProxy(); + void OnSubscriberDestory(); + public: NotificationSubscriber &subscriber_; sptr recipient_ {nullptr}; + std::atomic_bool isSubscriberDestory_ {false}; }; private: -- Gitee From 36cd74206765a3fca7330eb91eeacd04ffcabb49 Mon Sep 17 00:00:00 2001 From: z30053788 Date: Thu, 14 Nov 2024 22:38:12 +0800 Subject: [PATCH 133/167] cherry pick 61562cb from https://gitee.com/zhaobaoxin1/notification_distributed_notification_service/pulls/2424 update Signed-off-by: z30053788 Change-Id: Id5ff9cb4ae6399d61f460fe4ef26e4708320cac5 --- frameworks/core/src/ans_manager_stub.cpp | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/frameworks/core/src/ans_manager_stub.cpp b/frameworks/core/src/ans_manager_stub.cpp index 9b348e631..73002331e 100644 --- a/frameworks/core/src/ans_manager_stub.cpp +++ b/frameworks/core/src/ans_manager_stub.cpp @@ -808,6 +808,10 @@ ErrCode AnsManagerStub::HandleGetAllActiveNotifications(MessageParcel &data, Mes { std::vector> notifications; ErrCode result = GetAllActiveNotifications(notifications); + + if (!reply.SetMaxCapacity(NotificationConstant::NOTIFICATION_MAX_LIVE_VIEW_SIZE)) { + return ERR_ANS_PARCELABLE_FAILED; + } if (!WriteParcelableVector(notifications, reply, result)) { ANS_LOGE("[HandleGetAllActiveNotifications] fail: write notifications failed"); return ERR_ANS_PARCELABLE_FAILED; -- Gitee From 671270f72a1b16bf16345ec36324c83b558c66fb Mon Sep 17 00:00:00 2001 From: baozeyu <2455966574@qq.com> Date: Mon, 18 Nov 2024 17:28:17 +0800 Subject: [PATCH 134/167] =?UTF-8?q?cherry=20pick=203f73ea0=20from=20https:?= =?UTF-8?q?//gitee.com/baozeyu/notification=5Fdistributed=5Fnotification?= =?UTF-8?q?=5Fservice/pulls/2440=20=E4=BF=AE=E5=A4=8Dota=E5=9B=BE=E7=89=87?= =?UTF-8?q?=E6=97=A0=E6=B3=95=E6=81=A2=E5=A4=8D=E9=97=AE=E9=A2=98?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: baozeyu <2455966574@qq.com> Change-Id: I1138ac94f03bbb9dae2ddac1cf8a9dc2c7daf6e5 --- frameworks/ans/src/notification_request.cpp | 66 ++------------------ frameworks/core/src/ans_manager_proxy.cpp | 4 ++ frameworks/core/src/ans_subscriber_proxy.cpp | 3 + 3 files changed, 12 insertions(+), 61 deletions(-) diff --git a/frameworks/ans/src/notification_request.cpp b/frameworks/ans/src/notification_request.cpp index c1906adda..928f33d3b 100644 --- a/frameworks/ans/src/notification_request.cpp +++ b/frameworks/ans/src/notification_request.cpp @@ -300,13 +300,6 @@ int64_t NotificationRequest::GetArchiveDeadLine() const void NotificationRequest::SetLittleIcon(const std::shared_ptr &littleIcon) { littleIcon_ = littleIcon; - if (littleIcon != nullptr) { - Media::ImageInfo outImageInfo; - littleIcon->GetImageInfo(outImageInfo); - littleIconType_ = outImageInfo.encodedFormat; - } else { - littleIconType_ = ""; - } } const std::shared_ptr NotificationRequest::GetLittleIcon() const @@ -1241,37 +1234,10 @@ bool NotificationRequest::Marshalling(Parcel &parcel) const } if (valid) { - if (!parcel.WriteString(littleIconType_)) { - ANS_LOGE("Failed to write littleIconType"); - return false; - } - - bool isUnPackImage = true; - std::string littleIconString; - - if (!littleIconType_.empty()) { - littleIconString = AnsImageUtil::PackImage(littleIcon_, littleIconType_); - } - - if (isUnPackImage && !littleIconString.empty()) { - isUnPackImage = false; - } - - if (!parcel.WriteBool(isUnPackImage)) { + if (!parcel.WriteParcelable(littleIcon_.get())) { + ANS_LOGE("Failed to write littleIcon"); return false; } - ANS_LOGD("littleIcon_ : %{public}d, %{public}s", isUnPackImage, littleIconType_.c_str()); - if (isUnPackImage) { - if (!parcel.WriteParcelable(littleIcon_.get())) { - ANS_LOGE("Failed to write littleIcon"); - return false; - } - } else { - if (!parcel.WriteString(littleIconString)) { - ANS_LOGE("Failed to write littleIcon"); - return false; - } - } } valid = bigIcon_ ? true : false; @@ -1650,19 +1616,7 @@ bool NotificationRequest::ReadFromParcel(Parcel &parcel) valid = parcel.ReadBool(); if (valid) { - littleIconType_ = parcel.ReadString(); - bool isUnPackImage = parcel.ReadBool(); - if (isUnPackImage) { - littleIcon_ = std::shared_ptr(parcel.ReadParcelable()); - } else { - std::string littleIconString = parcel.ReadString(); - littleIcon_ = AnsImageUtil::UnPackImage(littleIconString, littleIconType_); - } - - if (!littleIcon_) { - ANS_LOGE("Failed to read littleIcon"); - return false; - } + littleIcon_ = std::shared_ptr(parcel.ReadParcelable()); } valid = parcel.ReadBool(); @@ -1972,7 +1926,6 @@ void NotificationRequest::CopyOther(const NotificationRequest &other) this->notificationBundleOption_ = other.notificationBundleOption_; this->notificationFlagsOfDevices_ = other.notificationFlagsOfDevices_; this->publishDelayTime_ = other.publishDelayTime_; - this->littleIconType_ = other.littleIconType_; } bool NotificationRequest::ConvertObjectsToJson(nlohmann::json &jsonObject) const @@ -2010,11 +1963,7 @@ bool NotificationRequest::ConvertObjectsToJson(nlohmann::json &jsonObject) const extraInfoStr = wWrapper.ToString(); } jsonObject["extraInfo"] = extraInfoStr; - - jsonObject["smallIconType"] = littleIconType_; - if (!littleIconType_.empty()) { - jsonObject["smallIcon"] = AnsImageUtil::PackImage(littleIcon_, littleIconType_); - } + jsonObject["smallIcon"] = AnsImageUtil::PackImage(littleIcon_); jsonObject["largeIcon"] = AnsImageUtil::PackImage(bigIcon_); jsonObject["overlayIcon"] = overlayIcon_ ? AnsImageUtil::PackImage(overlayIcon_) : ""; @@ -2260,14 +2209,9 @@ void NotificationRequest::ConvertJsonToPixelMap(NotificationRequest *target, con const auto &jsonEnd = jsonObject.cend(); - if (jsonObject.find("smallIconType") != jsonEnd && jsonObject.at("smallIconType").is_string()) { - std::string littleIconType = jsonObject.at("smallIconType").get(); - target->littleIconType_ = littleIconType; - } - if (jsonObject.find("smallIcon") != jsonEnd && jsonObject.at("smallIcon").is_string()) { auto littleIconStr = jsonObject.at("smallIcon").get(); - target->littleIcon_ = AnsImageUtil::UnPackImage(littleIconStr, target->littleIconType_); + target->littleIcon_ = AnsImageUtil::UnPackImage(littleIconStr); } if (jsonObject.find("largeIcon") != jsonEnd && jsonObject.at("largeIcon").is_string()) { diff --git a/frameworks/core/src/ans_manager_proxy.cpp b/frameworks/core/src/ans_manager_proxy.cpp index 31891d2e6..2297762f4 100644 --- a/frameworks/core/src/ans_manager_proxy.cpp +++ b/frameworks/core/src/ans_manager_proxy.cpp @@ -367,6 +367,10 @@ ErrCode AnsManagerProxy::GetAllActiveNotifications(std::vector> &n } MessageParcel data; + if (!data.SetMaxCapacity(NotificationConstant::NOTIFICATION_MAX_LIVE_VIEW_SIZE)) { + ANS_LOGE("[OnConsumedList] fail: set max capacity failed."); + } if (!data.WriteInterfaceToken(AnsSubscriberProxy::GetDescriptor())) { ANS_LOGE("Write interface token failed."); return; -- Gitee From bcbcaa093f8bbb4a6388c573ef34f09507cedf57 Mon Sep 17 00:00:00 2001 From: z30053788 Date: Tue, 19 Nov 2024 11:18:13 +0800 Subject: [PATCH 135/167] cherry pick ca1e903 from https://gitee.com/zhaobaoxin1/notification_distributed_notification_service/pulls/2441 update Signed-off-by: z30053788 Change-Id: Iab06e0ccdfd1075127d673daa82ac098662aa11b --- frameworks/ans/src/notification_sorting.cpp | 5 +++++ frameworks/ans/src/notification_sorting_map.cpp | 1 - frameworks/js/napi/include/common.h | 2 +- frameworks/js/napi/src/common.cpp | 4 ++-- interfaces/inner_api/notification_sorting.h | 12 ++++++++++-- 5 files changed, 18 insertions(+), 6 deletions(-) diff --git a/frameworks/ans/src/notification_sorting.cpp b/frameworks/ans/src/notification_sorting.cpp index 78699b112..6a392de8b 100644 --- a/frameworks/ans/src/notification_sorting.cpp +++ b/frameworks/ans/src/notification_sorting.cpp @@ -135,6 +135,10 @@ bool NotificationSorting::ReadFromParcel(Parcel &parcel) // read slot_ slot_ = parcel.ReadStrongParcelable(); + if (!slot_) { + ANS_LOGE("read slot failed."); + return false; + } return true; } @@ -143,6 +147,7 @@ NotificationSorting *NotificationSorting::Unmarshalling(Parcel &parcel) { NotificationSorting *sorting = new (std::nothrow) NotificationSorting(); if (sorting && !sorting->ReadFromParcel(parcel)) { + ANS_LOGE("NotificationSorting Unmarshalling failed."); delete sorting; sorting = nullptr; } diff --git a/frameworks/ans/src/notification_sorting_map.cpp b/frameworks/ans/src/notification_sorting_map.cpp index 919c88a8c..09b41fb3b 100644 --- a/frameworks/ans/src/notification_sorting_map.cpp +++ b/frameworks/ans/src/notification_sorting_map.cpp @@ -81,7 +81,6 @@ bool NotificationSortingMap::Marshalling(Parcel &parcel) const break; } } - return ret; } diff --git a/frameworks/js/napi/include/common.h b/frameworks/js/napi/include/common.h index adf7d992c..62bdabf81 100644 --- a/frameworks/js/napi/include/common.h +++ b/frameworks/js/napi/include/common.h @@ -335,7 +335,7 @@ public: * @return Returns the null object if success, returns the null value otherwise */ static napi_value SetNotificationSorting( - const napi_env &env, const NotificationSorting &sorting, napi_value &result); + const napi_env &env, NotificationSorting &sorting, napi_value &result); /** * @brief Sets a js object by specified NotificationSlot object diff --git a/frameworks/js/napi/src/common.cpp b/frameworks/js/napi/src/common.cpp index 70f42a17b..d206f9fb0 100644 --- a/frameworks/js/napi/src/common.cpp +++ b/frameworks/js/napi/src/common.cpp @@ -85,7 +85,7 @@ napi_value Common::SetNotificationSortingMap( return NapiGetBoolean(env, true); } -napi_value Common::SetNotificationSorting(const napi_env &env, const NotificationSorting &sorting, napi_value &result) +napi_value Common::SetNotificationSorting(const napi_env &env, NotificationSorting &sorting, napi_value &result) { ANS_LOGD("enter"); @@ -93,7 +93,7 @@ napi_value Common::SetNotificationSorting(const napi_env &env, const Notificatio napi_value slotResult = nullptr; napi_value value = nullptr; napi_create_object(env, &slotResult); - if (!SetNotificationSlot(env, sorting.GetSlot(), slotResult)) { + if (!sorting.GetSlot() || !SetNotificationSlot(env, *sorting.GetSlot(), slotResult)) { ANS_LOGE("SetNotificationSlot call failed"); return NapiGetBoolean(env, false); } diff --git a/interfaces/inner_api/notification_sorting.h b/interfaces/inner_api/notification_sorting.h index 324101613..fd8b4752e 100644 --- a/interfaces/inner_api/notification_sorting.h +++ b/interfaces/inner_api/notification_sorting.h @@ -20,6 +20,7 @@ #include "notification_slot.h" #include "parcel.h" #include "uri.h" +#include namespace OHOS { namespace Notification { @@ -74,9 +75,16 @@ public: * * @return Returns the NotificationSlot of the notification. */ - inline NotificationSlot GetSlot() const + inline NotificationSlot* GetSlot() { - return *slot_; + if (!slot_) { + slot_ = new (std::nothrow) NotificationSlot(NotificationConstant::SlotType::OTHER); + if (!slot_) { + ANS_LOGE("Failed to create NotificationSlot"); + slot_ = nullptr; + } + } + return slot_; }; /** -- Gitee From 2d4457d287c0cc000031a8bc170251a737248dc2 Mon Sep 17 00:00:00 2001 From: xdongs Date: Mon, 18 Nov 2024 10:49:09 +0800 Subject: [PATCH 136/167] =?UTF-8?q?resolve=20conflict=E5=BC=B9=E7=AA=97?= =?UTF-8?q?=E5=AD=97=E4=BD=93=E8=B7=9F=E9=9A=8F=E7=B3=BB=E7=BB=9F?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: xdongs --- .../AppScope/app.json | 7 +- .../resources/base/profile/configuration.json | 6 + .../NotificationServiceExtAbility.ts | 9 +- .../entry/src/main/ets/common/constant.ets | 16 +- .../entry/src/main/ets/common/utils.ets | 18 ++ .../src/main/ets/pages/notificationDialog.ets | 202 +++++++++--------- .../main/ets/pages/pcNotificationDialog.ets | 31 ++- 7 files changed, 173 insertions(+), 116 deletions(-) create mode 100644 services/dialog_ui/enable_notification_dialog/AppScope/resources/base/profile/configuration.json diff --git a/services/dialog_ui/enable_notification_dialog/AppScope/app.json b/services/dialog_ui/enable_notification_dialog/AppScope/app.json index 8bea06d5a..f2ee0dc8f 100644 --- a/services/dialog_ui/enable_notification_dialog/AppScope/app.json +++ b/services/dialog_ui/enable_notification_dialog/AppScope/app.json @@ -2,12 +2,13 @@ "app": { "bundleName": "com.ohos.notificationdialog", "vendor": "example", - "versionCode": 1000014, - "versionName": "1.1.4", + "versionCode": 1000015, + "versionName": "1.1.5", "icon": "$media:app_icon", "label": "$string:app_name", "distributedNotificationEnabled": true, "minAPIVersion": 10, - "targetAPIVersion": 10 + "targetAPIVersion": 10, + "configuration": "$profile:configuration" } } diff --git a/services/dialog_ui/enable_notification_dialog/AppScope/resources/base/profile/configuration.json b/services/dialog_ui/enable_notification_dialog/AppScope/resources/base/profile/configuration.json new file mode 100644 index 000000000..4bc20f7d5 --- /dev/null +++ b/services/dialog_ui/enable_notification_dialog/AppScope/resources/base/profile/configuration.json @@ -0,0 +1,6 @@ +{ + "configuration": { + "fontSizeScale": "followSystem", + "fontSizeMaxScale": "3.2" + } +} \ No newline at end of file diff --git a/services/dialog_ui/enable_notification_dialog/entry/src/main/ets/ServiceExtAbility/NotificationServiceExtAbility.ts b/services/dialog_ui/enable_notification_dialog/entry/src/main/ets/ServiceExtAbility/NotificationServiceExtAbility.ts index 95da819f6..c4ddaaa60 100644 --- a/services/dialog_ui/enable_notification_dialog/entry/src/main/ets/ServiceExtAbility/NotificationServiceExtAbility.ts +++ b/services/dialog_ui/enable_notification_dialog/entry/src/main/ets/ServiceExtAbility/NotificationServiceExtAbility.ts @@ -150,11 +150,12 @@ export class EnableNotificationDialog { }; let subWindow = await extensionWindow.createSubWindowWithOptions('subWindowForHost' + Date(), subWindowOpts); this.subWindow = subWindow; - await subWindow.loadContent(path, this.storage); + await this.sleep(200); let windowRect = extensionWindow.properties?.uiExtensionHostWindowProxyRect; + console.info(TAG, `size : ${windowRect?.left} ${windowRect?.top} ${windowRect?.width} ${windowRect?.height}`); await subWindow.moveWindowTo(windowRect?.left, windowRect?.top); await subWindow.resize(windowRect?.width, windowRect?.height); - console.info(TAG, `size : ${windowRect.left} ${windowRect.top} ${windowRect.width} ${windowRect.height}`); + await subWindow.loadContent(path, this.storage); try { await subWindow.hideNonSystemFloatingWindows(true); } catch (err) { @@ -177,6 +178,10 @@ export class EnableNotificationDialog { } } + async sleep(ms: number): Promise { + return new Promise(resolve => setTimeout(resolve, ms)); + } + async publishButtonClickedEvent(enabled: boolean): Promise { CommonEventManager.publish( COMMON_EVENT_NAME, diff --git a/services/dialog_ui/enable_notification_dialog/entry/src/main/ets/common/constant.ets b/services/dialog_ui/enable_notification_dialog/entry/src/main/ets/common/constant.ets index 00133b527..5bdf485fe 100644 --- a/services/dialog_ui/enable_notification_dialog/entry/src/main/ets/common/constant.ets +++ b/services/dialog_ui/enable_notification_dialog/entry/src/main/ets/common/constant.ets @@ -117,12 +117,12 @@ export default class Constants { static DIALOG_LABEL_LINE_HEIGHT = 14; // request text of dialog - static DIALOG_REQ_FONT_SIZE = 20; - static DIALOG_REQ_MARGIN_TOP = 16; - static DIALOG_REQ_MARGIN_BUTTOM = 16; - static DIALOG_REQ_MARGIN_LEFT = 24; - static DIALOG_REQ_MARGIN_RIGHT = 24; - static DIALOG_REQ_LINE_HEIGHT = 24; + public static DIALOG_REQ_FONT_SIZE = 20; + public static DIALOG_REQ_MARGIN_TOP = 16; + public static DIALOG_REQ_MARGIN_BUTTOM = 8; + public static DIALOG_REQ_MARGIN_LEFT = 24; + public static DIALOG_REQ_MARGIN_RIGHT = 24; + public static DIALOG_REQ_LINE_HEIGHT = 24; // description text of dialog public static DIALOG_DESP_FONT_SIZE = 16; @@ -146,6 +146,10 @@ export default class Constants { public static CROSS_LINE_RATIO = 0.2; public static CROSS_LINE_RESIZE_PARAM = 1.25; + public static FONT_SCALE_DEFAULT = 1; + public static FONT_SCALE_MAX = 2; + public static MAX_DIALOG_WIDTH = 400; + //pc public static PC_ICON_MARGIN_TOP = 24; diff --git a/services/dialog_ui/enable_notification_dialog/entry/src/main/ets/common/utils.ets b/services/dialog_ui/enable_notification_dialog/entry/src/main/ets/common/utils.ets index c98e8dffd..be487d359 100644 --- a/services/dialog_ui/enable_notification_dialog/entry/src/main/ets/common/utils.ets +++ b/services/dialog_ui/enable_notification_dialog/entry/src/main/ets/common/utils.ets @@ -16,6 +16,7 @@ import Constants from './constant'; import { MeasureOptions } from '@ohos.measure'; import { MeasureUtils } from '@ohos.arkui.UIContext'; +import common from '@ohos.app.ability.common'; /** * Omit display when application name is too long @@ -50,3 +51,20 @@ export function calContainerWidth( } return targetContainerWidth; } + +export function getFontSizeScale(context: common.UIAbilityContext, maxScale: number = 3.2): number { + let fontSizeScale = context.config?.fontSizeScale; + console.log(`NotificationDialog_Service fontSizeScale = ${fontSizeScale}`); + if(fontSizeScale === undefined) { + return Constants.FONT_SCALE_DEFAULT; + } + return fontSizeScale > maxScale ? maxScale : fontSizeScale; +} + +export function sourceToVp(source: Resource): number { + return px2vp(getContext().resourceManager.getNumber(source.id)); +} + +export function getLimitFontSize(fontSizeScale: number, sourceFontSize: number): string { + return `${sourceFontSize * fontSizeScale}vp`; +} diff --git a/services/dialog_ui/enable_notification_dialog/entry/src/main/ets/pages/notificationDialog.ets b/services/dialog_ui/enable_notification_dialog/entry/src/main/ets/pages/notificationDialog.ets index d671daff0..fc99751e7 100644 --- a/services/dialog_ui/enable_notification_dialog/entry/src/main/ets/pages/notificationDialog.ets +++ b/services/dialog_ui/enable_notification_dialog/entry/src/main/ets/pages/notificationDialog.ets @@ -16,7 +16,12 @@ import bundleResourceManager from '@ohos.bundle.bundleResourceManager'; import display from '@ohos.display'; import window from '@ohos.window'; -import { titleTrim, calContainerWidth } from '../common/utils'; +import { + titleTrim, + calContainerWidth, + getFontSizeScale, + sourceToVp, + getLimitFontSize } from '../common/utils'; import Constants from '../common/constant'; import fs from '@ohos.file.fs'; import configPolicy from '@ohos.configPolicy'; @@ -25,6 +30,7 @@ import { Callback} from '@ohos.base'; import UIExtensionContentSession from '@ohos.app.ability.UIExtensionContentSession'; import { MeasureOptions } from '@ohos.measure'; import { MeasureUtils } from '@ohos.arkui.UIContext'; +import common from '@ohos.app.ability.common'; const TAG = 'NotificationDialog_Service '; const permission: Record = { @@ -36,20 +42,14 @@ const bottomPopoverTypes = ['default', 'phone']; let storage = LocalStorage.getShared(); -@Extend(Button) function rightCustomizeButton() { +@Extend(Button) function customizeButton() { .backgroundColor(Color.Transparent) .fontColor($r('app.color.button_text')) - .fontSize(Constants.TEXT_MIDDLE_FONT_SIZE) - .fontWeight(FontWeight.Medium) - .height(Constants.BUTTON_HEIGHT) - .flexGrow(Constants.FLEX_GROW) - .width('50%') -} - -@Extend(Button) function leftCustomizeButton() { - .backgroundColor(Color.Transparent) - .fontColor($r('app.color.button_text')) - .fontSize(Constants.TEXT_MIDDLE_FONT_SIZE) + .fontSize( + getLimitFontSize( + Constants.TEXT_MIDDLE_FONT_SIZE, + getFontSizeScale(getContext(this) as common.UIAbilityContext, Constants.FONT_SCALE_MAX)) + ) .fontWeight(FontWeight.Medium) .height(Constants.BUTTON_HEIGHT) .flexGrow(Constants.FLEX_GROW) @@ -92,106 +92,106 @@ struct PermissionDialog { dialog?: EnableNotificationDialog; session?: UIExtensionContentSession; controller?: CustomDialogController; - @State titleContainerWidth: string|number = 'auto'; + @State titleContainerWidth: string | number = 'auto'; build() { - GridRow({ columns: { xs: Constants.XS_COLUMNS, sm: Constants.SM_COLUMNS, md: Constants.MD_COLUMNS, lg: Constants.LG_COLUMNS }, gutter: Constants.DIALOG_GUTTER }) { - GridCol({ span: { xs: Constants.XS_SPAN, sm: Constants.SM_SPAN, md: Constants.DIALOG_MD_SPAN, lg: Constants.DIALOG_LG_SPAN }, - offset: {xs: Constants.XS_OFFSET, sm: Constants.SM_OFFSET, md: Constants.DIALOG_MD_OFFSET, lg: Constants.DIALOG_LG_OFFSET} }) { - Flex({ justifyContent: FlexAlign.Center, alignItems: this.isBottomPopover ? ItemAlign.End : ItemAlign.Center }) { - Column() { - Scroll() { - Column() { - Row() { - Image(permission.icon) - .width(Constants.DIALOG_ICON_WIDTH) - .height(Constants.DIALOG_ICON_HEIGHT) - .margin({ - top: Constants.DIALOG_ICON_MARGIN_TOP - }) + Row(){ + Flex({ justifyContent: FlexAlign.Center, alignItems: this.isBottomPopover ? ItemAlign.End : ItemAlign.Center }) { + Column() { + Scroll() { + Column() { + Row() { + Image(permission.icon) + .width(Constants.DIALOG_ICON_WIDTH) + .height(Constants.DIALOG_ICON_HEIGHT) + .margin({ + top: Constants.DIALOG_ICON_MARGIN_TOP + }) + } + Row() { + Flex({ justifyContent: FlexAlign.Center }) { + Text($r('app.string.group_label_notification', this.appName)) + .fontSize($r('sys.float.ohos_id_text_size_headline8')) + .fontColor($r('app.color.text_primary')) + .fontWeight(FontWeight.Bold) + .minFontSize( + getLimitFontSize(Constants.TITLE_MIN_FONT_SIZE, + getFontSizeScale(getContext(this) as common.UIAbilityContext, Constants.FONT_SCALE_MAX)) + ) + .maxFontSize( + getLimitFontSize(sourceToVp($r('sys.float.ohos_id_text_size_headline8')), + getFontSizeScale(getContext(this) as common.UIAbilityContext, Constants.FONT_SCALE_MAX)) + ) + .heightAdaptivePolicy(TextHeightAdaptivePolicy.MAX_LINES_FIRST) + .maxLines(2) + .textOverflow({overflow: TextOverflow.Ellipsis}) + .width(this.titleContainerWidth) + .textAlign(TextAlign.Center) } - Row() { - Flex({ justifyContent: FlexAlign.Center }) { - Text($r('app.string.group_label_notification', this.appName)) - .fontSize($r('sys.float.ohos_id_text_size_headline8')) - .fontColor($r('app.color.text_primary')) - .fontWeight(FontWeight.Bold) - .minFontSize(Constants.TITLE_MIN_FONT_SIZE) - .maxFontSize($r('sys.float.ohos_id_text_size_headline8')) - .heightAdaptivePolicy(TextHeightAdaptivePolicy.MAX_LINES_FIRST) - .maxLines(2) - .textOverflow({overflow: TextOverflow.Ellipsis}) - .width(this.titleContainerWidth) - .textAlign(TextAlign.Center) + .margin({ + top: Constants.DIALOG_REQ_MARGIN_TOP, + bottom:Constants.DIALOG_REQ_MARGIN_BUTTOM, + left: Constants.DIALOG_REQ_MARGIN_LEFT, + right: Constants.DIALOG_REQ_MARGIN_RIGHT + }) + .onSizeChange((oldValue: SizeOptions, newValue: SizeOptions) => { + let containerWidth = newValue.width as number; + let options: MeasureOptions = { + textContent: $r('app.string.group_label_notification', this.appName), + fontSize: $r('sys.float.ohos_id_text_size_headline8'), + fontWeight: FontWeight.Bold, + }; + this.titleContainerWidth = calContainerWidth(containerWidth, options, + Constants.CROSS_LINE_RATIO, this.getUIContext().getMeasureUtils()); + console.info(TAG, `onSizeChange titleContainerWidth: ${this.titleContainerWidth}`); + }) + } + Row() { + Flex({ justifyContent: FlexAlign.Center }) { + Text() { + Span(permission.reason) } + .fontSize(Constants.DIALOG_DESP_FONT_SIZE) + .fontWeight(FontWeight.Regular) + .fontColor($r('app.color.text_primary')) + .lineHeight(Constants.DIALOG_DESP_LINE_HEIGHT) .margin({ - top: Constants.DIALOG_REQ_MARGIN_TOP, - bottom:Constants.DIALOG_REQ_MARGIN_BUTTOM, - left: Constants.DIALOG_REQ_MARGIN_LEFT, - right: Constants.DIALOG_REQ_MARGIN_RIGHT - }) - .onSizeChange((oldValue: SizeOptions, newValue: SizeOptions) => { - let containerWidth = newValue.width as number; - let options: MeasureOptions = { - textContent: $r('app.string.group_label_notification', this.appName), - fontSize: $r('sys.float.ohos_id_text_size_headline8'), - fontWeight: FontWeight.Bold, - }; - this.titleContainerWidth = calContainerWidth(containerWidth, options, - Constants.CROSS_LINE_RATIO, this.getUIContext().getMeasureUtils()); - console.info(TAG, `onSizeChange titleContainerWidth: ${this.titleContainerWidth}`); + top: Constants.DIALOG_DESP_MARGIN_TOP, + left: Constants.DIALOG_DESP_MARGIN_LEFT, + right: Constants.DIALOG_DESP_MARGIN_RIGHT, + bottom: Constants.DIALOG_DESP_MARGIN_BOTTOM }) } - Row() { - Flex({ justifyContent: FlexAlign.Center }) { - Text() { - Span(permission.reason) - } - .fontSize(Constants.DIALOG_DESP_FONT_SIZE) - .fontWeight(FontWeight.Regular) - .fontColor($r('app.color.text_primary')) - .lineHeight(Constants.DIALOG_DESP_LINE_HEIGHT) - .margin({ - top: Constants.DIALOG_DESP_MARGIN_TOP, - left: Constants.DIALOG_DESP_MARGIN_LEFT, - right: Constants.DIALOG_DESP_MARGIN_RIGHT, - bottom: Constants.DIALOG_DESP_MARGIN_BOTTOM + } + Row() { + Flex({ justifyContent: FlexAlign.SpaceBetween, alignItems: ItemAlign.Center }) { + Button($r('app.string.BAN')) + .onClick(async (): Promise => { + await this.enableNotification(false); }) - } - } - Row() { - Flex({ justifyContent: FlexAlign.SpaceBetween, alignItems: ItemAlign.Center }) { - Button($r('app.string.BAN')) - .onClick(async (): Promise => { - await this.enableNotification(false); - }) - .leftCustomizeButton() - Divider() - .color($r('app.color.comp_divider')) - .vertical(true) - .height(Constants.DIVIDER_HEIGHT) - .strokeWidth(Constants.DIVIDER_WIDTH) - .margin({left: Constants.BUTTON_LEFT, right: Constants.BUTTON_RIGHT}) - Button($r('app.string.ALLOW')) - .onClick(async (): Promise => { - await this.enableNotification(true); - }) - .rightCustomizeButton() - } - .margin({ left: Constants.BUTTON_MARGIN_LEFT, right: Constants.BUTTON_MARGIN_RIGHT }) + .customizeButton() + Divider() + .color($r('app.color.comp_divider')) + .vertical(true) + .height(Constants.DIVIDER_HEIGHT) + .strokeWidth(Constants.DIVIDER_WIDTH) + .margin({left: Constants.BUTTON_LEFT, right: Constants.BUTTON_RIGHT}) + Button($r('app.string.ALLOW')) + .onClick(async (): Promise => { + await this.enableNotification(true); + }) + .customizeButton() } + .margin({ left: Constants.BUTTON_MARGIN_LEFT, right: Constants.BUTTON_MARGIN_RIGHT }) } } - .constraintSize({ maxHeight: Constants.MAXIMUM_HEADER_HEIGHT }) } - .borderRadius(Constants.DIALOG_PRIVACY_BORDER_RADIUS) - .backgroundBlurStyle(BlurStyle.COMPONENT_ULTRA_THICK) - .width(Constants.FULL_WIDTH) - .padding({ bottom: Constants.DIALOG_PADDING_BOTTOM }) - .clip(true) } + .borderRadius(Constants.DIALOG_PRIVACY_BORDER_RADIUS) + .backgroundBlurStyle(BlurStyle.COMPONENT_ULTRA_THICK) .width(Constants.FULL_WIDTH) - .height(Constants.FULL_HEIGHT) + .padding({ bottom: Constants.DIALOG_PADDING_BOTTOM }) + .clip(true) } } .margin({ @@ -199,6 +199,10 @@ struct PermissionDialog { right: this.isBottomPopover ? Constants.DIALOG_MARGIN_VERTICAL : Constants.DIALOG_MARGIN, bottom: this.isBottomPopover ? this.naviHeight : 0 }) + .constraintSize({ + maxHeight: Constants.MAXIMUM_HEADER_HEIGHT, + maxWidth: Constants.MAX_DIALOG_WIDTH + }) } async updateApplicationName(bundleName: string): Promise { diff --git a/services/dialog_ui/enable_notification_dialog/entry/src/main/ets/pages/pcNotificationDialog.ets b/services/dialog_ui/enable_notification_dialog/entry/src/main/ets/pages/pcNotificationDialog.ets index afa4c6e2b..1ae25afdd 100644 --- a/services/dialog_ui/enable_notification_dialog/entry/src/main/ets/pages/pcNotificationDialog.ets +++ b/services/dialog_ui/enable_notification_dialog/entry/src/main/ets/pages/pcNotificationDialog.ets @@ -16,7 +16,12 @@ import bundleResourceManager from '@ohos.bundle.bundleResourceManager'; import display from '@ohos.display'; import window from '@ohos.window'; -import { titleTrim, calContainerWidth } from '../common/utils'; +import { + titleTrim, + calContainerWidth, + getFontSizeScale, + sourceToVp, + getLimitFontSize } from '../common/utils'; import Constants from '../common/constant'; import fs from '@ohos.file.fs'; import configPolicy from '@ohos.configPolicy'; @@ -26,6 +31,7 @@ import UIExtensionContentSession from '@ohos.app.ability.UIExtensionContentSessi import i18n from '@ohos.i18n'; import { MeasureOptions } from '@ohos.measure'; import { MeasureUtils } from '@ohos.arkui.UIContext'; +import common from '@ohos.app.ability.common'; const TAG = 'NotificationDialog_Service '; @@ -48,7 +54,11 @@ let storage = LocalStorage.getShared(); .type(ButtonType.Normal) .backgroundColor($r('sys.color.comp_background_tertiary')) .fontColor($r('sys.color.font_emphasize')) - .fontSize($r('sys.float.Body_L')) + .fontSize( + getLimitFontSize( + sourceToVp($r('sys.float.Body_L')), + getFontSizeScale(getContext(this) as common.UIAbilityContext, Constants.FONT_SCALE_MAX)) + ) .fontWeight(FontWeight.Medium) .height(Constants.PC_BUTTON_HEIGHT) .width('50%') @@ -94,7 +104,7 @@ struct PermissionDialog { dialog?: EnableNotificationDialog; session?: UIExtensionContentSession; controller?: CustomDialogController; - @State titleContainerWidth: string|number = 'auto'; + @State titleContainerWidth: string | number = 'auto'; build() { Row() { @@ -117,8 +127,14 @@ struct PermissionDialog { .fontSize($r('sys.float.Title_S')) .fontColor($r('sys.color.font_primary')) .fontWeight(FontWeight.Bold) - .minFontSize(Constants.TITLE_MIN_FONT_SIZE) - .maxFontSize($r('sys.float.Title_S')) + .minFontSize( + getLimitFontSize(Constants.TITLE_MIN_FONT_SIZE, + getFontSizeScale(getContext(this) as common.UIAbilityContext, Constants.FONT_SCALE_MAX)) + ) + .maxFontSize( + getLimitFontSize(sourceToVp($r('sys.float.Title_S')), + getFontSizeScale(getContext(this) as common.UIAbilityContext, Constants.FONT_SCALE_MAX)) + ) .heightAdaptivePolicy(TextHeightAdaptivePolicy.MAX_LINES_FIRST) .maxLines(2) .textOverflow({overflow: TextOverflow.Ellipsis}) @@ -147,7 +163,10 @@ struct PermissionDialog { Text() { Span(this.content) } - .fontSize($r('sys.float.Body_L')) + .fontSize( + getLimitFontSize(sourceToVp($r('sys.float.Body_L')), + getFontSizeScale(getContext(this) as common.UIAbilityContext)) + ) .fontWeight(FontWeight.Medium) .fontColor($r('sys.color.font_primary')) .margin({ -- Gitee From 78bd98baa4c5f80bde48ee661e040054c2c0dbfa Mon Sep 17 00:00:00 2001 From: songbao1 Date: Tue, 27 Aug 2024 15:30:17 +0800 Subject: [PATCH 137/167] =?UTF-8?q?=E6=89=93=E7=82=B9=E9=97=AE=E9=A2=98?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: luojingsong Change-Id: I3b601de60619222e6e4f96f8aa80ec54a9f31941 --- .../base_publish_process.cpp | 3 +++ .../ans/src/advanced_notification_publish_service.cpp | 1 - .../ans/src/advanced_notification_slot_service.cpp | 10 +++++++--- services/ans/src/notification_subscriber_manager.cpp | 3 --- 4 files changed, 10 insertions(+), 7 deletions(-) diff --git a/services/ans/src/advanced_notification_publish/base_publish_process.cpp b/services/ans/src/advanced_notification_publish/base_publish_process.cpp index afe9ddcbe..4b28139f9 100644 --- a/services/ans/src/advanced_notification_publish/base_publish_process.cpp +++ b/services/ans/src/advanced_notification_publish/base_publish_process.cpp @@ -43,11 +43,14 @@ ErrCode BasePublishProcess::CommonPublishCheck(const sptr & HaMetaMessage message = HaMetaMessage(EventSceneId::SCENE_2, EventBranchId::BRANCH_1); if (request->GetReceiverUserId() != SUBSCRIBE_USER_INIT) { if (!AccessTokenHelper::IsSystemApp()) { + message.Message("Not SystemApp"); message.ErrorCode(ERR_ANS_NON_SYSTEM_APP); NotificationAnalyticsUtil::ReportPublishFailedEvent(request, message); return ERR_ANS_NON_SYSTEM_APP; } if (!AccessTokenHelper::CheckPermission(OHOS_PERMISSION_NOTIFICATION_CONTROLLER)) { + message.BranchId(EventBranchId::BRANCH_3); + message.Message("CheckPermission denied"); message.ErrorCode(ERR_ANS_NON_SYSTEM_APP); NotificationAnalyticsUtil::ReportPublishFailedEvent(request, message); return ERR_ANS_PERMISSION_DENIED; diff --git a/services/ans/src/advanced_notification_publish_service.cpp b/services/ans/src/advanced_notification_publish_service.cpp index fd3b9435b..df1562f7b 100644 --- a/services/ans/src/advanced_notification_publish_service.cpp +++ b/services/ans/src/advanced_notification_publish_service.cpp @@ -164,7 +164,6 @@ ErrCode AdvancedNotificationService::Publish(const std::string &label, const spt } } while (0); - NotificationAnalyticsUtil::ReportPublishFailedEvent(request, message); SendPublishHiSysEvent(request, result); return result; } diff --git a/services/ans/src/advanced_notification_slot_service.cpp b/services/ans/src/advanced_notification_slot_service.cpp index 3a684e88e..a0c85e8ea 100644 --- a/services/ans/src/advanced_notification_slot_service.cpp +++ b/services/ans/src/advanced_notification_slot_service.cpp @@ -800,7 +800,8 @@ ErrCode AdvancedNotificationService::SetAdditionConfig(const std::string &key, c if (sync_result != ERR_OK) { ANS_LOGE("Sync addition config result: %{public}d, key: %{public}s, value: %{public}s", sync_result, key.c_str(), value.c_str()); - message.ErrorCode(sync_result).Append(" Sync failed"); + message.Message("Set addition config " + key + " ret " + std::to_string(sync_result)); + message.ErrorCode(sync_result); NotificationAnalyticsUtil::ReportModifyEvent(message); return sync_result; } @@ -814,8 +815,11 @@ ErrCode AdvancedNotificationService::SetAdditionConfig(const std::string &key, c notificationSvrQueue_->wait(handler); ANS_LOGI("Set addition config result: %{public}d, key: %{public}s, value: %{public}s", result, key.c_str(), value.c_str()); - message.ErrorCode(result); - NotificationAnalyticsUtil::ReportModifyEvent(message); + if (result != ERR_OK) { + message.ErrorCode(result); + message.Message("Set addition config " + key + " ret " + std::to_string(result)); + NotificationAnalyticsUtil::ReportModifyEvent(message); + } return result; } diff --git a/services/ans/src/notification_subscriber_manager.cpp b/services/ans/src/notification_subscriber_manager.cpp index 52d1ffe26..34de83985 100644 --- a/services/ans/src/notification_subscriber_manager.cpp +++ b/services/ans/src/notification_subscriber_manager.cpp @@ -508,9 +508,6 @@ void NotificationSubscriberManager::NotifyCanceledInner( liveViewContent->FillPictureMarshallingMap(); } - OHOS::Notification::HaMetaMessage haMetaMessage = HaMetaMessage(1, 6).ErrorCode(ERR_OK); - ReportDeleteFailedEventPushByNotification(notification, haMetaMessage, deleteReason, "success"); - ANS_LOGI("CancelNotification key = %{public}s", notification->GetKey().c_str()); for (auto record : subscriberRecordList_) { ANS_LOGD("%{public}s record->userId = <%{public}d>", __FUNCTION__, record->userId); -- Gitee From a00be35da78ce59a839f426f19cc25e298048f8d Mon Sep 17 00:00:00 2001 From: songbao1 Date: Sat, 31 Aug 2024 17:03:13 +0800 Subject: [PATCH 138/167] =?UTF-8?q?=E6=89=93=E7=82=B9=E6=9C=AA=E4=B8=8A?= =?UTF-8?q?=E6=8A=A5uid?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: songbao1 --- services/ans/src/common/notification_analytics_util.cpp | 1 + 1 file changed, 1 insertion(+) diff --git a/services/ans/src/common/notification_analytics_util.cpp b/services/ans/src/common/notification_analytics_util.cpp index 3659b6b02..5f9f2f0c9 100644 --- a/services/ans/src/common/notification_analytics_util.cpp +++ b/services/ans/src/common/notification_analytics_util.cpp @@ -203,6 +203,7 @@ void NotificationAnalyticsUtil::ReportNotificationEvent(const sptr(request->GetNotificationType()), contentType); want.SetParam("id", request->GetNotificationId()); + want.SetParam("uid", request->GetOwnerUid()); want.SetParam("slotType", static_cast(slotType)); want.SetParam("contentType", std::to_string(static_cast(contentType))); -- Gitee From 6c12b636b2078fbc4ae16ad279b73ecaf6f5b02c Mon Sep 17 00:00:00 2001 From: Ricky Date: Wed, 20 Nov 2024 15:59:09 +0800 Subject: [PATCH 139/167] fix music notification show reminder Signed-off-by: Ricky Change-Id: Ia9602af4d68a8a96bb0933640e0c3ea1a58f0d45 --- services/ans/src/advanced_notification_utils.cpp | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/services/ans/src/advanced_notification_utils.cpp b/services/ans/src/advanced_notification_utils.cpp index 65087524a..22f669fc1 100644 --- a/services/ans/src/advanced_notification_utils.cpp +++ b/services/ans/src/advanced_notification_utils.cpp @@ -1713,6 +1713,12 @@ ErrCode AdvancedNotificationService::PrePublishNotificationBySa(const sptrGetOwnerUid() == DEFAULT_UID) { + request->SetOwnerUid(request->GetCreatorUid()); + } + if (request->GetOwnerBundleName().empty()) { + request->SetOwnerBundleName(request->GetCreatorBundleName()); + } ANS_LOGD("creator uid=%{public}d, userId=%{public}d, bundleName=%{public}s ", uid, userId, bundle.c_str()); return ERR_OK; -- Gitee From 24a72d2084fef981aa31fde013d5ca3f65174770 Mon Sep 17 00:00:00 2001 From: xdongs Date: Tue, 26 Nov 2024 11:01:16 +0800 Subject: [PATCH 140/167] =?UTF-8?q?=E6=89=B9=E9=87=8F=E6=8F=92=E5=85=A5=20?= =?UTF-8?q?=EF=BC=88cherry=20picked=20commit=20from=20=20Signed-off-by:=20xd?= =?UTF-8?q?ongs=20?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../ans/src/notification_rdb_data_mgr.cpp | 20 ++++++++++--------- 1 file changed, 11 insertions(+), 9 deletions(-) diff --git a/services/ans/src/notification_rdb_data_mgr.cpp b/services/ans/src/notification_rdb_data_mgr.cpp index c7d99df5c..df81ee011 100644 --- a/services/ans/src/notification_rdb_data_mgr.cpp +++ b/services/ans/src/notification_rdb_data_mgr.cpp @@ -250,19 +250,21 @@ int32_t NotificationDataMgr::InsertBatchData(const std::unordered_map buckets; for (auto &value : values) { NativeRdb::ValuesBucket valuesBucket; valuesBucket.PutString(NOTIFICATION_KEY, value.first); valuesBucket.PutString(NOTIFICATION_VALUE, value.second); - ret = rdbStore_->InsertWithConflictResolution(rowId, tableName, valuesBucket, - NativeRdb::ConflictResolution::ON_CONFLICT_REPLACE); - if (ret == NativeRdb::E_SQLITE_CORRUPT) { - RestoreForMasterSlaver(); - } - if (ret != NativeRdb::E_OK) { - ANS_LOGE("Insert batch operation failed, result: %{public}d.", ret); - return NativeRdb::E_ERROR; - } + buckets.emplace_back(valuesBucket); + } + ret = rdbStore_->BatchInsert(rowId, tableName, buckets); + ANS_LOGI("BatchInsert ret = %{public}d affect row = %{public}zu", ret, rowId); + if (ret == NativeRdb::E_SQLITE_CORRUPT) { + RestoreForMasterSlaver(); + } + if (ret != NativeRdb::E_OK) { + ANS_LOGE("Insert batch operation failed, result: %{public}d.", ret); + return NativeRdb::E_ERROR; } } return NativeRdb::E_OK; -- Gitee From 541186734ae6c7256640d333d77a6b97c3814379 Mon Sep 17 00:00:00 2001 From: xdongs2009 Date: Thu, 28 Nov 2024 03:39:28 +0000 Subject: [PATCH 141/167] update services/ans/src/notification_rdb_data_mgr.cpp. Signed-off-by: xdongs2009 --- services/ans/src/notification_rdb_data_mgr.cpp | 1 - 1 file changed, 1 deletion(-) diff --git a/services/ans/src/notification_rdb_data_mgr.cpp b/services/ans/src/notification_rdb_data_mgr.cpp index df81ee011..7b9d4f772 100644 --- a/services/ans/src/notification_rdb_data_mgr.cpp +++ b/services/ans/src/notification_rdb_data_mgr.cpp @@ -258,7 +258,6 @@ int32_t NotificationDataMgr::InsertBatchData(const std::unordered_mapBatchInsert(rowId, tableName, buckets); - ANS_LOGI("BatchInsert ret = %{public}d affect row = %{public}zu", ret, rowId); if (ret == NativeRdb::E_SQLITE_CORRUPT) { RestoreForMasterSlaver(); } -- Gitee From 7c055c924a8c470e7e555af76e5fd7fa98cc2899 Mon Sep 17 00:00:00 2001 From: Ricky Date: Tue, 26 Nov 2024 20:49:53 +0800 Subject: [PATCH 142/167] remove ownerUid is default check Signed-off-by: Ricky Change-Id: I3b8b084b373d4cbf6f373c8d089016d1bc0fb12f --- frameworks/js/napi/src/subscribe.cpp | 2 +- .../ans/src/advanced_notification_slot_service.cpp | 11 ++++++++--- 2 files changed, 9 insertions(+), 4 deletions(-) diff --git a/frameworks/js/napi/src/subscribe.cpp b/frameworks/js/napi/src/subscribe.cpp index 23af5f9f1..f14fea9fc 100644 --- a/frameworks/js/napi/src/subscribe.cpp +++ b/frameworks/js/napi/src/subscribe.cpp @@ -144,7 +144,7 @@ SubscriberInstance::SubscriberInstance() SubscriberInstance::~SubscriberInstance() { if (unsubscribeCallbackInfo_.tsfn != nullptr) { - napi_release_threadsafe_function(unsubscribeCallbackInfo_.tsfn, napi_tsfn_abort); + napi_release_threadsafe_function(unsubscribeCallbackInfo_.tsfn, napi_tsfn_release); } if (canceCallbackInfo_.ref != nullptr) { napi_delete_reference(canceCallbackInfo_.env, canceCallbackInfo_.ref); diff --git a/services/ans/src/advanced_notification_slot_service.cpp b/services/ans/src/advanced_notification_slot_service.cpp index afc71a191..86c38eb4a 100644 --- a/services/ans/src/advanced_notification_slot_service.cpp +++ b/services/ans/src/advanced_notification_slot_service.cpp @@ -554,8 +554,8 @@ void AdvancedNotificationService::GenerateSlotReminderMode(const sptrGetBundleName(); - ANS_LOGI("The reminder mode of %{public}d is %{public}d in %{public}s", - slot->GetType(), slot->GetReminderMode(), bundleName.c_str()); + ANS_LOGI("The reminder mode of %{public}d is %{public}d in %{public}s,specifiedSlot:%{public}d default:%{public}u", + slot->GetType(), slot->GetReminderMode(), bundleName.c_str(), isSpecifiedSlot, defaultSlotFlags); } uint32_t AdvancedNotificationService::GetDefaultSlotFlags(const sptr &request) @@ -563,9 +563,14 @@ uint32_t AdvancedNotificationService::GetDefaultSlotFlags(const sptrGetNotificationControlFlags(); // SA publish own's notification with banner + if ((notificationControlFlags & NotificationConstant::ReminderFlag::SA_SELF_BANNER_FLAG) != 0) { + ANS_LOGI("Creator:%{public}s %{public}d,Owner: %{public}s %{public}d, controlFlags:%{public}d", + request->GetCreatorBundleName().c_str(), request->GetCreatorUid(), request->GetOwnerBundleName().c_str(), + request->GetOwnerUid(), request->GetNotificationControlFlags()); + } if (((notificationControlFlags & NotificationConstant::ReminderFlag::SA_SELF_BANNER_FLAG) != 0) && (request->GetCreatorUid() == IPCSkeleton::GetCallingUid() && request->GetCreatorBundleName().empty() && - request->GetOwnerBundleName().empty() && request->GetOwnerUid() == DEFAULT_UID)) { + request->GetOwnerBundleName().empty())) { return (flags |= NotificationConstant::ReminderFlag::BANNER_FLAG); } -- Gitee From 5983ff453ea16d9aaee25eef6c76f5748230bd9f Mon Sep 17 00:00:00 2001 From: xdongs Date: Thu, 5 Dec 2024 10:57:52 +0800 Subject: [PATCH 143/167] =?UTF-8?q?=E4=B8=8D=E5=85=81=E8=AE=B8=E5=AD=97?= =?UTF-8?q?=E4=BD=93=E5=A4=A7=E5=B0=8F=20=EF=BC=88cherry=20picked=20commit?= =?UTF-8?q?=20from=20=20Signed-off-by:=20xdongs=20?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../entry/src/main/ets/common/constant.ets | 2 +- .../entry/src/main/ets/pages/notificationDialog.ets | 3 ++- .../entry/src/main/ets/pages/pcNotificationDialog.ets | 3 ++- 3 files changed, 5 insertions(+), 3 deletions(-) diff --git a/services/dialog_ui/enable_notification_dialog/entry/src/main/ets/common/constant.ets b/services/dialog_ui/enable_notification_dialog/entry/src/main/ets/common/constant.ets index 5bdf485fe..103426d75 100644 --- a/services/dialog_ui/enable_notification_dialog/entry/src/main/ets/common/constant.ets +++ b/services/dialog_ui/enable_notification_dialog/entry/src/main/ets/common/constant.ets @@ -147,7 +147,7 @@ export default class Constants { public static CROSS_LINE_RESIZE_PARAM = 1.25; public static FONT_SCALE_DEFAULT = 1; - public static FONT_SCALE_MAX = 2; + public static FONT_SCALE_MAX = 1.8; public static MAX_DIALOG_WIDTH = 400; //pc diff --git a/services/dialog_ui/enable_notification_dialog/entry/src/main/ets/pages/notificationDialog.ets b/services/dialog_ui/enable_notification_dialog/entry/src/main/ets/pages/notificationDialog.ets index fc99751e7..bdc6bd9bc 100644 --- a/services/dialog_ui/enable_notification_dialog/entry/src/main/ets/pages/notificationDialog.ets +++ b/services/dialog_ui/enable_notification_dialog/entry/src/main/ets/pages/notificationDialog.ets @@ -138,7 +138,8 @@ struct PermissionDialog { let containerWidth = newValue.width as number; let options: MeasureOptions = { textContent: $r('app.string.group_label_notification', this.appName), - fontSize: $r('sys.float.ohos_id_text_size_headline8'), + fontSize: getLimitFontSize(sourceToVp($r('sys.float.ohos_id_text_size_headline8')), + getFontSizeScale(getContext(this) as common.UIAbilityContext, Constants.FONT_SCALE_MAX)), fontWeight: FontWeight.Bold, }; this.titleContainerWidth = calContainerWidth(containerWidth, options, diff --git a/services/dialog_ui/enable_notification_dialog/entry/src/main/ets/pages/pcNotificationDialog.ets b/services/dialog_ui/enable_notification_dialog/entry/src/main/ets/pages/pcNotificationDialog.ets index 1ae25afdd..2e9c3e103 100644 --- a/services/dialog_ui/enable_notification_dialog/entry/src/main/ets/pages/pcNotificationDialog.ets +++ b/services/dialog_ui/enable_notification_dialog/entry/src/main/ets/pages/pcNotificationDialog.ets @@ -150,7 +150,8 @@ struct PermissionDialog { let containerWidth = newValue.width as number; let options: MeasureOptions = { textContent: $r('app.string.group_label_notification', this.appName), - fontSize: $r('sys.float.Title_S'), + fontSize: getLimitFontSize(sourceToVp($r('sys.float.Title_S')), + getFontSizeScale(getContext(this) as common.UIAbilityContext, Constants.FONT_SCALE_MAX)), fontWeight: FontWeight.Bold, }; this.titleContainerWidth = calContainerWidth(containerWidth, options, -- Gitee From 406cf44b90f9a59eb6263a13bd9e6e208ecb54e0 Mon Sep 17 00:00:00 2001 From: baozeyu <2455966574@qq.com> Date: Mon, 2 Dec 2024 15:23:08 +0800 Subject: [PATCH 144/167] =?UTF-8?q?cherry=20pick=20bbffa5d=20from=20https:?= =?UTF-8?q?//gitee.com/baozeyu/notification=5Fdistributed=5Fnotification?= =?UTF-8?q?=5Fservice/pulls/2482=20cherry=20pick=20e2a494e=20from=20https:?= =?UTF-8?q?//gitee.com/baozeyu/notification=5Fdistributed=5Fnotification?= =?UTF-8?q?=5Fservice/pulls/2468=20=E5=85=8D=E6=89=93=E6=89=B0=E6=98=BE?= =?UTF-8?q?=E7=A4=BA=E9=94=81=E5=B1=8F=E9=80=9A=E7=9F=A5?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: baozeyu <2455966574@qq.com> Change-Id: Ia1245deba9989b855cc6218e1be8c7f17aedc68b --- services/ans/src/advanced_notification_service.cpp | 1 - 1 file changed, 1 deletion(-) diff --git a/services/ans/src/advanced_notification_service.cpp b/services/ans/src/advanced_notification_service.cpp index a0c6a9c08..891e6858c 100644 --- a/services/ans/src/advanced_notification_service.cpp +++ b/services/ans/src/advanced_notification_service.cpp @@ -813,7 +813,6 @@ void AdvancedNotificationService::DoNotDisturbUpdataReminderFlags(const std::sha } flags->SetSoundEnabled(NotificationConstant::FlagStatus::CLOSE); record->notification->SetEnableSound(false); - flags->SetLockScreenVisblenessEnabled(false); record->request->SetVisibleness(NotificationConstant::VisiblenessType::SECRET); flags->SetBannerEnabled(false); flags->SetLightScreenEnabled(false); -- Gitee From a8e167f04bfa6466c37602f750da1ce0f27b561e Mon Sep 17 00:00:00 2001 From: wangsen1994 Date: Thu, 28 Nov 2024 16:57:45 +0800 Subject: [PATCH 145/167] =?UTF-8?q?cherry=20pick=20ac0aaaa=20from=20https:?= =?UTF-8?q?//gitee.com/wangsen1994/notification=5Fdistributed=5Fnotificati?= =?UTF-8?q?on=5Fservice/pulls/2478=20=E6=94=AF=E6=8C=81=E6=8C=81=E4=B9=85?= =?UTF-8?q?=E5=8C=96=E5=85=8B=E9=9A=86=E4=BF=A1=E6=81=AF?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: wangsen1994 --- .../include/advanced_notification_service.h | 14 +- .../notification_clone_bundle_service.h | 4 +- .../notification_clone_disturb_service.h | 4 +- .../ans/include/notification_clone_manager.h | 2 + .../ans/include/notification_clone_template.h | 2 + .../ans/include/notification_preferences.h | 13 ++ .../notification_preferences_database.h | 15 ++ .../advanced_notification_publish_service.cpp | 2 +- .../ans/src/advanced_notification_utils.cpp | 127 +++++++++++++- .../notification_clone_bundle_service.cpp | 37 ++-- .../notification_clone_disturb_service.cpp | 40 ++--- .../src/clone/notification_clone_manager.cpp | 40 ++++- services/ans/src/notification_preferences.cpp | 79 ++++++++- .../src/notification_preferences_database.cpp | 163 ++++++++++++++++++ services/ans/src/system_event_observer.cpp | 3 + 15 files changed, 490 insertions(+), 55 deletions(-) diff --git a/services/ans/include/advanced_notification_service.h b/services/ans/include/advanced_notification_service.h index 4e7890bf7..1d10526bc 100644 --- a/services/ans/include/advanced_notification_service.h +++ b/services/ans/include/advanced_notification_service.h @@ -48,6 +48,7 @@ #ifdef NOTIFICATION_SMART_REMINDER_SUPPORTED #include "reminder_swing_decision_center.h" #endif +#include "notification_clone_bundle_info.h" namespace OHOS { namespace Notification { @@ -561,7 +562,7 @@ public: */ ErrCode CanPopEnableNotificationDialog(const sptr &callback, bool &canPop, std::string &bundleName) override; - + /** * @brief remove enable notification dialog. * @@ -1163,6 +1164,8 @@ public: int32_t OnBackup(MessageParcel& data, MessageParcel& reply); int32_t OnRestore(MessageParcel& data, MessageParcel& reply); + + void UpdateCloneBundleInfo(const NotificationCloneBundleInfo cloneBundleInfo); protected: /** * @brief Query whether there is a agent relationship between the two apps. @@ -1382,7 +1385,7 @@ private: const std::vector extraInfoKeys, sptr &newRequest); ErrCode IsAllowedRemoveSlot(const sptr &bundleOption, const NotificationConstant::SlotType &slotType); - void HandleBadgeEnabledChanged(const sptr &bundleOption, bool &enabled); + void HandleBadgeEnabledChanged(const sptr &bundleOption, bool enabled); ErrCode CheckBundleOptionValid(sptr &bundleOption); bool IsNeedNotifyConsumed(const sptr &request); ErrCode AddRecordToMemory(const std::shared_ptr &record, @@ -1431,6 +1434,13 @@ private: bool IsSystemUser(int32_t userId); ErrCode UpdateFlowCtrl(const std::shared_ptr &record); ErrCode PublishFlowControlInner(const std::shared_ptr &record); + ErrCode SetEnabledForBundleSlotInner(const sptr &bundleOption, + const sptr &bundle, + const NotificationConstant::SlotType &slotType, bool enabled, bool isForceControl); + ErrCode AddSlotThenPublishEvent( + const sptr &slot, + const sptr &bundle, + bool enabled, bool isForceControl); private: static sptr instance_; static std::mutex instanceMutex_; diff --git a/services/ans/include/notification_clone_bundle_service.h b/services/ans/include/notification_clone_bundle_service.h index 7e30c4664..f1a6b6ab8 100644 --- a/services/ans/include/notification_clone_bundle_service.h +++ b/services/ans/include/notification_clone_bundle_service.h @@ -30,10 +30,8 @@ public: ~NotificationCloneBundle() override; static std::shared_ptr GetInstance(); ErrCode OnBackup(nlohmann::json &jsonObject) override; + void OnRestoreStart(const std::string bundleName, int32_t appIndex, int32_t userId, int32_t uid) override; void OnRestore(const nlohmann::json &jsonObject) override; - void OnBundleDataAdd(const sptr &bundleOption); - void OnBundleDataUpdate(const sptr &bundleOption); - void HandleBundleEvent(const std::string bundleName, int32_t appIndex, int32_t uid); void OnUserSwitch(int32_t userId) override; private: std::vector bundlesInfo_; diff --git a/services/ans/include/notification_clone_disturb_service.h b/services/ans/include/notification_clone_disturb_service.h index ab8a3939c..47dfa98a3 100644 --- a/services/ans/include/notification_clone_disturb_service.h +++ b/services/ans/include/notification_clone_disturb_service.h @@ -31,9 +31,7 @@ public: static std::shared_ptr GetInstance(); ErrCode OnBackup(nlohmann::json &jsonObject) override; void OnRestore(const nlohmann::json &jsonObject) override; - void OnBundleDataAdd(const sptr &bundleOption); - void OnBundleDataUpdate(const sptr &bundleOption); - void HandlerBundleEvent(const std::string bundleName, int32_t appIndex, int32_t uid); + void OnRestoreStart(const std::string bundleName, int32_t appIndex, int32_t userId, int32_t uid) override; int32_t GetBundleUid(const std::string bundleName, int32_t userId, int32_t appIndex); void GetProfileUid(int32_t userId, std::map& uidMap, std::vector trustList, std::vector& exitBunldleList, diff --git a/services/ans/include/notification_clone_manager.h b/services/ans/include/notification_clone_manager.h index 1328e8fd9..a93a9846f 100644 --- a/services/ans/include/notification_clone_manager.h +++ b/services/ans/include/notification_clone_manager.h @@ -21,6 +21,7 @@ #include "unique_fd.h" #include "iremote_proxy.h" +#include "common_event_data.h" #include "notification_clone_template.h" namespace OHOS { namespace Notification { @@ -32,6 +33,7 @@ public: int32_t OnBackup(MessageParcel& data, MessageParcel& reply); int32_t OnRestore(MessageParcel& data, MessageParcel& reply); void OnUserSwitch(int32_t userId); + void OnRestoreStart(EventFwk::Want want); private: NotificationCloneManager(); diff --git a/services/ans/include/notification_clone_template.h b/services/ans/include/notification_clone_template.h index b9baa7472..02a486acd 100644 --- a/services/ans/include/notification_clone_template.h +++ b/services/ans/include/notification_clone_template.h @@ -29,6 +29,8 @@ public: virtual ErrCode OnBackup(nlohmann::json &jsonObject) = 0; virtual void OnRestore(const nlohmann::json &jsonObject) = 0; virtual void OnUserSwitch(int32_t userId) = 0; + virtual void OnRestoreStart(const std::string bundleName, int32_t appIndex, + int32_t userId, int32_t uid) = 0; }; } // namespace Notification } // namespace OHOS diff --git a/services/ans/include/notification_preferences.h b/services/ans/include/notification_preferences.h index 9665a5885..793a50030 100644 --- a/services/ans/include/notification_preferences.h +++ b/services/ans/include/notification_preferences.h @@ -386,6 +386,19 @@ public: void GetAllCLoneBundlesInfo(int32_t userId, std::vector &cloneBundles); void UpdateCloneBundleInfo(int32_t userId, const NotificationCloneBundleInfo& cloneBundleInfo); bool IsNotificationSlotFlagsExists(const sptr &bundleOption); + bool DelCloneProfileInfo(const int32_t &userId, const sptr& info); + bool UpdateBatchCloneProfileInfo(const int32_t &userId, + const std::vector>& profileInfo); + void GetAllCloneProfileInfo(const int32_t &userId, + std::vector>& profilesInfo); + void GetAllCloneBundleInfo(const int32_t &userId, std::vector& cloneBundleInfo); + bool UpdateBatchCloneBundleInfo(const int32_t &userId, + const std::vector& cloneBundleInfo); + bool DelCloneBundleInfo(const int32_t &userId, const NotificationCloneBundleInfo& cloneBundleInfo); + bool DelBatchCloneBundleInfo(const int32_t &userId, + const std::vector& cloneBundleInfo); + bool DelBatchCloneProfileInfo(const int32_t &userId, + const std::vector>& profileInfo); private: bool GetBundleInfo(NotificationPreferencesInfo &preferencesInfo, diff --git a/services/ans/include/notification_preferences_database.h b/services/ans/include/notification_preferences_database.h index 00b49d035..b6c6eeca1 100644 --- a/services/ans/include/notification_preferences_database.h +++ b/services/ans/include/notification_preferences_database.h @@ -247,6 +247,19 @@ public: bool UpdateBundleSlotToDisturbeDB(int32_t userId, const std::string &bundleName, const int32_t &bundleUid, const std::vector> &slots); bool IsNotificationSlotFlagsExists(const sptr &bundleOption); + bool DelCloneProfileInfo(const int32_t &userId, const sptr& info); + bool UpdateBatchCloneProfileInfo(const int32_t &userId, + const std::vector>& profileInfo); + void GetAllCloneProfileInfo(const int32_t &userId, + std::vector>& profilesInfo); + void GetAllCloneBundleInfo(const int32_t &userId, std::vector& cloneBundleInfo); + bool UpdateBatchCloneBundleInfo(const int32_t &userId, + const std::vector& cloneBundleInfo); + bool DelCloneBundleInfo(const int32_t &userId, const NotificationCloneBundleInfo& cloneBundleInfo); + bool DelBatchCloneProfileInfo(const int32_t &userId, + const std::vector>& profileInfo); + bool DelBatchCloneBundleInfo(const int32_t &userId, + const std::vector& cloneBundleInfo); private: bool CheckRdbStore(); @@ -320,6 +333,8 @@ private: void ParseSlotAuthorizedStatus(sptr &slot, const std::string &value) const; void ParseSlotAuthHitnCnt(sptr &slot, const std::string &value) const; void ParseSlotReminderMode(sptr &slot, const std::string &value) const; + bool UpdateCloneToDisturbeDB(const int32_t &userId, + const std::unordered_map values); std::string GenerateBundleLablel(const NotificationPreferencesInfo::BundleInfo &bundleInfo) const; std::string GenerateBundleLablel(const NotificationPreferencesInfo::BundleInfo &bundleInfo, diff --git a/services/ans/src/advanced_notification_publish_service.cpp b/services/ans/src/advanced_notification_publish_service.cpp index 35e5ea9ca..cc0298c08 100644 --- a/services/ans/src/advanced_notification_publish_service.cpp +++ b/services/ans/src/advanced_notification_publish_service.cpp @@ -781,7 +781,7 @@ ErrCode AdvancedNotificationService::SetShowBadgeEnabledForBundle( } void AdvancedNotificationService::HandleBadgeEnabledChanged( - const sptr &bundleOption, bool &enabled) + const sptr &bundleOption, bool enabled) { sptr enabledData = new (std::nothrow) EnabledNotificationCallbackData(bundleOption->GetBundleName(), bundleOption->GetUid(), enabled); diff --git a/services/ans/src/advanced_notification_utils.cpp b/services/ans/src/advanced_notification_utils.cpp index 22f669fc1..a71dbdb17 100644 --- a/services/ans/src/advanced_notification_utils.cpp +++ b/services/ans/src/advanced_notification_utils.cpp @@ -48,8 +48,6 @@ #include "advanced_notification_inline.cpp" #include "notification_analytics_util.h" -#include "notification_clone_disturb_service.h" -#include "notification_clone_bundle_service.h" #define CHECK_BUNDLE_OPTION_IS_INVALID(option) \ if (option == nullptr || option->GetBundleName().empty()) { \ @@ -590,10 +588,8 @@ void AdvancedNotificationService::OnBundleDataAdd(const sptrOnBundleDataAdd(bundleOption); }; - NotificationCloneDisturb::GetInstance()->OnBundleDataAdd(bundleOption); notificationSvrQueue_ != nullptr ? notificationSvrQueue_->submit(bundleInstall) : bundleInstall(); } @@ -621,7 +617,6 @@ void AdvancedNotificationService::OnBundleDataUpdate(const sptrOnBundleDataUpdate(bundleOption); notificationSvrQueue_ != nullptr ? notificationSvrQueue_->submit(bundleUpdate) : bundleUpdate(); } @@ -2082,5 +2077,127 @@ ErrCode AdvancedNotificationService::OnRecoverLiveView( BatchCancelTimer(timerIds); return ERR_OK; } + +ErrCode AdvancedNotificationService::SetEnabledForBundleSlotInner( + const sptr &bundleOption, + const sptr &bundle, + const NotificationConstant::SlotType &slotType, bool enabled, bool isForceControl) +{ + sptr slot; + ErrCode result = NotificationPreferences::GetInstance()->GetNotificationSlot(bundle, slotType, slot); + if (result == ERR_ANS_PREFERENCES_NOTIFICATION_SLOT_TYPE_NOT_EXIST || + result == ERR_ANS_PREFERENCES_NOTIFICATION_BUNDLE_NOT_EXIST) { + slot = new (std::nothrow) NotificationSlot(slotType); + if (slot == nullptr) { + ANS_LOGE("Failed to create NotificationSlot ptr."); + return ERR_ANS_NO_MEMORY; + } + GenerateSlotReminderMode(slot, bundleOption); + return AddSlotThenPublishEvent(slot, bundle, enabled, isForceControl); + } else if ((result == ERR_OK) && (slot != nullptr)) { + if (slot->GetEnable() == enabled && slot->GetForceControl() == isForceControl) { + slot->SetAuthorizedStatus(NotificationSlot::AuthorizedStatus::AUTHORIZED); + std::vector> slots; + slots.push_back(slot); + return NotificationPreferences::GetInstance()->AddNotificationSlots(bundle, slots); + } + NotificationPreferences::GetInstance()->RemoveNotificationSlot(bundle, slotType); + return AddSlotThenPublishEvent(slot, bundle, enabled, isForceControl); + } + ANS_LOGE("Set enable slot: GetNotificationSlot failed"); + return result; +} + +ErrCode AdvancedNotificationService::AddSlotThenPublishEvent( + const sptr &slot, + const sptr &bundle, + bool enabled, bool isForceControl) +{ + bool allowed = false; + ErrCode result = NotificationPreferences::GetInstance()->GetNotificationsEnabledForBundle(bundle, allowed); + if (result == ERR_ANS_PREFERENCES_NOTIFICATION_BUNDLE_NOT_EXIST) { + result = ERR_OK; + allowed = CheckApiCompatibility(bundle); + SetDefaultNotificationEnabled(bundle, allowed); + } + + slot->SetEnable(enabled); + slot->SetForceControl(isForceControl); + slot->SetAuthorizedStatus(NotificationSlot::AuthorizedStatus::AUTHORIZED); + std::vector> slots; + slots.push_back(slot); + result = NotificationPreferences::GetInstance()->AddNotificationSlots(bundle, slots); + if (result != ERR_OK) { + ANS_LOGE("Set enable slot: AddNotificationSlot failed"); + return result; + } + + if (!slot->GetEnable()) { + RemoveNotificationBySlot(bundle, slot, NotificationConstant::DISABLE_SLOT_REASON_DELETE); + } else { + if (!slot->GetForceControl() && !allowed) { + RemoveNotificationBySlot(bundle, slot, NotificationConstant::DISABLE_NOTIFICATION_REASON_DELETE); + } + } + + PublishSlotChangeCommonEvent(bundle); + return result; +} + +void AdvancedNotificationService::UpdateCloneBundleInfo(const NotificationCloneBundleInfo cloneBundleInfo) +{ + ANS_LOGI("Event bundle update %{public}s.", cloneBundleInfo.Dump().c_str()); + if (notificationSvrQueue_ == nullptr) { + return; + } + + ffrt::task_handle handler = notificationSvrQueue_->submit_h(std::bind([&, cloneBundleInfo]() { + sptr bundle = new (std::nothrow) NotificationBundleOption( + cloneBundleInfo.GetBundleName(), cloneBundleInfo.GetUid()); + if (bundle == nullptr) { + return; + } + bundle->SetAppIndex(cloneBundleInfo.GetAppIndex()); + if (NotificationPreferences::GetInstance()->SetNotificationsEnabledForBundle(bundle, + cloneBundleInfo.GetEnableNotification()) == ERR_OK) { + SetSlotFlagsTrustlistsAsBundle(bundle); + sptr bundleData = new (std::nothrow) EnabledNotificationCallbackData( + bundle->GetBundleName(), bundle->GetUid(), cloneBundleInfo.GetEnableNotification()); + if (bundleData == nullptr) { + return; + } + NotificationSubscriberManager::GetInstance()->NotifyEnabledNotificationChanged(bundleData); + } else { + ANS_LOGW("Set notification enable failed."); + return; + } + + if (cloneBundleInfo.GetSlotInfo().empty()) { + PublishSlotChangeCommonEvent(bundle); + } + if (NotificationPreferences::GetInstance()->SetNotificationSlotFlagsForBundle(bundle, + cloneBundleInfo.GetSlotFlags()) != ERR_OK) { + ANS_LOGW("Set notification slot failed."); + return; + } + if (UpdateSlotReminderModeBySlotFlags(bundle, cloneBundleInfo.GetSlotFlags()) != ERR_OK) { + ANS_LOGW("Set notification reminder slot failed."); + return; + } + + if (NotificationPreferences::GetInstance()->SetShowBadge(bundle, cloneBundleInfo.GetIsShowBadge()) == ERR_OK) { + HandleBadgeEnabledChanged(bundle, cloneBundleInfo.GetIsShowBadge()); + } else { + ANS_LOGW("Set notification badge failed."); + } + + for (auto& cloneSlot : cloneBundleInfo.GetSlotInfo()) { + if (SetEnabledForBundleSlotInner(bundle, bundle, cloneSlot.slotType_, cloneSlot.enable_, + cloneSlot.isForceControl_) != ERR_OK) { + ANS_LOGW("Set notification slots failed %{public}s.", cloneSlot.Dump().c_str()); + } + } + })); +} } // namespace Notification } // namespace OHOS diff --git a/services/ans/src/clone/notification_clone_bundle_service.cpp b/services/ans/src/clone/notification_clone_bundle_service.cpp index 3511ce3a0..4dae3d501 100644 --- a/services/ans/src/clone/notification_clone_bundle_service.cpp +++ b/services/ans/src/clone/notification_clone_bundle_service.cpp @@ -20,6 +20,7 @@ #include "notification_clone_util.h" #include "notification_clone_bundle_info.h" #include "os_account_manager_helper.h" +#include "advanced_notification_service.h" namespace OHOS { namespace Notification { @@ -75,7 +76,10 @@ void NotificationCloneBundle::OnRestore(const nlohmann::json &jsonObject) int32_t userId = NotificationCloneUtil::GetActiveUserId(); std::unique_lock lock(lock_); - bundlesInfo_.clear(); + if (!bundlesInfo_.empty()) { + NotificationPreferences::GetInstance()->DelBatchCloneBundleInfo(userId, bundlesInfo_); + bundlesInfo_.clear(); + } for (const auto &profile : jsonObject) { NotificationCloneBundleInfo cloneBundleInfo;; cloneBundleInfo.FromJson(profile); @@ -95,41 +99,32 @@ void NotificationCloneBundle::OnRestore(const nlohmann::json &jsonObject) continue; } bundle->SetUid(uid); - NotificationPreferences::GetInstance()->UpdateCloneBundleInfo(userId, *bundle); + AdvancedNotificationService::GetInstance()->UpdateCloneBundleInfo(*bundle); bundle = bundlesInfo_.erase(bundle); } + NotificationPreferences::GetInstance()->UpdateBatchCloneBundleInfo(userId, bundlesInfo_); for (auto bundle = bundlesInfo_.begin(); bundle != bundlesInfo_.end(); bundle++) { ANS_LOGI("Event bundle left %{public}s.", bundle->Dump().c_str()); } ANS_LOGI("Notification bundle list on restore end."); } -void NotificationCloneBundle::OnBundleDataAdd(const sptr &bundleOption) -{ - HandleBundleEvent(bundleOption->GetBundleName(), bundleOption->GetAppIndex(), bundleOption->GetUid()); -} - -void NotificationCloneBundle::OnBundleDataUpdate(const sptr &bundleOption) +void NotificationCloneBundle::OnRestoreStart(const std::string bundleName, int32_t appIndex, + int32_t userId, int32_t uid) { - HandleBundleEvent(bundleOption->GetBundleName(), bundleOption->GetAppIndex(), bundleOption->GetUid()); -} - -void NotificationCloneBundle::HandleBundleEvent(const std::string bundleName, int32_t appIndex, int32_t uid) -{ - ANS_LOGI("Handle bundle event %{public}s %{public}d %{public}d %{public}zu.", - bundleName.c_str(), appIndex, uid, bundlesInfo_.size()); + ANS_LOGI("Handle bundle event %{public}s %{public}d %{public}d %{public}d %{public}zu.", + bundleName.c_str(), appIndex, userId, uid, bundlesInfo_.size()); if (bundlesInfo_.empty()) { return; } - int32_t userId = -1; - OsAccountManagerHelper::GetInstance().GetOsAccountLocalIdFromUid(uid, userId); std::unique_lock lcck(lock_); for (auto bundle = bundlesInfo_.begin(); bundle != bundlesInfo_.end();) { if (bundle->GetBundleName() == bundleName && bundle->GetAppIndex() == appIndex) { bundle->SetUid(uid); - NotificationPreferences::GetInstance()->UpdateCloneBundleInfo(userId, *bundle); + AdvancedNotificationService::GetInstance()->UpdateCloneBundleInfo(*bundle); + NotificationPreferences::GetInstance()->DelCloneBundleInfo(userId, *bundle); bundle = bundlesInfo_.erase(bundle); break; } @@ -145,9 +140,13 @@ void NotificationCloneBundle::OnUserSwitch(int32_t userId) ANS_LOGW("Clone bundle queue is null."); return; } - cloneBundleQueue_->submit_h(std::bind([&]() { + cloneBundleQueue_->submit_h(std::bind([&, userId]() { std::unique_lock lock(lock_); bundlesInfo_.clear(); + NotificationPreferences::GetInstance()->GetAllCloneBundleInfo(userId, bundlesInfo_); + for (auto bundle = bundlesInfo_.begin(); bundle != bundlesInfo_.end(); bundle++) { + ANS_LOGI("Event bundle OnUserSwitch %{public}s.", bundle->Dump().c_str()); + } })); } diff --git a/services/ans/src/clone/notification_clone_disturb_service.cpp b/services/ans/src/clone/notification_clone_disturb_service.cpp index 6ec7c8466..95939dd84 100644 --- a/services/ans/src/clone/notification_clone_disturb_service.cpp +++ b/services/ans/src/clone/notification_clone_disturb_service.cpp @@ -69,7 +69,11 @@ void NotificationCloneDisturb::OnRestore(const nlohmann::json &jsonObject) return; } - profiles_.clear(); + int32_t userId = NotificationCloneUtil::GetActiveUserId(); + if (!profiles_.empty()) { + NotificationPreferences::GetInstance()->DelBatchCloneProfileInfo(userId, profiles_); + profiles_.clear(); + } for (const auto &profile : jsonObject) { sptr item = new (std::nothrow) NotificationDoNotDisturbProfile(); item->FromJson(profile.dump()); @@ -81,9 +85,7 @@ void NotificationCloneDisturb::OnRestore(const nlohmann::json &jsonObject) return; } - int32_t userId = NotificationCloneUtil::GetActiveUserId(); cloneDisturbQueue_->submit_h(std::bind([&, userId]() { - ANS_LOGI("Notification disturb profile ffrt start %{public}zu.", profiles_.size()); int32_t profileId = -1; std::string name; std::map uidMap; @@ -92,8 +94,7 @@ void NotificationCloneDisturb::OnRestore(const nlohmann::json &jsonObject) std::vector notExitBunldleList; name = (*profile)->GetProfileName(); profileId = (*profile)->GetProfileId(); - ANS_LOGI("Notification disturb profile %{public}d, %{public}zu.", profileId, - (*profile)->GetProfileTrustList().size()); + ANS_LOGI("Disturb %{public}d, %{public}zu.", profileId, (*profile)->GetProfileTrustList().size()); GetProfileUid(userId, uidMap, (*profile)->GetProfileTrustList(), exitBunldleList, notExitBunldleList); NotificationPreferences::GetInstance()->UpdateDoNotDisturbProfiles(userId, profileId, name, exitBunldleList); @@ -107,6 +108,7 @@ void NotificationCloneDisturb::OnRestore(const nlohmann::json &jsonObject) profileId = -1; } + NotificationPreferences::GetInstance()->UpdateBatchCloneProfileInfo(userId, profiles_); for (auto profile = profiles_.begin(); profile != profiles_.end(); profile++) { ANS_LOGI("Clone queue left %{public}d %{public}zu.", (*profile)->GetProfileId(), (*profile)->GetProfileTrustList().size()); @@ -139,16 +141,6 @@ void NotificationCloneDisturb::GetProfileUid(int32_t userId, std::map &bundleOption) -{ - HandlerBundleEvent(bundleOption->GetBundleName(), bundleOption->GetAppIndex(), bundleOption->GetUid()); -} - -void NotificationCloneDisturb::OnBundleDataUpdate(const sptr &bundleOption) -{ - HandlerBundleEvent(bundleOption->GetBundleName(), bundleOption->GetAppIndex(), bundleOption->GetUid()); -} - void NotificationCloneDisturb::OnUserSwitch(int32_t userId) { ANS_LOGI("Handler user switch %{public}d", userId); @@ -156,20 +148,26 @@ void NotificationCloneDisturb::OnUserSwitch(int32_t userId) ANS_LOGW("Clone disturb queue is null."); return; } - cloneDisturbQueue_->submit_h(std::bind([&]() { + cloneDisturbQueue_->submit_h(std::bind([&, userId]() { profiles_.clear(); + NotificationPreferences::GetInstance()->GetAllCloneProfileInfo(userId, profiles_); + for (auto profile = profiles_.begin(); profile != profiles_.end(); profile++) { + ANS_LOGI("Clone queue left %{public}d %{public}zu.", (*profile)->GetProfileId(), + (*profile)->GetProfileTrustList().size()); + } + ANS_LOGI("Notification disturb profile list on recover end."); })); } -void NotificationCloneDisturb::HandlerBundleEvent(const std::string bundleName, int32_t appIndex, int32_t uid) +void NotificationCloneDisturb::OnRestoreStart(const std::string bundleName, int32_t appIndex, + int32_t userId, int32_t uid) { - ANS_LOGI("Handler bundle event %{public}s %{public}d %{public}d %{public}zu.", - bundleName.c_str(), appIndex, uid, profiles_.size()); + ANS_LOGI("Handler bundle event %{public}s %{public}d %{public}d %{public}d %{public}zu.", + bundleName.c_str(), appIndex, userId, uid, profiles_.size()); if (profiles_.empty()) { return; } - int32_t userId = NotificationCloneUtil::GetActiveUserId(); NotificationBundleOption bundle(bundleName, uid); bundle.SetAppIndex(appIndex); if (cloneDisturbQueue_ == nullptr) { @@ -188,6 +186,7 @@ void NotificationCloneDisturb::HandlerBundleEvent(const std::string bundleName, NotificationPreferences::GetInstance()->UpdateDoNotDisturbProfiles(userId, profileId, name, bundleList); if (trustList.empty()) { + NotificationPreferences::GetInstance()->DelCloneProfileInfo(userId, *profile); profile = profiles_.erase(profile); } else { (*profile)->SetProfileTrustList(trustList); @@ -196,6 +195,7 @@ void NotificationCloneDisturb::HandlerBundleEvent(const std::string bundleName, name.clear(); profileId = -1; } + NotificationPreferences::GetInstance()->UpdateBatchCloneProfileInfo(userId, profiles_); for (auto profile = profiles_.begin(); profile != profiles_.end(); profile++) { ANS_LOGI("Event queue left %{public}d %{public}zu.", (*profile)->GetProfileId(), (*profile)->GetProfileTrustList().size()); diff --git a/services/ans/src/clone/notification_clone_manager.cpp b/services/ans/src/clone/notification_clone_manager.cpp index ae65acf2b..2b5b88903 100644 --- a/services/ans/src/clone/notification_clone_manager.cpp +++ b/services/ans/src/clone/notification_clone_manager.cpp @@ -26,6 +26,7 @@ #include "nlohmann/json.hpp" #include "notification_clone_disturb_service.h" #include "notification_clone_bundle_service.h" +#include "notification_clone_util.h" namespace OHOS { namespace Notification { @@ -41,6 +42,22 @@ NotificationCloneManager& NotificationCloneManager::GetInstance() return notificationCloneManager; } +static std::string SetBackUpReply() +{ + nlohmann::json reply; + nlohmann::json resultInfo = nlohmann::json::array(); + nlohmann::json errorInfo; + + errorInfo["type"] = "ErrorInfo"; + errorInfo["errorCode"] = std::to_string(ERR_OK); + errorInfo["errorInfo"] = ""; + + resultInfo.emplace_back(errorInfo); + reply["resultInfo"] = resultInfo; + + return reply.dump(); +} + int32_t NotificationCloneManager::OnBackup(MessageParcel& data, MessageParcel& reply) { if (cloneTemplates.empty()) { @@ -86,6 +103,7 @@ int32_t NotificationCloneManager::OnBackup(MessageParcel& data, MessageParcel& r int32_t NotificationCloneManager::OnRestore(MessageParcel& data, MessageParcel& reply) { + reply.WriteString(SetBackUpReply()); std::string storeMessage; UniqueFd fd(data.ReadFileDescriptor()); if (LoadConfig(fd, storeMessage) != ERR_OK) { @@ -182,7 +200,27 @@ void NotificationCloneManager::RemoveBackUpFile() void NotificationCloneManager::OnUserSwitch(int32_t userId) { for (auto iter = cloneTemplates.begin(); iter != cloneTemplates.end(); ++iter) { - iter->second->OnUserSwitch(userId); + if (iter->second != nullptr) { + iter->second->OnUserSwitch(userId); + } + } +} + +void NotificationCloneManager::OnRestoreStart(EventFwk::Want want) +{ + int32_t appIndex = want.GetIntParam("index", -1); + std::string bundleName = want.GetStringParam("bundleName"); + int32_t userId = NotificationCloneUtil::GetActiveUserId(); + if (appIndex == -1 || bundleName.empty()) { + ANS_LOGW("Invalid restore data %{public}d %{public}d %{public}s", + appIndex, userId, bundleName.c_str()); + return; + } + int32_t uid = NotificationCloneUtil::GetBundleUid(bundleName, userId, appIndex); + for (auto iter = cloneTemplates.begin(); iter != cloneTemplates.end(); ++iter) { + if (iter->second != nullptr) { + iter->second->OnRestoreStart(bundleName, appIndex, userId, uid); + } } } } diff --git a/services/ans/src/notification_preferences.cpp b/services/ans/src/notification_preferences.cpp index fbd23fde0..790532eec 100644 --- a/services/ans/src/notification_preferences.cpp +++ b/services/ans/src/notification_preferences.cpp @@ -689,7 +689,6 @@ void NotificationPreferences::UpdateCloneBundleInfo(int32_t userId, } /* after clone, override these witch */ - bundleInfo.SetSlotFlags(cloneBundleInfo.GetSlotFlags()); bundleInfo.SetIsShowBadge(cloneBundleInfo.GetIsShowBadge()); bundleInfo.SetEnableNotification(cloneBundleInfo.GetEnableNotification()); /* update property to db */ @@ -697,6 +696,12 @@ void NotificationPreferences::UpdateCloneBundleInfo(int32_t userId, ANS_LOGW("Clone bundle info failed %{public}s.", cloneBundleInfo.Dump().c_str()); return; } + + if (SaveBundleProperty(bundleInfo, bundleOption, + BundleType::BUNDLE_SLOTFLGS_TYPE, cloneBundleInfo.GetSlotFlags()) != ERR_OK) { + ANS_LOGW("Clone bundle slot info %{public}s.", cloneBundleInfo.Dump().c_str()); + return; + } preferencesInfo.SetBundleInfo(bundleInfo); /* update slot info */ @@ -1256,5 +1261,77 @@ std::string NotificationPreferences::GetAdditionalConfig(const std::string &key) } return preferncesDB_->GetAdditionalConfig(key); } + +bool NotificationPreferences::DelCloneProfileInfo(const int32_t &userId, + const sptr& info) +{ + if (preferncesDB_ == nullptr) { + return false; + } + return preferncesDB_->DelCloneProfileInfo(userId, info); +} + +bool NotificationPreferences::UpdateBatchCloneProfileInfo(const int32_t &userId, + const std::vector>& profileInfo) +{ + if (preferncesDB_ == nullptr) { + return false; + } + return preferncesDB_->UpdateBatchCloneProfileInfo(userId, profileInfo); +} + +void NotificationPreferences::GetAllCloneProfileInfo(const int32_t &userId, + std::vector>& profilesInfo) +{ + if (preferncesDB_ == nullptr) { + return; + } + return preferncesDB_->GetAllCloneProfileInfo(userId, profilesInfo); +} + +void NotificationPreferences::GetAllCloneBundleInfo(const int32_t &userId, + std::vector& cloneBundleInfo) +{ + if (preferncesDB_ == nullptr) { + return; + } + return preferncesDB_->GetAllCloneBundleInfo(userId, cloneBundleInfo); +} + +bool NotificationPreferences::UpdateBatchCloneBundleInfo(const int32_t &userId, + const std::vector& cloneBundleInfo) +{ + if (preferncesDB_ == nullptr) { + return false; + } + return preferncesDB_->UpdateBatchCloneBundleInfo(userId, cloneBundleInfo); +} + +bool NotificationPreferences::DelCloneBundleInfo(const int32_t &userId, + const NotificationCloneBundleInfo& cloneBundleInfo) +{ + if (preferncesDB_ == nullptr) { + return false; + } + return preferncesDB_->DelCloneBundleInfo(userId, cloneBundleInfo); +} + +bool NotificationPreferences::DelBatchCloneProfileInfo(const int32_t &userId, + const std::vector>& profileInfo) +{ + if (preferncesDB_ == nullptr) { + return false; + } + return preferncesDB_->DelBatchCloneProfileInfo(userId, profileInfo); +} + +bool NotificationPreferences::DelBatchCloneBundleInfo(const int32_t &userId, + const std::vector& cloneBundleInfo) +{ + if (preferncesDB_ == nullptr) { + return false; + } + return preferncesDB_->DelBatchCloneBundleInfo(userId, cloneBundleInfo); +} } // namespace Notification } // namespace OHOS diff --git a/services/ans/src/notification_preferences_database.cpp b/services/ans/src/notification_preferences_database.cpp index 3e1cdcb4d..7d2b325a1 100644 --- a/services/ans/src/notification_preferences_database.cpp +++ b/services/ans/src/notification_preferences_database.cpp @@ -223,6 +223,10 @@ const static std::string KEY_REMINDER_MODE = "reminderMode"; constexpr char RELATIONSHIP_JSON_KEY_SERVICE[] = "service"; constexpr char RELATIONSHIP_JSON_KEY_APP[] = "app"; +const static std::string KEY_CLONE_LABEL = "label_ans_clone_"; +const static std::string CLONE_BUNDLE = "bundle_"; +const static std::string CLONE_PROFILE = "profile_"; + NotificationPreferencesDatabase::NotificationPreferencesDatabase() { NotificationRdbConfig notificationRdbConfig; @@ -2119,5 +2123,164 @@ bool NotificationPreferencesDatabase::UpdateBundleSlotToDisturbeDB(int32_t userI int32_t result = rdbDataManager_->InsertBatchData(values, userId); return (result == NativeRdb::E_OK); } + +bool NotificationPreferencesDatabase::DelCloneProfileInfo(const int32_t &userId, + const sptr& info) +{ + if (!CheckRdbStore()) { + ANS_LOGE("RdbStore is nullptr."); + return false; + } + + std::string key = KEY_CLONE_LABEL + CLONE_PROFILE + std::to_string(info->GetProfileId()); + int32_t result = rdbDataManager_->DeleteData(key, userId); + if (result != NativeRdb::E_OK) { + ANS_LOGE("delete clone profile Info failed."); + return false; + } + return true; +} + +bool NotificationPreferencesDatabase::DelBatchCloneProfileInfo(const int32_t &userId, + const std::vector>& profileInfo) +{ + std::string cloneProfile = KEY_CLONE_LABEL + CLONE_PROFILE; + if (!CheckRdbStore()) { + ANS_LOGE("RdbStore is nullptr."); + return false; + } + + std::vector keys; + for (auto info : profileInfo) { + std::string key = cloneProfile + std::to_string(info->GetProfileId()); + keys.emplace_back(key); + } + + int32_t result = rdbDataManager_->DeleteBathchData(keys, userId); + if (result != NativeRdb::E_OK) { + ANS_LOGE("delete clone bundle Info failed."); + return false; + } + return true; +} + +bool NotificationPreferencesDatabase::UpdateBatchCloneProfileInfo(const int32_t &userId, + const std::vector>& profileInfo) +{ + std::string cloneProfile = KEY_CLONE_LABEL + CLONE_PROFILE; + std::unordered_map values; + for (auto& info : profileInfo) { + std::string key = cloneProfile + std::to_string(info->GetProfileId()); + std::string jsonString = info->ToJson(); + values.emplace(key, jsonString); + } + return UpdateCloneToDisturbeDB(userId, values); +} + +void NotificationPreferencesDatabase::GetAllCloneProfileInfo(const int32_t &userId, + std::vector>& profilesInfo) +{ + std::string cloneProfile = KEY_CLONE_LABEL + CLONE_PROFILE; + std::unordered_map values; + if (GetBatchKvsFromDb(cloneProfile, values, userId) != ERR_OK) { + ANS_LOGW("Get clone bundle map info failed %{public}d.", userId); + return; + } + + for (auto item : values) { + sptr profile = new (std::nothrow) NotificationDoNotDisturbProfile(); + profile->FromJson(item.second); + profilesInfo.push_back(profile); + } +} + +void NotificationPreferencesDatabase::GetAllCloneBundleInfo(const int32_t &userId, + std::vector& cloneBundleInfo) +{ + std::unordered_map values; + if (GetBatchKvsFromDb(KEY_CLONE_LABEL + CLONE_BUNDLE, values, userId) != ERR_OK) { + ANS_LOGW("Get clone bundle map info failed %{public}d.", userId); + return; + } + + for (auto item : values) { + NotificationCloneBundleInfo bundleInfo; + nlohmann::json jsonObject = nlohmann::json::parse(item.second, nullptr, false); + if (jsonObject.is_null() || !jsonObject.is_object()) { + ANS_LOGE("Invalid JSON object"); + continue; + } + bundleInfo.FromJson(jsonObject); + cloneBundleInfo.emplace_back(bundleInfo); + } +} + +bool NotificationPreferencesDatabase::DelBatchCloneBundleInfo(const int32_t &userId, + const std::vector& cloneBundleInfo) +{ + std::string cloneBundle = KEY_CLONE_LABEL + CLONE_BUNDLE; + if (!CheckRdbStore()) { + ANS_LOGE("RdbStore is nullptr."); + return false; + } + + std::vector keys; + for (auto bundleInfo : cloneBundleInfo) { + std::string key = cloneBundle + bundleInfo.GetBundleName() + + std::to_string(bundleInfo.GetAppIndex()); + keys.emplace_back(key); + } + int32_t result = rdbDataManager_->DeleteBathchData(keys, userId); + if (result != NativeRdb::E_OK) { + ANS_LOGE("delete clone bundle Info failed."); + return false; + } + return true; +} + +bool NotificationPreferencesDatabase::UpdateBatchCloneBundleInfo(const int32_t &userId, + const std::vector& cloneBundleInfo) +{ + std::string cloneBundle = KEY_CLONE_LABEL + CLONE_BUNDLE; + std::unordered_map values; + for (auto& info : cloneBundleInfo) { + nlohmann::json jsonNode; + std::string key = cloneBundle + info.GetBundleName() + std::to_string(info.GetAppIndex()); + info.ToJson(jsonNode); + values.emplace(key, jsonNode.dump()); + } + return UpdateCloneToDisturbeDB(userId, values); +} + +bool NotificationPreferencesDatabase::DelCloneBundleInfo(const int32_t &userId, + const NotificationCloneBundleInfo& cloneBundleInfo) +{ + std::string cloneBundle = KEY_CLONE_LABEL + CLONE_BUNDLE; + std::string key = cloneBundle + cloneBundleInfo.GetBundleName() + + std::to_string(cloneBundleInfo.GetAppIndex()); + if (!CheckRdbStore()) { + ANS_LOGE("RdbStore is nullptr."); + return false; + } + + int32_t result = rdbDataManager_->DeleteData(key, userId); + if (result != NativeRdb::E_OK) { + ANS_LOGE("delete clone bundle Info failed."); + return false; + } + return true; +} + +bool NotificationPreferencesDatabase::UpdateCloneToDisturbeDB(const int32_t &userId, + const std::unordered_map values) +{ + if (values.empty() || !CheckRdbStore()) { + ANS_LOGE("RdbStore is nullptr."); + return false; + } + + int32_t result = rdbDataManager_->InsertBatchData(values, userId); + return (result == NativeRdb::E_OK); +} } // namespace Notification } // namespace OHOS diff --git a/services/ans/src/system_event_observer.cpp b/services/ans/src/system_event_observer.cpp index 2fab63ba9..2ca95752e 100644 --- a/services/ans/src/system_event_observer.cpp +++ b/services/ans/src/system_event_observer.cpp @@ -43,6 +43,7 @@ SystemEventObserver::SystemEventObserver(const ISystemEvent &callbacks) : callba matchingSkills.AddEvent(EventFwk::CommonEventSupport::COMMON_EVENT_PACKAGE_ADDED); matchingSkills.AddEvent(EventFwk::CommonEventSupport::COMMON_EVENT_PACKAGE_CHANGED); matchingSkills.AddEvent(EventFwk::CommonEventSupport::COMMON_EVENT_BOOT_COMPLETED); + matchingSkills.AddEvent(EventFwk::CommonEventSupport::COMMON_EVENT_RESTORE_START); EventFwk::CommonEventSubscribeInfo commonEventSubscribeInfo(matchingSkills); commonEventSubscribeInfo.SetThreadMode(EventFwk::CommonEventSubscribeInfo::COMMON); @@ -119,6 +120,8 @@ void SystemEventObserver::OnReceiveEvent(const EventFwk::CommonEventData &data) callbacks_.onBundleDataCleared(bundleOption); } } + } else if (action == EventFwk::CommonEventSupport::COMMON_EVENT_RESTORE_START) { + NotificationCloneManager::GetInstance().OnRestoreStart(want); } else { OnReceiveEventInner(data); } -- Gitee From d598f8f01e33453667a2536879320606ecda88f8 Mon Sep 17 00:00:00 2001 From: z30053788 Date: Sat, 7 Dec 2024 10:35:34 +0800 Subject: [PATCH 146/167] cherry pick 6eef10d from https://gitee.com/zhaobaoxin1/notification_distributed_notification_service/pulls/2463 update1 Signed-off-by: z30053788 Change-Id: If707d63ee201ded6dc6ac1ad5577123e829ac5a8 --- frameworks/js/napi/src/manager/napi_display_badge.cpp | 4 ++-- frameworks/js/napi/src/manager/napi_distributed_enable.cpp | 6 +++--- frameworks/js/napi/src/publish.cpp | 2 +- 3 files changed, 6 insertions(+), 6 deletions(-) diff --git a/frameworks/js/napi/src/manager/napi_display_badge.cpp b/frameworks/js/napi/src/manager/napi_display_badge.cpp index 234664e0e..17e4c0bd8 100644 --- a/frameworks/js/napi/src/manager/napi_display_badge.cpp +++ b/frameworks/js/napi/src/manager/napi_display_badge.cpp @@ -199,7 +199,7 @@ napi_value ParseParameters(const napi_env &env, const napi_callback_info &info, NAPI_CALL(env, napi_typeof(env, argv[PARAM1], &valuetype)); if (valuetype != napi_number) { ANS_LOGE("Wrong argument type. Number expected."); - std::string msg = "Incorrect parameter types.The type of param must be number."; + std::string msg = "Incorrect parameter types.The type of badgeNumber must be number."; Common::NapiThrow(env, ERROR_PARAM_INVALID, msg); return nullptr; } @@ -209,7 +209,7 @@ napi_value ParseParameters(const napi_env &env, const napi_callback_info &info, // case2: setBadgeNumber(badgeNumber) if (valuetype != napi_number) { ANS_LOGW("Wrong argument type. Number expected."); - std::string msg = "Incorrect parameter types.The type of param must be object."; + std::string msg = "Incorrect parameter types.The type of badgeNumber must be number."; Common::NapiThrow(env, ERROR_PARAM_INVALID, msg); return nullptr; } diff --git a/frameworks/js/napi/src/manager/napi_distributed_enable.cpp b/frameworks/js/napi/src/manager/napi_distributed_enable.cpp index 9c958083e..05d9b172b 100644 --- a/frameworks/js/napi/src/manager/napi_distributed_enable.cpp +++ b/frameworks/js/napi/src/manager/napi_distributed_enable.cpp @@ -44,7 +44,7 @@ napi_value ParseParameters(const napi_env &env, const napi_callback_info &info, NAPI_CALL(env, napi_typeof(env, argv[PARAM0], &valuetype)); if (valuetype != napi_object) { ANS_LOGW("Parameter type error. Object expected."); - std::string msg = "Incorrect parameter types.The type of param must be object."; + std::string msg = "Incorrect parameter types.The type of bundleOption must be object."; Common::NapiThrow(env, ERROR_PARAM_INVALID, msg); return nullptr; } @@ -58,8 +58,8 @@ napi_value ParseParameters(const napi_env &env, const napi_callback_info &info, // argv[1]: deviceType NAPI_CALL(env, napi_typeof(env, argv[PARAM1], &valuetype)); if (valuetype != napi_string) { - ANS_LOGW("Wrong argument type. Bool expected."); - std::string msg = "Incorrect parameter types.The type of param must be boolean."; + ANS_LOGW("Wrong argument type.String expected."); + std::string msg = "Incorrect parameter types.The type of deviceType must be string."; Common::NapiThrow(env, ERROR_PARAM_INVALID, msg); return nullptr; } diff --git a/frameworks/js/napi/src/publish.cpp b/frameworks/js/napi/src/publish.cpp index 7ccf804d0..bc91f5553 100644 --- a/frameworks/js/napi/src/publish.cpp +++ b/frameworks/js/napi/src/publish.cpp @@ -439,7 +439,7 @@ napi_value ParsePublishAsBundleParameters( NAPI_CALL(env, napi_typeof(env, argv[PARAM2], &valuetype)); if (valuetype != napi_number) { ANS_LOGW("Wrong argument type. Number expected."); - std::string msg = "Incorrect parameter types.The type of param must be number."; + std::string msg = "Incorrect parameter types.The type of userId must be number."; Common::NapiThrow(env, ERROR_PARAM_INVALID, msg); return nullptr; } -- Gitee From 3be7933d9429fca89d85dbdc939ebf15c9fe580f Mon Sep 17 00:00:00 2001 From: Ricky Date: Mon, 21 Oct 2024 12:19:24 +0800 Subject: [PATCH 147/167] refactor ans subscriber logic to fix crash Signed-off-by: Ricky Change-Id: Ie7f2405d8e0931f473dc123d4498b3c0d8e5efb3 --- frameworks/ans/BUILD.gn | 1 + frameworks/ans/src/notification_helper.cpp | 28 ++ .../include/ans_manager_death_recipient.h | 7 +- frameworks/core/include/ans_notification.h | 109 +++++++- .../core/include/ans_subscriber_listener.h | 68 +++++ .../core/src/ans_manager_death_recipient.cpp | 25 +- frameworks/core/src/ans_notification.cpp | 126 ++++++++- .../core/src/ans_subscriber_listener.cpp | 195 ++++++++++++++ frameworks/core/test/unittest/BUILD.gn | 1 - .../ans_manager_death_recipient_test/BUILD.gn | 47 ---- .../ans_manager_death_recipient_unit_test.cpp | 102 ------- .../ans_notification_branch_test/BUILD.gn | 2 +- .../ans_notification_branch_test.cpp | 12 +- .../mock_ans_manager_proxy.cpp} | 71 +++-- frameworks/js/napi/include/subscribe.h | 42 +-- frameworks/js/napi/src/subscribe.cpp | 250 ++++-------------- .../js/napi/src/subscribe/napi_subscribe.cpp | 25 +- interfaces/inner_api/notification_helper.h | 98 ++++++- .../inner_api/notification_subscriber.h | 2 +- ...anced_notification_service_branch_test.cpp | 2 +- .../notification_shell_command_dump_test.cpp | 1 - 21 files changed, 734 insertions(+), 480 deletions(-) create mode 100644 frameworks/core/include/ans_subscriber_listener.h create mode 100644 frameworks/core/src/ans_subscriber_listener.cpp delete mode 100644 frameworks/core/test/unittest/ans_manager_death_recipient_test/BUILD.gn delete mode 100644 frameworks/core/test/unittest/ans_manager_death_recipient_test/ans_manager_death_recipient_unit_test.cpp rename frameworks/core/test/unittest/{ans_notification_branch_test/mock_ans_notification.cpp => mock/mock_ans_manager_proxy.cpp} (77%) mode change 100755 => 100644 diff --git a/frameworks/ans/BUILD.gn b/frameworks/ans/BUILD.gn index 52efeb5a6..0636bb553 100644 --- a/frameworks/ans/BUILD.gn +++ b/frameworks/ans/BUILD.gn @@ -62,6 +62,7 @@ ohos_shared_library("ans_innerkits") { "${core_path}/src/ans_manager_stub.cpp", "${core_path}/src/ans_manager_stub_invalid.cpp", "${core_path}/src/ans_notification.cpp", + "${core_path}/src/ans_subscriber_listener.cpp", "${core_path}/src/ans_subscriber_local_live_view_proxy.cpp", "${core_path}/src/ans_subscriber_local_live_view_stub.cpp", "${core_path}/src/ans_subscriber_proxy.cpp", diff --git a/frameworks/ans/src/notification_helper.cpp b/frameworks/ans/src/notification_helper.cpp index 89f4dcc5a..99e245e16 100644 --- a/frameworks/ans/src/notification_helper.cpp +++ b/frameworks/ans/src/notification_helper.cpp @@ -16,6 +16,7 @@ #include "notification_helper.h" #include "ans_notification.h" #include "singleton.h" +#include namespace OHOS { namespace Notification { @@ -203,11 +204,21 @@ ErrCode NotificationHelper::SubscribeNotification(const NotificationSubscriber & return DelayedSingleton::GetInstance()->SubscribeNotification(subscriber); } +ErrCode NotificationHelper::SubscribeNotification(const std::shared_ptr &subscriber) +{ + return DelayedSingleton::GetInstance()->SubscribeNotification(subscriber, nullptr); +} + ErrCode NotificationHelper::SubscribeNotificationSelf(const NotificationSubscriber &subscriber) { return DelayedSingleton::GetInstance()->SubscribeNotificationSelf(subscriber); } +ErrCode NotificationHelper::SubscribeNotificationSelf(const std::shared_ptr &subscriber) +{ + return DelayedSingleton::GetInstance()->SubscribeNotificationSelf(subscriber); +} + ErrCode NotificationHelper::SubscribeLocalLiveViewNotification(const NotificationLocalLiveViewSubscriber &subscriber, const bool isNative) { @@ -220,17 +231,34 @@ ErrCode NotificationHelper::SubscribeNotification( return DelayedSingleton::GetInstance()->SubscribeNotification(subscriber, subscribeInfo); } +ErrCode NotificationHelper::SubscribeNotification(const std::shared_ptr &subscriber, + const sptr &subscribeInfo) +{ + return DelayedSingleton::GetInstance()->SubscribeNotification(subscriber, subscribeInfo); +} + ErrCode NotificationHelper::UnSubscribeNotification(NotificationSubscriber &subscriber) { return DelayedSingleton::GetInstance()->UnSubscribeNotification(subscriber); } +ErrCode NotificationHelper::UnSubscribeNotification(const std::shared_ptr &subscriber) +{ + return DelayedSingleton::GetInstance()->UnSubscribeNotification(subscriber); +} + ErrCode NotificationHelper::UnSubscribeNotification( NotificationSubscriber &subscriber, NotificationSubscribeInfo subscribeInfo) { return DelayedSingleton::GetInstance()->UnSubscribeNotification(subscriber, subscribeInfo); } +ErrCode NotificationHelper::UnSubscribeNotification(const std::shared_ptr &subscriber, + const sptr &subscribeInfo) +{ + return DelayedSingleton::GetInstance()->UnSubscribeNotification(subscriber, subscribeInfo); +} + ErrCode NotificationHelper::TriggerLocalLiveView(const NotificationBundleOption &bundleOption, const int32_t notificationId, const NotificationButtonOption &buttonOption) { diff --git a/frameworks/core/include/ans_manager_death_recipient.h b/frameworks/core/include/ans_manager_death_recipient.h index 44a654662..4d48d311d 100644 --- a/frameworks/core/include/ans_manager_death_recipient.h +++ b/frameworks/core/include/ans_manager_death_recipient.h @@ -27,8 +27,6 @@ public: ~AnsManagerDeathRecipient() = default; void SubscribeSAManager(); - - bool GetIsSubscribeSAManager(); private: class SystemAbilityStatusChangeListener : public SystemAbilityStatusChangeStub { public: @@ -36,11 +34,8 @@ private: ~SystemAbilityStatusChangeListener() = default; void OnAddSystemAbility(int32_t systemAbilityId, const std::string& deviceId) override; void OnRemoveSystemAbility(int32_t systemAbilityId, const std::string& deviceId) override; - - private: - bool isSAOffline = false; }; - + std::mutex mutex_; sptr statusChangeListener_ = nullptr; }; } // namespace Notification diff --git a/frameworks/core/include/ans_notification.h b/frameworks/core/include/ans_notification.h index 32c2b1855..e7f8cde07 100644 --- a/frameworks/core/include/ans_notification.h +++ b/frameworks/core/include/ans_notification.h @@ -17,10 +17,12 @@ #define BASE_NOTIFICATION_ANS_STANDARD_FRAMEWORKS_ANS_CORE_INCLUDE_ANS_NOTIFICATION_H #include +#include #include "ans_dialog_host_client.h" #include "ans_manager_death_recipient.h" #include "ans_manager_interface.h" +#include "ans_subscriber_listener.h" #include "notification_subscriber.h" #include "notification_local_live_view_subscriber.h" #include "want_params.h" @@ -354,26 +356,57 @@ public: * notification. To subscribe to notifications published only by specified sources, for example, notifications from * certain applications, call the {SubscribeNotification(NotificationSubscriber, NotificationSubscribeInfo)} * method. - * + * @deprecated This function is deprecated, + * use 'SubscribeNotification(const std::shared_ptr &subscriber)'. * @param subscriber Indicates the {NotificationSubscriber} to receive notifications. * This parameter must be specified. * @return Returns subscribe notification result. */ ErrCode SubscribeNotification(const NotificationSubscriber &subscriber); + /** + * @brief Subscribes to notifications from all applications. This method can be called only by applications + * with required system permissions. + * @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. + * + * @param subscriber Indicates the {NotificationSubscriber} to receive notifications. + * This parameter must be specified. + * @return Returns subscribe notification result. + */ + ErrCode SubscribeNotification(const std::shared_ptr &subscriber); + /** * @brief Subscribes to notifications from the appliaction self. * @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. - * + * @deprecated This function is deprecated, + * use 'SubscribeNotificationSelf(const std::shared_ptr &subscriber)'. * @param subscriber Indicates the {NotificationSubscriber} to receive notifications. * This parameter must be specified. * @return Returns subscribe notification result. */ ErrCode SubscribeNotificationSelf(const NotificationSubscriber &subscriber); + /** + * @brief Subscribes to notifications from the appliaction self. + * @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. + * + * @param subscriber Indicates the {NotificationSubscriber} to receive notifications. + * This parameter must be specified. + * @return Returns subscribe notification result. + */ + ErrCode SubscribeNotificationSelf(const std::shared_ptr &subscriber); + /** * @brief Subscribes liveView notification. This method can be called only by applications * with required system permissions. @@ -397,7 +430,9 @@ public: * 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. - * + * @deprecated This function is deprecated, + * use 'SubscribeNotification(const std::shared_ptr &subscriber, + * const std::shared_ptr &subscribeInfo)'. * @param subscriber Indicates the subscribers to receive notifications. This parameter must be specified. * For details, see {NotificationSubscriber}. * @param subscribeInfo Indicates the filters for specified notification sources, including application name, @@ -406,6 +441,26 @@ public: */ ErrCode SubscribeNotification( const NotificationSubscriber &subscriber, const NotificationSubscribeInfo &subscribeInfo); + + /** + * @brief Subscribes to all notifications based on the filtering criteria. This method can be called only + * by applications with required system permissions. + * @note After {subscribeInfo} is specified, a subscriber receives only the notifications that + * meet the filter criteria specified by {subscribeInfo}. + * 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. + * + * @param subscriber Indicates the subscribers to receive notifications. This parameter must be specified. + * For details, see {NotificationSubscriber}. + * @param subscribeInfo Indicates the filters for specified notification sources, including application name, + * user ID, or device name. This parameter is optional. + * @return Returns subscribe notification result. + */ + ErrCode SubscribeNotification(const std::shared_ptr &subscriber, + const sptr &subscribeInfo); /** * @brief Unsubscribes from all notifications. This method can be called only by applications with required @@ -417,18 +472,39 @@ public: * To unsubscribe from notifications published only by specified sources, for example, * notifications from certain applications, call the * {UnSubscribeNotification(NotificationSubscriber, NotificationSubscribeInfo)} method. - * + * @deprecated This function is deprecated, + * use 'UnSubscribeNotification(const std::shared_ptr &subscriber)'. * @param subscriber Indicates the {NotificationSubscriber} to receive notifications. * This parameter must be specified. * @return Returns unsubscribe notification result. */ ErrCode UnSubscribeNotification(NotificationSubscriber &subscriber); + /** + * @brief Unsubscribes from all notifications. This method can be called only by applications with required + * system permissions. + * @note Generally, you subscribe to a notification by calling the + * {SubscribeNotification(NotificationSubscriber)} method. If you do not want your application + * to receive a notification any longer, unsubscribe from that notification using this method. + * You can unsubscribe from only those notifications that your application has subscribed to. + * To unsubscribe from notifications published only by specified sources, for example, + * notifications from certain applications, call the + * {UnSubscribeNotification(NotificationSubscriber, NotificationSubscribeInfo)} method. + * + * @param subscriber Indicates the {NotificationSubscriber} to receive notifications. + * This parameter must be specified. + * @return Returns unsubscribe notification result. + */ + ErrCode UnSubscribeNotification(const std::shared_ptr &subscriber); + /** * @brief Unsubscribes from all notifications based on the filtering criteria. This method can be called * only by applications with required system permissions. * @note A subscriber will no longer receive the notifications from specified notification sources. * + * @deprecated This function is deprecated, + * use 'UnSubscribeNotification(const std::shared_ptr &subscriber, + * const std::shared_ptr &subscribeInfo)'. * @param subscriber Indicates the {NotificationSubscriber} to receive notifications. * This parameter must be specified. * @param subscribeInfo Indicates the filters for , including application name, @@ -437,6 +513,20 @@ public: */ ErrCode UnSubscribeNotification(NotificationSubscriber &subscriber, NotificationSubscribeInfo subscribeInfo); + /** + * @brief Unsubscribes from all notifications based on the filtering criteria. This method can be called + * only by applications with required system permissions. + * @note A subscriber will no longer receive the notifications from specified notification sources. + * + * @param subscriber Indicates the {NotificationSubscriber} to receive notifications. + * This parameter must be specified. + * @param subscribeInfo Indicates the filters for , including application name, + * user ID, or device name. This parameter is optional. + * @return Returns unsubscribe notification result. + */ + ErrCode UnSubscribeNotification(const std::shared_ptr &subscriber, + const sptr &subscribeInfo); + /** * @brief Trigger the local live view after the button has been clicked. * @note Your application must have platform signature to use this method. @@ -1113,6 +1203,11 @@ public: * @return Returns ERR_OK on success, others on failure. */ ErrCode GetDoNotDisturbProfile(int32_t id, sptr &profile); + + /** + * @brief Ans service died, OnRemoteDied called. + */ + void OnServiceDied(); private: /** * @brief Gets Ans Manager proxy. @@ -1155,10 +1250,12 @@ private: bool IsValidTemplate(const NotificationRequest &request) const; bool IsValidDelayTime(const NotificationRequest &request) const; + void CreateSubscribeListener(const std::shared_ptr &subscriber, + sptr &listener); private: - std::mutex mutex_; - sptr ansManagerProxy_; + std::mutex subscriberMutex_; + std::map, sptr> subscribers_; #ifdef NOTIFICATION_SMART_REMINDER_SUPPORTED sptr swingCallBackStub_; #endif diff --git a/frameworks/core/include/ans_subscriber_listener.h b/frameworks/core/include/ans_subscriber_listener.h new file mode 100644 index 000000000..2ecd8bf32 --- /dev/null +++ b/frameworks/core/include/ans_subscriber_listener.h @@ -0,0 +1,68 @@ +/* + * Copyright (c) 2021-2024 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef BASE_NOTIFICATION_DISTRIBUTED_NOTIFICATION_SERVICE_CORE_NOTIFICATION_SUBSCRIBER_LISTENER_H +#define BASE_NOTIFICATION_DISTRIBUTED_NOTIFICATION_SERVICE_CORE_NOTIFICATION_SUBSCRIBER_LISTENER_H + +#include "ans_manager_interface.h" +#include "ans_subscriber_stub.h" +#include "notification_request.h" +#include "notification_sorting.h" +#include "notification_sorting_map.h" +#include "notification_subscriber.h" + +namespace OHOS { +namespace Notification { +class SubscriberListener final : public AnsSubscriberStub { +public: + SubscriberListener(const std::shared_ptr &subscriber); + ~SubscriberListener(); + + void OnConnected() override; + + void OnDisconnected() override; + + void OnConsumed( + const sptr ¬ification, const sptr ¬ificationMap) override; + + void OnConsumedList(const std::vector> ¬ifications, + const sptr ¬ificationMap) override; + + void OnCanceled(const sptr ¬ification, const sptr ¬ificationMap, + int32_t deleteReason) override; + + void OnCanceledList(const std::vector> ¬ifications, + const sptr ¬ificationMap, int32_t deleteReason) override; + + void OnBatchCanceled(const std::vector> ¬ifications, + const sptr ¬ificationMap, int32_t deleteReason); + + void OnUpdated(const sptr ¬ificationMap) override; + + void OnDoNotDisturbDateChange(const sptr &date) override; + + void OnEnabledNotificationChanged(const sptr &callbackData) override; + + void OnBadgeChanged(const sptr &badgeData) override; + + void OnBadgeEnabledChanged(const sptr &callbackData) override; + +public: + std::weak_ptr subscriber_; +}; +} // namespace Notification +} // namespace OHOS + +#endif // BASE_NOTIFICATION_DISTRIBUTED_NOTIFICATION_SERVICE_CORE_NOTIFICATION_SUBSCRIBER_LISTENER_H \ No newline at end of file diff --git a/frameworks/core/src/ans_manager_death_recipient.cpp b/frameworks/core/src/ans_manager_death_recipient.cpp index fab6f2f06..9048f8a58 100644 --- a/frameworks/core/src/ans_manager_death_recipient.cpp +++ b/frameworks/core/src/ans_manager_death_recipient.cpp @@ -24,6 +24,10 @@ namespace OHOS { namespace Notification { void AnsManagerDeathRecipient::SubscribeSAManager() { + std::lock_guard lock(mutex_); + if (statusChangeListener_ != nullptr) { + return; + } auto samgrProxy = SystemAbilityManagerClient::GetInstance().GetSystemAbilityManager(); statusChangeListener_ = new (std::nothrow) AnsManagerDeathRecipient::SystemAbilityStatusChangeListener(); if (samgrProxy == nullptr || statusChangeListener_ == nullptr) { @@ -37,29 +41,14 @@ void AnsManagerDeathRecipient::SubscribeSAManager() statusChangeListener_ = nullptr; } } - -bool AnsManagerDeathRecipient::GetIsSubscribeSAManager() -{ - return statusChangeListener_ != nullptr; -} - void AnsManagerDeathRecipient::SystemAbilityStatusChangeListener::OnAddSystemAbility( - int32_t systemAbilityId, const std::string& deviceId) -{ - if (!isSAOffline) { - return; - } - ANS_LOGI("Ans manager service restore, try to reconnect"); - DelayedSingleton::GetInstance()->Reconnect(); - isSAOffline = false; -} + int32_t systemAbilityId, const std::string& deviceId) {} void AnsManagerDeathRecipient::SystemAbilityStatusChangeListener::OnRemoveSystemAbility( int32_t systemAbilityId, const std::string& deviceId) { ANS_LOGI("Ans manager service died"); - DelayedSingleton::GetInstance()->ResetAnsManagerProxy(); - isSAOffline = true; + DelayedSingleton::GetInstance()->OnServiceDied(); } } // namespace Notification -} // namespace OHOS +} // namespace OHOS \ No newline at end of file diff --git a/frameworks/core/src/ans_notification.cpp b/frameworks/core/src/ans_notification.cpp index 0c3be2a2b..4e30fe577 100644 --- a/frameworks/core/src/ans_notification.cpp +++ b/frameworks/core/src/ans_notification.cpp @@ -17,6 +17,7 @@ #include "ans_const_define.h" #include "ans_inner_errors.h" #include "ans_log_wrapper.h" +#include "ans_manager_death_recipient.h" #include "ans_manager_proxy.h" #include "hitrace_meter_adapter.h" #include "ipc_skeleton.h" @@ -27,7 +28,9 @@ #include "reminder_request_calendar.h" #include "reminder_request_timer.h" #include "system_ability_definition.h" +#include "unique_fd.h" +#include #include namespace OHOS { @@ -670,6 +673,98 @@ ErrCode AnsNotification::UnSubscribeNotification( return proxy->Unsubscribe(subscriberSptr, sptrInfo); } +ErrCode AnsNotification::SubscribeNotification(const std::shared_ptr &subscriber) +{ + HITRACE_METER_NAME(HITRACE_TAG_NOTIFICATION, __PRETTY_FUNCTION__); + return SubscribeNotification(subscriber, nullptr); +} + +ErrCode AnsNotification::SubscribeNotificationSelf(const std::shared_ptr &subscriber) +{ + HITRACE_METER_NAME(HITRACE_TAG_NOTIFICATION, __PRETTY_FUNCTION__); + if (subscriber == nullptr) { + ANS_LOGE("Subscriber is nullptr."); + return ERR_ANS_INVALID_PARAM; + } + + sptr proxy = GetAnsManagerProxy(); + if (!proxy) { + ANS_LOGE("GetAnsManagerProxy fail."); + return ERR_ANS_SERVICE_NOT_CONNECTED; + } + + sptr listener = nullptr; + CreateSubscribeListener(subscriber, listener); + if (listener == nullptr) { + ANS_LOGE("Failed to subscribe due to create subscriber listener failed."); + return ERR_ANS_NO_MEMORY; + } + DelayedSingleton::GetInstance()->SubscribeSAManager(); + return proxy->SubscribeSelf(listener); +} + +ErrCode AnsNotification::SubscribeNotification(const std::shared_ptr &subscriber, + const sptr &subscribeInfo) +{ + HITRACE_METER_NAME(HITRACE_TAG_NOTIFICATION, __PRETTY_FUNCTION__); + if (subscriber == nullptr) { + ANS_LOGE("Subscriber is nullptr."); + return ERR_ANS_INVALID_PARAM; + } + + sptr proxy = GetAnsManagerProxy(); + if (!proxy) { + ANS_LOGE("Failed to GetAnsManagerProxy."); + return ERR_ANS_SERVICE_NOT_CONNECTED; + } + + sptr listener = nullptr; + CreateSubscribeListener(subscriber, listener); + if (listener == nullptr) { + ANS_LOGE("Failed to subscribe due to create subscriber listener failed."); + return ERR_ANS_NO_MEMORY; + } + if (subscribeInfo != nullptr) { + subscriber->SetDeviceType(subscribeInfo->GetDeviceType()); + } + DelayedSingleton::GetInstance()->SubscribeSAManager(); + return proxy->Subscribe(listener, subscribeInfo); +} + +ErrCode AnsNotification::UnSubscribeNotification(const std::shared_ptr &subscriber) +{ + HITRACE_METER_NAME(HITRACE_TAG_NOTIFICATION, __PRETTY_FUNCTION__); + return UnSubscribeNotification(subscriber, nullptr); +} + +ErrCode AnsNotification::UnSubscribeNotification(const std::shared_ptr &subscriber, + const sptr &subscribeInfo) +{ + HITRACE_METER_NAME(HITRACE_TAG_NOTIFICATION, __PRETTY_FUNCTION__); + if (subscriber == nullptr) { + ANS_LOGE("Subscriber is nullptr."); + return ERR_ANS_INVALID_PARAM; + } + + sptr proxy = GetAnsManagerProxy(); + if (!proxy) { + ANS_LOGE("GetAnsManagerProxy fail."); + return ERR_ANS_SERVICE_NOT_CONNECTED; + } + std::lock_guard lock(subscriberMutex_); + auto item = subscribers_.find(subscriber); + if (item != subscribers_.end()) { + sptr listener = item->second; + int32_t ret = proxy->Unsubscribe(listener, subscribeInfo); + if (ret == ERR_OK) { + subscribers_.erase(item); + } + return ret; + } + ANS_LOGE("Failed to unsubscribe due to subscriber not found."); + return ERR_ANS_INVALID_PARAM; +} + ErrCode AnsNotification::TriggerLocalLiveView(const NotificationBundleOption &bundleOption, const int32_t notificationId, const NotificationButtonOption &buttonOption) { @@ -1245,11 +1340,7 @@ ErrCode AnsNotification::GetDeviceRemindType(NotificationConstant::RemindType &r } void AnsNotification::ResetAnsManagerProxy() -{ - ANS_LOGD("enter"); - std::lock_guard lock(mutex_); - ansManagerProxy_ = nullptr; -} +{} void AnsNotification::Reconnect() { @@ -1910,6 +2001,31 @@ ErrCode AnsNotification::GetDoNotDisturbProfile(int32_t id, sptrGetDoNotDisturbProfile(id, profile); } +void AnsNotification::CreateSubscribeListener(const std::shared_ptr &subscriber, + sptr &listener) +{ + std::lock_guard lock(subscriberMutex_); + auto item = subscribers_.find(subscriber); + if (item != subscribers_.end()) { + listener = item->second; + ANS_LOGD("subscriber has listener"); + return; + } + listener = new (std::nothrow) SubscriberListener(subscriber); + if (listener != nullptr) { + subscribers_[subscriber] = listener; + ANS_LOGD("CreateSubscribeListener success"); + } +} + +void AnsNotification::OnServiceDied() +{ + std::lock_guard lock(subscriberMutex_); + for (auto item : subscribers_) { + item.first->OnDied(); + } +} + #ifdef NOTIFICATION_SMART_REMINDER_SUPPORTED ErrCode AnsNotification::RegisterSwingCallback(const std::function swingCbFunc) { diff --git a/frameworks/core/src/ans_subscriber_listener.cpp b/frameworks/core/src/ans_subscriber_listener.cpp new file mode 100644 index 000000000..e4c2af00b --- /dev/null +++ b/frameworks/core/src/ans_subscriber_listener.cpp @@ -0,0 +1,195 @@ +/* + * Copyright (c) 2021-2024 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "ans_subscriber_listener.h" +#include "notification_constant.h" +#include "hitrace_meter_adapter.h" +#include "iservice_registry.h" +#include "system_ability_definition.h" + +namespace OHOS { +namespace Notification { +SubscriberListener::SubscriberListener(const std::shared_ptr &subscriber) + : subscriber_(subscriber) +{}; + +SubscriberListener::~SubscriberListener() +{} + +void SubscriberListener::OnConnected() +{ + HITRACE_METER_NAME(HITRACE_TAG_NOTIFICATION, __PRETTY_FUNCTION__); + auto subscriber = subscriber_.lock(); + if (subscriber == nullptr) { + ANS_LOGW("Subscriber is nullptr"); + return; + } + subscriber->OnConnected(); +} + +void SubscriberListener::OnDisconnected() +{ + HITRACE_METER_NAME(HITRACE_TAG_NOTIFICATION, __PRETTY_FUNCTION__); + auto subscriber = subscriber_.lock(); + if (subscriber == nullptr) { + ANS_LOGW("Subscriber is nullptr"); + return; + } + subscriber->OnDisconnected(); +} + +void SubscriberListener::OnConsumed( + const sptr ¬ification, const sptr ¬ificationMap) +{ + HITRACE_METER_NAME(HITRACE_TAG_NOTIFICATION, __PRETTY_FUNCTION__); + auto subscriber = subscriber_.lock(); + if (subscriber == nullptr) { + ANS_LOGW("Subscriber is nullptr"); + return; + } + + std::shared_ptr sharedNotification = std::make_shared(*notification); +#ifdef NOTIFICATION_SMART_REMINDER_SUPPORTED + if (!subscriber->ProcessSyncDecision(subscriber->GetDeviceType(), sharedNotification)) { + return; + } +#endif + + subscriber->OnConsumed( + sharedNotification, std::make_shared(*notificationMap)); +} + +void SubscriberListener::OnConsumedList(const std::vector> ¬ifications, + const sptr ¬ificationMap) +{ + HITRACE_METER_NAME(HITRACE_TAG_NOTIFICATION, __PRETTY_FUNCTION__); + for (auto notification : notifications) { + OnConsumed(notification, notificationMap); + } +} + +void SubscriberListener::OnCanceled( + const sptr ¬ification, const sptr ¬ificationMap, int32_t deleteReason) +{ + HITRACE_METER_NAME(HITRACE_TAG_NOTIFICATION, __PRETTY_FUNCTION__); + auto subscriber = subscriber_.lock(); + if (subscriber == nullptr) { + ANS_LOGW("Subscriber is nullptr"); + return; + } + if (notificationMap == nullptr) { + subscriber->OnCanceled(std::make_shared(*notification), + std::make_shared(), deleteReason); + } else { + subscriber->OnCanceled(std::make_shared(*notification), + std::make_shared(*notificationMap), deleteReason); + } +} + +void SubscriberListener::OnBatchCanceled(const std::vector> ¬ifications, + const sptr ¬ificationMap, int32_t deleteReason) +{ + auto subscriber = subscriber_.lock(); + if (subscriber == nullptr) { + ANS_LOGW("Subscriber is nullptr"); + return; + } + std::vector> notificationList; + for (auto notification : notifications) { + notificationList.emplace_back(std::make_shared(*notification)); + } + if (notificationMap == nullptr) { + subscriber->OnBatchCanceled(notificationList, + std::make_shared(), deleteReason); + } else { + subscriber->OnBatchCanceled(notificationList, + std::make_shared(*notificationMap), deleteReason); + } +} + +void SubscriberListener::OnCanceledList(const std::vector> ¬ifications, + const sptr ¬ificationMap, int32_t deleteReason) +{ + HITRACE_METER_NAME(HITRACE_TAG_NOTIFICATION, __PRETTY_FUNCTION__); + auto subscriber = subscriber_.lock(); + if (subscriber == nullptr) { + ANS_LOGW("Subscriber is nullptr"); + return; + } + if (subscriber->HasOnBatchCancelCallback()) { + OnBatchCanceled(notifications, notificationMap, deleteReason); + return; + } + for (auto notification : notifications) { + OnCanceled(notification, notificationMap, deleteReason); + } +} + +void SubscriberListener::OnUpdated(const sptr ¬ificationMap) +{ + auto subscriber = subscriber_.lock(); + if (subscriber == nullptr) { + ANS_LOGW("Subscriber is nullptr"); + return; + } + subscriber->OnUpdate(std::make_shared(*notificationMap)); +} + +void SubscriberListener::OnDoNotDisturbDateChange(const sptr &date) +{ + auto subscriber = subscriber_.lock(); + if (subscriber == nullptr) { + ANS_LOGW("Subscriber is nullptr"); + return; + } + subscriber->OnDoNotDisturbDateChange(std::make_shared(*date)); +} + +void SubscriberListener::OnEnabledNotificationChanged( + const sptr &callbackData) +{ + HITRACE_METER_NAME(HITRACE_TAG_NOTIFICATION, __PRETTY_FUNCTION__); + auto subscriber = subscriber_.lock(); + if (subscriber == nullptr) { + ANS_LOGW("Subscriber is nullptr"); + return; + } + subscriber->OnEnabledNotificationChanged(std::make_shared(*callbackData)); +} + +void SubscriberListener::OnBadgeChanged(const sptr &badgeData) +{ + HITRACE_METER_NAME(HITRACE_TAG_NOTIFICATION, __PRETTY_FUNCTION__); + auto subscriber = subscriber_.lock(); + if (subscriber == nullptr) { + ANS_LOGW("Subscriber is nullptr"); + return; + } + subscriber->OnBadgeChanged(std::make_shared(*badgeData)); +} + +void SubscriberListener::OnBadgeEnabledChanged( + const sptr &callbackData) +{ + HITRACE_METER_NAME(HITRACE_TAG_NOTIFICATION, __PRETTY_FUNCTION__); + auto subscriber = subscriber_.lock(); + if (subscriber == nullptr) { + ANS_LOGW("Subscriber is nullptr"); + return; + } + subscriber->OnBadgeEnabledChanged(callbackData); +} +} // namespace Notification +} // namespace OHOS diff --git a/frameworks/core/test/unittest/BUILD.gn b/frameworks/core/test/unittest/BUILD.gn index 22ef009cc..94550b16b 100644 --- a/frameworks/core/test/unittest/BUILD.gn +++ b/frameworks/core/test/unittest/BUILD.gn @@ -17,7 +17,6 @@ group("unittest") { deps += [ "ans_image_util_test:unittest", - "ans_manager_death_recipient_test:unittest", "ans_manager_proxy_test:unittest", "ans_manager_stub_test:unittest", "ans_notification_annex_test:unittest", diff --git a/frameworks/core/test/unittest/ans_manager_death_recipient_test/BUILD.gn b/frameworks/core/test/unittest/ans_manager_death_recipient_test/BUILD.gn deleted file mode 100644 index 4f7cfcc8b..000000000 --- a/frameworks/core/test/unittest/ans_manager_death_recipient_test/BUILD.gn +++ /dev/null @@ -1,47 +0,0 @@ -# Copyright (c) 2022-2023 Huawei Device Co., Ltd. -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -import("//base/notification/distributed_notification_service/notification.gni") -import("//build/ohos.gni") -import("//build/test.gni") - -module_output_path = "${component_name}/unittest" - -ohos_unittest("ans_manager_death_recipient_test") { - module_out_path = module_output_path - include_dirs = [ "${core_path}/include" ] - - sources = [ "ans_manager_death_recipient_unit_test.cpp" ] - - deps = [ "${frameworks_module_ans_path}:ans_innerkits" ] - - external_deps = [ - "ability_base:want", - "ability_base:zuri", - "ability_runtime:wantagent_innerkits", - "c_utils:utils", - "hilog:libhilog", - "image_framework:image_native", - "relational_store:native_rdb", - ] - - subsystem_name = "${subsystem_name}" - part_name = "${component_name}" -} - -group("unittest") { - testonly = true - deps = [] - - deps += [ ":ans_manager_death_recipient_test" ] -} diff --git a/frameworks/core/test/unittest/ans_manager_death_recipient_test/ans_manager_death_recipient_unit_test.cpp b/frameworks/core/test/unittest/ans_manager_death_recipient_test/ans_manager_death_recipient_unit_test.cpp deleted file mode 100644 index 165d38141..000000000 --- a/frameworks/core/test/unittest/ans_manager_death_recipient_test/ans_manager_death_recipient_unit_test.cpp +++ /dev/null @@ -1,102 +0,0 @@ -/* - * Copyright (c) 2022 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#include - -#define private public -#define protected public -#include "ans_manager_death_recipient.h" -#include "ans_notification.h" -#undef private -#undef protected - -#include "singleton.h" - -using namespace testing::ext; -using namespace OHOS; -using namespace OHOS::Notification; - -class AnsManagerDeathRecipientUnitTest : public testing::Test { -public: - AnsManagerDeathRecipientUnitTest() {} - - virtual ~AnsManagerDeathRecipientUnitTest() {} - - static void SetUpTestCase(); - - static void TearDownTestCase(); - - void SetUp(); - - void TearDown(); -}; - -void AnsManagerDeathRecipientUnitTest::SetUpTestCase() {} - -void AnsManagerDeathRecipientUnitTest::TearDownTestCase() {} - -void AnsManagerDeathRecipientUnitTest::SetUp() {} - -void AnsManagerDeathRecipientUnitTest::TearDown() {} - -/* - * @tc.name: SubscribeSAManagerTest_0100 - * @tc.desc: test if AnsManagerDeathRecipient's SubscribeSAManager function executed as expected in normal case. - * @tc.type: FUNC - * @tc.require: #I5SJ62 - */ -HWTEST_F(AnsManagerDeathRecipientUnitTest, SubscribeSAManagerTest_0100, Function | MediumTest | Level1) -{ - GTEST_LOG_(INFO) - << "AnsManagerDeathRecipientUnitTest, SubscribeSAManagerTest_0100, TestSize.Level1"; - auto ansManagerDeathRecipient = OHOS::DelayedSingleton::GetInstance(); - ansManagerDeathRecipient->SubscribeSAManager(); - EXPECT_EQ(true, ansManagerDeathRecipient->GetIsSubscribeSAManager()); -} - -/* - * @tc.name: OnRemoveSystemAbilityTest_0100 - * @tc.desc: test if AnsManagerDeathRecipient's OnRemoveSystemAbility function executed as expected in normal case. - * @tc.type: FUNC - * @tc.require: #I5SJ62 - */ -HWTEST_F(AnsManagerDeathRecipientUnitTest, OnRemoveSystemAbilityTest_0100, Function | MediumTest | Level1) -{ - GTEST_LOG_(INFO) - << "AnsManagerDeathRecipientUnitTest, OnRemoveSystemAbilityTest_0100, TestSize.Level1"; - auto ansManagerDeathRecipient = OHOS::DelayedSingleton::GetInstance(); - ansManagerDeathRecipient->SubscribeSAManager(); - ansManagerDeathRecipient->statusChangeListener_->OnRemoveSystemAbility(0, ""); - auto ansNotification = OHOS::DelayedSingleton::GetInstance(); - EXPECT_TRUE(ansNotification->ansManagerProxy_ == nullptr); -} - -/* - * @tc.name: OnAddSystemAbilityTest_0100 - * @tc.desc: test if AnsManagerDeathRecipient's OnAddSystemAbility function executed as expected in normal case. - * @tc.type: FUNC - * @tc.require: #I5SJ62 - */ -HWTEST_F(AnsManagerDeathRecipientUnitTest, OnAddSystemAbilityTest_0100, Function | MediumTest | Level1) -{ - GTEST_LOG_(INFO) - << "AnsManagerDeathRecipientUnitTest, OnAddSystemAbilityTest_0100, TestSize.Level1"; - auto ansManagerDeathRecipient = OHOS::DelayedSingleton::GetInstance(); - ansManagerDeathRecipient->SubscribeSAManager(); - ansManagerDeathRecipient->statusChangeListener_->OnRemoveSystemAbility(0, ""); - ansManagerDeathRecipient->statusChangeListener_->OnAddSystemAbility(0, ""); - auto ansNotification = OHOS::DelayedSingleton::GetInstance(); - EXPECT_TRUE(ansNotification->ansManagerProxy_ == nullptr); -} diff --git a/frameworks/core/test/unittest/ans_notification_branch_test/BUILD.gn b/frameworks/core/test/unittest/ans_notification_branch_test/BUILD.gn index 95540f750..c96bda5b6 100755 --- a/frameworks/core/test/unittest/ans_notification_branch_test/BUILD.gn +++ b/frameworks/core/test/unittest/ans_notification_branch_test/BUILD.gn @@ -25,8 +25,8 @@ ohos_unittest("ans_notification_branch_test") { ] sources = [ + "../mock/mock_ans_manager_proxy.cpp", "ans_notification_branch_test.cpp", - "mock_ans_notification.cpp", ] deps = [ diff --git a/frameworks/core/test/unittest/ans_notification_branch_test/ans_notification_branch_test.cpp b/frameworks/core/test/unittest/ans_notification_branch_test/ans_notification_branch_test.cpp index fb620ab50..887c99809 100644 --- a/frameworks/core/test/unittest/ans_notification_branch_test/ans_notification_branch_test.cpp +++ b/frameworks/core/test/unittest/ans_notification_branch_test/ans_notification_branch_test.cpp @@ -31,7 +31,7 @@ #include "singleton.h" #include "notification_subscriber.h" -extern void MockGetAnsManagerProxy(bool mockRet); +extern void MockGetAnsManagerProxy(OHOS::sptr mockRet); using namespace testing; using namespace testing::ext; @@ -608,7 +608,10 @@ public: void SetUp(); }; -void AnsNotificationBranchTest::SetUpTestCase() {} +void AnsNotificationBranchTest::SetUpTestCase() +{ + MockGetAnsManagerProxy(nullptr); +} void AnsNotificationBranchTest::TearDownTestCase() {} @@ -645,7 +648,6 @@ HWTEST_F(AnsNotificationBranchTest, RemoveNotifications_0200, Function | MediumT std::vector hashcodes; hashcodes.emplace_back(hashcode); int32_t removeReason = 1; - MockGetAnsManagerProxy(false); ErrCode ret = ansNotification->RemoveNotifications(hashcodes, removeReason); EXPECT_EQ(ret, ERR_ANS_SERVICE_NOT_CONNECTED); } @@ -680,7 +682,6 @@ HWTEST_F(AnsNotificationBranchTest, RegisterPushCallback_0100, Function | Medium auto ansNotification = std::make_shared(); EXPECT_NE(ansNotification, nullptr); sptr pushCallback = nullptr; - MockGetAnsManagerProxy(false); sptr checkRequest = new (std::nothrow) NotificationCheckRequest(); ErrCode ret = ansNotification->RegisterPushCallback(pushCallback, checkRequest); EXPECT_EQ(ret, ERR_ANS_SERVICE_NOT_CONNECTED); @@ -713,7 +714,6 @@ HWTEST_F(AnsNotificationBranchTest, UnregisterPushCallback_0100, Function | Medi { auto ansNotification = std::make_shared(); EXPECT_NE(ansNotification, nullptr); - MockGetAnsManagerProxy(false); ErrCode ret = ansNotification->UnregisterPushCallback(); EXPECT_EQ(ret, ERR_ANS_SERVICE_NOT_CONNECTED); } @@ -865,7 +865,7 @@ HWTEST_F(AnsNotificationBranchTest, SetNotificationSlotFlagsAsBundle_0001, Funct HWTEST_F(AnsNotificationBranchTest, PublishNotification_0001, Function | MediumTest | Level1) { auto notification = std::make_shared(); - notification->ansManagerProxy_ = new (std::nothrow) MockAnsManagerInterface(); + MockGetAnsManagerProxy(new (std::nothrow) MockAnsManagerInterface()); NotificationRequest req; std::shared_ptr mediaContent = std::make_shared(); auto content = std::make_shared(mediaContent); diff --git a/frameworks/core/test/unittest/ans_notification_branch_test/mock_ans_notification.cpp b/frameworks/core/test/unittest/mock/mock_ans_manager_proxy.cpp old mode 100755 new mode 100644 similarity index 77% rename from frameworks/core/test/unittest/ans_notification_branch_test/mock_ans_notification.cpp rename to frameworks/core/test/unittest/mock/mock_ans_manager_proxy.cpp index fc40be3fe..ebf00dd06 --- a/frameworks/core/test/unittest/ans_notification_branch_test/mock_ans_notification.cpp +++ b/frameworks/core/test/unittest/mock/mock_ans_manager_proxy.cpp @@ -1,37 +1,34 @@ -/* - * Copyright (c) 2023 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#include "ans_notification.h" - -namespace { - bool g_mockGetAnsManagerProxy = true; -} - -void MockGetAnsManagerProxy(bool mockRet) -{ - g_mockGetAnsManagerProxy = mockRet; -} - -namespace OHOS { -namespace Notification { -sptr AnsNotification::GetAnsManagerProxy() -{ - if (g_mockGetAnsManagerProxy) { - return ansManagerProxy_; - } - return nullptr; -} -} // namespace Notification -} // namespace OHOS +/* + * Copyright (c) 2023 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "ans_notification.h" + +namespace { + OHOS::sptr g_mockGetAnsManagerProxy = nullptr; +} + +void MockGetAnsManagerProxy(OHOS::sptr mockRet) +{ + g_mockGetAnsManagerProxy = mockRet; +} + +namespace OHOS { +namespace Notification { +sptr AnsNotification::GetAnsManagerProxy() +{ + return g_mockGetAnsManagerProxy; +} +} // namespace Notification +} // namespace OHOS \ No newline at end of file diff --git a/frameworks/js/napi/include/subscribe.h b/frameworks/js/napi/include/subscribe.h index 4cbf1d101..1f1a27713 100644 --- a/frameworks/js/napi/include/subscribe.h +++ b/frameworks/js/napi/include/subscribe.h @@ -21,7 +21,7 @@ namespace OHOS { namespace NotificationNapi { using namespace OHOS::Notification; -class SubscriberInstance : public NotificationSubscriber, public std::enable_shared_from_this { +class SubscriberInstance : public NotificationSubscriber { public: SubscriberInstance(); virtual ~SubscriberInstance(); @@ -131,79 +131,47 @@ public: * @param ref Indicates the napi_ref of callback. */ void SetCallbackInfo(const napi_env &env, const std::string &type, const napi_ref &ref); - + /** - * @brief Sets the callback information by type. + * @brief Sets threadsafe_function. * - * @param type Indicates the type of callback. - * @param env Indicates the environment that the API is invoked under. - * @param ref Indicates the napi_ref of callback. * @param tsfn Indicates the napi_threadsafe_function of callback. */ - void SetCallbackInfo(const std::string &type, const napi_env &env, const napi_ref &ref, - const napi_threadsafe_function &tsfn); + void SetThreadSafeFunction(const napi_threadsafe_function &tsfn); private: void SetCancelCallbackInfo(const napi_env &env, const napi_ref &ref); - void SetCancelCallbackInfo(const napi_env &env, const napi_ref &ref, const napi_threadsafe_function &tsfn); - void SetConsumeCallbackInfo(const napi_env &env, const napi_ref &ref); - void SetConsumeCallbackInfo(const napi_env &env, const napi_ref &ref, const napi_threadsafe_function &tsfn); - void SetUpdateCallbackInfo(const napi_env &env, const napi_ref &ref); - void SetUpdateCallbackInfo(const napi_env &env, const napi_ref &ref, const napi_threadsafe_function &tsfn); - void SetSubscribeCallbackInfo(const napi_env &env, const napi_ref &ref); - void SetSubscribeCallbackInfo(const napi_env &env, const napi_ref &ref, const napi_threadsafe_function &tsfn); - void SetUnsubscribeCallbackInfo(const napi_env &env, const napi_ref &ref); - void SetUnsubscribeCallbackInfo(const napi_env &env, const napi_ref &ref, const napi_threadsafe_function &tsfn); - void SetDieCallbackInfo(const napi_env &env, const napi_ref &ref); - void SetDieCallbackInfo(const napi_env &env, const napi_ref &ref, const napi_threadsafe_function &tsfn); - void SetDisturbModeCallbackInfo(const napi_env &env, const napi_ref &ref); - void SetDisturbModeCallbackInfo(const napi_env &env, const napi_ref &ref, const napi_threadsafe_function &tsfn); - void SetDisturbDateCallbackInfo(const napi_env &env, const napi_ref &ref); - void SetDisturbDateCallbackInfo(const napi_env &env, const napi_ref &ref, const napi_threadsafe_function &tsfn); - void SetDisturbChangedCallbackInfo(const napi_env &env, const napi_ref &ref); - void SetDisturbChangedCallbackInfo(const napi_env &env, const napi_ref &ref, const napi_threadsafe_function &tsfn); - void SetEnabledNotificationCallbackInfo(const napi_env &env, const napi_ref &ref); - void SetEnabledNotificationCallbackInfo(const napi_env &env, const napi_ref &ref, - const napi_threadsafe_function &tsfn); - void SetBadgeCallbackInfo(const napi_env &env, const napi_ref &ref); - void SetBadgeCallbackInfo(const napi_env &env, const napi_ref &ref, const napi_threadsafe_function &tsfn); - void SetBadgeEnabledCallbackInfo(const napi_env &env, const napi_ref &ref); - void SetBadgeEnabledCallbackInfo(const napi_env &env, const napi_ref &ref, const napi_threadsafe_function &tsfn); - void SetBatchCancelCallbackInfo(const napi_env &env, const napi_ref &ref); - void SetBatchCancelCallbackInfo(const napi_env &env, const napi_ref &ref, const napi_threadsafe_function &tsfn); - private: struct CallbackInfo { napi_env env = nullptr; napi_ref ref = nullptr; - napi_threadsafe_function tsfn = nullptr; }; - + napi_threadsafe_function tsfn_ = nullptr; CallbackInfo canceCallbackInfo_; CallbackInfo consumeCallbackInfo_; CallbackInfo updateCallbackInfo_; diff --git a/frameworks/js/napi/src/subscribe.cpp b/frameworks/js/napi/src/subscribe.cpp index f14fea9fc..3b40214c6 100644 --- a/frameworks/js/napi/src/subscribe.cpp +++ b/frameworks/js/napi/src/subscribe.cpp @@ -143,8 +143,8 @@ SubscriberInstance::SubscriberInstance() SubscriberInstance::~SubscriberInstance() { - if (unsubscribeCallbackInfo_.tsfn != nullptr) { - napi_release_threadsafe_function(unsubscribeCallbackInfo_.tsfn, napi_tsfn_release); + if (tsfn_ != nullptr) { + napi_release_threadsafe_function(tsfn_, napi_tsfn_release); } if (canceCallbackInfo_.ref != nullptr) { napi_delete_reference(canceCallbackInfo_.env, canceCallbackInfo_.ref); @@ -243,9 +243,9 @@ void SubscriberInstance::OnCanceled(const std::shared_ptrref = canceCallbackInfo_.ref; dataWorker->type = Type::CANCEL; - napi_acquire_threadsafe_function(canceCallbackInfo_.tsfn); - napi_call_threadsafe_function(canceCallbackInfo_.tsfn, dataWorker, napi_tsfn_nonblocking); - napi_release_threadsafe_function(canceCallbackInfo_.tsfn, napi_tsfn_release); + napi_acquire_threadsafe_function(tsfn_); + napi_call_threadsafe_function(tsfn_, dataWorker, napi_tsfn_nonblocking); + napi_release_threadsafe_function(tsfn_, napi_tsfn_release); } void ThreadSafeOnBatchCancel(napi_env env, napi_value jsCallback, void* context, void* data) @@ -325,9 +325,9 @@ void SubscriberInstance::OnBatchCanceled(const std::vectorref = batchCancelCallbackInfo_.ref; dataWorker->type = Type::BATCH_CANCEL; - napi_acquire_threadsafe_function(batchCancelCallbackInfo_.tsfn); - napi_call_threadsafe_function(batchCancelCallbackInfo_.tsfn, dataWorker, napi_tsfn_nonblocking); - napi_release_threadsafe_function(batchCancelCallbackInfo_.tsfn, napi_tsfn_release); + napi_acquire_threadsafe_function(tsfn_); + napi_call_threadsafe_function(tsfn_, dataWorker, napi_tsfn_nonblocking); + napi_release_threadsafe_function(tsfn_, napi_tsfn_release); return; } @@ -382,7 +382,7 @@ void SubscriberInstance::OnConsumed(const std::shared_ptrenv = consumeCallbackInfo_.env; dataWorker->ref = consumeCallbackInfo_.ref; dataWorker->type = Type::CONSUME; - - napi_acquire_threadsafe_function(consumeCallbackInfo_.tsfn); - napi_call_threadsafe_function(consumeCallbackInfo_.tsfn, dataWorker, napi_tsfn_nonblocking); - napi_release_threadsafe_function(consumeCallbackInfo_.tsfn, napi_tsfn_release); + napi_acquire_threadsafe_function(tsfn_); + napi_call_threadsafe_function(tsfn_, dataWorker, napi_tsfn_nonblocking); + napi_release_threadsafe_function(tsfn_, napi_tsfn_release); } void ThreadSafeOnUpdate(napi_env env, napi_value jsCallback, void* context, void* data) @@ -473,9 +472,9 @@ void SubscriberInstance::OnUpdate(const std::shared_ptr dataWorker->ref = updateCallbackInfo_.ref; dataWorker->type = Type::UPDATE; - napi_acquire_threadsafe_function(updateCallbackInfo_.tsfn); - napi_call_threadsafe_function(updateCallbackInfo_.tsfn, dataWorker, napi_tsfn_nonblocking); - napi_release_threadsafe_function(updateCallbackInfo_.tsfn, napi_tsfn_release); + napi_acquire_threadsafe_function(tsfn_); + napi_call_threadsafe_function(tsfn_, dataWorker, napi_tsfn_nonblocking); + napi_release_threadsafe_function(tsfn_, napi_tsfn_release); } void ThreadSafeOnConnected(napi_env env, napi_value jsCallback, void* context, void* data) @@ -502,7 +501,7 @@ void SubscriberInstance::OnConnected() return; } - if (subscribeCallbackInfo_.tsfn == nullptr) { + if (tsfn_ == nullptr) { ANS_LOGI("subscribe tsfn is null"); return; } @@ -517,9 +516,9 @@ void SubscriberInstance::OnConnected() dataWorker->ref = subscribeCallbackInfo_.ref; dataWorker->type = Type::CONNECTED; - napi_acquire_threadsafe_function(subscribeCallbackInfo_.tsfn); - napi_call_threadsafe_function(subscribeCallbackInfo_.tsfn, dataWorker, napi_tsfn_nonblocking); - napi_release_threadsafe_function(subscribeCallbackInfo_.tsfn, napi_tsfn_release); + napi_acquire_threadsafe_function(tsfn_); + napi_call_threadsafe_function(tsfn_, dataWorker, napi_tsfn_nonblocking); + napi_release_threadsafe_function(tsfn_, napi_tsfn_release); } void ThreadSafeOnDisconnected(napi_env env, napi_value jsCallback, void* context, void* data) @@ -547,7 +546,7 @@ void SubscriberInstance::OnDisconnected() return; } - if (unsubscribeCallbackInfo_.tsfn == nullptr) { + if (tsfn_ == nullptr) { ANS_LOGI("unsubscribe tsfn is null"); return; } @@ -560,12 +559,12 @@ void SubscriberInstance::OnDisconnected() dataWorker->env = unsubscribeCallbackInfo_.env; dataWorker->ref = unsubscribeCallbackInfo_.ref; - dataWorker->subscriber = shared_from_this(); + dataWorker->subscriber = std::static_pointer_cast(shared_from_this()); dataWorker->type = Type::DIS_CONNECTED; - napi_acquire_threadsafe_function(unsubscribeCallbackInfo_.tsfn); - napi_call_threadsafe_function(unsubscribeCallbackInfo_.tsfn, dataWorker, napi_tsfn_nonblocking); - napi_release_threadsafe_function(unsubscribeCallbackInfo_.tsfn, napi_tsfn_release); + napi_acquire_threadsafe_function(tsfn_); + napi_call_threadsafe_function(tsfn_, dataWorker, napi_tsfn_nonblocking); + napi_release_threadsafe_function(tsfn_, napi_tsfn_release); } void ThreadSafeOnDestroy(napi_env env, napi_value jsCallback, void* context, void* data) @@ -604,9 +603,9 @@ void SubscriberInstance::OnDied() dataWorker->ref = dieCallbackInfo_.ref; dataWorker->type = Type::DIE; - napi_acquire_threadsafe_function(dieCallbackInfo_.tsfn); - napi_call_threadsafe_function(dieCallbackInfo_.tsfn, dataWorker, napi_tsfn_nonblocking); - napi_release_threadsafe_function(dieCallbackInfo_.tsfn, napi_tsfn_release); + napi_acquire_threadsafe_function(tsfn_); + napi_call_threadsafe_function(tsfn_, dataWorker, napi_tsfn_nonblocking); + napi_release_threadsafe_function(tsfn_, napi_tsfn_release); } void ThreadSafeOnDoNotDisturbDateChange(napi_env env, napi_value jsCallback, void* context, void* data) @@ -666,9 +665,9 @@ void SubscriberInstance::OnDoNotDisturbDateChange(const std::shared_ptrref = disturbDateCallbackInfo_.ref; dataWorker->type = Type::DISTURB_DATE_CHANGE; - napi_acquire_threadsafe_function(disturbDateCallbackInfo_.tsfn); - napi_call_threadsafe_function(disturbDateCallbackInfo_.tsfn, dataWorker, napi_tsfn_nonblocking); - napi_release_threadsafe_function(disturbDateCallbackInfo_.tsfn, napi_tsfn_release); + napi_acquire_threadsafe_function(tsfn_); + napi_call_threadsafe_function(tsfn_, dataWorker, napi_tsfn_nonblocking); + napi_release_threadsafe_function(tsfn_, napi_tsfn_release); } @@ -723,9 +722,9 @@ void SubscriberInstance::onDoNotDisturbChanged(const std::shared_ptrref = disturbChangedCallbackInfo_.ref; dataWorker->type = Type::DISTURB_CHANGED; - napi_acquire_threadsafe_function(disturbChangedCallbackInfo_.tsfn); - napi_call_threadsafe_function(disturbChangedCallbackInfo_.tsfn, dataWorker, napi_tsfn_nonblocking); - napi_release_threadsafe_function(disturbChangedCallbackInfo_.tsfn, napi_tsfn_release); + napi_acquire_threadsafe_function(tsfn_); + napi_call_threadsafe_function(tsfn_, dataWorker, napi_tsfn_nonblocking); + napi_release_threadsafe_function(tsfn_, napi_tsfn_release); } void ThreadSafeOnEnabledNotificationChanged(napi_env env, napi_value jsCallback, void* context, void* data) @@ -784,9 +783,9 @@ void SubscriberInstance::OnEnabledNotificationChanged( dataWorker->ref = enabledNotificationCallbackInfo_.ref; dataWorker->type = Type::ENABLE_NOTIFICATION_CHANGED; - napi_acquire_threadsafe_function(enabledNotificationCallbackInfo_.tsfn); - napi_call_threadsafe_function(enabledNotificationCallbackInfo_.tsfn, dataWorker, napi_tsfn_nonblocking); - napi_release_threadsafe_function(enabledNotificationCallbackInfo_.tsfn, napi_tsfn_release); + napi_acquire_threadsafe_function(tsfn_); + napi_call_threadsafe_function(tsfn_, dataWorker, napi_tsfn_nonblocking); + napi_release_threadsafe_function(tsfn_, napi_tsfn_release); } void ThreadSafeOnBadgeChanged(napi_env env, napi_value jsCallback, void* context, void* data) @@ -844,9 +843,9 @@ void SubscriberInstance::OnBadgeChanged( dataWorker->ref = setBadgeCallbackInfo_.ref; dataWorker->type = Type::BADGE_CHANGED; - napi_acquire_threadsafe_function(setBadgeCallbackInfo_.tsfn); - napi_call_threadsafe_function(setBadgeCallbackInfo_.tsfn, dataWorker, napi_tsfn_nonblocking); - napi_release_threadsafe_function(setBadgeCallbackInfo_.tsfn, napi_tsfn_release); + napi_acquire_threadsafe_function(tsfn_); + napi_call_threadsafe_function(tsfn_, dataWorker, napi_tsfn_nonblocking); + napi_release_threadsafe_function(tsfn_, napi_tsfn_release); } void ThreadSafeOnBadgeEnabledChanged(napi_env env, napi_value jsCallback, void* context, void* data) @@ -901,23 +900,20 @@ void SubscriberInstance::OnBadgeEnabledChanged( dataWorker->ref = setBadgeEnabledCallbackInfo_.ref; dataWorker->type = Type::BADGE_ENABLED_CHANGED; - napi_acquire_threadsafe_function(setBadgeEnabledCallbackInfo_.tsfn); - napi_call_threadsafe_function(setBadgeEnabledCallbackInfo_.tsfn, dataWorker, napi_tsfn_nonblocking); - napi_release_threadsafe_function(setBadgeEnabledCallbackInfo_.tsfn, napi_tsfn_release); + napi_acquire_threadsafe_function(tsfn_); + napi_call_threadsafe_function(tsfn_, dataWorker, napi_tsfn_nonblocking); + napi_release_threadsafe_function(tsfn_, napi_tsfn_release); } -void SubscriberInstance::SetCancelCallbackInfo(const napi_env &env, const napi_ref &ref) +void SubscriberInstance::SetThreadSafeFunction(const napi_threadsafe_function &tsfn) { - canceCallbackInfo_.env = env; - canceCallbackInfo_.ref = ref; + tsfn_ = tsfn; } -void SubscriberInstance::SetCancelCallbackInfo(const napi_env &env, const napi_ref &ref, - const napi_threadsafe_function &tsfn) +void SubscriberInstance::SetCancelCallbackInfo(const napi_env &env, const napi_ref &ref) { canceCallbackInfo_.env = env; canceCallbackInfo_.ref = ref; - canceCallbackInfo_.tsfn = tsfn; } void SubscriberInstance::SetConsumeCallbackInfo(const napi_env &env, const napi_ref &ref) @@ -926,139 +922,60 @@ void SubscriberInstance::SetConsumeCallbackInfo(const napi_env &env, const napi_ consumeCallbackInfo_.ref = ref; } -void SubscriberInstance::SetConsumeCallbackInfo(const napi_env &env, const napi_ref &ref, - const napi_threadsafe_function &tsfn) -{ - consumeCallbackInfo_.env = env; - consumeCallbackInfo_.ref = ref; - consumeCallbackInfo_.tsfn = tsfn; -} - void SubscriberInstance::SetUpdateCallbackInfo(const napi_env &env, const napi_ref &ref) { updateCallbackInfo_.env = env; updateCallbackInfo_.ref = ref; } -void SubscriberInstance::SetUpdateCallbackInfo(const napi_env &env, const napi_ref &ref, - const napi_threadsafe_function &tsfn) -{ - updateCallbackInfo_.env = env; - updateCallbackInfo_.ref = ref; - updateCallbackInfo_.tsfn = tsfn; -} - void SubscriberInstance::SetSubscribeCallbackInfo(const napi_env &env, const napi_ref &ref) { subscribeCallbackInfo_.env = env; subscribeCallbackInfo_.ref = ref; } -void SubscriberInstance::SetSubscribeCallbackInfo(const napi_env &env, const napi_ref &ref, - const napi_threadsafe_function &tsfn) -{ - subscribeCallbackInfo_.env = env; - subscribeCallbackInfo_.ref = ref; - subscribeCallbackInfo_.tsfn = tsfn; -} - void SubscriberInstance::SetUnsubscribeCallbackInfo(const napi_env &env, const napi_ref &ref) { unsubscribeCallbackInfo_.env = env; unsubscribeCallbackInfo_.ref = ref; } -void SubscriberInstance::SetUnsubscribeCallbackInfo(const napi_env &env, const napi_ref &ref, - const napi_threadsafe_function &tsfn) -{ - unsubscribeCallbackInfo_.env = env; - unsubscribeCallbackInfo_.ref = ref; - unsubscribeCallbackInfo_.tsfn = tsfn; -} - void SubscriberInstance::SetDieCallbackInfo(const napi_env &env, const napi_ref &ref) { dieCallbackInfo_.env = env; dieCallbackInfo_.ref = ref; } -void SubscriberInstance::SetDieCallbackInfo(const napi_env &env, const napi_ref &ref, - const napi_threadsafe_function &tsfn) -{ - dieCallbackInfo_.env = env; - dieCallbackInfo_.ref = ref; - dieCallbackInfo_.tsfn = tsfn; -} - void SubscriberInstance::SetDisturbModeCallbackInfo(const napi_env &env, const napi_ref &ref) { disturbModeCallbackInfo_.env = env; disturbModeCallbackInfo_.ref = ref; } -void SubscriberInstance::SetDisturbModeCallbackInfo(const napi_env &env, const napi_ref &ref, - const napi_threadsafe_function &tsfn) -{ - disturbModeCallbackInfo_.env = env; - disturbModeCallbackInfo_.ref = ref; - disturbModeCallbackInfo_.tsfn = tsfn; -} - void SubscriberInstance::SetEnabledNotificationCallbackInfo(const napi_env &env, const napi_ref &ref) { enabledNotificationCallbackInfo_.env = env; enabledNotificationCallbackInfo_.ref = ref; } -void SubscriberInstance::SetEnabledNotificationCallbackInfo(const napi_env &env, const napi_ref &ref, - const napi_threadsafe_function &tsfn) -{ - enabledNotificationCallbackInfo_.env = env; - enabledNotificationCallbackInfo_.ref = ref; - enabledNotificationCallbackInfo_.tsfn = tsfn; -} - void SubscriberInstance::SetDisturbDateCallbackInfo(const napi_env &env, const napi_ref &ref) { disturbDateCallbackInfo_.env = env; disturbDateCallbackInfo_.ref = ref; } -void SubscriberInstance::SetDisturbDateCallbackInfo(const napi_env &env, const napi_ref &ref, - const napi_threadsafe_function &tsfn) -{ - disturbDateCallbackInfo_.env = env; - disturbDateCallbackInfo_.ref = ref; - disturbDateCallbackInfo_.tsfn = tsfn; -} - void SubscriberInstance::SetDisturbChangedCallbackInfo(const napi_env &env, const napi_ref &ref) { disturbChangedCallbackInfo_.env = env; disturbChangedCallbackInfo_.ref = ref; } -void SubscriberInstance::SetDisturbChangedCallbackInfo(const napi_env &env, const napi_ref &ref, - const napi_threadsafe_function &tsfn) -{ - disturbChangedCallbackInfo_.env = env; - disturbChangedCallbackInfo_.ref = ref; - disturbChangedCallbackInfo_.tsfn = tsfn; -} - void SubscriberInstance::SetBadgeCallbackInfo(const napi_env &env, const napi_ref &ref) { setBadgeCallbackInfo_.env = env; setBadgeCallbackInfo_.ref = ref; } -void SubscriberInstance::SetBadgeCallbackInfo(const napi_env &env, const napi_ref &ref, - const napi_threadsafe_function &tsfn) -{ - setBadgeCallbackInfo_.env = env; - setBadgeCallbackInfo_.ref = ref; - setBadgeCallbackInfo_.tsfn = tsfn; -} void SubscriberInstance::SetBadgeEnabledCallbackInfo(const napi_env &env, const napi_ref &ref) { @@ -1066,29 +983,12 @@ void SubscriberInstance::SetBadgeEnabledCallbackInfo(const napi_env &env, const setBadgeEnabledCallbackInfo_.ref = ref; } -void SubscriberInstance::SetBadgeEnabledCallbackInfo(const napi_env &env, const napi_ref &ref, - const napi_threadsafe_function &tsfn) -{ - setBadgeEnabledCallbackInfo_.env = env; - setBadgeEnabledCallbackInfo_.ref = ref; - setBadgeEnabledCallbackInfo_.tsfn = tsfn; -} - void SubscriberInstance::SetBatchCancelCallbackInfo(const napi_env &env, const napi_ref &ref) { batchCancelCallbackInfo_.env = env; batchCancelCallbackInfo_.ref = ref; } -void SubscriberInstance::SetBatchCancelCallbackInfo(const napi_env &env, const napi_ref &ref, - const napi_threadsafe_function &tsfn) -{ - batchCancelCallbackInfo_.env = env; - batchCancelCallbackInfo_.ref = ref; - batchCancelCallbackInfo_.tsfn = tsfn; -} - - void SubscriberInstance::SetCallbackInfo(const napi_env &env, const std::string &type, const napi_ref &ref) { if (type == CONSUME) { @@ -1122,41 +1022,6 @@ void SubscriberInstance::SetCallbackInfo(const napi_env &env, const std::string } } - -void SubscriberInstance::SetCallbackInfo(const std::string &type, const napi_env &env, const napi_ref &ref, - const napi_threadsafe_function &tsfn) -{ - if (type == CONSUME) { - SetConsumeCallbackInfo(env, ref, tsfn); - } else if (type == CANCEL) { - SetCancelCallbackInfo(env, ref, tsfn); - } else if (type == UPDATE) { - SetUpdateCallbackInfo(env, ref, tsfn); - } else if (type == CONNECTED) { - SetSubscribeCallbackInfo(env, ref, tsfn); - } else if (type == DIS_CONNECTED) { - SetUnsubscribeCallbackInfo(env, ref, tsfn); - } else if (type == DIE) { - SetDieCallbackInfo(env, ref, tsfn); - } else if (type == DISTURB_MODE_CHANGE) { - SetDisturbModeCallbackInfo(env, ref, tsfn); - } else if (type == DISTURB_DATE_CHANGE) { - SetDisturbDateCallbackInfo(env, ref, tsfn); - } else if (type == DISTURB_CHANGED) { - SetDisturbChangedCallbackInfo(env, ref, tsfn); - } else if (type == ENABLE_NOTIFICATION_CHANGED) { - SetEnabledNotificationCallbackInfo(env, ref, tsfn); - } else if (type == BADGE_CHANGED) { - SetBadgeCallbackInfo(env, ref, tsfn); - } else if (type == BADGE_ENABLED_CHANGED) { - SetBadgeEnabledCallbackInfo(env, ref, tsfn); - } else if (type == BATCH_CANCEL) { - SetBatchCancelCallbackInfo(env, ref, tsfn); - } else { - ANS_LOGW("type is error"); - } -} - bool HasNotificationSubscriber(const napi_env &env, const napi_value &value, SubscriberInstancesInfo &subscriberInfo) { std::lock_guard lock(mutex_); @@ -1247,6 +1112,7 @@ napi_value GetNotificationSubscriber( napi_threadsafe_function tsfn = nullptr; napi_create_threadsafe_function(env, nullptr, nullptr, resourceName, 0, 1, subscriberInfo.ref, ThreadFinished, nullptr, ThreadSafeCommon, &tsfn); + subscriberInfo.subscriber->SetThreadSafeFunction(tsfn); // onConsume?:(data: SubscribeCallbackData) => void NAPI_CALL(env, napi_has_named_property(env, value, "onConsume", &hasProperty)); @@ -1261,7 +1127,7 @@ napi_value GetNotificationSubscriber( return nullptr; } napi_create_reference(env, nOnConsumed, 1, &result); - subscriberInfo.subscriber->SetCallbackInfo(CONSUME, env, result, tsfn); + subscriberInfo.subscriber->SetCallbackInfo(env, CONSUME, result); } // onCancel?:(data: SubscribeCallbackData) => void NAPI_CALL(env, napi_has_named_property(env, value, "onCancel", &hasProperty)); @@ -1276,7 +1142,7 @@ napi_value GetNotificationSubscriber( return nullptr; } napi_create_reference(env, nOnCanceled, 1, &result); - subscriberInfo.subscriber->SetCallbackInfo(CANCEL, env, result, tsfn); + subscriberInfo.subscriber->SetCallbackInfo(env, CANCEL, result); } // onUpdate?:(data: NotificationSortingMap) => void NAPI_CALL(env, napi_has_named_property(env, value, "onUpdate", &hasProperty)); @@ -1291,7 +1157,7 @@ napi_value GetNotificationSubscriber( return nullptr; } napi_create_reference(env, nOnUpdate, 1, &result); - subscriberInfo.subscriber->SetCallbackInfo(UPDATE, env, result, tsfn); + subscriberInfo.subscriber->SetCallbackInfo(env, UPDATE, result); } // onConnect?:() => void NAPI_CALL(env, napi_has_named_property(env, value, "onConnect", &hasProperty)); @@ -1306,7 +1172,7 @@ napi_value GetNotificationSubscriber( return nullptr; } napi_create_reference(env, nOnConnected, 1, &result); - subscriberInfo.subscriber->SetCallbackInfo(CONNECTED, env, result, tsfn); + subscriberInfo.subscriber->SetCallbackInfo(env, CONNECTED, result); } // onDisconnect?:() => void NAPI_CALL(env, napi_has_named_property(env, value, "onDisconnect", &hasProperty)); @@ -1321,7 +1187,7 @@ napi_value GetNotificationSubscriber( return nullptr; } napi_create_reference(env, nOnDisConnect, 1, &result); - subscriberInfo.subscriber->SetCallbackInfo(DIS_CONNECTED, env, result, tsfn); + subscriberInfo.subscriber->SetCallbackInfo(env, DIS_CONNECTED, result); } // onDestroy?:() => void NAPI_CALL(env, napi_has_named_property(env, value, "onDestroy", &hasProperty)); @@ -1336,7 +1202,7 @@ napi_value GetNotificationSubscriber( return nullptr; } napi_create_reference(env, nOnDied, 1, &result); - subscriberInfo.subscriber->SetCallbackInfo(DIE, env, result, tsfn); + subscriberInfo.subscriber->SetCallbackInfo(env, DIE, result); } // onDisturbModeChange?:(mode: notification.DoNotDisturbMode) => void NAPI_CALL(env, napi_has_named_property(env, value, "onDisturbModeChange", &hasProperty)); @@ -1367,7 +1233,7 @@ napi_value GetNotificationSubscriber( return nullptr; } napi_create_reference(env, nOnDisturbDateChanged, 1, &result); - subscriberInfo.subscriber->SetCallbackInfo(DISTURB_DATE_CHANGE, env, result, tsfn); + subscriberInfo.subscriber->SetCallbackInfo(env, DISTURB_DATE_CHANGE, result); } // onDoNotDisturbChanged?:(mode: notificationManager.DoNotDisturbDate) => void @@ -1383,7 +1249,7 @@ napi_value GetNotificationSubscriber( return nullptr; } napi_create_reference(env, nOnDoNotDisturbChanged, 1, &result); - subscriberInfo.subscriber->SetCallbackInfo(DISTURB_CHANGED, env, result, tsfn); + subscriberInfo.subscriber->SetCallbackInfo(env, DISTURB_CHANGED, result); } // onEnabledNotificationChanged?:(data: notification.EnabledNotificationCallbackData) => void @@ -1399,7 +1265,7 @@ napi_value GetNotificationSubscriber( return nullptr; } napi_create_reference(env, nOnEnabledNotificationChanged, 1, &result); - subscriberInfo.subscriber->SetCallbackInfo(ENABLE_NOTIFICATION_CHANGED, env, result, tsfn); + subscriberInfo.subscriber->SetCallbackInfo(env, ENABLE_NOTIFICATION_CHANGED, result); } // onBadgeChanged?:(data: BadgeNumberCallbackData) => void @@ -1415,7 +1281,7 @@ napi_value GetNotificationSubscriber( return nullptr; } napi_create_reference(env, nOnBadgeChanged, 1, &result); - subscriberInfo.subscriber->SetCallbackInfo(BADGE_CHANGED, env, result, tsfn); + subscriberInfo.subscriber->SetCallbackInfo(env, BADGE_CHANGED, result); } // onBadgeEnabledChanged?:(data: EnabledNotificationCallbackData) => void @@ -1431,7 +1297,7 @@ napi_value GetNotificationSubscriber( return nullptr; } napi_create_reference(env, nOnBadgeEnabledChanged, 1, &result); - subscriberInfo.subscriber->SetCallbackInfo(BADGE_ENABLED_CHANGED, env, result, tsfn); + subscriberInfo.subscriber->SetCallbackInfo(env, BADGE_ENABLED_CHANGED, result); } // onBatchCancel?:(data: Array) => void @@ -1447,7 +1313,7 @@ napi_value GetNotificationSubscriber( return nullptr; } napi_create_reference(env, onBatchCancel, 1, &result); - subscriberInfo.subscriber->SetCallbackInfo(BATCH_CANCEL, env, result, tsfn); + subscriberInfo.subscriber->SetCallbackInfo(env, BATCH_CANCEL, result); } return Common::NapiGetNull(env); diff --git a/frameworks/js/napi/src/subscribe/napi_subscribe.cpp b/frameworks/js/napi/src/subscribe/napi_subscribe.cpp index f1075db91..ef7d3910e 100644 --- a/frameworks/js/napi/src/subscribe/napi_subscribe.cpp +++ b/frameworks/js/napi/src/subscribe/napi_subscribe.cpp @@ -18,6 +18,8 @@ #include "ans_inner_errors.h" #include "subscribe.h" #include "unsubscribe.h" +#include +#include namespace OHOS { namespace NotificationNapi { @@ -58,18 +60,16 @@ napi_value NapiSubscribe(napi_env env, napi_callback_info info) if (asynccallbackinfo) { if (asynccallbackinfo->subscriberInfo.hasSubscribeInfo) { ANS_LOGI("Subscribe with NotificationSubscribeInfo"); - OHOS::Notification::NotificationSubscribeInfo subscribeInfo; - subscribeInfo.AddAppNames(asynccallbackinfo->subscriberInfo.bundleNames); - subscribeInfo.AddAppUserId(asynccallbackinfo->subscriberInfo.userId); - subscribeInfo.AddDeviceType(asynccallbackinfo->subscriberInfo.deviceType); + sptr subscribeInfo = + new (std::nothrow) OHOS::Notification::NotificationSubscribeInfo(); + subscribeInfo->AddAppNames(asynccallbackinfo->subscriberInfo.bundleNames); + subscribeInfo->AddAppUserId(asynccallbackinfo->subscriberInfo.userId); + subscribeInfo->AddDeviceType(asynccallbackinfo->subscriberInfo.deviceType); asynccallbackinfo->info.errorCode = - NotificationHelper::SubscribeNotification(*(asynccallbackinfo->objectInfo), subscribeInfo); + NotificationHelper::SubscribeNotification(asynccallbackinfo->objectInfo, subscribeInfo); } else { asynccallbackinfo->info.errorCode = - NotificationHelper::SubscribeNotification(*(asynccallbackinfo->objectInfo)); - } - if (asynccallbackinfo->info.errorCode == ERR_OK) { - DelDeletingSubscriber(asynccallbackinfo->objectInfo); + NotificationHelper::SubscribeNotification(asynccallbackinfo->objectInfo); } } }, @@ -142,10 +142,7 @@ napi_value NapiSubscribeSelf(napi_env env, napi_callback_info info) auto asynccallbackinfo = reinterpret_cast(data); if (asynccallbackinfo) { asynccallbackinfo->info.errorCode = - NotificationHelper::SubscribeNotificationSelf(*(asynccallbackinfo->objectInfo)); - if (asynccallbackinfo->info.errorCode == ERR_OK) { - DelDeletingSubscriber(asynccallbackinfo->objectInfo); - } + NotificationHelper::SubscribeNotificationSelf(asynccallbackinfo->objectInfo); } }, [](napi_env env, napi_status status, void *data) { @@ -219,7 +216,7 @@ napi_value NapiUnsubscribe(napi_env env, napi_callback_info info) bool ret = AddDeletingSubscriber(asynccallbackinfo->objectInfo); if (ret) { asynccallbackinfo->info.errorCode = - NotificationHelper::UnSubscribeNotification(*(asynccallbackinfo->objectInfo)); + NotificationHelper::UnSubscribeNotification(asynccallbackinfo->objectInfo); if (asynccallbackinfo->info.errorCode != ERR_OK) { DelDeletingSubscriber(asynccallbackinfo->objectInfo); } diff --git a/interfaces/inner_api/notification_helper.h b/interfaces/inner_api/notification_helper.h index acf94f806..da1170016 100644 --- a/interfaces/inner_api/notification_helper.h +++ b/interfaces/inner_api/notification_helper.h @@ -28,6 +28,7 @@ #include "notification_subscriber.h" #include "notification_local_live_view_subscriber.h" #include "want_params.h" +#include namespace OHOS { namespace Notification { @@ -355,26 +356,57 @@ public: * notification. To subscribe to notifications published only by specified sources, for example, * notifications from certain applications, * call the {SubscribeNotification(NotificationSubscriber, NotificationSubscribeInfo)} method. - * + * @deprecated This function is deprecated, + * use 'SubscribeNotification(const std::shared_ptr &subscriber)'. * @param subscriber Indicates the {NotificationSubscriber} to receive notifications. * This parameter must be specified. * @return Returns unsubscribe notification result. */ static ErrCode SubscribeNotification(const NotificationSubscriber &subscriber); + /** + * @brief Subscribes to notifications from all applications. This method can be called only by applications + * with required system permissions. + * @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. + * + * @param subscriber Indicates the {NotificationSubscriber} to receive notifications. + * This parameter must be specified. + * @return Returns unsubscribe notification result. + */ + static ErrCode SubscribeNotification(const std::shared_ptr &subscriber); + /** * @brief Subscribes to notifications from the appliaction self. * @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. - * + * @deprecated This function is deprecated, + * use 'SubscribeNotificationSelf(const std::shared_ptr &subscriber)'. * @param subscriber Indicates the {NotificationSubscriber} to receive notifications. * This parameter must be specified. * @return Returns unsubscribe notification result. */ static ErrCode SubscribeNotificationSelf(const NotificationSubscriber &subscriber); + /** + * @brief Subscribes to notifications from the appliaction self. + * @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. + * + * @param subscriber Indicates the {NotificationSubscriber} to receive notifications. + * This parameter must be specified. + * @return Returns unsubscribe notification result. + */ + static ErrCode SubscribeNotificationSelf(const std::shared_ptr &subscriber); + /** * @brief Subscribes to all notifications based on the filtering criteria. This method can be called only * by applications with required system permissions. @@ -385,7 +417,9 @@ public: * 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. - * + * @deprecated This function is deprecated, + * use 'SubscribeNotification(const std::shared_ptr &subscriber, + * const sptr &subscribeInfo)'. * @param subscriber Indicates the subscribers to receive notifications. This parameter must be specified. * For details, see {NotificationSubscriber}. * @param subscribeInfo Indicates the filters for specified notification sources, including application name, @@ -395,6 +429,26 @@ public: static ErrCode SubscribeNotification( const NotificationSubscriber &subscriber, const NotificationSubscribeInfo &subscribeInfo); + /** + * @brief Subscribes to all notifications based on the filtering criteria. This method can be called only + * by applications with required system permissions. + * @note After {subscribeInfo} is specified, a subscriber receives only the notifications that + * meet the filter criteria specified by {subscribeInfo}. + * 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. + * + * @param subscriber Indicates the subscribers to receive notifications. This parameter must be specified. + * For details, see {NotificationSubscriber}. + * @param subscribeInfo Indicates the filters for specified notification sources, including application name, + * user ID, or device name. This parameter is optional. + * @return Returns subscribe notification result. + */ + static ErrCode SubscribeNotification(const std::shared_ptr &subscriber, + const sptr &subscribeInfo); + /** * @brief Subscribes the localLiveView button click. This method can be called only * by applications with required system permissions. @@ -419,18 +473,38 @@ public: * To unsubscribe from notifications published only by specified sources, for example, * notifications from certain applications, call the * {UnSubscribeNotification(NotificationSubscriber, NotificationSubscribeInfo)} method. - * + * @deprecated This function is deprecated, + * use 'UnSubscribeNotification(const std::shared_ptr &subscriber)'. * @param subscriber Indicates the {NotificationSubscriber} to receive notifications. * This parameter must be specified. * @return Returns unsubscribe notification result. */ static ErrCode UnSubscribeNotification(NotificationSubscriber &subscriber); + /** + * @brief Unsubscribes from all notifications. This method can be called only by applications with required + * system permissions. + * @note Generally, you subscribe to a notification by calling the + * {SubscribeNotification(NotificationSubscriber)} method. If you do not want your application + * to receive a notification any longer, unsubscribe from that notification using this method. + * You can unsubscribe from only those notifications that your application has subscribed to. + * To unsubscribe from notifications published only by specified sources, for example, + * notifications from certain applications, call the + * {UnSubscribeNotification(NotificationSubscriber, NotificationSubscribeInfo)} method. + * + * @param subscriber Indicates the {NotificationSubscriber} to receive notifications. + * This parameter must be specified. + * @return Returns unsubscribe notification result. + */ + static ErrCode UnSubscribeNotification(const std::shared_ptr &subscriber); + /** * @brief Unsubscribes from all notifications based on the filtering criteria. This method can be called * only by applications with required system permissions. * @note A subscriber will no longer receive the notifications from specified notification sources. - * + * @deprecated This function is deprecated, + * use 'UnSubscribeNotification(const std::shared_ptr &subscriber, + * const sptr &subscribeInfo)'. * @param subscriber Indicates the {NotificationSubscriber} to receive notifications. * This parameter must be specified. * @param subscribeInfo Indicates the filters for , including application name, @@ -439,6 +513,20 @@ public: */ static ErrCode UnSubscribeNotification(NotificationSubscriber &subscriber, NotificationSubscribeInfo subscribeInfo); + /** + * @brief Unsubscribes from all notifications based on the filtering criteria. This method can be called + * only by applications with required system permissions. + * @note A subscriber will no longer receive the notifications from specified notification sources. + * + * @param subscriber Indicates the {NotificationSubscriber} to receive notifications. + * This parameter must be specified. + * @param subscribeInfo Indicates the filters for , including application name, + * user ID, or device name. This parameter is optional. + * @return Returns unsubscribe notification result. + */ + static ErrCode UnSubscribeNotification(const std::shared_ptr &subscriber, + const sptr &subscribeInfo); + /** * @brief Trigger the local live view after the button has been clicked. * @note Your application must have platform signature to use this method. diff --git a/interfaces/inner_api/notification_subscriber.h b/interfaces/inner_api/notification_subscriber.h index 988cfe497..63310b4d2 100644 --- a/interfaces/inner_api/notification_subscriber.h +++ b/interfaces/inner_api/notification_subscriber.h @@ -24,7 +24,7 @@ namespace OHOS { namespace Notification { -class NotificationSubscriber { +class NotificationSubscriber : public std::enable_shared_from_this { public: NotificationSubscriber(); diff --git a/services/ans/test/unittest/advanced_notification_service_branch_test.cpp b/services/ans/test/unittest/advanced_notification_service_branch_test.cpp index da98eac95..ff07401ed 100644 --- a/services/ans/test/unittest/advanced_notification_service_branch_test.cpp +++ b/services/ans/test/unittest/advanced_notification_service_branch_test.cpp @@ -25,6 +25,7 @@ #include "ans_const_define.h" #include "ans_inner_errors.h" #include "ans_log_wrapper.h" +#include "ans_subscriber_listener.h" #include "ans_ut_constant.h" #include "iremote_object.h" #include "want_agent_info.h" @@ -82,7 +83,6 @@ void AnsBranchTest::SetUp() advancedNotificationService_ = new (std::nothrow) AdvancedNotificationService(); IPCSkeleton::SetCallingTokenID(NATIVE_TOKEN); IPCSkeleton::SetCallingUid(SYSTEM_APP_UID); - NotificationPreferences::GetInstance()->ClearNotificationInRestoreFactorySettings(); advancedNotificationService_->CancelAll(0); MockGetTokenTypeFlag(Security::AccessToken::ATokenTypeEnum::TOKEN_NATIVE); MockIsSystemApp(true); diff --git a/tools/test/unittest/dump/notification_shell_command_dump_test.cpp b/tools/test/unittest/dump/notification_shell_command_dump_test.cpp index 76db6405c..c7e9b2fca 100644 --- a/tools/test/unittest/dump/notification_shell_command_dump_test.cpp +++ b/tools/test/unittest/dump/notification_shell_command_dump_test.cpp @@ -167,7 +167,6 @@ void AnmManagerDumpTest::MakeMockObjects() // set the mock proxy auto ansNotificationPtr = DelayedSingleton::GetInstance(); - ansNotificationPtr->ansManagerProxy_ = proxyPtr_; } /** -- Gitee From 6c8d468f0bc81ab1e71e610d9ff5954c5ba172c0 Mon Sep 17 00:00:00 2001 From: Ricky Date: Thu, 12 Dec 2024 20:05:57 +0800 Subject: [PATCH 148/167] fix crash, for multiple update template in different thread Signed-off-by: Ricky Change-Id: I81904b4ff424f29e0032ac4dc9fee86d2cc605c3 --- services/ans/src/advanced_notification_live_view_service.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/services/ans/src/advanced_notification_live_view_service.cpp b/services/ans/src/advanced_notification_live_view_service.cpp index 638f28c32..5032e2b0d 100644 --- a/services/ans/src/advanced_notification_live_view_service.cpp +++ b/services/ans/src/advanced_notification_live_view_service.cpp @@ -698,7 +698,7 @@ void AdvancedNotificationService::UpdateRecordByOwner( auto downloadTemplate = record->notification->GetNotificationRequest().GetTemplate(); auto content = record->notification->GetNotificationRequest().GetContent(); auto wantAgent = record->notification->GetNotificationRequest().GetWantAgent(); - record->request = oldRecord->request; + record->request = new (std::nothrow) NotificationRequest(*(oldRecord->request)); if (wantAgent != nullptr) { record->request->SetWantAgent(wantAgent); } -- Gitee From 4820c92aad615db3dcedc6f131a7355ef0ea6c1d Mon Sep 17 00:00:00 2001 From: z30053788 Date: Sat, 16 Nov 2024 11:41:22 +0800 Subject: [PATCH 149/167] cherry pick 3cbc728 from https://gitee.com/wufarong1/notification_distributed_notification_service/pulls/2432 TDD Signed-off-by: z30053788 Change-Id: Icaecb70df7d7f6be34018d0561c729d4a3b33a21 --- .../notification_subscriber_manager_branch_test.cpp | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/services/ans/test/unittest/notification_subscriber_manager_branch_test/notification_subscriber_manager_branch_test.cpp b/services/ans/test/unittest/notification_subscriber_manager_branch_test/notification_subscriber_manager_branch_test.cpp index 125426ef7..60d5f440a 100644 --- a/services/ans/test/unittest/notification_subscriber_manager_branch_test/notification_subscriber_manager_branch_test.cpp +++ b/services/ans/test/unittest/notification_subscriber_manager_branch_test/notification_subscriber_manager_branch_test.cpp @@ -535,7 +535,7 @@ HWTEST_F(NotificationSubscriberManagerBranchTest, AdvancedNotificationService_02 { IPCSkeleton::SetCallingUid(SYSTEM_APP_UID); - sptr bundleOption = nullptr; + sptr bundleOption = new NotificationBundleOption(); bool enabled = true; MockGetTokenTypeFlag(ATokenTypeEnum::TOKEN_HAP); @@ -654,7 +654,7 @@ HWTEST_F(NotificationSubscriberManagerBranchTest, AdvancedNotificationService_02 HWTEST_F(NotificationSubscriberManagerBranchTest, AdvancedNotificationService_02900, Function | SmallTest | Level1) { std::string deviceId = ""; - sptr bundleOption = nullptr; + sptr bundleOption = new NotificationBundleOption(); bool enabled = true; MockGetTokenTypeFlag(ATokenTypeEnum::TOKEN_HAP); @@ -1142,7 +1142,7 @@ HWTEST_F(NotificationSubscriberManagerBranchTest, AdvancedNotificationService_05 */ HWTEST_F(NotificationSubscriberManagerBranchTest, AdvancedNotificationService_05900, Function | SmallTest | Level1) { - sptr bundleOption = nullptr; + sptr bundleOption = new NotificationBundleOption(); NotificationConstant::SlotType slotType = NotificationConstant::SlotType::OTHER; bool enabled = true; bool isForceControl = false; -- Gitee From 3c3f61eb9421935a6439ecc0be5092f7ab0ed95b Mon Sep 17 00:00:00 2001 From: wufarong Date: Mon, 16 Dec 2024 17:36:43 +0800 Subject: [PATCH 150/167] =?UTF-8?q?ANS=20UT=E4=BF=AE=E5=A4=8D?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: wufarong Change-Id: Id87e5d55450989a896e821538ac463df1905883d --- .../unittest/notification_helper_test.cpp | 2 +- .../unittest/notification_sorting_test.cpp | 7 +- .../src/manager/ans_manager_proxy_bundle.cpp | 797 ++++++++++++++++++ services/ans/src/notification_preferences.cpp | 1 + ...notification_preferences_database_test.cpp | 2 +- 5 files changed, 806 insertions(+), 3 deletions(-) create mode 100644 frameworks/core/src/manager/ans_manager_proxy_bundle.cpp diff --git a/frameworks/ans/test/unittest/notification_helper_test.cpp b/frameworks/ans/test/unittest/notification_helper_test.cpp index cee8e7676..5ff4d9193 100644 --- a/frameworks/ans/test/unittest/notification_helper_test.cpp +++ b/frameworks/ans/test/unittest/notification_helper_test.cpp @@ -962,7 +962,7 @@ HWTEST_F(NotificationHelperTest, RemoveNotifications_00002, Function | SmallTest int32_t userId = 10; NotificationHelper notificationHelper; ErrCode ret = notificationHelper.RemoveNotifications(userId); - EXPECT_EQ(ret, (int)ERR_OK); + EXPECT_EQ(ret, (int)ERR_ANS_PERMISSION_DENIED); } /** diff --git a/frameworks/ans/test/unittest/notification_sorting_test.cpp b/frameworks/ans/test/unittest/notification_sorting_test.cpp index fc295f5bd..e28edabc1 100644 --- a/frameworks/ans/test/unittest/notification_sorting_test.cpp +++ b/frameworks/ans/test/unittest/notification_sorting_test.cpp @@ -71,11 +71,13 @@ HWTEST_F(NotificationSortingTest, Marshalling_00002, Function | SmallTest | Leve HWTEST_F(NotificationSortingTest, Unmarshalling_001, Function | SmallTest | Level1) { NotificationSorting sorting; + sptr slot = new (std::nothrow) NotificationSlot(); + sorting.SetSlot(slot); bool unmarshalling = true; Parcel parcel; std::shared_ptr result = std::make_shared(sorting); - + result->Marshalling(parcel); if (nullptr != result) { if (nullptr == result->Unmarshalling(parcel)) { unmarshalling = false; @@ -94,7 +96,10 @@ HWTEST_F(NotificationSortingTest, ReadFromParcel_00001, Function | SmallTest | L { Parcel parcel; NotificationSorting sorting; + sptr slot = new (std::nothrow) NotificationSlot(); + sorting.SetSlot(slot); auto rrc = std::make_shared(sorting); + rrc->Marshalling(parcel); EXPECT_EQ(rrc->ReadFromParcel(parcel), true); } diff --git a/frameworks/core/src/manager/ans_manager_proxy_bundle.cpp b/frameworks/core/src/manager/ans_manager_proxy_bundle.cpp new file mode 100644 index 000000000..4aae443ab --- /dev/null +++ b/frameworks/core/src/manager/ans_manager_proxy_bundle.cpp @@ -0,0 +1,797 @@ +/* + * Copyright (c) 2024 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include + +#include "ans_const_define.h" +#include "ans_inner_errors.h" +#include "ans_log_wrapper.h" +#include "ans_subscriber_local_live_view_interface.h" +#include "distributed_notification_service_ipc_interface_code.h" +#include "message_option.h" +#include "message_parcel.h" +#include "parcel.h" +#include "ans_manager_proxy.h" + +namespace OHOS { +namespace Notification { +ErrCode AnsManagerProxy::SetNotificationBadgeNum(int32_t num) +{ + MessageParcel data; + if (!data.WriteInterfaceToken(AnsManagerProxy::GetDescriptor())) { + ANS_LOGE("[SetNotificationBadgeNum] fail: write interface token failed."); + return ERR_ANS_PARCELABLE_FAILED; + } + + if (!data.WriteInt32(num)) { + ANS_LOGE("[SetNotificationBadgeNum] fail: write num failed."); + return ERR_ANS_PARCELABLE_FAILED; + } + + MessageParcel reply; + MessageOption option = {MessageOption::TF_SYNC}; + ErrCode result = InnerTransact(NotificationInterfaceCode::SET_NOTIFICATION_BADGE_NUM, option, data, reply); + if (result != ERR_OK) { + ANS_LOGE("[SetNotificationBadgeNum] fail: transact ErrCode=%{public}d", result); + return ERR_ANS_TRANSACT_FAILED; + } + + if (!reply.ReadInt32(result)) { + ANS_LOGE("[SetNotificationBadgeNum] fail: read result failed."); + return ERR_ANS_PARCELABLE_FAILED; + } + + return result; +} + +ErrCode AnsManagerProxy::GetBundleImportance(int32_t &importance) +{ + MessageParcel data; + if (!data.WriteInterfaceToken(AnsManagerProxy::GetDescriptor())) { + ANS_LOGE("[GetBundleImportance] fail: write interface token failed."); + return ERR_ANS_PARCELABLE_FAILED; + } + + MessageParcel reply; + MessageOption option = {MessageOption::TF_SYNC}; + ErrCode result = InnerTransact(NotificationInterfaceCode::GET_BUNDLE_IMPORTANCE, option, data, reply); + if (result != ERR_OK) { + ANS_LOGE("[GetBundleImportance] fail: transact ErrCode=%{public}d", result); + return ERR_ANS_TRANSACT_FAILED; + } + + if (!reply.ReadInt32(result)) { + ANS_LOGE("[GetBundleImportance] fail: read result failed."); + return ERR_ANS_PARCELABLE_FAILED; + } + + if (!reply.ReadInt32(importance)) { + ANS_LOGE("[GetBundleImportance] fail: read importance failed."); + return ERR_ANS_PARCELABLE_FAILED; + } + + return result; +} + +ErrCode AnsManagerProxy::HasNotificationPolicyAccessPermission(bool &granted) +{ + MessageParcel data; + if (!data.WriteInterfaceToken(AnsManagerProxy::GetDescriptor())) { + ANS_LOGE("[HasNotificationPolicyAccessPermission] fail: write interface token failed."); + return ERR_ANS_PARCELABLE_FAILED; + } + + MessageParcel reply; + MessageOption option = {MessageOption::TF_SYNC}; + ErrCode result = InnerTransact(NotificationInterfaceCode::IS_NOTIFICATION_POLICY_ACCESS_GRANTED, + option, data, reply); + if (result != ERR_OK) { + ANS_LOGE("[HasNotificationPolicyAccessPermission] fail: transact ErrCode=%{public}d", result); + return ERR_ANS_TRANSACT_FAILED; + } + + if (!reply.ReadInt32(result)) { + ANS_LOGE("[HasNotificationPolicyAccessPermission] fail: read result failed."); + return ERR_ANS_PARCELABLE_FAILED; + } + + if (!reply.ReadBool(granted)) { + ANS_LOGE("[HasNotificationPolicyAccessPermission] fail: read granted failed."); + return ERR_ANS_PARCELABLE_FAILED; + } + + return result; +} + +ErrCode AnsManagerProxy::RequestEnableNotification(const std::string &deviceId, + const sptr &callback, + const sptr &callerToken) +{ + ANS_LOGD("enter"); + MessageParcel data; + if (!data.WriteInterfaceToken(AnsManagerProxy::GetDescriptor())) { + ANS_LOGE("[RequestEnableNotification] fail: write interface token failed."); + return ERR_ANS_PARCELABLE_FAILED; + } + + if (!data.WriteString(deviceId)) { + ANS_LOGE("[RequestEnableNotification] fail: write deviceId failed"); + return ERR_ANS_PARCELABLE_FAILED; + } + + if (callback == nullptr || !data.WriteRemoteObject(callback->AsObject())) { + ANS_LOGE("[RequestEnableNotification] fail: write callback failed"); + return ERR_ANS_PARCELABLE_FAILED; + } + + if (!data.WriteBool(callerToken != nullptr)) { + ANS_LOGE("fail: write callerToken failed"); + return ERR_ANS_PARCELABLE_FAILED; + } + if (callerToken != nullptr) { + if (!data.WriteRemoteObject(callerToken)) { + ANS_LOGE("fail: write callerToken failed"); + return ERR_ANS_PARCELABLE_FAILED; + } + } + + MessageParcel reply; + MessageOption option = {MessageOption::TF_SYNC}; + ErrCode result = InnerTransact(NotificationInterfaceCode::REQUEST_ENABLE_NOTIFICATION, option, data, reply); + if (result != ERR_OK) { + ANS_LOGE("[RequestEnableNotification] fail: transact ErrCode=%{public}d", result); + return ERR_ANS_TRANSACT_FAILED; + } + + if (!reply.ReadInt32(result)) { + ANS_LOGE("[RequestEnableNotification] fail: read result failed."); + return ERR_ANS_PARCELABLE_FAILED; + } + return result; +} + +ErrCode AnsManagerProxy::SetNotificationsEnabledForBundle(const std::string &deviceId, bool enabled) +{ + MessageParcel data; + if (!data.WriteInterfaceToken(AnsManagerProxy::GetDescriptor())) { + ANS_LOGE("[SetNotificationsEnabledForBundle] fail: write interface token failed."); + return ERR_ANS_PARCELABLE_FAILED; + } + + if (!data.WriteString(deviceId)) { + ANS_LOGE("[SetNotificationsEnabledForBundle] fail: write deviceId failed"); + return ERR_ANS_PARCELABLE_FAILED; + } + + if (!data.WriteBool(enabled)) { + ANS_LOGE("[SetNotificationsEnabledForBundle] fail: write enabled failed"); + return ERR_ANS_PARCELABLE_FAILED; + } + + MessageParcel reply; + MessageOption option = {MessageOption::TF_SYNC}; + ErrCode result = InnerTransact(NotificationInterfaceCode::SET_NOTIFICATION_ENABLED_FOR_BUNDLE, option, data, reply); + if (result != ERR_OK) { + ANS_LOGE("[SetNotificationsEnabledForBundle] fail: transact ErrCode=%{public}d", result); + return ERR_ANS_TRANSACT_FAILED; + } + + if (!reply.ReadInt32(result)) { + ANS_LOGE("[SetNotificationsEnabledForBundle] fail: read result failed."); + return ERR_ANS_PARCELABLE_FAILED; + } + + return result; +} + +ErrCode AnsManagerProxy::SetNotificationsEnabledForAllBundles(const std::string &deviceId, bool enabled) +{ + MessageParcel data; + if (!data.WriteInterfaceToken(AnsManagerProxy::GetDescriptor())) { + ANS_LOGE("[SetNotificationsEnabledForAllBundles] fail: write interface token failed."); + return ERR_ANS_PARCELABLE_FAILED; + } + + if (!data.WriteString(deviceId)) { + ANS_LOGE("[SetNotificationsEnabledForAllBundles] fail: write deviceId failed"); + return ERR_ANS_PARCELABLE_FAILED; + } + + if (!data.WriteBool(enabled)) { + ANS_LOGE("[SetNotificationsEnabledForAllBundles] fail: write enabled failed"); + return ERR_ANS_PARCELABLE_FAILED; + } + + MessageParcel reply; + MessageOption option = {MessageOption::TF_SYNC}; + ErrCode result = InnerTransact(NotificationInterfaceCode::SET_NOTIFICATION_ENABLED_FOR_ALL_BUNDLE, + option, data, reply); + if (result != ERR_OK) { + ANS_LOGE("[SetNotificationsEnabledForAllBundles] fail: transact ErrCode=%{public}d", result); + return ERR_ANS_TRANSACT_FAILED; + } + + if (!reply.ReadInt32(result)) { + ANS_LOGE("[SetNotificationsEnabledForAllBundles] fail: read result failed."); + return ERR_ANS_PARCELABLE_FAILED; + } + + return result; +} + +ErrCode AnsManagerProxy::SetNotificationsEnabledForSpecialBundle( + const std::string &deviceId, const sptr &bundleOption, bool enabled) +{ + if (bundleOption == nullptr) { + ANS_LOGE("[SetNotificationsEnabledForSpecialBundle] fail: bundleOption is empty."); + return ERR_ANS_INVALID_PARAM; + } + + MessageParcel data; + if (!data.WriteInterfaceToken(AnsManagerProxy::GetDescriptor())) { + ANS_LOGE("[SetNotificationsEnabledForSpecialBundle] fail: write interface token failed."); + return ERR_ANS_PARCELABLE_FAILED; + } + + if (!data.WriteString(deviceId)) { + ANS_LOGE("[SetNotificationsEnabledForSpecialBundle] fail: write deviceId failed"); + return ERR_ANS_PARCELABLE_FAILED; + } + + if (!data.WriteParcelable(bundleOption)) { + ANS_LOGE("[SetNotificationsEnabledForSpecialBundle] fail: write bundleOption failed"); + return ERR_ANS_PARCELABLE_FAILED; + } + + if (!data.WriteBool(enabled)) { + ANS_LOGE("[SetNotificationsEnabledForSpecialBundle] fail: write enabled failed"); + return ERR_ANS_PARCELABLE_FAILED; + } + + MessageParcel reply; + MessageOption option = {MessageOption::TF_SYNC}; + ErrCode result = InnerTransact(NotificationInterfaceCode::SET_NOTIFICATION_ENABLED_FOR_SPECIAL_BUNDLE, + option, data, reply); + if (result != ERR_OK) { + ANS_LOGE("[SetNotificationsEnabledForSpecialBundle] fail: transact ErrCode=%{public}d", result); + return ERR_ANS_TRANSACT_FAILED; + } + + if (!reply.ReadInt32(result)) { + ANS_LOGE("[SetNotificationsEnabledForSpecialBundle] fail: read result failed."); + return ERR_ANS_PARCELABLE_FAILED; + } + + return result; +} + +ErrCode AnsManagerProxy::SetShowBadgeEnabledForBundle(const sptr &bundleOption, bool enabled) +{ + if (bundleOption == nullptr) { + ANS_LOGE("[SetShowBadgeEnabledForBundle] fail: bundle is empty."); + return ERR_ANS_INVALID_PARAM; + } + + MessageParcel data; + if (!data.WriteInterfaceToken(AnsManagerProxy::GetDescriptor())) { + ANS_LOGE("[SetShowBadgeEnabledForBundle] fail: write interface token failed."); + return ERR_ANS_PARCELABLE_FAILED; + } + + if (!data.WriteParcelable(bundleOption)) { + ANS_LOGE("[SetShowBadgeEnabledForBundle] fail:: write bundle failed"); + return ERR_ANS_PARCELABLE_FAILED; + } + + if (!data.WriteBool(enabled)) { + ANS_LOGE("[SetShowBadgeEnabledForBundle] fail:: write enabled failed"); + return ERR_ANS_PARCELABLE_FAILED; + } + + MessageParcel reply; + MessageOption option = {MessageOption::TF_SYNC}; + ErrCode result = InnerTransact(NotificationInterfaceCode::SET_SHOW_BADGE_ENABLED_FOR_BUNDLE, option, data, reply); + if (result != ERR_OK) { + ANS_LOGE("[SetShowBadgeEnabledForBundle] fail: transact ErrCode=%{public}d", result); + return ERR_ANS_TRANSACT_FAILED; + } + + if (!reply.ReadInt32(result)) { + ANS_LOGE("[SetShowBadgeEnabledForBundle] fail: read result failed."); + return ERR_ANS_PARCELABLE_FAILED; + } + + return result; +} + +ErrCode AnsManagerProxy::GetShowBadgeEnabledForBundle(const sptr &bundleOption, bool &enabled) +{ + if (bundleOption == nullptr) { + ANS_LOGE("[GetShowBadgeEnabledForBundle] fail: bundle is empty."); + return ERR_ANS_INVALID_PARAM; + } + + MessageParcel data; + if (!data.WriteInterfaceToken(AnsManagerProxy::GetDescriptor())) { + ANS_LOGE("[GetShowBadgeEnabledForBundle] fail: write interface token failed."); + return ERR_ANS_PARCELABLE_FAILED; + } + + if (!data.WriteParcelable(bundleOption)) { + ANS_LOGE("[GetShowBadgeEnabledForBundle] fail:: write bundle failed"); + return ERR_ANS_PARCELABLE_FAILED; + } + + MessageParcel reply; + MessageOption option = {MessageOption::TF_SYNC}; + ErrCode result = InnerTransact(NotificationInterfaceCode::GET_SHOW_BADGE_ENABLED_FOR_BUNDLE, option, data, reply); + if (result != ERR_OK) { + ANS_LOGE("[GetShowBadgeEnabledForBundle] fail: transact ErrCode=%{public}d", result); + return ERR_ANS_TRANSACT_FAILED; + } + + if (!reply.ReadInt32(result)) { + ANS_LOGE("[GetShowBadgeEnabledForBundle] fail: read result failed."); + return ERR_ANS_PARCELABLE_FAILED; + } + + if (!reply.ReadBool(enabled)) { + ANS_LOGE("[GetShowBadgeEnabledForBundle] fail: read enabled failed."); + return ERR_ANS_PARCELABLE_FAILED; + } + + return result; +} + +ErrCode AnsManagerProxy::GetShowBadgeEnabled(bool &enabled) +{ + MessageParcel data; + if (!data.WriteInterfaceToken(AnsManagerProxy::GetDescriptor())) { + ANS_LOGE("[GetShowBadgeEnabled] fail: write interface token failed."); + return ERR_ANS_PARCELABLE_FAILED; + } + + MessageParcel reply; + MessageOption option = {MessageOption::TF_SYNC}; + ErrCode result = InnerTransact(NotificationInterfaceCode::GET_SHOW_BADGE_ENABLED, option, data, reply); + if (result != ERR_OK) { + ANS_LOGE("[GetShowBadgeEnabled] fail: transact ErrCode=%{public}d", result); + return ERR_ANS_TRANSACT_FAILED; + } + + if (!reply.ReadInt32(result)) { + ANS_LOGE("[GetShowBadgeEnabled] fail: read result failed."); + return ERR_ANS_PARCELABLE_FAILED; + } + + if (!reply.ReadBool(enabled)) { + ANS_LOGE("[GetShowBadgeEnabled] fail: read enabled failed."); + return ERR_ANS_PARCELABLE_FAILED; + } + + return result; +} + +ErrCode AnsManagerProxy::IsAllowedNotify(bool &allowed) +{ + MessageParcel data; + if (!data.WriteInterfaceToken(AnsManagerProxy::GetDescriptor())) { + ANS_LOGE("[IsAllowedNotify] fail: write interface token failed."); + return ERR_ANS_PARCELABLE_FAILED; + } + + MessageParcel reply; + MessageOption option = {MessageOption::TF_SYNC}; + ErrCode result = InnerTransact(NotificationInterfaceCode::IS_ALLOWED_NOTIFY, option, data, reply); + if (result != ERR_OK) { + ANS_LOGE("[IsAllowedNotify] fail: transact ErrCode=%{public}d", result); + return ERR_ANS_TRANSACT_FAILED; + } + + if (!reply.ReadInt32(result)) { + ANS_LOGE("[IsAllowedNotify] fail: read result failed."); + return ERR_ANS_PARCELABLE_FAILED; + } + + if (!reply.ReadBool(allowed)) { + ANS_LOGE("[IsAllowedNotify] fail: read allowed failed."); + return ERR_ANS_PARCELABLE_FAILED; + } + + return result; +} + +ErrCode AnsManagerProxy::IsAllowedNotifySelf(bool &allowed) +{ + MessageParcel data; + if (!data.WriteInterfaceToken(AnsManagerProxy::GetDescriptor())) { + ANS_LOGE("[IsAllowedNotifySelf] fail: write interface token failed."); + return ERR_ANS_PARCELABLE_FAILED; + } + + MessageParcel reply; + MessageOption option = {MessageOption::TF_SYNC}; + ErrCode result = InnerTransact(NotificationInterfaceCode::IS_ALLOWED_NOTIFY_SELF, option, data, reply); + if (result != ERR_OK) { + ANS_LOGE("[IsAllowedNotifySelf] fail: transact ErrCode=%{public}d", result); + return ERR_ANS_TRANSACT_FAILED; + } + + if (!reply.ReadInt32(result)) { + ANS_LOGE("[IsAllowedNotifySelf] fail: read result failed."); + return ERR_ANS_PARCELABLE_FAILED; + } + + if (!reply.ReadBool(allowed)) { + ANS_LOGE("[IsAllowedNotifySelf] fail: read allowed failed."); + return ERR_ANS_PARCELABLE_FAILED; + } + + return result; +} + +ErrCode AnsManagerProxy::CanPopEnableNotificationDialog(const sptr &callback, + bool &canPop, std::string &bundleName) +{ + MessageParcel data; + if (!data.WriteInterfaceToken(AnsManagerProxy::GetDescriptor())) { + ANS_LOGE("[CanPopEnableNotificationDialog] fail: write interface token failed."); + return ERR_ANS_PARCELABLE_FAILED; + } + + if (callback == nullptr || !data.WriteRemoteObject(callback->AsObject())) { + ANS_LOGE("[CanPopEnableNotificationDialog] fail: write callback failed"); + return ERR_ANS_PARCELABLE_FAILED; + } + + MessageParcel reply; + MessageOption option = {MessageOption::TF_SYNC}; + ErrCode result = InnerTransact(NotificationInterfaceCode::CAN_POP_ENABLE_NOTIFICATION_DIALOG, + option, data, reply); + if (result != ERR_OK) { + ANS_LOGE("[CanPopEnableNotificationDialog] fail: transact ErrCode=%{public}d", result); + return ERR_ANS_TRANSACT_FAILED; + } + + if (!reply.ReadInt32(result)) { + ANS_LOGE("[CanPopEnableNotificationDialog] fail: read result failed."); + return ERR_ANS_PARCELABLE_FAILED; + } + + if (!reply.ReadBool(canPop)) { + ANS_LOGE("[CanPopEnableNotificationDialog] fail: read canPop failed."); + return ERR_ANS_PARCELABLE_FAILED; + } + if (!reply.ReadString(bundleName)) { + ANS_LOGE("[CanPopEnableNotificationDialog] fail: read bundleName failed."); + return ERR_ANS_PARCELABLE_FAILED; + } + + return result; +} + +ErrCode AnsManagerProxy::RemoveEnableNotificationDialog() +{ + MessageParcel data; + if (!data.WriteInterfaceToken(AnsManagerProxy::GetDescriptor())) { + ANS_LOGE("[CanPopEnableNotificationDialog] fail: write interface token failed."); + return ERR_ANS_PARCELABLE_FAILED; + } + MessageParcel reply; + MessageOption option = {MessageOption::TF_SYNC}; + ErrCode result = InnerTransact(NotificationInterfaceCode::REMOVE_ENABLE_NOTIFICATION_DIALOG, + option, data, reply); + if (result != ERR_OK) { + ANS_LOGE("[RemoveEnableNotificationDialog] fail: transact ErrCode=%{public}d", result); + return ERR_ANS_TRANSACT_FAILED; + } + if (!reply.ReadInt32(result)) { + ANS_LOGE("[CanPopEnableNotificationDialog] fail: read result failed."); + return ERR_ANS_PARCELABLE_FAILED; + } + return result; +} + +ErrCode AnsManagerProxy::IsSpecialBundleAllowedNotify(const sptr &bundleOption, bool &allowed) +{ + if (bundleOption == nullptr) { + ANS_LOGE("[IsSpecialBundleAllowedNotify] fail: bundle is empty."); + return ERR_ANS_INVALID_PARAM; + } + + MessageParcel data; + if (!data.WriteInterfaceToken(AnsManagerProxy::GetDescriptor())) { + ANS_LOGE("[IsSpecialBundleAllowedNotify] fail: write interface token failed."); + return ERR_ANS_PARCELABLE_FAILED; + } + + if (!data.WriteParcelable(bundleOption)) { + ANS_LOGE("[IsSpecialBundleAllowedNotify] fail: write bundle failed"); + return ERR_ANS_PARCELABLE_FAILED; + } + + MessageParcel reply; + MessageOption option = {MessageOption::TF_SYNC}; + ErrCode result = InnerTransact(NotificationInterfaceCode::IS_SPECIAL_BUNDLE_ALLOWED_NOTIFY, option, data, reply); + if (result != ERR_OK) { + ANS_LOGE("[IsSpecialBundleAllowedNotify] fail: transact ErrCode=%{public}d", result); + return ERR_ANS_TRANSACT_FAILED; + } + + if (!reply.ReadInt32(result)) { + ANS_LOGE("[IsSpecialBundleAllowedNotify] fail: read result failed."); + return ERR_ANS_PARCELABLE_FAILED; + } + + if (!reply.ReadBool(allowed)) { + ANS_LOGE("[IsSpecialBundleAllowedNotify] fail: read allowed error."); + return ERR_ANS_PARCELABLE_FAILED; + } + + return result; +} + +ErrCode AnsManagerProxy::IsSpecialUserAllowedNotify(const int32_t &userId, bool &allowed) +{ + MessageParcel data; + if (!data.WriteInterfaceToken(AnsManagerProxy::GetDescriptor())) { + ANS_LOGE("[IsSpecialUserAllowedNotify] fail: write interface token failed."); + return ERR_ANS_PARCELABLE_FAILED; + } + + if (!data.WriteInt32(userId)) { + ANS_LOGE("[IsSpecialUserAllowedNotify] fail: write userId failed"); + return ERR_ANS_PARCELABLE_FAILED; + } + + MessageParcel reply; + MessageOption option = {MessageOption::TF_SYNC}; + ErrCode result = InnerTransact(NotificationInterfaceCode::IS_SPECIAL_USER_ALLOWED_NOTIFY, option, data, reply); + if (result != ERR_OK) { + ANS_LOGE("[IsSpecialBundleAllowedNotify] fail: transact ErrCode=%{public}d", result); + return ERR_ANS_TRANSACT_FAILED; + } + + if (!reply.ReadInt32(result)) { + ANS_LOGE("[IsSpecialBundleAllowedNotify] fail: read result failed."); + return ERR_ANS_PARCELABLE_FAILED; + } + + if (!reply.ReadBool(allowed)) { + ANS_LOGE("[IsSpecialBundleAllowedNotify] fail: read allowed failed."); + return ERR_ANS_PARCELABLE_FAILED; + } + + return result; +} + +ErrCode AnsManagerProxy::SetNotificationsEnabledByUser(const int32_t &userId, bool enabled) +{ + MessageParcel data; + if (!data.WriteInterfaceToken(AnsManagerProxy::GetDescriptor())) { + ANS_LOGE("[SetNotificationsEnabledByUser] fail: write interface token failed."); + return ERR_ANS_PARCELABLE_FAILED; + } + + if (!data.WriteInt32(userId)) { + ANS_LOGE("[SetNotificationsEnabledByUser] fail: write userId failed"); + return ERR_ANS_PARCELABLE_FAILED; + } + + if (!data.WriteBool(enabled)) { + ANS_LOGE("[SetNotificationsEnabledByUser] fail: write enabled failed"); + return ERR_ANS_PARCELABLE_FAILED; + } + + MessageParcel reply; + MessageOption option = {MessageOption::TF_SYNC}; + ErrCode result = InnerTransact(NotificationInterfaceCode::SET_NOTIFICATION_ENABLED_BY_USER, option, data, reply); + if (result != ERR_OK) { + ANS_LOGE("[SetNotificationsEnabledByUser] fail: transact ErrCode=%{public}d", result); + return ERR_ANS_TRANSACT_FAILED; + } + + if (!reply.ReadInt32(result)) { + ANS_LOGE("[SetNotificationsEnabledByUser] fail: read result failed."); + return ERR_ANS_PARCELABLE_FAILED; + } + + return result; +} + +ErrCode AnsManagerProxy::SetSyncNotificationEnabledWithoutApp(const int32_t userId, const bool enabled) +{ + MessageParcel data; + if (!data.WriteInterfaceToken(AnsManagerProxy::GetDescriptor())) { + ANS_LOGE("[SetSyncNotificationEnabledWithoutApp] fail: write interface token failed."); + return ERR_ANS_PARCELABLE_FAILED; + } + + if (!data.WriteInt32(userId)) { + ANS_LOGE("[SetSyncNotificationEnabledWithoutApp] fail:: write userId failed."); + return ERR_ANS_PARCELABLE_FAILED; + } + + if (!data.WriteBool(enabled)) { + ANS_LOGE("[SetSyncNotificationEnabledWithoutApp] fail: write enabled failed"); + return ERR_ANS_PARCELABLE_FAILED; + } + + MessageParcel reply; + MessageOption option = {MessageOption::TF_SYNC}; + ErrCode result = InnerTransact(NotificationInterfaceCode::SET_SYNC_NOTIFICATION_ENABLED_WITHOUT_APP, + option, data, reply); + if (result != ERR_OK) { + ANS_LOGE("[SetSyncNotificationEnabledWithoutApp] fail: transact ErrCode=%{public}d", result); + return ERR_ANS_TRANSACT_FAILED; + } + + if (!reply.ReadInt32(result)) { + ANS_LOGE("[SetSyncNotificationEnabledWithoutApp] fail: read result failed."); + return ERR_ANS_PARCELABLE_FAILED; + } + + return result; +} + +ErrCode AnsManagerProxy::GetSyncNotificationEnabledWithoutApp(const int32_t userId, bool &enabled) +{ + MessageParcel data; + if (!data.WriteInterfaceToken(AnsManagerProxy::GetDescriptor())) { + ANS_LOGE("[GetSyncNotificationEnabledWithoutApp] fail: write interface token failed."); + return ERR_ANS_PARCELABLE_FAILED; + } + + if (!data.WriteInt32(userId)) { + ANS_LOGE("[GetSyncNotificationEnabledWithoutApp] fail:: write userId failed."); + return ERR_ANS_PARCELABLE_FAILED; + } + + MessageParcel reply; + MessageOption option = {MessageOption::TF_SYNC}; + ErrCode result = InnerTransact(NotificationInterfaceCode::GET_SYNC_NOTIFICATION_ENABLED_WITHOUT_APP, + option, data, reply); + if (result != ERR_OK) { + ANS_LOGE("[GetSyncNotificationEnabledWithoutApp] fail: transact ErrCode=%{public}d", result); + return ERR_ANS_TRANSACT_FAILED; + } + + if (!reply.ReadInt32(result)) { + ANS_LOGE("[GetSyncNotificationEnabledWithoutApp] fail: read result failed."); + return ERR_ANS_PARCELABLE_FAILED; + } + + if (!reply.ReadBool(enabled)) { + ANS_LOGE("[GetSyncNotificationEnabledWithoutApp] fail: read enable failed."); + return ERR_ANS_PARCELABLE_FAILED; + } + + return result; +} + +ErrCode AnsManagerProxy::SetBadgeNumber(int32_t badgeNumber, int32_t instanceKey) +{ + MessageParcel data; + if (!data.WriteInterfaceToken(AnsManagerProxy::GetDescriptor())) { + ANS_LOGE("[SetBadgeNumber] fail: write interface token failed."); + return ERR_ANS_PARCELABLE_FAILED; + } + + if (!data.WriteInt32(badgeNumber)) { + ANS_LOGE("[SetBadgeNumber] fail:: write badgeNumber failed."); + return ERR_ANS_PARCELABLE_FAILED; + } + + if (!data.WriteInt32(instanceKey)) { + ANS_LOGE("[SetBadgeNumber] fail:: write instancekey failed."); + return ERR_ANS_PARCELABLE_FAILED; + } + + MessageParcel reply; + MessageOption option = {MessageOption::TF_SYNC}; + ErrCode result = InnerTransact(NotificationInterfaceCode::SET_BADGE_NUMBER, option, data, reply); + if (result != ERR_OK) { + ANS_LOGE("[SetBadgeNumber] fail: transact ErrCode=%{public}d", result); + return ERR_ANS_TRANSACT_FAILED; + } + + if (!reply.ReadInt32(result)) { + ANS_LOGE("[SetBadgeNumber] fail: read result failed."); + return ERR_ANS_PARCELABLE_FAILED; + } + + return result; +} + +ErrCode AnsManagerProxy::SetBadgeNumberByBundle(const sptr &bundleOption, int32_t badgeNumber) +{ + if (bundleOption == nullptr) { + ANS_LOGE("Bundle is empty."); + return ERR_ANS_INVALID_PARAM; + } + MessageParcel data; + if (!data.WriteInterfaceToken(AnsManagerProxy::GetDescriptor())) { + ANS_LOGE("Write interface token failed."); + return ERR_ANS_PARCELABLE_FAILED; + } + if (!data.WriteParcelable(bundleOption)) { + ANS_LOGE("Write bundle option failed."); + return ERR_ANS_PARCELABLE_FAILED; + } + if (!data.WriteInt32(badgeNumber)) { + ANS_LOGE("Write badge number failed."); + return ERR_ANS_PARCELABLE_FAILED; + } + + MessageParcel reply; + MessageOption option = { MessageOption::TF_SYNC }; + ErrCode result = InnerTransact(NotificationInterfaceCode::SET_BADGE_NUMBER_BY_BUNDLE, option, data, reply); + if (result != ERR_OK) { + ANS_LOGE("Transact error code is: %{public}d", result); + return ERR_ANS_TRANSACT_FAILED; + } + if (!reply.ReadInt32(result)) { + ANS_LOGE("Read result failed."); + return ERR_ANS_PARCELABLE_FAILED; + } + return result; +} + +ErrCode AnsManagerProxy::GetAllNotificationEnabledBundles(std::vector &bundleOption) +{ + ANS_LOGD("Called."); + MessageParcel data; + int32_t vectorSize = 0; + if (!data.WriteInterfaceToken(AnsManagerProxy::GetDescriptor())) { + ANS_LOGE("Write interface token failed."); + return ERR_ANS_PARCELABLE_FAILED; + } + + MessageParcel reply; + MessageOption option = { MessageOption::TF_SYNC }; + ErrCode result = InnerTransact(NotificationInterfaceCode::GET_ALL_NOTIFICATION_ENABLE_STATUS, option, data, reply); + if (result != ERR_OK) { + ANS_LOGE("Fail: transact ErrCode=%{public}d", result); + return ERR_ANS_TRANSACT_FAILED; + } + + if (!reply.ReadInt32(result)) { + ANS_LOGE("Fail: read result failed."); + return ERR_ANS_PARCELABLE_FAILED; + } + + if (!reply.ReadInt32(vectorSize)) { + ANS_LOGE("Fail: read vectorSize failed."); + return ERR_ANS_PARCELABLE_FAILED; + } + + if (vectorSize > MAX_STATUS_VECTOR_NUM) { + ANS_LOGE("Bundle status vector is over size"); + return ERR_ANS_PARCELABLE_FAILED; + } + + for (auto i = 0; i < vectorSize; i++) { + sptr obj = reply.ReadParcelable(); + if (obj == nullptr) { + ANS_LOGE("The obj of Bundle status vector is nullptr."); + return ERR_ANS_PARCELABLE_FAILED; + } + bundleOption.emplace_back(*obj); + } + + return result; +} +} // namespace Notification +} // namespace OHOS diff --git a/services/ans/src/notification_preferences.cpp b/services/ans/src/notification_preferences.cpp index 790532eec..ec3993cd8 100644 --- a/services/ans/src/notification_preferences.cpp +++ b/services/ans/src/notification_preferences.cpp @@ -859,6 +859,7 @@ ErrCode NotificationPreferences::CheckSlotForRemoveSlot(const sptrGenerateBundleLablel(bundleInfo, deviceType); - ASSERT_EQ(ret, "enabledNotificationDistributed-name-1-test"); + ASSERT_EQ(ret, "enabledDistributedNotification-name-1-test"); } /** -- Gitee From 93dd7f845bad42dd484bddb33fe36c936e7cd610 Mon Sep 17 00:00:00 2001 From: wufarong Date: Tue, 17 Dec 2024 14:55:10 +0800 Subject: [PATCH 151/167] =?UTF-8?q?=E4=BF=AE=E5=A4=8DRemoveNotifications?= =?UTF-8?q?=5F00002=E5=A4=B1=E8=B4=A5?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: wufarong Change-Id: I631aa38bef9db0c9926abec62f796f520567d17e --- frameworks/ans/test/unittest/notification_helper_test.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/frameworks/ans/test/unittest/notification_helper_test.cpp b/frameworks/ans/test/unittest/notification_helper_test.cpp index 5ff4d9193..cee8e7676 100644 --- a/frameworks/ans/test/unittest/notification_helper_test.cpp +++ b/frameworks/ans/test/unittest/notification_helper_test.cpp @@ -962,7 +962,7 @@ HWTEST_F(NotificationHelperTest, RemoveNotifications_00002, Function | SmallTest int32_t userId = 10; NotificationHelper notificationHelper; ErrCode ret = notificationHelper.RemoveNotifications(userId); - EXPECT_EQ(ret, (int)ERR_ANS_PERMISSION_DENIED); + EXPECT_EQ(ret, (int)ERR_OK); } /** -- Gitee From 967707c22865eb2e48d85480a38450b34ffff24a Mon Sep 17 00:00:00 2001 From: markYao Date: Tue, 17 Dec 2024 15:24:42 +0800 Subject: [PATCH 152/167] =?UTF-8?q?pushCallBacks=5F=E4=BD=BF=E7=94=A8?= =?UTF-8?q?=E6=97=B6=E5=A2=9E=E5=8A=A0=E9=94=81=E4=BF=9D=E6=8A=A4?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: markYao --- services/ans/src/advanced_notification_service.cpp | 11 ++++++++--- 1 file changed, 8 insertions(+), 3 deletions(-) diff --git a/services/ans/src/advanced_notification_service.cpp b/services/ans/src/advanced_notification_service.cpp index 891e6858c..45bd3673a 100644 --- a/services/ans/src/advanced_notification_service.cpp +++ b/services/ans/src/advanced_notification_service.cpp @@ -2014,8 +2014,10 @@ ErrCode AdvancedNotificationService::RegisterPushCallback( return ERROR_INTERNAL_ERROR; } } - - pushCallBacks_.insert_or_assign(slotType, pushCallBack); + { + std::lock_guard lock(pushMutex_); + pushCallBacks_.insert_or_assign(slotType, pushCallBack); + } ANS_LOGD("insert pushCallBack, slot type %{public}d", slotType); notificationCheckRequest->SetUid(uid); checkRequests_.insert_or_assign(slotType, notificationCheckRequest); @@ -2048,7 +2050,10 @@ ErrCode AdvancedNotificationService::UnregisterPushCallback() return ERR_INVALID_OPERATION; } - pushCallBacks_.clear(); + { + std::lock_guard lock(pushMutex_); + pushCallBacks_.clear(); + } ANS_LOGD("end"); return ERR_OK; -- Gitee From a2de176fe2f43b060e47083f02f27db2f108e9d8 Mon Sep 17 00:00:00 2001 From: z30053788 Date: Sat, 7 Dec 2024 18:39:59 +0800 Subject: [PATCH 153/167] cherry pick ab4f78f from https://gitee.com/zhaobaoxin1/notification_distributed_notification_service/pulls/2485 update Signed-off-by: z30053788 Change-Id: I6dbe704e63ca2963cd993bcfb45b9ac9984fc6c1 --- services/ans/include/system_event_observer.h | 1 + services/ans/src/system_event_observer.cpp | 17 ++++++++++++++++- 2 files changed, 17 insertions(+), 1 deletion(-) diff --git a/services/ans/include/system_event_observer.h b/services/ans/include/system_event_observer.h index 132200d76..e072e87b9 100644 --- a/services/ans/include/system_event_observer.h +++ b/services/ans/include/system_event_observer.h @@ -44,6 +44,7 @@ private: void OnReceiveEvent(const EventFwk::CommonEventData &data); void OnReceiveEventInner(const EventFwk::CommonEventData &data); sptr GetBundleOption(AAFwk::Want want); + sptr GetBundleOptionDataCleared(AAFwk::Want want); void OnBundleUpdateEventInner(const EventFwk::CommonEventData &data); void OnBundleAddEventInner(const EventFwk::CommonEventData &data); diff --git a/services/ans/src/system_event_observer.cpp b/services/ans/src/system_event_observer.cpp index 2ca95752e..c45b548dd 100644 --- a/services/ans/src/system_event_observer.cpp +++ b/services/ans/src/system_event_observer.cpp @@ -73,6 +73,21 @@ sptr SystemEventObserver::GetBundleOption(AAFwk::Want return bundleOption; } +sptr SystemEventObserver::GetBundleOptionDataCleared(AAFwk::Want want) +{ + auto element = want.GetElement(); + std::string bundleName = element.GetBundleName(); + int32_t appIndex = want.GetIntParam("appIndex", -1); + int32_t uid = want.GetIntParam("ohos.aafwk.param.targetUid", -1); + sptr bundleOption = new (std::nothrow) NotificationBundleOption(bundleName, uid); + bundleOption->SetAppIndex(appIndex); + if (bundleOption == nullptr) { + ANS_LOGE("Failed to create bundleOption."); + return nullptr; + } + return bundleOption; +} + void SystemEventObserver::OnReceiveEvent(const EventFwk::CommonEventData &data) { auto want = data.GetWant(); @@ -115,7 +130,7 @@ void SystemEventObserver::OnReceiveEvent(const EventFwk::CommonEventData &data) } } else if (action == EventFwk::CommonEventSupport::COMMON_EVENT_PACKAGE_DATA_CLEARED) { if (callbacks_.onBundleDataCleared != nullptr) { - sptr bundleOption = GetBundleOption(want); + sptr bundleOption = GetBundleOptionDataCleared(want); if (bundleOption != nullptr) { callbacks_.onBundleDataCleared(bundleOption); } -- Gitee From 1bf07a084cbe22d017571d46111450955e0895fc Mon Sep 17 00:00:00 2001 From: markYao Date: Wed, 25 Dec 2024 15:26:23 +0800 Subject: [PATCH 154/167] Revert "cherry pick ac0aaaa from https://gitee.com/wangsen1994/notification_distributed_notification_service/pulls/2478" This reverts commit a8e167f04bfa6466c37602f750da1ce0f27b561e. Signed-off-by: markYao --- .../include/advanced_notification_service.h | 14 +- .../notification_clone_bundle_service.h | 4 +- .../notification_clone_disturb_service.h | 4 +- .../ans/include/notification_clone_manager.h | 2 - .../ans/include/notification_clone_template.h | 2 - .../ans/include/notification_preferences.h | 13 -- .../notification_preferences_database.h | 15 -- .../advanced_notification_publish_service.cpp | 2 +- .../ans/src/advanced_notification_utils.cpp | 127 +------------- .../notification_clone_bundle_service.cpp | 37 ++-- .../notification_clone_disturb_service.cpp | 40 ++--- .../src/clone/notification_clone_manager.cpp | 40 +---- services/ans/src/notification_preferences.cpp | 79 +-------- .../src/notification_preferences_database.cpp | 163 ------------------ services/ans/src/system_event_observer.cpp | 3 - 15 files changed, 55 insertions(+), 490 deletions(-) diff --git a/services/ans/include/advanced_notification_service.h b/services/ans/include/advanced_notification_service.h index 1d10526bc..4e7890bf7 100644 --- a/services/ans/include/advanced_notification_service.h +++ b/services/ans/include/advanced_notification_service.h @@ -48,7 +48,6 @@ #ifdef NOTIFICATION_SMART_REMINDER_SUPPORTED #include "reminder_swing_decision_center.h" #endif -#include "notification_clone_bundle_info.h" namespace OHOS { namespace Notification { @@ -562,7 +561,7 @@ public: */ ErrCode CanPopEnableNotificationDialog(const sptr &callback, bool &canPop, std::string &bundleName) override; - + /** * @brief remove enable notification dialog. * @@ -1164,8 +1163,6 @@ public: int32_t OnBackup(MessageParcel& data, MessageParcel& reply); int32_t OnRestore(MessageParcel& data, MessageParcel& reply); - - void UpdateCloneBundleInfo(const NotificationCloneBundleInfo cloneBundleInfo); protected: /** * @brief Query whether there is a agent relationship between the two apps. @@ -1385,7 +1382,7 @@ private: const std::vector extraInfoKeys, sptr &newRequest); ErrCode IsAllowedRemoveSlot(const sptr &bundleOption, const NotificationConstant::SlotType &slotType); - void HandleBadgeEnabledChanged(const sptr &bundleOption, bool enabled); + void HandleBadgeEnabledChanged(const sptr &bundleOption, bool &enabled); ErrCode CheckBundleOptionValid(sptr &bundleOption); bool IsNeedNotifyConsumed(const sptr &request); ErrCode AddRecordToMemory(const std::shared_ptr &record, @@ -1434,13 +1431,6 @@ private: bool IsSystemUser(int32_t userId); ErrCode UpdateFlowCtrl(const std::shared_ptr &record); ErrCode PublishFlowControlInner(const std::shared_ptr &record); - ErrCode SetEnabledForBundleSlotInner(const sptr &bundleOption, - const sptr &bundle, - const NotificationConstant::SlotType &slotType, bool enabled, bool isForceControl); - ErrCode AddSlotThenPublishEvent( - const sptr &slot, - const sptr &bundle, - bool enabled, bool isForceControl); private: static sptr instance_; static std::mutex instanceMutex_; diff --git a/services/ans/include/notification_clone_bundle_service.h b/services/ans/include/notification_clone_bundle_service.h index f1a6b6ab8..7e30c4664 100644 --- a/services/ans/include/notification_clone_bundle_service.h +++ b/services/ans/include/notification_clone_bundle_service.h @@ -30,8 +30,10 @@ public: ~NotificationCloneBundle() override; static std::shared_ptr GetInstance(); ErrCode OnBackup(nlohmann::json &jsonObject) override; - void OnRestoreStart(const std::string bundleName, int32_t appIndex, int32_t userId, int32_t uid) override; void OnRestore(const nlohmann::json &jsonObject) override; + void OnBundleDataAdd(const sptr &bundleOption); + void OnBundleDataUpdate(const sptr &bundleOption); + void HandleBundleEvent(const std::string bundleName, int32_t appIndex, int32_t uid); void OnUserSwitch(int32_t userId) override; private: std::vector bundlesInfo_; diff --git a/services/ans/include/notification_clone_disturb_service.h b/services/ans/include/notification_clone_disturb_service.h index 47dfa98a3..ab8a3939c 100644 --- a/services/ans/include/notification_clone_disturb_service.h +++ b/services/ans/include/notification_clone_disturb_service.h @@ -31,7 +31,9 @@ public: static std::shared_ptr GetInstance(); ErrCode OnBackup(nlohmann::json &jsonObject) override; void OnRestore(const nlohmann::json &jsonObject) override; - void OnRestoreStart(const std::string bundleName, int32_t appIndex, int32_t userId, int32_t uid) override; + void OnBundleDataAdd(const sptr &bundleOption); + void OnBundleDataUpdate(const sptr &bundleOption); + void HandlerBundleEvent(const std::string bundleName, int32_t appIndex, int32_t uid); int32_t GetBundleUid(const std::string bundleName, int32_t userId, int32_t appIndex); void GetProfileUid(int32_t userId, std::map& uidMap, std::vector trustList, std::vector& exitBunldleList, diff --git a/services/ans/include/notification_clone_manager.h b/services/ans/include/notification_clone_manager.h index a93a9846f..1328e8fd9 100644 --- a/services/ans/include/notification_clone_manager.h +++ b/services/ans/include/notification_clone_manager.h @@ -21,7 +21,6 @@ #include "unique_fd.h" #include "iremote_proxy.h" -#include "common_event_data.h" #include "notification_clone_template.h" namespace OHOS { namespace Notification { @@ -33,7 +32,6 @@ public: int32_t OnBackup(MessageParcel& data, MessageParcel& reply); int32_t OnRestore(MessageParcel& data, MessageParcel& reply); void OnUserSwitch(int32_t userId); - void OnRestoreStart(EventFwk::Want want); private: NotificationCloneManager(); diff --git a/services/ans/include/notification_clone_template.h b/services/ans/include/notification_clone_template.h index 02a486acd..b9baa7472 100644 --- a/services/ans/include/notification_clone_template.h +++ b/services/ans/include/notification_clone_template.h @@ -29,8 +29,6 @@ public: virtual ErrCode OnBackup(nlohmann::json &jsonObject) = 0; virtual void OnRestore(const nlohmann::json &jsonObject) = 0; virtual void OnUserSwitch(int32_t userId) = 0; - virtual void OnRestoreStart(const std::string bundleName, int32_t appIndex, - int32_t userId, int32_t uid) = 0; }; } // namespace Notification } // namespace OHOS diff --git a/services/ans/include/notification_preferences.h b/services/ans/include/notification_preferences.h index 793a50030..9665a5885 100644 --- a/services/ans/include/notification_preferences.h +++ b/services/ans/include/notification_preferences.h @@ -386,19 +386,6 @@ public: void GetAllCLoneBundlesInfo(int32_t userId, std::vector &cloneBundles); void UpdateCloneBundleInfo(int32_t userId, const NotificationCloneBundleInfo& cloneBundleInfo); bool IsNotificationSlotFlagsExists(const sptr &bundleOption); - bool DelCloneProfileInfo(const int32_t &userId, const sptr& info); - bool UpdateBatchCloneProfileInfo(const int32_t &userId, - const std::vector>& profileInfo); - void GetAllCloneProfileInfo(const int32_t &userId, - std::vector>& profilesInfo); - void GetAllCloneBundleInfo(const int32_t &userId, std::vector& cloneBundleInfo); - bool UpdateBatchCloneBundleInfo(const int32_t &userId, - const std::vector& cloneBundleInfo); - bool DelCloneBundleInfo(const int32_t &userId, const NotificationCloneBundleInfo& cloneBundleInfo); - bool DelBatchCloneBundleInfo(const int32_t &userId, - const std::vector& cloneBundleInfo); - bool DelBatchCloneProfileInfo(const int32_t &userId, - const std::vector>& profileInfo); private: bool GetBundleInfo(NotificationPreferencesInfo &preferencesInfo, diff --git a/services/ans/include/notification_preferences_database.h b/services/ans/include/notification_preferences_database.h index b6c6eeca1..00b49d035 100644 --- a/services/ans/include/notification_preferences_database.h +++ b/services/ans/include/notification_preferences_database.h @@ -247,19 +247,6 @@ public: bool UpdateBundleSlotToDisturbeDB(int32_t userId, const std::string &bundleName, const int32_t &bundleUid, const std::vector> &slots); bool IsNotificationSlotFlagsExists(const sptr &bundleOption); - bool DelCloneProfileInfo(const int32_t &userId, const sptr& info); - bool UpdateBatchCloneProfileInfo(const int32_t &userId, - const std::vector>& profileInfo); - void GetAllCloneProfileInfo(const int32_t &userId, - std::vector>& profilesInfo); - void GetAllCloneBundleInfo(const int32_t &userId, std::vector& cloneBundleInfo); - bool UpdateBatchCloneBundleInfo(const int32_t &userId, - const std::vector& cloneBundleInfo); - bool DelCloneBundleInfo(const int32_t &userId, const NotificationCloneBundleInfo& cloneBundleInfo); - bool DelBatchCloneProfileInfo(const int32_t &userId, - const std::vector>& profileInfo); - bool DelBatchCloneBundleInfo(const int32_t &userId, - const std::vector& cloneBundleInfo); private: bool CheckRdbStore(); @@ -333,8 +320,6 @@ private: void ParseSlotAuthorizedStatus(sptr &slot, const std::string &value) const; void ParseSlotAuthHitnCnt(sptr &slot, const std::string &value) const; void ParseSlotReminderMode(sptr &slot, const std::string &value) const; - bool UpdateCloneToDisturbeDB(const int32_t &userId, - const std::unordered_map values); std::string GenerateBundleLablel(const NotificationPreferencesInfo::BundleInfo &bundleInfo) const; std::string GenerateBundleLablel(const NotificationPreferencesInfo::BundleInfo &bundleInfo, diff --git a/services/ans/src/advanced_notification_publish_service.cpp b/services/ans/src/advanced_notification_publish_service.cpp index cc0298c08..35e5ea9ca 100644 --- a/services/ans/src/advanced_notification_publish_service.cpp +++ b/services/ans/src/advanced_notification_publish_service.cpp @@ -781,7 +781,7 @@ ErrCode AdvancedNotificationService::SetShowBadgeEnabledForBundle( } void AdvancedNotificationService::HandleBadgeEnabledChanged( - const sptr &bundleOption, bool enabled) + const sptr &bundleOption, bool &enabled) { sptr enabledData = new (std::nothrow) EnabledNotificationCallbackData(bundleOption->GetBundleName(), bundleOption->GetUid(), enabled); diff --git a/services/ans/src/advanced_notification_utils.cpp b/services/ans/src/advanced_notification_utils.cpp index a71dbdb17..22f669fc1 100644 --- a/services/ans/src/advanced_notification_utils.cpp +++ b/services/ans/src/advanced_notification_utils.cpp @@ -48,6 +48,8 @@ #include "advanced_notification_inline.cpp" #include "notification_analytics_util.h" +#include "notification_clone_disturb_service.h" +#include "notification_clone_bundle_service.h" #define CHECK_BUNDLE_OPTION_IS_INVALID(option) \ if (option == nullptr || option->GetBundleName().empty()) { \ @@ -588,8 +590,10 @@ void AdvancedNotificationService::OnBundleDataAdd(const sptrOnBundleDataAdd(bundleOption); }; + NotificationCloneDisturb::GetInstance()->OnBundleDataAdd(bundleOption); notificationSvrQueue_ != nullptr ? notificationSvrQueue_->submit(bundleInstall) : bundleInstall(); } @@ -617,6 +621,7 @@ void AdvancedNotificationService::OnBundleDataUpdate(const sptrOnBundleDataUpdate(bundleOption); notificationSvrQueue_ != nullptr ? notificationSvrQueue_->submit(bundleUpdate) : bundleUpdate(); } @@ -2077,127 +2082,5 @@ ErrCode AdvancedNotificationService::OnRecoverLiveView( BatchCancelTimer(timerIds); return ERR_OK; } - -ErrCode AdvancedNotificationService::SetEnabledForBundleSlotInner( - const sptr &bundleOption, - const sptr &bundle, - const NotificationConstant::SlotType &slotType, bool enabled, bool isForceControl) -{ - sptr slot; - ErrCode result = NotificationPreferences::GetInstance()->GetNotificationSlot(bundle, slotType, slot); - if (result == ERR_ANS_PREFERENCES_NOTIFICATION_SLOT_TYPE_NOT_EXIST || - result == ERR_ANS_PREFERENCES_NOTIFICATION_BUNDLE_NOT_EXIST) { - slot = new (std::nothrow) NotificationSlot(slotType); - if (slot == nullptr) { - ANS_LOGE("Failed to create NotificationSlot ptr."); - return ERR_ANS_NO_MEMORY; - } - GenerateSlotReminderMode(slot, bundleOption); - return AddSlotThenPublishEvent(slot, bundle, enabled, isForceControl); - } else if ((result == ERR_OK) && (slot != nullptr)) { - if (slot->GetEnable() == enabled && slot->GetForceControl() == isForceControl) { - slot->SetAuthorizedStatus(NotificationSlot::AuthorizedStatus::AUTHORIZED); - std::vector> slots; - slots.push_back(slot); - return NotificationPreferences::GetInstance()->AddNotificationSlots(bundle, slots); - } - NotificationPreferences::GetInstance()->RemoveNotificationSlot(bundle, slotType); - return AddSlotThenPublishEvent(slot, bundle, enabled, isForceControl); - } - ANS_LOGE("Set enable slot: GetNotificationSlot failed"); - return result; -} - -ErrCode AdvancedNotificationService::AddSlotThenPublishEvent( - const sptr &slot, - const sptr &bundle, - bool enabled, bool isForceControl) -{ - bool allowed = false; - ErrCode result = NotificationPreferences::GetInstance()->GetNotificationsEnabledForBundle(bundle, allowed); - if (result == ERR_ANS_PREFERENCES_NOTIFICATION_BUNDLE_NOT_EXIST) { - result = ERR_OK; - allowed = CheckApiCompatibility(bundle); - SetDefaultNotificationEnabled(bundle, allowed); - } - - slot->SetEnable(enabled); - slot->SetForceControl(isForceControl); - slot->SetAuthorizedStatus(NotificationSlot::AuthorizedStatus::AUTHORIZED); - std::vector> slots; - slots.push_back(slot); - result = NotificationPreferences::GetInstance()->AddNotificationSlots(bundle, slots); - if (result != ERR_OK) { - ANS_LOGE("Set enable slot: AddNotificationSlot failed"); - return result; - } - - if (!slot->GetEnable()) { - RemoveNotificationBySlot(bundle, slot, NotificationConstant::DISABLE_SLOT_REASON_DELETE); - } else { - if (!slot->GetForceControl() && !allowed) { - RemoveNotificationBySlot(bundle, slot, NotificationConstant::DISABLE_NOTIFICATION_REASON_DELETE); - } - } - - PublishSlotChangeCommonEvent(bundle); - return result; -} - -void AdvancedNotificationService::UpdateCloneBundleInfo(const NotificationCloneBundleInfo cloneBundleInfo) -{ - ANS_LOGI("Event bundle update %{public}s.", cloneBundleInfo.Dump().c_str()); - if (notificationSvrQueue_ == nullptr) { - return; - } - - ffrt::task_handle handler = notificationSvrQueue_->submit_h(std::bind([&, cloneBundleInfo]() { - sptr bundle = new (std::nothrow) NotificationBundleOption( - cloneBundleInfo.GetBundleName(), cloneBundleInfo.GetUid()); - if (bundle == nullptr) { - return; - } - bundle->SetAppIndex(cloneBundleInfo.GetAppIndex()); - if (NotificationPreferences::GetInstance()->SetNotificationsEnabledForBundle(bundle, - cloneBundleInfo.GetEnableNotification()) == ERR_OK) { - SetSlotFlagsTrustlistsAsBundle(bundle); - sptr bundleData = new (std::nothrow) EnabledNotificationCallbackData( - bundle->GetBundleName(), bundle->GetUid(), cloneBundleInfo.GetEnableNotification()); - if (bundleData == nullptr) { - return; - } - NotificationSubscriberManager::GetInstance()->NotifyEnabledNotificationChanged(bundleData); - } else { - ANS_LOGW("Set notification enable failed."); - return; - } - - if (cloneBundleInfo.GetSlotInfo().empty()) { - PublishSlotChangeCommonEvent(bundle); - } - if (NotificationPreferences::GetInstance()->SetNotificationSlotFlagsForBundle(bundle, - cloneBundleInfo.GetSlotFlags()) != ERR_OK) { - ANS_LOGW("Set notification slot failed."); - return; - } - if (UpdateSlotReminderModeBySlotFlags(bundle, cloneBundleInfo.GetSlotFlags()) != ERR_OK) { - ANS_LOGW("Set notification reminder slot failed."); - return; - } - - if (NotificationPreferences::GetInstance()->SetShowBadge(bundle, cloneBundleInfo.GetIsShowBadge()) == ERR_OK) { - HandleBadgeEnabledChanged(bundle, cloneBundleInfo.GetIsShowBadge()); - } else { - ANS_LOGW("Set notification badge failed."); - } - - for (auto& cloneSlot : cloneBundleInfo.GetSlotInfo()) { - if (SetEnabledForBundleSlotInner(bundle, bundle, cloneSlot.slotType_, cloneSlot.enable_, - cloneSlot.isForceControl_) != ERR_OK) { - ANS_LOGW("Set notification slots failed %{public}s.", cloneSlot.Dump().c_str()); - } - } - })); -} } // namespace Notification } // namespace OHOS diff --git a/services/ans/src/clone/notification_clone_bundle_service.cpp b/services/ans/src/clone/notification_clone_bundle_service.cpp index 4dae3d501..3511ce3a0 100644 --- a/services/ans/src/clone/notification_clone_bundle_service.cpp +++ b/services/ans/src/clone/notification_clone_bundle_service.cpp @@ -20,7 +20,6 @@ #include "notification_clone_util.h" #include "notification_clone_bundle_info.h" #include "os_account_manager_helper.h" -#include "advanced_notification_service.h" namespace OHOS { namespace Notification { @@ -76,10 +75,7 @@ void NotificationCloneBundle::OnRestore(const nlohmann::json &jsonObject) int32_t userId = NotificationCloneUtil::GetActiveUserId(); std::unique_lock lock(lock_); - if (!bundlesInfo_.empty()) { - NotificationPreferences::GetInstance()->DelBatchCloneBundleInfo(userId, bundlesInfo_); - bundlesInfo_.clear(); - } + bundlesInfo_.clear(); for (const auto &profile : jsonObject) { NotificationCloneBundleInfo cloneBundleInfo;; cloneBundleInfo.FromJson(profile); @@ -99,32 +95,41 @@ void NotificationCloneBundle::OnRestore(const nlohmann::json &jsonObject) continue; } bundle->SetUid(uid); - AdvancedNotificationService::GetInstance()->UpdateCloneBundleInfo(*bundle); + NotificationPreferences::GetInstance()->UpdateCloneBundleInfo(userId, *bundle); bundle = bundlesInfo_.erase(bundle); } - NotificationPreferences::GetInstance()->UpdateBatchCloneBundleInfo(userId, bundlesInfo_); for (auto bundle = bundlesInfo_.begin(); bundle != bundlesInfo_.end(); bundle++) { ANS_LOGI("Event bundle left %{public}s.", bundle->Dump().c_str()); } ANS_LOGI("Notification bundle list on restore end."); } -void NotificationCloneBundle::OnRestoreStart(const std::string bundleName, int32_t appIndex, - int32_t userId, int32_t uid) +void NotificationCloneBundle::OnBundleDataAdd(const sptr &bundleOption) +{ + HandleBundleEvent(bundleOption->GetBundleName(), bundleOption->GetAppIndex(), bundleOption->GetUid()); +} + +void NotificationCloneBundle::OnBundleDataUpdate(const sptr &bundleOption) { - ANS_LOGI("Handle bundle event %{public}s %{public}d %{public}d %{public}d %{public}zu.", - bundleName.c_str(), appIndex, userId, uid, bundlesInfo_.size()); + HandleBundleEvent(bundleOption->GetBundleName(), bundleOption->GetAppIndex(), bundleOption->GetUid()); +} + +void NotificationCloneBundle::HandleBundleEvent(const std::string bundleName, int32_t appIndex, int32_t uid) +{ + ANS_LOGI("Handle bundle event %{public}s %{public}d %{public}d %{public}zu.", + bundleName.c_str(), appIndex, uid, bundlesInfo_.size()); if (bundlesInfo_.empty()) { return; } + int32_t userId = -1; + OsAccountManagerHelper::GetInstance().GetOsAccountLocalIdFromUid(uid, userId); std::unique_lock lcck(lock_); for (auto bundle = bundlesInfo_.begin(); bundle != bundlesInfo_.end();) { if (bundle->GetBundleName() == bundleName && bundle->GetAppIndex() == appIndex) { bundle->SetUid(uid); - AdvancedNotificationService::GetInstance()->UpdateCloneBundleInfo(*bundle); - NotificationPreferences::GetInstance()->DelCloneBundleInfo(userId, *bundle); + NotificationPreferences::GetInstance()->UpdateCloneBundleInfo(userId, *bundle); bundle = bundlesInfo_.erase(bundle); break; } @@ -140,13 +145,9 @@ void NotificationCloneBundle::OnUserSwitch(int32_t userId) ANS_LOGW("Clone bundle queue is null."); return; } - cloneBundleQueue_->submit_h(std::bind([&, userId]() { + cloneBundleQueue_->submit_h(std::bind([&]() { std::unique_lock lock(lock_); bundlesInfo_.clear(); - NotificationPreferences::GetInstance()->GetAllCloneBundleInfo(userId, bundlesInfo_); - for (auto bundle = bundlesInfo_.begin(); bundle != bundlesInfo_.end(); bundle++) { - ANS_LOGI("Event bundle OnUserSwitch %{public}s.", bundle->Dump().c_str()); - } })); } diff --git a/services/ans/src/clone/notification_clone_disturb_service.cpp b/services/ans/src/clone/notification_clone_disturb_service.cpp index 95939dd84..6ec7c8466 100644 --- a/services/ans/src/clone/notification_clone_disturb_service.cpp +++ b/services/ans/src/clone/notification_clone_disturb_service.cpp @@ -69,11 +69,7 @@ void NotificationCloneDisturb::OnRestore(const nlohmann::json &jsonObject) return; } - int32_t userId = NotificationCloneUtil::GetActiveUserId(); - if (!profiles_.empty()) { - NotificationPreferences::GetInstance()->DelBatchCloneProfileInfo(userId, profiles_); - profiles_.clear(); - } + profiles_.clear(); for (const auto &profile : jsonObject) { sptr item = new (std::nothrow) NotificationDoNotDisturbProfile(); item->FromJson(profile.dump()); @@ -85,7 +81,9 @@ void NotificationCloneDisturb::OnRestore(const nlohmann::json &jsonObject) return; } + int32_t userId = NotificationCloneUtil::GetActiveUserId(); cloneDisturbQueue_->submit_h(std::bind([&, userId]() { + ANS_LOGI("Notification disturb profile ffrt start %{public}zu.", profiles_.size()); int32_t profileId = -1; std::string name; std::map uidMap; @@ -94,7 +92,8 @@ void NotificationCloneDisturb::OnRestore(const nlohmann::json &jsonObject) std::vector notExitBunldleList; name = (*profile)->GetProfileName(); profileId = (*profile)->GetProfileId(); - ANS_LOGI("Disturb %{public}d, %{public}zu.", profileId, (*profile)->GetProfileTrustList().size()); + ANS_LOGI("Notification disturb profile %{public}d, %{public}zu.", profileId, + (*profile)->GetProfileTrustList().size()); GetProfileUid(userId, uidMap, (*profile)->GetProfileTrustList(), exitBunldleList, notExitBunldleList); NotificationPreferences::GetInstance()->UpdateDoNotDisturbProfiles(userId, profileId, name, exitBunldleList); @@ -108,7 +107,6 @@ void NotificationCloneDisturb::OnRestore(const nlohmann::json &jsonObject) profileId = -1; } - NotificationPreferences::GetInstance()->UpdateBatchCloneProfileInfo(userId, profiles_); for (auto profile = profiles_.begin(); profile != profiles_.end(); profile++) { ANS_LOGI("Clone queue left %{public}d %{public}zu.", (*profile)->GetProfileId(), (*profile)->GetProfileTrustList().size()); @@ -141,6 +139,16 @@ void NotificationCloneDisturb::GetProfileUid(int32_t userId, std::map &bundleOption) +{ + HandlerBundleEvent(bundleOption->GetBundleName(), bundleOption->GetAppIndex(), bundleOption->GetUid()); +} + +void NotificationCloneDisturb::OnBundleDataUpdate(const sptr &bundleOption) +{ + HandlerBundleEvent(bundleOption->GetBundleName(), bundleOption->GetAppIndex(), bundleOption->GetUid()); +} + void NotificationCloneDisturb::OnUserSwitch(int32_t userId) { ANS_LOGI("Handler user switch %{public}d", userId); @@ -148,26 +156,20 @@ void NotificationCloneDisturb::OnUserSwitch(int32_t userId) ANS_LOGW("Clone disturb queue is null."); return; } - cloneDisturbQueue_->submit_h(std::bind([&, userId]() { + cloneDisturbQueue_->submit_h(std::bind([&]() { profiles_.clear(); - NotificationPreferences::GetInstance()->GetAllCloneProfileInfo(userId, profiles_); - for (auto profile = profiles_.begin(); profile != profiles_.end(); profile++) { - ANS_LOGI("Clone queue left %{public}d %{public}zu.", (*profile)->GetProfileId(), - (*profile)->GetProfileTrustList().size()); - } - ANS_LOGI("Notification disturb profile list on recover end."); })); } -void NotificationCloneDisturb::OnRestoreStart(const std::string bundleName, int32_t appIndex, - int32_t userId, int32_t uid) +void NotificationCloneDisturb::HandlerBundleEvent(const std::string bundleName, int32_t appIndex, int32_t uid) { - ANS_LOGI("Handler bundle event %{public}s %{public}d %{public}d %{public}d %{public}zu.", - bundleName.c_str(), appIndex, userId, uid, profiles_.size()); + ANS_LOGI("Handler bundle event %{public}s %{public}d %{public}d %{public}zu.", + bundleName.c_str(), appIndex, uid, profiles_.size()); if (profiles_.empty()) { return; } + int32_t userId = NotificationCloneUtil::GetActiveUserId(); NotificationBundleOption bundle(bundleName, uid); bundle.SetAppIndex(appIndex); if (cloneDisturbQueue_ == nullptr) { @@ -186,7 +188,6 @@ void NotificationCloneDisturb::OnRestoreStart(const std::string bundleName, int3 NotificationPreferences::GetInstance()->UpdateDoNotDisturbProfiles(userId, profileId, name, bundleList); if (trustList.empty()) { - NotificationPreferences::GetInstance()->DelCloneProfileInfo(userId, *profile); profile = profiles_.erase(profile); } else { (*profile)->SetProfileTrustList(trustList); @@ -195,7 +196,6 @@ void NotificationCloneDisturb::OnRestoreStart(const std::string bundleName, int3 name.clear(); profileId = -1; } - NotificationPreferences::GetInstance()->UpdateBatchCloneProfileInfo(userId, profiles_); for (auto profile = profiles_.begin(); profile != profiles_.end(); profile++) { ANS_LOGI("Event queue left %{public}d %{public}zu.", (*profile)->GetProfileId(), (*profile)->GetProfileTrustList().size()); diff --git a/services/ans/src/clone/notification_clone_manager.cpp b/services/ans/src/clone/notification_clone_manager.cpp index 2b5b88903..ae65acf2b 100644 --- a/services/ans/src/clone/notification_clone_manager.cpp +++ b/services/ans/src/clone/notification_clone_manager.cpp @@ -26,7 +26,6 @@ #include "nlohmann/json.hpp" #include "notification_clone_disturb_service.h" #include "notification_clone_bundle_service.h" -#include "notification_clone_util.h" namespace OHOS { namespace Notification { @@ -42,22 +41,6 @@ NotificationCloneManager& NotificationCloneManager::GetInstance() return notificationCloneManager; } -static std::string SetBackUpReply() -{ - nlohmann::json reply; - nlohmann::json resultInfo = nlohmann::json::array(); - nlohmann::json errorInfo; - - errorInfo["type"] = "ErrorInfo"; - errorInfo["errorCode"] = std::to_string(ERR_OK); - errorInfo["errorInfo"] = ""; - - resultInfo.emplace_back(errorInfo); - reply["resultInfo"] = resultInfo; - - return reply.dump(); -} - int32_t NotificationCloneManager::OnBackup(MessageParcel& data, MessageParcel& reply) { if (cloneTemplates.empty()) { @@ -103,7 +86,6 @@ int32_t NotificationCloneManager::OnBackup(MessageParcel& data, MessageParcel& r int32_t NotificationCloneManager::OnRestore(MessageParcel& data, MessageParcel& reply) { - reply.WriteString(SetBackUpReply()); std::string storeMessage; UniqueFd fd(data.ReadFileDescriptor()); if (LoadConfig(fd, storeMessage) != ERR_OK) { @@ -200,27 +182,7 @@ void NotificationCloneManager::RemoveBackUpFile() void NotificationCloneManager::OnUserSwitch(int32_t userId) { for (auto iter = cloneTemplates.begin(); iter != cloneTemplates.end(); ++iter) { - if (iter->second != nullptr) { - iter->second->OnUserSwitch(userId); - } - } -} - -void NotificationCloneManager::OnRestoreStart(EventFwk::Want want) -{ - int32_t appIndex = want.GetIntParam("index", -1); - std::string bundleName = want.GetStringParam("bundleName"); - int32_t userId = NotificationCloneUtil::GetActiveUserId(); - if (appIndex == -1 || bundleName.empty()) { - ANS_LOGW("Invalid restore data %{public}d %{public}d %{public}s", - appIndex, userId, bundleName.c_str()); - return; - } - int32_t uid = NotificationCloneUtil::GetBundleUid(bundleName, userId, appIndex); - for (auto iter = cloneTemplates.begin(); iter != cloneTemplates.end(); ++iter) { - if (iter->second != nullptr) { - iter->second->OnRestoreStart(bundleName, appIndex, userId, uid); - } + iter->second->OnUserSwitch(userId); } } } diff --git a/services/ans/src/notification_preferences.cpp b/services/ans/src/notification_preferences.cpp index ec3993cd8..e40736e29 100644 --- a/services/ans/src/notification_preferences.cpp +++ b/services/ans/src/notification_preferences.cpp @@ -689,6 +689,7 @@ void NotificationPreferences::UpdateCloneBundleInfo(int32_t userId, } /* after clone, override these witch */ + bundleInfo.SetSlotFlags(cloneBundleInfo.GetSlotFlags()); bundleInfo.SetIsShowBadge(cloneBundleInfo.GetIsShowBadge()); bundleInfo.SetEnableNotification(cloneBundleInfo.GetEnableNotification()); /* update property to db */ @@ -696,12 +697,6 @@ void NotificationPreferences::UpdateCloneBundleInfo(int32_t userId, ANS_LOGW("Clone bundle info failed %{public}s.", cloneBundleInfo.Dump().c_str()); return; } - - if (SaveBundleProperty(bundleInfo, bundleOption, - BundleType::BUNDLE_SLOTFLGS_TYPE, cloneBundleInfo.GetSlotFlags()) != ERR_OK) { - ANS_LOGW("Clone bundle slot info %{public}s.", cloneBundleInfo.Dump().c_str()); - return; - } preferencesInfo.SetBundleInfo(bundleInfo); /* update slot info */ @@ -1262,77 +1257,5 @@ std::string NotificationPreferences::GetAdditionalConfig(const std::string &key) } return preferncesDB_->GetAdditionalConfig(key); } - -bool NotificationPreferences::DelCloneProfileInfo(const int32_t &userId, - const sptr& info) -{ - if (preferncesDB_ == nullptr) { - return false; - } - return preferncesDB_->DelCloneProfileInfo(userId, info); -} - -bool NotificationPreferences::UpdateBatchCloneProfileInfo(const int32_t &userId, - const std::vector>& profileInfo) -{ - if (preferncesDB_ == nullptr) { - return false; - } - return preferncesDB_->UpdateBatchCloneProfileInfo(userId, profileInfo); -} - -void NotificationPreferences::GetAllCloneProfileInfo(const int32_t &userId, - std::vector>& profilesInfo) -{ - if (preferncesDB_ == nullptr) { - return; - } - return preferncesDB_->GetAllCloneProfileInfo(userId, profilesInfo); -} - -void NotificationPreferences::GetAllCloneBundleInfo(const int32_t &userId, - std::vector& cloneBundleInfo) -{ - if (preferncesDB_ == nullptr) { - return; - } - return preferncesDB_->GetAllCloneBundleInfo(userId, cloneBundleInfo); -} - -bool NotificationPreferences::UpdateBatchCloneBundleInfo(const int32_t &userId, - const std::vector& cloneBundleInfo) -{ - if (preferncesDB_ == nullptr) { - return false; - } - return preferncesDB_->UpdateBatchCloneBundleInfo(userId, cloneBundleInfo); -} - -bool NotificationPreferences::DelCloneBundleInfo(const int32_t &userId, - const NotificationCloneBundleInfo& cloneBundleInfo) -{ - if (preferncesDB_ == nullptr) { - return false; - } - return preferncesDB_->DelCloneBundleInfo(userId, cloneBundleInfo); -} - -bool NotificationPreferences::DelBatchCloneProfileInfo(const int32_t &userId, - const std::vector>& profileInfo) -{ - if (preferncesDB_ == nullptr) { - return false; - } - return preferncesDB_->DelBatchCloneProfileInfo(userId, profileInfo); -} - -bool NotificationPreferences::DelBatchCloneBundleInfo(const int32_t &userId, - const std::vector& cloneBundleInfo) -{ - if (preferncesDB_ == nullptr) { - return false; - } - return preferncesDB_->DelBatchCloneBundleInfo(userId, cloneBundleInfo); -} } // namespace Notification } // namespace OHOS diff --git a/services/ans/src/notification_preferences_database.cpp b/services/ans/src/notification_preferences_database.cpp index 7d2b325a1..3e1cdcb4d 100644 --- a/services/ans/src/notification_preferences_database.cpp +++ b/services/ans/src/notification_preferences_database.cpp @@ -223,10 +223,6 @@ const static std::string KEY_REMINDER_MODE = "reminderMode"; constexpr char RELATIONSHIP_JSON_KEY_SERVICE[] = "service"; constexpr char RELATIONSHIP_JSON_KEY_APP[] = "app"; -const static std::string KEY_CLONE_LABEL = "label_ans_clone_"; -const static std::string CLONE_BUNDLE = "bundle_"; -const static std::string CLONE_PROFILE = "profile_"; - NotificationPreferencesDatabase::NotificationPreferencesDatabase() { NotificationRdbConfig notificationRdbConfig; @@ -2123,164 +2119,5 @@ bool NotificationPreferencesDatabase::UpdateBundleSlotToDisturbeDB(int32_t userI int32_t result = rdbDataManager_->InsertBatchData(values, userId); return (result == NativeRdb::E_OK); } - -bool NotificationPreferencesDatabase::DelCloneProfileInfo(const int32_t &userId, - const sptr& info) -{ - if (!CheckRdbStore()) { - ANS_LOGE("RdbStore is nullptr."); - return false; - } - - std::string key = KEY_CLONE_LABEL + CLONE_PROFILE + std::to_string(info->GetProfileId()); - int32_t result = rdbDataManager_->DeleteData(key, userId); - if (result != NativeRdb::E_OK) { - ANS_LOGE("delete clone profile Info failed."); - return false; - } - return true; -} - -bool NotificationPreferencesDatabase::DelBatchCloneProfileInfo(const int32_t &userId, - const std::vector>& profileInfo) -{ - std::string cloneProfile = KEY_CLONE_LABEL + CLONE_PROFILE; - if (!CheckRdbStore()) { - ANS_LOGE("RdbStore is nullptr."); - return false; - } - - std::vector keys; - for (auto info : profileInfo) { - std::string key = cloneProfile + std::to_string(info->GetProfileId()); - keys.emplace_back(key); - } - - int32_t result = rdbDataManager_->DeleteBathchData(keys, userId); - if (result != NativeRdb::E_OK) { - ANS_LOGE("delete clone bundle Info failed."); - return false; - } - return true; -} - -bool NotificationPreferencesDatabase::UpdateBatchCloneProfileInfo(const int32_t &userId, - const std::vector>& profileInfo) -{ - std::string cloneProfile = KEY_CLONE_LABEL + CLONE_PROFILE; - std::unordered_map values; - for (auto& info : profileInfo) { - std::string key = cloneProfile + std::to_string(info->GetProfileId()); - std::string jsonString = info->ToJson(); - values.emplace(key, jsonString); - } - return UpdateCloneToDisturbeDB(userId, values); -} - -void NotificationPreferencesDatabase::GetAllCloneProfileInfo(const int32_t &userId, - std::vector>& profilesInfo) -{ - std::string cloneProfile = KEY_CLONE_LABEL + CLONE_PROFILE; - std::unordered_map values; - if (GetBatchKvsFromDb(cloneProfile, values, userId) != ERR_OK) { - ANS_LOGW("Get clone bundle map info failed %{public}d.", userId); - return; - } - - for (auto item : values) { - sptr profile = new (std::nothrow) NotificationDoNotDisturbProfile(); - profile->FromJson(item.second); - profilesInfo.push_back(profile); - } -} - -void NotificationPreferencesDatabase::GetAllCloneBundleInfo(const int32_t &userId, - std::vector& cloneBundleInfo) -{ - std::unordered_map values; - if (GetBatchKvsFromDb(KEY_CLONE_LABEL + CLONE_BUNDLE, values, userId) != ERR_OK) { - ANS_LOGW("Get clone bundle map info failed %{public}d.", userId); - return; - } - - for (auto item : values) { - NotificationCloneBundleInfo bundleInfo; - nlohmann::json jsonObject = nlohmann::json::parse(item.second, nullptr, false); - if (jsonObject.is_null() || !jsonObject.is_object()) { - ANS_LOGE("Invalid JSON object"); - continue; - } - bundleInfo.FromJson(jsonObject); - cloneBundleInfo.emplace_back(bundleInfo); - } -} - -bool NotificationPreferencesDatabase::DelBatchCloneBundleInfo(const int32_t &userId, - const std::vector& cloneBundleInfo) -{ - std::string cloneBundle = KEY_CLONE_LABEL + CLONE_BUNDLE; - if (!CheckRdbStore()) { - ANS_LOGE("RdbStore is nullptr."); - return false; - } - - std::vector keys; - for (auto bundleInfo : cloneBundleInfo) { - std::string key = cloneBundle + bundleInfo.GetBundleName() + - std::to_string(bundleInfo.GetAppIndex()); - keys.emplace_back(key); - } - int32_t result = rdbDataManager_->DeleteBathchData(keys, userId); - if (result != NativeRdb::E_OK) { - ANS_LOGE("delete clone bundle Info failed."); - return false; - } - return true; -} - -bool NotificationPreferencesDatabase::UpdateBatchCloneBundleInfo(const int32_t &userId, - const std::vector& cloneBundleInfo) -{ - std::string cloneBundle = KEY_CLONE_LABEL + CLONE_BUNDLE; - std::unordered_map values; - for (auto& info : cloneBundleInfo) { - nlohmann::json jsonNode; - std::string key = cloneBundle + info.GetBundleName() + std::to_string(info.GetAppIndex()); - info.ToJson(jsonNode); - values.emplace(key, jsonNode.dump()); - } - return UpdateCloneToDisturbeDB(userId, values); -} - -bool NotificationPreferencesDatabase::DelCloneBundleInfo(const int32_t &userId, - const NotificationCloneBundleInfo& cloneBundleInfo) -{ - std::string cloneBundle = KEY_CLONE_LABEL + CLONE_BUNDLE; - std::string key = cloneBundle + cloneBundleInfo.GetBundleName() + - std::to_string(cloneBundleInfo.GetAppIndex()); - if (!CheckRdbStore()) { - ANS_LOGE("RdbStore is nullptr."); - return false; - } - - int32_t result = rdbDataManager_->DeleteData(key, userId); - if (result != NativeRdb::E_OK) { - ANS_LOGE("delete clone bundle Info failed."); - return false; - } - return true; -} - -bool NotificationPreferencesDatabase::UpdateCloneToDisturbeDB(const int32_t &userId, - const std::unordered_map values) -{ - if (values.empty() || !CheckRdbStore()) { - ANS_LOGE("RdbStore is nullptr."); - return false; - } - - int32_t result = rdbDataManager_->InsertBatchData(values, userId); - return (result == NativeRdb::E_OK); -} } // namespace Notification } // namespace OHOS diff --git a/services/ans/src/system_event_observer.cpp b/services/ans/src/system_event_observer.cpp index c45b548dd..dedd0a1e7 100644 --- a/services/ans/src/system_event_observer.cpp +++ b/services/ans/src/system_event_observer.cpp @@ -43,7 +43,6 @@ SystemEventObserver::SystemEventObserver(const ISystemEvent &callbacks) : callba matchingSkills.AddEvent(EventFwk::CommonEventSupport::COMMON_EVENT_PACKAGE_ADDED); matchingSkills.AddEvent(EventFwk::CommonEventSupport::COMMON_EVENT_PACKAGE_CHANGED); matchingSkills.AddEvent(EventFwk::CommonEventSupport::COMMON_EVENT_BOOT_COMPLETED); - matchingSkills.AddEvent(EventFwk::CommonEventSupport::COMMON_EVENT_RESTORE_START); EventFwk::CommonEventSubscribeInfo commonEventSubscribeInfo(matchingSkills); commonEventSubscribeInfo.SetThreadMode(EventFwk::CommonEventSubscribeInfo::COMMON); @@ -135,8 +134,6 @@ void SystemEventObserver::OnReceiveEvent(const EventFwk::CommonEventData &data) callbacks_.onBundleDataCleared(bundleOption); } } - } else if (action == EventFwk::CommonEventSupport::COMMON_EVENT_RESTORE_START) { - NotificationCloneManager::GetInstance().OnRestoreStart(want); } else { OnReceiveEventInner(data); } -- Gitee From 7c61862003f7f7e1a13402a909c6769639795785 Mon Sep 17 00:00:00 2001 From: gaojiaqi Date: Wed, 25 Dec 2024 14:41:40 +0800 Subject: [PATCH 155/167] update Signed-off-by: gaojiaqi --- frameworks/ans/src/reminder_request.cpp | 13 ++++ .../ans/src/reminder_request_calendar.cpp | 6 ++ interfaces/inner_api/reminder_request.h | 1 + services/ans/include/reminder_data_manager.h | 10 +++- services/ans/src/reminder_data_manager.cpp | 60 +++++++++++++++---- services/ans/src/reminder_event_manager.cpp | 3 +- services/ans/src/reminder_store.cpp | 6 +- .../reminderdatamanager_fuzzer.cpp | 2 +- 8 files changed, 80 insertions(+), 21 deletions(-) diff --git a/frameworks/ans/src/reminder_request.cpp b/frameworks/ans/src/reminder_request.cpp index 50360754b..f338ac850 100644 --- a/frameworks/ans/src/reminder_request.cpp +++ b/frameworks/ans/src/reminder_request.cpp @@ -43,6 +43,8 @@ const int32_t BUTTON_PKG_INDEX = 2; const int32_t BUTTON_ABILITY_INDEX = 3; const int32_t WANT_AGENT_URI_INDEX = 2; const int32_t INDENT = -1; + +const char* const PARAM_EXTRA_KEY = "NotificationRequest_extraInfo"; } int32_t ReminderRequest::GLOBAL_ID = 0; @@ -1023,6 +1025,7 @@ void ReminderRequest::UpdateNotificationRequest(UpdateNotificationType type, std ANSR_LOGI("UpdateNotification want_agent"); AppExecFwk::ElementName wantAgent("", wantAgentInfo_->pkgName, wantAgentInfo_->abilityName); SetWantAgent(wantAgent); + SetExtraInfo(wantAgentInfo_->parameters); break; } case UpdateNotificationType::MAX_SCREEN_WANT_AGENT: { @@ -1580,6 +1583,15 @@ void ReminderRequest::SetWantAgent(AppExecFwk::ElementName &element) notificationRequest_->SetWantAgent(wantAgent); } +void ReminderRequest::SetExtraInfo(const AAFwk::WantParams& params) +{ + if (params.HasParam(PARAM_EXTRA_KEY)) { + std::shared_ptr extras = std::make_shared( + params.GetWantParams(PARAM_EXTRA_KEY)); + notificationRequest_->SetAdditionalData(extras); + } +} + void ReminderRequest::SetState(bool deSet, const uint8_t newState, std::string function) { uint8_t oldState = state_; @@ -1674,6 +1686,7 @@ void ReminderRequest::UpdateNotificationBundleInfo() ANSR_LOGD("ownerBundleName=%{public}s, bundleName_=%{public}s", ownerBundleName.c_str(), bundleName_.c_str()); notificationRequest_->SetOwnerBundleName(bundleName_); + notificationRequest_->SetOwnerUid(uid_); notificationRequest_->SetCreatorBundleName(bundleName_); notificationRequest_->SetCreatorUid(uid_); notificationRequest_->SetCreatorUserId(userId_); diff --git a/frameworks/ans/src/reminder_request_calendar.cpp b/frameworks/ans/src/reminder_request_calendar.cpp index 3bfad8e46..df26f548c 100644 --- a/frameworks/ans/src/reminder_request_calendar.cpp +++ b/frameworks/ans/src/reminder_request_calendar.cpp @@ -618,6 +618,9 @@ bool ReminderRequestCalendar::UpdateNextReminder() ANSR_LOGI("No need to update next trigger time as it is an one-time reminder."); SetSnoozeTimesDynamic(GetSnoozeTimes()); SetTriggerTimeInMilli(INVALID_LONG_LONG_VALUE); + if (startDateTime_ == endDateTime_) { + SetExpired(true); + } return false; } uint8_t leftSnoozeTimes = GetSnoozeTimesDynamic(); @@ -630,6 +633,9 @@ bool ReminderRequestCalendar::UpdateNextReminder() if ((repeatMonth_ == 0 || repeatDay_ == 0) && (repeatDaysOfWeek_ == 0)) { ANSR_LOGI("Not a day repeat reminder, no need to update to next trigger time."); SetTriggerTimeInMilli(INVALID_LONG_LONG_VALUE); + if (startDateTime_ == endDateTime_) { + SetExpired(true); + } return false; } else { uint64_t nextTriggerTime = GetNextTriggerTime(); diff --git a/interfaces/inner_api/reminder_request.h b/interfaces/inner_api/reminder_request.h index d25264dcb..eb5c2de54 100644 --- a/interfaces/inner_api/reminder_request.h +++ b/interfaces/inner_api/reminder_request.h @@ -1058,6 +1058,7 @@ private: void SetMaxScreenWantAgent(AppExecFwk::ElementName &element); void SetState(bool deSet, const uint8_t newState, std::string function); void SetWantAgent(AppExecFwk::ElementName &element); + void SetExtraInfo(const AAFwk::WantParams& params); void UpdateActionButtons(const bool &setSnooze); bool UpdateNextReminder(const bool &force); void UpdateNotificationContent(const bool &setSnooze); diff --git a/services/ans/include/reminder_data_manager.h b/services/ans/include/reminder_data_manager.h index 38777ba3b..50b3eea4b 100644 --- a/services/ans/include/reminder_data_manager.h +++ b/services/ans/include/reminder_data_manager.h @@ -106,7 +106,7 @@ public: * @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); + void CloseReminder(const OHOS::EventFwk::Want &want, bool cancelNotification, bool isButtonClick = true); /** * Dump all the reminders information. @@ -259,7 +259,7 @@ public: * Update action button title. */ void UpdateReminderLanguageLocked(const int32_t uid, const std::vector>& reminders); - + /** * @brief System language change */ @@ -536,7 +536,8 @@ private: void SetActiveReminder(const sptr &reminder); void SetAlertingReminder(const sptr &reminder); - void ShowActiveReminderExtendLocked(sptr &reminder); + void ShowActiveReminderExtendLocked(sptr &reminder, + std::vector>& extensionReminders); static bool StartExtensionAbility(const sptr &reminder); static void AsyncStartExtensionAbility(const sptr &reminder, int32_t times); void InitServiceHandler(); @@ -662,6 +663,9 @@ private: */ void ReportSysEvent(const sptr& reminder); + ErrCode PublishNotificationRequest(sptr& request, + const sptr& bundleOption); + /** * Single instance. */ diff --git a/services/ans/src/reminder_data_manager.cpp b/services/ans/src/reminder_data_manager.cpp index 87c0556f8..779e9dc56 100644 --- a/services/ans/src/reminder_data_manager.cpp +++ b/services/ans/src/reminder_data_manager.cpp @@ -505,7 +505,7 @@ bool ReminderDataManager::cmp(sptr &reminderRequest, sptrGetTriggerTimeInMilli() < other->GetTriggerTimeInMilli(); } -void ReminderDataManager::CloseReminder(const OHOS::EventFwk::Want &want, bool cancelNotification) +void ReminderDataManager::CloseReminder(const OHOS::EventFwk::Want &want, bool cancelNotification, bool isButtonClick) { int32_t reminderId = static_cast(want.GetIntParam(ReminderRequest::PARAM_REMINDER_ID, -1)); sptr reminder = FindReminderRequestLocked(reminderId); @@ -520,8 +520,10 @@ void ReminderDataManager::CloseReminder(const OHOS::EventFwk::Want &want, bool c CloseRemindersByGroupId(reminderId, packageName, groupId); } CloseReminder(reminder, cancelNotification); - UpdateAppDatabase(reminder, ReminderRequest::ActionButtonType::CLOSE); - CheckNeedNotifyStatus(reminder, ReminderRequest::ActionButtonType::CLOSE); + if (isButtonClick) { + UpdateAppDatabase(reminder, ReminderRequest::ActionButtonType::CLOSE); + CheckNeedNotifyStatus(reminder, ReminderRequest::ActionButtonType::CLOSE); + } StartRecentReminder(); } @@ -813,7 +815,9 @@ void ReminderDataManager::TerminateAlerting(const sptr &reminde } // Set the notification SoundEnabled and VibrationEnabled by soltType advancedNotificationService_->SetRequestBySlotType(notificationRequest, bundleOption); - advancedNotificationService_->PublishPreparedNotification(notificationRequest, bundleOption); + // Since Ans and reminder share a notificationRequest, there is a multi-threaded contention, + // so need to make a copy when calling the Ans interface + PublishNotificationRequest(notificationRequest, bundleOption); store_->UpdateOrInsert(reminder, bundleOption); } @@ -905,7 +909,9 @@ void ReminderDataManager::ShowActiveReminder(const EventFwk::Want &want) if (HandleSysTimeChange(reminder)) { return; } - ShowActiveReminderExtendLocked(reminder); + std::vector> extensionReminders; + ShowActiveReminderExtendLocked(reminder, extensionReminders); + HandleExtensionReminder(extensionReminders); StartRecentReminder(); } @@ -944,7 +950,8 @@ void ReminderDataManager::SetAlertingReminder(const sptr &remin ANSR_LOGD("Set alertingReminderId=%{public}d", alertingReminderId_.load()); } -void ReminderDataManager::ShowActiveReminderExtendLocked(sptr &reminder) +void ReminderDataManager::ShowActiveReminderExtendLocked(sptr& reminder, + std::vector>& extensionReminders) { std::lock_guard lock(ReminderDataManager::MUTEX); uint64_t triggerTime = reminder->GetTriggerTimeInMilli(); @@ -965,7 +972,7 @@ void ReminderDataManager::ShowActiveReminderExtendLocked(sptr & if (!(*it)->IsNeedNotification()) { continue; } - ReminderDataManager::AsyncStartExtensionAbility((*it), CONNECT_EXTENSION_MAX_RETRY_TIMES); + extensionReminders.push_back((*it)); if ((*it)->CheckExcludeDate()) { ANSR_LOGI("reminder[%{public}d] trigger time is in exclude date", (*it)->GetReminderId()); continue; @@ -1032,8 +1039,6 @@ void ReminderDataManager::AsyncStartExtensionAbility(const 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()); int32_t reminderId = reminder->GetReminderId(); sptr bundleOption = reminder->GetNotificationBundleOption(); sptr notificationRequest = reminder->GetNotificationRequest(); @@ -1064,7 +1069,9 @@ void ReminderDataManager::ShowReminder(const sptr &reminder, co } // Set the notification SoundEnabled and VibrationEnabled by soltType advancedNotificationService_->SetRequestBySlotType(notificationRequest, bundleOption); - ErrCode errCode = advancedNotificationService_->PublishPreparedNotification(notificationRequest, bundleOption); + // Since Ans and reminder share a notificationRequest, there is a multi-threaded contention, + // so need to make a copy when calling the Ans interface + ErrCode errCode = PublishNotificationRequest(notificationRequest, bundleOption); if (errCode != ERR_OK) { reminder->OnShowFail(); RemoveFromShowedReminders(reminder); @@ -1148,7 +1155,9 @@ void ReminderDataManager::SnoozeReminderImpl(sptr &reminder) } // Set the notification SoundEnabled and VibrationEnabled by soltType advancedNotificationService_->SetRequestBySlotType(notificationRequest, bundleOption); - advancedNotificationService_->PublishPreparedNotification(notificationRequest, bundleOption); + // Since Ans and reminder share a notificationRequest, there is a multi-threaded contention, + // so need to make a copy when calling the Ans interface + PublishNotificationRequest(notificationRequest, bundleOption); StartRecentReminder(); } @@ -1830,15 +1839,18 @@ void ReminderDataManager::StopTimer(TimerType type) void ReminderDataManager::ResetStates(TimerType type) { + uint64_t timerId = 0; switch (type) { case TimerType::TRIGGER_TIMER: { ANSR_LOGD("ResetStates(activeReminderId, timerId(next triggerTime))"); + timerId = timerId_; timerId_ = 0; activeReminderId_ = -1; break; } case TimerType::ALERTING_TIMER: { ANSR_LOGD("ResetStates(alertingReminderId, timeId(alerting time out))"); + timerId = timerIdAlerting_; timerIdAlerting_ = 0; alertingReminderId_ = -1; break; @@ -1848,6 +1860,14 @@ void ReminderDataManager::ResetStates(TimerType type) break; } } + sptr timer = MiscServices::TimeServiceClient::GetInstance(); + if (timer == nullptr) { + ANSR_LOGE("Failed to destroy timer due to get TimeServiceClient is null."); + return; + } + if (timerId != 0) { + timer->DestroyTimer(timerId); + } } void ReminderDataManager::HandleCustomButtonClick(const OHOS::EventFwk::Want &want) @@ -1892,8 +1912,6 @@ void ReminderDataManager::ClickReminder(const OHOS::EventFwk::Want &want) return; } CloseReminder(reminder, true); - UpdateAppDatabase(reminder, ReminderRequest::ActionButtonType::CLOSE); - CheckNeedNotifyStatus(reminder, ReminderRequest::ActionButtonType::CLOSE); StartRecentReminder(); auto wantInfo = reminder->GetWantAgentInfo(); @@ -1985,6 +2003,9 @@ void ReminderDataManager::OnLanguageChanged() { std::lock_guard lock(ReminderDataManager::MUTEX); for (auto it = reminderVector_.begin(); it != reminderVector_.end(); ++it) { + if ((*it)->IsExpired() || (*it)->GetTriggerTimeInMilli() == 0) { + continue; + } reminders[(*it)->GetUid()].push_back((*it)); } } @@ -2071,5 +2092,18 @@ void ReminderDataManager::CheckNeedNotifyStatus(const sptr &rem ANSR_LOGI("notify reminder status change %{public}s", bundleName.c_str()); } } + +ErrCode ReminderDataManager::PublishNotificationRequest(sptr& request, + const sptr& bundleOption) +{ + MessageParcel data; + data.WriteParcelable(request); + sptr newRequest = data.ReadParcelable(); + if (newRequest == nullptr) { + ANSR_LOGE("NotificationRequest is nullptr"); + return ERR_REMINDER_INVALID_PARAM; + } + return advancedNotificationService_->PublishPreparedNotification(newRequest, bundleOption); +} } } diff --git a/services/ans/src/reminder_event_manager.cpp b/services/ans/src/reminder_event_manager.cpp index 868fbd6a5..6b8b629b1 100644 --- a/services/ans/src/reminder_event_manager.cpp +++ b/services/ans/src/reminder_event_manager.cpp @@ -167,7 +167,7 @@ void ReminderEventManager::ReminderEventCustomSubscriber::OnReceiveEvent(const E return; } if (action == ReminderRequest::REMINDER_EVENT_REMOVE_NOTIFICATION) { - reminderDataManager_->CloseReminder(want, false); + reminderDataManager_->CloseReminder(want, false, false); return; } if (action == ReminderRequest::REMINDER_EVENT_CLICK_ALERT) { @@ -312,6 +312,7 @@ void ReminderEventManager::ReminderNotificationSubscriber::OnCanceled( const std::shared_ptr ¬ification, const std::shared_ptr &sortingMap, int deleteReason) { + // Note: Don't modify param notification if (deleteReason != NotificationConstant::TRIGGER_AUTO_DELETE_REASON_DELETE) { return; } diff --git a/services/ans/src/reminder_store.cpp b/services/ans/src/reminder_store.cpp index d9a42d6f5..74e08b9fc 100644 --- a/services/ans/src/reminder_store.cpp +++ b/services/ans/src/reminder_store.cpp @@ -730,14 +730,14 @@ std::vector> ReminderStore::GetReminders(const std::string return reminders; } bool isAtLastRow = false; - queryResultSet->IsAtLastRow(isAtLastRow); - while (!isAtLastRow) { + int32_t ret = queryResultSet->IsAtLastRow(isAtLastRow); + while (ret == NativeRdb::E_OK && !isAtLastRow) { queryResultSet->GoToNextRow(); sptr reminder = BuildReminder(queryResultSet); if (reminder != nullptr) { reminders.push_back(reminder); } - queryResultSet->IsAtLastRow(isAtLastRow); + ret = queryResultSet->IsAtLastRow(isAtLastRow); } ANSR_LOGD("Size=%{public}zu", reminders.size()); return reminders; diff --git a/test/fuzztest/reminderdatamanager_fuzzer/reminderdatamanager_fuzzer.cpp b/test/fuzztest/reminderdatamanager_fuzzer/reminderdatamanager_fuzzer.cpp index 221f8d765..e9fa30ab7 100644 --- a/test/fuzztest/reminderdatamanager_fuzzer/reminderdatamanager_fuzzer.cpp +++ b/test/fuzztest/reminderdatamanager_fuzzer/reminderdatamanager_fuzzer.cpp @@ -108,7 +108,7 @@ namespace OHOS { manager->RemoveReminderLocked(reminderId); manager->SetActiveReminder(reminder); manager->SetAlertingReminder(reminder); - manager->ShowActiveReminderExtendLocked(reminder); + manager->ShowActiveReminderExtendLocked(reminder, reminders); std::vector> extensionReminders; std::vector> immediatelyReminders; -- Gitee From d5c8c5fbf446f67b95d6554d40367121dd7c2bb7 Mon Sep 17 00:00:00 2001 From: pancras Date: Thu, 26 Dec 2024 09:19:30 +0800 Subject: [PATCH 156/167] =?UTF-8?q?=E4=BB=A3=E7=A0=81=E5=90=8C=E6=AD=A5?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: pancras --- frameworks/ans/src/notification_helper.cpp | 5 +++ .../unittest/notification_helper_test.cpp | 14 ++++++++ .../core/include/ans_manager_interface.h | 8 +++++ frameworks/core/include/ans_manager_proxy.h | 8 +++++ frameworks/core/include/ans_manager_stub.h | 9 ++++++ frameworks/core/include/ans_notification.h | 8 +++++ ..._notification_service_ipc_interface_code.h | 1 + frameworks/core/src/ans_manager_proxy.cpp | 29 +++++++++++++++++ frameworks/core/src/ans_manager_stub.cpp | 16 ++++++++++ .../core/src/ans_manager_stub_invalid.cpp | 6 ++++ frameworks/core/src/ans_notification.cpp | 10 ++++++ .../ans_manager_proxy_unit_test.cpp | 22 +++++++++++++ .../ans_manager_stub_test.cpp | 13 ++++++++ .../ans_notification_branch_test.cpp | 5 +++ interfaces/inner_api/notification_helper.h | 8 +++++ .../include/advanced_notification_service.h | 25 +++++++++++++++ ...dvanced_notification_live_view_service.cpp | 29 +++++++++++++++++ .../ans/src/advanced_notification_service.cpp | 21 ++++++++++++ ...ed_notification_live_view_service_test.cpp | 32 +++++++++++++++++++ .../ansmanagerstub_fuzzer.cpp | 3 ++ 20 files changed, 272 insertions(+) diff --git a/frameworks/ans/src/notification_helper.cpp b/frameworks/ans/src/notification_helper.cpp index 99e245e16..ccfb6618b 100644 --- a/frameworks/ans/src/notification_helper.cpp +++ b/frameworks/ans/src/notification_helper.cpp @@ -592,5 +592,10 @@ ErrCode NotificationHelper::GetDoNotDisturbProfile(int32_t id, sptr::GetInstance()->GetDoNotDisturbProfile(id, profile); } + +ErrCode NotificationHelper::UpdateNotificationTimerByUid(const int32_t uid, const bool isPaused) +{ + return DelayedSingleton::GetInstance()->UpdateNotificationTimerByUid(uid, isPaused); +} } // namespace Notification } // namespace OHOS diff --git a/frameworks/ans/test/unittest/notification_helper_test.cpp b/frameworks/ans/test/unittest/notification_helper_test.cpp index cee8e7676..ad2574b85 100644 --- a/frameworks/ans/test/unittest/notification_helper_test.cpp +++ b/frameworks/ans/test/unittest/notification_helper_test.cpp @@ -1305,5 +1305,19 @@ HWTEST_F(NotificationHelperTest, RegisterSwingCallback_0100, TestSize.Level1) EXPECT_EQ(ret, ERR_OK); #endif } + +/** + * @tc.name: UpdateNotificationTimerByUid_00001 + * @tc.desc: Test UpdateNotificationTimerByUid. + * @tc.type: FUNC + */ +HWTEST_F(NotificationHelperTest, UpdateNotificationTimerByUid_00001, Function | SmallTest | Level1) +{ + int32_t uid = 20099999; + bool isPaused = true; + NotificationHelper notificationHelper; + ErrCode ret = notificationHelper.UpdateNotificationTimerByUid(uid, isPaused); + EXPECT_EQ(ret, ERR_OK); +} } } diff --git a/frameworks/core/include/ans_manager_interface.h b/frameworks/core/include/ans_manager_interface.h index 882db3e95..66e893e89 100644 --- a/frameworks/core/include/ans_manager_interface.h +++ b/frameworks/core/include/ans_manager_interface.h @@ -975,6 +975,14 @@ public: */ virtual ErrCode RegisterSwingCallback(const sptr& swingCallback) = 0; #endif + + /** + * @brief Update Notification Timer by uid + * + * @param uid uid. + * @return Returns Update result. + */ + virtual ErrCode UpdateNotificationTimerByUid(const int32_t uid, const bool isPaused) = 0; }; } // namespace Notification } // namespace OHOS diff --git a/frameworks/core/include/ans_manager_proxy.h b/frameworks/core/include/ans_manager_proxy.h index be402287f..121f2b555 100644 --- a/frameworks/core/include/ans_manager_proxy.h +++ b/frameworks/core/include/ans_manager_proxy.h @@ -965,6 +965,14 @@ public: ErrCode RegisterSwingCallback(const sptr &swingCallback) override; #endif + /** + * @brief Update Notification Timer by uid + * + * @param uid uid. + * @return Returns Update result. + */ + ErrCode UpdateNotificationTimerByUid(const int32_t uid, const bool isPaused) override; + private: ErrCode InnerTransact(NotificationInterfaceCode code, MessageOption &flags, MessageParcel &data, MessageParcel &reply); diff --git a/frameworks/core/include/ans_manager_stub.h b/frameworks/core/include/ans_manager_stub.h index b50a79fc8..c84bc06ba 100644 --- a/frameworks/core/include/ans_manager_stub.h +++ b/frameworks/core/include/ans_manager_stub.h @@ -966,6 +966,14 @@ public: */ ErrCode RegisterSwingCallback(const sptr& swingCallback) override; #endif + + /** + * @brief Update Notification Timer by uid + * + * @param uid uid. + * @return Returns Update result. + */ + virtual ErrCode UpdateNotificationTimerByUid(const int32_t uid, const bool isPaused) override; private: ErrCode HandlePublish(MessageParcel &data, MessageParcel &reply); @@ -1073,6 +1081,7 @@ private: #ifdef NOTIFICATION_SMART_REMINDER_SUPPORTED ErrCode HandleRegisterSwingCallback(MessageParcel &data, MessageParcel &reply); #endif + ErrCode HandleUpdateNotificationTimerByUid(MessageParcel &data, MessageParcel &reply); template bool WriteParcelableVector(const std::vector> &parcelableVector, MessageParcel &reply, ErrCode &result) { diff --git a/frameworks/core/include/ans_notification.h b/frameworks/core/include/ans_notification.h index e7f8cde07..6b23f74ee 100644 --- a/frameworks/core/include/ans_notification.h +++ b/frameworks/core/include/ans_notification.h @@ -1204,6 +1204,14 @@ public: */ ErrCode GetDoNotDisturbProfile(int32_t id, sptr &profile); + /** + * @brief Update Notification Timer by uid + * + * @param uid uid. + * @return Returns Update result. + */ + ErrCode UpdateNotificationTimerByUid(const int32_t uid, const bool isPaused); + /** * @brief Ans service died, OnRemoteDied called. */ diff --git a/frameworks/core/include/distributed_notification_service_ipc_interface_code.h b/frameworks/core/include/distributed_notification_service_ipc_interface_code.h index ff7a3606c..fc620668a 100644 --- a/frameworks/core/include/distributed_notification_service_ipc_interface_code.h +++ b/frameworks/core/include/distributed_notification_service_ipc_interface_code.h @@ -151,6 +151,7 @@ namespace Notification { DEL_EXCLUDE_DATES_REMINDER, GET_EXCLUDE_DATES_REMINDER, GET_DONOTDISTURB_PROFILE, + UPDATE_NOTIFICATION_TIMER, }; } } diff --git a/frameworks/core/src/ans_manager_proxy.cpp b/frameworks/core/src/ans_manager_proxy.cpp index 2297762f4..cb0202713 100644 --- a/frameworks/core/src/ans_manager_proxy.cpp +++ b/frameworks/core/src/ans_manager_proxy.cpp @@ -2262,5 +2262,34 @@ ErrCode AnsManagerProxy::RegisterSwingCallback(const sptr &swingC return result; } #endif + +ErrCode AnsManagerProxy::UpdateNotificationTimerByUid(const int32_t uid, const bool isPaused) +{ + MessageParcel data; + if (!data.WriteInterfaceToken(AnsManagerProxy::GetDescriptor())) { + ANS_LOGE("write interface token failed."); + return ERR_ANS_PARCELABLE_FAILED; + } + + if (!data.WriteInt32(uid)) { + ANS_LOGE("write uid failed."); + return ERR_ANS_PARCELABLE_FAILED; + } + + if (!data.WriteBool(isPaused)) { + ANS_LOGE("write isPaused failed."); + return ERR_ANS_PARCELABLE_FAILED; + } + + MessageParcel reply; + MessageOption option = { MessageOption::TF_ASYNC }; + ErrCode result = InnerTransact(NotificationInterfaceCode::UPDATE_NOTIFICATION_TIMER, option, data, reply); + if (result != ERR_OK) { + ANS_LOGE("transact ErrCode=%{public}d", result); + return ERR_ANS_TRANSACT_FAILED; + } + + return result; +} } // namespace Notification } // namespace OHOS diff --git a/frameworks/core/src/ans_manager_stub.cpp b/frameworks/core/src/ans_manager_stub.cpp index 73002331e..f71bb65ea 100644 --- a/frameworks/core/src/ans_manager_stub.cpp +++ b/frameworks/core/src/ans_manager_stub.cpp @@ -457,6 +457,10 @@ int32_t AnsManagerStub::OnRemoteRequest(uint32_t code, MessageParcel &data, Mess result = HandleGetDoNotDisturbProfile(data, reply); break; } + case static_cast(NotificationInterfaceCode::UPDATE_NOTIFICATION_TIMER): { + result = HandleUpdateNotificationTimerByUid(data, reply); + break; + } default: { ANS_LOGE("[OnRemoteRequest] fail: unknown code!"); return IPCObjectStub::OnRemoteRequest(code, data, reply, flags); @@ -2691,5 +2695,17 @@ ErrCode AnsManagerStub::HandleRegisterSwingCallback(MessageParcel &data, Message return result; } #endif + +ErrCode AnsManagerStub::HandleUpdateNotificationTimerByUid(MessageParcel &data, MessageParcel &reply) +{ + int32_t uid = data.ReadInt32(); + bool isPaused = data.ReadBool(); + ErrCode result = UpdateNotificationTimerByUid(uid, isPaused); + if (!reply.WriteInt32(result)) { + ANS_LOGE("[HandleUpdateNotificationTimerByUid] fail: write result failed, ErrCode=%{public}d", result); + return ERR_ANS_PARCELABLE_FAILED; + } + return result; +} } // namespace Notification } // namespace OHOS diff --git a/frameworks/core/src/ans_manager_stub_invalid.cpp b/frameworks/core/src/ans_manager_stub_invalid.cpp index b58e45de5..c42c7ac85 100644 --- a/frameworks/core/src/ans_manager_stub_invalid.cpp +++ b/frameworks/core/src/ans_manager_stub_invalid.cpp @@ -671,5 +671,11 @@ ErrCode AnsManagerStub::RegisterSwingCallback(const sptr& swingCa return ERR_INVALID_OPERATION; } #endif + +ErrCode AnsManagerStub::UpdateNotificationTimerByUid(const int32_t uid, const bool isPaused) +{ + ANS_LOGE("UpdateNotificationTimerByUid called!"); + return ERR_INVALID_OPERATION; +} } // namespace Notification } // namespace OHOS diff --git a/frameworks/core/src/ans_notification.cpp b/frameworks/core/src/ans_notification.cpp index 4e30fe577..655393448 100644 --- a/frameworks/core/src/ans_notification.cpp +++ b/frameworks/core/src/ans_notification.cpp @@ -2043,5 +2043,15 @@ ErrCode AnsNotification::RegisterSwingCallback(const std::functionRegisterSwingCallback(swingCallBackStub_->AsObject()); } #endif + +ErrCode AnsNotification::UpdateNotificationTimerByUid(const int32_t uid, const bool isPaused) +{ + sptr proxy = GetAnsManagerProxy(); + if (!proxy) { + ANS_LOGE("UpdateNotificationTimerByUid fail."); + return ERR_ANS_SERVICE_NOT_CONNECTED; + } + return proxy->UpdateNotificationTimerByUid(uid, isPaused); +} } // namespace Notification } // namespace OHOS diff --git a/frameworks/core/test/unittest/ans_manager_proxy_test/ans_manager_proxy_unit_test.cpp b/frameworks/core/test/unittest/ans_manager_proxy_test/ans_manager_proxy_unit_test.cpp index 3dc08617d..2a609a055 100644 --- a/frameworks/core/test/unittest/ans_manager_proxy_test/ans_manager_proxy_unit_test.cpp +++ b/frameworks/core/test/unittest/ans_manager_proxy_test/ans_manager_proxy_unit_test.cpp @@ -8188,5 +8188,27 @@ HWTEST_F(AnsManagerProxyUnitTest, IsNeedSilentInDoNotDisturbModeTest_0500, Funct int32_t result = proxy->IsNeedSilentInDoNotDisturbMode(phoneNumber, callerType); EXPECT_EQ(ERR_OK, result); } + +/* + * @tc.name: UpdateNotificationTimerByUid_0100 + * @tc.desc: test UpdateNotificationTimerByUid function + * @tc.type: FUNC + */ +HWTEST_F(AnsManagerProxyUnitTest, UpdateNotificationTimerByUid_0100, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) + << "AnsManagerProxyUnitTest, UpdateNotificationTimerByUid_0100, TestSize.Level1"; + sptr iremoteObject = new (std::nothrow) MockIRemoteObject(); + ASSERT_NE(nullptr, iremoteObject); + EXPECT_CALL(*iremoteObject, SendRequest(_, _, _, _)).Times(1) + .WillRepeatedly(DoAll(Invoke(std::bind(SendRequestReplace, _1, _2, _3, _4, + ERR_OK, true, false, false)), Return(NO_ERROR))); + std::shared_ptr proxy = std::make_shared(iremoteObject); + ASSERT_NE(nullptr, proxy); + int32_t uid = 20099999; + bool isPaused = true; + int32_t result = proxy->UpdateNotificationTimerByUid(uid, isPaused); + EXPECT_EQ(ERR_OK, result); +} } // namespace Notification } // namespace OHOS diff --git a/frameworks/core/test/unittest/ans_manager_stub_test/ans_manager_stub_test.cpp b/frameworks/core/test/unittest/ans_manager_stub_test/ans_manager_stub_test.cpp index 01be185ce..96bb54b63 100644 --- a/frameworks/core/test/unittest/ans_manager_stub_test/ans_manager_stub_test.cpp +++ b/frameworks/core/test/unittest/ans_manager_stub_test/ans_manager_stub_test.cpp @@ -5473,5 +5473,18 @@ HWTEST_F(AnsManagerStubTest, IsNeedSilentInDoNotDisturbMode01, Function | SmallT ErrCode result = ansManagerStub_->IsNeedSilentInDoNotDisturbMode(phoneNumber, callerType); EXPECT_EQ(result, (int)ERR_INVALID_OPERATION); } + +/** + * @tc.name: UpdateNotificationTimerByUid_01 + * @tc.desc: Test UpdateNotificationTimerByUid return. + * @tc.type: FUNC + */ +HWTEST_F(AnsManagerStubTest, UpdateNotificationTimerByUid_01, Function | SmallTest | Level1) +{ + int32_t uid = 20099999; + bool isPaused = true; + ErrCode result = ansManagerStub_->UpdateNotificationTimerByUid(uid, isPaused); + EXPECT_EQ(result, (int)ERR_INVALID_OPERATION); +} } } diff --git a/frameworks/core/test/unittest/ans_notification_branch_test/ans_notification_branch_test.cpp b/frameworks/core/test/unittest/ans_notification_branch_test/ans_notification_branch_test.cpp index 887c99809..b03eb1d7f 100644 --- a/frameworks/core/test/unittest/ans_notification_branch_test/ans_notification_branch_test.cpp +++ b/frameworks/core/test/unittest/ans_notification_branch_test/ans_notification_branch_test.cpp @@ -593,6 +593,11 @@ public: return ERR_ANS_INVALID_PARAM; } #endif + + ErrCode UpdateNotificationTimerByUid(const int32_t uid, const bool isPaused) override + { + return ERR_ANS_INVALID_PARAM; + } }; class AnsNotificationBranchTest : public testing::Test { diff --git a/interfaces/inner_api/notification_helper.h b/interfaces/inner_api/notification_helper.h index da1170016..95a3d9c99 100644 --- a/interfaces/inner_api/notification_helper.h +++ b/interfaces/inner_api/notification_helper.h @@ -1118,6 +1118,14 @@ public: * @return Returns ERR_OK on success, others on failure. */ static ErrCode GetDoNotDisturbProfile(int32_t id, sptr &profile); + + /** + * @brief Update Notification Timer by uid + * + * @param uid uid. + * @return Returns Update result. + */ + static ErrCode UpdateNotificationTimerByUid(const int32_t uid, const bool isPaused); }; } // namespace Notification } // namespace OHOS diff --git a/services/ans/include/advanced_notification_service.h b/services/ans/include/advanced_notification_service.h index 4e7890bf7..95fa86a7d 100644 --- a/services/ans/include/advanced_notification_service.h +++ b/services/ans/include/advanced_notification_service.h @@ -1163,6 +1163,20 @@ public: int32_t OnBackup(MessageParcel& data, MessageParcel& reply); int32_t OnRestore(MessageParcel& data, MessageParcel& reply); +<<<<<<< Updated upstream +======= + + void UpdateCloneBundleInfo(const NotificationCloneBundleInfo cloneBundleInfo); + + /** + * @brief Update notification timer by uid + * + * @param uid uid. + * @param isPaused if paused + * @return Returns ERR_OK on success, others on failure. + */ + ErrCode UpdateNotificationTimerByUid(const int32_t uid, const bool isPaused) override; +>>>>>>> Stashed changes protected: /** * @brief Query whether there is a agent relationship between the two apps. @@ -1431,6 +1445,17 @@ private: bool IsSystemUser(int32_t userId); ErrCode UpdateFlowCtrl(const std::shared_ptr &record); ErrCode PublishFlowControlInner(const std::shared_ptr &record); +<<<<<<< Updated upstream +======= + ErrCode SetEnabledForBundleSlotInner(const sptr &bundleOption, + const sptr &bundle, + const NotificationConstant::SlotType &slotType, bool enabled, bool isForceControl); + ErrCode AddSlotThenPublishEvent( + const sptr &slot, + const sptr &bundle, + bool enabled, bool isForceControl); + void HandleUpdateLiveViewNotificationTimer(const int32_t uid, const bool isPaused); +>>>>>>> Stashed changes private: static sptr instance_; static std::mutex instanceMutex_; diff --git a/services/ans/src/advanced_notification_live_view_service.cpp b/services/ans/src/advanced_notification_live_view_service.cpp index 5032e2b0d..2e4ee8fae 100644 --- a/services/ans/src/advanced_notification_live_view_service.cpp +++ b/services/ans/src/advanced_notification_live_view_service.cpp @@ -40,6 +40,8 @@ namespace OHOS { namespace Notification { const std::string LOCK_SCREEN_PICTURE_TAG = "lock_screen_picture"; const std::string PROGRESS_VALUE = "progressValue"; +constexpr int32_t BGTASK_UID = 3051; +constexpr int32_t TYPE_CODE_DOWNLOAD = 8; void AdvancedNotificationService::RecoverLiveViewFromDb(int32_t userId) { if (notificationSvrQueue_ == nullptr) { @@ -740,5 +742,32 @@ void AdvancedNotificationService::StartFinishTimerForUpdate( NotificationConstant::TRIGGER_THIRTY_MINUTES_REASON_DELETE); } } + +void AdvancedNotificationService::HandleUpdateLiveViewNotificationTimer(const int32_t uid, const bool isPaused) +{ + for (const auto &record : notificationList_) { + const auto &request = record->request; + if (!request || request->GetOwnerUid() != uid) { + continue; + } + if (!request->GetContent() || !request->GetContent()->GetNotificationContent()) { + continue; + } + + bool isContinuousLiveView = request->IsSystemLiveView() && request->GetCreatorUid() == BGTASK_UID; + const auto &liveViewContent = std::static_pointer_cast( + request->GetContent()->GetNotificationContent()); + if (isContinuousLiveView && liveViewContent->GetType() == TYPE_CODE_DOWNLOAD) { + if (isPaused) { + ANS_LOGI("liveview notification timer is being cancelled, uid: %{public}d", uid); + CancelTimer(record->notification->GetFinishTimer()); + } else { + ANS_LOGI("liveview notification timer is being reset, uid: %{public}d", uid); + StartFinishTimer(record, GetCurrentTime() + NotificationConstant::FIFTEEN_MINUTES, + NotificationConstant::TRIGGER_THIRTY_MINUTES_REASON_DELETE); + } + } + } +} } } diff --git a/services/ans/src/advanced_notification_service.cpp b/services/ans/src/advanced_notification_service.cpp index 45bd3673a..8b3ab5fa1 100644 --- a/services/ans/src/advanced_notification_service.cpp +++ b/services/ans/src/advanced_notification_service.cpp @@ -89,6 +89,7 @@ constexpr int32_t MAX_LIVEVIEW_HINT_COUNT = 1; constexpr int32_t BUNDLE_OPTION_UID_DEFAULT_VALUE = 0; constexpr int32_t MAX_SOUND_ITEM_LENGTH = 2048; constexpr int32_t RSS_UID = 3051; +constexpr int32_t RESSCHED_UID = 1096; const std::string DO_NOT_DISTURB_MODE = "1"; constexpr const char *KEY_UNIFIED_GROUP_ENABLE = "unified_group_enable"; @@ -2353,6 +2354,26 @@ ErrCode AdvancedNotificationService::RegisterSwingCallback(const sptrsubmit_h(std::bind([&]() { + HandleUpdateLiveViewNotificationTimer(uid, isPaused); + })); + notificationSvrQueue_->wait(handler); + return ERR_OK; +} + void PushCallbackRecipient::OnRemoteDied(const wptr &remote) { ANS_LOGI("Push Callback died, remove the proxy object"); diff --git a/services/ans/test/unittest/advanced_notification_live_view_service_test.cpp b/services/ans/test/unittest/advanced_notification_live_view_service_test.cpp index 109ae8d0e..bb1b585d2 100644 --- a/services/ans/test/unittest/advanced_notification_live_view_service_test.cpp +++ b/services/ans/test/unittest/advanced_notification_live_view_service_test.cpp @@ -306,5 +306,37 @@ HWTEST_F(AnsLiveViewServiceTest, IsSaCreateSystemLiveViewAsBundle_002, Function flag = advancedNotificationService_->IsSaCreateSystemLiveViewAsBundle(record, creatorUid); ASSERT_EQ(flag, false); } + +/** + * @tc.name: HandleUpdateLiveViewNotificationTimer_001 + * @tc.desc: Test HandleUpdateLiveViewNotificationTimer + * @tc.type: FUNC + * @tc.require: issue + */ +HWTEST_F(AnsLiveViewServiceTest, HandleUpdateLiveViewNotificationTimer_001, Function | SmallTest | Level1) +{ + sptr request = new (std::nothrow) NotificationRequest(); + auto slotType = NotificationConstant::SlotType::LIVE_VIEW; + request->SetSlotType(slotType); + request->SetNotificationId(1); + int32_t TYPE_CODE_DOWNLOAD = 8; + auto localLiveViewContent = std::make_shared(); + localLiveViewContent->SetType(TYPE_CODE_DOWNLOAD); + auto content = std::make_shared(localLiveViewContent); + request->SetContent(content); + int creatorUid = 3051; + request->SetCreatorUid(creatorUid); + int ownerUid = 20099999; + request->SetOwnerUid(ownerUid); + sptr bundle = new NotificationBundleOption("test", ownerUid); + auto record = advancedNotificationService_->MakeNotificationRecord(request, bundle); + advancedNotificationService_->AddToNotificationList(record); + MockGetTokenTypeFlag(Security::AccessToken::ATokenTypeEnum::TOKEN_NATIVE); + auto timer = record->notification->GetFinishTimer(); + advancedNotificationService_->HandleUpdateLiveViewNotificationTimer(ownerUid, true); + ASSERT_EQ(timer, record->notification->GetFinishTimer()); + advancedNotificationService_->HandleUpdateLiveViewNotificationTimer(ownerUid, false); + ASSERT_NE(timer, record->notification->GetFinishTimer()); +} } // namespace Notification } // namespace OHOS diff --git a/test/fuzztest/ansmanagerstub_fuzzer/ansmanagerstub_fuzzer.cpp b/test/fuzztest/ansmanagerstub_fuzzer/ansmanagerstub_fuzzer.cpp index 9df1eecfa..ebb7c6f67 100644 --- a/test/fuzztest/ansmanagerstub_fuzzer/ansmanagerstub_fuzzer.cpp +++ b/test/fuzztest/ansmanagerstub_fuzzer/ansmanagerstub_fuzzer.cpp @@ -317,6 +317,9 @@ namespace OHOS { datas.WriteString(stringData); datas.WriteInt32(intData); ansManagerStub.HandleSetTargetDeviceStatus(datas, reply); + datas.WriteInt32(intData); + datas.WriteBool(boolData); + ansManagerStub.HandleUpdateNotificationTimerByUid(datas, reply); sptr notification2 = new Notification::NotificationRequest(); notification2->SetOwnerUid(fuzzData.GenerateRandomInt32()); notification2->SetCreatorUid(fuzzData.GenerateRandomInt32()); -- Gitee From 8858496c2e8f31547316a9ba1da0d266ecaa2921 Mon Sep 17 00:00:00 2001 From: PancrasLiu Date: Thu, 26 Dec 2024 01:33:56 +0000 Subject: [PATCH 157/167] =?UTF-8?q?=E4=BB=A3=E7=A0=81=E5=90=8C=E6=AD=A5?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: PancrasLiu --- .../ans/include/advanced_notification_service.h | 15 --------------- 1 file changed, 15 deletions(-) diff --git a/services/ans/include/advanced_notification_service.h b/services/ans/include/advanced_notification_service.h index 95fa86a7d..9a55f742f 100644 --- a/services/ans/include/advanced_notification_service.h +++ b/services/ans/include/advanced_notification_service.h @@ -1163,11 +1163,7 @@ public: int32_t OnBackup(MessageParcel& data, MessageParcel& reply); int32_t OnRestore(MessageParcel& data, MessageParcel& reply); -<<<<<<< Updated upstream -======= - void UpdateCloneBundleInfo(const NotificationCloneBundleInfo cloneBundleInfo); - /** * @brief Update notification timer by uid * @@ -1176,7 +1172,6 @@ public: * @return Returns ERR_OK on success, others on failure. */ ErrCode UpdateNotificationTimerByUid(const int32_t uid, const bool isPaused) override; ->>>>>>> Stashed changes protected: /** * @brief Query whether there is a agent relationship between the two apps. @@ -1445,17 +1440,7 @@ private: bool IsSystemUser(int32_t userId); ErrCode UpdateFlowCtrl(const std::shared_ptr &record); ErrCode PublishFlowControlInner(const std::shared_ptr &record); -<<<<<<< Updated upstream -======= - ErrCode SetEnabledForBundleSlotInner(const sptr &bundleOption, - const sptr &bundle, - const NotificationConstant::SlotType &slotType, bool enabled, bool isForceControl); - ErrCode AddSlotThenPublishEvent( - const sptr &slot, - const sptr &bundle, - bool enabled, bool isForceControl); void HandleUpdateLiveViewNotificationTimer(const int32_t uid, const bool isPaused); ->>>>>>> Stashed changes private: static sptr instance_; static std::mutex instanceMutex_; -- Gitee From 480acf8730f8c0e34c688d40ba16112290056684 Mon Sep 17 00:00:00 2001 From: markYao Date: Fri, 27 Dec 2024 17:23:36 +0800 Subject: [PATCH 158/167] =?UTF-8?q?=E3=80=905.0.2-release=E3=80=91?= =?UTF-8?q?=E4=BF=AE=E6=94=B9=E5=90=8C=E6=AD=A5=E5=88=B05.0.2-release?= =?UTF-8?q?=E5=88=86=E6=94=AF?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: markYao --- .../core/include/ans_manager_interface.h | 2 +- frameworks/core/include/ans_manager_proxy.h | 2 +- frameworks/core/include/ans_manager_stub.h | 2 +- frameworks/core/include/ans_notification.h | 10 +++--- .../napi/src/manager/napi_local_live_view.cpp | 1 + frameworks/js/napi/src/subscribe.cpp | 3 ++ .../include/advanced_notification_service.h | 7 ++-- ...dvanced_notification_live_view_service.cpp | 11 ++++--- .../advanced_notification_service_ability.cpp | 2 ++ .../ans/src/advanced_notification_utils.cpp | 6 +--- .../src/common/notification_config_parse.cpp | 2 +- services/ans/src/notification_preferences.cpp | 17 +++++----- .../src/notification_preferences_database.cpp | 32 +++++++++---------- services/ans/src/system_event_observer.cpp | 4 +-- 14 files changed, 52 insertions(+), 49 deletions(-) diff --git a/frameworks/core/include/ans_manager_interface.h b/frameworks/core/include/ans_manager_interface.h index 66e893e89..4a00c8c45 100644 --- a/frameworks/core/include/ans_manager_interface.h +++ b/frameworks/core/include/ans_manager_interface.h @@ -977,7 +977,7 @@ public: #endif /** - * @brief Update Notification Timer by uid + * @brief Update Notification Timer by uid. * * @param uid uid. * @return Returns Update result. diff --git a/frameworks/core/include/ans_manager_proxy.h b/frameworks/core/include/ans_manager_proxy.h index 121f2b555..fe7bfba0f 100644 --- a/frameworks/core/include/ans_manager_proxy.h +++ b/frameworks/core/include/ans_manager_proxy.h @@ -966,7 +966,7 @@ public: #endif /** - * @brief Update Notification Timer by uid + * @brief Update Notification Timer by uid. * * @param uid uid. * @return Returns Update result. diff --git a/frameworks/core/include/ans_manager_stub.h b/frameworks/core/include/ans_manager_stub.h index c84bc06ba..0444b7ec2 100644 --- a/frameworks/core/include/ans_manager_stub.h +++ b/frameworks/core/include/ans_manager_stub.h @@ -968,7 +968,7 @@ public: #endif /** - * @brief Update Notification Timer by uid + * @brief Update Notification Timer by uid. * * @param uid uid. * @return Returns Update result. diff --git a/frameworks/core/include/ans_notification.h b/frameworks/core/include/ans_notification.h index 6b23f74ee..c2f881744 100644 --- a/frameworks/core/include/ans_notification.h +++ b/frameworks/core/include/ans_notification.h @@ -1204,6 +1204,11 @@ public: */ ErrCode GetDoNotDisturbProfile(int32_t id, sptr &profile); + /** + * @brief Ans service died, OnRemoteDied called. + */ + void OnServiceDied(); + /** * @brief Update Notification Timer by uid * @@ -1211,11 +1216,6 @@ public: * @return Returns Update result. */ ErrCode UpdateNotificationTimerByUid(const int32_t uid, const bool isPaused); - - /** - * @brief Ans service died, OnRemoteDied called. - */ - void OnServiceDied(); private: /** * @brief Gets Ans Manager proxy. diff --git a/frameworks/js/napi/src/manager/napi_local_live_view.cpp b/frameworks/js/napi/src/manager/napi_local_live_view.cpp index 6d5845d32..4ba18a5e6 100644 --- a/frameworks/js/napi/src/manager/napi_local_live_view.cpp +++ b/frameworks/js/napi/src/manager/napi_local_live_view.cpp @@ -171,6 +171,7 @@ napi_value NapiTriggerLocalLiveView(napi_env env, napi_callback_info info) if (ParseTriggerParameters(env, info, asynccallbackinfo, callback) == nullptr) { Common::NapiThrow(env, ERROR_PARAM_INVALID); + delete asynccallbackinfo; return Common::NapiGetUndefined(env); } diff --git a/frameworks/js/napi/src/subscribe.cpp b/frameworks/js/napi/src/subscribe.cpp index 3b40214c6..7b2479840 100644 --- a/frameworks/js/napi/src/subscribe.cpp +++ b/frameworks/js/napi/src/subscribe.cpp @@ -15,6 +15,7 @@ #include "subscribe.h" #include "ans_inner_errors.h" +#include "inner_event.h" #include #include @@ -22,6 +23,7 @@ namespace OHOS { namespace NotificationNapi { const int32_t SUBSRIBE_MAX_PARA = 3; const int32_t NO_DELETE_REASON = -1; + const std::string CONSUME = "onConsume"; const std::string CANCEL = "onCancel"; const std::string UPDATE = "onUpdate"; @@ -1360,6 +1362,7 @@ bool DelSubscriberInstancesInfo(const napi_env &env, const std::shared_ptr &subscriber, napi_ref &callback) { diff --git a/services/ans/include/advanced_notification_service.h b/services/ans/include/advanced_notification_service.h index 9a55f742f..1a91c366d 100644 --- a/services/ans/include/advanced_notification_service.h +++ b/services/ans/include/advanced_notification_service.h @@ -1149,8 +1149,6 @@ public: */ bool AllowUseReminder(const std::string& bundleName); - void ResetDistributedEnabled(); - /** * @brief Get do not disturb profile by id. * @@ -1164,6 +1162,8 @@ public: int32_t OnRestore(MessageParcel& data, MessageParcel& reply); + void ResetDistributedEnabled(); + /** * @brief Update notification timer by uid * @@ -1436,10 +1436,11 @@ private: ErrCode ExcuteDelete(const std::string &key, const int32_t removeReason); ErrCode CheckNeedSilent(const std::string &phoneNumber, int32_t callerType, int32_t userId); uint32_t GetDefaultSlotFlags(const sptr &request); - ErrCode OnRecoverLiveView(const std::vector &keys); bool IsSystemUser(int32_t userId); ErrCode UpdateFlowCtrl(const std::shared_ptr &record); ErrCode PublishFlowControlInner(const std::shared_ptr &record); + + ErrCode OnRecoverLiveView(const std::vector &keys); void HandleUpdateLiveViewNotificationTimer(const int32_t uid, const bool isPaused); private: static sptr instance_; diff --git a/services/ans/src/advanced_notification_live_view_service.cpp b/services/ans/src/advanced_notification_live_view_service.cpp index 2e4ee8fae..a992adeab 100644 --- a/services/ans/src/advanced_notification_live_view_service.cpp +++ b/services/ans/src/advanced_notification_live_view_service.cpp @@ -81,11 +81,6 @@ void AdvancedNotificationService::RecoverLiveViewFromDb(int32_t userId) continue; } - if (FlowControl(record) != ERR_OK) { - ANS_LOGE("Flow control failed."); - continue; - } - // Turn off ringtone and vibration during recovery process auto notificationFlags = record->request->GetFlags(); notificationFlags->SetSoundEnabled(NotificationConstant::FlagStatus::CLOSE); @@ -365,6 +360,10 @@ int32_t AdvancedNotificationService::GetBatchNotificationRequestsFromDb( return static_cast(errorCode); } } + if (decryptValue.empty() || !nlohmann::json::accept(decryptValue)) { + ANS_LOGE("Invalid json"); + continue; + } auto jsonObject = nlohmann::json::parse(decryptValue); auto *request = NotificationJsonConverter::ConvertFromJson(jsonObject); if (request == nullptr) { @@ -719,6 +718,8 @@ void AdvancedNotificationService::UpdateRecordByOwner( } StartFinishTimerForUpdate(record, process); timerId = record->notification->GetFinishTimer(); + ANS_LOGI("TimerForUpdate,oldTimeId:%{public}d,newTimeId:%{public}d", + (int)(oldRecord->notification->GetFinishTimer()), (int)timerId); } record->notification = new (std::nothrow) Notification(record->request); if (record->notification == nullptr) { diff --git a/services/ans/src/advanced_notification_service_ability.cpp b/services/ans/src/advanced_notification_service_ability.cpp index a6478684b..e02fe5b70 100644 --- a/services/ans/src/advanced_notification_service_ability.cpp +++ b/services/ans/src/advanced_notification_service_ability.cpp @@ -95,11 +95,13 @@ void AdvancedNotificationServiceAbility::OnAddSystemAbility(int32_t systemAbilit } EventFwk::CommonEventManager::SubscribeCommonEvent(subscriber_); } else if (systemAbilityId == BUNDLE_MGR_SERVICE_SYS_ABILITY_ID) { + ANS_LOGW("BUNDLE_MGR_SERVICE_SYS_ABILITY_ID"); if (isDatashaReready_) { return; } auto notificationService = AdvancedNotificationService::GetInstance(); if (notificationService == nullptr) { + ANS_LOGW("notification service is not initial."); return; } notificationService->ResetDistributedEnabled(); diff --git a/services/ans/src/advanced_notification_utils.cpp b/services/ans/src/advanced_notification_utils.cpp index 22f669fc1..ff581aa3d 100644 --- a/services/ans/src/advanced_notification_utils.cpp +++ b/services/ans/src/advanced_notification_utils.cpp @@ -1777,6 +1777,7 @@ uint64_t AdvancedNotificationService::StartAutoDelete(const std::shared_ptr wThis = this; auto triggerFunc = [wThis, record, reason, deleteTimePoint] { sptr sThis = wThis.promote(); @@ -2041,11 +2042,6 @@ ErrCode AdvancedNotificationService::OnRecoverLiveView( { ANS_LOGD("enter"); - if (notificationSvrQueue_ == nullptr) { - ANS_LOGE("NotificationSvrQueue is nullptr."); - return ERR_ANS_INVALID_PARAM; - } - std::vector> notifications; int32_t removeReason = NotificationConstant::RECOVER_LIVE_VIEW_DELETE; std::vector timerIds; diff --git a/services/ans/src/common/notification_config_parse.cpp b/services/ans/src/common/notification_config_parse.cpp index af14a94fe..0274bccc6 100644 --- a/services/ans/src/common/notification_config_parse.cpp +++ b/services/ans/src/common/notification_config_parse.cpp @@ -18,8 +18,8 @@ #include "notification_config_parse.h" #include "ans_log_wrapper.h" -#include "notification_slot.h" #include "notification_trust_list.h" +#include "notification_slot.h" #include "file_utils.h" namespace OHOS { diff --git a/services/ans/src/notification_preferences.cpp b/services/ans/src/notification_preferences.cpp index e40736e29..13ee4a43a 100644 --- a/services/ans/src/notification_preferences.cpp +++ b/services/ans/src/notification_preferences.cpp @@ -321,6 +321,14 @@ ErrCode NotificationPreferences::GetNotificationSlotFlagsForBundle( return GetBundleProperty(bundleOption, BundleType::BUNDLE_SLOTFLGS_TYPE, slotFlags); } +bool NotificationPreferences::IsNotificationSlotFlagsExists( + const sptr &bundleOption) +{ + if (bundleOption == nullptr || bundleOption->GetBundleName().empty()) { + return false; + } + return preferncesDB_->IsNotificationSlotFlagsExists(bundleOption); +} ErrCode NotificationPreferences::SetNotificationSlotFlagsForBundle( const sptr &bundleOption, uint32_t slotFlags) @@ -574,15 +582,6 @@ ErrCode NotificationPreferences::AddDoNotDisturbProfiles( return ERR_OK; } -bool NotificationPreferences::IsNotificationSlotFlagsExists( - const sptr &bundleOption) -{ - if (bundleOption == nullptr || bundleOption->GetBundleName().empty()) { - return false; - } - return preferncesDB_->IsNotificationSlotFlagsExists(bundleOption); -} - bool NotificationPreferences::GetBundleInfo(NotificationPreferencesInfo &preferencesInfo, const sptr &bundleOption, NotificationPreferencesInfo::BundleInfo &info) const { diff --git a/services/ans/src/notification_preferences_database.cpp b/services/ans/src/notification_preferences_database.cpp index 3e1cdcb4d..20e0c68d4 100644 --- a/services/ans/src/notification_preferences_database.cpp +++ b/services/ans/src/notification_preferences_database.cpp @@ -313,20 +313,6 @@ bool NotificationPreferencesDatabase::PutBundlePropertyToDisturbeDB( return result; } -bool NotificationPreferencesDatabase::IsNotificationSlotFlagsExists(const sptr &bundleOption) -{ - if (bundleOption == nullptr || bundleOption->GetBundleName().empty()) { - return false; - } - std::string bundleKey = bundleOption->GetBundleName().append(std::to_string(bundleOption->GetUid())); - std::string key = GenerateBundleKey(bundleKey, KEY_BUNDLE_SLOTFLGS_TYPE); - std::string value; - int32_t userId = -1; - OsAccountManagerHelper::GetInstance().GetOsAccountLocalIdFromUid(bundleOption->GetUid(), userId); - int32_t result = rdbDataManager_->QueryData(key, value, userId); - return (result == NativeRdb::E_OK) || (!value.empty()); -} - bool NotificationPreferencesDatabase::PutShowBadge( const NotificationPreferencesInfo::BundleInfo &bundleInfo, const bool &enable) { @@ -449,6 +435,20 @@ bool NotificationPreferencesDatabase::PutHasPoppedDialog( return (result == NativeRdb::E_OK); } +bool NotificationPreferencesDatabase::IsNotificationSlotFlagsExists(const sptr &bundleOption) +{ + if (bundleOption == nullptr || bundleOption->GetBundleName().empty()) { + return false; + } + std::string bundleKey = bundleOption->GetBundleName().append(std::to_string(bundleOption->GetUid())); + std::string key = GenerateBundleKey(bundleKey, KEY_BUNDLE_SLOTFLGS_TYPE); + std::string value; + int32_t userId = -1; + OsAccountManagerHelper::GetInstance().GetOsAccountLocalIdFromUid(bundleOption->GetUid(), userId); + int32_t result = rdbDataManager_->QueryData(key, value, userId); + return (result == NativeRdb::E_OK) || (!value.empty()); +} + bool NotificationPreferencesDatabase::PutDoNotDisturbDate( const int32_t &userId, const sptr &date) { @@ -1221,7 +1221,7 @@ int32_t NotificationPreferencesDatabase::StringToInt(const std::string &str) con { int32_t value = 0; if (!str.empty()) { - value = stoi(str, nullptr); + value = atoi(str.c_str()); } return value; } @@ -1230,7 +1230,7 @@ int64_t NotificationPreferencesDatabase::StringToInt64(const std::string &str) c { int64_t value = 0; if (!str.empty()) { - value = stoll(str, nullptr); + value = atoll(str.c_str()); } return value; } diff --git a/services/ans/src/system_event_observer.cpp b/services/ans/src/system_event_observer.cpp index dedd0a1e7..bf740a9c8 100644 --- a/services/ans/src/system_event_observer.cpp +++ b/services/ans/src/system_event_observer.cpp @@ -64,11 +64,11 @@ sptr SystemEventObserver::GetBundleOption(AAFwk::Want int32_t appIndex = want.GetIntParam("appIndex", -1); int32_t uid = want.GetIntParam(AppExecFwk::Constants::UID, -1); sptr bundleOption = new (std::nothrow) NotificationBundleOption(bundleName, uid); - bundleOption->SetAppIndex(appIndex); if (bundleOption == nullptr) { ANS_LOGE("Failed to create bundleOption."); return nullptr; } + bundleOption->SetAppIndex(appIndex); return bundleOption; } @@ -79,11 +79,11 @@ sptr SystemEventObserver::GetBundleOptionDataCleared(A int32_t appIndex = want.GetIntParam("appIndex", -1); int32_t uid = want.GetIntParam("ohos.aafwk.param.targetUid", -1); sptr bundleOption = new (std::nothrow) NotificationBundleOption(bundleName, uid); - bundleOption->SetAppIndex(appIndex); if (bundleOption == nullptr) { ANS_LOGE("Failed to create bundleOption."); return nullptr; } + bundleOption->SetAppIndex(appIndex); return bundleOption; } -- Gitee From a6b26d490dd8008d2c16bb917355e5ce7060cb0a Mon Sep 17 00:00:00 2001 From: luojingsong Date: Wed, 6 Nov 2024 11:23:37 +0800 Subject: [PATCH 159/167] =?UTF-8?q?=E5=AD=97=E8=8A=82=E9=95=BF=E5=BA=A6?= =?UTF-8?q?=E8=B0=83=E6=95=B4?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: luojingsong Change-Id: Ia6c20fd52dfd31e5aaaa94551a275eeb9eab0e99 --- .../src/notification_long_text_content.cpp | 2 +- frameworks/js/napi/include/common.h | 2 + .../js/napi/src/common_convert_content.cpp | 110 +++++++++--------- 3 files changed, 59 insertions(+), 55 deletions(-) diff --git a/frameworks/ans/src/notification_long_text_content.cpp b/frameworks/ans/src/notification_long_text_content.cpp index 72f693110..8efbac17e 100644 --- a/frameworks/ans/src/notification_long_text_content.cpp +++ b/frameworks/ans/src/notification_long_text_content.cpp @@ -25,7 +25,7 @@ namespace OHOS { namespace Notification { -const std::size_t NotificationLongTextContent::MAX_LONGTEXT_LENGTH {1024}; +const std::size_t NotificationLongTextContent::MAX_LONGTEXT_LENGTH {3072}; NotificationLongTextContent::NotificationLongTextContent(const std::string &longText) { diff --git a/frameworks/js/napi/include/common.h b/frameworks/js/napi/include/common.h index 62bdabf81..4ee85a84c 100644 --- a/frameworks/js/napi/include/common.h +++ b/frameworks/js/napi/include/common.h @@ -33,6 +33,8 @@ constexpr int32_t STR_MAX_SIZE = 204; constexpr int32_t LONG_STR_MAX_SIZE = 1028; constexpr uint8_t OPERATION_MAX_TYPE = 3; constexpr int32_t LONG_LONG_STR_MAX_SIZE = 25600; +constexpr int32_t COMMON_TEXT_SIZE = 3074; +constexpr int32_t SHORT_TEXT_SIZE = 1026; constexpr int8_t NO_ERROR = 0; constexpr int8_t ERROR = -1; constexpr uint8_t PARAM0 = 0; diff --git a/frameworks/js/napi/src/common_convert_content.cpp b/frameworks/js/napi/src/common_convert_content.cpp index d6dcc0436..43edd2bf4 100644 --- a/frameworks/js/napi/src/common_convert_content.cpp +++ b/frameworks/js/napi/src/common_convert_content.cpp @@ -544,7 +544,8 @@ napi_value Common::GetNotificationBasicContentDetailed( ANS_LOGD("enter"); bool hasProperty = false; - char str[STR_MAX_SIZE] = {0}; + char commonStr[COMMON_TEXT_SIZE] = {0}; + char shortStr[SHORT_TEXT_SIZE] = {0}; size_t strLen = 0; // title: string @@ -553,13 +554,13 @@ napi_value Common::GetNotificationBasicContentDetailed( ANS_LOGE("Failed to get title from js."); return nullptr; } - NAPI_CALL(env, napi_get_value_string_utf8(env, value, str, STR_MAX_SIZE - 1, &strLen)); - if (std::strlen(str) == 0) { + NAPI_CALL(env, napi_get_value_string_utf8(env, value, shortStr, SHORT_TEXT_SIZE - 1, &strLen)); + if (std::strlen(shortStr) == 0) { ANS_LOGE("Property title is empty"); return nullptr; } - basicContent->SetTitle(str); - ANS_LOGD("normal::title = %{public}s", str); + basicContent->SetTitle(shortStr); + ANS_LOGD("normal::title = %{public}s", shortStr); // text: string value = AppExecFwk::GetPropertyValueByPropertyName(env, contentResult, "text", napi_string); @@ -567,13 +568,13 @@ napi_value Common::GetNotificationBasicContentDetailed( ANS_LOGE("Failed to get text from js."); return nullptr; } - NAPI_CALL(env, napi_get_value_string_utf8(env, value, str, STR_MAX_SIZE - 1, &strLen)); - if (std::strlen(str) == 0) { + NAPI_CALL(env, napi_get_value_string_utf8(env, value, commonStr, COMMON_TEXT_SIZE - 1, &strLen)); + if (std::strlen(commonStr) == 0) { ANS_LOGE("Property text is empty"); return nullptr; } - basicContent->SetText(str); - ANS_LOGD("normal::text = %{public}s", str); + basicContent->SetText(commonStr); + ANS_LOGD("normal::text = %{public}s", commonStr); // additionalText?: string NAPI_CALL(env, napi_has_named_property(env, contentResult, "additionalText", &hasProperty)); @@ -583,9 +584,9 @@ napi_value Common::GetNotificationBasicContentDetailed( ANS_LOGE("Failed to get additionalText from js."); return nullptr; } - NAPI_CALL(env, napi_get_value_string_utf8(env, value, str, STR_MAX_SIZE - 1, &strLen)); - basicContent->SetAdditionalText(str); - ANS_LOGD("normal::additionalText = %{public}s", str); + NAPI_CALL(env, napi_get_value_string_utf8(env, value, commonStr, COMMON_TEXT_SIZE - 1, &strLen)); + basicContent->SetAdditionalText(commonStr); + ANS_LOGD("normal::additionalText = %{public}s", commonStr); } // lockScreenPicture?: pixelMap @@ -639,8 +640,8 @@ napi_value Common::GetNotificationLongTextContentDetailed( 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}; + char commonStr[COMMON_TEXT_SIZE] = {0}; + char shortStr[SHORT_TEXT_SIZE] = {0}; size_t strLen = 0; if (GetNotificationBasicContentDetailed(env, contentResult, longContent) == nullptr) { @@ -659,13 +660,13 @@ napi_value Common::GetNotificationLongTextContentDetailed( ANS_LOGE("Wrong argument type. String expected."); return nullptr; } - NAPI_CALL(env, napi_get_value_string_utf8(env, longContentResult, long_str, LONG_STR_MAX_SIZE, &strLen)); - if (std::strlen(long_str) == 0) { + NAPI_CALL(env, napi_get_value_string_utf8(env, longContentResult, commonStr, COMMON_TEXT_SIZE-1, &strLen)); + if (std::strlen(commonStr) == 0) { ANS_LOGE("Property longText is empty"); return nullptr; } - longContent->SetLongText(long_str); - ANS_LOGD("longText::longText = %{public}s", long_str); + longContent->SetLongText(commonStr); + ANS_LOGD("longText::longText = %{public}s", commonStr); // briefText: string NAPI_CALL(env, napi_has_named_property(env, contentResult, "briefText", &hasProperty)); @@ -679,13 +680,13 @@ napi_value Common::GetNotificationLongTextContentDetailed( ANS_LOGE("Wrong argument type. String expected."); return nullptr; } - NAPI_CALL(env, napi_get_value_string_utf8(env, longContentResult, str, STR_MAX_SIZE - 1, &strLen)); - if (std::strlen(str) == 0) { + NAPI_CALL(env, napi_get_value_string_utf8(env, longContentResult, shortStr, SHORT_TEXT_SIZE - 1, &strLen)); + if (std::strlen(shortStr) == 0) { ANS_LOGE("Property briefText is empty"); return nullptr; } - longContent->SetBriefText(str); - ANS_LOGD("longText::briefText = %{public}s", str); + longContent->SetBriefText(shortStr); + ANS_LOGD("longText::briefText = %{public}s", shortStr); // expandedTitle: string NAPI_CALL(env, napi_has_named_property(env, contentResult, "expandedTitle", &hasProperty)); @@ -699,13 +700,13 @@ napi_value Common::GetNotificationLongTextContentDetailed( ANS_LOGE("Wrong argument type. String expected."); return nullptr; } - NAPI_CALL(env, napi_get_value_string_utf8(env, longContentResult, str, STR_MAX_SIZE - 1, &strLen)); - if (std::strlen(str) == 0) { + NAPI_CALL(env, napi_get_value_string_utf8(env, longContentResult, shortStr, SHORT_TEXT_SIZE - 1, &strLen)); + if (std::strlen(shortStr) == 0) { ANS_LOGE("Property expandedTitle is empty"); return nullptr; } - longContent->SetExpandedTitle(str); - ANS_LOGD("longText::expandedTitle = %{public}s", str); + longContent->SetExpandedTitle(shortStr); + ANS_LOGD("longText::expandedTitle = %{public}s", shortStr); return NapiGetNull(env); } @@ -754,7 +755,7 @@ napi_value Common::GetNotificationPictureContentDetailed(const napi_env &env, napi_valuetype valuetype = napi_undefined; napi_value pictureContentResult = nullptr; bool hasProperty = false; - char str[STR_MAX_SIZE] = {0}; + char shortStr[SHORT_TEXT_SIZE] = {0}; size_t strLen = 0; if (GetNotificationBasicContentDetailed(env, contentResult, pictureContent) == nullptr) { @@ -773,12 +774,12 @@ napi_value Common::GetNotificationPictureContentDetailed(const napi_env &env, ANS_LOGE("Wrong argument type. String expected."); return nullptr; } - NAPI_CALL(env, napi_get_value_string_utf8(env, pictureContentResult, str, STR_MAX_SIZE - 1, &strLen)); - if (std::strlen(str) == 0) { + NAPI_CALL(env, napi_get_value_string_utf8(env, pictureContentResult, shortStr, SHORT_TEXT_SIZE - 1, &strLen)); + if (std::strlen(shortStr) == 0) { ANS_LOGE("Property briefText is empty"); return nullptr; } - pictureContent->SetBriefText(str); + pictureContent->SetBriefText(shortStr); // expandedTitle: string NAPI_CALL(env, napi_has_named_property(env, contentResult, "expandedTitle", &hasProperty)); @@ -792,12 +793,12 @@ napi_value Common::GetNotificationPictureContentDetailed(const napi_env &env, ANS_LOGE("Wrong argument type. String expected."); return nullptr; } - NAPI_CALL(env, napi_get_value_string_utf8(env, pictureContentResult, str, STR_MAX_SIZE - 1, &strLen)); - if (std::strlen(str) == 0) { + NAPI_CALL(env, napi_get_value_string_utf8(env, pictureContentResult, shortStr, SHORT_TEXT_SIZE - 1, &strLen)); + if (std::strlen(shortStr) == 0) { ANS_LOGE("Property expandedTitle is empty"); return nullptr; } - pictureContent->SetExpandedTitle(str); + pictureContent->SetExpandedTitle(shortStr); // picture: image.PixelMap NAPI_CALL(env, napi_has_named_property(env, contentResult, "picture", &hasProperty)); @@ -1065,7 +1066,7 @@ napi_value Common::GetNotificationConversationalContentTitle( napi_valuetype valuetype = napi_undefined; napi_value conversationalContentResult = nullptr; bool hasProperty = false; - char str[STR_MAX_SIZE] = {0}; + char shortStr[SHORT_TEXT_SIZE] = {0}; size_t strLen = 0; // conversationTitle: string @@ -1080,9 +1081,10 @@ napi_value Common::GetNotificationConversationalContentTitle( ANS_LOGE("Wrong argument type. String expected."); return nullptr; } - NAPI_CALL(env, napi_get_value_string_utf8(env, conversationalContentResult, str, STR_MAX_SIZE - 1, &strLen)); - conversationalContent->SetConversationTitle(str); - ANS_LOGD("conversationTitle = %{public}s", str); + NAPI_CALL(env, napi_get_value_string_utf8( + env, conversationalContentResult, shortStr, SHORT_TEXT_SIZE - 1, &strLen)); + conversationalContent->SetConversationTitle(shortStr); + ANS_LOGD("conversationTitle = %{public}s", shortStr); return NapiGetNull(env); } @@ -1183,7 +1185,7 @@ napi_value Common::GetConversationalMessageBasicInfo(const napi_env &env, const napi_valuetype valuetype = napi_undefined; bool hasProperty = false; - char str[STR_MAX_SIZE] = {0}; + char commonStr[COMMON_TEXT_SIZE] = {0}; size_t strLen = 0; std::string text; int64_t timestamp = 0; @@ -1202,9 +1204,9 @@ napi_value Common::GetConversationalMessageBasicInfo(const napi_env &env, const ANS_LOGE("Wrong argument type. String expected."); return nullptr; } - 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); + NAPI_CALL(env, napi_get_value_string_utf8(env, textResult, commonStr, COMMON_TEXT_SIZE - 1, &strLen)); + text = commonStr; + ANS_LOGI("conversationalMessage::text = %{public}s", commonStr); // timestamp: number NAPI_CALL(env, napi_has_named_property(env, conversationalMessage, "timestamp", &hasProperty)); @@ -1306,7 +1308,7 @@ napi_value Common::GetNotificationMultiLineContent( napi_value contentResult = nullptr; napi_value multiLineContentResult = nullptr; bool hasProperty = false; - char str[STR_MAX_SIZE] = {0}; + char shortStr[SHORT_TEXT_SIZE] = {0}; size_t strLen = 0; NAPI_CALL(env, napi_has_named_property(env, result, "multiLine", &hasProperty)); @@ -1344,13 +1346,13 @@ napi_value Common::GetNotificationMultiLineContent( ANS_LOGE("Wrong argument type. String expected."); return nullptr; } - NAPI_CALL(env, napi_get_value_string_utf8(env, multiLineContentResult, str, STR_MAX_SIZE - 1, &strLen)); - if (std::strlen(str) == 0) { + NAPI_CALL(env, napi_get_value_string_utf8(env, multiLineContentResult, shortStr, SHORT_TEXT_SIZE - 1, &strLen)); + if (std::strlen(shortStr) == 0) { ANS_LOGE("Property briefText is empty"); return nullptr; } - multiLineContent->SetBriefText(str); - ANS_LOGD("multiLine: briefText = %{public}s", str); + multiLineContent->SetBriefText(shortStr); + ANS_LOGD("multiLine: briefText = %{public}s", shortStr); // longTitle: string NAPI_CALL(env, napi_has_named_property(env, contentResult, "longTitle", &hasProperty)); @@ -1364,13 +1366,13 @@ napi_value Common::GetNotificationMultiLineContent( ANS_LOGE("Wrong argument type. String expected."); return nullptr; } - NAPI_CALL(env, napi_get_value_string_utf8(env, multiLineContentResult, str, STR_MAX_SIZE - 1, &strLen)); - if (std::strlen(str) == 0) { + NAPI_CALL(env, napi_get_value_string_utf8(env, multiLineContentResult, shortStr, SHORT_TEXT_SIZE - 1, &strLen)); + if (std::strlen(shortStr) == 0) { ANS_LOGE("Property longTitle is empty"); return nullptr; } - multiLineContent->SetExpandedTitle(str); - ANS_LOGD("multiLine: longTitle = %{public}s", str); + multiLineContent->SetExpandedTitle(shortStr); + ANS_LOGD("multiLine: longTitle = %{public}s", shortStr); // lines: Array NAPI_CALL(env, napi_has_named_property(env, contentResult, "lines", &hasProperty)); @@ -1396,7 +1398,7 @@ napi_value Common::GetNotificationMultiLineContentLines(const napi_env &env, con bool isArray = false; napi_valuetype valuetype = napi_undefined; napi_value multilines = nullptr; - char str[STR_MAX_SIZE] = {0}; + char shortStr[SHORT_TEXT_SIZE] = {0}; size_t strLen = 0; uint32_t length = 0; @@ -1420,9 +1422,9 @@ napi_value Common::GetNotificationMultiLineContentLines(const napi_env &env, con ANS_LOGE("Wrong argument type. String expected."); return nullptr; } - NAPI_CALL(env, napi_get_value_string_utf8(env, line, str, STR_MAX_SIZE - 1, &strLen)); - multiLineContent->AddSingleLine(str); - ANS_LOGI("multiLine: lines : addSingleLine = %{public}s", str); + NAPI_CALL(env, napi_get_value_string_utf8(env, line, shortStr, SHORT_TEXT_SIZE - 1, &strLen)); + multiLineContent->AddSingleLine(shortStr); + ANS_LOGI("multiLine: lines : addSingleLine = %{public}s", shortStr); } return NapiGetNull(env); -- Gitee From 2e10de36a4d887e2d9e1634877ce1fcf9d5aeab3 Mon Sep 17 00:00:00 2001 From: gaojiaqi Date: Fri, 27 Dec 2024 16:54:49 +0800 Subject: [PATCH 160/167] update Signed-off-by: gaojiaqi --- services/ans/include/reminder_data_manager.h | 10 ++-- services/ans/src/reminder_data_manager.cpp | 47 +++++++++++++++---- .../ans/src/reminder_data_manager_inner.cpp | 27 +++++++++++ .../unittest/reminder_data_manager_test.cpp | 4 +- .../reminderdatamanager_fuzzer.cpp | 2 +- 5 files changed, 75 insertions(+), 15 deletions(-) diff --git a/services/ans/include/reminder_data_manager.h b/services/ans/include/reminder_data_manager.h index 50b3eea4b..f7c92ee80 100644 --- a/services/ans/include/reminder_data_manager.h +++ b/services/ans/include/reminder_data_manager.h @@ -434,7 +434,7 @@ private: sptr GetRecentReminderLocked(); void HandleImmediatelyShow(std::vector> &showImmediately, bool isSysTimeChanged); - void HandleExtensionReminder(std::vector> &extensionReminders); + void HandleExtensionReminder(std::vector> &extensionReminders, const int8_t type); /** * @brief Refresh the reminder due to date/time or timeZone change by user. @@ -538,8 +538,9 @@ private: void SetAlertingReminder(const sptr &reminder); void ShowActiveReminderExtendLocked(sptr &reminder, std::vector>& extensionReminders); - static bool StartExtensionAbility(const sptr &reminder); - static void AsyncStartExtensionAbility(const sptr &reminder, int32_t times); + static bool StartExtensionAbility(const sptr &reminder, const int8_t type); + static void AsyncStartExtensionAbility(const sptr &reminder, + int32_t times, const int8_t type); void InitServiceHandler(); /** * @brief Show the reminder on SystemUI. @@ -666,6 +667,9 @@ private: ErrCode PublishNotificationRequest(sptr& request, const sptr& bundleOption); + bool CheckShowLimit(std::unordered_map& limits, int32_t& totalCount, + sptr& reminder); + /** * Single instance. */ diff --git a/services/ans/src/reminder_data_manager.cpp b/services/ans/src/reminder_data_manager.cpp index 779e9dc56..4bf214faa 100644 --- a/services/ans/src/reminder_data_manager.cpp +++ b/services/ans/src/reminder_data_manager.cpp @@ -62,6 +62,8 @@ const int REASON_APP_API = 1; const int INDEX_KEY = 0; const int INDEX_TYPE = 1; const int INDEX_VALUE = 2; +constexpr int8_t NORMAL_CALLBACK = 0; // timer callback +constexpr int8_t REISSUE_CALLBACK = 1; // time change, boot complte callback } /** @@ -766,7 +768,7 @@ void ReminderDataManager::RefreshRemindersDueToSysTimeChange(uint8_t type) std::vector> extensionReminders; RefreshRemindersLocked(type, showImmediately, extensionReminders); HandleImmediatelyShow(showImmediately, true); - HandleExtensionReminder(extensionReminders); + HandleExtensionReminder(extensionReminders, REISSUE_CALLBACK); StartRecentReminder(); } @@ -911,7 +913,7 @@ void ReminderDataManager::ShowActiveReminder(const EventFwk::Want &want) } std::vector> extensionReminders; ShowActiveReminderExtendLocked(reminder, extensionReminders); - HandleExtensionReminder(extensionReminders); + HandleExtensionReminder(extensionReminders, NORMAL_CALLBACK); StartRecentReminder(); } @@ -957,6 +959,8 @@ void ReminderDataManager::ShowActiveReminderExtendLocked(sptr& uint64_t triggerTime = reminder->GetTriggerTimeInMilli(); bool isAlerting = false; sptr playSoundReminder = nullptr; + std::unordered_map limits; + int32_t totalCount = 0; for (auto it = reminderVector_.begin(); it != reminderVector_.end(); ++it) { if ((*it)->IsExpired()) { continue; @@ -977,6 +981,11 @@ void ReminderDataManager::ShowActiveReminderExtendLocked(sptr& ANSR_LOGI("reminder[%{public}d] trigger time is in exclude date", (*it)->GetReminderId()); continue; } + if (!CheckShowLimit(limits, totalCount, (*it))) { + (*it)->OnShow(false, false, false); + store_->UpdateOrInsert((*it), (*it)->GetNotificationBundleOption()); + continue; + } if (((*it)->GetRingDuration() > 0) && !isAlerting) { playSoundReminder = (*it); isAlerting = true; @@ -989,7 +998,7 @@ void ReminderDataManager::ShowActiveReminderExtendLocked(sptr& } } -bool ReminderDataManager::StartExtensionAbility(const sptr &reminder) +bool ReminderDataManager::StartExtensionAbility(const sptr &reminder, const int8_t type) { ANSR_LOGD("StartExtensionAbility"); if (reminder->GetReminderType() == ReminderRequest::ReminderType::CALENDAR) { @@ -999,6 +1008,7 @@ bool ReminderDataManager::StartExtensionAbility(const sptr &rem AAFwk::Want want; want.SetElementName(wantInfo->pkgName, wantInfo->abilityName); want.SetParam(ReminderRequest::PARAM_REMINDER_ID, reminder->GetReminderId()); + want.SetParam("PULL_TYPE", type); int32_t result = IN_PROCESS_CALL( AAFwk::AbilityManagerClient::GetInstance()->StartExtensionAbility(want, nullptr)); if (result != ERR_OK) { @@ -1010,7 +1020,8 @@ bool ReminderDataManager::StartExtensionAbility(const sptr &rem return true; } -void ReminderDataManager::AsyncStartExtensionAbility(const sptr &reminder, int32_t times) +void ReminderDataManager::AsyncStartExtensionAbility(const sptr &reminder, int32_t times, + const int8_t type) { auto manager = ReminderDataManager::GetInstance(); if (manager == nullptr) { @@ -1026,12 +1037,14 @@ void ReminderDataManager::AsyncStartExtensionAbility(const sptr return; } times--; - bool ret = ReminderDataManager::StartExtensionAbility(reminder); + bool ret = ReminderDataManager::StartExtensionAbility(reminder, type); if (!ret && times > 0 && serviceQueue_ != nullptr) { ANSR_LOGD("StartExtensionAbilty failed, reminder times: %{public}d", times); ffrt::task_attr taskAttr; taskAttr.delay(CONNECT_EXTENSION_INTERVAL); - auto callback = [reminder, times]() { ReminderDataManager::AsyncStartExtensionAbility(reminder, times); }; + auto callback = [reminder, times, type]() { + ReminderDataManager::AsyncStartExtensionAbility(reminder, times, type); + }; serviceQueue_->submit(callback, taskAttr); } } @@ -1280,10 +1293,18 @@ void ReminderDataManager::HandleImmediatelyShow( std::vector> &showImmediately, bool isSysTimeChanged) { bool isAlerting = false; + std::unordered_map limits; + int32_t totalCount = 0; for (auto it = showImmediately.begin(); it != showImmediately.end(); ++it) { if ((*it)->IsShowing()) { continue; } + if (!CheckShowLimit(limits, totalCount, (*it))) { + std::lock_guard lock(ReminderDataManager::MUTEX); + (*it)->OnShow(false, isSysTimeChanged, false); + store_->UpdateOrInsert((*it), (*it)->GetNotificationBundleOption()); + continue; + } if (((*it)->GetRingDuration() > 0) && !isAlerting) { std::lock_guard lock(ReminderDataManager::MUTEX); ShowReminder((*it), true, false, isSysTimeChanged, true); @@ -1295,10 +1316,11 @@ void ReminderDataManager::HandleImmediatelyShow( } } -void ReminderDataManager::HandleExtensionReminder(std::vector>& extensionReminders) +void ReminderDataManager::HandleExtensionReminder(std::vector>& extensionReminders, + const int8_t type) { for (auto& reminder : extensionReminders) { - ReminderDataManager::AsyncStartExtensionAbility(reminder, CONNECT_EXTENSION_MAX_RETRY_TIMES); + ReminderDataManager::AsyncStartExtensionAbility(reminder, CONNECT_EXTENSION_MAX_RETRY_TIMES, type); } } @@ -1369,7 +1391,7 @@ void ReminderDataManager::Init(bool isFromBootComplete) std::vector> extensionReminders; CheckReminderTime(immediatelyReminders, extensionReminders); HandleImmediatelyShow(immediatelyReminders, false); - HandleExtensionReminder(extensionReminders); + HandleExtensionReminder(extensionReminders, REISSUE_CALLBACK); StartRecentReminder(); } if (IsReminderAgentReady()) { @@ -1613,6 +1635,13 @@ void ReminderDataManager::PlaySoundAndVibration(const sptr &rem } ANSR_LOGI("Play custom sound, reminderId:[%{public}d].", reminder->GetReminderId()); } + constexpr int32_t STREAM_ALARM = 4; + constexpr int32_t DEFAULT_VALUE = 0; // CONTENT_UNKNOWN + Media::Format format; + (void)format.PutIntValue(Media::PlayerKeys::CONTENT_TYPE, DEFAULT_VALUE); + (void)format.PutIntValue(Media::PlayerKeys::STREAM_USAGE, STREAM_ALARM); + (void)format.PutIntValue(Media::PlayerKeys::RENDERER_FLAG, DEFAULT_VALUE); + soundPlayer_->SetParameter(format); soundPlayer_->SetLooping(true); soundPlayer_->PrepareAsync(); soundPlayer_->Play(); diff --git a/services/ans/src/reminder_data_manager_inner.cpp b/services/ans/src/reminder_data_manager_inner.cpp index 46284fe3a..cef2dd13c 100644 --- a/services/ans/src/reminder_data_manager_inner.cpp +++ b/services/ans/src/reminder_data_manager_inner.cpp @@ -54,6 +54,10 @@ namespace OHOS { namespace Notification { namespace { constexpr int32_t ALL_SA_READY_FLAG = 2; // bundle service and ability service ready. +// The maximum number of applications that can be displayed at a time +constexpr int32_t ONE_HAP_MAX_NUMBER_SHOW_AT_ONCE = 10; +// The maximum number of system that can be displayed at a time +constexpr int32_t TOTAL_MAX_NUMBER_SHOW_AT_ONCE = 500; } bool ReminderDataManager::IsSystemReady() @@ -164,5 +168,28 @@ void ReminderDataManager::ReportSysEvent(const sptr& reminder) "RING_TIME", ringTime); #endif } + +bool ReminderDataManager::CheckShowLimit(std::unordered_map& limits, int32_t& totalCount, + sptr& reminder) +{ + if (totalCount > TOTAL_MAX_NUMBER_SHOW_AT_ONCE) { + ANSR_LOGW("The maximum number of displays that can be displayed at a time has been reached."); + return false; + } + ++totalCount; + std::string key = std::to_string(reminder->GetUid()) + "_" + std::to_string(reminder->GetTriggerTimeInMilli()); + auto iter = limits.find(key); + if (iter == limits.end()) { + limits[key] = 1; + return true; + } + if (iter->second > ONE_HAP_MAX_NUMBER_SHOW_AT_ONCE) { + ANSR_LOGW("The maximum number of displays that can be displayed in a single app[%{public}s] has been reached", + reminder->GetBundleName().c_str()); + return false; + } + ++iter->second; + return true; +} } } diff --git a/services/ans/test/unittest/reminder_data_manager_test.cpp b/services/ans/test/unittest/reminder_data_manager_test.cpp index 5ca3295b1..081af4ba6 100644 --- a/services/ans/test/unittest/reminder_data_manager_test.cpp +++ b/services/ans/test/unittest/reminder_data_manager_test.cpp @@ -614,13 +614,13 @@ HWTEST_F(ReminderDataManagerTest, ReminderEventManagerTest_004, Level1) HWTEST_F(ReminderDataManagerTest, StartExtensionAbilityTest_001, Level1) { auto reminder1 = new ReminderRequestCalendar(10); - bool ret1 = manager->StartExtensionAbility(reminder1); + bool ret1 = manager->StartExtensionAbility(reminder1, 0); EXPECT_TRUE(ret1); auto reminder2 = new ReminderRequestCalendar(10); auto wantInfo = std::make_shared(); reminder2->SetRRuleWantAgentInfo(wantInfo); - bool ret2 = manager->StartExtensionAbility(reminder2); + bool ret2 = manager->StartExtensionAbility(reminder2, 0); EXPECT_TRUE(ret2); } diff --git a/test/fuzztest/reminderdatamanager_fuzzer/reminderdatamanager_fuzzer.cpp b/test/fuzztest/reminderdatamanager_fuzzer/reminderdatamanager_fuzzer.cpp index e9fa30ab7..8d71f1190 100644 --- a/test/fuzztest/reminderdatamanager_fuzzer/reminderdatamanager_fuzzer.cpp +++ b/test/fuzztest/reminderdatamanager_fuzzer/reminderdatamanager_fuzzer.cpp @@ -117,7 +117,7 @@ namespace OHOS { manager->FindReminderRequestLocked(reminderId, bundleName); manager->GetRecentReminderLocked(); manager->HandleImmediatelyShow(immediatelyReminders, value); - manager->HandleExtensionReminder(extensionReminders); + manager->HandleExtensionReminder(extensionReminders, 0); manager->HandleSameNotificationIdShowing(reminder); manager->IsBelongToSameApp(option, option); manager->CheckIsSameApp(reminder, option); -- Gitee From 851ff65a0ca6beaefd5c5fe8d222ded53c211a31 Mon Sep 17 00:00:00 2001 From: gaojiaqi Date: Tue, 31 Dec 2024 18:01:15 +0800 Subject: [PATCH 161/167] fix ut Signed-off-by: gaojiaqi --- services/ans/test/unittest/reminder_data_manager_test.cpp | 1 + 1 file changed, 1 insertion(+) diff --git a/services/ans/test/unittest/reminder_data_manager_test.cpp b/services/ans/test/unittest/reminder_data_manager_test.cpp index 081af4ba6..543d00f2a 100644 --- a/services/ans/test/unittest/reminder_data_manager_test.cpp +++ b/services/ans/test/unittest/reminder_data_manager_test.cpp @@ -689,6 +689,7 @@ HWTEST_F(ReminderDataManagerTest, CheckPulishReminder_0001, Level1) */ HWTEST_F(ReminderDataManagerTest, OnLanguageChanged_0001, Level1) { + sleep(2); sptr reminder = new ReminderRequestTimer(10); reminder->SetReminderId(10); std::string title = "this is title"; -- Gitee From cb820beeb412bca17178cce7bb5c6b0b891ed283 Mon Sep 17 00:00:00 2001 From: MengYao Date: Tue, 3 Dec 2024 21:57:32 +0800 Subject: [PATCH 162/167] =?UTF-8?q?cherry=20pick=20f27179f=20from=20https:?= =?UTF-8?q?//gitee.com/guaguahanhan/notification=5Fdistributed=5Fnotificat?= =?UTF-8?q?ion=5Fservice/pulls/2473=20rdb=E9=80=82=E9=85=8D?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: MengYao --- .../notification_rdb_data_mgr_test.cpp | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/services/ans/test/unittest/notification_rdb_data_mgr_test/notification_rdb_data_mgr_test.cpp b/services/ans/test/unittest/notification_rdb_data_mgr_test/notification_rdb_data_mgr_test.cpp index 4f8469b7e..f1aa458be 100755 --- a/services/ans/test/unittest/notification_rdb_data_mgr_test/notification_rdb_data_mgr_test.cpp +++ b/services/ans/test/unittest/notification_rdb_data_mgr_test/notification_rdb_data_mgr_test.cpp @@ -127,7 +127,7 @@ class RdbStoreTest : public RdbStore { return nullptr; }; virtual std::shared_ptr QueryByStep( - const std::string &sql, const std::vector &bindArgs = {}) + const std::string &sql, const std::vector &bindArgs = {}, bool preCount = true) { return nullptr; }; @@ -185,7 +185,7 @@ class RdbStoreTest : public RdbStore { return nullptr; }; virtual std::shared_ptr QueryByStep( - const AbsRdbPredicates &predicates, const std::vector &columns) + const AbsRdbPredicates &predicates, const std::vector &columns, bool preCount = true) { return nullptr; }; -- Gitee From be9e73c0b48016cc0eabeecc697f848d84ee2e01 Mon Sep 17 00:00:00 2001 From: yangjun Date: Fri, 3 Jan 2025 11:34:13 +0800 Subject: [PATCH 163/167] =?UTF-8?q?=E6=B7=BB=E5=8A=A0=E5=BA=94=E7=94=A8?= =?UTF-8?q?=E7=BA=A7=E6=B5=81=E6=8E=A7?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: yangjun Change-Id: I0551bccd7a5a4a73a3a3e2a33ef48353a716433c Signed-off-by: yangjun --- .../core/common/include/ans_const_define.h | 7 +- services/ans/BUILD.gn | 1 + ...vanced_notification_flow_control_service.h | 81 ++++++ .../include/advanced_notification_service.h | 13 +- .../ans/include/notification_config_parse.h | 6 + ...nced_notification_flow_control_service.cpp | 274 ++++++++++++++++++ .../advanced_notification_publish_service.cpp | 19 +- .../ans/src/advanced_notification_service.cpp | 137 +-------- .../ans/src/advanced_notification_utils.cpp | 20 +- .../src/common/notification_config_parse.cpp | 37 +++ services/ans/test/unittest/BUILD.gn | 1 + ...notification_flow_control_service_test.cpp | 103 +++++++ .../advanced_notification_service_test.cpp | 10 +- 13 files changed, 551 insertions(+), 158 deletions(-) create mode 100644 services/ans/include/advanced_notification_flow_control_service.h create mode 100644 services/ans/src/advanced_notification_flow_control_service.cpp create mode 100644 services/ans/test/unittest/advanced_notification_flow_control_service_test.cpp diff --git a/frameworks/core/common/include/ans_const_define.h b/frameworks/core/common/include/ans_const_define.h index 24135987d..f58eea322 100644 --- a/frameworks/core/common/include/ans_const_define.h +++ b/frameworks/core/common/include/ans_const_define.h @@ -27,8 +27,11 @@ namespace Notification { // Max active notification number constexpr size_t MAX_ACTIVE_NUM = 1000; constexpr uint32_t MAX_ACTIVE_NUM_PERAPP = 100; -constexpr uint32_t MAX_ACTIVE_NUM_PERSECOND = 10; -constexpr uint32_t MAX_UPDATE_NUM_PERSECOND = 20; +constexpr uint32_t MAX_CREATE_NUM_PERSECOND = 15; +constexpr uint32_t MAX_UPDATE_NUM_PERSECOND = 30; +constexpr uint32_t MAX_CREATE_NUM_PERSECOND_PERAPP = 10; +constexpr uint32_t MAX_UPDATE_NUM_PERSECOND_PERAPP = 20; +constexpr std::chrono::seconds SINGLE_APP_FLOW_CONTRL_EXPIRE_TIME = std::chrono::seconds(1); constexpr size_t MAX_SLOT_NUM = 5; constexpr uint32_t MAX_ICON_SIZE = 192 * 1024; constexpr uint32_t MAX_PICTURE_SIZE = 2 * 1024 * 1024; diff --git a/services/ans/BUILD.gn b/services/ans/BUILD.gn index db7951874..9c2059a1a 100644 --- a/services/ans/BUILD.gn +++ b/services/ans/BUILD.gn @@ -51,6 +51,7 @@ ohos_shared_library("libans") { "src/advanced_datashare_observer.cpp", "src/advanced_notification_clone_service.cpp", "src/advanced_notification_event_service.cpp", + "src/advanced_notification_flow_control_service.cpp", "src/advanced_notification_inline.cpp", "src/advanced_notification_live_view_service.cpp", "src/advanced_notification_publish/base_publish_process.cpp", diff --git a/services/ans/include/advanced_notification_flow_control_service.h b/services/ans/include/advanced_notification_flow_control_service.h new file mode 100644 index 000000000..cb182f817 --- /dev/null +++ b/services/ans/include/advanced_notification_flow_control_service.h @@ -0,0 +1,81 @@ +/* + * Copyright (c) 2021-2024 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef BASE_NOTIFICATION_DISTRIBUTED_NOTIFICATION_SERVICE_SERVICES_ANS_INCLUDE_NOTIFICATION_FLOW_CONTROL_SERVICE_H +#define BASE_NOTIFICATION_DISTRIBUTED_NOTIFICATION_SERVICE_SERVICES_ANS_INCLUDE_NOTIFICATION_FLOW_CONTROL_SERVICE_H + +#include +#include +#include +#include + +#include "errors.h" +#include "singleton.h" +#include "ans_const_define.h" +#include "notification_record.h" + +namespace OHOS { +namespace Notification { +struct FlowControlThreshold { + uint32_t maxCreateNumPerSecond = MAX_CREATE_NUM_PERSECOND; + uint32_t maxUpdateNumPerSecond = MAX_UPDATE_NUM_PERSECOND; + uint32_t maxCreateNumPerSecondPerApp = MAX_CREATE_NUM_PERSECOND_PERAPP; + uint32_t maxUpdateNumPerSecondPerApp = MAX_UPDATE_NUM_PERSECOND_PERAPP; +}; + +class FlowControlService : public DelayedSingleton { +public: + FlowControlService(); + ErrCode FlowControl(const std::shared_ptr &record, + const int32_t callingUid, bool isNotificationExists); + +private: + ErrCode PublishFlowCtrl(const std::shared_ptr &record, const int32_t callingUid); + ErrCode PublishGlobalFlowCtrl(const std::shared_ptr &record, + std::chrono::system_clock::time_point now); + ErrCode PublishSingleAppFlowCtrl(const std::shared_ptr &record, + std::chrono::system_clock::time_point now, const int32_t callingUid); + void PublishRecordTimestamp(const std::shared_ptr &record, + std::chrono::system_clock::time_point now, const int32_t callingUid); + void PublishSingleAppFlowCtrlRemoveExpire(std::chrono::system_clock::time_point now); + + ErrCode UpdateFlowCtrl(const std::shared_ptr &record, const int32_t callingUid); + ErrCode UpdateGlobalFlowCtrl(const std::shared_ptr &record, + std::chrono::system_clock::time_point now); + ErrCode UpdateSingleAppFlowCtrl(const std::shared_ptr &record, + std::chrono::system_clock::time_point now, const int32_t callingUid); + void UpdateRecordTimestamp(const std::shared_ptr &record, + std::chrono::system_clock::time_point now, const int32_t callingUid); + void UpdateSingleAppFlowCtrlRemoveExpire(std::chrono::system_clock::time_point now); + +private: + static std::mutex flowControlMutex_; + std::list flowControlUpdateTimestampList_; + std::list flowControlPublishTimestampList_; + static std::mutex systemFlowControlMutex_; + std::list systemFlowControlUpdateTimestampList_; + std::list systemFlowControlPublishTimestampList_; + static std::mutex singleAppFlowControlMutex_; + std::map>> singleAppFlowControlUpdateTimestampMap_; + std::map>> singleAppFlowControlPublishTimestampMap_; + + FlowControlThreshold threshold_; +}; +} // namespace Notification +} // namespace OHOS + +#endif // BASE_NOTIFICATION_DISTRIBUTED_NOTIFICATION_SERVICE_SERVICES_ANS_INCLUDE_NOTIFICATION_FLOW_CONTROL_SERVICE_H \ No newline at end of file diff --git a/services/ans/include/advanced_notification_service.h b/services/ans/include/advanced_notification_service.h index 1a91c366d..36cab66f5 100644 --- a/services/ans/include/advanced_notification_service.h +++ b/services/ans/include/advanced_notification_service.h @@ -1240,8 +1240,7 @@ private: void SortNotificationList(); static bool NotificationCompare( const std::shared_ptr &first, const std::shared_ptr &second); - ErrCode FlowControl(const std::shared_ptr &record); - ErrCode PublishFlowControl(const std::shared_ptr &record); + ErrCode PublishInNotificationList(const std::shared_ptr &record); ErrCode RemoveNotificationBySlot(const sptr &bundleOption, const sptr &slot, const int reason); @@ -1437,8 +1436,6 @@ private: ErrCode CheckNeedSilent(const std::string &phoneNumber, int32_t callerType, int32_t userId); uint32_t GetDefaultSlotFlags(const sptr &request); bool IsSystemUser(int32_t userId); - ErrCode UpdateFlowCtrl(const std::shared_ptr &record); - ErrCode PublishFlowControlInner(const std::shared_ptr &record); ErrCode OnRecoverLiveView(const std::vector &keys); void HandleUpdateLiveViewNotificationTimer(const int32_t uid, const bool isPaused); @@ -1452,14 +1449,6 @@ private: std::shared_ptr runner_ = nullptr; std::shared_ptr handler_ = nullptr; std::list> notificationList_; - static std::mutex flowControlMutex_; - std::list flowControlTimestampList_; - std::list flowControlUpdateTimestampList_; - std::list flowControlPublishTimestampList_; - static std::mutex systemFlowControlMutex_; - std::list systemFlowControlTimestampList_; - std::list systemFlowControlUpdateTimestampList_; - std::list systemFlowControlPublishTimestampList_; std::shared_ptr recentInfo_ = nullptr; std::shared_ptr distributedKvStoreDeathRecipient_ = nullptr; std::shared_ptr systemEventObserver_ = nullptr; diff --git a/services/ans/include/notification_config_parse.h b/services/ans/include/notification_config_parse.h index 04c06d6e9..18d1bdc2c 100644 --- a/services/ans/include/notification_config_parse.h +++ b/services/ans/include/notification_config_parse.h @@ -28,6 +28,7 @@ #include "notification_bundle_option.h" #include "notification_constant.h" #include "notification_flags.h" +#include "advanced_notification_flow_control_service.h" namespace OHOS { namespace Notification { @@ -42,6 +43,7 @@ public: uint32_t GetConfigSlotReminderModeByType(NotificationConstant::SlotType slotType) const; uint32_t GetConfigSlotReminderModeByType(NotificationConstant::SlotType slotType, const sptr &bundleOption) const; + void GetFlowCtrlConfigFromCCM(FlowControlThreshold &threshold); private: std::map defaultCurrentSlotReminder_; @@ -53,6 +55,10 @@ public: constexpr static const char* CFG_KEY_NAME = "name"; constexpr static const char* CFG_KEY_REMINDER_FLAGS = "reminderFlags"; constexpr static const char* APP_PRIVILEGES = "appPrivileges"; + constexpr static const char* CFG_KEY_MAX_CREATE_NUM_PERSECOND = "MaxCreateNumPerSecond"; + constexpr static const char* CFG_KEY_MAX_UPDATE_NUM_PERSECOND = "MaxUpdateNumPerSecond"; + constexpr static const char* CFG_KEY_MAX_CREATE_NUM_PERSECOND_PERAPP = "MaxCreateNumPerSecondPerApp"; + constexpr static const char* CFG_KEY_MAX_UPDATE_NUM_PERSECOND_PERAPP = "MaxUpdateNumPerSecondPerApp"; #ifdef CONFIG_POLICY_ENABLE constexpr static const char* NOTIFICAITON_CONFIG_FILE = "etc/notification/notification_config.json"; # else diff --git a/services/ans/src/advanced_notification_flow_control_service.cpp b/services/ans/src/advanced_notification_flow_control_service.cpp new file mode 100644 index 000000000..79b23e060 --- /dev/null +++ b/services/ans/src/advanced_notification_flow_control_service.cpp @@ -0,0 +1,274 @@ +/* + * Copyright (c) 2021-2024 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "advanced_notification_flow_control_service.h" + +#include "ans_inner_errors.h" +#include "notification_config_parse.h" +#include "notification_analytics_util.h" + +namespace OHOS { +namespace Notification { +std::mutex FlowControlService::flowControlMutex_; +std::mutex FlowControlService::systemFlowControlMutex_; +std::mutex FlowControlService::singleAppFlowControlMutex_; + +FlowControlService::FlowControlService() +{ + DelayedSingleton::GetInstance()->GetFlowCtrlConfigFromCCM(threshold_); +} + +ErrCode FlowControlService::FlowControl(const std::shared_ptr &record, + const int32_t callingUid, bool isNotificationExists) +{ + if (record->isNeedFlowCtrl == false) { + return ERR_OK; + } + + ErrCode result = ERR_OK; + if (!isNotificationExists) { + result = PublishFlowCtrl(record, callingUid); + } else { + result = UpdateFlowCtrl(record, callingUid); + } + + return result; +} + +ErrCode FlowControlService::PublishFlowCtrl(const std::shared_ptr &record, + const int32_t callingUid) +{ + if (record->isNeedFlowCtrl == false) { + return ERR_OK; + } + std::chrono::system_clock::time_point now = std::chrono::system_clock::now(); + ErrCode result = ERR_OK; + result = PublishSingleAppFlowCtrl(record, now, callingUid); + if (result != ERR_OK) { + return result; + } + result = PublishGlobalFlowCtrl(record, now); + if (result != ERR_OK) { + return result; + } + PublishRecordTimestamp(record, now, callingUid); + PublishSingleAppFlowCtrlRemoveExpire(now); + return ERR_OK; +} + +ErrCode FlowControlService::PublishGlobalFlowCtrl(const std::shared_ptr &record, + std::chrono::system_clock::time_point now) +{ + ANS_LOGD("PublishGlobalFlowCtrl size %{public}zu,%{public}zu", + flowControlPublishTimestampList_.size(), systemFlowControlPublishTimestampList_.size()); + if (record->isThirdparty == true) { + // Third-part flow control + std::lock_guard lock(flowControlMutex_); + NotificationAnalyticsUtil::RemoveExpired(flowControlPublishTimestampList_, now); + if (flowControlPublishTimestampList_.size() >= threshold_.maxCreateNumPerSecond) { + ANS_LOGE("Third-part PublishGlobalFlowCtrl failed"); + HaMetaMessage message = HaMetaMessage(EventSceneId::SCENE_3, EventBranchId::BRANCH_2) + .ErrorCode(ERR_ANS_OVER_MAX_ACTIVE_PERSECOND).Message("Third-part PublishGlobalFlowCtrl failed"); + if (record != nullptr) { + NotificationAnalyticsUtil::ReportPublishFailedEvent(record->request, message); + } + return ERR_ANS_OVER_MAX_ACTIVE_PERSECOND; + } + } else { + // System flow control + std::lock_guard lock(systemFlowControlMutex_); + NotificationAnalyticsUtil::RemoveExpired(systemFlowControlPublishTimestampList_, now); + if (systemFlowControlPublishTimestampList_.size() >= threshold_.maxCreateNumPerSecond) { + ANS_LOGE("System PublishGlobalFlowCtrl failed"); + HaMetaMessage message = HaMetaMessage(EventSceneId::SCENE_3, EventBranchId::BRANCH_3) + .ErrorCode(ERR_ANS_OVER_MAX_ACTIVE_PERSECOND).Message("System PublishGlobalFlowCtrl failed"); + if (record != nullptr) { + NotificationAnalyticsUtil::ReportPublishFailedEvent(record->request, message); + } + return ERR_ANS_OVER_MAX_ACTIVE_PERSECOND; + } + } + return ERR_OK; +} + +ErrCode FlowControlService::PublishSingleAppFlowCtrl(const std::shared_ptr &record, + std::chrono::system_clock::time_point now, const int32_t callingUid) +{ + std::lock_guard lock(singleAppFlowControlMutex_); + auto singleAppFlowControlIter = singleAppFlowControlPublishTimestampMap_.find(callingUid); + if (singleAppFlowControlIter == singleAppFlowControlPublishTimestampMap_.end()) { + return ERR_OK; + } + NotificationAnalyticsUtil::RemoveExpired(*(singleAppFlowControlIter->second), now); + if (singleAppFlowControlIter->second->size() >= threshold_.maxCreateNumPerSecondPerApp) { + ANS_LOGE("SingleAppPublishFlowControl failed"); + HaMetaMessage message = HaMetaMessage(EventSceneId::SCENE_3, EventBranchId::BRANCH_4) + .ErrorCode(ERR_ANS_OVER_MAX_ACTIVE_PERSECOND).Message("SingleAppPublishFlowControl failed"); + if (record != nullptr) { + NotificationAnalyticsUtil::ReportPublishFailedEvent(record->request, message); + } + return ERR_ANS_OVER_MAX_ACTIVE_PERSECOND; + } + return ERR_OK; +} + +void FlowControlService::PublishRecordTimestamp(const std::shared_ptr &record, + std::chrono::system_clock::time_point now, const int32_t callingUid) +{ + if (record->isThirdparty == true) { + std::lock_guard lock(flowControlMutex_); + flowControlPublishTimestampList_.push_back(now); + } else { + std::lock_guard lock(systemFlowControlMutex_); + systemFlowControlPublishTimestampList_.push_back(now); + } + + std::lock_guard lock(singleAppFlowControlMutex_); + auto singleAppFlowControlIter = singleAppFlowControlPublishTimestampMap_.find(callingUid); + if (singleAppFlowControlIter == singleAppFlowControlPublishTimestampMap_.end()) { + singleAppFlowControlPublishTimestampMap_[callingUid] = + std::make_shared>(); + singleAppFlowControlIter = singleAppFlowControlPublishTimestampMap_.find(callingUid); + } + singleAppFlowControlIter->second->push_back(now); +} + +void FlowControlService::PublishSingleAppFlowCtrlRemoveExpire(std::chrono::system_clock::time_point now) +{ + std::lock_guard lock(singleAppFlowControlMutex_); + for (auto iter = singleAppFlowControlPublishTimestampMap_.begin(); + iter != singleAppFlowControlPublishTimestampMap_.end();) { + auto latest = iter->second->back(); + if (std::chrono::abs(now - latest) > SINGLE_APP_FLOW_CONTRL_EXPIRE_TIME) { + iter = singleAppFlowControlPublishTimestampMap_.erase(iter); + } else { + ++iter; + } + } +} + +ErrCode FlowControlService::UpdateFlowCtrl(const std::shared_ptr &record, + const int32_t callingUid) +{ + if (record->isNeedFlowCtrl == false) { + return ERR_OK; + } + std::chrono::system_clock::time_point now = std::chrono::system_clock::now(); + ErrCode result = ERR_OK; + result = UpdateSingleAppFlowCtrl(record, now, callingUid); + if (result != ERR_OK) { + return result; + } + result = UpdateGlobalFlowCtrl(record, now); + if (result != ERR_OK) { + return result; + } + UpdateRecordTimestamp(record, now, callingUid); + UpdateSingleAppFlowCtrlRemoveExpire(now); + return result; +} + +ErrCode FlowControlService::UpdateGlobalFlowCtrl(const std::shared_ptr &record, + std::chrono::system_clock::time_point now) +{ + ANS_LOGD("UpdateGlobalFlowCtrl size %{public}zu,%{public}zu", + flowControlUpdateTimestampList_.size(), systemFlowControlUpdateTimestampList_.size()); + if (record->isThirdparty == true) { + // Third-part flow control + std::lock_guard lock(flowControlMutex_); + NotificationAnalyticsUtil::RemoveExpired(flowControlUpdateTimestampList_, now); + if (flowControlUpdateTimestampList_.size() >= threshold_.maxUpdateNumPerSecond) { + ANS_LOGE("Third-part UpdateGlobalFlowCtrl failed"); + HaMetaMessage message = HaMetaMessage(EventSceneId::SCENE_4, EventBranchId::BRANCH_3) + .ErrorCode(ERR_ANS_OVER_MAX_UPDATE_PERSECOND).Message("Third-part updateGlobalFlowCtrl failed"); + if (record != nullptr) { + NotificationAnalyticsUtil::ReportPublishFailedEvent(record->request, message); + } + return ERR_ANS_OVER_MAX_UPDATE_PERSECOND; + } + } else { + // System flow control + std::lock_guard lock(systemFlowControlMutex_); + NotificationAnalyticsUtil::RemoveExpired(systemFlowControlUpdateTimestampList_, now); + if (systemFlowControlUpdateTimestampList_.size() >= threshold_.maxUpdateNumPerSecond) { + ANS_LOGE("System UpdateGlobalFlowCtrl failed"); + HaMetaMessage message = HaMetaMessage(EventSceneId::SCENE_4, EventBranchId::BRANCH_4) + .ErrorCode(ERR_ANS_OVER_MAX_UPDATE_PERSECOND).Message("System updateGlobalFlowCtrl failed"); + if (record != nullptr) { + NotificationAnalyticsUtil::ReportPublishFailedEvent(record->request, message); + } + return ERR_ANS_OVER_MAX_UPDATE_PERSECOND; + } + } + return ERR_OK; +} + +ErrCode FlowControlService::UpdateSingleAppFlowCtrl(const std::shared_ptr &record, + std::chrono::system_clock::time_point now, const int32_t callingUid) +{ + std::lock_guard lock(singleAppFlowControlMutex_); + auto singleAppFlowControlIter = singleAppFlowControlUpdateTimestampMap_.find(callingUid); + if (singleAppFlowControlIter == singleAppFlowControlUpdateTimestampMap_.end()) { + return ERR_OK; + } + NotificationAnalyticsUtil::RemoveExpired(*(singleAppFlowControlIter->second), now); + if (singleAppFlowControlIter->second->size() >= threshold_.maxUpdateNumPerSecondPerApp) { + ANS_LOGE("SingleAppUpdateFlowControl failed"); + HaMetaMessage message = HaMetaMessage(EventSceneId::SCENE_4, EventBranchId::BRANCH_5) + .ErrorCode(ERR_ANS_OVER_MAX_UPDATE_PERSECOND).Message("SingleAppUpdateFlowControl failed"); + if (record != nullptr) { + NotificationAnalyticsUtil::ReportPublishFailedEvent(record->request, message); + } + return ERR_ANS_OVER_MAX_UPDATE_PERSECOND; + } + return ERR_OK; +} + +void FlowControlService::UpdateRecordTimestamp(const std::shared_ptr &record, + std::chrono::system_clock::time_point now, const int32_t callingUid) +{ + if (record->isThirdparty == true) { + std::lock_guard lock(flowControlMutex_); + flowControlUpdateTimestampList_.push_back(now); + } else { + std::lock_guard lock(systemFlowControlMutex_); + systemFlowControlUpdateTimestampList_.push_back(now); + } + + std::lock_guard lock(singleAppFlowControlMutex_); + auto singleAppFlowControlIter = singleAppFlowControlUpdateTimestampMap_.find(callingUid); + if (singleAppFlowControlIter == singleAppFlowControlUpdateTimestampMap_.end()) { + singleAppFlowControlUpdateTimestampMap_[callingUid] = + std::make_shared>(); + singleAppFlowControlIter = singleAppFlowControlUpdateTimestampMap_.find(callingUid); + } + singleAppFlowControlIter->second->push_back(now); +} + +void FlowControlService::UpdateSingleAppFlowCtrlRemoveExpire(std::chrono::system_clock::time_point now) +{ + std::lock_guard lock(singleAppFlowControlMutex_); + for (auto iter = singleAppFlowControlUpdateTimestampMap_.begin(); + iter != singleAppFlowControlUpdateTimestampMap_.end();) { + auto latest = iter->second->back(); + if (std::chrono::abs(now - latest) > SINGLE_APP_FLOW_CONTRL_EXPIRE_TIME) { + iter = singleAppFlowControlUpdateTimestampMap_.erase(iter); + } else { + ++iter; + } + } +} +} // namespace Notification +} // namespace OHOS \ No newline at end of file diff --git a/services/ans/src/advanced_notification_publish_service.cpp b/services/ans/src/advanced_notification_publish_service.cpp index 35e5ea9ca..d6e313e04 100644 --- a/services/ans/src/advanced_notification_publish_service.cpp +++ b/services/ans/src/advanced_notification_publish_service.cpp @@ -50,6 +50,7 @@ #include "if_system_ability_manager.h" #include "iservice_registry.h" #include "datashare_predicates.h" +#include "advanced_notification_flow_control_service.h" namespace OHOS { namespace Notification { @@ -230,7 +231,11 @@ ErrCode AdvancedNotificationService::PublishNotificationForIndirectProxy(const s } return; } - + bool isNotificationExists = IsNotificationExists(record->notification->GetKey()); + result = FlowControlService::GetInstance()->FlowControl(record, ipcUid, isNotificationExists); + if (result != ERR_OK) { + return; + } if (AssignToNotificationList(record) != ERR_OK) { ANS_LOGE("Failed to assign notification list"); return; @@ -2401,16 +2406,12 @@ ErrCode AdvancedNotificationService::PublishNotificationBySa(const sptrrequest, bundleOption); #ifdef ENABLE_ANS_EXT_WRAPPER EXTENTION_WRAPPER->GetUnifiedGroupInfo(request); #endif - auto ipcUid = IPCSkeleton::GetCallingUid(); + const int32_t ipcUid = IPCSkeleton::GetCallingUid(); ffrt::task_handle handler = notificationSvrQueue_->submit_h([&]() { if (!bundleOption->GetBundleName().empty()) { ErrCode ret = AssignValidNotificationSlot(record, bundleOption); @@ -2429,7 +2430,11 @@ ErrCode AdvancedNotificationService::PublishNotificationBySa(const sptrnotification->GetKey()); + result = FlowControlService::GetInstance()->FlowControl(record, ipcUid, isNotificationExists); + if (result != ERR_OK) { + return; + } if (AssignToNotificationList(record) != ERR_OK) { ANS_LOGE("Failed to assign notification list"); return; diff --git a/services/ans/src/advanced_notification_service.cpp b/services/ans/src/advanced_notification_service.cpp index 8b3ab5fa1..9430fa44e 100644 --- a/services/ans/src/advanced_notification_service.cpp +++ b/services/ans/src/advanced_notification_service.cpp @@ -74,6 +74,7 @@ #include "advanced_notification_inline.cpp" #include "advanced_datashare_helper_ext.h" #include "notification_analytics_util.h" +#include "advanced_notification_flow_control_service.h" namespace OHOS { namespace Notification { @@ -98,8 +99,6 @@ constexpr const char *KEY_UNIFIED_GROUP_ENABLE = "unified_group_enable"; sptr AdvancedNotificationService::instance_; std::mutex AdvancedNotificationService::instanceMutex_; std::mutex AdvancedNotificationService::pushMutex_; -std::mutex AdvancedNotificationService::flowControlMutex_; -std::mutex AdvancedNotificationService::systemFlowControlMutex_; std::mutex AdvancedNotificationService::doNotDisturbMutex_; std::map slotFlagsDefaultMap_; @@ -366,7 +365,7 @@ ErrCode AdvancedNotificationService::AssignToNotificationList(const std::shared_ ErrCode result = ERR_OK; if (!IsNotificationExists(record->notification->GetKey())) { record->request->SetCreateTime(GetCurrentTime()); - result = PublishFlowControl(record); + result = PublishInNotificationList(record); } else { if (record->request->IsAlertOneTime()) { CloseAlert(record); @@ -655,15 +654,10 @@ ErrCode AdvancedNotificationService::PublishPreparedNotification(const sptrGetUnifiedGroupInfo(request); #endif - int32_t uid = IPCSkeleton::GetCallingUid(); + const int32_t uid = IPCSkeleton::GetCallingUid(); ffrt::task_handle handler = notificationSvrQueue_->submit_h(std::bind([&]() { ANS_LOGD("ffrt enter!"); if (record->request->GetSlotType() == NotificationConstant::SlotType::LIVE_VIEW && @@ -676,7 +670,11 @@ ErrCode AdvancedNotificationService::PublishPreparedNotification(const sptrnotification->GetKey()); + result = FlowControlService::GetInstance()->FlowControl(record, uid, isNotificationExists); + if (result != ERR_OK) { + return; + } result = AddRecordToMemory(record, isSystemApp, isUpdateByOwner, isAgentController); if (result != ERR_OK) { return; @@ -998,50 +996,8 @@ void AdvancedNotificationService::AddToNotificationList(const std::shared_ptr &record) -{ - if (record->isNeedFlowCtrl == false) { - return ERR_OK; - } - std::chrono::system_clock::time_point now = std::chrono::system_clock::now(); - ANS_LOGD("UpdateInNotificationList size %{public}zu,%{public}zu", - flowControlUpdateTimestampList_.size(), systemFlowControlUpdateTimestampList_.size()); - if (record->isThirdparty == true) { - // 三方流控 - std::lock_guard lock(flowControlMutex_); - NotificationAnalyticsUtil::RemoveExpired(flowControlUpdateTimestampList_, now); - if (flowControlUpdateTimestampList_.size() >= MAX_UPDATE_NUM_PERSECOND) { - HaMetaMessage message = HaMetaMessage(EventSceneId::SCENE_2, EventBranchId::BRANCH_4) - .ErrorCode(ERR_ANS_OVER_MAX_UPDATE_PERSECOND).Message("UpdateInNotificationList failed"); - if (record != nullptr) { - NotificationAnalyticsUtil::ReportPublishFailedEvent(record->request, message); - } - return ERR_ANS_OVER_MAX_UPDATE_PERSECOND; - } - flowControlUpdateTimestampList_.push_back(now); - } else { - // 系统流控 - std::lock_guard lock(systemFlowControlMutex_); - NotificationAnalyticsUtil::RemoveExpired(systemFlowControlUpdateTimestampList_, now); - if (systemFlowControlUpdateTimestampList_.size() >= MAX_UPDATE_NUM_PERSECOND) { - HaMetaMessage message = HaMetaMessage(EventSceneId::SCENE_2, EventBranchId::BRANCH_4) - .ErrorCode(ERR_ANS_OVER_MAX_UPDATE_PERSECOND).Message("UpdateInNotificationList failed"); - if (record != nullptr) { - NotificationAnalyticsUtil::ReportPublishFailedEvent(record->request, message); - } - return ERR_ANS_OVER_MAX_UPDATE_PERSECOND; - } - systemFlowControlUpdateTimestampList_.push_back(now); - } - return ERR_OK; -} - ErrCode AdvancedNotificationService::UpdateInNotificationList(const std::shared_ptr &record) { - ErrCode result = UpdateFlowCtrl(record); - if (result != ERR_OK) { - return result; - } auto iter = notificationList_.begin(); while (iter != notificationList_.end()) { if ((*iter)->notification->GetKey() == record->notification->GetKey()) { @@ -1524,89 +1480,14 @@ static bool SortNotificationsByLevelAndTime( } return (first->slot->GetLevel() < second->slot->GetLevel()); } - - -ErrCode AdvancedNotificationService::FlowControl(const std::shared_ptr &record) -{ - if (record->isNeedFlowCtrl == false) { - return ERR_OK; - } - HaMetaMessage message = HaMetaMessage(EventSceneId::SCENE_4, EventBranchId::BRANCH_2); - std::chrono::system_clock::time_point now = std::chrono::system_clock::now(); - ANS_LOGD("FlowControl size %{public}zu,%{public}zu", - flowControlTimestampList_.size(), systemFlowControlTimestampList_.size()); - if (record->isThirdparty == true) { - std::lock_guard lock(flowControlMutex_); - NotificationAnalyticsUtil::RemoveExpired(flowControlTimestampList_, now); - if (flowControlTimestampList_.size() >= MAX_ACTIVE_NUM_PERSECOND + MAX_UPDATE_NUM_PERSECOND) { - message.ErrorCode(ERR_ANS_OVER_MAX_ACTIVE_PERSECOND); - NotificationAnalyticsUtil::ReportPublishFailedEvent(record->request, message); - return ERR_ANS_OVER_MAX_ACTIVE_PERSECOND; - } - flowControlTimestampList_.push_back(now); - } else { - std::lock_guard lock(systemFlowControlMutex_); - NotificationAnalyticsUtil::RemoveExpired(systemFlowControlTimestampList_, now); - if (systemFlowControlTimestampList_.size() >= MAX_ACTIVE_NUM_PERSECOND + MAX_UPDATE_NUM_PERSECOND) { - message.ErrorCode(ERR_ANS_OVER_MAX_ACTIVE_PERSECOND); - NotificationAnalyticsUtil::ReportPublishFailedEvent(record->request, message); - return ERR_ANS_OVER_MAX_ACTIVE_PERSECOND; - } - systemFlowControlTimestampList_.push_back(now); - } - - return ERR_OK; -} bool AdvancedNotificationService::IsSystemUser(int32_t userId) { return ((userId >= SUBSCRIBE_USER_SYSTEM_BEGIN) && (userId <= SUBSCRIBE_USER_SYSTEM_END)); } -ErrCode AdvancedNotificationService::PublishFlowControlInner(const std::shared_ptr &record) -{ - if (record->isNeedFlowCtrl == false) { - return ERR_OK; - } - std::chrono::system_clock::time_point now = std::chrono::system_clock::now(); - ANS_LOGD("PublishFlowControl size %{public}zu,%{public}zu", - flowControlPublishTimestampList_.size(), systemFlowControlPublishTimestampList_.size()); - if (record->isThirdparty == true) { - // 三方流控 - std::lock_guard lock(flowControlMutex_); - NotificationAnalyticsUtil::RemoveExpired(flowControlPublishTimestampList_, now); - if (flowControlPublishTimestampList_.size() >= MAX_ACTIVE_NUM_PERSECOND) { - HaMetaMessage message = HaMetaMessage(EventSceneId::SCENE_2, EventBranchId::BRANCH_3) - .ErrorCode(ERR_ANS_OVER_MAX_ACTIVE_PERSECOND).Message("PublishFlowControl failed"); - if (record != nullptr) { - NotificationAnalyticsUtil::ReportPublishFailedEvent(record->request, message); - } - return ERR_ANS_OVER_MAX_ACTIVE_PERSECOND; - } - flowControlPublishTimestampList_.push_back(now); - } else { - // 系统流控 - std::lock_guard lock(systemFlowControlMutex_); - NotificationAnalyticsUtil::RemoveExpired(systemFlowControlPublishTimestampList_, now); - if (systemFlowControlPublishTimestampList_.size() >= MAX_ACTIVE_NUM_PERSECOND) { - HaMetaMessage message = HaMetaMessage(EventSceneId::SCENE_2, EventBranchId::BRANCH_3) - .ErrorCode(ERR_ANS_OVER_MAX_ACTIVE_PERSECOND).Message("PublishFlowControl failed"); - if (record != nullptr) { - NotificationAnalyticsUtil::ReportPublishFailedEvent(record->request, message); - } - return ERR_ANS_OVER_MAX_ACTIVE_PERSECOND; - } - systemFlowControlPublishTimestampList_.push_back(now); - } - return ERR_OK; -} - -ErrCode AdvancedNotificationService::PublishFlowControl(const std::shared_ptr &record) +ErrCode AdvancedNotificationService::PublishInNotificationList(const std::shared_ptr &record) { - ErrCode result = PublishFlowControlInner(record); - if (result != ERR_OK) { - return result; - } std::list> bundleList; for (auto item : notificationList_) { if (record->notification->GetBundleName() == item->notification->GetBundleName()) { diff --git a/services/ans/src/advanced_notification_utils.cpp b/services/ans/src/advanced_notification_utils.cpp index ff581aa3d..9d50da0cf 100644 --- a/services/ans/src/advanced_notification_utils.cpp +++ b/services/ans/src/advanced_notification_utils.cpp @@ -50,6 +50,7 @@ #include "notification_analytics_util.h" #include "notification_clone_disturb_service.h" #include "notification_clone_bundle_service.h" +#include "advanced_notification_flow_control_service.h" #define CHECK_BUNDLE_OPTION_IS_INVALID(option) \ if (option == nullptr || option->GetBundleName().empty()) { \ @@ -915,7 +916,8 @@ void AdvancedNotificationService::OnDistributedPublish( ANS_LOGE("notificationSvrQueue_ is nullptr."); return; } - notificationSvrQueue_->submit(std::bind([this, deviceId, bundleName, request, activeUserId]() { + const int32_t callingUid = IPCSkeleton::GetCallingUid(); + notificationSvrQueue_->submit(std::bind([this, deviceId, bundleName, request, activeUserId, callingUid]() { ANS_LOGD("ffrt enter!"); if (!CheckDistributedNotificationType(request)) { ANS_LOGD("CheckDistributedNotificationType is false."); @@ -965,7 +967,12 @@ void AdvancedNotificationService::OnDistributedPublish( return; } - result = PublishFlowControl(record); + bool isNotificationExists = IsNotificationExists(record->notification->GetKey()); + result = FlowControlService::GetInstance()->FlowControl(record, callingUid, isNotificationExists); + if (result != ERR_OK) { + return; + } + result = PublishInNotificationList(record); if (result != ERR_OK) { return; } @@ -990,7 +997,8 @@ void AdvancedNotificationService::OnDistributedUpdate( ANS_LOGE("Serial queue is invalid."); return; } - notificationSvrQueue_->submit(std::bind([this, deviceId, bundleName, request, activeUserId]() { + const int32_t callingUid = IPCSkeleton::GetCallingUid(); + notificationSvrQueue_->submit(std::bind([this, deviceId, bundleName, request, activeUserId, callingUid]() { ANS_LOGD("ffrt enter!"); if (!CheckDistributedNotificationType(request)) { ANS_LOGD("device type not support display."); @@ -1038,7 +1046,11 @@ void AdvancedNotificationService::OnDistributedUpdate( ANS_LOGE("Reject by filters: %{public}d", result); return; } - + bool isNotificationExists = IsNotificationExists(record->notification->GetKey()); + result = FlowControlService::GetInstance()->FlowControl(record, callingUid, isNotificationExists); + if (result != ERR_OK) { + return; + } if (IsNotificationExists(record->notification->GetKey())) { if (record->request->IsAlertOneTime()) { CloseAlert(record); diff --git a/services/ans/src/common/notification_config_parse.cpp b/services/ans/src/common/notification_config_parse.cpp index 0274bccc6..3804b084e 100644 --- a/services/ans/src/common/notification_config_parse.cpp +++ b/services/ans/src/common/notification_config_parse.cpp @@ -144,5 +144,42 @@ uint32_t NotificationConfigParse::GetConfigSlotReminderModeByType(NotificationCo } return reminderFlags; } + +void NotificationConfigParse::GetFlowCtrlConfigFromCCM(FlowControlThreshold &threshold) +{ + nlohmann::json root; + std::string JsonPoint = "/"; + JsonPoint.append(CFG_KEY_NOTIFICATION_SERVICE); + if (!GetConfigJson(JsonPoint, root)) { + ANS_LOGE("Failed to get JsonPoint CCM config file"); + return; + } + if (!root.contains(CFG_KEY_NOTIFICATION_SERVICE)) { + ANS_LOGW("GetFlowCtrlConfigFromCCM not found jsonKey"); + return; + } + nlohmann::json affects = root[CFG_KEY_NOTIFICATION_SERVICE]; + if (affects.is_null() || affects.empty()) { + ANS_LOGE("GetFlowCtrlConfigFromCCM failed as invalid ccmFlowCtrlConfig json"); + return; + } + if (affects.contains(CFG_KEY_MAX_CREATE_NUM_PERSECOND)) { + threshold.maxCreateNumPerSecond = affects[CFG_KEY_MAX_CREATE_NUM_PERSECOND]; + } + + if (affects.contains(CFG_KEY_MAX_UPDATE_NUM_PERSECOND)) { + threshold.maxUpdateNumPerSecond = affects[CFG_KEY_MAX_UPDATE_NUM_PERSECOND]; + } + + if (affects.contains(CFG_KEY_MAX_CREATE_NUM_PERSECOND_PERAPP)) { + threshold.maxCreateNumPerSecondPerApp = affects[CFG_KEY_MAX_CREATE_NUM_PERSECOND_PERAPP]; + } + + if (affects.contains(CFG_KEY_MAX_UPDATE_NUM_PERSECOND_PERAPP)) { + threshold.maxUpdateNumPerSecondPerApp = affects[CFG_KEY_MAX_UPDATE_NUM_PERSECOND_PERAPP]; + } + + ANS_LOGI("GetFlowCtrlConfigFromCCM success"); +} } // namespace Notification } // namespace OHOS diff --git a/services/ans/test/unittest/BUILD.gn b/services/ans/test/unittest/BUILD.gn index e626898bf..f088f19bc 100644 --- a/services/ans/test/unittest/BUILD.gn +++ b/services/ans/test/unittest/BUILD.gn @@ -467,6 +467,7 @@ ohos_unittest("notification_publish_service_test") { sources = [ "${test_path}/mock/mock_tokenid_kit.cpp", + "advanced_notification_flow_control_service_test.cpp", "advanced_notification_publish_service_test.cpp", "mock/blob.cpp", "mock/distributed_kv_data_manager.cpp", diff --git a/services/ans/test/unittest/advanced_notification_flow_control_service_test.cpp b/services/ans/test/unittest/advanced_notification_flow_control_service_test.cpp new file mode 100644 index 000000000..5cdebef47 --- /dev/null +++ b/services/ans/test/unittest/advanced_notification_flow_control_service_test.cpp @@ -0,0 +1,103 @@ +/* + * Copyright (c) 2024 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "advanced_notification_flow_control_service.h" + +#include "gtest/gtest.h" + +#include "ans_const_define.h" +#include "ans_inner_errors.h" + +using namespace testing::ext; + +namespace OHOS { +namespace Notification { +namespace { + constexpr int32_t NON_SYSTEM_APP_UID = 1000; +} +class FlowControlServiceTest : public testing::Test { +public: + static void SetUpTestCase(); + static void TearDownTestCase(); + void SetUp(); + void TearDown(); +}; + +void FlowControlServiceTest::SetUpTestCase() {} + +void FlowControlServiceTest::TearDownTestCase() {} + +void FlowControlServiceTest::SetUp() {} + +void FlowControlServiceTest::TearDown() {} + +/** + * @tc.number : FlowControl_00001 + * @tc.name : Test FlowControl + * @tc.desc : Test FlowControl + */ +HWTEST_F(FlowControlServiceTest, FlowControl_00001, Function | SmallTest | Level1) +{ + sptr request = new (std::nothrow) NotificationRequest(); + sptr notification = new (std::nothrow) Notification(request); + auto record = std::make_shared(); + record->request = request; + record->notification = notification; + record->isThirdparty = false; + record->isNeedFlowCtrl = true; + ErrCode result = ERR_OK; + int32_t callingUid = DEFAULT_UID; + + // create flow control + // single app flow control test + for (int i = 0; i < MAX_CREATE_NUM_PERSECOND_PERAPP; i++) { + result = FlowControlService::GetInstance()->FlowControl(record, callingUid, false); + } + ASSERT_EQ(result, (int)ERR_OK); + result = FlowControlService::GetInstance()->FlowControl(record, callingUid, false); + ASSERT_EQ(result, (int)ERR_ANS_OVER_MAX_ACTIVE_PERSECOND); + + // global flow control test + int gap = MAX_CREATE_NUM_PERSECOND - MAX_CREATE_NUM_PERSECOND_PERAPP; + callingUid = NON_SYSTEM_APP_UID; + for (int i = 0; i < gap; i++) { + result = FlowControlService::GetInstance()->FlowControl(record, callingUid, false); + } + ASSERT_EQ(result, (int)ERR_OK); + result = FlowControlService::GetInstance()->FlowControl(record, callingUid, false); + ASSERT_EQ(result, (int)ERR_ANS_OVER_MAX_ACTIVE_PERSECOND); + + // update flow control + // single app flow control test + callingUid = DEFAULT_UID; + for (int i = 0; i < MAX_UPDATE_NUM_PERSECOND_PERAPP; i++) { + result = FlowControlService::GetInstance()->FlowControl(record, callingUid, true); + } + ASSERT_EQ(result, (int)ERR_OK); + result = FlowControlService::GetInstance()->FlowControl(record, callingUid, true); + ASSERT_EQ(result, (int)ERR_ANS_OVER_MAX_UPDATE_PERSECOND); + + // global flow control test + gap = MAX_UPDATE_NUM_PERSECOND - MAX_UPDATE_NUM_PERSECOND_PERAPP; + callingUid = NON_SYSTEM_APP_UID; + for (int i = 0; i < gap; i++) { + result = FlowControlService::GetInstance()->FlowControl(record, callingUid, true); + } + ASSERT_EQ(result, (int)ERR_OK); + result = FlowControlService::GetInstance()->FlowControl(record, callingUid, true); + ASSERT_EQ(result, (int)ERR_ANS_OVER_MAX_UPDATE_PERSECOND); +} +} // namespace Notification +} // namespace OHOS \ No newline at end of file diff --git a/services/ans/test/unittest/advanced_notification_service_test.cpp b/services/ans/test/unittest/advanced_notification_service_test.cpp index 19a1d18a5..bcd5e50f4 100644 --- a/services/ans/test/unittest/advanced_notification_service_test.cpp +++ b/services/ans/test/unittest/advanced_notification_service_test.cpp @@ -3762,12 +3762,12 @@ HWTEST_F(AdvancedNotificationServiceTest, GetExcludeDates_00001, Function | Smal } /** - * @tc.number : PublishFlowControl_00001 - * @tc.name : Test PublishFlowControl - * @tc.desc : Test PublishFlowControl function when the record->slot is nullptr + * @tc.number : PublishInNotificationList_00001 + * @tc.name : Test PublishInNotificationList + * @tc.desc : Test PublishInNotificationList function when the record->slot is nullptr * @tc.require : issueI5S4VP */ -HWTEST_F(AdvancedNotificationServiceTest, PublishFlowControl_00001, Function | SmallTest | Level1) +HWTEST_F(AdvancedNotificationServiceTest, PublishInNotificationList_00001, Function | SmallTest | Level1) { for (int i = 0; i < 100; i++) { sptr request = new (std::nothrow) NotificationRequest(); @@ -3783,7 +3783,7 @@ HWTEST_F(AdvancedNotificationServiceTest, PublishFlowControl_00001, Function | S auto record = std::make_shared(); record->request = request; record->notification = notification; - advancedNotificationService_->PublishFlowControl(record); + advancedNotificationService_->PublishInNotificationList(record); ASSERT_EQ(advancedNotificationService_->notificationList_.size(), 100); } } // namespace Notification -- Gitee From e98f6b0a943e2a94e2226b640cdefedfbeef5639 Mon Sep 17 00:00:00 2001 From: Ricky Date: Wed, 9 Oct 2024 16:28:51 +0800 Subject: [PATCH 164/167] cherry pick 83c17b1 from https://gitee.com/wufarong1/notification_distributed_notification_service/pulls/2273 verify bundleOption when assignValidNotificationSlot Signed-off-by: Ricky Change-Id: I8bc8b4d327137b87a0e061b058b2b83db0821a5b --- .../include/advanced_notification_service.h | 2 +- services/ans/include/notification_dialog.h | 1 - .../ans/src/advanced_datashare_helper_ext.cpp | 12 +++--- .../advanced_notification_publish_service.cpp | 15 ++++---- .../ans/src/advanced_notification_service.cpp | 2 +- .../ans/src/advanced_notification_utils.cpp | 37 +++++++------------ .../ans/src/clone/notification_clone_util.cpp | 10 ++--- services/ans/src/notification_dialog.cpp | 20 ++-------- .../src/notification_preferences_database.cpp | 9 ++--- .../ans/src/os_account_manager_helper.cpp | 10 +++-- services/ans/src/reminder_data_manager.cpp | 11 +----- .../mock_os_account_manager_annex.cpp | 14 +++---- .../notification_dialog_test.cpp | 32 +++------------- ...ication_subscriber_manager_branch_test.cpp | 12 +++--- 14 files changed, 65 insertions(+), 122 deletions(-) diff --git a/services/ans/include/advanced_notification_service.h b/services/ans/include/advanced_notification_service.h index 1a91c366d..50594af61 100644 --- a/services/ans/include/advanced_notification_service.h +++ b/services/ans/include/advanced_notification_service.h @@ -1265,7 +1265,7 @@ private: void AdjustDateForDndTypeOnce(int64_t &beginDate, int64_t &endDate); ErrCode PrepareNotificationRequest(const sptr &request); ErrCode PrepareContinuousTaskNotificationRequest(const sptr &request, const int32_t &uid); - static bool GetActiveUserId(int& userId); + void TriggerRemoveWantAgent(const sptr &request); bool CheckApiCompatibility(const sptr &bundleOption); ErrCode IsAllowedNotifySelf(const sptr &bundleOption, bool &allowed); diff --git a/services/ans/include/notification_dialog.h b/services/ans/include/notification_dialog.h index ea37aa5ae..941e7f47f 100644 --- a/services/ans/include/notification_dialog.h +++ b/services/ans/include/notification_dialog.h @@ -36,7 +36,6 @@ public: std::string appBundleName, const sptr &callerToken); - static int32_t GetActiveUserId(); static int32_t GetUidByBundleName(const std::string &bundleName); }; } // namespace Notification diff --git a/services/ans/src/advanced_datashare_helper_ext.cpp b/services/ans/src/advanced_datashare_helper_ext.cpp index 347f9dd03..48415abff 100644 --- a/services/ans/src/advanced_datashare_helper_ext.cpp +++ b/services/ans/src/advanced_datashare_helper_ext.cpp @@ -20,8 +20,10 @@ #include "iservice_registry.h" #include "message_parcel.h" #include "os_account_manager.h" +#include "os_account_manager_helper.h" #include "singleton.h" #include "system_ability_definition.h" +#include namespace OHOS { namespace Notification { @@ -88,13 +90,9 @@ bool AdvancedDatashareHelperExt::Query(Uri &uri, const std::string &key, std::st std::string AdvancedDatashareHelperExt::GetUnifiedGroupEnableUri() const { - std::vector accountIds; - OHOS::AccountSA::OsAccountManager::QueryActiveOsAccountIds(accountIds); - std::string userId = "100"; - if (!accountIds.empty()) { - userId = std::to_string(accountIds[0]); - } - return USER_SETTINGS_DATA_SECURE_URI + userId + UNIFIED_GROUP_ENABLE_URI; + int32_t userId = 100; + OsAccountManagerHelper::GetInstance().GetCurrentActiveUserId(userId); + return USER_SETTINGS_DATA_SECURE_URI + std::to_string(userId) + UNIFIED_GROUP_ENABLE_URI; } } // namespace Notification } // namespace OHOS diff --git a/services/ans/src/advanced_notification_publish_service.cpp b/services/ans/src/advanced_notification_publish_service.cpp index 35e5ea9ca..0d1c6fb05 100644 --- a/services/ans/src/advanced_notification_publish_service.cpp +++ b/services/ans/src/advanced_notification_publish_service.cpp @@ -37,6 +37,7 @@ #include "common_event_manager.h" #include "common_event_support.h" #include "common_event_publish_info.h" +#include "os_account_manager_helper.h" #include "want_params_wrapper.h" #include "ans_convert_enum.h" #include "notification_analytics_util.h" @@ -682,7 +683,7 @@ ErrCode AdvancedNotificationService::DeleteAll() ffrt::task_handle handler = notificationSvrQueue_->submit_h(std::bind([&]() { ANS_LOGD("ffrt enter!"); int32_t activeUserId = SUBSCRIBE_USER_INIT; - if (!GetActiveUserId(activeUserId)) { + if (OsAccountManagerHelper::GetInstance().GetCurrentActiveUserId(activeUserId) != ERR_OK) { return; } std::vector keys = GetNotificationKeys(nullptr); @@ -947,7 +948,7 @@ ErrCode AdvancedNotificationService::SetNotificationsEnabledForAllBundles(const } int32_t userId = SUBSCRIBE_USER_INIT; - if (!GetActiveUserId(userId)) { + if (OsAccountManagerHelper::GetInstance().GetCurrentActiveUserId(userId) != ERR_OK) { return ERR_ANS_GET_ACTIVE_USER_FAILED; } @@ -1054,7 +1055,7 @@ ErrCode AdvancedNotificationService::IsAllowedNotify(bool &allowed) } int32_t userId = SUBSCRIBE_USER_INIT; - if (!GetActiveUserId(userId)) { + if (OsAccountManagerHelper::GetInstance().GetCurrentActiveUserId(userId) != ERR_OK) { return ERR_ANS_GET_ACTIVE_USER_FAILED; } @@ -1185,7 +1186,7 @@ ErrCode AdvancedNotificationService::IsAllowedNotifySelf(const sptrGetOwnerUid() == DEFAULT_UID) { - GetActiveUserId(userId); + OsAccountManagerHelper::GetInstance().GetCurrentActiveUserId(userId); uid = bundleManager->GetDefaultUidByBundleName(request->GetOwnerBundleName(), userId); } else { uid = request->GetOwnerUid(); diff --git a/services/ans/src/advanced_notification_utils.cpp b/services/ans/src/advanced_notification_utils.cpp index ff581aa3d..4dbdb10f2 100644 --- a/services/ans/src/advanced_notification_utils.cpp +++ b/services/ans/src/advanced_notification_utils.cpp @@ -32,6 +32,7 @@ #include "os_account_manager.h" #include "notification_preferences.h" #include "distributed_database.h" +#include "os_account_manager_helper.h" #include "singleton.h" #include "want_agent_helper.h" #include "hitrace_meter.h" @@ -137,7 +138,7 @@ sptr AdvancedNotificationService::GenerateValidBundleO std::shared_ptr bundleManager = BundleManagerHelper::GetInstance(); if (bundleManager != nullptr) { int32_t activeUserId = -1; - if (!GetActiveUserId(activeUserId)) { + if (OsAccountManagerHelper::GetInstance().GetCurrentActiveUserId(activeUserId) != ERR_OK) { ANS_LOGE("Failed to get active user id!"); return validBundleOption; } @@ -322,7 +323,7 @@ void AdvancedNotificationService::SetAgentNotification(sptr { auto bundleManager = BundleManagerHelper::GetInstance(); int32_t activeUserId = -1; - if (!GetActiveUserId(activeUserId)) { + if (OsAccountManagerHelper::GetInstance().GetCurrentActiveUserId(activeUserId) != ERR_OK) { ANSR_LOGW("Failed to get active user id!"); return; } @@ -772,7 +773,7 @@ ErrCode AdvancedNotificationService::SetDoNotDisturbDate(const sptrsubmit(std::bind([this, deviceId, bundleName, label, id]() { ANS_LOGD("ffrt enter!"); int32_t activeUserId = -1; - if (!GetActiveUserId(activeUserId)) { + if (OsAccountManagerHelper::GetInstance().GetCurrentActiveUserId(activeUserId) != ERR_OK) { ANS_LOGE("Failed to get active user id!"); return; } @@ -1277,18 +1278,6 @@ ErrCode AdvancedNotificationService::IsSupportTemplate(const std::string& templa return result; } -bool AdvancedNotificationService::GetActiveUserId(int& userId) -{ - std::vector activeUserId; - OHOS::AccountSA::OsAccountManager::QueryActiveOsAccountIds(activeUserId); - if (activeUserId.size() > 0) { - userId = activeUserId[0]; - ANS_LOGD("Return active userId=%{public}d", userId); - return true; - } - return false; -} - void AdvancedNotificationService::TriggerRemoveWantAgent(const sptr &request) { HITRACE_METER_NAME(HITRACE_TAG_NOTIFICATION, __PRETTY_FUNCTION__); @@ -1908,7 +1897,7 @@ ErrCode AdvancedNotificationService::CheckBundleOptionValid(sptr AdvancedNotificationService::GetBundlesOfAct } std::vector activeUserId; - AccountSA::OsAccountManager::QueryActiveOsAccountIds(activeUserId); + OsAccountManagerHelper::GetInstance().GetAllActiveOsAccount(activeUserId); if (activeUserId.empty()) { activeUserId.push_back(MAIN_USER_ID); } diff --git a/services/ans/src/clone/notification_clone_util.cpp b/services/ans/src/clone/notification_clone_util.cpp index eeb074b79..38590b55d 100644 --- a/services/ans/src/clone/notification_clone_util.cpp +++ b/services/ans/src/clone/notification_clone_util.cpp @@ -17,6 +17,7 @@ #include "bundle_manager_helper.h" #include "os_account_manager.h" +#include "os_account_manager_helper.h" namespace OHOS { namespace Notification { @@ -24,12 +25,9 @@ namespace Notification { constexpr int32_t MAIN_USER_ID = 100; int32_t NotificationCloneUtil::GetActiveUserId() { - std::vector activeUserId; - OHOS::AccountSA::OsAccountManager::QueryActiveOsAccountIds(activeUserId); - if (activeUserId.size() > 0) { - return activeUserId[0]; - } - return MAIN_USER_ID; + int32_t userId = MAIN_USER_ID; + OsAccountManagerHelper::GetInstance().GetCurrentActiveUserId(userId); + return userId; } int32_t NotificationCloneUtil::GetBundleUid(const std::string bundleName, int32_t userId, int32_t appIndex) diff --git a/services/ans/src/notification_dialog.cpp b/services/ans/src/notification_dialog.cpp index cd01f5b96..8b635cf9f 100644 --- a/services/ans/src/notification_dialog.cpp +++ b/services/ans/src/notification_dialog.cpp @@ -21,32 +21,18 @@ #include "bundle_manager_helper.h" #include "in_process_call_wrapper.h" #include "os_account_manager.h" +#include "os_account_manager_helper.h" #include "system_dialog_connect_stb.h" #include "extension_manager_client.h" namespace OHOS { namespace Notification { constexpr int32_t DEFAULT_VALUE = -1; -int32_t NotificationDialog::GetActiveUserId() -{ - std::vector activeUserId; - auto errCode = AccountSA::OsAccountManager::QueryActiveOsAccountIds(activeUserId); - if (errCode != ERR_OK) { - ANS_LOGE("Query active accountIds failed with %{public}d.", errCode); - return AppExecFwk::Constants::ANY_USERID; - } - - if (activeUserId.empty()) { - ANS_LOGE("Active accountIds is empty."); - return AppExecFwk::Constants::ANY_USERID; - } - - return activeUserId.front(); -} int32_t NotificationDialog::GetUidByBundleName(const std::string &bundleName) { - auto userId = NotificationDialog::GetActiveUserId(); + int32_t userId = AppExecFwk::Constants::ANY_USERID; + OsAccountManagerHelper::GetInstance().GetCurrentActiveUserId(userId); return IN_PROCESS_CALL(BundleManagerHelper::GetInstance()->GetDefaultUidByBundleName(bundleName, userId)); } diff --git a/services/ans/src/notification_preferences_database.cpp b/services/ans/src/notification_preferences_database.cpp index 20e0c68d4..b0ba16893 100644 --- a/services/ans/src/notification_preferences_database.cpp +++ b/services/ans/src/notification_preferences_database.cpp @@ -832,9 +832,9 @@ bool NotificationPreferencesDatabase::HandleDataBaseMap( { std::regex matchBundlenamePattern("^ans_bundle_(.*)_name$"); std::smatch match; - std::vector ids; + int32_t currentUserId = SUBSCRIBE_USER_INIT; ErrCode result = ERR_OK; - result = OHOS::AccountSA::OsAccountManager::QueryActiveOsAccountIds(ids); + result = OsAccountManagerHelper::GetInstance().GetCurrentActiveUserId(currentUserId); if (result != ERR_OK) { ANS_LOGE("Get account id fail"); return false; @@ -859,13 +859,12 @@ bool NotificationPreferencesDatabase::HandleDataBaseMap( continue; } int userid = -1; - constexpr int FIRST_USERID = 0; result = - OHOS::AccountSA::OsAccountManager::GetOsAccountLocalIdFromUid(StringToInt(uidItem->second), userid); + OsAccountManagerHelper::GetInstance().GetOsAccountLocalIdFromUid(StringToInt(uidItem->second), userid); if (result != ERR_OK) { return false; } - if (userid != ids[FIRST_USERID]) { + if (userid != currentUserId) { continue; } NotificationBundleOption obj(value, StringToInt(uidItem->second)); diff --git a/services/ans/src/os_account_manager_helper.cpp b/services/ans/src/os_account_manager_helper.cpp index fa92124aa..1355bfec8 100644 --- a/services/ans/src/os_account_manager_helper.cpp +++ b/services/ans/src/os_account_manager_helper.cpp @@ -57,10 +57,12 @@ ErrCode OsAccountManagerHelper::GetCurrentCallingUserId(int32_t &userId) ErrCode OsAccountManagerHelper::GetCurrentActiveUserId(int32_t &id) { - std::vector activeUserId; - int32_t ret = GetAllActiveOsAccount(activeUserId); - if (activeUserId.size() > 0) { - id = activeUserId[0]; + int32_t ret = OHOS::AccountSA::OsAccountManager::GetForegroundOsAccountLocalId(id); + if (ret != ERR_OK) { + HaMetaMessage message = HaMetaMessage(EventSceneId::SCENE_6, EventBranchId::BRANCH_4) + .Message("Get foreground os account failed ret " + std::to_string(ret)); + NotificationAnalyticsUtil::ReportModifyEvent(message); + ANS_LOGE("Failed to call OsAccountManager::GetForegroundOsAccountLocalId, code is %{public}d", ret); } return ret; } diff --git a/services/ans/src/reminder_data_manager.cpp b/services/ans/src/reminder_data_manager.cpp index 4bf214faa..27e4042bb 100644 --- a/services/ans/src/reminder_data_manager.cpp +++ b/services/ans/src/reminder_data_manager.cpp @@ -1456,15 +1456,8 @@ void ReminderDataManager::CheckReminderTime(std::vector>& void ReminderDataManager::InitUserId() { - std::vector activeUserId; - AccountSA::OsAccountManager::QueryActiveOsAccountIds(activeUserId); - if (activeUserId.size() > 0) { - currentUserId_ = activeUserId[0]; - ANSR_LOGD("Init user id=%{private}d", currentUserId_); - } else { - currentUserId_ = MAIN_USER_ID; - ANSR_LOGE("Failed to get active user id."); - } + currentUserId_ = MAIN_USER_ID; + OsAccountManagerHelper::GetInstance().GetCurrentActiveUserId(currentUserId_); } bool ReminderDataManager::RegisterConfigurationObserver() diff --git a/services/ans/test/unittest/notification_dialog_test/mock_os_account_manager_annex.cpp b/services/ans/test/unittest/notification_dialog_test/mock_os_account_manager_annex.cpp index 067b2eff5..8be5780b3 100644 --- a/services/ans/test/unittest/notification_dialog_test/mock_os_account_manager_annex.cpp +++ b/services/ans/test/unittest/notification_dialog_test/mock_os_account_manager_annex.cpp @@ -17,15 +17,15 @@ namespace { int32_t g_mockId = 100; // default id when there is no os_account part -bool g_mockQueryActiveOsAccountIdsRet = true; +bool g_mockQueryForgroundOsAccountRet = true; bool g_mockGetOsAccountLocalIdFromUidRet = true; int32_t g_mockIdForGetOsAccountLocalIdFromUid = 100; bool g_mockOsAccountExists = true; } -void MockQueryActiveOsAccountIds(bool mockRet, uint8_t mockCase) +void MockQueryForgroundOsAccountId(bool mockRet, uint8_t mockCase) { - g_mockQueryActiveOsAccountIdsRet = mockRet; + g_mockQueryForgroundOsAccountRet = mockRet; switch (mockCase) { case 1: { g_mockId = 101; // 101 mockcase1 @@ -46,7 +46,7 @@ void MockIsOsAccountExists(bool mockRet) void ResetAccountMock() { g_mockId = 100; // 100 mockId - g_mockQueryActiveOsAccountIdsRet = true; + g_mockQueryForgroundOsAccountRet = true; g_mockGetOsAccountLocalIdFromUidRet = true; g_mockIdForGetOsAccountLocalIdFromUid = 100; g_mockOsAccountExists = true; @@ -73,12 +73,12 @@ void MockGetOsAccountLocalIdFromUid(bool mockRet, uint8_t mockCase = 0) namespace OHOS { namespace AccountSA { -ErrCode OsAccountManager::QueryActiveOsAccountIds(std::vector& ids) +ErrCode OsAccountManager::GetForegroundOsAccountLocalId(int32_t &id) { - if (!g_mockQueryActiveOsAccountIdsRet) { + if (!g_mockQueryForgroundOsAccountRet) { return ERR_INVALID_OPERATION; } - ids.emplace_back(g_mockId); + id = g_mockId; return ERR_OK; } diff --git a/services/ans/test/unittest/notification_dialog_test/notification_dialog_test.cpp b/services/ans/test/unittest/notification_dialog_test/notification_dialog_test.cpp index fc2cde99a..a43ffabdb 100644 --- a/services/ans/test/unittest/notification_dialog_test/notification_dialog_test.cpp +++ b/services/ans/test/unittest/notification_dialog_test/notification_dialog_test.cpp @@ -24,7 +24,7 @@ #undef protected #include "ans_inner_errors.h" -extern void MockQueryActiveOsAccountIds(bool mockRet, uint8_t mockCase); +extern void MockQueryForgroundOsAccountId(bool mockRet, uint8_t mockCase); using namespace testing::ext; @@ -38,30 +38,14 @@ public: void TearDown() {}; }; -/** - * @tc.name : NotificationDialog_00100 - * @tc.number : - * @tc.desc : test GetActiveUserId function and QueryActiveOsAccountIds is ERR_OK - */ -HWTEST_F(NotificationDialogTest, NotificationDialog_00100, Function | SmallTest | Level1) -{ - MockQueryActiveOsAccountIds(true, 0); - int32_t result = NotificationDialog::GetActiveUserId(); - int32_t activeUserId = 100; - ASSERT_EQ(result, activeUserId); -} - /** * @tc.name : NotificationDialog_00200 * @tc.number : - * @tc.desc : test GetActiveUserId function and QueryActiveOsAccountIds is ERR_INVALID_OPERATION + * @tc.desc : test QueryActiveOsAccountIds is ERR_INVALID_OPERATION */ HWTEST_F(NotificationDialogTest, NotificationDialog_00200, Function | SmallTest | Level1) { - MockQueryActiveOsAccountIds(false, 1); - int32_t result = NotificationDialog::GetActiveUserId(); - int32_t activeUserId = -4; - ASSERT_EQ(result, activeUserId); + MockQueryForgroundOsAccountId(false, 1); std::string bundleName = "BundleName"; int32_t result2 = NotificationDialog::GetUidByBundleName(bundleName); @@ -76,10 +60,7 @@ HWTEST_F(NotificationDialogTest, NotificationDialog_00200, Function | SmallTest */ HWTEST_F(NotificationDialogTest, NotificationDialog_00300, Function | SmallTest | Level1) { - MockQueryActiveOsAccountIds(false, 1); - int32_t result = NotificationDialog::GetActiveUserId(); - int32_t activeUserId = -4; - ASSERT_EQ(result, activeUserId); + MockQueryForgroundOsAccountId(false, 1); std::string bundleName = "BundleName"; int32_t result2 = NotificationDialog::GetUidByBundleName(bundleName); @@ -104,10 +85,7 @@ HWTEST_F(NotificationDialogTest, NotificationDialog_00300, Function | SmallTest */ HWTEST_F(NotificationDialogTest, NotificationDialog_00400, Function | SmallTest | Level1) { - MockQueryActiveOsAccountIds(false, 1); - int32_t result = NotificationDialog::GetActiveUserId(); - int32_t activeUserId = -4; - ASSERT_EQ(result, activeUserId); + MockQueryForgroundOsAccountId(false, 1); std::string bundleName = "BundleName"; int32_t result2 = NotificationDialog::GetUidByBundleName(bundleName); diff --git a/services/ans/test/unittest/notification_subscriber_manager_branch_test/notification_subscriber_manager_branch_test.cpp b/services/ans/test/unittest/notification_subscriber_manager_branch_test/notification_subscriber_manager_branch_test.cpp index 60d5f440a..a8ae3da03 100644 --- a/services/ans/test/unittest/notification_subscriber_manager_branch_test/notification_subscriber_manager_branch_test.cpp +++ b/services/ans/test/unittest/notification_subscriber_manager_branch_test/notification_subscriber_manager_branch_test.cpp @@ -30,7 +30,7 @@ extern void MockGetUserId(bool mockRet); extern void MockGetBundleName(bool mockRet); extern void MockGetNotificationSlotRet(bool mockRet); -extern void MockQueryActiveOsAccountIds(bool mockRet, uint8_t mockCase); +extern void MockQueryForgroundOsAccountId(bool mockRet, uint8_t mockCase); using namespace OHOS::Security::AccessToken; using namespace testing::ext; @@ -639,7 +639,7 @@ HWTEST_F(NotificationSubscriberManagerBranchTest, AdvancedNotificationService_02 std::string deviceId = ""; bool enabled = true; MockGetTokenTypeFlag(ATokenTypeEnum::TOKEN_NATIVE); - MockQueryActiveOsAccountIds(false, 1); + MockQueryForgroundOsAccountId(false, 1); AdvancedNotificationService advancedNotificationService; ASSERT_EQ(advancedNotificationService.SetNotificationsEnabledForAllBundles(deviceId, enabled), @@ -689,7 +689,7 @@ HWTEST_F(NotificationSubscriberManagerBranchTest, AdvancedNotificationService_03 bool enabled = true; MockGetTokenTypeFlag(ATokenTypeEnum::TOKEN_NATIVE); - MockQueryActiveOsAccountIds(false, 1); + MockQueryForgroundOsAccountId(false, 1); AdvancedNotificationService advancedNotificationService; ASSERT_EQ(advancedNotificationService.IsAllowedNotify(enabled), ERR_ANS_GET_ACTIVE_USER_FAILED); } @@ -735,7 +735,7 @@ HWTEST_F(NotificationSubscriberManagerBranchTest, AdvancedNotificationService_03 HWTEST_F(NotificationSubscriberManagerBranchTest, AdvancedNotificationService_03400, Function | SmallTest | Level1) { sptr bundleOption = new NotificationBundleOption(); - MockQueryActiveOsAccountIds(false, 1); + MockQueryForgroundOsAccountId(false, 1); bool allowed = true; int32_t uid = 2; @@ -923,7 +923,7 @@ HWTEST_F(NotificationSubscriberManagerBranchTest, AdvancedNotificationService_04 HWTEST_F(NotificationSubscriberManagerBranchTest, AdvancedNotificationService_04500, Function | SmallTest | Level1) { sptr date = nullptr; - MockQueryActiveOsAccountIds(false, 1); + MockQueryForgroundOsAccountId(false, 1); MockGetTokenTypeFlag(ATokenTypeEnum::TOKEN_NATIVE); AdvancedNotificationService advancedNotificationService; @@ -953,7 +953,7 @@ HWTEST_F(NotificationSubscriberManagerBranchTest, AdvancedNotificationService_04 HWTEST_F(NotificationSubscriberManagerBranchTest, AdvancedNotificationService_04700, Function | SmallTest | Level1) { sptr date = nullptr; - MockQueryActiveOsAccountIds(false, 1); + MockQueryForgroundOsAccountId(false, 1); MockGetTokenTypeFlag(ATokenTypeEnum::TOKEN_NATIVE); AdvancedNotificationService advancedNotificationService; -- Gitee From a365d453e07b8951e2b76c146a2fa0c32236e441 Mon Sep 17 00:00:00 2001 From: luojingsong Date: Thu, 9 Jan 2025 09:26:52 +0800 Subject: [PATCH 165/167] =?UTF-8?q?=E5=85=8D=E6=89=93=E6=89=B0=E9=97=AE?= =?UTF-8?q?=E9=A2=98=E5=A4=84=E7=90=86?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: luojingsong Change-Id: I5c9dfce5d4f1e9cdf3bda9eea4f31f91e70af152 --- services/ans/src/advanced_notification_publish_service.cpp | 1 + 1 file changed, 1 insertion(+) diff --git a/services/ans/src/advanced_notification_publish_service.cpp b/services/ans/src/advanced_notification_publish_service.cpp index 35e5ea9ca..82fd06467 100644 --- a/services/ans/src/advanced_notification_publish_service.cpp +++ b/services/ans/src/advanced_notification_publish_service.cpp @@ -220,6 +220,7 @@ ErrCode AdvancedNotificationService::PublishNotificationForIndirectProxy(const s ANS_LOGE("Can not assign valid slot!"); } + CheckDoNotDisturbProfile(record); ChangeNotificationByControlFlags(record, isAgentController); if (IsSaCreateSystemLiveViewAsBundle(record, ipcUid) && (std::static_pointer_cast( -- Gitee From dd0559d11eb0f273d62ed7fc370ed552047c9c0a Mon Sep 17 00:00:00 2001 From: luojingsong Date: Mon, 13 Jan 2025 19:04:08 +0800 Subject: [PATCH 166/167] =?UTF-8?q?=E5=A4=84=E7=90=86alert?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: luojingsong Change-Id: I835d778e9d0bef42a4abaf1f1796a135af9a6608 --- services/ans/src/advanced_notification_utils.cpp | 1 + 1 file changed, 1 insertion(+) diff --git a/services/ans/src/advanced_notification_utils.cpp b/services/ans/src/advanced_notification_utils.cpp index a0e22d5b3..b7e6baa68 100644 --- a/services/ans/src/advanced_notification_utils.cpp +++ b/services/ans/src/advanced_notification_utils.cpp @@ -1968,6 +1968,7 @@ void AdvancedNotificationService::CloseAlert(const std::shared_ptrSetSoundEnabled(NotificationConstant::FlagStatus::CLOSE); flag->SetLightScreenEnabled(false); flag->SetVibrationEnabled(NotificationConstant::FlagStatus::CLOSE); + flag->SetBannerEnabled(false); record->request->SetFlags(flag); ANS_LOGI("SetFlags-CloseAlert, notificationKey = %{public}s flags = %{public}d", record->request->GetKey().c_str(), flag->GetReminderFlags()); -- Gitee From 2d0a7bc7fdfb01dfa722c090cc04b059b90d0c67 Mon Sep 17 00:00:00 2001 From: luojingsong Date: Mon, 20 Jan 2025 20:00:46 +0800 Subject: [PATCH 167/167] TDD Signed-off-by: luojingsong Change-Id: I847186e7002d09646f81e73bfe17bbfe237fdcd8 --- .../unittest/notification_sorting_test.cpp | 2 +- .../notification_subscribe_info_test.cpp | 2 +- .../notification_shell_command_dump_test.cpp | 41 +++++++++++++++---- 3 files changed, 36 insertions(+), 9 deletions(-) diff --git a/frameworks/ans/test/unittest/notification_sorting_test.cpp b/frameworks/ans/test/unittest/notification_sorting_test.cpp index e28edabc1..d57a2d5dc 100644 --- a/frameworks/ans/test/unittest/notification_sorting_test.cpp +++ b/frameworks/ans/test/unittest/notification_sorting_test.cpp @@ -132,7 +132,7 @@ HWTEST_F(NotificationSortingTest, Dump_00001, Function | SmallTest | Level1) "visiblenessOverride = 30, isDisplayBadge = false, isHiddenNotification = true, " "groupKeyOverride = GroupKeyOverride, slot = NotificationSlot{ id = OTHER, name " "= OTHER, description = , type = 3, level = 1, isBypassDnd = false, visibleness = " - "3, sound = , isLightEnabled = false, lightColor = 0, isVibrate = false, vibration " + "3, sound = file://system/etc/Light.ogg, isLightEnabled = false, lightColor = 0, isVibrate = false, vibration " "= , isShowBadge = true, enabled = true, slotFlags = 0, remindMode = 0 } }"; EXPECT_EQ(rrc->Dump(), ret); } diff --git a/frameworks/ans/test/unittest/notification_subscribe_info_test.cpp b/frameworks/ans/test/unittest/notification_subscribe_info_test.cpp index 10766f6ac..d01af4692 100644 --- a/frameworks/ans/test/unittest/notification_subscribe_info_test.cpp +++ b/frameworks/ans/test/unittest/notification_subscribe_info_test.cpp @@ -167,7 +167,7 @@ HWTEST_F(NotificationSubscribeInfoTest, Dump_00001, Function | SmallTest | Level "appNames = [" + appName + ", ]" + "deviceType = " + deviceType + "userId = " + std::to_string(userId) + - " }"; + "slotTypes = []filterType = 0 }"; EXPECT_EQ(res, rrc->Dump()); } } diff --git a/tools/test/unittest/dump/notification_shell_command_dump_test.cpp b/tools/test/unittest/dump/notification_shell_command_dump_test.cpp index c7e9b2fca..8d0677864 100644 --- a/tools/test/unittest/dump/notification_shell_command_dump_test.cpp +++ b/tools/test/unittest/dump/notification_shell_command_dump_test.cpp @@ -61,11 +61,20 @@ static char g_dumpActiveUser[] = " --receiver, -r dump the info filter by the specified receiver userId\n"; static char g_enableErrorInformation[] = -"error: option 'e' requires a value.\nusage: anm setting []\noptions list:\n" +"error: option 'e' requires a value.\n" +"usage: anm setting []\n" +"options list:\n" " --help, -h help menu\n" -" --recent-count -c set the max count of recent notifications keeping in memory\n --enable-notification" -" -e set notification enabled for the bundle, eg: -e com.example:10100:1\n --set-device-status" -" -d set device status, eg: -d device:1\n"; +" --recent-count -c set the max count of recent notifications keeping in memory\n" +" --enable-notification -e set notification enabled for the bundle, " +"eg: -e com.example:10100:1\n" +" --set-device-status -d set device status, eg: -d device:1\n" +" --collaboration-switch -k set collaboration status, eg: -k wearable:1\n" +" --collaboration-switch-bundle -b set bundle collaboration switch status\n" +" eg: -b wearable:example:10100:1\n" +" --collaboration-switch-slot -o set slot collaboration switch status\n" +" --get-device-status -o set device status\n" +" eg: -o wearable:0:1\n"; static char g_enableBundleNameNull[] = "error: setting information error\n" @@ -73,7 +82,13 @@ static char g_enableBundleNameNull[] = "options list:\n --help, -h help menu\n" " --recent-count -c set the max count of recent notifications keeping in memory\n --enable-notification" " -e set notification enabled for the bundle, eg: -e com.example:10100:1\n --set-device-status" -" -d set device status, eg: -d device:1\n"; +" -d set device status, eg: -d device:1\n" +" --collaboration-switch -k set collaboration status, eg: -k wearable:1\n" +" --collaboration-switch-bundle -b set bundle collaboration switch status\n" +" eg: -b wearable:example:10100:1\n" +" --collaboration-switch-slot -o set slot collaboration switch status\n" +" --get-device-status -o set device status\n" +" eg: -o wearable:0:1\n"; static char g_enableObjectNull[] = "error: object is null\n" @@ -82,7 +97,13 @@ static char g_enableObjectNull[] = "options list:\n --help, -h help menu\n" " --recent-count -c set the max count of recent notifications keeping in memory\n --enable-notification" " -e set notification enabled for the bundle, eg: -e com.example:10100:1\n --set-device-status" -" -d set device status, eg: -d device:1\n"; +" -d set device status, eg: -d device:1\n" +" --collaboration-switch -k set collaboration status, eg: -k wearable:1\n" +" --collaboration-switch-bundle -b set bundle collaboration switch status\n" +" eg: -b wearable:example:10100:1\n" +" --collaboration-switch-slot -o set slot collaboration switch status\n" +" --get-device-status -o set device status\n" +" eg: -o wearable:0:1\n"; static char g_unknownOption[] = "error: unknown option.\n" @@ -102,7 +123,13 @@ static char g_dumpActiveCount[] = " --help, -h help menu\n" " --recent-count -c set the max count of recent notifications keeping in memory\n --enable-notification" " -e set notification enabled for the bundle, eg: -e com.example:10100:1\n --set-device-status" -" -d set device status, eg: -d device:1\n"; +" -d set device status, eg: -d device:1\n" +" --collaboration-switch -k set collaboration status, eg: -k wearable:1\n" +" --collaboration-switch-bundle -b set bundle collaboration switch status\n" +" eg: -b wearable:example:10100:1\n" +" --collaboration-switch-slot -o set slot collaboration switch status\n" +" --get-device-status -o set device status\n" +" eg: -o wearable:0:1\n"; static char g_helpMsg[] = "error: unknown option.\n" -- Gitee