• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright (c) 2021-2024 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 "accesstoken_kit.h"
23 #include "ans_const_define.h"
24 #include "ans_inner_errors.h"
25 #include "ans_log_wrapper.h"
26 #include "errors.h"
27 
28 #include "ipc_skeleton.h"
29 #include "notification_bundle_option.h"
30 #include "notification_constant.h"
31 #include "hitrace_meter_adapter.h"
32 #include "notification_unified_group_Info.h"
33 #include "os_account_manager.h"
34 #include "distributed_screen_status_manager.h"
35 #include "notification_extension_wrapper.h"
36 #include "notification_local_live_view_subscriber_manager.h"
37 #include "common_event_manager.h"
38 #include "common_event_support.h"
39 #include "common_event_publish_info.h"
40 #include "os_account_manager_helper.h"
41 #include "want_params_wrapper.h"
42 #include "ans_convert_enum.h"
43 #include "notification_analytics_util.h"
44 
45 #include "advanced_notification_inline.cpp"
46 #include "notification_analytics_util.h"
47 #include "advanced_datashare_helper.h"
48 #include "advanced_datashare_helper_ext.h"
49 #include "datashare_result_set.h"
50 #include "system_ability_definition.h"
51 #include "if_system_ability_manager.h"
52 #include "iservice_registry.h"
53 #include "datashare_predicates.h"
54 #include "advanced_notification_flow_control_service.h"
55 
56 namespace OHOS {
57 namespace Notification {
58 
59 constexpr char FOUNDATION_BUNDLE_NAME[] = "ohos.global.systemres";
60 constexpr uint32_t SECONDS_IN_ONE_DAY = 24 * 60 * 60;
61 const static std::string NOTIFICATION_EVENT_PUSH_AGENT = "notification.event.PUSH_AGENT";
62 constexpr int32_t RSS_PID = 3051;
63 constexpr int32_t ANS_UID = 5523;
64 constexpr int32_t BROKER_UID = 5557;
65 constexpr int32_t AVSEESAION_PID = 6700;
66 constexpr int32_t TYPE_CODE_DOWNLOAD = 8;
67 constexpr const char *FOCUS_MODE_REPEAT_CALLERS_ENABLE = "1";
68 constexpr const char *CONTACT_DATA = "datashare:///com.ohos.contactsdataability/contacts/contact_data?Proxy=true";
69 constexpr int32_t OPERATION_TYPE_COMMON_EVENT = 4;
70 
SetDefaultNotificationEnabled(const sptr<NotificationBundleOption> & bundleOption,bool enabled)71 ErrCode AdvancedNotificationService::SetDefaultNotificationEnabled(
72     const sptr<NotificationBundleOption> &bundleOption, bool enabled)
73 {
74     sptr<NotificationBundleOption> bundle = GenerateValidBundleOption(bundleOption);
75     if (bundle == nullptr) {
76         return ERR_ANS_INVALID_BUNDLE;
77     }
78     sptr<EnabledNotificationCallbackData> bundleData =
79         new (std::nothrow) EnabledNotificationCallbackData(bundle->GetBundleName(), bundle->GetUid(), enabled);
80     if (bundleData == nullptr) {
81         ANS_LOGE("Failed to create EnabledNotificationCallbackData instance");
82         return ERR_NO_MEMORY;
83     }
84 
85     ErrCode result = ERR_OK;
86     result = NotificationPreferences::GetInstance()->SetNotificationsEnabledForBundle(bundle, enabled);
87     if (result == ERR_OK) {
88         NotificationSubscriberManager::GetInstance()->NotifyEnabledNotificationChanged(bundleData);
89         PublishSlotChangeCommonEvent(bundle);
90     }
91 
92     SendEnableNotificationHiSysEvent(bundleOption, enabled, result);
93     return result;
94 }
95 
Publish(const std::string & label,const sptr<NotificationRequest> & request)96 ErrCode AdvancedNotificationService::Publish(const std::string &label, const sptr<NotificationRequest> &request)
97 {
98     HITRACE_METER_NAME(HITRACE_TAG_NOTIFICATION, __PRETTY_FUNCTION__);
99     ANS_LOGD("%{public}s", __FUNCTION__);
100 
101     if (!request) {
102         ANSR_LOGE("ReminderRequest object is nullptr");
103         return ERR_ANS_INVALID_PARAM;
104     }
105 
106     if (!InitPublishProcess()) {
107         return ERR_ANS_NO_MEMORY;
108     }
109 
110     request->SetCreateTime(GetCurrentTime());
111     HaMetaMessage message = HaMetaMessage(EventSceneId::SCENE_1, EventBranchId::BRANCH_1);
112     bool isUpdateByOwnerAllowed = IsUpdateSystemLiveviewByOwner(request);
113     ErrCode result = publishProcess_[request->GetSlotType()]->PublishPreWork(request, isUpdateByOwnerAllowed);
114     if (result != ERR_OK) {
115         message.BranchId(EventBranchId::BRANCH_0).ErrorCode(result).Message("publish prework failed", true);
116         NotificationAnalyticsUtil::ReportPublishFailedEvent(request, message);
117         return result;
118     }
119     result = CheckUserIdParams(request->GetReceiverUserId());
120     if (result != ERR_OK) {
121         message.SceneId(EventSceneId::SCENE_3).ErrorCode(result).Message("User is invalid", true);
122         NotificationAnalyticsUtil::ReportPublishFailedEvent(request, message);
123         return result;
124     }
125     bool isSubsystem = AccessTokenHelper::VerifyNativeToken(IPCSkeleton::GetCallingTokenID());
126     if (isSubsystem) {
127         return PublishNotificationBySa(request);
128     }
129     if (request->GetRemovalWantAgent() != nullptr && request->GetRemovalWantAgent()->GetPendingWant() != nullptr) {
130         uint32_t operationType = (uint32_t)(request->GetRemovalWantAgent()->GetPendingWant()
131             ->GetType(request->GetRemovalWantAgent()->GetPendingWant()->GetTarget()));
132         bool isSystemApp = AccessTokenHelper::IsSystemApp();
133         if (!isSubsystem && !isSystemApp && operationType != OPERATION_TYPE_COMMON_EVENT) {
134             ANS_LOGI("SetRemovalWantAgent as nullptr");
135             request->SetRemovalWantAgent(nullptr);
136         }
137     }
138     do {
139         result = publishProcess_[request->GetSlotType()]->PublishNotificationByApp(request);
140         if (result != ERR_OK) {
141             break;
142         }
143 
144         sptr<NotificationBundleOption> bundleOption;
145         result = PrepareNotificationInfo(request, bundleOption);
146         if (result != ERR_OK) {
147             break;
148         }
149 
150         result = CheckSoundPermission(request, bundleOption->GetBundleName());
151         if (result != ERR_OK) {
152             message.ErrorCode(result).Message("Check sound failed.");
153             NotificationAnalyticsUtil::ReportPublishFailedEvent(request, message);
154             break;
155         }
156 
157         if (IsNeedPushCheck(request)) {
158             result = PushCheck(request);
159         }
160         if (result != ERR_OK) {
161             break;
162         }
163         result = PublishPreparedNotification(request, bundleOption, isUpdateByOwnerAllowed);
164         if (result != ERR_OK) {
165             break;
166         }
167     } while (0);
168 
169     SendPublishHiSysEvent(request, result);
170     return result;
171 }
172 
PublishNotificationForIndirectProxy(const sptr<NotificationRequest> & request)173 ErrCode AdvancedNotificationService::PublishNotificationForIndirectProxy(const sptr<NotificationRequest> &request)
174 {
175     HITRACE_METER_NAME(HITRACE_TAG_NOTIFICATION, __PRETTY_FUNCTION__);
176     ANS_LOGD("%{public}s", __FUNCTION__);
177 
178     if (!request) {
179         ANSR_LOGE("ReminderRequest object is nullptr");
180         return ERR_ANS_INVALID_PARAM;
181     }
182     ErrCode result = PrePublishRequest(request);
183     if (result != ERR_OK) {
184         return result;
185     }
186     auto tokenCaller = IPCSkeleton::GetCallingTokenID();
187     bool isAgentController = AccessTokenHelper::VerifyCallerPermission(tokenCaller,
188         OHOS_PERMISSION_NOTIFICATION_AGENT_CONTROLLER);
189     // SA not support sound
190     if (!request->GetSound().empty()) {
191         request->SetSound("");
192     }
193     std::string bundle = request->GetCreatorBundleName();
194     int32_t uid = request->GetCreatorUid();
195     request->SetOwnerUid(uid);
196     request->SetOwnerBundleName(bundle);
197     std::shared_ptr<NotificationRecord> record = std::make_shared<NotificationRecord>();
198     record->request = request;
199     record->bundleOption = new (std::nothrow) NotificationBundleOption(bundle, uid);
200     record->bundleOption->SetAppInstanceKey(request->GetAppInstanceKey());
201     sptr<NotificationBundleOption> bundleOption = new (std::nothrow) NotificationBundleOption(bundle, uid);
202     if (record->bundleOption == nullptr || bundleOption == nullptr) {
203         ANS_LOGE("Failed to create bundleOption");
204         return ERR_ANS_NO_MEMORY;
205     }
206     record->notification = new (std::nothrow) Notification(request);
207     if (record->notification == nullptr) {
208         ANS_LOGE("Failed to create notification");
209         return ERR_ANS_NO_MEMORY;
210     }
211 
212     if (notificationSvrQueue_ == nullptr) {
213         ANS_LOGE("Serial queue is invalid.");
214         return ERR_ANS_INVALID_PARAM;
215     }
216 
217     SetRequestBySlotType(record->request, bundleOption);
218 
219     auto ipcUid = IPCSkeleton::GetCallingUid();
220     ffrt::task_handle handler = notificationSvrQueue_->submit_h([&]() {
221         if (AssignValidNotificationSlot(record, bundleOption) != ERR_OK) {
222             ANS_LOGE("Can not assign valid slot!");
223         }
224 
225         CheckDoNotDisturbProfile(record);
226         ChangeNotificationByControlFlags(record, isAgentController);
227         if (IsSaCreateSystemLiveViewAsBundle(record, ipcUid) &&
228         (std::static_pointer_cast<OHOS::Notification::NotificationLocalLiveViewContent>(
229         record->request->GetContent()->GetNotificationContent())->GetType() == TYPE_CODE_DOWNLOAD)) {
230             result = SaPublishSystemLiveViewAsBundle(record);
231             if (result == ERR_OK) {
232                 SendLiveViewUploadHiSysEvent(record, UploadStatus::CREATE);
233             }
234             return;
235         }
236         bool isNotificationExists = IsNotificationExists(record->notification->GetKey());
237         result = FlowControlService::GetInstance()->FlowControl(record, ipcUid, isNotificationExists);
238         if (result != ERR_OK) {
239             return;
240         }
241         if (AssignToNotificationList(record) != ERR_OK) {
242             ANS_LOGE("Failed to assign notification list");
243             return;
244         }
245 
246         sptr<NotificationSortingMap> sortingMap = GenerateSortingMap();
247         NotificationSubscriberManager::GetInstance()->NotifyConsumed(record->notification, sortingMap);
248     });
249     notificationSvrQueue_->wait(handler);
250     if (result != ERR_OK) {
251         return result;
252     }
253 
254     if ((record->request->GetAutoDeletedTime() > GetCurrentTime()) && !record->request->IsCommonLiveView()) {
255         StartAutoDelete(record,
256             record->request->GetAutoDeletedTime(), NotificationConstant::TRIGGER_AUTO_DELETE_REASON_DELETE);
257     }
258     return ERR_OK;
259 }
260 
InitPublishProcess()261 bool AdvancedNotificationService::InitPublishProcess()
262 {
263     if (publishProcess_.size() > 0) {
264         return true;
265     }
266 
267     std::shared_ptr<LivePublishProcess> livePublishProcess = LivePublishProcess::GetInstance();
268     if (livePublishProcess == nullptr) {
269         ANS_LOGE("InitPublishProcess fail as livePublishProcess is nullptr.");
270         return false;
271     }
272     publishProcess_.insert_or_assign(NotificationConstant::SlotType::LIVE_VIEW, livePublishProcess);
273     std::shared_ptr<CommonNotificationPublishProcess> commonNotificationPublishProcess =
274         CommonNotificationPublishProcess::GetInstance();
275     if (commonNotificationPublishProcess == nullptr) {
276         ANS_LOGE("InitPublishProcess fail as commonNotificationPublishProcess is nullptr.");
277         publishProcess_.clear();
278         return false;
279     }
280     publishProcess_.insert_or_assign(
281         NotificationConstant::SlotType::SOCIAL_COMMUNICATION, commonNotificationPublishProcess);
282     publishProcess_.insert_or_assign(
283         NotificationConstant::SlotType::SERVICE_REMINDER, commonNotificationPublishProcess);
284     publishProcess_.insert_or_assign(
285         NotificationConstant::SlotType::CONTENT_INFORMATION, commonNotificationPublishProcess);
286     publishProcess_.insert_or_assign(
287         NotificationConstant::SlotType::OTHER, commonNotificationPublishProcess);
288     publishProcess_.insert_or_assign(
289         NotificationConstant::SlotType::CUSTOM, commonNotificationPublishProcess);
290     publishProcess_.insert_or_assign(
291         NotificationConstant::SlotType::CUSTOMER_SERVICE, commonNotificationPublishProcess);
292     publishProcess_.insert_or_assign(
293         NotificationConstant::SlotType::EMERGENCY_INFORMATION, commonNotificationPublishProcess);
294     return true;
295 }
296 
Cancel(int32_t notificationId,const std::string & label,const std::string & instanceKey)297 ErrCode AdvancedNotificationService::Cancel(int32_t notificationId,
298     const std::string &label, const std::string &instanceKey)
299 {
300     ANS_LOGD("%{public}s", __FUNCTION__);
301 
302     sptr<NotificationBundleOption> bundleOption = GenerateBundleOption();
303     if (bundleOption == nullptr) {
304         std::string message = "get bundleOption is null.";
305         OHOS::Notification::HaMetaMessage haMetaMessage = HaMetaMessage(1, 1)
306             .ErrorCode(ERR_ANS_INVALID_BUNDLE).NotificationId(notificationId);
307         ReportDeleteFailedEventPush(haMetaMessage, NotificationConstant::APP_CANCEL_REASON_DELETE,
308             message);
309         ANS_LOGE("%{public}s", message.c_str());
310         return ERR_ANS_INVALID_BUNDLE;
311     }
312     bundleOption->SetAppInstanceKey(instanceKey);
313     return CancelPreparedNotification(notificationId, label, bundleOption,
314         NotificationConstant::APP_CANCEL_REASON_DELETE);
315 }
316 
CancelAll(const std::string & instanceKey)317 ErrCode AdvancedNotificationService::CancelAll(const std::string &instanceKey)
318 {
319     ANS_LOGD("%{public}s", __FUNCTION__);
320     const int reason = NotificationConstant::APP_CANCEL_ALL_REASON_DELETE;
321     sptr<NotificationBundleOption> bundleOption = GenerateBundleOption();
322     if (bundleOption == nullptr) {
323         return ERR_ANS_INVALID_BUNDLE;
324     }
325     bundleOption->SetAppInstanceKey(instanceKey);
326 
327     if (notificationSvrQueue_ == nullptr) {
328         ANS_LOGE("Serial queue is invalidated.");
329         return ERR_ANS_INVALID_PARAM;
330     }
331     ErrCode result = ExcuteCancelAll(bundleOption, reason);
332     return result;
333 }
334 
ExcuteCancelAll(const sptr<NotificationBundleOption> & bundleOption,const int32_t reason)335 ErrCode AdvancedNotificationService::ExcuteCancelAll(
336     const sptr<NotificationBundleOption>& bundleOption, const int32_t reason)
337 {
338     ErrCode result = ERR_OK;
339     ffrt::task_handle handler = notificationSvrQueue_->submit_h(std::bind([&]() {
340         ANS_LOGD("ffrt enter!");
341         sptr<Notification> notification = nullptr;
342 
343         std::vector<std::string> keys = GetNotificationKeysByBundle(bundleOption);
344         std::vector<sptr<Notification>> notifications;
345         std::vector<uint64_t> timerIds;
346         for (auto key : keys) {
347 #ifdef DISTRIBUTED_NOTIFICATION_SUPPORTED
348             std::string deviceId;
349             std::string bundleName;
350             GetDistributedInfo(key, deviceId, bundleName);
351 #endif
352             result = RemoveFromNotificationList(key, notification, true, reason);
353             if (result != ERR_OK) {
354                 continue;
355             }
356 
357             if (notification != nullptr) {
358                 UpdateRecentNotification(notification, true, reason);
359                 notifications.emplace_back(notification);
360                 timerIds.emplace_back(notification->GetAutoDeletedTimer());
361 #ifdef DISTRIBUTED_NOTIFICATION_SUPPORTED
362                 DoDistributedDelete(deviceId, bundleName, notification);
363 #endif
364             }
365             if (notifications.size() >= MAX_CANCELED_PARCELABLE_VECTOR_NUM) {
366                 std::vector<sptr<Notification>> currNotificationList = notifications;
367                 NotificationSubscriberManager::GetInstance()->BatchNotifyCanceled(
368                     currNotificationList, nullptr, reason);
369                 notifications.clear();
370             }
371         }
372 
373         if (!notifications.empty()) {
374             NotificationSubscriberManager::GetInstance()->BatchNotifyCanceled(
375                 notifications, nullptr, reason);
376         }
377         BatchCancelTimer(timerIds);
378         result = ERR_OK;
379     }));
380     notificationSvrQueue_->wait(handler);
381     return result;
382 }
383 
CancelAsBundle(const sptr<NotificationBundleOption> & bundleOption,int32_t notificationId,int32_t userId)384 ErrCode AdvancedNotificationService::CancelAsBundle(
385     const sptr<NotificationBundleOption> &bundleOption, int32_t notificationId, int32_t userId)
386 {
387     ANS_LOGD("%{public}s", __FUNCTION__);
388     int32_t reason = NotificationConstant::APP_CANCEL_AS_BUNELE_REASON_DELETE;
389     bool isSubsystem = AccessTokenHelper::VerifyNativeToken(IPCSkeleton::GetCallingTokenID());
390     if (!isSubsystem && !AccessTokenHelper::IsSystemApp()) {
391         std::string message = "not systemApp";
392         OHOS::Notification::HaMetaMessage haMetaMessage = HaMetaMessage(2, 1)
393             .ErrorCode(ERR_ANS_NON_SYSTEM_APP).NotificationId(notificationId);
394         ReportDeleteFailedEventPush(haMetaMessage, reason, message);
395         ANS_LOGE("%{public}s", message.c_str());
396         return ERR_ANS_NON_SYSTEM_APP;
397     }
398 
399     if (!AccessTokenHelper::CheckPermission(OHOS_PERMISSION_NOTIFICATION_CONTROLLER) ||
400         !AccessTokenHelper::CheckPermission(OHOS_PERMISSION_NOTIFICATION_AGENT_CONTROLLER)) {
401         std::string message = "no acl permission";
402         OHOS::Notification::HaMetaMessage haMetaMessage = HaMetaMessage(2, 2)
403             .ErrorCode(ERR_ANS_PERMISSION_DENIED).NotificationId(notificationId);
404         ReportDeleteFailedEventPush(haMetaMessage, reason, message);
405         ANS_LOGE("%{public}s", message.c_str());
406         return ERR_ANS_PERMISSION_DENIED;
407     }
408 
409     int32_t errCode = CheckUserIdParams(userId);
410     if (errCode != ERR_OK) {
411         return errCode;
412     }
413 
414     int32_t uid = -1;
415     if (bundleOption->GetUid() == DEFAULT_UID) {
416         std::shared_ptr<BundleManagerHelper> bundleManager = BundleManagerHelper::GetInstance();
417         if (bundleManager != nullptr) {
418             uid = BundleManagerHelper::GetInstance()->GetDefaultUidByBundleName(bundleOption->GetBundleName(), userId);
419         }
420     } else {
421         uid = bundleOption->GetUid();
422     }
423     if (uid < 0) {
424         std::string message = "uid error";
425         OHOS::Notification::HaMetaMessage haMetaMessage = HaMetaMessage(2, 3)
426             .ErrorCode(ERR_ANS_INVALID_UID).NotificationId(notificationId);
427         ReportDeleteFailedEventPush(haMetaMessage, reason, message);
428         ANS_LOGE("%{public}s", message.c_str());
429         return ERR_ANS_INVALID_UID;
430     }
431     sptr<NotificationBundleOption> bundle = new (std::nothrow) NotificationBundleOption(
432         bundleOption->GetBundleName(), uid);
433     return CancelPreparedNotification(notificationId, "", bundle, reason);
434 }
435 
CancelAsBundle(const sptr<NotificationBundleOption> & bundleOption,int32_t notificationId)436 ErrCode AdvancedNotificationService::CancelAsBundle(
437     const sptr<NotificationBundleOption> &bundleOption, int32_t notificationId)
438 {
439     ANS_LOGD("%{public}s, uid = %{public}d", __FUNCTION__, bundleOption->GetUid());
440     int32_t userId = -1;
441     if (bundleOption->GetUid() != 0) {
442         OHOS::AccountSA::OsAccountManager::GetOsAccountLocalIdFromUid(bundleOption->GetUid(), userId);
443     } else {
444         OHOS::AccountSA::OsAccountManager::GetOsAccountLocalIdFromUid(IPCSkeleton::GetCallingUid(), userId);
445     }
446     return CancelAsBundle(bundleOption, notificationId, userId);
447 }
448 
CancelAsBundle(int32_t notificationId,const std::string & representativeBundle,int32_t userId)449 ErrCode AdvancedNotificationService::CancelAsBundle(
450     int32_t notificationId, const std::string &representativeBundle, int32_t userId)
451 {
452     ANS_LOGD("%{public}s", __FUNCTION__);
453     sptr<NotificationBundleOption> bundleOption = new (std::nothrow) NotificationBundleOption(
454          representativeBundle, DEFAULT_UID);
455     return CancelAsBundle(bundleOption, notificationId, userId);
456 }
457 
CancelAsBundleWithAgent(const sptr<NotificationBundleOption> & bundleOption,const int32_t id)458 ErrCode AdvancedNotificationService::CancelAsBundleWithAgent(
459     const sptr<NotificationBundleOption> &bundleOption, const int32_t id)
460 {
461     ANS_LOGD("Called.");
462     int32_t reason = NotificationConstant::APP_CANCEL_AS_BUNELE_WITH_AGENT_REASON_DELETE;
463     bool isSubsystem = AccessTokenHelper::VerifyNativeToken(IPCSkeleton::GetCallingTokenID());
464     if (!isSubsystem && !AccessTokenHelper::IsSystemApp()) {
465         std::string message = "not systemApp";
466         OHOS::Notification::HaMetaMessage haMetaMessage = HaMetaMessage(2, 4)
467             .ErrorCode(ERR_ANS_NON_SYSTEM_APP).NotificationId(id);
468         ReportDeleteFailedEventPush(haMetaMessage, reason, message);
469         ANS_LOGE("%{public}s", message.c_str());
470         return ERR_ANS_NON_SYSTEM_APP;
471     }
472 
473     if (IsAgentRelationship(GetClientBundleName(), bundleOption->GetBundleName())) {
474         int32_t userId = -1;
475         if (bundleOption->GetUid() != 0) {
476             OHOS::AccountSA::OsAccountManager::GetOsAccountLocalIdFromUid(bundleOption->GetUid(), userId);
477         } else {
478             OHOS::AccountSA::OsAccountManager::GetOsAccountLocalIdFromUid(IPCSkeleton::GetCallingUid(), userId);
479         }
480         int32_t uid = -1;
481         if (bundleOption->GetUid() == DEFAULT_UID) {
482             std::shared_ptr<BundleManagerHelper> bundleManager = BundleManagerHelper::GetInstance();
483             if (bundleManager != nullptr) {
484                 uid = BundleManagerHelper::GetInstance()->GetDefaultUidByBundleName(
485                     bundleOption->GetBundleName(), userId);
486             }
487         } else {
488             uid = bundleOption->GetUid();
489         }
490         if (uid < 0) {
491             std::string message = "uid error";
492             OHOS::Notification::HaMetaMessage haMetaMessage = HaMetaMessage(2, 5)
493                 .ErrorCode(ERR_ANS_INVALID_UID).NotificationId(id);
494             ReportDeleteFailedEventPush(haMetaMessage, reason, message);
495             ANS_LOGE("%{public}s", message.c_str());
496             return ERR_ANS_INVALID_UID;
497         }
498         sptr<NotificationBundleOption> bundle = new (std::nothrow) NotificationBundleOption(
499             bundleOption->GetBundleName(), uid);
500         return CancelPreparedNotification(id, "", bundle, reason);
501     }
502     std::string message = "no agent setting";
503     OHOS::Notification::HaMetaMessage haMetaMessage = HaMetaMessage(2, 6)
504         .ErrorCode(ERR_ANS_NO_AGENT_SETTING).NotificationId(id);
505     ReportDeleteFailedEventPush(haMetaMessage, reason, message);
506     ANS_LOGE("%{public}s", message.c_str());
507     return ERR_ANS_NO_AGENT_SETTING;
508 }
509 
PublishAsBundle(const sptr<NotificationRequest> notification,const std::string & representativeBundle)510 ErrCode AdvancedNotificationService::PublishAsBundle(
511     const sptr<NotificationRequest> notification, const std::string &representativeBundle)
512 {
513     return ERR_INVALID_OPERATION;
514 }
515 
SetNotificationBadgeNum(int32_t num)516 ErrCode AdvancedNotificationService::SetNotificationBadgeNum(int32_t num)
517 {
518     ANS_LOGD("%{public}s", __FUNCTION__);
519 
520     sptr<NotificationBundleOption> bundleOption = GenerateBundleOption();
521     if (bundleOption == nullptr) {
522         ANS_LOGD("BundleOption is null.");
523         return ERR_ANS_INVALID_BUNDLE;
524     }
525 
526     if (notificationSvrQueue_ == nullptr) {
527         ANS_LOGE("Serial queue is invalidity.");
528         return ERR_ANS_INVALID_PARAM;
529     }
530     ErrCode result = ERR_OK;
531     ffrt::task_handle handler = notificationSvrQueue_->submit_h(
532         std::bind([&]() {
533             ANS_LOGD("ffrt enter!");
534             result = NotificationPreferences::GetInstance()->SetTotalBadgeNums(bundleOption, num);
535         }));
536     notificationSvrQueue_->wait(handler);
537     return result;
538 }
539 
Delete(const std::string & key,int32_t removeReason)540 ErrCode AdvancedNotificationService::Delete(const std::string &key, int32_t removeReason)
541 {
542     ANS_LOGD("%{public}s", __FUNCTION__);
543     bool isSubsystem = AccessTokenHelper::VerifyNativeToken(IPCSkeleton::GetCallingTokenID());
544     if (!isSubsystem && !AccessTokenHelper::IsSystemApp()) {
545         std::string message = "not systemApp. key:" + key + ".";
546         OHOS::Notification::HaMetaMessage haMetaMessage = HaMetaMessage(4, 1)
547             .ErrorCode(ERR_ANS_NON_SYSTEM_APP);
548         ReportDeleteFailedEventPush(haMetaMessage, removeReason, message);
549         ANS_LOGE("%{public}s", message.c_str());
550         return ERR_ANS_NON_SYSTEM_APP;
551     }
552 
553     if (!AccessTokenHelper::CheckPermission(OHOS_PERMISSION_NOTIFICATION_CONTROLLER)) {
554         std::string message = "no acl permission. key:" + key + ".";
555         OHOS::Notification::HaMetaMessage haMetaMessage = HaMetaMessage(4, 2)
556             .ErrorCode(ERR_ANS_PERMISSION_DENIED);
557         ReportDeleteFailedEventPush(haMetaMessage, removeReason, message);
558         ANS_LOGE("%{public}s", message.c_str());
559         return ERR_ANS_PERMISSION_DENIED;
560     }
561 
562     if (notificationSvrQueue_ == nullptr) {
563         std::string message = "Serial queue is invalidated. key:" + key + ".";
564         ANS_LOGE("%{public}s", message.c_str());
565         return ERR_ANS_INVALID_PARAM;
566     }
567 
568     return ExcuteDelete(key, removeReason);
569 }
570 
ExcuteDelete(const std::string & key,const int32_t removeReason)571 ErrCode AdvancedNotificationService::ExcuteDelete(const std::string &key, const int32_t removeReason)
572 {
573     ErrCode result = ERR_OK;
574     ffrt::task_handle handler = notificationSvrQueue_->submit_h(std::bind([&]() {
575         ANS_LOGD("ffrt enter!");
576         sptr<Notification> notification = nullptr;
577 #ifdef DISTRIBUTED_NOTIFICATION_SUPPORTED
578         std::string deviceId;
579         std::string bundleName;
580         GetDistributedInfo(key, deviceId, bundleName);
581 #endif
582         result = RemoveFromNotificationList(key, notification, false, removeReason);
583         if (result != ERR_OK) {
584             return;
585         }
586 
587         if (notification != nullptr) {
588             UpdateRecentNotification(notification, true, removeReason);
589             CancelTimer(notification->GetAutoDeletedTimer());
590             NotificationSubscriberManager::GetInstance()->NotifyCanceled(notification, nullptr, removeReason);
591 #ifdef DISTRIBUTED_NOTIFICATION_SUPPORTED
592             DoDistributedDelete(deviceId, bundleName, notification);
593 #endif
594         }
595     }));
596     notificationSvrQueue_->wait(handler);
597 
598     return result;
599 }
600 
DeleteByBundle(const sptr<NotificationBundleOption> & bundleOption)601 ErrCode AdvancedNotificationService::DeleteByBundle(const sptr<NotificationBundleOption> &bundleOption)
602 {
603     ANS_LOGD("%{public}s", __FUNCTION__);
604 
605     bool isSubsystem = AccessTokenHelper::VerifyNativeToken(IPCSkeleton::GetCallingTokenID());
606     if (!isSubsystem && !AccessTokenHelper::IsSystemApp()) {
607         ANS_LOGD("VerifyNativeToken is false.");
608         return ERR_ANS_NON_SYSTEM_APP;
609     }
610 
611     if (!AccessTokenHelper::CheckPermission(OHOS_PERMISSION_NOTIFICATION_CONTROLLER)) {
612         return ERR_ANS_PERMISSION_DENIED;
613     }
614 
615     sptr<NotificationBundleOption> bundle = GenerateValidBundleOption(bundleOption);
616     if (bundle == nullptr) {
617         ANS_LOGD("bundle is false.");
618         return ERR_ANS_INVALID_BUNDLE;
619     }
620 
621     if (notificationSvrQueue_ == nullptr) {
622         ANS_LOGE("Serial queue is invalid.");
623         return ERR_ANS_INVALID_PARAM;
624     }
625     ErrCode result = ERR_OK;
626     ffrt::task_handle handler = notificationSvrQueue_->submit_h(std::bind([&]() {
627         ANS_LOGD("ffrt enter!");
628         std::vector<std::string> keys = GetNotificationKeys(bundle);
629         for (auto key : keys) {
630 #ifdef DISTRIBUTED_NOTIFICATION_SUPPORTED
631             std::string deviceId;
632             std::string bundleName;
633             GetDistributedInfo(key, deviceId, bundleName);
634 #endif
635             sptr<Notification> notification = nullptr;
636 
637             result = RemoveFromNotificationList(key, notification, false, NotificationConstant::CANCEL_REASON_DELETE);
638             if (result != ERR_OK) {
639                 continue;
640             }
641 
642             if (notification != nullptr) {
643                 int32_t reason = NotificationConstant::CANCEL_REASON_DELETE;
644                 UpdateRecentNotification(notification, true, reason);
645                 CancelTimer(notification->GetAutoDeletedTimer());
646                 NotificationSubscriberManager::GetInstance()->NotifyCanceled(notification, nullptr, reason);
647 #ifdef DISTRIBUTED_NOTIFICATION_SUPPORTED
648                 DoDistributedDelete(deviceId, bundleName, notification);
649 #endif
650             }
651         }
652 
653         result = ERR_OK;
654     }));
655     notificationSvrQueue_->wait(handler);
656 
657     return result;
658 }
659 
DeleteAll()660 ErrCode AdvancedNotificationService::DeleteAll()
661 {
662     ANS_LOGD("%{public}s", __FUNCTION__);
663 
664     const int32_t reason = NotificationConstant::CANCEL_ALL_REASON_DELETE;
665     bool isSubsystem = AccessTokenHelper::VerifyNativeToken(IPCSkeleton::GetCallingTokenID());
666     if (!isSubsystem && !AccessTokenHelper::IsSystemApp()) {
667         std::string message = "not system app.";
668         OHOS::Notification::HaMetaMessage haMetaMessage = HaMetaMessage(6, 8)
669             .ErrorCode(ERR_ANS_NON_SYSTEM_APP);
670         ReportDeleteFailedEventPush(haMetaMessage, reason, message);
671         ANS_LOGE("%{public}s", message.c_str());
672         return ERR_ANS_NON_SYSTEM_APP;
673     }
674 
675     if (!AccessTokenHelper::CheckPermission(OHOS_PERMISSION_NOTIFICATION_CONTROLLER)) {
676         std::string message = "no acl permission.";
677         OHOS::Notification::HaMetaMessage haMetaMessage = HaMetaMessage(6, 9)
678             .ErrorCode(ERR_ANS_PERMISSION_DENIED);
679         ReportDeleteFailedEventPush(haMetaMessage, reason, message);
680         ANS_LOGE("%{public}s", message.c_str());
681         return ERR_ANS_PERMISSION_DENIED;
682     }
683 
684     if (notificationSvrQueue_ == nullptr) {
685         std::string message = "Serial queue is invalidity.";
686         ANS_LOGE("%{public}s", message.c_str());
687         return ERR_ANS_INVALID_PARAM;
688     }
689     ErrCode result = ERR_OK;
690     ffrt::task_handle handler = notificationSvrQueue_->submit_h(std::bind([&]() {
691         ANS_LOGD("ffrt enter!");
692         int32_t activeUserId = SUBSCRIBE_USER_INIT;
693         if (OsAccountManagerHelper::GetInstance().GetCurrentActiveUserId(activeUserId) != ERR_OK) {
694             return;
695         }
696         std::vector<std::string> keys = GetNotificationKeys(nullptr);
697         std::vector<sptr<Notification>> notifications;
698         std::vector<uint64_t> timerIds;
699         for (auto key : keys) {
700 #ifdef DISTRIBUTED_NOTIFICATION_SUPPORTED
701             std::string deviceId;
702             std::string bundleName;
703             GetDistributedInfo(key, deviceId, bundleName);
704 #endif
705             sptr<Notification> notification = nullptr;
706 
707             result = RemoveFromNotificationListForDeleteAll(key, activeUserId, notification);
708             if ((result != ERR_OK) || (notification == nullptr)) {
709                 continue;
710             }
711 
712             if (notification->GetUserId() == activeUserId) {
713                 UpdateRecentNotification(notification, true, reason);
714                 notifications.emplace_back(notification);
715                 timerIds.emplace_back(notification->GetAutoDeletedTimer());
716 #ifdef DISTRIBUTED_NOTIFICATION_SUPPORTED
717                 DoDistributedDelete(deviceId, bundleName, notification);
718 #endif
719             }
720             if (notifications.size() >= MAX_CANCELED_PARCELABLE_VECTOR_NUM) {
721                 ANS_LOGD("Notifications size greater than or equal to MAX_CANCELED_PARCELABLE_VECTOR_NUM.");
722                 SendNotificationsOnCanceled(notifications, nullptr, reason);
723             }
724         }
725         if (!notifications.empty()) {
726             NotificationSubscriberManager::GetInstance()->BatchNotifyCanceled(
727                 notifications, nullptr, reason);
728         }
729         BatchCancelTimer(timerIds);
730         result = ERR_OK;
731     }));
732     notificationSvrQueue_->wait(handler);
733 
734     return result;
735 }
736 
SetShowBadgeEnabledForBundle(const sptr<NotificationBundleOption> & bundleOption,bool enabled)737 ErrCode AdvancedNotificationService::SetShowBadgeEnabledForBundle(
738     const sptr<NotificationBundleOption> &bundleOption, bool enabled)
739 {
740     if (bundleOption == nullptr) {
741         ANS_LOGE("BundleOption is null.");
742         return ERR_ANS_INVALID_BUNDLE;
743     }
744 
745     HaMetaMessage message = HaMetaMessage(EventSceneId::SCENE_8, EventBranchId::BRANCH_3);
746     message.Message(bundleOption->GetBundleName() + "_" + std::to_string(bundleOption->GetUid()) +
747         " enabled:" + std::to_string(enabled));
748 
749     bool isSubsystem = AccessTokenHelper::VerifyNativeToken(IPCSkeleton::GetCallingTokenID());
750     if (!isSubsystem && !AccessTokenHelper::IsSystemApp()) {
751         ANS_LOGE("IsSystemApp is false.");
752         message.ErrorCode(ERR_ANS_NON_SYSTEM_APP).Append(" Not SystemApp");
753         NotificationAnalyticsUtil::ReportModifyEvent(message);
754         return ERR_ANS_NON_SYSTEM_APP;
755     }
756 
757     if (!AccessTokenHelper::CheckPermission(OHOS_PERMISSION_NOTIFICATION_CONTROLLER)) {
758         ANS_LOGE("Permission Denied.");
759         message.ErrorCode(ERR_ANS_PERMISSION_DENIED).Append(" Permission Denied");
760         NotificationAnalyticsUtil::ReportModifyEvent(message);
761         return ERR_ANS_PERMISSION_DENIED;
762     }
763 
764     sptr<NotificationBundleOption> bundle = GenerateValidBundleOption(bundleOption);
765     if (bundle == nullptr) {
766         ANS_LOGE("Bundle is nullptr.");
767         return ERR_ANS_INVALID_BUNDLE;
768     }
769 
770     if (notificationSvrQueue_ == nullptr) {
771         ANS_LOGE("NotificationSvrQueue_ is invalid.");
772         return ERR_ANS_INVALID_PARAM;
773     }
774     ErrCode result = ERR_OK;
775     ffrt::task_handle handler = notificationSvrQueue_->submit_h(
776         std::bind([&]() {
777             ANS_LOGD("ffrt enter!");
778             result = NotificationPreferences::GetInstance()->SetShowBadge(bundle, enabled);
779             if (result == ERR_OK) {
780                 HandleBadgeEnabledChanged(bundle, enabled);
781             }
782         }));
783     notificationSvrQueue_->wait(handler);
784     ANS_LOGI("%{public}s_%{public}d, enabled: %{public}s, Set show badge enabled for bundle result: %{public}d",
785         bundleOption->GetBundleName().c_str(), bundleOption->GetUid(), std::to_string(enabled).c_str(), result);
786     message.ErrorCode(result);
787     NotificationAnalyticsUtil::ReportModifyEvent(message);
788     return result;
789 }
790 
HandleBadgeEnabledChanged(const sptr<NotificationBundleOption> & bundleOption,bool enabled)791 void AdvancedNotificationService::HandleBadgeEnabledChanged(
792     const sptr<NotificationBundleOption> &bundleOption, bool enabled)
793 {
794     sptr<EnabledNotificationCallbackData> enabledData = new (std::nothrow)
795         EnabledNotificationCallbackData(bundleOption->GetBundleName(), bundleOption->GetUid(), enabled);
796     if (enabledData == nullptr) {
797         ANS_LOGE("Failed to create badge enabled data object.");
798         return;
799     }
800 
801     NotificationSubscriberManager::GetInstance()->NotifyBadgeEnabledChanged(enabledData);
802 }
803 
GetShowBadgeEnabledForBundle(const sptr<NotificationBundleOption> & bundleOption,bool & enabled)804 ErrCode AdvancedNotificationService::GetShowBadgeEnabledForBundle(
805     const sptr<NotificationBundleOption> &bundleOption, bool &enabled)
806 {
807     ANS_LOGD("%{public}s", __FUNCTION__);
808 
809     bool isSubsystem = AccessTokenHelper::VerifyNativeToken(IPCSkeleton::GetCallingTokenID());
810     if (!isSubsystem && !AccessTokenHelper::IsSystemApp()) {
811         ANS_LOGD("VerifyNativeToken is bogus.");
812         return ERR_ANS_NON_SYSTEM_APP;
813     }
814 
815     if (!AccessTokenHelper::CheckPermission(OHOS_PERMISSION_NOTIFICATION_CONTROLLER)) {
816         return ERR_ANS_PERMISSION_DENIED;
817     }
818 
819     sptr<NotificationBundleOption> bundle = GenerateValidBundleOption(bundleOption);
820     if (bundle == nullptr) {
821         ANS_LOGD("Failed to generateValidBundleOption.");
822         return ERR_ANS_INVALID_BUNDLE;
823     }
824 
825     if (notificationSvrQueue_ == nullptr) {
826         ANS_LOGE("Serial queue is invalid.");
827         return ERR_ANS_INVALID_PARAM;
828     }
829     ErrCode result = ERR_OK;
830     ffrt::task_handle handler = notificationSvrQueue_->submit_h(std::bind([&]() {
831         ANS_LOGD("ffrt enter!");
832         result = NotificationPreferences::GetInstance()->IsShowBadge(bundle, enabled);
833         if (result == ERR_ANS_PREFERENCES_NOTIFICATION_BUNDLE_NOT_EXIST) {
834             result = ERR_OK;
835             enabled = true;
836         }
837     }));
838     notificationSvrQueue_->wait(handler);
839     return result;
840 }
841 
GetShowBadgeEnabled(bool & enabled)842 ErrCode AdvancedNotificationService::GetShowBadgeEnabled(bool &enabled)
843 {
844     ANS_LOGD("%{public}s", __FUNCTION__);
845 
846     sptr<NotificationBundleOption> bundleOption = GenerateBundleOption();
847     if (bundleOption == nullptr) {
848         return ERR_ANS_INVALID_BUNDLE;
849     }
850 
851     if (notificationSvrQueue_ == nullptr) {
852         ANS_LOGE("Serial queue is ineffective.");
853         return ERR_ANS_INVALID_PARAM;
854     }
855     ErrCode result = ERR_OK;
856     ffrt::task_handle handler = notificationSvrQueue_->submit_h(std::bind([&]() {
857         ANS_LOGD("ffrt enter!");
858         result = NotificationPreferences::GetInstance()->IsShowBadge(bundleOption, enabled);
859         if (result == ERR_ANS_PREFERENCES_NOTIFICATION_BUNDLE_NOT_EXIST) {
860             result = ERR_OK;
861             enabled = true;
862         }
863     }));
864     notificationSvrQueue_->wait(handler);
865     return result;
866 }
867 
RequestEnableNotification(const std::string & deviceId,const sptr<AnsDialogCallback> & callback,const sptr<IRemoteObject> & callerToken)868 ErrCode AdvancedNotificationService::RequestEnableNotification(const std::string &deviceId,
869     const sptr<AnsDialogCallback> &callback,
870     const sptr<IRemoteObject> &callerToken)
871 {
872     ANS_LOGD("%{public}s", __FUNCTION__);
873     if (callback == nullptr) {
874         ANS_LOGE("callback == nullptr");
875         return ERR_ANS_INVALID_PARAM;
876     }
877 
878     ErrCode result = ERR_OK;
879     sptr<NotificationBundleOption> bundleOption = GenerateBundleOption();
880     if (bundleOption == nullptr) {
881         ANS_LOGE("bundleOption is nullptr.");
882         return ERR_ANS_INVALID_BUNDLE;
883     }
884     // To get the permission
885     bool allowedNotify = false;
886     HaMetaMessage message = HaMetaMessage(EventSceneId::SCENE_8, EventBranchId::BRANCH_5);
887     message.Message(bundleOption->GetBundleName() + "_" + std::to_string(bundleOption->GetUid()) +
888             " deviceId:" + deviceId);
889     result = IsAllowedNotifySelf(bundleOption, allowedNotify);
890     if (result != ERR_OK) {
891         ANS_LOGE("Not allowed notify self");
892         message.ErrorCode(result).Append(" Allow failed");
893         NotificationAnalyticsUtil::ReportModifyEvent(message);
894         return ERROR_INTERNAL_ERROR;
895     }
896     ANS_LOGI("allowedNotify = %{public}d, bundle = %{public}s", allowedNotify,
897         bundleOption->GetBundleName().c_str());
898     if (allowedNotify) {
899         message.ErrorCode(ERR_OK).Append(" Allow success");
900         NotificationAnalyticsUtil::ReportModifyEvent(message);
901         return ERR_OK;
902     }
903     // Check to see if it has been popover before
904     bool hasPopped = false;
905     result = GetHasPoppedDialog(bundleOption, hasPopped);
906     if (result != ERR_OK) {
907         ANS_LOGE("Get has popped dialog failed.");
908         message.ErrorCode(result).Append(" Get dialog failed.");
909         NotificationAnalyticsUtil::ReportModifyEvent(message);
910         return ERROR_INTERNAL_ERROR;
911     }
912     if (hasPopped) {
913         ANS_LOGE("Has popped is true.");
914         message.ErrorCode(ERR_ANS_NOT_ALLOWED).Append(" Has popped");
915         NotificationAnalyticsUtil::ReportModifyEvent(message);
916         return ERR_ANS_NOT_ALLOWED;
917     }
918 
919     if (!CreateDialogManager()) {
920         ANS_LOGE("Create dialog manager failed.");
921         message.ErrorCode(ERR_ANS_NOT_ALLOWED).Append(" Create dialog failed");
922         NotificationAnalyticsUtil::ReportModifyEvent(message);
923         return ERROR_INTERNAL_ERROR;
924     }
925 
926     result = dialogManager_->RequestEnableNotificationDailog(bundleOption, callback, callerToken);
927     if (result == ERR_OK) {
928         result = ERR_ANS_DIALOG_POP_SUCCEEDED;
929     }
930 
931     ANS_LOGI("%{public}s_%{public}d, deviceId: %{public}s, Request enable notification dailog result: %{public}d",
932         bundleOption->GetBundleName().c_str(), bundleOption->GetUid(), deviceId.c_str(), result);
933     message.ErrorCode(result);
934     NotificationAnalyticsUtil::ReportModifyEvent(message);
935     return result;
936 }
937 
SetNotificationsEnabledForBundle(const std::string & deviceId,bool enabled)938 ErrCode AdvancedNotificationService::SetNotificationsEnabledForBundle(const std::string &deviceId, bool enabled)
939 {
940     return ERR_INVALID_OPERATION;
941 }
942 
SetNotificationsEnabledForAllBundles(const std::string & deviceId,bool enabled)943 ErrCode AdvancedNotificationService::SetNotificationsEnabledForAllBundles(const std::string &deviceId, bool enabled)
944 {
945     ANS_LOGD("%{public}s", __FUNCTION__);
946 
947     bool isSubsystem = AccessTokenHelper::VerifyNativeToken(IPCSkeleton::GetCallingTokenID());
948     if (!isSubsystem && !AccessTokenHelper::IsSystemApp()) {
949         ANS_LOGD("VerifyNativeToken and IsSystemApp is false.");
950         return ERR_ANS_NON_SYSTEM_APP;
951     }
952 
953     if (!AccessTokenHelper::CheckPermission(OHOS_PERMISSION_NOTIFICATION_CONTROLLER)) {
954         return ERR_ANS_PERMISSION_DENIED;
955     }
956 
957     int32_t userId = SUBSCRIBE_USER_INIT;
958     if (OsAccountManagerHelper::GetInstance().GetCurrentActiveUserId(userId) != ERR_OK) {
959         return ERR_ANS_GET_ACTIVE_USER_FAILED;
960     }
961 
962     if (notificationSvrQueue_ == nullptr) {
963         ANS_LOGE("Serial queue is invalidity.");
964         return ERR_ANS_INVALID_PARAM;
965     }
966     ErrCode result = ERR_OK;
967     ffrt::task_handle handler = notificationSvrQueue_->submit_h(std::bind([&]() {
968         ANS_LOGD("ffrt enter!");
969         if (deviceId.empty()) {
970             // Local device
971             result = NotificationPreferences::GetInstance()->SetNotificationsEnabled(userId, enabled);
972         } else {
973             // Remote device
974         }
975     }));
976     notificationSvrQueue_->wait(handler);
977     return result;
978 }
979 
SetNotificationsEnabledForSpecialBundle(const std::string & deviceId,const sptr<NotificationBundleOption> & bundleOption,bool enabled)980 ErrCode AdvancedNotificationService::SetNotificationsEnabledForSpecialBundle(
981     const std::string &deviceId, const sptr<NotificationBundleOption> &bundleOption, bool enabled)
982 {
983     HITRACE_METER_NAME(HITRACE_TAG_NOTIFICATION, __PRETTY_FUNCTION__);
984     ANS_LOGD("%{public}s", __FUNCTION__);
985     if (bundleOption == nullptr) {
986         ANS_LOGE("BundleOption is null.");
987         return ERR_ANS_INVALID_BUNDLE;
988     }
989 
990     HaMetaMessage message = HaMetaMessage(EventSceneId::SCENE_8, EventBranchId::BRANCH_4);
991     message.Message(bundleOption->GetBundleName() + "_" + std::to_string(bundleOption->GetUid()) +
992             " enabled:" + std::to_string(enabled) +
993             " deviceId:" + deviceId);
994     bool isSubsystem = AccessTokenHelper::VerifyNativeToken(IPCSkeleton::GetCallingTokenID());
995     if (!isSubsystem && !AccessTokenHelper::IsSystemApp()) {
996         ANS_LOGE("IsSystemApp is false.");
997         message.ErrorCode(ERR_ANS_NON_SYSTEM_APP).Append(" Not SystemApp");
998         NotificationAnalyticsUtil::ReportModifyEvent(message);
999         return ERR_ANS_NON_SYSTEM_APP;
1000     }
1001 
1002     int32_t callingUid = IPCSkeleton::GetCallingUid();
1003     if (callingUid != ANS_UID && !AccessTokenHelper::CheckPermission(OHOS_PERMISSION_NOTIFICATION_CONTROLLER)) {
1004         ANS_LOGE("Permission Denied.");
1005         message.ErrorCode(ERR_ANS_PERMISSION_DENIED).Append(" Permission Denied");
1006         NotificationAnalyticsUtil::ReportModifyEvent(message);
1007         return ERR_ANS_PERMISSION_DENIED;
1008     }
1009 
1010     sptr<NotificationBundleOption> bundle = GenerateValidBundleOption(bundleOption);
1011     if (bundle == nullptr) {
1012         message.ErrorCode(ERR_ANS_INVALID_BUNDLE).Append(" Bundle is nullptr.");
1013         NotificationAnalyticsUtil::ReportModifyEvent(message);
1014         ANS_LOGE(" Bundle is nullptr.");
1015         return ERR_ANS_INVALID_BUNDLE;
1016     }
1017 
1018     sptr<EnabledNotificationCallbackData> bundleData = new (std::nothrow)
1019         EnabledNotificationCallbackData(bundle->GetBundleName(), bundle->GetUid(), enabled);
1020     if (bundleData == nullptr) {
1021         ANS_LOGE("Failed to create EnabledNotificationCallbackData instance");
1022         return ERR_NO_MEMORY;
1023     }
1024 
1025     ErrCode result = ERR_OK;
1026     if (deviceId.empty()) {
1027         // Local device
1028         result = NotificationPreferences::GetInstance()->SetNotificationsEnabledForBundle(bundle, enabled);
1029         if (result == ERR_OK) {
1030             if (!enabled) {
1031                 result = RemoveAllNotificationsForDisable(bundle);
1032             }
1033             SetSlotFlagsTrustlistsAsBundle(bundle);
1034             NotificationSubscriberManager::GetInstance()->NotifyEnabledNotificationChanged(bundleData);
1035             PublishSlotChangeCommonEvent(bundle);
1036         }
1037     } else {
1038         // Remote device
1039     }
1040 
1041     ANS_LOGI("%{public}s_%{public}d, deviceId: %{public}s, enable: %{public}s, "
1042         "Set notifications enabled for special bundle result: %{public}d", bundleOption->GetBundleName().c_str(),
1043         bundleOption->GetUid(), deviceId.c_str(), std::to_string(enabled).c_str(), result);
1044     message.ErrorCode(result);
1045     NotificationAnalyticsUtil::ReportModifyEvent(message);
1046     SendEnableNotificationHiSysEvent(bundleOption, enabled, result);
1047     return result;
1048 }
1049 
IsAllowedNotify(bool & allowed)1050 ErrCode AdvancedNotificationService::IsAllowedNotify(bool &allowed)
1051 {
1052     ANS_LOGD("%{public}s", __FUNCTION__);
1053 
1054     bool isSubsystem = AccessTokenHelper::VerifyNativeToken(IPCSkeleton::GetCallingTokenID());
1055     if (!isSubsystem && !AccessTokenHelper::IsSystemApp()) {
1056         return ERR_ANS_NON_SYSTEM_APP;
1057     }
1058 
1059     if (!AccessTokenHelper::CheckPermission(OHOS_PERMISSION_NOTIFICATION_CONTROLLER)) {
1060         ANS_LOGD("AccessTokenHelper::CheckPermission is false");
1061         return ERR_ANS_PERMISSION_DENIED;
1062     }
1063 
1064     int32_t userId = SUBSCRIBE_USER_INIT;
1065     if (OsAccountManagerHelper::GetInstance().GetCurrentActiveUserId(userId) != ERR_OK) {
1066         return ERR_ANS_GET_ACTIVE_USER_FAILED;
1067     }
1068 
1069     if (notificationSvrQueue_ == nullptr) {
1070         ANS_LOGE("Serial queue is invalid.");
1071         return ERR_ANS_INVALID_PARAM;
1072     }
1073     ErrCode result = ERR_OK;
1074     ffrt::task_handle handler = notificationSvrQueue_->submit_h(std::bind([&]() {
1075         ANS_LOGD("ffrt enter!");
1076         allowed = false;
1077         result = NotificationPreferences::GetInstance()->GetNotificationsEnabled(userId, allowed);
1078     }));
1079     notificationSvrQueue_->wait(handler);
1080     return result;
1081 }
1082 
IsAllowedNotifySelf(bool & allowed)1083 ErrCode AdvancedNotificationService::IsAllowedNotifySelf(bool &allowed)
1084 {
1085     ANS_LOGD("%{public}s", __FUNCTION__);
1086 
1087     sptr<NotificationBundleOption> bundleOption = GenerateBundleOption();
1088     if (bundleOption == nullptr) {
1089         return ERR_ANS_INVALID_BUNDLE;
1090     }
1091     return IsAllowedNotifySelf(bundleOption, allowed);
1092 }
1093 
CanPopEnableNotificationDialog(const sptr<AnsDialogCallback> & callback,bool & canPop,std::string & bundleName)1094 ErrCode AdvancedNotificationService::CanPopEnableNotificationDialog(
1095     const sptr<AnsDialogCallback> &callback, bool &canPop, std::string &bundleName)
1096 {
1097     ANS_LOGD("%{public}s", __FUNCTION__);
1098     canPop = false;
1099     ErrCode result = ERR_OK;
1100     sptr<NotificationBundleOption> bundleOption = GenerateBundleOption();
1101     if (bundleOption == nullptr) {
1102         ANS_LOGE("bundleOption is nullptr.");
1103         return ERR_ANS_INVALID_BUNDLE;
1104     }
1105     // To get the permission
1106     bool allowedNotify = false;
1107     HaMetaMessage message = HaMetaMessage(EventSceneId::SCENE_2, EventBranchId::BRANCH_2);
1108     message.Message(bundleOption->GetBundleName() + "_" + std::to_string(bundleOption->GetUid()) +
1109         " canPop:" + std::to_string(canPop));
1110     result = IsAllowedNotifySelf(bundleOption, allowedNotify);
1111     if (result != ERR_OK) {
1112         ANS_LOGE("Not allowed Notify self.");
1113         message.ErrorCode(result).Append(" Not Allow");
1114         NotificationAnalyticsUtil::ReportModifyEvent(message);
1115         return ERROR_INTERNAL_ERROR;
1116     }
1117     ANS_LOGI("allowedNotify = %{public}d", allowedNotify);
1118     if (allowedNotify) {
1119         message.ErrorCode(ERR_OK).Append(" Allow success");
1120         NotificationAnalyticsUtil::ReportModifyEvent(message);
1121         return ERR_OK;
1122     }
1123     // Check to see if it has been popover before
1124     bool hasPopped = false;
1125     result = GetHasPoppedDialog(bundleOption, hasPopped);
1126     if (result != ERR_OK) {
1127         ANS_LOGE("Get has popped dialog failed. result: %{public}d", result);
1128         message.ErrorCode(result).Append(" Has popped");
1129         NotificationAnalyticsUtil::ReportModifyEvent(message);
1130         return ERROR_INTERNAL_ERROR;
1131     }
1132     if (hasPopped) {
1133         ANS_LOGE("Has popped is true.");
1134         message.ErrorCode(ERR_ANS_NOT_ALLOWED).Append(" Haspopped true");
1135         NotificationAnalyticsUtil::ReportModifyEvent(message);
1136         return ERR_ANS_NOT_ALLOWED;
1137     }
1138 
1139     if (!CreateDialogManager()) {
1140         ANS_LOGE("Create dialog manager failed.");
1141         message.ErrorCode(ERR_ANS_NOT_ALLOWED).Append(" Create dialog failed");
1142         NotificationAnalyticsUtil::ReportModifyEvent(message);
1143         return ERROR_INTERNAL_ERROR;
1144     }
1145     result = dialogManager_->AddDialogInfo(bundleOption, callback);
1146     if (result != ERR_OK) {
1147         ANS_LOGI("AddDialogInfo result: %{public}d", result);
1148         message.ErrorCode(result).Append(" AddDialogInfo");
1149         NotificationAnalyticsUtil::ReportModifyEvent(message);
1150         return result;
1151     }
1152 
1153     canPop = true;
1154     bundleName = bundleOption->GetBundleName();
1155     ANS_LOGI("%{public}s_%{public}d, canPop: %{public}s, CanPopEnableNotificationDialog result: %{public}d",
1156         bundleOption->GetBundleName().c_str(), bundleOption->GetUid(), std::to_string(canPop).c_str(), result);
1157     message.ErrorCode(result).Append(" CanPopEnableNotificationDialog end");
1158     NotificationAnalyticsUtil::ReportModifyEvent(message);
1159     return ERR_OK;
1160 }
1161 
RemoveEnableNotificationDialog()1162 ErrCode AdvancedNotificationService::RemoveEnableNotificationDialog()
1163 {
1164     ANS_LOGD("%{public}s", __FUNCTION__);
1165     ErrCode result = ERR_OK;
1166     sptr<NotificationBundleOption> bundleOption = GenerateBundleOption();
1167     if (bundleOption == nullptr) {
1168         ANS_LOGE("bundleOption == nullptr");
1169         return ERR_ANS_INVALID_BUNDLE;
1170     }
1171     return RemoveEnableNotificationDialog(bundleOption);
1172 }
1173 
RemoveEnableNotificationDialog(const sptr<NotificationBundleOption> & bundleOption)1174 ErrCode AdvancedNotificationService::RemoveEnableNotificationDialog(const sptr<NotificationBundleOption> &bundleOption)
1175 {
1176     ANS_LOGI("RemoveEnableNotificationDialog  %{public}s, %{public}d",
1177         bundleOption->GetBundleName().c_str(),
1178         bundleOption->GetUid());
1179     if (!CreateDialogManager()) {
1180         return ERROR_INTERNAL_ERROR;
1181     }
1182     std::unique_ptr<NotificationDialogManager::DialogInfo> dialogInfoRemoved = nullptr;
1183     dialogManager_->RemoveDialogInfoByBundleOption(bundleOption, dialogInfoRemoved);
1184     return ERR_OK;
1185 }
1186 
IsAllowedNotifySelf(const sptr<NotificationBundleOption> & bundleOption,bool & allowed)1187 ErrCode AdvancedNotificationService::IsAllowedNotifySelf(const sptr<NotificationBundleOption> &bundleOption,
1188     bool &allowed)
1189 {
1190     ANS_LOGD("%{public}s", __FUNCTION__);
1191     if (bundleOption == nullptr) {
1192         return ERR_ANS_INVALID_BUNDLE;
1193     }
1194 
1195     int32_t userId = SUBSCRIBE_USER_INIT;
1196     if (OsAccountManagerHelper::GetInstance().GetCurrentActiveUserId(userId) != ERR_OK) {
1197         ANS_LOGD("GetActiveUserId is false");
1198         return ERR_ANS_GET_ACTIVE_USER_FAILED;
1199     }
1200 
1201     ErrCode result = ERR_OK;
1202     allowed = false;
1203     result = NotificationPreferences::GetInstance()->GetNotificationsEnabled(userId, allowed);
1204     if (result == ERR_OK && allowed) {
1205         result = NotificationPreferences::GetInstance()->GetNotificationsEnabledForBundle(bundleOption, allowed);
1206         if (result == ERR_ANS_PREFERENCES_NOTIFICATION_BUNDLE_NOT_EXIST) {
1207             SetSlotFlagsTrustlistsAsBundle(bundleOption);
1208             result = ERR_OK;
1209             // FA model app can publish notification without user confirm
1210             allowed = CheckApiCompatibility(bundleOption);
1211             SetDefaultNotificationEnabled(bundleOption, allowed);
1212         }
1213     }
1214     return result;
1215 }
1216 
IsAllowedNotifyForBundle(const sptr<NotificationBundleOption> & bundleOption,bool & allowed)1217 ErrCode AdvancedNotificationService::IsAllowedNotifyForBundle(const sptr<NotificationBundleOption>
1218     &bundleOption, bool &allowed)
1219 {
1220     ANS_LOGD("%{public}s", __FUNCTION__);
1221     if (bundleOption == nullptr) {
1222         return ERR_ANS_INVALID_BUNDLE;
1223     }
1224 
1225     int32_t userId = SUBSCRIBE_USER_INIT;
1226     if (OsAccountManagerHelper::GetInstance().GetCurrentActiveUserId(userId) != ERR_OK) {
1227         ANS_LOGD("GetActiveUserId is false");
1228         return ERR_ANS_GET_ACTIVE_USER_FAILED;
1229     }
1230 
1231     ErrCode result = ERR_OK;
1232     allowed = false;
1233     result = NotificationPreferences::GetInstance()->GetNotificationsEnabled(userId, allowed);
1234     if (result == ERR_OK && allowed) {
1235         result = NotificationPreferences::GetInstance()->GetNotificationsEnabledForBundle(bundleOption, allowed);
1236         if (result == ERR_ANS_PREFERENCES_NOTIFICATION_BUNDLE_NOT_EXIST) {
1237             result = ERR_OK;
1238             // FA model app can publish notification without user confirm
1239             allowed = CheckApiCompatibility(bundleOption);
1240         }
1241     }
1242     return result;
1243 }
1244 
IsSpecialBundleAllowedNotify(const sptr<NotificationBundleOption> & bundleOption,bool & allowed)1245 ErrCode AdvancedNotificationService::IsSpecialBundleAllowedNotify(
1246     const sptr<NotificationBundleOption> &bundleOption, bool &allowed)
1247 {
1248     ANS_LOGD("%{public}s", __FUNCTION__);
1249 
1250     bool isSubsystem = AccessTokenHelper::VerifyNativeToken(IPCSkeleton::GetCallingTokenID());
1251     if (!isSubsystem && !AccessTokenHelper::IsSystemApp()) {
1252         ANS_LOGE("Not system application");
1253         return ERR_ANS_NON_SYSTEM_APP;
1254     }
1255 
1256     int32_t callingUid = IPCSkeleton::GetCallingUid();
1257     if ((callingUid != ANS_UID && callingUid != BROKER_UID)
1258         && !AccessTokenHelper::CheckPermission(OHOS_PERMISSION_NOTIFICATION_CONTROLLER)) {
1259         return ERR_ANS_PERMISSION_DENIED;
1260     }
1261 
1262     sptr<NotificationBundleOption> targetBundle = nullptr;
1263     if (isSubsystem) {
1264         if (bundleOption != nullptr) {
1265             targetBundle = GenerateValidBundleOption(bundleOption);
1266         }
1267     } else {
1268         ErrCode result = GetAppTargetBundle(bundleOption, targetBundle);
1269         if (result != ERR_OK) {
1270             return result;
1271         }
1272     }
1273 
1274     if (targetBundle == nullptr) {
1275         return ERR_ANS_INVALID_BUNDLE;
1276     }
1277 
1278     int32_t userId = SUBSCRIBE_USER_INIT;
1279     if (OsAccountManagerHelper::GetInstance().GetCurrentActiveUserId(userId) != ERR_OK) {
1280         return ERR_ANS_GET_ACTIVE_USER_FAILED;
1281     }
1282 
1283     ErrCode result = ERR_OK;
1284         allowed = false;
1285         result = NotificationPreferences::GetInstance()->GetNotificationsEnabled(userId, allowed);
1286         if (result == ERR_OK && allowed) {
1287             result = NotificationPreferences::GetInstance()->GetNotificationsEnabledForBundle(targetBundle, allowed);
1288             if (result == ERR_ANS_PREFERENCES_NOTIFICATION_BUNDLE_NOT_EXIST) {
1289                 result = ERR_OK;
1290                 allowed = CheckApiCompatibility(targetBundle);
1291                 SetNotificationsEnabledForSpecialBundle("", bundleOption, allowed);
1292             }
1293         }
1294     return result;
1295 }
1296 
PublishContinuousTaskNotification(const sptr<NotificationRequest> & request)1297 ErrCode AdvancedNotificationService::PublishContinuousTaskNotification(const sptr<NotificationRequest> &request)
1298 {
1299     ANS_LOGD("%{public}s", __FUNCTION__);
1300 
1301     bool isSubsystem = AccessTokenHelper::VerifyNativeToken(IPCSkeleton::GetCallingTokenID());
1302     if (!isSubsystem) {
1303         return ERR_ANS_NOT_SYSTEM_SERVICE;
1304     }
1305 
1306     int32_t uid = IPCSkeleton::GetCallingUid();
1307     int32_t userId = SUBSCRIBE_USER_INIT;
1308     OHOS::AccountSA::OsAccountManager::GetOsAccountLocalIdFromUid(uid, userId);
1309     request->SetCreatorUserId(userId);
1310     ANS_LOGD("%{public}s, uid=%{public}d userId=%{public}d", __FUNCTION__, uid, userId);
1311 
1312     if (request->GetCreatorBundleName().empty()) {
1313         request->SetCreatorBundleName(FOUNDATION_BUNDLE_NAME);
1314     }
1315 
1316     if (request->GetOwnerBundleName().empty()) {
1317         request->SetOwnerBundleName(FOUNDATION_BUNDLE_NAME);
1318     }
1319 
1320     sptr<NotificationBundleOption> bundleOption = nullptr;
1321     bundleOption = new (std::nothrow) NotificationBundleOption(std::string(), uid);
1322     if (bundleOption == nullptr) {
1323         ANS_LOGE("Failed to create NotificationBundleOption instance");
1324         return ERR_NO_MEMORY;
1325     }
1326 
1327     ErrCode result = PrepareContinuousTaskNotificationRequest(request, uid);
1328     if (result != ERR_OK) {
1329         return result;
1330     }
1331     request->SetUnremovable(true);
1332     std::shared_ptr<NotificationRecord> record = std::make_shared<NotificationRecord>();
1333     record->request = request;
1334     record->bundleOption = bundleOption;
1335     record->notification = new (std::nothrow) Notification(request);
1336     if (record->notification == nullptr) {
1337         ANS_LOGE("Failed to create Notification instance");
1338         return ERR_NO_MEMORY;
1339     }
1340     record->notification->SetSourceType(NotificationConstant::SourceType::TYPE_CONTINUOUS);
1341 
1342     if (notificationSvrQueue_ == nullptr) {
1343         ANS_LOGE("Serial queue is invalid.");
1344         return ERR_ANS_INVALID_PARAM;
1345     }
1346     ffrt::task_handle handler = notificationSvrQueue_->submit_h(std::bind([&]() {
1347         ANS_LOGD("ffrt enter!");
1348         if (!IsNotificationExists(record->notification->GetKey())) {
1349             AddToNotificationList(record);
1350         } else {
1351             if (record->request->IsAlertOneTime()) {
1352                 CloseAlert(record);
1353             }
1354             UpdateInNotificationList(record);
1355         }
1356 
1357         UpdateRecentNotification(record->notification, false, 0);
1358         sptr<NotificationSortingMap> sortingMap = GenerateSortingMap();
1359         NotificationSubscriberManager::GetInstance()->NotifyConsumed(record->notification, sortingMap);
1360     }));
1361     notificationSvrQueue_->wait(handler);
1362 
1363     return result;
1364 }
1365 
CancelContinuousTaskNotification(const std::string & label,int32_t notificationId)1366 ErrCode AdvancedNotificationService::CancelContinuousTaskNotification(const std::string &label, int32_t notificationId)
1367 {
1368     ANS_LOGD("%{public}s", __FUNCTION__);
1369 
1370     bool isSubsystem = AccessTokenHelper::VerifyNativeToken(IPCSkeleton::GetCallingTokenID());
1371     if (!isSubsystem) {
1372         return ERR_ANS_NOT_SYSTEM_SERVICE;
1373     }
1374 
1375     if (notificationSvrQueue_ == nullptr) {
1376         ANS_LOGE("Serial queue is invalid.");
1377         return ERR_ANS_INVALID_PARAM;
1378     }
1379     int32_t uid = IPCSkeleton::GetCallingUid();
1380     ErrCode result = ERR_OK;
1381     ffrt::task_handle handler = notificationSvrQueue_->submit_h(std::bind([&]() {
1382         ANS_LOGD("ffrt enter!");
1383         sptr<Notification> notification = nullptr;
1384         for (auto record : notificationList_) {
1385             if ((record->bundleOption->GetBundleName().empty()) && (record->bundleOption->GetUid() == uid) &&
1386                 (record->notification->GetId() == notificationId) && (record->notification->GetLabel() == label)) {
1387                 notification = record->notification;
1388                 notificationList_.remove(record);
1389                 result = ERR_OK;
1390                 break;
1391             }
1392         }
1393         if (notification != nullptr) {
1394             int32_t reason = NotificationConstant::APP_CANCEL_REASON_DELETE;
1395             UpdateRecentNotification(notification, true, reason);
1396             CancelTimer(notification->GetAutoDeletedTimer());
1397             NotificationSubscriberManager::GetInstance()->NotifyCanceled(notification, nullptr, reason);
1398         }
1399     }));
1400     notificationSvrQueue_->wait(handler);
1401     return result;
1402 }
1403 
RemoveSystemLiveViewNotifications(const std::string & bundleName,const int32_t uid)1404 ErrCode AdvancedNotificationService::RemoveSystemLiveViewNotifications(
1405     const std::string& bundleName, const int32_t uid)
1406 {
1407     std::vector<std::shared_ptr<NotificationRecord>> recordList;
1408     if (notificationSvrQueue_ == nullptr) {
1409         ANS_LOGE("NotificationSvrQueue is nullptr");
1410         return ERR_ANS_INVALID_PARAM;
1411     }
1412     ErrCode result = ERR_OK;
1413     ffrt::task_handle handler = notificationSvrQueue_->submit_h(std::bind([&]() {
1414         LivePublishProcess::GetInstance()->EraseLiveViewSubsciber(uid);
1415         GetTargetRecordList(uid,  NotificationConstant::SlotType::LIVE_VIEW,
1416             NotificationContent::Type::LOCAL_LIVE_VIEW, recordList);
1417         GetCommonTargetRecordList(uid,  NotificationConstant::SlotType::LIVE_VIEW,
1418             NotificationContent::Type::LIVE_VIEW, recordList);
1419         if (recordList.size() == 0) {
1420             ANS_LOGE("Get Target record list fail.");
1421             result = ERR_ANS_NOTIFICATION_NOT_EXISTS;
1422             return;
1423         }
1424         result = RemoveNotificationFromRecordList(recordList);
1425     }));
1426     notificationSvrQueue_->wait(handler);
1427     return result;
1428 }
1429 
RemoveSystemLiveViewNotificationsOfSa(int32_t uid)1430 ErrCode AdvancedNotificationService::RemoveSystemLiveViewNotificationsOfSa(int32_t uid)
1431 {
1432     {
1433         std::lock_guard<std::mutex> lock(delayNotificationMutext_);
1434         for (auto iter = delayNotificationList_.begin(); iter != delayNotificationList_.end();) {
1435             if ((*iter).first->notification->GetNotificationRequest().GetCreatorUid() == uid &&
1436                 (*iter).first->notification->GetNotificationRequest().IsInProgress()) {
1437                 CancelTimer((*iter).second);
1438                 iter = delayNotificationList_.erase(iter);
1439             } else {
1440                 iter++;
1441             }
1442         }
1443     }
1444 
1445     ErrCode result = ERR_OK;
1446     ffrt::task_handle handler = notificationSvrQueue_->submit_h(std::bind([&]() {
1447         LivePublishProcess::GetInstance()->EraseLiveViewSubsciber(uid);
1448         std::vector<std::shared_ptr<NotificationRecord>> recordList;
1449         for (auto item : notificationList_) {
1450             if (item->notification->GetNotificationRequest().GetCreatorUid() == uid &&
1451                 item->notification->GetNotificationRequest().IsInProgress()) {
1452                 recordList.emplace_back(item);
1453             }
1454         }
1455         if (!recordList.empty()) {
1456             result = RemoveNotificationFromRecordList(recordList);
1457         }
1458     }));
1459     notificationSvrQueue_->wait(handler);
1460     return result;
1461 }
1462 
TriggerLocalLiveView(const sptr<NotificationBundleOption> & bundleOption,const int32_t notificationId,const sptr<NotificationButtonOption> & buttonOption)1463 ErrCode AdvancedNotificationService::TriggerLocalLiveView(const sptr<NotificationBundleOption> &bundleOption,
1464     const int32_t notificationId, const sptr<NotificationButtonOption> &buttonOption)
1465 {
1466     HITRACE_METER_NAME(HITRACE_TAG_NOTIFICATION, __PRETTY_FUNCTION__);
1467     ANS_LOGD("%{public}s", __FUNCTION__);
1468 
1469     bool isSubsystem = AccessTokenHelper::VerifyNativeToken(IPCSkeleton::GetCallingTokenID());
1470     if (!isSubsystem && !AccessTokenHelper::IsSystemApp()) {
1471         return ERR_ANS_NON_SYSTEM_APP;
1472     }
1473 
1474     if (!AccessTokenHelper::CheckPermission(OHOS_PERMISSION_NOTIFICATION_CONTROLLER)) {
1475         ANS_LOGD("AccessTokenHelper::CheckPermission is bogus.");
1476         return ERR_ANS_PERMISSION_DENIED;
1477     }
1478 
1479     sptr<NotificationBundleOption> bundle = GenerateValidBundleOption(bundleOption);
1480     if (bundle == nullptr) {
1481         return ERR_ANS_INVALID_BUNDLE;
1482     }
1483 
1484     ErrCode result = ERR_ANS_NOTIFICATION_NOT_EXISTS;
1485     ffrt::task_handle handler = notificationSvrQueue_->submit_h(std::bind([&]() {
1486         ANS_LOGD("ffrt enter!");
1487         sptr<Notification> notification = nullptr;
1488 
1489         for (auto record : notificationList_) {
1490             if (record->request->GetAgentBundle() != nullptr) {
1491                 if ((record->request->GetAgentBundle()->GetBundleName() == bundle->GetBundleName()) &&
1492                     (record->request->GetAgentBundle()->GetUid() == bundle->GetUid()) &&
1493                     (record->notification->GetId() == notificationId)) {
1494                     notification = record->notification;
1495                     result = ERR_OK;
1496                     break;
1497                 }
1498             } else {
1499                 if ((record->bundleOption->GetBundleName() == bundle->GetBundleName()) &&
1500                     (record->bundleOption->GetUid() == bundle->GetUid()) &&
1501                     (record->notification->GetId() == notificationId)) {
1502                     notification = record->notification;
1503                     result = ERR_OK;
1504                     break;
1505                 }
1506             }
1507         }
1508 
1509         if (notification != nullptr) {
1510             NotificationLocalLiveViewSubscriberManager::GetInstance()->NotifyTriggerResponse(notification,
1511                 buttonOption);
1512         }
1513     }));
1514     notificationSvrQueue_->wait(handler);
1515     return result;
1516 }
1517 
RemoveNotification(const sptr<NotificationBundleOption> & bundleOption,int32_t notificationId,const std::string & label,int32_t removeReason)1518 ErrCode AdvancedNotificationService::RemoveNotification(const sptr<NotificationBundleOption> &bundleOption,
1519     int32_t notificationId, const std::string &label, int32_t removeReason)
1520 {
1521     HITRACE_METER_NAME(HITRACE_TAG_NOTIFICATION, __PRETTY_FUNCTION__);
1522     ANS_LOGD("%{public}s", __FUNCTION__);
1523 
1524     bool isSubsystem = AccessTokenHelper::VerifyNativeToken(IPCSkeleton::GetCallingTokenID());
1525     if (!isSubsystem && !AccessTokenHelper::IsSystemApp()) {
1526         std::string message = "not systemApp.";
1527         OHOS::Notification::HaMetaMessage haMetaMessage = HaMetaMessage(4, 4)
1528             .ErrorCode(ERR_ANS_NON_SYSTEM_APP).NotificationId(notificationId);
1529         ReportDeleteFailedEventPush(haMetaMessage, removeReason, message);
1530         ANS_LOGE("%{public}s", message.c_str());
1531         return ERR_ANS_NON_SYSTEM_APP;
1532     }
1533 
1534     int32_t callingUid = IPCSkeleton::GetCallingUid();
1535     if (callingUid != BROKER_UID && !AccessTokenHelper::CheckPermission(OHOS_PERMISSION_NOTIFICATION_CONTROLLER)) {
1536         std::string message = "no acl controller permission.";
1537         OHOS::Notification::HaMetaMessage haMetaMessage = HaMetaMessage(4, 5)
1538             .ErrorCode(ERR_ANS_PERMISSION_DENIED).NotificationId(notificationId);
1539         ReportDeleteFailedEventPush(haMetaMessage, removeReason, message);
1540         ANS_LOGE("%{public}s", message.c_str());
1541         return ERR_ANS_PERMISSION_DENIED;
1542     }
1543 
1544     sptr<NotificationBundleOption> bundle = GenerateValidBundleOption(bundleOption);
1545     if (bundle == nullptr) {
1546         return ERR_ANS_INVALID_BUNDLE;
1547     }
1548 
1549     if (notificationSvrQueue_ == nullptr) {
1550         std::string message = "NotificationSvrQueue_ is null.";
1551         ANS_LOGE("%{public}s", message.c_str());
1552         return ERR_ANS_INVALID_PARAM;
1553     }
1554     ErrCode result = ERR_ANS_NOTIFICATION_NOT_EXISTS;
1555     ffrt::task_handle handler = notificationSvrQueue_->submit_h(std::bind([&]() {
1556         ANS_LOGD("ffrt enter!");
1557         sptr<Notification> notification = nullptr;
1558         sptr<NotificationRequest> notificationRequest = nullptr;
1559 
1560 #ifdef DISTRIBUTED_NOTIFICATION_SUPPORTED
1561         std::string deviceId;
1562         std::string bundleName;
1563 #endif
1564         for (auto record : notificationList_) {
1565             if ((record->bundleOption->GetBundleName() == bundle->GetBundleName()) &&
1566                 (record->bundleOption->GetUid() == bundle->GetUid()) &&
1567 #ifdef DISTRIBUTED_NOTIFICATION_SUPPORTED
1568                 (record->deviceId.empty()) &&
1569 #endif
1570                 (record->notification->GetId() == notificationId) && (record->notification->GetLabel() == label)) {
1571                 if (!record->notification->IsRemoveAllowed()) {
1572                     result = ERR_ANS_NOTIFICATION_IS_UNALLOWED_REMOVEALLOWED;
1573                     break;
1574                 }
1575 #ifdef DISTRIBUTED_NOTIFICATION_SUPPORTED
1576                 deviceId = record->deviceId;
1577                 bundleName = record->bundleName;
1578 #endif
1579                 notification = record->notification;
1580                 notificationRequest = record->request;
1581 
1582                 if (removeReason != NotificationConstant::CLICK_REASON_DELETE) {
1583                     ProcForDeleteLiveView(record);
1584                 }
1585 
1586                 notificationList_.remove(record);
1587                 result = ERR_OK;
1588                 break;
1589             }
1590         }
1591 
1592         if (notification != nullptr) {
1593             UpdateRecentNotification(notification, true, removeReason);
1594             CancelTimer(notification->GetAutoDeletedTimer());
1595             NotificationSubscriberManager::GetInstance()->NotifyCanceled(notification, nullptr, removeReason);
1596 #ifdef DISTRIBUTED_NOTIFICATION_SUPPORTED
1597             DoDistributedDelete(deviceId, bundleName, notification);
1598 #endif
1599         }
1600         if (removeReason != NotificationConstant::CLICK_REASON_DELETE) {
1601             TriggerRemoveWantAgent(notificationRequest);
1602         }
1603     }));
1604     notificationSvrQueue_->wait(handler);
1605     if (result != ERR_OK) {
1606         std::string message = "remove notificaiton error";
1607         ANS_LOGE("%{public}s", message.c_str());
1608     }
1609     SendRemoveHiSysEvent(notificationId, label, bundleOption, result);
1610     return result;
1611 }
1612 
RemoveAllNotificationsForDisable(const sptr<NotificationBundleOption> & bundleOption)1613 ErrCode AdvancedNotificationService::RemoveAllNotificationsForDisable(
1614     const sptr<NotificationBundleOption> &bundleOption)
1615 {
1616     return RemoveAllNotificationsInner(bundleOption, NotificationConstant::DISABLE_NOTIFICATION_REASON_DELETE);
1617 }
1618 
RemoveAllNotifications(const sptr<NotificationBundleOption> & bundleOption)1619 ErrCode AdvancedNotificationService::RemoveAllNotifications(const sptr<NotificationBundleOption> &bundleOption)
1620 {
1621     return RemoveAllNotificationsInner(bundleOption, NotificationConstant::APP_REMOVE_ALL_REASON_DELETE);
1622 }
1623 
RemoveAllNotificationsInner(const sptr<NotificationBundleOption> & bundleOption,int32_t reason)1624 ErrCode AdvancedNotificationService::RemoveAllNotificationsInner(const sptr<NotificationBundleOption> &bundleOption,
1625     int32_t reason)
1626 {
1627     HITRACE_METER_NAME(HITRACE_TAG_NOTIFICATION, __PRETTY_FUNCTION__);
1628     ANS_LOGD("%{public}s", __FUNCTION__);
1629 
1630     bool isSubsystem = AccessTokenHelper::VerifyNativeToken(IPCSkeleton::GetCallingTokenID());
1631     if (!isSubsystem && !AccessTokenHelper::IsSystemApp()) {
1632         std::string message = "not system app.";
1633         OHOS::Notification::HaMetaMessage haMetaMessage = HaMetaMessage(6, 1)
1634             .ErrorCode(ERR_ANS_NON_SYSTEM_APP);
1635         ReportDeleteFailedEventPush(haMetaMessage, reason, message);
1636         ANS_LOGE("%{public}s", message.c_str());
1637         return ERR_ANS_NON_SYSTEM_APP;
1638     }
1639 
1640     int32_t callingUid = IPCSkeleton::GetCallingUid();
1641     if (callingUid != ANS_UID && !AccessTokenHelper::CheckPermission(OHOS_PERMISSION_NOTIFICATION_CONTROLLER)) {
1642         std::string message = "no acl permission.";
1643         OHOS::Notification::HaMetaMessage haMetaMessage = HaMetaMessage(6, 2)
1644             .ErrorCode(ERR_ANS_PERMISSION_DENIED);
1645         ReportDeleteFailedEventPush(haMetaMessage, reason, message);
1646         ANS_LOGE("%{public}s", message.c_str());
1647         return ERR_ANS_PERMISSION_DENIED;
1648     }
1649 
1650     sptr<NotificationBundleOption> bundle = GenerateValidBundleOption(bundleOption);
1651     if (bundle == nullptr) {
1652         std::string message = "budle is nullptr.";
1653         OHOS::Notification::HaMetaMessage haMetaMessage = HaMetaMessage(6, 3)
1654             .ErrorCode(ERR_ANS_INVALID_BUNDLE);
1655         ReportDeleteFailedEventPush(haMetaMessage, reason, message);
1656         ANS_LOGE("%{public}s", message.c_str());
1657         return ERR_ANS_INVALID_BUNDLE;
1658     }
1659 
1660     if (notificationSvrQueue_ == nullptr) {
1661         std::string message = "Serial queue is nullptr.";
1662         ANS_LOGE("%{public}s", message.c_str());
1663         return ERR_ANS_INVALID_PARAM;
1664     }
1665     ffrt::task_handle handler = notificationSvrQueue_->submit_h(std::bind([&]() {
1666         std::vector<std::shared_ptr<NotificationRecord>> removeList;
1667         ANS_LOGD("ffrt enter!");
1668         for (auto record : notificationList_) {
1669             bool isAllowedNotification = true;
1670             if (IsAllowedNotifyForBundle(bundleOption, isAllowedNotification) != ERR_OK) {
1671                 ANSR_LOGW("The application does not request enable notification.");
1672             }
1673             if (!record->notification->IsRemoveAllowed() && isAllowedNotification) {
1674                 ANS_LOGI("BatchRemove-FILTER-RemoveNotAllowed-%{public}s", record->notification->GetKey().c_str());
1675                 continue;
1676             }
1677             if (record->slot != nullptr) {
1678                 if (record->slot->GetForceControl() && record->slot->GetEnable()) {
1679                     ANS_LOGI("BatchRemove-FILTER-ForceControl-%{public}s", record->notification->GetKey().c_str());
1680                     continue;
1681                 }
1682             }
1683             if ((record->bundleOption->GetBundleName() == bundle->GetBundleName()) &&
1684                 (record->bundleOption->GetUid() == bundle->GetUid())
1685 #ifdef DISTRIBUTED_NOTIFICATION_SUPPORTED
1686                 && record->deviceId.empty()
1687 #endif
1688                 ) {
1689                 auto notificationRequest = record->request;
1690                 if (!BundleManagerHelper::GetInstance()->IsSystemApp(bundle->GetUid()) &&
1691                     notificationRequest->IsSystemLiveView()) {
1692                     auto localLiveviewContent = std::static_pointer_cast<NotificationLocalLiveViewContent>(
1693                         notificationRequest->GetContent()->GetNotificationContent());
1694                     if (localLiveviewContent->GetType() == 0) {
1695                         continue;
1696                     }
1697                 }
1698                 ProcForDeleteLiveView(record);
1699                 removeList.push_back(record);
1700             }
1701         }
1702 
1703         std::vector<sptr<Notification>> notifications;
1704         std::vector<uint64_t> timerIds;
1705         for (auto record : removeList) {
1706             notificationList_.remove(record);
1707             if (record->notification != nullptr) {
1708                 ANS_LOGD("record->notification is not nullptr.");
1709                 UpdateRecentNotification(record->notification, true, reason);
1710                 notifications.emplace_back(record->notification);
1711                 timerIds.emplace_back(record->notification->GetAutoDeletedTimer());
1712 #ifdef DISTRIBUTED_NOTIFICATION_SUPPORTED
1713                 DoDistributedDelete(record->deviceId, record->bundleName, record->notification);
1714 #endif
1715             }
1716             if (notifications.size() >= MAX_CANCELED_PARCELABLE_VECTOR_NUM) {
1717                 SendNotificationsOnCanceled(notifications, nullptr, reason);
1718             }
1719 
1720             TriggerRemoveWantAgent(record->request);
1721         }
1722 
1723         if (!notifications.empty()) {
1724             NotificationSubscriberManager::GetInstance()->BatchNotifyCanceled(notifications, nullptr, reason);
1725         }
1726         BatchCancelTimer(timerIds);
1727     }));
1728     notificationSvrQueue_->wait(handler);
1729 
1730     return ERR_OK;
1731 }
1732 
RemoveNotifications(const std::vector<std::string> & keys,int32_t removeReason)1733 ErrCode AdvancedNotificationService::RemoveNotifications(
1734     const std::vector<std::string> &keys, int32_t removeReason)
1735 {
1736     HITRACE_METER_NAME(HITRACE_TAG_NOTIFICATION, __PRETTY_FUNCTION__);
1737     ANS_LOGD("enter");
1738 
1739     bool isSubsystem = AccessTokenHelper::VerifyNativeToken(IPCSkeleton::GetCallingTokenID());
1740     if (!isSubsystem && !AccessTokenHelper::IsSystemApp()) {
1741         return ERR_ANS_NON_SYSTEM_APP;
1742     }
1743 
1744     if (!AccessTokenHelper::CheckPermission(OHOS_PERMISSION_NOTIFICATION_CONTROLLER)) {
1745         return ERR_ANS_PERMISSION_DENIED;
1746     }
1747 
1748     if (notificationSvrQueue_ == nullptr) {
1749         ANS_LOGE("NotificationSvrQueue is nullptr.");
1750         return ERR_ANS_INVALID_PARAM;
1751     }
1752     ffrt::task_handle handler = notificationSvrQueue_->submit_h(std::bind([&]() {
1753         std::vector<sptr<Notification>> notifications;
1754         std::vector<uint64_t> timerIds;
1755         for (auto key : keys) {
1756             sptr<Notification> notification = nullptr;
1757 #ifdef DISTRIBUTED_NOTIFICATION_SUPPORTED
1758             std::string deviceId;
1759             std::string bundleName;
1760             GetDistributedInfo(key, deviceId, bundleName);
1761 #endif
1762             ErrCode result = RemoveFromNotificationList(key, notification, false, removeReason);
1763             if (result != ERR_OK) {
1764                 continue;
1765             }
1766             if (notification != nullptr) {
1767                 UpdateRecentNotification(notification, true, removeReason);
1768                 notifications.emplace_back(notification);
1769                 timerIds.emplace_back(notification->GetAutoDeletedTimer());
1770 #ifdef DISTRIBUTED_NOTIFICATION_SUPPORTED
1771                 DoDistributedDelete(deviceId, bundleName, notification);
1772 #endif
1773             }
1774             if (notifications.size() >= MAX_CANCELED_PARCELABLE_VECTOR_NUM) {
1775                 std::vector<sptr<Notification>> currNotificationList = notifications;
1776                 NotificationSubscriberManager::GetInstance()->BatchNotifyCanceled(
1777                     currNotificationList, nullptr, removeReason);
1778                 notifications.clear();
1779             }
1780         }
1781 
1782         if (!notifications.empty()) {
1783             NotificationSubscriberManager::GetInstance()->BatchNotifyCanceled(notifications, nullptr, removeReason);
1784         }
1785         BatchCancelTimer(timerIds);
1786     }));
1787     notificationSvrQueue_->wait(handler);
1788 
1789     return ERR_OK;
1790 }
1791 
RemoveNotificationBySlot(const sptr<NotificationBundleOption> & bundleOption,const sptr<NotificationSlot> & slot,const int reason)1792 ErrCode AdvancedNotificationService::RemoveNotificationBySlot(const sptr<NotificationBundleOption> &bundleOption,
1793     const sptr<NotificationSlot> &slot, const int reason)
1794 {
1795     HITRACE_METER_NAME(HITRACE_TAG_NOTIFICATION, __PRETTY_FUNCTION__);
1796     ANS_LOGD("%{public}s", __FUNCTION__);
1797 
1798     bool isSubsystem = AccessTokenHelper::VerifyNativeToken(IPCSkeleton::GetCallingTokenID());
1799     if (!isSubsystem && !AccessTokenHelper::IsSystemApp()) {
1800         return ERR_ANS_NON_SYSTEM_APP;
1801     }
1802 
1803     sptr<NotificationBundleOption> bundle = GenerateValidBundleOption(bundleOption);
1804     if (bundle == nullptr) {
1805         return ERR_ANS_INVALID_BUNDLE;
1806     }
1807 
1808     ErrCode result = ERR_ANS_NOTIFICATION_NOT_EXISTS;
1809     sptr<Notification> notification = nullptr;
1810     sptr<NotificationRequest> notificationRequest = nullptr;
1811 
1812     for (std::list<std::shared_ptr<NotificationRecord>>::iterator it = notificationList_.begin();
1813         it != notificationList_.end();) {
1814         if (((*it)->bundleOption->GetBundleName() == bundle->GetBundleName()) &&
1815             ((*it)->bundleOption->GetUid() == bundle->GetUid()) &&
1816             ((*it)->request->GetSlotType() == slot->GetType())) {
1817             if (((*it)->request->GetAgentBundle() != nullptr && (*it)->request->IsSystemLiveView())) {
1818                 ANS_LOGI("Agent systemliveview no need remove.");
1819                 it++;
1820                 continue;
1821             }
1822             notification = (*it)->notification;
1823             notificationRequest = (*it)->request;
1824 
1825             ProcForDeleteLiveView(*it);
1826             it = notificationList_.erase(it);
1827 
1828             if (notification != nullptr) {
1829                 UpdateRecentNotification(notification, true, NotificationConstant::DISABLE_SLOT_REASON_DELETE);
1830                 CancelTimer(notification->GetAutoDeletedTimer());
1831                 NotificationSubscriberManager::GetInstance()->NotifyCanceled(notification, nullptr,
1832                     NotificationConstant::DISABLE_SLOT_REASON_DELETE);
1833             }
1834 
1835             TriggerRemoveWantAgent(notificationRequest);
1836             result = ERR_OK;
1837         } else {
1838             it++;
1839         }
1840     }
1841     return result;
1842 }
1843 
IsNeedSilentInDoNotDisturbMode(const std::string & phoneNumber,int32_t callerType)1844 ErrCode AdvancedNotificationService::IsNeedSilentInDoNotDisturbMode(
1845     const std::string &phoneNumber, int32_t callerType)
1846 {
1847     ANS_LOGD("%{public}s", __FUNCTION__);
1848 
1849     int32_t callingUid = IPCSkeleton::GetCallingUid();
1850     if (callingUid != ANS_UID && !AccessTokenHelper::CheckPermission(OHOS_PERMISSION_NOTIFICATION_CONTROLLER)) {
1851         ANS_LOGD("IsNeedSilentInDoNotDisturbMode CheckPermission failed.");
1852         return ERR_ANS_PERMISSION_DENIED;
1853     }
1854 
1855     int32_t userId = SUBSCRIBE_USER_INIT;
1856     if (OsAccountManagerHelper::GetInstance().GetCurrentActiveUserId(userId) != ERR_OK) {
1857         ANS_LOGD("GetActiveUserId is false");
1858         return ERR_ANS_GET_ACTIVE_USER_FAILED;
1859     }
1860     return CheckNeedSilent(phoneNumber, callerType, userId);
1861 }
1862 
CheckNeedSilent(const std::string & phoneNumber,int32_t callerType,int32_t userId)1863 ErrCode AdvancedNotificationService::CheckNeedSilent(
1864     const std::string &phoneNumber, int32_t callerType, int32_t userId)
1865 {
1866     auto datashareHelper = DelayedSingleton<AdvancedDatashareHelper>::GetInstance();
1867     if (datashareHelper == nullptr) {
1868         ANS_LOGE("The data share helper is nullptr.");
1869         return -1;
1870     }
1871 
1872     int isNeedSilent = 0;
1873     std::string policy;
1874     Uri policyUri(datashareHelper->GetFocusModeCallPolicyUri(userId));
1875     bool ret = datashareHelper->Query(policyUri, KEY_FOCUS_MODE_CALL_MESSAGE_POLICY, policy);
1876     if (!ret) {
1877         ANS_LOGE("Query focus mode call message policy fail.");
1878         return -1;
1879     }
1880     std::string repeat_call;
1881     Uri repeatUri(datashareHelper->GetFocusModeRepeatCallUri(userId));
1882     bool repeat_ret = datashareHelper->Query(repeatUri, KEY_FOCUS_MODE_REPEAT_CALLERS_ENABLE, repeat_call);
1883     if (!repeat_ret) {
1884         ANS_LOGE("Query focus mode repeat callers enable fail.");
1885     }
1886     ANS_LOGI("IsNeedSilent: policy: %{public}s, repeat: %{public}s, callerType: %{public}d",
1887         policy.c_str(), repeat_call.c_str(), callerType);
1888     if (repeat_call == FOCUS_MODE_REPEAT_CALLERS_ENABLE &&
1889         callerType == 0 && atoi(policy.c_str()) != ContactPolicy::ALLOW_EVERYONE) {
1890         if (datashareHelper->isRepeatCall(phoneNumber)) {
1891             return 1;
1892         }
1893     }
1894     switch (atoi(policy.c_str())) {
1895         case ContactPolicy::FORBID_EVERYONE:
1896             break;
1897         case ContactPolicy::ALLOW_EVERYONE:
1898             isNeedSilent = 1;
1899             break;
1900         case ContactPolicy::ALLOW_EXISTING_CONTACTS:
1901         case ContactPolicy::ALLOW_FAVORITE_CONTACTS:
1902         case ContactPolicy::ALLOW_SPECIFIED_CONTACTS:
1903             Uri uri(CONTACT_DATA);
1904             isNeedSilent = datashareHelper->QueryContact(uri, phoneNumber, policy);
1905             break;
1906     }
1907     ANS_LOGI("IsNeedSilentInDoNotDisturbMode: %{public}d", isNeedSilent);
1908     return isNeedSilent;
1909 }
1910 
CancelGroup(const std::string & groupName,const std::string & instanceKey)1911 ErrCode AdvancedNotificationService::CancelGroup(const std::string &groupName, const std::string &instanceKey)
1912 {
1913     ANS_LOGD("%{public}s", __FUNCTION__);
1914 
1915     int32_t reason = NotificationConstant::APP_CANCEL_GROPU_REASON_DELETE;
1916     if (groupName.empty()) {
1917         std::string message = "groupName empty.";
1918         OHOS::Notification::HaMetaMessage haMetaMessage = HaMetaMessage(3, 1)
1919             .ErrorCode(ERR_ANS_INVALID_PARAM);
1920         ReportDeleteFailedEventPush(haMetaMessage, reason, message);
1921         ANS_LOGE("%{public}s", message.c_str());
1922         return ERR_ANS_INVALID_PARAM;
1923     }
1924 
1925     sptr<NotificationBundleOption> bundleOption = GenerateBundleOption();
1926     if (bundleOption == nullptr) {
1927         std::string message = "bundle is nullptr.";
1928         OHOS::Notification::HaMetaMessage haMetaMessage = HaMetaMessage(3, 2)
1929             .ErrorCode(ERR_ANS_INVALID_BUNDLE);
1930         ReportDeleteFailedEventPush(haMetaMessage, reason, message);
1931         ANS_LOGE("%{public}s", message.c_str());
1932         return ERR_ANS_INVALID_BUNDLE;
1933     }
1934     bundleOption->SetAppInstanceKey(instanceKey);
1935 
1936     if (notificationSvrQueue_ == nullptr) {
1937         std::string message = "Serial queue is invalid.";
1938         ANS_LOGE("%{public}s", message.c_str());
1939         return ERR_ANS_INVALID_PARAM;
1940     }
1941 
1942     ExcuteCancelGroupCancel(bundleOption, groupName, reason);
1943     return ERR_OK;
1944 }
1945 
ExcuteCancelGroupCancel(const sptr<NotificationBundleOption> & bundleOption,const std::string & groupName,const int32_t reason)1946 void AdvancedNotificationService::ExcuteCancelGroupCancel(
1947     const sptr<NotificationBundleOption>& bundleOption,
1948     const std::string &groupName, const int32_t reason)
1949 {
1950     ffrt::task_handle handler = notificationSvrQueue_->submit_h(std::bind([&]() {
1951         ANS_LOGD("ffrt enter!");
1952         std::vector<std::shared_ptr<NotificationRecord>> removeList;
1953         for (auto record : notificationList_) {
1954             ANS_LOGD("ExcuteCancelGroupCancel instanceKey(%{public}s, %{public}s).",
1955                 record->notification->GetInstanceKey().c_str(), bundleOption->GetAppInstanceKey().c_str());
1956             if ((record->bundleOption->GetBundleName() == bundleOption->GetBundleName()) &&
1957                 (record->bundleOption->GetUid() == bundleOption->GetUid()) &&
1958                 (record->notification->GetInstanceKey() == bundleOption->GetAppInstanceKey()) &&
1959 #ifdef DISTRIBUTED_NOTIFICATION_SUPPORTED
1960                 record->deviceId.empty() &&
1961 #endif
1962                 (record->request->GetGroupName() == groupName)) {
1963                 removeList.push_back(record);
1964             }
1965         }
1966 
1967         std::vector<sptr<Notification>> notifications;
1968         std::vector<uint64_t> timerIds;
1969         for (auto record : removeList) {
1970             notificationList_.remove(record);
1971             if (record->notification != nullptr) {
1972                 UpdateRecentNotification(record->notification, true, reason);
1973                 notifications.emplace_back(record->notification);
1974                 timerIds.emplace_back(record->notification->GetAutoDeletedTimer());
1975 #ifdef DISTRIBUTED_NOTIFICATION_SUPPORTED
1976                 DoDistributedDelete(record->deviceId, record->bundleName, record->notification);
1977 #endif
1978             }
1979             if (notifications.size() >= MAX_CANCELED_PARCELABLE_VECTOR_NUM) {
1980                 std::vector<sptr<Notification>> currNotificationList = notifications;
1981                 NotificationSubscriberManager::GetInstance()->BatchNotifyCanceled(
1982                     currNotificationList, nullptr, reason);
1983                 notifications.clear();
1984             }
1985         }
1986 
1987         if (!notifications.empty()) {
1988             NotificationSubscriberManager::GetInstance()->BatchNotifyCanceled(
1989                 notifications, nullptr, reason);
1990         }
1991         BatchCancelTimer(timerIds);
1992     }));
1993     notificationSvrQueue_->wait(handler);
1994 }
1995 
RemoveGroupByBundle(const sptr<NotificationBundleOption> & bundleOption,const std::string & groupName)1996 ErrCode AdvancedNotificationService::RemoveGroupByBundle(
1997     const sptr<NotificationBundleOption> &bundleOption, const std::string &groupName)
1998 {
1999     ANS_LOGD("%{public}s", __FUNCTION__);
2000     const int32_t reason = NotificationConstant::APP_REMOVE_GROUP_REASON_DELETE;
2001     bool isSubsystem = AccessTokenHelper::VerifyNativeToken(IPCSkeleton::GetCallingTokenID());
2002     if (!isSubsystem && !AccessTokenHelper::IsSystemApp()) {
2003         std::string message = "not systemApp.";
2004         OHOS::Notification::HaMetaMessage haMetaMessage = HaMetaMessage(5, 1)
2005             .ErrorCode(ERR_ANS_NON_SYSTEM_APP);
2006         ReportDeleteFailedEventPush(haMetaMessage, reason, message);
2007         ANS_LOGE("%{public}s", message.c_str());
2008         return ERR_ANS_NON_SYSTEM_APP;
2009     }
2010 
2011     if (!AccessTokenHelper::CheckPermission(OHOS_PERMISSION_NOTIFICATION_CONTROLLER)) {
2012         std::string message = "no acl permission";
2013         OHOS::Notification::HaMetaMessage haMetaMessage = HaMetaMessage(5, 2)
2014             .ErrorCode(ERR_ANS_PERMISSION_DENIED);
2015         ReportDeleteFailedEventPush(haMetaMessage, reason, message);
2016         ANS_LOGE("%{public}s", message.c_str());
2017         return ERR_ANS_PERMISSION_DENIED;
2018     }
2019 
2020     if (bundleOption == nullptr || groupName.empty()) {
2021         std::string message = "groupName empty";
2022         OHOS::Notification::HaMetaMessage haMetaMessage = HaMetaMessage(5, 3)
2023             .ErrorCode(ERR_ANS_INVALID_PARAM);
2024         ReportDeleteFailedEventPush(haMetaMessage, reason, message);
2025         ANS_LOGE("%{public}s", message.c_str());
2026         return ERR_ANS_INVALID_PARAM;
2027     }
2028 
2029     sptr<NotificationBundleOption> bundle = GenerateValidBundleOption(bundleOption);
2030     if (bundle == nullptr) {
2031         std::string message = "bundle is nullptr";
2032         OHOS::Notification::HaMetaMessage haMetaMessage = HaMetaMessage(5, 4)
2033             .ErrorCode(ERR_ANS_INVALID_PARAM);
2034         ReportDeleteFailedEventPush(haMetaMessage, reason, message);
2035         ANS_LOGE("%{public}s", message.c_str());
2036         return ERR_ANS_INVALID_BUNDLE;
2037     }
2038 
2039     if (notificationSvrQueue_ == nullptr) {
2040         std::string message = "Serial queue is invalid.";
2041         ANS_LOGE("%{public}s", message.c_str());
2042         return ERR_ANS_INVALID_PARAM;
2043     }
2044     ffrt::task_handle handler = notificationSvrQueue_->submit_h(std::bind([&]() {
2045         ANS_LOGD("ffrt enter!");
2046         std::vector<std::shared_ptr<NotificationRecord>> removeList;
2047         int32_t reason = NotificationConstant::CANCEL_REASON_DELETE;
2048         for (auto record : notificationList_) {
2049             if (!record->notification->IsRemoveAllowed()) {
2050                 continue;
2051             }
2052             if ((record->bundleOption->GetBundleName() == bundle->GetBundleName()) &&
2053                 (record->bundleOption->GetUid() == bundle->GetUid()) && !record->request->IsUnremovable() &&
2054 #ifdef DISTRIBUTED_NOTIFICATION_SUPPORTED
2055                 record->deviceId.empty() &&
2056 #endif
2057                 (record->request->GetGroupName() == groupName)) {
2058                 ANS_LOGD("RemoveList push enter.");
2059                 removeList.push_back(record);
2060             }
2061         }
2062 
2063         std::vector<sptr<Notification>> notifications;
2064         std::vector<uint64_t> timerIds;
2065         for (auto record : removeList) {
2066             notificationList_.remove(record);
2067             ProcForDeleteLiveView(record);
2068 
2069             if (record->notification != nullptr) {
2070                 UpdateRecentNotification(record->notification, true, reason);
2071                 notifications.emplace_back(record->notification);
2072                 timerIds.emplace_back(record->notification->GetAutoDeletedTimer());
2073 #ifdef DISTRIBUTED_NOTIFICATION_SUPPORTED
2074                 DoDistributedDelete(record->deviceId, record->bundleName, record->notification);
2075 #endif
2076             }
2077             if (notifications.size() >= MAX_CANCELED_PARCELABLE_VECTOR_NUM) {
2078                 SendNotificationsOnCanceled(notifications, nullptr, reason);
2079             }
2080         }
2081 
2082         if (!notifications.empty()) {
2083             NotificationSubscriberManager::GetInstance()->BatchNotifyCanceled(notifications, nullptr, reason);
2084         }
2085         BatchCancelTimer(timerIds);
2086     }));
2087     notificationSvrQueue_->wait(handler);
2088 
2089     return ERR_OK;
2090 }
2091 
RemoveNotificationFromRecordList(const std::vector<std::shared_ptr<NotificationRecord>> & recordList)2092 ErrCode AdvancedNotificationService::RemoveNotificationFromRecordList(
2093     const std::vector<std::shared_ptr<NotificationRecord>>& recordList)
2094 {
2095     ErrCode result = ERR_OK;
2096         std::vector<sptr<Notification>> notifications;
2097         std::vector<uint64_t> timerIds;
2098         for (auto& record : recordList) {
2099             std::string key = record->notification->GetKey();
2100             sptr<Notification> notification = nullptr;
2101 #ifdef DISTRIBUTED_NOTIFICATION_SUPPORTED
2102             std::string deviceId;
2103             std::string bundleName;
2104             GetDistributedInfo(key, deviceId, bundleName);
2105 #endif
2106             result = RemoveFromNotificationList(key, notification, true,
2107                 NotificationConstant::USER_STOPPED_REASON_DELETE);
2108             if (result != ERR_OK) {
2109                 continue;
2110             }
2111             if (notification != nullptr) {
2112                 int32_t reason = NotificationConstant::USER_STOPPED_REASON_DELETE;
2113                 UpdateRecentNotification(notification, true, reason);
2114                 notifications.emplace_back(notification);
2115                 timerIds.emplace_back(notification->GetAutoDeletedTimer());
2116 #ifdef DISTRIBUTED_NOTIFICATION_SUPPORTED
2117             DoDistributedDelete(deviceId, bundleName, notification);
2118 #endif
2119             }
2120             if (notifications.size() >= MAX_CANCELED_PARCELABLE_VECTOR_NUM) {
2121                 std::vector<sptr<Notification>> currNotificationList = notifications;
2122                 NotificationSubscriberManager::GetInstance()->BatchNotifyCanceled(
2123                     currNotificationList, nullptr, NotificationConstant::USER_STOPPED_REASON_DELETE);
2124                 notifications.clear();
2125             }
2126         }
2127         if (!notifications.empty()) {
2128             NotificationSubscriberManager::GetInstance()->BatchNotifyCanceled(
2129                 notifications, nullptr, NotificationConstant::USER_STOPPED_REASON_DELETE);
2130         }
2131         BatchCancelTimer(timerIds);
2132         return result;
2133 }
2134 
IsSpecialUserAllowedNotify(const int32_t & userId,bool & allowed)2135 ErrCode AdvancedNotificationService::IsSpecialUserAllowedNotify(const int32_t &userId, bool &allowed)
2136 {
2137     ANS_LOGD("%{public}s", __FUNCTION__);
2138 
2139     bool isSubsystem = AccessTokenHelper::VerifyNativeToken(IPCSkeleton::GetCallingTokenID());
2140     if (!isSubsystem && !AccessTokenHelper::IsSystemApp()) {
2141         return ERR_ANS_NON_SYSTEM_APP;
2142     }
2143 
2144     if (!AccessTokenHelper::CheckPermission(OHOS_PERMISSION_NOTIFICATION_CONTROLLER)) {
2145         ANS_LOGD("Failed to checkPermission");
2146         return ERR_ANS_PERMISSION_DENIED;
2147     }
2148 
2149     if (notificationSvrQueue_ == nullptr) {
2150         ANS_LOGE("NotificationSvrQueue_ is nullptr.");
2151         return ERR_ANS_INVALID_PARAM;
2152     }
2153     ErrCode result = ERR_OK;
2154     ffrt::task_handle handler = notificationSvrQueue_->submit_h(std::bind([&]() {
2155         ANS_LOGD("ffrt enter!");
2156         allowed = false;
2157         result = NotificationPreferences::GetInstance()->GetNotificationsEnabled(userId, allowed);
2158     }));
2159     notificationSvrQueue_->wait(handler);
2160     return result;
2161 }
2162 
SetNotificationsEnabledByUser(const int32_t & userId,bool enabled)2163 ErrCode AdvancedNotificationService::SetNotificationsEnabledByUser(const int32_t &userId, bool enabled)
2164 {
2165     ANS_LOGD("%{public}s", __FUNCTION__);
2166 
2167     bool isSubsystem = AccessTokenHelper::VerifyNativeToken(IPCSkeleton::GetCallingTokenID());
2168     if (!isSubsystem && !AccessTokenHelper::IsSystemApp()) {
2169         return ERR_ANS_NON_SYSTEM_APP;
2170     }
2171 
2172     if (!AccessTokenHelper::CheckPermission(OHOS_PERMISSION_NOTIFICATION_CONTROLLER)) {
2173         return ERR_ANS_PERMISSION_DENIED;
2174     }
2175 
2176     if (notificationSvrQueue_ == nullptr) {
2177         ANS_LOGE("Serial queue is ineffectiveness.");
2178         return ERR_ANS_INVALID_PARAM;
2179     }
2180     ErrCode result = ERR_OK;
2181     ffrt::task_handle handler = notificationSvrQueue_->submit_h(std::bind([&]() {
2182         ANS_LOGD("ffrt enter!");
2183         result = NotificationPreferences::GetInstance()->SetNotificationsEnabled(userId, enabled);
2184     }));
2185     notificationSvrQueue_->wait(handler);
2186     return result;
2187 }
2188 
SetEnabledForBundleSlot(const sptr<NotificationBundleOption> & bundleOption,const NotificationConstant::SlotType & slotType,bool enabled,bool isForceControl)2189 ErrCode AdvancedNotificationService::SetEnabledForBundleSlot(const sptr<NotificationBundleOption> &bundleOption,
2190     const NotificationConstant::SlotType &slotType, bool enabled, bool isForceControl)
2191 {
2192     HITRACE_METER_NAME(HITRACE_TAG_NOTIFICATION, __PRETTY_FUNCTION__);
2193     ANS_LOGD("slotType: %{public}d, enabled: %{public}d, isForceControl: %{public}d",
2194         slotType, enabled, isForceControl);
2195 
2196     ErrCode result = CheckCommonParams();
2197     if (result != ERR_OK) {
2198         return result;
2199     }
2200 
2201     sptr<NotificationBundleOption> bundle = GenerateValidBundleOption(bundleOption);
2202     if (bundle == nullptr) {
2203         return ERR_ANS_INVALID_BUNDLE;
2204     }
2205 
2206     HaMetaMessage message = HaMetaMessage(EventSceneId::SCENE_5, EventBranchId::BRANCH_4);
2207     message.Message(bundleOption->GetBundleName() + "_" +std::to_string(bundleOption->GetUid()) +
2208         " slotType: " + std::to_string(static_cast<uint32_t>(slotType)) +
2209         " enabled: " +std::to_string(enabled) + "isForceControl" + std::to_string(isForceControl));
2210     result = ERR_OK;
2211     ffrt::task_handle handler = notificationSvrQueue_->submit_h(std::bind([&]() {
2212         sptr<NotificationSlot> slot;
2213         result = NotificationPreferences::GetInstance()->GetNotificationSlot(bundle, slotType, slot);
2214         if (result == ERR_ANS_PREFERENCES_NOTIFICATION_SLOT_TYPE_NOT_EXIST ||
2215             result == ERR_ANS_PREFERENCES_NOTIFICATION_BUNDLE_NOT_EXIST) {
2216             slot = new (std::nothrow) NotificationSlot(slotType);
2217             if (slot == nullptr) {
2218                 ANS_LOGE("Failed to create NotificationSlot ptr.");
2219                 result = ERR_ANS_NO_MEMORY;
2220                 return;
2221             }
2222             GenerateSlotReminderMode(slot, bundleOption);
2223         } else if ((result == ERR_OK) && (slot != nullptr)) {
2224             if (slot->GetEnable() == enabled && slot->GetForceControl() == isForceControl) {
2225                 // 设置authorizedStatus为已授权
2226                 slot->SetAuthorizedStatus(NotificationSlot::AuthorizedStatus::AUTHORIZED);
2227                 std::vector<sptr<NotificationSlot>> slots;
2228                 slots.push_back(slot);
2229                 result = NotificationPreferences::GetInstance()->AddNotificationSlots(bundle, slots);
2230                 return;
2231             }
2232             NotificationPreferences::GetInstance()->RemoveNotificationSlot(bundle, slotType);
2233         } else {
2234             ANS_LOGE("Set enable slot: GetNotificationSlot failed");
2235             return;
2236         }
2237         bool allowed = false;
2238         result = NotificationPreferences::GetInstance()->GetNotificationsEnabledForBundle(bundle, allowed);
2239         if (result == ERR_ANS_PREFERENCES_NOTIFICATION_BUNDLE_NOT_EXIST) {
2240             result = ERR_OK;
2241             allowed = CheckApiCompatibility(bundle);
2242             SetDefaultNotificationEnabled(bundle, allowed);
2243         }
2244 
2245         slot->SetEnable(enabled);
2246         slot->SetForceControl(isForceControl);
2247         // 设置authorizedStatus为已授权
2248         slot->SetAuthorizedStatus(NotificationSlot::AuthorizedStatus::AUTHORIZED);
2249         std::vector<sptr<NotificationSlot>> slots;
2250         slots.push_back(slot);
2251         result = NotificationPreferences::GetInstance()->AddNotificationSlots(bundle, slots);
2252         if (result != ERR_OK) {
2253             ANS_LOGE("Set enable slot: AddNotificationSlot failed");
2254             return;
2255         }
2256 
2257         if (!slot->GetEnable()) {
2258             RemoveNotificationBySlot(bundle, slot, NotificationConstant::DISABLE_SLOT_REASON_DELETE);
2259         } else {
2260             if (!slot->GetForceControl() && !allowed) {
2261                 RemoveNotificationBySlot(bundle, slot, NotificationConstant::DISABLE_NOTIFICATION_REASON_DELETE);
2262             }
2263         }
2264 
2265         PublishSlotChangeCommonEvent(bundle);
2266     }));
2267     notificationSvrQueue_->wait(handler);
2268 
2269     message.ErrorCode(result);
2270     NotificationAnalyticsUtil::ReportModifyEvent(message);
2271     ANS_LOGI("%{public}s_%{public}d, SetEnabledForBundleSlot successful.",
2272         bundleOption->GetBundleName().c_str(), bundleOption->GetUid());
2273     SendEnableNotificationSlotHiSysEvent(bundleOption, slotType, enabled, result);
2274     return result;
2275 }
2276 
GetEnabledForBundleSlot(const sptr<NotificationBundleOption> & bundleOption,const NotificationConstant::SlotType & slotType,bool & enabled)2277 ErrCode AdvancedNotificationService::GetEnabledForBundleSlot(
2278     const sptr<NotificationBundleOption> &bundleOption, const NotificationConstant::SlotType &slotType, bool &enabled)
2279 {
2280     ANS_LOGD("slotType: %{public}d", slotType);
2281 
2282     bool isSubsystem = AccessTokenHelper::VerifyNativeToken(IPCSkeleton::GetCallingTokenID());
2283     if (!isSubsystem && !AccessTokenHelper::IsSystemApp()) {
2284         ANS_LOGD("VerifyNativeToken and isSystemApp failed.");
2285         return ERR_ANS_NON_SYSTEM_APP;
2286     }
2287 
2288     if (!AccessTokenHelper::CheckPermission(OHOS_PERMISSION_NOTIFICATION_CONTROLLER)) {
2289         return ERR_ANS_PERMISSION_DENIED;
2290     }
2291 
2292     sptr<NotificationBundleOption> bundle = GenerateValidBundleOption(bundleOption);
2293     if (bundle == nullptr) {
2294         return ERR_ANS_INVALID_BUNDLE;
2295     }
2296 
2297     if (notificationSvrQueue_ == nullptr) {
2298         ANS_LOGE("Serial queue is invalid.");
2299         return ERR_ANS_INVALID_PARAM;
2300     }
2301     ErrCode result = ERR_OK;
2302     ffrt::task_handle handler = notificationSvrQueue_->submit_h(std::bind([&]() {
2303         ANS_LOGD("ffrt enter!");
2304         sptr<NotificationSlot> slot;
2305         result = NotificationPreferences::GetInstance()->GetNotificationSlot(bundle, slotType, slot);
2306         if (result != ERR_OK) {
2307             ANS_LOGE("Get enable slot: GetNotificationSlot failed");
2308             return;
2309         }
2310         if (slot == nullptr) {
2311             ANS_LOGW("Get enable slot: object is null, enabled default true");
2312             enabled = true;
2313             result = ERR_OK;
2314             return;
2315         }
2316         enabled = slot->GetEnable();
2317     }));
2318     notificationSvrQueue_->wait(handler);
2319 
2320     return result;
2321 }
2322 
UpdateUnifiedGroupInfo(const std::string & key,std::shared_ptr<NotificationUnifiedGroupInfo> & groupInfo)2323 void AdvancedNotificationService::UpdateUnifiedGroupInfo(const std::string &key,
2324     std::shared_ptr<NotificationUnifiedGroupInfo> &groupInfo)
2325 {
2326     if (notificationSvrQueue_ == nullptr) {
2327         ANS_LOGE("Serial queue is invalid.");
2328         return;
2329     }
2330 
2331     ffrt::task_handle handler = notificationSvrQueue_->submit_h([=]() {
2332         for (const auto& item : notificationList_) {
2333             if (item->notification->GetKey() == key) {
2334                 ANS_LOGD("update group info matched key %s", key.c_str());
2335                 item->notification->GetNotificationRequestPoint()->SetUnifiedGroupInfo(groupInfo);
2336 
2337                 CloseAlert(item);
2338 
2339                 UpdateRecentNotification(item->notification, false, 0);
2340                 sptr<NotificationSortingMap> sortingMap = GenerateSortingMap();
2341                 NotificationSubscriberManager::GetInstance()->NotifyConsumed(item->notification, sortingMap);
2342                 break;
2343             }
2344         }
2345     });
2346 }
2347 
PublishNotificationBySa(const sptr<NotificationRequest> & request)2348 ErrCode AdvancedNotificationService::PublishNotificationBySa(const sptr<NotificationRequest> &request)
2349 {
2350     ANS_LOGD("%{public}s", __FUNCTION__);
2351 
2352     bool isAgentController = AccessTokenHelper::CheckPermission(OHOS_PERMISSION_NOTIFICATION_AGENT_CONTROLLER);
2353     HaMetaMessage message = HaMetaMessage(EventSceneId::SCENE_4, EventBranchId::BRANCH_1);
2354     int32_t uid = request->GetCreatorUid();
2355     if (request->GetOwnerUid() != DEFAULT_UID) {
2356         std::shared_ptr<NotificationBundleOption> agentBundle =
2357         std::make_shared<NotificationBundleOption>("", uid);
2358         request->SetAgentBundle(agentBundle);
2359     }
2360 
2361     if (request->IsAgentNotification()) {
2362         uid = request->GetOwnerUid();
2363     }
2364     if (uid <= 0) {
2365         message.ErrorCode(ERR_ANS_INVALID_UID).Message("createUid failed" + std::to_string(uid), true);
2366         NotificationAnalyticsUtil::ReportPublishFailedEvent(request, message);
2367         return ERR_ANS_INVALID_UID;
2368     }
2369     std::string bundle = "";
2370     ErrCode result = PrePublishNotificationBySa(request, uid, bundle);
2371     if (request->GetCreatorUid() == RSS_PID && request->IsSystemLiveView() &&
2372         (std::static_pointer_cast<OHOS::Notification::NotificationLocalLiveViewContent>(
2373         request->GetContent()->GetNotificationContent())->GetType() != TYPE_CODE_DOWNLOAD)) {
2374         request->SetSlotType(NotificationConstant::SlotType::OTHER);
2375         request->GetContent()->ResetToBasicContent();
2376         request->SetUnremovable(true);
2377         request->SetTapDismissed(false);
2378     }
2379     if (result != ERR_OK) {
2380         return result;
2381     }
2382 
2383     // SA not support sound
2384     if (!request->GetSound().empty()) {
2385         request->SetSound("");
2386     }
2387     std::shared_ptr<NotificationRecord> record = std::make_shared<NotificationRecord>();
2388     record->request = request;
2389     record->isThirdparty = false;
2390     if (request->IsAgentNotification()) {
2391         record->bundleOption = new (std::nothrow) NotificationBundleOption("", request->GetCreatorUid());
2392     } else {
2393         record->bundleOption = new (std::nothrow) NotificationBundleOption(bundle, uid);
2394     }
2395     record->bundleOption->SetAppInstanceKey(request->GetAppInstanceKey());
2396     sptr<NotificationBundleOption> bundleOption = new (std::nothrow) NotificationBundleOption(bundle, uid);
2397     if (record->bundleOption == nullptr || bundleOption == nullptr) {
2398         ANS_LOGE("Failed to create bundleOption");
2399         return ERR_ANS_NO_MEMORY;
2400     }
2401     int32_t ipcUid = IPCSkeleton::GetCallingUid();
2402     uint32_t hashCodeGeneratetype = NotificationPreferences::GetInstance()->GetHashCodeRule(ipcUid);
2403     request->SetHashCodeGenerateType(hashCodeGeneratetype);
2404     record->notification = new (std::nothrow) Notification(request);
2405     if (record->notification == nullptr) {
2406         ANS_LOGE("Failed to create notification");
2407         return ERR_ANS_NO_MEMORY;
2408     }
2409 
2410     if (notificationSvrQueue_ == nullptr) {
2411         ANS_LOGE("Serial queue is invalid.");
2412         return ERR_ANS_INVALID_PARAM;
2413     }
2414 
2415     SetRequestBySlotType(record->request, bundleOption);
2416 #ifdef ENABLE_ANS_EXT_WRAPPER
2417     EXTENTION_WRAPPER->GetUnifiedGroupInfo(request);
2418 #endif
2419 
2420     ffrt::task_handle handler = notificationSvrQueue_->submit_h([&]() {
2421         if (!bundleOption->GetBundleName().empty() &&
2422             !(request->GetSlotType() == NotificationConstant::SlotType::LIVE_VIEW && request->IsAgentNotification())) {
2423             ErrCode ret = AssignValidNotificationSlot(record, bundleOption);
2424             if (ret != ERR_OK) {
2425                 ANS_LOGE("Can not assign valid slot!");
2426             }
2427         }
2428 
2429         ChangeNotificationByControlFlags(record, isAgentController);
2430         if (IsSaCreateSystemLiveViewAsBundle(record, ipcUid) &&
2431         (std::static_pointer_cast<OHOS::Notification::NotificationLocalLiveViewContent>(
2432         record->request->GetContent()->GetNotificationContent())->GetType() == TYPE_CODE_DOWNLOAD)) {
2433             result = SaPublishSystemLiveViewAsBundle(record);
2434             if (result == ERR_OK) {
2435                 SendLiveViewUploadHiSysEvent(record, UploadStatus::CREATE);
2436             }
2437             return;
2438         }
2439         bool isNotificationExists = IsNotificationExists(record->notification->GetKey());
2440         result = FlowControlService::GetInstance()->FlowControl(record, ipcUid, isNotificationExists);
2441         if (result != ERR_OK) {
2442             return;
2443         }
2444         if (AssignToNotificationList(record) != ERR_OK) {
2445             ANS_LOGE("Failed to assign notification list");
2446             return;
2447         }
2448 
2449         UpdateRecentNotification(record->notification, false, 0);
2450         sptr<NotificationSortingMap> sortingMap = GenerateSortingMap();
2451         NotificationSubscriberManager::GetInstance()->NotifyConsumed(record->notification, sortingMap);
2452     });
2453     notificationSvrQueue_->wait(handler);
2454     if (result != ERR_OK) {
2455         return result;
2456     }
2457 
2458     if ((record->request->GetAutoDeletedTime() > GetCurrentTime()) && !record->request->IsCommonLiveView()) {
2459         StartAutoDeletedTimer(record);
2460     }
2461     return ERR_OK;
2462 }
2463 
SetBadgeNumber(int32_t badgeNumber,const std::string & instanceKey)2464 ErrCode AdvancedNotificationService::SetBadgeNumber(int32_t badgeNumber, const std::string &instanceKey)
2465 {
2466     ANS_LOGD("%{public}s", __FUNCTION__);
2467     if (notificationSvrQueue_ == nullptr) {
2468         ANS_LOGE("Serial queue is invalid.");
2469         return ERR_ANS_INVALID_PARAM;
2470     }
2471     int32_t callingUid = IPCSkeleton::GetCallingUid();
2472     std::string bundleName = GetClientBundleName();
2473     ANS_LOGD("SetBadgeNumber receive instanceKey:%{public}s", instanceKey.c_str());
2474     sptr<BadgeNumberCallbackData> badgeData = new (std::nothrow) BadgeNumberCallbackData(
2475         bundleName, instanceKey, callingUid, badgeNumber);
2476     if (badgeData == nullptr) {
2477         ANS_LOGE("Failed to create BadgeNumberCallbackData.");
2478         return ERR_ANS_NO_MEMORY;
2479     }
2480 
2481     ffrt::task_handle handler = notificationSvrQueue_->submit_h([&]() {
2482         ANS_LOGD("ffrt enter!");
2483         NotificationSubscriberManager::GetInstance()->SetBadgeNumber(badgeData);
2484     });
2485     notificationSvrQueue_->wait(handler);
2486     return ERR_OK;
2487 }
2488 
SetBadgeNumberByBundle(const sptr<NotificationBundleOption> & bundleOption,int32_t badgeNumber)2489 ErrCode AdvancedNotificationService::SetBadgeNumberByBundle(
2490     const sptr<NotificationBundleOption> &bundleOption, int32_t badgeNumber)
2491 {
2492     if (bundleOption == nullptr || bundleOption->GetBundleName().empty()) {
2493         return ERR_ANS_INVALID_PARAM;
2494     }
2495     HaMetaMessage message = HaMetaMessage(EventSceneId::SCENE_7, EventBranchId::BRANCH_6);
2496     message.Message(bundleOption->GetBundleName() + "_" +std::to_string(bundleOption->GetUid()) +
2497         " badgeNumber: " + std::to_string(badgeNumber));
2498     if (notificationSvrQueue_ == nullptr) {
2499         return ERR_ANS_INVALID_PARAM;
2500     }
2501 
2502     bool isSubsystem = AccessTokenHelper::VerifyNativeToken(IPCSkeleton::GetCallingTokenID());
2503     if (!isSubsystem && !AccessTokenHelper::IsSystemApp()) {
2504         message.ErrorCode(ERR_ANS_NON_SYSTEM_APP).Append(" Not system app.");
2505         NotificationAnalyticsUtil::ReportModifyEvent(message);
2506         ANS_LOGE("Not system app.");
2507         return ERR_ANS_NON_SYSTEM_APP;
2508     }
2509 
2510     sptr<NotificationBundleOption> bundle = bundleOption;
2511     ErrCode result = CheckBundleOptionValid(bundle);
2512     if (result != ERR_OK) {
2513         message.ErrorCode(result).Append(" Bundle is invalid.");
2514         NotificationAnalyticsUtil::ReportModifyEvent(message);
2515         ANS_LOGE("Bundle is invalid.");
2516         return result;
2517     }
2518 
2519     if (!AccessTokenHelper::CheckPermission(OHOS_PERMISSION_NOTIFICATION_AGENT_CONTROLLER)) {
2520         std::string bundleName = GetClientBundleName();
2521         if (bundleName.empty()) {
2522             ANS_LOGE("Failed to get client bundle name.");
2523             return result;
2524         }
2525         bool isAgent = false;
2526         isAgent = IsAgentRelationship(bundleName, bundle->GetBundleName());
2527         if (!isAgent) {
2528             message.ErrorCode(ERR_ANS_NO_AGENT_SETTING).Append(" No agent setting.");
2529             NotificationAnalyticsUtil::ReportModifyEvent(message);
2530             ANS_LOGE("No agent setting.");
2531             return ERR_ANS_NO_AGENT_SETTING;
2532         }
2533     }
2534 
2535     ffrt::task_handle handler = notificationSvrQueue_->submit_h([&]() {
2536         ANS_LOGD("ffrt enter!");
2537         sptr<BadgeNumberCallbackData> badgeData = new (std::nothrow) BadgeNumberCallbackData(
2538             bundle->GetBundleName(), bundle->GetUid(), badgeNumber);
2539         if (badgeData == nullptr) {
2540             ANS_LOGE("Failed to create badge number callback data.");
2541             result = ERR_ANS_NO_MEMORY;
2542         }
2543         NotificationSubscriberManager::GetInstance()->SetBadgeNumber(badgeData);
2544     });
2545     notificationSvrQueue_->wait(handler);
2546     return result;
2547 }
2548 
SubscribeLocalLiveView(const sptr<AnsSubscriberLocalLiveViewInterface> & subscriber,const sptr<NotificationSubscribeInfo> & info,const bool isNative)2549 ErrCode AdvancedNotificationService::SubscribeLocalLiveView(
2550     const sptr<AnsSubscriberLocalLiveViewInterface> &subscriber,
2551     const sptr<NotificationSubscribeInfo> &info, const bool isNative)
2552 {
2553     HITRACE_METER_NAME(HITRACE_TAG_NOTIFICATION, __PRETTY_FUNCTION__);
2554     ANS_LOGD("%{public}s, isNative: %{public}d", __FUNCTION__, isNative);
2555 
2556     ErrCode errCode = ERR_OK;
2557     do {
2558         if (!isNative) {
2559             bool isSubsystem = AccessTokenHelper::VerifyNativeToken(IPCSkeleton::GetCallingTokenID());
2560             if (!isSubsystem && !AccessTokenHelper::IsSystemApp()) {
2561                 ANS_LOGE("Client is not a system app or subsystem.");
2562                 errCode = ERR_ANS_NON_SYSTEM_APP;
2563                 break;
2564             }
2565         }
2566 
2567         if (subscriber == nullptr) {
2568             errCode = ERR_ANS_INVALID_PARAM;
2569             break;
2570         }
2571 
2572         errCode = NotificationLocalLiveViewSubscriberManager::GetInstance()->AddLocalLiveViewSubscriber(
2573             subscriber, info);
2574         if (errCode != ERR_OK) {
2575             break;
2576         }
2577     } while (0);
2578     if (errCode == ERR_OK) {
2579         int32_t callingUid = IPCSkeleton::GetCallingUid();
2580         ffrt::task_handle handler = notificationSvrQueue_->submit_h(std::bind([&]() {
2581             LivePublishProcess::GetInstance()->AddLiveViewSubscriber(callingUid);
2582         }));
2583         notificationSvrQueue_->wait(handler);
2584     }
2585     SendSubscribeHiSysEvent(IPCSkeleton::GetCallingPid(), IPCSkeleton::GetCallingUid(), info, errCode);
2586     return errCode;
2587 }
2588 
SetDistributedEnabledByBundle(const sptr<NotificationBundleOption> & bundleOption,const std::string & deviceType,const bool enabled)2589 ErrCode AdvancedNotificationService::SetDistributedEnabledByBundle(const sptr<NotificationBundleOption> &bundleOption,
2590     const std::string &deviceType, const bool enabled)
2591 {
2592     ANS_LOGD("%{public}s", __FUNCTION__);
2593     if (bundleOption == nullptr) {
2594         ANS_LOGE("BundleOption is null.");
2595         return ERR_ANS_INVALID_BUNDLE;
2596     }
2597 
2598     HaMetaMessage message = HaMetaMessage(EventSceneId::SCENE_9, EventBranchId::BRANCH_3);
2599     message.Message(bundleOption->GetBundleName() + "_" + std::to_string(bundleOption->GetUid()) +
2600         " enabled:" + std::to_string(enabled) +
2601         " deviceType:" + deviceType);
2602     bool isSubsystem = AccessTokenHelper::VerifyNativeToken(IPCSkeleton::GetCallingTokenID());
2603     if (!isSubsystem && !AccessTokenHelper::IsSystemApp()) {
2604         ANS_LOGE("IsSystemApp is false.");
2605         message.ErrorCode(ERR_ANS_NON_SYSTEM_APP).Append("Not SystemApp");
2606         NotificationAnalyticsUtil::ReportModifyEvent(message);
2607         return ERR_ANS_NON_SYSTEM_APP;
2608     }
2609 
2610     if (!AccessTokenHelper::CheckPermission(OHOS_PERMISSION_NOTIFICATION_CONTROLLER)) {
2611         ANS_LOGE("Permission Denied.");
2612         message.ErrorCode(ERR_ANS_PERMISSION_DENIED).Append("No permission");
2613         NotificationAnalyticsUtil::ReportModifyEvent(message);
2614         return ERR_ANS_PERMISSION_DENIED;
2615     }
2616 
2617     sptr<NotificationBundleOption> bundle = GenerateValidBundleOption(bundleOption);
2618     if (bundle == nullptr) {
2619         ANS_LOGE("bundle is nullptr");
2620         return ERR_ANS_INVALID_BUNDLE;
2621     }
2622     ErrCode result = NotificationPreferences::GetInstance()->SetDistributedEnabledByBundle(bundle,
2623         deviceType, enabled);
2624 
2625     ANS_LOGI("%{public}s_%{public}d, deviceType: %{public}s, enabled: %{public}s, "
2626         "SetDistributedEnabledByBundle result: %{public}d", bundleOption->GetBundleName().c_str(),
2627         bundleOption->GetUid(), deviceType.c_str(), std::to_string(enabled).c_str(), result);
2628     message.ErrorCode(result);
2629     NotificationAnalyticsUtil::ReportModifyEvent(message);
2630 
2631     return result;
2632 }
2633 
IsDistributedEnabledByBundle(const sptr<NotificationBundleOption> & bundleOption,const std::string & deviceType,bool & enabled)2634 ErrCode AdvancedNotificationService::IsDistributedEnabledByBundle(const sptr<NotificationBundleOption> &bundleOption,
2635     const std::string &deviceType, bool &enabled)
2636 {
2637     ANS_LOGD("%{public}s", __FUNCTION__);
2638 
2639     bool isSubsystem = AccessTokenHelper::VerifyNativeToken(IPCSkeleton::GetCallingTokenID());
2640     if (!isSubsystem && !AccessTokenHelper::IsSystemApp()) {
2641         ANS_LOGD("IsSystemApp is bogus.");
2642         return ERR_ANS_NON_SYSTEM_APP;
2643     }
2644 
2645     if (!AccessTokenHelper::CheckPermission(OHOS_PERMISSION_NOTIFICATION_CONTROLLER)) {
2646         ANS_LOGE("no permission");
2647         return ERR_ANS_PERMISSION_DENIED;
2648     }
2649 
2650     sptr<NotificationBundleOption> bundle = GenerateValidBundleOption(bundleOption);
2651     if (bundle == nullptr) {
2652         return ERR_ANS_INVALID_BUNDLE;
2653     }
2654 
2655     return NotificationPreferences::GetInstance()->IsDistributedEnabledByBundle(bundle, deviceType, enabled);
2656 }
2657 
DuplicateMsgControl(const sptr<NotificationRequest> & request)2658 ErrCode AdvancedNotificationService::DuplicateMsgControl(const sptr<NotificationRequest> &request)
2659 {
2660     if (request->IsCommonLiveView() || request->GetAppMessageId().empty()) {
2661         return ERR_OK;
2662     }
2663 
2664     RemoveExpiredUniqueKey();
2665     std::string uniqueKey = request->GenerateUniqueKey();
2666     if (IsDuplicateMsg(uniqueKey)) {
2667         ANS_LOGI("Duplicate msg, no need to notify, key is %{public}s, appmessageId is %{public}s",
2668             request->GetKey().c_str(), request->GetAppMessageId().c_str());
2669         return ERR_ANS_DUPLICATE_MSG;
2670     }
2671 
2672     uniqueKeyList_.emplace_back(std::make_pair(std::chrono::steady_clock::now(), uniqueKey));
2673     return ERR_OK;
2674 }
2675 
DeleteDuplicateMsgs(const sptr<NotificationBundleOption> & bundleOption)2676 void AdvancedNotificationService::DeleteDuplicateMsgs(const sptr<NotificationBundleOption> &bundleOption)
2677 {
2678     if (bundleOption == nullptr) {
2679         ANS_LOGE("bundleOption is nullptr");
2680         return;
2681     }
2682     const char *keySpliter = "_";
2683     std::stringstream stream;
2684     stream << bundleOption->GetUid() << keySpliter << bundleOption->GetBundleName() << keySpliter;
2685     std::string uniqueKeyHead = stream.str();
2686     auto iter = uniqueKeyList_.begin();
2687     for (auto iter = uniqueKeyList_.begin(); iter != uniqueKeyList_.end();) {
2688         if ((*iter).second.find(uniqueKeyHead) == 0) {
2689             iter = uniqueKeyList_.erase(iter);
2690         } else {
2691             ++iter;
2692         }
2693     }
2694 }
2695 
RemoveExpiredUniqueKey()2696 void AdvancedNotificationService::RemoveExpiredUniqueKey()
2697 {
2698     std::chrono::steady_clock::time_point now = std::chrono::steady_clock::now();
2699     auto iter = uniqueKeyList_.begin();
2700     while (iter != uniqueKeyList_.end()) {
2701         if (std::chrono::duration_cast<std::chrono::seconds>(now - (*iter).first).count() > SECONDS_IN_ONE_DAY) {
2702             iter = uniqueKeyList_.erase(iter);
2703         } else {
2704             break;
2705         }
2706     }
2707 }
2708 
IsDuplicateMsg(const std::string & uniqueKey)2709 bool AdvancedNotificationService::IsDuplicateMsg(const std::string &uniqueKey)
2710 {
2711     for (auto record : uniqueKeyList_) {
2712         if (strcmp(record.second.c_str(), uniqueKey.c_str()) == 0) {
2713             return true;
2714         }
2715     }
2716 
2717     return false;
2718 }
2719 
PublishRemoveDuplicateEvent(const std::shared_ptr<NotificationRecord> & record)2720 ErrCode AdvancedNotificationService::PublishRemoveDuplicateEvent(const std::shared_ptr<NotificationRecord> &record)
2721 {
2722     if (record == nullptr) {
2723         return ERR_ANS_INVALID_PARAM;
2724     }
2725 
2726     if (!record->request->IsAgentNotification()) {
2727         ANS_LOGD("Only push agent need remove duplicate event");
2728         return ERR_OK;
2729     }
2730 
2731     std::string extraStr;
2732     if (record->request->GetUnifiedGroupInfo() != nullptr) {
2733         auto extraInfo = record->request->GetUnifiedGroupInfo()->GetExtraInfo();
2734         if (extraInfo != nullptr) {
2735             AAFwk::WantParamWrapper wWrapper(*extraInfo);
2736             extraStr = wWrapper.ToString();
2737         }
2738     }
2739 
2740     NotificationNapi::SlotType slotType;
2741     NotificationNapi::ContentType contentType;
2742     NotificationNapi::AnsEnumUtil::ContentTypeCToJS(
2743         static_cast<NotificationContent::Type>(record->request->GetNotificationType()), contentType);
2744     NotificationNapi::AnsEnumUtil::SlotTypeCToJS(
2745         static_cast<NotificationConstant::SlotType>(record->request->GetSlotType()), slotType);
2746 
2747     EventFwk::Want want;
2748     want.SetParam("bundleName", record->bundleOption->GetBundleName());
2749     want.SetParam("uid", record->request->GetOwnerUid());
2750     want.SetParam("id", record->request->GetNotificationId());
2751     want.SetParam("slotType", static_cast<int32_t>(slotType));
2752     want.SetParam("contentType", static_cast<int32_t>(contentType));
2753     want.SetParam("appMessageId", record->request->GetAppMessageId());
2754     want.SetParam("extraInfo", extraStr);
2755     want.SetAction(NOTIFICATION_EVENT_PUSH_AGENT);
2756     EventFwk::CommonEventData commonData {want, 1, ""};
2757     EventFwk::CommonEventPublishInfo publishInfo;
2758     publishInfo.SetSubscriberPermissions({OHOS_PERMISSION_NOTIFICATION_AGENT_CONTROLLER});
2759     if (!EventFwk::CommonEventManager::PublishCommonEvent(commonData, publishInfo)) {
2760         ANS_LOGE("PublishCommonEvent failed");
2761         return ERR_ANS_TASK_ERR;
2762     }
2763 
2764     return ERR_OK;
2765 }
2766 
SetSmartReminderEnabled(const std::string & deviceType,const bool enabled)2767 ErrCode AdvancedNotificationService::SetSmartReminderEnabled(const std::string &deviceType, const bool enabled)
2768 {
2769     ANS_LOGD("%{public}s", __FUNCTION__);
2770     HaMetaMessage message = HaMetaMessage(EventSceneId::SCENE_8, EventBranchId::BRANCH_6);
2771     message.Message(" enabled:" + std::to_string(enabled) + " deviceType:" + deviceType);
2772     bool isSubsystem = AccessTokenHelper::VerifyNativeToken(IPCSkeleton::GetCallingTokenID());
2773     if (!isSubsystem && !AccessTokenHelper::IsSystemApp()) {
2774         ANS_LOGE("IsSystemApp is false.");
2775         message.ErrorCode(ERR_ANS_NON_SYSTEM_APP).Append(" Not SystemApp");
2776         NotificationAnalyticsUtil::ReportModifyEvent(message);
2777         return ERR_ANS_NON_SYSTEM_APP;
2778     }
2779 
2780     if (!AccessTokenHelper::CheckPermission(OHOS_PERMISSION_NOTIFICATION_CONTROLLER)) {
2781         ANS_LOGE("Permission Denied.");
2782         message.ErrorCode(ERR_ANS_PERMISSION_DENIED).Append(" Permission Denied");
2783         NotificationAnalyticsUtil::ReportModifyEvent(message);
2784         return ERR_ANS_PERMISSION_DENIED;
2785     }
2786     ErrCode result = NotificationPreferences::GetInstance()->SetSmartReminderEnabled(deviceType, enabled);
2787 
2788     ANS_LOGI("enabled: %{public}s, deviceType: %{public}s,Set smart reminder enabled: %{public}d",
2789         std::to_string(enabled).c_str(), deviceType.c_str(), result);
2790     message.ErrorCode(result);
2791     NotificationAnalyticsUtil::ReportModifyEvent(message);
2792     return result;
2793 }
2794 
IsSmartReminderEnabled(const std::string & deviceType,bool & enabled)2795 ErrCode AdvancedNotificationService::IsSmartReminderEnabled(const std::string &deviceType, bool &enabled)
2796 {
2797     ANS_LOGD("%{public}s", __FUNCTION__);
2798     bool isSubsystem = AccessTokenHelper::VerifyNativeToken(IPCSkeleton::GetCallingTokenID());
2799     if (!isSubsystem && !AccessTokenHelper::IsSystemApp()) {
2800         ANS_LOGD("IsSystemApp is bogus.");
2801         return ERR_ANS_NON_SYSTEM_APP;
2802     }
2803 
2804     if (!AccessTokenHelper::CheckPermission(OHOS_PERMISSION_NOTIFICATION_CONTROLLER)) {
2805         ANS_LOGE("no permission");
2806         return ERR_ANS_PERMISSION_DENIED;
2807     }
2808 
2809     return NotificationPreferences::GetInstance()->IsSmartReminderEnabled(deviceType, enabled);
2810 }
2811 
SetTargetDeviceStatus(const std::string & deviceType,const uint32_t status)2812 ErrCode AdvancedNotificationService::SetTargetDeviceStatus(const std::string &deviceType, const uint32_t status)
2813 {
2814     ANS_LOGD("%{public}s", __FUNCTION__);
2815     uint32_t status_ = status;
2816     bool isSubsystem = AccessTokenHelper::VerifyNativeToken(IPCSkeleton::GetCallingTokenID());
2817     if (!isSubsystem) {
2818         ANS_LOGD("isSubsystem is bogus.");
2819         return ERR_ANS_NON_SYSTEM_APP;
2820     }
2821     if (deviceType.empty()) {
2822         return ERR_ANS_INVALID_PARAM;
2823     }
2824 
2825     int ret = DelayedSingleton<DistributedDeviceStatus>::GetInstance()->SetDeviceStatus(deviceType, status_);
2826     ANS_LOGI("%{public}s device status update with %{public}u",
2827         deviceType.c_str(), DelayedSingleton<DistributedDeviceStatus>::GetInstance()->GetDeviceStatus(deviceType));
2828     return ret;
2829 }
2830 
ClearAllNotificationGroupInfo(std::string localSwitch)2831 void AdvancedNotificationService::ClearAllNotificationGroupInfo(std::string localSwitch)
2832 {
2833     ANS_LOGD("ClearNotification enter.");
2834     bool status = (localSwitch == "true");
2835     if (notificationSvrQueue_ == nullptr) {
2836         ANS_LOGE("ClearNotification Serial queue is invalid.");
2837         return;
2838     }
2839 
2840     ffrt::task_handle handler = notificationSvrQueue_->submit_h([=]() {
2841         if (aggregateLocalSwitch_ && !status) {
2842             for (const auto& item : notificationList_) {
2843                 item->notification->GetNotificationRequestPoint()->SetUnifiedGroupInfo(nullptr);
2844             }
2845         }
2846         aggregateLocalSwitch_ = status;
2847     });
2848 }
2849 
SetHashCodeRule(const uint32_t type)2850 ErrCode AdvancedNotificationService::SetHashCodeRule(const uint32_t type)
2851 {
2852     ANS_LOGI("%{public}s", __FUNCTION__);
2853     HaMetaMessage message = HaMetaMessage(EventSceneId::SCENE_8, EventBranchId::BRANCH_8);
2854     bool isSubsystem = AccessTokenHelper::VerifyNativeToken(IPCSkeleton::GetCallingTokenID());
2855     if (!isSubsystem && !AccessTokenHelper::IsSystemApp()) {
2856         ANS_LOGE("IsSystemApp is false.");
2857         message.ErrorCode(ERR_ANS_NON_SYSTEM_APP).Append("Not SystemApp");
2858         NotificationAnalyticsUtil::ReportModifyEvent(message);
2859         return ERR_ANS_NON_SYSTEM_APP;
2860     }
2861 
2862     int32_t uid = IPCSkeleton::GetCallingUid();
2863     if (uid != AVSEESAION_PID) {
2864         ANS_LOGE("Permission Denied.");
2865         message.ErrorCode(ERR_ANS_PERMISSION_DENIED).Append("No permission");
2866         NotificationAnalyticsUtil::ReportModifyEvent(message);
2867         return ERR_ANS_PERMISSION_DENIED;
2868     }
2869     ErrCode result = NotificationPreferences::GetInstance()->SetHashCodeRule(uid, type);
2870     ANS_LOGI("SetHashCodeRule uid = %{public}d type =  %{public}d, result  %{public}d", uid, type, result);
2871     message.ErrorCode(result);
2872     NotificationAnalyticsUtil::ReportModifyEvent(message);
2873 
2874     return result;
2875 }
2876 }  // namespace Notification
2877 }  // namespace OHOS
2878