• 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 "fa_ability_context.h"
23 #include "ability_info.h"
24 #include "access_token_helper.h"
25 #include "accesstoken_kit.h"
26 #include "advanced_datashare_helper.h"
27 #include "advanced_datashare_helper_ext.h"
28 #include "ans_const_define.h"
29 #include "ans_inner_errors.h"
30 #include "ans_log_wrapper.h"
31 #include "ans_permission_def.h"
32 #include "errors.h"
33 #include "notification_extension_wrapper.h"
34 #include "notification_bundle_option.h"
35 #include "notification_record.h"
36 #include "os_account_manager_helper.h"
37 #include "os_account_manager.h"
38 #ifdef DEVICE_USAGE_STATISTICS_ENABLE
39 #include "bundle_active_client.h"
40 #endif
41 #include "common_event_manager.h"
42 #include "common_event_support.h"
43 #include "event_report.h"
44 #include "hitrace_meter_adapter.h"
45 #include "ipc_skeleton.h"
46 #include "nlohmann/json.hpp"
47 #include "notification_constant.h"
48 #include "notification_dialog_manager.h"
49 #include "notification_filter.h"
50 #include "notification_preferences.h"
51 #include "notification_request.h"
52 #include "notification_slot.h"
53 #include "notification_slot_filter.h"
54 #include "notification_subscriber_manager.h"
55 #include "notification_local_live_view_subscriber_manager.h"
56 #include "os_account_manager_helper.h"
57 #include "permission_filter.h"
58 #include "push_callback_proxy.h"
59 #include "trigger_info.h"
60 #include "want_agent_helper.h"
61 #include "notification_timer_info.h"
62 #include "time_service_client.h"
63 #include "notification_config_parse.h"
64 #include "want_params_wrapper.h"
65 #include "reminder_swing_decision_center.h"
66 #include "notification_extension_wrapper.h"
67 #include "bool_wrapper.h"
68 #include "notification_config_parse.h"
69 
70 #ifdef DISTRIBUTED_NOTIFICATION_SUPPORTED
71 #include "distributed_notification_manager.h"
72 #include "distributed_preferences.h"
73 #include "distributed_screen_status_manager.h"
74 #endif
75 
76 #include "advanced_notification_inline.cpp"
77 #include "advanced_datashare_helper_ext.h"
78 #include "notification_analytics_util.h"
79 #include "advanced_notification_flow_control_service.h"
80 #include "distributed_device_manager.h"
81 #include "liveview_all_scenarios_extension_wrapper.h"
82 #include "notification_operation_service.h"
83 #include "string_wrapper.h"
84 
85 namespace OHOS {
86 namespace Notification {
87 namespace {
88 
89 constexpr int32_t DEFAULT_RECENT_COUNT = 16;
90 constexpr int32_t DIALOG_DEFAULT_WIDTH = 400;
91 constexpr int32_t DIALOG_DEFAULT_HEIGHT = 240;
92 constexpr int32_t WINDOW_DEFAULT_WIDTH = 720;
93 constexpr int32_t WINDOW_DEFAULT_HEIGHT = 1280;
94 constexpr int32_t UI_HALF = 2;
95 constexpr int32_t MAX_LIVEVIEW_HINT_COUNT = 1;
96 constexpr int32_t MAX_SOUND_ITEM_LENGTH = 2048;
97 constexpr int32_t BUNDLE_OPTION_UID_DEFAULT_VALUE = 0;
98 constexpr int32_t RSS_UID = 3051;
99 constexpr int32_t RESSCHED_UID = 1096;
100 constexpr int32_t TYPE_CODE_VOIP = 0;
101 constexpr int32_t CONTROL_BY_DO_NOT_DISTURB_MODE = 1 << 14;
102 constexpr int32_t CONTROL_BY_INTELLIGENT_EXPERIENCE = 1 << 31;
103 constexpr int32_t FIRST_USERID = 0;
104 
105 const std::string DO_NOT_DISTURB_MODE = "1";
106 const std::string INTELLIGENT_EXPERIENCE = "1";
107 const std::string ANS_VOIP = "ANS_VOIP";
108 const std::string ANS_VERIFICATION_CODE = "ANS_VERIFICATION_CODE";
109 constexpr const char *KEY_UNIFIED_GROUP_ENABLE = "unified_group_enable";
110 }  // namespace
111 
112 sptr<AdvancedNotificationService> AdvancedNotificationService::instance_;
113 std::mutex AdvancedNotificationService::instanceMutex_;
114 std::mutex AdvancedNotificationService::pushMutex_;
115 std::mutex AdvancedNotificationService::doNotDisturbMutex_;
116 std::map<std::string, uint32_t> slotFlagsDefaultMap_;
117 
118 std::map<NotificationConstant::SlotType, sptr<IPushCallBack>> AdvancedNotificationService::pushCallBacks_;
119 std::map<NotificationConstant::SlotType, sptr<NotificationCheckRequest>> AdvancedNotificationService::checkRequests_;
120 
PrepareNotificationRequest(const sptr<NotificationRequest> & request)121 ErrCode AdvancedNotificationService::PrepareNotificationRequest(const sptr<NotificationRequest> &request)
122 {
123     ANS_LOGD("%{public}s", __FUNCTION__);
124 
125     std::string bundle = GetClientBundleName();
126     if (bundle.empty()) {
127         return ERR_ANS_INVALID_BUNDLE;
128     }
129     if (request == nullptr) {
130         ANSR_LOGE("NotificationRequest object is nullptr");
131         return ERR_ANS_INVALID_PARAM;
132     }
133 
134     if (request->IsAgentNotification()) {
135         bool isSubsystem = AccessTokenHelper::VerifyNativeToken(IPCSkeleton::GetCallingTokenID());
136         if (!isSubsystem && !AccessTokenHelper::IsSystemApp()) {
137             return ERR_ANS_NON_SYSTEM_APP;
138         }
139 
140         if (!AccessTokenHelper::CheckPermission(OHOS_PERMISSION_NOTIFICATION_CONTROLLER) ||
141             !AccessTokenHelper::CheckPermission(OHOS_PERMISSION_NOTIFICATION_AGENT_CONTROLLER)) {
142             return ERR_ANS_PERMISSION_DENIED;
143         }
144 
145         std::shared_ptr<BundleManagerHelper> bundleManager = BundleManagerHelper::GetInstance();
146         int32_t uid = -1;
147         if (request->GetOwnerUserId() != SUBSCRIBE_USER_INIT) {
148             if (bundleManager != nullptr) {
149                 uid = bundleManager->GetDefaultUidByBundleName(request->GetOwnerBundleName(),
150                 request->GetOwnerUserId());
151             }
152             if (uid < 0) {
153                 return ERR_ANS_INVALID_UID;
154             }
155         } else {
156             int32_t userId = SUBSCRIBE_USER_INIT;
157             if (request->GetOwnerUid() < DEFAULT_UID) {
158                 return ERR_ANS_GET_ACTIVE_USER_FAILED;
159             }
160             if (request->GetOwnerUid() == DEFAULT_UID) {
161                 OsAccountManagerHelper::GetInstance().GetCurrentActiveUserId(userId);
162                 uid = bundleManager->GetDefaultUidByBundleName(request->GetOwnerBundleName(), userId);
163             } else {
164                 uid = request->GetOwnerUid();
165             }
166         }
167         request->SetOwnerUid(uid);
168         // set agentBundle
169         std::string bundle = "";
170         if (!AccessTokenHelper::VerifyNativeToken(IPCSkeleton::GetCallingTokenID())) {
171             bundle = GetClientBundleName();
172             if (bundle.empty()) {
173                 ANS_LOGE("Failed to GetClientBundleName");
174                 return ERR_ANS_INVALID_BUNDLE;
175             }
176         }
177 
178         int32_t agentUid = IPCSkeleton::GetCallingUid();
179         std::shared_ptr<NotificationBundleOption> agentBundle =
180             std::make_shared<NotificationBundleOption>(bundle, agentUid);
181         if (agentBundle == nullptr) {
182             ANS_LOGE("Failed to create agentBundle instance");
183             return ERR_ANS_INVALID_BUNDLE;
184         }
185         request->SetAgentBundle(agentBundle);
186     } else {
187         std::string sourceBundleName =
188             request->GetBundleOption() == nullptr ? "" : request->GetBundleOption()->GetBundleName();
189         if (!sourceBundleName.empty() && NotificationPreferences::GetInstance()->IsAgentRelationship(
190             bundle, sourceBundleName)) {
191             ANS_LOGD("There is agent relationship between %{public}s and %{public}s",
192                 bundle.c_str(), sourceBundleName.c_str());
193             if (request->GetBundleOption()->GetUid() < DEFAULT_UID) {
194                 return ERR_ANS_INVALID_UID;
195             }
196             int32_t uid = -1;
197             if (request->GetBundleOption()->GetUid() == DEFAULT_UID) {
198                 int32_t userId = SUBSCRIBE_USER_INIT;
199                 OsAccountManagerHelper::GetInstance().GetCurrentActiveUserId(userId);
200                 if (request->GetOwnerUserId() != SUBSCRIBE_USER_INIT) {
201                     userId = request->GetOwnerUserId();
202                 }
203                 std::shared_ptr<BundleManagerHelper> bundleManager = BundleManagerHelper::GetInstance();
204                 if (bundleManager != nullptr) {
205                     uid = bundleManager->GetDefaultUidByBundleName(sourceBundleName, userId);
206                 }
207             } else {
208                 uid = request->GetBundleOption()->GetUid();
209             }
210             if (uid < 0) {
211                 return ERR_ANS_INVALID_UID;
212             }
213             request->SetOwnerUid(uid);
214             int32_t agentUid = IPCSkeleton::GetCallingUid();
215             std::shared_ptr<NotificationBundleOption> agentBundle =
216                 std::make_shared<NotificationBundleOption>(bundle, agentUid);
217             if (agentBundle == nullptr) {
218                 ANS_LOGE("Failed to create agentBundle instance");
219                 return ERR_ANS_INVALID_BUNDLE;
220             }
221             request->SetAgentBundle(agentBundle);
222         }
223         request->SetOwnerBundleName(sourceBundleName);
224     }
225 
226     int32_t uid = IPCSkeleton::GetCallingUid();
227     int32_t pid = IPCSkeleton::GetCallingPid();
228     request->SetCreatorUid(uid);
229     request->SetCreatorPid(pid);
230     if (request->GetOwnerUid() == DEFAULT_UID) {
231         request->SetOwnerUid(uid);
232     }
233 
234     int32_t userId = SUBSCRIBE_USER_INIT;
235     OsAccountManagerHelper::GetInstance().GetOsAccountLocalIdFromUid(uid, userId);
236     request->SetCreatorUserId(userId);
237     request->SetCreatorBundleName(bundle);
238     if (request->GetOwnerBundleName().empty()) {
239         request->SetOwnerBundleName(bundle);
240     }
241     if (request->GetOwnerUserId() == SUBSCRIBE_USER_INIT) {
242         int32_t ownerUserId = SUBSCRIBE_USER_INIT;
243         OsAccountManagerHelper::GetInstance().GetOsAccountLocalIdFromUid(request->GetOwnerUid(), ownerUserId);
244         request->SetOwnerUserId(ownerUserId);
245         std::shared_ptr<AAFwk::WantParams> additionalData = request->GetAdditionalData();
246         if (AccessTokenHelper::CheckPermission(OHOS_PERMISSION_NOTIFICATION_CONTROLLER) &&
247             AccessTokenHelper::CheckPermission(OHOS_PERMISSION_NOTIFICATION_AGENT_CONTROLLER) &&
248             additionalData && additionalData->HasParam("is_ancoNotification")) {
249             AAFwk::IBoolean *bo = AAFwk::IBoolean::Query(additionalData->GetParam("is_ancoNotification"));
250             if (AAFwk::Boolean::Unbox(bo)) {
251                 ANS_LOGI("push publish notification");
252                 request->SetOwnerUserId(DEFAULT_USER_ID);
253             }
254         }
255     }
256 
257     ErrCode result = CheckPictureSize(request);
258 
259     if (request->GetDeliveryTime() <= 0) {
260         request->SetDeliveryTime(GetCurrentTime());
261     }
262 
263     FillActionButtons(request);
264     return result;
265 }
266 
GetInstance()267 sptr<AdvancedNotificationService> AdvancedNotificationService::GetInstance()
268 {
269     std::lock_guard<std::mutex> lock(instanceMutex_);
270 
271     if (instance_ == nullptr) {
272         instance_ = new (std::nothrow) AdvancedNotificationService();
273         if (instance_ == nullptr) {
274             ANS_LOGE("Failed to create AdvancedNotificationService instance");
275             return nullptr;
276         }
277     }
278 
279     return instance_;
280 }
281 
GetDefaultSlotConfig()282 std::map<std::string, uint32_t>& AdvancedNotificationService::GetDefaultSlotConfig()
283 {
284     return slotFlagsDefaultMap_;
285 }
286 
287 #ifdef DISTRIBUTED_NOTIFICATION_SUPPORTED
InitDistributeCallBack()288 void AdvancedNotificationService::InitDistributeCallBack()
289 {
290     DistributedNotificationManager::IDistributedCallback distributedCallback = {
291         .OnPublish = std::bind(&AdvancedNotificationService::OnDistributedPublish,
292             this,
293             std::placeholders::_1,
294             std::placeholders::_2,
295             std::placeholders::_3),
296         .OnUpdate = std::bind(&AdvancedNotificationService::OnDistributedUpdate,
297             this,
298             std::placeholders::_1,
299             std::placeholders::_2,
300             std::placeholders::_3),
301         .OnDelete = std::bind(&AdvancedNotificationService::OnDistributedDelete,
302             this,
303             std::placeholders::_1,
304             std::placeholders::_2,
305             std::placeholders::_3,
306             std::placeholders::_4),
307     };
308     DistributedNotificationManager::GetInstance()->RegisterCallback(distributedCallback);
309 }
310 #endif
311 
AdvancedNotificationService()312 AdvancedNotificationService::AdvancedNotificationService()
313 {
314     ANS_LOGI("constructor");
315     notificationSvrQueue_ = std::make_shared<ffrt::queue>("NotificationSvrMain");
316     if (!notificationSvrQueue_) {
317         ANS_LOGE("ffrt create failed!");
318         return;
319     }
320     soundPermissionInfo_ = std::make_shared<SoundPermissionInfo>();
321     recentInfo_ = std::make_shared<RecentInfo>();
322 #ifdef DISABLE_DISTRIBUTED_NOTIFICATION_SUPPORTED
323     distributedKvStoreDeathRecipient_ = std::make_shared<DistributedKvStoreDeathRecipient>(
324         std::bind(&AdvancedNotificationService::OnDistributedKvStoreDeathRecipient, this));
325 #endif
326     permissonFilter_ = std::make_shared<PermissionFilter>();
327     notificationSlotFilter_ = std::make_shared<NotificationSlotFilter>();
328     StartFilters();
329 
330     RecoverLiveViewFromDb();
331 
332     ISystemEvent iSystemEvent = {
333         std::bind(&AdvancedNotificationService::OnBundleRemoved, this, std::placeholders::_1),
334 #ifdef DISTRIBUTED_NOTIFICATION_SUPPORTED
335         std::bind(&AdvancedNotificationService::OnScreenOn, this),
336         std::bind(&AdvancedNotificationService::OnScreenOff, this),
337 #endif
338         std::bind(&AdvancedNotificationService::OnResourceRemove, this, std::placeholders::_1),
339         std::bind(&AdvancedNotificationService::OnBundleDataCleared, this, std::placeholders::_1),
340         std::bind(&AdvancedNotificationService::OnBundleDataAdd, this, std::placeholders::_1),
341         std::bind(&AdvancedNotificationService::OnBundleDataUpdate, this, std::placeholders::_1),
342         std::bind(&AdvancedNotificationService::OnBootSystemCompleted, this),
343     };
344     systemEventObserver_ = std::make_shared<SystemEventObserver>(iSystemEvent);
345 #ifdef DISABLE_DISTRIBUTED_NOTIFICATION_SUPPORTED
346     dataManager_.RegisterKvStoreServiceDeathRecipient(distributedKvStoreDeathRecipient_);
347 #endif
348     DelayedSingleton<NotificationConfigParse>::GetInstance()->GetReportTrustListConfig();
349 #ifdef DISTRIBUTED_NOTIFICATION_SUPPORTED
350     InitDistributeCallBack();
351 #endif
352 }
353 
~AdvancedNotificationService()354 AdvancedNotificationService::~AdvancedNotificationService()
355 {
356     ANS_LOGI("deconstructor");
357     NotificationSubscriberManager::GetInstance()->UnRegisterOnSubscriberAddCallback();
358 
359     StopFilters();
360 #ifdef DISTRIBUTED_NOTIFICATION_SUPPORTED
361     DistributedNotificationManager::GetInstance()->UngegisterCallback();
362 #endif
363     SelfClean();
364     slotFlagsDefaultMap_.clear();
365 }
366 
SelfClean()367 void AdvancedNotificationService::SelfClean()
368 {
369     if (notificationSvrQueue_ != nullptr) {
370         notificationSvrQueue_.reset();
371     }
372 
373     NotificationSubscriberManager::GetInstance()->ResetFfrtQueue();
374 #ifdef DISTRIBUTED_NOTIFICATION_SUPPORTED
375     DistributedNotificationManager::GetInstance()->ResetFfrtQueue();
376 #endif
377     NotificationLocalLiveViewSubscriberManager::GetInstance()->ResetFfrtQueue();
378 }
379 
AssignToNotificationList(const std::shared_ptr<NotificationRecord> & record)380 ErrCode AdvancedNotificationService::AssignToNotificationList(const std::shared_ptr<NotificationRecord> &record)
381 {
382     ErrCode result = ERR_OK;
383     if (!IsNotificationExists(record->notification->GetKey())) {
384         if (record->request->IsUpdateOnly()) {
385             ANS_LOGW("Notification not exists when update");
386             return ERR_ANS_NOTIFICATION_NOT_EXISTS;
387         }
388         record->request->SetCreateTime(GetCurrentTime());
389         result = PublishInNotificationList(record);
390     } else {
391         if (record->request->IsAlertOneTime()) {
392             CloseAlert(record);
393         }
394         result = UpdateInNotificationList(record);
395     }
396     return result;
397 }
398 
CancelPreparedNotification(int32_t notificationId,const std::string & label,const sptr<NotificationBundleOption> & bundleOption,int32_t reason)399 ErrCode AdvancedNotificationService::CancelPreparedNotification(int32_t notificationId,
400     const std::string &label, const sptr<NotificationBundleOption> &bundleOption, int32_t reason)
401 {
402     HITRACE_METER_NAME(HITRACE_TAG_NOTIFICATION, __PRETTY_FUNCTION__);
403     if (bundleOption == nullptr) {
404         std::string message = "bundleOption is null";
405         OHOS::Notification::HaMetaMessage haMetaMessage = HaMetaMessage(1, 2)
406             .ErrorCode(ERR_ANS_INVALID_BUNDLE).NotificationId(notificationId);
407         ReportDeleteFailedEventPush(haMetaMessage, reason, message);
408         ANS_LOGE("%{public}s", message.c_str());
409         return ERR_ANS_INVALID_BUNDLE;
410     }
411 
412     if (notificationSvrQueue_ == nullptr) {
413         std::string message = "notificationSvrQueue is null";
414         ANS_LOGE("%{public}s", message.c_str());
415         return ERR_ANS_INVALID_PARAM;
416     }
417     ErrCode result = ERR_OK;
418     ffrt::task_handle handler = notificationSvrQueue_->submit_h(std::bind([&]() {
419         ANS_LOGD("ffrt enter!");
420         sptr<Notification> notification = nullptr;
421         NotificationKey notificationKey;
422         notificationKey.id = notificationId;
423         notificationKey.label = label;
424         result = RemoveFromNotificationList(bundleOption, notificationKey, notification, reason, true);
425         if (result != ERR_OK) {
426             return;
427         }
428 
429         if (notification != nullptr) {
430             UpdateRecentNotification(notification, true, reason);
431             CancelTimer(notification->GetAutoDeletedTimer());
432             NotificationSubscriberManager::GetInstance()->NotifyCanceled(notification, nullptr, reason);
433 #ifdef DISTRIBUTED_NOTIFICATION_SUPPORTED
434             DoDistributedDelete("", "", notification);
435 #endif
436         }
437     }));
438     notificationSvrQueue_->wait(handler);
439     SendCancelHiSysEvent(notificationId, label, bundleOption, result);
440     return result;
441 }
442 
PrepareNotificationInfo(const sptr<NotificationRequest> & request,sptr<NotificationBundleOption> & bundleOption)443 ErrCode AdvancedNotificationService::PrepareNotificationInfo(
444     const sptr<NotificationRequest> &request, sptr<NotificationBundleOption> &bundleOption)
445 {
446     HITRACE_METER_NAME(HITRACE_TAG_NOTIFICATION, __PRETTY_FUNCTION__);
447     if (request == nullptr) {
448         ANS_LOGE("request is invalid.");
449         return ERR_ANS_INVALID_PARAM;
450     }
451     bool isSubsystem = AccessTokenHelper::VerifyNativeToken(IPCSkeleton::GetCallingTokenID());
452     if ((request->GetSlotType() == NotificationConstant::SlotType::CUSTOM) &&
453         !AccessTokenHelper::IsSystemApp() && !isSubsystem) {
454         return ERR_ANS_NON_SYSTEM_APP;
455     }
456     ErrCode result = PrepareNotificationRequest(request);
457     if (result != ERR_OK) {
458         return result;
459     }
460     std::string sourceBundleName =
461         request->GetBundleOption() == nullptr ? "" : request->GetBundleOption()->GetBundleName();
462     if (request->IsAgentNotification()) {
463         bundleOption = new (std::nothrow) NotificationBundleOption(request->GetOwnerBundleName(),
464             request->GetOwnerUid());
465     } else {
466         if ((!sourceBundleName.empty() &&
467             NotificationPreferences::GetInstance()->IsAgentRelationship(GetClientBundleName(), sourceBundleName) &&
468             !AccessTokenHelper::CheckPermission(OHOS_PERMISSION_NOTIFICATION_AGENT_CONTROLLER))) {
469             request->SetCreatorUid(request->GetOwnerUid());
470             request->SetCreatorBundleName(request->GetOwnerBundleName());
471             bundleOption = new (std::nothrow) NotificationBundleOption(request->GetOwnerBundleName(),
472                 request->GetOwnerUid());
473         } else {
474             bundleOption = new (std::nothrow) NotificationBundleOption(request->GetCreatorBundleName(),
475                 request->GetCreatorUid());
476         }
477     }
478 
479     if (bundleOption == nullptr) {
480         return ERR_ANS_INVALID_BUNDLE;
481     }
482     SetClassificationWithVoip(request);
483     ANS_LOGI(
484         "bundleName=%{public}s, uid=%{public}d", (bundleOption->GetBundleName()).c_str(), bundleOption->GetUid());
485 
486     SetRequestBySlotType(request, bundleOption);
487     return ERR_OK;
488 }
489 
StartFinishTimer(const std::shared_ptr<NotificationRecord> & record,int64_t expiredTimePoint,const int32_t reason)490 ErrCode AdvancedNotificationService::StartFinishTimer(const std::shared_ptr<NotificationRecord> &record,
491     int64_t expiredTimePoint, const int32_t reason)
492 {
493     uint64_t timerId = StartAutoDelete(record,
494         expiredTimePoint, reason);
495     if (timerId == NotificationConstant::INVALID_TIMER_ID) {
496         std::string message = "Start finish auto delete timer failed.";
497         OHOS::Notification::HaMetaMessage haMetaMessage = HaMetaMessage(7, 1)
498             .ErrorCode(ERR_ANS_TASK_ERR);
499         ReportDeleteFailedEventPush(haMetaMessage, reason, message);
500         ANS_LOGE("%{public}s", message.c_str());
501         return ERR_ANS_TASK_ERR;
502     }
503     record->notification->SetFinishTimer(timerId);
504     return ERR_OK;
505 }
506 
SetFinishTimer(const std::shared_ptr<NotificationRecord> & record)507 ErrCode AdvancedNotificationService::SetFinishTimer(const std::shared_ptr<NotificationRecord> &record)
508 {
509     int64_t maxExpiredTime = GetCurrentTime() + NotificationConstant::MAX_FINISH_TIME;
510     auto result = StartFinishTimer(record, maxExpiredTime,
511         NotificationConstant::TRIGGER_EIGHT_HOUR_REASON_DELETE);
512     if (result != ERR_OK) {
513         return result;
514     }
515     record->request->SetFinishDeadLine(maxExpiredTime);
516     return ERR_OK;
517 }
518 
CancelFinishTimer(const std::shared_ptr<NotificationRecord> & record)519 void AdvancedNotificationService::CancelFinishTimer(const std::shared_ptr<NotificationRecord> &record)
520 {
521     record->request->SetFinishDeadLine(0);
522     CancelTimer(record->notification->GetFinishTimer());
523     record->notification->SetFinishTimer(NotificationConstant::INVALID_TIMER_ID);
524 }
525 
StartUpdateTimer(const std::shared_ptr<NotificationRecord> & record,int64_t expireTimePoint,const int32_t reason)526 ErrCode AdvancedNotificationService::StartUpdateTimer(
527     const std::shared_ptr<NotificationRecord> &record, int64_t expireTimePoint,
528     const int32_t reason)
529 {
530     uint64_t timerId = StartAutoDelete(record,
531         expireTimePoint, reason);
532     if (timerId == NotificationConstant::INVALID_TIMER_ID) {
533         std::string message = "Start update auto delete timer failed.";
534         OHOS::Notification::HaMetaMessage haMetaMessage = HaMetaMessage(7, 2)
535             .ErrorCode(ERR_ANS_TASK_ERR);
536         ReportDeleteFailedEventPush(haMetaMessage, reason, message);
537         ANS_LOGE("%{public}s", message.c_str());
538         return ERR_ANS_TASK_ERR;
539     }
540     record->notification->SetUpdateTimer(timerId);
541     return ERR_OK;
542 }
543 
SetUpdateTimer(const std::shared_ptr<NotificationRecord> & record)544 ErrCode AdvancedNotificationService::SetUpdateTimer(const std::shared_ptr<NotificationRecord> &record)
545 {
546     int64_t maxExpiredTime = GetCurrentTime() + NotificationConstant::MAX_UPDATE_TIME;
547     ErrCode result = StartUpdateTimer(record, maxExpiredTime,
548         NotificationConstant::TRIGGER_FOUR_HOUR_REASON_DELETE);
549     if (result != ERR_OK) {
550         return result;
551     }
552     record->request->SetUpdateDeadLine(maxExpiredTime);
553     return ERR_OK;
554 }
555 
CancelUpdateTimer(const std::shared_ptr<NotificationRecord> & record)556 void AdvancedNotificationService::CancelUpdateTimer(const std::shared_ptr<NotificationRecord> &record)
557 {
558     record->request->SetUpdateDeadLine(0);
559     CancelTimer(record->notification->GetUpdateTimer());
560     record->notification->SetUpdateTimer(NotificationConstant::INVALID_TIMER_ID);
561 }
562 
StartArchiveTimer(const std::shared_ptr<NotificationRecord> & record)563 void AdvancedNotificationService::StartArchiveTimer(const std::shared_ptr<NotificationRecord> &record)
564 {
565     auto deleteTime = record->request->GetAutoDeletedTime();
566     if (deleteTime == NotificationConstant::NO_DELAY_DELETE_TIME) {
567         TriggerAutoDelete(record->notification->GetKey(),
568             NotificationConstant::TRIGGER_START_ARCHIVE_REASON_DELETE);
569         return;
570     }
571     if (deleteTime <= NotificationConstant::INVALID_AUTO_DELETE_TIME) {
572         deleteTime = NotificationConstant::DEFAULT_AUTO_DELETE_TIME;
573     }
574     int64_t maxExpiredTime = GetCurrentTime() +
575         NotificationConstant::SECOND_TO_MS * deleteTime;
576     uint64_t timerId = StartAutoDelete(record,
577         maxExpiredTime, NotificationConstant::TRIGGER_START_ARCHIVE_REASON_DELETE);
578     if (timerId == NotificationConstant::INVALID_TIMER_ID) {
579         ANS_LOGE("Start archive auto delete timer failed.");
580     }
581     record->notification->SetArchiveTimer(timerId);
582 }
583 
CancelArchiveTimer(const std::shared_ptr<NotificationRecord> & record)584 void AdvancedNotificationService::CancelArchiveTimer(const std::shared_ptr<NotificationRecord> &record)
585 {
586     record->request->SetArchiveDeadLine(0);
587     CancelTimer(record->notification->GetArchiveTimer());
588     record->notification->SetArchiveTimer(NotificationConstant::INVALID_TIMER_ID);
589 }
590 
StartAutoDeletedTimer(const std::shared_ptr<NotificationRecord> & record)591 ErrCode AdvancedNotificationService::StartAutoDeletedTimer(const std::shared_ptr<NotificationRecord> &record)
592 {
593     uint64_t timerId = StartAutoDelete(record,
594         record->request->GetAutoDeletedTime(), NotificationConstant::TRIGGER_AUTO_DELETE_REASON_DELETE);
595     if (timerId == NotificationConstant::INVALID_TIMER_ID) {
596         std::string message = "Start autoDeleted auto delete timer failed.";
597         ANS_LOGE("%{public}s", message.c_str());
598         return ERR_ANS_TASK_ERR;
599     }
600     record->notification->SetAutoDeletedTimer(timerId);
601     return ERR_OK;
602 }
603 
FillNotificationRecord(const NotificationRequestDb & requestdbObj,std::shared_ptr<NotificationRecord> record)604 ErrCode AdvancedNotificationService::FillNotificationRecord(
605     const NotificationRequestDb &requestdbObj, std::shared_ptr<NotificationRecord> record)
606 {
607     if (requestdbObj.request == nullptr || requestdbObj.bundleOption == nullptr || record == nullptr) {
608         ANS_LOGE("Invalid param.");
609         return ERR_ANS_INVALID_PARAM;
610     }
611 
612     record->request = requestdbObj.request;
613     record->notification = new (std::nothrow) Notification(requestdbObj.request);
614     if (record->notification == nullptr) {
615         ANS_LOGE("Failed to create notification.");
616         return ERR_ANS_NO_MEMORY;
617     }
618     SetNotificationRemindType(record->notification, true);
619 
620     record->bundleOption = requestdbObj.bundleOption;
621     ErrCode ret = AssignValidNotificationSlot(record, record->bundleOption);
622     if (ret != ERR_OK) {
623         ANS_LOGE("Assign valid notification slot failed!");
624         return ret;
625     }
626 
627     return ERR_OK;
628 }
629 
MakeNotificationRecord(const sptr<NotificationRequest> & request,const sptr<NotificationBundleOption> & bundleOption)630 std::shared_ptr<NotificationRecord> AdvancedNotificationService::MakeNotificationRecord(
631     const sptr<NotificationRequest> &request, const sptr<NotificationBundleOption> &bundleOption)
632 {
633     auto record = std::make_shared<NotificationRecord>();
634     record->request = request;
635     record->notification = new (std::nothrow) Notification(request);
636     if (record->notification == nullptr) {
637         ANS_LOGE("Failed to create notification.");
638         return nullptr;
639     }
640     if (bundleOption != nullptr) {
641         bundleOption->SetAppInstanceKey(request->GetAppInstanceKey());
642     }
643     record->bundleOption = bundleOption;
644     SetNotificationRemindType(record->notification, true);
645     return record;
646 }
647 
PublishPreparedNotification(const sptr<NotificationRequest> & request,const sptr<NotificationBundleOption> & bundleOption,bool isUpdateByOwner)648 ErrCode AdvancedNotificationService::PublishPreparedNotification(const sptr<NotificationRequest> &request,
649     const sptr<NotificationBundleOption> &bundleOption, bool isUpdateByOwner)
650 {
651     HITRACE_METER_NAME(HITRACE_TAG_NOTIFICATION, __PRETTY_FUNCTION__);
652     ANS_LOGI("PublishPreparedNotification");
653     auto tokenCaller = IPCSkeleton::GetCallingTokenID();
654     bool isAgentController = AccessTokenHelper::VerifyCallerPermission(tokenCaller,
655         OHOS_PERMISSION_NOTIFICATION_AGENT_CONTROLLER);
656     HaMetaMessage message = HaMetaMessage(EventSceneId::SCENE_5, EventBranchId::BRANCH_1);
657 #ifdef ENABLE_ANS_ADDITIONAL_CONTROL
658     NotificationConstant::SlotType oldType = request->GetSlotType();
659     int32_t ctrlResult = EXTENTION_WRAPPER->LocalControl(request);
660     if (ctrlResult != ERR_OK) {
661         message.ErrorCode(ctrlResult);
662         NotificationAnalyticsUtil::ReportPublishFailedEvent(request, message);
663         return ctrlResult;
664     }
665     if (request->GetSlotType() != oldType) {
666         SetRequestBySlotType(request, bundleOption);
667     }
668 #endif
669     bool isSystemApp = AccessTokenHelper::IsSystemApp();
670     bool isSubsystem = AccessTokenHelper::VerifyNativeToken(tokenCaller);
671     bool isThirdparty;
672     if (isSystemApp || isSubsystem) {
673         isThirdparty = false;
674     } else {
675         isThirdparty = true;
676     }
677     auto record = MakeNotificationRecord(request, bundleOption);
678     if (record == nullptr) {
679         ANS_LOGE("Make notification record failed.");
680         return ERR_ANS_NO_MEMORY;
681     }
682     record->isThirdparty = isThirdparty;
683     ErrCode result = CheckPublishPreparedNotification(record, isSystemApp);
684     if (result != ERR_OK) {
685         message.ErrorCode(result);
686         NotificationAnalyticsUtil::ReportPublishFailedEvent(request, message);
687         return result;
688     }
689     bool isDisableNotification = IsNeedToControllerByDisableNotification(request);
690     auto ownerBundleName = request->GetOwnerBundleName();
691 #ifdef ENABLE_ANS_AGGREGATION
692     EXTENTION_WRAPPER->GetUnifiedGroupInfo(request);
693 #endif
694     const int32_t uid = IPCSkeleton::GetCallingUid();
695     ffrt::task_handle handler = notificationSvrQueue_->submit_h(std::bind([&]() {
696         ANS_LOGD("ffrt enter!");
697         if (isDisableNotification && IsDisableNotification(ownerBundleName)) {
698             ANS_LOGE("bundle: %{public}s in disable notification list", (request->GetOwnerBundleName()).c_str());
699             result = ERR_ANS_REJECTED_WITH_DISABLE_NOTIFICATION;
700             return;
701         }
702         if (record->request->GetSlotType() == NotificationConstant::SlotType::LIVE_VIEW &&
703             !LivePublishProcess::GetInstance()->CheckLocalLiveViewSubscribed(record->request, isUpdateByOwner, uid)) {
704             result = ERR_ANS_INVALID_PARAM;
705             ANS_LOGE("CheckLocalLiveViewSubscribed Failed!");
706             return;
707         }
708         if (DuplicateMsgControl(record->request) == ERR_ANS_DUPLICATE_MSG) {
709             (void)PublishRemoveDuplicateEvent(record);
710             return;
711         }
712         bool isNotificationExists = IsNotificationExists(record->notification->GetKey());
713         result = FlowControlService::GetInstance()->FlowControl(record, uid, isNotificationExists);
714         if (result != ERR_OK) {
715             return;
716         }
717         result = AddRecordToMemory(record, isSystemApp, isUpdateByOwner, isAgentController);
718         if (result != ERR_OK) {
719             return;
720         }
721 
722         UpdateRecentNotification(record->notification, false, 0);
723         UpdateSlotAuthInfo(record);
724         sptr<NotificationSortingMap> sortingMap = GenerateSortingMap();
725         ReportInfoToResourceSchedule(request->GetCreatorUserId(), bundleOption->GetBundleName());
726         if (IsNeedNotifyConsumed(record->request)) {
727             NotificationSubscriberManager::GetInstance()->NotifyConsumed(record->notification, sortingMap);
728         }
729 #ifdef DISTRIBUTED_NOTIFICATION_SUPPORTED
730         if (!request->IsAgentNotification()) {
731             DoDistributedPublish(bundleOption, record);
732         }
733 #endif
734         NotificationRequestDb requestDb = { .request = record->request, .bundleOption = bundleOption};
735         UpdateNotificationTimerInfo(record);
736         result = SetNotificationRequestToDb(requestDb);
737         if (result != ERR_OK) {
738             return;
739         }
740         NotificationAnalyticsUtil::ReportPublishSuccessEvent(request, message);
741     }));
742     notificationSvrQueue_->wait(handler);
743     // live view handled in UpdateNotificationTimerInfo, ignore here.
744     if ((record->request->GetAutoDeletedTime() > GetCurrentTime()) && !record->request->IsCommonLiveView()) {
745         StartAutoDeletedTimer(record);
746     }
747     return result;
748 }
749 
QueryDoNotDisturbProfile(const int32_t & userId,std::string & enable,std::string & profileId)750 void AdvancedNotificationService::QueryDoNotDisturbProfile(const int32_t &userId,
751     std::string &enable, std::string &profileId)
752 {
753     auto datashareHelper = DelayedSingleton<AdvancedDatashareHelper>::GetInstance();
754     if (datashareHelper == nullptr) {
755         ANS_LOGE("The data share helper is nullptr.");
756         return;
757     }
758     Uri enableUri(datashareHelper->GetFocusModeEnableUri(userId));
759     bool ret = datashareHelper->Query(enableUri, KEY_FOCUS_MODE_ENABLE, enable);
760     if (!ret) {
761         ANS_LOGE("Query focus mode enable fail.");
762         return;
763     }
764     if (enable != DO_NOT_DISTURB_MODE) {
765         ANS_LOGI("Currently not is do not disturb mode.");
766         return;
767     }
768     Uri idUri(datashareHelper->GetFocusModeProfileUri(userId));
769     ret = datashareHelper->Query(idUri, KEY_FOCUS_MODE_PROFILE, profileId);
770     if (!ret) {
771         ANS_LOGE("Query focus mode id fail.");
772         return;
773     }
774 }
775 
QueryIntelligentExperienceEnable(const int32_t & userId,std::string & enable)776 void AdvancedNotificationService::QueryIntelligentExperienceEnable(const int32_t &userId, std::string &enable)
777 {
778     auto datashareHelper = DelayedSingleton<AdvancedDatashareHelper>::GetInstance();
779     if (datashareHelper == nullptr) {
780         ANS_LOGE("The data share helper is nullptr.");
781         return;
782     }
783     Uri enableUri(datashareHelper->GetIntelligentExperienceUri(userId));
784     bool ret = datashareHelper->Query(enableUri, KEY_INTELLIGENT_EXPERIENCE, enable);
785     if (!ret) {
786         ANS_LOGE("Query intelligent experience enable fail.");
787         return;
788     }
789     if (enable == INTELLIGENT_EXPERIENCE) {
790         ANS_LOGI("Currently is intelligent experience.");
791         return;
792     }
793 }
794 
ReportDoNotDisturbModeChanged(const int32_t & userId,std::string & enable)795 void AdvancedNotificationService::ReportDoNotDisturbModeChanged(const int32_t &userId, std::string &enable)
796 {
797     std::lock_guard<std::mutex> lock(doNotDisturbMutex_);
798     HaMetaMessage message = HaMetaMessage(EventSceneId::SCENE_3, EventBranchId::BRANCH_2);
799     std::string info = "Do not disturb mode changed, userId: " + std::to_string(userId) + ", enable: " + enable;
800     auto it = doNotDisturbEnableRecord_.find(userId);
801     if (it != doNotDisturbEnableRecord_.end()) {
802         if (it->second != enable) {
803             ANS_LOGI("%{public}s", info.c_str());
804             message.Message(info);
805             NotificationAnalyticsUtil::ReportModifyEvent(message);
806             doNotDisturbEnableRecord_.insert_or_assign(userId, enable);
807         }
808     } else {
809         if (enable == DO_NOT_DISTURB_MODE) {
810             ANS_LOGI("%{public}s", info.c_str());
811             message.Message(info);
812             NotificationAnalyticsUtil::ReportModifyEvent(message);
813         }
814         doNotDisturbEnableRecord_.insert_or_assign(userId, enable);
815     }
816 }
817 
CheckDoNotDisturbProfile(const std::shared_ptr<NotificationRecord> & record)818 void AdvancedNotificationService::CheckDoNotDisturbProfile(const std::shared_ptr<NotificationRecord> &record)
819 {
820     ANS_LOGD("Called.");
821     if (record == nullptr || record->notification == nullptr || record->bundleOption == nullptr) {
822         ANS_LOGE("Make notification record failed.");
823         return;
824     }
825     int32_t userId = record->notification->GetRecvUserId();
826     if (userId == FIRST_USERID) {
827         OHOS::AccountSA::OsAccountManager::GetForegroundOsAccountLocalId(userId);
828     }
829     std::string enable;
830     std::string profileId;
831     QueryDoNotDisturbProfile(userId, enable, profileId);
832     ReportDoNotDisturbModeChanged(userId, enable);
833     if (enable != DO_NOT_DISTURB_MODE) {
834         ANS_LOGD("Currently not is do not disturb mode.");
835         return;
836     }
837     auto notificationControlFlags = record->request->GetNotificationControlFlags();
838     if ((notificationControlFlags & CONTROL_BY_DO_NOT_DISTURB_MODE) == 0) {
839         record->request->SetNotificationControlFlags(notificationControlFlags | CONTROL_BY_DO_NOT_DISTURB_MODE);
840     }
841     std::string bundleName = record->bundleOption->GetBundleName();
842     ANS_LOGI("The disturbMode is on, userId:%{public}d, bundle:%{public}s, profileId:%{public}s",
843         userId, bundleName.c_str(), profileId.c_str());
844     if (record->request->IsCommonLiveView() || record->request->GetClassification() == ANS_VERIFICATION_CODE) {
845         std::string intelligentExperience;
846         QueryIntelligentExperienceEnable(userId, intelligentExperience);
847         if (intelligentExperience == INTELLIGENT_EXPERIENCE) {
848             notificationControlFlags = record->request->GetNotificationControlFlags();
849             record->request->SetNotificationControlFlags(notificationControlFlags | CONTROL_BY_INTELLIGENT_EXPERIENCE);
850             return;
851         }
852     }
853     sptr<NotificationDoNotDisturbProfile> profile = new (std::nothrow) NotificationDoNotDisturbProfile();
854     if (NotificationPreferences::GetInstance()->GetDoNotDisturbProfile(atoll(profileId.c_str()), userId, profile) !=
855         ERR_OK) {
856         ANS_LOGE("profile failed. pid: %{public}s, userid: %{public}d", profileId.c_str(), userId);
857         return;
858     }
859     if (profile == nullptr) {
860         ANS_LOGE("The do not disturb profile is nullptr.");
861         return;
862     }
863     auto uid = record->bundleOption->GetUid();
864     ANS_LOGD("The uid is %{public}d", uid);
865     std::vector<NotificationBundleOption> trustlist = profile->GetProfileTrustList();
866     for (auto &trust : trustlist) {
867         if ((bundleName == trust.GetBundleName()) &&
868             (trust.GetUid() == BUNDLE_OPTION_UID_DEFAULT_VALUE || trust.GetUid() == uid)) {
869             ANS_LOGW("Do not disturb profile bundle name is in trust.");
870             return;
871         }
872     }
873     DoNotDisturbUpdataReminderFlags(record);
874 }
875 
DoNotDisturbUpdataReminderFlags(const std::shared_ptr<NotificationRecord> & record)876 void AdvancedNotificationService::DoNotDisturbUpdataReminderFlags(const std::shared_ptr<NotificationRecord> &record)
877 {
878     ANS_LOGD("Called.");
879     if (record == nullptr || record->request == nullptr || record->notification == nullptr) {
880         ANS_LOGE("Make notification record failed.");
881         return;
882     }
883     auto flags = record->request->GetFlags();
884     if (flags == nullptr) {
885         ANS_LOGE("The flags is nullptr.");
886         return;
887     }
888     flags->SetSoundEnabled(NotificationConstant::FlagStatus::CLOSE);
889     record->notification->SetEnableSound(false);
890     record->request->SetVisibleness(NotificationConstant::VisiblenessType::SECRET);
891     flags->SetBannerEnabled(false);
892     flags->SetLightScreenEnabled(false);
893     flags->SetVibrationEnabled(NotificationConstant::FlagStatus::CLOSE);
894     record->notification->SetEnableVibration(false);
895 }
896 
UpdateSlotAuthInfo(const std::shared_ptr<NotificationRecord> & record)897 ErrCode AdvancedNotificationService::UpdateSlotAuthInfo(const std::shared_ptr<NotificationRecord> &record)
898 {
899     ErrCode result = ERR_OK;
900     sptr<NotificationSlot> slot = record->slot;
901     // only update auth info for LIVE_VIEW notification
902     if (record->request->GetSlotType() == NotificationConstant::SlotType::LIVE_VIEW) {
903         // update authHintCnt when authorizedStatus is NOT_AUTHORIZED
904         if (slot->GetAuthorizedStatus() == NotificationSlot::AuthorizedStatus::NOT_AUTHORIZED) {
905             slot->AddAuthHintCnt();
906         }
907         // change authorizedStatus to AUTHORIZED when authHintCnt exceeds MAX_LIVEVIEW_HINT_COUNT
908         if (slot->GetAuthHintCnt() > MAX_LIVEVIEW_HINT_COUNT) {
909             slot->SetAuthorizedStatus(NotificationSlot::AuthorizedStatus::AUTHORIZED);
910         }
911     } else {
912         // for other notification, set status to AUTHORIZED directly
913         if (slot->GetAuthorizedStatus() == NotificationSlot::AuthorizedStatus::NOT_AUTHORIZED) {
914             slot->SetAuthorizedStatus(NotificationSlot::AuthorizedStatus::AUTHORIZED);
915         }
916     }
917     if (record->request->IsSystemLiveView()) {
918         ANS_LOGI("System live view no need add sloty.");
919         return ERR_OK;
920     }
921     std::vector<sptr<NotificationSlot>> slots;
922     slots.push_back(slot);
923     result = NotificationPreferences::GetInstance()->AddNotificationSlots(record->bundleOption, slots);
924     ANS_LOGD("UpdateSlotAuthInfo status: %{public}d), cnt: %{public}d, res: %{public}d.",
925         slot->GetAuthorizedStatus(), slot->GetAuthHintCnt(), result);
926     if (result != ERR_OK) {
927         ANS_LOGE("UpdateSlotAuthInfo failed result: %{public}d.", result);
928     }
929     return result;
930 }
931 
ReportInfoToResourceSchedule(const int32_t userId,const std::string & bundleName)932 void AdvancedNotificationService::ReportInfoToResourceSchedule(const int32_t userId, const std::string &bundleName)
933 {
934 #ifdef DEVICE_USAGE_STATISTICS_ENABLE
935     DeviceUsageStats::BundleActiveEvent event(DeviceUsageStats::BundleActiveEvent::NOTIFICATION_SEEN, bundleName);
936     DeviceUsageStats::BundleActiveClient::GetInstance().ReportEvent(event, userId);
937 #endif
938 }
939 
IsNotificationExists(const std::string & key)940 bool AdvancedNotificationService::IsNotificationExists(const std::string &key)
941 {
942     bool isExists = false;
943 
944     for (auto item : notificationList_) {
945         if (item->notification->GetKey() == key) {
946             isExists = true;
947             break;
948         }
949     }
950 
951     return isExists;
952 }
953 
Filter(const std::shared_ptr<NotificationRecord> & record,bool isRecover)954 ErrCode AdvancedNotificationService::Filter(const std::shared_ptr<NotificationRecord> &record, bool isRecover)
955 {
956     ErrCode result = ERR_OK;
957 
958     if (!isRecover) {
959         auto oldRecord = GetFromNotificationList(record->notification->GetKey());
960         result = record->request->CheckNotificationRequest((oldRecord == nullptr) ? nullptr : oldRecord->request);
961         if (result != ERR_OK) {
962             bool liveView = record->request->IsCommonLiveView();
963             int32_t slotType = liveView ? NotificationConstant::SlotType::LIVE_VIEW :
964                 NotificationConstant::SlotType::ILLEGAL_TYPE;
965             HaMetaMessage message = HaMetaMessage(EventSceneId::SCENE_3, EventBranchId::BRANCH_5)
966                 .ErrorCode(result).SlotType(slotType).Message("CheckNotificationRequest failed: ");
967             NotificationAnalyticsUtil::ReportPublishFailedEvent(record->request, message);
968             ANS_LOGE("Notification(key %{public}s) isn't ready on publish failed with %{public}d.",
969                 record->notification->GetKey().c_str(), result);
970             return result;
971         }
972     }
973 
974     if (permissonFilter_ == nullptr || notificationSlotFilter_ == nullptr) {
975         ANS_LOGE("Filter is invalid.");
976         return ERR_ANS_INVALID_PARAM;
977     }
978 
979     result = permissonFilter_->OnPublish(record);
980     if (result != ERR_OK) {
981         ANS_LOGE("Permission filter on publish failed with %{public}d.", result);
982         return result;
983     }
984 
985     result = notificationSlotFilter_->OnPublish(record);
986     if (result != ERR_OK) {
987         ANS_LOGE("Notification slot filter on publish failed with %{public}d.", result);
988         return result;
989     }
990 
991     return ERR_OK;
992 }
993 
ChangeNotificationByControlFlags(const std::shared_ptr<NotificationRecord> & record,const bool isAgentController)994 void AdvancedNotificationService::ChangeNotificationByControlFlags(const std::shared_ptr<NotificationRecord> &record,
995     const bool isAgentController)
996 {
997     ANS_LOGD("Called.");
998     if (record == nullptr || record->request == nullptr || record->notification == nullptr) {
999         ANS_LOGE("Make notification record failed.");
1000         return;
1001     }
1002     uint32_t notificationControlFlags = record->request->GetNotificationControlFlags();
1003     if (notificationControlFlags == 0) {
1004         ANS_LOGD("The notificationControlFlags is undefined.");
1005         return;
1006     }
1007 
1008     if (!isAgentController) {
1009         record->request->SetNotificationControlFlags(notificationControlFlags & 0xFFFF);
1010     }
1011 
1012     auto flags = record->request->GetFlags();
1013     if (flags == nullptr) {
1014         ANS_LOGE("The flags is nullptr.");
1015         return;
1016     }
1017 
1018     if (flags->IsSoundEnabled() == NotificationConstant::FlagStatus::OPEN &&
1019         (notificationControlFlags & NotificationConstant::ReminderFlag::SOUND_FLAG) != 0) {
1020         flags->SetSoundEnabled(NotificationConstant::FlagStatus::CLOSE);
1021         record->notification->SetEnableSound(false);
1022     }
1023 
1024     if (flags->IsLockScreenVisblenessEnabled() &&
1025         (notificationControlFlags & NotificationConstant::ReminderFlag::LOCKSCREEN_FLAG) != 0) {
1026         flags->SetLockScreenVisblenessEnabled(false);
1027         record->request->SetVisibleness(NotificationConstant::VisiblenessType::SECRET);
1028     }
1029 
1030     if (flags->IsBannerEnabled() && (notificationControlFlags & NotificationConstant::ReminderFlag::BANNER_FLAG) != 0) {
1031         flags->SetBannerEnabled(false);
1032     }
1033 
1034     if (flags->IsLightScreenEnabled() &&
1035         (notificationControlFlags & NotificationConstant::ReminderFlag::LIGHTSCREEN_FLAG) != 0) {
1036         flags->SetLightScreenEnabled(false);
1037     }
1038 
1039     if (flags->IsVibrationEnabled() == NotificationConstant::FlagStatus::OPEN &&
1040         (notificationControlFlags & NotificationConstant::ReminderFlag::VIBRATION_FLAG) != 0) {
1041         flags->SetVibrationEnabled(NotificationConstant::FlagStatus::CLOSE);
1042         record->notification->SetEnableVibration(false);
1043     }
1044 
1045     if (flags->IsStatusIconEnabled() &&
1046         (notificationControlFlags & NotificationConstant::ReminderFlag::STATUSBAR_ICON_FLAG) != 0) {
1047         flags->SetStatusIconEnabled(false);
1048     }
1049 
1050 #ifdef ENABLE_ANS_PRIVILEGED_MESSAGE_EXT_WRAPPER
1051     bool isPrivileged = EXTENTION_WRAPPER->ModifyReminderFlags(record->request);
1052     if (isPrivileged) {
1053         record->notification->SetPrivileged(true);
1054         if (flags->IsSoundEnabled() == NotificationConstant::FlagStatus::OPEN) {
1055             record->notification->SetEnableSound(true);
1056             record->notification->SetSound(DEFAULT_NOTIFICATION_SOUND);
1057         }
1058         if (flags->IsVibrationEnabled() == NotificationConstant::FlagStatus::OPEN) {
1059             record->notification->SetEnableVibration(true);
1060         }
1061     }
1062 #endif
1063 }
1064 
CheckPublishPreparedNotification(const std::shared_ptr<NotificationRecord> & record,bool isSystemApp)1065 ErrCode AdvancedNotificationService::CheckPublishPreparedNotification(
1066     const std::shared_ptr<NotificationRecord> &record, bool isSystemApp)
1067 {
1068     if (notificationSvrQueue_ == nullptr) {
1069         ANS_LOGE("Serial queue is invalid.");
1070         return ERR_ANS_INVALID_PARAM;
1071     }
1072 
1073     if (record == nullptr || record->request == nullptr) {
1074         ANS_LOGE("Make notification record failed.");
1075         return ERR_ANS_NO_MEMORY;
1076     }
1077 
1078     if (!isSystemApp && record->request->GetSlotType() == NotificationConstant::SlotType::EMERGENCY_INFORMATION) {
1079         ANS_LOGE("Non system app used illegal slot type.");
1080         return ERR_ANS_INVALID_PARAM;
1081     }
1082 
1083     return ERR_OK;
1084 }
1085 
AddToNotificationList(const std::shared_ptr<NotificationRecord> & record)1086 void AdvancedNotificationService::AddToNotificationList(const std::shared_ptr<NotificationRecord> &record)
1087 {
1088     notificationList_.push_back(record);
1089     SortNotificationList();
1090 }
1091 
ReplyDistributeOperation(const std::string & hashCode,const int32_t result)1092 ErrCode AdvancedNotificationService::ReplyDistributeOperation(const std::string& hashCode, const int32_t result)
1093 {
1094     bool isSubsystem = AccessTokenHelper::VerifyNativeToken(IPCSkeleton::GetCallingTokenID());
1095     if (!isSubsystem && !AccessTokenHelper::IsSystemApp()) {
1096         return ERR_ANS_NON_SYSTEM_APP;
1097     }
1098 
1099     if (!AccessTokenHelper::CheckPermission(OHOS_PERMISSION_NOTIFICATION_CONTROLLER)) {
1100         ANS_LOGD("Check permission is false.");
1101         return ERR_ANS_PERMISSION_DENIED;
1102     }
1103 
1104     if (hashCode.empty()) {
1105         ANS_LOGE("Hash code is invalid.");
1106         return ERR_ANS_INVALID_PARAM;
1107     }
1108     ANS_LOGI("Reply operation key %{public}s %{public}d.", hashCode.c_str(), result);
1109     DistributedOperationService::GetInstance().ReplyOperationResponse(hashCode, result);
1110     return ERR_OK;
1111 }
1112 
GetNotificationRequestByHashCode(const std::string & hashCode,sptr<NotificationRequest> & notificationRequest)1113 ErrCode AdvancedNotificationService::GetNotificationRequestByHashCode(
1114     const std::string& hashCode, sptr<NotificationRequest>& notificationRequest)
1115 {
1116     bool isSubsystem = AccessTokenHelper::VerifyNativeToken(IPCSkeleton::GetCallingTokenID());
1117     if (!isSubsystem && !AccessTokenHelper::IsSystemApp()) {
1118         return ERR_ANS_NON_SYSTEM_APP;
1119     }
1120 
1121     if (!AccessTokenHelper::CheckPermission(OHOS_PERMISSION_NOTIFICATION_CONTROLLER)) {
1122         ANS_LOGD("Check permission is false.");
1123         return ERR_ANS_PERMISSION_DENIED;
1124     }
1125 
1126     if (notificationSvrQueue_ == nullptr) {
1127         ANS_LOGE("Serial queue is invalid.");
1128         return ERR_ANS_INVALID_PARAM;
1129     }
1130 
1131     ffrt::task_handle handler = notificationSvrQueue_->submit_h(std::bind([&]() {
1132         auto record = GetFromNotificationList(hashCode);
1133         if (record != nullptr) {
1134             notificationRequest = record->request;
1135         }
1136     }));
1137     notificationSvrQueue_->wait(handler);
1138     return ERR_OK;
1139 }
1140 
UpdateInNotificationList(const std::shared_ptr<NotificationRecord> & record)1141 ErrCode AdvancedNotificationService::UpdateInNotificationList(const std::shared_ptr<NotificationRecord> &record)
1142 {
1143     auto iter = notificationList_.begin();
1144     while (iter != notificationList_.end()) {
1145         if ((*iter)->notification->GetKey() == record->notification->GetKey()) {
1146             record->request->FillMissingParameters((*iter)->request);
1147             if (record->request->IsCommonLiveView()) {
1148                 LIVEVIEW_ALL_SCENARIOS_EXTENTION_WRAPPER->UpdateLiveviewVoiceContent(record->request);
1149             }
1150             FillLockScreenPicture(record->request, (*iter)->request);
1151             record->notification->SetUpdateTimer((*iter)->notification->GetUpdateTimer());
1152             if (!record->request->IsSystemLiveView()) {
1153                 record->notification->SetFinishTimer((*iter)->notification->GetFinishTimer());
1154             }
1155             *iter = record;
1156             break;
1157         }
1158         iter++;
1159     }
1160 
1161     SortNotificationList();
1162     return ERR_OK;
1163 }
1164 
SortNotificationList()1165 void AdvancedNotificationService::SortNotificationList()
1166 {
1167     notificationList_.sort(AdvancedNotificationService::NotificationCompare);
1168 }
1169 
NotificationCompare(const std::shared_ptr<NotificationRecord> & first,const std::shared_ptr<NotificationRecord> & second)1170 bool AdvancedNotificationService::NotificationCompare(
1171     const std::shared_ptr<NotificationRecord> &first, const std::shared_ptr<NotificationRecord> &second)
1172 {
1173     // sorting notifications by create time
1174     return (first->request->GetCreateTime() < second->request->GetCreateTime());
1175 }
1176 
StartFilters()1177 void AdvancedNotificationService::StartFilters()
1178 {
1179     if (permissonFilter_ != nullptr) {
1180         permissonFilter_->OnStart();
1181     }
1182 
1183     if (notificationSlotFilter_ != nullptr) {
1184         notificationSlotFilter_->OnStart();
1185     }
1186 }
1187 
StopFilters()1188 void AdvancedNotificationService::StopFilters()
1189 {
1190     if (permissonFilter_ != nullptr) {
1191         permissonFilter_->OnStop();
1192     }
1193 
1194     if (notificationSlotFilter_ != nullptr) {
1195         notificationSlotFilter_->OnStop();
1196     }
1197 }
1198 
GetActiveNotifications(std::vector<sptr<NotificationRequest>> & notifications,const std::string & instanceKey)1199 ErrCode AdvancedNotificationService::GetActiveNotifications(
1200     std::vector<sptr<NotificationRequest>> &notifications, const std::string &instanceKey)
1201 {
1202     ANS_LOGD("%{public}s", __FUNCTION__);
1203 
1204     sptr<NotificationBundleOption> bundleOption = GenerateBundleOption();
1205     if (bundleOption == nullptr) {
1206         return ERR_ANS_INVALID_BUNDLE;
1207     }
1208     bundleOption->SetAppInstanceKey(instanceKey);
1209 
1210     if (notificationSvrQueue_ == nullptr) {
1211         ANS_LOGE("Serial queue is invalidated.");
1212         return ERR_ANS_INVALID_PARAM;
1213     }
1214     ffrt::task_handle handler = notificationSvrQueue_->submit_h(std::bind([&]() {
1215         ANS_LOGD("ffrt enter!");
1216         notifications.clear();
1217         for (auto record : notificationList_) {
1218             if ((record->bundleOption->GetBundleName() == bundleOption->GetBundleName()) &&
1219                 (record->bundleOption->GetUid() == bundleOption->GetUid()) &&
1220                 (record->notification->GetInstanceKey() == bundleOption->GetAppInstanceKey())) {
1221                 notifications.push_back(record->request);
1222             }
1223         }
1224     }));
1225     notificationSvrQueue_->wait(handler);
1226     return ERR_OK;
1227 }
1228 
GetActiveNotificationNums(uint64_t & num)1229 ErrCode AdvancedNotificationService::GetActiveNotificationNums(uint64_t &num)
1230 {
1231     ANS_LOGD("%{public}s", __FUNCTION__);
1232 
1233     sptr<NotificationBundleOption> bundleOption = GenerateBundleOption();
1234     if (bundleOption == nullptr) {
1235         ANS_LOGD("BundleOption is nullptr.");
1236         return ERR_ANS_INVALID_BUNDLE;
1237     }
1238 
1239     if (notificationSvrQueue_ == nullptr) {
1240         ANS_LOGE("Serial queue is invalid.");
1241         return ERR_ANS_INVALID_PARAM;
1242     }
1243     ffrt::task_handle handler = notificationSvrQueue_->submit_h(std::bind([&]() {
1244         ANS_LOGD("ffrt enter!");
1245         size_t count = 0;
1246         for (auto record : notificationList_) {
1247             if ((record->bundleOption->GetBundleName() == bundleOption->GetBundleName()) &&
1248                 (record->bundleOption->GetUid() == bundleOption->GetUid())) {
1249                 count += 1;
1250             }
1251         }
1252         num = static_cast<uint64_t>(count);
1253     }));
1254     notificationSvrQueue_->wait(handler);
1255     return ERR_OK;
1256 }
1257 
CanPublishAsBundle(const std::string & representativeBundle,bool & canPublish)1258 ErrCode AdvancedNotificationService::CanPublishAsBundle(const std::string &representativeBundle, bool &canPublish)
1259 {
1260     return ERR_INVALID_OPERATION;
1261 }
1262 
GetBundleImportance(int32_t & importance)1263 ErrCode AdvancedNotificationService::GetBundleImportance(int32_t &importance)
1264 {
1265     ANS_LOGD("%{public}s", __FUNCTION__);
1266 
1267     sptr<NotificationBundleOption> bundleOption = GenerateBundleOption();
1268     if (bundleOption == nullptr) {
1269         ANS_LOGD("GenerateBundleOption failed.");
1270         return ERR_ANS_INVALID_BUNDLE;
1271     }
1272 
1273     if (notificationSvrQueue_ == nullptr) {
1274         ANS_LOGE("Serial queue is invalid.");
1275         return ERR_ANS_INVALID_PARAM;
1276     }
1277     ErrCode result = ERR_OK;
1278     ffrt::task_handle handler = notificationSvrQueue_->submit_h(
1279         std::bind([&]() {
1280             ANS_LOGD("ffrt enter!");
1281             result = NotificationPreferences::GetInstance()->GetImportance(bundleOption, importance);
1282         }));
1283     notificationSvrQueue_->wait(handler);
1284     return result;
1285 }
1286 
HasNotificationPolicyAccessPermission(bool & granted)1287 ErrCode AdvancedNotificationService::HasNotificationPolicyAccessPermission(bool &granted)
1288 {
1289     return ERR_OK;
1290 }
1291 
GetUnifiedGroupInfoFromDb(std::string & enable)1292 ErrCode AdvancedNotificationService::GetUnifiedGroupInfoFromDb(std::string &enable)
1293 {
1294     auto datashareHelper = DelayedSingleton<AdvancedDatashareHelperExt>::GetInstance();
1295     if (datashareHelper == nullptr) {
1296         ANS_LOGE("The data share helper is nullptr.");
1297         return -1;
1298     }
1299     Uri enableUri(datashareHelper->GetUnifiedGroupEnableUri());
1300     bool ret = datashareHelper->Query(enableUri, KEY_UNIFIED_GROUP_ENABLE, enable);
1301     if (!ret) {
1302         ANS_LOGE("Query smart aggregation switch failed.");
1303         return -1;
1304     }
1305 
1306     return ERR_OK;
1307 }
1308 
GetNotificationKeys(const sptr<NotificationBundleOption> & bundleOption)1309 std::vector<std::string> AdvancedNotificationService::GetNotificationKeys(
1310     const sptr<NotificationBundleOption> &bundleOption)
1311 {
1312     std::vector<std::string> keys;
1313 
1314     for (auto record : notificationList_) {
1315         if ((bundleOption != nullptr) &&
1316             (record->bundleOption->GetUid() != bundleOption->GetUid())) {
1317             continue;
1318         }
1319         keys.push_back(record->notification->GetKey());
1320     }
1321 
1322     std::lock_guard<std::mutex> lock(delayNotificationMutext_);
1323     for (auto delayNotification : delayNotificationList_) {
1324         auto delayRequest = delayNotification.first->notification->GetNotificationRequest();
1325         if (bundleOption != nullptr && delayRequest.GetOwnerUid() == bundleOption->GetUid()) {
1326             keys.push_back(delayNotification.first->notification->GetKey());
1327         }
1328     }
1329 
1330     return keys;
1331 }
1332 
GetNotificationKeysByBundle(const sptr<NotificationBundleOption> & bundleOption)1333 std::vector<std::string> AdvancedNotificationService::GetNotificationKeysByBundle(
1334     const sptr<NotificationBundleOption> &bundleOption)
1335 {
1336     std::vector<std::string> keys;
1337     if (bundleOption == nullptr) {
1338         return keys;
1339     }
1340 
1341     for (auto record : notificationList_) {
1342         if ((record->bundleOption->GetUid() != bundleOption->GetUid())) {
1343             continue;
1344         }
1345         ANS_LOGD("GetNotificationKeys instanceKey(%{public}s, %{public}s)",
1346             record->notification->GetInstanceKey().c_str(), bundleOption->GetAppInstanceKey().c_str());
1347         if (record->notification->GetInstanceKey() == "" || bundleOption->GetAppInstanceKey() == "" ||
1348             record->notification->GetInstanceKey() == bundleOption->GetAppInstanceKey()) {
1349                 keys.push_back(record->notification->GetKey());
1350         }
1351     }
1352 
1353     std::lock_guard<std::mutex> lock(delayNotificationMutext_);
1354     for (auto delayNotification : delayNotificationList_) {
1355         auto delayRequest = delayNotification.first->notification->GetNotificationRequest();
1356         if (bundleOption != nullptr && delayRequest.GetOwnerUid() == bundleOption->GetUid()) {
1357             keys.push_back(delayNotification.first->notification->GetKey());
1358         }
1359     }
1360 
1361     return keys;
1362 }
1363 
CancelOnceWantAgent(const std::shared_ptr<AbilityRuntime::WantAgent::WantAgent> & wantAgent)1364 void AdvancedNotificationService::CancelOnceWantAgent(
1365     const std::shared_ptr<AbilityRuntime::WantAgent::WantAgent> &wantAgent)
1366 {
1367     AbilityRuntime::WantAgent::WantAgentHelper::Cancel(wantAgent, AbilityRuntime::WantAgent::FLAG_ONE_SHOT |
1368         AbilityRuntime::WantAgent::FLAG_ALLOW_CANCEL);
1369 }
1370 
CancelWantAgent(const sptr<Notification> & notification)1371 void AdvancedNotificationService::CancelWantAgent(const sptr<Notification> &notification)
1372 {
1373     if (notification->GetNotificationRequestPoint()->GetWantAgent()) {
1374         CancelOnceWantAgent(notification->GetNotificationRequestPoint()->GetWantAgent());
1375     }
1376     if (notification->GetNotificationRequestPoint()->GetRemovalWantAgent()) {
1377         CancelOnceWantAgent(notification->GetNotificationRequestPoint()->GetRemovalWantAgent());
1378     }
1379     if (notification->GetNotificationRequestPoint()->GetMaxScreenWantAgent()) {
1380         CancelOnceWantAgent(notification->GetNotificationRequestPoint()->GetMaxScreenWantAgent());
1381     }
1382     auto actionButtons = notification->GetNotificationRequestPoint()->GetActionButtons();
1383     for (auto it = actionButtons.begin(); it != actionButtons.end(); ++it) {
1384         CancelOnceWantAgent((*it)->GetWantAgent());
1385     }
1386     auto content = notification->GetNotificationRequestPoint()->GetContent();
1387     if (content != nullptr && content->GetContentType() == NotificationContent::Type::MULTILINE) {
1388         auto multiLineContent =
1389             std::static_pointer_cast<NotificationMultiLineContent>(content->GetNotificationContent());
1390         if (multiLineContent != nullptr) {
1391             auto lineWantAgents = multiLineContent->GetLineWantAgents();
1392             for (auto it = lineWantAgents.begin(); it != lineWantAgents.end(); ++it) {
1393                 CancelOnceWantAgent(*it);
1394             }
1395         }
1396     }
1397 }
1398 
RemoveFromNotificationList(const sptr<NotificationBundleOption> & bundleOption,NotificationKey notificationKey,sptr<Notification> & notification,int32_t removeReason,bool isCancel)1399 ErrCode AdvancedNotificationService::RemoveFromNotificationList(const sptr<NotificationBundleOption> &bundleOption,
1400     NotificationKey notificationKey, sptr<Notification> &notification, int32_t removeReason, bool isCancel)
1401 {
1402     for (auto record : notificationList_) {
1403         if ((record->bundleOption->GetBundleName() == bundleOption->GetBundleName()) &&
1404             (record->bundleOption->GetUid() == bundleOption->GetUid()) &&
1405             (record->notification->GetInstanceKey() == bundleOption->GetAppInstanceKey()) &&
1406             (record->notification->GetLabel() == notificationKey.label) &&
1407             (record->notification->GetId() == notificationKey.id)
1408 #ifdef DISTRIBUTED_NOTIFICATION_SUPPORTED
1409             && record->deviceId.empty()
1410 #endif
1411         ) {
1412             if (!isCancel && !record->notification->IsRemoveAllowed()) {
1413                 ANS_LOGI("UnRemoved-%{public}s", record->notification->GetKey().c_str());
1414                 return ERR_ANS_NOTIFICATION_IS_UNALLOWED_REMOVEALLOWED;
1415             }
1416             notification = record->notification;
1417             // delete or delete all, call the function
1418             if (!isCancel) {
1419                 TriggerRemoveWantAgent(record->request, removeReason, record->isThirdparty);
1420             }
1421             CancelWantAgent(notification);
1422             ProcForDeleteLiveView(record);
1423             notificationList_.remove(record);
1424             if (IsSaCreateSystemLiveViewAsBundle(record,
1425                 record->notification->GetNotificationRequest().GetCreatorUid())) {
1426                 SendLiveViewUploadHiSysEvent(record, UploadStatus::END);
1427             }
1428             return ERR_OK;
1429         }
1430     }
1431 
1432     std::lock_guard<std::mutex> lock(delayNotificationMutext_);
1433     for (auto delayNotification : delayNotificationList_) {
1434         if ((delayNotification.first->bundleOption->GetUid() == bundleOption->GetUid()) &&
1435             (delayNotification.first->notification->GetLabel() == notificationKey.label) &&
1436             (delayNotification.first->notification->GetId() == notificationKey.id)) {
1437             CancelTimer(delayNotification.second);
1438             delayNotificationList_.remove(delayNotification);
1439             return ERR_OK;
1440         }
1441     }
1442     ANS_LOGE("notification not exist,notification:%{public}d, bundleName:%{public}s, uid:%{public}d",
1443         notificationKey.id, bundleOption->GetBundleName().c_str(), bundleOption->GetUid());
1444     return ERR_ANS_NOTIFICATION_NOT_EXISTS;
1445 }
1446 
RemoveFromNotificationList(const std::string & key,sptr<Notification> & notification,bool isCancel,int32_t removeReason)1447 ErrCode AdvancedNotificationService::RemoveFromNotificationList(
1448     const std::string &key, sptr<Notification> &notification, bool isCancel, int32_t removeReason)
1449 {
1450     for (auto record : notificationList_) {
1451         if (record->notification->GetKey() != key) {
1452             continue;
1453         }
1454 
1455         if (!isCancel && !record->notification->IsRemoveAllowed()) {
1456             ANS_LOGI("UnRemoved-%{public}s", record->notification->GetKey().c_str());
1457             return ERR_ANS_NOTIFICATION_IS_UNALLOWED_REMOVEALLOWED;
1458         }
1459         notification = record->notification;
1460         // delete or delete all, call the function
1461         if (removeReason != NotificationConstant::CLICK_REASON_DELETE) {
1462             ProcForDeleteLiveView(record);
1463             if (!isCancel) {
1464                 TriggerRemoveWantAgent(record->request, removeReason, record->isThirdparty);
1465             }
1466         }
1467         CancelWantAgent(notification);
1468         notificationList_.remove(record);
1469         return ERR_OK;
1470     }
1471     RemoveFromDelayedNotificationList(key);
1472     std::string message = "notification not exist. key:" + key + ".";
1473     ANS_LOGE("%{public}s", message.c_str());
1474     return ERR_ANS_NOTIFICATION_NOT_EXISTS;
1475 }
1476 
RemoveFromNotificationListForDeleteAll(const std::string & key,const int32_t & userId,sptr<Notification> & notification)1477 ErrCode AdvancedNotificationService::RemoveFromNotificationListForDeleteAll(
1478     const std::string &key, const int32_t &userId, sptr<Notification> &notification)
1479 {
1480     for (auto record : notificationList_) {
1481         if ((record->notification->GetKey() == key) &&
1482             (record->notification->GetUserId() == userId)) {
1483             if (!record->notification->IsRemoveAllowed()) {
1484                 return ERR_ANS_NOTIFICATION_IS_UNALLOWED_REMOVEALLOWED;
1485             }
1486             if (record->request->IsUnremovable()) {
1487                 return ERR_ANS_NOTIFICATION_IS_UNREMOVABLE;
1488             }
1489 
1490             ProcForDeleteLiveView(record);
1491 
1492             notification = record->notification;
1493             notificationList_.remove(record);
1494             return ERR_OK;
1495         }
1496     }
1497 
1498     return ERR_ANS_NOTIFICATION_NOT_EXISTS;
1499 }
1500 
RemoveFromDelayedNotificationList(const std::string & key)1501 bool AdvancedNotificationService::RemoveFromDelayedNotificationList(const std::string &key)
1502 {
1503     std::lock_guard<std::mutex> lock(delayNotificationMutext_);
1504     for (auto delayNotification : delayNotificationList_) {
1505         if (delayNotification.first->notification->GetKey() == key) {
1506             CancelTimer(delayNotification.second);
1507             delayNotificationList_.remove(delayNotification);
1508             return true;
1509         }
1510     }
1511     return false;
1512 }
1513 
GetFromNotificationList(const std::string & key)1514 std::shared_ptr<NotificationRecord> AdvancedNotificationService::GetFromNotificationList(const std::string &key)
1515 {
1516     for (auto item : notificationList_) {
1517         if (item->notification->GetKey() == key) {
1518             return item;
1519         }
1520     }
1521     return nullptr;
1522 }
1523 
GetFromNotificationList(const int32_t ownerUid,const int32_t notificationId)1524 std::shared_ptr<NotificationRecord> AdvancedNotificationService::GetFromNotificationList(
1525     const int32_t ownerUid, const int32_t notificationId)
1526 {
1527     for (auto item : notificationList_) {
1528         auto oldRequest = item->notification->GetNotificationRequest();
1529         if (oldRequest.GetOwnerUid() == ownerUid &&
1530             oldRequest.GetNotificationId() == notificationId &&
1531             oldRequest.IsSystemLiveView() && oldRequest.IsUpdateByOwnerAllowed()) {
1532             return item;
1533         }
1534     }
1535 
1536     return nullptr;
1537 }
1538 
GetFromDelayedNotificationList(const int32_t ownerUid,const int32_t notificationId)1539 std::shared_ptr<NotificationRecord> AdvancedNotificationService::GetFromDelayedNotificationList(
1540     const int32_t ownerUid, const int32_t notificationId)
1541 {
1542     std::lock_guard<std::mutex> lock(delayNotificationMutext_);
1543     for (auto delayNotification : delayNotificationList_) {
1544         auto delayRequest = delayNotification.first->notification->GetNotificationRequest();
1545         if (delayRequest.GetOwnerUid() == ownerUid &&
1546             delayRequest.GetNotificationId() == notificationId &&
1547             delayRequest.IsSystemLiveView() && delayRequest.IsUpdateByOwnerAllowed()) {
1548             return delayNotification.first;
1549         }
1550     }
1551 
1552     return nullptr;
1553 }
1554 
GetAllActiveNotifications(std::vector<sptr<Notification>> & notifications)1555 ErrCode AdvancedNotificationService::GetAllActiveNotifications(std::vector<sptr<Notification>> &notifications)
1556 {
1557     ANS_LOGD("%{public}s", __FUNCTION__);
1558 
1559     bool isSubsystem = AccessTokenHelper::VerifyNativeToken(IPCSkeleton::GetCallingTokenID());
1560     if (!isSubsystem && !AccessTokenHelper::IsSystemApp()) {
1561         return ERR_ANS_NON_SYSTEM_APP;
1562     }
1563 
1564     int32_t callingUid = IPCSkeleton::GetCallingUid();
1565     if (callingUid != RSS_UID && !AccessTokenHelper::CheckPermission(OHOS_PERMISSION_NOTIFICATION_CONTROLLER)) {
1566         ANS_LOGW("AccessTokenHelper::CheckPermission failed.");
1567         return ERR_ANS_PERMISSION_DENIED;
1568     }
1569 
1570     if (notificationSvrQueue_ == nullptr) {
1571         ANS_LOGE("Serial queue is invalidity.");
1572         return ERR_ANS_INVALID_PARAM;
1573     }
1574     ffrt::task_handle handler = notificationSvrQueue_->submit_h(std::bind([&]() {
1575         ANS_LOGD("ffrt enter!");
1576         notifications.clear();
1577         for (auto record : notificationList_) {
1578             if (record->notification != nullptr && record->notification->request_ != nullptr) {
1579                 notifications.push_back(record->notification);
1580             }
1581         }
1582     }));
1583     notificationSvrQueue_->wait(handler);
1584     return ERR_OK;
1585 }
1586 
GetAllNotificationsBySlotType(std::vector<sptr<Notification>> & notifications,const NotificationConstant::SlotType slotType)1587 ErrCode AdvancedNotificationService::GetAllNotificationsBySlotType(std::vector<sptr<Notification>> &notifications,
1588     const NotificationConstant::SlotType slotType)
1589 {
1590     ANS_LOGD("%{public}s", __FUNCTION__);
1591 
1592     bool isSubsystem = AccessTokenHelper::VerifyNativeToken(IPCSkeleton::GetCallingTokenID());
1593     if (!isSubsystem && !AccessTokenHelper::IsSystemApp()) {
1594         return ERR_ANS_NON_SYSTEM_APP;
1595     }
1596 
1597     if (!AccessTokenHelper::CheckPermission(OHOS_PERMISSION_NOTIFICATION_CONTROLLER)) {
1598         ANS_LOGW("AccessTokenHelper::CheckPermission failed.");
1599         return ERR_ANS_PERMISSION_DENIED;
1600     }
1601 
1602     if (notificationSvrQueue_ == nullptr) {
1603         ANS_LOGE("Serial queue is invalidity.");
1604         return ERR_ANS_INVALID_PARAM;
1605     }
1606     ffrt::task_handle handler = notificationSvrQueue_->submit_h(std::bind([&]() {
1607         ANS_LOGD("ffrt enter!");
1608         notifications.clear();
1609         for (auto record : notificationList_) {
1610             if (record->notification != nullptr && record->notification->request_ != nullptr &&
1611                 record->notification->request_->GetSlotType() == slotType) {
1612                 notifications.push_back(record->notification);
1613             }
1614         }
1615     }));
1616     notificationSvrQueue_->wait(handler);
1617     return ERR_OK;
1618 }
1619 
IsContained(const std::vector<std::string> & vec,const std::string & target)1620 inline bool IsContained(const std::vector<std::string> &vec, const std::string &target)
1621 {
1622     bool isContained = false;
1623 
1624     auto iter = vec.begin();
1625     while (iter != vec.end()) {
1626         if (*iter == target) {
1627             isContained = true;
1628             break;
1629         }
1630         iter++;
1631     }
1632 
1633     return isContained;
1634 }
1635 
GetSpecialActiveNotifications(const std::vector<std::string> & key,std::vector<sptr<Notification>> & notifications)1636 ErrCode AdvancedNotificationService::GetSpecialActiveNotifications(
1637     const std::vector<std::string> &key, std::vector<sptr<Notification>> &notifications)
1638 {
1639     ANS_LOGD("%{public}s", __FUNCTION__);
1640 
1641     bool isSubsystem = AccessTokenHelper::VerifyNativeToken(IPCSkeleton::GetCallingTokenID());
1642     if (!isSubsystem && !AccessTokenHelper::IsSystemApp()) {
1643         return ERR_ANS_NON_SYSTEM_APP;
1644     }
1645 
1646     if (!AccessTokenHelper::CheckPermission(OHOS_PERMISSION_NOTIFICATION_CONTROLLER)) {
1647         ANS_LOGD("Check permission is false.");
1648         return ERR_ANS_PERMISSION_DENIED;
1649     }
1650 
1651     if (notificationSvrQueue_ == nullptr) {
1652         ANS_LOGE("Serial queue is invalid.");
1653         return ERR_ANS_INVALID_PARAM;
1654     }
1655     ffrt::task_handle handler = notificationSvrQueue_->submit_h(std::bind([&]() {
1656         ANS_LOGD("ffrt enter!");
1657         for (auto record : notificationList_) {
1658             if (IsContained(key, record->notification->GetKey())) {
1659                 notifications.push_back(record->notification);
1660             }
1661         }
1662     }));
1663     notificationSvrQueue_->wait(handler);
1664     return ERR_OK;
1665 }
1666 
GetRecordFromNotificationList(int32_t notificationId,int32_t uid,const std::string & label,const std::string & bundleName)1667 std::shared_ptr<NotificationRecord> AdvancedNotificationService::GetRecordFromNotificationList(
1668     int32_t notificationId, int32_t uid, const std::string &label, const std::string &bundleName)
1669 {
1670     for (auto &record : notificationList_) {
1671         if ((record->notification->GetLabel() == label) &&
1672             (record->notification->GetId() == notificationId) &&
1673             (record->bundleOption->GetUid() == uid) &&
1674             (record->bundleOption->GetBundleName() == bundleName)) {
1675             return record;
1676         }
1677     }
1678     return nullptr;
1679 }
1680 
SetRecentNotificationCount(const std::string arg)1681 ErrCode AdvancedNotificationService::SetRecentNotificationCount(const std::string arg)
1682 {
1683     ANS_LOGD("%{public}s arg = %{public}s", __FUNCTION__, arg.c_str());
1684     int32_t count = atoi(arg.c_str());
1685     if ((count < NOTIFICATION_MIN_COUNT) || (count > NOTIFICATION_MAX_COUNT)) {
1686         return ERR_ANS_INVALID_PARAM;
1687     }
1688 
1689     recentInfo_->recentCount = count;
1690     while (recentInfo_->list.size() > recentInfo_->recentCount) {
1691         recentInfo_->list.pop_back();
1692     }
1693     return ERR_OK;
1694 }
1695 
UpdateRecentNotification(sptr<Notification> & notification,bool isDelete,int32_t reason)1696 void AdvancedNotificationService::UpdateRecentNotification(sptr<Notification> &notification,
1697     bool isDelete, int32_t reason)
1698 {
1699     return;
1700 }
SortNotificationsByLevelAndTime(const std::shared_ptr<NotificationRecord> & first,const std::shared_ptr<NotificationRecord> & second)1701 static bool SortNotificationsByLevelAndTime(
1702     const std::shared_ptr<NotificationRecord> &first, const std::shared_ptr<NotificationRecord> &second)
1703 {
1704     if (first->slot ==nullptr || second->slot == nullptr) {
1705         return (first->request->GetCreateTime() < second->request->GetCreateTime());
1706     }
1707     return (first->slot->GetLevel() < second->slot->GetLevel());
1708 }
1709 
IsSystemUser(int32_t userId)1710 bool AdvancedNotificationService::IsSystemUser(int32_t userId)
1711 {
1712     return ((userId >= SUBSCRIBE_USER_SYSTEM_BEGIN) && (userId <= SUBSCRIBE_USER_SYSTEM_END));
1713 }
1714 
PublishInNotificationList(const std::shared_ptr<NotificationRecord> & record)1715 ErrCode AdvancedNotificationService::PublishInNotificationList(const std::shared_ptr<NotificationRecord> &record)
1716 {
1717     std::list<std::shared_ptr<NotificationRecord>> bundleList;
1718     for (auto item : notificationList_) {
1719         if (record->notification->GetBundleName() == item->notification->GetBundleName()) {
1720             bundleList.push_back(item);
1721         }
1722     }
1723 
1724     std::shared_ptr<NotificationRecord> recordToRemove;
1725     if (bundleList.size() >= MAX_ACTIVE_NUM_PERAPP) {
1726         bundleList.sort(SortNotificationsByLevelAndTime);
1727         recordToRemove = bundleList.front();
1728         SendFlowControlOccurHiSysEvent(recordToRemove);
1729         RemoveNotificationList(bundleList.front());
1730     }
1731 
1732     if (notificationList_.size() >= MAX_ACTIVE_NUM) {
1733         if (bundleList.size() > 0) {
1734             bundleList.sort(SortNotificationsByLevelAndTime);
1735             recordToRemove = bundleList.front();
1736             SendFlowControlOccurHiSysEvent(recordToRemove);
1737             RemoveNotificationList(bundleList.front());
1738         } else {
1739             std::list<std::shared_ptr<NotificationRecord>> sorted = notificationList_;
1740             sorted.sort(SortNotificationsByLevelAndTime);
1741             recordToRemove = sorted.front();
1742             SendFlowControlOccurHiSysEvent(recordToRemove);
1743             RemoveNotificationList(sorted.front());
1744         }
1745     }
1746 
1747     AddToNotificationList(record);
1748 
1749     return ERR_OK;
1750 }
1751 
IsDistributedEnabled(bool & enabled)1752 ErrCode AdvancedNotificationService::IsDistributedEnabled(bool &enabled)
1753 {
1754     ANS_LOGD("%{public}s", __FUNCTION__);
1755 #ifdef DISTRIBUTED_NOTIFICATION_SUPPORTED
1756     if (notificationSvrQueue_ == nullptr) {
1757         ANS_LOGE("Serial queue is invalid.");
1758         return ERR_ANS_INVALID_PARAM;
1759     }
1760     ErrCode result = ERR_OK;
1761     ffrt::task_handle handler = notificationSvrQueue_->submit_h(std::bind([&]() {
1762         ANS_LOGD("ffrt enter!");
1763         result = DistributedPreferences::GetInstance()->GetDistributedEnable(enabled);
1764         if (result != ERR_OK) {
1765             result = ERR_OK;
1766             enabled = false;
1767         }
1768     }));
1769     notificationSvrQueue_->wait(handler);
1770     return result;
1771 #else
1772     return ERR_INVALID_OPERATION;
1773 #endif
1774 }
1775 
EnableDistributed(bool enabled)1776 ErrCode AdvancedNotificationService::EnableDistributed(bool enabled)
1777 {
1778     ANS_LOGD("%{public}s", __FUNCTION__);
1779 
1780 #ifdef DISTRIBUTED_NOTIFICATION_SUPPORTED
1781     bool isSubsystem = AccessTokenHelper::VerifyNativeToken(IPCSkeleton::GetCallingTokenID());
1782     if (!isSubsystem && !AccessTokenHelper::IsSystemApp()) {
1783         ANS_LOGD("VerifyNativeToken and IsSystemApp is false.");
1784         return ERR_ANS_NON_SYSTEM_APP;
1785     }
1786 
1787     if (!AccessTokenHelper::CheckPermission(OHOS_PERMISSION_NOTIFICATION_CONTROLLER)) {
1788         return ERR_ANS_PERMISSION_DENIED;
1789     }
1790 
1791     if (notificationSvrQueue_ == nullptr) {
1792         ANS_LOGE("Serial queue is invalidity.");
1793         return ERR_ANS_INVALID_PARAM;
1794     }
1795     ErrCode result = ERR_OK;
1796     ffrt::task_handle handler = notificationSvrQueue_->submit_h(
1797         std::bind([&]() {
1798             result = DistributedPreferences::GetInstance()->SetDistributedEnable(enabled);
1799             ANS_LOGE("ffrt enter!");
1800         }));
1801     notificationSvrQueue_->wait(handler);
1802     return result;
1803 #else
1804     return ERR_INVALID_OPERATION;
1805 #endif
1806 }
1807 
EnableDistributedByBundle(const sptr<NotificationBundleOption> & bundleOption,bool enabled)1808 ErrCode AdvancedNotificationService::EnableDistributedByBundle(
1809     const sptr<NotificationBundleOption> &bundleOption, bool enabled)
1810 {
1811     ANS_LOGD("%{public}s", __FUNCTION__);
1812 
1813 #ifdef DISTRIBUTED_NOTIFICATION_SUPPORTED
1814     bool isSubsystem = AccessTokenHelper::VerifyNativeToken(IPCSkeleton::GetCallingTokenID());
1815     if (!isSubsystem && !AccessTokenHelper::IsSystemApp()) {
1816         return ERR_ANS_NON_SYSTEM_APP;
1817     }
1818 
1819     if (!AccessTokenHelper::CheckPermission(OHOS_PERMISSION_NOTIFICATION_CONTROLLER)) {
1820         ANS_LOGD("AccessTokenHelper::CheckPermission is false.");
1821         return ERR_ANS_PERMISSION_DENIED;
1822     }
1823 
1824     sptr<NotificationBundleOption> bundle = GenerateValidBundleOption(bundleOption);
1825     if (bundle == nullptr) {
1826         ANS_LOGD("Create bundle failed.");
1827         return ERR_ANS_INVALID_BUNDLE;
1828     }
1829 
1830     bool appInfoEnable = true;
1831     GetDistributedEnableInApplicationInfo(bundle, appInfoEnable);
1832     if (!appInfoEnable) {
1833         ANS_LOGD("Get from bms is %{public}d", appInfoEnable);
1834         return ERR_ANS_PERMISSION_DENIED;
1835     }
1836 
1837     if (notificationSvrQueue_ == nullptr) {
1838         ANS_LOGE("Serial queue is invalid.");
1839         return ERR_ANS_INVALID_PARAM;
1840     }
1841     ErrCode result = ERR_OK;
1842     ffrt::task_handle handler = notificationSvrQueue_->submit_h(std::bind([&]() {
1843         ANS_LOGD("ffrt enter!");
1844         result = DistributedPreferences::GetInstance()->SetDistributedBundleEnable(bundle, enabled);
1845         if (result != ERR_OK) {
1846             result = ERR_OK;
1847             enabled = false;
1848         }
1849     }));
1850     notificationSvrQueue_->wait(handler);
1851     return result;
1852 #else
1853     return ERR_INVALID_OPERATION;
1854 #endif
1855 }
1856 
EnableDistributedSelf(const bool enabled)1857 ErrCode AdvancedNotificationService::EnableDistributedSelf(const bool enabled)
1858 {
1859     ANS_LOGD("%{public}s", __FUNCTION__);
1860 #ifdef DISTRIBUTED_NOTIFICATION_SUPPORTED
1861     sptr<NotificationBundleOption> bundleOption = GenerateBundleOption();
1862     if (bundleOption == nullptr) {
1863         return ERR_ANS_INVALID_BUNDLE;
1864     }
1865 
1866     bool appInfoEnable = true;
1867     GetDistributedEnableInApplicationInfo(bundleOption, appInfoEnable);
1868     if (!appInfoEnable) {
1869         ANS_LOGD("Get from bms is %{public}d", appInfoEnable);
1870         return ERR_ANS_PERMISSION_DENIED;
1871     }
1872 
1873     if (notificationSvrQueue_ == nullptr) {
1874         ANS_LOGE("notificationSvrQueue_ is nullptr.");
1875         return ERR_ANS_INVALID_PARAM;
1876     }
1877     ErrCode result = ERR_OK;
1878     ffrt::task_handle handler = notificationSvrQueue_->submit_h(std::bind(
1879         [&]() {
1880             ANS_LOGD("ffrt enter!");
1881             result = DistributedPreferences::GetInstance()->SetDistributedBundleEnable(bundleOption, enabled);
1882         }));
1883     notificationSvrQueue_->wait(handler);
1884     return result;
1885 #else
1886     return ERR_INVALID_OPERATION;
1887 #endif
1888 }
1889 
IsDistributedEnableByBundle(const sptr<NotificationBundleOption> & bundleOption,bool & enabled)1890 ErrCode AdvancedNotificationService::IsDistributedEnableByBundle(
1891     const sptr<NotificationBundleOption> &bundleOption, bool &enabled)
1892 {
1893     ANS_LOGD("%{public}s", __FUNCTION__);
1894 
1895 #ifdef DISTRIBUTED_NOTIFICATION_SUPPORTED
1896     bool isSubsystem = AccessTokenHelper::VerifyNativeToken(IPCSkeleton::GetCallingTokenID());
1897     if (!isSubsystem && !AccessTokenHelper::IsSystemApp()) {
1898         return ERR_ANS_NON_SYSTEM_APP;
1899     }
1900 
1901     if (!AccessTokenHelper::CheckPermission(OHOS_PERMISSION_NOTIFICATION_CONTROLLER)) {
1902         return ERR_ANS_PERMISSION_DENIED;
1903     }
1904 
1905     sptr<NotificationBundleOption> bundle = GenerateValidBundleOption(bundleOption);
1906     if (bundle == nullptr) {
1907         ANS_LOGD("Failed to create bundle.");
1908         return ERR_ANS_INVALID_BUNDLE;
1909     }
1910 
1911     bool appInfoEnable = true;
1912     GetDistributedEnableInApplicationInfo(bundle, appInfoEnable);
1913     if (!appInfoEnable) {
1914         ANS_LOGD("Get from bms is %{public}d", appInfoEnable);
1915         enabled = appInfoEnable;
1916         return ERR_OK;
1917     }
1918 
1919     if (notificationSvrQueue_ == nullptr) {
1920         ANS_LOGE("Serial queue is invalid.");
1921         return ERR_ANS_INVALID_PARAM;
1922     }
1923     ErrCode result = ERR_OK;
1924     ffrt::task_handle handler = notificationSvrQueue_->submit_h(std::bind([&]() {
1925         ANS_LOGD("ffrt enter!");
1926         result = DistributedPreferences::GetInstance()->GetDistributedBundleEnable(bundle, enabled);
1927         if (result != ERR_OK) {
1928             result = ERR_OK;
1929             enabled = false;
1930         }
1931     }));
1932     notificationSvrQueue_->wait(handler);
1933     return result;
1934 #else
1935     return ERR_INVALID_OPERATION;
1936 #endif
1937 }
1938 
GetHasPoppedDialog(const sptr<NotificationBundleOption> bundleOption,bool & hasPopped)1939 ErrCode AdvancedNotificationService::GetHasPoppedDialog(
1940     const sptr<NotificationBundleOption> bundleOption, bool &hasPopped)
1941 {
1942     ANS_LOGD("%{public}s", __FUNCTION__);
1943     if (notificationSvrQueue_ == nullptr) {
1944         ANS_LOGE("Serial queue is invalid.");
1945         return ERR_ANS_INVALID_PARAM;
1946     }
1947     ErrCode result = ERR_OK;
1948     ffrt::task_handle handler = notificationSvrQueue_->submit_h(std::bind([&]() {
1949         result = NotificationPreferences::GetInstance()->GetHasPoppedDialog(bundleOption, hasPopped);
1950     }));
1951     notificationSvrQueue_->wait(handler);
1952     return result;
1953 }
1954 
SetSyncNotificationEnabledWithoutApp(const int32_t userId,const bool enabled)1955 ErrCode AdvancedNotificationService::SetSyncNotificationEnabledWithoutApp(const int32_t userId, const bool enabled)
1956 {
1957     ANS_LOGD("userId: %{public}d, enabled: %{public}d", userId, enabled);
1958 
1959 #ifdef DISTRIBUTED_NOTIFICATION_SUPPORTED
1960     bool isSubsystem = AccessTokenHelper::VerifyNativeToken(IPCSkeleton::GetCallingTokenID());
1961     if (!isSubsystem && !AccessTokenHelper::IsSystemApp()) {
1962         return ERR_ANS_NON_SYSTEM_APP;
1963     }
1964 
1965     if (!AccessTokenHelper::CheckPermission(OHOS_PERMISSION_NOTIFICATION_CONTROLLER)) {
1966         ANS_LOGD("AccessTokenHelper::CheckPermission is false.");
1967         return ERR_ANS_PERMISSION_DENIED;
1968     }
1969 
1970     if (notificationSvrQueue_ == nullptr) {
1971         ANS_LOGE("Serial queue is invalidity.");
1972         return ERR_ANS_INVALID_PARAM;
1973     }
1974     ErrCode result = ERR_OK;
1975     ffrt::task_handle handler = notificationSvrQueue_->submit_h(
1976         std::bind([&]() {
1977             ANS_LOGD("ffrt enter!");
1978             result = DistributedPreferences::GetInstance()->SetSyncEnabledWithoutApp(userId, enabled);
1979         }));
1980     notificationSvrQueue_->wait(handler);
1981     return result;
1982 #else
1983     return ERR_INVALID_OPERATION;
1984 #endif
1985 }
1986 
GetSyncNotificationEnabledWithoutApp(const int32_t userId,bool & enabled)1987 ErrCode AdvancedNotificationService::GetSyncNotificationEnabledWithoutApp(const int32_t userId, bool &enabled)
1988 {
1989     ANS_LOGD("userId: %{public}d", userId);
1990 
1991 #ifdef DISTRIBUTED_NOTIFICATION_SUPPORTED
1992     bool isSubsystem = AccessTokenHelper::VerifyNativeToken(IPCSkeleton::GetCallingTokenID());
1993     if (!isSubsystem && !AccessTokenHelper::IsSystemApp()) {
1994         return ERR_ANS_NON_SYSTEM_APP;
1995     }
1996 
1997     if (!AccessTokenHelper::CheckPermission(OHOS_PERMISSION_NOTIFICATION_CONTROLLER)) {
1998         return ERR_ANS_PERMISSION_DENIED;
1999     }
2000 
2001     if (notificationSvrQueue_ == nullptr) {
2002         ANS_LOGE("Serial queue is invalid.");
2003         return ERR_ANS_INVALID_PARAM;
2004     }
2005     ErrCode result = ERR_OK;
2006     ffrt::task_handle handler = notificationSvrQueue_->submit_h(
2007         std::bind([&]() {
2008             ANS_LOGD("ffrt enter!");
2009             result = DistributedPreferences::GetInstance()->GetSyncEnabledWithoutApp(userId, enabled);
2010         }));
2011     notificationSvrQueue_->wait(handler);
2012     return result;
2013 #else
2014     return ERR_INVALID_OPERATION;
2015 #endif
2016 }
2017 
ResetPushCallbackProxy()2018 void AdvancedNotificationService::ResetPushCallbackProxy()
2019 {
2020     ANS_LOGD("enter");
2021     std::lock_guard<std::mutex> lock(pushMutex_);
2022     if (pushCallBacks_.empty()) {
2023         ANS_LOGE("invalid proxy state");
2024         return;
2025     }
2026     for (auto it = pushCallBacks_.begin(); it != pushCallBacks_.end(); it++) {
2027         if (it->second->AsObject() == nullptr) {
2028             ANS_LOGE("invalid proxy state");
2029         } else {
2030             it->second->AsObject()->RemoveDeathRecipient(pushRecipient_);
2031         }
2032     }
2033     pushCallBacks_.clear();
2034 }
2035 
RegisterPushCallback(const sptr<IRemoteObject> & pushCallback,const sptr<NotificationCheckRequest> & notificationCheckRequest)2036 ErrCode AdvancedNotificationService::RegisterPushCallback(
2037     const sptr<IRemoteObject> &pushCallback, const sptr<NotificationCheckRequest> &notificationCheckRequest)
2038 {
2039     bool isSubSystem = AccessTokenHelper::VerifyNativeToken(IPCSkeleton::GetCallingTokenID());
2040     if (!isSubSystem && !AccessTokenHelper::IsSystemApp()) {
2041         ANS_LOGW("Not system app or SA!");
2042         return ERR_ANS_NON_SYSTEM_APP;
2043     }
2044 
2045     if (!AccessTokenHelper::CheckPermission(OHOS_PERMISSION_NOTIFICATION_AGENT_CONTROLLER)) {
2046         ANS_LOGW("Not have OHOS_PERMISSION_NOTIFICATION_AGENT_CONTROLLER approval!");
2047         return ERR_ANS_PERMISSION_DENIED;
2048     }
2049 
2050     if (!AccessTokenHelper::CheckPermission(OHOS_PERMISSION_NOTIFICATION_CONTROLLER)) {
2051         ANS_LOGW("Not have OHOS_PERMISSION_NOTIFICATION_CONTROLLER Permission!");
2052         return ERR_ANS_PERMISSION_DENIED;
2053     }
2054 
2055     if (pushCallback == nullptr) {
2056         ANS_LOGW("pushCallback is null.");
2057         return ERR_INVALID_VALUE;
2058     }
2059 
2060     if (notificationCheckRequest == nullptr) {
2061         ANS_LOGW("notificationCheckRequest is null.");
2062         return ERR_INVALID_VALUE;
2063     }
2064 
2065     pushRecipient_ = new (std::nothrow) PushCallbackRecipient();
2066     if (!pushRecipient_) {
2067         ANS_LOGE("Failed to create death Recipient ptr PushCallbackRecipient!");
2068         return ERR_NO_INIT;
2069     }
2070     pushCallback->AddDeathRecipient(pushRecipient_);
2071 
2072     sptr<IPushCallBack> pushCallBack = iface_cast<IPushCallBack>(pushCallback);
2073     NotificationConstant::SlotType slotType = notificationCheckRequest->GetSlotType();
2074     int32_t uid = IPCSkeleton::GetCallingUid();
2075 
2076     if (pushCallBacks_.find(slotType) != pushCallBacks_.end()) {
2077         if (checkRequests_[slotType]->GetUid() != uid) {
2078             return ERROR_INTERNAL_ERROR;
2079         }
2080     }
2081     {
2082         std::lock_guard<std::mutex> lock(pushMutex_);
2083         pushCallBacks_.insert_or_assign(slotType, pushCallBack);
2084     }
2085     ANS_LOGD("insert pushCallBack, slot type %{public}d", slotType);
2086     notificationCheckRequest->SetUid(uid);
2087     checkRequests_.insert_or_assign(slotType, notificationCheckRequest);
2088     ANS_LOGD("insert notificationCheckRequest, slot type %{public}d, content type %{public}d",
2089         slotType, notificationCheckRequest->GetContentType());
2090 
2091     ANS_LOGD("end");
2092     return ERR_OK;
2093 }
2094 
UnregisterPushCallback()2095 ErrCode AdvancedNotificationService::UnregisterPushCallback()
2096 {
2097     if (!AccessTokenHelper::IsSystemApp()) {
2098         ANS_LOGW("Not system app!");
2099         return ERR_ANS_NON_SYSTEM_APP;
2100     }
2101 
2102     if (!AccessTokenHelper::CheckPermission(OHOS_PERMISSION_NOTIFICATION_AGENT_CONTROLLER)) {
2103         ANS_LOGW("Not have OHOS_PERMISSION_NOTIFICATION_AGENT_CONTROLLER Permission!");
2104         return ERR_ANS_PERMISSION_DENIED;
2105     }
2106 
2107     if (!AccessTokenHelper::CheckPermission(OHOS_PERMISSION_NOTIFICATION_CONTROLLER)) {
2108         ANS_LOGW("Not have OHOS_PERMISSION_NOTIFICATION_CONTROLLER Permission!");
2109         return ERR_ANS_PERMISSION_DENIED;
2110     }
2111 
2112     if (pushCallBacks_.empty()) {
2113         ANS_LOGE("The registration callback has not been processed yet.");
2114         return ERR_INVALID_OPERATION;
2115     }
2116 
2117     {
2118         std::lock_guard<std::mutex> lock(pushMutex_);
2119         pushCallBacks_.clear();
2120     }
2121 
2122     ANS_LOGD("end");
2123     return ERR_OK;
2124 }
2125 
IsNeedPushCheck(const sptr<NotificationRequest> & request)2126 bool AdvancedNotificationService::IsNeedPushCheck(const sptr<NotificationRequest> &request)
2127 {
2128     NotificationConstant::SlotType slotType = request->GetSlotType();
2129     NotificationContent::Type contentType = request->GetNotificationType();
2130     ANS_LOGD("NotificationRequest slotType:%{public}d, contentType:%{public}d", slotType, contentType);
2131 
2132     if (request->IsCommonLiveView()) {
2133         std::shared_ptr<NotificationContent> content = request->GetContent();
2134         auto liveViewContent = std::static_pointer_cast<NotificationLiveViewContent>(content->GetNotificationContent());
2135         auto status = liveViewContent->GetLiveViewStatus();
2136         if (status != NotificationLiveViewContent::LiveViewStatus::LIVE_VIEW_CREATE) {
2137             ANS_LOGI("Status of common live view is not create, no need to check.");
2138             return false;
2139         }
2140 
2141         NotificationSubscriberManager::GetInstance()->NotifyApplicationInfoNeedChanged(request->GetCreatorBundleName());
2142         ANS_LOGI("Common live view requires push check.");
2143         return true;
2144     }
2145 
2146     if (pushCallBacks_.find(slotType) == pushCallBacks_.end()) {
2147         ANS_LOGI("pushCallback Unregistered, no need to check.");
2148         return false;
2149     }
2150 
2151     if (contentType == checkRequests_[slotType]->GetContentType()) {
2152         ANS_LOGI("Need push check.");
2153         return true;
2154     }
2155     return false;
2156 }
2157 
FillExtraInfoToJson(const sptr<NotificationRequest> & request,sptr<NotificationCheckRequest> & checkRequest,nlohmann::json & jsonObject)2158 void AdvancedNotificationService::FillExtraInfoToJson(
2159     const sptr<NotificationRequest> &request, sptr<NotificationCheckRequest> &checkRequest, nlohmann::json &jsonObject)
2160 {
2161     std::shared_ptr<NotificationContent> content = request->GetContent();
2162     auto liveViewContent = std::static_pointer_cast<NotificationLiveViewContent>(content->GetNotificationContent());
2163     auto extraInfo = liveViewContent->GetExtraInfo();
2164     if (extraInfo == nullptr) {
2165         return;
2166     }
2167 
2168     std::shared_ptr<AAFwk::WantParams> checkExtraInfo = std::make_shared<AAFwk::WantParams>();
2169     if (checkExtraInfo == nullptr) {
2170         return;
2171     }
2172 
2173     if (checkRequest->GetExtraKeys().size() == 0) {
2174         checkExtraInfo = extraInfo;
2175     } else {
2176         for (auto key : checkRequest->GetExtraKeys()) {
2177             if (extraInfo->HasParam(key)) {
2178                 checkExtraInfo->SetParam(key, extraInfo->GetParam(key));
2179             }
2180         }
2181     }
2182 
2183     if (checkExtraInfo) {
2184         AAFwk::WantParamWrapper wWrapper(*checkExtraInfo);
2185         jsonObject["extraInfo"] = wWrapper.ToString();
2186     }
2187 }
2188 
CreatePushCheckJson(const sptr<NotificationRequest> & request,sptr<NotificationCheckRequest> & checkRequest,nlohmann::json & jsonObject)2189 void AdvancedNotificationService::CreatePushCheckJson(
2190     const sptr<NotificationRequest> &request, sptr<NotificationCheckRequest> &checkRequest, nlohmann::json &jsonObject)
2191 {
2192     if (request->IsAgentNotification()) {
2193         jsonObject["pkgName"] = request->GetOwnerBundleName();
2194     } else {
2195         jsonObject["pkgName"] = request->GetCreatorBundleName();
2196     }
2197     jsonObject["notifyId"] = request->GetNotificationId();
2198     jsonObject["contentType"] = static_cast<int32_t>(request->GetNotificationType());
2199     jsonObject["creatorUserId"] = request->GetCreatorUserId();
2200     jsonObject["slotType"] = static_cast<int32_t>(request->GetSlotType());
2201     jsonObject["label"] = request->GetLabel();
2202     if (request->IsCommonLiveView()) {
2203         FillExtraInfoToJson(request, checkRequest, jsonObject);
2204     }
2205 }
2206 
PushCheck(const sptr<NotificationRequest> & request)2207 ErrCode AdvancedNotificationService::PushCheck(const sptr<NotificationRequest> &request)
2208 {
2209     ANS_LOGD("start.");
2210     if (pushCallBacks_.find(request->GetSlotType()) == pushCallBacks_.end()) {
2211         return ERR_ANS_PUSH_CHECK_UNREGISTERED;
2212     }
2213     sptr<IPushCallBack> pushCallBack = pushCallBacks_[request->GetSlotType()];
2214     sptr<NotificationCheckRequest> checkRequest = checkRequests_[request->GetSlotType()];
2215     if (request->GetCreatorUid() == checkRequest->GetUid()) {
2216         return ERR_OK;
2217     }
2218 
2219     nlohmann::json jsonObject;
2220     CreatePushCheckJson(request, checkRequest, jsonObject);
2221     std::shared_ptr<PushCallBackParam> pushCallBackParam = std::make_shared<PushCallBackParam>();
2222     std::shared_ptr<AAFwk::WantParams> extroInfo = nullptr;
2223     if (request->IsCommonLiveView()) {
2224         auto content = request->GetContent()->GetNotificationContent();
2225         auto liveViewContent = std::static_pointer_cast<NotificationLiveViewContent>(content);
2226         extroInfo = liveViewContent->GetExtraInfo();
2227         if (pushCallBackParam != nullptr) {
2228             if (extroInfo != nullptr && extroInfo->HasParam("event")) {
2229                 pushCallBackParam->event = extroInfo->GetStringParam("event");
2230                 ANS_LOGI("get event,%{public}s", pushCallBackParam->event.c_str());
2231             }
2232         }
2233     }
2234 
2235     ErrCode result = pushCallBack->OnCheckNotification(jsonObject.dump(), pushCallBackParam);
2236     if (AccessTokenHelper::CheckPermission(OHOS_PERMISSION_NOTIFICATION_CONTROLLER) &&
2237         AccessTokenHelper::CheckPermission(OHOS_PERMISSION_NOTIFICATION_AGENT_CONTROLLER) &&
2238         result != ERR_OK) {
2239         ANS_LOGI("The application with the permission fails to pushcheck.");
2240         result = ERR_OK;
2241     }
2242     if (result != ERR_OK) {
2243         HaMetaMessage message = HaMetaMessage(EventSceneId::SCENE_2, EventBranchId::BRANCH_5)
2244             .ErrorCode(result).Message("Push OnCheckNotification failed.");
2245         NotificationAnalyticsUtil::ReportPublishFailedEvent(request, message);
2246     }
2247     if (pushCallBackParam != nullptr && !pushCallBackParam->eventControl.empty() && extroInfo != nullptr) {
2248         extroInfo->SetParam("eventControl", AAFwk::String::Box(pushCallBackParam->eventControl));
2249     } else if (extroInfo != nullptr) {
2250         extroInfo->Remove("eventControl");
2251     }
2252     return result;
2253 }
2254 
TriggerAutoDelete(const std::string & hashCode,int32_t reason)2255 void AdvancedNotificationService::TriggerAutoDelete(const std::string &hashCode, int32_t reason)
2256 {
2257     ANS_LOGD("Enter");
2258 
2259     for (const auto &record : notificationList_) {
2260         if (!record->request) {
2261             continue;
2262         }
2263 
2264         if (record->notification->GetKey() == hashCode) {
2265             UpdateRecentNotification(record->notification, true, reason);
2266             CancelTimer(record->notification->GetAutoDeletedTimer());
2267             NotificationSubscriberManager::GetInstance()->NotifyCanceled(record->notification, nullptr, reason);
2268             ProcForDeleteLiveView(record);
2269             notificationList_.remove(record);
2270             break;
2271         }
2272     }
2273 }
2274 
CreateDialogManager()2275 bool AdvancedNotificationService::CreateDialogManager()
2276 {
2277     static std::mutex dialogManagerMutex_;
2278     std::lock_guard<std::mutex> lock(dialogManagerMutex_);
2279     if (dialogManager_ == nullptr) {
2280         dialogManager_ = std::make_unique<NotificationDialogManager>(*this);
2281         if (!dialogManager_->Init()) {
2282             dialogManager_ = nullptr;
2283             return false;
2284         }
2285     }
2286     return true;
2287 }
2288 
FillActionButtons(const sptr<NotificationRequest> & request)2289 void AdvancedNotificationService::FillActionButtons(const sptr<NotificationRequest> &request)
2290 {
2291     if (request->IsCoverActionButtons()) {
2292         ANS_LOGD("Cover old action buttons.");
2293         return;
2294     }
2295 
2296     if (notificationSvrQueue_ == nullptr) {
2297         ANS_LOGE("Serial queue is invalid.");
2298         return;
2299     }
2300 
2301     ffrt::task_handle handler = notificationSvrQueue_->submit_h(std::bind([&]() {
2302         ANS_LOGD("ffrt enter!");
2303         auto iter = notificationList_.begin();
2304         while (iter != notificationList_.end()) {
2305             if ((*iter)->request->GetKey() == request->GetKey()) {
2306                 break;
2307             }
2308             iter++;
2309         }
2310 
2311         if (iter == notificationList_.end()) {
2312             ANS_LOGD("No old action buttons.");
2313             return;
2314         }
2315 
2316         for (auto actionButton : (*iter)->request->GetActionButtons()) {
2317             request->AddActionButton(actionButton);
2318         }
2319     }));
2320     notificationSvrQueue_->wait(handler);
2321 }
2322 
IsNeedNotifyConsumed(const sptr<NotificationRequest> & request)2323 bool AdvancedNotificationService::IsNeedNotifyConsumed(const sptr<NotificationRequest> &request)
2324 {
2325     if (!request->IsCommonLiveView()) {
2326         return true;
2327     }
2328 
2329     auto content = request->GetContent()->GetNotificationContent();
2330     auto liveViewContent = std::static_pointer_cast<NotificationLiveViewContent>(content);
2331     auto status = liveViewContent->GetLiveViewStatus();
2332     if (status != NotificationLiveViewContent::LiveViewStatus::LIVE_VIEW_END) {
2333         return true;
2334     }
2335 
2336     auto deleteTime = request->GetAutoDeletedTime();
2337     return deleteTime != NotificationConstant::NO_DELAY_DELETE_TIME;
2338 }
2339 
CheckSoundPermission(const sptr<NotificationRequest> & request,std::string bundleName)2340 ErrCode AdvancedNotificationService::CheckSoundPermission(const sptr<NotificationRequest> &request,
2341     std::string bundleName)
2342 {
2343     ANS_LOGD("%{public}s", __FUNCTION__);
2344     if (request->GetSound().empty()) {
2345         ANS_LOGD("request sound length empty");
2346         return ERR_OK;
2347     }
2348 
2349     int32_t length = request->GetSound().length();
2350     if (length > MAX_SOUND_ITEM_LENGTH) {
2351         ANS_LOGE("Check sound length failed: %{public}d", length);
2352         return ERR_ANS_INVALID_PARAM;
2353     }
2354 
2355     // Update sound permission info cache
2356     ANS_LOGD("Check sound permission: %{public}d, %{public}s, %{public}d", length, bundleName.c_str(),
2357         soundPermissionInfo_->needUpdateCache_.load());
2358     if (soundPermissionInfo_->needUpdateCache_.load()) {
2359         std::lock_guard<std::mutex> lock(soundPermissionInfo_->dbMutex_);
2360         if (soundPermissionInfo_->needUpdateCache_.load()) {
2361             soundPermissionInfo_->allPackage_ = false;
2362             soundPermissionInfo_->bundleName_.clear();
2363             NotificationPreferences::GetInstance()->GetBundleSoundPermission(
2364                 soundPermissionInfo_->allPackage_, soundPermissionInfo_->bundleName_);
2365             soundPermissionInfo_->needUpdateCache_ = false;
2366         }
2367     }
2368 
2369     if (!soundPermissionInfo_->allPackage_ && soundPermissionInfo_->bundleName_.count(bundleName) == 0) {
2370         request->SetSound("");
2371     }
2372     return ERR_OK;
2373 }
2374 
CheckLongTermLiveView(const sptr<NotificationRequest> & request,const std::string & key)2375 ErrCode AdvancedNotificationService::CheckLongTermLiveView(const sptr<NotificationRequest> &request,
2376     const std::string &key)
2377 {
2378     // live view, not update
2379     std::shared_ptr<AAFwk::WantParams> additionalData = request->GetAdditionalData();
2380     if (additionalData && additionalData->HasParam("SYSTEM_UPDATE_ONLY")) {
2381         auto updateIt = additionalData->GetParam("SYSTEM_UPDATE_ONLY");
2382         AAFwk::IBoolean *bo = AAFwk::IBoolean::Query(updateIt);
2383         if (bo == nullptr) {
2384             return ERR_OK;
2385         }
2386 
2387         if (AAFwk::Boolean::Unbox(bo) && !IsNotificationExists(key)) {
2388             ANS_LOGE("CheckLongTermLiveView check failed, cant update.");
2389             return ERR_ANS_INVALID_PARAM;
2390         }
2391     }
2392     return ERR_OK;
2393 }
2394 
AddRecordToMemory(const std::shared_ptr<NotificationRecord> & record,bool isSystemApp,bool isUpdateByOwner,const bool isAgentController)2395 ErrCode AdvancedNotificationService::AddRecordToMemory(
2396     const std::shared_ptr<NotificationRecord> &record, bool isSystemApp, bool isUpdateByOwner,
2397     const bool isAgentController)
2398 {
2399     auto result = AssignValidNotificationSlot(record, record->bundleOption);
2400     if (result != ERR_OK) {
2401         ANS_LOGE("Can not assign valid slot!");
2402         return result;
2403     }
2404 
2405     result = Filter(record);
2406     if (result != ERR_OK) {
2407         ANS_LOGE("Reject by filters: %{public}d", result);
2408         return result;
2409     }
2410 
2411     if (isSystemApp) {
2412         ChangeNotificationByControlFlags(record, isAgentController);
2413     }
2414     CheckDoNotDisturbProfile(record);
2415 
2416     bool remove = false;
2417     if (isUpdateByOwner) {
2418         UpdateRecordByOwner(record, isSystemApp);
2419         remove = RemoveFromDelayedNotificationList(record->notification->GetKey());
2420     }
2421 
2422     // solve long term continuous update(music)
2423     if (!remove && CheckLongTermLiveView(record->request, record->notification->GetKey()) != ERR_OK) {
2424         return ERR_ANS_INVALID_PARAM;
2425     }
2426 
2427     result = AssignToNotificationList(record);
2428     if (result != ERR_OK) {
2429         return result;
2430     }
2431 
2432     return ERR_OK;
2433 }
2434 
2435 #ifdef NOTIFICATION_SMART_REMINDER_SUPPORTED
RegisterSwingCallback(const sptr<IRemoteObject> & swingCallback)2436 ErrCode AdvancedNotificationService::RegisterSwingCallback(const sptr<IRemoteObject> &swingCallback)
2437 {
2438     bool isSubSystem = AccessTokenHelper::VerifyNativeToken(IPCSkeleton::GetCallingTokenID());
2439     if (!isSubSystem) {
2440         ANS_LOGW("Not SA!");
2441         return ERR_ANS_NON_SYSTEM_APP;
2442     }
2443     if (!AccessTokenHelper::CheckPermission(OHOS_PERMISSION_NOTIFICATION_CONTROLLER)) {
2444         ANS_LOGW("Not have OHOS_PERMISSION_NOTIFICATION_CONTROLLER Permission!");
2445         return ERR_ANS_PERMISSION_DENIED;
2446     }
2447     return ReminderSwingDecisionCenter::GetInstance().RegisterSwingCallback(swingCallback);
2448 }
2449 #endif
2450 
UpdateNotificationTimerByUid(const int32_t uid,const bool isPaused)2451 ErrCode AdvancedNotificationService::UpdateNotificationTimerByUid(const int32_t uid, const bool isPaused)
2452 {
2453     bool isSubSystem = AccessTokenHelper::VerifyNativeToken(IPCSkeleton::GetCallingTokenID());
2454     int32_t callingUid = IPCSkeleton::GetCallingUid();
2455     if (!isSubSystem || callingUid != RESSCHED_UID) {
2456         ANS_LOGE("caller is not ressched, callingUid: %{public}d", callingUid);
2457         return ERR_ANS_NOT_SYSTEM_SERVICE;
2458     }
2459 
2460     if (!notificationSvrQueue_) {
2461         ANS_LOGE("Serial queue is invalidated.");
2462         return ERR_ANS_INVALID_PARAM;
2463     }
2464     ffrt::task_handle handler = notificationSvrQueue_->submit_h(std::bind([&]() {
2465         HandleUpdateLiveViewNotificationTimer(uid, isPaused);
2466     }));
2467     notificationSvrQueue_->wait(handler);
2468     return ERR_OK;
2469 }
2470 
OnRemoteDied(const wptr<IRemoteObject> & remote)2471 void PushCallbackRecipient::OnRemoteDied(const wptr<IRemoteObject> &remote)
2472 {
2473     ANS_LOGI("Push Callback died, remove the proxy object");
2474     AdvancedNotificationService::GetInstance()->ResetPushCallbackProxy();
2475 }
2476 
RemoveNotificationList(const std::shared_ptr<NotificationRecord> & record)2477 void AdvancedNotificationService::RemoveNotificationList(const std::shared_ptr<NotificationRecord> &record)
2478 {
2479 #ifdef ENABLE_ANS_AGGREGATION
2480     std::vector<sptr<Notification>> notifications;
2481     notifications.emplace_back(record->notification);
2482     EXTENTION_WRAPPER->UpdateByCancel(notifications, NotificationConstant::FLOW_CONTROL_REASON_DELETE);
2483 #endif
2484     notificationList_.remove(record);
2485 }
2486 
PushCallbackRecipient()2487 PushCallbackRecipient::PushCallbackRecipient() {}
2488 
~PushCallbackRecipient()2489 PushCallbackRecipient::~PushCallbackRecipient() {}
2490 
DisableNotificationFeature(const sptr<NotificationDisable> & notificationDisable)2491 ErrCode AdvancedNotificationService::DisableNotificationFeature(const sptr<NotificationDisable> &notificationDisable)
2492 {
2493     ANS_LOGD("called");
2494     if (notificationDisable == nullptr) {
2495         ANS_LOGE("notificationDisable is nullptr");
2496         return ERR_ANS_INVALID_PARAM;
2497     }
2498     bool isSubsystem = AccessTokenHelper::VerifyNativeToken(IPCSkeleton::GetCallingTokenID());
2499     if (!isSubsystem && !AccessTokenHelper::IsSystemApp()) {
2500         ANS_LOGE("notificationDisable is no system app");
2501         return ERR_ANS_NON_SYSTEM_APP;
2502     }
2503     if (!AccessTokenHelper::CheckPermission(OHOS_PERMISSION_NOTIFICATION_CONTROLLER)) {
2504         ANS_LOGE("notificationDisable is permission denied");
2505         return ERR_ANS_PERMISSION_DENIED;
2506     }
2507     if (notificationSvrQueue_ == nullptr) {
2508         ANS_LOGE("serial queue is invalid");
2509         return ERR_ANS_INVALID_PARAM;
2510     }
2511     ffrt::task_handle handler =
2512         notificationSvrQueue_->submit_h(std::bind([copyNotificationDisable = notificationDisable]() {
2513             ANS_LOGD("the ffrt enter");
2514             NotificationPreferences::GetInstance()->SetDisableNotificationInfo(copyNotificationDisable);
2515         }));
2516     notificationSvrQueue_->wait(handler);
2517     if (notificationDisable->GetDisabled()) {
2518         std::vector<std::string> bundleList = notificationDisable->GetBundleList();
2519         for (auto bundle : bundleList) {
2520             RemoveAllNotificationsByBundleName(
2521                 bundle, NotificationConstant::DISABLE_NOTIFICATION_FEATURE_REASON_DELETE);
2522         }
2523     }
2524     return ERR_OK;
2525 }
2526 
SetClassificationWithVoip(const sptr<NotificationRequest> & request)2527 void AdvancedNotificationService::SetClassificationWithVoip(const sptr<NotificationRequest> &request)
2528 {
2529     if (!request->GetClassification().empty() && request->GetClassification() != ANS_VOIP) {
2530         return;
2531     }
2532     if (!AccessTokenHelper::CheckPermission(OHOS_PERMISSION_NOTIFICATION_AGENT_CONTROLLER)) {
2533         ANS_LOGI("set classification empty");
2534         request->SetClassification("");
2535         return;
2536     }
2537     auto requestContent = request->GetContent();
2538     if (request->IsSystemLiveView() && requestContent != nullptr &&
2539         requestContent->GetNotificationContent() != nullptr) {
2540         auto localLiveViewContent = std::static_pointer_cast<NotificationLocalLiveViewContent>(
2541             requestContent->GetNotificationContent());
2542         if (localLiveViewContent->GetType() == TYPE_CODE_VOIP) {
2543             request->SetClassification(ANS_VOIP);
2544         }
2545     }
2546 }
2547 }  // namespace Notification
2548 }  // namespace OHOS
2549