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