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 "accesstoken_kit.h"
23 #include "ans_const_define.h"
24 #include "ans_inner_errors.h"
25 #include "ans_log_wrapper.h"
26 #include "errors.h"
27
28 #include "ipc_skeleton.h"
29 #include "notification_bundle_option.h"
30 #include "notification_constant.h"
31 #include "hitrace_meter_adapter.h"
32 #include "notification_unified_group_Info.h"
33 #include "os_account_manager.h"
34 #include "distributed_screen_status_manager.h"
35 #include "notification_extension_wrapper.h"
36 #include "notification_local_live_view_subscriber_manager.h"
37 #include "common_event_manager.h"
38 #include "common_event_support.h"
39 #include "common_event_publish_info.h"
40 #include "os_account_manager_helper.h"
41 #include "want_params_wrapper.h"
42 #include "ans_convert_enum.h"
43 #include "notification_analytics_util.h"
44
45 #include "advanced_notification_inline.cpp"
46 #include "notification_analytics_util.h"
47 #include "advanced_datashare_helper.h"
48 #include "advanced_datashare_helper_ext.h"
49 #include "datashare_result_set.h"
50 #include "system_ability_definition.h"
51 #include "if_system_ability_manager.h"
52 #include "iservice_registry.h"
53 #include "datashare_predicates.h"
54
55 namespace OHOS {
56 namespace Notification {
57
58 constexpr char FOUNDATION_BUNDLE_NAME[] = "ohos.global.systemres";
59 constexpr int32_t HOURS_IN_ONE_DAY = 24;
60 const static std::string NOTIFICATION_EVENT_PUSH_AGENT = "notification.event.PUSH_AGENT";
61 constexpr int32_t RSS_PID = 3051;
62 constexpr int32_t ANS_UID = 5523;
63 constexpr int32_t TYPE_CODE_DOWNLOAD = 8;
64 constexpr const char *FOCUS_MODE_REPEAT_CALLERS_ENABLE = "1";
65 constexpr const char *CONTACT_DATA = "datashare:///com.ohos.contactsdataability/contacts/contact_data?Proxy=true";
66 constexpr int32_t OPERATION_TYPE_COMMON_EVENT = 4;
67
SetDefaultNotificationEnabled( const sptr<NotificationBundleOption> &bundleOption, bool enabled)68 ErrCode AdvancedNotificationService::SetDefaultNotificationEnabled(
69 const sptr<NotificationBundleOption> &bundleOption, bool enabled)
70 {
71 sptr<NotificationBundleOption> bundle = GenerateValidBundleOption(bundleOption);
72 if (bundle == nullptr) {
73 return ERR_ANS_INVALID_BUNDLE;
74 }
75 sptr<EnabledNotificationCallbackData> bundleData =
76 new (std::nothrow) EnabledNotificationCallbackData(bundle->GetBundleName(), bundle->GetUid(), enabled);
77 if (bundleData == nullptr) {
78 ANS_LOGE("Failed to create EnabledNotificationCallbackData instance");
79 return ERR_NO_MEMORY;
80 }
81 SetSlotFlagsTrustlistsAsBundle(bundle);
82 ErrCode result = ERR_OK;
83 result = NotificationPreferences::GetInstance()->SetNotificationsEnabledForBundle(bundle, enabled);
84 if (result == ERR_OK) {
85 NotificationSubscriberManager::GetInstance()->NotifyEnabledNotificationChanged(bundleData);
86 PublishSlotChangeCommonEvent(bundle);
87 }
88
89 SendEnableNotificationHiSysEvent(bundleOption, enabled, result);
90 return result;
91 }
92
Publish(const std::string &label, const sptr<NotificationRequest> &request)93 ErrCode AdvancedNotificationService::Publish(const std::string &label, const sptr<NotificationRequest> &request)
94 {
95 HITRACE_METER_NAME(HITRACE_TAG_NOTIFICATION, __PRETTY_FUNCTION__);
96 ANS_LOGD("%{public}s", __FUNCTION__);
97
98 if (!request) {
99 ANSR_LOGE("ReminderRequest object is nullptr");
100 return ERR_ANS_INVALID_PARAM;
101 }
102
103 if (!InitPublishProcess()) {
104 return ERR_ANS_NO_MEMORY;
105 }
106
107 request->SetCreateTime(GetCurrentTime());
108 HaMetaMessage message = HaMetaMessage(EventSceneId::SCENE_1, EventBranchId::BRANCH_1);
109 bool isUpdateByOwnerAllowed = IsUpdateSystemLiveviewByOwner(request);
110 ErrCode result = publishProcess_[request->GetSlotType()]->PublishPreWork(request, isUpdateByOwnerAllowed);
111 if (result != ERR_OK) {
112 message.BranchId(EventBranchId::BRANCH_0).ErrorCode(result).Message("publish prework failed", true);
113 NotificationAnalyticsUtil::ReportPublishFailedEvent(request, message);
114 return result;
115 }
116 result = CheckUserIdParams(request->GetReceiverUserId());
117 if (result != ERR_OK) {
118 message.SceneId(EventSceneId::SCENE_3).ErrorCode(result).Message("User is invalid", true);
119 NotificationAnalyticsUtil::ReportPublishFailedEvent(request, message);
120 return result;
121 }
122 bool isSubsystem = AccessTokenHelper::VerifyNativeToken(IPCSkeleton::GetCallingTokenID());
123 if (isSubsystem) {
124 return PublishNotificationBySa(request);
125 }
126 if (request->GetRemovalWantAgent() != nullptr && request->GetRemovalWantAgent()->GetPendingWant() != nullptr) {
127 uint32_t operationType = (uint32_t)(request->GetRemovalWantAgent()->GetPendingWant()
128 ->GetType(request->GetRemovalWantAgent()->GetPendingWant()->GetTarget()));
129 bool isSystemApp = AccessTokenHelper::IsSystemApp();
130 if (!isSubsystem && !isSystemApp && operationType != OPERATION_TYPE_COMMON_EVENT) {
131 ANS_LOGI("SetRemovalWantAgent as nullptr");
132 request->SetRemovalWantAgent(nullptr);
133 }
134 }
135 do {
136 result = publishProcess_[request->GetSlotType()]->PublishNotificationByApp(request);
137 if (result != ERR_OK) {
138 break;
139 }
140
141 sptr<NotificationBundleOption> bundleOption;
142 result = PrepareNotificationInfo(request, bundleOption);
143 if (result != ERR_OK) {
144 break;
145 }
146
147 result = CheckSoundPermission(request, bundleOption->GetBundleName());
148 if (result != ERR_OK) {
149 message.ErrorCode(result).Message("Check sound failed.");
150 break;
151 }
152
153 #ifndef IS_EMULATOR
154 if (IsNeedPushCheck(request)) {
155 result = PushCheck(request);
156 }
157 #endif
158
159 if (result != ERR_OK) {
160 message.ErrorCode(result).Message("Push check failed.");
161 break;
162 }
163 result = PublishPreparedNotification(request, bundleOption, isUpdateByOwnerAllowed);
164 if (result != ERR_OK) {
165 message.ErrorCode(result).Message("Publish prepared failed.");
166 break;
167 }
168 } while (0);
169
170 SendPublishHiSysEvent(request, result);
171 return result;
172 }
173
PublishNotificationForIndirectProxy(const sptr<NotificationRequest> &request)174 ErrCode AdvancedNotificationService::PublishNotificationForIndirectProxy(const sptr<NotificationRequest> &request)
175 {
176 HITRACE_METER_NAME(HITRACE_TAG_NOTIFICATION, __PRETTY_FUNCTION__);
177 ANS_LOGD("%{public}s", __FUNCTION__);
178
179 if (!request) {
180 ANSR_LOGE("ReminderRequest object is nullptr");
181 return ERR_ANS_INVALID_PARAM;
182 }
183 ErrCode result = PrePublishRequest(request);
184 if (result != ERR_OK) {
185 return result;
186 }
187 auto tokenCaller = IPCSkeleton::GetCallingTokenID();
188 bool isAgentController = AccessTokenHelper::VerifyCallerPermission(tokenCaller,
189 OHOS_PERMISSION_NOTIFICATION_AGENT_CONTROLLER);
190 // SA not support sound
191 if (!request->GetSound().empty()) {
192 request->SetSound("");
193 }
194 std::string bundle = request->GetCreatorBundleName();
195 int32_t uid = request->GetCreatorUid();
196 std::shared_ptr<NotificationRecord> record = std::make_shared<NotificationRecord>();
197 record->request = request;
198 record->isThirdparty = false;
199 record->bundleOption = new (std::nothrow) NotificationBundleOption(bundle, uid);
200 record->bundleOption->SetInstanceKey(request->GetCreatorInstanceKey());
201 sptr<NotificationBundleOption> bundleOption = new (std::nothrow) NotificationBundleOption(bundle, uid);
202 if (record->bundleOption == nullptr || bundleOption == nullptr) {
203 ANS_LOGE("Failed to create bundleOption");
204 return ERR_ANS_NO_MEMORY;
205 }
206 record->notification = new (std::nothrow) Notification(request);
207 if (record->notification == nullptr) {
208 ANS_LOGE("Failed to create notification");
209 return ERR_ANS_NO_MEMORY;
210 }
211
212 if (notificationSvrQueue_ == nullptr) {
213 ANS_LOGE("Serial queue is invalid.");
214 return ERR_ANS_INVALID_PARAM;
215 }
216
217 SetRequestBySlotType(record->request, bundleOption);
218
219 auto ipcUid = IPCSkeleton::GetCallingUid();
220 ffrt::task_handle handler = notificationSvrQueue_->submit_h([&]() {
221 if (AssignValidNotificationSlot(record, bundleOption) != ERR_OK) {
222 ANS_LOGE("Can not assign valid slot!");
223 }
224
225 ChangeNotificationByControlFlags(record, isAgentController);
226 if (IsSaCreateSystemLiveViewAsBundle(record, ipcUid) &&
227 (std::static_pointer_cast<OHOS::Notification::NotificationLocalLiveViewContent>(
228 record->request->GetContent()->GetNotificationContent())->GetType() == TYPE_CODE_DOWNLOAD)) {
229 result = SaPublishSystemLiveViewAsBundle(record);
230 if (result == ERR_OK) {
231 SendLiveViewUploadHiSysEvent(record, UploadStatus::CREATE);
232 }
233 return;
234 }
235
236 if (AssignToNotificationList(record) != ERR_OK) {
237 ANS_LOGE("Failed to assign notification list");
238 return;
239 }
240
241 sptr<NotificationSortingMap> sortingMap = GenerateSortingMap();
242 NotificationSubscriberManager::GetInstance()->NotifyConsumed(record->notification, sortingMap);
243 });
244 notificationSvrQueue_->wait(handler);
245 if (result != ERR_OK) {
246 return result;
247 }
248
249 if ((record->request->GetAutoDeletedTime() > GetCurrentTime()) && !record->request->IsCommonLiveView()) {
250 StartAutoDelete(record,
251 record->request->GetAutoDeletedTime(), NotificationConstant::TRIGGER_AUTO_DELETE_REASON_DELETE);
252 }
253 return ERR_OK;
254 }
255
InitPublishProcess()256 bool AdvancedNotificationService::InitPublishProcess()
257 {
258 if (publishProcess_.size() > 0) {
259 return true;
260 }
261
262 std::shared_ptr<LivePublishProcess> livePublishProcess = LivePublishProcess::GetInstance();
263 if (livePublishProcess == nullptr) {
264 ANS_LOGE("InitPublishProcess fail as livePublishProcess is nullptr.");
265 return false;
266 }
267 publishProcess_.insert_or_assign(NotificationConstant::SlotType::LIVE_VIEW, livePublishProcess);
268 std::shared_ptr<CommonNotificationPublishProcess> commonNotificationPublishProcess =
269 CommonNotificationPublishProcess::GetInstance();
270 if (commonNotificationPublishProcess == nullptr) {
271 ANS_LOGE("InitPublishProcess fail as commonNotificationPublishProcess is nullptr.");
272 publishProcess_.clear();
273 return false;
274 }
275 publishProcess_.insert_or_assign(
276 NotificationConstant::SlotType::SOCIAL_COMMUNICATION, commonNotificationPublishProcess);
277 publishProcess_.insert_or_assign(
278 NotificationConstant::SlotType::SERVICE_REMINDER, commonNotificationPublishProcess);
279 publishProcess_.insert_or_assign(
280 NotificationConstant::SlotType::CONTENT_INFORMATION, commonNotificationPublishProcess);
281 publishProcess_.insert_or_assign(
282 NotificationConstant::SlotType::OTHER, commonNotificationPublishProcess);
283 publishProcess_.insert_or_assign(
284 NotificationConstant::SlotType::CUSTOM, commonNotificationPublishProcess);
285 publishProcess_.insert_or_assign(
286 NotificationConstant::SlotType::CUSTOMER_SERVICE, commonNotificationPublishProcess);
287 publishProcess_.insert_or_assign(
288 NotificationConstant::SlotType::EMERGENCY_INFORMATION, commonNotificationPublishProcess);
289 return true;
290 }
291
Cancel(int32_t notificationId, const std::string &label, int32_t instanceKey)292 ErrCode AdvancedNotificationService::Cancel(int32_t notificationId, const std::string &label, int32_t instanceKey)
293 {
294 ANS_LOGD("%{public}s", __FUNCTION__);
295
296 sptr<NotificationBundleOption> bundleOption = GenerateBundleOption();
297 if (bundleOption == nullptr) {
298 std::string message = "get bundleOption is null.";
299 OHOS::Notification::HaMetaMessage haMetaMessage = HaMetaMessage(1, 1)
300 .ErrorCode(ERR_ANS_INVALID_BUNDLE).NotificationId(notificationId);
301 ReportDeleteFailedEventPush(haMetaMessage, NotificationConstant::APP_CANCEL_REASON_DELETE,
302 message);
303 ANS_LOGE("%{public}s", message.c_str());
304 return ERR_ANS_INVALID_BUNDLE;
305 }
306 bundleOption->SetInstanceKey(instanceKey);
307 return CancelPreparedNotification(notificationId, label, bundleOption,
308 NotificationConstant::APP_CANCEL_REASON_DELETE);
309 }
310
CancelAll(int32_t instanceKey)311 ErrCode AdvancedNotificationService::CancelAll(int32_t instanceKey)
312 {
313 ANS_LOGD("%{public}s", __FUNCTION__);
314 const int reason = NotificationConstant::APP_CANCEL_ALL_REASON_DELETE;
315 sptr<NotificationBundleOption> bundleOption = GenerateBundleOption();
316 if (bundleOption == nullptr) {
317 return ERR_ANS_INVALID_BUNDLE;
318 }
319 bundleOption->SetInstanceKey(instanceKey);
320
321 if (notificationSvrQueue_ == nullptr) {
322 ANS_LOGE("Serial queue is invalidated.");
323 return ERR_ANS_INVALID_PARAM;
324 }
325 ErrCode result = ExcuteCancelAll(bundleOption, reason);
326 return result;
327 }
328
ExcuteCancelAll( const sptr<NotificationBundleOption>& bundleOption, const int32_t reason)329 ErrCode AdvancedNotificationService::ExcuteCancelAll(
330 const sptr<NotificationBundleOption>& bundleOption, const int32_t reason)
331 {
332 ErrCode result = ERR_OK;
333 ffrt::task_handle handler = notificationSvrQueue_->submit_h(std::bind([&]() {
334 ANS_LOGD("ffrt enter!");
335 sptr<Notification> notification = nullptr;
336
337 std::vector<std::string> keys = GetNotificationKeys(bundleOption);
338 std::vector<sptr<Notification>> notifications;
339 std::vector<uint64_t> timerIds;
340 for (auto key : keys) {
341 #ifdef DISTRIBUTED_NOTIFICATION_SUPPORTED
342 std::string deviceId;
343 std::string bundleName;
344 GetDistributedInfo(key, deviceId, bundleName);
345 #endif
346 result = RemoveFromNotificationList(key, notification, true, reason);
347 if (result != ERR_OK) {
348 continue;
349 }
350
351 if (notification != nullptr) {
352 UpdateRecentNotification(notification, true, reason);
353 notifications.emplace_back(notification);
354 timerIds.emplace_back(notification->GetAutoDeletedTimer());
355 #ifdef DISTRIBUTED_NOTIFICATION_SUPPORTED
356 DoDistributedDelete(deviceId, bundleName, notification);
357 #endif
358 }
359 if (notifications.size() >= MAX_CANCELED_PARCELABLE_VECTOR_NUM) {
360 std::vector<sptr<Notification>> currNotificationList = notifications;
361 NotificationSubscriberManager::GetInstance()->BatchNotifyCanceled(
362 currNotificationList, nullptr, reason);
363 notifications.clear();
364 }
365 }
366
367 if (!notifications.empty()) {
368 NotificationSubscriberManager::GetInstance()->BatchNotifyCanceled(
369 notifications, nullptr, reason);
370 }
371 BatchCancelTimer(timerIds);
372 result = ERR_OK;
373 }));
374 notificationSvrQueue_->wait(handler);
375 return result;
376 }
377
CancelAsBundle( const sptr<NotificationBundleOption> &bundleOption, int32_t notificationId, int32_t userId)378 ErrCode AdvancedNotificationService::CancelAsBundle(
379 const sptr<NotificationBundleOption> &bundleOption, int32_t notificationId, int32_t userId)
380 {
381 ANS_LOGD("%{public}s", __FUNCTION__);
382 int32_t reason = NotificationConstant::APP_CANCEL_AS_BUNELE_REASON_DELETE;
383 bool isSubsystem = AccessTokenHelper::VerifyNativeToken(IPCSkeleton::GetCallingTokenID());
384 if (!isSubsystem && !AccessTokenHelper::IsSystemApp()) {
385 std::string message = "not systemApp";
386 OHOS::Notification::HaMetaMessage haMetaMessage = HaMetaMessage(2, 1)
387 .ErrorCode(ERR_ANS_NON_SYSTEM_APP).NotificationId(notificationId);
388 ReportDeleteFailedEventPush(haMetaMessage, reason, message);
389 ANS_LOGE("%{public}s", message.c_str());
390 return ERR_ANS_NON_SYSTEM_APP;
391 }
392
393 if (!AccessTokenHelper::CheckPermission(OHOS_PERMISSION_NOTIFICATION_CONTROLLER) ||
394 !AccessTokenHelper::CheckPermission(OHOS_PERMISSION_NOTIFICATION_AGENT_CONTROLLER)) {
395 std::string message = "no acl permission";
396 OHOS::Notification::HaMetaMessage haMetaMessage = HaMetaMessage(2, 2)
397 .ErrorCode(ERR_ANS_PERMISSION_DENIED).NotificationId(notificationId);
398 ReportDeleteFailedEventPush(haMetaMessage, reason, message);
399 ANS_LOGE("%{public}s", message.c_str());
400 return ERR_ANS_PERMISSION_DENIED;
401 }
402
403 int32_t errCode = CheckUserIdParams(userId);
404 if (errCode != ERR_OK) {
405 return errCode;
406 }
407
408 int32_t uid = -1;
409 if (bundleOption->GetUid() == DEFAULT_UID) {
410 std::shared_ptr<BundleManagerHelper> bundleManager = BundleManagerHelper::GetInstance();
411 if (bundleManager != nullptr) {
412 uid = BundleManagerHelper::GetInstance()->GetDefaultUidByBundleName(bundleOption->GetBundleName(), userId);
413 }
414 } else {
415 uid = bundleOption->GetUid();
416 }
417 if (uid < 0) {
418 std::string message = "uid error";
419 OHOS::Notification::HaMetaMessage haMetaMessage = HaMetaMessage(2, 3)
420 .ErrorCode(ERR_ANS_INVALID_UID).NotificationId(notificationId);
421 ReportDeleteFailedEventPush(haMetaMessage, reason, message);
422 ANS_LOGE("%{public}s", message.c_str());
423 return ERR_ANS_INVALID_UID;
424 }
425 sptr<NotificationBundleOption> bundle = new (std::nothrow) NotificationBundleOption(
426 bundleOption->GetBundleName(), uid);
427 return CancelPreparedNotification(notificationId, "", bundle, reason);
428 }
429
CancelAsBundle( const sptr<NotificationBundleOption> &bundleOption, int32_t notificationId)430 ErrCode AdvancedNotificationService::CancelAsBundle(
431 const sptr<NotificationBundleOption> &bundleOption, int32_t notificationId)
432 {
433 ANS_LOGD("%{public}s, uid = %{public}d", __FUNCTION__, bundleOption->GetUid());
434 int32_t userId = -1;
435 if (bundleOption->GetUid() != 0) {
436 OHOS::AccountSA::OsAccountManager::GetOsAccountLocalIdFromUid(bundleOption->GetUid(), userId);
437 } else {
438 OHOS::AccountSA::OsAccountManager::GetOsAccountLocalIdFromUid(IPCSkeleton::GetCallingUid(), userId);
439 }
440 return CancelAsBundle(bundleOption, notificationId, userId);
441 }
442
CancelAsBundle( int32_t notificationId, const std::string &representativeBundle, int32_t userId)443 ErrCode AdvancedNotificationService::CancelAsBundle(
444 int32_t notificationId, const std::string &representativeBundle, int32_t userId)
445 {
446 ANS_LOGD("%{public}s", __FUNCTION__);
447 sptr<NotificationBundleOption> bundleOption = new (std::nothrow) NotificationBundleOption(
448 representativeBundle, DEFAULT_UID);
449 return CancelAsBundle(bundleOption, notificationId, userId);
450 }
451
CancelAsBundleWithAgent( const sptr<NotificationBundleOption> &bundleOption, const int32_t id)452 ErrCode AdvancedNotificationService::CancelAsBundleWithAgent(
453 const sptr<NotificationBundleOption> &bundleOption, const int32_t id)
454 {
455 ANS_LOGD("Called.");
456 int32_t reason = NotificationConstant::APP_CANCEL_AS_BUNELE_WITH_AGENT_REASON_DELETE;
457 bool isSubsystem = AccessTokenHelper::VerifyNativeToken(IPCSkeleton::GetCallingTokenID());
458 if (!isSubsystem && !AccessTokenHelper::IsSystemApp()) {
459 std::string message = "not systemApp";
460 OHOS::Notification::HaMetaMessage haMetaMessage = HaMetaMessage(2, 4)
461 .ErrorCode(ERR_ANS_NON_SYSTEM_APP).NotificationId(id);
462 ReportDeleteFailedEventPush(haMetaMessage, reason, message);
463 ANS_LOGE("%{public}s", message.c_str());
464 return ERR_ANS_NON_SYSTEM_APP;
465 }
466
467 if (IsAgentRelationship(GetClientBundleName(), bundleOption->GetBundleName())) {
468 int32_t userId = -1;
469 if (bundleOption->GetUid() != 0) {
470 OHOS::AccountSA::OsAccountManager::GetOsAccountLocalIdFromUid(bundleOption->GetUid(), userId);
471 } else {
472 OHOS::AccountSA::OsAccountManager::GetOsAccountLocalIdFromUid(IPCSkeleton::GetCallingUid(), userId);
473 }
474 int32_t uid = -1;
475 if (bundleOption->GetUid() == DEFAULT_UID) {
476 std::shared_ptr<BundleManagerHelper> bundleManager = BundleManagerHelper::GetInstance();
477 if (bundleManager != nullptr) {
478 uid = BundleManagerHelper::GetInstance()->GetDefaultUidByBundleName(
479 bundleOption->GetBundleName(), userId);
480 }
481 } else {
482 uid = bundleOption->GetUid();
483 }
484 if (uid < 0) {
485 std::string message = "uid error";
486 OHOS::Notification::HaMetaMessage haMetaMessage = HaMetaMessage(2, 5)
487 .ErrorCode(ERR_ANS_INVALID_UID).NotificationId(id);
488 ReportDeleteFailedEventPush(haMetaMessage, reason, message);
489 ANS_LOGE("%{public}s", message.c_str());
490 return ERR_ANS_INVALID_UID;
491 }
492 sptr<NotificationBundleOption> bundle = new (std::nothrow) NotificationBundleOption(
493 bundleOption->GetBundleName(), uid);
494 return CancelPreparedNotification(id, "", bundle, reason);
495 }
496 std::string message = "no agent setting";
497 OHOS::Notification::HaMetaMessage haMetaMessage = HaMetaMessage(2, 6)
498 .ErrorCode(ERR_ANS_NO_AGENT_SETTING).NotificationId(id);
499 ReportDeleteFailedEventPush(haMetaMessage, reason, message);
500 ANS_LOGE("%{public}s", message.c_str());
501 return ERR_ANS_NO_AGENT_SETTING;
502 }
503
PublishAsBundle( const sptr<NotificationRequest> notification, const std::string &representativeBundle)504 ErrCode AdvancedNotificationService::PublishAsBundle(
505 const sptr<NotificationRequest> notification, const std::string &representativeBundle)
506 {
507 return ERR_INVALID_OPERATION;
508 }
509
SetNotificationBadgeNum(int32_t num)510 ErrCode AdvancedNotificationService::SetNotificationBadgeNum(int32_t num)
511 {
512 ANS_LOGD("%{public}s", __FUNCTION__);
513
514 sptr<NotificationBundleOption> bundleOption = GenerateBundleOption();
515 if (bundleOption == nullptr) {
516 ANS_LOGD("BundleOption is null.");
517 return ERR_ANS_INVALID_BUNDLE;
518 }
519
520 if (notificationSvrQueue_ == nullptr) {
521 ANS_LOGE("Serial queue is invalidity.");
522 return ERR_ANS_INVALID_PARAM;
523 }
524 ErrCode result = ERR_OK;
525 ffrt::task_handle handler = notificationSvrQueue_->submit_h(
526 std::bind([&]() {
527 ANS_LOGD("ffrt enter!");
528 result = NotificationPreferences::GetInstance()->SetTotalBadgeNums(bundleOption, num);
529 }));
530 notificationSvrQueue_->wait(handler);
531 return result;
532 }
533
Delete(const std::string &key, int32_t removeReason)534 ErrCode AdvancedNotificationService::Delete(const std::string &key, int32_t removeReason)
535 {
536 ANS_LOGD("%{public}s", __FUNCTION__);
537 bool isSubsystem = AccessTokenHelper::VerifyNativeToken(IPCSkeleton::GetCallingTokenID());
538 if (!isSubsystem && !AccessTokenHelper::IsSystemApp()) {
539 std::string message = "not systemApp. key:" + key + ".";
540 OHOS::Notification::HaMetaMessage haMetaMessage = HaMetaMessage(4, 1)
541 .ErrorCode(ERR_ANS_NON_SYSTEM_APP);
542 ReportDeleteFailedEventPush(haMetaMessage, removeReason, message);
543 ANS_LOGE("%{public}s", message.c_str());
544 return ERR_ANS_NON_SYSTEM_APP;
545 }
546
547 if (!AccessTokenHelper::CheckPermission(OHOS_PERMISSION_NOTIFICATION_CONTROLLER)) {
548 std::string message = "no acl permission. key:" + key + ".";
549 OHOS::Notification::HaMetaMessage haMetaMessage = HaMetaMessage(4, 2)
550 .ErrorCode(ERR_ANS_PERMISSION_DENIED);
551 ReportDeleteFailedEventPush(haMetaMessage, removeReason, message);
552 ANS_LOGE("%{public}s", message.c_str());
553 return ERR_ANS_PERMISSION_DENIED;
554 }
555
556 if (notificationSvrQueue_ == nullptr) {
557 std::string message = "Serial queue is invalidated. key:" + key + ".";
558 ANS_LOGE("%{public}s", message.c_str());
559 return ERR_ANS_INVALID_PARAM;
560 }
561
562 return ExcuteDelete(key, removeReason);
563 }
564
ExcuteDelete(const std::string &key, const int32_t removeReason)565 ErrCode AdvancedNotificationService::ExcuteDelete(const std::string &key, const int32_t removeReason)
566 {
567 ErrCode result = ERR_OK;
568 ffrt::task_handle handler = notificationSvrQueue_->submit_h(std::bind([&]() {
569 ANS_LOGD("ffrt enter!");
570 sptr<Notification> notification = nullptr;
571 #ifdef DISTRIBUTED_NOTIFICATION_SUPPORTED
572 std::string deviceId;
573 std::string bundleName;
574 GetDistributedInfo(key, deviceId, bundleName);
575 #endif
576 result = RemoveFromNotificationList(key, notification, false, removeReason);
577 if (result != ERR_OK) {
578 return;
579 }
580
581 if (notification != nullptr) {
582 UpdateRecentNotification(notification, true, removeReason);
583 CancelTimer(notification->GetAutoDeletedTimer());
584 NotificationSubscriberManager::GetInstance()->NotifyCanceled(notification, nullptr, removeReason);
585 #ifdef DISTRIBUTED_NOTIFICATION_SUPPORTED
586 DoDistributedDelete(deviceId, bundleName, notification);
587 #endif
588 }
589 }));
590 notificationSvrQueue_->wait(handler);
591
592 return result;
593 }
594
DeleteByBundle(const sptr<NotificationBundleOption> &bundleOption)595 ErrCode AdvancedNotificationService::DeleteByBundle(const sptr<NotificationBundleOption> &bundleOption)
596 {
597 ANS_LOGD("%{public}s", __FUNCTION__);
598
599 bool isSubsystem = AccessTokenHelper::VerifyNativeToken(IPCSkeleton::GetCallingTokenID());
600 if (!isSubsystem && !AccessTokenHelper::IsSystemApp()) {
601 ANS_LOGD("VerifyNativeToken is false.");
602 return ERR_ANS_NON_SYSTEM_APP;
603 }
604
605 if (!AccessTokenHelper::CheckPermission(OHOS_PERMISSION_NOTIFICATION_CONTROLLER)) {
606 return ERR_ANS_PERMISSION_DENIED;
607 }
608
609 sptr<NotificationBundleOption> bundle = GenerateValidBundleOption(bundleOption);
610 if (bundle == nullptr) {
611 ANS_LOGD("bundle is false.");
612 return ERR_ANS_INVALID_BUNDLE;
613 }
614
615 if (notificationSvrQueue_ == nullptr) {
616 ANS_LOGE("Serial queue is invalid.");
617 return ERR_ANS_INVALID_PARAM;
618 }
619 ErrCode result = ERR_OK;
620 ffrt::task_handle handler = notificationSvrQueue_->submit_h(std::bind([&]() {
621 ANS_LOGD("ffrt enter!");
622 std::vector<std::string> keys = GetNotificationKeys(bundle);
623 for (auto key : keys) {
624 #ifdef DISTRIBUTED_NOTIFICATION_SUPPORTED
625 std::string deviceId;
626 std::string bundleName;
627 GetDistributedInfo(key, deviceId, bundleName);
628 #endif
629 sptr<Notification> notification = nullptr;
630
631 result = RemoveFromNotificationList(key, notification, false, NotificationConstant::CANCEL_REASON_DELETE);
632 if (result != ERR_OK) {
633 continue;
634 }
635
636 if (notification != nullptr) {
637 int32_t reason = NotificationConstant::CANCEL_REASON_DELETE;
638 UpdateRecentNotification(notification, true, reason);
639 CancelTimer(notification->GetAutoDeletedTimer());
640 NotificationSubscriberManager::GetInstance()->NotifyCanceled(notification, nullptr, reason);
641 #ifdef DISTRIBUTED_NOTIFICATION_SUPPORTED
642 DoDistributedDelete(deviceId, bundleName, notification);
643 #endif
644 }
645 }
646
647 result = ERR_OK;
648 }));
649 notificationSvrQueue_->wait(handler);
650
651 return result;
652 }
653
DeleteAll()654 ErrCode AdvancedNotificationService::DeleteAll()
655 {
656 ANS_LOGD("%{public}s", __FUNCTION__);
657
658 const int32_t reason = NotificationConstant::CANCEL_ALL_REASON_DELETE;
659 bool isSubsystem = AccessTokenHelper::VerifyNativeToken(IPCSkeleton::GetCallingTokenID());
660 if (!isSubsystem && !AccessTokenHelper::IsSystemApp()) {
661 std::string message = "not system app.";
662 OHOS::Notification::HaMetaMessage haMetaMessage = HaMetaMessage(6, 8)
663 .ErrorCode(ERR_ANS_NON_SYSTEM_APP);
664 ReportDeleteFailedEventPush(haMetaMessage, reason, message);
665 ANS_LOGE("%{public}s", message.c_str());
666 return ERR_ANS_NON_SYSTEM_APP;
667 }
668
669 if (!AccessTokenHelper::CheckPermission(OHOS_PERMISSION_NOTIFICATION_CONTROLLER)) {
670 std::string message = "no acl permission.";
671 OHOS::Notification::HaMetaMessage haMetaMessage = HaMetaMessage(6, 9)
672 .ErrorCode(ERR_ANS_PERMISSION_DENIED);
673 ReportDeleteFailedEventPush(haMetaMessage, reason, message);
674 ANS_LOGE("%{public}s", message.c_str());
675 return ERR_ANS_PERMISSION_DENIED;
676 }
677
678 if (notificationSvrQueue_ == nullptr) {
679 std::string message = "Serial queue is invalidity.";
680 ANS_LOGE("%{public}s", message.c_str());
681 return ERR_ANS_INVALID_PARAM;
682 }
683 ErrCode result = ERR_OK;
684 ffrt::task_handle handler = notificationSvrQueue_->submit_h(std::bind([&]() {
685 ANS_LOGD("ffrt enter!");
686 int32_t activeUserId = SUBSCRIBE_USER_INIT;
687 if (OsAccountManagerHelper::GetInstance().GetCurrentActiveUserId(activeUserId) != ERR_OK) {
688 return;
689 }
690 std::vector<std::string> keys = GetNotificationKeys(nullptr);
691 std::vector<sptr<Notification>> notifications;
692 std::vector<uint64_t> timerIds;
693 for (auto key : keys) {
694 #ifdef DISTRIBUTED_NOTIFICATION_SUPPORTED
695 std::string deviceId;
696 std::string bundleName;
697 GetDistributedInfo(key, deviceId, bundleName);
698 #endif
699 sptr<Notification> notification = nullptr;
700
701 result = RemoveFromNotificationListForDeleteAll(key, activeUserId, notification);
702 if ((result != ERR_OK) || (notification == nullptr)) {
703 continue;
704 }
705
706 if (notification->GetUserId() == activeUserId) {
707 UpdateRecentNotification(notification, true, reason);
708 notifications.emplace_back(notification);
709 timerIds.emplace_back(notification->GetAutoDeletedTimer());
710 #ifdef DISTRIBUTED_NOTIFICATION_SUPPORTED
711 DoDistributedDelete(deviceId, bundleName, notification);
712 #endif
713 }
714 if (notifications.size() >= MAX_CANCELED_PARCELABLE_VECTOR_NUM) {
715 ANS_LOGD("Notifications size greater than or equal to MAX_CANCELED_PARCELABLE_VECTOR_NUM.");
716 SendNotificationsOnCanceled(notifications, nullptr, reason);
717 }
718 }
719 if (!notifications.empty()) {
720 NotificationSubscriberManager::GetInstance()->BatchNotifyCanceled(
721 notifications, nullptr, reason);
722 }
723 BatchCancelTimer(timerIds);
724 result = ERR_OK;
725 }));
726 notificationSvrQueue_->wait(handler);
727
728 return result;
729 }
730
SetShowBadgeEnabledForBundle( const sptr<NotificationBundleOption> &bundleOption, bool enabled)731 ErrCode AdvancedNotificationService::SetShowBadgeEnabledForBundle(
732 const sptr<NotificationBundleOption> &bundleOption, bool enabled)
733 {
734 bool isSubsystem = AccessTokenHelper::VerifyNativeToken(IPCSkeleton::GetCallingTokenID());
735 if (!isSubsystem && !AccessTokenHelper::IsSystemApp()) {
736 return ERR_ANS_NON_SYSTEM_APP;
737 }
738
739 if (!AccessTokenHelper::CheckPermission(OHOS_PERMISSION_NOTIFICATION_CONTROLLER)) {
740 ANS_LOGD("Check permission is false.");
741 return ERR_ANS_PERMISSION_DENIED;
742 }
743
744 sptr<NotificationBundleOption> bundle = GenerateValidBundleOption(bundleOption);
745 if (bundle == nullptr) {
746 return ERR_ANS_INVALID_BUNDLE;
747 }
748
749 if (notificationSvrQueue_ == nullptr) {
750 ANS_LOGE("NotificationSvrQueue_ is invalid.");
751 return ERR_ANS_INVALID_PARAM;
752 }
753 ErrCode result = ERR_OK;
754 ffrt::task_handle handler = notificationSvrQueue_->submit_h(
755 std::bind([&]() {
756 ANS_LOGD("ffrt enter!");
757 result = NotificationPreferences::GetInstance()->SetShowBadge(bundle, enabled);
758 if (result == ERR_OK) {
759 HandleBadgeEnabledChanged(bundle, enabled);
760 }
761 }));
762 notificationSvrQueue_->wait(handler);
763 return result;
764 }
765
HandleBadgeEnabledChanged( const sptr<NotificationBundleOption> &bundleOption, bool &enabled)766 void AdvancedNotificationService::HandleBadgeEnabledChanged(
767 const sptr<NotificationBundleOption> &bundleOption, bool &enabled)
768 {
769 sptr<EnabledNotificationCallbackData> enabledData = new (std::nothrow)
770 EnabledNotificationCallbackData(bundleOption->GetBundleName(), bundleOption->GetUid(), enabled);
771 if (enabledData == nullptr) {
772 ANS_LOGE("Failed to create badge enabled data object.");
773 return;
774 }
775
776 NotificationSubscriberManager::GetInstance()->NotifyBadgeEnabledChanged(enabledData);
777 }
778
GetShowBadgeEnabledForBundle( const sptr<NotificationBundleOption> &bundleOption, bool &enabled)779 ErrCode AdvancedNotificationService::GetShowBadgeEnabledForBundle(
780 const sptr<NotificationBundleOption> &bundleOption, bool &enabled)
781 {
782 ANS_LOGD("%{public}s", __FUNCTION__);
783
784 bool isSubsystem = AccessTokenHelper::VerifyNativeToken(IPCSkeleton::GetCallingTokenID());
785 if (!isSubsystem && !AccessTokenHelper::IsSystemApp()) {
786 ANS_LOGD("VerifyNativeToken is bogus.");
787 return ERR_ANS_NON_SYSTEM_APP;
788 }
789
790 if (!AccessTokenHelper::CheckPermission(OHOS_PERMISSION_NOTIFICATION_CONTROLLER)) {
791 return ERR_ANS_PERMISSION_DENIED;
792 }
793
794 sptr<NotificationBundleOption> bundle = GenerateValidBundleOption(bundleOption);
795 if (bundle == nullptr) {
796 ANS_LOGD("Failed to generateValidBundleOption.");
797 return ERR_ANS_INVALID_BUNDLE;
798 }
799
800 if (notificationSvrQueue_ == nullptr) {
801 ANS_LOGE("Serial queue is invalid.");
802 return ERR_ANS_INVALID_PARAM;
803 }
804 ErrCode result = ERR_OK;
805 ffrt::task_handle handler = notificationSvrQueue_->submit_h(std::bind([&]() {
806 ANS_LOGD("ffrt enter!");
807 result = NotificationPreferences::GetInstance()->IsShowBadge(bundle, enabled);
808 if (result == ERR_ANS_PREFERENCES_NOTIFICATION_BUNDLE_NOT_EXIST) {
809 result = ERR_OK;
810 enabled = true;
811 }
812 }));
813 notificationSvrQueue_->wait(handler);
814 return result;
815 }
816
GetShowBadgeEnabled(bool &enabled)817 ErrCode AdvancedNotificationService::GetShowBadgeEnabled(bool &enabled)
818 {
819 ANS_LOGD("%{public}s", __FUNCTION__);
820
821 sptr<NotificationBundleOption> bundleOption = GenerateBundleOption();
822 if (bundleOption == nullptr) {
823 return ERR_ANS_INVALID_BUNDLE;
824 }
825
826 if (notificationSvrQueue_ == nullptr) {
827 ANS_LOGE("Serial queue is ineffective.");
828 return ERR_ANS_INVALID_PARAM;
829 }
830 ErrCode result = ERR_OK;
831 ffrt::task_handle handler = notificationSvrQueue_->submit_h(std::bind([&]() {
832 ANS_LOGD("ffrt enter!");
833 result = NotificationPreferences::GetInstance()->IsShowBadge(bundleOption, enabled);
834 if (result == ERR_ANS_PREFERENCES_NOTIFICATION_BUNDLE_NOT_EXIST) {
835 result = ERR_OK;
836 enabled = true;
837 }
838 }));
839 notificationSvrQueue_->wait(handler);
840 return result;
841 }
842
RequestEnableNotification(const std::string &deviceId, const sptr<AnsDialogCallback> &callback, const sptr<IRemoteObject> &callerToken)843 ErrCode AdvancedNotificationService::RequestEnableNotification(const std::string &deviceId,
844 const sptr<AnsDialogCallback> &callback,
845 const sptr<IRemoteObject> &callerToken)
846 {
847 ANS_LOGD("%{public}s", __FUNCTION__);
848 if (callback == nullptr) {
849 ANS_LOGE("callback == nullptr");
850 return ERR_ANS_INVALID_PARAM;
851 }
852
853 ErrCode result = ERR_OK;
854 sptr<NotificationBundleOption> bundleOption = GenerateBundleOption();
855 if (bundleOption == nullptr) {
856 ANS_LOGD("bundleOption == nullptr");
857 return ERR_ANS_INVALID_BUNDLE;
858 }
859 // To get the permission
860 bool allowedNotify = false;
861 HaMetaMessage message = HaMetaMessage(EventSceneId::SCENE_2, EventBranchId::BRANCH_1)
862 .BundleName(bundleOption->GetBundleName());
863 result = IsAllowedNotifySelf(bundleOption, allowedNotify);
864 if (result != ERR_OK) {
865 message.Message("Allow notify self failed: " + std::to_string(result));
866 NotificationAnalyticsUtil::ReportModifyEvent(message);
867 return ERROR_INTERNAL_ERROR;
868 }
869 ANS_LOGI("allowedNotify = %{public}d, bundle = %{public}s", allowedNotify,
870 bundleOption->GetBundleName().c_str());
871 if (allowedNotify) {
872 return ERR_OK;
873 }
874 // Check to see if it has been popover before
875 bool hasPopped = false;
876 result = GetHasPoppedDialog(bundleOption, hasPopped);
877 if (result != ERR_OK) {
878 message.Message("Has popped dialog: " + std::to_string(result));
879 NotificationAnalyticsUtil::ReportModifyEvent(message);
880 return ERROR_INTERNAL_ERROR;
881 }
882 if (hasPopped) {
883 return ERR_ANS_NOT_ALLOWED;
884 }
885
886 if (!CreateDialogManager()) {
887 return ERROR_INTERNAL_ERROR;
888 }
889
890 result = dialogManager_->RequestEnableNotificationDailog(bundleOption, callback, callerToken);
891 if (result == ERR_OK) {
892 result = ERR_ANS_DIALOG_POP_SUCCEEDED;
893 }
894 message.Message("Request dialog: " + std::to_string(result));
895 NotificationAnalyticsUtil::ReportModifyEvent(message);
896 return result;
897 }
898
SetNotificationsEnabledForBundle(const std::string &deviceId, bool enabled)899 ErrCode AdvancedNotificationService::SetNotificationsEnabledForBundle(const std::string &deviceId, bool enabled)
900 {
901 return ERR_INVALID_OPERATION;
902 }
903
SetNotificationsEnabledForAllBundles(const std::string &deviceId, bool enabled)904 ErrCode AdvancedNotificationService::SetNotificationsEnabledForAllBundles(const std::string &deviceId, bool enabled)
905 {
906 ANS_LOGD("%{public}s", __FUNCTION__);
907
908 bool isSubsystem = AccessTokenHelper::VerifyNativeToken(IPCSkeleton::GetCallingTokenID());
909 if (!isSubsystem && !AccessTokenHelper::IsSystemApp()) {
910 ANS_LOGD("VerifyNativeToken and IsSystemApp is false.");
911 return ERR_ANS_NON_SYSTEM_APP;
912 }
913
914 if (!AccessTokenHelper::CheckPermission(OHOS_PERMISSION_NOTIFICATION_CONTROLLER)) {
915 return ERR_ANS_PERMISSION_DENIED;
916 }
917
918 int32_t userId = SUBSCRIBE_USER_INIT;
919 if (OsAccountManagerHelper::GetInstance().GetCurrentActiveUserId(userId) != ERR_OK) {
920 return ERR_ANS_GET_ACTIVE_USER_FAILED;
921 }
922
923 if (notificationSvrQueue_ == nullptr) {
924 ANS_LOGE("Serial queue is invalidity.");
925 return ERR_ANS_INVALID_PARAM;
926 }
927 ErrCode result = ERR_OK;
928 ffrt::task_handle handler = notificationSvrQueue_->submit_h(std::bind([&]() {
929 ANS_LOGD("ffrt enter!");
930 if (deviceId.empty()) {
931 // Local device
932 result = NotificationPreferences::GetInstance()->SetNotificationsEnabled(userId, enabled);
933 } else {
934 // Remote device
935 }
936 }));
937 notificationSvrQueue_->wait(handler);
938 return result;
939 }
940
SetNotificationsEnabledForSpecialBundle( const std::string &deviceId, const sptr<NotificationBundleOption> &bundleOption, bool enabled)941 ErrCode AdvancedNotificationService::SetNotificationsEnabledForSpecialBundle(
942 const std::string &deviceId, const sptr<NotificationBundleOption> &bundleOption, bool enabled)
943 {
944 HITRACE_METER_NAME(HITRACE_TAG_NOTIFICATION, __PRETTY_FUNCTION__);
945 ANS_LOGD("%{public}s", __FUNCTION__);
946
947 bool isSubsystem = AccessTokenHelper::VerifyNativeToken(IPCSkeleton::GetCallingTokenID());
948 if (!isSubsystem && !AccessTokenHelper::IsSystemApp()) {
949 ANS_LOGD("IsSystemApp is bogus.");
950 return ERR_ANS_NON_SYSTEM_APP;
951 }
952
953 int32_t callingUid = IPCSkeleton::GetCallingUid();
954 if (callingUid != ANS_UID && !AccessTokenHelper::CheckPermission(OHOS_PERMISSION_NOTIFICATION_CONTROLLER)) {
955 return ERR_ANS_PERMISSION_DENIED;
956 }
957
958 sptr<NotificationBundleOption> bundle = GenerateValidBundleOption(bundleOption);
959 if (bundle == nullptr) {
960 return ERR_ANS_INVALID_BUNDLE;
961 }
962
963 sptr<EnabledNotificationCallbackData> bundleData = new (std::nothrow)
964 EnabledNotificationCallbackData(bundle->GetBundleName(), bundle->GetUid(), enabled);
965 if (bundleData == nullptr) {
966 ANS_LOGE("Failed to create EnabledNotificationCallbackData instance");
967 return ERR_NO_MEMORY;
968 }
969
970 ErrCode result = ERR_OK;
971 if (deviceId.empty()) {
972 bool notificationEnable = false;
973 ErrCode saveRef = NotificationPreferences::GetInstance()->GetNotificationsEnabledForBundle(
974 bundle, notificationEnable);
975 // Local device
976 result = NotificationPreferences::GetInstance()->SetNotificationsEnabledForBundle(bundle, enabled);
977 bool enableSuccessed = result == ERR_OK;
978 if (result == ERR_OK) {
979 if (!enabled) {
980 result = RemoveAllNotificationsForDisable(bundle);
981 }
982 if (saveRef != ERR_OK) {
983 SetSlotFlagsTrustlistsAsBundle(bundle);
984 }
985 NotificationSubscriberManager::GetInstance()->NotifyEnabledNotificationChanged(bundleData);
986 PublishSlotChangeCommonEvent(bundle);
987 }
988 } else {
989 // Remote device
990 }
991
992 SendEnableNotificationHiSysEvent(bundleOption, enabled, result);
993 return result;
994 }
995
IsAllowedNotify(bool &allowed)996 ErrCode AdvancedNotificationService::IsAllowedNotify(bool &allowed)
997 {
998 ANS_LOGD("%{public}s", __FUNCTION__);
999
1000 bool isSubsystem = AccessTokenHelper::VerifyNativeToken(IPCSkeleton::GetCallingTokenID());
1001 if (!isSubsystem && !AccessTokenHelper::IsSystemApp()) {
1002 return ERR_ANS_NON_SYSTEM_APP;
1003 }
1004
1005 if (!AccessTokenHelper::CheckPermission(OHOS_PERMISSION_NOTIFICATION_CONTROLLER)) {
1006 ANS_LOGD("AccessTokenHelper::CheckPermission is false");
1007 return ERR_ANS_PERMISSION_DENIED;
1008 }
1009
1010 int32_t userId = SUBSCRIBE_USER_INIT;
1011 if (OsAccountManagerHelper::GetInstance().GetCurrentActiveUserId(userId) != ERR_OK) {
1012 return ERR_ANS_GET_ACTIVE_USER_FAILED;
1013 }
1014
1015 if (notificationSvrQueue_ == nullptr) {
1016 ANS_LOGE("Serial queue is invalid.");
1017 return ERR_ANS_INVALID_PARAM;
1018 }
1019 ErrCode result = ERR_OK;
1020 ffrt::task_handle handler = notificationSvrQueue_->submit_h(std::bind([&]() {
1021 ANS_LOGD("ffrt enter!");
1022 allowed = false;
1023 result = NotificationPreferences::GetInstance()->GetNotificationsEnabled(userId, allowed);
1024 }));
1025 notificationSvrQueue_->wait(handler);
1026 return result;
1027 }
1028
IsAllowedNotifySelf(bool &allowed)1029 ErrCode AdvancedNotificationService::IsAllowedNotifySelf(bool &allowed)
1030 {
1031 ANS_LOGD("%{public}s", __FUNCTION__);
1032
1033 sptr<NotificationBundleOption> bundleOption = GenerateBundleOption();
1034 if (bundleOption == nullptr) {
1035 return ERR_ANS_INVALID_BUNDLE;
1036 }
1037 return IsAllowedNotifySelf(bundleOption, allowed);
1038 }
1039
CanPopEnableNotificationDialog( const sptr<AnsDialogCallback> &callback, bool &canPop, std::string &bundleName)1040 ErrCode AdvancedNotificationService::CanPopEnableNotificationDialog(
1041 const sptr<AnsDialogCallback> &callback, bool &canPop, std::string &bundleName)
1042 {
1043 ANS_LOGD("%{public}s", __FUNCTION__);
1044 canPop = false;
1045 ErrCode result = ERR_OK;
1046 HaMetaMessage message = HaMetaMessage(EventSceneId::SCENE_2, EventBranchId::BRANCH_2);
1047 sptr<NotificationBundleOption> bundleOption = GenerateBundleOption();
1048 if (bundleOption == nullptr) {
1049 ANS_LOGE("bundleOption == nullptr");
1050 return ERR_ANS_INVALID_BUNDLE;
1051 }
1052 // To get the permission
1053 bool allowedNotify = false;
1054 message.BundleName(bundleOption->GetBundleName());
1055 result = IsAllowedNotifySelf(bundleOption, allowedNotify);
1056 if (result != ERR_OK) {
1057 message.Message("Allow notify self failed: " + std::to_string(result));
1058 NotificationAnalyticsUtil::ReportModifyEvent(message);
1059 return ERROR_INTERNAL_ERROR;
1060 }
1061 ANS_LOGI("allowedNotify = %{public}d, bundle = %{public}s", allowedNotify,
1062 bundleOption->GetBundleName().c_str());
1063 if (allowedNotify) {
1064 return ERR_OK;
1065 }
1066 // Check to see if it has been popover before
1067 bool hasPopped = false;
1068 result = GetHasPoppedDialog(bundleOption, hasPopped);
1069 if (result != ERR_OK) {
1070 message.Message("Has popped dialog: " + std::to_string(result));
1071 NotificationAnalyticsUtil::ReportModifyEvent(message);
1072 return ERROR_INTERNAL_ERROR;
1073 }
1074 if (hasPopped) {
1075 return ERR_ANS_NOT_ALLOWED;
1076 }
1077
1078 if (!CreateDialogManager()) {
1079 return ERROR_INTERNAL_ERROR;
1080 }
1081 result = dialogManager_->AddDialogInfo(bundleOption, callback);
1082 if (result != ERR_OK) {
1083 return result;
1084 }
1085
1086 canPop = true;
1087 bundleName = bundleOption->GetBundleName();
1088 ANS_LOGI("CanPopEnableNotificationDialog end");
1089 return ERR_OK;
1090 }
1091
RemoveEnableNotificationDialog()1092 ErrCode AdvancedNotificationService::RemoveEnableNotificationDialog()
1093 {
1094 ANS_LOGD("%{public}s", __FUNCTION__);
1095 ErrCode result = ERR_OK;
1096 sptr<NotificationBundleOption> bundleOption = GenerateBundleOption();
1097 if (bundleOption == nullptr) {
1098 ANS_LOGE("bundleOption == nullptr");
1099 return ERR_ANS_INVALID_BUNDLE;
1100 }
1101 return RemoveEnableNotificationDialog(bundleOption);
1102 }
1103
RemoveEnableNotificationDialog(const sptr<NotificationBundleOption> &bundleOption)1104 ErrCode AdvancedNotificationService::RemoveEnableNotificationDialog(const sptr<NotificationBundleOption> &bundleOption)
1105 {
1106 ANS_LOGI("RemoveEnableNotificationDialog %{public}s, %{public}d",
1107 bundleOption->GetBundleName().c_str(),
1108 bundleOption->GetUid());
1109 if (!CreateDialogManager()) {
1110 return ERROR_INTERNAL_ERROR;
1111 }
1112 std::unique_ptr<NotificationDialogManager::DialogInfo> dialogInfoRemoved = nullptr;
1113 dialogManager_->RemoveDialogInfoByBundleOption(bundleOption, dialogInfoRemoved);
1114 return ERR_OK;
1115 }
1116
IsAllowedNotifySelf(const sptr<NotificationBundleOption> &bundleOption, bool &allowed)1117 ErrCode AdvancedNotificationService::IsAllowedNotifySelf(const sptr<NotificationBundleOption> &bundleOption,
1118 bool &allowed)
1119 {
1120 ANS_LOGD("%{public}s", __FUNCTION__);
1121 if (bundleOption == nullptr) {
1122 return ERR_ANS_INVALID_BUNDLE;
1123 }
1124
1125 int32_t userId = SUBSCRIBE_USER_INIT;
1126 if (OsAccountManagerHelper::GetInstance().GetCurrentActiveUserId(userId) != ERR_OK) {
1127 ANS_LOGD("GetActiveUserId is false");
1128 return ERR_ANS_GET_ACTIVE_USER_FAILED;
1129 }
1130
1131 ErrCode result = ERR_OK;
1132 allowed = false;
1133 result = NotificationPreferences::GetInstance()->GetNotificationsEnabled(userId, allowed);
1134 if (result == ERR_OK && allowed) {
1135 result = NotificationPreferences::GetInstance()->GetNotificationsEnabledForBundle(bundleOption, allowed);
1136 if (result == ERR_ANS_PREFERENCES_NOTIFICATION_BUNDLE_NOT_EXIST) {
1137 result = ERR_OK;
1138 // FA model app can publish notification without user confirm
1139 allowed = CheckApiCompatibility(bundleOption);
1140 SetDefaultNotificationEnabled(bundleOption, allowed);
1141 }
1142 }
1143 return result;
1144 }
1145
IsAllowedNotifyForBundle(const sptr<NotificationBundleOption> &bundleOption, bool &allowed)1146 ErrCode AdvancedNotificationService::IsAllowedNotifyForBundle(const sptr<NotificationBundleOption>
1147 &bundleOption, bool &allowed)
1148 {
1149 ANS_LOGD("%{public}s", __FUNCTION__);
1150 if (bundleOption == nullptr) {
1151 return ERR_ANS_INVALID_BUNDLE;
1152 }
1153
1154 int32_t userId = SUBSCRIBE_USER_INIT;
1155 if (OsAccountManagerHelper::GetInstance().GetCurrentActiveUserId(userId) != ERR_OK) {
1156 ANS_LOGD("GetActiveUserId is false");
1157 return ERR_ANS_GET_ACTIVE_USER_FAILED;
1158 }
1159
1160 ErrCode result = ERR_OK;
1161 allowed = false;
1162 result = NotificationPreferences::GetInstance()->GetNotificationsEnabled(userId, allowed);
1163 if (result == ERR_OK && allowed) {
1164 result = NotificationPreferences::GetInstance()->GetNotificationsEnabledForBundle(bundleOption, allowed);
1165 if (result == ERR_ANS_PREFERENCES_NOTIFICATION_BUNDLE_NOT_EXIST) {
1166 result = ERR_OK;
1167 // FA model app can publish notification without user confirm
1168 allowed = CheckApiCompatibility(bundleOption);
1169 }
1170 }
1171 return result;
1172 }
1173
IsSpecialBundleAllowedNotify( const sptr<NotificationBundleOption> &bundleOption, bool &allowed)1174 ErrCode AdvancedNotificationService::IsSpecialBundleAllowedNotify(
1175 const sptr<NotificationBundleOption> &bundleOption, bool &allowed)
1176 {
1177 ANS_LOGD("%{public}s", __FUNCTION__);
1178
1179 bool isSubsystem = AccessTokenHelper::VerifyNativeToken(IPCSkeleton::GetCallingTokenID());
1180 if (!isSubsystem && !AccessTokenHelper::IsSystemApp()) {
1181 ANS_LOGE("Not system application");
1182 return ERR_ANS_NON_SYSTEM_APP;
1183 }
1184
1185 int32_t callingUid = IPCSkeleton::GetCallingUid();
1186 if (callingUid != ANS_UID && !AccessTokenHelper::CheckPermission(OHOS_PERMISSION_NOTIFICATION_CONTROLLER)) {
1187 return ERR_ANS_PERMISSION_DENIED;
1188 }
1189
1190 sptr<NotificationBundleOption> targetBundle = nullptr;
1191 if (isSubsystem) {
1192 if (bundleOption != nullptr) {
1193 targetBundle = GenerateValidBundleOption(bundleOption);
1194 }
1195 } else {
1196 ErrCode result = GetAppTargetBundle(bundleOption, targetBundle);
1197 if (result != ERR_OK) {
1198 return result;
1199 }
1200 }
1201
1202 if (targetBundle == nullptr) {
1203 return ERR_ANS_INVALID_BUNDLE;
1204 }
1205
1206 int32_t userId = SUBSCRIBE_USER_INIT;
1207 if (OsAccountManagerHelper::GetInstance().GetCurrentActiveUserId(userId) != ERR_OK) {
1208 return ERR_ANS_GET_ACTIVE_USER_FAILED;
1209 }
1210
1211 ErrCode result = ERR_OK;
1212 allowed = false;
1213 result = NotificationPreferences::GetInstance()->GetNotificationsEnabled(userId, allowed);
1214 if (result == ERR_OK && allowed) {
1215 result = NotificationPreferences::GetInstance()->GetNotificationsEnabledForBundle(targetBundle, allowed);
1216 if (result == ERR_ANS_PREFERENCES_NOTIFICATION_BUNDLE_NOT_EXIST) {
1217 result = ERR_OK;
1218 allowed = CheckApiCompatibility(targetBundle);
1219 SetNotificationsEnabledForSpecialBundle("", bundleOption, allowed);
1220 }
1221 }
1222 return result;
1223 }
1224
PublishContinuousTaskNotification(const sptr<NotificationRequest> &request)1225 ErrCode AdvancedNotificationService::PublishContinuousTaskNotification(const sptr<NotificationRequest> &request)
1226 {
1227 ANS_LOGD("%{public}s", __FUNCTION__);
1228
1229 bool isSubsystem = AccessTokenHelper::VerifyNativeToken(IPCSkeleton::GetCallingTokenID());
1230 if (!isSubsystem) {
1231 return ERR_ANS_NOT_SYSTEM_SERVICE;
1232 }
1233
1234 int32_t uid = IPCSkeleton::GetCallingUid();
1235 int32_t userId = SUBSCRIBE_USER_INIT;
1236 OHOS::AccountSA::OsAccountManager::GetOsAccountLocalIdFromUid(uid, userId);
1237 request->SetCreatorUserId(userId);
1238 ANS_LOGD("%{public}s, uid=%{public}d userId=%{public}d", __FUNCTION__, uid, userId);
1239
1240 if (request->GetCreatorBundleName().empty()) {
1241 request->SetCreatorBundleName(FOUNDATION_BUNDLE_NAME);
1242 }
1243
1244 if (request->GetOwnerBundleName().empty()) {
1245 request->SetOwnerBundleName(FOUNDATION_BUNDLE_NAME);
1246 }
1247
1248 sptr<NotificationBundleOption> bundleOption = nullptr;
1249 bundleOption = new (std::nothrow) NotificationBundleOption(std::string(), uid);
1250 if (bundleOption == nullptr) {
1251 ANS_LOGE("Failed to create NotificationBundleOption instance");
1252 return ERR_NO_MEMORY;
1253 }
1254
1255 ErrCode result = PrepareContinuousTaskNotificationRequest(request, uid);
1256 if (result != ERR_OK) {
1257 return result;
1258 }
1259 request->SetUnremovable(true);
1260 std::shared_ptr<NotificationRecord> record = std::make_shared<NotificationRecord>();
1261 record->request = request;
1262 record->bundleOption = bundleOption;
1263 record->notification = new (std::nothrow) Notification(request);
1264 if (record->notification == nullptr) {
1265 ANS_LOGE("Failed to create Notification instance");
1266 return ERR_NO_MEMORY;
1267 }
1268 record->notification->SetSourceType(NotificationConstant::SourceType::TYPE_CONTINUOUS);
1269
1270 if (notificationSvrQueue_ == nullptr) {
1271 ANS_LOGE("Serial queue is invalid.");
1272 return ERR_ANS_INVALID_PARAM;
1273 }
1274 ffrt::task_handle handler = notificationSvrQueue_->submit_h(std::bind([&]() {
1275 ANS_LOGD("ffrt enter!");
1276 if (!IsNotificationExists(record->notification->GetKey())) {
1277 AddToNotificationList(record);
1278 } else {
1279 if (record->request->IsAlertOneTime()) {
1280 CloseAlert(record);
1281 }
1282 UpdateInNotificationList(record);
1283 }
1284
1285 UpdateRecentNotification(record->notification, false, 0);
1286 sptr<NotificationSortingMap> sortingMap = GenerateSortingMap();
1287 NotificationSubscriberManager::GetInstance()->NotifyConsumed(record->notification, sortingMap);
1288 }));
1289 notificationSvrQueue_->wait(handler);
1290
1291 return result;
1292 }
1293
CancelContinuousTaskNotification(const std::string &label, int32_t notificationId)1294 ErrCode AdvancedNotificationService::CancelContinuousTaskNotification(const std::string &label, int32_t notificationId)
1295 {
1296 ANS_LOGD("%{public}s", __FUNCTION__);
1297
1298 bool isSubsystem = AccessTokenHelper::VerifyNativeToken(IPCSkeleton::GetCallingTokenID());
1299 if (!isSubsystem) {
1300 return ERR_ANS_NOT_SYSTEM_SERVICE;
1301 }
1302
1303 if (notificationSvrQueue_ == nullptr) {
1304 ANS_LOGE("Serial queue is invalid.");
1305 return ERR_ANS_INVALID_PARAM;
1306 }
1307 int32_t uid = IPCSkeleton::GetCallingUid();
1308 ErrCode result = ERR_OK;
1309 ffrt::task_handle handler = notificationSvrQueue_->submit_h(std::bind([&]() {
1310 ANS_LOGD("ffrt enter!");
1311 sptr<Notification> notification = nullptr;
1312 for (auto record : notificationList_) {
1313 if ((record->bundleOption->GetBundleName().empty()) && (record->bundleOption->GetUid() == uid) &&
1314 (record->notification->GetId() == notificationId) && (record->notification->GetLabel() == label)) {
1315 notification = record->notification;
1316 notificationList_.remove(record);
1317 result = ERR_OK;
1318 break;
1319 }
1320 }
1321 if (notification != nullptr) {
1322 int32_t reason = NotificationConstant::APP_CANCEL_REASON_DELETE;
1323 UpdateRecentNotification(notification, true, reason);
1324 CancelTimer(notification->GetAutoDeletedTimer());
1325 NotificationSubscriberManager::GetInstance()->NotifyCanceled(notification, nullptr, reason);
1326 }
1327 }));
1328 notificationSvrQueue_->wait(handler);
1329 return result;
1330 }
1331
RemoveSystemLiveViewNotifications( const std::string& bundleName, const int32_t uid)1332 ErrCode AdvancedNotificationService::RemoveSystemLiveViewNotifications(
1333 const std::string& bundleName, const int32_t uid)
1334 {
1335 std::vector<std::shared_ptr<NotificationRecord>> recordList;
1336 if (notificationSvrQueue_ == nullptr) {
1337 ANS_LOGE("NotificationSvrQueue is nullptr");
1338 return ERR_ANS_INVALID_PARAM;
1339 }
1340 ErrCode result = ERR_OK;
1341 ffrt::task_handle handler = notificationSvrQueue_->submit_h(std::bind([&]() {
1342 LivePublishProcess::GetInstance()->EraseLiveViewSubsciber(uid);
1343 GetTargetRecordList(uid, NotificationConstant::SlotType::LIVE_VIEW,
1344 NotificationContent::Type::LOCAL_LIVE_VIEW, recordList);
1345 GetCommonTargetRecordList(uid, NotificationConstant::SlotType::LIVE_VIEW,
1346 NotificationContent::Type::LIVE_VIEW, recordList);
1347 if (recordList.size() == 0) {
1348 ANS_LOGE("Get Target record list fail.");
1349 result = ERR_ANS_NOTIFICATION_NOT_EXISTS;
1350 return;
1351 }
1352 result = RemoveNotificationFromRecordList(recordList);
1353 }));
1354 notificationSvrQueue_->wait(handler);
1355 return result;
1356 }
1357
RemoveSystemLiveViewNotificationsOfSa(int32_t uid)1358 ErrCode AdvancedNotificationService::RemoveSystemLiveViewNotificationsOfSa(int32_t uid)
1359 {
1360 {
1361 std::lock_guard<std::mutex> lock(delayNotificationMutext_);
1362 for (auto iter = delayNotificationList_.begin(); iter != delayNotificationList_.end();) {
1363 if ((*iter).first->notification->GetNotificationRequest().GetCreatorUid() == uid &&
1364 (*iter).first->notification->GetNotificationRequest().IsInProgress()) {
1365 CancelTimer((*iter).second);
1366 iter = delayNotificationList_.erase(iter);
1367 } else {
1368 iter++;
1369 }
1370 }
1371 }
1372
1373 ErrCode result = ERR_OK;
1374 ffrt::task_handle handler = notificationSvrQueue_->submit_h(std::bind([&]() {
1375 LivePublishProcess::GetInstance()->EraseLiveViewSubsciber(uid);
1376 std::vector<std::shared_ptr<NotificationRecord>> recordList;
1377 for (auto item : notificationList_) {
1378 if (item->notification->GetNotificationRequest().GetCreatorUid() == uid &&
1379 item->notification->GetNotificationRequest().IsInProgress()) {
1380 recordList.emplace_back(item);
1381 }
1382 }
1383 if (!recordList.empty()) {
1384 result = RemoveNotificationFromRecordList(recordList);
1385 }
1386 }));
1387 notificationSvrQueue_->wait(handler);
1388 return result;
1389 }
1390
TriggerLocalLiveView(const sptr<NotificationBundleOption> &bundleOption, const int32_t notificationId, const sptr<NotificationButtonOption> &buttonOption)1391 ErrCode AdvancedNotificationService::TriggerLocalLiveView(const sptr<NotificationBundleOption> &bundleOption,
1392 const int32_t notificationId, const sptr<NotificationButtonOption> &buttonOption)
1393 {
1394 HITRACE_METER_NAME(HITRACE_TAG_NOTIFICATION, __PRETTY_FUNCTION__);
1395 ANS_LOGD("%{public}s", __FUNCTION__);
1396
1397 bool isSubsystem = AccessTokenHelper::VerifyNativeToken(IPCSkeleton::GetCallingTokenID());
1398 if (!isSubsystem && !AccessTokenHelper::IsSystemApp()) {
1399 return ERR_ANS_NON_SYSTEM_APP;
1400 }
1401
1402 if (!AccessTokenHelper::CheckPermission(OHOS_PERMISSION_NOTIFICATION_CONTROLLER)) {
1403 ANS_LOGD("AccessTokenHelper::CheckPermission is bogus.");
1404 return ERR_ANS_PERMISSION_DENIED;
1405 }
1406
1407 sptr<NotificationBundleOption> bundle = GenerateValidBundleOption(bundleOption);
1408 if (bundle == nullptr) {
1409 return ERR_ANS_INVALID_BUNDLE;
1410 }
1411
1412 ErrCode result = ERR_ANS_NOTIFICATION_NOT_EXISTS;
1413 ffrt::task_handle handler = notificationSvrQueue_->submit_h(std::bind([&]() {
1414 ANS_LOGD("ffrt enter!");
1415 sptr<Notification> notification = nullptr;
1416
1417 for (auto record : notificationList_) {
1418 if (record->request->GetAgentBundle() != nullptr) {
1419 if ((record->request->GetAgentBundle()->GetBundleName() == bundle->GetBundleName()) &&
1420 (record->request->GetAgentBundle()->GetUid() == bundle->GetUid()) &&
1421 (record->notification->GetId() == notificationId)) {
1422 notification = record->notification;
1423 result = ERR_OK;
1424 break;
1425 }
1426 } else {
1427 if ((record->bundleOption->GetBundleName() == bundle->GetBundleName()) &&
1428 (record->bundleOption->GetUid() == bundle->GetUid()) &&
1429 (record->notification->GetId() == notificationId)) {
1430 notification = record->notification;
1431 result = ERR_OK;
1432 break;
1433 }
1434 }
1435 }
1436
1437 if (notification != nullptr) {
1438 NotificationLocalLiveViewSubscriberManager::GetInstance()->NotifyTriggerResponse(notification,
1439 buttonOption);
1440 }
1441 }));
1442 notificationSvrQueue_->wait(handler);
1443 return result;
1444 }
1445
RemoveNotification(const sptr<NotificationBundleOption> &bundleOption, int32_t notificationId, const std::string &label, int32_t removeReason)1446 ErrCode AdvancedNotificationService::RemoveNotification(const sptr<NotificationBundleOption> &bundleOption,
1447 int32_t notificationId, const std::string &label, int32_t removeReason)
1448 {
1449 HITRACE_METER_NAME(HITRACE_TAG_NOTIFICATION, __PRETTY_FUNCTION__);
1450 ANS_LOGD("%{public}s", __FUNCTION__);
1451
1452 bool isSubsystem = AccessTokenHelper::VerifyNativeToken(IPCSkeleton::GetCallingTokenID());
1453 if (!isSubsystem && !AccessTokenHelper::IsSystemApp()) {
1454 std::string message = "not systemApp.";
1455 OHOS::Notification::HaMetaMessage haMetaMessage = HaMetaMessage(4, 4)
1456 .ErrorCode(ERR_ANS_NON_SYSTEM_APP).NotificationId(notificationId);
1457 ReportDeleteFailedEventPush(haMetaMessage, removeReason, message);
1458 ANS_LOGE("%{public}s", message.c_str());
1459 return ERR_ANS_NON_SYSTEM_APP;
1460 }
1461
1462 if (!AccessTokenHelper::CheckPermission(OHOS_PERMISSION_NOTIFICATION_CONTROLLER)) {
1463 std::string message = "no acl controller permission.";
1464 OHOS::Notification::HaMetaMessage haMetaMessage = HaMetaMessage(4, 5)
1465 .ErrorCode(ERR_ANS_PERMISSION_DENIED).NotificationId(notificationId);
1466 ReportDeleteFailedEventPush(haMetaMessage, removeReason, message);
1467 ANS_LOGE("%{public}s", message.c_str());
1468 return ERR_ANS_PERMISSION_DENIED;
1469 }
1470
1471 sptr<NotificationBundleOption> bundle = GenerateValidBundleOption(bundleOption);
1472 if (bundle == nullptr) {
1473 return ERR_ANS_INVALID_BUNDLE;
1474 }
1475
1476 if (notificationSvrQueue_ == nullptr) {
1477 std::string message = "NotificationSvrQueue_ is null.";
1478 ANS_LOGE("%{public}s", message.c_str());
1479 return ERR_ANS_INVALID_PARAM;
1480 }
1481 ErrCode result = ERR_ANS_NOTIFICATION_NOT_EXISTS;
1482 ffrt::task_handle handler = notificationSvrQueue_->submit_h(std::bind([&]() {
1483 ANS_LOGD("ffrt enter!");
1484 sptr<Notification> notification = nullptr;
1485 sptr<NotificationRequest> notificationRequest = nullptr;
1486
1487 #ifdef DISTRIBUTED_NOTIFICATION_SUPPORTED
1488 std::string deviceId;
1489 std::string bundleName;
1490 #endif
1491 for (auto record : notificationList_) {
1492 if ((record->bundleOption->GetBundleName() == bundle->GetBundleName()) &&
1493 (record->bundleOption->GetUid() == bundle->GetUid()) &&
1494 #ifdef DISTRIBUTED_NOTIFICATION_SUPPORTED
1495 (record->deviceId.empty()) &&
1496 #endif
1497 (record->notification->GetId() == notificationId) && (record->notification->GetLabel() == label)) {
1498 if (!record->notification->IsRemoveAllowed()) {
1499 result = ERR_ANS_NOTIFICATION_IS_UNALLOWED_REMOVEALLOWED;
1500 break;
1501 }
1502 #ifdef DISTRIBUTED_NOTIFICATION_SUPPORTED
1503 deviceId = record->deviceId;
1504 bundleName = record->bundleName;
1505 #endif
1506 notification = record->notification;
1507 notificationRequest = record->request;
1508
1509 if (removeReason != NotificationConstant::CLICK_REASON_DELETE) {
1510 ProcForDeleteLiveView(record);
1511 }
1512
1513 notificationList_.remove(record);
1514 result = ERR_OK;
1515 break;
1516 }
1517 }
1518
1519 if (notification != nullptr) {
1520 UpdateRecentNotification(notification, true, removeReason);
1521 CancelTimer(notification->GetAutoDeletedTimer());
1522 NotificationSubscriberManager::GetInstance()->NotifyCanceled(notification, nullptr, removeReason);
1523 #ifdef DISTRIBUTED_NOTIFICATION_SUPPORTED
1524 DoDistributedDelete(deviceId, bundleName, notification);
1525 #endif
1526 }
1527 if (removeReason != NotificationConstant::CLICK_REASON_DELETE) {
1528 TriggerRemoveWantAgent(notificationRequest);
1529 }
1530 }));
1531 notificationSvrQueue_->wait(handler);
1532 if (result != ERR_OK) {
1533 std::string message = "remove notificaiton error";
1534 OHOS::Notification::HaMetaMessage haMetaMessage = HaMetaMessage(4, 7)
1535 .ErrorCode(result).NotificationId(notificationId);
1536 ReportDeleteFailedEventPush(haMetaMessage, removeReason, message);
1537 ANS_LOGE("%{public}s", message.c_str());
1538 }
1539 SendRemoveHiSysEvent(notificationId, label, bundleOption, result);
1540 return result;
1541 }
1542
RemoveAllNotificationsForDisable( const sptr<NotificationBundleOption> &bundleOption)1543 ErrCode AdvancedNotificationService::RemoveAllNotificationsForDisable(
1544 const sptr<NotificationBundleOption> &bundleOption)
1545 {
1546 return RemoveAllNotificationsInner(bundleOption, NotificationConstant::DISABLE_NOTIFICATION_REASON_DELETE);
1547 }
1548
RemoveAllNotifications(const sptr<NotificationBundleOption> &bundleOption)1549 ErrCode AdvancedNotificationService::RemoveAllNotifications(const sptr<NotificationBundleOption> &bundleOption)
1550 {
1551 return RemoveAllNotificationsInner(bundleOption, NotificationConstant::APP_REMOVE_ALL_REASON_DELETE);
1552 }
1553
RemoveAllNotificationsInner(const sptr<NotificationBundleOption> &bundleOption, int32_t reason)1554 ErrCode AdvancedNotificationService::RemoveAllNotificationsInner(const sptr<NotificationBundleOption> &bundleOption,
1555 int32_t reason)
1556 {
1557 HITRACE_METER_NAME(HITRACE_TAG_NOTIFICATION, __PRETTY_FUNCTION__);
1558 ANS_LOGD("%{public}s", __FUNCTION__);
1559
1560 bool isSubsystem = AccessTokenHelper::VerifyNativeToken(IPCSkeleton::GetCallingTokenID());
1561 if (!isSubsystem && !AccessTokenHelper::IsSystemApp()) {
1562 std::string message = "not system app.";
1563 OHOS::Notification::HaMetaMessage haMetaMessage = HaMetaMessage(6, 1)
1564 .ErrorCode(ERR_ANS_NON_SYSTEM_APP);
1565 ReportDeleteFailedEventPush(haMetaMessage, reason, message);
1566 ANS_LOGE("%{public}s", message.c_str());
1567 return ERR_ANS_NON_SYSTEM_APP;
1568 }
1569
1570 int32_t callingUid = IPCSkeleton::GetCallingUid();
1571 if (callingUid != ANS_UID && !AccessTokenHelper::CheckPermission(OHOS_PERMISSION_NOTIFICATION_CONTROLLER)) {
1572 std::string message = "no acl permission.";
1573 OHOS::Notification::HaMetaMessage haMetaMessage = HaMetaMessage(6, 2)
1574 .ErrorCode(ERR_ANS_PERMISSION_DENIED);
1575 ReportDeleteFailedEventPush(haMetaMessage, reason, message);
1576 ANS_LOGE("%{public}s", message.c_str());
1577 return ERR_ANS_PERMISSION_DENIED;
1578 }
1579
1580 sptr<NotificationBundleOption> bundle = GenerateValidBundleOption(bundleOption);
1581 if (bundle == nullptr) {
1582 std::string message = "budle is nullptr.";
1583 OHOS::Notification::HaMetaMessage haMetaMessage = HaMetaMessage(6, 3)
1584 .ErrorCode(ERR_ANS_INVALID_BUNDLE);
1585 ReportDeleteFailedEventPush(haMetaMessage, reason, message);
1586 ANS_LOGE("%{public}s", message.c_str());
1587 return ERR_ANS_INVALID_BUNDLE;
1588 }
1589
1590 if (notificationSvrQueue_ == nullptr) {
1591 std::string message = "Serial queue is nullptr.";
1592 ANS_LOGE("%{public}s", message.c_str());
1593 return ERR_ANS_INVALID_PARAM;
1594 }
1595 ffrt::task_handle handler = notificationSvrQueue_->submit_h(std::bind([&]() {
1596 std::vector<std::shared_ptr<NotificationRecord>> removeList;
1597 ANS_LOGD("ffrt enter!");
1598 for (auto record : notificationList_) {
1599 bool isAllowedNotification = true;
1600 if (IsAllowedNotifyForBundle(bundleOption, isAllowedNotification) != ERR_OK) {
1601 ANSR_LOGW("The application does not request enable notification.");
1602 }
1603 if (!record->notification->IsRemoveAllowed() && isAllowedNotification) {
1604 ANS_LOGI("BatchRemove-FILTER-RemoveNotAllowed-%{public}s", record->notification->GetKey().c_str());
1605 continue;
1606 }
1607 if (record->slot != nullptr) {
1608 if (record->slot->GetForceControl() && record->slot->GetEnable()) {
1609 ANS_LOGI("BatchRemove-FILTER-ForceControl-%{public}s", record->notification->GetKey().c_str());
1610 continue;
1611 }
1612 }
1613 if ((record->bundleOption->GetBundleName() == bundle->GetBundleName()) &&
1614 (record->bundleOption->GetUid() == bundle->GetUid())
1615 #ifdef DISTRIBUTED_NOTIFICATION_SUPPORTED
1616 && record->deviceId.empty()
1617 #endif
1618 ) {
1619 auto notificationRequest = record->request;
1620 if (!BundleManagerHelper::GetInstance()->IsSystemApp(bundle->GetUid()) &&
1621 notificationRequest->IsSystemLiveView()) {
1622 auto localLiveviewContent = std::static_pointer_cast<NotificationLocalLiveViewContent>(
1623 notificationRequest->GetContent()->GetNotificationContent());
1624 if (localLiveviewContent->GetType() == 0) {
1625 continue;
1626 }
1627 }
1628 ProcForDeleteLiveView(record);
1629 removeList.push_back(record);
1630 }
1631 }
1632
1633 std::vector<sptr<Notification>> notifications;
1634 std::vector<uint64_t> timerIds;
1635 for (auto record : removeList) {
1636 notificationList_.remove(record);
1637 if (record->notification != nullptr) {
1638 ANS_LOGD("record->notification is not nullptr.");
1639 UpdateRecentNotification(record->notification, true, reason);
1640 notifications.emplace_back(record->notification);
1641 timerIds.emplace_back(record->notification->GetAutoDeletedTimer());
1642 #ifdef DISTRIBUTED_NOTIFICATION_SUPPORTED
1643 DoDistributedDelete(record->deviceId, record->bundleName, record->notification);
1644 #endif
1645 }
1646 if (notifications.size() >= MAX_CANCELED_PARCELABLE_VECTOR_NUM) {
1647 SendNotificationsOnCanceled(notifications, nullptr, reason);
1648 }
1649
1650 TriggerRemoveWantAgent(record->request);
1651 }
1652
1653 if (!notifications.empty()) {
1654 NotificationSubscriberManager::GetInstance()->BatchNotifyCanceled(notifications, nullptr, reason);
1655 }
1656 BatchCancelTimer(timerIds);
1657 }));
1658 notificationSvrQueue_->wait(handler);
1659
1660 return ERR_OK;
1661 }
1662
RemoveNotifications( const std::vector<std::string> &keys, int32_t removeReason)1663 ErrCode AdvancedNotificationService::RemoveNotifications(
1664 const std::vector<std::string> &keys, int32_t removeReason)
1665 {
1666 HITRACE_METER_NAME(HITRACE_TAG_NOTIFICATION, __PRETTY_FUNCTION__);
1667 ANS_LOGD("enter");
1668
1669 bool isSubsystem = AccessTokenHelper::VerifyNativeToken(IPCSkeleton::GetCallingTokenID());
1670 if (!isSubsystem && !AccessTokenHelper::IsSystemApp()) {
1671 return ERR_ANS_NON_SYSTEM_APP;
1672 }
1673 if (!AccessTokenHelper::CheckPermission(OHOS_PERMISSION_NOTIFICATION_CONTROLLER)) {
1674 return ERR_ANS_PERMISSION_DENIED;
1675 }
1676 if (notificationSvrQueue_ == nullptr) {
1677 ANS_LOGE("NotificationSvrQueue is nullptr.");
1678 return ERR_ANS_INVALID_PARAM;
1679 }
1680 ffrt::task_handle handler = notificationSvrQueue_->submit_h(std::bind([&]() {
1681 std::vector<sptr<Notification>> notifications;
1682 std::vector<uint64_t> timerIds;
1683 for (auto key : keys) {
1684 sptr<Notification> notification = nullptr;
1685 #ifdef DISTRIBUTED_NOTIFICATION_SUPPORTED
1686 std::string deviceId;
1687 std::string bundleName;
1688 GetDistributedInfo(key, deviceId, bundleName);
1689 #endif
1690 ErrCode result = RemoveFromNotificationList(key, notification, false, removeReason);
1691 if (result != ERR_OK) {
1692 continue;
1693 }
1694 if (notification != nullptr) {
1695 UpdateRecentNotification(notification, true, removeReason);
1696 notifications.emplace_back(notification);
1697 timerIds.emplace_back(notification->GetAutoDeletedTimer());
1698 #ifdef DISTRIBUTED_NOTIFICATION_SUPPORTED
1699 DoDistributedDelete(deviceId, bundleName, notification);
1700 #endif
1701 }
1702 if (notifications.size() >= MAX_CANCELED_PARCELABLE_VECTOR_NUM) {
1703 std::vector<sptr<Notification>> currNotificationList = notifications;
1704 NotificationSubscriberManager::GetInstance()->BatchNotifyCanceled(
1705 currNotificationList, nullptr, removeReason);
1706 notifications.clear();
1707 }
1708 }
1709
1710 if (!notifications.empty()) {
1711 NotificationSubscriberManager::GetInstance()->BatchNotifyCanceled(notifications, nullptr, removeReason);
1712 }
1713 BatchCancelTimer(timerIds);
1714 }));
1715 notificationSvrQueue_->wait(handler);
1716
1717 return ERR_OK;
1718 }
1719
RemoveNotificationBySlot(const sptr<NotificationBundleOption> &bundleOption, const sptr<NotificationSlot> &slot, const int reason)1720 ErrCode AdvancedNotificationService::RemoveNotificationBySlot(const sptr<NotificationBundleOption> &bundleOption,
1721 const sptr<NotificationSlot> &slot, const int reason)
1722 {
1723 HITRACE_METER_NAME(HITRACE_TAG_NOTIFICATION, __PRETTY_FUNCTION__);
1724 ANS_LOGD("%{public}s", __FUNCTION__);
1725
1726 bool isSubsystem = AccessTokenHelper::VerifyNativeToken(IPCSkeleton::GetCallingTokenID());
1727 if (!isSubsystem && !AccessTokenHelper::IsSystemApp()) {
1728 return ERR_ANS_NON_SYSTEM_APP;
1729 }
1730
1731 sptr<NotificationBundleOption> bundle = GenerateValidBundleOption(bundleOption);
1732 if (bundle == nullptr) {
1733 return ERR_ANS_INVALID_BUNDLE;
1734 }
1735
1736 ErrCode result = ERR_ANS_NOTIFICATION_NOT_EXISTS;
1737 sptr<Notification> notification = nullptr;
1738 sptr<NotificationRequest> notificationRequest = nullptr;
1739
1740 for (std::list<std::shared_ptr<NotificationRecord>>::iterator it = notificationList_.begin();
1741 it != notificationList_.end();) {
1742 if (((*it)->bundleOption->GetBundleName() == bundle->GetBundleName()) &&
1743 ((*it)->bundleOption->GetUid() == bundle->GetUid()) &&
1744 ((*it)->request->GetSlotType() == slot->GetType())) {
1745 if (((*it)->request->GetAgentBundle() != nullptr && (*it)->request->IsSystemLiveView())) {
1746 ANS_LOGI("Agent systemliveview no need remove.");
1747 it++;
1748 continue;
1749 }
1750 notification = (*it)->notification;
1751 notificationRequest = (*it)->request;
1752
1753 ProcForDeleteLiveView(*it);
1754 it = notificationList_.erase(it);
1755
1756 if (notification != nullptr) {
1757 UpdateRecentNotification(notification, true, NotificationConstant::DISABLE_SLOT_REASON_DELETE);
1758 CancelTimer(notification->GetAutoDeletedTimer());
1759 NotificationSubscriberManager::GetInstance()->NotifyCanceled(notification, nullptr,
1760 NotificationConstant::DISABLE_SLOT_REASON_DELETE);
1761 }
1762
1763 TriggerRemoveWantAgent(notificationRequest);
1764 result = ERR_OK;
1765 } else {
1766 it++;
1767 }
1768 }
1769 return result;
1770 }
1771
IsNeedSilentInDoNotDisturbMode( const std::string &phoneNumber, int32_t callerType)1772 ErrCode AdvancedNotificationService::IsNeedSilentInDoNotDisturbMode(
1773 const std::string &phoneNumber, int32_t callerType)
1774 {
1775 ANS_LOGD("%{public}s", __FUNCTION__);
1776
1777 int32_t callingUid = IPCSkeleton::GetCallingUid();
1778 if (callingUid != ANS_UID && !AccessTokenHelper::CheckPermission(OHOS_PERMISSION_NOTIFICATION_CONTROLLER)) {
1779 ANS_LOGD("IsNeedSilentInDoNotDisturbMode CheckPermission failed.");
1780 return ERR_ANS_PERMISSION_DENIED;
1781 }
1782
1783 int32_t userId = SUBSCRIBE_USER_INIT;
1784 if (OsAccountManagerHelper::GetInstance().GetCurrentActiveUserId(userId) != ERR_OK) {
1785 ANS_LOGD("GetActiveUserId is false");
1786 return ERR_ANS_GET_ACTIVE_USER_FAILED;
1787 }
1788 return CheckNeedSilent(phoneNumber, callerType, userId);
1789 }
1790
CheckNeedSilent( const std::string &phoneNumber, int32_t callerType, int32_t userId)1791 ErrCode AdvancedNotificationService::CheckNeedSilent(
1792 const std::string &phoneNumber, int32_t callerType, int32_t userId)
1793 {
1794 auto datashareHelper = DelayedSingleton<AdvancedDatashareHelper>::GetInstance();
1795 if (datashareHelper == nullptr) {
1796 ANS_LOGE("The data share helper is nullptr.");
1797 return -1;
1798 }
1799
1800 int isNeedSilent = 0;
1801 std::string policy;
1802 Uri policyUri(datashareHelper->GetFocusModeCallPolicyUri(userId));
1803 bool ret = datashareHelper->Query(policyUri, KEY_FOCUS_MODE_CALL_MESSAGE_POLICY, policy);
1804 if (!ret) {
1805 ANS_LOGE("Query focus mode call message policy fail.");
1806 return -1;
1807 }
1808 std::string repeat_call;
1809 Uri repeatUri(datashareHelper->GetFocusModeRepeatCallUri(userId));
1810 bool repeat_ret = datashareHelper->Query(repeatUri, KEY_FOCUS_MODE_REPEAT_CALLERS_ENABLE, repeat_call);
1811 if (!repeat_ret) {
1812 ANS_LOGE("Query focus mode repeat callers enable fail.");
1813 }
1814 ANS_LOGI("IsNeedSilent: policy: %{public}s, repeat: %{public}s, callerType: %{public}d",
1815 policy.c_str(), repeat_call.c_str(), callerType);
1816 if (repeat_call == FOCUS_MODE_REPEAT_CALLERS_ENABLE &&
1817 callerType == 0 && atoi(policy.c_str()) != ContactPolicy::ALLOW_EVERYONE) {
1818 if (datashareHelper->isRepeatCall(phoneNumber)) {
1819 return 1;
1820 }
1821 }
1822 switch (atoi(policy.c_str())) {
1823 case ContactPolicy::FORBID_EVERYONE:
1824 break;
1825 case ContactPolicy::ALLOW_EVERYONE:
1826 isNeedSilent = 1;
1827 break;
1828 case ContactPolicy::ALLOW_EXISTING_CONTACTS:
1829 case ContactPolicy::ALLOW_FAVORITE_CONTACTS:
1830 case ContactPolicy::ALLOW_SPECIFIED_CONTACTS:
1831 Uri uri(CONTACT_DATA);
1832 isNeedSilent = datashareHelper->QueryContact(uri, phoneNumber, policy);
1833 break;
1834 }
1835 ANS_LOGI("IsNeedSilentInDoNotDisturbMode: %{public}d", isNeedSilent);
1836 return isNeedSilent;
1837 }
1838
CancelGroup(const std::string &groupName, int32_t instanceKey)1839 ErrCode AdvancedNotificationService::CancelGroup(const std::string &groupName, int32_t instanceKey)
1840 {
1841 ANS_LOGD("%{public}s", __FUNCTION__);
1842
1843 int32_t reason = NotificationConstant::APP_CANCEL_GROPU_REASON_DELETE;
1844 if (groupName.empty()) {
1845 std::string message = "groupName empty.";
1846 OHOS::Notification::HaMetaMessage haMetaMessage = HaMetaMessage(3, 1)
1847 .ErrorCode(ERR_ANS_INVALID_PARAM);
1848 ReportDeleteFailedEventPush(haMetaMessage, reason, message);
1849 ANS_LOGE("%{public}s", message.c_str());
1850 return ERR_ANS_INVALID_PARAM;
1851 }
1852
1853 sptr<NotificationBundleOption> bundleOption = GenerateBundleOption();
1854 if (bundleOption == nullptr) {
1855 std::string message = "bundle is nullptr.";
1856 OHOS::Notification::HaMetaMessage haMetaMessage = HaMetaMessage(3, 2)
1857 .ErrorCode(ERR_ANS_INVALID_BUNDLE);
1858 ReportDeleteFailedEventPush(haMetaMessage, reason, message);
1859 ANS_LOGE("%{public}s", message.c_str());
1860 return ERR_ANS_INVALID_BUNDLE;
1861 }
1862 bundleOption->SetInstanceKey(instanceKey);
1863
1864 if (notificationSvrQueue_ == nullptr) {
1865 std::string message = "Serial queue is invalid.";
1866 ANS_LOGE("%{public}s", message.c_str());
1867 return ERR_ANS_INVALID_PARAM;
1868 }
1869
1870 ExcuteCancelGroupCancel(bundleOption, groupName, reason);
1871 return ERR_OK;
1872 }
1873
ExcuteCancelGroupCancel( const sptr<NotificationBundleOption>& bundleOption, const std::string &groupName, const int32_t reason)1874 void AdvancedNotificationService::ExcuteCancelGroupCancel(
1875 const sptr<NotificationBundleOption>& bundleOption,
1876 const std::string &groupName, const int32_t reason)
1877 {
1878 ffrt::task_handle handler = notificationSvrQueue_->submit_h(std::bind([&]() {
1879 ANS_LOGD("ffrt enter!");
1880 std::vector<std::shared_ptr<NotificationRecord>> removeList;
1881 for (auto record : notificationList_) {
1882 if ((record->bundleOption->GetBundleName() == bundleOption->GetBundleName()) &&
1883 (record->bundleOption->GetUid() == bundleOption->GetUid()) &&
1884 #ifdef DISTRIBUTED_NOTIFICATION_SUPPORTED
1885 record->deviceId.empty() &&
1886 #endif
1887 (record->request->GetGroupName() == groupName)) {
1888 removeList.push_back(record);
1889 }
1890 }
1891
1892 std::vector<sptr<Notification>> notifications;
1893 std::vector<uint64_t> timerIds;
1894 for (auto record : removeList) {
1895 notificationList_.remove(record);
1896 if (record->notification != nullptr) {
1897 UpdateRecentNotification(record->notification, true, reason);
1898 notifications.emplace_back(record->notification);
1899 timerIds.emplace_back(record->notification->GetAutoDeletedTimer());
1900 #ifdef DISTRIBUTED_NOTIFICATION_SUPPORTED
1901 DoDistributedDelete(record->deviceId, record->bundleName, record->notification);
1902 #endif
1903 }
1904 if (notifications.size() >= MAX_CANCELED_PARCELABLE_VECTOR_NUM) {
1905 std::vector<sptr<Notification>> currNotificationList = notifications;
1906 NotificationSubscriberManager::GetInstance()->BatchNotifyCanceled(
1907 currNotificationList, nullptr, reason);
1908 notifications.clear();
1909 }
1910 }
1911
1912 if (!notifications.empty()) {
1913 NotificationSubscriberManager::GetInstance()->BatchNotifyCanceled(
1914 notifications, nullptr, reason);
1915 }
1916 BatchCancelTimer(timerIds);
1917 }));
1918 notificationSvrQueue_->wait(handler);
1919 }
1920
RemoveGroupByBundle( const sptr<NotificationBundleOption> &bundleOption, const std::string &groupName)1921 ErrCode AdvancedNotificationService::RemoveGroupByBundle(
1922 const sptr<NotificationBundleOption> &bundleOption, const std::string &groupName)
1923 {
1924 ANS_LOGD("%{public}s", __FUNCTION__);
1925 const int32_t reason = NotificationConstant::APP_REMOVE_GROUP_REASON_DELETE;
1926 bool isSubsystem = AccessTokenHelper::VerifyNativeToken(IPCSkeleton::GetCallingTokenID());
1927 if (!isSubsystem && !AccessTokenHelper::IsSystemApp()) {
1928 std::string message = "not systemApp.";
1929 OHOS::Notification::HaMetaMessage haMetaMessage = HaMetaMessage(5, 1)
1930 .ErrorCode(ERR_ANS_NON_SYSTEM_APP);
1931 ReportDeleteFailedEventPush(haMetaMessage, reason, message);
1932 ANS_LOGE("%{public}s", message.c_str());
1933 return ERR_ANS_NON_SYSTEM_APP;
1934 }
1935
1936 if (!AccessTokenHelper::CheckPermission(OHOS_PERMISSION_NOTIFICATION_CONTROLLER)) {
1937 std::string message = "no acl permission";
1938 OHOS::Notification::HaMetaMessage haMetaMessage = HaMetaMessage(5, 2)
1939 .ErrorCode(ERR_ANS_PERMISSION_DENIED);
1940 ReportDeleteFailedEventPush(haMetaMessage, reason, message);
1941 ANS_LOGE("%{public}s", message.c_str());
1942 return ERR_ANS_PERMISSION_DENIED;
1943 }
1944
1945 if (bundleOption == nullptr || groupName.empty()) {
1946 std::string message = "groupName empty";
1947 OHOS::Notification::HaMetaMessage haMetaMessage = HaMetaMessage(5, 3)
1948 .ErrorCode(ERR_ANS_INVALID_PARAM);
1949 ReportDeleteFailedEventPush(haMetaMessage, reason, message);
1950 ANS_LOGE("%{public}s", message.c_str());
1951 return ERR_ANS_INVALID_PARAM;
1952 }
1953
1954 sptr<NotificationBundleOption> bundle = GenerateValidBundleOption(bundleOption);
1955 if (bundle == nullptr) {
1956 std::string message = "bundle is nullptr";
1957 OHOS::Notification::HaMetaMessage haMetaMessage = HaMetaMessage(5, 4)
1958 .ErrorCode(ERR_ANS_INVALID_PARAM);
1959 ReportDeleteFailedEventPush(haMetaMessage, reason, message);
1960 ANS_LOGE("%{public}s", message.c_str());
1961 return ERR_ANS_INVALID_BUNDLE;
1962 }
1963
1964 if (notificationSvrQueue_ == nullptr) {
1965 std::string message = "Serial queue is invalid.";
1966 ANS_LOGE("%{public}s", message.c_str());
1967 return ERR_ANS_INVALID_PARAM;
1968 }
1969 ffrt::task_handle handler = notificationSvrQueue_->submit_h(std::bind([&]() {
1970 ANS_LOGD("ffrt enter!");
1971 std::vector<std::shared_ptr<NotificationRecord>> removeList;
1972 int32_t reason = NotificationConstant::CANCEL_REASON_DELETE;
1973 for (auto record : notificationList_) {
1974 if (!record->notification->IsRemoveAllowed()) {
1975 continue;
1976 }
1977 if ((record->bundleOption->GetBundleName() == bundle->GetBundleName()) &&
1978 (record->bundleOption->GetUid() == bundle->GetUid()) && !record->request->IsUnremovable() &&
1979 #ifdef DISTRIBUTED_NOTIFICATION_SUPPORTED
1980 record->deviceId.empty() &&
1981 #endif
1982 (record->request->GetGroupName() == groupName)) {
1983 ANS_LOGD("RemoveList push enter.");
1984 removeList.push_back(record);
1985 }
1986 }
1987
1988 std::vector<sptr<Notification>> notifications;
1989 std::vector<uint64_t> timerIds;
1990 for (auto record : removeList) {
1991 notificationList_.remove(record);
1992 ProcForDeleteLiveView(record);
1993
1994 if (record->notification != nullptr) {
1995 UpdateRecentNotification(record->notification, true, reason);
1996 notifications.emplace_back(record->notification);
1997 timerIds.emplace_back(record->notification->GetAutoDeletedTimer());
1998 #ifdef DISTRIBUTED_NOTIFICATION_SUPPORTED
1999 DoDistributedDelete(record->deviceId, record->bundleName, record->notification);
2000 #endif
2001 }
2002 if (notifications.size() >= MAX_CANCELED_PARCELABLE_VECTOR_NUM) {
2003 SendNotificationsOnCanceled(notifications, nullptr, reason);
2004 }
2005 }
2006
2007 if (!notifications.empty()) {
2008 NotificationSubscriberManager::GetInstance()->BatchNotifyCanceled(notifications, nullptr, reason);
2009 }
2010 BatchCancelTimer(timerIds);
2011 }));
2012 notificationSvrQueue_->wait(handler);
2013
2014 return ERR_OK;
2015 }
2016
RemoveNotificationFromRecordList( const std::vector<std::shared_ptr<NotificationRecord>>& recordList)2017 ErrCode AdvancedNotificationService::RemoveNotificationFromRecordList(
2018 const std::vector<std::shared_ptr<NotificationRecord>>& recordList)
2019 {
2020 ErrCode result = ERR_OK;
2021 std::vector<sptr<Notification>> notifications;
2022 std::vector<uint64_t> timerIds;
2023 for (auto& record : recordList) {
2024 std::string key = record->notification->GetKey();
2025 sptr<Notification> notification = nullptr;
2026 #ifdef DISTRIBUTED_NOTIFICATION_SUPPORTED
2027 std::string deviceId;
2028 std::string bundleName;
2029 GetDistributedInfo(key, deviceId, bundleName);
2030 #endif
2031 result = RemoveFromNotificationList(key, notification, true,
2032 NotificationConstant::USER_STOPPED_REASON_DELETE);
2033 if (result != ERR_OK) {
2034 continue;
2035 }
2036 if (notification != nullptr) {
2037 int32_t reason = NotificationConstant::USER_STOPPED_REASON_DELETE;
2038 UpdateRecentNotification(notification, true, reason);
2039 notifications.emplace_back(notification);
2040 timerIds.emplace_back(notification->GetAutoDeletedTimer());
2041 #ifdef DISTRIBUTED_NOTIFICATION_SUPPORTED
2042 DoDistributedDelete(deviceId, bundleName, notification);
2043 #endif
2044 }
2045 if (notifications.size() >= MAX_CANCELED_PARCELABLE_VECTOR_NUM) {
2046 std::vector<sptr<Notification>> currNotificationList = notifications;
2047 NotificationSubscriberManager::GetInstance()->BatchNotifyCanceled(
2048 currNotificationList, nullptr, NotificationConstant::USER_STOPPED_REASON_DELETE);
2049 notifications.clear();
2050 }
2051 }
2052 if (!notifications.empty()) {
2053 NotificationSubscriberManager::GetInstance()->BatchNotifyCanceled(
2054 notifications, nullptr, NotificationConstant::USER_STOPPED_REASON_DELETE);
2055 }
2056 BatchCancelTimer(timerIds);
2057 return result;
2058 }
2059
IsSpecialUserAllowedNotify(const int32_t &userId, bool &allowed)2060 ErrCode AdvancedNotificationService::IsSpecialUserAllowedNotify(const int32_t &userId, bool &allowed)
2061 {
2062 ANS_LOGD("%{public}s", __FUNCTION__);
2063
2064 bool isSubsystem = AccessTokenHelper::VerifyNativeToken(IPCSkeleton::GetCallingTokenID());
2065 if (!isSubsystem && !AccessTokenHelper::IsSystemApp()) {
2066 return ERR_ANS_NON_SYSTEM_APP;
2067 }
2068
2069 if (!AccessTokenHelper::CheckPermission(OHOS_PERMISSION_NOTIFICATION_CONTROLLER)) {
2070 ANS_LOGD("Failed to checkPermission");
2071 return ERR_ANS_PERMISSION_DENIED;
2072 }
2073
2074 if (notificationSvrQueue_ == nullptr) {
2075 ANS_LOGE("NotificationSvrQueue_ is nullptr.");
2076 return ERR_ANS_INVALID_PARAM;
2077 }
2078 ErrCode result = ERR_OK;
2079 ffrt::task_handle handler = notificationSvrQueue_->submit_h(std::bind([&]() {
2080 ANS_LOGD("ffrt enter!");
2081 allowed = false;
2082 result = NotificationPreferences::GetInstance()->GetNotificationsEnabled(userId, allowed);
2083 }));
2084 notificationSvrQueue_->wait(handler);
2085 return result;
2086 }
2087
SetNotificationsEnabledByUser(const int32_t &userId, bool enabled)2088 ErrCode AdvancedNotificationService::SetNotificationsEnabledByUser(const int32_t &userId, bool enabled)
2089 {
2090 ANS_LOGD("%{public}s", __FUNCTION__);
2091
2092 bool isSubsystem = AccessTokenHelper::VerifyNativeToken(IPCSkeleton::GetCallingTokenID());
2093 if (!isSubsystem && !AccessTokenHelper::IsSystemApp()) {
2094 return ERR_ANS_NON_SYSTEM_APP;
2095 }
2096
2097 if (!AccessTokenHelper::CheckPermission(OHOS_PERMISSION_NOTIFICATION_CONTROLLER)) {
2098 return ERR_ANS_PERMISSION_DENIED;
2099 }
2100
2101 if (notificationSvrQueue_ == nullptr) {
2102 ANS_LOGE("Serial queue is ineffectiveness.");
2103 return ERR_ANS_INVALID_PARAM;
2104 }
2105 ErrCode result = ERR_OK;
2106 ffrt::task_handle handler = notificationSvrQueue_->submit_h(std::bind([&]() {
2107 ANS_LOGD("ffrt enter!");
2108 result = NotificationPreferences::GetInstance()->SetNotificationsEnabled(userId, enabled);
2109 }));
2110 notificationSvrQueue_->wait(handler);
2111 return result;
2112 }
2113
UpdateUnifiedGroupInfo(const std::string &key, std::shared_ptr<NotificationUnifiedGroupInfo> &groupInfo)2114 void AdvancedNotificationService::UpdateUnifiedGroupInfo(const std::string &key,
2115 std::shared_ptr<NotificationUnifiedGroupInfo> &groupInfo)
2116 {
2117 if (notificationSvrQueue_ == nullptr) {
2118 ANS_LOGE("Serial queue is invalid.");
2119 return;
2120 }
2121
2122 ffrt::task_handle handler = notificationSvrQueue_->submit_h([=]() {
2123 for (const auto& item : notificationList_) {
2124 if (item->notification->GetKey() == key) {
2125 ANS_LOGD("update group info matched key %s", key.c_str());
2126 item->notification->GetNotificationRequestPoint()->SetUnifiedGroupInfo(groupInfo);
2127
2128 CloseAlert(item);
2129
2130 UpdateRecentNotification(item->notification, false, 0);
2131 sptr<NotificationSortingMap> sortingMap = GenerateSortingMap();
2132 NotificationSubscriberManager::GetInstance()->NotifyConsumed(item->notification, sortingMap);
2133 break;
2134 }
2135 }
2136 });
2137 }
2138
PublishNotificationBySa(const sptr<NotificationRequest> &request)2139 ErrCode AdvancedNotificationService::PublishNotificationBySa(const sptr<NotificationRequest> &request)
2140 {
2141 ANS_LOGD("%{public}s", __FUNCTION__);
2142
2143 auto tokenCaller = IPCSkeleton::GetCallingTokenID();
2144 bool isSystemApp = AccessTokenHelper::IsSystemApp();
2145 bool isSubsystem = AccessTokenHelper::VerifyNativeToken(tokenCaller);
2146 bool isThirdparty;
2147 if (isSystemApp || isSubsystem) {
2148 isThirdparty = false;
2149 } else {
2150 isThirdparty = true;
2151 }
2152 bool isAgentController = AccessTokenHelper::VerifyCallerPermission(tokenCaller,
2153 OHOS_PERMISSION_NOTIFICATION_AGENT_CONTROLLER);
2154 HaMetaMessage message = HaMetaMessage(EventSceneId::SCENE_4, EventBranchId::BRANCH_1);
2155 int32_t uid = request->GetCreatorUid();
2156 if (request->GetOwnerUid() != DEFAULT_UID) {
2157 std::shared_ptr<NotificationBundleOption> agentBundle =
2158 std::make_shared<NotificationBundleOption>("", uid);
2159 request->SetAgentBundle(agentBundle);
2160 }
2161
2162 if (request->IsAgentNotification()) {
2163 uid = request->GetOwnerUid();
2164 }
2165 if (uid <= 0) {
2166 message.ErrorCode(ERR_ANS_INVALID_UID).Message("createUid failed" + std::to_string(uid), true);
2167 NotificationAnalyticsUtil::ReportPublishFailedEvent(request, message);
2168 return ERR_ANS_INVALID_UID;
2169 }
2170 std::string bundle = "";
2171 ErrCode result = PrePublishNotificationBySa(request, uid, bundle);
2172 if (request->GetCreatorUid() == RSS_PID && request->IsSystemLiveView() &&
2173 (std::static_pointer_cast<OHOS::Notification::NotificationLocalLiveViewContent>(
2174 request->GetContent()->GetNotificationContent())->GetType() != TYPE_CODE_DOWNLOAD)) {
2175 request->SetSlotType(NotificationConstant::SlotType::OTHER);
2176 request->GetContent()->ResetToBasicContent();
2177 request->SetUnremovable(true);
2178 request->SetTapDismissed(false);
2179 }
2180 if (result != ERR_OK) {
2181 return result;
2182 }
2183
2184 // SA not support sound
2185 if (!request->GetSound().empty()) {
2186 request->SetSound("");
2187 }
2188 std::shared_ptr<NotificationRecord> record = std::make_shared<NotificationRecord>();
2189 record->request = request;
2190 record->isThirdparty = isThirdparty;
2191 if (request->IsAgentNotification()) {
2192 record->bundleOption = new (std::nothrow) NotificationBundleOption("", request->GetCreatorUid());
2193 } else {
2194 record->bundleOption = new (std::nothrow) NotificationBundleOption(bundle, uid);
2195 }
2196 record->bundleOption->SetInstanceKey(request->GetCreatorInstanceKey());
2197 sptr<NotificationBundleOption> bundleOption = new (std::nothrow) NotificationBundleOption(bundle, uid);
2198 if (record->bundleOption == nullptr || bundleOption == nullptr) {
2199 ANS_LOGE("Failed to create bundleOption");
2200 return ERR_ANS_NO_MEMORY;
2201 }
2202 record->notification = new (std::nothrow) Notification(request);
2203 if (record->notification == nullptr) {
2204 ANS_LOGE("Failed to create notification");
2205 return ERR_ANS_NO_MEMORY;
2206 }
2207
2208 if (notificationSvrQueue_ == nullptr) {
2209 ANS_LOGE("Serial queue is invalid.");
2210 return ERR_ANS_INVALID_PARAM;
2211 }
2212
2213 SetRequestBySlotType(record->request, bundleOption);
2214 #ifdef ENABLE_ANS_EXT_WRAPPER
2215 EXTENTION_WRAPPER->GetUnifiedGroupInfo(request);
2216 #endif
2217
2218 auto ipcUid = IPCSkeleton::GetCallingUid();
2219 ffrt::task_handle handler = notificationSvrQueue_->submit_h([&]() {
2220 if (!bundleOption->GetBundleName().empty()) {
2221 ErrCode ret = AssignValidNotificationSlot(record, bundleOption);
2222 if (ret != ERR_OK) {
2223 ANS_LOGE("Can not assign valid slot!");
2224 }
2225 }
2226
2227 ChangeNotificationByControlFlags(record, isAgentController);
2228 if (IsSaCreateSystemLiveViewAsBundle(record, ipcUid) &&
2229 (std::static_pointer_cast<OHOS::Notification::NotificationLocalLiveViewContent>(
2230 record->request->GetContent()->GetNotificationContent())->GetType() == TYPE_CODE_DOWNLOAD)) {
2231 result = SaPublishSystemLiveViewAsBundle(record);
2232 if (result == ERR_OK) {
2233 SendLiveViewUploadHiSysEvent(record, UploadStatus::CREATE);
2234 }
2235 return;
2236 }
2237
2238 if (AssignToNotificationList(record) != ERR_OK) {
2239 ANS_LOGE("Failed to assign notification list");
2240 return;
2241 }
2242
2243 UpdateRecentNotification(record->notification, false, 0);
2244 sptr<NotificationSortingMap> sortingMap = GenerateSortingMap();
2245 NotificationSubscriberManager::GetInstance()->NotifyConsumed(record->notification, sortingMap);
2246 });
2247 notificationSvrQueue_->wait(handler);
2248 if (result != ERR_OK) {
2249 return result;
2250 }
2251
2252 if ((record->request->GetAutoDeletedTime() > GetCurrentTime()) && !record->request->IsCommonLiveView()) {
2253 StartAutoDeletedTimer(record);
2254 }
2255 return ERR_OK;
2256 }
2257
SetBadgeNumber(int32_t badgeNumber, int32_t instanceKey)2258 ErrCode AdvancedNotificationService::SetBadgeNumber(int32_t badgeNumber, int32_t instanceKey)
2259 {
2260 ANS_LOGD("%{public}s", __FUNCTION__);
2261 if (notificationSvrQueue_ == nullptr) {
2262 ANS_LOGE("Serial queue is invalid.");
2263 return ERR_ANS_INVALID_PARAM;
2264 }
2265 int32_t callingUid = IPCSkeleton::GetCallingUid();
2266 std::string bundleName = GetClientBundleName();
2267 sptr<BadgeNumberCallbackData> badgeData = new (std::nothrow) BadgeNumberCallbackData(
2268 bundleName, callingUid, badgeNumber, instanceKey);
2269 if (badgeData == nullptr) {
2270 ANS_LOGE("Failed to create BadgeNumberCallbackData.");
2271 return ERR_ANS_NO_MEMORY;
2272 }
2273
2274 ffrt::task_handle handler = notificationSvrQueue_->submit_h([&]() {
2275 ANS_LOGD("ffrt enter!");
2276 NotificationSubscriberManager::GetInstance()->SetBadgeNumber(badgeData);
2277 });
2278 notificationSvrQueue_->wait(handler);
2279 return ERR_OK;
2280 }
2281
SetBadgeNumberByBundle( const sptr<NotificationBundleOption> &bundleOption, int32_t badgeNumber)2282 ErrCode AdvancedNotificationService::SetBadgeNumberByBundle(
2283 const sptr<NotificationBundleOption> &bundleOption, int32_t badgeNumber)
2284 {
2285 HaMetaMessage message = HaMetaMessage(EventSceneId::SCENE_7, EventBranchId::BRANCH_1);
2286 if (notificationSvrQueue_ == nullptr) {
2287 return ERR_ANS_INVALID_PARAM;
2288 }
2289
2290 bool isSubsystem = AccessTokenHelper::VerifyNativeToken(IPCSkeleton::GetCallingTokenID());
2291 if (!isSubsystem && !AccessTokenHelper::IsSystemApp()) {
2292 message.Message("Client is not a system app or subsystem.", true);
2293 NotificationAnalyticsUtil::ReportModifyEvent(message);
2294 return ERR_ANS_NON_SYSTEM_APP;
2295 }
2296
2297 sptr<NotificationBundleOption> bundle = bundleOption;
2298 ErrCode result = CheckBundleOptionValid(bundle);
2299 if (result != ERR_OK) {
2300 message.Message("Input bundle option is not correct: " + std::to_string(result), true);
2301 NotificationAnalyticsUtil::ReportModifyEvent(message);
2302 return result;
2303 }
2304
2305 if (!AccessTokenHelper::CheckPermission(OHOS_PERMISSION_NOTIFICATION_AGENT_CONTROLLER)) {
2306 std::string bundleName = GetClientBundleName();
2307 if (bundleName.empty()) {
2308 ANS_LOGE("Failed to get client bundle name.");
2309 return result;
2310 }
2311 bool isAgent = false;
2312 isAgent = IsAgentRelationship(bundleName, bundle->GetBundleName());
2313 if (!isAgent) {
2314 message.Message("the caller has no agent relationship with the specified bundle.", true);
2315 NotificationAnalyticsUtil::ReportModifyEvent(message);
2316 return ERR_ANS_NO_AGENT_SETTING;
2317 }
2318 }
2319
2320 ffrt::task_handle handler = notificationSvrQueue_->submit_h([&]() {
2321 ANS_LOGD("ffrt enter!");
2322 sptr<BadgeNumberCallbackData> badgeData = new (std::nothrow) BadgeNumberCallbackData(
2323 bundle->GetBundleName(), bundle->GetUid(), badgeNumber);
2324 if (badgeData == nullptr) {
2325 ANS_LOGE("Failed to create badge number callback data.");
2326 result = ERR_ANS_NO_MEMORY;
2327 }
2328 NotificationSubscriberManager::GetInstance()->SetBadgeNumber(badgeData);
2329 });
2330 notificationSvrQueue_->wait(handler);
2331 return result;
2332 }
2333
SubscribeLocalLiveView( const sptr<AnsSubscriberLocalLiveViewInterface> &subscriber, const sptr<NotificationSubscribeInfo> &info, const bool isNative)2334 ErrCode AdvancedNotificationService::SubscribeLocalLiveView(
2335 const sptr<AnsSubscriberLocalLiveViewInterface> &subscriber,
2336 const sptr<NotificationSubscribeInfo> &info, const bool isNative)
2337 {
2338 HITRACE_METER_NAME(HITRACE_TAG_NOTIFICATION, __PRETTY_FUNCTION__);
2339 ANS_LOGD("%{public}s, isNative: %{public}d", __FUNCTION__, isNative);
2340
2341 ErrCode errCode = ERR_OK;
2342 do {
2343 if (!isNative) {
2344 bool isSubsystem = AccessTokenHelper::VerifyNativeToken(IPCSkeleton::GetCallingTokenID());
2345 if (!isSubsystem && !AccessTokenHelper::IsSystemApp()) {
2346 ANS_LOGE("Client is not a system app or subsystem.");
2347 errCode = ERR_ANS_NON_SYSTEM_APP;
2348 break;
2349 }
2350 }
2351
2352 if (subscriber == nullptr) {
2353 errCode = ERR_ANS_INVALID_PARAM;
2354 break;
2355 }
2356
2357 errCode = NotificationLocalLiveViewSubscriberManager::GetInstance()->AddLocalLiveViewSubscriber(
2358 subscriber, info);
2359 if (errCode != ERR_OK) {
2360 break;
2361 }
2362 } while (0);
2363 if (errCode == ERR_OK) {
2364 int32_t callingUid = IPCSkeleton::GetCallingUid();
2365 ffrt::task_handle handler = notificationSvrQueue_->submit_h(std::bind([&]() {
2366 LivePublishProcess::GetInstance()->AddLiveViewSubscriber(callingUid);
2367 }));
2368 notificationSvrQueue_->wait(handler);
2369 }
2370 SendSubscribeHiSysEvent(IPCSkeleton::GetCallingPid(), IPCSkeleton::GetCallingUid(), info, errCode);
2371 return errCode;
2372 }
2373
SetDistributedEnabledByBundle(const sptr<NotificationBundleOption> &bundleOption, const std::string &deviceType, const bool enabled)2374 ErrCode AdvancedNotificationService::SetDistributedEnabledByBundle(const sptr<NotificationBundleOption> &bundleOption,
2375 const std::string &deviceType, const bool enabled)
2376 {
2377 ANS_LOGD("%{public}s", __FUNCTION__);
2378
2379 bool isSubsystem = AccessTokenHelper::VerifyNativeToken(IPCSkeleton::GetCallingTokenID());
2380 if (!isSubsystem && !AccessTokenHelper::IsSystemApp()) {
2381 ANS_LOGD("IsSystemApp is bogus.");
2382 return ERR_ANS_NON_SYSTEM_APP;
2383 }
2384
2385 if (!AccessTokenHelper::CheckPermission(OHOS_PERMISSION_NOTIFICATION_CONTROLLER)) {
2386 return ERR_ANS_PERMISSION_DENIED;
2387 }
2388
2389 sptr<NotificationBundleOption> bundle = GenerateValidBundleOption(bundleOption);
2390 if (bundle == nullptr) {
2391 ANS_LOGE("bundle is nullptr");
2392 return ERR_ANS_INVALID_BUNDLE;
2393 }
2394
2395 return NotificationPreferences::GetInstance()->SetDistributedEnabledByBundle(bundle, deviceType, enabled);
2396 }
2397
IsDistributedEnabledByBundle(const sptr<NotificationBundleOption> &bundleOption, const std::string &deviceType, bool &enabled)2398 ErrCode AdvancedNotificationService::IsDistributedEnabledByBundle(const sptr<NotificationBundleOption> &bundleOption,
2399 const std::string &deviceType, bool &enabled)
2400 {
2401 ANS_LOGD("%{public}s", __FUNCTION__);
2402
2403 bool isSubsystem = AccessTokenHelper::VerifyNativeToken(IPCSkeleton::GetCallingTokenID());
2404 if (!isSubsystem && !AccessTokenHelper::IsSystemApp()) {
2405 ANS_LOGD("IsSystemApp is bogus.");
2406 return ERR_ANS_NON_SYSTEM_APP;
2407 }
2408
2409 if (!AccessTokenHelper::CheckPermission(OHOS_PERMISSION_NOTIFICATION_CONTROLLER)) {
2410 ANS_LOGE("no permission");
2411 return ERR_ANS_PERMISSION_DENIED;
2412 }
2413
2414 sptr<NotificationBundleOption> bundle = GenerateValidBundleOption(bundleOption);
2415 if (bundle == nullptr) {
2416 return ERR_ANS_INVALID_BUNDLE;
2417 }
2418
2419 return NotificationPreferences::GetInstance()->IsDistributedEnabledByBundle(bundle, deviceType, enabled);
2420 }
2421
DuplicateMsgControl(const sptr<NotificationRequest> &request)2422 ErrCode AdvancedNotificationService::DuplicateMsgControl(const sptr<NotificationRequest> &request)
2423 {
2424 if (request->IsCommonLiveView() || request->GetAppMessageId().empty()) {
2425 return ERR_OK;
2426 }
2427
2428 RemoveExpiredUniqueKey();
2429 std::string uniqueKey = request->GenerateUniqueKey();
2430 if (IsDuplicateMsg(uniqueKey)) {
2431 ANS_LOGI("Duplicate msg, no need to notify, key is %{public}s, appmessageId is %{public}s",
2432 request->GetKey().c_str(), request->GetAppMessageId().c_str());
2433 return ERR_ANS_DUPLICATE_MSG;
2434 }
2435
2436 uniqueKeyList_.emplace_back(std::make_pair(std::chrono::steady_clock::now(), uniqueKey));
2437 return ERR_OK;
2438 }
2439
DeleteDuplicateMsgs(const sptr<NotificationBundleOption> &bundleOption)2440 void AdvancedNotificationService::DeleteDuplicateMsgs(const sptr<NotificationBundleOption> &bundleOption)
2441 {
2442 if (bundleOption == nullptr) {
2443 ANS_LOGE("bundleOption is nullptr");
2444 return;
2445 }
2446 const char *keySpliter = "_";
2447 std::stringstream stream;
2448 stream << bundleOption->GetUid() << keySpliter << bundleOption->GetBundleName() << keySpliter;
2449 std::string uniqueKeyHead = stream.str();
2450 auto iter = uniqueKeyList_.begin();
2451 for (auto iter = uniqueKeyList_.begin(); iter != uniqueKeyList_.end();) {
2452 if ((*iter).second.find(uniqueKeyHead) == 0) {
2453 iter = uniqueKeyList_.erase(iter);
2454 } else {
2455 ++iter;
2456 }
2457 }
2458 }
2459
RemoveExpiredUniqueKey()2460 void AdvancedNotificationService::RemoveExpiredUniqueKey()
2461 {
2462 std::chrono::steady_clock::time_point now = std::chrono::steady_clock::now();
2463 auto iter = uniqueKeyList_.begin();
2464 while (iter != uniqueKeyList_.end()) {
2465 if (abs(now - (*iter).first) > std::chrono::hours(HOURS_IN_ONE_DAY)) {
2466 iter = uniqueKeyList_.erase(iter);
2467 } else {
2468 break;
2469 }
2470 }
2471 }
2472
IsDuplicateMsg(const std::string &uniqueKey)2473 bool AdvancedNotificationService::IsDuplicateMsg(const std::string &uniqueKey)
2474 {
2475 for (auto record : uniqueKeyList_) {
2476 if (strcmp(record.second.c_str(), uniqueKey.c_str()) == 0) {
2477 return true;
2478 }
2479 }
2480
2481 return false;
2482 }
2483
PublishRemoveDuplicateEvent(const std::shared_ptr<NotificationRecord> &record)2484 ErrCode AdvancedNotificationService::PublishRemoveDuplicateEvent(const std::shared_ptr<NotificationRecord> &record)
2485 {
2486 if (record == nullptr) {
2487 return ERR_ANS_INVALID_PARAM;
2488 }
2489
2490 if (!record->request->IsAgentNotification()) {
2491 ANS_LOGD("Only push agent need remove duplicate event");
2492 return ERR_OK;
2493 }
2494
2495 std::string extraStr;
2496 if (record->request->GetUnifiedGroupInfo() != nullptr) {
2497 auto extraInfo = record->request->GetUnifiedGroupInfo()->GetExtraInfo();
2498 if (extraInfo != nullptr) {
2499 AAFwk::WantParamWrapper wWrapper(*extraInfo);
2500 extraStr = wWrapper.ToString();
2501 }
2502 }
2503
2504 NotificationNapi::SlotType slotType;
2505 NotificationNapi::ContentType contentType;
2506 NotificationNapi::AnsEnumUtil::ContentTypeCToJS(
2507 static_cast<NotificationContent::Type>(record->request->GetNotificationType()), contentType);
2508 NotificationNapi::AnsEnumUtil::SlotTypeCToJS(
2509 static_cast<NotificationConstant::SlotType>(record->request->GetSlotType()), slotType);
2510
2511 EventFwk::Want want;
2512 want.SetParam("bundleName", record->bundleOption->GetBundleName());
2513 want.SetParam("uid", record->request->GetOwnerUid());
2514 want.SetParam("id", record->request->GetNotificationId());
2515 want.SetParam("slotType", static_cast<int32_t>(slotType));
2516 want.SetParam("contentType", static_cast<int32_t>(contentType));
2517 want.SetParam("appMessageId", record->request->GetAppMessageId());
2518 want.SetParam("extraInfo", extraStr);
2519 want.SetAction(NOTIFICATION_EVENT_PUSH_AGENT);
2520 EventFwk::CommonEventData commonData {want, 1, ""};
2521 EventFwk::CommonEventPublishInfo publishInfo;
2522 publishInfo.SetSubscriberPermissions({OHOS_PERMISSION_NOTIFICATION_AGENT_CONTROLLER});
2523 if (!EventFwk::CommonEventManager::PublishCommonEvent(commonData, publishInfo)) {
2524 ANS_LOGE("PublishCommonEvent failed");
2525 return ERR_ANS_TASK_ERR;
2526 }
2527
2528 return ERR_OK;
2529 }
2530
SetSmartReminderEnabled(const std::string &deviceType, const bool enabled)2531 ErrCode AdvancedNotificationService::SetSmartReminderEnabled(const std::string &deviceType, const bool enabled)
2532 {
2533 ANS_LOGD("%{public}s", __FUNCTION__);
2534 bool isSubsystem = AccessTokenHelper::VerifyNativeToken(IPCSkeleton::GetCallingTokenID());
2535 if (!isSubsystem && !AccessTokenHelper::IsSystemApp()) {
2536 ANS_LOGD("IsSystemApp is bogus.");
2537 return ERR_ANS_NON_SYSTEM_APP;
2538 }
2539
2540 if (!AccessTokenHelper::CheckPermission(OHOS_PERMISSION_NOTIFICATION_CONTROLLER)) {
2541 return ERR_ANS_PERMISSION_DENIED;
2542 }
2543 ErrCode result = NotificationPreferences::GetInstance()->SetSmartReminderEnabled(deviceType, enabled);
2544 return result;
2545 }
2546
IsSmartReminderEnabled(const std::string &deviceType, bool &enabled)2547 ErrCode AdvancedNotificationService::IsSmartReminderEnabled(const std::string &deviceType, bool &enabled)
2548 {
2549 ANS_LOGD("%{public}s", __FUNCTION__);
2550 bool isSubsystem = AccessTokenHelper::VerifyNativeToken(IPCSkeleton::GetCallingTokenID());
2551 if (!isSubsystem && !AccessTokenHelper::IsSystemApp()) {
2552 ANS_LOGD("IsSystemApp is bogus.");
2553 return ERR_ANS_NON_SYSTEM_APP;
2554 }
2555
2556 if (!AccessTokenHelper::CheckPermission(OHOS_PERMISSION_NOTIFICATION_CONTROLLER)) {
2557 ANS_LOGE("no permission");
2558 return ERR_ANS_PERMISSION_DENIED;
2559 }
2560
2561 return NotificationPreferences::GetInstance()->IsSmartReminderEnabled(deviceType, enabled);
2562 }
2563
SetTargetDeviceStatus(const std::string &deviceType, const uint32_t status)2564 ErrCode AdvancedNotificationService::SetTargetDeviceStatus(const std::string &deviceType, const uint32_t status)
2565 {
2566 ANS_LOGD("%{public}s", __FUNCTION__);
2567 uint32_t status_ = status;
2568 bool isSubsystem = AccessTokenHelper::VerifyNativeToken(IPCSkeleton::GetCallingTokenID());
2569 if (!isSubsystem) {
2570 ANS_LOGD("isSubsystem is bogus.");
2571 return ERR_ANS_NON_SYSTEM_APP;
2572 }
2573 if (deviceType.empty()) {
2574 return ERR_ANS_INVALID_PARAM;
2575 }
2576
2577 int ret = DelayedSingleton<DistributedDeviceStatus>::GetInstance()->SetDeviceStatus(deviceType, status_);
2578 ANS_LOGI("%{public}s device status update with %{public}u",
2579 deviceType.c_str(), DelayedSingleton<DistributedDeviceStatus>::GetInstance()->GetDeviceStatus(deviceType));
2580 return ret;
2581 }
2582
ClearAllNotificationGroupInfo(std::string localSwitch)2583 void AdvancedNotificationService::ClearAllNotificationGroupInfo(std::string localSwitch)
2584 {
2585 ANS_LOGD("ClearNotification enter.");
2586 bool status = (localSwitch == "true");
2587 if (notificationSvrQueue_ == nullptr) {
2588 ANS_LOGE("ClearNotification Serial queue is invalid.");
2589 return;
2590 }
2591
2592 ffrt::task_handle handler = notificationSvrQueue_->submit_h([=]() {
2593 if (aggregateLocalSwitch_ && !status) {
2594 for (const auto& item : notificationList_) {
2595 item->notification->GetNotificationRequestPoint()->SetUnifiedGroupInfo(nullptr);
2596 }
2597 }
2598 aggregateLocalSwitch_ = status;
2599 });
2600 }
2601 } // namespace Notification
2602 } // namespace OHOS
2603