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