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