• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright (c) 2021-2023 Huawei Device Co., Ltd.
3  * Licensed under the Apache License, Version 2.0 (the "License");
4  * you may not use this file except in compliance with the License.
5  * You may obtain a copy of the License at
6  *
7  *     http://www.apache.org/licenses/LICENSE-2.0
8  *
9  * Unless required by applicable law or agreed to in writing, software
10  * distributed under the License is distributed on an "AS IS" BASIS,
11  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12  * See the License for the specific language governing permissions and
13  * limitations under the License.
14  */
15 
16 #include "advanced_notification_service.h"
17 
18 #include <functional>
19 #include <iomanip>
20 #include <sstream>
21 
22 #include "ability_context.h"
23 #include "ability_info.h"
24 #include "access_token_helper.h"
25 #include "accesstoken_kit.h"
26 #include "ans_const_define.h"
27 #include "ans_inner_errors.h"
28 #include "ans_log_wrapper.h"
29 #include "ans_watchdog.h"
30 #include "ans_permission_def.h"
31 #include "bundle_manager_helper.h"
32 #ifdef DEVICE_USAGE_STATISTICS_ENABLE
33 #include "bundle_active_client.h"
34 #endif
35 #include "common_event_manager.h"
36 #include "common_event_support.h"
37 #include "event_report.h"
38 #include "hitrace_meter.h"
39 #include "ipc_skeleton.h"
40 #include "nlohmann/json.hpp"
41 #include "notification_constant.h"
42 #include "notification_dialog.h"
43 #include "notification_filter.h"
44 #include "notification_preferences.h"
45 #include "notification_slot.h"
46 #include "notification_slot_filter.h"
47 #include "notification_subscriber_manager.h"
48 #include "os_account_manager.h"
49 #include "permission_filter.h"
50 #include "push_callback_proxy.h"
51 #include "reminder_data_manager.h"
52 #include "trigger_info.h"
53 #include "want_agent_helper.h"
54 
55 #ifdef DISTRIBUTED_NOTIFICATION_SUPPORTED
56 #include "distributed_notification_manager.h"
57 #include "distributed_preferences.h"
58 #include "distributed_screen_status_manager.h"
59 #endif
60 
61 namespace OHOS {
62 namespace Notification {
63 namespace {
64 constexpr char ACTIVE_NOTIFICATION_OPTION[] = "active";
65 constexpr char RECENT_NOTIFICATION_OPTION[] = "recent";
66 constexpr char HELP_NOTIFICATION_OPTION[] = "help";
67 #ifdef DISTRIBUTED_NOTIFICATION_SUPPORTED
68 constexpr char DISTRIBUTED_NOTIFICATION_OPTION[] = "distributed";
69 #endif
70 constexpr char SET_RECENT_COUNT_OPTION[] = "setRecentCount";
71 constexpr char FOUNDATION_BUNDLE_NAME[] = "ohos.global.systemres";
72 
73 constexpr int32_t DEFAULT_RECENT_COUNT = 16;
74 
75 constexpr int32_t HOURS_IN_ONE_DAY = 24;
76 
77 constexpr int32_t DIALOG_DEFAULT_WIDTH = 400;
78 constexpr int32_t DIALOG_DEFAULT_HEIGHT = 240;
79 constexpr int32_t WINDOW_DEFAULT_WIDTH = 720;
80 constexpr int32_t WINDOW_DEFAULT_HEIGHT = 1280;
81 constexpr int32_t UI_HALF = 2;
82 
83 constexpr char HIDUMPER_HELP_MSG[] =
84     "Usage:dump <command> [options]\n"
85     "Description::\n"
86     "  --active, -a                 list all active notifications\n"
87     "  --recent, -r                 list recent notifications\n";
88 
89 constexpr char HIDUMPER_ERR_MSG[] =
90     "error: unknown option.\nThe arguments are illegal and you can enter '-h' for help.";
91 
92 const std::unordered_map<std::string, std::string> HIDUMPER_CMD_MAP = {
93     { "--help", HELP_NOTIFICATION_OPTION },
94     { "--active", ACTIVE_NOTIFICATION_OPTION },
95     { "--recent", RECENT_NOTIFICATION_OPTION },
96     { "-h", HELP_NOTIFICATION_OPTION },
97     { "-a", ACTIVE_NOTIFICATION_OPTION },
98     { "-r", RECENT_NOTIFICATION_OPTION },
99 };
100 
101 struct RecentNotification {
102     sptr<Notification> notification = nullptr;
103     bool isActive = false;
104     int32_t deleteReason = 0;
105     int64_t deleteTime = 0;
106 };
107 }  // namespace
108 
109 struct AdvancedNotificationService::RecentInfo {
110     std::list<std::shared_ptr<RecentNotification>> list;
111     size_t recentCount = DEFAULT_RECENT_COUNT;
112 };
113 
114 sptr<AdvancedNotificationService> AdvancedNotificationService::instance_;
115 std::mutex AdvancedNotificationService::instanceMutex_;
116 std::mutex AdvancedNotificationService::pushMutex_;
117 sptr<IPushCallBack> AdvancedNotificationService::pushCallBack_;
118 
GetClientBundleName()119 inline std::string GetClientBundleName()
120 {
121     std::string bundle;
122 
123     int32_t callingUid = IPCSkeleton::GetCallingUid();
124 
125     std::shared_ptr<BundleManagerHelper> bundleManager = BundleManagerHelper::GetInstance();
126     if (bundleManager != nullptr) {
127         bundle = bundleManager->GetBundleNameByUid(callingUid);
128     }
129 
130     return bundle;
131 }
132 
ResetSeconds(int64_t date)133 inline int64_t ResetSeconds(int64_t date)
134 {
135     auto milliseconds = std::chrono::milliseconds(date);
136     auto tp = std::chrono::time_point<std::chrono::system_clock, std::chrono::milliseconds>(milliseconds);
137     auto tp_minutes = std::chrono::time_point_cast<std::chrono::minutes>(tp);
138     auto duration = std::chrono::duration_cast<std::chrono::milliseconds>(tp_minutes.time_since_epoch());
139     return duration.count();
140 }
141 
GetCurrentTime()142 inline int64_t GetCurrentTime()
143 {
144     auto now = std::chrono::system_clock::now();
145     auto duration = std::chrono::duration_cast<std::chrono::milliseconds>(now.time_since_epoch());
146     return duration.count();
147 }
148 
GetLocalTime(time_t time)149 inline tm GetLocalTime(time_t time)
150 {
151     struct tm ret = {0};
152     localtime_r(&time, &ret);
153     return ret;
154 }
155 
AssignValidNotificationSlot(const std::shared_ptr<NotificationRecord> & record)156 inline ErrCode AssignValidNotificationSlot(const std::shared_ptr<NotificationRecord> &record)
157 {
158     sptr<NotificationSlot> slot;
159     NotificationConstant::SlotType slotType = record->request->GetSlotType();
160     ErrCode result = NotificationPreferences::GetInstance().GetNotificationSlot(record->bundleOption, slotType, slot);
161     if ((result == ERR_ANS_PREFERENCES_NOTIFICATION_BUNDLE_NOT_EXIST) ||
162         (result == ERR_ANS_PREFERENCES_NOTIFICATION_SLOT_TYPE_NOT_EXIST)) {
163         slot = new NotificationSlot(slotType);
164         std::vector<sptr<NotificationSlot>> slots;
165         slots.push_back(slot);
166         result = NotificationPreferences::GetInstance().AddNotificationSlots(record->bundleOption, slots);
167     }
168     if (result == ERR_OK) {
169         if (slot != nullptr && slot->GetEnable()) {
170             record->slot = slot;
171         } else {
172             result = ERR_ANS_PREFERENCES_NOTIFICATION_SLOT_ENABLED;
173             ANS_LOGE("Type[%{public}d] slot enable closed", slotType);
174         }
175     }
176     return result;
177 }
178 
CheckPictureSize(const sptr<NotificationRequest> & request)179 inline ErrCode CheckPictureSize(const sptr<NotificationRequest> &request)
180 {
181     ErrCode result = ERR_OK;
182 
183     auto content = request->GetContent();
184     if (content != nullptr && content->GetContentType() == NotificationContent::Type::PICTURE) {
185         std::shared_ptr<NotificationPictureContent> pictureContent =
186             std::static_pointer_cast<NotificationPictureContent>(content->GetNotificationContent());
187         if (pictureContent != nullptr) {
188             auto picture = pictureContent->GetBigPicture();
189             if (picture != nullptr && static_cast<uint32_t>(picture->GetByteCount()) > MAX_PICTURE_SIZE) {
190                 result = ERR_ANS_PICTURE_OVER_SIZE;
191             }
192         }
193     }
194 
195     auto littleIcon = request->GetLittleIcon();
196     if (littleIcon != nullptr && static_cast<uint32_t>(littleIcon->GetByteCount()) > MAX_ICON_SIZE) {
197         result = ERR_ANS_ICON_OVER_SIZE;
198     }
199 
200     auto bigIcon = request->GetBigIcon();
201     if (bigIcon != nullptr && static_cast<uint32_t>(bigIcon->GetByteCount()) > MAX_ICON_SIZE) {
202         result = ERR_ANS_ICON_OVER_SIZE;
203     }
204 
205     return result;
206 }
207 
PrepareNotificationRequest(const sptr<NotificationRequest> & request)208 ErrCode AdvancedNotificationService::PrepareNotificationRequest(const sptr<NotificationRequest> &request)
209 {
210     ANS_LOGD("%{public}s", __FUNCTION__);
211 
212     std::string bundle = GetClientBundleName();
213     if (bundle.empty()) {
214         return ERR_ANS_INVALID_BUNDLE;
215     }
216     if (request == nullptr) {
217         ANSR_LOGE("NotificationRequest object is nullptr");
218         return ERR_ANS_INVALID_PARAM;
219     }
220 
221     if (request == nullptr) {
222         ANSR_LOGE("NotificationRequest object is nullptr");
223         return ERR_ANS_INVALID_PARAM;
224     }
225 
226     if (request->IsAgentNotification()) {
227         bool isSubsystem = AccessTokenHelper::VerifyNativeToken(IPCSkeleton::GetCallingTokenID());
228         if (!isSubsystem && !AccessTokenHelper::IsSystemApp()) {
229             return ERR_ANS_NON_SYSTEM_APP;
230         }
231 
232         if (!CheckPermission(OHOS_PERMISSION_NOTIFICATION_CONTROLLER) ||
233             !CheckPermission(OHOS_PERMISSION_NOTIFICATION_AGENT_CONTROLLER)) {
234             return ERR_ANS_PERMISSION_DENIED;
235         }
236 
237         std::shared_ptr<BundleManagerHelper> bundleManager = BundleManagerHelper::GetInstance();
238         int32_t uid = -1;
239         if (bundleManager != nullptr) {
240             uid = bundleManager->GetDefaultUidByBundleName(request->GetOwnerBundleName(), request->GetOwnerUserId());
241         }
242         if (uid < 0) {
243             return ERR_ANS_INVALID_UID;
244         }
245         request->SetOwnerUid(uid);
246     } else {
247         request->SetOwnerBundleName(bundle);
248     }
249     request->SetCreatorBundleName(bundle);
250 
251     int32_t uid = IPCSkeleton::GetCallingUid();
252     int32_t pid = IPCSkeleton::GetCallingPid();
253     request->SetCreatorUid(uid);
254     request->SetCreatorPid(pid);
255 
256     int32_t userId = SUBSCRIBE_USER_INIT;
257     OHOS::AccountSA::OsAccountManager::GetOsAccountLocalIdFromUid(uid, userId);
258     request->SetCreatorUserId(userId);
259     ErrCode result = CheckPictureSize(request);
260 
261     if (request->GetDeliveryTime() <= 0) {
262         request->SetDeliveryTime(GetCurrentTime());
263     }
264 
265     return result;
266 }
267 
GetInstance()268 sptr<AdvancedNotificationService> AdvancedNotificationService::GetInstance()
269 {
270     std::lock_guard<std::mutex> lock(instanceMutex_);
271 
272     if (instance_ == nullptr) {
273         instance_ = new AdvancedNotificationService();
274     }
275     return instance_;
276 }
277 
AdvancedNotificationService()278 AdvancedNotificationService::AdvancedNotificationService()
279 {
280     ANS_LOGI("constructor");
281     notificationSvrQueue_ = std::make_shared<ffrt::queue>("NotificationSvrMain");
282     if (!notificationSvrQueue_) {
283         ANS_LOGE("ffrt create failed!");
284     }
285     recentInfo_ = std::make_shared<RecentInfo>();
286     distributedKvStoreDeathRecipient_ = std::make_shared<DistributedKvStoreDeathRecipient>(
287         std::bind(&AdvancedNotificationService::OnDistributedKvStoreDeathRecipient, this));
288 
289     StartFilters();
290 
291     ISystemEvent iSystemEvent = {
292         std::bind(&AdvancedNotificationService::OnBundleRemoved, this, std::placeholders::_1),
293 #ifdef DISTRIBUTED_NOTIFICATION_SUPPORTED
294         std::bind(&AdvancedNotificationService::OnScreenOn, this),
295         std::bind(&AdvancedNotificationService::OnScreenOff, this),
296 #endif
297         std::bind(&AdvancedNotificationService::OnResourceRemove, this, std::placeholders::_1),
298         std::bind(&AdvancedNotificationService::OnBundleDataCleared, this, std::placeholders::_1),
299     };
300     systemEventObserver_ = std::make_shared<SystemEventObserver>(iSystemEvent);
301 
302     dataManager_.RegisterKvStoreServiceDeathRecipient(distributedKvStoreDeathRecipient_);
303 
304 #ifdef DISTRIBUTED_NOTIFICATION_SUPPORTED
305     DistributedNotificationManager::IDistributedCallback distributedCallback = {
306         .OnPublish = std::bind(&AdvancedNotificationService::OnDistributedPublish,
307             this,
308             std::placeholders::_1,
309             std::placeholders::_2,
310             std::placeholders::_3),
311         .OnUpdate = std::bind(&AdvancedNotificationService::OnDistributedUpdate,
312             this,
313             std::placeholders::_1,
314             std::placeholders::_2,
315             std::placeholders::_3),
316         .OnDelete = std::bind(&AdvancedNotificationService::OnDistributedDelete,
317             this,
318             std::placeholders::_1,
319             std::placeholders::_2,
320             std::placeholders::_3,
321             std::placeholders::_4),
322     };
323     DistributedNotificationManager::GetInstance()->RegisterCallback(distributedCallback);
324 #endif
325     permissonFilter_ = std::make_shared<PermissionFilter>();
326     notificationSlotFilter_ = std::make_shared<NotificationSlotFilter>();
327 }
328 
~AdvancedNotificationService()329 AdvancedNotificationService::~AdvancedNotificationService()
330 {
331     ANS_LOGI("deconstructor");
332     dataManager_.UnRegisterKvStoreServiceDeathRecipient(distributedKvStoreDeathRecipient_);
333 
334     StopFilters();
335 #ifdef DISTRIBUTED_NOTIFICATION_SUPPORTED
336     DistributedNotificationManager::GetInstance()->UngegisterCallback();
337 #endif
338     SelfClean();
339 }
340 
SelfClean()341 void AdvancedNotificationService::SelfClean()
342 {
343     if (notificationSvrQueue_ != nullptr) {
344         notificationSvrQueue_.reset();
345     }
346 
347     NotificationSubscriberManager::GetInstance()->ResetFfrtQueue();
348     DistributedNotificationManager::GetInstance()->ResetFfrtQueue();
349 }
350 
SetDefaultNotificationEnabled(const sptr<NotificationBundleOption> & bundleOption,bool enabled)351 ErrCode AdvancedNotificationService::SetDefaultNotificationEnabled(
352     const sptr<NotificationBundleOption> &bundleOption, bool enabled)
353 {
354     sptr<NotificationBundleOption> bundle = GenerateValidBundleOption(bundleOption);
355     if (bundle == nullptr) {
356         return ERR_ANS_INVALID_BUNDLE;
357     }
358     sptr<EnabledNotificationCallbackData> bundleData =
359         new EnabledNotificationCallbackData(bundle->GetBundleName(), bundle->GetUid(), enabled);
360 
361     ErrCode result = ERR_OK;
362     result = NotificationPreferences::GetInstance().SetNotificationsEnabledForBundle(bundle, enabled);
363 
364     if (!enabled) {
365         ANS_LOGI("result = %{public}d", result);
366         result = RemoveAllNotifications(bundle);
367     }
368     if (result == ERR_OK) {
369         NotificationSubscriberManager::GetInstance()->NotifyEnabledNotificationChanged(bundleData);
370         PublishSlotChangeCommonEvent(bundle);
371     }
372 
373     SendEnableNotificationHiSysEvent(bundleOption, enabled, result);
374     return result;
375 }
376 
GenerateBundleOption()377 sptr<NotificationBundleOption> AdvancedNotificationService::GenerateBundleOption()
378 {
379     sptr<NotificationBundleOption> bundleOption = nullptr;
380     std::string bundle = GetClientBundleName();
381     if (bundle.empty()) {
382         return nullptr;
383     }
384     int32_t uid = IPCSkeleton::GetCallingUid();
385     bundleOption = new NotificationBundleOption(bundle, uid);
386     return bundleOption;
387 }
388 
GenerateValidBundleOption(const sptr<NotificationBundleOption> & bundleOption)389 sptr<NotificationBundleOption> AdvancedNotificationService::GenerateValidBundleOption(
390     const sptr<NotificationBundleOption> &bundleOption)
391 {
392     sptr<NotificationBundleOption> validBundleOption = nullptr;
393     if (bundleOption->GetUid() <= 0) {
394         std::shared_ptr<BundleManagerHelper> bundleManager = BundleManagerHelper::GetInstance();
395         if (bundleManager != nullptr) {
396             int32_t activeUserId = -1;
397             if (!GetActiveUserId(activeUserId)) {
398                 ANS_LOGE("Failed to get active user id!");
399                 return validBundleOption;
400             }
401             int32_t uid = bundleManager->GetDefaultUidByBundleName(bundleOption->GetBundleName(), activeUserId);
402             if (uid > 0) {
403                 validBundleOption = new NotificationBundleOption(bundleOption->GetBundleName(), uid);
404             }
405         }
406     } else {
407         validBundleOption = bundleOption;
408     }
409     return validBundleOption;
410 }
411 
AssignToNotificationList(const std::shared_ptr<NotificationRecord> & record)412 ErrCode AdvancedNotificationService::AssignToNotificationList(const std::shared_ptr<NotificationRecord> &record)
413 {
414     ErrCode result = ERR_OK;
415     if (!IsNotificationExists(record->notification->GetKey())) {
416         result = FlowControl(record);
417     } else {
418         if (record->request->IsAlertOneTime()) {
419             record->notification->SetEnableLight(false);
420             record->notification->SetEnableSound(false);
421             record->notification->SetEnableVibration(false);
422         }
423         UpdateInNotificationList(record);
424     }
425     return result;
426 }
427 
CancelPreparedNotification(int32_t notificationId,const std::string & label,const sptr<NotificationBundleOption> & bundleOption)428 ErrCode AdvancedNotificationService::CancelPreparedNotification(
429     int32_t notificationId, const std::string &label, const sptr<NotificationBundleOption> &bundleOption)
430 {
431     HITRACE_METER_NAME(HITRACE_TAG_NOTIFICATION, __PRETTY_FUNCTION__);
432     if (bundleOption == nullptr) {
433         return ERR_ANS_INVALID_BUNDLE;
434     }
435 
436     if (notificationSvrQueue_ == nullptr) {
437         ANS_LOGE("Serial queue is invalid.");
438         return ERR_ANS_INVALID_PARAM;
439     }
440     ErrCode result = ERR_OK;
441     ffrt::task_handle handler = notificationSvrQueue_->submit_h(std::bind([&]() {
442         ANS_LOGD("ffrt enter!");
443         sptr<Notification> notification = nullptr;
444         result = RemoveFromNotificationList(bundleOption, label, notificationId, notification, true);
445         if (result != ERR_OK) {
446             return;
447         }
448 
449         if (notification != nullptr) {
450             int32_t reason = NotificationConstant::APP_CANCEL_REASON_DELETE;
451             UpdateRecentNotification(notification, true, reason);
452             NotificationSubscriberManager::GetInstance()->NotifyCanceled(notification, nullptr, reason);
453 #ifdef DISTRIBUTED_NOTIFICATION_SUPPORTED
454             DoDistributedDelete("", "", notification);
455 #endif
456         }
457     }));
458     notificationSvrQueue_->wait(handler);
459     SendCancelHiSysEvent(notificationId, label, bundleOption, result);
460     return result;
461 }
462 
PrepareNotificationInfo(const sptr<NotificationRequest> & request,sptr<NotificationBundleOption> & bundleOption)463 ErrCode AdvancedNotificationService::PrepareNotificationInfo(
464     const sptr<NotificationRequest> &request, sptr<NotificationBundleOption> &bundleOption)
465 {
466     HITRACE_METER_NAME(HITRACE_TAG_NOTIFICATION, __PRETTY_FUNCTION__);
467     if (request == nullptr) {
468         ANS_LOGE("request is invalid.");
469         return ERR_ANS_INVALID_PARAM;
470     }
471     bool isSubsystem = AccessTokenHelper::VerifyNativeToken(IPCSkeleton::GetCallingTokenID());
472     if ((request->GetSlotType() == NotificationConstant::SlotType::CUSTOM) &&
473         !AccessTokenHelper::IsSystemApp() && !isSubsystem) {
474         return ERR_ANS_NON_SYSTEM_APP;
475     }
476     ErrCode result = PrepareNotificationRequest(request);
477     if (result != ERR_OK) {
478         return result;
479     }
480 
481     if (request->IsAgentNotification()) {
482         bundleOption = new (std::nothrow) NotificationBundleOption(request->GetOwnerBundleName(),
483             request->GetOwnerUid());
484     } else {
485         bundleOption = GenerateBundleOption();
486     }
487 
488     if (bundleOption == nullptr) {
489         return ERR_ANS_INVALID_BUNDLE;
490     }
491     ANS_LOGI(
492         "bundleName=%{public}s, uid=%{public}d", (bundleOption->GetBundleName()).c_str(), bundleOption->GetUid());
493     return ERR_OK;
494 }
495 
PublishPreparedNotification(const sptr<NotificationRequest> & request,const sptr<NotificationBundleOption> & bundleOption)496 ErrCode AdvancedNotificationService::PublishPreparedNotification(
497     const sptr<NotificationRequest> &request, const sptr<NotificationBundleOption> &bundleOption)
498 {
499     HITRACE_METER_NAME(HITRACE_TAG_NOTIFICATION, __PRETTY_FUNCTION__);
500     ANS_LOGI("PublishPreparedNotification");
501     auto record = std::make_shared<NotificationRecord>();
502     record->request = request;
503     record->notification = new (std::nothrow) Notification(request);
504 
505     if (record->notification == nullptr) {
506         ANS_LOGE("Failed to create notification.");
507         return ERR_ANS_NO_MEMORY;
508     }
509     record->bundleOption = bundleOption;
510     SetNotificationRemindType(record->notification, true);
511 
512     if (notificationSvrQueue_ == nullptr) {
513         ANS_LOGE("Serial queue is invalid.");
514         return ERR_ANS_INVALID_PARAM;
515     }
516     ErrCode result = ERR_OK;
517     ffrt::task_handle handler = notificationSvrQueue_->submit_h(std::bind([&]() {
518         ANS_LOGD("ffrt enter!");
519         result = AssignValidNotificationSlot(record);
520         if (result != ERR_OK) {
521             ANS_LOGE("Can not assign valid slot!");
522             return;
523         }
524 
525         result = Filter(record);
526         if (result != ERR_OK) {
527             ANS_LOGE("Reject by filters: %{public}d", result);
528             return;
529         }
530 
531         result = AssignToNotificationList(record);
532         if (result != ERR_OK) {
533             return;
534         }
535         UpdateRecentNotification(record->notification, false, 0);
536         sptr<NotificationSortingMap> sortingMap = GenerateSortingMap();
537         ReportInfoToResourceSchedule(request->GetCreatorUserId(), bundleOption->GetBundleName());
538         NotificationSubscriberManager::GetInstance()->NotifyConsumed(record->notification, sortingMap);
539 #ifdef DISTRIBUTED_NOTIFICATION_SUPPORTED
540         if (!request->IsAgentNotification()) {
541             DoDistributedPublish(bundleOption, record);
542         }
543 #endif
544     }));
545     notificationSvrQueue_->wait(handler);
546     if (record->request->GetAutoDeletedTime() > GetCurrentTime()) {
547         StartAutoDelete(record);
548     }
549     return result;
550 }
551 
Publish(const std::string & label,const sptr<NotificationRequest> & request)552 ErrCode AdvancedNotificationService::Publish(const std::string &label, const sptr<NotificationRequest> &request)
553 {
554     HITRACE_METER_NAME(HITRACE_TAG_NOTIFICATION, __PRETTY_FUNCTION__);
555     ANS_LOGD("%{public}s", __FUNCTION__);
556 
557     if (!request) {
558         ANSR_LOGE("ReminderRequest object is nullptr");
559         return ERR_ANS_INVALID_PARAM;
560     }
561 
562     if (!request->IsRemoveAllowed()) {
563         if (!AccessTokenHelper::IsSystemApp() || !CheckPermission(OHOS_PERMISSION_NOTIFICATION_CONTROLLER)) {
564             request->SetRemoveAllowed(true);
565         }
566     }
567 
568     ErrCode result = ERR_OK;
569     bool isSubsystem = AccessTokenHelper::VerifyNativeToken(IPCSkeleton::GetCallingTokenID());
570     if (isSubsystem) {
571         return PublishNotificationBySa(request);
572     }
573 
574     do {
575         if (request->GetReceiverUserId() != SUBSCRIBE_USER_INIT) {
576             if (!AccessTokenHelper::IsSystemApp()) {
577                 result = ERR_ANS_NON_SYSTEM_APP;
578                 break;
579             }
580             if (!CheckPermission(OHOS_PERMISSION_NOTIFICATION_CONTROLLER)) {
581                 result = ERR_ANS_PERMISSION_DENIED;
582                 break;
583             }
584         }
585 
586         Security::AccessToken::AccessTokenID callerToken = IPCSkeleton::GetCallingTokenID();
587         if (AccessTokenHelper::IsDlpHap(callerToken)) {
588             result = ERR_ANS_DLP_HAP;
589             ANS_LOGE("DLP hap not allowed to send notifications");
590             break;
591         }
592 
593         sptr<NotificationBundleOption> bundleOption;
594         result = PrepareNotificationInfo(request, bundleOption);
595         if (result != ERR_OK) {
596             break;
597         }
598 
599         if (IsNeedPushCheck(request->GetSlotType())) {
600             result = PushCheck(request);
601         }
602         if (result != ERR_OK) {
603             break;
604         }
605         result = PublishPreparedNotification(request, bundleOption);
606         if (result != ERR_OK) {
607             break;
608         }
609     } while (0);
610 
611     SendPublishHiSysEvent(request, result);
612     return result;
613 }
614 
ReportInfoToResourceSchedule(const int32_t userId,const std::string & bundleName)615 void AdvancedNotificationService::ReportInfoToResourceSchedule(const int32_t userId, const std::string &bundleName)
616 {
617 #ifdef DEVICE_USAGE_STATISTICS_ENABLE
618     DeviceUsageStats::BundleActiveEvent event(DeviceUsageStats::BundleActiveEvent::NOTIFICATION_SEEN, bundleName);
619     DeviceUsageStats::BundleActiveClient::GetInstance().ReportEvent(event, userId);
620 #endif
621 }
622 
IsNotificationExists(const std::string & key)623 bool AdvancedNotificationService::IsNotificationExists(const std::string &key)
624 {
625     bool isExists = false;
626 
627     for (auto item : notificationList_) {
628         if (item->notification->GetKey() == key) {
629             isExists = true;
630             break;
631         }
632     }
633 
634     return isExists;
635 }
636 
Filter(const std::shared_ptr<NotificationRecord> & record)637 ErrCode AdvancedNotificationService::Filter(const std::shared_ptr<NotificationRecord> &record)
638 {
639     if (permissonFilter_ == nullptr || notificationSlotFilter_ == nullptr) {
640         ANS_LOGE("Filter is invalid.");
641         return ERR_ANS_INVALID_PARAM;
642     }
643 
644     auto result = permissonFilter_->OnPublish(record);
645     if (result != ERR_OK) {
646         ANS_LOGE("Permission filter on publish failed with %{public}d.", result);
647         return result;
648     }
649 
650     result = notificationSlotFilter_->OnPublish(record);
651     if (result != ERR_OK) {
652         ANS_LOGE("Notification slot filter on publish failed with %{public}d.", result);
653         return result;
654     }
655 
656     return ERR_OK;
657 }
658 
AddToNotificationList(const std::shared_ptr<NotificationRecord> & record)659 void AdvancedNotificationService::AddToNotificationList(const std::shared_ptr<NotificationRecord> &record)
660 {
661     notificationList_.push_back(record);
662     SortNotificationList();
663 }
664 
UpdateInNotificationList(const std::shared_ptr<NotificationRecord> & record)665 void AdvancedNotificationService::UpdateInNotificationList(const std::shared_ptr<NotificationRecord> &record)
666 {
667     auto iter = notificationList_.begin();
668     while (iter != notificationList_.end()) {
669         if ((*iter)->notification->GetKey() == record->notification->GetKey()) {
670             *iter = record;
671             break;
672         }
673         iter++;
674     }
675 
676     SortNotificationList();
677 }
678 
SortNotificationList()679 void AdvancedNotificationService::SortNotificationList()
680 {
681     notificationList_.sort(AdvancedNotificationService::NotificationCompare);
682 }
683 
NotificationCompare(const std::shared_ptr<NotificationRecord> & first,const std::shared_ptr<NotificationRecord> & second)684 bool AdvancedNotificationService::NotificationCompare(
685     const std::shared_ptr<NotificationRecord> &first, const std::shared_ptr<NotificationRecord> &second)
686 {
687     // sorting notifications by create time
688     return (first->request->GetCreateTime() < second->request->GetCreateTime());
689 }
690 
GenerateSortingMap()691 sptr<NotificationSortingMap> AdvancedNotificationService::GenerateSortingMap()
692 {
693     std::vector<NotificationSorting> sortingList;
694     for (auto record : notificationList_) {
695         NotificationSorting sorting;
696         sorting.SetRanking(static_cast<uint64_t>(sortingList.size()));
697         sorting.SetKey(record->notification->GetKey());
698         sorting.SetSlot(record->slot);
699         sortingList.push_back(sorting);
700     }
701 
702     sptr<NotificationSortingMap> sortingMap = new NotificationSortingMap(sortingList);
703 
704     return sortingMap;
705 }
706 
StartFilters()707 void AdvancedNotificationService::StartFilters()
708 {
709     if (permissonFilter_ != nullptr) {
710         permissonFilter_->OnStart();
711     }
712 
713     if (notificationSlotFilter_ != nullptr) {
714         notificationSlotFilter_->OnStart();
715     }
716 }
717 
StopFilters()718 void AdvancedNotificationService::StopFilters()
719 {
720     if (permissonFilter_ != nullptr) {
721         permissonFilter_->OnStop();
722     }
723 
724     if (notificationSlotFilter_ != nullptr) {
725         notificationSlotFilter_->OnStop();
726     }
727 }
728 
Cancel(int32_t notificationId,const std::string & label)729 ErrCode AdvancedNotificationService::Cancel(int32_t notificationId, const std::string &label)
730 {
731     ANS_LOGD("%{public}s", __FUNCTION__);
732 
733     sptr<NotificationBundleOption> bundleOption = GenerateBundleOption();
734     return CancelPreparedNotification(notificationId, label, bundleOption);
735 }
736 
CancelAll()737 ErrCode AdvancedNotificationService::CancelAll()
738 {
739     ANS_LOGD("%{public}s", __FUNCTION__);
740 
741     sptr<NotificationBundleOption> bundleOption = GenerateBundleOption();
742     if (bundleOption == nullptr) {
743         return ERR_ANS_INVALID_BUNDLE;
744     }
745 
746     if (notificationSvrQueue_ == nullptr) {
747         ANS_LOGE("Serial queue is invalid.");
748         return ERR_ANS_INVALID_PARAM;
749     }
750     ErrCode result = ERR_OK;
751     ffrt::task_handle handler = notificationSvrQueue_->submit_h(std::bind([&]() {
752         ANS_LOGD("ffrt enter!");
753         sptr<Notification> notification = nullptr;
754 
755         std::vector<std::string> keys = GetNotificationKeys(bundleOption);
756         std::vector<sptr<Notification>> notifications;
757         for (auto key : keys) {
758 #ifdef DISTRIBUTED_NOTIFICATION_SUPPORTED
759             std::string deviceId;
760             std::string bundleName;
761             GetDistributedInfo(key, deviceId, bundleName);
762 #endif
763             result = RemoveFromNotificationList(key, notification, true,
764                 NotificationConstant::APP_CANCEL_ALL_REASON_DELETE);
765             if (result != ERR_OK) {
766                 continue;
767             }
768 
769             if (notification != nullptr) {
770                 int32_t reason = NotificationConstant::APP_CANCEL_ALL_REASON_DELETE;
771                 UpdateRecentNotification(notification, true, reason);
772                 notifications.emplace_back(notification);
773 #ifdef DISTRIBUTED_NOTIFICATION_SUPPORTED
774                 DoDistributedDelete(deviceId, bundleName, notification);
775 #endif
776             }
777             if (notifications.size() >= MAX_CANCELED_PARCELABLE_VECTOR_NUM) {
778                 std::vector<sptr<Notification>> currNotificationList = notifications;
779                 NotificationSubscriberManager::GetInstance()->BatchNotifyCanceled(
780                     currNotificationList, nullptr, NotificationConstant::APP_CANCEL_ALL_REASON_DELETE);
781                 notifications.clear();
782             }
783         }
784 
785         if (!notifications.empty()) {
786             NotificationSubscriberManager::GetInstance()->BatchNotifyCanceled(
787                 notifications, nullptr, NotificationConstant::APP_CANCEL_ALL_REASON_DELETE);
788         }
789         result = ERR_OK;
790     }));
791     notificationSvrQueue_->wait(handler);
792     return result;
793 }
794 
CancelAsBundle(int32_t notificationId,const std::string & representativeBundle,int32_t userId)795 ErrCode AdvancedNotificationService::CancelAsBundle(
796     int32_t notificationId, const std::string &representativeBundle, int32_t userId)
797 {
798     ANS_LOGD("%{public}s", __FUNCTION__);
799 
800     bool isSubsystem = AccessTokenHelper::VerifyNativeToken(IPCSkeleton::GetCallingTokenID());
801     if (!isSubsystem && !AccessTokenHelper::IsSystemApp()) {
802         return ERR_ANS_NON_SYSTEM_APP;
803     }
804 
805     if (!CheckPermission(OHOS_PERMISSION_NOTIFICATION_CONTROLLER) ||
806         !CheckPermission(OHOS_PERMISSION_NOTIFICATION_AGENT_CONTROLLER)) {
807         return ERR_ANS_PERMISSION_DENIED;
808     }
809 
810     int32_t uid = -1;
811     std::shared_ptr<BundleManagerHelper> bundleManager = BundleManagerHelper::GetInstance();
812     if (bundleManager != nullptr) {
813         uid = BundleManagerHelper::GetInstance()->GetDefaultUidByBundleName(representativeBundle, userId);
814     }
815     if (uid < 0) {
816         return ERR_ANS_INVALID_UID;
817     }
818     sptr<NotificationBundleOption> bundleOption = new (std::nothrow) NotificationBundleOption(
819         representativeBundle, uid);
820     return CancelPreparedNotification(notificationId, "", bundleOption);
821 }
822 
AddSlots(const std::vector<sptr<NotificationSlot>> & slots)823 ErrCode AdvancedNotificationService::AddSlots(const std::vector<sptr<NotificationSlot>> &slots)
824 {
825     ANS_LOGD("%{public}s", __FUNCTION__);
826 
827     bool isSubsystem = AccessTokenHelper::VerifyNativeToken(IPCSkeleton::GetCallingTokenID());
828     if (!isSubsystem && !AccessTokenHelper::IsSystemApp()) {
829         return ERR_ANS_NON_SYSTEM_APP;
830     }
831 
832     if (!CheckPermission(OHOS_PERMISSION_NOTIFICATION_CONTROLLER)) {
833         return ERR_ANS_PERMISSION_DENIED;
834     }
835 
836     sptr<NotificationBundleOption> bundleOption = GenerateBundleOption();
837     if (bundleOption == nullptr) {
838         return ERR_ANS_INVALID_BUNDLE;
839     }
840 
841     if (slots.size() == 0) {
842         return ERR_ANS_INVALID_PARAM;
843     }
844 
845     if (notificationSvrQueue_ == nullptr) {
846         ANS_LOGE("Serial queue is invalid.");
847         return ERR_ANS_INVALID_PARAM;
848     }
849     ErrCode result = ERR_OK;
850     ffrt::task_handle handler = notificationSvrQueue_->submit_h(std::bind([&]() {
851         ANS_LOGD("ffrt enter!");
852         std::vector<sptr<NotificationSlot>> addSlots;
853         for (auto slot : slots) {
854             sptr<NotificationSlot> originalSlot;
855             result =
856                 NotificationPreferences::GetInstance().GetNotificationSlot(bundleOption, slot->GetType(), originalSlot);
857             if ((result == ERR_OK) && (originalSlot != nullptr)) {
858                 continue;
859             } else {
860                 addSlots.push_back(slot);
861             }
862         }
863 
864         if (addSlots.size() == 0) {
865             result = ERR_OK;
866         } else {
867             result = NotificationPreferences::GetInstance().AddNotificationSlots(bundleOption, addSlots);
868         }
869     }));
870     notificationSvrQueue_->wait(handler);
871     return result;
872 }
873 
GetSlots(std::vector<sptr<NotificationSlot>> & slots)874 ErrCode AdvancedNotificationService::GetSlots(std::vector<sptr<NotificationSlot>> &slots)
875 {
876     ANS_LOGD("%{public}s", __FUNCTION__);
877 
878     sptr<NotificationBundleOption> bundleOption = GenerateBundleOption();
879     if (bundleOption == nullptr) {
880         return ERR_ANS_INVALID_BUNDLE;
881     }
882 
883     if (notificationSvrQueue_ == nullptr) {
884         ANS_LOGE("Serial queue is invalid.");
885         return ERR_ANS_INVALID_PARAM;
886     }
887     ErrCode result = ERR_OK;
888     ffrt::task_handle handler = notificationSvrQueue_->submit_h(std::bind([&]() {
889         ANS_LOGD("ffrt enter!");
890         result = NotificationPreferences::GetInstance().GetNotificationAllSlots(bundleOption, slots);
891         if (result == ERR_ANS_PREFERENCES_NOTIFICATION_BUNDLE_NOT_EXIST) {
892             result = ERR_OK;
893             slots.clear();
894         }
895     }));
896     notificationSvrQueue_->wait(handler);
897     return result;
898 }
899 
GetActiveNotifications(std::vector<sptr<NotificationRequest>> & notifications)900 ErrCode AdvancedNotificationService::GetActiveNotifications(std::vector<sptr<NotificationRequest>> &notifications)
901 {
902     ANS_LOGD("%{public}s", __FUNCTION__);
903 
904     sptr<NotificationBundleOption> bundleOption = GenerateBundleOption();
905     if (bundleOption == nullptr) {
906         return ERR_ANS_INVALID_BUNDLE;
907     }
908 
909     if (notificationSvrQueue_ == nullptr) {
910         ANS_LOGE("Serial queue is invalid.");
911         return ERR_ANS_INVALID_PARAM;
912     }
913     ffrt::task_handle handler = notificationSvrQueue_->submit_h(std::bind([&]() {
914         ANS_LOGD("ffrt enter!");
915         notifications.clear();
916         for (auto record : notificationList_) {
917             if ((record->bundleOption->GetBundleName() == bundleOption->GetBundleName()) &&
918                 (record->bundleOption->GetUid() == bundleOption->GetUid())) {
919                 notifications.push_back(record->request);
920             }
921         }
922     }));
923     notificationSvrQueue_->wait(handler);
924     return ERR_OK;
925 }
926 
GetActiveNotificationNums(uint64_t & num)927 ErrCode AdvancedNotificationService::GetActiveNotificationNums(uint64_t &num)
928 {
929     ANS_LOGD("%{public}s", __FUNCTION__);
930 
931     sptr<NotificationBundleOption> bundleOption = GenerateBundleOption();
932     if (bundleOption == nullptr) {
933         return ERR_ANS_INVALID_BUNDLE;
934     }
935 
936     if (notificationSvrQueue_ == nullptr) {
937         ANS_LOGE("Serial queue is invalid.");
938         return ERR_ANS_INVALID_PARAM;
939     }
940     ffrt::task_handle handler = notificationSvrQueue_->submit_h(std::bind([&]() {
941         ANS_LOGD("ffrt enter!");
942         size_t count = 0;
943         for (auto record : notificationList_) {
944             if ((record->bundleOption->GetBundleName() == bundleOption->GetBundleName()) &&
945                 (record->bundleOption->GetUid() == bundleOption->GetUid())) {
946                 count += 1;
947             }
948         }
949         num = static_cast<uint64_t>(count);
950     }));
951     notificationSvrQueue_->wait(handler);
952     return ERR_OK;
953 }
954 
SetNotificationAgent(const std::string & agent)955 ErrCode AdvancedNotificationService::SetNotificationAgent(const std::string &agent)
956 {
957     return ERR_INVALID_OPERATION;
958 }
959 
GetNotificationAgent(std::string & agent)960 ErrCode AdvancedNotificationService::GetNotificationAgent(std::string &agent)
961 {
962     return ERR_INVALID_OPERATION;
963 }
964 
CanPublishAsBundle(const std::string & representativeBundle,bool & canPublish)965 ErrCode AdvancedNotificationService::CanPublishAsBundle(const std::string &representativeBundle, bool &canPublish)
966 {
967     return ERR_INVALID_OPERATION;
968 }
969 
PublishAsBundle(const sptr<NotificationRequest> notification,const std::string & representativeBundle)970 ErrCode AdvancedNotificationService::PublishAsBundle(
971     const sptr<NotificationRequest> notification, const std::string &representativeBundle)
972 {
973     return ERR_INVALID_OPERATION;
974 }
975 
SetNotificationBadgeNum(int32_t num)976 ErrCode AdvancedNotificationService::SetNotificationBadgeNum(int32_t num)
977 {
978     ANS_LOGD("%{public}s", __FUNCTION__);
979 
980     sptr<NotificationBundleOption> bundleOption = GenerateBundleOption();
981     if (bundleOption == nullptr) {
982         return ERR_ANS_INVALID_BUNDLE;
983     }
984 
985     if (notificationSvrQueue_ == nullptr) {
986         ANS_LOGE("Serial queue is invalid.");
987         return ERR_ANS_INVALID_PARAM;
988     }
989     ErrCode result = ERR_OK;
990     ffrt::task_handle handler = notificationSvrQueue_->submit_h(
991         std::bind([&]() {
992             ANS_LOGD("ffrt enter!");
993             result = NotificationPreferences::GetInstance().SetTotalBadgeNums(bundleOption, num);
994         }));
995     notificationSvrQueue_->wait(handler);
996     return result;
997 }
998 
GetBundleImportance(int32_t & importance)999 ErrCode AdvancedNotificationService::GetBundleImportance(int32_t &importance)
1000 {
1001     ANS_LOGD("%{public}s", __FUNCTION__);
1002 
1003     sptr<NotificationBundleOption> bundleOption = GenerateBundleOption();
1004     if (bundleOption == nullptr) {
1005         return ERR_ANS_INVALID_BUNDLE;
1006     }
1007 
1008     if (notificationSvrQueue_ == nullptr) {
1009         ANS_LOGE("Serial queue is invalid.");
1010         return ERR_ANS_INVALID_PARAM;
1011     }
1012     ErrCode result = ERR_OK;
1013     ffrt::task_handle handler = notificationSvrQueue_->submit_h(
1014         std::bind([&]() {
1015             ANS_LOGD("ffrt enter!");
1016             result = NotificationPreferences::GetInstance().GetImportance(bundleOption, importance);
1017         }));
1018     notificationSvrQueue_->wait(handler);
1019     return result;
1020 }
1021 
HasNotificationPolicyAccessPermission(bool & granted)1022 ErrCode AdvancedNotificationService::HasNotificationPolicyAccessPermission(bool &granted)
1023 {
1024     return ERR_OK;
1025 }
1026 
Delete(const std::string & key,int32_t removeReason)1027 ErrCode AdvancedNotificationService::Delete(const std::string &key, int32_t removeReason)
1028 {
1029     ANS_LOGD("%{public}s", __FUNCTION__);
1030 
1031     bool isSubsystem = AccessTokenHelper::VerifyNativeToken(IPCSkeleton::GetCallingTokenID());
1032     if (!isSubsystem && !AccessTokenHelper::IsSystemApp()) {
1033         return ERR_ANS_NON_SYSTEM_APP;
1034     }
1035 
1036     if (!CheckPermission(OHOS_PERMISSION_NOTIFICATION_CONTROLLER)) {
1037         return ERR_ANS_PERMISSION_DENIED;
1038     }
1039 
1040     if (notificationSvrQueue_ == nullptr) {
1041         ANS_LOGE("Serial queue is invalid.");
1042         return ERR_ANS_INVALID_PARAM;
1043     }
1044     ErrCode result = ERR_OK;
1045     ffrt::task_handle handler = notificationSvrQueue_->submit_h(std::bind([&]() {
1046         ANS_LOGD("ffrt enter!");
1047         sptr<Notification> notification = nullptr;
1048 #ifdef DISTRIBUTED_NOTIFICATION_SUPPORTED
1049         std::string deviceId;
1050         std::string bundleName;
1051         GetDistributedInfo(key, deviceId, bundleName);
1052 #endif
1053         result = RemoveFromNotificationList(key, notification, false, removeReason);
1054         if (result != ERR_OK) {
1055             return;
1056         }
1057 
1058         if (notification != nullptr) {
1059             UpdateRecentNotification(notification, true, removeReason);
1060             NotificationSubscriberManager::GetInstance()->NotifyCanceled(notification, nullptr, removeReason);
1061 #ifdef DISTRIBUTED_NOTIFICATION_SUPPORTED
1062             DoDistributedDelete(deviceId, bundleName, notification);
1063 #endif
1064         }
1065     }));
1066     notificationSvrQueue_->wait(handler);
1067 
1068     return result;
1069 }
1070 
DeleteByBundle(const sptr<NotificationBundleOption> & bundleOption)1071 ErrCode AdvancedNotificationService::DeleteByBundle(const sptr<NotificationBundleOption> &bundleOption)
1072 {
1073     ANS_LOGD("%{public}s", __FUNCTION__);
1074 
1075     bool isSubsystem = AccessTokenHelper::VerifyNativeToken(IPCSkeleton::GetCallingTokenID());
1076     if (!isSubsystem && !AccessTokenHelper::IsSystemApp()) {
1077         return ERR_ANS_NON_SYSTEM_APP;
1078     }
1079 
1080     if (!CheckPermission(OHOS_PERMISSION_NOTIFICATION_CONTROLLER)) {
1081         return ERR_ANS_PERMISSION_DENIED;
1082     }
1083 
1084     sptr<NotificationBundleOption> bundle = GenerateValidBundleOption(bundleOption);
1085     if (bundle == nullptr) {
1086         return ERR_ANS_INVALID_BUNDLE;
1087     }
1088 
1089     if (notificationSvrQueue_ == nullptr) {
1090         ANS_LOGE("Serial queue is invalid.");
1091         return ERR_ANS_INVALID_PARAM;
1092     }
1093     ErrCode result = ERR_OK;
1094     ffrt::task_handle handler = notificationSvrQueue_->submit_h(std::bind([&]() {
1095         ANS_LOGD("ffrt enter!");
1096         std::vector<std::string> keys = GetNotificationKeys(bundle);
1097         for (auto key : keys) {
1098 #ifdef DISTRIBUTED_NOTIFICATION_SUPPORTED
1099             std::string deviceId;
1100             std::string bundleName;
1101             GetDistributedInfo(key, deviceId, bundleName);
1102 #endif
1103             sptr<Notification> notification = nullptr;
1104 
1105             result = RemoveFromNotificationList(key, notification, false, NotificationConstant::CANCEL_REASON_DELETE);
1106             if (result != ERR_OK) {
1107                 continue;
1108             }
1109 
1110             if (notification != nullptr) {
1111                 int32_t reason = NotificationConstant::CANCEL_REASON_DELETE;
1112                 UpdateRecentNotification(notification, true, reason);
1113                 NotificationSubscriberManager::GetInstance()->NotifyCanceled(notification, nullptr, reason);
1114 #ifdef DISTRIBUTED_NOTIFICATION_SUPPORTED
1115                 DoDistributedDelete(deviceId, bundleName, notification);
1116 #endif
1117             }
1118         }
1119 
1120         result = ERR_OK;
1121     }));
1122     notificationSvrQueue_->wait(handler);
1123 
1124     return result;
1125 }
1126 
DeleteAll()1127 ErrCode AdvancedNotificationService::DeleteAll()
1128 {
1129     ANS_LOGD("%{public}s", __FUNCTION__);
1130 
1131     bool isSubsystem = AccessTokenHelper::VerifyNativeToken(IPCSkeleton::GetCallingTokenID());
1132     if (!isSubsystem && !AccessTokenHelper::IsSystemApp()) {
1133         return ERR_ANS_NON_SYSTEM_APP;
1134     }
1135 
1136     if (!CheckPermission(OHOS_PERMISSION_NOTIFICATION_CONTROLLER)) {
1137         return ERR_ANS_PERMISSION_DENIED;
1138     }
1139 
1140     if (notificationSvrQueue_ == nullptr) {
1141         ANS_LOGE("Serial queue is invalid.");
1142         return ERR_ANS_INVALID_PARAM;
1143     }
1144     ErrCode result = ERR_OK;
1145     ffrt::task_handle handler = notificationSvrQueue_->submit_h(std::bind([&]() {
1146         ANS_LOGD("ffrt enter!");
1147         int32_t activeUserId = SUBSCRIBE_USER_INIT;
1148         (void)GetActiveUserId(activeUserId);
1149         std::vector<std::string> keys = GetNotificationKeys(nullptr);
1150         std::vector<sptr<Notification>> notifications;
1151         for (auto key : keys) {
1152 #ifdef DISTRIBUTED_NOTIFICATION_SUPPORTED
1153             std::string deviceId;
1154             std::string bundleName;
1155             GetDistributedInfo(key, deviceId, bundleName);
1156 #endif
1157             sptr<Notification> notification = nullptr;
1158 
1159             result = RemoveFromNotificationListForDeleteAll(key, activeUserId, notification);
1160             if ((result != ERR_OK) || (notification == nullptr)) {
1161                 continue;
1162             }
1163 
1164             if (notification->GetUserId() == activeUserId) {
1165                 int32_t reason = NotificationConstant::CANCEL_ALL_REASON_DELETE;
1166                 UpdateRecentNotification(notification, true, reason);
1167                 notifications.emplace_back(notification);
1168 #ifdef DISTRIBUTED_NOTIFICATION_SUPPORTED
1169                 DoDistributedDelete(deviceId, bundleName, notification);
1170 #endif
1171             }
1172             if (notifications.size() >= MAX_CANCELED_PARCELABLE_VECTOR_NUM) {
1173                 SendNotificationsOnCanceled(notifications, nullptr, NotificationConstant::CANCEL_ALL_REASON_DELETE);
1174             }
1175         }
1176         if (!notifications.empty()) {
1177             NotificationSubscriberManager::GetInstance()->BatchNotifyCanceled(
1178                 notifications, nullptr, NotificationConstant::CANCEL_REASON_DELETE);
1179         }
1180 
1181         result = ERR_OK;
1182     }));
1183     notificationSvrQueue_->wait(handler);
1184 
1185     return result;
1186 }
1187 
GetNotificationKeys(const sptr<NotificationBundleOption> & bundleOption)1188 std::vector<std::string> AdvancedNotificationService::GetNotificationKeys(
1189     const sptr<NotificationBundleOption> &bundleOption)
1190 {
1191     std::vector<std::string> keys;
1192 
1193     for (auto record : notificationList_) {
1194         if ((bundleOption != nullptr) && (record->bundleOption->GetBundleName() != bundleOption->GetBundleName()) &&
1195             (record->bundleOption->GetUid() != bundleOption->GetUid())) {
1196             continue;
1197         }
1198         keys.push_back(record->notification->GetKey());
1199     }
1200 
1201     return keys;
1202 }
1203 
GetSlotsByBundle(const sptr<NotificationBundleOption> & bundleOption,std::vector<sptr<NotificationSlot>> & slots)1204 ErrCode AdvancedNotificationService::GetSlotsByBundle(
1205     const sptr<NotificationBundleOption> &bundleOption, std::vector<sptr<NotificationSlot>> &slots)
1206 {
1207     ANS_LOGD("%{public}s", __FUNCTION__);
1208 
1209     bool isSubsystem = AccessTokenHelper::VerifyNativeToken(IPCSkeleton::GetCallingTokenID());
1210     if (!isSubsystem && !AccessTokenHelper::IsSystemApp()) {
1211         return ERR_ANS_NON_SYSTEM_APP;
1212     }
1213 
1214     if (!CheckPermission(OHOS_PERMISSION_NOTIFICATION_CONTROLLER)) {
1215         return ERR_ANS_PERMISSION_DENIED;
1216     }
1217 
1218     sptr<NotificationBundleOption> bundle = GenerateValidBundleOption(bundleOption);
1219     if (bundle == nullptr) {
1220         return ERR_ANS_INVALID_BUNDLE;
1221     }
1222 
1223     if (notificationSvrQueue_ == nullptr) {
1224         ANS_LOGE("Serial queue is invalid.");
1225         return ERR_ANS_INVALID_PARAM;
1226     }
1227     ErrCode result = ERR_OK;
1228     ffrt::task_handle handler = notificationSvrQueue_->submit_h(std::bind([&]() {
1229         ANS_LOGD("ffrt enter!");
1230         result = NotificationPreferences::GetInstance().GetNotificationAllSlots(bundle, slots);
1231         if (result == ERR_ANS_PREFERENCES_NOTIFICATION_BUNDLE_NOT_EXIST) {
1232             result = ERR_OK;
1233             slots.clear();
1234         }
1235     }));
1236 
1237     notificationSvrQueue_->wait(handler);
1238     return result;
1239 }
1240 
UpdateSlots(const sptr<NotificationBundleOption> & bundleOption,const std::vector<sptr<NotificationSlot>> & slots)1241 ErrCode AdvancedNotificationService::UpdateSlots(
1242     const sptr<NotificationBundleOption> &bundleOption, const std::vector<sptr<NotificationSlot>> &slots)
1243 {
1244     ANS_LOGD("%{public}s", __FUNCTION__);
1245 
1246     bool isSubsystem = AccessTokenHelper::VerifyNativeToken(IPCSkeleton::GetCallingTokenID());
1247     if (!isSubsystem && !AccessTokenHelper::IsSystemApp()) {
1248         return ERR_ANS_NON_SYSTEM_APP;
1249     }
1250 
1251     if (!CheckPermission(OHOS_PERMISSION_NOTIFICATION_CONTROLLER)) {
1252         return ERR_ANS_PERMISSION_DENIED;
1253     }
1254 
1255     sptr<NotificationBundleOption> bundle = GenerateValidBundleOption(bundleOption);
1256     if (bundle == nullptr) {
1257         return ERR_ANS_INVALID_BUNDLE;
1258     }
1259 
1260     if (notificationSvrQueue_ == nullptr) {
1261         ANS_LOGE("Serial queue is invalid.");
1262         return ERR_ANS_INVALID_PARAM;
1263     }
1264     ErrCode result = ERR_OK;
1265     ffrt::task_handle handler = notificationSvrQueue_->submit_h(std::bind([&]() {
1266         ANS_LOGD("ffrt enter!");
1267         result = NotificationPreferences::GetInstance().UpdateNotificationSlots(bundle, slots);
1268         if (result == ERR_ANS_PREFERENCES_NOTIFICATION_BUNDLE_NOT_EXIST) {
1269             result = ERR_ANS_PREFERENCES_NOTIFICATION_SLOT_TYPE_NOT_EXIST;
1270         }
1271     }));
1272     notificationSvrQueue_->wait(handler);
1273 
1274     if (result == ERR_OK) {
1275         PublishSlotChangeCommonEvent(bundle);
1276     }
1277 
1278     return result;
1279 }
1280 
SetShowBadgeEnabledForBundle(const sptr<NotificationBundleOption> & bundleOption,bool enabled)1281 ErrCode AdvancedNotificationService::SetShowBadgeEnabledForBundle(
1282     const sptr<NotificationBundleOption> &bundleOption, bool enabled)
1283 {
1284     ANS_LOGD("%{public}s", __FUNCTION__);
1285 
1286     bool isSubsystem = AccessTokenHelper::VerifyNativeToken(IPCSkeleton::GetCallingTokenID());
1287     if (!isSubsystem && !AccessTokenHelper::IsSystemApp()) {
1288         return ERR_ANS_NON_SYSTEM_APP;
1289     }
1290 
1291     if (!CheckPermission(OHOS_PERMISSION_NOTIFICATION_CONTROLLER)) {
1292         return ERR_ANS_PERMISSION_DENIED;
1293     }
1294 
1295     sptr<NotificationBundleOption> bundle = GenerateValidBundleOption(bundleOption);
1296     if (bundle == nullptr) {
1297         return ERR_ANS_INVALID_BUNDLE;
1298     }
1299 
1300     if (notificationSvrQueue_ == nullptr) {
1301         ANS_LOGE("Serial queue is invalid.");
1302         return ERR_ANS_INVALID_PARAM;
1303     }
1304     ErrCode result = ERR_OK;
1305     ffrt::task_handle handler = notificationSvrQueue_->submit_h(
1306         std::bind([&]() {
1307             result = NotificationPreferences::GetInstance().SetShowBadge(bundle, enabled);
1308             ANS_LOGD("ffrt enter!");
1309         }));
1310     notificationSvrQueue_->wait(handler);
1311     return result;
1312 }
1313 
GetShowBadgeEnabledForBundle(const sptr<NotificationBundleOption> & bundleOption,bool & enabled)1314 ErrCode AdvancedNotificationService::GetShowBadgeEnabledForBundle(
1315     const sptr<NotificationBundleOption> &bundleOption, bool &enabled)
1316 {
1317     ANS_LOGD("%{public}s", __FUNCTION__);
1318 
1319     bool isSubsystem = AccessTokenHelper::VerifyNativeToken(IPCSkeleton::GetCallingTokenID());
1320     if (!isSubsystem && !AccessTokenHelper::IsSystemApp()) {
1321         return ERR_ANS_NON_SYSTEM_APP;
1322     }
1323 
1324     if (!CheckPermission(OHOS_PERMISSION_NOTIFICATION_CONTROLLER)) {
1325         return ERR_ANS_PERMISSION_DENIED;
1326     }
1327 
1328     sptr<NotificationBundleOption> bundle = GenerateValidBundleOption(bundleOption);
1329     if (bundle == nullptr) {
1330         return ERR_ANS_INVALID_BUNDLE;
1331     }
1332 
1333     if (notificationSvrQueue_ == nullptr) {
1334         ANS_LOGE("Serial queue is invalid.");
1335         return ERR_ANS_INVALID_PARAM;
1336     }
1337     ErrCode result = ERR_OK;
1338     ffrt::task_handle handler = notificationSvrQueue_->submit_h(std::bind([&]() {
1339         ANS_LOGD("ffrt enter!");
1340         result = NotificationPreferences::GetInstance().IsShowBadge(bundle, enabled);
1341         if (result == ERR_ANS_PREFERENCES_NOTIFICATION_BUNDLE_NOT_EXIST) {
1342             result = ERR_OK;
1343             enabled = false;
1344         }
1345     }));
1346     notificationSvrQueue_->wait(handler);
1347     return result;
1348 }
1349 
GetShowBadgeEnabled(bool & enabled)1350 ErrCode AdvancedNotificationService::GetShowBadgeEnabled(bool &enabled)
1351 {
1352     ANS_LOGD("%{public}s", __FUNCTION__);
1353 
1354     sptr<NotificationBundleOption> bundleOption = GenerateBundleOption();
1355     if (bundleOption == nullptr) {
1356         return ERR_ANS_INVALID_BUNDLE;
1357     }
1358 
1359     if (notificationSvrQueue_ == nullptr) {
1360         ANS_LOGE("Serial queue is invalid.");
1361         return ERR_ANS_INVALID_PARAM;
1362     }
1363     ErrCode result = ERR_OK;
1364     ffrt::task_handle handler = notificationSvrQueue_->submit_h(std::bind([&]() {
1365         ANS_LOGD("ffrt enter!");
1366         result = NotificationPreferences::GetInstance().IsShowBadge(bundleOption, enabled);
1367         if (result == ERR_ANS_PREFERENCES_NOTIFICATION_BUNDLE_NOT_EXIST) {
1368             result = ERR_OK;
1369             enabled = false;
1370         }
1371     }));
1372     notificationSvrQueue_->wait(handler);
1373     return result;
1374 }
1375 
RemoveFromNotificationList(const sptr<NotificationBundleOption> & bundleOption,const std::string & label,int32_t notificationId,sptr<Notification> & notification,bool isCancel)1376 ErrCode AdvancedNotificationService::RemoveFromNotificationList(const sptr<NotificationBundleOption> &bundleOption,
1377     const std::string &label, int32_t notificationId, sptr<Notification> &notification, bool isCancel)
1378 {
1379     for (auto record : notificationList_) {
1380         if ((record->bundleOption->GetBundleName() == bundleOption->GetBundleName()) &&
1381             (record->bundleOption->GetUid() == bundleOption->GetUid()) &&
1382             (record->notification->GetLabel() == label) &&
1383             (record->notification->GetId() == notificationId)
1384 #ifdef DISTRIBUTED_NOTIFICATION_SUPPORTED
1385             && record->deviceId.empty()
1386 #endif
1387         ) {
1388             if (!isCancel && !record->notification->IsRemoveAllowed()) {
1389                 return ERR_ANS_NOTIFICATION_IS_UNALLOWED_REMOVEALLOWED;
1390             }
1391             notification = record->notification;
1392             // delete or delete all, call the function
1393             if (!isCancel) {
1394                 TriggerRemoveWantAgent(record->request);
1395             }
1396             notificationList_.remove(record);
1397             return ERR_OK;
1398         }
1399     }
1400 
1401     return ERR_ANS_NOTIFICATION_NOT_EXISTS;
1402 }
1403 
RemoveFromNotificationList(const std::string & key,sptr<Notification> & notification,bool isCancel,int32_t removeReason)1404 ErrCode AdvancedNotificationService::RemoveFromNotificationList(
1405     const std::string &key, sptr<Notification> &notification, bool isCancel, int32_t removeReason)
1406 {
1407     for (auto record : notificationList_) {
1408         if (record->notification->GetKey() == key) {
1409             if (!isCancel && !record->notification->IsRemoveAllowed()) {
1410                 return ERR_ANS_NOTIFICATION_IS_UNALLOWED_REMOVEALLOWED;
1411             }
1412             notification = record->notification;
1413             // delete or delete all, call the function
1414             if (!isCancel && removeReason != NotificationConstant::CLICK_REASON_DELETE) {
1415                 TriggerRemoveWantAgent(record->request);
1416             }
1417             notificationList_.remove(record);
1418             return ERR_OK;
1419         }
1420     }
1421 
1422     return ERR_ANS_NOTIFICATION_NOT_EXISTS;
1423 }
1424 
RemoveFromNotificationListForDeleteAll(const std::string & key,const int32_t & userId,sptr<Notification> & notification)1425 ErrCode AdvancedNotificationService::RemoveFromNotificationListForDeleteAll(
1426     const std::string &key, const int32_t &userId, sptr<Notification> &notification)
1427 {
1428     for (auto record : notificationList_) {
1429         if ((record->notification->GetKey() == key) && (record->notification->GetUserId() == userId)) {
1430             if (!record->notification->IsRemoveAllowed()) {
1431                 return ERR_ANS_NOTIFICATION_IS_UNALLOWED_REMOVEALLOWED;
1432             }
1433             if (record->request->IsUnremovable()) {
1434                 return ERR_ANS_NOTIFICATION_IS_UNREMOVABLE;
1435             }
1436             notification = record->notification;
1437             notificationList_.remove(record);
1438             return ERR_OK;
1439         }
1440     }
1441 
1442     return ERR_ANS_NOTIFICATION_NOT_EXISTS;
1443 }
1444 
Subscribe(const sptr<AnsSubscriberInterface> & subscriber,const sptr<NotificationSubscribeInfo> & info)1445 ErrCode AdvancedNotificationService::Subscribe(
1446     const sptr<AnsSubscriberInterface> &subscriber, const sptr<NotificationSubscribeInfo> &info)
1447 {
1448     HITRACE_METER_NAME(HITRACE_TAG_NOTIFICATION, __PRETTY_FUNCTION__);
1449     ANS_LOGD("%{public}s", __FUNCTION__);
1450 
1451     ErrCode errCode = ERR_OK;
1452     do {
1453         if (subscriber == nullptr) {
1454             errCode = ERR_ANS_INVALID_PARAM;
1455             break;
1456         }
1457 
1458         bool isSubsystem = AccessTokenHelper::VerifyNativeToken(IPCSkeleton::GetCallingTokenID());
1459         if (!isSubsystem && !AccessTokenHelper::IsSystemApp()) {
1460             ANS_LOGE("Client is not a system app or subsystem");
1461             errCode = ERR_ANS_NON_SYSTEM_APP;
1462             break;
1463         }
1464 
1465         if (!CheckPermission(OHOS_PERMISSION_NOTIFICATION_CONTROLLER)) {
1466             errCode = ERR_ANS_PERMISSION_DENIED;
1467             break;
1468         }
1469 
1470         errCode = NotificationSubscriberManager::GetInstance()->AddSubscriber(subscriber, info);
1471         if (errCode != ERR_OK) {
1472             break;
1473         }
1474     } while (0);
1475 
1476     SendSubscribeHiSysEvent(IPCSkeleton::GetCallingPid(), IPCSkeleton::GetCallingUid(), info, errCode);
1477     return errCode;
1478 }
1479 
Unsubscribe(const sptr<AnsSubscriberInterface> & subscriber,const sptr<NotificationSubscribeInfo> & info)1480 ErrCode AdvancedNotificationService::Unsubscribe(
1481     const sptr<AnsSubscriberInterface> &subscriber, const sptr<NotificationSubscribeInfo> &info)
1482 {
1483     HITRACE_METER_NAME(HITRACE_TAG_NOTIFICATION, __PRETTY_FUNCTION__);
1484     ANS_LOGD("%{public}s", __FUNCTION__);
1485 
1486     SendUnSubscribeHiSysEvent(IPCSkeleton::GetCallingPid(), IPCSkeleton::GetCallingUid(), info);
1487 
1488     bool isSubsystem = AccessTokenHelper::VerifyNativeToken(IPCSkeleton::GetCallingTokenID());
1489     if (!isSubsystem && !AccessTokenHelper::IsSystemApp()) {
1490         ANS_LOGE("Client is not a system app or subsystem");
1491         return ERR_ANS_NON_SYSTEM_APP;
1492     }
1493 
1494     if (!CheckPermission(OHOS_PERMISSION_NOTIFICATION_CONTROLLER)) {
1495         return ERR_ANS_PERMISSION_DENIED;
1496     }
1497 
1498     if (subscriber == nullptr) {
1499         return ERR_ANS_INVALID_PARAM;
1500     }
1501 
1502     ErrCode errCode = NotificationSubscriberManager::GetInstance()->RemoveSubscriber(subscriber, info);
1503     if (errCode != ERR_OK) {
1504         return errCode;
1505     }
1506 
1507     return ERR_OK;
1508 }
1509 
GetSlotByType(const NotificationConstant::SlotType & slotType,sptr<NotificationSlot> & slot)1510 ErrCode AdvancedNotificationService::GetSlotByType(
1511     const NotificationConstant::SlotType &slotType, sptr<NotificationSlot> &slot)
1512 {
1513     ANS_LOGD("%{public}s", __FUNCTION__);
1514 
1515     sptr<NotificationBundleOption> bundleOption = GenerateBundleOption();
1516     if (bundleOption == nullptr) {
1517         return ERR_ANS_INVALID_BUNDLE;
1518     }
1519 
1520     if (notificationSvrQueue_ == nullptr) {
1521         ANS_LOGE("Serial queue is invalid.");
1522         return ERR_ANS_INVALID_PARAM;
1523     }
1524     ffrt::task_handle handler = notificationSvrQueue_->submit_h(std::bind([&]() {
1525         ANS_LOGD("ffrt enter!");
1526         NotificationPreferences::GetInstance().GetNotificationSlot(bundleOption, slotType, slot);
1527     }));
1528     notificationSvrQueue_->wait(handler);
1529     // if get slot failed, it still return ok.
1530     return ERR_OK;
1531 }
1532 
RemoveSlotByType(const NotificationConstant::SlotType & slotType)1533 ErrCode AdvancedNotificationService::RemoveSlotByType(const NotificationConstant::SlotType &slotType)
1534 {
1535     ANS_LOGD("%{public}s", __FUNCTION__);
1536 
1537     sptr<NotificationBundleOption> bundleOption = GenerateBundleOption();
1538     if (bundleOption == nullptr) {
1539         return ERR_ANS_INVALID_BUNDLE;
1540     }
1541 
1542     if (notificationSvrQueue_ == nullptr) {
1543         ANS_LOGE("Serial queue is invalid.");
1544         return ERR_ANS_INVALID_PARAM;
1545     }
1546     ffrt::task_handle handler = notificationSvrQueue_->submit_h(std::bind([&]() {
1547         ANS_LOGD("ffrt enter!");
1548         NotificationPreferences::GetInstance().RemoveNotificationSlot(bundleOption, slotType);
1549     }));
1550     notificationSvrQueue_->wait(handler);
1551     // if remove slot failed, it still return ok.
1552     return ERR_OK;
1553 }
1554 
GetAllActiveNotifications(std::vector<sptr<Notification>> & notifications)1555 ErrCode AdvancedNotificationService::GetAllActiveNotifications(std::vector<sptr<Notification>> &notifications)
1556 {
1557     ANS_LOGD("%{public}s", __FUNCTION__);
1558 
1559     bool isSubsystem = AccessTokenHelper::VerifyNativeToken(IPCSkeleton::GetCallingTokenID());
1560     if (!isSubsystem && !AccessTokenHelper::IsSystemApp()) {
1561         return ERR_ANS_NON_SYSTEM_APP;
1562     }
1563 
1564     if (!CheckPermission(OHOS_PERMISSION_NOTIFICATION_CONTROLLER)) {
1565         return ERR_ANS_PERMISSION_DENIED;
1566     }
1567 
1568     if (notificationSvrQueue_ == nullptr) {
1569         ANS_LOGE("Serial queue is invalid.");
1570         return ERR_ANS_INVALID_PARAM;
1571     }
1572     ffrt::task_handle handler = notificationSvrQueue_->submit_h(std::bind([&]() {
1573         ANS_LOGD("ffrt enter!");
1574         notifications.clear();
1575         for (auto record : notificationList_) {
1576             if (record->notification != nullptr) {
1577                 notifications.push_back(record->notification);
1578             }
1579         }
1580     }));
1581     notificationSvrQueue_->wait(handler);
1582     return ERR_OK;
1583 }
1584 
IsContained(const std::vector<std::string> & vec,const std::string & target)1585 inline bool IsContained(const std::vector<std::string> &vec, const std::string &target)
1586 {
1587     bool isContained = false;
1588 
1589     auto iter = vec.begin();
1590     while (iter != vec.end()) {
1591         if (*iter == target) {
1592             isContained = true;
1593             break;
1594         }
1595         iter++;
1596     }
1597 
1598     return isContained;
1599 }
1600 
GetSpecialActiveNotifications(const std::vector<std::string> & key,std::vector<sptr<Notification>> & notifications)1601 ErrCode AdvancedNotificationService::GetSpecialActiveNotifications(
1602     const std::vector<std::string> &key, std::vector<sptr<Notification>> &notifications)
1603 {
1604     ANS_LOGD("%{public}s", __FUNCTION__);
1605 
1606     bool isSubsystem = AccessTokenHelper::VerifyNativeToken(IPCSkeleton::GetCallingTokenID());
1607     if (!isSubsystem && !AccessTokenHelper::IsSystemApp()) {
1608         return ERR_ANS_NON_SYSTEM_APP;
1609     }
1610 
1611     if (!CheckPermission(OHOS_PERMISSION_NOTIFICATION_CONTROLLER)) {
1612         return ERR_ANS_PERMISSION_DENIED;
1613     }
1614 
1615     if (notificationSvrQueue_ == nullptr) {
1616         ANS_LOGE("Serial queue is invalid.");
1617         return ERR_ANS_INVALID_PARAM;
1618     }
1619     ffrt::task_handle handler = notificationSvrQueue_->submit_h(std::bind([&]() {
1620         ANS_LOGD("ffrt enter!");
1621         for (auto record : notificationList_) {
1622             if (IsContained(key, record->notification->GetKey())) {
1623                 notifications.push_back(record->notification);
1624             }
1625         }
1626     }));
1627     notificationSvrQueue_->wait(handler);
1628     return ERR_OK;
1629 }
1630 
RequestEnableNotification(const std::string & deviceId,const sptr<IRemoteObject> & callerToken)1631 ErrCode AdvancedNotificationService::RequestEnableNotification(
1632     const std::string &deviceId, const sptr<IRemoteObject> &callerToken)
1633 {
1634     ANS_LOGD("%{public}s", __FUNCTION__);
1635 
1636     ErrCode result = ERR_OK;
1637     sptr<NotificationBundleOption> bundleOption = GenerateBundleOption();
1638     if (bundleOption == nullptr) {
1639         ANS_LOGD("bundleOption == nullptr");
1640         return ERR_ANS_INVALID_BUNDLE;
1641     }
1642 
1643     // To get the permission
1644     bool allowedNotify = false;
1645     result = IsAllowedNotifySelf(bundleOption, allowedNotify);
1646     ANS_LOGI("result = %{public}d, allowedNotify = %{public}d", result, allowedNotify);
1647     if (result != ERR_OK || allowedNotify) {
1648         ANS_LOGD("Already granted permission");
1649         return result;
1650     }
1651 
1652     // Check to see if it has been popover before
1653     bool hasPopped = false;
1654     result = GetHasPoppedDialog(bundleOption, hasPopped);
1655     if (result != ERR_OK || hasPopped) {
1656         ANS_LOGD("Already shown dialog");
1657         return result;
1658     }
1659 
1660     ANS_LOGI("hasPopped = %{public}d, allowedNotify = %{public}d", hasPopped, allowedNotify);
1661     if (!hasPopped && !allowedNotify) {
1662         auto notificationDialog = std::make_shared<NotificationDialog>();
1663         result = notificationDialog->StartEnableNotificationDialogAbility(bundleOption->GetUid(), callerToken);
1664         if (result != ERR_OK) {
1665             ANS_LOGD("StartEnableNotificationDialogAbility failed, result = %{public}d", result);
1666             return result;
1667         }
1668     }
1669     SetHasPoppedDialog(bundleOption, true);
1670     return result;
1671 }
1672 
SetNotificationsEnabledForBundle(const std::string & deviceId,bool enabled)1673 ErrCode AdvancedNotificationService::SetNotificationsEnabledForBundle(const std::string &deviceId, bool enabled)
1674 {
1675     return ERR_INVALID_OPERATION;
1676 }
1677 
SetNotificationsEnabledForAllBundles(const std::string & deviceId,bool enabled)1678 ErrCode AdvancedNotificationService::SetNotificationsEnabledForAllBundles(const std::string &deviceId, bool enabled)
1679 {
1680     ANS_LOGD("%{public}s", __FUNCTION__);
1681 
1682     bool isSubsystem = AccessTokenHelper::VerifyNativeToken(IPCSkeleton::GetCallingTokenID());
1683     if (!isSubsystem && !AccessTokenHelper::IsSystemApp()) {
1684         return ERR_ANS_NON_SYSTEM_APP;
1685     }
1686 
1687     if (!CheckPermission(OHOS_PERMISSION_NOTIFICATION_CONTROLLER)) {
1688         return ERR_ANS_PERMISSION_DENIED;
1689     }
1690 
1691     int32_t userId = SUBSCRIBE_USER_INIT;
1692     if (!GetActiveUserId(userId)) {
1693         return ERR_ANS_GET_ACTIVE_USER_FAILED;
1694     }
1695 
1696     if (notificationSvrQueue_ == nullptr) {
1697         ANS_LOGE("Serial queue is invalid.");
1698         return ERR_ANS_INVALID_PARAM;
1699     }
1700     ErrCode result = ERR_OK;
1701     ffrt::task_handle handler = notificationSvrQueue_->submit_h(std::bind([&]() {
1702         ANS_LOGD("ffrt enter!");
1703         if (deviceId.empty()) {
1704             // Local device
1705             result = NotificationPreferences::GetInstance().SetNotificationsEnabled(userId, enabled);
1706         } else {
1707             // Remote device
1708         }
1709     }));
1710     notificationSvrQueue_->wait(handler);
1711     return result;
1712 }
1713 
SetNotificationsEnabledForSpecialBundle(const std::string & deviceId,const sptr<NotificationBundleOption> & bundleOption,bool enabled)1714 ErrCode AdvancedNotificationService::SetNotificationsEnabledForSpecialBundle(
1715     const std::string &deviceId, const sptr<NotificationBundleOption> &bundleOption, bool enabled)
1716 {
1717     HITRACE_METER_NAME(HITRACE_TAG_NOTIFICATION, __PRETTY_FUNCTION__);
1718     ANS_LOGD("%{public}s", __FUNCTION__);
1719 
1720     bool isSubsystem = AccessTokenHelper::VerifyNativeToken(IPCSkeleton::GetCallingTokenID());
1721     if (!isSubsystem && !AccessTokenHelper::IsSystemApp()) {
1722         return ERR_ANS_NON_SYSTEM_APP;
1723     }
1724 
1725     if (!CheckPermission(OHOS_PERMISSION_NOTIFICATION_CONTROLLER)) {
1726         return ERR_ANS_PERMISSION_DENIED;
1727     }
1728 
1729     sptr<NotificationBundleOption> bundle = GenerateValidBundleOption(bundleOption);
1730     if (bundle == nullptr) {
1731         return ERR_ANS_INVALID_BUNDLE;
1732     }
1733 
1734     sptr<EnabledNotificationCallbackData> bundleData =
1735         new EnabledNotificationCallbackData(bundle->GetBundleName(), bundle->GetUid(), enabled);
1736 
1737     ErrCode result = ERR_OK;
1738     if (deviceId.empty()) {
1739         // Local device
1740         result = NotificationPreferences::GetInstance().SetNotificationsEnabledForBundle(bundle, enabled);
1741         if (!enabled) {
1742             result = RemoveAllNotifications(bundle);
1743         }
1744         if (result == ERR_OK) {
1745             NotificationSubscriberManager::GetInstance()->NotifyEnabledNotificationChanged(bundleData);
1746             PublishSlotChangeCommonEvent(bundle);
1747         }
1748     } else {
1749         // Remote revice
1750     }
1751 
1752     SendEnableNotificationHiSysEvent(bundleOption, enabled, result);
1753     return result;
1754 }
1755 
IsAllowedNotify(bool & allowed)1756 ErrCode AdvancedNotificationService::IsAllowedNotify(bool &allowed)
1757 {
1758     ANS_LOGD("%{public}s", __FUNCTION__);
1759 
1760     bool isSubsystem = AccessTokenHelper::VerifyNativeToken(IPCSkeleton::GetCallingTokenID());
1761     if (!isSubsystem && !AccessTokenHelper::IsSystemApp()) {
1762         return ERR_ANS_NON_SYSTEM_APP;
1763     }
1764 
1765     if (!CheckPermission(OHOS_PERMISSION_NOTIFICATION_CONTROLLER)) {
1766         return ERR_ANS_PERMISSION_DENIED;
1767     }
1768 
1769     int32_t userId = SUBSCRIBE_USER_INIT;
1770     if (!GetActiveUserId(userId)) {
1771         return ERR_ANS_GET_ACTIVE_USER_FAILED;
1772     }
1773 
1774     if (notificationSvrQueue_ == nullptr) {
1775         ANS_LOGE("Serial queue is invalid.");
1776         return ERR_ANS_INVALID_PARAM;
1777     }
1778     ErrCode result = ERR_OK;
1779     ffrt::task_handle handler = notificationSvrQueue_->submit_h(std::bind([&]() {
1780         ANS_LOGD("ffrt enter!");
1781         allowed = false;
1782         result = NotificationPreferences::GetInstance().GetNotificationsEnabled(userId, allowed);
1783     }));
1784     notificationSvrQueue_->wait(handler);
1785     return result;
1786 }
1787 
IsAllowedNotifySelf(bool & allowed)1788 ErrCode AdvancedNotificationService::IsAllowedNotifySelf(bool &allowed)
1789 {
1790     ANS_LOGD("%{public}s", __FUNCTION__);
1791 
1792     sptr<NotificationBundleOption> bundleOption = GenerateBundleOption();
1793     if (bundleOption == nullptr) {
1794         return ERR_ANS_INVALID_BUNDLE;
1795     }
1796     return IsAllowedNotifySelf(bundleOption, allowed);
1797 }
1798 
IsAllowedNotifySelf(const sptr<NotificationBundleOption> & bundleOption,bool & allowed)1799 ErrCode AdvancedNotificationService::IsAllowedNotifySelf(const sptr<NotificationBundleOption> &bundleOption,
1800     bool &allowed)
1801 {
1802     ANS_LOGD("%{public}s", __FUNCTION__);
1803     if (bundleOption == nullptr) {
1804         return ERR_ANS_INVALID_BUNDLE;
1805     }
1806 
1807     int32_t userId = SUBSCRIBE_USER_INIT;
1808     if (!GetActiveUserId(userId)) {
1809         return ERR_ANS_GET_ACTIVE_USER_FAILED;
1810     }
1811 
1812     ErrCode result = ERR_OK;
1813         allowed = false;
1814         result = NotificationPreferences::GetInstance().GetNotificationsEnabled(userId, allowed);
1815         if (result == ERR_OK && allowed) {
1816             result = NotificationPreferences::GetInstance().GetNotificationsEnabledForBundle(bundleOption, allowed);
1817             if (result == ERR_ANS_PREFERENCES_NOTIFICATION_BUNDLE_NOT_EXIST) {
1818                 result = ERR_OK;
1819                 allowed = CheckApiCompatibility(bundleOption);
1820                 SetDefaultNotificationEnabled(bundleOption, allowed);
1821             }
1822         }
1823     return result;
1824 }
1825 
GetAppTargetBundle(const sptr<NotificationBundleOption> & bundleOption,sptr<NotificationBundleOption> & targetBundle)1826 ErrCode AdvancedNotificationService::GetAppTargetBundle(const sptr<NotificationBundleOption> &bundleOption,
1827     sptr<NotificationBundleOption> &targetBundle)
1828 {
1829     sptr<NotificationBundleOption> clientBundle = GenerateBundleOption();
1830     if (clientBundle == nullptr) {
1831         return ERR_ANS_INVALID_BUNDLE;
1832     }
1833 
1834     if (bundleOption == nullptr) {
1835         targetBundle = clientBundle;
1836     } else {
1837         if ((clientBundle->GetBundleName() == bundleOption->GetBundleName()) &&
1838             (clientBundle->GetUid() == bundleOption->GetUid())) {
1839             targetBundle = bundleOption;
1840         } else {
1841             bool isSubsystem = AccessTokenHelper::VerifyNativeToken(IPCSkeleton::GetCallingTokenID());
1842             if (!isSubsystem && !AccessTokenHelper::IsSystemApp()) {
1843                 return ERR_ANS_NON_SYSTEM_APP;
1844             }
1845             targetBundle = GenerateValidBundleOption(bundleOption);
1846         }
1847     }
1848     return ERR_OK;
1849 }
1850 
IsSpecialBundleAllowedNotify(const sptr<NotificationBundleOption> & bundleOption,bool & allowed)1851 ErrCode AdvancedNotificationService::IsSpecialBundleAllowedNotify(
1852     const sptr<NotificationBundleOption> &bundleOption, bool &allowed)
1853 {
1854     ANS_LOGD("%{public}s", __FUNCTION__);
1855 
1856     bool isSubsystem = AccessTokenHelper::VerifyNativeToken(IPCSkeleton::GetCallingTokenID());
1857     if (!isSubsystem && !AccessTokenHelper::IsSystemApp()) {
1858         ANS_LOGE("Not system application");
1859         return ERR_ANS_NON_SYSTEM_APP;
1860     }
1861 
1862     if (!CheckPermission(OHOS_PERMISSION_NOTIFICATION_CONTROLLER)) {
1863         return ERR_ANS_PERMISSION_DENIED;
1864     }
1865 
1866     sptr<NotificationBundleOption> targetBundle = nullptr;
1867     if (isSubsystem) {
1868         if (bundleOption != nullptr) {
1869             targetBundle = GenerateValidBundleOption(bundleOption);
1870         }
1871     } else {
1872         ErrCode result = GetAppTargetBundle(bundleOption, targetBundle);
1873         if (result != ERR_OK) {
1874             return result;
1875         }
1876     }
1877 
1878     if (targetBundle == nullptr) {
1879         return ERR_ANS_INVALID_BUNDLE;
1880     }
1881 
1882     int32_t userId = SUBSCRIBE_USER_INIT;
1883     if (!GetActiveUserId(userId)) {
1884         return ERR_ANS_GET_ACTIVE_USER_FAILED;
1885     }
1886 
1887     ErrCode result = ERR_OK;
1888         allowed = false;
1889         result = NotificationPreferences::GetInstance().GetNotificationsEnabled(userId, allowed);
1890         if (result == ERR_OK && allowed) {
1891             result = NotificationPreferences::GetInstance().GetNotificationsEnabledForBundle(targetBundle, allowed);
1892             if (result == ERR_ANS_PREFERENCES_NOTIFICATION_BUNDLE_NOT_EXIST) {
1893                 result = ERR_OK;
1894                 allowed = CheckApiCompatibility(targetBundle);
1895                 SetNotificationsEnabledForSpecialBundle("", bundleOption, allowed);
1896             }
1897         }
1898     return result;
1899 }
1900 
PublishContinuousTaskNotification(const sptr<NotificationRequest> & request)1901 ErrCode AdvancedNotificationService::PublishContinuousTaskNotification(const sptr<NotificationRequest> &request)
1902 {
1903     ANS_LOGD("%{public}s", __FUNCTION__);
1904 
1905     bool isSubsystem = AccessTokenHelper::VerifyNativeToken(IPCSkeleton::GetCallingTokenID());
1906     if (!isSubsystem) {
1907         return ERR_ANS_NOT_SYSTEM_SERVICE;
1908     }
1909 
1910     int32_t uid = IPCSkeleton::GetCallingUid();
1911     int32_t userId = SUBSCRIBE_USER_INIT;
1912     OHOS::AccountSA::OsAccountManager::GetOsAccountLocalIdFromUid(uid, userId);
1913     request->SetCreatorUserId(userId);
1914     ANS_LOGD("%{public}s, uid=%{public}d userId=%{public}d", __FUNCTION__, uid, userId);
1915 
1916     if (request->GetCreatorBundleName().empty()) {
1917         request->SetCreatorBundleName(FOUNDATION_BUNDLE_NAME);
1918     }
1919 
1920     if (request->GetOwnerBundleName().empty()) {
1921         request->SetOwnerBundleName(FOUNDATION_BUNDLE_NAME);
1922     }
1923 
1924     sptr<NotificationBundleOption> bundleOption = nullptr;
1925     bundleOption = new NotificationBundleOption(std::string(), uid);
1926     if (bundleOption == nullptr) {
1927         return ERR_ANS_INVALID_BUNDLE;
1928     }
1929 
1930     ErrCode result = PrepareContinuousTaskNotificationRequest(request, uid);
1931     if (result != ERR_OK) {
1932         return result;
1933     }
1934     request->SetUnremovable(true);
1935     std::shared_ptr<NotificationRecord> record = std::make_shared<NotificationRecord>();
1936     record->request = request;
1937     record->bundleOption = bundleOption;
1938     record->notification = new Notification(request);
1939     if (record->notification != nullptr) {
1940         record->notification->SetSourceType(NotificationConstant::SourceType::TYPE_CONTINUOUS);
1941     }
1942 
1943     if (notificationSvrQueue_ == nullptr) {
1944         ANS_LOGE("Serial queue is invalid.");
1945         return ERR_ANS_INVALID_PARAM;
1946     }
1947     ffrt::task_handle handler = notificationSvrQueue_->submit_h(std::bind([&]() {
1948         ANS_LOGD("ffrt enter!");
1949         if (!IsNotificationExists(record->notification->GetKey())) {
1950             AddToNotificationList(record);
1951         } else {
1952             if (record->request->IsAlertOneTime()) {
1953                 record->notification->SetEnableLight(false);
1954                 record->notification->SetEnableSound(false);
1955                 record->notification->SetEnableVibration(false);
1956             }
1957             UpdateInNotificationList(record);
1958         }
1959 
1960         UpdateRecentNotification(record->notification, false, 0);
1961         sptr<NotificationSortingMap> sortingMap = GenerateSortingMap();
1962         NotificationSubscriberManager::GetInstance()->NotifyConsumed(record->notification, sortingMap);
1963     }));
1964     notificationSvrQueue_->wait(handler);
1965 
1966     return result;
1967 }
1968 
CancelContinuousTaskNotification(const std::string & label,int32_t notificationId)1969 ErrCode AdvancedNotificationService::CancelContinuousTaskNotification(const std::string &label, int32_t notificationId)
1970 {
1971     ANS_LOGD("%{public}s", __FUNCTION__);
1972 
1973     bool isSubsystem = AccessTokenHelper::VerifyNativeToken(IPCSkeleton::GetCallingTokenID());
1974     if (!isSubsystem) {
1975         return ERR_ANS_NOT_SYSTEM_SERVICE;
1976     }
1977 
1978     if (notificationSvrQueue_ == nullptr) {
1979         ANS_LOGE("Serial queue is invalid.");
1980         return ERR_ANS_INVALID_PARAM;
1981     }
1982     int32_t uid = IPCSkeleton::GetCallingUid();
1983     ErrCode result = ERR_OK;
1984     ffrt::task_handle handler = notificationSvrQueue_->submit_h(std::bind([&]() {
1985         ANS_LOGD("ffrt enter!");
1986         sptr<Notification> notification = nullptr;
1987         for (auto record : notificationList_) {
1988             if ((record->bundleOption->GetBundleName().empty()) && (record->bundleOption->GetUid() == uid) &&
1989                 (record->notification->GetId() == notificationId) && (record->notification->GetLabel() == label)) {
1990                 notification = record->notification;
1991                 notificationList_.remove(record);
1992                 result = ERR_OK;
1993                 break;
1994             }
1995         }
1996         if (notification != nullptr) {
1997             int32_t reason = NotificationConstant::APP_CANCEL_REASON_DELETE;
1998             UpdateRecentNotification(notification, true, reason);
1999             NotificationSubscriberManager::GetInstance()->NotifyCanceled(notification, nullptr, reason);
2000         }
2001     }));
2002     notificationSvrQueue_->wait(handler);
2003     return result;
2004 }
2005 
PublishReminder(sptr<ReminderRequest> & reminder)2006 ErrCode AdvancedNotificationService::PublishReminder(sptr<ReminderRequest> &reminder)
2007 {
2008     ANSR_LOGI("Publish reminder");
2009     if (!reminder) {
2010         ANSR_LOGE("ReminderRequest object is nullptr");
2011         return ERR_ANS_INVALID_PARAM;
2012     }
2013 
2014     Security::AccessToken::AccessTokenID callerToken = IPCSkeleton::GetCallingTokenID();
2015     ErrCode result = Security::AccessToken::AccessTokenKit::VerifyAccessToken(
2016         callerToken, "ohos.permission.PUBLISH_AGENT_REMINDER");
2017     if (result != Security::AccessToken::PermissionState::PERMISSION_GRANTED) {
2018         ANSR_LOGW("Permission denied: ohos.permission.PUBLISH_AGENT_REMINDER");
2019         return ERR_REMINDER_PERMISSION_DENIED;
2020     }
2021 
2022     sptr<NotificationRequest> notificationRequest = reminder->GetNotificationRequest();
2023     std::string bundle = GetClientBundleName();
2024     if (reminder->GetWantAgentInfo() == nullptr || reminder->GetMaxScreenWantAgentInfo() == nullptr) {
2025         ANSR_LOGE("wantagent info is nullptr");
2026         return ERR_ANS_INVALID_PARAM;
2027     }
2028     std::string wantAgentName = reminder->GetWantAgentInfo()->pkgName;
2029     std::string msWantAgentName = reminder->GetMaxScreenWantAgentInfo()->pkgName;
2030     if (wantAgentName != msWantAgentName && wantAgentName != "" && msWantAgentName != "") {
2031         ANSR_LOGE("wantAgentName is not same to msWantAgentName, wantAgentName:%{public}s, msWantAgentName:%{public}s",
2032             wantAgentName.c_str(), msWantAgentName.c_str());
2033         return ERR_ANS_INVALID_PARAM;
2034     }
2035     if (wantAgentName != bundle && wantAgentName != "") {
2036         ANSR_LOGI("Set agent reminder, bundle:%{public}s, wantAgentName:%{public}s", bundle.c_str(),
2037             wantAgentName.c_str());
2038         SetAgentNotification(notificationRequest, wantAgentName);
2039     } else if (msWantAgentName != bundle && msWantAgentName != "") {
2040         ANSR_LOGI("Set agent reminder, bundle:%{public}s, msWantAgentName:%{public}s", bundle.c_str(),
2041             msWantAgentName.c_str());
2042         SetAgentNotification(notificationRequest, msWantAgentName);
2043     }
2044     sptr<NotificationBundleOption> bundleOption = nullptr;
2045     result = PrepareNotificationInfo(notificationRequest, bundleOption);
2046     if (result != ERR_OK) {
2047         ANSR_LOGW("PrepareNotificationInfo fail");
2048         return result;
2049     }
2050     bool allowedNotify = false;
2051     result = IsAllowedNotifySelf(bundleOption, allowedNotify);
2052     if (!reminder->IsSystemApp() && (result != ERR_OK || !allowedNotify)) {
2053         ANSR_LOGW("The application does not request enable notification");
2054         return ERR_REMINDER_NOTIFICATION_NOT_ENABLE;
2055     }
2056     auto rdm = ReminderDataManager::GetInstance();
2057     if (rdm == nullptr) {
2058         return ERR_NO_INIT;
2059     }
2060     return rdm->PublishReminder(reminder, bundleOption);
2061 }
2062 
SetAgentNotification(sptr<NotificationRequest> & notificationRequest,std::string & bundleName)2063 void AdvancedNotificationService::SetAgentNotification(sptr<NotificationRequest>& notificationRequest,
2064     std::string& bundleName)
2065 {
2066     auto bundleManager = BundleManagerHelper::GetInstance();
2067     int32_t activeUserId = -1;
2068     if (!GetActiveUserId(activeUserId)) {
2069         ANSR_LOGW("Failed to get active user id!");
2070         return;
2071     }
2072 
2073     notificationRequest->SetIsAgentNotification(true);
2074     notificationRequest->SetOwnerUserId(activeUserId);
2075     notificationRequest->SetOwnerBundleName(bundleName);
2076 }
2077 
CancelReminder(const int32_t reminderId)2078 ErrCode AdvancedNotificationService::CancelReminder(const int32_t reminderId)
2079 {
2080     ANSR_LOGI("Cancel Reminder");
2081     sptr<NotificationBundleOption> bundleOption = GenerateBundleOption();
2082     if (bundleOption == nullptr) {
2083         return ERR_ANS_INVALID_BUNDLE;
2084     }
2085     auto rdm = ReminderDataManager::GetInstance();
2086     if (rdm == nullptr) {
2087         return ERR_NO_INIT;
2088     }
2089     return rdm->CancelReminder(reminderId, bundleOption);
2090 }
2091 
CancelAllReminders()2092 ErrCode AdvancedNotificationService::CancelAllReminders()
2093 {
2094     ANSR_LOGI("Cancel all reminders");
2095     sptr<NotificationBundleOption> bundleOption = GenerateBundleOption();
2096     if (bundleOption == nullptr) {
2097         return ERR_ANS_INVALID_BUNDLE;
2098     }
2099     int32_t userId = -1;
2100     AccountSA::OsAccountManager::GetOsAccountLocalIdFromUid(bundleOption->GetUid(), userId);
2101     auto rdm = ReminderDataManager::GetInstance();
2102     if (rdm == nullptr) {
2103         return ERR_NO_INIT;
2104     }
2105     return rdm->CancelAllReminders(bundleOption->GetBundleName(), userId);
2106 }
2107 
GetValidReminders(std::vector<sptr<ReminderRequest>> & reminders)2108 ErrCode AdvancedNotificationService::GetValidReminders(std::vector<sptr<ReminderRequest>> &reminders)
2109 {
2110     ANSR_LOGI("GetValidReminders");
2111     reminders.clear();
2112     sptr<NotificationBundleOption> bundleOption = GenerateBundleOption();
2113     if (bundleOption == nullptr) {
2114         return ERR_ANS_INVALID_BUNDLE;
2115     }
2116     auto rdm = ReminderDataManager::GetInstance();
2117     if (rdm == nullptr) {
2118         return ERR_NO_INIT;
2119     }
2120     rdm->GetValidReminders(bundleOption, reminders);
2121     ANSR_LOGD("Valid reminders size=%{public}zu", reminders.size());
2122     return ERR_OK;
2123 }
2124 
ActiveNotificationDump(const std::string & bundle,int32_t userId,std::vector<std::string> & dumpInfo)2125 ErrCode AdvancedNotificationService::ActiveNotificationDump(const std::string& bundle, int32_t userId,
2126     std::vector<std::string> &dumpInfo)
2127 {
2128     ANS_LOGD("%{public}s", __FUNCTION__);
2129     std::stringstream stream;
2130     for (const auto &record : notificationList_) {
2131         if (record->notification == nullptr || record->request == nullptr) {
2132             continue;
2133         }
2134         if (userId != SUBSCRIBE_USER_INIT && userId != record->notification->GetUserId()) {
2135             continue;
2136         }
2137         if (!bundle.empty() && bundle != record->notification->GetBundleName()) {
2138             continue;
2139         }
2140 #ifdef DISTRIBUTED_NOTIFICATION_SUPPORTED
2141         if (!record->deviceId.empty()) {
2142             continue;
2143         }
2144 #endif
2145         stream.clear();
2146         stream.str("");
2147         stream << "\tUserId: " << record->notification->GetUserId() << "\n";
2148         stream << "\tCreatePid: " << record->request->GetCreatorPid() << "\n";
2149         stream << "\tOwnerBundleName: " << record->notification->GetBundleName() << "\n";
2150         if (record->request->GetOwnerUid() > 0) {
2151             stream << "\tOwnerUid: " << record->request->GetOwnerUid() << "\n";
2152         } else {
2153             stream << "\tOwnerUid: " << record->request->GetCreatorUid() << "\n";
2154         }
2155         stream << "\tDeliveryTime = " << TimeToString(record->request->GetDeliveryTime()) << "\n";
2156         stream << "\tNotification:\n";
2157         stream << "\t\tId: " << record->notification->GetId() << "\n";
2158         stream << "\t\tLabel: " << record->notification->GetLabel() << "\n";
2159         stream << "\t\tSlotType = " << record->request->GetSlotType() << "\n";
2160         dumpInfo.push_back(stream.str());
2161     }
2162     return ERR_OK;
2163 }
2164 
RecentNotificationDump(const std::string & bundle,int32_t userId,std::vector<std::string> & dumpInfo)2165 ErrCode AdvancedNotificationService::RecentNotificationDump(const std::string& bundle, int32_t userId,
2166     std::vector<std::string> &dumpInfo)
2167 {
2168     ANS_LOGD("%{public}s", __FUNCTION__);
2169     std::stringstream stream;
2170     for (auto recentNotification : recentInfo_->list) {
2171         if (recentNotification->notification == nullptr) {
2172             continue;
2173         }
2174         const auto &notificationRequest = recentNotification->notification->GetNotificationRequest();
2175         if (userId != SUBSCRIBE_USER_INIT && userId != notificationRequest.GetOwnerUserId()) {
2176             continue;
2177         }
2178         if (!bundle.empty() && bundle != recentNotification->notification->GetBundleName()) {
2179             continue;
2180         }
2181         stream.clear();
2182         stream.str("");
2183         stream << "\tUserId: " << notificationRequest.GetCreatorUserId() << "\n";
2184         stream << "\tCreatePid: " << notificationRequest.GetCreatorPid() << "\n";
2185         stream << "\tBundleName: " << recentNotification->notification->GetBundleName() << "\n";
2186         if (notificationRequest.GetOwnerUid() > 0) {
2187             stream << "\tOwnerUid: " << notificationRequest.GetOwnerUid() << "\n";
2188         } else {
2189             stream << "\tOwnerUid: " << notificationRequest.GetCreatorUid() << "\n";
2190         }
2191         stream << "\tDeliveryTime = " << TimeToString(notificationRequest.GetDeliveryTime()) << "\n";
2192         if (!recentNotification->isActive) {
2193             stream << "\tDeleteTime: " << TimeToString(recentNotification->deleteTime) << "\n";
2194             stream << "\tDeleteReason: " << recentNotification->deleteReason << "\n";
2195         }
2196         stream << "\tNotification:\n";
2197         stream << "\t\tId: " << recentNotification->notification->GetId() << "\n";
2198         stream << "\t\tLabel: " << recentNotification->notification->GetLabel() << "\n";
2199         stream << "\t\tSlotType = " << notificationRequest.GetSlotType() << "\n";
2200         dumpInfo.push_back(stream.str());
2201     }
2202     return ERR_OK;
2203 }
2204 
2205 #ifdef DISTRIBUTED_NOTIFICATION_SUPPORTED
DistributedNotificationDump(const std::string & bundle,int32_t userId,std::vector<std::string> & dumpInfo)2206 ErrCode AdvancedNotificationService::DistributedNotificationDump(const std::string& bundle, int32_t userId,
2207     std::vector<std::string> &dumpInfo)
2208 {
2209     ANS_LOGD("%{public}s", __FUNCTION__);
2210     std::stringstream stream;
2211     for (auto record : notificationList_) {
2212         if (record->notification == nullptr) {
2213             continue;
2214         }
2215         if (userId != SUBSCRIBE_USER_INIT && userId != record->notification->GetUserId()) {
2216             continue;
2217         }
2218         if (!bundle.empty() && bundle != record->notification->GetBundleName()) {
2219             continue;
2220         }
2221         if (record->deviceId.empty()) {
2222             continue;
2223         }
2224         stream.clear();
2225         stream.str("");
2226         stream << "\tUserId: " << record->notification->GetUserId() << "\n";
2227         stream << "\tCreatePid: " << record->request->GetCreatorPid() << "\n";
2228         stream << "\tOwnerBundleName: " << record->notification->GetBundleName() << "\n";
2229         if (record->request->GetOwnerUid() > 0) {
2230             stream << "\tOwnerUid: " << record->request->GetOwnerUid() << "\n";
2231         } else {
2232             stream << "\tOwnerUid: " << record->request->GetCreatorUid() << "\n";
2233         }
2234         stream << "\tDeliveryTime = " << TimeToString(record->request->GetDeliveryTime()) << "\n";
2235         stream << "\tNotification:\n";
2236         stream << "\t\tId: " << record->notification->GetId() << "\n";
2237         stream << "\t\tLabel: " << record->notification->GetLabel() << "\n";
2238         stream << "\t\tSlotType = " << record->request->GetSlotType() << "\n";
2239         dumpInfo.push_back(stream.str());
2240     }
2241 
2242     return ERR_OK;
2243 }
2244 #endif
2245 
SetRecentNotificationCount(const std::string arg)2246 ErrCode AdvancedNotificationService::SetRecentNotificationCount(const std::string arg)
2247 {
2248     ANS_LOGD("%{public}s arg = %{public}s", __FUNCTION__, arg.c_str());
2249     int32_t count = atoi(arg.c_str());
2250     if ((count < NOTIFICATION_MIN_COUNT) || (count > NOTIFICATION_MAX_COUNT)) {
2251         return ERR_ANS_INVALID_PARAM;
2252     }
2253 
2254     recentInfo_->recentCount = count;
2255     while (recentInfo_->list.size() > recentInfo_->recentCount) {
2256         recentInfo_->list.pop_back();
2257     }
2258     return ERR_OK;
2259 }
2260 
TimeToString(int64_t time)2261 std::string AdvancedNotificationService::TimeToString(int64_t time)
2262 {
2263     auto timePoint = std::chrono::time_point<std::chrono::system_clock>(std::chrono::milliseconds(time));
2264     auto timeT = std::chrono::system_clock::to_time_t(timePoint);
2265 
2266     std::stringstream stream;
2267     struct tm ret = {0};
2268     localtime_r(&timeT, &ret);
2269     stream << std::put_time(&ret, "%F, %T");
2270     return stream.str();
2271 }
2272 
GetNowSysTime()2273 int64_t AdvancedNotificationService::GetNowSysTime()
2274 {
2275     std::chrono::time_point<std::chrono::system_clock> nowSys = std::chrono::system_clock::now();
2276     auto epoch = nowSys.time_since_epoch();
2277     auto value = std::chrono::duration_cast<std::chrono::milliseconds>(epoch);
2278     int64_t duration = value.count();
2279     return duration;
2280 }
2281 
UpdateRecentNotification(sptr<Notification> & notification,bool isDelete,int32_t reason)2282 void AdvancedNotificationService::UpdateRecentNotification(sptr<Notification> &notification,
2283     bool isDelete, int32_t reason)
2284 {
2285     for (auto recentNotification : recentInfo_->list) {
2286         if (recentNotification->notification->GetKey() == notification->GetKey()) {
2287             if (!isDelete) {
2288                 recentInfo_->list.remove(recentNotification);
2289                 recentNotification->isActive = true;
2290                 recentNotification->notification = notification;
2291                 recentInfo_->list.emplace_front(recentNotification);
2292             } else {
2293                 recentNotification->isActive = false;
2294                 recentNotification->deleteReason = reason;
2295                 recentNotification->deleteTime = GetNowSysTime();
2296             }
2297             return;
2298         }
2299     }
2300 
2301     if (!isDelete) {
2302         if (recentInfo_->list.size() >= recentInfo_->recentCount) {
2303             recentInfo_->list.pop_back();
2304         }
2305         auto recentNotification = std::make_shared<RecentNotification>();
2306         recentNotification->isActive = true;
2307         recentNotification->notification = notification;
2308         recentInfo_->list.emplace_front(recentNotification);
2309     }
2310 }
2311 
RemoveExpired(std::list<std::chrono::system_clock::time_point> & list,const std::chrono::system_clock::time_point & now)2312 inline void RemoveExpired(
2313     std::list<std::chrono::system_clock::time_point> &list, const std::chrono::system_clock::time_point &now)
2314 {
2315     auto iter = list.begin();
2316     while (iter != list.end()) {
2317         if (abs(now - *iter) > std::chrono::seconds(1)) {
2318             iter = list.erase(iter);
2319         } else {
2320             break;
2321         }
2322     }
2323 }
2324 
SortNotificationsByLevelAndTime(const std::shared_ptr<NotificationRecord> & first,const std::shared_ptr<NotificationRecord> & second)2325 static bool SortNotificationsByLevelAndTime(
2326     const std::shared_ptr<NotificationRecord> &first, const std::shared_ptr<NotificationRecord> &second)
2327 {
2328     if (first->slot->GetLevel() != second->slot->GetLevel()) {
2329         return (first->slot->GetLevel() < second->slot->GetLevel());
2330     }
2331     return (first->request->GetCreateTime() < second->request->GetCreateTime());
2332 }
2333 
FlowControl(const std::shared_ptr<NotificationRecord> & record)2334 ErrCode AdvancedNotificationService::FlowControl(const std::shared_ptr<NotificationRecord> &record)
2335 {
2336     std::chrono::system_clock::time_point now = std::chrono::system_clock::now();
2337     RemoveExpired(flowControlTimestampList_, now);
2338     if (flowControlTimestampList_.size() >= MAX_ACTIVE_NUM_PERSECOND) {
2339         return ERR_ANS_OVER_MAX_ACTIVE_PERSECOND;
2340     }
2341 
2342     flowControlTimestampList_.push_back(now);
2343 
2344     std::list<std::shared_ptr<NotificationRecord>> bundleList;
2345     for (auto item : notificationList_) {
2346         if (record->notification->GetBundleName() == item->notification->GetBundleName()) {
2347             bundleList.push_back(item);
2348         }
2349     }
2350 
2351     std::shared_ptr<NotificationRecord> recordToRemove;
2352     if (bundleList.size() >= MAX_ACTIVE_NUM_PERAPP) {
2353         bundleList.sort(SortNotificationsByLevelAndTime);
2354         recordToRemove = bundleList.front();
2355         SendFlowControlOccurHiSysEvent(recordToRemove);
2356         notificationList_.remove(bundleList.front());
2357     }
2358 
2359     if (notificationList_.size() >= MAX_ACTIVE_NUM) {
2360         if (bundleList.size() > 0) {
2361             bundleList.sort(SortNotificationsByLevelAndTime);
2362             recordToRemove = bundleList.front();
2363             SendFlowControlOccurHiSysEvent(recordToRemove);
2364             notificationList_.remove(bundleList.front());
2365         } else {
2366             std::list<std::shared_ptr<NotificationRecord>> sorted = notificationList_;
2367             sorted.sort(SortNotificationsByLevelAndTime);
2368             recordToRemove = sorted.front();
2369             SendFlowControlOccurHiSysEvent(recordToRemove);
2370             notificationList_.remove(sorted.front());
2371         }
2372     }
2373 
2374     AddToNotificationList(record);
2375 
2376     return ERR_OK;
2377 }
2378 
OnBundleRemoved(const sptr<NotificationBundleOption> & bundleOption)2379 void AdvancedNotificationService::OnBundleRemoved(const sptr<NotificationBundleOption> &bundleOption)
2380 {
2381     ANS_LOGD("%{public}s", __FUNCTION__);
2382     if (notificationSvrQueue_ == nullptr) {
2383         ANS_LOGE("Serial queue is invalid.");
2384         return;
2385     }
2386     notificationSvrQueue_->submit(std::bind([this, bundleOption]() {
2387         ANS_LOGD("ffrt enter!");
2388         ErrCode result = NotificationPreferences::GetInstance().RemoveNotificationForBundle(bundleOption);
2389         if (result != ERR_OK) {
2390             ANS_LOGW("NotificationPreferences::RemoveNotificationForBundle failed: %{public}d", result);
2391         }
2392 #ifdef DISTRIBUTED_NOTIFICATION_SUPPORTED
2393         DistributedPreferences::GetInstance()->DeleteDistributedBundleInfo(bundleOption);
2394         std::vector<std::string> keys = GetLocalNotificationKeys(bundleOption);
2395 #else
2396         std::vector<std::string> keys = GetNotificationKeys(bundleOption);
2397 #endif
2398         std::vector<sptr<Notification>> notifications;
2399         for (auto key : keys) {
2400             sptr<Notification> notification = nullptr;
2401             result = RemoveFromNotificationList(key, notification, true,
2402                 NotificationConstant::PACKAGE_CHANGED_REASON_DELETE);
2403             if (result != ERR_OK) {
2404                 continue;
2405             }
2406 
2407             if (notification != nullptr) {
2408                 int32_t reason = NotificationConstant::PACKAGE_CHANGED_REASON_DELETE;
2409                 UpdateRecentNotification(notification, true, reason);
2410                 notifications.emplace_back(notification);
2411                 if (notifications.size() >= MAX_CANCELED_PARCELABLE_VECTOR_NUM) {
2412                     std::vector<sptr<Notification>> currNotificationList = notifications;
2413                     NotificationSubscriberManager::GetInstance()->BatchNotifyCanceled(
2414                         currNotificationList, nullptr, reason);
2415                     notifications.clear();
2416                 }
2417 #ifdef DISTRIBUTED_NOTIFICATION_SUPPORTED
2418                 DoDistributedDelete("", "", notification);
2419 #endif
2420             }
2421         }
2422         if (!notifications.empty()) {
2423             NotificationSubscriberManager::GetInstance()->BatchNotifyCanceled(
2424                 notifications, nullptr, NotificationConstant::PACKAGE_CHANGED_REASON_DELETE);
2425         }
2426 
2427         NotificationPreferences::GetInstance().RemoveAnsBundleDbInfo(bundleOption);
2428     }));
2429 }
2430 
2431 #ifdef DISTRIBUTED_NOTIFICATION_SUPPORTED
OnScreenOn()2432 void AdvancedNotificationService::OnScreenOn()
2433 {
2434     ANS_LOGI("%{public}s", __FUNCTION__);
2435     localScreenOn_ = true;
2436     DistributedScreenStatusManager::GetInstance()->SetLocalScreenStatus(true);
2437 }
2438 
OnScreenOff()2439 void AdvancedNotificationService::OnScreenOff()
2440 {
2441     ANS_LOGI("%{public}s", __FUNCTION__);
2442     localScreenOn_ = false;
2443     DistributedScreenStatusManager::GetInstance()->SetLocalScreenStatus(false);
2444 }
2445 #endif
2446 
OnDistributedKvStoreDeathRecipient()2447 void AdvancedNotificationService::OnDistributedKvStoreDeathRecipient()
2448 {
2449     ANS_LOGD("%{public}s", __FUNCTION__);
2450     if (notificationSvrQueue_ == nullptr) {
2451         ANS_LOGE("Serial queue is invalid.");
2452         return;
2453     }
2454     ffrt::task_handle handler = notificationSvrQueue_->submit_h(std::bind([&]() {
2455         ANS_LOGD("ffrt enter!");
2456         NotificationPreferences::GetInstance().OnDistributedKvStoreDeathRecipient();
2457 #ifdef DISTRIBUTED_NOTIFICATION_SUPPORTED
2458         DistributedNotificationManager::GetInstance()->OnDistributedKvStoreDeathRecipient();
2459 #endif
2460     }));
2461 }
2462 
RemoveAllSlots()2463 ErrCode AdvancedNotificationService::RemoveAllSlots()
2464 {
2465     ANS_LOGD("%{public}s", __FUNCTION__);
2466 
2467     sptr<NotificationBundleOption> bundleOption = GenerateBundleOption();
2468     if (bundleOption == nullptr) {
2469         return ERR_ANS_INVALID_BUNDLE;
2470     }
2471 
2472     if (notificationSvrQueue_ == nullptr) {
2473         ANS_LOGE("Serial queue is invalid.");
2474         return ERR_ANS_INVALID_PARAM;
2475     }
2476     ErrCode result = ERR_OK;
2477     ffrt::task_handle handler = notificationSvrQueue_->submit_h(std::bind([&]() {
2478         ANS_LOGD("ffrt enter!");
2479         result = NotificationPreferences::GetInstance().RemoveNotificationAllSlots(bundleOption);
2480         if (result == ERR_ANS_PREFERENCES_NOTIFICATION_BUNDLE_NOT_EXIST) {
2481             result = ERR_OK;
2482         }
2483     }));
2484     notificationSvrQueue_->wait(handler);
2485     return result;
2486 }
2487 
AddSlotByType(NotificationConstant::SlotType slotType)2488 ErrCode AdvancedNotificationService::AddSlotByType(NotificationConstant::SlotType slotType)
2489 {
2490     ANS_LOGD("%{public}s", __FUNCTION__);
2491 
2492     sptr<NotificationBundleOption> bundleOption = GenerateBundleOption();
2493     if (bundleOption == nullptr) {
2494         return ERR_ANS_INVALID_BUNDLE;
2495     }
2496 
2497     if (notificationSvrQueue_ == nullptr) {
2498         ANS_LOGE("Serial queue is invalid.");
2499         return ERR_ANS_INVALID_PARAM;
2500     }
2501     ErrCode result = ERR_OK;
2502     ffrt::task_handle handler = notificationSvrQueue_->submit_h(std::bind([&]() {
2503         ANS_LOGD("ffrt enter!");
2504         sptr<NotificationSlot> slot;
2505         result = NotificationPreferences::GetInstance().GetNotificationSlot(bundleOption, slotType, slot);
2506         if ((result == ERR_OK) && (slot != nullptr)) {
2507             return;
2508         } else {
2509             slot = new NotificationSlot(slotType);
2510             std::vector<sptr<NotificationSlot>> slots;
2511             slots.push_back(slot);
2512             result = NotificationPreferences::GetInstance().AddNotificationSlots(bundleOption, slots);
2513         }
2514     }));
2515     notificationSvrQueue_->wait(handler);
2516     return result;
2517 }
2518 
RemoveNotification(const sptr<NotificationBundleOption> & bundleOption,int32_t notificationId,const std::string & label,int32_t removeReason)2519 ErrCode AdvancedNotificationService::RemoveNotification(const sptr<NotificationBundleOption> &bundleOption,
2520     int32_t notificationId, const std::string &label, int32_t removeReason)
2521 {
2522     HITRACE_METER_NAME(HITRACE_TAG_NOTIFICATION, __PRETTY_FUNCTION__);
2523     ANS_LOGD("%{public}s", __FUNCTION__);
2524 
2525     bool isSubsystem = AccessTokenHelper::VerifyNativeToken(IPCSkeleton::GetCallingTokenID());
2526     if (!isSubsystem && !AccessTokenHelper::IsSystemApp()) {
2527         return ERR_ANS_NON_SYSTEM_APP;
2528     }
2529 
2530     if (!CheckPermission(OHOS_PERMISSION_NOTIFICATION_CONTROLLER)) {
2531         return ERR_ANS_PERMISSION_DENIED;
2532     }
2533 
2534     sptr<NotificationBundleOption> bundle = GenerateValidBundleOption(bundleOption);
2535     if (bundle == nullptr) {
2536         return ERR_ANS_INVALID_BUNDLE;
2537     }
2538 
2539     if (notificationSvrQueue_ == nullptr) {
2540         ANS_LOGE("Serial queue is invalid.");
2541         return ERR_ANS_INVALID_PARAM;
2542     }
2543     ErrCode result = ERR_ANS_NOTIFICATION_NOT_EXISTS;
2544     ffrt::task_handle handler = notificationSvrQueue_->submit_h(std::bind([&]() {
2545         ANS_LOGD("ffrt enter!");
2546         sptr<Notification> notification = nullptr;
2547         sptr<NotificationRequest> notificationRequest = nullptr;
2548 
2549 #ifdef DISTRIBUTED_NOTIFICATION_SUPPORTED
2550         std::string deviceId;
2551         std::string bundleName;
2552 #endif
2553         for (auto record : notificationList_) {
2554             if ((record->bundleOption->GetBundleName() == bundle->GetBundleName()) &&
2555                 (record->bundleOption->GetUid() == bundle->GetUid()) &&
2556 #ifdef DISTRIBUTED_NOTIFICATION_SUPPORTED
2557                 (record->deviceId.empty()) &&
2558 #endif
2559                 (record->notification->GetId() == notificationId) && (record->notification->GetLabel() == label)) {
2560                 if (!record->notification->IsRemoveAllowed()) {
2561                     result = ERR_ANS_NOTIFICATION_IS_UNALLOWED_REMOVEALLOWED;
2562                     break;
2563                 }
2564 #ifdef DISTRIBUTED_NOTIFICATION_SUPPORTED
2565                 deviceId = record->deviceId;
2566                 bundleName = record->bundleName;
2567 #endif
2568                 notification = record->notification;
2569                 notificationRequest = record->request;
2570                 notificationList_.remove(record);
2571                 result = ERR_OK;
2572                 break;
2573             }
2574         }
2575 
2576         if (notification != nullptr) {
2577             UpdateRecentNotification(notification, true, removeReason);
2578             NotificationSubscriberManager::GetInstance()->NotifyCanceled(notification, nullptr, removeReason);
2579 #ifdef DISTRIBUTED_NOTIFICATION_SUPPORTED
2580             DoDistributedDelete(deviceId, bundleName, notification);
2581 #endif
2582         }
2583         if (removeReason != NotificationConstant::CLICK_REASON_DELETE) {
2584             TriggerRemoveWantAgent(notificationRequest);
2585         }
2586     }));
2587     notificationSvrQueue_->wait(handler);
2588 
2589     SendRemoveHiSysEvent(notificationId, label, bundleOption, result);
2590     return result;
2591 }
2592 
RemoveAllNotifications(const sptr<NotificationBundleOption> & bundleOption)2593 ErrCode AdvancedNotificationService::RemoveAllNotifications(const sptr<NotificationBundleOption> &bundleOption)
2594 {
2595     HITRACE_METER_NAME(HITRACE_TAG_NOTIFICATION, __PRETTY_FUNCTION__);
2596     ANS_LOGD("%{public}s", __FUNCTION__);
2597 
2598     bool isSubsystem = AccessTokenHelper::VerifyNativeToken(IPCSkeleton::GetCallingTokenID());
2599     if (!isSubsystem && !AccessTokenHelper::IsSystemApp()) {
2600         return ERR_ANS_NON_SYSTEM_APP;
2601     }
2602 
2603     if (!CheckPermission(OHOS_PERMISSION_NOTIFICATION_CONTROLLER)) {
2604         return ERR_ANS_PERMISSION_DENIED;
2605     }
2606 
2607     sptr<NotificationBundleOption> bundle = GenerateValidBundleOption(bundleOption);
2608     if (bundle == nullptr) {
2609         return ERR_ANS_INVALID_BUNDLE;
2610     }
2611 
2612     if (notificationSvrQueue_ == nullptr) {
2613         ANS_LOGE("Serial queue is invalid.");
2614         return ERR_ANS_INVALID_PARAM;
2615     }
2616     ffrt::task_handle handler = notificationSvrQueue_->submit_h(std::bind([&]() {
2617         ANS_LOGD("ffrt enter!");
2618         std::vector<std::shared_ptr<NotificationRecord>> removeList;
2619         int32_t reason = NotificationConstant::CANCEL_REASON_DELETE;
2620         for (auto record : notificationList_) {
2621             if (!record->notification->IsRemoveAllowed()) {
2622                 continue;
2623             }
2624 
2625             if ((record->bundleOption->GetBundleName() == bundle->GetBundleName()) &&
2626                 (record->bundleOption->GetUid() == bundle->GetUid()) &&
2627 #ifdef DISTRIBUTED_NOTIFICATION_SUPPORTED
2628                 record->deviceId.empty() &&
2629 #endif
2630                 !record->request->IsUnremovable()) {
2631                 removeList.push_back(record);
2632             }
2633         }
2634 
2635         std::vector<sptr<Notification>> notifications;
2636         for (auto record : removeList) {
2637             notificationList_.remove(record);
2638             if (record->notification != nullptr) {
2639                 UpdateRecentNotification(record->notification, true, reason);
2640                 notifications.emplace_back(record->notification);
2641 #ifdef DISTRIBUTED_NOTIFICATION_SUPPORTED
2642                 DoDistributedDelete(record->deviceId, record->bundleName, record->notification);
2643 #endif
2644             }
2645             if (notifications.size() >= MAX_CANCELED_PARCELABLE_VECTOR_NUM) {
2646                 SendNotificationsOnCanceled(notifications, nullptr, reason);
2647             }
2648 
2649             TriggerRemoveWantAgent(record->request);
2650         }
2651 
2652         if (!notifications.empty()) {
2653             NotificationSubscriberManager::GetInstance()->BatchNotifyCanceled(notifications, nullptr, reason);
2654         }
2655     }));
2656     notificationSvrQueue_->wait(handler);
2657 
2658     return ERR_OK;
2659 }
2660 
RemoveNotifications(const std::vector<std::string> & keys,int32_t removeReason)2661 ErrCode AdvancedNotificationService::RemoveNotifications(
2662     const std::vector<std::string> &keys, int32_t removeReason)
2663 {
2664     HITRACE_METER_NAME(HITRACE_TAG_NOTIFICATION, __PRETTY_FUNCTION__);
2665     ANS_LOGD("enter");
2666 
2667     bool isSubsystem = AccessTokenHelper::VerifyNativeToken(IPCSkeleton::GetCallingTokenID());
2668     if (!isSubsystem && !AccessTokenHelper::IsSystemApp()) {
2669         return ERR_ANS_NON_SYSTEM_APP;
2670     }
2671 
2672     if (!CheckPermission(OHOS_PERMISSION_NOTIFICATION_CONTROLLER)) {
2673         return ERR_ANS_PERMISSION_DENIED;
2674     }
2675 
2676     if (notificationSvrQueue_ == nullptr) {
2677         ANS_LOGE("Serial queue is invalid.");
2678         return ERR_ANS_INVALID_PARAM;
2679     }
2680     ffrt::task_handle handler = notificationSvrQueue_->submit_h(std::bind([&]() {
2681         std::vector<sptr<Notification>> notifications;
2682         for (auto key : keys) {
2683             sptr<Notification> notification = nullptr;
2684 #ifdef DISTRIBUTED_NOTIFICATION_SUPPORTED
2685             std::string deviceId;
2686             std::string bundleName;
2687             GetDistributedInfo(key, deviceId, bundleName);
2688 #endif
2689             ErrCode result = RemoveFromNotificationList(key, notification, false, removeReason);
2690             if (result != ERR_OK) {
2691                 continue;
2692             }
2693             if (notification != nullptr) {
2694                 UpdateRecentNotification(notification, true, removeReason);
2695                 notifications.emplace_back(notification);
2696 #ifdef DISTRIBUTED_NOTIFICATION_SUPPORTED
2697                 DoDistributedDelete(deviceId, bundleName, notification);
2698 #endif
2699             }
2700             if (notifications.size() >= MAX_CANCELED_PARCELABLE_VECTOR_NUM) {
2701                 std::vector<sptr<Notification>> currNotificationList = notifications;
2702                 NotificationSubscriberManager::GetInstance()->BatchNotifyCanceled(
2703                     currNotificationList, nullptr, removeReason);
2704                 notifications.clear();
2705             }
2706         }
2707 
2708         if (!notifications.empty()) {
2709             NotificationSubscriberManager::GetInstance()->BatchNotifyCanceled(notifications, nullptr, removeReason);
2710         }
2711     }));
2712     notificationSvrQueue_->wait(handler);
2713 
2714     return ERR_OK;
2715 }
2716 
GetSlotNumAsBundle(const sptr<NotificationBundleOption> & bundleOption,uint64_t & num)2717 ErrCode AdvancedNotificationService::GetSlotNumAsBundle(
2718     const sptr<NotificationBundleOption> &bundleOption, uint64_t &num)
2719 {
2720     ANS_LOGD("%{public}s", __FUNCTION__);
2721 
2722     bool isSubsystem = AccessTokenHelper::VerifyNativeToken(IPCSkeleton::GetCallingTokenID());
2723     if (!isSubsystem && !AccessTokenHelper::IsSystemApp()) {
2724         return ERR_ANS_NON_SYSTEM_APP;
2725     }
2726 
2727     if (!CheckPermission(OHOS_PERMISSION_NOTIFICATION_CONTROLLER)) {
2728         return ERR_ANS_PERMISSION_DENIED;
2729     }
2730 
2731     sptr<NotificationBundleOption> bundle = GenerateValidBundleOption(bundleOption);
2732     if (bundle == nullptr) {
2733         return ERR_ANS_INVALID_BUNDLE;
2734     }
2735 
2736     if (notificationSvrQueue_ == nullptr) {
2737         ANS_LOGE("Serial queue is invalid.");
2738         return ERR_ANS_INVALID_PARAM;
2739     }
2740     ErrCode result = ERR_OK;
2741     ffrt::task_handle handler = notificationSvrQueue_->submit_h(std::bind([&]() {
2742         ANS_LOGD("ffrt enter!");
2743         result = NotificationPreferences::GetInstance().GetNotificationSlotsNumForBundle(bundle, num);
2744         if (result == ERR_ANS_PREFERENCES_NOTIFICATION_BUNDLE_NOT_EXIST) {
2745             result = ERR_OK;
2746             num = 0;
2747         }
2748     }));
2749     notificationSvrQueue_->wait(handler);
2750 
2751     return result;
2752 }
2753 
CancelGroup(const std::string & groupName)2754 ErrCode AdvancedNotificationService::CancelGroup(const std::string &groupName)
2755 {
2756     ANS_LOGD("%{public}s", __FUNCTION__);
2757 
2758     if (groupName.empty()) {
2759         return ERR_ANS_INVALID_PARAM;
2760     }
2761 
2762     sptr<NotificationBundleOption> bundleOption = GenerateBundleOption();
2763     if (bundleOption == nullptr) {
2764         return ERR_ANS_INVALID_BUNDLE;
2765     }
2766 
2767     if (notificationSvrQueue_ == nullptr) {
2768         ANS_LOGE("Serial queue is invalid.");
2769         return ERR_ANS_INVALID_PARAM;
2770     }
2771     ffrt::task_handle handler = notificationSvrQueue_->submit_h(std::bind([&]() {
2772         ANS_LOGD("ffrt enter!");
2773         std::vector<std::shared_ptr<NotificationRecord>> removeList;
2774         for (auto record : notificationList_) {
2775             if ((record->bundleOption->GetBundleName() == bundleOption->GetBundleName()) &&
2776                 (record->bundleOption->GetUid() == bundleOption->GetUid()) &&
2777 #ifdef DISTRIBUTED_NOTIFICATION_SUPPORTED
2778                 record->deviceId.empty() &&
2779 #endif
2780                 (record->request->GetGroupName() == groupName)) {
2781                 removeList.push_back(record);
2782             }
2783         }
2784 
2785         std::vector<sptr<Notification>> notifications;
2786         for (auto record : removeList) {
2787             notificationList_.remove(record);
2788 
2789             if (record->notification != nullptr) {
2790                 int32_t reason = NotificationConstant::APP_CANCEL_REASON_DELETE;
2791                 UpdateRecentNotification(record->notification, true, reason);
2792                 notifications.emplace_back(record->notification);
2793 #ifdef DISTRIBUTED_NOTIFICATION_SUPPORTED
2794                 DoDistributedDelete(record->deviceId, record->bundleName, record->notification);
2795 #endif
2796             }
2797             if (notifications.size() >= MAX_CANCELED_PARCELABLE_VECTOR_NUM) {
2798                 std::vector<sptr<Notification>> currNotificationList = notifications;
2799                 NotificationSubscriberManager::GetInstance()->BatchNotifyCanceled(
2800                     currNotificationList, nullptr, NotificationConstant::APP_CANCEL_REASON_DELETE);
2801                 notifications.clear();
2802             }
2803         }
2804 
2805         if (!notifications.empty()) {
2806             NotificationSubscriberManager::GetInstance()->BatchNotifyCanceled(
2807                 notifications, nullptr, NotificationConstant::APP_CANCEL_REASON_DELETE);
2808         }
2809     }));
2810     notificationSvrQueue_->wait(handler);
2811 
2812     return ERR_OK;
2813 }
2814 
RemoveGroupByBundle(const sptr<NotificationBundleOption> & bundleOption,const std::string & groupName)2815 ErrCode AdvancedNotificationService::RemoveGroupByBundle(
2816     const sptr<NotificationBundleOption> &bundleOption, const std::string &groupName)
2817 {
2818     ANS_LOGD("%{public}s", __FUNCTION__);
2819 
2820     bool isSubsystem = AccessTokenHelper::VerifyNativeToken(IPCSkeleton::GetCallingTokenID());
2821     if (!isSubsystem && !AccessTokenHelper::IsSystemApp()) {
2822         return ERR_ANS_NON_SYSTEM_APP;
2823     }
2824 
2825     if (!CheckPermission(OHOS_PERMISSION_NOTIFICATION_CONTROLLER)) {
2826         return ERR_ANS_PERMISSION_DENIED;
2827     }
2828 
2829     if (bundleOption == nullptr || groupName.empty()) {
2830         return ERR_ANS_INVALID_PARAM;
2831     }
2832 
2833     sptr<NotificationBundleOption> bundle = GenerateValidBundleOption(bundleOption);
2834     if (bundle == nullptr) {
2835         return ERR_ANS_INVALID_BUNDLE;
2836     }
2837 
2838     if (notificationSvrQueue_ == nullptr) {
2839         ANS_LOGE("Serial queue is invalid.");
2840         return ERR_ANS_INVALID_PARAM;
2841     }
2842     ffrt::task_handle handler = notificationSvrQueue_->submit_h(std::bind([&]() {
2843         ANS_LOGD("ffrt enter!");
2844         std::vector<std::shared_ptr<NotificationRecord>> removeList;
2845         int32_t reason = NotificationConstant::CANCEL_REASON_DELETE;
2846         for (auto record : notificationList_) {
2847             if (!record->notification->IsRemoveAllowed()) {
2848                 continue;
2849             }
2850             if ((record->bundleOption->GetBundleName() == bundle->GetBundleName()) &&
2851                 (record->bundleOption->GetUid() == bundle->GetUid()) && !record->request->IsUnremovable() &&
2852 #ifdef DISTRIBUTED_NOTIFICATION_SUPPORTED
2853                 record->deviceId.empty() &&
2854 #endif
2855                 (record->request->GetGroupName() == groupName)) {
2856                 removeList.push_back(record);
2857             }
2858         }
2859 
2860         std::vector<sptr<Notification>> notifications;
2861         for (auto record : removeList) {
2862             notificationList_.remove(record);
2863 
2864             if (record->notification != nullptr) {
2865                 UpdateRecentNotification(record->notification, true, reason);
2866                 notifications.emplace_back(record->notification);
2867 #ifdef DISTRIBUTED_NOTIFICATION_SUPPORTED
2868                 DoDistributedDelete(record->deviceId, record->bundleName, record->notification);
2869 #endif
2870             }
2871             if (notifications.size() >= MAX_CANCELED_PARCELABLE_VECTOR_NUM) {
2872                 SendNotificationsOnCanceled(notifications, nullptr, reason);
2873             }
2874         }
2875 
2876         if (!notifications.empty()) {
2877             NotificationSubscriberManager::GetInstance()->BatchNotifyCanceled(notifications, nullptr, reason);
2878         }
2879     }));
2880     notificationSvrQueue_->wait(handler);
2881 
2882     return ERR_OK;
2883 }
2884 
AdjustDateForDndTypeOnce(int64_t & beginDate,int64_t & endDate)2885 void AdvancedNotificationService::AdjustDateForDndTypeOnce(int64_t &beginDate, int64_t &endDate)
2886 {
2887     std::chrono::system_clock::time_point now = std::chrono::system_clock::now();
2888     time_t nowT = std::chrono::system_clock::to_time_t(now);
2889     tm nowTm = GetLocalTime(nowT);
2890 
2891     auto beginDateMilliseconds = std::chrono::milliseconds(beginDate);
2892     auto beginDateTimePoint =
2893         std::chrono::time_point<std::chrono::system_clock, std::chrono::milliseconds>(beginDateMilliseconds);
2894     time_t beginDateT = std::chrono::system_clock::to_time_t(beginDateTimePoint);
2895     tm beginDateTm = GetLocalTime(beginDateT);
2896 
2897     auto endDateMilliseconds = std::chrono::milliseconds(endDate);
2898     auto endDateTimePoint =
2899         std::chrono::time_point<std::chrono::system_clock, std::chrono::milliseconds>(endDateMilliseconds);
2900     time_t endDateT = std::chrono::system_clock::to_time_t(endDateTimePoint);
2901     tm endDateTm = GetLocalTime(endDateT);
2902 
2903     tm todayBeginTm = nowTm;
2904     todayBeginTm.tm_sec = 0;
2905     todayBeginTm.tm_min = beginDateTm.tm_min;
2906     todayBeginTm.tm_hour = beginDateTm.tm_hour;
2907 
2908     tm todayEndTm = nowTm;
2909     todayEndTm.tm_sec = 0;
2910     todayEndTm.tm_min = endDateTm.tm_min;
2911     todayEndTm.tm_hour = endDateTm.tm_hour;
2912 
2913     time_t todayBeginT = mktime(&todayBeginTm);
2914     if (todayBeginT == -1) {
2915         return;
2916     }
2917     time_t todayEndT = mktime(&todayEndTm);
2918     if (todayEndT == -1) {
2919         return;
2920     }
2921 
2922     auto newBeginTimePoint = std::chrono::system_clock::from_time_t(todayBeginT);
2923     auto newEndTimePoint = std::chrono::system_clock::from_time_t(todayEndT);
2924     if (newBeginTimePoint >= newEndTimePoint) {
2925         newEndTimePoint += std::chrono::hours(HOURS_IN_ONE_DAY);
2926     }
2927 
2928     if (newEndTimePoint < now) {
2929         newBeginTimePoint += std::chrono::hours(HOURS_IN_ONE_DAY);
2930         newEndTimePoint += std::chrono::hours(HOURS_IN_ONE_DAY);
2931     }
2932 
2933     auto newBeginDuration = std::chrono::duration_cast<std::chrono::milliseconds>(newBeginTimePoint.time_since_epoch());
2934     beginDate = newBeginDuration.count();
2935 
2936     auto newEndDuration = std::chrono::duration_cast<std::chrono::milliseconds>(newEndTimePoint.time_since_epoch());
2937     endDate = newEndDuration.count();
2938 }
2939 
SetDoNotDisturbDate(const sptr<NotificationDoNotDisturbDate> & date)2940 ErrCode AdvancedNotificationService::SetDoNotDisturbDate(const sptr<NotificationDoNotDisturbDate> &date)
2941 {
2942     ANS_LOGD("%{public}s", __FUNCTION__);
2943 
2944     bool isSubsystem = AccessTokenHelper::VerifyNativeToken(IPCSkeleton::GetCallingTokenID());
2945     if (!isSubsystem && !AccessTokenHelper::IsSystemApp()) {
2946         ANS_LOGW("Not system app!");
2947         return ERR_ANS_NON_SYSTEM_APP;
2948     }
2949 
2950     if (!CheckPermission(OHOS_PERMISSION_NOTIFICATION_CONTROLLER)) {
2951         ANS_LOGW("Check permission denied!");
2952         return ERR_ANS_PERMISSION_DENIED;
2953     }
2954 
2955     int32_t userId = SUBSCRIBE_USER_INIT;
2956     if (!GetActiveUserId(userId)) {
2957         ANS_LOGW("No active user found!");
2958         return ERR_ANS_GET_ACTIVE_USER_FAILED;
2959     }
2960 
2961     return SetDoNotDisturbDateByUser(userId, date);
2962 }
2963 
GetDoNotDisturbDate(sptr<NotificationDoNotDisturbDate> & date)2964 ErrCode AdvancedNotificationService::GetDoNotDisturbDate(sptr<NotificationDoNotDisturbDate> &date)
2965 {
2966     ANS_LOGD("%{public}s", __FUNCTION__);
2967 
2968     bool isSubsystem = AccessTokenHelper::VerifyNativeToken(IPCSkeleton::GetCallingTokenID());
2969     if (!isSubsystem && !AccessTokenHelper::IsSystemApp()) {
2970         return ERR_ANS_NON_SYSTEM_APP;
2971     }
2972 
2973     if (!CheckPermission(OHOS_PERMISSION_NOTIFICATION_CONTROLLER)) {
2974         return ERR_ANS_PERMISSION_DENIED;
2975     }
2976 
2977     int32_t userId = SUBSCRIBE_USER_INIT;
2978     if (!GetActiveUserId(userId)) {
2979         return ERR_ANS_GET_ACTIVE_USER_FAILED;
2980     }
2981 
2982     return GetDoNotDisturbDateByUser(userId, date);
2983 }
2984 
DoesSupportDoNotDisturbMode(bool & doesSupport)2985 ErrCode AdvancedNotificationService::DoesSupportDoNotDisturbMode(bool &doesSupport)
2986 {
2987     ANS_LOGD("%{public}s", __FUNCTION__);
2988 
2989     bool isSubsystem = AccessTokenHelper::VerifyNativeToken(IPCSkeleton::GetCallingTokenID());
2990     if (!isSubsystem && !AccessTokenHelper::IsSystemApp()) {
2991         return ERR_ANS_NON_SYSTEM_APP;
2992     }
2993 
2994     if (!CheckPermission(OHOS_PERMISSION_NOTIFICATION_CONTROLLER)) {
2995         return ERR_ANS_PERMISSION_DENIED;
2996     }
2997 
2998     doesSupport = SUPPORT_DO_NOT_DISTRUB;
2999     return ERR_OK;
3000 }
3001 
CheckPermission(const std::string & permission)3002 bool AdvancedNotificationService::CheckPermission(const std::string &permission)
3003 {
3004     ANS_LOGD("%{public}s", __FUNCTION__);
3005 
3006     bool isSubsystem = AccessTokenHelper::VerifyNativeToken(IPCSkeleton::GetCallingTokenID());
3007     if (isSubsystem) {
3008         return true;
3009     }
3010 
3011     auto tokenCaller = IPCSkeleton::GetCallingTokenID();
3012     bool result = AccessTokenHelper::VerifyCallerPermission(tokenCaller, permission);
3013     if (!result) {
3014         ANS_LOGE("Permission denied");
3015     }
3016     return result;
3017 }
3018 
IsDistributedEnabled(bool & enabled)3019 ErrCode AdvancedNotificationService::IsDistributedEnabled(bool &enabled)
3020 {
3021     ANS_LOGD("%{public}s", __FUNCTION__);
3022 #ifdef DISTRIBUTED_NOTIFICATION_SUPPORTED
3023     if (notificationSvrQueue_ == nullptr) {
3024         ANS_LOGE("Serial queue is invalid.");
3025         return ERR_ANS_INVALID_PARAM;
3026     }
3027     ErrCode result = ERR_OK;
3028     ffrt::task_handle handler = notificationSvrQueue_->submit_h(std::bind([&]() {
3029         ANS_LOGD("ffrt enter!");
3030         result = DistributedPreferences::GetInstance()->GetDistributedEnable(enabled);
3031         if (result != ERR_OK) {
3032             result = ERR_OK;
3033             enabled = false;
3034         }
3035     }));
3036     notificationSvrQueue_->wait(handler);
3037     return result;
3038 #else
3039     return ERR_INVALID_OPERATION;
3040 #endif
3041 }
3042 
EnableDistributed(bool enabled)3043 ErrCode AdvancedNotificationService::EnableDistributed(bool enabled)
3044 {
3045     ANS_LOGD("%{public}s", __FUNCTION__);
3046 
3047 #ifdef DISTRIBUTED_NOTIFICATION_SUPPORTED
3048     bool isSubsystem = AccessTokenHelper::VerifyNativeToken(IPCSkeleton::GetCallingTokenID());
3049     if (!isSubsystem && !AccessTokenHelper::IsSystemApp()) {
3050         return ERR_ANS_NON_SYSTEM_APP;
3051     }
3052 
3053     if (!CheckPermission(OHOS_PERMISSION_NOTIFICATION_CONTROLLER)) {
3054         return ERR_ANS_PERMISSION_DENIED;
3055     }
3056 
3057     if (notificationSvrQueue_ == nullptr) {
3058         ANS_LOGE("Serial queue is invalid.");
3059         return ERR_ANS_INVALID_PARAM;
3060     }
3061     ErrCode result = ERR_OK;
3062     ffrt::task_handle handler = notificationSvrQueue_->submit_h(
3063         std::bind([&]() {
3064             result = DistributedPreferences::GetInstance()->SetDistributedEnable(enabled);
3065             ANS_LOGE("ffrt enter!");
3066         }));
3067     notificationSvrQueue_->wait(handler);
3068     return result;
3069 #else
3070     return ERR_INVALID_OPERATION;
3071 #endif
3072 }
3073 
EnableDistributedByBundle(const sptr<NotificationBundleOption> & bundleOption,bool enabled)3074 ErrCode AdvancedNotificationService::EnableDistributedByBundle(
3075     const sptr<NotificationBundleOption> &bundleOption, bool enabled)
3076 {
3077     ANS_LOGD("%{public}s", __FUNCTION__);
3078 
3079 #ifdef DISTRIBUTED_NOTIFICATION_SUPPORTED
3080     bool isSubsystem = AccessTokenHelper::VerifyNativeToken(IPCSkeleton::GetCallingTokenID());
3081     if (!isSubsystem && !AccessTokenHelper::IsSystemApp()) {
3082         return ERR_ANS_NON_SYSTEM_APP;
3083     }
3084 
3085     if (!CheckPermission(OHOS_PERMISSION_NOTIFICATION_CONTROLLER)) {
3086         return ERR_ANS_PERMISSION_DENIED;
3087     }
3088 
3089     sptr<NotificationBundleOption> bundle = GenerateValidBundleOption(bundleOption);
3090     if (bundle == nullptr) {
3091         return ERR_ANS_INVALID_BUNDLE;
3092     }
3093 
3094     bool appInfoEnable = true;
3095     GetDistributedEnableInApplicationInfo(bundle, appInfoEnable);
3096     if (!appInfoEnable) {
3097         ANS_LOGD("Get from bms is %{public}d", appInfoEnable);
3098         return ERR_ANS_PERMISSION_DENIED;
3099     }
3100 
3101     if (notificationSvrQueue_ == nullptr) {
3102         ANS_LOGE("Serial queue is invalid.");
3103         return ERR_ANS_INVALID_PARAM;
3104     }
3105     ErrCode result = ERR_OK;
3106     ffrt::task_handle handler = notificationSvrQueue_->submit_h(std::bind([&]() {
3107         ANS_LOGD("ffrt enter!");
3108         result = DistributedPreferences::GetInstance()->SetDistributedBundleEnable(bundle, enabled);
3109         if (result != ERR_OK) {
3110             result = ERR_OK;
3111             enabled = false;
3112         }
3113     }));
3114     notificationSvrQueue_->wait(handler);
3115     return result;
3116 #else
3117     return ERR_INVALID_OPERATION;
3118 #endif
3119 }
3120 
EnableDistributedSelf(const bool enabled)3121 ErrCode AdvancedNotificationService::EnableDistributedSelf(const bool enabled)
3122 {
3123     ANS_LOGD("%{public}s", __FUNCTION__);
3124 #ifdef DISTRIBUTED_NOTIFICATION_SUPPORTED
3125     sptr<NotificationBundleOption> bundleOption = GenerateBundleOption();
3126     if (bundleOption == nullptr) {
3127         return ERR_ANS_INVALID_BUNDLE;
3128     }
3129 
3130     bool appInfoEnable = true;
3131     GetDistributedEnableInApplicationInfo(bundleOption, appInfoEnable);
3132     if (!appInfoEnable) {
3133         ANS_LOGD("Get from bms is %{public}d", appInfoEnable);
3134         return ERR_ANS_PERMISSION_DENIED;
3135     }
3136 
3137     if (notificationSvrQueue_ == nullptr) {
3138         ANS_LOGE("Serial queue is invalid.");
3139         return ERR_ANS_INVALID_PARAM;
3140     }
3141     ErrCode result = ERR_OK;
3142     ffrt::task_handle handler = notificationSvrQueue_->submit_h(std::bind(
3143         [&]() {
3144             ANS_LOGD("ffrt enter!");
3145             result = DistributedPreferences::GetInstance()->SetDistributedBundleEnable(bundleOption, enabled);
3146         }));
3147     notificationSvrQueue_->wait(handler);
3148     return result;
3149 #else
3150     return ERR_INVALID_OPERATION;
3151 #endif
3152 }
3153 
IsDistributedEnableByBundle(const sptr<NotificationBundleOption> & bundleOption,bool & enabled)3154 ErrCode AdvancedNotificationService::IsDistributedEnableByBundle(
3155     const sptr<NotificationBundleOption> &bundleOption, bool &enabled)
3156 {
3157     ANS_LOGD("%{public}s", __FUNCTION__);
3158 
3159 #ifdef DISTRIBUTED_NOTIFICATION_SUPPORTED
3160     bool isSubsystem = AccessTokenHelper::VerifyNativeToken(IPCSkeleton::GetCallingTokenID());
3161     if (!isSubsystem && !AccessTokenHelper::IsSystemApp()) {
3162         return ERR_ANS_NON_SYSTEM_APP;
3163     }
3164 
3165     if (!CheckPermission(OHOS_PERMISSION_NOTIFICATION_CONTROLLER)) {
3166         return ERR_ANS_PERMISSION_DENIED;
3167     }
3168 
3169     sptr<NotificationBundleOption> bundle = GenerateValidBundleOption(bundleOption);
3170     if (bundle == nullptr) {
3171         return ERR_ANS_INVALID_BUNDLE;
3172     }
3173 
3174     bool appInfoEnable = true;
3175     GetDistributedEnableInApplicationInfo(bundle, appInfoEnable);
3176     if (!appInfoEnable) {
3177         ANS_LOGD("Get from bms is %{public}d", appInfoEnable);
3178         enabled = appInfoEnable;
3179         return ERR_OK;
3180     }
3181 
3182     if (notificationSvrQueue_ == nullptr) {
3183         ANS_LOGE("Serial queue is invalid.");
3184         return ERR_ANS_INVALID_PARAM;
3185     }
3186     ErrCode result = ERR_OK;
3187     ffrt::task_handle handler = notificationSvrQueue_->submit_h(std::bind([&]() {
3188         ANS_LOGD("ffrt enter!");
3189         result = DistributedPreferences::GetInstance()->GetDistributedBundleEnable(bundle, enabled);
3190         if (result != ERR_OK) {
3191             result = ERR_OK;
3192             enabled = false;
3193         }
3194     }));
3195     notificationSvrQueue_->wait(handler);
3196     return result;
3197 #else
3198     return ERR_INVALID_OPERATION;
3199 #endif
3200 }
3201 
GetDeviceRemindType(NotificationConstant::RemindType & remindType)3202 ErrCode AdvancedNotificationService::GetDeviceRemindType(NotificationConstant::RemindType &remindType)
3203 {
3204     ANS_LOGD("%{public}s", __FUNCTION__);
3205 
3206     bool isSubsystem = AccessTokenHelper::VerifyNativeToken(IPCSkeleton::GetCallingTokenID());
3207     if (!isSubsystem && !AccessTokenHelper::IsSystemApp()) {
3208         return ERR_ANS_NON_SYSTEM_APP;
3209     }
3210 
3211     if (!CheckPermission(OHOS_PERMISSION_NOTIFICATION_CONTROLLER)) {
3212         return ERR_ANS_PERMISSION_DENIED;
3213     }
3214 
3215 #ifdef DISTRIBUTED_NOTIFICATION_SUPPORTED
3216     if (notificationSvrQueue_ == nullptr) {
3217         ANS_LOGE("Serial queue is invalid.");
3218         return ERR_ANS_INVALID_PARAM;
3219     }
3220     ffrt::task_handle handler = notificationSvrQueue_->submit_h(std::bind([&]() { remindType = GetRemindType(); }));
3221     notificationSvrQueue_->wait(handler);
3222     return ERR_OK;
3223 #else
3224     return ERR_INVALID_OPERATION;
3225 #endif
3226 }
3227 
SetNotificationRemindType(sptr<Notification> notification,bool isLocal)3228 ErrCode AdvancedNotificationService::SetNotificationRemindType(sptr<Notification> notification, bool isLocal)
3229 {
3230 #ifdef DISTRIBUTED_NOTIFICATION_SUPPORTED
3231     notification->SetRemindType(GetRemindType());
3232 #else
3233     notification->SetRemindType(NotificationConstant::RemindType::NONE);
3234 #endif
3235     return ERR_OK;
3236 }
3237 
3238 #ifdef DISTRIBUTED_NOTIFICATION_SUPPORTED
GetLocalNotificationKeys(const sptr<NotificationBundleOption> & bundleOption)3239 std::vector<std::string> AdvancedNotificationService::GetLocalNotificationKeys(
3240     const sptr<NotificationBundleOption> &bundleOption)
3241 {
3242     std::vector<std::string> keys;
3243 
3244     for (auto record : notificationList_) {
3245         if ((bundleOption != nullptr) && (record->bundleOption->GetBundleName() != bundleOption->GetBundleName()) &&
3246             (record->bundleOption->GetUid() != bundleOption->GetUid()) && record->deviceId.empty()) {
3247             continue;
3248         }
3249         keys.push_back(record->notification->GetKey());
3250     }
3251 
3252     return keys;
3253 }
3254 
GetRemindType()3255 NotificationConstant::RemindType AdvancedNotificationService::GetRemindType()
3256 {
3257     bool remind = localScreenOn_;
3258     if (distributedReminderPolicy_ == NotificationConstant::DistributedReminderPolicy::DEFAULT) {
3259         bool remoteUsing = false;
3260         ErrCode result = DistributedScreenStatusManager::GetInstance()->CheckRemoteDevicesIsUsing(remoteUsing);
3261         if (result != ERR_OK) {
3262             remind = true;
3263         }
3264         if (!localScreenOn_ && !remoteUsing) {
3265             remind = true;
3266         }
3267     } else if (distributedReminderPolicy_ == NotificationConstant::DistributedReminderPolicy::ALWAYS_REMIND) {
3268         remind = true;
3269     } else if (distributedReminderPolicy_ == NotificationConstant::DistributedReminderPolicy::DO_NOT_REMIND) {
3270         remind = false;
3271     }
3272 
3273     if (localScreenOn_) {
3274         if (remind) {
3275             return NotificationConstant::RemindType::DEVICE_ACTIVE_REMIND;
3276         } else {
3277             return NotificationConstant::RemindType::DEVICE_ACTIVE_DONOT_REMIND;
3278         }
3279     } else {
3280         if (remind) {
3281             return NotificationConstant::RemindType::DEVICE_IDLE_REMIND;
3282         } else {
3283             return NotificationConstant::RemindType::DEVICE_IDLE_DONOT_REMIND;
3284         }
3285     }
3286 }
3287 
GetDistributedInfo(const std::string & key,std::string & deviceId,std::string & bundleName)3288 void AdvancedNotificationService::GetDistributedInfo(
3289     const std::string &key, std::string &deviceId, std::string &bundleName)
3290 {
3291     for (auto record : notificationList_) {
3292         if (record->notification->GetKey() == key) {
3293             deviceId = record->deviceId;
3294             bundleName = record->bundleName;
3295             break;
3296         }
3297     }
3298 }
3299 
DoDistributedPublish(const sptr<NotificationBundleOption> bundleOption,const std::shared_ptr<NotificationRecord> record)3300 ErrCode AdvancedNotificationService::DoDistributedPublish(
3301     const sptr<NotificationBundleOption> bundleOption, const std::shared_ptr<NotificationRecord> record)
3302 {
3303     bool appInfoEnable = true;
3304     GetDistributedEnableInApplicationInfo(bundleOption, appInfoEnable);
3305     if (!appInfoEnable) {
3306         return ERR_OK;
3307     }
3308 
3309     if (!record->request->GetNotificationDistributedOptions().IsDistributed()) {
3310         return ERR_OK;
3311     }
3312 
3313     ErrCode result;
3314     bool distributedEnable = false;
3315     result = DistributedPreferences::GetInstance()->GetDistributedEnable(distributedEnable);
3316     if (result != ERR_OK || !distributedEnable) {
3317         return result;
3318     }
3319 
3320     bool bundleDistributedEnable = false;
3321     result = DistributedPreferences::GetInstance()->GetDistributedBundleEnable(bundleOption, bundleDistributedEnable);
3322     if (result != ERR_OK || !bundleDistributedEnable) {
3323         return result;
3324     }
3325 
3326     return DistributedNotificationManager::GetInstance()->Publish(record->notification->GetBundleName(),
3327         record->notification->GetLabel(),
3328         record->notification->GetId(),
3329         record->request);
3330 }
3331 
DoDistributedDelete(const std::string deviceId,const std::string bundleName,const sptr<Notification> notification)3332 ErrCode AdvancedNotificationService::DoDistributedDelete(
3333     const std::string deviceId, const std::string bundleName, const sptr<Notification> notification)
3334 {
3335     HITRACE_METER_NAME(HITRACE_TAG_NOTIFICATION, __PRETTY_FUNCTION__);
3336     if (!notification->GetNotificationRequest().GetNotificationDistributedOptions().IsDistributed()) {
3337         return ERR_OK;
3338     }
3339     if (deviceId.empty()) {
3340         return DistributedNotificationManager::GetInstance()->Delete(
3341             notification->GetBundleName(), notification->GetLabel(), notification->GetId());
3342     } else {
3343         return DistributedNotificationManager::GetInstance()->DeleteRemoteNotification(
3344             deviceId, bundleName, notification->GetLabel(), notification->GetId());
3345     }
3346 
3347     return ERR_OK;
3348 }
3349 
CheckDistributedNotificationType(const sptr<NotificationRequest> & request)3350 bool AdvancedNotificationService::CheckDistributedNotificationType(const sptr<NotificationRequest> &request)
3351 {
3352     auto deviceTypeList = request->GetNotificationDistributedOptions().GetDevicesSupportDisplay();
3353     if (deviceTypeList.empty()) {
3354         return true;
3355     }
3356 
3357     DistributedDatabase::DeviceInfo localDeviceInfo;
3358     DistributedNotificationManager::GetInstance()->GetLocalDeviceInfo(localDeviceInfo);
3359     for (auto device : deviceTypeList) {
3360         if (atoi(device.c_str()) == localDeviceInfo.deviceTypeId) {
3361             return true;
3362         }
3363     }
3364     return false;
3365 }
3366 
OnDistributedPublish(const std::string & deviceId,const std::string & bundleName,sptr<NotificationRequest> & request)3367 void AdvancedNotificationService::OnDistributedPublish(
3368     const std::string &deviceId, const std::string &bundleName, sptr<NotificationRequest> &request)
3369 {
3370     ANS_LOGD("%{public}s", __FUNCTION__);
3371     int32_t activeUserId = -1;
3372     if (!GetActiveUserId(activeUserId)) {
3373         ANS_LOGE("Failed to get active user id!");
3374         return;
3375     }
3376 
3377     if (notificationSvrQueue_ == nullptr) {
3378         ANS_LOGE("Serial queue is invalid.");
3379         return;
3380     }
3381     notificationSvrQueue_->submit(std::bind([this, deviceId, bundleName, request, activeUserId]() {
3382         ANS_LOGD("ffrt enter!");
3383         if (!CheckDistributedNotificationType(request)) {
3384             ANS_LOGD("device type not support display.");
3385             return;
3386         }
3387 
3388         int32_t uid = BundleManagerHelper::GetInstance()->GetDefaultUidByBundleName(bundleName, activeUserId);
3389         if (uid <= 0) {
3390             if (CheckPublishWithoutApp(activeUserId, request)) {
3391                 request->SetOwnerBundleName(FOUNDATION_BUNDLE_NAME);
3392                 request->SetCreatorBundleName(FOUNDATION_BUNDLE_NAME);
3393             } else {
3394                 ANS_LOGE("bundle does not exit and enable off!");
3395                 return;
3396             }
3397         }
3398         std::string bundle = request->GetOwnerBundleName();
3399         request->SetCreatorUid(BundleManagerHelper::GetInstance()->GetDefaultUidByBundleName(bundle, activeUserId));
3400         sptr<NotificationBundleOption> bundleOption =
3401             GenerateValidBundleOption(new NotificationBundleOption(bundle, 0));
3402 
3403         std::shared_ptr<NotificationRecord> record = std::make_shared<NotificationRecord>();
3404         if (record == nullptr) {
3405             return;
3406         }
3407         record->request = request;
3408         record->notification = new Notification(deviceId, request);
3409         record->bundleOption = bundleOption;
3410         record->deviceId = deviceId;
3411         record->bundleName = bundleName;
3412         SetNotificationRemindType(record->notification, false);
3413 
3414         ErrCode result = AssignValidNotificationSlot(record);
3415         if (result != ERR_OK) {
3416             ANS_LOGE("Can not assign valid slot!");
3417             return;
3418         }
3419 
3420         result = Filter(record);
3421         if (result != ERR_OK) {
3422             ANS_LOGE("Reject by filters: %{public}d", result);
3423             return;
3424         }
3425 
3426         result = FlowControl(record);
3427         if (result != ERR_OK) {
3428             return;
3429         }
3430 
3431         UpdateRecentNotification(record->notification, false, 0);
3432         sptr<NotificationSortingMap> sortingMap = GenerateSortingMap();
3433         NotificationSubscriberManager::GetInstance()->NotifyConsumed(record->notification, sortingMap);
3434     }));
3435 }
3436 
OnDistributedUpdate(const std::string & deviceId,const std::string & bundleName,sptr<NotificationRequest> & request)3437 void AdvancedNotificationService::OnDistributedUpdate(
3438     const std::string &deviceId, const std::string &bundleName, sptr<NotificationRequest> &request)
3439 {
3440     ANS_LOGD("%{public}s", __FUNCTION__);
3441     int32_t activeUserId = -1;
3442     if (!GetActiveUserId(activeUserId)) {
3443         ANS_LOGE("Failed to get active user id!");
3444         return;
3445     }
3446 
3447     if (notificationSvrQueue_ == nullptr) {
3448         ANS_LOGE("Serial queue is invalid.");
3449         return;
3450     }
3451     notificationSvrQueue_->submit(std::bind([this, deviceId, bundleName, request, activeUserId]() {
3452         ANS_LOGD("ffrt enter!");
3453         if (!CheckDistributedNotificationType(request)) {
3454             ANS_LOGD("device type not support display.");
3455             return;
3456         }
3457 
3458         int32_t uid = BundleManagerHelper::GetInstance()->GetDefaultUidByBundleName(bundleName, activeUserId);
3459         if (uid <= 0) {
3460             if (CheckPublishWithoutApp(activeUserId, request)) {
3461                 request->SetOwnerBundleName(FOUNDATION_BUNDLE_NAME);
3462                 request->SetCreatorBundleName(FOUNDATION_BUNDLE_NAME);
3463             } else {
3464                 ANS_LOGE("bundle does not exit and enable off!");
3465                 return;
3466             }
3467         }
3468         std::string bundle = request->GetOwnerBundleName();
3469         request->SetCreatorUid(BundleManagerHelper::GetInstance()->GetDefaultUidByBundleName(bundle, activeUserId));
3470         sptr<NotificationBundleOption> bundleOption =
3471             GenerateValidBundleOption(new NotificationBundleOption(bundle, 0));
3472 
3473         std::shared_ptr<NotificationRecord> record = std::make_shared<NotificationRecord>();
3474         if (record == nullptr) {
3475             return;
3476         }
3477         record->request = request;
3478         record->notification = new Notification(deviceId, request);
3479         record->bundleOption = bundleOption;
3480         record->deviceId = deviceId;
3481         record->bundleName = bundleName;
3482         SetNotificationRemindType(record->notification, false);
3483 
3484         ErrCode result = AssignValidNotificationSlot(record);
3485         if (result != ERR_OK) {
3486             ANS_LOGE("Can not assign valid slot!");
3487             return;
3488         }
3489 
3490         result = Filter(record);
3491         if (result != ERR_OK) {
3492             ANS_LOGE("Reject by filters: %{public}d", result);
3493             return;
3494         }
3495 
3496         if (IsNotificationExists(record->notification->GetKey())) {
3497             if (record->request->IsAlertOneTime()) {
3498                 record->notification->SetEnableLight(false);
3499                 record->notification->SetEnableSound(false);
3500                 record->notification->SetEnableVibration(false);
3501             }
3502             UpdateInNotificationList(record);
3503         }
3504 
3505         UpdateRecentNotification(record->notification, false, 0);
3506         sptr<NotificationSortingMap> sortingMap = GenerateSortingMap();
3507         NotificationSubscriberManager::GetInstance()->NotifyConsumed(record->notification, sortingMap);
3508     }));
3509 }
3510 
OnDistributedDelete(const std::string & deviceId,const std::string & bundleName,const std::string & label,int32_t id)3511 void AdvancedNotificationService::OnDistributedDelete(
3512     const std::string &deviceId, const std::string &bundleName, const std::string &label, int32_t id)
3513 {
3514     ANS_LOGD("%{public}s", __FUNCTION__);
3515     if (notificationSvrQueue_ == nullptr) {
3516         ANS_LOGE("Serial queue is invalid.");
3517         return;
3518     }
3519     notificationSvrQueue_->submit(std::bind([this, deviceId, bundleName, label, id]() {
3520         ANS_LOGD("ffrt enter!");
3521         int32_t activeUserId = -1;
3522         if (!GetActiveUserId(activeUserId)) {
3523             ANS_LOGE("Failed to get active user id!");
3524             return;
3525         }
3526         int32_t uid = BundleManagerHelper::GetInstance()->GetDefaultUidByBundleName(bundleName, activeUserId);
3527         std::string bundle = (uid > 0) ? bundleName : FOUNDATION_BUNDLE_NAME;
3528         sptr<NotificationBundleOption> bundleOption =
3529             GenerateValidBundleOption(new NotificationBundleOption(bundle, 0));
3530 
3531         std::string recordDeviceId;
3532         DistributedDatabase::DeviceInfo localDeviceInfo;
3533         if (DistributedNotificationManager::GetInstance()->GetLocalDeviceInfo(localDeviceInfo) == ERR_OK &&
3534             strcmp(deviceId.c_str(), localDeviceInfo.deviceId) == 0) {
3535             recordDeviceId = "";
3536         } else {
3537             recordDeviceId = deviceId;
3538         }
3539 
3540         sptr<Notification> notification = nullptr;
3541         for (auto record : notificationList_) {
3542             if ((record->deviceId == recordDeviceId) &&
3543                 ((record->bundleOption->GetBundleName() == bundleOption->GetBundleName()) ||
3544                 (record->bundleName == bundleName)) &&
3545                 (record->bundleOption->GetUid() == bundleOption->GetUid()) &&
3546                 (record->notification->GetLabel() == label) && (record->notification->GetId() == id)) {
3547                 notification = record->notification;
3548                 notificationList_.remove(record);
3549                 break;
3550             }
3551         }
3552 
3553         if (notification != nullptr) {
3554             int32_t reason = NotificationConstant::APP_CANCEL_REASON_OTHER;
3555             UpdateRecentNotification(notification, true, reason);
3556             NotificationSubscriberManager::GetInstance()->NotifyCanceled(notification, nullptr, reason);
3557         }
3558     }));
3559 }
3560 
GetDistributedEnableInApplicationInfo(const sptr<NotificationBundleOption> bundleOption,bool & enable)3561 ErrCode AdvancedNotificationService::GetDistributedEnableInApplicationInfo(
3562     const sptr<NotificationBundleOption> bundleOption, bool &enable)
3563 {
3564     int32_t userId = SUBSCRIBE_USER_INIT;
3565     OHOS::AccountSA::OsAccountManager::GetOsAccountLocalIdFromUid(bundleOption->GetUid(), userId);
3566 
3567     if (userId >= SUBSCRIBE_USER_SYSTEM_BEGIN && userId <= SUBSCRIBE_USER_SYSTEM_END) {
3568         enable = true;
3569     } else {
3570         enable = BundleManagerHelper::GetInstance()->GetDistributedNotificationEnabled(
3571             bundleOption->GetBundleName(), userId);
3572     }
3573 
3574     return ERR_OK;
3575 }
3576 
CheckPublishWithoutApp(const int32_t userId,const sptr<NotificationRequest> & request)3577 bool AdvancedNotificationService::CheckPublishWithoutApp(const int32_t userId, const sptr<NotificationRequest> &request)
3578 {
3579     bool enabled = false;
3580     DistributedPreferences::GetInstance()->GetSyncEnabledWithoutApp(userId, enabled);
3581     if (!enabled) {
3582         ANS_LOGE("enable is false, userId[%{public}d]", userId);
3583         return false;
3584     }
3585 
3586     std::shared_ptr<AbilityRuntime::WantAgent::WantAgent> wantAgent = request->GetWantAgent();
3587     if (!wantAgent) {
3588         ANS_LOGE("Failed to get wantAgent!");
3589         return false;
3590     }
3591 
3592     std::shared_ptr<AAFwk::Want> want = AbilityRuntime::WantAgent::WantAgentHelper::GetWant(wantAgent);
3593     if (!want || want->GetDeviceId().empty()) {
3594         ANS_LOGE("Failed to get want!");
3595         return false;
3596     }
3597 
3598     return true;
3599 }
3600 #endif
3601 
PrepareContinuousTaskNotificationRequest(const sptr<NotificationRequest> & request,const int32_t & uid)3602 ErrCode AdvancedNotificationService::PrepareContinuousTaskNotificationRequest(
3603     const sptr<NotificationRequest> &request, const int32_t &uid)
3604 {
3605     int32_t pid = IPCSkeleton::GetCallingPid();
3606     request->SetCreatorUid(uid);
3607     request->SetCreatorPid(pid);
3608     if (request->GetDeliveryTime() <= 0) {
3609         request->SetDeliveryTime(GetCurrentTime());
3610     }
3611 
3612     ErrCode result = CheckPictureSize(request);
3613     return result;
3614 }
3615 
IsSupportTemplate(const std::string & templateName,bool & support)3616 ErrCode AdvancedNotificationService::IsSupportTemplate(const std::string& templateName, bool &support)
3617 {
3618     ANS_LOGD("%{public}s", __FUNCTION__);
3619     if (notificationSvrQueue_ == nullptr) {
3620         ANS_LOGE("Serial queue is invalid.");
3621         return ERR_ANS_INVALID_PARAM;
3622     }
3623     ErrCode result = ERR_OK;
3624     ffrt::task_handle handler = notificationSvrQueue_->submit_h(std::bind([&]() {
3625         ANS_LOGD("ffrt enter!");
3626         support = false;
3627         result = NotificationPreferences::GetInstance().GetTemplateSupported(templateName, support);
3628     }));
3629     notificationSvrQueue_->wait(handler);
3630     return result;
3631 }
3632 
GetActiveUserId(int & userId)3633 bool AdvancedNotificationService::GetActiveUserId(int& userId)
3634 {
3635     std::vector<int> activeUserId;
3636     OHOS::AccountSA::OsAccountManager::QueryActiveOsAccountIds(activeUserId);
3637     if (activeUserId.size() > 0) {
3638         userId = activeUserId[0];
3639         ANS_LOGD("Return active userId=%{public}d", userId);
3640         return true;
3641     }
3642     return false;
3643 }
3644 
TriggerRemoveWantAgent(const sptr<NotificationRequest> & request)3645 void AdvancedNotificationService::TriggerRemoveWantAgent(const sptr<NotificationRequest> &request)
3646 {
3647     HITRACE_METER_NAME(HITRACE_TAG_NOTIFICATION, __PRETTY_FUNCTION__);
3648     ANS_LOGD("%{public}s", __FUNCTION__);
3649 
3650     if ((request == nullptr) || (request->GetRemovalWantAgent() == nullptr)) {
3651         return;
3652     }
3653     OHOS::AbilityRuntime::WantAgent::TriggerInfo triggerInfo;
3654     std::shared_ptr<AbilityRuntime::WantAgent::WantAgent> agent = request->GetRemovalWantAgent();
3655     AbilityRuntime::WantAgent::WantAgentHelper::TriggerWantAgent(agent, nullptr, triggerInfo);
3656 }
3657 
IsSpecialUserAllowedNotify(const int32_t & userId,bool & allowed)3658 ErrCode AdvancedNotificationService::IsSpecialUserAllowedNotify(const int32_t &userId, bool &allowed)
3659 {
3660     ANS_LOGD("%{public}s", __FUNCTION__);
3661 
3662     bool isSubsystem = AccessTokenHelper::VerifyNativeToken(IPCSkeleton::GetCallingTokenID());
3663     if (!isSubsystem && !AccessTokenHelper::IsSystemApp()) {
3664         return ERR_ANS_NON_SYSTEM_APP;
3665     }
3666 
3667     if (!CheckPermission(OHOS_PERMISSION_NOTIFICATION_CONTROLLER)) {
3668         return ERR_ANS_PERMISSION_DENIED;
3669     }
3670 
3671     if (notificationSvrQueue_ == nullptr) {
3672         ANS_LOGE("Serial queue is invalid.");
3673         return ERR_ANS_INVALID_PARAM;
3674     }
3675     ErrCode result = ERR_OK;
3676     ffrt::task_handle handler = notificationSvrQueue_->submit_h(std::bind([&]() {
3677         ANS_LOGD("ffrt enter!");
3678         allowed = false;
3679         result = NotificationPreferences::GetInstance().GetNotificationsEnabled(userId, allowed);
3680     }));
3681     notificationSvrQueue_->wait(handler);
3682     return result;
3683 }
3684 
SetNotificationsEnabledByUser(const int32_t & userId,bool enabled)3685 ErrCode AdvancedNotificationService::SetNotificationsEnabledByUser(const int32_t &userId, bool enabled)
3686 {
3687     ANS_LOGD("%{public}s", __FUNCTION__);
3688 
3689     bool isSubsystem = AccessTokenHelper::VerifyNativeToken(IPCSkeleton::GetCallingTokenID());
3690     if (!isSubsystem && !AccessTokenHelper::IsSystemApp()) {
3691         return ERR_ANS_NON_SYSTEM_APP;
3692     }
3693 
3694     if (!CheckPermission(OHOS_PERMISSION_NOTIFICATION_CONTROLLER)) {
3695         return ERR_ANS_PERMISSION_DENIED;
3696     }
3697 
3698     if (notificationSvrQueue_ == nullptr) {
3699         ANS_LOGE("Serial queue is invalid.");
3700         return ERR_ANS_INVALID_PARAM;
3701     }
3702     ErrCode result = ERR_OK;
3703     ffrt::task_handle handler = notificationSvrQueue_->submit_h(std::bind([&]() {
3704         ANS_LOGD("ffrt enter!");
3705         result = NotificationPreferences::GetInstance().SetNotificationsEnabled(userId, enabled);
3706     }));
3707     notificationSvrQueue_->wait(handler);
3708     return result;
3709 }
3710 
DeleteAllByUser(const int32_t & userId)3711 ErrCode AdvancedNotificationService::DeleteAllByUser(const int32_t &userId)
3712 {
3713     ANS_LOGD("%{public}s", __FUNCTION__);
3714 
3715     bool isSubsystem = AccessTokenHelper::VerifyNativeToken(IPCSkeleton::GetCallingTokenID());
3716     if (!isSubsystem && !AccessTokenHelper::IsSystemApp()) {
3717         return ERR_ANS_NON_SYSTEM_APP;
3718     }
3719 
3720     if (userId <= SUBSCRIBE_USER_INIT) {
3721         ANS_LOGE("Input userId is invalid.");
3722         return ERR_ANS_INVALID_PARAM;
3723     }
3724 
3725     if (notificationSvrQueue_ == nullptr) {
3726         ANS_LOGE("Serial queue is invalid.");
3727         return ERR_ANS_INVALID_PARAM;
3728     }
3729     ErrCode result = ERR_OK;
3730     ffrt::task_handle handler = notificationSvrQueue_->submit_h(std::bind([&]() {
3731         ANS_LOGD("ffrt enter!");
3732         std::vector<std::string> keys = GetNotificationKeys(nullptr);
3733         std::vector<sptr<Notification>> notifications;
3734         for (auto key : keys) {
3735 #ifdef DISTRIBUTED_NOTIFICATION_SUPPORTED
3736             std::string deviceId;
3737             std::string bundleName;
3738             GetDistributedInfo(key, deviceId, bundleName);
3739 #endif
3740             sptr<Notification> notification = nullptr;
3741 
3742             result = RemoveFromNotificationListForDeleteAll(key, userId, notification);
3743             if ((result != ERR_OK) || (notification == nullptr)) {
3744                 continue;
3745             }
3746 
3747             if (notification->GetUserId() == userId) {
3748                 int32_t reason = NotificationConstant::CANCEL_ALL_REASON_DELETE;
3749                 UpdateRecentNotification(notification, true, reason);
3750                 notifications.emplace_back(notification);
3751 #ifdef DISTRIBUTED_NOTIFICATION_SUPPORTED
3752                 DoDistributedDelete(deviceId, bundleName, notification);
3753 #endif
3754             }
3755             if (notifications.size() >= MAX_CANCELED_PARCELABLE_VECTOR_NUM) {
3756                 SendNotificationsOnCanceled(notifications, nullptr, NotificationConstant::CANCEL_ALL_REASON_DELETE);
3757             }
3758         }
3759 
3760         if (!notifications.empty()) {
3761             NotificationSubscriberManager::GetInstance()->BatchNotifyCanceled(
3762                 notifications, nullptr, NotificationConstant::CANCEL_ALL_REASON_DELETE);
3763         }
3764 
3765         result = ERR_OK;
3766     }));
3767     notificationSvrQueue_->wait(handler);
3768 
3769     return result;
3770 }
3771 
SetDoNotDisturbDate(const int32_t & userId,const sptr<NotificationDoNotDisturbDate> & date)3772 ErrCode AdvancedNotificationService::SetDoNotDisturbDate(const int32_t &userId,
3773     const sptr<NotificationDoNotDisturbDate> &date)
3774 {
3775     ANS_LOGD("%{public}s", __FUNCTION__);
3776 
3777     if (userId <= SUBSCRIBE_USER_INIT) {
3778         ANS_LOGE("Input userId is invalid.");
3779         return ERR_ANS_INVALID_PARAM;
3780     }
3781 
3782     bool isSubsystem = AccessTokenHelper::VerifyNativeToken(IPCSkeleton::GetCallingTokenID());
3783     if (!isSubsystem && !AccessTokenHelper::IsSystemApp()) {
3784         return ERR_ANS_NON_SYSTEM_APP;
3785     }
3786 
3787     if (!CheckPermission(OHOS_PERMISSION_NOTIFICATION_CONTROLLER)) {
3788         return ERR_ANS_PERMISSION_DENIED;
3789     }
3790 
3791     return SetDoNotDisturbDateByUser(userId, date);
3792 }
3793 
GetDoNotDisturbDate(const int32_t & userId,sptr<NotificationDoNotDisturbDate> & date)3794 ErrCode AdvancedNotificationService::GetDoNotDisturbDate(const int32_t &userId,
3795     sptr<NotificationDoNotDisturbDate> &date)
3796 {
3797     ANS_LOGD("%{public}s", __FUNCTION__);
3798 
3799     if (userId <= SUBSCRIBE_USER_INIT) {
3800         ANS_LOGE("Input userId is invalid.");
3801         return ERR_ANS_INVALID_PARAM;
3802     }
3803 
3804     bool isSubsystem = AccessTokenHelper::VerifyNativeToken(IPCSkeleton::GetCallingTokenID());
3805     if (!isSubsystem && !AccessTokenHelper::IsSystemApp()) {
3806         return ERR_ANS_NON_SYSTEM_APP;
3807     }
3808 
3809     if (!CheckPermission(OHOS_PERMISSION_NOTIFICATION_CONTROLLER)) {
3810         return ERR_ANS_PERMISSION_DENIED;
3811     }
3812 
3813     return GetDoNotDisturbDateByUser(userId, date);
3814 }
3815 
SetDoNotDisturbDateByUser(const int32_t & userId,const sptr<NotificationDoNotDisturbDate> & date)3816 ErrCode AdvancedNotificationService::SetDoNotDisturbDateByUser(const int32_t &userId,
3817     const sptr<NotificationDoNotDisturbDate> &date)
3818 {
3819     ANS_LOGD("%{public}s enter, userId = %{public}d", __FUNCTION__, userId);
3820     if (date == nullptr) {
3821         ANS_LOGE("Invalid date param");
3822         return ERR_ANS_INVALID_PARAM;
3823     }
3824 
3825     ErrCode result = ERR_OK;
3826 
3827     int64_t beginDate = ResetSeconds(date->GetBeginDate());
3828     int64_t endDate = ResetSeconds(date->GetEndDate());
3829     switch (date->GetDoNotDisturbType()) {
3830         case NotificationConstant::DoNotDisturbType::NONE:
3831             beginDate = 0;
3832             endDate = 0;
3833             break;
3834         case NotificationConstant::DoNotDisturbType::ONCE:
3835             AdjustDateForDndTypeOnce(beginDate, endDate);
3836             break;
3837         case NotificationConstant::DoNotDisturbType::CLEARLY:
3838             if (beginDate >= endDate) {
3839                 return ERR_ANS_INVALID_PARAM;
3840             }
3841             break;
3842         default:
3843             break;
3844     }
3845     ANS_LOGD("Before set SetDoNotDisturbDate beginDate = %{public}" PRId64 ", endDate = %{public}" PRId64,
3846              beginDate, endDate);
3847     const sptr<NotificationDoNotDisturbDate> newConfig = new NotificationDoNotDisturbDate(
3848         date->GetDoNotDisturbType(),
3849         beginDate,
3850         endDate
3851     );
3852 
3853     sptr<NotificationBundleOption> bundleOption = GenerateBundleOption();
3854     if (bundleOption == nullptr) {
3855         ANS_LOGE("Generate invalid bundle option!");
3856         return ERR_ANS_INVALID_BUNDLE;
3857     }
3858 
3859     if (notificationSvrQueue_ == nullptr) {
3860         ANS_LOGE("Serial queue is invalid.");
3861         return ERR_ANS_INVALID_PARAM;
3862     }
3863     ffrt::task_handle handler = notificationSvrQueue_->submit_h(std::bind([&]() {
3864         ANS_LOGD("ffrt enter!");
3865         result = NotificationPreferences::GetInstance().SetDoNotDisturbDate(userId, newConfig);
3866         if (result == ERR_OK) {
3867             NotificationSubscriberManager::GetInstance()->NotifyDoNotDisturbDateChanged(newConfig);
3868         }
3869     }));
3870     notificationSvrQueue_->wait(handler);
3871 
3872     return ERR_OK;
3873 }
3874 
GetDoNotDisturbDateByUser(const int32_t & userId,sptr<NotificationDoNotDisturbDate> & date)3875 ErrCode AdvancedNotificationService::GetDoNotDisturbDateByUser(const int32_t &userId,
3876     sptr<NotificationDoNotDisturbDate> &date)
3877 {
3878     ErrCode result = ERR_OK;
3879     if (notificationSvrQueue_ == nullptr) {
3880         ANS_LOGE("Serial queue is invalid.");
3881         return ERR_ANS_INVALID_PARAM;
3882     }
3883     ffrt::task_handle handler = notificationSvrQueue_->submit_h(std::bind([&]() {
3884         ANS_LOGD("ffrt enter!");
3885         sptr<NotificationDoNotDisturbDate> currentConfig = nullptr;
3886         result = NotificationPreferences::GetInstance().GetDoNotDisturbDate(userId, currentConfig);
3887         if (result == ERR_OK) {
3888             int64_t now = GetCurrentTime();
3889             switch (currentConfig->GetDoNotDisturbType()) {
3890                 case NotificationConstant::DoNotDisturbType::CLEARLY:
3891                 case NotificationConstant::DoNotDisturbType::ONCE:
3892                     if (now >= currentConfig->GetEndDate()) {
3893                         date = new NotificationDoNotDisturbDate(NotificationConstant::DoNotDisturbType::NONE, 0, 0);
3894                         NotificationPreferences::GetInstance().SetDoNotDisturbDate(userId, date);
3895                     } else {
3896                         date = currentConfig;
3897                     }
3898                     break;
3899                 default:
3900                     date = currentConfig;
3901                     break;
3902             }
3903         }
3904     }));
3905     notificationSvrQueue_->wait(handler);
3906 
3907     return ERR_OK;
3908 }
3909 
SetHasPoppedDialog(const sptr<NotificationBundleOption> bundleOption,bool hasPopped)3910 ErrCode AdvancedNotificationService::SetHasPoppedDialog(
3911     const sptr<NotificationBundleOption> bundleOption, bool hasPopped)
3912 {
3913     ANS_LOGD("%{public}s", __FUNCTION__);
3914     if (notificationSvrQueue_ == nullptr) {
3915         ANS_LOGE("Serial queue is invalid.");
3916         return ERR_ANS_INVALID_PARAM;
3917     }
3918     ErrCode result = ERR_OK;
3919     ANS_LOGE("ffrt start!");
3920     ffrt::task_handle handler = notificationSvrQueue_->submit_h(std::bind([&]() {
3921         ANS_LOGE("ffrt enter!");
3922         result = NotificationPreferences::GetInstance().SetHasPoppedDialog(bundleOption, hasPopped);
3923     }));
3924     notificationSvrQueue_->wait(handler);
3925     ANS_LOGE("ffrt end!");
3926     return result;
3927 }
3928 
GetHasPoppedDialog(const sptr<NotificationBundleOption> bundleOption,bool & hasPopped)3929 ErrCode AdvancedNotificationService::GetHasPoppedDialog(
3930     const sptr<NotificationBundleOption> bundleOption, bool &hasPopped)
3931 {
3932     ANS_LOGD("%{public}s", __FUNCTION__);
3933     if (notificationSvrQueue_ == nullptr) {
3934         ANS_LOGE("Serial queue is invalid.");
3935         return ERR_ANS_INVALID_PARAM;
3936     }
3937     ErrCode result = ERR_OK;
3938     ffrt::task_handle handler = notificationSvrQueue_->submit_h(std::bind([&]() {
3939         result = NotificationPreferences::GetInstance().GetHasPoppedDialog(bundleOption, hasPopped);
3940     }));
3941     notificationSvrQueue_->wait(handler);
3942     return result;
3943 }
3944 
CheckApiCompatibility(const sptr<NotificationBundleOption> & bundleOption)3945 bool AdvancedNotificationService::CheckApiCompatibility(const sptr<NotificationBundleOption> &bundleOption)
3946 {
3947     ANS_LOGD("%{public}s", __FUNCTION__);
3948     std::shared_ptr<BundleManagerHelper> bundleManager = BundleManagerHelper::GetInstance();
3949     if (bundleManager == nullptr) {
3950         return false;
3951     }
3952     return bundleManager->CheckApiCompatibility(bundleOption);
3953 }
3954 
OnResourceRemove(int32_t userId)3955 void AdvancedNotificationService::OnResourceRemove(int32_t userId)
3956 {
3957     DeleteAllByUser(userId);
3958 
3959     if (notificationSvrQueue_ == nullptr) {
3960         ANS_LOGE("Serial queue is invalid.");
3961         return;
3962     }
3963     ffrt::task_handle handler = notificationSvrQueue_->submit_h(std::bind([&]() {
3964         ANS_LOGD("ffrt enter!");
3965         NotificationPreferences::GetInstance().RemoveSettings(userId);
3966     }));
3967     notificationSvrQueue_->wait(handler);
3968 }
3969 
OnBundleDataCleared(const sptr<NotificationBundleOption> & bundleOption)3970 void AdvancedNotificationService::OnBundleDataCleared(const sptr<NotificationBundleOption> &bundleOption)
3971 {
3972     if (notificationSvrQueue_ == nullptr) {
3973         ANS_LOGE("Serial queue is invalid.");
3974         return;
3975     }
3976     ffrt::task_handle handler = notificationSvrQueue_->submit_h(std::bind([&]() {
3977         ANS_LOGD("ffrt enter!");
3978         std::vector<std::string> keys = GetNotificationKeys(bundleOption);
3979         std::vector<sptr<Notification>> notifications;
3980         for (auto key : keys) {
3981 #ifdef DISTRIBUTED_NOTIFICATION_SUPPORTED
3982             std::string deviceId;
3983             std::string bundleName;
3984             GetDistributedInfo(key, deviceId, bundleName);
3985 #endif
3986             sptr<Notification> notification = nullptr;
3987 
3988             ErrCode result = RemoveFromNotificationList(key, notification, true,
3989                 NotificationConstant::PACKAGE_CHANGED_REASON_DELETE);
3990             if (result != ERR_OK) {
3991                 continue;
3992             }
3993 
3994             if (notification != nullptr) {
3995                 int32_t reason = NotificationConstant::PACKAGE_CHANGED_REASON_DELETE;
3996                 UpdateRecentNotification(notification, true, reason);
3997                 notifications.emplace_back(notification);
3998 #ifdef DISTRIBUTED_NOTIFICATION_SUPPORTED
3999                 DoDistributedDelete(deviceId, bundleName, notification);
4000 #endif
4001             }
4002             if (notifications.size() >= MAX_CANCELED_PARCELABLE_VECTOR_NUM) {
4003                 std::vector<sptr<Notification>> currNotificationList = notifications;
4004                 NotificationSubscriberManager::GetInstance()->BatchNotifyCanceled(
4005                     currNotificationList, nullptr, NotificationConstant::PACKAGE_CHANGED_REASON_DELETE);
4006                 notifications.clear();
4007             }
4008         }
4009 
4010         if (!notifications.empty()) {
4011             NotificationSubscriberManager::GetInstance()->BatchNotifyCanceled(
4012                 notifications, nullptr, NotificationConstant::PACKAGE_CHANGED_REASON_DELETE);
4013         }
4014     }));
4015     notificationSvrQueue_->wait(handler);
4016 }
4017 
SetEnabledForBundleSlot(const sptr<NotificationBundleOption> & bundleOption,const NotificationConstant::SlotType & slotType,bool enabled)4018 ErrCode AdvancedNotificationService::SetEnabledForBundleSlot(
4019     const sptr<NotificationBundleOption> &bundleOption, const NotificationConstant::SlotType &slotType, bool enabled)
4020 {
4021     HITRACE_METER_NAME(HITRACE_TAG_NOTIFICATION, __PRETTY_FUNCTION__);
4022     ANS_LOGD("slotType: %{public}d, enabled: %{public}d", slotType, enabled);
4023 
4024     bool isSubsystem = AccessTokenHelper::VerifyNativeToken(IPCSkeleton::GetCallingTokenID());
4025     if (!isSubsystem && !AccessTokenHelper::IsSystemApp()) {
4026         return ERR_ANS_NON_SYSTEM_APP;
4027     }
4028 
4029     if (!CheckPermission(OHOS_PERMISSION_NOTIFICATION_CONTROLLER)) {
4030         return ERR_ANS_PERMISSION_DENIED;
4031     }
4032 
4033     sptr<NotificationBundleOption> bundle = GenerateValidBundleOption(bundleOption);
4034     if (bundle == nullptr) {
4035         return ERR_ANS_INVALID_BUNDLE;
4036     }
4037 
4038     if (notificationSvrQueue_ == nullptr) {
4039         ANS_LOGE("Serial queue is invalid.");
4040         return ERR_ANS_INVALID_PARAM;
4041     }
4042     ErrCode result = ERR_OK;
4043     ffrt::task_handle handler = notificationSvrQueue_->submit_h(std::bind([&]() {
4044         sptr<NotificationSlot> slot;
4045         result = NotificationPreferences::GetInstance().GetNotificationSlot(bundle, slotType, slot);
4046         if (result == ERR_ANS_PREFERENCES_NOTIFICATION_SLOT_TYPE_NOT_EXIST ||
4047             result == ERR_ANS_PREFERENCES_NOTIFICATION_BUNDLE_NOT_EXIST) {
4048             slot = new (std::nothrow) NotificationSlot(slotType);
4049             if (slot == nullptr) {
4050                 ANS_LOGE("Failed to create NotificationSlot ptr.");
4051                 result = ERR_ANS_NO_MEMORY;
4052                 return;
4053             }
4054         } else if ((result == ERR_OK) && (slot != nullptr)) {
4055             if (slot->GetEnable() == enabled) {
4056                 return;
4057             }
4058             NotificationPreferences::GetInstance().RemoveNotificationSlot(bundle, slotType);
4059         } else {
4060             ANS_LOGE("Set enable slot: GetNotificationSlot failed");
4061             return;
4062         }
4063 
4064         slot->SetEnable(enabled);
4065         std::vector<sptr<NotificationSlot>> slots;
4066         slots.push_back(slot);
4067         result = NotificationPreferences::GetInstance().AddNotificationSlots(bundle, slots);
4068         if (result != ERR_OK) {
4069             ANS_LOGE("Set enable slot: AddNotificationSlot failed");
4070             return;
4071         }
4072 
4073         PublishSlotChangeCommonEvent(bundle);
4074     }));
4075     notificationSvrQueue_->wait(handler);
4076 
4077     SendEnableNotificationSlotHiSysEvent(bundleOption, slotType, enabled, result);
4078     return result;
4079 }
4080 
GetEnabledForBundleSlot(const sptr<NotificationBundleOption> & bundleOption,const NotificationConstant::SlotType & slotType,bool & enabled)4081 ErrCode AdvancedNotificationService::GetEnabledForBundleSlot(
4082     const sptr<NotificationBundleOption> &bundleOption, const NotificationConstant::SlotType &slotType, bool &enabled)
4083 {
4084     ANS_LOGD("slotType: %{public}d", slotType);
4085 
4086     bool isSubsystem = AccessTokenHelper::VerifyNativeToken(IPCSkeleton::GetCallingTokenID());
4087     if (!isSubsystem && !AccessTokenHelper::IsSystemApp()) {
4088         return ERR_ANS_NON_SYSTEM_APP;
4089     }
4090 
4091     if (!CheckPermission(OHOS_PERMISSION_NOTIFICATION_CONTROLLER)) {
4092         return ERR_ANS_PERMISSION_DENIED;
4093     }
4094 
4095     sptr<NotificationBundleOption> bundle = GenerateValidBundleOption(bundleOption);
4096     if (bundle == nullptr) {
4097         return ERR_ANS_INVALID_BUNDLE;
4098     }
4099 
4100     if (notificationSvrQueue_ == nullptr) {
4101         ANS_LOGE("Serial queue is invalid.");
4102         return ERR_ANS_INVALID_PARAM;
4103     }
4104     ErrCode result = ERR_OK;
4105     ffrt::task_handle handler = notificationSvrQueue_->submit_h(std::bind([&]() {
4106         ANS_LOGD("ffrt enter!");
4107         sptr<NotificationSlot> slot;
4108         result = NotificationPreferences::GetInstance().GetNotificationSlot(bundle, slotType, slot);
4109         if (result != ERR_OK) {
4110             ANS_LOGE("Get enable slot: GetNotificationSlot failed");
4111             return;
4112         }
4113         if (slot == nullptr) {
4114             ANS_LOGW("Get enable slot: object is null, enabled default true");
4115             enabled = true;
4116             result = ERR_OK;
4117             return;
4118         }
4119         enabled = slot->GetEnable();
4120     }));
4121     notificationSvrQueue_->wait(handler);
4122 
4123     return result;
4124 }
4125 
PublishSlotChangeCommonEvent(const sptr<NotificationBundleOption> & bundleOption)4126 bool AdvancedNotificationService::PublishSlotChangeCommonEvent(const sptr<NotificationBundleOption> &bundleOption)
4127 {
4128     HITRACE_METER_NAME(HITRACE_TAG_NOTIFICATION, __PRETTY_FUNCTION__);
4129     ANS_LOGD("bundle [%{public}s : %{public}d]", bundleOption->GetBundleName().c_str(), bundleOption->GetUid());
4130 
4131     EventFwk::Want want;
4132     AppExecFwk::ElementName element;
4133     element.SetBundleName(bundleOption->GetBundleName());
4134     want.SetElement(element);
4135     want.SetParam(AppExecFwk::Constants::UID, bundleOption->GetUid());
4136     want.SetAction(EventFwk::CommonEventSupport::COMMON_EVENT_SLOT_CHANGE);
4137     EventFwk::CommonEventData commonData {want};
4138     if (!EventFwk::CommonEventManager::PublishCommonEvent(commonData)) {
4139         ANS_LOGE("PublishCommonEvent failed");
4140         return false;
4141     }
4142 
4143     return true;
4144 }
4145 
ShellDump(const std::string & cmd,const std::string & bundle,int32_t userId,std::vector<std::string> & dumpInfo)4146 ErrCode AdvancedNotificationService::ShellDump(const std::string &cmd, const std::string &bundle, int32_t userId,
4147     std::vector<std::string> &dumpInfo)
4148 {
4149     ANS_LOGD("%{public}s", __FUNCTION__);
4150 
4151     auto callerToken = IPCSkeleton::GetCallingTokenID();
4152     if (!AccessTokenHelper::VerifyShellToken(callerToken) && !AccessTokenHelper::VerifyNativeToken(callerToken)) {
4153         ANS_LOGE("Not subsystem or shell request");
4154         return ERR_ANS_PERMISSION_DENIED;
4155     }
4156 
4157     if (notificationSvrQueue_ == nullptr) {
4158         ANS_LOGE("Serial queue is invalid.");
4159         return ERR_ANS_INVALID_PARAM;
4160     }
4161     ErrCode result = ERR_ANS_NOT_ALLOWED;
4162     ffrt::task_handle handler = notificationSvrQueue_->submit_h(std::bind([&]() {
4163         ANS_LOGD("ffrt enter!");
4164         if (cmd == ACTIVE_NOTIFICATION_OPTION) {
4165             result = ActiveNotificationDump(bundle, userId, dumpInfo);
4166         } else if (cmd == RECENT_NOTIFICATION_OPTION) {
4167             result = RecentNotificationDump(bundle, userId, dumpInfo);
4168 #ifdef DISTRIBUTED_NOTIFICATION_SUPPORTED
4169         } else if (cmd == DISTRIBUTED_NOTIFICATION_OPTION) {
4170             result = DistributedNotificationDump(bundle, userId, dumpInfo);
4171 #endif
4172         } else if (cmd.substr(0, cmd.find_first_of(" ", 0)) == SET_RECENT_COUNT_OPTION) {
4173             result = SetRecentNotificationCount(cmd.substr(cmd.find_first_of(" ", 0) + 1));
4174         } else {
4175             result = ERR_ANS_INVALID_PARAM;
4176         }
4177     }));
4178     notificationSvrQueue_->wait(handler);
4179     return result;
4180 }
4181 
Dump(int fd,const std::vector<std::u16string> & args)4182 int AdvancedNotificationService::Dump(int fd, const std::vector<std::u16string> &args)
4183 {
4184     ANS_LOGD("enter");
4185     std::string result;
4186     GetDumpInfo(args, result);
4187     int ret = dprintf(fd, "%s\n", result.c_str());
4188     if (ret < 0) {
4189         ANS_LOGE("dprintf error");
4190         return ERR_ANS_INVALID_PARAM;
4191     }
4192     return ERR_OK;
4193 }
4194 
GetDumpInfo(const std::vector<std::u16string> & args,std::string & result)4195 void AdvancedNotificationService::GetDumpInfo(const std::vector<std::u16string> &args, std::string &result)
4196 {
4197     if (args.size() != 1) {
4198         result = HIDUMPER_ERR_MSG;
4199         return;
4200     }
4201     std::vector<std::string> dumpInfo;
4202     std::string cmd = Str16ToStr8(args.front());
4203     if (HIDUMPER_CMD_MAP.find(cmd) == HIDUMPER_CMD_MAP.end()) {
4204         result = HIDUMPER_ERR_MSG;
4205         return;
4206     }
4207     std::string cmdValue = HIDUMPER_CMD_MAP.find(cmd)->second;
4208     if (cmdValue == HELP_NOTIFICATION_OPTION) {
4209         result = HIDUMPER_HELP_MSG;
4210     }
4211     ShellDump(cmdValue, "", SUBSCRIBE_USER_INIT, dumpInfo);
4212     if (dumpInfo.empty()) {
4213         result.append("no notification\n");
4214         return;
4215     }
4216     int32_t index = 0;
4217     result.append("notification list:\n");
4218     for (const auto &info: dumpInfo) {
4219         result.append("No." + std::to_string(++index) + "\n");
4220         result.append(info);
4221     }
4222 }
4223 
SendSubscribeHiSysEvent(int32_t pid,int32_t uid,const sptr<NotificationSubscribeInfo> & info,ErrCode errCode)4224 void AdvancedNotificationService::SendSubscribeHiSysEvent(int32_t pid, int32_t uid,
4225     const sptr<NotificationSubscribeInfo> &info, ErrCode errCode)
4226 {
4227     EventInfo eventInfo;
4228     eventInfo.pid = pid;
4229     eventInfo.uid = uid;
4230     if (info != nullptr) {
4231         eventInfo.userId = info->GetAppUserId();
4232         std::vector<std::string> appNames = info->GetAppNames();
4233         eventInfo.bundleName = std::accumulate(appNames.begin(), appNames.end(), std::string(""),
4234             [appNames](const std::string &bundleName, const std::string &str) {
4235                 return (str == appNames.front()) ? (bundleName + str) : (bundleName + "," + str);
4236             });
4237     }
4238 
4239     if (errCode != ERR_OK) {
4240         eventInfo.errCode = errCode;
4241         EventReport::SendHiSysEvent(SUBSCRIBE_ERROR, eventInfo);
4242     } else {
4243         EventReport::SendHiSysEvent(SUBSCRIBE, eventInfo);
4244     }
4245 }
4246 
SendUnSubscribeHiSysEvent(int32_t pid,int32_t uid,const sptr<NotificationSubscribeInfo> & info)4247 void AdvancedNotificationService::SendUnSubscribeHiSysEvent(int32_t pid, int32_t uid,
4248     const sptr<NotificationSubscribeInfo> &info)
4249 {
4250     EventInfo eventInfo;
4251     eventInfo.pid = pid;
4252     eventInfo.uid = uid;
4253     if (info != nullptr) {
4254         eventInfo.userId = info->GetAppUserId();
4255         std::vector<std::string> appNames = info->GetAppNames();
4256         eventInfo.bundleName = std::accumulate(appNames.begin(), appNames.end(), std::string(""),
4257             [appNames](const std::string &bundleName, const std::string &str) {
4258                 return (str == appNames.front()) ? (bundleName + str) : (bundleName + "," + str);
4259             });
4260     }
4261 
4262     EventReport::SendHiSysEvent(UNSUBSCRIBE, eventInfo);
4263 }
4264 
SendPublishHiSysEvent(const sptr<NotificationRequest> & request,ErrCode errCode)4265 void AdvancedNotificationService::SendPublishHiSysEvent(const sptr<NotificationRequest> &request, ErrCode errCode)
4266 {
4267     if (request == nullptr) {
4268         return;
4269     }
4270 
4271     EventInfo eventInfo;
4272     eventInfo.notificationId = request->GetNotificationId();
4273     eventInfo.contentType = static_cast<int32_t>(request->GetNotificationType());
4274     eventInfo.bundleName = request->GetCreatorBundleName();
4275     eventInfo.userId = request->GetCreatorUserId();
4276     if (errCode != ERR_OK) {
4277         eventInfo.errCode = errCode;
4278         EventReport::SendHiSysEvent(PUBLISH_ERROR, eventInfo);
4279     } else {
4280         EventReport::SendHiSysEvent(PUBLISH, eventInfo);
4281     }
4282 }
4283 
SendCancelHiSysEvent(int32_t notificationId,const std::string & label,const sptr<NotificationBundleOption> & bundleOption,ErrCode errCode)4284 void AdvancedNotificationService::SendCancelHiSysEvent(int32_t notificationId, const std::string &label,
4285     const sptr<NotificationBundleOption> &bundleOption, ErrCode errCode)
4286 {
4287     if (bundleOption == nullptr || errCode != ERR_OK) {
4288         return;
4289     }
4290 
4291     EventInfo eventInfo;
4292     eventInfo.notificationId = notificationId;
4293     eventInfo.notificationLabel = label;
4294     eventInfo.bundleName = bundleOption->GetBundleName();
4295     eventInfo.uid = bundleOption->GetUid();
4296     EventReport::SendHiSysEvent(CANCEL, eventInfo);
4297 }
4298 
SendRemoveHiSysEvent(int32_t notificationId,const std::string & label,const sptr<NotificationBundleOption> & bundleOption,ErrCode errCode)4299 void AdvancedNotificationService::SendRemoveHiSysEvent(int32_t notificationId, const std::string &label,
4300     const sptr<NotificationBundleOption> &bundleOption, ErrCode errCode)
4301 {
4302     if (bundleOption == nullptr || errCode != ERR_OK) {
4303         return;
4304     }
4305 
4306     EventInfo eventInfo;
4307     eventInfo.notificationId = notificationId;
4308     eventInfo.notificationLabel = label;
4309     eventInfo.bundleName = bundleOption->GetBundleName();
4310     eventInfo.uid = bundleOption->GetUid();
4311     EventReport::SendHiSysEvent(REMOVE, eventInfo);
4312 }
4313 
SendEnableNotificationHiSysEvent(const sptr<NotificationBundleOption> & bundleOption,bool enabled,ErrCode errCode)4314 void AdvancedNotificationService::SendEnableNotificationHiSysEvent(const sptr<NotificationBundleOption> &bundleOption,
4315     bool enabled, ErrCode errCode)
4316 {
4317     if (bundleOption == nullptr) {
4318         return;
4319     }
4320 
4321     EventInfo eventInfo;
4322     eventInfo.bundleName = bundleOption->GetBundleName();
4323     eventInfo.uid = bundleOption->GetUid();
4324     eventInfo.enable = enabled;
4325     if (errCode != ERR_OK) {
4326         eventInfo.errCode = errCode;
4327         EventReport::SendHiSysEvent(ENABLE_NOTIFICATION_ERROR, eventInfo);
4328     } else {
4329         EventReport::SendHiSysEvent(ENABLE_NOTIFICATION, eventInfo);
4330     }
4331 }
4332 
SendEnableNotificationSlotHiSysEvent(const sptr<NotificationBundleOption> & bundleOption,const NotificationConstant::SlotType & slotType,bool enabled,ErrCode errCode)4333 void AdvancedNotificationService::SendEnableNotificationSlotHiSysEvent(
4334     const sptr<NotificationBundleOption> &bundleOption, const NotificationConstant::SlotType &slotType,
4335     bool enabled, ErrCode errCode)
4336 {
4337     if (bundleOption == nullptr) {
4338         return;
4339     }
4340 
4341     EventInfo eventInfo;
4342     eventInfo.bundleName = bundleOption->GetBundleName();
4343     eventInfo.uid = bundleOption->GetUid();
4344     eventInfo.slotType = slotType;
4345     eventInfo.enable = enabled;
4346     if (errCode != ERR_OK) {
4347         eventInfo.errCode = errCode;
4348         EventReport::SendHiSysEvent(ENABLE_NOTIFICATION_SLOT_ERROR, eventInfo);
4349     } else {
4350         EventReport::SendHiSysEvent(ENABLE_NOTIFICATION_SLOT, eventInfo);
4351     }
4352 }
4353 
SendFlowControlOccurHiSysEvent(const std::shared_ptr<NotificationRecord> & record)4354 void AdvancedNotificationService::SendFlowControlOccurHiSysEvent(const std::shared_ptr<NotificationRecord> &record)
4355 {
4356     if (record == nullptr || record->request == nullptr || record->bundleOption == nullptr) {
4357         return;
4358     }
4359 
4360     EventInfo eventInfo;
4361     eventInfo.notificationId = record->request->GetNotificationId();
4362     eventInfo.bundleName = record->bundleOption->GetBundleName();
4363     eventInfo.uid = record->bundleOption->GetUid();
4364     EventReport::SendHiSysEvent(FLOW_CONTROL_OCCUR, eventInfo);
4365 }
4366 
SetSyncNotificationEnabledWithoutApp(const int32_t userId,const bool enabled)4367 ErrCode AdvancedNotificationService::SetSyncNotificationEnabledWithoutApp(const int32_t userId, const bool enabled)
4368 {
4369     ANS_LOGD("userId: %{public}d, enabled: %{public}d", userId, enabled);
4370 
4371 #ifdef DISTRIBUTED_NOTIFICATION_SUPPORTED
4372     bool isSubsystem = AccessTokenHelper::VerifyNativeToken(IPCSkeleton::GetCallingTokenID());
4373     if (!isSubsystem && !AccessTokenHelper::IsSystemApp()) {
4374         return ERR_ANS_NON_SYSTEM_APP;
4375     }
4376 
4377     if (!CheckPermission(OHOS_PERMISSION_NOTIFICATION_CONTROLLER)) {
4378         return ERR_ANS_PERMISSION_DENIED;
4379     }
4380 
4381     if (notificationSvrQueue_ == nullptr) {
4382         ANS_LOGE("Serial queue is invalid.");
4383         return ERR_ANS_INVALID_PARAM;
4384     }
4385     ErrCode result = ERR_OK;
4386     ffrt::task_handle handler = notificationSvrQueue_->submit_h(
4387         std::bind([&]() {
4388             ANS_LOGD("ffrt enter!");
4389             result = DistributedPreferences::GetInstance()->SetSyncEnabledWithoutApp(userId, enabled);
4390         }));
4391     notificationSvrQueue_->wait(handler);
4392     return result;
4393 #else
4394     return ERR_INVALID_OPERATION;
4395 #endif
4396 }
4397 
GetSyncNotificationEnabledWithoutApp(const int32_t userId,bool & enabled)4398 ErrCode AdvancedNotificationService::GetSyncNotificationEnabledWithoutApp(const int32_t userId, bool &enabled)
4399 {
4400     ANS_LOGD("userId: %{public}d", userId);
4401 
4402 #ifdef DISTRIBUTED_NOTIFICATION_SUPPORTED
4403     bool isSubsystem = AccessTokenHelper::VerifyNativeToken(IPCSkeleton::GetCallingTokenID());
4404     if (!isSubsystem && !AccessTokenHelper::IsSystemApp()) {
4405         return ERR_ANS_NON_SYSTEM_APP;
4406     }
4407 
4408     if (!CheckPermission(OHOS_PERMISSION_NOTIFICATION_CONTROLLER)) {
4409         return ERR_ANS_PERMISSION_DENIED;
4410     }
4411 
4412     if (notificationSvrQueue_ == nullptr) {
4413         ANS_LOGE("Serial queue is invalid.");
4414         return ERR_ANS_INVALID_PARAM;
4415     }
4416     ErrCode result = ERR_OK;
4417     ffrt::task_handle handler = notificationSvrQueue_->submit_h(
4418         std::bind([&]() {
4419             ANS_LOGD("ffrt enter!");
4420             result = DistributedPreferences::GetInstance()->GetSyncEnabledWithoutApp(userId, enabled);
4421         }));
4422     notificationSvrQueue_->wait(handler);
4423     return result;
4424 #else
4425     return ERR_INVALID_OPERATION;
4426 #endif
4427 }
4428 
PublishNotificationBySa(const sptr<NotificationRequest> & request)4429 ErrCode AdvancedNotificationService::PublishNotificationBySa(const sptr<NotificationRequest> &request)
4430 {
4431     ANS_LOGD("%{public}s", __FUNCTION__);
4432 
4433     int32_t uid = request->GetCreatorUid();
4434     if (uid <= 0) {
4435         ANS_LOGE("CreatorUid[%{public}d] error", uid);
4436         return ERR_ANS_INVALID_UID;
4437     }
4438 
4439     std::shared_ptr<BundleManagerHelper> bundleManager = BundleManagerHelper::GetInstance();
4440     if (bundleManager == nullptr) {
4441         ANS_LOGE("failed to get bundleManager!");
4442         return ERR_ANS_INVALID_BUNDLE;
4443     }
4444     std::string bundle = bundleManager->GetBundleNameByUid(uid);
4445     if (request->GetCreatorBundleName().empty()) {
4446         request->SetCreatorBundleName(bundle);
4447     }
4448     if (request->GetOwnerBundleName().empty()) {
4449         request->SetOwnerBundleName(bundle);
4450     }
4451 
4452     request->SetCreatorPid(IPCSkeleton::GetCallingPid());
4453     int32_t userId = SUBSCRIBE_USER_INIT;
4454     OHOS::AccountSA::OsAccountManager::GetOsAccountLocalIdFromUid(IPCSkeleton::GetCallingUid(), userId);
4455     request->SetCreatorUserId(userId);
4456     if (request->GetDeliveryTime() <= 0) {
4457         request->SetDeliveryTime(GetCurrentTime());
4458     }
4459     ANS_LOGD("creator uid=%{public}d, userId=%{public}d, bundleName=%{public}s ", uid, userId, bundle.c_str());
4460 
4461     ErrCode result = CheckPictureSize(request);
4462     if (result != ERR_OK) {
4463         ANS_LOGE("Failed to check picture size");
4464         return result;
4465     }
4466 
4467     sptr<NotificationBundleOption> bundleOption = new NotificationBundleOption(bundle, uid);
4468     if (bundleOption == nullptr) {
4469         ANS_LOGE("Failed to create bundleOption");
4470         return ERR_ANS_NO_MEMORY;
4471     }
4472 
4473     std::shared_ptr<NotificationRecord> record = std::make_shared<NotificationRecord>();
4474     record->request = request;
4475     record->bundleOption = bundleOption;
4476     record->notification = new (std::nothrow) Notification(request);
4477 
4478     if (record->notification == nullptr) {
4479         ANS_LOGE("Failed to create notification");
4480         return ERR_ANS_NO_MEMORY;
4481     }
4482 
4483     if (notificationSvrQueue_ == nullptr) {
4484         ANS_LOGE("Serial queue is invalid.");
4485         return ERR_ANS_INVALID_PARAM;
4486     }
4487     ffrt::task_handle handler = notificationSvrQueue_->submit_h([this, &record]() {
4488         if (AssignToNotificationList(record) != ERR_OK) {
4489             ANS_LOGE("Failed to assign notification list");
4490             return;
4491         }
4492 
4493         UpdateRecentNotification(record->notification, false, 0);
4494         sptr<NotificationSortingMap> sortingMap = GenerateSortingMap();
4495         NotificationSubscriberManager::GetInstance()->NotifyConsumed(record->notification, sortingMap);
4496     });
4497     notificationSvrQueue_->wait(handler);
4498 
4499     return result;
4500 }
SetBadgeNumber(int32_t badgeNumber)4501 ErrCode AdvancedNotificationService::SetBadgeNumber(int32_t badgeNumber)
4502 {
4503     ANS_LOGD("%{public}s", __FUNCTION__);
4504     if (notificationSvrQueue_ == nullptr) {
4505         ANS_LOGE("Serial queue is invalid.");
4506         return ERR_ANS_INVALID_PARAM;
4507     }
4508     int32_t callingUid = IPCSkeleton::GetCallingUid();
4509     std::string bundleName = GetClientBundleName();
4510     sptr<BadgeNumberCallbackData> badgeData = new (std::nothrow) BadgeNumberCallbackData(
4511         bundleName, callingUid, badgeNumber);
4512     if (badgeData == nullptr) {
4513         ANS_LOGE("Failed to create BadgeNumberCallbackData.");
4514         return ERR_ANS_NO_MEMORY;
4515     }
4516 
4517     ffrt::task_handle handler = notificationSvrQueue_->submit_h([&]() {
4518         ANS_LOGD("ffrt enter!");
4519         NotificationSubscriberManager::GetInstance()->SetBadgeNumber(badgeData);
4520     });
4521     notificationSvrQueue_->wait(handler);
4522     return ERR_OK;
4523 }
4524 
ResetPushCallbackProxy()4525 void AdvancedNotificationService::ResetPushCallbackProxy()
4526 {
4527     ANS_LOGD("enter");
4528     std::lock_guard<std::mutex> lock(pushMutex_);
4529     if ((pushCallBack_ == nullptr) || (pushCallBack_->AsObject() == nullptr)) {
4530         ANS_LOGE("invalid proxy state");
4531         return;
4532     }
4533     pushCallBack_->AsObject()->RemoveDeathRecipient(pushRecipient_);
4534     pushCallBack_ = nullptr;
4535 }
4536 
RegisterPushCallback(const sptr<IRemoteObject> & pushCallback)4537 ErrCode AdvancedNotificationService::RegisterPushCallback(const sptr<IRemoteObject> &pushCallback)
4538 {
4539     if (!AccessTokenHelper::IsSystemApp()) {
4540         ANS_LOGW("Not system app!");
4541         return ERR_ANS_NON_SYSTEM_APP;
4542     }
4543 
4544     if (!CheckPermission(OHOS_PERMISSION_NOTIFICATION_AGENT_CONTROLLER)) {
4545         ANS_LOGW("Not have OHOS_PERMISSION_NOTIFICATION_AGENT_CONTROLLER Permission!");
4546         return ERR_ANS_PERMISSION_DENIED;
4547     }
4548 
4549     if (!CheckPermission(OHOS_PERMISSION_NOTIFICATION_CONTROLLER)) {
4550         ANS_LOGW("Not have OHOS_PERMISSION_NOTIFICATION_CONTROLLER Permission!");
4551         return ERR_ANS_PERMISSION_DENIED;
4552     }
4553 
4554     if (pushCallBack_) {
4555         ANS_LOGW("Duplicate register pushcallback.");
4556         return ERR_ALREADY_EXISTS;
4557     }
4558 
4559     if (pushCallback == nullptr) {
4560         ANS_LOGW("pushCallback is null.");
4561         return ERR_INVALID_VALUE;
4562     }
4563 
4564     pushRecipient_ = new (std::nothrow) PushCallbackRecipient();
4565     if (!pushRecipient_) {
4566         ANS_LOGE("Failed to create death Recipient ptr PushCallbackRecipient!");
4567         return ERR_NO_INIT;
4568     }
4569     pushCallback->AddDeathRecipient(pushRecipient_);
4570 
4571     pushCallBack_ = iface_cast<IPushCallBack>(pushCallback);
4572     ANS_LOGD("end");
4573     return ERR_OK;
4574 }
4575 
UnregisterPushCallback()4576 ErrCode AdvancedNotificationService::UnregisterPushCallback()
4577 {
4578     if (!AccessTokenHelper::IsSystemApp()) {
4579         ANS_LOGW("Not system app!");
4580         return ERR_ANS_NON_SYSTEM_APP;
4581     }
4582 
4583     if (!CheckPermission(OHOS_PERMISSION_NOTIFICATION_AGENT_CONTROLLER)) {
4584         ANS_LOGW("Not have OHOS_PERMISSION_NOTIFICATION_AGENT_CONTROLLER Permission!");
4585         return ERR_ANS_PERMISSION_DENIED;
4586     }
4587 
4588     if (!CheckPermission(OHOS_PERMISSION_NOTIFICATION_CONTROLLER)) {
4589         ANS_LOGW("Not have OHOS_PERMISSION_NOTIFICATION_CONTROLLER Permission!");
4590         return ERR_ANS_PERMISSION_DENIED;
4591     }
4592 
4593     if (pushCallBack_ == nullptr) {
4594         ANS_LOGW("The registration callback has not been processed yet.");
4595         return ERR_INVALID_OPERATION;
4596     }
4597 
4598     pushCallBack_ = nullptr;
4599     ANS_LOGD("end");
4600     return ERR_OK;
4601 }
4602 
IsNeedPushCheck(NotificationConstant::SlotType slotType)4603 bool AdvancedNotificationService::IsNeedPushCheck(NotificationConstant::SlotType slotType)
4604 {
4605     ANS_LOGD("slotType:%{public}d.", slotType);
4606     if (AccessTokenHelper::IsSystemApp()) {
4607         ANS_LOGI("System applications do not require push check.");
4608         return false;
4609     }
4610 
4611     if (slotType != NotificationConstant::SlotType::CONTENT_INFORMATION) {
4612         ANS_LOGI("SlotType: CONTENT_INFORMATION except do not require push check.");
4613         return false;
4614     }
4615     return true;
4616 }
4617 
PushCheck(const sptr<NotificationRequest> & request)4618 ErrCode AdvancedNotificationService::PushCheck(const sptr<NotificationRequest> &request)
4619 {
4620     ANS_LOGD("start.");
4621     if (pushCallBack_) {
4622         nlohmann::json jsonObject;
4623         jsonObject["pkgName"] = request->GetCreatorBundleName();
4624         jsonObject["notifyId"] = request->GetNotificationId();
4625         jsonObject["contentType"] = static_cast<int32_t>(request->GetNotificationType());
4626         if (!(pushCallBack_->OnCheckNotification(jsonObject.dump()))) {
4627             ANS_LOGE("Notification push check failed.");
4628             return ERR_ANS_NOTIFICATION_PUSH_CHECK_FAILED;
4629         }
4630     }
4631     return ERR_OK;
4632 }
4633 
StartAutoDelete(const std::shared_ptr<NotificationRecord> & record)4634 void AdvancedNotificationService::StartAutoDelete(const std::shared_ptr<NotificationRecord> &record)
4635 {
4636     ANS_LOGD("enter");
4637     auto triggerFunc = std::bind(&AdvancedNotificationService::TriggerAutoDelete,
4638         this, record->notification->GetKey());
4639     int64_t autoDeleteTime = record->request->GetAutoDeletedTime() - GetCurrentTime();
4640 
4641     if (notificationSvrQueue_ == nullptr) {
4642         ANS_LOGE("Serial queue is invalid.");
4643         return;
4644     }
4645     ffrt::task_handle handler = notificationSvrQueue_->submit_h(triggerFunc,
4646         ffrt::task_attr().delay(autoDeleteTime * 1000));
4647 }
4648 
TriggerAutoDelete(std::string hashCode)4649 void AdvancedNotificationService::TriggerAutoDelete(std::string hashCode)
4650 {
4651     ANS_LOGD("enter");
4652     for (auto record : notificationList_) {
4653         if (!record->request) {
4654             continue;
4655         }
4656 
4657         if (record->notification->GetKey() == hashCode) {
4658             int32_t reason = NotificationConstant::APP_CANCEL_REASON_DELETE;
4659             UpdateRecentNotification(record->notification, true, reason);
4660             NotificationSubscriberManager::GetInstance()->NotifyCanceled(record->notification, nullptr, reason);
4661             notificationList_.remove(record);
4662             break;
4663         }
4664     }
4665 }
4666 
SendNotificationsOnCanceled(std::vector<sptr<Notification>> & notifications,const sptr<NotificationSortingMap> & notificationMap,int32_t deleteReason)4667 void AdvancedNotificationService::SendNotificationsOnCanceled(std::vector<sptr<Notification>> &notifications,
4668     const sptr<NotificationSortingMap> &notificationMap, int32_t deleteReason)
4669 {
4670     std::vector<sptr<Notification>> currNotifications;
4671     for (auto notification : notifications) {
4672         currNotifications.emplace_back(notification);
4673     }
4674     NotificationSubscriberManager::GetInstance()->BatchNotifyCanceled(
4675         currNotifications, nullptr, deleteReason);
4676     notifications.clear();
4677 }
OnRemoteDied(const wptr<IRemoteObject> & remote)4678 void PushCallbackRecipient::OnRemoteDied(const wptr<IRemoteObject> &remote)
4679 {
4680     ANS_LOGI("Push Callback died, remove the proxy object");
4681     AdvancedNotificationService::GetInstance()->ResetPushCallbackProxy();
4682 }
4683 
PushCallbackRecipient()4684 PushCallbackRecipient::PushCallbackRecipient() {}
4685 
~PushCallbackRecipient()4686 PushCallbackRecipient::~PushCallbackRecipient() {}
4687 }  // namespace Notification
4688 }  // namespace OHOS
4689