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