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