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