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