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 #ifdef DISTRIBUTED_NOTIFICATION_SUPPORTED
35 #include "distributed_screen_status_manager.h"
36 #endif
37 #include "notification_extension_wrapper.h"
38 #include "notification_local_live_view_subscriber_manager.h"
39 #include "common_event_manager.h"
40 #include "common_event_support.h"
41 #include "common_event_publish_info.h"
42 #include "os_account_manager_helper.h"
43 #include "want_params_wrapper.h"
44 #include "ans_convert_enum.h"
45 #include "notification_analytics_util.h"
46
47 #include "advanced_notification_inline.cpp"
48 #include "notification_analytics_util.h"
49 #include "advanced_datashare_helper.h"
50 #include "advanced_datashare_helper_ext.h"
51 #include "datashare_result_set.h"
52 #include "parameter.h"
53 #include "system_ability_definition.h"
54 #include "if_system_ability_manager.h"
55 #include "iservice_registry.h"
56 #include "datashare_predicates.h"
57 #include "notification_config_parse.h"
58 #include "advanced_notification_flow_control_service.h"
59 #include "notification_operation_info.h"
60 #include "notification_operation_service.h"
61
62 namespace OHOS {
63 namespace Notification {
64
65 constexpr char FOUNDATION_BUNDLE_NAME[] = "ohos.global.systemres";
66 constexpr uint32_t SECONDS_IN_ONE_DAY = 24 * 60 * 60;
67 const static std::string NOTIFICATION_EVENT_PUSH_AGENT = "notification.event.PUSH_AGENT";
68 const static std::string NOTIFICATION_EVENT_SUBSCRIBER_STATUS = "notification.event.SUBSCRIBER_STATUS";
69 constexpr int32_t RSS_PID = 3051;
70 constexpr int32_t ANS_UID = 5523;
71 constexpr int32_t AVSEESAION_PID = 6700;
72 constexpr int32_t TYPE_CODE_DOWNLOAD = 8;
73 constexpr const char *FOCUS_MODE_REPEAT_CALLERS_ENABLE = "1";
74 constexpr const char *CONTACT_DATA = "datashare:///com.ohos.contactsdataability/contacts/contact_data?Proxy=true";
75 constexpr const char *SUPPORT_INTEGELLIGENT_SCENE = "true";
76 constexpr int32_t OPERATION_TYPE_COMMON_EVENT = 4;
77 const static std::string BUNDLE_NAME_ZYT = "com.zhuoyi.appstore.lite";
78 const static std::string BUNDLE_NAME_ABROAD = "com.easy.transfer.abroad";
79 const static std::string INSTALL_SOURCE_EASYABROAD = "com.easy.abroad";
80 constexpr int32_t BADGE_NUM_LIMIT = 0;
81 constexpr int32_t CLEAR_SLOT_FROM_AVSEESAION = 1;
82 constexpr int32_t CLEAR_SLOT_FROM_RSS = 2;
83
SetDefaultNotificationEnabled(const sptr<NotificationBundleOption> & bundleOption,bool enabled)84 ErrCode AdvancedNotificationService::SetDefaultNotificationEnabled(
85 const sptr<NotificationBundleOption> &bundleOption, bool enabled)
86 {
87 sptr<NotificationBundleOption> bundle = GenerateValidBundleOption(bundleOption);
88 if (bundle == nullptr) {
89 return ERR_ANS_INVALID_BUNDLE;
90 }
91 sptr<EnabledNotificationCallbackData> bundleData =
92 new (std::nothrow) EnabledNotificationCallbackData(bundle->GetBundleName(), bundle->GetUid(), enabled);
93 if (bundleData == nullptr) {
94 ANS_LOGE("Failed to create EnabledNotificationCallbackData instance");
95 return ERR_NO_MEMORY;
96 }
97 SetSlotFlagsTrustlistsAsBundle(bundle);
98 ErrCode result = ERR_OK;
99 result = NotificationPreferences::GetInstance()->SetNotificationsEnabledForBundle(bundle, enabled);
100 if (result == ERR_OK) {
101 NotificationSubscriberManager::GetInstance()->NotifyEnabledNotificationChanged(bundleData);
102 PublishSlotChangeCommonEvent(bundle);
103 }
104
105 SendEnableNotificationHiSysEvent(bundleOption, enabled, result);
106 return result;
107 }
108
Publish(const std::string & label,const sptr<NotificationRequest> & request)109 ErrCode AdvancedNotificationService::Publish(const std::string &label, const sptr<NotificationRequest> &request)
110 {
111 HITRACE_METER_NAME(HITRACE_TAG_NOTIFICATION, __PRETTY_FUNCTION__);
112 ANS_LOGD("%{public}s", __FUNCTION__);
113
114 if (!request) {
115 ANSR_LOGE("ReminderRequest object is nullptr");
116 return ERR_ANS_INVALID_PARAM;
117 }
118
119 if (request->GetDistributedCollaborate()) {
120 return CollaboratePublish(request);
121 }
122
123 if (!InitPublishProcess()) {
124 return ERR_ANS_NO_MEMORY;
125 }
126
127 request->SetCreateTime(GetCurrentTime());
128 HaMetaMessage message = HaMetaMessage(EventSceneId::SCENE_1, EventBranchId::BRANCH_1);
129 bool isUpdateByOwnerAllowed = IsUpdateSystemLiveviewByOwner(request);
130 ErrCode result = publishProcess_[request->GetSlotType()]->PublishPreWork(request, isUpdateByOwnerAllowed);
131 if (result != ERR_OK) {
132 message.BranchId(EventBranchId::BRANCH_0).ErrorCode(result).Message("publish prework failed", true);
133 NotificationAnalyticsUtil::ReportPublishFailedEvent(request, message);
134 return result;
135 }
136 result = CheckUserIdParams(request->GetReceiverUserId());
137 if (result != ERR_OK) {
138 message.SceneId(EventSceneId::SCENE_3).ErrorCode(result).Message("User is invalid", true);
139 NotificationAnalyticsUtil::ReportPublishFailedEvent(request, message);
140 return result;
141 }
142 bool isSubsystem = AccessTokenHelper::VerifyNativeToken(IPCSkeleton::GetCallingTokenID());
143 request->SetIsSystemApp(AccessTokenHelper::IsSystemApp() || isSubsystem);
144 if (isSubsystem) {
145 return PublishNotificationBySa(request);
146 }
147 if (request->GetRemovalWantAgent() != nullptr && request->GetRemovalWantAgent()->GetPendingWant() != nullptr) {
148 uint32_t operationType = (uint32_t)(request->GetRemovalWantAgent()->GetPendingWant()
149 ->GetType(request->GetRemovalWantAgent()->GetPendingWant()->GetTarget()));
150 bool isSystemApp = AccessTokenHelper::IsSystemApp();
151 if (!isSubsystem && !isSystemApp && operationType != OPERATION_TYPE_COMMON_EVENT) {
152 ANS_LOGI("SetRemovalWantAgent as nullptr");
153 request->SetRemovalWantAgent(nullptr);
154 }
155 }
156 do {
157 result = publishProcess_[request->GetSlotType()]->PublishNotificationByApp(request);
158 if (result != ERR_OK) {
159 break;
160 }
161
162 sptr<NotificationBundleOption> bundleOption;
163 result = PrepareNotificationInfo(request, bundleOption);
164 if (result != ERR_OK) {
165 message.ErrorCode(result).Message("PrepareNotificationInfo failed.");
166 NotificationAnalyticsUtil::ReportPublishFailedEvent(request, message);
167 break;
168 }
169
170 result = CheckSoundPermission(request, bundleOption->GetBundleName());
171 if (result != ERR_OK) {
172 message.ErrorCode(result).Message("Check sound failed.");
173 NotificationAnalyticsUtil::ReportPublishFailedEvent(request, message);
174 break;
175 }
176
177 #ifndef IS_EMULATOR
178 if (IsNeedPushCheck(request)) {
179 result = PushCheck(request);
180 }
181 #endif
182
183 if (result != ERR_OK) {
184 break;
185 }
186 result = PublishPreparedNotification(request, bundleOption, isUpdateByOwnerAllowed);
187 if (result != ERR_OK) {
188 break;
189 }
190 } while (0);
191
192 SendPublishHiSysEvent(request, result);
193 return result;
194 }
195
SetCollaborateReminderFlag(const sptr<NotificationRequest> & request)196 void AdvancedNotificationService::SetCollaborateReminderFlag(const sptr<NotificationRequest> &request)
197 {
198 ANS_LOGI("Before %{public}s", request->GetKey().c_str());
199 auto flags = std::make_shared<NotificationFlags>();
200 flags->SetReminderFlags(request->GetCollaboratedReminderFlag());
201 request->SetFlags(flags);
202 ANS_LOGI("SetFlags %{public}d %{public}d", flags->GetReminderFlags(),
203 request->GetCollaboratedReminderFlag());
204 }
205
UpdateCollaborateTimerInfo(const std::shared_ptr<NotificationRecord> & record)206 void AdvancedNotificationService::UpdateCollaborateTimerInfo(const std::shared_ptr<NotificationRecord> &record)
207 {
208 if (!record->request->IsCommonLiveView()) {
209 return;
210 }
211
212 auto content = record->request->GetContent()->GetNotificationContent();
213 auto liveViewContent = std::static_pointer_cast<NotificationLiveViewContent>(content);
214 auto status = liveViewContent->GetLiveViewStatus();
215 switch (status) {
216 case NotificationLiveViewContent::LiveViewStatus::LIVE_VIEW_CREATE: {
217 SetFinishTimer(record);
218 SetUpdateTimer(record);
219 CancelArchiveTimer(record);
220 return;
221 }
222 case NotificationLiveViewContent::LiveViewStatus::LIVE_VIEW_INCREMENTAL_UPDATE:
223 case NotificationLiveViewContent::LiveViewStatus::LIVE_VIEW_FULL_UPDATE: {
224 if (record->notification->GetFinishTimer() == NotificationConstant::INVALID_TIMER_ID) {
225 int64_t finishedTime = record->request->GetFinishDeadLine();
226 StartFinishTimer(record, finishedTime,
227 NotificationConstant::TRIGGER_EIGHT_HOUR_REASON_DELETE);
228 }
229 CancelUpdateTimer(record);
230 SetUpdateTimer(record);
231 CancelArchiveTimer(record);
232 return;
233 }
234 case NotificationLiveViewContent::LiveViewStatus::LIVE_VIEW_END:
235 CancelUpdateTimer(record);
236 CancelFinishTimer(record);
237 StartArchiveTimer(record);
238 break;
239 default:
240 ANS_LOGE("Invalid status %{public}d.", status);
241 }
242 }
243
CollaboratePublish(const sptr<NotificationRequest> & request)244 ErrCode AdvancedNotificationService::CollaboratePublish(const sptr<NotificationRequest> &request)
245 {
246 auto tokenCaller = IPCSkeleton::GetCallingTokenID();
247 if (!AccessTokenHelper::VerifyNativeToken(tokenCaller) ||
248 !AccessTokenHelper::VerifyCallerPermission(tokenCaller, OHOS_PERMISSION_NOTIFICATION_CONTROLLER)) {
249 ANS_LOGE("Collaborate publish cheak permission failed.");
250 return ERR_ANS_PERMISSION_DENIED;
251 }
252
253 int32_t uid = IPCSkeleton::GetCallingUid();
254 int32_t pid = IPCSkeleton::GetCallingPid();
255 request->SetCreatorUid(uid);
256 request->SetCreatorPid(pid);
257 if (request->GetOwnerUid() == DEFAULT_UID) {
258 request->SetOwnerUid(uid);
259 }
260
261 int32_t userId = SUBSCRIBE_USER_INIT;
262 OsAccountManagerHelper::GetInstance().GetCurrentActiveUserId(userId);
263 request->SetCreatorUserId(userId);
264 request->SetCreateTime(GetCurrentTime());
265 if (request->GetDeliveryTime() <= 0) {
266 request->SetDeliveryTime(GetCurrentTime());
267 }
268 std::shared_ptr<NotificationRecord> record = std::make_shared<NotificationRecord>();
269 record->request = request;
270 record->notification = new (std::nothrow) Notification(request);
271 if (record->notification == nullptr) {
272 ANS_LOGE("Failed to create notification");
273 return ERR_ANS_NO_MEMORY;
274 }
275 record->bundleOption = new (std::nothrow) NotificationBundleOption(request->GetCreatorBundleName(), 0);
276 record->notification->SetKey(request->GetLabel() + request->GetDistributedHashCode());
277 SetCollaborateReminderFlag(record->request);
278 if (notificationSvrQueue_ == nullptr) {
279 ANS_LOGE("Serial queue is invalid.");
280 return ERR_ANS_INVALID_PARAM;
281 }
282 ffrt::task_handle handler = notificationSvrQueue_->submit_h([&]() {
283 if (AssignToNotificationList(record) != ERR_OK) {
284 ANS_LOGE("Failed to assign notification list");
285 return;
286 }
287
288 UpdateRecentNotification(record->notification, false, 0);
289 sptr<NotificationSortingMap> sortingMap = GenerateSortingMap();
290 NotificationSubscriberManager::GetInstance()->NotifyConsumed(record->notification, sortingMap);
291
292 NotificationRequestDb requestDb = { .request = record->request, .bundleOption = record->bundleOption};
293 UpdateCollaborateTimerInfo(record);
294 SetNotificationRequestToDb(requestDb);
295 });
296 notificationSvrQueue_->wait(handler);
297 return ERR_OK;
298 }
299
PublishNotificationForIndirectProxy(const sptr<NotificationRequest> & request)300 ErrCode AdvancedNotificationService::PublishNotificationForIndirectProxy(const sptr<NotificationRequest> &request)
301 {
302 HITRACE_METER_NAME(HITRACE_TAG_NOTIFICATION, __PRETTY_FUNCTION__);
303 ANS_LOGD("%{public}s", __FUNCTION__);
304
305 HaMetaMessage message = HaMetaMessage(EventSceneId::SCENE_9, EventBranchId::BRANCH_0);
306 if (!request) {
307 ANS_LOGE("Request object is nullptr");
308 return ERR_ANS_INVALID_PARAM;
309 }
310 ErrCode result = PrePublishRequest(request);
311 if (result != ERR_OK) {
312 return result;
313 }
314 auto tokenCaller = IPCSkeleton::GetCallingTokenID();
315 bool isAgentController = AccessTokenHelper::VerifyCallerPermission(tokenCaller,
316 OHOS_PERMISSION_NOTIFICATION_AGENT_CONTROLLER);
317 // SA not support sound
318 if (!request->GetSound().empty()) {
319 request->SetSound("");
320 }
321 std::string bundle = request->GetCreatorBundleName();
322 int32_t uid = request->GetCreatorUid();
323 request->SetOwnerUid(uid);
324 request->SetOwnerBundleName(bundle);
325 std::shared_ptr<NotificationRecord> record = std::make_shared<NotificationRecord>();
326 record->request = request;
327 record->isThirdparty = false;
328 record->bundleOption = new (std::nothrow) NotificationBundleOption(bundle, uid);
329 sptr<NotificationBundleOption> bundleOption = new (std::nothrow) NotificationBundleOption(bundle, uid);
330 if (record->bundleOption == nullptr || bundleOption == nullptr) {
331 ANS_LOGE("Failed to create bundleOption");
332 return ERR_ANS_NO_MEMORY;
333 }
334 record->bundleOption->SetAppInstanceKey(request->GetAppInstanceKey());
335 record->notification = new (std::nothrow) Notification(request);
336 if (record->notification == nullptr) {
337 ANS_LOGE("Failed to create notification");
338 return ERR_ANS_NO_MEMORY;
339 }
340
341 if (notificationSvrQueue_ == nullptr) {
342 ANS_LOGE("Serial queue is invalid.");
343 return ERR_ANS_INVALID_PARAM;
344 }
345
346 SetRequestBySlotType(record->request, bundleOption);
347
348 const int32_t ipcUid = IPCSkeleton::GetCallingUid();
349 ffrt::task_handle handler = notificationSvrQueue_->submit_h([&]() {
350 if (IsDisableNotification(bundle)) {
351 ANS_LOGE("bundle in Disable Notification list, bundleName=%{public}s", bundle.c_str());
352 result = ERR_ANS_REJECTED_WITH_DISABLE_NOTIFICATION;
353 message.BranchId(EventBranchId::BRANCH_1)
354 .ErrorCode(result).Message("bundle in Disable Notification list, bundleName=" + bundle);
355 return;
356 }
357 if (AssignValidNotificationSlot(record, bundleOption) != ERR_OK) {
358 ANS_LOGE("Can not assign valid slot!");
359 }
360 result = Filter(record);
361 if (result != ERR_OK) {
362 ANS_LOGE("Reject by filters: %{public}d", result);
363 return;
364 }
365
366 CheckDoNotDisturbProfile(record);
367 ChangeNotificationByControlFlags(record, isAgentController);
368 if (IsSaCreateSystemLiveViewAsBundle(record, ipcUid) &&
369 (std::static_pointer_cast<OHOS::Notification::NotificationLocalLiveViewContent>(
370 record->request->GetContent()->GetNotificationContent())->GetType() == TYPE_CODE_DOWNLOAD)) {
371 result = SaPublishSystemLiveViewAsBundle(record);
372 if (result == ERR_OK) {
373 SendLiveViewUploadHiSysEvent(record, UploadStatus::CREATE);
374 }
375 return;
376 }
377
378 bool isNotificationExists = IsNotificationExists(record->notification->GetKey());
379 result = FlowControlService::GetInstance()->FlowControl(record, ipcUid, isNotificationExists);
380 if (result != ERR_OK) {
381 message.BranchId(EventBranchId::BRANCH_5).ErrorCode(result).Message("publish failed with FlowControl");
382 return;
383 }
384 if (AssignToNotificationList(record) != ERR_OK) {
385 ANS_LOGE("Failed to assign notification list");
386 message.BranchId(EventBranchId::BRANCH_5).ErrorCode(result).Message("Failed to assign notification list");
387 return;
388 }
389
390 sptr<NotificationSortingMap> sortingMap = GenerateSortingMap();
391 NotificationSubscriberManager::GetInstance()->NotifyConsumed(record->notification, sortingMap);
392 });
393 notificationSvrQueue_->wait(handler);
394 if (result != ERR_OK) {
395 NotificationAnalyticsUtil::ReportPublishFailedEvent(request, message);
396 return result;
397 }
398
399 if ((record->request->GetAutoDeletedTime() > GetCurrentTime()) && !record->request->IsCommonLiveView()) {
400 StartAutoDelete(record,
401 record->request->GetAutoDeletedTime(), NotificationConstant::TRIGGER_AUTO_DELETE_REASON_DELETE);
402 }
403 return ERR_OK;
404 }
405
InitPublishProcess()406 bool AdvancedNotificationService::InitPublishProcess()
407 {
408 if (publishProcess_.size() > 0) {
409 return true;
410 }
411
412 std::shared_ptr<LivePublishProcess> livePublishProcess = LivePublishProcess::GetInstance();
413 if (livePublishProcess == nullptr) {
414 ANS_LOGE("InitPublishProcess fail as livePublishProcess is nullptr.");
415 return false;
416 }
417 publishProcess_.insert_or_assign(NotificationConstant::SlotType::LIVE_VIEW, livePublishProcess);
418 std::shared_ptr<CommonNotificationPublishProcess> commonNotificationPublishProcess =
419 CommonNotificationPublishProcess::GetInstance();
420 if (commonNotificationPublishProcess == nullptr) {
421 ANS_LOGE("InitPublishProcess fail as commonNotificationPublishProcess is nullptr.");
422 publishProcess_.clear();
423 return false;
424 }
425 publishProcess_.insert_or_assign(
426 NotificationConstant::SlotType::SOCIAL_COMMUNICATION, commonNotificationPublishProcess);
427 publishProcess_.insert_or_assign(
428 NotificationConstant::SlotType::SERVICE_REMINDER, commonNotificationPublishProcess);
429 publishProcess_.insert_or_assign(
430 NotificationConstant::SlotType::CONTENT_INFORMATION, commonNotificationPublishProcess);
431 publishProcess_.insert_or_assign(
432 NotificationConstant::SlotType::OTHER, commonNotificationPublishProcess);
433 publishProcess_.insert_or_assign(
434 NotificationConstant::SlotType::CUSTOM, commonNotificationPublishProcess);
435 publishProcess_.insert_or_assign(
436 NotificationConstant::SlotType::CUSTOMER_SERVICE, commonNotificationPublishProcess);
437 publishProcess_.insert_or_assign(
438 NotificationConstant::SlotType::EMERGENCY_INFORMATION, commonNotificationPublishProcess);
439 return true;
440 }
441
Cancel(int32_t notificationId,const std::string & label,const std::string & instanceKey)442 ErrCode AdvancedNotificationService::Cancel(int32_t notificationId,
443 const std::string &label, const std::string &instanceKey)
444 {
445 ANS_LOGD("%{public}s", __FUNCTION__);
446
447 sptr<NotificationBundleOption> bundleOption = GenerateBundleOption();
448 if (bundleOption == nullptr) {
449 std::string message = "get bundleOption is null.";
450 OHOS::Notification::HaMetaMessage haMetaMessage = HaMetaMessage(1, 1)
451 .ErrorCode(ERR_ANS_INVALID_BUNDLE).NotificationId(notificationId);
452 ReportDeleteFailedEventPush(haMetaMessage, NotificationConstant::APP_CANCEL_REASON_DELETE,
453 message);
454 ANS_LOGE("%{public}s", message.c_str());
455 return ERR_ANS_INVALID_BUNDLE;
456 }
457 bundleOption->SetAppInstanceKey(instanceKey);
458 return CancelPreparedNotification(notificationId, label, bundleOption,
459 NotificationConstant::APP_CANCEL_REASON_DELETE);
460 }
461
CancelAll(const std::string & instanceKey)462 ErrCode AdvancedNotificationService::CancelAll(const std::string &instanceKey)
463 {
464 ANS_LOGD("%{public}s", __FUNCTION__);
465 const int reason = NotificationConstant::APP_CANCEL_ALL_REASON_DELETE;
466 sptr<NotificationBundleOption> bundleOption = GenerateBundleOption();
467 if (bundleOption == nullptr) {
468 return ERR_ANS_INVALID_BUNDLE;
469 }
470 bundleOption->SetAppInstanceKey(instanceKey);
471
472 if (notificationSvrQueue_ == nullptr) {
473 ANS_LOGE("Serial queue is invalidated.");
474 return ERR_ANS_INVALID_PARAM;
475 }
476 ErrCode result = ExcuteCancelAll(bundleOption, reason);
477 return result;
478 }
479
ExcuteCancelAll(const sptr<NotificationBundleOption> & bundleOption,const int32_t reason)480 ErrCode AdvancedNotificationService::ExcuteCancelAll(
481 const sptr<NotificationBundleOption>& bundleOption, const int32_t reason)
482 {
483 ErrCode result = ERR_OK;
484 ffrt::task_handle handler = notificationSvrQueue_->submit_h(std::bind([&]() {
485 ANS_LOGD("ffrt enter!");
486 sptr<Notification> notification = nullptr;
487
488 std::vector<std::string> keys = GetNotificationKeysByBundle(bundleOption);
489 std::vector<sptr<Notification>> notifications;
490 std::vector<uint64_t> timerIds;
491 for (auto key : keys) {
492 #ifdef DISTRIBUTED_NOTIFICATION_SUPPORTED
493 std::string deviceId;
494 std::string bundleName;
495 GetDistributedInfo(key, deviceId, bundleName);
496 #endif
497 result = RemoveFromNotificationList(key, notification, true, reason);
498 if (result != ERR_OK) {
499 continue;
500 }
501
502 if (notification != nullptr) {
503 UpdateRecentNotification(notification, true, reason);
504 notifications.emplace_back(notification);
505 timerIds.emplace_back(notification->GetAutoDeletedTimer());
506 #ifdef DISTRIBUTED_NOTIFICATION_SUPPORTED
507 DoDistributedDelete(deviceId, bundleName, notification);
508 #endif
509 }
510 if (notifications.size() >= MAX_CANCELED_PARCELABLE_VECTOR_NUM) {
511 std::vector<sptr<Notification>> currNotificationList = notifications;
512 NotificationSubscriberManager::GetInstance()->BatchNotifyCanceled(
513 currNotificationList, nullptr, reason);
514 notifications.clear();
515 }
516 }
517
518 if (!notifications.empty()) {
519 NotificationSubscriberManager::GetInstance()->BatchNotifyCanceled(
520 notifications, nullptr, reason);
521 }
522 BatchCancelTimer(timerIds);
523 result = ERR_OK;
524 }));
525 notificationSvrQueue_->wait(handler);
526 return result;
527 }
528
CancelAsBundle(const sptr<NotificationBundleOption> & bundleOption,int32_t notificationId,int32_t userId)529 ErrCode AdvancedNotificationService::CancelAsBundle(
530 const sptr<NotificationBundleOption> &bundleOption, int32_t notificationId, int32_t userId)
531 {
532 ANS_LOGD("%{public}s", __FUNCTION__);
533 int32_t reason = NotificationConstant::APP_CANCEL_AS_BUNELE_REASON_DELETE;
534 bool isSubsystem = AccessTokenHelper::VerifyNativeToken(IPCSkeleton::GetCallingTokenID());
535 if (!isSubsystem && !AccessTokenHelper::IsSystemApp()) {
536 std::string message = "not systemApp";
537 OHOS::Notification::HaMetaMessage haMetaMessage = HaMetaMessage(2, 1)
538 .ErrorCode(ERR_ANS_NON_SYSTEM_APP).NotificationId(notificationId);
539 ReportDeleteFailedEventPush(haMetaMessage, reason, message);
540 ANS_LOGE("%{public}s", message.c_str());
541 return ERR_ANS_NON_SYSTEM_APP;
542 }
543
544 if (!AccessTokenHelper::CheckPermission(OHOS_PERMISSION_NOTIFICATION_CONTROLLER) ||
545 !AccessTokenHelper::CheckPermission(OHOS_PERMISSION_NOTIFICATION_AGENT_CONTROLLER)) {
546 std::string message = "no acl permission";
547 OHOS::Notification::HaMetaMessage haMetaMessage = HaMetaMessage(2, 2)
548 .ErrorCode(ERR_ANS_PERMISSION_DENIED).NotificationId(notificationId);
549 ReportDeleteFailedEventPush(haMetaMessage, reason, message);
550 ANS_LOGE("%{public}s", message.c_str());
551 return ERR_ANS_PERMISSION_DENIED;
552 }
553
554 int32_t errCode = CheckUserIdParams(userId);
555 if (errCode != ERR_OK) {
556 return errCode;
557 }
558
559 int32_t uid = -1;
560 if (bundleOption->GetUid() == DEFAULT_UID) {
561 std::shared_ptr<BundleManagerHelper> bundleManager = BundleManagerHelper::GetInstance();
562 if (bundleManager != nullptr) {
563 uid = BundleManagerHelper::GetInstance()->GetDefaultUidByBundleName(bundleOption->GetBundleName(), userId);
564 }
565 } else {
566 uid = bundleOption->GetUid();
567 }
568 if (uid < 0) {
569 std::string message = "uid error";
570 OHOS::Notification::HaMetaMessage haMetaMessage = HaMetaMessage(2, 3)
571 .ErrorCode(ERR_ANS_INVALID_UID).NotificationId(notificationId);
572 ReportDeleteFailedEventPush(haMetaMessage, reason, message);
573 ANS_LOGE("%{public}s", message.c_str());
574 return ERR_ANS_INVALID_UID;
575 }
576 sptr<NotificationBundleOption> bundle = new (std::nothrow) NotificationBundleOption(
577 bundleOption->GetBundleName(), uid);
578 return CancelPreparedNotification(notificationId, "", bundle, reason);
579 }
580
CancelAsBundle(const sptr<NotificationBundleOption> & bundleOption,int32_t notificationId)581 ErrCode AdvancedNotificationService::CancelAsBundle(
582 const sptr<NotificationBundleOption> &bundleOption, int32_t notificationId)
583 {
584 ANS_LOGD("%{public}s, uid = %{public}d", __FUNCTION__, bundleOption->GetUid());
585 int32_t userId = -1;
586 if (bundleOption->GetUid() != 0) {
587 OHOS::AccountSA::OsAccountManager::GetOsAccountLocalIdFromUid(bundleOption->GetUid(), userId);
588 } else {
589 OHOS::AccountSA::OsAccountManager::GetOsAccountLocalIdFromUid(IPCSkeleton::GetCallingUid(), userId);
590 }
591 return CancelAsBundle(bundleOption, notificationId, userId);
592 }
593
CancelAsBundle(int32_t notificationId,const std::string & representativeBundle,int32_t userId)594 ErrCode AdvancedNotificationService::CancelAsBundle(
595 int32_t notificationId, const std::string &representativeBundle, int32_t userId)
596 {
597 ANS_LOGD("%{public}s", __FUNCTION__);
598 sptr<NotificationBundleOption> bundleOption = new (std::nothrow) NotificationBundleOption(
599 representativeBundle, DEFAULT_UID);
600 return CancelAsBundle(bundleOption, notificationId, userId);
601 }
602
CancelAsBundleWithAgent(const sptr<NotificationBundleOption> & bundleOption,const int32_t id)603 ErrCode AdvancedNotificationService::CancelAsBundleWithAgent(
604 const sptr<NotificationBundleOption> &bundleOption, const int32_t id)
605 {
606 ANS_LOGD("Called.");
607 int32_t reason = NotificationConstant::APP_CANCEL_AS_BUNELE_WITH_AGENT_REASON_DELETE;
608 bool isSubsystem = AccessTokenHelper::VerifyNativeToken(IPCSkeleton::GetCallingTokenID());
609 if (!isSubsystem && !AccessTokenHelper::IsSystemApp()) {
610 std::string message = "not systemApp";
611 OHOS::Notification::HaMetaMessage haMetaMessage = HaMetaMessage(2, 4)
612 .ErrorCode(ERR_ANS_NON_SYSTEM_APP).NotificationId(id);
613 ReportDeleteFailedEventPush(haMetaMessage, reason, message);
614 ANS_LOGE("%{public}s", message.c_str());
615 return ERR_ANS_NON_SYSTEM_APP;
616 }
617
618 if (IsAgentRelationship(GetClientBundleName(), bundleOption->GetBundleName())) {
619 int32_t userId = -1;
620 if (bundleOption->GetUid() != 0) {
621 OHOS::AccountSA::OsAccountManager::GetOsAccountLocalIdFromUid(bundleOption->GetUid(), userId);
622 } else {
623 OHOS::AccountSA::OsAccountManager::GetOsAccountLocalIdFromUid(IPCSkeleton::GetCallingUid(), userId);
624 }
625 int32_t uid = -1;
626 if (bundleOption->GetUid() == DEFAULT_UID) {
627 std::shared_ptr<BundleManagerHelper> bundleManager = BundleManagerHelper::GetInstance();
628 if (bundleManager != nullptr) {
629 uid = BundleManagerHelper::GetInstance()->GetDefaultUidByBundleName(
630 bundleOption->GetBundleName(), userId);
631 }
632 } else {
633 uid = bundleOption->GetUid();
634 }
635 if (uid < 0) {
636 std::string message = "uid error";
637 OHOS::Notification::HaMetaMessage haMetaMessage = HaMetaMessage(2, 5)
638 .ErrorCode(ERR_ANS_INVALID_UID).NotificationId(id);
639 ReportDeleteFailedEventPush(haMetaMessage, reason, message);
640 ANS_LOGE("%{public}s", message.c_str());
641 return ERR_ANS_INVALID_UID;
642 }
643 sptr<NotificationBundleOption> bundle = new (std::nothrow) NotificationBundleOption(
644 bundleOption->GetBundleName(), uid);
645 return CancelPreparedNotification(id, "", bundle, reason);
646 }
647 std::string message = "no agent setting";
648 OHOS::Notification::HaMetaMessage haMetaMessage = HaMetaMessage(2, 6)
649 .ErrorCode(ERR_ANS_NO_AGENT_SETTING).NotificationId(id);
650 ReportDeleteFailedEventPush(haMetaMessage, reason, message);
651 ANS_LOGE("%{public}s", message.c_str());
652 return ERR_ANS_NO_AGENT_SETTING;
653 }
654
PublishAsBundle(const sptr<NotificationRequest> notification,const std::string & representativeBundle)655 ErrCode AdvancedNotificationService::PublishAsBundle(
656 const sptr<NotificationRequest> notification, const std::string &representativeBundle)
657 {
658 return ERR_INVALID_OPERATION;
659 }
660
SetNotificationBadgeNum(int32_t num)661 ErrCode AdvancedNotificationService::SetNotificationBadgeNum(int32_t num)
662 {
663 ANS_LOGD("%{public}s", __FUNCTION__);
664
665 sptr<NotificationBundleOption> bundleOption = GenerateBundleOption();
666 if (bundleOption == nullptr) {
667 ANS_LOGD("BundleOption is null.");
668 return ERR_ANS_INVALID_BUNDLE;
669 }
670
671 if (notificationSvrQueue_ == nullptr) {
672 ANS_LOGE("Serial queue is invalidity.");
673 return ERR_ANS_INVALID_PARAM;
674 }
675 ErrCode result = ERR_OK;
676 ffrt::task_handle handler = notificationSvrQueue_->submit_h(
677 std::bind([&]() {
678 ANS_LOGD("ffrt enter!");
679 result = NotificationPreferences::GetInstance()->SetTotalBadgeNums(bundleOption, num);
680 }));
681 notificationSvrQueue_->wait(handler);
682 return result;
683 }
684
Delete(const std::string & key,int32_t removeReason)685 ErrCode AdvancedNotificationService::Delete(const std::string &key, int32_t removeReason)
686 {
687 ANS_LOGD("%{public}s", __FUNCTION__);
688 bool isSubsystem = AccessTokenHelper::VerifyNativeToken(IPCSkeleton::GetCallingTokenID());
689 if (!isSubsystem && !AccessTokenHelper::IsSystemApp()) {
690 std::string message = "not systemApp. key:" + key + ".";
691 OHOS::Notification::HaMetaMessage haMetaMessage = HaMetaMessage(4, 1)
692 .ErrorCode(ERR_ANS_NON_SYSTEM_APP);
693 ReportDeleteFailedEventPush(haMetaMessage, removeReason, message);
694 ANS_LOGE("%{public}s", message.c_str());
695 return ERR_ANS_NON_SYSTEM_APP;
696 }
697
698 if (!AccessTokenHelper::CheckPermission(OHOS_PERMISSION_NOTIFICATION_CONTROLLER)) {
699 std::string message = "no acl permission. key:" + key + ".";
700 OHOS::Notification::HaMetaMessage haMetaMessage = HaMetaMessage(4, 2)
701 .ErrorCode(ERR_ANS_PERMISSION_DENIED);
702 ReportDeleteFailedEventPush(haMetaMessage, removeReason, message);
703 ANS_LOGE("%{public}s", message.c_str());
704 return ERR_ANS_PERMISSION_DENIED;
705 }
706
707 if (notificationSvrQueue_ == nullptr) {
708 std::string message = "Serial queue is invalidated. key:" + key + ".";
709 ANS_LOGE("%{public}s", message.c_str());
710 return ERR_ANS_INVALID_PARAM;
711 }
712
713 return ExcuteDelete(key, removeReason);
714 }
715
ExcuteDelete(const std::string & key,const int32_t removeReason)716 ErrCode AdvancedNotificationService::ExcuteDelete(const std::string &key, const int32_t removeReason)
717 {
718 ErrCode result = ERR_OK;
719 ffrt::task_handle handler = notificationSvrQueue_->submit_h(std::bind([&]() {
720 ANS_LOGD("ffrt enter!");
721 sptr<Notification> notification = nullptr;
722 #ifdef DISTRIBUTED_NOTIFICATION_SUPPORTED
723 std::string deviceId;
724 std::string bundleName;
725 GetDistributedInfo(key, deviceId, bundleName);
726 #endif
727 result = RemoveFromNotificationList(key, notification, false, removeReason);
728 if (result != ERR_OK) {
729 return;
730 }
731
732 if (notification != nullptr) {
733 UpdateRecentNotification(notification, true, removeReason);
734 CancelTimer(notification->GetAutoDeletedTimer());
735 NotificationSubscriberManager::GetInstance()->NotifyCanceled(notification, nullptr, removeReason);
736 #ifdef DISTRIBUTED_NOTIFICATION_SUPPORTED
737 DoDistributedDelete(deviceId, bundleName, notification);
738 #endif
739 }
740 }));
741 notificationSvrQueue_->wait(handler);
742
743 return result;
744 }
745
DeleteByBundle(const sptr<NotificationBundleOption> & bundleOption)746 ErrCode AdvancedNotificationService::DeleteByBundle(const sptr<NotificationBundleOption> &bundleOption)
747 {
748 ANS_LOGD("%{public}s", __FUNCTION__);
749
750 bool isSubsystem = AccessTokenHelper::VerifyNativeToken(IPCSkeleton::GetCallingTokenID());
751 if (!isSubsystem && !AccessTokenHelper::IsSystemApp()) {
752 ANS_LOGD("VerifyNativeToken is false.");
753 return ERR_ANS_NON_SYSTEM_APP;
754 }
755
756 if (!AccessTokenHelper::CheckPermission(OHOS_PERMISSION_NOTIFICATION_CONTROLLER)) {
757 return ERR_ANS_PERMISSION_DENIED;
758 }
759
760 sptr<NotificationBundleOption> bundle = GenerateValidBundleOption(bundleOption);
761 if (bundle == nullptr) {
762 ANS_LOGD("bundle is false.");
763 return ERR_ANS_INVALID_BUNDLE;
764 }
765
766 if (notificationSvrQueue_ == nullptr) {
767 ANS_LOGE("Serial queue is invalid.");
768 return ERR_ANS_INVALID_PARAM;
769 }
770 ErrCode result = ERR_OK;
771 ffrt::task_handle handler = notificationSvrQueue_->submit_h(std::bind([&]() {
772 ANS_LOGD("ffrt enter!");
773 std::vector<std::string> keys = GetNotificationKeys(bundle);
774 for (auto key : keys) {
775 #ifdef DISTRIBUTED_NOTIFICATION_SUPPORTED
776 std::string deviceId;
777 std::string bundleName;
778 GetDistributedInfo(key, deviceId, bundleName);
779 #endif
780 sptr<Notification> notification = nullptr;
781
782 result = RemoveFromNotificationList(key, notification, false, NotificationConstant::CANCEL_REASON_DELETE);
783 if (result != ERR_OK) {
784 continue;
785 }
786
787 if (notification != nullptr) {
788 int32_t reason = NotificationConstant::CANCEL_REASON_DELETE;
789 UpdateRecentNotification(notification, true, reason);
790 CancelTimer(notification->GetAutoDeletedTimer());
791 NotificationSubscriberManager::GetInstance()->NotifyCanceled(notification, nullptr, reason);
792 #ifdef DISTRIBUTED_NOTIFICATION_SUPPORTED
793 DoDistributedDelete(deviceId, bundleName, notification);
794 #endif
795 }
796 }
797
798 result = ERR_OK;
799 }));
800 notificationSvrQueue_->wait(handler);
801
802 return result;
803 }
804
DeleteAll()805 ErrCode AdvancedNotificationService::DeleteAll()
806 {
807 ANS_LOGD("%{public}s", __FUNCTION__);
808
809 const int32_t reason = NotificationConstant::CANCEL_ALL_REASON_DELETE;
810 bool isSubsystem = AccessTokenHelper::VerifyNativeToken(IPCSkeleton::GetCallingTokenID());
811 if (!isSubsystem && !AccessTokenHelper::IsSystemApp()) {
812 std::string message = "not system app.";
813 OHOS::Notification::HaMetaMessage haMetaMessage = HaMetaMessage(6, 8)
814 .ErrorCode(ERR_ANS_NON_SYSTEM_APP);
815 ReportDeleteFailedEventPush(haMetaMessage, reason, message);
816 ANS_LOGE("%{public}s", message.c_str());
817 return ERR_ANS_NON_SYSTEM_APP;
818 }
819
820 if (!AccessTokenHelper::CheckPermission(OHOS_PERMISSION_NOTIFICATION_CONTROLLER)) {
821 std::string message = "no acl permission.";
822 OHOS::Notification::HaMetaMessage haMetaMessage = HaMetaMessage(6, 9)
823 .ErrorCode(ERR_ANS_PERMISSION_DENIED);
824 ReportDeleteFailedEventPush(haMetaMessage, reason, message);
825 ANS_LOGE("%{public}s", message.c_str());
826 return ERR_ANS_PERMISSION_DENIED;
827 }
828
829 if (notificationSvrQueue_ == nullptr) {
830 std::string message = "Serial queue is invalidity.";
831 ANS_LOGE("%{public}s", message.c_str());
832 return ERR_ANS_INVALID_PARAM;
833 }
834 ErrCode result = ERR_OK;
835 ffrt::task_handle handler = notificationSvrQueue_->submit_h(std::bind([&]() {
836 ANS_LOGD("ffrt enter!");
837 int32_t activeUserId = SUBSCRIBE_USER_INIT;
838 if (OsAccountManagerHelper::GetInstance().GetCurrentActiveUserId(activeUserId) != ERR_OK) {
839 return;
840 }
841 std::vector<std::string> keys = GetNotificationKeys(nullptr);
842 std::vector<sptr<Notification>> notifications;
843 std::vector<uint64_t> timerIds;
844 for (auto key : keys) {
845 #ifdef DISTRIBUTED_NOTIFICATION_SUPPORTED
846 std::string deviceId;
847 std::string bundleName;
848 GetDistributedInfo(key, deviceId, bundleName);
849 #endif
850 sptr<Notification> notification = nullptr;
851
852 result = RemoveFromNotificationListForDeleteAll(key, activeUserId, notification);
853 if ((result != ERR_OK) || (notification == nullptr)) {
854 continue;
855 }
856
857 if (notification->GetUserId() == activeUserId) {
858 UpdateRecentNotification(notification, true, reason);
859 notifications.emplace_back(notification);
860 timerIds.emplace_back(notification->GetAutoDeletedTimer());
861 #ifdef DISTRIBUTED_NOTIFICATION_SUPPORTED
862 DoDistributedDelete(deviceId, bundleName, notification);
863 #endif
864 }
865 if (notifications.size() >= MAX_CANCELED_PARCELABLE_VECTOR_NUM) {
866 ANS_LOGD("Notifications size greater than or equal to MAX_CANCELED_PARCELABLE_VECTOR_NUM.");
867 SendNotificationsOnCanceled(notifications, nullptr, reason);
868 }
869 }
870 if (!notifications.empty()) {
871 NotificationSubscriberManager::GetInstance()->BatchNotifyCanceled(
872 notifications, nullptr, reason);
873 }
874 BatchCancelTimer(timerIds);
875 result = ERR_OK;
876 }));
877 notificationSvrQueue_->wait(handler);
878
879 return result;
880 }
881
SetShowBadgeEnabledForBundle(const sptr<NotificationBundleOption> & bundleOption,bool enabled)882 ErrCode AdvancedNotificationService::SetShowBadgeEnabledForBundle(
883 const sptr<NotificationBundleOption> &bundleOption, bool enabled)
884 {
885 if (bundleOption == nullptr) {
886 ANS_LOGE("BundleOption is null.");
887 return ERR_ANS_INVALID_BUNDLE;
888 }
889
890 HaMetaMessage message = HaMetaMessage(EventSceneId::SCENE_8, EventBranchId::BRANCH_3);
891 message.Message(bundleOption->GetBundleName() + "_" + std::to_string(bundleOption->GetUid()) +
892 " enabled:" + std::to_string(enabled));
893
894 bool isSubsystem = AccessTokenHelper::VerifyNativeToken(IPCSkeleton::GetCallingTokenID());
895 if (!isSubsystem && !AccessTokenHelper::IsSystemApp()) {
896 ANS_LOGE("IsSystemApp is false.");
897 message.ErrorCode(ERR_ANS_NON_SYSTEM_APP).Append(" Not SystemApp");
898 NotificationAnalyticsUtil::ReportModifyEvent(message);
899 return ERR_ANS_NON_SYSTEM_APP;
900 }
901
902 if (!AccessTokenHelper::CheckPermission(OHOS_PERMISSION_NOTIFICATION_CONTROLLER)) {
903 ANS_LOGE("Permission Denied.");
904 message.ErrorCode(ERR_ANS_PERMISSION_DENIED).Append(" Permission Denied");
905 NotificationAnalyticsUtil::ReportModifyEvent(message);
906 return ERR_ANS_PERMISSION_DENIED;
907 }
908
909 sptr<NotificationBundleOption> bundle = GenerateValidBundleOption(bundleOption);
910 if (bundle == nullptr) {
911 ANS_LOGE("Bundle is nullptr.");
912 return ERR_ANS_INVALID_BUNDLE;
913 }
914
915 if (notificationSvrQueue_ == nullptr) {
916 ANS_LOGE("NotificationSvrQueue_ is invalid.");
917 return ERR_ANS_INVALID_PARAM;
918 }
919 ErrCode result = ERR_OK;
920 ffrt::task_handle handler = notificationSvrQueue_->submit_h(
921 std::bind([&]() {
922 ANS_LOGD("ffrt enter!");
923 result = NotificationPreferences::GetInstance()->SetShowBadge(bundle, enabled);
924 if (result == ERR_OK) {
925 HandleBadgeEnabledChanged(bundle, enabled);
926 }
927 }));
928 notificationSvrQueue_->wait(handler);
929 ANS_LOGI("%{public}s_%{public}d, enabled: %{public}s, Set show badge enabled for bundle result: %{public}d",
930 bundleOption->GetBundleName().c_str(), bundleOption->GetUid(), std::to_string(enabled).c_str(), result);
931 message.ErrorCode(result);
932 NotificationAnalyticsUtil::ReportModifyEvent(message);
933 return result;
934 }
935
HandleBadgeEnabledChanged(const sptr<NotificationBundleOption> & bundleOption,bool enabled)936 void AdvancedNotificationService::HandleBadgeEnabledChanged(
937 const sptr<NotificationBundleOption> &bundleOption, bool enabled)
938 {
939 sptr<EnabledNotificationCallbackData> enabledData = new (std::nothrow)
940 EnabledNotificationCallbackData(bundleOption->GetBundleName(), bundleOption->GetUid(), enabled);
941 if (enabledData == nullptr) {
942 ANS_LOGE("Failed to create badge enabled data object.");
943 return;
944 }
945
946 NotificationSubscriberManager::GetInstance()->NotifyBadgeEnabledChanged(enabledData);
947 }
948
GetShowBadgeEnabledForBundle(const sptr<NotificationBundleOption> & bundleOption,bool & enabled)949 ErrCode AdvancedNotificationService::GetShowBadgeEnabledForBundle(
950 const sptr<NotificationBundleOption> &bundleOption, bool &enabled)
951 {
952 ANS_LOGD("%{public}s", __FUNCTION__);
953
954 bool isSubsystem = AccessTokenHelper::VerifyNativeToken(IPCSkeleton::GetCallingTokenID());
955 if (!isSubsystem && !AccessTokenHelper::IsSystemApp()) {
956 ANS_LOGD("VerifyNativeToken is bogus.");
957 return ERR_ANS_NON_SYSTEM_APP;
958 }
959
960 if (!AccessTokenHelper::CheckPermission(OHOS_PERMISSION_NOTIFICATION_CONTROLLER)) {
961 return ERR_ANS_PERMISSION_DENIED;
962 }
963
964 sptr<NotificationBundleOption> bundle = GenerateValidBundleOption(bundleOption);
965 if (bundle == nullptr) {
966 ANS_LOGD("Failed to generateValidBundleOption.");
967 return ERR_ANS_INVALID_BUNDLE;
968 }
969
970 if (notificationSvrQueue_ == nullptr) {
971 ANS_LOGE("Serial queue is invalid.");
972 return ERR_ANS_INVALID_PARAM;
973 }
974 ErrCode result = ERR_OK;
975 ffrt::task_handle handler = notificationSvrQueue_->submit_h(std::bind([&]() {
976 ANS_LOGD("ffrt enter!");
977 result = NotificationPreferences::GetInstance()->IsShowBadge(bundle, enabled);
978 if (result == ERR_ANS_PREFERENCES_NOTIFICATION_BUNDLE_NOT_EXIST) {
979 result = ERR_OK;
980 enabled = true;
981 }
982 }));
983 notificationSvrQueue_->wait(handler);
984 return result;
985 }
986
GetShowBadgeEnabled(bool & enabled)987 ErrCode AdvancedNotificationService::GetShowBadgeEnabled(bool &enabled)
988 {
989 ANS_LOGD("%{public}s", __FUNCTION__);
990
991 sptr<NotificationBundleOption> bundleOption = GenerateBundleOption();
992 if (bundleOption == nullptr) {
993 return ERR_ANS_INVALID_BUNDLE;
994 }
995
996 if (notificationSvrQueue_ == nullptr) {
997 ANS_LOGE("Serial queue is ineffective.");
998 return ERR_ANS_INVALID_PARAM;
999 }
1000 ErrCode result = ERR_OK;
1001 ffrt::task_handle handler = notificationSvrQueue_->submit_h(std::bind([&]() {
1002 ANS_LOGD("ffrt enter!");
1003 result = NotificationPreferences::GetInstance()->IsShowBadge(bundleOption, enabled);
1004 if (result == ERR_ANS_PREFERENCES_NOTIFICATION_BUNDLE_NOT_EXIST) {
1005 result = ERR_OK;
1006 enabled = true;
1007 }
1008 }));
1009 notificationSvrQueue_->wait(handler);
1010 return result;
1011 }
1012
RequestEnableNotification(const std::string & deviceId,const sptr<AnsDialogCallback> & callback,const sptr<IRemoteObject> & callerToken)1013 ErrCode AdvancedNotificationService::RequestEnableNotification(const std::string &deviceId,
1014 const sptr<AnsDialogCallback> &callback,
1015 const sptr<IRemoteObject> &callerToken)
1016 {
1017 ANS_LOGD("%{public}s", __FUNCTION__);
1018 if (callback == nullptr) {
1019 ANS_LOGE("callback == nullptr");
1020 return ERR_ANS_INVALID_PARAM;
1021 }
1022 sptr<NotificationBundleOption> bundleOption = GenerateBundleOption();
1023 return CommonRequestEnableNotification(deviceId, callback, callerToken, bundleOption, false);
1024 }
1025
RequestEnableNotification(const std::string bundleName,const int32_t uid)1026 ErrCode AdvancedNotificationService::RequestEnableNotification(const std::string bundleName, const int32_t uid)
1027 {
1028 ANS_LOGI("RequestEnableNotification bundleName = %{public}s uid = %{public}d", bundleName.c_str(), uid);
1029 if (!AccessTokenHelper::CheckPermission(OHOS_PERMISSION_NOTIFICATION_CONTROLLER)) {
1030 return ERR_ANS_PERMISSION_DENIED;
1031 }
1032 if (bundleName == BUNDLE_NAME_ZYT || bundleName == BUNDLE_NAME_ABROAD) {
1033 ANS_LOGI("RequestEnableNotification zyt or abroad");
1034 return ERR_ANS_NOT_ALLOWED;
1035 }
1036
1037 AppExecFwk::BundleInfo bundleInfo;
1038 BundleManagerHelper::GetInstance()->GetBundleInfoV9(bundleName, 1, bundleInfo, 0);
1039 if (bundleInfo.applicationInfo.installSource == INSTALL_SOURCE_EASYABROAD) {
1040 ANS_LOGI("RequestEnableNotification abroad app");
1041 return ERR_ANS_NOT_ALLOWED;
1042 }
1043 sptr<NotificationBundleOption> bundleOption = new (std::nothrow) NotificationBundleOption(bundleName, uid);
1044 return CommonRequestEnableNotification("", nullptr, nullptr, bundleOption, true);
1045 }
1046
CommonRequestEnableNotification(const std::string & deviceId,const sptr<AnsDialogCallback> & callback,const sptr<IRemoteObject> & callerToken,const sptr<NotificationBundleOption> bundleOption,const bool innerLake)1047 ErrCode AdvancedNotificationService::CommonRequestEnableNotification(const std::string &deviceId,
1048 const sptr<AnsDialogCallback> &callback,
1049 const sptr<IRemoteObject> &callerToken,
1050 const sptr<NotificationBundleOption> bundleOption,
1051 const bool innerLake)
1052 {
1053 ANS_LOGI("%{public}s", __FUNCTION__);
1054 ErrCode result = ERR_OK;
1055 // To get the permission
1056 bool allowedNotify = false;
1057 HaMetaMessage message = HaMetaMessage(EventSceneId::SCENE_8, EventBranchId::BRANCH_5);
1058 message.Message(bundleOption->GetBundleName() + "_" + std::to_string(bundleOption->GetUid()) +
1059 " deviceId:" + deviceId);
1060 result = IsAllowedNotifySelf(bundleOption, allowedNotify);
1061 if (result != ERR_OK) {
1062 ANS_LOGE("Not allowed notify self");
1063 message.ErrorCode(result).Append(" Allow failed");
1064 NotificationAnalyticsUtil::ReportModifyEvent(message);
1065 return ERROR_INTERNAL_ERROR;
1066 }
1067 ANS_LOGI("allowedNotify = %{public}d, bundle = %{public}s", allowedNotify,
1068 bundleOption->GetBundleName().c_str());
1069 if (allowedNotify) {
1070 message.ErrorCode(ERR_OK).Append(" Allow success");
1071 NotificationAnalyticsUtil::ReportModifyEvent(message);
1072 return ERR_OK;
1073 }
1074 // Check to see if it has been popover before
1075 bool hasPopped = false;
1076 result = GetHasPoppedDialog(bundleOption, hasPopped);
1077 if (result != ERR_OK) {
1078 ANS_LOGE("Get has popped dialog failed.");
1079 message.ErrorCode(result).Append(" Get dialog failed.");
1080 NotificationAnalyticsUtil::ReportModifyEvent(message);
1081 return ERROR_INTERNAL_ERROR;
1082 }
1083 if (hasPopped) {
1084 ANS_LOGE("Has popped is true.");
1085 message.ErrorCode(ERR_ANS_NOT_ALLOWED).Append(" Has popped");
1086 NotificationAnalyticsUtil::ReportModifyEvent(message);
1087 return ERR_ANS_NOT_ALLOWED;
1088 }
1089
1090 if (!CreateDialogManager()) {
1091 ANS_LOGE("Create dialog manager failed.");
1092 message.ErrorCode(ERR_ANS_NOT_ALLOWED).Append(" Create dialog failed");
1093 NotificationAnalyticsUtil::ReportModifyEvent(message);
1094 return ERROR_INTERNAL_ERROR;
1095 }
1096
1097 result = dialogManager_->RequestEnableNotificationDailog(bundleOption, callback, callerToken, innerLake);
1098 if (result == ERR_OK) {
1099 result = ERR_ANS_DIALOG_POP_SUCCEEDED;
1100 }
1101
1102 ANS_LOGI("%{public}s_%{public}d, deviceId: %{public}s, Request enable notification dailog result: %{public}d",
1103 bundleOption->GetBundleName().c_str(), bundleOption->GetUid(), deviceId.c_str(), result);
1104 message.ErrorCode(result);
1105 NotificationAnalyticsUtil::ReportModifyEvent(message);
1106 return result;
1107 }
1108
SetNotificationsEnabledForBundle(const std::string & deviceId,bool enabled)1109 ErrCode AdvancedNotificationService::SetNotificationsEnabledForBundle(const std::string &deviceId, bool enabled)
1110 {
1111 return ERR_INVALID_OPERATION;
1112 }
1113
SetNotificationsEnabledForAllBundles(const std::string & deviceId,bool enabled)1114 ErrCode AdvancedNotificationService::SetNotificationsEnabledForAllBundles(const std::string &deviceId, bool enabled)
1115 {
1116 ANS_LOGD("%{public}s", __FUNCTION__);
1117
1118 bool isSubsystem = AccessTokenHelper::VerifyNativeToken(IPCSkeleton::GetCallingTokenID());
1119 if (!isSubsystem && !AccessTokenHelper::IsSystemApp()) {
1120 ANS_LOGD("VerifyNativeToken and IsSystemApp is false.");
1121 return ERR_ANS_NON_SYSTEM_APP;
1122 }
1123
1124 if (!AccessTokenHelper::CheckPermission(OHOS_PERMISSION_NOTIFICATION_CONTROLLER)) {
1125 return ERR_ANS_PERMISSION_DENIED;
1126 }
1127
1128 int32_t userId = SUBSCRIBE_USER_INIT;
1129 if (OsAccountManagerHelper::GetInstance().GetCurrentActiveUserId(userId) != ERR_OK) {
1130 return ERR_ANS_GET_ACTIVE_USER_FAILED;
1131 }
1132
1133 if (notificationSvrQueue_ == nullptr) {
1134 ANS_LOGE("Serial queue is invalidity.");
1135 return ERR_ANS_INVALID_PARAM;
1136 }
1137 ErrCode result = ERR_OK;
1138 ffrt::task_handle handler = notificationSvrQueue_->submit_h(std::bind([&]() {
1139 ANS_LOGD("ffrt enter!");
1140 if (deviceId.empty()) {
1141 // Local device
1142 result = NotificationPreferences::GetInstance()->SetNotificationsEnabled(userId, enabled);
1143 } else {
1144 // Remote device
1145 }
1146 }));
1147 notificationSvrQueue_->wait(handler);
1148 return result;
1149 }
1150
SetNotificationsEnabledForSpecialBundle(const std::string & deviceId,const sptr<NotificationBundleOption> & bundleOption,bool enabled)1151 ErrCode AdvancedNotificationService::SetNotificationsEnabledForSpecialBundle(
1152 const std::string &deviceId, const sptr<NotificationBundleOption> &bundleOption, bool enabled)
1153 {
1154 HITRACE_METER_NAME(HITRACE_TAG_NOTIFICATION, __PRETTY_FUNCTION__);
1155 ANS_LOGD("%{public}s", __FUNCTION__);
1156 if (bundleOption == nullptr) {
1157 ANS_LOGE("BundleOption is null.");
1158 return ERR_ANS_INVALID_BUNDLE;
1159 }
1160
1161 HaMetaMessage message = HaMetaMessage(EventSceneId::SCENE_8, EventBranchId::BRANCH_4);
1162 message.Message(bundleOption->GetBundleName() + "_" + std::to_string(bundleOption->GetUid()) +
1163 " enabled:" + std::to_string(enabled) +
1164 " deviceId:" + deviceId);
1165 bool isSubsystem = AccessTokenHelper::VerifyNativeToken(IPCSkeleton::GetCallingTokenID());
1166 if (!isSubsystem && !AccessTokenHelper::IsSystemApp()) {
1167 ANS_LOGE("IsSystemApp is false.");
1168 message.ErrorCode(ERR_ANS_NON_SYSTEM_APP).Append(" Not SystemApp");
1169 NotificationAnalyticsUtil::ReportModifyEvent(message);
1170 return ERR_ANS_NON_SYSTEM_APP;
1171 }
1172
1173 int32_t callingUid = IPCSkeleton::GetCallingUid();
1174 if (callingUid != ANS_UID && !AccessTokenHelper::CheckPermission(OHOS_PERMISSION_NOTIFICATION_CONTROLLER)) {
1175 ANS_LOGE("Permission Denied.");
1176 message.ErrorCode(ERR_ANS_PERMISSION_DENIED).Append(" Permission Denied");
1177 NotificationAnalyticsUtil::ReportModifyEvent(message);
1178 return ERR_ANS_PERMISSION_DENIED;
1179 }
1180
1181 sptr<NotificationBundleOption> bundle = GenerateValidBundleOption(bundleOption);
1182 if (bundle == nullptr) {
1183 message.ErrorCode(ERR_ANS_INVALID_BUNDLE).Append(" Bundle is nullptr.");
1184 NotificationAnalyticsUtil::ReportModifyEvent(message);
1185 ANS_LOGE(" Bundle is nullptr.");
1186 return ERR_ANS_INVALID_BUNDLE;
1187 }
1188
1189 sptr<EnabledNotificationCallbackData> bundleData = new (std::nothrow)
1190 EnabledNotificationCallbackData(bundle->GetBundleName(), bundle->GetUid(), enabled);
1191 if (bundleData == nullptr) {
1192 ANS_LOGE("Failed to create EnabledNotificationCallbackData instance");
1193 return ERR_NO_MEMORY;
1194 }
1195
1196 ErrCode result = ERR_OK;
1197 if (deviceId.empty()) {
1198 // Local device
1199 result = NotificationPreferences::GetInstance()->SetNotificationsEnabledForBundle(bundle, enabled);
1200 if (result == ERR_OK) {
1201 if (!enabled) {
1202 result = RemoveAllNotificationsForDisable(bundle);
1203 }
1204 SetSlotFlagsTrustlistsAsBundle(bundle);
1205 NotificationSubscriberManager::GetInstance()->NotifyEnabledNotificationChanged(bundleData);
1206 PublishSlotChangeCommonEvent(bundle);
1207 }
1208 } else {
1209 // Remote device
1210 }
1211
1212 ANS_LOGI("%{public}s_%{public}d, deviceId: %{public}s, enable: %{public}s, "
1213 "Set notifications enabled for special bundle result: %{public}d", bundleOption->GetBundleName().c_str(),
1214 bundleOption->GetUid(), deviceId.c_str(), std::to_string(enabled).c_str(), result);
1215 message.ErrorCode(result);
1216 NotificationAnalyticsUtil::ReportModifyEvent(message);
1217 SendEnableNotificationHiSysEvent(bundleOption, enabled, result);
1218 return result;
1219 }
1220
IsAllowedNotify(bool & allowed)1221 ErrCode AdvancedNotificationService::IsAllowedNotify(bool &allowed)
1222 {
1223 ANS_LOGD("%{public}s", __FUNCTION__);
1224
1225 bool isSubsystem = AccessTokenHelper::VerifyNativeToken(IPCSkeleton::GetCallingTokenID());
1226 if (!isSubsystem && !AccessTokenHelper::IsSystemApp()) {
1227 return ERR_ANS_NON_SYSTEM_APP;
1228 }
1229
1230 if (!AccessTokenHelper::CheckPermission(OHOS_PERMISSION_NOTIFICATION_CONTROLLER)) {
1231 ANS_LOGD("AccessTokenHelper::CheckPermission is false");
1232 return ERR_ANS_PERMISSION_DENIED;
1233 }
1234
1235 int32_t userId = SUBSCRIBE_USER_INIT;
1236 if (OsAccountManagerHelper::GetInstance().GetCurrentActiveUserId(userId) != ERR_OK) {
1237 return ERR_ANS_GET_ACTIVE_USER_FAILED;
1238 }
1239
1240 if (notificationSvrQueue_ == nullptr) {
1241 ANS_LOGE("Serial queue is invalid.");
1242 return ERR_ANS_INVALID_PARAM;
1243 }
1244 ErrCode result = ERR_OK;
1245 ffrt::task_handle handler = notificationSvrQueue_->submit_h(std::bind([&]() {
1246 ANS_LOGD("ffrt enter!");
1247 allowed = false;
1248 result = NotificationPreferences::GetInstance()->GetNotificationsEnabled(userId, allowed);
1249 }));
1250 notificationSvrQueue_->wait(handler);
1251 return result;
1252 }
1253
IsAllowedNotifySelf(bool & allowed)1254 ErrCode AdvancedNotificationService::IsAllowedNotifySelf(bool &allowed)
1255 {
1256 ANS_LOGD("%{public}s", __FUNCTION__);
1257
1258 sptr<NotificationBundleOption> bundleOption = GenerateBundleOption();
1259 if (bundleOption == nullptr) {
1260 return ERR_ANS_INVALID_BUNDLE;
1261 }
1262 return IsAllowedNotifySelf(bundleOption, allowed);
1263 }
1264
CanPopEnableNotificationDialog(const sptr<AnsDialogCallback> & callback,bool & canPop,std::string & bundleName)1265 ErrCode AdvancedNotificationService::CanPopEnableNotificationDialog(
1266 const sptr<AnsDialogCallback> &callback, bool &canPop, std::string &bundleName)
1267 {
1268 ANS_LOGD("%{public}s", __FUNCTION__);
1269 canPop = false;
1270 ErrCode result = ERR_OK;
1271 sptr<NotificationBundleOption> bundleOption = GenerateBundleOption();
1272 if (bundleOption == nullptr) {
1273 ANS_LOGE("bundleOption is nullptr.");
1274 return ERR_ANS_INVALID_BUNDLE;
1275 }
1276 // To get the permission
1277 bool allowedNotify = false;
1278 HaMetaMessage message = HaMetaMessage(EventSceneId::SCENE_2, EventBranchId::BRANCH_2);
1279 message.Message(bundleOption->GetBundleName() + "_" + std::to_string(bundleOption->GetUid()) +
1280 " canPop:" + std::to_string(canPop));
1281 result = IsAllowedNotifySelf(bundleOption, allowedNotify);
1282 if (result != ERR_OK) {
1283 ANS_LOGE("Not allowed Notify self.");
1284 message.ErrorCode(result).Append(" Not Allow");
1285 NotificationAnalyticsUtil::ReportModifyEvent(message);
1286 return ERROR_INTERNAL_ERROR;
1287 }
1288 ANS_LOGI("allowedNotify = %{public}d, bundle = %{public}s", allowedNotify,
1289 bundleOption->GetBundleName().c_str());
1290 if (allowedNotify) {
1291 message.ErrorCode(ERR_OK).Append(" Allow success");
1292 NotificationAnalyticsUtil::ReportModifyEvent(message);
1293 return ERR_OK;
1294 }
1295 // Check to see if it has been popover before
1296 bool hasPopped = false;
1297 result = GetHasPoppedDialog(bundleOption, hasPopped);
1298 if (result != ERR_OK) {
1299 ANS_LOGE("Get has popped dialog failed. result: %{public}d", result);
1300 message.ErrorCode(result).Append(" Has popped");
1301 NotificationAnalyticsUtil::ReportModifyEvent(message);
1302 return ERROR_INTERNAL_ERROR;
1303 }
1304 if (hasPopped) {
1305 ANS_LOGE("Has popped is true.");
1306 message.ErrorCode(ERR_ANS_NOT_ALLOWED).Append(" Haspopped true");
1307 NotificationAnalyticsUtil::ReportModifyEvent(message);
1308 return ERR_ANS_NOT_ALLOWED;
1309 }
1310
1311 if (!CreateDialogManager()) {
1312 ANS_LOGE("Create dialog manager failed.");
1313 message.ErrorCode(ERR_ANS_NOT_ALLOWED).Append(" Create dialog failed");
1314 NotificationAnalyticsUtil::ReportModifyEvent(message);
1315 return ERROR_INTERNAL_ERROR;
1316 }
1317 result = dialogManager_->AddDialogInfo(bundleOption, callback);
1318 if (result != ERR_OK) {
1319 ANS_LOGI("AddDialogInfo result: %{public}d", result);
1320 message.ErrorCode(result).Append(" AddDialogInfo");
1321 NotificationAnalyticsUtil::ReportModifyEvent(message);
1322 return result;
1323 }
1324
1325 canPop = true;
1326 bundleName = bundleOption->GetBundleName();
1327 ANS_LOGI("%{public}s_%{public}d, canPop: %{public}s, CanPopEnableNotificationDialog result: %{public}d",
1328 bundleOption->GetBundleName().c_str(), bundleOption->GetUid(), std::to_string(canPop).c_str(), result);
1329 message.ErrorCode(result).Append(" CanPopEnableNotificationDialog end");
1330 NotificationAnalyticsUtil::ReportModifyEvent(message);
1331 return ERR_OK;
1332 }
1333
RemoveEnableNotificationDialog()1334 ErrCode AdvancedNotificationService::RemoveEnableNotificationDialog()
1335 {
1336 ANS_LOGD("%{public}s", __FUNCTION__);
1337 ErrCode result = ERR_OK;
1338 sptr<NotificationBundleOption> bundleOption = GenerateBundleOption();
1339 if (bundleOption == nullptr) {
1340 ANS_LOGE("bundleOption == nullptr");
1341 return ERR_ANS_INVALID_BUNDLE;
1342 }
1343 return RemoveEnableNotificationDialog(bundleOption);
1344 }
1345
RemoveEnableNotificationDialog(const sptr<NotificationBundleOption> & bundleOption)1346 ErrCode AdvancedNotificationService::RemoveEnableNotificationDialog(const sptr<NotificationBundleOption> &bundleOption)
1347 {
1348 ANS_LOGI("RemoveEnableNotificationDialog %{public}s, %{public}d",
1349 bundleOption->GetBundleName().c_str(),
1350 bundleOption->GetUid());
1351 if (!CreateDialogManager()) {
1352 return ERROR_INTERNAL_ERROR;
1353 }
1354 std::unique_ptr<NotificationDialogManager::DialogInfo> dialogInfoRemoved = nullptr;
1355 dialogManager_->RemoveDialogInfoByBundleOption(bundleOption, dialogInfoRemoved);
1356 return ERR_OK;
1357 }
1358
IsAllowedNotifySelf(const sptr<NotificationBundleOption> & bundleOption,bool & allowed)1359 ErrCode AdvancedNotificationService::IsAllowedNotifySelf(const sptr<NotificationBundleOption> &bundleOption,
1360 bool &allowed)
1361 {
1362 ANS_LOGD("%{public}s", __FUNCTION__);
1363 if (bundleOption == nullptr) {
1364 return ERR_ANS_INVALID_BUNDLE;
1365 }
1366
1367 int32_t userId = SUBSCRIBE_USER_INIT;
1368 if (OsAccountManagerHelper::GetInstance().GetCurrentActiveUserId(userId) != ERR_OK) {
1369 ANS_LOGD("GetActiveUserId is false");
1370 return ERR_ANS_GET_ACTIVE_USER_FAILED;
1371 }
1372
1373 ErrCode result = ERR_OK;
1374 allowed = false;
1375 result = NotificationPreferences::GetInstance()->GetNotificationsEnabled(userId, allowed);
1376 if (result == ERR_OK && allowed) {
1377 result = NotificationPreferences::GetInstance()->GetNotificationsEnabledForBundle(bundleOption, allowed);
1378 if (result == ERR_ANS_PREFERENCES_NOTIFICATION_BUNDLE_NOT_EXIST) {
1379 result = ERR_OK;
1380 // FA model app can publish notification without user confirm
1381 allowed = CheckApiCompatibility(bundleOption);
1382 SetDefaultNotificationEnabled(bundleOption, allowed);
1383 }
1384 }
1385 return result;
1386 }
1387
IsAllowedNotifyForBundle(const sptr<NotificationBundleOption> & bundleOption,bool & allowed)1388 ErrCode AdvancedNotificationService::IsAllowedNotifyForBundle(const sptr<NotificationBundleOption>
1389 &bundleOption, bool &allowed)
1390 {
1391 ANS_LOGD("%{public}s", __FUNCTION__);
1392 if (bundleOption == nullptr) {
1393 return ERR_ANS_INVALID_BUNDLE;
1394 }
1395
1396 int32_t userId = SUBSCRIBE_USER_INIT;
1397 if (OsAccountManagerHelper::GetInstance().GetCurrentActiveUserId(userId) != ERR_OK) {
1398 ANS_LOGD("GetActiveUserId is false");
1399 return ERR_ANS_GET_ACTIVE_USER_FAILED;
1400 }
1401
1402 ErrCode result = ERR_OK;
1403 allowed = false;
1404 result = NotificationPreferences::GetInstance()->GetNotificationsEnabled(userId, allowed);
1405 if (result == ERR_OK && allowed) {
1406 result = NotificationPreferences::GetInstance()->GetNotificationsEnabledForBundle(bundleOption, allowed);
1407 if (result == ERR_ANS_PREFERENCES_NOTIFICATION_BUNDLE_NOT_EXIST) {
1408 result = ERR_OK;
1409 // FA model app can publish notification without user confirm
1410 allowed = CheckApiCompatibility(bundleOption);
1411 }
1412 }
1413 return result;
1414 }
1415
IsSpecialBundleAllowedNotify(const sptr<NotificationBundleOption> & bundleOption,bool & allowed)1416 ErrCode AdvancedNotificationService::IsSpecialBundleAllowedNotify(
1417 const sptr<NotificationBundleOption> &bundleOption, bool &allowed)
1418 {
1419 ANS_LOGD("%{public}s", __FUNCTION__);
1420
1421 bool isSubsystem = AccessTokenHelper::VerifyNativeToken(IPCSkeleton::GetCallingTokenID());
1422 if (!isSubsystem && !AccessTokenHelper::IsSystemApp()) {
1423 ANS_LOGE("Not system application");
1424 return ERR_ANS_NON_SYSTEM_APP;
1425 }
1426
1427 int32_t callingUid = IPCSkeleton::GetCallingUid();
1428 if (callingUid != ANS_UID && !AccessTokenHelper::CheckPermission(OHOS_PERMISSION_NOTIFICATION_CONTROLLER)) {
1429 return ERR_ANS_PERMISSION_DENIED;
1430 }
1431
1432 sptr<NotificationBundleOption> targetBundle = nullptr;
1433 if (isSubsystem) {
1434 if (bundleOption != nullptr) {
1435 targetBundle = GenerateValidBundleOption(bundleOption);
1436 }
1437 } else {
1438 ErrCode result = GetAppTargetBundle(bundleOption, targetBundle);
1439 if (result != ERR_OK) {
1440 return result;
1441 }
1442 }
1443
1444 if (targetBundle == nullptr) {
1445 return ERR_ANS_INVALID_BUNDLE;
1446 }
1447
1448 int32_t userId = SUBSCRIBE_USER_INIT;
1449 if (OsAccountManagerHelper::GetInstance().GetCurrentActiveUserId(userId) != ERR_OK) {
1450 return ERR_ANS_GET_ACTIVE_USER_FAILED;
1451 }
1452
1453 ErrCode result = ERR_OK;
1454 allowed = false;
1455 result = NotificationPreferences::GetInstance()->GetNotificationsEnabled(userId, allowed);
1456 if (result == ERR_OK && allowed) {
1457 result = NotificationPreferences::GetInstance()->GetNotificationsEnabledForBundle(targetBundle, allowed);
1458 if (result == ERR_ANS_PREFERENCES_NOTIFICATION_BUNDLE_NOT_EXIST) {
1459 result = ERR_OK;
1460 allowed = CheckApiCompatibility(targetBundle);
1461 SetNotificationsEnabledForSpecialBundle("", bundleOption, allowed);
1462 }
1463 }
1464 return result;
1465 }
1466
PublishContinuousTaskNotification(const sptr<NotificationRequest> & request)1467 ErrCode AdvancedNotificationService::PublishContinuousTaskNotification(const sptr<NotificationRequest> &request)
1468 {
1469 ANS_LOGD("%{public}s", __FUNCTION__);
1470
1471 bool isSubsystem = AccessTokenHelper::VerifyNativeToken(IPCSkeleton::GetCallingTokenID());
1472 if (!isSubsystem) {
1473 return ERR_ANS_NOT_SYSTEM_SERVICE;
1474 }
1475
1476 int32_t uid = IPCSkeleton::GetCallingUid();
1477 int32_t userId = SUBSCRIBE_USER_INIT;
1478 OHOS::AccountSA::OsAccountManager::GetOsAccountLocalIdFromUid(uid, userId);
1479 request->SetCreatorUserId(userId);
1480 ANS_LOGD("%{public}s, uid=%{public}d userId=%{public}d", __FUNCTION__, uid, userId);
1481
1482 if (request->GetCreatorBundleName().empty()) {
1483 request->SetCreatorBundleName(FOUNDATION_BUNDLE_NAME);
1484 }
1485
1486 if (request->GetOwnerBundleName().empty()) {
1487 request->SetOwnerBundleName(FOUNDATION_BUNDLE_NAME);
1488 }
1489
1490 sptr<NotificationBundleOption> bundleOption = nullptr;
1491 bundleOption = new (std::nothrow) NotificationBundleOption(std::string(), uid);
1492 if (bundleOption == nullptr) {
1493 ANS_LOGE("Failed to create NotificationBundleOption instance");
1494 return ERR_NO_MEMORY;
1495 }
1496
1497 ErrCode result = PrepareContinuousTaskNotificationRequest(request, uid);
1498 if (result != ERR_OK) {
1499 return result;
1500 }
1501 request->SetUnremovable(true);
1502 std::shared_ptr<NotificationRecord> record = std::make_shared<NotificationRecord>();
1503 record->request = request;
1504 record->bundleOption = bundleOption;
1505 record->notification = new (std::nothrow) Notification(request);
1506 if (record->notification == nullptr) {
1507 ANS_LOGE("Failed to create Notification instance");
1508 return ERR_NO_MEMORY;
1509 }
1510 record->notification->SetSourceType(NotificationConstant::SourceType::TYPE_CONTINUOUS);
1511
1512 if (notificationSvrQueue_ == nullptr) {
1513 ANS_LOGE("Serial queue is invalid.");
1514 return ERR_ANS_INVALID_PARAM;
1515 }
1516 ffrt::task_handle handler = notificationSvrQueue_->submit_h(std::bind([&]() {
1517 ANS_LOGD("ffrt enter!");
1518 if (!IsNotificationExists(record->notification->GetKey())) {
1519 AddToNotificationList(record);
1520 } else {
1521 if (record->request->IsAlertOneTime()) {
1522 CloseAlert(record);
1523 }
1524 UpdateInNotificationList(record);
1525 }
1526
1527 UpdateRecentNotification(record->notification, false, 0);
1528 sptr<NotificationSortingMap> sortingMap = GenerateSortingMap();
1529 NotificationSubscriberManager::GetInstance()->NotifyConsumed(record->notification, sortingMap);
1530 }));
1531 notificationSvrQueue_->wait(handler);
1532
1533 return result;
1534 }
1535
CancelContinuousTaskNotification(const std::string & label,int32_t notificationId)1536 ErrCode AdvancedNotificationService::CancelContinuousTaskNotification(const std::string &label, int32_t notificationId)
1537 {
1538 ANS_LOGD("%{public}s", __FUNCTION__);
1539
1540 bool isSubsystem = AccessTokenHelper::VerifyNativeToken(IPCSkeleton::GetCallingTokenID());
1541 if (!isSubsystem) {
1542 return ERR_ANS_NOT_SYSTEM_SERVICE;
1543 }
1544
1545 if (notificationSvrQueue_ == nullptr) {
1546 ANS_LOGE("Serial queue is invalid.");
1547 return ERR_ANS_INVALID_PARAM;
1548 }
1549 int32_t uid = IPCSkeleton::GetCallingUid();
1550 ErrCode result = ERR_OK;
1551 ffrt::task_handle handler = notificationSvrQueue_->submit_h(std::bind([&]() {
1552 ANS_LOGD("ffrt enter!");
1553 sptr<Notification> notification = nullptr;
1554 for (auto record : notificationList_) {
1555 if ((record->bundleOption->GetBundleName().empty()) && (record->bundleOption->GetUid() == uid) &&
1556 (record->notification->GetId() == notificationId) && (record->notification->GetLabel() == label)) {
1557 notification = record->notification;
1558 notificationList_.remove(record);
1559 result = ERR_OK;
1560 break;
1561 }
1562 }
1563 if (notification != nullptr) {
1564 int32_t reason = NotificationConstant::APP_CANCEL_REASON_DELETE;
1565 UpdateRecentNotification(notification, true, reason);
1566 CancelTimer(notification->GetAutoDeletedTimer());
1567 NotificationSubscriberManager::GetInstance()->NotifyCanceled(notification, nullptr, reason);
1568 }
1569 }));
1570 notificationSvrQueue_->wait(handler);
1571 return result;
1572 }
1573
RemoveSystemLiveViewNotifications(const std::string & bundleName,const int32_t uid)1574 ErrCode AdvancedNotificationService::RemoveSystemLiveViewNotifications(
1575 const std::string& bundleName, const int32_t uid)
1576 {
1577 std::vector<std::shared_ptr<NotificationRecord>> recordList;
1578 if (notificationSvrQueue_ == nullptr) {
1579 ANS_LOGE("NotificationSvrQueue is nullptr");
1580 return ERR_ANS_INVALID_PARAM;
1581 }
1582 ErrCode result = ERR_OK;
1583 ffrt::task_handle handler = notificationSvrQueue_->submit_h(std::bind([&]() {
1584 LivePublishProcess::GetInstance()->EraseLiveViewSubsciber(uid);
1585 GetTargetRecordList(uid, NotificationConstant::SlotType::LIVE_VIEW,
1586 NotificationContent::Type::LOCAL_LIVE_VIEW, recordList);
1587 GetCommonTargetRecordList(uid, NotificationConstant::SlotType::LIVE_VIEW,
1588 NotificationContent::Type::LIVE_VIEW, recordList);
1589 if (recordList.size() == 0) {
1590 ANS_LOGE("Get Target record list fail.");
1591 result = ERR_ANS_NOTIFICATION_NOT_EXISTS;
1592 return;
1593 }
1594 result = RemoveNotificationFromRecordList(recordList);
1595 }));
1596 notificationSvrQueue_->wait(handler);
1597 return result;
1598 }
1599
RemoveSystemLiveViewNotificationsOfSa(int32_t uid)1600 ErrCode AdvancedNotificationService::RemoveSystemLiveViewNotificationsOfSa(int32_t uid)
1601 {
1602 {
1603 std::lock_guard<std::mutex> lock(delayNotificationMutext_);
1604 for (auto iter = delayNotificationList_.begin(); iter != delayNotificationList_.end();) {
1605 if ((*iter).first->notification->GetNotificationRequest().GetCreatorUid() == uid &&
1606 (*iter).first->notification->GetNotificationRequest().IsInProgress()) {
1607 CancelTimer((*iter).second);
1608 iter = delayNotificationList_.erase(iter);
1609 } else {
1610 iter++;
1611 }
1612 }
1613 }
1614
1615 ErrCode result = ERR_OK;
1616 ffrt::task_handle handler = notificationSvrQueue_->submit_h(std::bind([&]() {
1617 LivePublishProcess::GetInstance()->EraseLiveViewSubsciber(uid);
1618 std::vector<std::shared_ptr<NotificationRecord>> recordList;
1619 for (auto item : notificationList_) {
1620 if (item->notification->GetNotificationRequest().GetCreatorUid() == uid &&
1621 item->notification->GetNotificationRequest().IsInProgress()) {
1622 recordList.emplace_back(item);
1623 }
1624 }
1625 if (!recordList.empty()) {
1626 result = RemoveNotificationFromRecordList(recordList);
1627 }
1628 }));
1629 notificationSvrQueue_->wait(handler);
1630 return result;
1631 }
1632
TriggerLocalLiveView(const sptr<NotificationBundleOption> & bundleOption,const int32_t notificationId,const sptr<NotificationButtonOption> & buttonOption)1633 ErrCode AdvancedNotificationService::TriggerLocalLiveView(const sptr<NotificationBundleOption> &bundleOption,
1634 const int32_t notificationId, const sptr<NotificationButtonOption> &buttonOption)
1635 {
1636 HITRACE_METER_NAME(HITRACE_TAG_NOTIFICATION, __PRETTY_FUNCTION__);
1637 ANS_LOGD("%{public}s", __FUNCTION__);
1638
1639 bool isSubsystem = AccessTokenHelper::VerifyNativeToken(IPCSkeleton::GetCallingTokenID());
1640 if (!isSubsystem && !AccessTokenHelper::IsSystemApp()) {
1641 return ERR_ANS_NON_SYSTEM_APP;
1642 }
1643
1644 if (!AccessTokenHelper::CheckPermission(OHOS_PERMISSION_NOTIFICATION_CONTROLLER)) {
1645 ANS_LOGD("AccessTokenHelper::CheckPermission is bogus.");
1646 return ERR_ANS_PERMISSION_DENIED;
1647 }
1648
1649 sptr<NotificationBundleOption> bundle = GenerateValidBundleOption(bundleOption);
1650 if (bundle == nullptr) {
1651 return ERR_ANS_INVALID_BUNDLE;
1652 }
1653
1654 ErrCode result = ERR_ANS_NOTIFICATION_NOT_EXISTS;
1655 ffrt::task_handle handler = notificationSvrQueue_->submit_h(std::bind([&]() {
1656 ANS_LOGD("ffrt enter!");
1657 sptr<Notification> notification = nullptr;
1658
1659 for (auto record : notificationList_) {
1660 if (record->request->GetAgentBundle() != nullptr) {
1661 if ((record->request->GetAgentBundle()->GetBundleName() == bundle->GetBundleName()) &&
1662 (record->request->GetAgentBundle()->GetUid() == bundle->GetUid()) &&
1663 (record->notification->GetId() == notificationId)) {
1664 notification = record->notification;
1665 result = ERR_OK;
1666 break;
1667 }
1668 } else {
1669 if ((record->bundleOption->GetBundleName() == bundle->GetBundleName()) &&
1670 (record->bundleOption->GetUid() == bundle->GetUid()) &&
1671 (record->notification->GetId() == notificationId)) {
1672 notification = record->notification;
1673 result = ERR_OK;
1674 break;
1675 }
1676 }
1677 }
1678
1679 if (notification != nullptr) {
1680 NotificationLocalLiveViewSubscriberManager::GetInstance()->NotifyTriggerResponse(notification,
1681 buttonOption);
1682 }
1683 }));
1684 notificationSvrQueue_->wait(handler);
1685 return result;
1686 }
1687
RemoveNotification(const sptr<NotificationBundleOption> & bundleOption,int32_t notificationId,const std::string & label,int32_t removeReason)1688 ErrCode AdvancedNotificationService::RemoveNotification(const sptr<NotificationBundleOption> &bundleOption,
1689 int32_t notificationId, const std::string &label, int32_t removeReason)
1690 {
1691 HITRACE_METER_NAME(HITRACE_TAG_NOTIFICATION, __PRETTY_FUNCTION__);
1692 ANS_LOGD("%{public}s", __FUNCTION__);
1693
1694 bool isSubsystem = AccessTokenHelper::VerifyNativeToken(IPCSkeleton::GetCallingTokenID());
1695 if (!isSubsystem && !AccessTokenHelper::IsSystemApp()) {
1696 std::string message = "not systemApp.";
1697 OHOS::Notification::HaMetaMessage haMetaMessage = HaMetaMessage(4, 4)
1698 .ErrorCode(ERR_ANS_NON_SYSTEM_APP).NotificationId(notificationId);
1699 ReportDeleteFailedEventPush(haMetaMessage, removeReason, message);
1700 ANS_LOGE("%{public}s", message.c_str());
1701 return ERR_ANS_NON_SYSTEM_APP;
1702 }
1703
1704 if (!AccessTokenHelper::CheckPermission(OHOS_PERMISSION_NOTIFICATION_CONTROLLER)) {
1705 std::string message = "no acl controller permission.";
1706 OHOS::Notification::HaMetaMessage haMetaMessage = HaMetaMessage(4, 5)
1707 .ErrorCode(ERR_ANS_PERMISSION_DENIED).NotificationId(notificationId);
1708 ReportDeleteFailedEventPush(haMetaMessage, removeReason, message);
1709 ANS_LOGE("%{public}s", message.c_str());
1710 return ERR_ANS_PERMISSION_DENIED;
1711 }
1712
1713 sptr<NotificationBundleOption> bundle = GenerateValidBundleOption(bundleOption);
1714 if (bundle == nullptr) {
1715 return ERR_ANS_INVALID_BUNDLE;
1716 }
1717
1718 if (notificationSvrQueue_ == nullptr) {
1719 std::string message = "NotificationSvrQueue_ is null.";
1720 ANS_LOGE("%{public}s", message.c_str());
1721 return ERR_ANS_INVALID_PARAM;
1722 }
1723 ErrCode result = ERR_ANS_NOTIFICATION_NOT_EXISTS;
1724 ffrt::task_handle handler = notificationSvrQueue_->submit_h(std::bind([&]() {
1725 ANS_LOGD("ffrt enter!");
1726 bool isThirdParty = true;
1727 sptr<Notification> notification = nullptr;
1728 sptr<NotificationRequest> notificationRequest = nullptr;
1729
1730 #ifdef DISTRIBUTED_NOTIFICATION_SUPPORTED
1731 std::string deviceId;
1732 std::string bundleName;
1733 #endif
1734 for (auto record : notificationList_) {
1735 if ((record->bundleOption->GetBundleName() == bundle->GetBundleName()) &&
1736 (record->bundleOption->GetUid() == bundle->GetUid()) &&
1737 #ifdef DISTRIBUTED_NOTIFICATION_SUPPORTED
1738 (record->deviceId.empty()) &&
1739 #endif
1740 (record->notification->GetId() == notificationId) && (record->notification->GetLabel() == label)) {
1741 if (!record->notification->IsRemoveAllowed()) {
1742 result = ERR_ANS_NOTIFICATION_IS_UNALLOWED_REMOVEALLOWED;
1743 break;
1744 }
1745 #ifdef DISTRIBUTED_NOTIFICATION_SUPPORTED
1746 deviceId = record->deviceId;
1747 bundleName = record->bundleName;
1748 #endif
1749 notification = record->notification;
1750 notificationRequest = record->request;
1751 isThirdParty = record->isThirdparty;
1752
1753 if (removeReason != NotificationConstant::CLICK_REASON_DELETE) {
1754 ProcForDeleteLiveView(record);
1755 }
1756
1757 notificationList_.remove(record);
1758 result = ERR_OK;
1759 break;
1760 }
1761 }
1762
1763 if (notification != nullptr) {
1764 UpdateRecentNotification(notification, true, removeReason);
1765 CancelTimer(notification->GetAutoDeletedTimer());
1766 NotificationSubscriberManager::GetInstance()->NotifyCanceled(notification, nullptr, removeReason);
1767 #ifdef DISTRIBUTED_NOTIFICATION_SUPPORTED
1768 DoDistributedDelete(deviceId, bundleName, notification);
1769 #endif
1770 }
1771 if (removeReason != NotificationConstant::CLICK_REASON_DELETE) {
1772 TriggerRemoveWantAgent(notificationRequest, removeReason, isThirdParty);
1773 }
1774 }));
1775 notificationSvrQueue_->wait(handler);
1776 if (result != ERR_OK) {
1777 std::string message = "remove notificaiton error";
1778 ANS_LOGE("%{public}s", message.c_str());
1779 }
1780 SendRemoveHiSysEvent(notificationId, label, bundleOption, result);
1781 return result;
1782 }
1783
RemoveAllNotificationsForDisable(const sptr<NotificationBundleOption> & bundleOption)1784 ErrCode AdvancedNotificationService::RemoveAllNotificationsForDisable(
1785 const sptr<NotificationBundleOption> &bundleOption)
1786 {
1787 return RemoveAllNotificationsInner(bundleOption, NotificationConstant::DISABLE_NOTIFICATION_REASON_DELETE);
1788 }
1789
RemoveAllNotifications(const sptr<NotificationBundleOption> & bundleOption)1790 ErrCode AdvancedNotificationService::RemoveAllNotifications(const sptr<NotificationBundleOption> &bundleOption)
1791 {
1792 return RemoveAllNotificationsInner(bundleOption, NotificationConstant::APP_REMOVE_ALL_REASON_DELETE);
1793 }
1794
RemoveAllNotificationsInner(const sptr<NotificationBundleOption> & bundleOption,int32_t reason)1795 ErrCode AdvancedNotificationService::RemoveAllNotificationsInner(const sptr<NotificationBundleOption> &bundleOption,
1796 int32_t reason)
1797 {
1798 HITRACE_METER_NAME(HITRACE_TAG_NOTIFICATION, __PRETTY_FUNCTION__);
1799 ANS_LOGD("%{public}s", __FUNCTION__);
1800
1801 bool isSubsystem = AccessTokenHelper::VerifyNativeToken(IPCSkeleton::GetCallingTokenID());
1802 if (!isSubsystem && !AccessTokenHelper::IsSystemApp()) {
1803 std::string message = "not system app.";
1804 OHOS::Notification::HaMetaMessage haMetaMessage = HaMetaMessage(6, 1)
1805 .ErrorCode(ERR_ANS_NON_SYSTEM_APP);
1806 ReportDeleteFailedEventPush(haMetaMessage, reason, message);
1807 ANS_LOGE("%{public}s", message.c_str());
1808 return ERR_ANS_NON_SYSTEM_APP;
1809 }
1810
1811 int32_t callingUid = IPCSkeleton::GetCallingUid();
1812 if (callingUid != ANS_UID && !AccessTokenHelper::CheckPermission(OHOS_PERMISSION_NOTIFICATION_CONTROLLER)) {
1813 std::string message = "no acl permission.";
1814 OHOS::Notification::HaMetaMessage haMetaMessage = HaMetaMessage(6, 2)
1815 .ErrorCode(ERR_ANS_PERMISSION_DENIED);
1816 ReportDeleteFailedEventPush(haMetaMessage, reason, message);
1817 ANS_LOGE("%{public}s", message.c_str());
1818 return ERR_ANS_PERMISSION_DENIED;
1819 }
1820
1821 sptr<NotificationBundleOption> bundle = GenerateValidBundleOption(bundleOption);
1822 if (bundle == nullptr) {
1823 std::string message = "budle is nullptr.";
1824 OHOS::Notification::HaMetaMessage haMetaMessage = HaMetaMessage(6, 3)
1825 .ErrorCode(ERR_ANS_INVALID_BUNDLE);
1826 ReportDeleteFailedEventPush(haMetaMessage, reason, message);
1827 ANS_LOGE("%{public}s", message.c_str());
1828 return ERR_ANS_INVALID_BUNDLE;
1829 }
1830
1831 if (notificationSvrQueue_ == nullptr) {
1832 std::string message = "Serial queue is nullptr.";
1833 ANS_LOGE("%{public}s", message.c_str());
1834 return ERR_ANS_INVALID_PARAM;
1835 }
1836 ffrt::task_handle handler = notificationSvrQueue_->submit_h(std::bind([&]() {
1837 std::vector<std::shared_ptr<NotificationRecord>> removeList;
1838 ANS_LOGD("ffrt enter!");
1839 for (auto record : notificationList_) {
1840 bool isAllowedNotification = true;
1841 if (IsAllowedNotifyForBundle(bundleOption, isAllowedNotification) != ERR_OK) {
1842 ANSR_LOGW("The application does not request enable notification.");
1843 }
1844 if (!record->notification->IsRemoveAllowed() && isAllowedNotification) {
1845 ANS_LOGI("BatchRemove-FILTER-RemoveNotAllowed-%{public}s", record->notification->GetKey().c_str());
1846 continue;
1847 }
1848 if (record->slot != nullptr) {
1849 if (record->slot->GetForceControl() && record->slot->GetEnable()) {
1850 ANS_LOGI("BatchRemove-FILTER-ForceControl-%{public}s", record->notification->GetKey().c_str());
1851 continue;
1852 }
1853 }
1854 if ((record->bundleOption->GetBundleName() == bundle->GetBundleName()) &&
1855 (record->bundleOption->GetUid() == bundle->GetUid())
1856 #ifdef DISTRIBUTED_NOTIFICATION_SUPPORTED
1857 && record->deviceId.empty()
1858 #endif
1859 ) {
1860 auto notificationRequest = record->request;
1861 if (!BundleManagerHelper::GetInstance()->IsSystemApp(bundle->GetUid()) &&
1862 notificationRequest->IsSystemLiveView()) {
1863 auto localLiveviewContent = std::static_pointer_cast<NotificationLocalLiveViewContent>(
1864 notificationRequest->GetContent()->GetNotificationContent());
1865 if (localLiveviewContent->GetType() == 0) {
1866 continue;
1867 }
1868 }
1869 ProcForDeleteLiveView(record);
1870 removeList.push_back(record);
1871 }
1872 }
1873
1874 std::vector<sptr<Notification>> notifications;
1875 std::vector<uint64_t> timerIds;
1876 for (auto record : removeList) {
1877 notificationList_.remove(record);
1878 if (record->notification != nullptr) {
1879 ANS_LOGD("record->notification is not nullptr.");
1880 UpdateRecentNotification(record->notification, true, reason);
1881 notifications.emplace_back(record->notification);
1882 timerIds.emplace_back(record->notification->GetAutoDeletedTimer());
1883 #ifdef DISTRIBUTED_NOTIFICATION_SUPPORTED
1884 DoDistributedDelete(record->deviceId, record->bundleName, record->notification);
1885 #endif
1886 }
1887 if (notifications.size() >= MAX_CANCELED_PARCELABLE_VECTOR_NUM) {
1888 SendNotificationsOnCanceled(notifications, nullptr, reason);
1889 }
1890
1891 TriggerRemoveWantAgent(record->request, reason, record->isThirdparty);
1892 }
1893
1894 if (!notifications.empty()) {
1895 NotificationSubscriberManager::GetInstance()->BatchNotifyCanceled(notifications, nullptr, reason);
1896 }
1897 BatchCancelTimer(timerIds);
1898 }));
1899 notificationSvrQueue_->wait(handler);
1900
1901 return ERR_OK;
1902 }
1903
RemoveNotifications(const std::vector<std::string> & keys,int32_t removeReason)1904 ErrCode AdvancedNotificationService::RemoveNotifications(
1905 const std::vector<std::string> &keys, int32_t removeReason)
1906 {
1907 HITRACE_METER_NAME(HITRACE_TAG_NOTIFICATION, __PRETTY_FUNCTION__);
1908 ANS_LOGD("enter");
1909
1910 bool isSubsystem = AccessTokenHelper::VerifyNativeToken(IPCSkeleton::GetCallingTokenID());
1911 if (!isSubsystem && !AccessTokenHelper::IsSystemApp()) {
1912 return ERR_ANS_NON_SYSTEM_APP;
1913 }
1914 if (!AccessTokenHelper::CheckPermission(OHOS_PERMISSION_NOTIFICATION_CONTROLLER)) {
1915 return ERR_ANS_PERMISSION_DENIED;
1916 }
1917 if (notificationSvrQueue_ == nullptr) {
1918 ANS_LOGE("NotificationSvrQueue is nullptr.");
1919 return ERR_ANS_INVALID_PARAM;
1920 }
1921 ffrt::task_handle handler = notificationSvrQueue_->submit_h(std::bind([&]() {
1922 std::vector<sptr<Notification>> notifications;
1923 std::vector<uint64_t> timerIds;
1924 for (auto key : keys) {
1925 sptr<Notification> notification = nullptr;
1926 #ifdef DISTRIBUTED_NOTIFICATION_SUPPORTED
1927 std::string deviceId;
1928 std::string bundleName;
1929 GetDistributedInfo(key, deviceId, bundleName);
1930 #endif
1931 ErrCode result = RemoveFromNotificationList(key, notification, false, removeReason);
1932 if (result != ERR_OK) {
1933 continue;
1934 }
1935 if (notification != nullptr) {
1936 UpdateRecentNotification(notification, true, removeReason);
1937 notifications.emplace_back(notification);
1938 timerIds.emplace_back(notification->GetAutoDeletedTimer());
1939 #ifdef DISTRIBUTED_NOTIFICATION_SUPPORTED
1940 DoDistributedDelete(deviceId, bundleName, notification);
1941 #endif
1942 }
1943 if (notifications.size() >= MAX_CANCELED_PARCELABLE_VECTOR_NUM) {
1944 std::vector<sptr<Notification>> currNotificationList = notifications;
1945 NotificationSubscriberManager::GetInstance()->BatchNotifyCanceled(
1946 currNotificationList, nullptr, removeReason);
1947 notifications.clear();
1948 }
1949 }
1950
1951 if (!notifications.empty()) {
1952 NotificationSubscriberManager::GetInstance()->BatchNotifyCanceled(notifications, nullptr, removeReason);
1953 }
1954 BatchCancelTimer(timerIds);
1955 }));
1956 notificationSvrQueue_->wait(handler);
1957
1958 return ERR_OK;
1959 }
1960
RemoveNotificationBySlot(const sptr<NotificationBundleOption> & bundleOption,const sptr<NotificationSlot> & slot,const int reason)1961 ErrCode AdvancedNotificationService::RemoveNotificationBySlot(const sptr<NotificationBundleOption> &bundleOption,
1962 const sptr<NotificationSlot> &slot, const int reason)
1963 {
1964 HITRACE_METER_NAME(HITRACE_TAG_NOTIFICATION, __PRETTY_FUNCTION__);
1965 ANS_LOGD("%{public}s", __FUNCTION__);
1966
1967 bool isSubsystem = AccessTokenHelper::VerifyNativeToken(IPCSkeleton::GetCallingTokenID());
1968 if (!isSubsystem && !AccessTokenHelper::IsSystemApp()) {
1969 return ERR_ANS_NON_SYSTEM_APP;
1970 }
1971
1972 sptr<NotificationBundleOption> bundle = GenerateValidBundleOption(bundleOption);
1973 if (bundle == nullptr) {
1974 return ERR_ANS_INVALID_BUNDLE;
1975 }
1976 ErrCode result = ERR_ANS_NOTIFICATION_NOT_EXISTS;
1977 std::vector<std::shared_ptr<NotificationRecord>> removeList;
1978 for (auto record : notificationList_) {
1979 if (record == nullptr) {
1980 ANS_LOGE("record is nullptr");
1981 continue;
1982 }
1983 if ((record->bundleOption->GetBundleName() == bundle->GetBundleName()) &&
1984 (record->bundleOption->GetUid() == bundle->GetUid()) &&
1985 (record->request->GetSlotType() == slot->GetType())) {
1986 if ((record->request->GetAgentBundle() != nullptr && record->request->IsSystemLiveView())) {
1987 ANS_LOGW("Agent systemliveview no need remove.");
1988 continue;
1989 }
1990 ProcForDeleteLiveView(record);
1991 removeList.push_back(record);
1992 }
1993 }
1994
1995 std::vector<sptr<Notification>> notifications;
1996 std::vector<uint64_t> timerIds;
1997 for (auto record : removeList) {
1998 if (record == nullptr) {
1999 ANS_LOGE("record is nullptr");
2000 continue;
2001 }
2002 notificationList_.remove(record);
2003 if (record->notification != nullptr) {
2004 ANS_LOGD("record->notification is not nullptr.");
2005 UpdateRecentNotification(record->notification, true, reason);
2006 notifications.emplace_back(record->notification);
2007 timerIds.emplace_back(record->notification->GetAutoDeletedTimer());
2008 }
2009 if (notifications.size() >= MAX_CANCELED_PARCELABLE_VECTOR_NUM) {
2010 SendNotificationsOnCanceled(notifications, nullptr, reason);
2011 }
2012
2013 TriggerRemoveWantAgent(record->request, reason, record->isThirdparty);
2014 result = ERR_OK;
2015 }
2016
2017 if (!notifications.empty()) {
2018 NotificationSubscriberManager::GetInstance()->BatchNotifyCanceled(notifications, nullptr, reason);
2019 }
2020 BatchCancelTimer(timerIds);
2021 return result;
2022 }
2023
IsNeedSilentInDoNotDisturbMode(const std::string & phoneNumber,int32_t callerType)2024 ErrCode AdvancedNotificationService::IsNeedSilentInDoNotDisturbMode(
2025 const std::string &phoneNumber, int32_t callerType)
2026 {
2027 ANS_LOGD("%{public}s", __FUNCTION__);
2028
2029 int32_t callingUid = IPCSkeleton::GetCallingUid();
2030 if (callingUid != ANS_UID && !AccessTokenHelper::CheckPermission(OHOS_PERMISSION_NOTIFICATION_CONTROLLER)) {
2031 ANS_LOGD("IsNeedSilentInDoNotDisturbMode CheckPermission failed.");
2032 return ERR_ANS_PERMISSION_DENIED;
2033 }
2034
2035 int32_t userId = SUBSCRIBE_USER_INIT;
2036 if (OsAccountManagerHelper::GetInstance().GetCurrentActiveUserId(userId) != ERR_OK) {
2037 ANS_LOGD("GetActiveUserId is false");
2038 return ERR_ANS_GET_ACTIVE_USER_FAILED;
2039 }
2040 return CheckNeedSilent(phoneNumber, callerType, userId);
2041 }
2042
CheckNeedSilent(const std::string & phoneNumber,int32_t callerType,int32_t userId)2043 ErrCode AdvancedNotificationService::CheckNeedSilent(
2044 const std::string &phoneNumber, int32_t callerType, int32_t userId)
2045 {
2046 auto datashareHelper = DelayedSingleton<AdvancedDatashareHelper>::GetInstance();
2047 if (datashareHelper == nullptr) {
2048 ANS_LOGE("The data share helper is nullptr.");
2049 return -1;
2050 }
2051
2052 int isNeedSilent = 0;
2053 std::string policy;
2054 Uri policyUri(datashareHelper->GetFocusModeCallPolicyUri(userId));
2055 bool ret = datashareHelper->Query(policyUri, KEY_FOCUS_MODE_CALL_MESSAGE_POLICY, policy);
2056 if (!ret) {
2057 ANS_LOGE("Query focus mode call message policy fail.");
2058 return -1;
2059 }
2060 std::string repeat_call;
2061 Uri repeatUri(datashareHelper->GetFocusModeRepeatCallUri(userId));
2062 bool repeat_ret = datashareHelper->Query(repeatUri, KEY_FOCUS_MODE_REPEAT_CALLERS_ENABLE, repeat_call);
2063 if (!repeat_ret) {
2064 ANS_LOGE("Query focus mode repeat callers enable fail.");
2065 }
2066 ANS_LOGI("IsNeedSilent: policy: %{public}s, repeat: %{public}s, callerType: %{public}d",
2067 policy.c_str(), repeat_call.c_str(), callerType);
2068 if (repeat_call == FOCUS_MODE_REPEAT_CALLERS_ENABLE &&
2069 callerType == 0 && atoi(policy.c_str()) != ContactPolicy::ALLOW_EVERYONE) {
2070 if (datashareHelper->isRepeatCall(phoneNumber)) {
2071 return 1;
2072 }
2073 }
2074 switch (atoi(policy.c_str())) {
2075 case ContactPolicy::FORBID_EVERYONE:
2076 break;
2077 case ContactPolicy::ALLOW_EVERYONE:
2078 isNeedSilent = 1;
2079 break;
2080 case ContactPolicy::ALLOW_EXISTING_CONTACTS:
2081 case ContactPolicy::ALLOW_FAVORITE_CONTACTS:
2082 case ContactPolicy::ALLOW_SPECIFIED_CONTACTS:
2083 case ContactPolicy::FORBID_SPECIFIED_CONTACTS:
2084 isNeedSilent = QueryContactByProfileId(phoneNumber, policy, userId);
2085 break;
2086 }
2087 ANS_LOGI("IsNeedSilentInDoNotDisturbMode: %{public}d", isNeedSilent);
2088 return isNeedSilent;
2089 }
2090
QueryContactByProfileId(const std::string & phoneNumber,const std::string & policy,int32_t userId)2091 ErrCode AdvancedNotificationService::QueryContactByProfileId(const std::string &phoneNumber,
2092 const std::string &policy, int32_t userId)
2093 {
2094 char buf[256] = { 0 };
2095 const std::string ¶mName = "const.intelligentscene.enable";
2096 std::string isSupportIntelligentScene = "false";
2097 const std::string defaultValue = "false";
2098
2099 auto res = GetParameter(paramName.c_str(), defaultValue.c_str(), buf, sizeof(buf));
2100 if (res <= 0) {
2101 ANS_LOGD("isSupportIntelligentScene GetParameter is false");
2102 } else {
2103 isSupportIntelligentScene = buf;
2104 }
2105 ANS_LOGI("isSupportIntelligentScene is %{public}s", isSupportIntelligentScene.c_str());
2106
2107 auto datashareHelper = DelayedSingleton<AdvancedDatashareHelper>::GetInstance();
2108 if (datashareHelper == nullptr) {
2109 ANS_LOGE("The data share helper is nullptr.");
2110 return -1;
2111 }
2112
2113 std::string uri = CONTACT_DATA;
2114 if (isSupportIntelligentScene == SUPPORT_INTEGELLIGENT_SCENE &&
2115 (atoi(policy.c_str()) == ContactPolicy::ALLOW_SPECIFIED_CONTACTS ||
2116 atoi(policy.c_str()) == ContactPolicy::FORBID_SPECIFIED_CONTACTS)) {
2117 uri = datashareHelper->GetIntelligentUri();
2118 }
2119 ANS_LOGI("QueryContactByProfileId uri is %{public}s", uri.c_str());
2120
2121 std::string profileId;
2122 Uri profileIdUri(datashareHelper->GetFocusModeProfileUri(userId));
2123 bool profile_ret = datashareHelper->Query(profileIdUri, KEY_FOCUS_MODE_PROFILE, profileId);
2124 if (!profile_ret) {
2125 ANS_LOGE("Query profile id fail.");
2126 return -1;
2127 }
2128
2129 Uri contactUri(uri);
2130 return datashareHelper->QueryContact(contactUri, phoneNumber, policy, profileId, isSupportIntelligentScene);
2131 }
2132
CancelGroup(const std::string & groupName,const std::string & instanceKey)2133 ErrCode AdvancedNotificationService::CancelGroup(const std::string &groupName, const std::string &instanceKey)
2134 {
2135 ANS_LOGD("%{public}s", __FUNCTION__);
2136
2137 int32_t reason = NotificationConstant::APP_CANCEL_GROPU_REASON_DELETE;
2138 if (groupName.empty()) {
2139 std::string message = "groupName empty.";
2140 OHOS::Notification::HaMetaMessage haMetaMessage = HaMetaMessage(3, 1)
2141 .ErrorCode(ERR_ANS_INVALID_PARAM);
2142 ReportDeleteFailedEventPush(haMetaMessage, reason, message);
2143 ANS_LOGE("%{public}s", message.c_str());
2144 return ERR_ANS_INVALID_PARAM;
2145 }
2146
2147 sptr<NotificationBundleOption> bundleOption = GenerateBundleOption();
2148 if (bundleOption == nullptr) {
2149 std::string message = "bundle is nullptr.";
2150 OHOS::Notification::HaMetaMessage haMetaMessage = HaMetaMessage(3, 2)
2151 .ErrorCode(ERR_ANS_INVALID_BUNDLE);
2152 ReportDeleteFailedEventPush(haMetaMessage, reason, message);
2153 ANS_LOGE("%{public}s", message.c_str());
2154 return ERR_ANS_INVALID_BUNDLE;
2155 }
2156 bundleOption->SetAppInstanceKey(instanceKey);
2157
2158 if (notificationSvrQueue_ == nullptr) {
2159 std::string message = "Serial queue is invalid.";
2160 ANS_LOGE("%{public}s", message.c_str());
2161 return ERR_ANS_INVALID_PARAM;
2162 }
2163
2164 ExcuteCancelGroupCancel(bundleOption, groupName, reason);
2165 return ERR_OK;
2166 }
2167
ExcuteCancelGroupCancel(const sptr<NotificationBundleOption> & bundleOption,const std::string & groupName,const int32_t reason)2168 void AdvancedNotificationService::ExcuteCancelGroupCancel(
2169 const sptr<NotificationBundleOption>& bundleOption,
2170 const std::string &groupName, const int32_t reason)
2171 {
2172 ffrt::task_handle handler = notificationSvrQueue_->submit_h(std::bind([&]() {
2173 ANS_LOGD("ffrt enter!");
2174 std::vector<std::shared_ptr<NotificationRecord>> removeList;
2175 for (auto record : notificationList_) {
2176 ANS_LOGD("ExcuteCancelGroupCancel instanceKey(%{public}s, %{public}s).",
2177 record->notification->GetInstanceKey().c_str(), bundleOption->GetAppInstanceKey().c_str());
2178 if ((record->bundleOption->GetBundleName() == bundleOption->GetBundleName()) &&
2179 (record->bundleOption->GetUid() == bundleOption->GetUid()) &&
2180 (record->notification->GetInstanceKey() == bundleOption->GetAppInstanceKey()) &&
2181 #ifdef DISTRIBUTED_NOTIFICATION_SUPPORTED
2182 record->deviceId.empty() &&
2183 #endif
2184 (record->request->GetGroupName() == groupName)) {
2185 removeList.push_back(record);
2186 }
2187 }
2188
2189 std::vector<sptr<Notification>> notifications;
2190 std::vector<uint64_t> timerIds;
2191 for (auto record : removeList) {
2192 notificationList_.remove(record);
2193 if (record->notification != nullptr) {
2194 UpdateRecentNotification(record->notification, true, reason);
2195 notifications.emplace_back(record->notification);
2196 timerIds.emplace_back(record->notification->GetAutoDeletedTimer());
2197 #ifdef DISTRIBUTED_NOTIFICATION_SUPPORTED
2198 DoDistributedDelete(record->deviceId, record->bundleName, record->notification);
2199 #endif
2200 }
2201 if (notifications.size() >= MAX_CANCELED_PARCELABLE_VECTOR_NUM) {
2202 std::vector<sptr<Notification>> currNotificationList = notifications;
2203 NotificationSubscriberManager::GetInstance()->BatchNotifyCanceled(
2204 currNotificationList, nullptr, reason);
2205 notifications.clear();
2206 }
2207 }
2208
2209 if (!notifications.empty()) {
2210 NotificationSubscriberManager::GetInstance()->BatchNotifyCanceled(
2211 notifications, nullptr, reason);
2212 }
2213 BatchCancelTimer(timerIds);
2214 }));
2215 notificationSvrQueue_->wait(handler);
2216 }
2217
RemoveGroupByBundle(const sptr<NotificationBundleOption> & bundleOption,const std::string & groupName)2218 ErrCode AdvancedNotificationService::RemoveGroupByBundle(
2219 const sptr<NotificationBundleOption> &bundleOption, const std::string &groupName)
2220 {
2221 ANS_LOGD("%{public}s", __FUNCTION__);
2222 const int32_t reason = NotificationConstant::APP_REMOVE_GROUP_REASON_DELETE;
2223 bool isSubsystem = AccessTokenHelper::VerifyNativeToken(IPCSkeleton::GetCallingTokenID());
2224 if (!isSubsystem && !AccessTokenHelper::IsSystemApp()) {
2225 std::string message = "not systemApp.";
2226 OHOS::Notification::HaMetaMessage haMetaMessage = HaMetaMessage(5, 1)
2227 .ErrorCode(ERR_ANS_NON_SYSTEM_APP);
2228 ReportDeleteFailedEventPush(haMetaMessage, reason, message);
2229 ANS_LOGE("%{public}s", message.c_str());
2230 return ERR_ANS_NON_SYSTEM_APP;
2231 }
2232
2233 if (!AccessTokenHelper::CheckPermission(OHOS_PERMISSION_NOTIFICATION_CONTROLLER)) {
2234 std::string message = "no acl permission";
2235 OHOS::Notification::HaMetaMessage haMetaMessage = HaMetaMessage(5, 2)
2236 .ErrorCode(ERR_ANS_PERMISSION_DENIED);
2237 ReportDeleteFailedEventPush(haMetaMessage, reason, message);
2238 ANS_LOGE("%{public}s", message.c_str());
2239 return ERR_ANS_PERMISSION_DENIED;
2240 }
2241
2242 if (bundleOption == nullptr || groupName.empty()) {
2243 std::string message = "groupName empty";
2244 OHOS::Notification::HaMetaMessage haMetaMessage = HaMetaMessage(5, 3)
2245 .ErrorCode(ERR_ANS_INVALID_PARAM);
2246 ReportDeleteFailedEventPush(haMetaMessage, reason, message);
2247 ANS_LOGE("%{public}s", message.c_str());
2248 return ERR_ANS_INVALID_PARAM;
2249 }
2250
2251 sptr<NotificationBundleOption> bundle = GenerateValidBundleOption(bundleOption);
2252 if (bundle == nullptr) {
2253 std::string message = "bundle is nullptr";
2254 OHOS::Notification::HaMetaMessage haMetaMessage = HaMetaMessage(5, 4)
2255 .ErrorCode(ERR_ANS_INVALID_PARAM);
2256 ReportDeleteFailedEventPush(haMetaMessage, reason, message);
2257 ANS_LOGE("%{public}s", message.c_str());
2258 return ERR_ANS_INVALID_BUNDLE;
2259 }
2260
2261 if (notificationSvrQueue_ == nullptr) {
2262 std::string message = "Serial queue is invalid.";
2263 ANS_LOGE("%{public}s", message.c_str());
2264 return ERR_ANS_INVALID_PARAM;
2265 }
2266 ffrt::task_handle handler = notificationSvrQueue_->submit_h(std::bind([&]() {
2267 ANS_LOGD("ffrt enter!");
2268 std::vector<std::shared_ptr<NotificationRecord>> removeList;
2269 int32_t reason = NotificationConstant::CANCEL_REASON_DELETE;
2270 for (auto record : notificationList_) {
2271 if (!record->notification->IsRemoveAllowed()) {
2272 continue;
2273 }
2274 if ((record->bundleOption->GetBundleName() == bundle->GetBundleName()) &&
2275 (record->bundleOption->GetUid() == bundle->GetUid()) && !record->request->IsUnremovable() &&
2276 #ifdef DISTRIBUTED_NOTIFICATION_SUPPORTED
2277 record->deviceId.empty() &&
2278 #endif
2279 (record->request->GetGroupName() == groupName)) {
2280 ANS_LOGD("RemoveList push enter.");
2281 removeList.push_back(record);
2282 }
2283 }
2284
2285 std::vector<sptr<Notification>> notifications;
2286 std::vector<uint64_t> timerIds;
2287 for (auto record : removeList) {
2288 notificationList_.remove(record);
2289 ProcForDeleteLiveView(record);
2290
2291 if (record->notification != nullptr) {
2292 UpdateRecentNotification(record->notification, true, reason);
2293 notifications.emplace_back(record->notification);
2294 timerIds.emplace_back(record->notification->GetAutoDeletedTimer());
2295 #ifdef DISTRIBUTED_NOTIFICATION_SUPPORTED
2296 DoDistributedDelete(record->deviceId, record->bundleName, record->notification);
2297 #endif
2298 }
2299 if (notifications.size() >= MAX_CANCELED_PARCELABLE_VECTOR_NUM) {
2300 SendNotificationsOnCanceled(notifications, nullptr, reason);
2301 }
2302 }
2303
2304 if (!notifications.empty()) {
2305 NotificationSubscriberManager::GetInstance()->BatchNotifyCanceled(notifications, nullptr, reason);
2306 }
2307 BatchCancelTimer(timerIds);
2308 }));
2309 notificationSvrQueue_->wait(handler);
2310
2311 return ERR_OK;
2312 }
2313
RemoveNotificationFromRecordList(const std::vector<std::shared_ptr<NotificationRecord>> & recordList)2314 ErrCode AdvancedNotificationService::RemoveNotificationFromRecordList(
2315 const std::vector<std::shared_ptr<NotificationRecord>>& recordList)
2316 {
2317 ErrCode result = ERR_OK;
2318 std::vector<sptr<Notification>> notifications;
2319 std::vector<uint64_t> timerIds;
2320 for (auto& record : recordList) {
2321 std::string key = record->notification->GetKey();
2322 sptr<Notification> notification = nullptr;
2323 #ifdef DISTRIBUTED_NOTIFICATION_SUPPORTED
2324 std::string deviceId;
2325 std::string bundleName;
2326 GetDistributedInfo(key, deviceId, bundleName);
2327 #endif
2328 result = RemoveFromNotificationList(key, notification, true,
2329 NotificationConstant::USER_STOPPED_REASON_DELETE);
2330 if (result != ERR_OK) {
2331 continue;
2332 }
2333 if (notification != nullptr) {
2334 int32_t reason = NotificationConstant::USER_STOPPED_REASON_DELETE;
2335 UpdateRecentNotification(notification, true, reason);
2336 notifications.emplace_back(notification);
2337 timerIds.emplace_back(notification->GetAutoDeletedTimer());
2338 #ifdef DISTRIBUTED_NOTIFICATION_SUPPORTED
2339 DoDistributedDelete(deviceId, bundleName, notification);
2340 #endif
2341 }
2342 if (notifications.size() >= MAX_CANCELED_PARCELABLE_VECTOR_NUM) {
2343 std::vector<sptr<Notification>> currNotificationList = notifications;
2344 NotificationSubscriberManager::GetInstance()->BatchNotifyCanceled(
2345 currNotificationList, nullptr, NotificationConstant::USER_STOPPED_REASON_DELETE);
2346 notifications.clear();
2347 }
2348 }
2349 if (!notifications.empty()) {
2350 NotificationSubscriberManager::GetInstance()->BatchNotifyCanceled(
2351 notifications, nullptr, NotificationConstant::USER_STOPPED_REASON_DELETE);
2352 }
2353 BatchCancelTimer(timerIds);
2354 return result;
2355 }
2356
IsSpecialUserAllowedNotify(const int32_t & userId,bool & allowed)2357 ErrCode AdvancedNotificationService::IsSpecialUserAllowedNotify(const int32_t &userId, bool &allowed)
2358 {
2359 ANS_LOGD("%{public}s", __FUNCTION__);
2360
2361 bool isSubsystem = AccessTokenHelper::VerifyNativeToken(IPCSkeleton::GetCallingTokenID());
2362 if (!isSubsystem && !AccessTokenHelper::IsSystemApp()) {
2363 return ERR_ANS_NON_SYSTEM_APP;
2364 }
2365
2366 if (!AccessTokenHelper::CheckPermission(OHOS_PERMISSION_NOTIFICATION_CONTROLLER)) {
2367 ANS_LOGD("Failed to checkPermission");
2368 return ERR_ANS_PERMISSION_DENIED;
2369 }
2370
2371 if (notificationSvrQueue_ == nullptr) {
2372 ANS_LOGE("NotificationSvrQueue_ is nullptr.");
2373 return ERR_ANS_INVALID_PARAM;
2374 }
2375 ErrCode result = ERR_OK;
2376 ffrt::task_handle handler = notificationSvrQueue_->submit_h(std::bind([&]() {
2377 ANS_LOGD("ffrt enter!");
2378 allowed = false;
2379 result = NotificationPreferences::GetInstance()->GetNotificationsEnabled(userId, allowed);
2380 }));
2381 notificationSvrQueue_->wait(handler);
2382 return result;
2383 }
2384
SetNotificationsEnabledByUser(const int32_t & userId,bool enabled)2385 ErrCode AdvancedNotificationService::SetNotificationsEnabledByUser(const int32_t &userId, bool enabled)
2386 {
2387 ANS_LOGD("%{public}s", __FUNCTION__);
2388
2389 bool isSubsystem = AccessTokenHelper::VerifyNativeToken(IPCSkeleton::GetCallingTokenID());
2390 if (!isSubsystem && !AccessTokenHelper::IsSystemApp()) {
2391 return ERR_ANS_NON_SYSTEM_APP;
2392 }
2393
2394 if (!AccessTokenHelper::CheckPermission(OHOS_PERMISSION_NOTIFICATION_CONTROLLER)) {
2395 return ERR_ANS_PERMISSION_DENIED;
2396 }
2397
2398 if (notificationSvrQueue_ == nullptr) {
2399 ANS_LOGE("Serial queue is ineffectiveness.");
2400 return ERR_ANS_INVALID_PARAM;
2401 }
2402 ErrCode result = ERR_OK;
2403 ffrt::task_handle handler = notificationSvrQueue_->submit_h(std::bind([&]() {
2404 ANS_LOGD("ffrt enter!");
2405 result = NotificationPreferences::GetInstance()->SetNotificationsEnabled(userId, enabled);
2406 }));
2407 notificationSvrQueue_->wait(handler);
2408 return result;
2409 }
2410
UpdateUnifiedGroupInfo(const std::string & key,std::shared_ptr<NotificationUnifiedGroupInfo> & groupInfo)2411 void AdvancedNotificationService::UpdateUnifiedGroupInfo(const std::string &key,
2412 std::shared_ptr<NotificationUnifiedGroupInfo> &groupInfo)
2413 {
2414 if (notificationSvrQueue_ == nullptr) {
2415 ANS_LOGE("Serial queue is invalid.");
2416 return;
2417 }
2418
2419 ffrt::task_handle handler = notificationSvrQueue_->submit_h([=]() {
2420 for (const auto& item : notificationList_) {
2421 if (item->notification->GetKey() == key) {
2422 ANS_LOGD("update group info matched key %s", key.c_str());
2423 item->notification->GetNotificationRequestPoint()->SetUnifiedGroupInfo(groupInfo);
2424
2425 CloseAlert(item);
2426
2427 UpdateRecentNotification(item->notification, false, 0);
2428 sptr<NotificationSortingMap> sortingMap = GenerateSortingMap();
2429 NotificationSubscriberManager::GetInstance()->NotifyConsumed(item->notification, sortingMap);
2430 break;
2431 }
2432 }
2433 });
2434 }
2435
ClearSlotTypeData(const sptr<NotificationRequest> & request,int32_t callingUid,int32_t sourceType)2436 void AdvancedNotificationService::ClearSlotTypeData(const sptr<NotificationRequest> &request, int32_t callingUid,
2437 int32_t sourceType)
2438 {
2439 if (request == nullptr || (sourceType != CLEAR_SLOT_FROM_AVSEESAION && sourceType != CLEAR_SLOT_FROM_RSS)) {
2440 return;
2441 }
2442
2443 if (sourceType == CLEAR_SLOT_FROM_AVSEESAION) {
2444 if (callingUid != AVSEESAION_PID ||
2445 request->GetSlotType() != NotificationConstant::SlotType::LIVE_VIEW) {
2446 return;
2447 }
2448 }
2449 if (sourceType == CLEAR_SLOT_FROM_RSS) {
2450 if (request->GetCreatorUid() != RSS_PID || !request->IsSystemLiveView()) {
2451 return;
2452 }
2453 }
2454
2455 int32_t uid = request->GetOwnerUid();
2456 std::string bundleName = BundleManagerHelper::GetInstance()->GetBundleNameByUid(uid);
2457 sptr<NotificationBundleOption> bundleOption = new (std::nothrow) NotificationBundleOption(bundleName, uid);
2458 if (bundleOption == nullptr) {
2459 ANS_LOGW("Notification get bundle failed %{public}d", uid);
2460 return;
2461 }
2462
2463 if (NotificationPreferences::GetInstance()->GetBundleRemoveFlag(bundleOption,
2464 NotificationConstant::SlotType::LIVE_VIEW, sourceType)) {
2465 return;
2466 }
2467 NotificationPreferences::GetInstance()->RemoveNotificationSlot(bundleOption,
2468 NotificationConstant::SlotType::LIVE_VIEW);
2469 NotificationPreferences::GetInstance()->SetBundleRemoveFlag(bundleOption,
2470 NotificationConstant::SlotType::LIVE_VIEW, sourceType);
2471 }
2472
PublishNotificationBySa(const sptr<NotificationRequest> & request)2473 ErrCode AdvancedNotificationService::PublishNotificationBySa(const sptr<NotificationRequest> &request)
2474 {
2475 ANS_LOGD("%{public}s", __FUNCTION__);
2476
2477 auto tokenCaller = IPCSkeleton::GetCallingTokenID();
2478 bool isSystemApp = AccessTokenHelper::IsSystemApp();
2479 bool isSubsystem = AccessTokenHelper::VerifyNativeToken(tokenCaller);
2480 bool isThirdparty;
2481 if (isSystemApp || isSubsystem) {
2482 isThirdparty = false;
2483 } else {
2484 isThirdparty = true;
2485 }
2486 bool isAgentController = AccessTokenHelper::VerifyCallerPermission(tokenCaller,
2487 OHOS_PERMISSION_NOTIFICATION_AGENT_CONTROLLER);
2488 HaMetaMessage message = HaMetaMessage(EventSceneId::SCENE_4, EventBranchId::BRANCH_1);
2489 int32_t uid = request->GetCreatorUid();
2490 if (request->GetOwnerUid() != DEFAULT_UID) {
2491 std::shared_ptr<NotificationBundleOption> agentBundle =
2492 std::make_shared<NotificationBundleOption>("", uid);
2493 request->SetAgentBundle(agentBundle);
2494 }
2495
2496 if (request->IsAgentNotification()) {
2497 uid = request->GetOwnerUid();
2498 }
2499 if (uid <= 0) {
2500 message.ErrorCode(ERR_ANS_INVALID_UID).Message("createUid failed" + std::to_string(uid), true);
2501 NotificationAnalyticsUtil::ReportPublishFailedEvent(request, message);
2502 return ERR_ANS_INVALID_UID;
2503 }
2504 std::string bundle = "";
2505 ErrCode result = PrePublishNotificationBySa(request, uid, bundle);
2506 if (request->GetCreatorUid() == RSS_PID && request->IsSystemLiveView() &&
2507 (std::static_pointer_cast<OHOS::Notification::NotificationLocalLiveViewContent>(
2508 request->GetContent()->GetNotificationContent())->GetType() != TYPE_CODE_DOWNLOAD)) {
2509 request->SetSlotType(NotificationConstant::SlotType::OTHER);
2510 request->GetContent()->ResetToBasicContent();
2511 request->SetUnremovable(true);
2512 request->SetTapDismissed(false);
2513 }
2514 if (result != ERR_OK) {
2515 return result;
2516 }
2517
2518 // SA not support sound
2519 if (!request->GetSound().empty()) {
2520 request->SetSound("");
2521 }
2522 std::shared_ptr<NotificationRecord> record = std::make_shared<NotificationRecord>();
2523 record->request = request;
2524 record->isThirdparty = isThirdparty;
2525 if (request->IsAgentNotification()) {
2526 record->bundleOption = new (std::nothrow) NotificationBundleOption("", request->GetCreatorUid());
2527 } else {
2528 #ifdef ENABLE_ANS_ADDITIONAL_CONTROL
2529 int32_t ctrlResult = EXTENTION_WRAPPER->LocalControl(request);
2530 if (ctrlResult != ERR_OK) {
2531 message.ErrorCode(ctrlResult);
2532 NotificationAnalyticsUtil::ReportPublishFailedEvent(request, message);
2533 return ctrlResult;
2534 }
2535 #endif
2536 record->bundleOption = new (std::nothrow) NotificationBundleOption(bundle, uid);
2537 }
2538 sptr<NotificationBundleOption> bundleOption = new (std::nothrow) NotificationBundleOption(bundle, uid);
2539 if (record->bundleOption == nullptr || bundleOption == nullptr) {
2540 ANS_LOGE("Failed to create bundleOption");
2541 return ERR_ANS_NO_MEMORY;
2542 }
2543 record->bundleOption->SetAppInstanceKey(request->GetAppInstanceKey());
2544 int32_t ipcUid = IPCSkeleton::GetCallingUid();
2545 uint32_t hashCodeGeneratetype = NotificationPreferences::GetInstance()->GetHashCodeRule(ipcUid);
2546 request->SetHashCodeGenerateType(hashCodeGeneratetype);
2547 record->notification = new (std::nothrow) Notification(request);
2548 if (record->notification == nullptr) {
2549 ANS_LOGE("Failed to create notification");
2550 return ERR_ANS_NO_MEMORY;
2551 }
2552
2553 if (notificationSvrQueue_ == nullptr) {
2554 ANS_LOGE("Serial queue is invalid.");
2555 return ERR_ANS_INVALID_PARAM;
2556 }
2557
2558 SetRequestBySlotType(record->request, bundleOption);
2559 #ifdef ENABLE_ANS_AGGREGATION
2560 EXTENTION_WRAPPER->GetUnifiedGroupInfo(request);
2561 #endif
2562
2563 ffrt::task_handle handler = notificationSvrQueue_->submit_h([&]() {
2564 if (!bundle.empty() && IsDisableNotification(bundle)) {
2565 ANS_LOGE("bundle in Disable Notification list, bundleName=%{public}s", bundle.c_str());
2566 result = ERR_ANS_REJECTED_WITH_DISABLE_NOTIFICATION;
2567 return;
2568 }
2569 if (!bundleOption->GetBundleName().empty() &&
2570 !(request->GetSlotType() == NotificationConstant::SlotType::LIVE_VIEW && request->IsAgentNotification())) {
2571 ErrCode ret = AssignValidNotificationSlot(record, bundleOption);
2572 if (ret != ERR_OK) {
2573 ANS_LOGE("PublishNotificationBySA Can not assign valid slot!");
2574 }
2575 if (!request->IsAgentNotification()) {
2576 result = Filter(record);
2577 if (result != ERR_OK) {
2578 ANS_LOGE("PublishNotificationBySA Reject by filters: %{public}d", result);
2579 return;
2580 }
2581 }
2582 }
2583
2584 CheckDoNotDisturbProfile(record);
2585 ChangeNotificationByControlFlags(record, isAgentController);
2586 if (IsSaCreateSystemLiveViewAsBundle(record, ipcUid) &&
2587 (std::static_pointer_cast<OHOS::Notification::NotificationLocalLiveViewContent>(
2588 record->request->GetContent()->GetNotificationContent())->GetType() == TYPE_CODE_DOWNLOAD)) {
2589 result = SaPublishSystemLiveViewAsBundle(record);
2590 if (result == ERR_OK) {
2591 SendLiveViewUploadHiSysEvent(record, UploadStatus::CREATE);
2592 }
2593 ClearSlotTypeData(record->request, ipcUid, CLEAR_SLOT_FROM_RSS);
2594 return;
2595 }
2596 bool isNotificationExists = IsNotificationExists(record->notification->GetKey());
2597 result = FlowControlService::GetInstance()->FlowControl(record, ipcUid, isNotificationExists);
2598 if (result != ERR_OK) {
2599 return;
2600 }
2601 if (AssignToNotificationList(record) != ERR_OK) {
2602 ANS_LOGE("Failed to assign notification list");
2603 return;
2604 }
2605
2606 UpdateRecentNotification(record->notification, false, 0);
2607 sptr<NotificationSortingMap> sortingMap = GenerateSortingMap();
2608 NotificationSubscriberManager::GetInstance()->NotifyConsumed(record->notification, sortingMap);
2609 });
2610 notificationSvrQueue_->wait(handler);
2611 if (result != ERR_OK) {
2612 return result;
2613 }
2614
2615 if ((record->request->GetAutoDeletedTime() > GetCurrentTime()) && !record->request->IsCommonLiveView()) {
2616 StartAutoDeletedTimer(record);
2617 }
2618 return ERR_OK;
2619 }
2620
GetTargetDeviceStatus(const std::string & deviceType,int32_t & status)2621 ErrCode AdvancedNotificationService::GetTargetDeviceStatus(const std::string &deviceType, int32_t &status)
2622 {
2623 ANS_LOGD("%{public}s", __FUNCTION__);
2624 bool isSubsystem = AccessTokenHelper::VerifyNativeToken(IPCSkeleton::GetCallingTokenID());
2625 if (!isSubsystem) {
2626 ANS_LOGD("isSubsystem is bogus.");
2627 return ERR_ANS_NON_SYSTEM_APP;
2628 }
2629 if (deviceType.empty()) {
2630 return ERR_ANS_INVALID_PARAM;
2631 }
2632
2633 uint32_t result = DelayedSingleton<DistributedDeviceStatus>::GetInstance()->GetDeviceStatus(deviceType);
2634 status = static_cast<int32_t>(result);
2635 ANS_LOGI("Get %{public}s status %{public}u", deviceType.c_str(), status);
2636 return ERR_OK;
2637 }
2638
SetBadgeNumber(int32_t badgeNumber,const std::string & instanceKey)2639 ErrCode AdvancedNotificationService::SetBadgeNumber(int32_t badgeNumber, const std::string &instanceKey)
2640 {
2641 ANS_LOGD("%{public}s", __FUNCTION__);
2642 if (notificationSvrQueue_ == nullptr) {
2643 ANS_LOGE("Serial queue is invalid.");
2644 return ERR_ANS_INVALID_PARAM;
2645 }
2646 int32_t callingUid = IPCSkeleton::GetCallingUid();
2647 std::string bundleName = GetClientBundleName();
2648 ANS_LOGD("SetBadgeNumber receive instanceKey:%{public}s", instanceKey.c_str());
2649 sptr<BadgeNumberCallbackData> badgeData = new (std::nothrow) BadgeNumberCallbackData(
2650 bundleName, instanceKey, callingUid, badgeNumber);
2651 if (badgeData == nullptr) {
2652 ANS_LOGE("Failed to create BadgeNumberCallbackData.");
2653 return ERR_ANS_NO_MEMORY;
2654 }
2655
2656 ffrt::task_handle handler = notificationSvrQueue_->submit_h([&]() {
2657 ANS_LOGD("ffrt enter!");
2658 NotificationSubscriberManager::GetInstance()->SetBadgeNumber(badgeData);
2659 });
2660 notificationSvrQueue_->wait(handler);
2661 return ERR_OK;
2662 }
2663
SetBadgeNumberForDhByBundle(const sptr<NotificationBundleOption> & bundleOption,int32_t badgeNumber)2664 ErrCode AdvancedNotificationService::SetBadgeNumberForDhByBundle(
2665 const sptr<NotificationBundleOption> &bundleOption, int32_t badgeNumber)
2666 {
2667 if (bundleOption == nullptr || bundleOption->GetBundleName().empty() ||
2668 bundleOption->GetUid() <= DEFAULT_UID) {
2669 ANS_LOGE("SetBadgeNumberForDhByBundle invalid bundleOption");
2670 return ERR_ANS_INVALID_PARAM;
2671 }
2672 if (badgeNumber < BADGE_NUM_LIMIT) {
2673 ANS_LOGE("SetBadgeNumberForDhByBundle invalid badgeNumber");
2674 return ERR_ANS_INVALID_PARAM;
2675 }
2676 ANS_LOGI("SetBadgeNumberForDhByBundle bundleName = %{public}s uid = %{public}d",
2677 bundleOption->GetBundleName().c_str(), bundleOption->GetUid());
2678 HaMetaMessage message = HaMetaMessage(EventSceneId::SCENE_7, EventBranchId::BRANCH_6);
2679 message.Message(bundleOption->GetBundleName() + "_" +std::to_string(bundleOption->GetUid()) +
2680 " badgeNumber: " + std::to_string(badgeNumber));
2681 if (notificationSvrQueue_ == nullptr) {
2682 return ERR_ANS_INVALID_PARAM;
2683 }
2684
2685 bool isSubsystem = AccessTokenHelper::VerifyNativeToken(IPCSkeleton::GetCallingTokenID());
2686 if (!isSubsystem && !AccessTokenHelper::IsSystemApp()) {
2687 message.ErrorCode(ERR_ANS_NON_SYSTEM_APP).Append(" Not system app.");
2688 NotificationAnalyticsUtil::ReportModifyEvent(message);
2689 ANS_LOGE("Not system app.");
2690 return ERR_ANS_NON_SYSTEM_APP;
2691 }
2692 ErrCode result = ERR_OK;
2693 ffrt::task_handle handler = notificationSvrQueue_->submit_h([&]() {
2694 ANS_LOGD("ffrt enter!");
2695 sptr<BadgeNumberCallbackData> badgeData = new (std::nothrow) BadgeNumberCallbackData(
2696 bundleOption->GetBundleName(), bundleOption->GetUid(), badgeNumber);
2697 if (badgeData == nullptr) {
2698 ANS_LOGE("Failed to create badge number callback data.");
2699 result = ERR_ANS_NO_MEMORY;
2700 }
2701 NotificationSubscriberManager::GetInstance()->SetBadgeNumber(badgeData);
2702 });
2703 notificationSvrQueue_->wait(handler);
2704 return result;
2705 }
2706
SetBadgeNumberByBundle(const sptr<NotificationBundleOption> & bundleOption,int32_t badgeNumber)2707 ErrCode AdvancedNotificationService::SetBadgeNumberByBundle(
2708 const sptr<NotificationBundleOption> &bundleOption, int32_t badgeNumber)
2709 {
2710 if (bundleOption == nullptr || bundleOption->GetBundleName().empty()) {
2711 return ERR_ANS_INVALID_PARAM;
2712 }
2713 HaMetaMessage message = HaMetaMessage(EventSceneId::SCENE_7, EventBranchId::BRANCH_6);
2714 message.Message(bundleOption->GetBundleName() + "_" +std::to_string(bundleOption->GetUid()) +
2715 " badgeNumber: " + std::to_string(badgeNumber));
2716 if (notificationSvrQueue_ == nullptr) {
2717 return ERR_ANS_INVALID_PARAM;
2718 }
2719
2720 bool isSubsystem = AccessTokenHelper::VerifyNativeToken(IPCSkeleton::GetCallingTokenID());
2721 if (!isSubsystem && !AccessTokenHelper::IsSystemApp()) {
2722 message.ErrorCode(ERR_ANS_NON_SYSTEM_APP).Append(" Not system app.");
2723 NotificationAnalyticsUtil::ReportModifyEvent(message);
2724 ANS_LOGE("Not system app.");
2725 return ERR_ANS_NON_SYSTEM_APP;
2726 }
2727
2728 sptr<NotificationBundleOption> bundle = bundleOption;
2729 ErrCode result = CheckBundleOptionValid(bundle);
2730 if (result != ERR_OK) {
2731 ANS_LOGE("Bundle is invalid.");
2732 return result;
2733 }
2734
2735 if (!AccessTokenHelper::CheckPermission(OHOS_PERMISSION_NOTIFICATION_AGENT_CONTROLLER)) {
2736 std::string bundleName = GetClientBundleName();
2737 if (bundleName.empty()) {
2738 ANS_LOGE("Failed to get client bundle name.");
2739 return result;
2740 }
2741 bool isAgent = false;
2742 isAgent = IsAgentRelationship(bundleName, bundle->GetBundleName());
2743 if (!isAgent) {
2744 message.ErrorCode(ERR_ANS_NO_AGENT_SETTING).Append(" No agent setting.");
2745 NotificationAnalyticsUtil::ReportModifyEvent(message);
2746 ANS_LOGE("No agent setting.");
2747 return ERR_ANS_NO_AGENT_SETTING;
2748 }
2749 }
2750
2751 ffrt::task_handle handler = notificationSvrQueue_->submit_h([&]() {
2752 ANS_LOGD("ffrt enter!");
2753 sptr<BadgeNumberCallbackData> badgeData = new (std::nothrow) BadgeNumberCallbackData(
2754 bundle->GetBundleName(), bundle->GetUid(), badgeNumber);
2755 if (badgeData == nullptr) {
2756 ANS_LOGE("Failed to create badge number callback data.");
2757 result = ERR_ANS_NO_MEMORY;
2758 }
2759 NotificationSubscriberManager::GetInstance()->SetBadgeNumber(badgeData);
2760 });
2761 notificationSvrQueue_->wait(handler);
2762 return result;
2763 }
2764
SubscribeLocalLiveView(const sptr<AnsSubscriberLocalLiveViewInterface> & subscriber,const sptr<NotificationSubscribeInfo> & info,const bool isNative)2765 ErrCode AdvancedNotificationService::SubscribeLocalLiveView(
2766 const sptr<AnsSubscriberLocalLiveViewInterface> &subscriber,
2767 const sptr<NotificationSubscribeInfo> &info, const bool isNative)
2768 {
2769 HITRACE_METER_NAME(HITRACE_TAG_NOTIFICATION, __PRETTY_FUNCTION__);
2770 ANS_LOGD("%{public}s, isNative: %{public}d", __FUNCTION__, isNative);
2771
2772 ErrCode errCode = ERR_OK;
2773 do {
2774 if (!isNative) {
2775 bool isSubsystem = AccessTokenHelper::VerifyNativeToken(IPCSkeleton::GetCallingTokenID());
2776 if (!isSubsystem && !AccessTokenHelper::IsSystemApp()) {
2777 ANS_LOGE("Client is not a system app or subsystem.");
2778 errCode = ERR_ANS_NON_SYSTEM_APP;
2779 break;
2780 }
2781 }
2782
2783 if (subscriber == nullptr) {
2784 errCode = ERR_ANS_INVALID_PARAM;
2785 break;
2786 }
2787
2788 errCode = NotificationLocalLiveViewSubscriberManager::GetInstance()->AddLocalLiveViewSubscriber(
2789 subscriber, info);
2790 if (errCode != ERR_OK) {
2791 break;
2792 }
2793 } while (0);
2794 if (errCode == ERR_OK) {
2795 int32_t callingUid = IPCSkeleton::GetCallingUid();
2796 ffrt::task_handle handler = notificationSvrQueue_->submit_h(std::bind([&]() {
2797 LivePublishProcess::GetInstance()->AddLiveViewSubscriber(callingUid);
2798 }));
2799 notificationSvrQueue_->wait(handler);
2800 }
2801 SendSubscribeHiSysEvent(IPCSkeleton::GetCallingPid(), IPCSkeleton::GetCallingUid(), info, errCode);
2802 return errCode;
2803 }
2804
SetDistributedEnabledByBundle(const sptr<NotificationBundleOption> & bundleOption,const std::string & deviceType,const bool enabled)2805 ErrCode AdvancedNotificationService::SetDistributedEnabledByBundle(const sptr<NotificationBundleOption> &bundleOption,
2806 const std::string &deviceType, const bool enabled)
2807 {
2808 ANS_LOGD("%{public}s", __FUNCTION__);
2809 if (bundleOption == nullptr) {
2810 ANS_LOGE("BundleOption is null.");
2811 return ERR_ANS_INVALID_BUNDLE;
2812 }
2813
2814 HaMetaMessage message = HaMetaMessage(EventSceneId::SCENE_9, EventBranchId::BRANCH_3);
2815 message.Message(bundleOption->GetBundleName() + "_" + std::to_string(bundleOption->GetUid()) +
2816 " enabled:" + std::to_string(enabled) +
2817 " deviceType:" + deviceType);
2818 bool isSubsystem = AccessTokenHelper::VerifyNativeToken(IPCSkeleton::GetCallingTokenID());
2819 if (!isSubsystem && !AccessTokenHelper::IsSystemApp()) {
2820 ANS_LOGE("IsSystemApp is false.");
2821 message.ErrorCode(ERR_ANS_NON_SYSTEM_APP).Append("Not SystemApp");
2822 NotificationAnalyticsUtil::ReportModifyEvent(message);
2823 return ERR_ANS_NON_SYSTEM_APP;
2824 }
2825
2826 if (!AccessTokenHelper::CheckPermission(OHOS_PERMISSION_NOTIFICATION_CONTROLLER)) {
2827 ANS_LOGE("Permission Denied.");
2828 message.ErrorCode(ERR_ANS_PERMISSION_DENIED).Append("No permission");
2829 NotificationAnalyticsUtil::ReportModifyEvent(message);
2830 return ERR_ANS_PERMISSION_DENIED;
2831 }
2832
2833 sptr<NotificationBundleOption> bundle = GenerateValidBundleOption(bundleOption);
2834 if (bundle == nullptr) {
2835 ANS_LOGE("bundle is nullptr");
2836 return ERR_ANS_INVALID_BUNDLE;
2837 }
2838 ErrCode result = NotificationPreferences::GetInstance()->SetDistributedEnabledByBundle(bundle,
2839 deviceType, enabled);
2840
2841 ANS_LOGI("%{public}s_%{public}d, deviceType: %{public}s, enabled: %{public}s, "
2842 "SetDistributedEnabledByBundle result: %{public}d", bundleOption->GetBundleName().c_str(),
2843 bundleOption->GetUid(), deviceType.c_str(), std::to_string(enabled).c_str(), result);
2844 message.ErrorCode(result);
2845 NotificationAnalyticsUtil::ReportModifyEvent(message);
2846
2847 return result;
2848 }
2849
IsDistributedEnabledByBundle(const sptr<NotificationBundleOption> & bundleOption,const std::string & deviceType,bool & enabled)2850 ErrCode AdvancedNotificationService::IsDistributedEnabledByBundle(const sptr<NotificationBundleOption> &bundleOption,
2851 const std::string &deviceType, bool &enabled)
2852 {
2853 ANS_LOGD("%{public}s", __FUNCTION__);
2854
2855 bool isSubsystem = AccessTokenHelper::VerifyNativeToken(IPCSkeleton::GetCallingTokenID());
2856 if (!isSubsystem && !AccessTokenHelper::IsSystemApp()) {
2857 ANS_LOGD("IsSystemApp is bogus.");
2858 return ERR_ANS_NON_SYSTEM_APP;
2859 }
2860
2861 if (!AccessTokenHelper::CheckPermission(OHOS_PERMISSION_NOTIFICATION_CONTROLLER)) {
2862 ANS_LOGE("no permission");
2863 return ERR_ANS_PERMISSION_DENIED;
2864 }
2865
2866 sptr<NotificationBundleOption> bundle = GenerateValidBundleOption(bundleOption);
2867 if (bundle == nullptr) {
2868 return ERR_ANS_INVALID_BUNDLE;
2869 }
2870
2871 return NotificationPreferences::GetInstance()->IsDistributedEnabledByBundle(bundle, deviceType, enabled);
2872 }
2873
SetDistributedEnabledBySlot(const NotificationConstant::SlotType & slotType,const std::string & deviceType,const bool enabled)2874 ErrCode AdvancedNotificationService::SetDistributedEnabledBySlot(
2875 const NotificationConstant::SlotType &slotType, const std::string &deviceType, const bool enabled)
2876 {
2877 ANS_LOGD("%{public}s", __FUNCTION__);
2878 HaMetaMessage message = HaMetaMessage(EventSceneId::SCENE_8, EventBranchId::BRANCH_7);
2879 bool isSubsystem = AccessTokenHelper::VerifyNativeToken(IPCSkeleton::GetCallingTokenID());
2880 if (!isSubsystem && !AccessTokenHelper::IsSystemApp()) {
2881 ANS_LOGE("IsSystemApp is false.");
2882 message.ErrorCode(ERR_ANS_NON_SYSTEM_APP).Append("Not SystemApp");
2883 NotificationAnalyticsUtil::ReportModifyEvent(message);
2884 return ERR_ANS_NON_SYSTEM_APP;
2885 }
2886
2887 if (!AccessTokenHelper::CheckPermission(OHOS_PERMISSION_NOTIFICATION_CONTROLLER)) {
2888 ANS_LOGE("Permission Denied.");
2889 message.ErrorCode(ERR_ANS_PERMISSION_DENIED).Append("No permission");
2890 NotificationAnalyticsUtil::ReportModifyEvent(message);
2891 return ERR_ANS_PERMISSION_DENIED;
2892 }
2893
2894 ErrCode result = NotificationPreferences::GetInstance()->SetDistributedEnabledBySlot(slotType,
2895 deviceType, enabled);
2896
2897 ANS_LOGI("SetDistributedEnabledBySlot %{public}d, deviceType: %{public}s, enabled: %{public}s, "
2898 "SetDistributedEnabledBySlot result: %{public}d",
2899 slotType, deviceType.c_str(), std::to_string(enabled).c_str(), result);
2900 message.ErrorCode(result);
2901 NotificationAnalyticsUtil::ReportModifyEvent(message);
2902
2903 return result;
2904 }
2905
IsDistributedEnabledBySlot(const NotificationConstant::SlotType & slotType,const std::string & deviceType,bool & enabled)2906 ErrCode AdvancedNotificationService::IsDistributedEnabledBySlot(
2907 const NotificationConstant::SlotType &slotType, const std::string &deviceType, bool &enabled)
2908 {
2909 ANS_LOGD("%{public}s", __FUNCTION__);
2910
2911 bool isSubsystem = AccessTokenHelper::VerifyNativeToken(IPCSkeleton::GetCallingTokenID());
2912 if (!isSubsystem && !AccessTokenHelper::IsSystemApp()) {
2913 ANS_LOGD("IsSystemApp is bogus.");
2914 return ERR_ANS_NON_SYSTEM_APP;
2915 }
2916
2917 if (!AccessTokenHelper::CheckPermission(OHOS_PERMISSION_NOTIFICATION_CONTROLLER)) {
2918 ANS_LOGE("no permission");
2919 return ERR_ANS_PERMISSION_DENIED;
2920 }
2921
2922 return NotificationPreferences::GetInstance()->IsDistributedEnabledBySlot(slotType, deviceType, enabled);
2923 }
2924
DuplicateMsgControl(const sptr<NotificationRequest> & request)2925 ErrCode AdvancedNotificationService::DuplicateMsgControl(const sptr<NotificationRequest> &request)
2926 {
2927 if (request->IsCommonLiveView() || request->GetAppMessageId().empty()) {
2928 return ERR_OK;
2929 }
2930
2931 RemoveExpiredUniqueKey();
2932 std::string uniqueKey = request->GenerateUniqueKey();
2933 if (IsDuplicateMsg(uniqueKey)) {
2934 ANS_LOGI("Duplicate msg, no need to notify, key is %{public}s, appmessageId is %{public}s",
2935 request->GetKey().c_str(), request->GetAppMessageId().c_str());
2936 return ERR_ANS_DUPLICATE_MSG;
2937 }
2938
2939 uniqueKeyList_.emplace_back(std::make_pair(std::chrono::system_clock::now(), uniqueKey));
2940 return ERR_OK;
2941 }
2942
DeleteDuplicateMsgs(const sptr<NotificationBundleOption> & bundleOption)2943 void AdvancedNotificationService::DeleteDuplicateMsgs(const sptr<NotificationBundleOption> &bundleOption)
2944 {
2945 if (bundleOption == nullptr) {
2946 ANS_LOGE("bundleOption is nullptr");
2947 return;
2948 }
2949 const char *keySpliter = "_";
2950 std::stringstream stream;
2951 stream << bundleOption->GetUid() << keySpliter << bundleOption->GetBundleName() << keySpliter;
2952 std::string uniqueKeyHead = stream.str();
2953 auto iter = uniqueKeyList_.begin();
2954 for (auto iter = uniqueKeyList_.begin(); iter != uniqueKeyList_.end();) {
2955 if ((*iter).second.find(uniqueKeyHead) == 0) {
2956 iter = uniqueKeyList_.erase(iter);
2957 } else {
2958 ++iter;
2959 }
2960 }
2961 }
2962
RemoveExpiredUniqueKey()2963 void AdvancedNotificationService::RemoveExpiredUniqueKey()
2964 {
2965 std::chrono::system_clock::time_point now = std::chrono::system_clock::now();
2966 auto iter = uniqueKeyList_.begin();
2967 while (iter != uniqueKeyList_.end()) {
2968 uint32_t duration = std::chrono::duration_cast<std::chrono::seconds>(abs(now - (*iter).first)).count();
2969 ANS_LOGD("RemoveExpiredUniqueKey duration is %{public}u", duration);
2970 if (duration > SECONDS_IN_ONE_DAY) {
2971 ANS_LOGD("RemoveExpiredUniqueKey end duration is %{public}u", duration);
2972 iter = uniqueKeyList_.erase(iter);
2973 } else {
2974 break;
2975 }
2976 }
2977 }
2978
IsDuplicateMsg(const std::string & uniqueKey)2979 bool AdvancedNotificationService::IsDuplicateMsg(const std::string &uniqueKey)
2980 {
2981 for (auto record : uniqueKeyList_) {
2982 if (strcmp(record.second.c_str(), uniqueKey.c_str()) == 0) {
2983 return true;
2984 }
2985 }
2986
2987 return false;
2988 }
2989
PublishRemoveDuplicateEvent(const std::shared_ptr<NotificationRecord> & record)2990 ErrCode AdvancedNotificationService::PublishRemoveDuplicateEvent(const std::shared_ptr<NotificationRecord> &record)
2991 {
2992 if (record == nullptr) {
2993 return ERR_ANS_INVALID_PARAM;
2994 }
2995
2996 if (!record->request->IsAgentNotification()) {
2997 ANS_LOGD("Only push agent need remove duplicate event");
2998 return ERR_OK;
2999 }
3000
3001 std::string extraStr;
3002 if (record->request->GetUnifiedGroupInfo() != nullptr) {
3003 auto extraInfo = record->request->GetUnifiedGroupInfo()->GetExtraInfo();
3004 if (extraInfo != nullptr) {
3005 AAFwk::WantParamWrapper wWrapper(*extraInfo);
3006 extraStr = wWrapper.ToString();
3007 }
3008 }
3009
3010 NotificationNapi::SlotType slotType;
3011 NotificationNapi::ContentType contentType;
3012 NotificationNapi::AnsEnumUtil::ContentTypeCToJS(
3013 static_cast<NotificationContent::Type>(record->request->GetNotificationType()), contentType);
3014 NotificationNapi::AnsEnumUtil::SlotTypeCToJS(
3015 static_cast<NotificationConstant::SlotType>(record->request->GetSlotType()), slotType);
3016
3017 EventFwk::Want want;
3018 want.SetParam("bundleName", record->bundleOption->GetBundleName());
3019 want.SetParam("uid", record->request->GetOwnerUid());
3020 want.SetParam("id", record->request->GetNotificationId());
3021 want.SetParam("slotType", static_cast<int32_t>(slotType));
3022 want.SetParam("contentType", static_cast<int32_t>(contentType));
3023 want.SetParam("appMessageId", record->request->GetAppMessageId());
3024 want.SetParam("extraInfo", extraStr);
3025 want.SetAction(NOTIFICATION_EVENT_PUSH_AGENT);
3026 EventFwk::CommonEventData commonData {want, 1, ""};
3027 EventFwk::CommonEventPublishInfo publishInfo;
3028 publishInfo.SetSubscriberPermissions({OHOS_PERMISSION_NOTIFICATION_AGENT_CONTROLLER});
3029 if (!EventFwk::CommonEventManager::PublishCommonEvent(commonData, publishInfo)) {
3030 ANS_LOGE("PublishCommonEvent failed");
3031 return ERR_ANS_TASK_ERR;
3032 }
3033
3034 return ERR_OK;
3035 }
3036
SetSmartReminderEnabled(const std::string & deviceType,const bool enabled)3037 ErrCode AdvancedNotificationService::SetSmartReminderEnabled(const std::string &deviceType, const bool enabled)
3038 {
3039 ANS_LOGD("%{public}s", __FUNCTION__);
3040 HaMetaMessage message = HaMetaMessage(EventSceneId::SCENE_8, EventBranchId::BRANCH_6);
3041 message.Message(" enabled:" + std::to_string(enabled) + " deviceType:" + deviceType);
3042 bool isSubsystem = AccessTokenHelper::VerifyNativeToken(IPCSkeleton::GetCallingTokenID());
3043 if (!isSubsystem && !AccessTokenHelper::IsSystemApp()) {
3044 ANS_LOGE("IsSystemApp is false.");
3045 message.ErrorCode(ERR_ANS_NON_SYSTEM_APP).Append(" Not SystemApp");
3046 NotificationAnalyticsUtil::ReportModifyEvent(message);
3047 return ERR_ANS_NON_SYSTEM_APP;
3048 }
3049
3050 if (!AccessTokenHelper::CheckPermission(OHOS_PERMISSION_NOTIFICATION_CONTROLLER)) {
3051 ANS_LOGE("Permission Denied.");
3052 message.ErrorCode(ERR_ANS_PERMISSION_DENIED).Append(" Permission Denied");
3053 NotificationAnalyticsUtil::ReportModifyEvent(message);
3054 return ERR_ANS_PERMISSION_DENIED;
3055 }
3056 ErrCode result = NotificationPreferences::GetInstance()->SetSmartReminderEnabled(deviceType, enabled);
3057
3058 ANS_LOGI("enabled: %{public}s, deviceType: %{public}s,Set smart reminder enabled: %{public}d",
3059 std::to_string(enabled).c_str(), deviceType.c_str(), result);
3060 message.ErrorCode(result);
3061 NotificationAnalyticsUtil::ReportModifyEvent(message);
3062 return result;
3063 }
3064
IsSmartReminderEnabled(const std::string & deviceType,bool & enabled)3065 ErrCode AdvancedNotificationService::IsSmartReminderEnabled(const std::string &deviceType, bool &enabled)
3066 {
3067 ANS_LOGD("%{public}s", __FUNCTION__);
3068 bool isSubsystem = AccessTokenHelper::VerifyNativeToken(IPCSkeleton::GetCallingTokenID());
3069 if (!isSubsystem && !AccessTokenHelper::IsSystemApp()) {
3070 ANS_LOGD("IsSystemApp is bogus.");
3071 return ERR_ANS_NON_SYSTEM_APP;
3072 }
3073
3074 if (!AccessTokenHelper::CheckPermission(OHOS_PERMISSION_NOTIFICATION_CONTROLLER)) {
3075 ANS_LOGE("no permission");
3076 return ERR_ANS_PERMISSION_DENIED;
3077 }
3078
3079 return NotificationPreferences::GetInstance()->IsSmartReminderEnabled(deviceType, enabled);
3080 }
3081
SetTargetDeviceStatus(const std::string & deviceType,const uint32_t status)3082 ErrCode AdvancedNotificationService::SetTargetDeviceStatus(const std::string &deviceType, const uint32_t status)
3083 {
3084 ANS_LOGD("%{public}s", __FUNCTION__);
3085 uint32_t status_ = status;
3086 bool isSubsystem = AccessTokenHelper::VerifyNativeToken(IPCSkeleton::GetCallingTokenID());
3087 if (!isSubsystem) {
3088 ANS_LOGD("isSubsystem is bogus.");
3089 return ERR_ANS_NON_SYSTEM_APP;
3090 }
3091 if (deviceType.empty()) {
3092 return ERR_ANS_INVALID_PARAM;
3093 }
3094
3095 DelayedSingleton<DistributedDeviceStatus>::GetInstance()->SetDeviceStatus(deviceType, status_,
3096 DistributedDeviceStatus::DISTURB_DEFAULT_FLAG);
3097 ANS_LOGI("update %{public}s status %{public}u", deviceType.c_str(), status);
3098 return ERR_OK;
3099 }
3100
SetTargetDeviceStatus(const std::string & deviceType,const uint32_t status,const uint32_t controlFlag)3101 ErrCode AdvancedNotificationService::SetTargetDeviceStatus(const std::string &deviceType, const uint32_t status,
3102 const uint32_t controlFlag)
3103 {
3104 ANS_LOGD("%{public}s", __FUNCTION__);
3105 if (deviceType.empty()) {
3106 return ERR_ANS_INVALID_PARAM;
3107 }
3108
3109 bool isSubsystem = AccessTokenHelper::VerifyNativeToken(IPCSkeleton::GetCallingTokenID());
3110 if (!isSubsystem) {
3111 ANS_LOGD("isSubsystem is bogus.");
3112 return ERR_ANS_NON_SYSTEM_APP;
3113 }
3114
3115 if (!AccessTokenHelper::CheckPermission(OHOS_PERMISSION_NOTIFICATION_CONTROLLER)) {
3116 ANS_LOGE("no permission");
3117 return ERR_ANS_PERMISSION_DENIED;
3118 }
3119
3120 DelayedSingleton<DistributedDeviceStatus>::GetInstance()->SetDeviceStatus(deviceType, status, controlFlag);
3121 ANS_LOGI("update %{public}s status %{public}u %{public}u", deviceType.c_str(), status, controlFlag);
3122 return ERR_OK;
3123 }
3124
ClearAllNotificationGroupInfo(std::string localSwitch)3125 void AdvancedNotificationService::ClearAllNotificationGroupInfo(std::string localSwitch)
3126 {
3127 ANS_LOGD("ClearNotification enter.");
3128 bool status = (localSwitch == "true");
3129 if (notificationSvrQueue_ == nullptr) {
3130 ANS_LOGE("ClearNotification Serial queue is invalid.");
3131 return;
3132 }
3133
3134 ffrt::task_handle handler = notificationSvrQueue_->submit_h([=]() {
3135 if (aggregateLocalSwitch_ && !status) {
3136 for (const auto& item : notificationList_) {
3137 item->notification->GetNotificationRequestPoint()->SetUnifiedGroupInfo(nullptr);
3138 }
3139 }
3140 aggregateLocalSwitch_ = status;
3141 });
3142 }
3143
IsDisableNotification(const std::string & bundleName)3144 bool AdvancedNotificationService::IsDisableNotification(const std::string &bundleName)
3145 {
3146 NotificationDisable notificationDisable;
3147 if (NotificationPreferences::GetInstance()->GetDisableNotificationInfo(notificationDisable)) {
3148 if (notificationDisable.GetDisabled()) {
3149 ANS_LOGD("get disabled is open");
3150 std::vector<std::string> bundleList = notificationDisable.GetBundleList();
3151 auto it = std::find(bundleList.begin(), bundleList.end(), bundleName);
3152 if (it != bundleList.end()) {
3153 return true;
3154 }
3155 }
3156 } else {
3157 ANS_LOGD("no disabled has been set up or set disabled to close");
3158 }
3159 return false;
3160 }
3161
IsNeedToControllerByDisableNotification(const sptr<NotificationRequest> & request)3162 bool AdvancedNotificationService::IsNeedToControllerByDisableNotification(const sptr<NotificationRequest> &request)
3163 {
3164 if (request == nullptr) {
3165 ANS_LOGE("request is nullptr");
3166 return false;
3167 }
3168 if (request->IsAgentNotification()) {
3169 return true;
3170 }
3171 std::string bundleName = "";
3172 auto agentBundle = request->GetAgentBundle();
3173 if (agentBundle != nullptr) {
3174 bundleName = agentBundle->GetBundleName();
3175 }
3176 if (!(request->GetOwnerBundleName().empty()) && !bundleName.empty() &&
3177 NotificationPreferences::GetInstance()->IsAgentRelationship(bundleName, request->GetOwnerBundleName()) &&
3178 AccessTokenHelper::CheckPermission(OHOS_PERMISSION_NOTIFICATION_AGENT_CONTROLLER)) {
3179 return false;
3180 }
3181 return true;
3182 }
3183
SetAndPublishSubscriberExistFlag(const std::string & deviceType,bool existFlag)3184 void AdvancedNotificationService::SetAndPublishSubscriberExistFlag(const std::string& deviceType, bool existFlag)
3185 {
3186 ANS_LOGD("%{public}s", __FUNCTION__);
3187 if (deviceType.empty()) {
3188 ANS_LOGE("deviceType is empty");
3189 return;
3190 }
3191
3192 auto result = NotificationPreferences::GetInstance()->SetSubscriberExistFlag(deviceType, existFlag);
3193 if (result != ERR_OK) {
3194 ANS_LOGE("SetSubscriberExistFlag failed");
3195 return;
3196 }
3197
3198 bool headsetExistFlag = false;
3199 bool wearableExistFlag = false;
3200 if (deviceType == DEVICE_TYPE_HEADSET) {
3201 headsetExistFlag = existFlag;
3202 result =
3203 NotificationPreferences::GetInstance()->GetSubscriberExistFlag(DEVICE_TYPE_WEARABLE, wearableExistFlag);
3204 if (result != ERR_OK) {
3205 ANS_LOGE("GetSubscriberExistFlag failed");
3206 return;
3207 }
3208 } else if (deviceType == DEVICE_TYPE_WEARABLE) {
3209 wearableExistFlag = existFlag;
3210 result = NotificationPreferences::GetInstance()->GetSubscriberExistFlag(DEVICE_TYPE_HEADSET, headsetExistFlag);
3211 if (result != ERR_OK) {
3212 ANS_LOGE("GetSubscriberExistFlag failed");
3213 return;
3214 }
3215 }
3216 PublishSubscriberExistFlagEvent(headsetExistFlag, wearableExistFlag);
3217 }
3218
PublishSubscriberExistFlagEvent(bool headsetExistFlag,bool wearableExistFlag)3219 void AdvancedNotificationService::PublishSubscriberExistFlagEvent(bool headsetExistFlag, bool wearableExistFlag)
3220 {
3221 ANS_LOGD("%{public}s, headsetExistFlag = %{public}d, wearableExistFlag = %{public}d", __FUNCTION__,
3222 headsetExistFlag, wearableExistFlag);
3223 EventFwk::Want want;
3224 want.SetParam("SUBSCRIBER_EXISTED_HEADSET", headsetExistFlag);
3225 want.SetParam("SUBSCRIBER_EXISTED_WEARABLE", wearableExistFlag);
3226 want.SetAction(NOTIFICATION_EVENT_SUBSCRIBER_STATUS);
3227 EventFwk::CommonEventData commonData { want, 0, "" };
3228 EventFwk::CommonEventPublishInfo publishInfo;
3229 publishInfo.SetSticky(true);
3230 publishInfo.SetSubscriberType(EventFwk::SubscriberType::SYSTEM_SUBSCRIBER_TYPE);
3231 int32_t userId = SUBSCRIBE_USER_INIT;
3232 if (OsAccountManagerHelper::GetInstance().GetCurrentActiveUserId(userId) != ERR_OK) {
3233 ANS_LOGD("GetCurrentActiveUserId failed");
3234 return;
3235 }
3236 if (!EventFwk::CommonEventManager::PublishCommonEventAsUser(commonData, publishInfo, userId)) {
3237 ANS_LOGE("PublishCommonEventAsUser failed");
3238 }
3239 }
3240
RemoveAllNotificationsByBundleName(const std::string & bundleName,int32_t reason)3241 ErrCode AdvancedNotificationService::RemoveAllNotificationsByBundleName(const std::string &bundleName, int32_t reason)
3242 {
3243 HITRACE_METER_NAME(HITRACE_TAG_NOTIFICATION, __PRETTY_FUNCTION__);
3244 ANS_LOGD("%{public}s", __FUNCTION__);
3245
3246 if (bundleName.empty()) {
3247 std::string message = "bundle name is empty.";
3248 OHOS::Notification::HaMetaMessage haMetaMessage = HaMetaMessage(8, 1).ErrorCode(ERR_ANS_INVALID_BUNDLE);
3249 ReportDeleteFailedEventPush(haMetaMessage, reason, message);
3250 ANS_LOGE("%{public}s", message.c_str());
3251 return ERR_ANS_INVALID_BUNDLE;
3252 }
3253
3254 if (notificationSvrQueue_ == nullptr) {
3255 std::string message = "Serial queue is nullptr.";
3256 ANS_LOGE("%{public}s", message.c_str());
3257 return ERR_ANS_INVALID_PARAM;
3258 }
3259 ffrt::task_handle handler = notificationSvrQueue_->submit_h(std::bind([&]() {
3260 std::vector<std::shared_ptr<NotificationRecord>> removeList;
3261 ANS_LOGD("ffrt enter!");
3262 for (auto record : notificationList_) {
3263 if (record == nullptr) {
3264 ANS_LOGE("record is nullptr");
3265 continue;
3266 }
3267 if ((record->bundleOption->GetBundleName() == bundleName)
3268 #ifdef DISTRIBUTED_NOTIFICATION_SUPPORTED
3269 && record->deviceId.empty()
3270 #endif
3271 ) {
3272 ProcForDeleteLiveView(record);
3273 removeList.push_back(record);
3274 }
3275 }
3276
3277 std::vector<sptr<Notification>> notifications;
3278 std::vector<uint64_t> timerIds;
3279 for (auto record : removeList) {
3280 if (record == nullptr) {
3281 ANS_LOGE("record is nullptr");
3282 continue;
3283 }
3284 notificationList_.remove(record);
3285 if (record->notification != nullptr) {
3286 ANS_LOGD("record->notification is not nullptr.");
3287 UpdateRecentNotification(record->notification, true, reason);
3288 notifications.emplace_back(record->notification);
3289 timerIds.emplace_back(record->notification->GetAutoDeletedTimer());
3290 #ifdef DISTRIBUTED_NOTIFICATION_SUPPORTED
3291 DoDistributedDelete(record->deviceId, record->bundleName, record->notification);
3292 #endif
3293 }
3294 if (notifications.size() >= MAX_CANCELED_PARCELABLE_VECTOR_NUM) {
3295 SendNotificationsOnCanceled(notifications, nullptr, reason);
3296 }
3297
3298 TriggerRemoveWantAgent(record->request, reason, record->isThirdparty);
3299 }
3300
3301 if (!notifications.empty()) {
3302 NotificationSubscriberManager::GetInstance()->BatchNotifyCanceled(notifications, nullptr, reason);
3303 }
3304 BatchCancelTimer(timerIds);
3305 }));
3306 notificationSvrQueue_->wait(handler);
3307
3308 return ERR_OK;
3309 }
3310
DistributeOperationParamCheck(sptr<NotificationOperationInfo> & operationInfo,const sptr<OperationCallbackInterface> & callback)3311 ErrCode DistributeOperationParamCheck(sptr<NotificationOperationInfo>& operationInfo,
3312 const sptr<OperationCallbackInterface> &callback)
3313 {
3314 if (operationInfo == nullptr || operationInfo->GetHashCode().empty()) {
3315 ANS_LOGE("hashCode is empty.");
3316 return ERR_ANS_INVALID_PARAM;
3317 }
3318
3319 OperationType operationType = operationInfo->GetOperationType();
3320 if (operationType != OperationType::DISTRIBUTE_OPERATION_JUMP &&
3321 operationType != OperationType::DISTRIBUTE_OPERATION_REPLY) {
3322 ANS_LOGE("operation type is error.");
3323 return ERR_ANS_INVALID_PARAM;
3324 }
3325
3326 bool isSubsystem = AccessTokenHelper::VerifyNativeToken(IPCSkeleton::GetCallingTokenID());
3327 if (!isSubsystem && !AccessTokenHelper::IsSystemApp()) {
3328 ANS_LOGE("is not system app.");
3329 return ERR_ANS_NON_SYSTEM_APP;
3330 }
3331
3332 if (!AccessTokenHelper::CheckPermission(OHOS_PERMISSION_NOTIFICATION_CONTROLLER)) {
3333 ANS_LOGE("not have permission.");
3334 return ERR_ANS_PERMISSION_DENIED;
3335 }
3336 return ERR_OK;
3337 }
3338
DistributeOperation(sptr<NotificationOperationInfo> & operationInfo,const sptr<OperationCallbackInterface> & callback)3339 ErrCode AdvancedNotificationService::DistributeOperation(sptr<NotificationOperationInfo>& operationInfo,
3340 const sptr<OperationCallbackInterface> &callback)
3341 {
3342 ErrCode result = DistributeOperationParamCheck(operationInfo, callback);
3343 if (result != ERR_OK) {
3344 return result;
3345 }
3346
3347 if (notificationSvrQueue_ == nullptr) {
3348 ANS_LOGE("Serial queue is invalidated");
3349 return ERR_ANS_INVALID_PARAM;
3350 }
3351
3352 OperationType operationType = operationInfo->GetOperationType();
3353 if (operationType == OperationType::DISTRIBUTE_OPERATION_REPLY) {
3354 operationInfo->SetEventId(std::to_string(GetCurrentTime()));
3355 std::string key = operationInfo->GetHashCode() + operationInfo->GetEventId();
3356 DistributedOperationService::GetInstance().AddOperation(key, callback);
3357 }
3358 ANS_LOGI("DistributeOperation trigger hashcode %{public}s.", operationInfo->GetHashCode().c_str());
3359 ffrt::task_handle handler = notificationSvrQueue_->submit_h(std::bind([&]() {
3360 std::string hashCode = operationInfo->GetHashCode();
3361 for (auto record : notificationList_) {
3362 if (record->notification->GetKey() != hashCode) {
3363 continue;
3364 }
3365 if (record->notification->GetNotificationRequestPoint() == nullptr) {
3366 continue;
3367 }
3368 auto request = record->notification->GetNotificationRequestPoint();
3369 if (!request->GetDistributedCollaborate()) {
3370 ANS_LOGI("Not collaborate hashcode %{public}s.", hashCode.c_str());
3371 continue;
3372 }
3373 result = NotificationSubscriberManager::GetInstance()->DistributeOperation(operationInfo);
3374 return;
3375 }
3376 ANS_LOGI("DistributeOperation not exist hashcode.");
3377 result = ERR_ANS_INVALID_PARAM;
3378 }));
3379 notificationSvrQueue_->wait(handler);
3380 if (result != ERR_OK && operationType == OperationType::DISTRIBUTE_OPERATION_REPLY) {
3381 std::string key = operationInfo->GetHashCode() + operationInfo->GetEventId();
3382 DistributedOperationService::GetInstance().RemoveOperationResponse(key);
3383 }
3384 return result;
3385 }
3386
SetHashCodeRule(const uint32_t type)3387 ErrCode AdvancedNotificationService::SetHashCodeRule(const uint32_t type)
3388 {
3389 ANS_LOGI("%{public}s", __FUNCTION__);
3390 HaMetaMessage message = HaMetaMessage(EventSceneId::SCENE_8, EventBranchId::BRANCH_8);
3391 bool isSubsystem = AccessTokenHelper::VerifyNativeToken(IPCSkeleton::GetCallingTokenID());
3392 if (!isSubsystem && !AccessTokenHelper::IsSystemApp()) {
3393 ANS_LOGE("IsSystemApp is false.");
3394 message.ErrorCode(ERR_ANS_NON_SYSTEM_APP).Append("Not SystemApp");
3395 NotificationAnalyticsUtil::ReportModifyEvent(message);
3396 return ERR_ANS_NON_SYSTEM_APP;
3397 }
3398
3399 int32_t uid = IPCSkeleton::GetCallingUid();
3400 if (uid != AVSEESAION_PID) {
3401 ANS_LOGE("Permission Denied.");
3402 message.ErrorCode(ERR_ANS_PERMISSION_DENIED).Append("No permission");
3403 NotificationAnalyticsUtil::ReportModifyEvent(message);
3404 return ERR_ANS_PERMISSION_DENIED;
3405 }
3406 ErrCode result = NotificationPreferences::GetInstance()->SetHashCodeRule(uid, type);
3407 ANS_LOGI("SetHashCodeRule uid = %{public}d type = %{public}d, result %{public}d", uid, type, result);
3408 message.ErrorCode(result);
3409 NotificationAnalyticsUtil::ReportModifyEvent(message);
3410
3411 return result;
3412 }
3413 } // namespace Notification
3414 } // namespace OHOS
3415