1 /*
2 * Copyright (c) 2021-2022 Huawei Device Co., Ltd.
3 * Licensed under the Apache License, Version 2.0 (the "License");
4 * you may not use this file except in compliance with the License.
5 * You may obtain a copy of the License at
6 *
7 * http://www.apache.org/licenses/LICENSE-2.0
8 *
9 * Unless required by applicable law or agreed to in writing, software
10 * distributed under the License is distributed on an "AS IS" BASIS,
11 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 * See the License for the specific language governing permissions and
13 * limitations under the License.
14 */
15
16 #include "advanced_notification_service.h"
17
18 #include <functional>
19 #include <iomanip>
20 #include <sstream>
21
22 #include "ability_context.h"
23 #include "ability_info.h"
24 #include "access_token_helper.h"
25 #include "accesstoken_kit.h"
26 #include "ans_const_define.h"
27 #include "ans_inner_errors.h"
28 #include "ans_log_wrapper.h"
29 #include "ans_watchdog.h"
30 #include "ans_permission_def.h"
31 #include "bundle_manager_helper.h"
32 #ifdef DEVICE_USAGE_STATISTICS_ENABLE
33 #include "bundle_active_client.h"
34 #endif
35 #include "common_event_manager.h"
36 #include "common_event_support.h"
37 #include "display_manager.h"
38 #include "event_report.h"
39 #include "hitrace_meter.h"
40 #include "ipc_skeleton.h"
41 #include "notification_constant.h"
42 #include "notification_dialog.h"
43 #include "notification_filter.h"
44 #include "notification_preferences.h"
45 #include "notification_slot.h"
46 #include "notification_slot_filter.h"
47 #include "notification_subscriber_manager.h"
48 #include "os_account_manager.h"
49 #include "permission_filter.h"
50 #include "reminder_data_manager.h"
51 #include "trigger_info.h"
52 #include "ui_service_mgr_client.h"
53 #include "want_agent_helper.h"
54
55 #ifdef DISTRIBUTED_NOTIFICATION_SUPPORTED
56 #include "distributed_notification_manager.h"
57 #include "distributed_preferences.h"
58 #include "distributed_screen_status_manager.h"
59 #endif
60
61 namespace OHOS {
62 namespace Notification {
63 namespace {
64 constexpr char ACTIVE_NOTIFICATION_OPTION[] = "active";
65 constexpr char RECENT_NOTIFICATION_OPTION[] = "recent";
66 constexpr char HELP_NOTIFICATION_OPTION[] = "help";
67 #ifdef DISTRIBUTED_NOTIFICATION_SUPPORTED
68 constexpr char DISTRIBUTED_NOTIFICATION_OPTION[] = "distributed";
69 #endif
70 constexpr char SET_RECENT_COUNT_OPTION[] = "setRecentCount";
71 constexpr char FOUNDATION_BUNDLE_NAME[] = "ohos.global.systemres";
72
73 constexpr int32_t DEFAULT_RECENT_COUNT = 16;
74
75 constexpr int32_t HOURS_IN_ONE_DAY = 24;
76
77 constexpr int32_t DIALOG_DEFAULT_WIDTH = 400;
78 constexpr int32_t DIALOG_DEFAULT_HEIGHT = 240;
79 constexpr int32_t WINDOW_DEFAULT_WIDTH = 720;
80 constexpr int32_t WINDOW_DEFAULT_HEIGHT = 1280;
81 constexpr int32_t UI_HALF = 2;
82
83 constexpr char HIDUMPER_HELP_MSG[] =
84 "Usage:dump <command> [options]\n"
85 "Description::\n"
86 " --active, -a list all active notifications\n"
87 " --recent, -r list recent notifications\n";
88
89 constexpr char HIDUMPER_ERR_MSG[] =
90 "error: unknown option.\nThe arguments are illegal and you can enter '-h' for help.";
91
92 const std::unordered_map<std::string, std::string> HIDUMPER_CMD_MAP = {
93 { "--help", HELP_NOTIFICATION_OPTION },
94 { "--active", ACTIVE_NOTIFICATION_OPTION },
95 { "--recent", RECENT_NOTIFICATION_OPTION },
96 { "-h", HELP_NOTIFICATION_OPTION },
97 { "-a", ACTIVE_NOTIFICATION_OPTION },
98 { "-r", RECENT_NOTIFICATION_OPTION },
99 };
100
101 struct RecentNotification {
102 sptr<Notification> notification = nullptr;
103 bool isActive = false;
104 int32_t deleteReason = 0;
105 int64_t deleteTime = 0;
106 };
107 } // namespace
108
109 struct AdvancedNotificationService::RecentInfo {
110 std::list<std::shared_ptr<RecentNotification>> list;
111 size_t recentCount = DEFAULT_RECENT_COUNT;
112 };
113
114 sptr<AdvancedNotificationService> AdvancedNotificationService::instance_;
115 std::mutex AdvancedNotificationService::instanceMutex_;
116
117 static const std::shared_ptr<INotificationFilter> NOTIFICATION_FILTERS[] = {
118 std::make_shared<PermissionFilter>(),
119 std::make_shared<NotificationSlotFilter>(),
120 };
121
GetClientBundleName()122 inline std::string GetClientBundleName()
123 {
124 std::string bundle;
125
126 int32_t callingUid = IPCSkeleton::GetCallingUid();
127
128 std::shared_ptr<BundleManagerHelper> bundleManager = BundleManagerHelper::GetInstance();
129 if (bundleManager != nullptr) {
130 bundle = bundleManager->GetBundleNameByUid(callingUid);
131 }
132
133 return bundle;
134 }
135
IsSystemApp()136 inline bool IsSystemApp()
137 {
138 bool isSystemApp = false;
139
140 int32_t callingUid = IPCSkeleton::GetCallingUid();
141
142 std::shared_ptr<BundleManagerHelper> bundleManager = BundleManagerHelper::GetInstance();
143 if (bundleManager != nullptr) {
144 isSystemApp = bundleManager->IsSystemApp(callingUid);
145 }
146
147 return isSystemApp || AccessTokenHelper::IsSystemHap();
148 }
149
ResetSeconds(int64_t date)150 inline int64_t ResetSeconds(int64_t date)
151 {
152 auto milliseconds = std::chrono::milliseconds(date);
153 auto tp = std::chrono::time_point<std::chrono::system_clock, std::chrono::milliseconds>(milliseconds);
154 auto tp_minutes = std::chrono::time_point_cast<std::chrono::minutes>(tp);
155 auto duration = std::chrono::duration_cast<std::chrono::milliseconds>(tp_minutes.time_since_epoch());
156 return duration.count();
157 }
158
GetCurrentTime()159 inline int64_t GetCurrentTime()
160 {
161 auto now = std::chrono::system_clock::now();
162 auto duration = std::chrono::duration_cast<std::chrono::milliseconds>(now.time_since_epoch());
163 return duration.count();
164 }
165
GetLocalTime(time_t time)166 inline tm GetLocalTime(time_t time)
167 {
168 struct tm ret = {0};
169 localtime_r(&time, &ret);
170 return ret;
171 }
172
AssignValidNotificationSlot(const std::shared_ptr<NotificationRecord> & record)173 inline ErrCode AssignValidNotificationSlot(const std::shared_ptr<NotificationRecord> &record)
174 {
175 sptr<NotificationSlot> slot;
176 NotificationConstant::SlotType slotType = record->request->GetSlotType();
177 ErrCode result = NotificationPreferences::GetInstance().GetNotificationSlot(record->bundleOption, slotType, slot);
178 if ((result == ERR_ANS_PREFERENCES_NOTIFICATION_BUNDLE_NOT_EXIST) ||
179 (result == ERR_ANS_PREFERENCES_NOTIFICATION_SLOT_TYPE_NOT_EXIST)) {
180 slot = new NotificationSlot(slotType);
181 std::vector<sptr<NotificationSlot>> slots;
182 slots.push_back(slot);
183 result = NotificationPreferences::GetInstance().AddNotificationSlots(record->bundleOption, slots);
184 }
185 if (result == ERR_OK) {
186 if (slot != nullptr && slot->GetEnable()) {
187 record->slot = slot;
188 } else {
189 result = ERR_ANS_PREFERENCES_NOTIFICATION_SLOT_ENABLED;
190 ANS_LOGE("Type[%{public}d] slot enable closed", slotType);
191 }
192 }
193 return result;
194 }
195
CheckPictureSize(const sptr<NotificationRequest> & request)196 inline ErrCode CheckPictureSize(const sptr<NotificationRequest> &request)
197 {
198 ErrCode result = ERR_OK;
199
200 auto content = request->GetContent();
201 if (content != nullptr && content->GetContentType() == NotificationContent::Type::PICTURE) {
202 std::shared_ptr<NotificationPictureContent> pictureContent =
203 std::static_pointer_cast<NotificationPictureContent>(content->GetNotificationContent());
204 if (pictureContent != nullptr) {
205 auto picture = pictureContent->GetBigPicture();
206 if (picture != nullptr && static_cast<uint32_t>(picture->GetByteCount()) > MAX_PICTURE_SIZE) {
207 result = ERR_ANS_PICTURE_OVER_SIZE;
208 }
209 }
210 }
211
212 auto littleIcon = request->GetLittleIcon();
213 if (littleIcon != nullptr && static_cast<uint32_t>(littleIcon->GetByteCount()) > MAX_ICON_SIZE) {
214 result = ERR_ANS_ICON_OVER_SIZE;
215 }
216
217 auto bigIcon = request->GetBigIcon();
218 if (bigIcon != nullptr && static_cast<uint32_t>(bigIcon->GetByteCount()) > MAX_ICON_SIZE) {
219 result = ERR_ANS_ICON_OVER_SIZE;
220 }
221
222 return result;
223 }
224
PrepareNotificationRequest(const sptr<NotificationRequest> & request)225 ErrCode AdvancedNotificationService::PrepareNotificationRequest(const sptr<NotificationRequest> &request)
226 {
227 ANS_LOGD("%{public}s", __FUNCTION__);
228
229 std::string bundle = GetClientBundleName();
230 if (bundle.empty()) {
231 return ERR_ANS_INVALID_BUNDLE;
232 }
233
234 if (request->IsAgentNotification()) {
235 if (!IsSystemApp()) {
236 return ERR_ANS_NON_SYSTEM_APP;
237 }
238
239 if (!CheckPermission(OHOS_PERMISSION_NOTIFICATION_CONTROLLER) ||
240 !CheckPermission(OHOS_PERMISSION_NOTIFICATION_AGENT_CONTROLLER)) {
241 return ERR_ANS_PERMISSION_DENIED;
242 }
243
244 std::shared_ptr<BundleManagerHelper> bundleManager = BundleManagerHelper::GetInstance();
245 int32_t uid = -1;
246 if (bundleManager != nullptr) {
247 uid = bundleManager->GetDefaultUidByBundleName(request->GetOwnerBundleName(), request->GetOwnerUserId());
248 }
249 if (uid < 0) {
250 return ERR_ANS_INVALID_UID;
251 }
252 request->SetOwnerUid(uid);
253 } else {
254 request->SetOwnerBundleName(bundle);
255 }
256 request->SetCreatorBundleName(bundle);
257
258 int32_t uid = IPCSkeleton::GetCallingUid();
259 int32_t pid = IPCSkeleton::GetCallingPid();
260 request->SetCreatorUid(uid);
261 request->SetCreatorPid(pid);
262
263 int32_t userId = SUBSCRIBE_USER_INIT;
264 OHOS::AccountSA::OsAccountManager::GetOsAccountLocalIdFromUid(uid, userId);
265 request->SetCreatorUserId(userId);
266 ErrCode result = CheckPictureSize(request);
267
268 if (request->GetDeliveryTime() <= 0) {
269 request->SetDeliveryTime(GetCurrentTime());
270 }
271
272 return result;
273 }
274
GetInstance()275 sptr<AdvancedNotificationService> AdvancedNotificationService::GetInstance()
276 {
277 std::lock_guard<std::mutex> lock(instanceMutex_);
278
279 if (instance_ == nullptr) {
280 instance_ = new AdvancedNotificationService();
281 }
282 return instance_;
283 }
284
AdvancedNotificationService()285 AdvancedNotificationService::AdvancedNotificationService()
286 {
287 runner_ = OHOS::AppExecFwk::EventRunner::Create("NotificationSvrMain");
288 handler_ = std::make_shared<OHOS::AppExecFwk::EventHandler>(runner_);
289 AnsWatchdog::AddHandlerThread(handler_, runner_);
290 recentInfo_ = std::make_shared<RecentInfo>();
291 distributedKvStoreDeathRecipient_ = std::make_shared<DistributedKvStoreDeathRecipient>(
292 std::bind(&AdvancedNotificationService::OnDistributedKvStoreDeathRecipient, this));
293
294 StartFilters();
295
296 ISystemEvent iSystemEvent = {
297 std::bind(&AdvancedNotificationService::OnBundleRemoved, this, std::placeholders::_1),
298 #ifdef DISTRIBUTED_NOTIFICATION_SUPPORTED
299 std::bind(&AdvancedNotificationService::OnScreenOn, this),
300 std::bind(&AdvancedNotificationService::OnScreenOff, this),
301 #endif
302 std::bind(&AdvancedNotificationService::OnResourceRemove, this, std::placeholders::_1),
303 std::bind(&AdvancedNotificationService::OnBundleDataCleared, this, std::placeholders::_1),
304 };
305 systemEventObserver_ = std::make_shared<SystemEventObserver>(iSystemEvent);
306
307 dataManager_.RegisterKvStoreServiceDeathRecipient(distributedKvStoreDeathRecipient_);
308
309 #ifdef DISTRIBUTED_NOTIFICATION_SUPPORTED
310 DistributedNotificationManager::IDistributedCallback distributedCallback = {
311 .OnPublish = std::bind(&AdvancedNotificationService::OnDistributedPublish,
312 this,
313 std::placeholders::_1,
314 std::placeholders::_2,
315 std::placeholders::_3),
316 .OnUpdate = std::bind(&AdvancedNotificationService::OnDistributedUpdate,
317 this,
318 std::placeholders::_1,
319 std::placeholders::_2,
320 std::placeholders::_3),
321 .OnDelete = std::bind(&AdvancedNotificationService::OnDistributedDelete,
322 this,
323 std::placeholders::_1,
324 std::placeholders::_2,
325 std::placeholders::_3,
326 std::placeholders::_4),
327 };
328 DistributedNotificationManager::GetInstance()->RegisterCallback(distributedCallback);
329 #endif
330 }
331
~AdvancedNotificationService()332 AdvancedNotificationService::~AdvancedNotificationService()
333 {
334 dataManager_.UnRegisterKvStoreServiceDeathRecipient(distributedKvStoreDeathRecipient_);
335
336 StopFilters();
337 #ifdef DISTRIBUTED_NOTIFICATION_SUPPORTED
338 DistributedNotificationManager::GetInstance()->UngegisterCallback();
339 #endif
340 }
341
GenerateBundleOption()342 sptr<NotificationBundleOption> AdvancedNotificationService::GenerateBundleOption()
343 {
344 sptr<NotificationBundleOption> bundleOption = nullptr;
345 std::string bundle = GetClientBundleName();
346 if (bundle.empty()) {
347 return nullptr;
348 }
349 int32_t uid = IPCSkeleton::GetCallingUid();
350 bundleOption = new NotificationBundleOption(bundle, uid);
351 return bundleOption;
352 }
353
GenerateValidBundleOption(const sptr<NotificationBundleOption> & bundleOption)354 sptr<NotificationBundleOption> AdvancedNotificationService::GenerateValidBundleOption(
355 const sptr<NotificationBundleOption> &bundleOption)
356 {
357 sptr<NotificationBundleOption> validBundleOption = nullptr;
358 if (bundleOption->GetUid() <= 0) {
359 std::shared_ptr<BundleManagerHelper> bundleManager = BundleManagerHelper::GetInstance();
360 if (bundleManager != nullptr) {
361 int32_t activeUserId = -1;
362 if (!GetActiveUserId(activeUserId)) {
363 ANS_LOGE("Failed to get active user id!");
364 return validBundleOption;
365 }
366 int32_t uid = bundleManager->GetDefaultUidByBundleName(bundleOption->GetBundleName(), activeUserId);
367 if (uid > 0) {
368 validBundleOption = new NotificationBundleOption(bundleOption->GetBundleName(), uid);
369 }
370 }
371 } else {
372 validBundleOption = bundleOption;
373 }
374 return validBundleOption;
375 }
376
AssignToNotificationList(const std::shared_ptr<NotificationRecord> & record)377 ErrCode AdvancedNotificationService::AssignToNotificationList(const std::shared_ptr<NotificationRecord> &record)
378 {
379 ErrCode result = ERR_OK;
380 if (!IsNotificationExists(record->notification->GetKey())) {
381 result = FlowControl(record);
382 } else {
383 if (record->request->IsAlertOneTime()) {
384 record->notification->SetEnableLight(false);
385 record->notification->SetEnableSound(false);
386 record->notification->SetEnableVibration(false);
387 }
388 UpdateInNotificationList(record);
389 }
390 return result;
391 }
392
CancelPreparedNotification(int32_t notificationId,const std::string & label,const sptr<NotificationBundleOption> & bundleOption)393 ErrCode AdvancedNotificationService::CancelPreparedNotification(
394 int32_t notificationId, const std::string &label, const sptr<NotificationBundleOption> &bundleOption)
395 {
396 HITRACE_METER_NAME(HITRACE_TAG_NOTIFICATION, __PRETTY_FUNCTION__);
397 if (bundleOption == nullptr) {
398 return ERR_ANS_INVALID_BUNDLE;
399 }
400 ErrCode result = ERR_OK;
401 handler_->PostSyncTask(std::bind([&]() {
402 sptr<Notification> notification = nullptr;
403 result = RemoveFromNotificationList(bundleOption, label, notificationId, notification, true);
404 if (result != ERR_OK) {
405 return;
406 }
407
408 if (notification != nullptr) {
409 int32_t reason = NotificationConstant::APP_CANCEL_REASON_DELETE;
410 UpdateRecentNotification(notification, true, reason);
411 sptr<NotificationSortingMap> sortingMap = GenerateSortingMap();
412 NotificationSubscriberManager::GetInstance()->NotifyCanceled(notification, sortingMap, reason);
413 #ifdef DISTRIBUTED_NOTIFICATION_SUPPORTED
414 DoDistributedDelete("", "", notification);
415 #endif
416 }
417 }));
418
419 SendCancelHiSysEvent(notificationId, label, bundleOption, result);
420 return result;
421 }
422
PrepareNotificationInfo(const sptr<NotificationRequest> & request,sptr<NotificationBundleOption> & bundleOption)423 ErrCode AdvancedNotificationService::PrepareNotificationInfo(
424 const sptr<NotificationRequest> &request, sptr<NotificationBundleOption> &bundleOption)
425 {
426 HITRACE_METER_NAME(HITRACE_TAG_NOTIFICATION, __PRETTY_FUNCTION__);
427 if ((request->GetSlotType() == NotificationConstant::SlotType::CUSTOM) && !IsSystemApp()) {
428 return ERR_ANS_NON_SYSTEM_APP;
429 }
430 ErrCode result = PrepareNotificationRequest(request);
431 if (result != ERR_OK) {
432 return result;
433 }
434
435 if (request->IsAgentNotification()) {
436 bundleOption = new (std::nothrow) NotificationBundleOption(request->GetOwnerBundleName(),
437 request->GetOwnerUid());
438 } else {
439 bundleOption = GenerateBundleOption();
440 }
441
442 if (bundleOption == nullptr) {
443 return ERR_ANS_INVALID_BUNDLE;
444 }
445 ANS_LOGI(
446 "bundleName=%{public}s, uid=%{public}d", (bundleOption->GetBundleName()).c_str(), bundleOption->GetUid());
447 return ERR_OK;
448 }
449
PublishPreparedNotification(const sptr<NotificationRequest> & request,const sptr<NotificationBundleOption> & bundleOption)450 ErrCode AdvancedNotificationService::PublishPreparedNotification(
451 const sptr<NotificationRequest> &request, const sptr<NotificationBundleOption> &bundleOption)
452 {
453 HITRACE_METER_NAME(HITRACE_TAG_NOTIFICATION, __PRETTY_FUNCTION__);
454 ANS_LOGI("PublishPreparedNotification");
455 auto record = std::make_shared<NotificationRecord>();
456 record->request = request;
457 record->notification = new (std::nothrow) Notification(request);
458 if (record->notification == nullptr) {
459 ANS_LOGE("Failed to create notification.");
460 return ERR_ANS_NO_MEMORY;
461 }
462 record->bundleOption = bundleOption;
463 SetNotificationRemindType(record->notification, true);
464
465 ErrCode result = ERR_OK;
466 handler_->PostSyncTask(std::bind([&]() {
467 result = AssignValidNotificationSlot(record);
468 if (result != ERR_OK) {
469 ANS_LOGE("Can not assign valid slot!");
470 return;
471 }
472
473 result = Filter(record);
474 if (result != ERR_OK) {
475 ANS_LOGE("Reject by filters: %{public}d", result);
476 return;
477 }
478
479 result = AssignToNotificationList(record);
480 if (result != ERR_OK) {
481 return;
482 }
483 UpdateRecentNotification(record->notification, false, 0);
484 sptr<NotificationSortingMap> sortingMap = GenerateSortingMap();
485 ReportInfoToResourceSchedule(request->GetCreatorUserId(), bundleOption->GetBundleName());
486 NotificationSubscriberManager::GetInstance()->NotifyConsumed(record->notification, sortingMap);
487 #ifdef DISTRIBUTED_NOTIFICATION_SUPPORTED
488 if (!request->IsAgentNotification()) {
489 DoDistributedPublish(bundleOption, record);
490 }
491 #endif
492 }));
493 return result;
494 }
495
Publish(const std::string & label,const sptr<NotificationRequest> & request)496 ErrCode AdvancedNotificationService::Publish(const std::string &label, const sptr<NotificationRequest> &request)
497 {
498 HITRACE_METER_NAME(HITRACE_TAG_NOTIFICATION, __PRETTY_FUNCTION__);
499 ANS_LOGD("%{public}s", __FUNCTION__);
500
501 if (!request) {
502 ANSR_LOGE("ReminderRequest object is nullptr");
503 return ERR_ANS_INVALID_PARAM;
504 }
505 ErrCode result = ERR_OK;
506 bool isSubsystem = AccessTokenHelper::VerifyNativeToken(IPCSkeleton::GetCallingTokenID());
507 if (isSubsystem) {
508 return PublishNotificationBySa(request);
509 }
510
511 do {
512 if (request->GetReceiverUserId() != SUBSCRIBE_USER_INIT && !IsSystemApp()) {
513 result = ERR_ANS_NON_SYSTEM_APP;
514 break;
515 }
516
517 Security::AccessToken::AccessTokenID callerToken = IPCSkeleton::GetCallingTokenID();
518 if (AccessTokenHelper::IsDlpHap(callerToken)) {
519 result = ERR_ANS_DLP_HAP;
520 ANS_LOGE("DLP hap not allowed to send notifications");
521 break;
522 }
523
524 sptr<NotificationBundleOption> bundleOption;
525 result = PrepareNotificationInfo(request, bundleOption);
526 if (result != ERR_OK) {
527 break;
528 }
529
530 result = PublishPreparedNotification(request, bundleOption);
531 if (result != ERR_OK) {
532 break;
533 }
534 } while (0);
535
536 SendPublishHiSysEvent(request, result);
537 return result;
538 }
539
ReportInfoToResourceSchedule(const int32_t userId,const std::string & bundleName)540 void AdvancedNotificationService::ReportInfoToResourceSchedule(const int32_t userId, const std::string &bundleName)
541 {
542 #ifdef DEVICE_USAGE_STATISTICS_ENABLE
543 DeviceUsageStats::BundleActiveEvent event(DeviceUsageStats::BundleActiveEvent::NOTIFICATION_SEEN, bundleName);
544 DeviceUsageStats::BundleActiveClient::GetInstance().ReportEvent(event, userId);
545 #endif
546 }
547
IsNotificationExists(const std::string & key)548 bool AdvancedNotificationService::IsNotificationExists(const std::string &key)
549 {
550 bool isExists = false;
551
552 for (auto item : notificationList_) {
553 if (item->notification->GetKey() == key) {
554 isExists = true;
555 break;
556 }
557 }
558
559 return isExists;
560 }
561
Filter(const std::shared_ptr<NotificationRecord> & record)562 ErrCode AdvancedNotificationService::Filter(const std::shared_ptr<NotificationRecord> &record)
563 {
564 ErrCode result = ERR_OK;
565
566 for (auto filter : NOTIFICATION_FILTERS) {
567 result = filter->OnPublish(record);
568 if (result != ERR_OK) {
569 break;
570 }
571 }
572
573 return result;
574 }
575
AddToNotificationList(const std::shared_ptr<NotificationRecord> & record)576 void AdvancedNotificationService::AddToNotificationList(const std::shared_ptr<NotificationRecord> &record)
577 {
578 notificationList_.push_back(record);
579 SortNotificationList();
580 }
581
UpdateInNotificationList(const std::shared_ptr<NotificationRecord> & record)582 void AdvancedNotificationService::UpdateInNotificationList(const std::shared_ptr<NotificationRecord> &record)
583 {
584 auto iter = notificationList_.begin();
585 while (iter != notificationList_.end()) {
586 if ((*iter)->notification->GetKey() == record->notification->GetKey()) {
587 *iter = record;
588 break;
589 }
590 iter++;
591 }
592
593 SortNotificationList();
594 }
595
SortNotificationList()596 void AdvancedNotificationService::SortNotificationList()
597 {
598 notificationList_.sort(AdvancedNotificationService::NotificationCompare);
599 }
600
NotificationCompare(const std::shared_ptr<NotificationRecord> & first,const std::shared_ptr<NotificationRecord> & second)601 bool AdvancedNotificationService::NotificationCompare(
602 const std::shared_ptr<NotificationRecord> &first, const std::shared_ptr<NotificationRecord> &second)
603 {
604 // sorting notifications by create time
605 return (first->request->GetCreateTime() < second->request->GetCreateTime());
606 }
607
GenerateSortingMap()608 sptr<NotificationSortingMap> AdvancedNotificationService::GenerateSortingMap()
609 {
610 std::vector<NotificationSorting> sortingList;
611 for (auto record : notificationList_) {
612 NotificationSorting sorting;
613 sorting.SetRanking(static_cast<uint64_t>(sortingList.size()));
614 sorting.SetKey(record->notification->GetKey());
615 sorting.SetSlot(record->slot);
616 sortingList.push_back(sorting);
617 }
618
619 sptr<NotificationSortingMap> sortingMap = new NotificationSortingMap(sortingList);
620
621 return sortingMap;
622 }
623
StartFilters()624 void AdvancedNotificationService::StartFilters()
625 {
626 for (auto filter : NOTIFICATION_FILTERS) {
627 filter->OnStart();
628 }
629 }
630
StopFilters()631 void AdvancedNotificationService::StopFilters()
632 {
633 for (auto filter : NOTIFICATION_FILTERS) {
634 filter->OnStop();
635 }
636 }
637
Cancel(int32_t notificationId,const std::string & label)638 ErrCode AdvancedNotificationService::Cancel(int32_t notificationId, const std::string &label)
639 {
640 ANS_LOGD("%{public}s", __FUNCTION__);
641
642 sptr<NotificationBundleOption> bundleOption = GenerateBundleOption();
643 return CancelPreparedNotification(notificationId, label, bundleOption);
644 }
645
CancelAll()646 ErrCode AdvancedNotificationService::CancelAll()
647 {
648 ANS_LOGD("%{public}s", __FUNCTION__);
649
650 sptr<NotificationBundleOption> bundleOption = GenerateBundleOption();
651 if (bundleOption == nullptr) {
652 return ERR_ANS_INVALID_BUNDLE;
653 }
654
655 ErrCode result = ERR_OK;
656
657 handler_->PostSyncTask(std::bind([&]() {
658 sptr<Notification> notification = nullptr;
659
660 std::vector<std::string> keys = GetNotificationKeys(bundleOption);
661 for (auto key : keys) {
662 #ifdef DISTRIBUTED_NOTIFICATION_SUPPORTED
663 std::string deviceId;
664 std::string bundleName;
665 GetDistributedInfo(key, deviceId, bundleName);
666 #endif
667 result = RemoveFromNotificationList(key, notification, true,
668 NotificationConstant::APP_CANCEL_ALL_REASON_DELETE);
669 if (result != ERR_OK) {
670 continue;
671 }
672
673 if (notification != nullptr) {
674 int32_t reason = NotificationConstant::APP_CANCEL_ALL_REASON_DELETE;
675 UpdateRecentNotification(notification, true, reason);
676 sptr<NotificationSortingMap> sortingMap = GenerateSortingMap();
677 NotificationSubscriberManager::GetInstance()->NotifyCanceled(notification, sortingMap, reason);
678 #ifdef DISTRIBUTED_NOTIFICATION_SUPPORTED
679 DoDistributedDelete(deviceId, bundleName, notification);
680 #endif
681 }
682 }
683
684 result = ERR_OK;
685 }));
686 return result;
687 }
688
CancelAsBundle(int32_t notificationId,const std::string & representativeBundle,int32_t userId)689 ErrCode AdvancedNotificationService::CancelAsBundle(
690 int32_t notificationId, const std::string &representativeBundle, int32_t userId)
691 {
692 ANS_LOGD("%{public}s", __FUNCTION__);
693
694 if (!IsSystemApp()) {
695 return ERR_ANS_NON_SYSTEM_APP;
696 }
697
698 if (!CheckPermission(OHOS_PERMISSION_NOTIFICATION_CONTROLLER) ||
699 !CheckPermission(OHOS_PERMISSION_NOTIFICATION_AGENT_CONTROLLER)) {
700 return ERR_ANS_PERMISSION_DENIED;
701 }
702
703 int32_t uid = -1;
704 std::shared_ptr<BundleManagerHelper> bundleManager = BundleManagerHelper::GetInstance();
705 if (bundleManager != nullptr) {
706 uid = BundleManagerHelper::GetInstance()->GetDefaultUidByBundleName(representativeBundle, userId);
707 }
708 if (uid < 0) {
709 return ERR_ANS_INVALID_UID;
710 }
711 sptr<NotificationBundleOption> bundleOption = new (std::nothrow) NotificationBundleOption(
712 representativeBundle, uid);
713 return CancelPreparedNotification(notificationId, "", bundleOption);
714 }
715
AddSlots(const std::vector<sptr<NotificationSlot>> & slots)716 ErrCode AdvancedNotificationService::AddSlots(const std::vector<sptr<NotificationSlot>> &slots)
717 {
718 ANS_LOGD("%{public}s", __FUNCTION__);
719
720 if (!IsSystemApp()) {
721 return ERR_ANS_NON_SYSTEM_APP;
722 }
723
724 if (!CheckPermission(OHOS_PERMISSION_NOTIFICATION_CONTROLLER)) {
725 return ERR_ANS_PERMISSION_DENIED;
726 }
727
728 sptr<NotificationBundleOption> bundleOption = GenerateBundleOption();
729 if (bundleOption == nullptr) {
730 return ERR_ANS_INVALID_BUNDLE;
731 }
732
733 if (slots.size() == 0) {
734 return ERR_ANS_INVALID_PARAM;
735 }
736
737 ErrCode result = ERR_OK;
738 handler_->PostSyncTask(std::bind([&]() {
739 std::vector<sptr<NotificationSlot>> addSlots;
740 for (auto slot : slots) {
741 sptr<NotificationSlot> originalSlot;
742 result =
743 NotificationPreferences::GetInstance().GetNotificationSlot(bundleOption, slot->GetType(), originalSlot);
744 if ((result == ERR_OK) && (originalSlot != nullptr)) {
745 continue;
746 } else {
747 addSlots.push_back(slot);
748 }
749 }
750
751 if (addSlots.size() == 0) {
752 result = ERR_OK;
753 } else {
754 result = NotificationPreferences::GetInstance().AddNotificationSlots(bundleOption, addSlots);
755 }
756 }));
757 return result;
758 }
759
GetSlots(std::vector<sptr<NotificationSlot>> & slots)760 ErrCode AdvancedNotificationService::GetSlots(std::vector<sptr<NotificationSlot>> &slots)
761 {
762 ANS_LOGD("%{public}s", __FUNCTION__);
763
764 sptr<NotificationBundleOption> bundleOption = GenerateBundleOption();
765 if (bundleOption == nullptr) {
766 return ERR_ANS_INVALID_BUNDLE;
767 }
768
769 ErrCode result = ERR_OK;
770 handler_->PostSyncTask(std::bind([&]() {
771 result = NotificationPreferences::GetInstance().GetNotificationAllSlots(bundleOption, slots);
772 if (result == ERR_ANS_PREFERENCES_NOTIFICATION_BUNDLE_NOT_EXIST) {
773 result = ERR_OK;
774 slots.clear();
775 }
776 }));
777 return result;
778 }
779
GetActiveNotifications(std::vector<sptr<NotificationRequest>> & notifications)780 ErrCode AdvancedNotificationService::GetActiveNotifications(std::vector<sptr<NotificationRequest>> ¬ifications)
781 {
782 ANS_LOGD("%{public}s", __FUNCTION__);
783
784 sptr<NotificationBundleOption> bundleOption = GenerateBundleOption();
785 if (bundleOption == nullptr) {
786 return ERR_ANS_INVALID_BUNDLE;
787 }
788
789 ErrCode result = ERR_OK;
790 handler_->PostSyncTask(std::bind([&]() {
791 notifications.clear();
792 for (auto record : notificationList_) {
793 if ((record->bundleOption->GetBundleName() == bundleOption->GetBundleName()) &&
794 (record->bundleOption->GetUid() == bundleOption->GetUid())) {
795 notifications.push_back(record->request);
796 }
797 }
798 }));
799 return result;
800 }
801
GetActiveNotificationNums(uint64_t & num)802 ErrCode AdvancedNotificationService::GetActiveNotificationNums(uint64_t &num)
803 {
804 ANS_LOGD("%{public}s", __FUNCTION__);
805
806 sptr<NotificationBundleOption> bundleOption = GenerateBundleOption();
807 if (bundleOption == nullptr) {
808 return ERR_ANS_INVALID_BUNDLE;
809 }
810
811 ErrCode result = ERR_OK;
812 handler_->PostSyncTask(std::bind([&]() {
813 size_t count = 0;
814 for (auto record : notificationList_) {
815 if ((record->bundleOption->GetBundleName() == bundleOption->GetBundleName()) &&
816 (record->bundleOption->GetUid() == bundleOption->GetUid())) {
817 count += 1;
818 }
819 }
820 num = static_cast<uint64_t>(count);
821 }));
822 return result;
823 }
824
SetNotificationAgent(const std::string & agent)825 ErrCode AdvancedNotificationService::SetNotificationAgent(const std::string &agent)
826 {
827 return ERR_INVALID_OPERATION;
828 }
829
GetNotificationAgent(std::string & agent)830 ErrCode AdvancedNotificationService::GetNotificationAgent(std::string &agent)
831 {
832 return ERR_INVALID_OPERATION;
833 }
834
CanPublishAsBundle(const std::string & representativeBundle,bool & canPublish)835 ErrCode AdvancedNotificationService::CanPublishAsBundle(const std::string &representativeBundle, bool &canPublish)
836 {
837 return ERR_INVALID_OPERATION;
838 }
839
PublishAsBundle(const sptr<NotificationRequest> notification,const std::string & representativeBundle)840 ErrCode AdvancedNotificationService::PublishAsBundle(
841 const sptr<NotificationRequest> notification, const std::string &representativeBundle)
842 {
843 return ERR_INVALID_OPERATION;
844 }
845
SetNotificationBadgeNum(int32_t num)846 ErrCode AdvancedNotificationService::SetNotificationBadgeNum(int32_t num)
847 {
848 ANS_LOGD("%{public}s", __FUNCTION__);
849
850 sptr<NotificationBundleOption> bundleOption = GenerateBundleOption();
851 if (bundleOption == nullptr) {
852 return ERR_ANS_INVALID_BUNDLE;
853 }
854
855 ErrCode result = ERR_OK;
856 handler_->PostSyncTask(
857 std::bind([&]() { result = NotificationPreferences::GetInstance().SetTotalBadgeNums(bundleOption, num); }));
858 return result;
859 }
860
GetBundleImportance(int32_t & importance)861 ErrCode AdvancedNotificationService::GetBundleImportance(int32_t &importance)
862 {
863 ANS_LOGD("%{public}s", __FUNCTION__);
864
865 sptr<NotificationBundleOption> bundleOption = GenerateBundleOption();
866 if (bundleOption == nullptr) {
867 return ERR_ANS_INVALID_BUNDLE;
868 }
869
870 ErrCode result = ERR_OK;
871 handler_->PostSyncTask(
872 std::bind([&]() { result = NotificationPreferences::GetInstance().GetImportance(bundleOption, importance); }));
873 return result;
874 }
875
HasNotificationPolicyAccessPermission(bool & granted)876 ErrCode AdvancedNotificationService::HasNotificationPolicyAccessPermission(bool &granted)
877 {
878 return ERR_OK;
879 }
880
SetPrivateNotificationsAllowed(bool allow)881 ErrCode AdvancedNotificationService::SetPrivateNotificationsAllowed(bool allow)
882 {
883 ANS_LOGD("%{public}s", __FUNCTION__);
884
885 sptr<NotificationBundleOption> bundleOption = GenerateBundleOption();
886 if (bundleOption == nullptr) {
887 return ERR_ANS_INVALID_BUNDLE;
888 }
889
890 ErrCode result = ERR_OK;
891 handler_->PostSyncTask(std::bind([&]() {
892 result = NotificationPreferences::GetInstance().SetPrivateNotificationsAllowed(bundleOption, allow);
893 }));
894 return result;
895 }
896
GetPrivateNotificationsAllowed(bool & allow)897 ErrCode AdvancedNotificationService::GetPrivateNotificationsAllowed(bool &allow)
898 {
899 ANS_LOGD("%{public}s", __FUNCTION__);
900
901 sptr<NotificationBundleOption> bundleOption = GenerateBundleOption();
902 if (bundleOption == nullptr) {
903 return ERR_ANS_INVALID_BUNDLE;
904 }
905
906 ErrCode result = ERR_OK;
907 handler_->PostSyncTask(std::bind([&]() {
908 result = NotificationPreferences::GetInstance().GetPrivateNotificationsAllowed(bundleOption, allow);
909 if (result == ERR_ANS_PREFERENCES_NOTIFICATION_BUNDLE_NOT_EXIST) {
910 result = ERR_OK;
911 allow = false;
912 }
913 }));
914 return result;
915 }
916
Delete(const std::string & key,int32_t removeReason)917 ErrCode AdvancedNotificationService::Delete(const std::string &key, int32_t removeReason)
918 {
919 ANS_LOGD("%{public}s", __FUNCTION__);
920
921 if (!IsSystemApp()) {
922 return ERR_ANS_NON_SYSTEM_APP;
923 }
924
925 if (!CheckPermission(OHOS_PERMISSION_NOTIFICATION_CONTROLLER)) {
926 return ERR_ANS_PERMISSION_DENIED;
927 }
928
929 ErrCode result = ERR_OK;
930
931 handler_->PostSyncTask(std::bind([&]() {
932 sptr<Notification> notification = nullptr;
933 #ifdef DISTRIBUTED_NOTIFICATION_SUPPORTED
934 std::string deviceId;
935 std::string bundleName;
936 GetDistributedInfo(key, deviceId, bundleName);
937 #endif
938 result = RemoveFromNotificationList(key, notification, false, removeReason);
939 if (result != ERR_OK) {
940 return;
941 }
942
943 if (notification != nullptr) {
944 UpdateRecentNotification(notification, true, removeReason);
945 sptr<NotificationSortingMap> sortingMap = GenerateSortingMap();
946 NotificationSubscriberManager::GetInstance()->NotifyCanceled(notification, sortingMap, removeReason);
947 #ifdef DISTRIBUTED_NOTIFICATION_SUPPORTED
948 DoDistributedDelete(deviceId, bundleName, notification);
949 #endif
950 }
951 }));
952
953 return result;
954 }
955
DeleteByBundle(const sptr<NotificationBundleOption> & bundleOption)956 ErrCode AdvancedNotificationService::DeleteByBundle(const sptr<NotificationBundleOption> &bundleOption)
957 {
958 ANS_LOGD("%{public}s", __FUNCTION__);
959
960 if (!IsSystemApp()) {
961 return ERR_ANS_NON_SYSTEM_APP;
962 }
963
964 if (!CheckPermission(OHOS_PERMISSION_NOTIFICATION_CONTROLLER)) {
965 return ERR_ANS_PERMISSION_DENIED;
966 }
967
968 sptr<NotificationBundleOption> bundle = GenerateValidBundleOption(bundleOption);
969 if (bundle == nullptr) {
970 return ERR_ANS_INVALID_BUNDLE;
971 }
972
973 ErrCode result = ERR_OK;
974 handler_->PostSyncTask(std::bind([&]() {
975 std::vector<std::string> keys = GetNotificationKeys(bundle);
976 for (auto key : keys) {
977 #ifdef DISTRIBUTED_NOTIFICATION_SUPPORTED
978 std::string deviceId;
979 std::string bundleName;
980 GetDistributedInfo(key, deviceId, bundleName);
981 #endif
982 sptr<Notification> notification = nullptr;
983
984 result = RemoveFromNotificationList(key, notification, false, NotificationConstant::CANCEL_REASON_DELETE);
985 if (result != ERR_OK) {
986 continue;
987 }
988
989 if (notification != nullptr) {
990 int32_t reason = NotificationConstant::CANCEL_REASON_DELETE;
991 UpdateRecentNotification(notification, true, reason);
992 sptr<NotificationSortingMap> sortingMap = GenerateSortingMap();
993 NotificationSubscriberManager::GetInstance()->NotifyCanceled(notification, sortingMap, reason);
994 #ifdef DISTRIBUTED_NOTIFICATION_SUPPORTED
995 DoDistributedDelete(deviceId, bundleName, notification);
996 #endif
997 }
998 }
999
1000 result = ERR_OK;
1001 }));
1002
1003 return result;
1004 }
1005
DeleteAll()1006 ErrCode AdvancedNotificationService::DeleteAll()
1007 {
1008 ANS_LOGD("%{public}s", __FUNCTION__);
1009
1010 if (!IsSystemApp()) {
1011 return ERR_ANS_NON_SYSTEM_APP;
1012 }
1013
1014 if (!CheckPermission(OHOS_PERMISSION_NOTIFICATION_CONTROLLER)) {
1015 return ERR_ANS_PERMISSION_DENIED;
1016 }
1017
1018 ErrCode result = ERR_OK;
1019 handler_->PostSyncTask(std::bind([&]() {
1020 int32_t activeUserId = SUBSCRIBE_USER_INIT;
1021 (void)GetActiveUserId(activeUserId);
1022 std::vector<std::string> keys = GetNotificationKeys(nullptr);
1023 for (auto key : keys) {
1024 #ifdef DISTRIBUTED_NOTIFICATION_SUPPORTED
1025 std::string deviceId;
1026 std::string bundleName;
1027 GetDistributedInfo(key, deviceId, bundleName);
1028 #endif
1029 sptr<Notification> notification = nullptr;
1030
1031 result = RemoveFromNotificationListForDeleteAll(key, activeUserId, notification);
1032 if ((result != ERR_OK) || (notification == nullptr)) {
1033 continue;
1034 }
1035
1036 if (notification->GetUserId() == activeUserId) {
1037 int32_t reason = NotificationConstant::CANCEL_ALL_REASON_DELETE;
1038 UpdateRecentNotification(notification, true, reason);
1039 sptr<NotificationSortingMap> sortingMap = GenerateSortingMap();
1040 NotificationSubscriberManager::GetInstance()->NotifyCanceled(notification, sortingMap, reason);
1041 #ifdef DISTRIBUTED_NOTIFICATION_SUPPORTED
1042 DoDistributedDelete(deviceId, bundleName, notification);
1043 #endif
1044 }
1045 }
1046
1047 result = ERR_OK;
1048 }));
1049
1050 return result;
1051 }
1052
GetNotificationKeys(const sptr<NotificationBundleOption> & bundleOption)1053 std::vector<std::string> AdvancedNotificationService::GetNotificationKeys(
1054 const sptr<NotificationBundleOption> &bundleOption)
1055 {
1056 std::vector<std::string> keys;
1057
1058 for (auto record : notificationList_) {
1059 if ((bundleOption != nullptr) && (record->bundleOption->GetBundleName() != bundleOption->GetBundleName()) &&
1060 (record->bundleOption->GetUid() != bundleOption->GetUid())) {
1061 continue;
1062 }
1063 keys.push_back(record->notification->GetKey());
1064 }
1065
1066 return keys;
1067 }
1068
GetSlotsByBundle(const sptr<NotificationBundleOption> & bundleOption,std::vector<sptr<NotificationSlot>> & slots)1069 ErrCode AdvancedNotificationService::GetSlotsByBundle(
1070 const sptr<NotificationBundleOption> &bundleOption, std::vector<sptr<NotificationSlot>> &slots)
1071 {
1072 ANS_LOGD("%{public}s", __FUNCTION__);
1073
1074 if (!IsSystemApp()) {
1075 return ERR_ANS_NON_SYSTEM_APP;
1076 }
1077
1078 if (!CheckPermission(OHOS_PERMISSION_NOTIFICATION_CONTROLLER)) {
1079 return ERR_ANS_PERMISSION_DENIED;
1080 }
1081
1082 sptr<NotificationBundleOption> bundle = GenerateValidBundleOption(bundleOption);
1083 if (bundle == nullptr) {
1084 return ERR_ANS_INVALID_BUNDLE;
1085 }
1086
1087 ErrCode result = ERR_OK;
1088 handler_->PostSyncTask(std::bind([&]() {
1089 result = NotificationPreferences::GetInstance().GetNotificationAllSlots(bundle, slots);
1090 if (result == ERR_ANS_PREFERENCES_NOTIFICATION_BUNDLE_NOT_EXIST) {
1091 result = ERR_OK;
1092 slots.clear();
1093 }
1094 }));
1095 return result;
1096 }
1097
UpdateSlots(const sptr<NotificationBundleOption> & bundleOption,const std::vector<sptr<NotificationSlot>> & slots)1098 ErrCode AdvancedNotificationService::UpdateSlots(
1099 const sptr<NotificationBundleOption> &bundleOption, const std::vector<sptr<NotificationSlot>> &slots)
1100 {
1101 ANS_LOGD("%{public}s", __FUNCTION__);
1102
1103 if (!IsSystemApp()) {
1104 return ERR_ANS_NON_SYSTEM_APP;
1105 }
1106
1107 if (!CheckPermission(OHOS_PERMISSION_NOTIFICATION_CONTROLLER)) {
1108 return ERR_ANS_PERMISSION_DENIED;
1109 }
1110
1111 sptr<NotificationBundleOption> bundle = GenerateValidBundleOption(bundleOption);
1112 if (bundle == nullptr) {
1113 return ERR_ANS_INVALID_BUNDLE;
1114 }
1115
1116 ErrCode result = ERR_OK;
1117 handler_->PostSyncTask(std::bind([&]() {
1118 result = NotificationPreferences::GetInstance().UpdateNotificationSlots(bundle, slots);
1119 if (result == ERR_ANS_PREFERENCES_NOTIFICATION_BUNDLE_NOT_EXIST) {
1120 result = ERR_ANS_PREFERENCES_NOTIFICATION_SLOT_TYPE_NOT_EXIST;
1121 }
1122 }));
1123
1124 if (result == ERR_OK) {
1125 PublishSlotChangeCommonEvent(bundle);
1126 }
1127
1128 return result;
1129 }
1130
SetShowBadgeEnabledForBundle(const sptr<NotificationBundleOption> & bundleOption,bool enabled)1131 ErrCode AdvancedNotificationService::SetShowBadgeEnabledForBundle(
1132 const sptr<NotificationBundleOption> &bundleOption, bool enabled)
1133 {
1134 ANS_LOGD("%{public}s", __FUNCTION__);
1135
1136 if (!IsSystemApp()) {
1137 return ERR_ANS_NON_SYSTEM_APP;
1138 }
1139
1140 if (!CheckPermission(OHOS_PERMISSION_NOTIFICATION_CONTROLLER)) {
1141 return ERR_ANS_PERMISSION_DENIED;
1142 }
1143
1144 sptr<NotificationBundleOption> bundle = GenerateValidBundleOption(bundleOption);
1145 if (bundle == nullptr) {
1146 return ERR_ANS_INVALID_BUNDLE;
1147 }
1148
1149 ErrCode result = ERR_OK;
1150 handler_->PostSyncTask(
1151 std::bind([&]() { result = NotificationPreferences::GetInstance().SetShowBadge(bundle, enabled); }));
1152 return result;
1153 }
1154
GetShowBadgeEnabledForBundle(const sptr<NotificationBundleOption> & bundleOption,bool & enabled)1155 ErrCode AdvancedNotificationService::GetShowBadgeEnabledForBundle(
1156 const sptr<NotificationBundleOption> &bundleOption, bool &enabled)
1157 {
1158 ANS_LOGD("%{public}s", __FUNCTION__);
1159
1160 if (!IsSystemApp()) {
1161 return ERR_ANS_NON_SYSTEM_APP;
1162 }
1163
1164 if (!CheckPermission(OHOS_PERMISSION_NOTIFICATION_CONTROLLER)) {
1165 return ERR_ANS_PERMISSION_DENIED;
1166 }
1167
1168 sptr<NotificationBundleOption> bundle = GenerateValidBundleOption(bundleOption);
1169 if (bundle == nullptr) {
1170 return ERR_ANS_INVALID_BUNDLE;
1171 }
1172
1173 ErrCode result = ERR_OK;
1174 handler_->PostSyncTask(std::bind([&]() {
1175 result = NotificationPreferences::GetInstance().IsShowBadge(bundle, enabled);
1176 if (result == ERR_ANS_PREFERENCES_NOTIFICATION_BUNDLE_NOT_EXIST) {
1177 result = ERR_OK;
1178 enabled = false;
1179 }
1180 }));
1181 return result;
1182 }
1183
GetShowBadgeEnabled(bool & enabled)1184 ErrCode AdvancedNotificationService::GetShowBadgeEnabled(bool &enabled)
1185 {
1186 ANS_LOGD("%{public}s", __FUNCTION__);
1187
1188 sptr<NotificationBundleOption> bundleOption = GenerateBundleOption();
1189 if (bundleOption == nullptr) {
1190 return ERR_ANS_INVALID_BUNDLE;
1191 }
1192
1193 ErrCode result = ERR_OK;
1194 handler_->PostSyncTask(std::bind([&]() {
1195 result = NotificationPreferences::GetInstance().IsShowBadge(bundleOption, enabled);
1196 if (result == ERR_ANS_PREFERENCES_NOTIFICATION_BUNDLE_NOT_EXIST) {
1197 result = ERR_OK;
1198 enabled = false;
1199 }
1200 }));
1201 return result;
1202 }
1203
RemoveFromNotificationList(const sptr<NotificationBundleOption> & bundleOption,const std::string & label,int32_t notificationId,sptr<Notification> & notification,bool isCancel)1204 ErrCode AdvancedNotificationService::RemoveFromNotificationList(const sptr<NotificationBundleOption> &bundleOption,
1205 const std::string &label, int32_t notificationId, sptr<Notification> ¬ification, bool isCancel)
1206 {
1207 for (auto record : notificationList_) {
1208 if ((record->bundleOption->GetBundleName() == bundleOption->GetBundleName()) &&
1209 (record->bundleOption->GetUid() == bundleOption->GetUid()) &&
1210 (record->notification->GetLabel() == label) &&
1211 (record->notification->GetId() == notificationId)
1212 #ifdef DISTRIBUTED_NOTIFICATION_SUPPORTED
1213 && record->deviceId.empty()
1214 #endif
1215 ) {
1216 if (!isCancel && !record->notification->IsRemoveAllowed()) {
1217 return ERR_ANS_NOTIFICATION_IS_UNALLOWED_REMOVEALLOWED;
1218 }
1219 notification = record->notification;
1220 // delete or delete all, call the function
1221 if (!isCancel) {
1222 TriggerRemoveWantAgent(record->request);
1223 }
1224 notificationList_.remove(record);
1225 return ERR_OK;
1226 }
1227 }
1228
1229 return ERR_ANS_NOTIFICATION_NOT_EXISTS;
1230 }
1231
RemoveFromNotificationList(const std::string & key,sptr<Notification> & notification,bool isCancel,int32_t removeReason)1232 ErrCode AdvancedNotificationService::RemoveFromNotificationList(
1233 const std::string &key, sptr<Notification> ¬ification, bool isCancel, int32_t removeReason)
1234 {
1235 for (auto record : notificationList_) {
1236 if (record->notification->GetKey() == key) {
1237 if (!isCancel && !record->notification->IsRemoveAllowed()) {
1238 return ERR_ANS_NOTIFICATION_IS_UNALLOWED_REMOVEALLOWED;
1239 }
1240 notification = record->notification;
1241 // delete or delete all, call the function
1242 if (!isCancel && removeReason != NotificationConstant::CLICK_REASON_DELETE) {
1243 TriggerRemoveWantAgent(record->request);
1244 }
1245 notificationList_.remove(record);
1246 return ERR_OK;
1247 }
1248 }
1249
1250 return ERR_ANS_NOTIFICATION_NOT_EXISTS;
1251 }
1252
RemoveFromNotificationListForDeleteAll(const std::string & key,const int32_t & userId,sptr<Notification> & notification)1253 ErrCode AdvancedNotificationService::RemoveFromNotificationListForDeleteAll(
1254 const std::string &key, const int32_t &userId, sptr<Notification> ¬ification)
1255 {
1256 for (auto record : notificationList_) {
1257 if ((record->notification->GetKey() == key) && (record->notification->GetUserId() == userId)) {
1258 if (!record->notification->IsRemoveAllowed()) {
1259 return ERR_ANS_NOTIFICATION_IS_UNALLOWED_REMOVEALLOWED;
1260 }
1261 if (record->request->IsUnremovable()) {
1262 return ERR_ANS_NOTIFICATION_IS_UNREMOVABLE;
1263 }
1264 notification = record->notification;
1265 notificationList_.remove(record);
1266 return ERR_OK;
1267 }
1268 }
1269
1270 return ERR_ANS_NOTIFICATION_NOT_EXISTS;
1271 }
1272
Subscribe(const sptr<AnsSubscriberInterface> & subscriber,const sptr<NotificationSubscribeInfo> & info)1273 ErrCode AdvancedNotificationService::Subscribe(
1274 const sptr<AnsSubscriberInterface> &subscriber, const sptr<NotificationSubscribeInfo> &info)
1275 {
1276 HITRACE_METER_NAME(HITRACE_TAG_NOTIFICATION, __PRETTY_FUNCTION__);
1277 ANS_LOGD("%{public}s", __FUNCTION__);
1278
1279 ErrCode errCode = ERR_OK;
1280 do {
1281 if (subscriber == nullptr) {
1282 errCode = ERR_ANS_INVALID_PARAM;
1283 break;
1284 }
1285
1286 bool isSubsystem = AccessTokenHelper::VerifyNativeToken(IPCSkeleton::GetCallingTokenID());
1287 if (!IsSystemApp() && !isSubsystem) {
1288 ANS_LOGE("Client is not a system app or subsystem");
1289 errCode = ERR_ANS_NON_SYSTEM_APP;
1290 break;
1291 }
1292
1293 if (!CheckPermission(OHOS_PERMISSION_NOTIFICATION_CONTROLLER)) {
1294 errCode = ERR_ANS_PERMISSION_DENIED;
1295 break;
1296 }
1297
1298 errCode = NotificationSubscriberManager::GetInstance()->AddSubscriber(subscriber, info);
1299 if (errCode != ERR_OK) {
1300 break;
1301 }
1302 } while (0);
1303
1304 SendSubscribeHiSysEvent(IPCSkeleton::GetCallingPid(), IPCSkeleton::GetCallingUid(), info, errCode);
1305 return errCode;
1306 }
1307
Unsubscribe(const sptr<AnsSubscriberInterface> & subscriber,const sptr<NotificationSubscribeInfo> & info)1308 ErrCode AdvancedNotificationService::Unsubscribe(
1309 const sptr<AnsSubscriberInterface> &subscriber, const sptr<NotificationSubscribeInfo> &info)
1310 {
1311 HITRACE_METER_NAME(HITRACE_TAG_NOTIFICATION, __PRETTY_FUNCTION__);
1312 ANS_LOGD("%{public}s", __FUNCTION__);
1313
1314 SendUnSubscribeHiSysEvent(IPCSkeleton::GetCallingPid(), IPCSkeleton::GetCallingUid(), info);
1315
1316 bool isSubsystem = AccessTokenHelper::VerifyNativeToken(IPCSkeleton::GetCallingTokenID());
1317 if (!IsSystemApp() && !isSubsystem) {
1318 ANS_LOGE("Client is not a system app or subsystem");
1319 return ERR_ANS_NON_SYSTEM_APP;
1320 }
1321
1322 if (!CheckPermission(OHOS_PERMISSION_NOTIFICATION_CONTROLLER)) {
1323 return ERR_ANS_PERMISSION_DENIED;
1324 }
1325
1326 if (subscriber == nullptr) {
1327 return ERR_ANS_INVALID_PARAM;
1328 }
1329
1330 ErrCode errCode = NotificationSubscriberManager::GetInstance()->RemoveSubscriber(subscriber, info);
1331 if (errCode != ERR_OK) {
1332 return errCode;
1333 }
1334
1335 return ERR_OK;
1336 }
1337
GetSlotByType(const NotificationConstant::SlotType & slotType,sptr<NotificationSlot> & slot)1338 ErrCode AdvancedNotificationService::GetSlotByType(
1339 const NotificationConstant::SlotType &slotType, sptr<NotificationSlot> &slot)
1340 {
1341 ANS_LOGD("%{public}s", __FUNCTION__);
1342
1343 sptr<NotificationBundleOption> bundleOption = GenerateBundleOption();
1344 if (bundleOption == nullptr) {
1345 return ERR_ANS_INVALID_BUNDLE;
1346 }
1347
1348 handler_->PostSyncTask(std::bind([&]() {
1349 NotificationPreferences::GetInstance().GetNotificationSlot(bundleOption, slotType, slot);
1350 }));
1351 // if get slot failed, it still return ok.
1352 return ERR_OK;
1353 }
1354
RemoveSlotByType(const NotificationConstant::SlotType & slotType)1355 ErrCode AdvancedNotificationService::RemoveSlotByType(const NotificationConstant::SlotType &slotType)
1356 {
1357 ANS_LOGD("%{public}s", __FUNCTION__);
1358
1359 sptr<NotificationBundleOption> bundleOption = GenerateBundleOption();
1360 if (bundleOption == nullptr) {
1361 return ERR_ANS_INVALID_BUNDLE;
1362 }
1363
1364 handler_->PostSyncTask(std::bind([&]() {
1365 NotificationPreferences::GetInstance().RemoveNotificationSlot(bundleOption, slotType);
1366 }));
1367 // if remove slot failed, it still return ok.
1368 return ERR_OK;
1369 }
1370
GetAllActiveNotifications(std::vector<sptr<Notification>> & notifications)1371 ErrCode AdvancedNotificationService::GetAllActiveNotifications(std::vector<sptr<Notification>> ¬ifications)
1372 {
1373 ANS_LOGD("%{public}s", __FUNCTION__);
1374
1375 bool isSubsystem = AccessTokenHelper::VerifyNativeToken(IPCSkeleton::GetCallingTokenID());
1376 if (!IsSystemApp() && !isSubsystem) {
1377 return ERR_ANS_NON_SYSTEM_APP;
1378 }
1379
1380 if (!CheckPermission(OHOS_PERMISSION_NOTIFICATION_CONTROLLER)) {
1381 return ERR_ANS_PERMISSION_DENIED;
1382 }
1383
1384 ErrCode result = ERR_OK;
1385 handler_->PostSyncTask(std::bind([&]() {
1386 notifications.clear();
1387 for (auto record : notificationList_) {
1388 if (record->notification != nullptr) {
1389 notifications.push_back(record->notification);
1390 }
1391 }
1392 }));
1393 return result;
1394 }
1395
IsContained(const std::vector<std::string> & vec,const std::string & target)1396 inline bool IsContained(const std::vector<std::string> &vec, const std::string &target)
1397 {
1398 bool isContained = false;
1399
1400 auto iter = vec.begin();
1401 while (iter != vec.end()) {
1402 if (*iter == target) {
1403 isContained = true;
1404 break;
1405 }
1406 iter++;
1407 }
1408
1409 return isContained;
1410 }
1411
GetSpecialActiveNotifications(const std::vector<std::string> & key,std::vector<sptr<Notification>> & notifications)1412 ErrCode AdvancedNotificationService::GetSpecialActiveNotifications(
1413 const std::vector<std::string> &key, std::vector<sptr<Notification>> ¬ifications)
1414 {
1415 ANS_LOGD("%{public}s", __FUNCTION__);
1416
1417 if (!IsSystemApp()) {
1418 return ERR_ANS_NON_SYSTEM_APP;
1419 }
1420
1421 if (!CheckPermission(OHOS_PERMISSION_NOTIFICATION_CONTROLLER)) {
1422 return ERR_ANS_PERMISSION_DENIED;
1423 }
1424
1425 ErrCode result = ERR_OK;
1426 handler_->PostSyncTask(std::bind([&]() {
1427 for (auto record : notificationList_) {
1428 if (IsContained(key, record->notification->GetKey())) {
1429 notifications.push_back(record->notification);
1430 }
1431 }
1432 }));
1433 return result;
1434 }
1435
RequestEnableNotification(const std::string & deviceId)1436 ErrCode AdvancedNotificationService::RequestEnableNotification(const std::string &deviceId)
1437 {
1438 ANS_LOGD("%{public}s", __FUNCTION__);
1439
1440 ErrCode result = ERR_OK;
1441 sptr<NotificationBundleOption> bundleOption = GenerateBundleOption();
1442 if (bundleOption == nullptr) {
1443 ANS_LOGD("bundleOption == nullptr");
1444 return ERR_ANS_INVALID_BUNDLE;
1445 }
1446
1447 // To get the permission
1448 bool allowedNotify = false;
1449 result = IsAllowedNotifySelf(bundleOption, allowedNotify);
1450 ANS_LOGI("result = %{public}d, allowedNotify = %{public}d", result, allowedNotify);
1451 if (result != ERR_OK || allowedNotify) {
1452 ANS_LOGD("Already granted permission");
1453 return result;
1454 }
1455
1456 // Check to see if it has been popover before
1457 bool hasPopped = false;
1458 result = GetHasPoppedDialog(bundleOption, hasPopped);
1459 if (result != ERR_OK || hasPopped) {
1460 ANS_LOGD("Already shown dialog");
1461 return result;
1462 }
1463
1464 ANS_LOGI("hasPopped = %{public}d, allowedNotify = %{public}d", hasPopped, allowedNotify);
1465 if (!hasPopped && !allowedNotify) {
1466 auto notificationDialog = std::make_shared<NotificationDialog>();
1467 result = notificationDialog->StartEnableNotificationDialogAbility();
1468 if (result != ERR_OK) {
1469 ANS_LOGD("StartEnableNotificationDialogAbility failed, result = %{public}d", result);
1470 return result;
1471 }
1472 }
1473 SetHasPoppedDialog(bundleOption, true);
1474 return result;
1475 }
1476
SetNotificationsEnabledForBundle(const std::string & deviceId,bool enabled)1477 ErrCode AdvancedNotificationService::SetNotificationsEnabledForBundle(const std::string &deviceId, bool enabled)
1478 {
1479 return ERR_INVALID_OPERATION;
1480 }
1481
SetNotificationsEnabledForAllBundles(const std::string & deviceId,bool enabled)1482 ErrCode AdvancedNotificationService::SetNotificationsEnabledForAllBundles(const std::string &deviceId, bool enabled)
1483 {
1484 ANS_LOGD("%{public}s", __FUNCTION__);
1485
1486 if (!IsSystemApp()) {
1487 return ERR_ANS_NON_SYSTEM_APP;
1488 }
1489
1490 if (!CheckPermission(OHOS_PERMISSION_NOTIFICATION_CONTROLLER)) {
1491 return ERR_ANS_PERMISSION_DENIED;
1492 }
1493
1494 int32_t userId = SUBSCRIBE_USER_INIT;
1495 if (!GetActiveUserId(userId)) {
1496 return ERR_ANS_GET_ACTIVE_USER_FAILED;
1497 }
1498
1499 ErrCode result = ERR_OK;
1500 handler_->PostSyncTask(std::bind([&]() {
1501 if (deviceId.empty()) {
1502 // Local device
1503 result = NotificationPreferences::GetInstance().SetNotificationsEnabled(userId, enabled);
1504 } else {
1505 // Remote device
1506 }
1507 }));
1508 return result;
1509 }
1510
SetNotificationsEnabledForSpecialBundle(const std::string & deviceId,const sptr<NotificationBundleOption> & bundleOption,bool enabled)1511 ErrCode AdvancedNotificationService::SetNotificationsEnabledForSpecialBundle(
1512 const std::string &deviceId, const sptr<NotificationBundleOption> &bundleOption, bool enabled)
1513 {
1514 HITRACE_METER_NAME(HITRACE_TAG_NOTIFICATION, __PRETTY_FUNCTION__);
1515 ANS_LOGD("%{public}s", __FUNCTION__);
1516
1517 if (!IsSystemApp()) {
1518 return ERR_ANS_NON_SYSTEM_APP;
1519 }
1520
1521 if (!CheckPermission(OHOS_PERMISSION_NOTIFICATION_CONTROLLER)) {
1522 return ERR_ANS_PERMISSION_DENIED;
1523 }
1524
1525 sptr<NotificationBundleOption> bundle = GenerateValidBundleOption(bundleOption);
1526 if (bundle == nullptr) {
1527 return ERR_ANS_INVALID_BUNDLE;
1528 }
1529
1530 sptr<EnabledNotificationCallbackData> bundleData =
1531 new EnabledNotificationCallbackData(bundle->GetBundleName(), bundle->GetUid(), enabled);
1532
1533 ErrCode result = ERR_OK;
1534 handler_->PostSyncTask(std::bind([&]() {
1535 if (deviceId.empty()) {
1536 // Local device
1537 result = NotificationPreferences::GetInstance().SetNotificationsEnabledForBundle(bundle, enabled);
1538 if (!enabled) {
1539 result = RemoveAllNotifications(bundle);
1540 }
1541 if (result == ERR_OK) {
1542 NotificationSubscriberManager::GetInstance()->NotifyEnabledNotificationChanged(bundleData);
1543 PublishSlotChangeCommonEvent(bundle);
1544 }
1545 } else {
1546 // Remote revice
1547 }
1548 }));
1549
1550 SendEnableNotificationHiSysEvent(bundleOption, enabled, result);
1551 return result;
1552 }
1553
IsAllowedNotify(bool & allowed)1554 ErrCode AdvancedNotificationService::IsAllowedNotify(bool &allowed)
1555 {
1556 ANS_LOGD("%{public}s", __FUNCTION__);
1557
1558 if (!IsSystemApp()) {
1559 return ERR_ANS_NON_SYSTEM_APP;
1560 }
1561
1562 if (!CheckPermission(OHOS_PERMISSION_NOTIFICATION_CONTROLLER)) {
1563 return ERR_ANS_PERMISSION_DENIED;
1564 }
1565
1566 int32_t userId = SUBSCRIBE_USER_INIT;
1567 if (!GetActiveUserId(userId)) {
1568 return ERR_ANS_GET_ACTIVE_USER_FAILED;
1569 }
1570
1571 ErrCode result = ERR_OK;
1572 handler_->PostSyncTask(std::bind([&]() {
1573 allowed = false;
1574 result = NotificationPreferences::GetInstance().GetNotificationsEnabled(userId, allowed);
1575 }));
1576 return result;
1577 }
1578
IsAllowedNotifySelf(bool & allowed)1579 ErrCode AdvancedNotificationService::IsAllowedNotifySelf(bool &allowed)
1580 {
1581 ANS_LOGD("%{public}s", __FUNCTION__);
1582
1583 sptr<NotificationBundleOption> bundleOption = GenerateBundleOption();
1584 if (bundleOption == nullptr) {
1585 return ERR_ANS_INVALID_BUNDLE;
1586 }
1587 return IsAllowedNotifySelf(bundleOption, allowed);
1588 }
1589
IsAllowedNotifySelf(const sptr<NotificationBundleOption> & bundleOption,bool & allowed)1590 ErrCode AdvancedNotificationService::IsAllowedNotifySelf(const sptr<NotificationBundleOption> &bundleOption,
1591 bool &allowed)
1592 {
1593 ANS_LOGD("%{public}s", __FUNCTION__);
1594 if (bundleOption == nullptr) {
1595 return ERR_ANS_INVALID_BUNDLE;
1596 }
1597
1598 int32_t userId = SUBSCRIBE_USER_INIT;
1599 if (!GetActiveUserId(userId)) {
1600 return ERR_ANS_GET_ACTIVE_USER_FAILED;
1601 }
1602
1603 ErrCode result = ERR_OK;
1604 handler_->PostSyncTask(std::bind([&]() {
1605 allowed = false;
1606 result = NotificationPreferences::GetInstance().GetNotificationsEnabled(userId, allowed);
1607 if (result == ERR_OK && allowed) {
1608 result = NotificationPreferences::GetInstance().GetNotificationsEnabledForBundle(bundleOption, allowed);
1609 if (result == ERR_ANS_PREFERENCES_NOTIFICATION_BUNDLE_NOT_EXIST) {
1610 result = ERR_OK;
1611 allowed = CheckApiCompatibility(bundleOption);
1612 SetNotificationsEnabledForSpecialBundle("", bundleOption, allowed);
1613 }
1614 }
1615 }));
1616 return result;
1617 }
1618
GetAppTargetBundle(const sptr<NotificationBundleOption> & bundleOption,sptr<NotificationBundleOption> & targetBundle)1619 ErrCode AdvancedNotificationService::GetAppTargetBundle(const sptr<NotificationBundleOption> &bundleOption,
1620 sptr<NotificationBundleOption> &targetBundle)
1621 {
1622 sptr<NotificationBundleOption> clientBundle = GenerateBundleOption();
1623 if (clientBundle == nullptr) {
1624 return ERR_ANS_INVALID_BUNDLE;
1625 }
1626
1627 if (bundleOption == nullptr) {
1628 targetBundle = clientBundle;
1629 } else {
1630 if ((clientBundle->GetBundleName() == bundleOption->GetBundleName()) &&
1631 (clientBundle->GetUid() == bundleOption->GetUid())) {
1632 targetBundle = bundleOption;
1633 } else {
1634 if (!IsSystemApp()) {
1635 return ERR_ANS_NON_SYSTEM_APP;
1636 }
1637 targetBundle = GenerateValidBundleOption(bundleOption);
1638 }
1639 }
1640 return ERR_OK;
1641 }
1642
IsSpecialBundleAllowedNotify(const sptr<NotificationBundleOption> & bundleOption,bool & allowed)1643 ErrCode AdvancedNotificationService::IsSpecialBundleAllowedNotify(
1644 const sptr<NotificationBundleOption> &bundleOption, bool &allowed)
1645 {
1646 ANS_LOGD("%{public}s", __FUNCTION__);
1647
1648 if (!CheckPermission(OHOS_PERMISSION_NOTIFICATION_CONTROLLER)) {
1649 return ERR_ANS_PERMISSION_DENIED;
1650 }
1651
1652 sptr<NotificationBundleOption> targetBundle = nullptr;
1653 bool isSubsystem = AccessTokenHelper::VerifyNativeToken(IPCSkeleton::GetCallingTokenID());
1654 if (isSubsystem) {
1655 if (bundleOption != nullptr) {
1656 targetBundle = GenerateValidBundleOption(bundleOption);
1657 }
1658 } else {
1659 ErrCode result = GetAppTargetBundle(bundleOption, targetBundle);
1660 if (result != ERR_OK) {
1661 return result;
1662 }
1663 }
1664
1665 if (targetBundle == nullptr) {
1666 return ERR_ANS_INVALID_BUNDLE;
1667 }
1668
1669 int32_t userId = SUBSCRIBE_USER_INIT;
1670 if (!GetActiveUserId(userId)) {
1671 return ERR_ANS_GET_ACTIVE_USER_FAILED;
1672 }
1673
1674 ErrCode result = ERR_OK;
1675 handler_->PostSyncTask(std::bind([&]() {
1676 allowed = false;
1677 result = NotificationPreferences::GetInstance().GetNotificationsEnabled(userId, allowed);
1678 if (result == ERR_OK && allowed) {
1679 result = NotificationPreferences::GetInstance().GetNotificationsEnabledForBundle(targetBundle, allowed);
1680 if (result == ERR_ANS_PREFERENCES_NOTIFICATION_BUNDLE_NOT_EXIST) {
1681 result = ERR_OK;
1682 allowed = CheckApiCompatibility(targetBundle);
1683 SetNotificationsEnabledForSpecialBundle("", bundleOption, allowed);
1684 }
1685 }
1686 }));
1687 return result;
1688 }
1689
PublishContinuousTaskNotification(const sptr<NotificationRequest> & request)1690 ErrCode AdvancedNotificationService::PublishContinuousTaskNotification(const sptr<NotificationRequest> &request)
1691 {
1692 ANS_LOGD("%{public}s", __FUNCTION__);
1693
1694 bool isSubsystem = AccessTokenHelper::VerifyNativeToken(IPCSkeleton::GetCallingTokenID());
1695 if (!isSubsystem) {
1696 return ERR_ANS_NOT_SYSTEM_SERVICE;
1697 }
1698
1699 int32_t uid = IPCSkeleton::GetCallingUid();
1700 int32_t userId = SUBSCRIBE_USER_INIT;
1701 OHOS::AccountSA::OsAccountManager::GetOsAccountLocalIdFromUid(uid, userId);
1702 request->SetCreatorUserId(userId);
1703 ANS_LOGD("%{public}s, uid=%{public}d userId=%{public}d", __FUNCTION__, uid, userId);
1704
1705 if (request->GetCreatorBundleName().empty()) {
1706 request->SetCreatorBundleName(FOUNDATION_BUNDLE_NAME);
1707 }
1708
1709 if (request->GetOwnerBundleName().empty()) {
1710 request->SetOwnerBundleName(FOUNDATION_BUNDLE_NAME);
1711 }
1712
1713 sptr<NotificationBundleOption> bundleOption = nullptr;
1714 bundleOption = new NotificationBundleOption(std::string(), uid);
1715 if (bundleOption == nullptr) {
1716 return ERR_ANS_INVALID_BUNDLE;
1717 }
1718
1719 ErrCode result = PrepareContinuousTaskNotificationRequest(request, uid);
1720 if (result != ERR_OK) {
1721 return result;
1722 }
1723 request->SetUnremovable(true);
1724 std::shared_ptr<NotificationRecord> record = std::make_shared<NotificationRecord>();
1725 record->request = request;
1726 record->bundleOption = bundleOption;
1727 record->notification = new Notification(request);
1728 if (record->notification != nullptr) {
1729 record->notification->SetSourceType(NotificationConstant::SourceType::TYPE_CONTINUOUS);
1730 }
1731
1732 handler_->PostSyncTask(std::bind([&]() {
1733 if (!IsNotificationExists(record->notification->GetKey())) {
1734 AddToNotificationList(record);
1735 } else {
1736 if (record->request->IsAlertOneTime()) {
1737 record->notification->SetEnableLight(false);
1738 record->notification->SetEnableSound(false);
1739 record->notification->SetEnableVibration(false);
1740 }
1741 UpdateInNotificationList(record);
1742 }
1743
1744 UpdateRecentNotification(record->notification, false, 0);
1745 sptr<NotificationSortingMap> sortingMap = GenerateSortingMap();
1746 NotificationSubscriberManager::GetInstance()->NotifyConsumed(record->notification, sortingMap);
1747 }));
1748
1749 return result;
1750 }
1751
CancelContinuousTaskNotification(const std::string & label,int32_t notificationId)1752 ErrCode AdvancedNotificationService::CancelContinuousTaskNotification(const std::string &label, int32_t notificationId)
1753 {
1754 ANS_LOGD("%{public}s", __FUNCTION__);
1755
1756 bool isSubsystem = AccessTokenHelper::VerifyNativeToken(IPCSkeleton::GetCallingTokenID());
1757 if (!isSubsystem) {
1758 return ERR_ANS_NOT_SYSTEM_SERVICE;
1759 }
1760
1761 int32_t uid = IPCSkeleton::GetCallingUid();
1762 ErrCode result = ERR_OK;
1763 handler_->PostSyncTask(std::bind([&]() {
1764 sptr<Notification> notification = nullptr;
1765 for (auto record : notificationList_) {
1766 if ((record->bundleOption->GetBundleName().empty()) && (record->bundleOption->GetUid() == uid) &&
1767 (record->notification->GetId() == notificationId) && (record->notification->GetLabel() == label)) {
1768 notification = record->notification;
1769 notificationList_.remove(record);
1770 result = ERR_OK;
1771 break;
1772 }
1773 }
1774 if (notification != nullptr) {
1775 int32_t reason = NotificationConstant::APP_CANCEL_REASON_DELETE;
1776 UpdateRecentNotification(notification, true, reason);
1777 sptr<NotificationSortingMap> sortingMap = GenerateSortingMap();
1778 NotificationSubscriberManager::GetInstance()->NotifyCanceled(notification, sortingMap, reason);
1779 }
1780 }));
1781 return result;
1782 }
1783
PublishReminder(sptr<ReminderRequest> & reminder)1784 ErrCode AdvancedNotificationService::PublishReminder(sptr<ReminderRequest> &reminder)
1785 {
1786 ANSR_LOGI("Publish reminder");
1787 if (!reminder) {
1788 ANSR_LOGE("ReminderRequest object is nullptr");
1789 return ERR_ANS_INVALID_PARAM;
1790 }
1791
1792 Security::AccessToken::AccessTokenID callerToken = IPCSkeleton::GetCallingTokenID();
1793 ErrCode result = Security::AccessToken::AccessTokenKit::VerifyAccessToken(
1794 callerToken, "ohos.permission.PUBLISH_AGENT_REMINDER");
1795 if (result != Security::AccessToken::PermissionState::PERMISSION_GRANTED) {
1796 ANSR_LOGW("Permission denied: ohos.permission.PUBLISH_AGENT_REMINDER");
1797 return ERR_REMINDER_PERMISSION_DENIED;
1798 }
1799
1800 sptr<NotificationRequest> notificationRequest = reminder->GetNotificationRequest();
1801 sptr<NotificationBundleOption> bundleOption = nullptr;
1802 result = PrepareNotificationInfo(notificationRequest, bundleOption);
1803 if (result != ERR_OK) {
1804 ANSR_LOGW("PrepareNotificationInfo fail");
1805 return result;
1806 }
1807 bool allowedNotify = false;
1808 result = IsAllowedNotifySelf(bundleOption, allowedNotify);
1809 if (result != ERR_OK || !allowedNotify) {
1810 ANSR_LOGW("The application does not request enable notification");
1811 return ERR_REMINDER_NOTIFICATION_NOT_ENABLE;
1812 }
1813 auto rdm = ReminderDataManager::GetInstance();
1814 if (rdm == nullptr) {
1815 return ERR_NO_INIT;
1816 }
1817 return rdm->PublishReminder(reminder, bundleOption);
1818 }
1819
CancelReminder(const int32_t reminderId)1820 ErrCode AdvancedNotificationService::CancelReminder(const int32_t reminderId)
1821 {
1822 ANSR_LOGI("Cancel Reminder");
1823 sptr<NotificationBundleOption> bundleOption = GenerateBundleOption();
1824 if (bundleOption == nullptr) {
1825 return ERR_ANS_INVALID_BUNDLE;
1826 }
1827 auto rdm = ReminderDataManager::GetInstance();
1828 if (rdm == nullptr) {
1829 return ERR_NO_INIT;
1830 }
1831 return rdm->CancelReminder(reminderId, bundleOption);
1832 }
1833
CancelAllReminders()1834 ErrCode AdvancedNotificationService::CancelAllReminders()
1835 {
1836 ANSR_LOGI("Cancel all reminders");
1837 sptr<NotificationBundleOption> bundleOption = GenerateBundleOption();
1838 if (bundleOption == nullptr) {
1839 return ERR_ANS_INVALID_BUNDLE;
1840 }
1841 int32_t userId = -1;
1842 AccountSA::OsAccountManager::GetOsAccountLocalIdFromUid(bundleOption->GetUid(), userId);
1843 auto rdm = ReminderDataManager::GetInstance();
1844 if (rdm == nullptr) {
1845 return ERR_NO_INIT;
1846 }
1847 return rdm->CancelAllReminders(bundleOption->GetBundleName(), userId);
1848 }
1849
GetValidReminders(std::vector<sptr<ReminderRequest>> & reminders)1850 ErrCode AdvancedNotificationService::GetValidReminders(std::vector<sptr<ReminderRequest>> &reminders)
1851 {
1852 ANSR_LOGI("GetValidReminders");
1853 reminders.clear();
1854 sptr<NotificationBundleOption> bundleOption = GenerateBundleOption();
1855 if (bundleOption == nullptr) {
1856 return ERR_ANS_INVALID_BUNDLE;
1857 }
1858 auto rdm = ReminderDataManager::GetInstance();
1859 if (rdm == nullptr) {
1860 return ERR_NO_INIT;
1861 }
1862 rdm->GetValidReminders(bundleOption, reminders);
1863 ANSR_LOGD("Valid reminders size=%{public}zu", reminders.size());
1864 return ERR_OK;
1865 }
1866
ActiveNotificationDump(const std::string & bundle,int32_t userId,std::vector<std::string> & dumpInfo)1867 ErrCode AdvancedNotificationService::ActiveNotificationDump(const std::string& bundle, int32_t userId,
1868 std::vector<std::string> &dumpInfo)
1869 {
1870 ANS_LOGD("%{public}s", __FUNCTION__);
1871 std::stringstream stream;
1872 for (const auto &record : notificationList_) {
1873 if (record->notification == nullptr || record->request == nullptr) {
1874 continue;
1875 }
1876 if (userId != SUBSCRIBE_USER_INIT && userId != record->notification->GetUserId()) {
1877 continue;
1878 }
1879 if (!bundle.empty() && bundle != record->notification->GetBundleName()) {
1880 continue;
1881 }
1882 #ifdef DISTRIBUTED_NOTIFICATION_SUPPORTED
1883 if (!record->deviceId.empty()) {
1884 continue;
1885 }
1886 #endif
1887 stream.clear();
1888 stream.str("");
1889 stream << "\tUserId: " << record->notification->GetUserId() << "\n";
1890 stream << "\tCreatePid: " << record->request->GetCreatorPid() << "\n";
1891 stream << "\tOwnerBundleName: " << record->notification->GetBundleName() << "\n";
1892 if (record->request->GetOwnerUid() > 0) {
1893 stream << "\tOwnerUid: " << record->request->GetOwnerUid() << "\n";
1894 } else {
1895 stream << "\tOwnerUid: " << record->request->GetCreatorUid() << "\n";
1896 }
1897 stream << "\tDeliveryTime = " << TimeToString(record->request->GetDeliveryTime()) << "\n";
1898 stream << "\tNotification:\n";
1899 stream << "\t\tId: " << record->notification->GetId() << "\n";
1900 stream << "\t\tLabel: " << record->notification->GetLabel() << "\n";
1901 stream << "\t\tSlotType = " << record->request->GetSlotType() << "\n";
1902 dumpInfo.push_back(stream.str());
1903 }
1904 return ERR_OK;
1905 }
1906
RecentNotificationDump(const std::string & bundle,int32_t userId,std::vector<std::string> & dumpInfo)1907 ErrCode AdvancedNotificationService::RecentNotificationDump(const std::string& bundle, int32_t userId,
1908 std::vector<std::string> &dumpInfo)
1909 {
1910 ANS_LOGD("%{public}s", __FUNCTION__);
1911 std::stringstream stream;
1912 for (auto recentNotification : recentInfo_->list) {
1913 if (recentNotification->notification == nullptr) {
1914 continue;
1915 }
1916 const auto ¬ificationRequest = recentNotification->notification->GetNotificationRequest();
1917 if (userId != SUBSCRIBE_USER_INIT && userId != notificationRequest.GetOwnerUserId()) {
1918 continue;
1919 }
1920 if (!bundle.empty() && bundle != recentNotification->notification->GetBundleName()) {
1921 continue;
1922 }
1923 stream.clear();
1924 stream.str("");
1925 stream << "\tUserId: " << notificationRequest.GetCreatorUserId() << "\n";
1926 stream << "\tCreatePid: " << notificationRequest.GetCreatorPid() << "\n";
1927 stream << "\tBundleName: " << recentNotification->notification->GetBundleName() << "\n";
1928 if (notificationRequest.GetOwnerUid() > 0) {
1929 stream << "\tOwnerUid: " << notificationRequest.GetOwnerUid() << "\n";
1930 } else {
1931 stream << "\tOwnerUid: " << notificationRequest.GetCreatorUid() << "\n";
1932 }
1933 stream << "\tDeliveryTime = " << TimeToString(notificationRequest.GetDeliveryTime()) << "\n";
1934 if (!recentNotification->isActive) {
1935 stream << "\tDeleteTime: " << TimeToString(recentNotification->deleteTime) << "\n";
1936 stream << "\tDeleteReason: " << recentNotification->deleteReason << "\n";
1937 }
1938 stream << "\tNotification:\n";
1939 stream << "\t\tId: " << recentNotification->notification->GetId() << "\n";
1940 stream << "\t\tLabel: " << recentNotification->notification->GetLabel() << "\n";
1941 stream << "\t\tSlotType = " << notificationRequest.GetSlotType() << "\n";
1942 dumpInfo.push_back(stream.str());
1943 }
1944 return ERR_OK;
1945 }
1946
1947 #ifdef DISTRIBUTED_NOTIFICATION_SUPPORTED
DistributedNotificationDump(const std::string & bundle,int32_t userId,std::vector<std::string> & dumpInfo)1948 ErrCode AdvancedNotificationService::DistributedNotificationDump(const std::string& bundle, int32_t userId,
1949 std::vector<std::string> &dumpInfo)
1950 {
1951 ANS_LOGD("%{public}s", __FUNCTION__);
1952 std::stringstream stream;
1953 for (auto record : notificationList_) {
1954 if (record->notification == nullptr) {
1955 continue;
1956 }
1957 if (userId != SUBSCRIBE_USER_INIT && userId != record->notification->GetUserId()) {
1958 continue;
1959 }
1960 if (!bundle.empty() && bundle != record->notification->GetBundleName()) {
1961 continue;
1962 }
1963 if (record->deviceId.empty()) {
1964 continue;
1965 }
1966 stream.clear();
1967 stream.str("");
1968 stream << "\tUserId: " << record->notification->GetUserId() << "\n";
1969 stream << "\tCreatePid: " << record->request->GetCreatorPid() << "\n";
1970 stream << "\tOwnerBundleName: " << record->notification->GetBundleName() << "\n";
1971 if (record->request->GetOwnerUid() > 0) {
1972 stream << "\tOwnerUid: " << record->request->GetOwnerUid() << "\n";
1973 } else {
1974 stream << "\tOwnerUid: " << record->request->GetCreatorUid() << "\n";
1975 }
1976 stream << "\tDeliveryTime = " << TimeToString(record->request->GetDeliveryTime()) << "\n";
1977 stream << "\tNotification:\n";
1978 stream << "\t\tId: " << record->notification->GetId() << "\n";
1979 stream << "\t\tLabel: " << record->notification->GetLabel() << "\n";
1980 stream << "\t\tSlotType = " << record->request->GetSlotType() << "\n";
1981 dumpInfo.push_back(stream.str());
1982 }
1983
1984 return ERR_OK;
1985 }
1986 #endif
1987
SetRecentNotificationCount(const std::string arg)1988 ErrCode AdvancedNotificationService::SetRecentNotificationCount(const std::string arg)
1989 {
1990 ANS_LOGD("%{public}s arg = %{public}s", __FUNCTION__, arg.c_str());
1991 int32_t count = atoi(arg.c_str());
1992 if ((count < NOTIFICATION_MIN_COUNT) || (count > NOTIFICATION_MAX_COUNT)) {
1993 return ERR_ANS_INVALID_PARAM;
1994 }
1995
1996 recentInfo_->recentCount = count;
1997 while (recentInfo_->list.size() > recentInfo_->recentCount) {
1998 recentInfo_->list.pop_back();
1999 }
2000 return ERR_OK;
2001 }
2002
TimeToString(int64_t time)2003 std::string AdvancedNotificationService::TimeToString(int64_t time)
2004 {
2005 auto timePoint = std::chrono::time_point<std::chrono::system_clock>(std::chrono::milliseconds(time));
2006 auto timeT = std::chrono::system_clock::to_time_t(timePoint);
2007
2008 std::stringstream stream;
2009 struct tm ret = {0};
2010 localtime_r(&timeT, &ret);
2011 stream << std::put_time(&ret, "%F, %T");
2012 return stream.str();
2013 }
2014
GetNowSysTime()2015 int64_t AdvancedNotificationService::GetNowSysTime()
2016 {
2017 std::chrono::time_point<std::chrono::system_clock> nowSys = std::chrono::system_clock::now();
2018 auto epoch = nowSys.time_since_epoch();
2019 auto value = std::chrono::duration_cast<std::chrono::milliseconds>(epoch);
2020 int64_t duration = value.count();
2021 return duration;
2022 }
2023
UpdateRecentNotification(sptr<Notification> & notification,bool isDelete,int32_t reason)2024 void AdvancedNotificationService::UpdateRecentNotification(sptr<Notification> ¬ification,
2025 bool isDelete, int32_t reason)
2026 {
2027 for (auto recentNotification : recentInfo_->list) {
2028 if (recentNotification->notification->GetKey() == notification->GetKey()) {
2029 if (!isDelete) {
2030 recentInfo_->list.remove(recentNotification);
2031 recentNotification->isActive = true;
2032 recentNotification->notification = notification;
2033 recentInfo_->list.emplace_front(recentNotification);
2034 } else {
2035 recentNotification->isActive = false;
2036 recentNotification->deleteReason = reason;
2037 recentNotification->deleteTime = GetNowSysTime();
2038 }
2039 return;
2040 }
2041 }
2042
2043 if (!isDelete) {
2044 if (recentInfo_->list.size() >= recentInfo_->recentCount) {
2045 recentInfo_->list.pop_back();
2046 }
2047 auto recentNotification = std::make_shared<RecentNotification>();
2048 recentNotification->isActive = true;
2049 recentNotification->notification = notification;
2050 recentInfo_->list.emplace_front(recentNotification);
2051 }
2052 }
2053
RemoveExpired(std::list<std::chrono::system_clock::time_point> & list,const std::chrono::system_clock::time_point & now)2054 inline void RemoveExpired(
2055 std::list<std::chrono::system_clock::time_point> &list, const std::chrono::system_clock::time_point &now)
2056 {
2057 auto iter = list.begin();
2058 while (iter != list.end()) {
2059 if (abs(now - *iter) > std::chrono::seconds(1)) {
2060 iter = list.erase(iter);
2061 } else {
2062 break;
2063 }
2064 }
2065 }
2066
SortNotificationsByLevelAndTime(const std::shared_ptr<NotificationRecord> & first,const std::shared_ptr<NotificationRecord> & second)2067 static bool SortNotificationsByLevelAndTime(
2068 const std::shared_ptr<NotificationRecord> &first, const std::shared_ptr<NotificationRecord> &second)
2069 {
2070 if (first->slot->GetLevel() != second->slot->GetLevel()) {
2071 return (first->slot->GetLevel() < second->slot->GetLevel());
2072 }
2073 return (first->request->GetCreateTime() < second->request->GetCreateTime());
2074 }
2075
FlowControl(const std::shared_ptr<NotificationRecord> & record)2076 ErrCode AdvancedNotificationService::FlowControl(const std::shared_ptr<NotificationRecord> &record)
2077 {
2078 std::chrono::system_clock::time_point now = std::chrono::system_clock::now();
2079 RemoveExpired(flowControlTimestampList_, now);
2080 if (flowControlTimestampList_.size() >= MAX_ACTIVE_NUM_PERSECOND) {
2081 return ERR_ANS_OVER_MAX_ACTIVE_PERSECOND;
2082 }
2083
2084 flowControlTimestampList_.push_back(now);
2085
2086 std::list<std::shared_ptr<NotificationRecord>> bundleList;
2087 for (auto item : notificationList_) {
2088 if (record->notification->GetBundleName() == item->notification->GetBundleName()) {
2089 bundleList.push_back(item);
2090 }
2091 }
2092
2093 std::shared_ptr<NotificationRecord> recordToRemove;
2094 if (bundleList.size() >= MAX_ACTIVE_NUM_PERAPP) {
2095 bundleList.sort(SortNotificationsByLevelAndTime);
2096 recordToRemove = bundleList.front();
2097 SendFlowControlOccurHiSysEvent(recordToRemove);
2098 notificationList_.remove(bundleList.front());
2099 }
2100
2101 if (notificationList_.size() >= MAX_ACTIVE_NUM) {
2102 if (bundleList.size() > 0) {
2103 bundleList.sort(SortNotificationsByLevelAndTime);
2104 recordToRemove = bundleList.front();
2105 SendFlowControlOccurHiSysEvent(recordToRemove);
2106 notificationList_.remove(bundleList.front());
2107 } else {
2108 std::list<std::shared_ptr<NotificationRecord>> sorted = notificationList_;
2109 sorted.sort(SortNotificationsByLevelAndTime);
2110 recordToRemove = sorted.front();
2111 SendFlowControlOccurHiSysEvent(recordToRemove);
2112 notificationList_.remove(sorted.front());
2113 }
2114 }
2115
2116 AddToNotificationList(record);
2117
2118 return ERR_OK;
2119 }
2120
OnBundleRemoved(const sptr<NotificationBundleOption> & bundleOption)2121 void AdvancedNotificationService::OnBundleRemoved(const sptr<NotificationBundleOption> &bundleOption)
2122 {
2123 ANS_LOGD("%{public}s", __FUNCTION__);
2124
2125 handler_->PostTask(std::bind([this, bundleOption]() {
2126 ErrCode result = NotificationPreferences::GetInstance().RemoveNotificationForBundle(bundleOption);
2127 if (result != ERR_OK) {
2128 ANS_LOGW("NotificationPreferences::RemoveNotificationForBundle failed: %{public}d", result);
2129 }
2130 #ifdef DISTRIBUTED_NOTIFICATION_SUPPORTED
2131 DistributedPreferences::GetInstance()->DeleteDistributedBundleInfo(bundleOption);
2132 std::vector<std::string> keys = GetLocalNotificationKeys(bundleOption);
2133 #else
2134 std::vector<std::string> keys = GetNotificationKeys(bundleOption);
2135 #endif
2136 for (auto key : keys) {
2137 sptr<Notification> notification = nullptr;
2138 result = RemoveFromNotificationList(key, notification, true,
2139 NotificationConstant::PACKAGE_CHANGED_REASON_DELETE);
2140 if (result != ERR_OK) {
2141 continue;
2142 }
2143
2144 if (notification != nullptr) {
2145 int32_t reason = NotificationConstant::PACKAGE_CHANGED_REASON_DELETE;
2146 UpdateRecentNotification(notification, true, reason);
2147 sptr<NotificationSortingMap> sortingMap = GenerateSortingMap();
2148 NotificationSubscriberManager::GetInstance()->NotifyCanceled(notification, sortingMap, reason);
2149 #ifdef DISTRIBUTED_NOTIFICATION_SUPPORTED
2150 DoDistributedDelete("", "", notification);
2151 #endif
2152 }
2153 }
2154
2155 NotificationPreferences::GetInstance().RemoveAnsBundleDbInfo(bundleOption);
2156 }));
2157 }
2158
2159 #ifdef DISTRIBUTED_NOTIFICATION_SUPPORTED
OnScreenOn()2160 void AdvancedNotificationService::OnScreenOn()
2161 {
2162 ANS_LOGI("%{public}s", __FUNCTION__);
2163 localScreenOn_ = true;
2164 DistributedScreenStatusManager::GetInstance()->SetLocalScreenStatus(true);
2165 }
2166
OnScreenOff()2167 void AdvancedNotificationService::OnScreenOff()
2168 {
2169 ANS_LOGI("%{public}s", __FUNCTION__);
2170 localScreenOn_ = false;
2171 DistributedScreenStatusManager::GetInstance()->SetLocalScreenStatus(false);
2172 }
2173 #endif
2174
OnDistributedKvStoreDeathRecipient()2175 void AdvancedNotificationService::OnDistributedKvStoreDeathRecipient()
2176 {
2177 ANS_LOGD("%{public}s", __FUNCTION__);
2178 handler_->PostTask(std::bind([&]() {
2179 NotificationPreferences::GetInstance().OnDistributedKvStoreDeathRecipient();
2180 #ifdef DISTRIBUTED_NOTIFICATION_SUPPORTED
2181 DistributedNotificationManager::GetInstance()->OnDistributedKvStoreDeathRecipient();
2182 #endif
2183 }));
2184 }
2185
RemoveAllSlots()2186 ErrCode AdvancedNotificationService::RemoveAllSlots()
2187 {
2188 ANS_LOGD("%{public}s", __FUNCTION__);
2189
2190 sptr<NotificationBundleOption> bundleOption = GenerateBundleOption();
2191 if (bundleOption == nullptr) {
2192 return ERR_ANS_INVALID_BUNDLE;
2193 }
2194
2195 ErrCode result = ERR_OK;
2196 handler_->PostSyncTask(std::bind([&]() {
2197 result = NotificationPreferences::GetInstance().RemoveNotificationAllSlots(bundleOption);
2198 if (result == ERR_ANS_PREFERENCES_NOTIFICATION_BUNDLE_NOT_EXIST) {
2199 result = ERR_OK;
2200 }
2201 }));
2202 return result;
2203 }
2204
AddSlotByType(NotificationConstant::SlotType slotType)2205 ErrCode AdvancedNotificationService::AddSlotByType(NotificationConstant::SlotType slotType)
2206 {
2207 ANS_LOGD("%{public}s", __FUNCTION__);
2208
2209 sptr<NotificationBundleOption> bundleOption = GenerateBundleOption();
2210 if (bundleOption == nullptr) {
2211 return ERR_ANS_INVALID_BUNDLE;
2212 }
2213
2214 ErrCode result = ERR_OK;
2215 handler_->PostSyncTask(std::bind([&]() {
2216 sptr<NotificationSlot> slot;
2217 result = NotificationPreferences::GetInstance().GetNotificationSlot(bundleOption, slotType, slot);
2218 if ((result == ERR_OK) && (slot != nullptr)) {
2219 return;
2220 } else {
2221 slot = new NotificationSlot(slotType);
2222 std::vector<sptr<NotificationSlot>> slots;
2223 slots.push_back(slot);
2224 result = NotificationPreferences::GetInstance().AddNotificationSlots(bundleOption, slots);
2225 }
2226 }));
2227 return result;
2228 }
2229
RemoveNotification(const sptr<NotificationBundleOption> & bundleOption,int32_t notificationId,const std::string & label,int32_t removeReason)2230 ErrCode AdvancedNotificationService::RemoveNotification(const sptr<NotificationBundleOption> &bundleOption,
2231 int32_t notificationId, const std::string &label, int32_t removeReason)
2232 {
2233 HITRACE_METER_NAME(HITRACE_TAG_NOTIFICATION, __PRETTY_FUNCTION__);
2234 ANS_LOGD("%{public}s", __FUNCTION__);
2235
2236 if (!IsSystemApp()) {
2237 return ERR_ANS_NON_SYSTEM_APP;
2238 }
2239
2240 if (!CheckPermission(OHOS_PERMISSION_NOTIFICATION_CONTROLLER)) {
2241 return ERR_ANS_PERMISSION_DENIED;
2242 }
2243
2244 sptr<NotificationBundleOption> bundle = GenerateValidBundleOption(bundleOption);
2245 if (bundle == nullptr) {
2246 return ERR_ANS_INVALID_BUNDLE;
2247 }
2248
2249 ErrCode result = ERR_ANS_NOTIFICATION_NOT_EXISTS;
2250
2251 handler_->PostSyncTask(std::bind([&]() {
2252 sptr<Notification> notification = nullptr;
2253 sptr<NotificationRequest> notificationRequest = nullptr;
2254
2255 #ifdef DISTRIBUTED_NOTIFICATION_SUPPORTED
2256 std::string deviceId;
2257 std::string bundleName;
2258 #endif
2259 for (auto record : notificationList_) {
2260 if ((record->bundleOption->GetBundleName() == bundle->GetBundleName()) &&
2261 (record->bundleOption->GetUid() == bundle->GetUid()) &&
2262 #ifdef DISTRIBUTED_NOTIFICATION_SUPPORTED
2263 (record->deviceId.empty()) &&
2264 #endif
2265 (record->notification->GetId() == notificationId) && (record->notification->GetLabel() == label)) {
2266 if (!record->notification->IsRemoveAllowed()) {
2267 result = ERR_ANS_NOTIFICATION_IS_UNALLOWED_REMOVEALLOWED;
2268 break;
2269 }
2270 #ifdef DISTRIBUTED_NOTIFICATION_SUPPORTED
2271 deviceId = record->deviceId;
2272 bundleName = record->bundleName;
2273 #endif
2274 notification = record->notification;
2275 notificationRequest = record->request;
2276 notificationList_.remove(record);
2277 result = ERR_OK;
2278 break;
2279 }
2280 }
2281
2282 if (notification != nullptr) {
2283 UpdateRecentNotification(notification, true, removeReason);
2284 sptr<NotificationSortingMap> sortingMap = GenerateSortingMap();
2285 NotificationSubscriberManager::GetInstance()->NotifyCanceled(notification, sortingMap, removeReason);
2286 #ifdef DISTRIBUTED_NOTIFICATION_SUPPORTED
2287 DoDistributedDelete(deviceId, bundleName, notification);
2288 #endif
2289 }
2290 if (removeReason != NotificationConstant::CLICK_REASON_DELETE) {
2291 TriggerRemoveWantAgent(notificationRequest);
2292 }
2293 }));
2294
2295 SendRemoveHiSysEvent(notificationId, label, bundleOption, result);
2296 return result;
2297 }
2298
RemoveAllNotifications(const sptr<NotificationBundleOption> & bundleOption)2299 ErrCode AdvancedNotificationService::RemoveAllNotifications(const sptr<NotificationBundleOption> &bundleOption)
2300 {
2301 HITRACE_METER_NAME(HITRACE_TAG_NOTIFICATION, __PRETTY_FUNCTION__);
2302 ANS_LOGD("%{public}s", __FUNCTION__);
2303
2304 if (!IsSystemApp()) {
2305 return ERR_ANS_NON_SYSTEM_APP;
2306 }
2307
2308 if (!CheckPermission(OHOS_PERMISSION_NOTIFICATION_CONTROLLER)) {
2309 return ERR_ANS_PERMISSION_DENIED;
2310 }
2311
2312 sptr<NotificationBundleOption> bundle = GenerateValidBundleOption(bundleOption);
2313 if (bundle == nullptr) {
2314 return ERR_ANS_INVALID_BUNDLE;
2315 }
2316
2317 handler_->PostSyncTask(std::bind([&]() {
2318 std::vector<std::shared_ptr<NotificationRecord>> removeList;
2319 for (auto record : notificationList_) {
2320 if (!record->notification->IsRemoveAllowed()) {
2321 continue;
2322 }
2323
2324 if ((record->bundleOption->GetBundleName() == bundleOption->GetBundleName()) &&
2325 (record->bundleOption->GetUid() == bundleOption->GetUid()) &&
2326 #ifdef DISTRIBUTED_NOTIFICATION_SUPPORTED
2327 record->deviceId.empty() &&
2328 #endif
2329 !record->request->IsUnremovable()) {
2330 removeList.push_back(record);
2331 }
2332 }
2333
2334 for (auto record : removeList) {
2335 notificationList_.remove(record);
2336 if (record->notification != nullptr) {
2337 int32_t reason = NotificationConstant::CANCEL_REASON_DELETE;
2338 UpdateRecentNotification(record->notification, true, reason);
2339 sptr<NotificationSortingMap> sortingMap = GenerateSortingMap();
2340 NotificationSubscriberManager::GetInstance()->NotifyCanceled(record->notification, sortingMap, reason);
2341 #ifdef DISTRIBUTED_NOTIFICATION_SUPPORTED
2342 DoDistributedDelete(record->deviceId, record->bundleName, record->notification);
2343 #endif
2344 }
2345
2346 TriggerRemoveWantAgent(record->request);
2347 }
2348 }));
2349
2350 return ERR_OK;
2351 }
2352
GetSlotNumAsBundle(const sptr<NotificationBundleOption> & bundleOption,uint64_t & num)2353 ErrCode AdvancedNotificationService::GetSlotNumAsBundle(
2354 const sptr<NotificationBundleOption> &bundleOption, uint64_t &num)
2355 {
2356 ANS_LOGD("%{public}s", __FUNCTION__);
2357
2358 if (!IsSystemApp()) {
2359 return ERR_ANS_NON_SYSTEM_APP;
2360 }
2361
2362 if (!CheckPermission(OHOS_PERMISSION_NOTIFICATION_CONTROLLER)) {
2363 return ERR_ANS_PERMISSION_DENIED;
2364 }
2365
2366 sptr<NotificationBundleOption> bundle = GenerateValidBundleOption(bundleOption);
2367 if (bundle == nullptr) {
2368 return ERR_ANS_INVALID_BUNDLE;
2369 }
2370
2371 ErrCode result = ERR_OK;
2372
2373 handler_->PostSyncTask(std::bind([&]() {
2374 result = NotificationPreferences::GetInstance().GetNotificationSlotsNumForBundle(bundle, num);
2375 if (result == ERR_ANS_PREFERENCES_NOTIFICATION_BUNDLE_NOT_EXIST) {
2376 result = ERR_OK;
2377 num = 0;
2378 }
2379 }));
2380
2381 return result;
2382 }
2383
CancelGroup(const std::string & groupName)2384 ErrCode AdvancedNotificationService::CancelGroup(const std::string &groupName)
2385 {
2386 ANS_LOGD("%{public}s", __FUNCTION__);
2387
2388 if (groupName.empty()) {
2389 return ERR_ANS_INVALID_PARAM;
2390 }
2391
2392 sptr<NotificationBundleOption> bundleOption = GenerateBundleOption();
2393 if (bundleOption == nullptr) {
2394 return ERR_ANS_INVALID_BUNDLE;
2395 }
2396
2397 handler_->PostSyncTask(std::bind([&]() {
2398 std::vector<std::shared_ptr<NotificationRecord>> removeList;
2399 for (auto record : notificationList_) {
2400 if ((record->bundleOption->GetBundleName() == bundleOption->GetBundleName()) &&
2401 (record->bundleOption->GetUid() == bundleOption->GetUid()) &&
2402 #ifdef DISTRIBUTED_NOTIFICATION_SUPPORTED
2403 record->deviceId.empty() &&
2404 #endif
2405 (record->request->GetGroupName() == groupName)) {
2406 removeList.push_back(record);
2407 }
2408 }
2409
2410 for (auto record : removeList) {
2411 notificationList_.remove(record);
2412
2413 if (record->notification != nullptr) {
2414 int32_t reason = NotificationConstant::APP_CANCEL_REASON_DELETE;
2415 UpdateRecentNotification(record->notification, true, reason);
2416 sptr<NotificationSortingMap> sortingMap = GenerateSortingMap();
2417 NotificationSubscriberManager::GetInstance()->NotifyCanceled(record->notification, sortingMap, reason);
2418 #ifdef DISTRIBUTED_NOTIFICATION_SUPPORTED
2419 DoDistributedDelete(record->deviceId, record->bundleName, record->notification);
2420 #endif
2421 }
2422 }
2423 }));
2424
2425 return ERR_OK;
2426 }
2427
RemoveGroupByBundle(const sptr<NotificationBundleOption> & bundleOption,const std::string & groupName)2428 ErrCode AdvancedNotificationService::RemoveGroupByBundle(
2429 const sptr<NotificationBundleOption> &bundleOption, const std::string &groupName)
2430 {
2431 ANS_LOGD("%{public}s", __FUNCTION__);
2432
2433 if (!IsSystemApp()) {
2434 return ERR_ANS_NON_SYSTEM_APP;
2435 }
2436
2437 if (!CheckPermission(OHOS_PERMISSION_NOTIFICATION_CONTROLLER)) {
2438 return ERR_ANS_PERMISSION_DENIED;
2439 }
2440
2441 if (bundleOption == nullptr || groupName.empty()) {
2442 return ERR_ANS_INVALID_PARAM;
2443 }
2444
2445 sptr<NotificationBundleOption> bundle = GenerateValidBundleOption(bundleOption);
2446 if (bundle == nullptr) {
2447 return ERR_ANS_INVALID_BUNDLE;
2448 }
2449
2450 handler_->PostSyncTask(std::bind([&]() {
2451 std::vector<std::shared_ptr<NotificationRecord>> removeList;
2452 for (auto record : notificationList_) {
2453 if (!record->notification->IsRemoveAllowed()) {
2454 continue;
2455 }
2456 if ((record->bundleOption->GetBundleName() == bundle->GetBundleName()) &&
2457 (record->bundleOption->GetUid() == bundle->GetUid()) && !record->request->IsUnremovable() &&
2458 #ifdef DISTRIBUTED_NOTIFICATION_SUPPORTED
2459 record->deviceId.empty() &&
2460 #endif
2461 (record->request->GetGroupName() == groupName)) {
2462 removeList.push_back(record);
2463 }
2464 }
2465
2466 for (auto record : removeList) {
2467 notificationList_.remove(record);
2468
2469 if (record->notification != nullptr) {
2470 int32_t reason = NotificationConstant::CANCEL_REASON_DELETE;
2471 UpdateRecentNotification(record->notification, true, reason);
2472 sptr<NotificationSortingMap> sortingMap = GenerateSortingMap();
2473 NotificationSubscriberManager::GetInstance()->NotifyCanceled(record->notification, sortingMap, reason);
2474 #ifdef DISTRIBUTED_NOTIFICATION_SUPPORTED
2475 DoDistributedDelete(record->deviceId, record->bundleName, record->notification);
2476 #endif
2477 }
2478 }
2479 }));
2480
2481 return ERR_OK;
2482 }
2483
AdjustDateForDndTypeOnce(int64_t & beginDate,int64_t & endDate)2484 void AdvancedNotificationService::AdjustDateForDndTypeOnce(int64_t &beginDate, int64_t &endDate)
2485 {
2486 std::chrono::system_clock::time_point now = std::chrono::system_clock::now();
2487 time_t nowT = std::chrono::system_clock::to_time_t(now);
2488 tm nowTm = GetLocalTime(nowT);
2489
2490 auto beginDateMilliseconds = std::chrono::milliseconds(beginDate);
2491 auto beginDateTimePoint =
2492 std::chrono::time_point<std::chrono::system_clock, std::chrono::milliseconds>(beginDateMilliseconds);
2493 time_t beginDateT = std::chrono::system_clock::to_time_t(beginDateTimePoint);
2494 tm beginDateTm = GetLocalTime(beginDateT);
2495
2496 auto endDateMilliseconds = std::chrono::milliseconds(endDate);
2497 auto endDateTimePoint =
2498 std::chrono::time_point<std::chrono::system_clock, std::chrono::milliseconds>(endDateMilliseconds);
2499 time_t endDateT = std::chrono::system_clock::to_time_t(endDateTimePoint);
2500 tm endDateTm = GetLocalTime(endDateT);
2501
2502 tm todayBeginTm = nowTm;
2503 todayBeginTm.tm_sec = 0;
2504 todayBeginTm.tm_min = beginDateTm.tm_min;
2505 todayBeginTm.tm_hour = beginDateTm.tm_hour;
2506
2507 tm todayEndTm = nowTm;
2508 todayEndTm.tm_sec = 0;
2509 todayEndTm.tm_min = endDateTm.tm_min;
2510 todayEndTm.tm_hour = endDateTm.tm_hour;
2511
2512 time_t todayBeginT = mktime(&todayBeginTm);
2513 if (todayBeginT == -1) {
2514 return;
2515 }
2516 time_t todayEndT = mktime(&todayEndTm);
2517 if (todayEndT == -1) {
2518 return;
2519 }
2520
2521 auto newBeginTimePoint = std::chrono::system_clock::from_time_t(todayBeginT);
2522 auto newEndTimePoint = std::chrono::system_clock::from_time_t(todayEndT);
2523 if (newBeginTimePoint >= newEndTimePoint) {
2524 newEndTimePoint += std::chrono::hours(HOURS_IN_ONE_DAY);
2525 }
2526
2527 if (newEndTimePoint < now) {
2528 newBeginTimePoint += std::chrono::hours(HOURS_IN_ONE_DAY);
2529 newEndTimePoint += std::chrono::hours(HOURS_IN_ONE_DAY);
2530 }
2531
2532 auto newBeginDuration = std::chrono::duration_cast<std::chrono::milliseconds>(newBeginTimePoint.time_since_epoch());
2533 beginDate = newBeginDuration.count();
2534
2535 auto newEndDuration = std::chrono::duration_cast<std::chrono::milliseconds>(newEndTimePoint.time_since_epoch());
2536 endDate = newEndDuration.count();
2537 }
2538
SetDoNotDisturbDate(const sptr<NotificationDoNotDisturbDate> & date)2539 ErrCode AdvancedNotificationService::SetDoNotDisturbDate(const sptr<NotificationDoNotDisturbDate> &date)
2540 {
2541 ANS_LOGD("%{public}s", __FUNCTION__);
2542
2543 if (!IsSystemApp()) {
2544 ANS_LOGW("Not system app!");
2545 return ERR_ANS_NON_SYSTEM_APP;
2546 }
2547
2548 if (!CheckPermission(OHOS_PERMISSION_NOTIFICATION_CONTROLLER)) {
2549 ANS_LOGW("Check permission denied!");
2550 return ERR_ANS_PERMISSION_DENIED;
2551 }
2552
2553 int32_t userId = SUBSCRIBE_USER_INIT;
2554 if (!GetActiveUserId(userId)) {
2555 ANS_LOGW("No active user found!");
2556 return ERR_ANS_GET_ACTIVE_USER_FAILED;
2557 }
2558
2559 return SetDoNotDisturbDateByUser(userId, date);
2560 }
2561
GetDoNotDisturbDate(sptr<NotificationDoNotDisturbDate> & date)2562 ErrCode AdvancedNotificationService::GetDoNotDisturbDate(sptr<NotificationDoNotDisturbDate> &date)
2563 {
2564 ANS_LOGD("%{public}s", __FUNCTION__);
2565
2566 if (!IsSystemApp()) {
2567 return ERR_ANS_NON_SYSTEM_APP;
2568 }
2569
2570 if (!CheckPermission(OHOS_PERMISSION_NOTIFICATION_CONTROLLER)) {
2571 return ERR_ANS_PERMISSION_DENIED;
2572 }
2573
2574 int32_t userId = SUBSCRIBE_USER_INIT;
2575 if (!GetActiveUserId(userId)) {
2576 return ERR_ANS_GET_ACTIVE_USER_FAILED;
2577 }
2578
2579 return GetDoNotDisturbDateByUser(userId, date);
2580 }
2581
DoesSupportDoNotDisturbMode(bool & doesSupport)2582 ErrCode AdvancedNotificationService::DoesSupportDoNotDisturbMode(bool &doesSupport)
2583 {
2584 ANS_LOGD("%{public}s", __FUNCTION__);
2585
2586 if (!IsSystemApp()) {
2587 return ERR_ANS_NON_SYSTEM_APP;
2588 }
2589
2590 if (!CheckPermission(OHOS_PERMISSION_NOTIFICATION_CONTROLLER)) {
2591 return ERR_ANS_PERMISSION_DENIED;
2592 }
2593
2594 doesSupport = SUPPORT_DO_NOT_DISTRUB;
2595 return ERR_OK;
2596 }
2597
CheckPermission(const std::string & permission)2598 bool AdvancedNotificationService::CheckPermission(const std::string &permission)
2599 {
2600 ANS_LOGD("%{public}s", __FUNCTION__);
2601
2602 bool isSubsystem = AccessTokenHelper::VerifyNativeToken(IPCSkeleton::GetCallingTokenID());
2603 if (isSubsystem) {
2604 return true;
2605 }
2606
2607 auto tokenCaller = IPCSkeleton::GetCallingTokenID();
2608 bool result = AccessTokenHelper::VerifyCallerPermission(tokenCaller, permission);
2609 if (!result) {
2610 ANS_LOGE("Permission denied");
2611 }
2612 return result;
2613 }
2614
IsDistributedEnabled(bool & enabled)2615 ErrCode AdvancedNotificationService::IsDistributedEnabled(bool &enabled)
2616 {
2617 ANS_LOGD("%{public}s", __FUNCTION__);
2618 #ifdef DISTRIBUTED_NOTIFICATION_SUPPORTED
2619 ErrCode result = ERR_OK;
2620 handler_->PostSyncTask(std::bind([&]() {
2621 result = DistributedPreferences::GetInstance()->GetDistributedEnable(enabled);
2622 if (result != ERR_OK) {
2623 result = ERR_OK;
2624 enabled = false;
2625 }
2626 }));
2627 return result;
2628 #else
2629 return ERR_INVALID_OPERATION;
2630 #endif
2631 }
2632
EnableDistributed(bool enabled)2633 ErrCode AdvancedNotificationService::EnableDistributed(bool enabled)
2634 {
2635 ANS_LOGD("%{public}s", __FUNCTION__);
2636
2637 #ifdef DISTRIBUTED_NOTIFICATION_SUPPORTED
2638 if (!IsSystemApp()) {
2639 return ERR_ANS_NON_SYSTEM_APP;
2640 }
2641
2642 if (!CheckPermission(OHOS_PERMISSION_NOTIFICATION_CONTROLLER)) {
2643 return ERR_ANS_PERMISSION_DENIED;
2644 }
2645
2646 ErrCode result = ERR_OK;
2647 handler_->PostSyncTask(
2648 std::bind([&]() { result = DistributedPreferences::GetInstance()->SetDistributedEnable(enabled); }));
2649 return result;
2650 #else
2651 return ERR_INVALID_OPERATION;
2652 #endif
2653 }
2654
EnableDistributedByBundle(const sptr<NotificationBundleOption> & bundleOption,bool enabled)2655 ErrCode AdvancedNotificationService::EnableDistributedByBundle(
2656 const sptr<NotificationBundleOption> &bundleOption, bool enabled)
2657 {
2658 ANS_LOGD("%{public}s", __FUNCTION__);
2659
2660 #ifdef DISTRIBUTED_NOTIFICATION_SUPPORTED
2661 if (!IsSystemApp()) {
2662 return ERR_ANS_NON_SYSTEM_APP;
2663 }
2664
2665 if (!CheckPermission(OHOS_PERMISSION_NOTIFICATION_CONTROLLER)) {
2666 return ERR_ANS_PERMISSION_DENIED;
2667 }
2668
2669 sptr<NotificationBundleOption> bundle = GenerateValidBundleOption(bundleOption);
2670 if (bundle == nullptr) {
2671 return ERR_ANS_INVALID_BUNDLE;
2672 }
2673
2674 bool appInfoEnable = true;
2675 GetDistributedEnableInApplicationInfo(bundle, appInfoEnable);
2676 if (!appInfoEnable) {
2677 ANS_LOGD("Get from bms is %{public}d", appInfoEnable);
2678 return ERR_ANS_PERMISSION_DENIED;
2679 }
2680
2681 ErrCode result = ERR_OK;
2682 handler_->PostSyncTask(std::bind([&]() {
2683 result = DistributedPreferences::GetInstance()->SetDistributedBundleEnable(bundle, enabled);
2684 if (result != ERR_OK) {
2685 result = ERR_OK;
2686 enabled = false;
2687 }
2688 }));
2689 return result;
2690 #else
2691 return ERR_INVALID_OPERATION;
2692 #endif
2693 }
2694
EnableDistributedSelf(const bool enabled)2695 ErrCode AdvancedNotificationService::EnableDistributedSelf(const bool enabled)
2696 {
2697 ANS_LOGD("%{public}s", __FUNCTION__);
2698 #ifdef DISTRIBUTED_NOTIFICATION_SUPPORTED
2699 sptr<NotificationBundleOption> bundleOption = GenerateBundleOption();
2700 if (bundleOption == nullptr) {
2701 return ERR_ANS_INVALID_BUNDLE;
2702 }
2703
2704 bool appInfoEnable = true;
2705 GetDistributedEnableInApplicationInfo(bundleOption, appInfoEnable);
2706 if (!appInfoEnable) {
2707 ANS_LOGD("Get from bms is %{public}d", appInfoEnable);
2708 return ERR_ANS_PERMISSION_DENIED;
2709 }
2710
2711 ErrCode result = ERR_OK;
2712 handler_->PostSyncTask(std::bind(
2713 [&]() { result = DistributedPreferences::GetInstance()->SetDistributedBundleEnable(bundleOption, enabled); }));
2714 return result;
2715 #else
2716 return ERR_INVALID_OPERATION;
2717 #endif
2718 }
2719
IsDistributedEnableByBundle(const sptr<NotificationBundleOption> & bundleOption,bool & enabled)2720 ErrCode AdvancedNotificationService::IsDistributedEnableByBundle(
2721 const sptr<NotificationBundleOption> &bundleOption, bool &enabled)
2722 {
2723 ANS_LOGD("%{public}s", __FUNCTION__);
2724
2725 #ifdef DISTRIBUTED_NOTIFICATION_SUPPORTED
2726 if (!IsSystemApp()) {
2727 return ERR_ANS_NON_SYSTEM_APP;
2728 }
2729
2730 if (!CheckPermission(OHOS_PERMISSION_NOTIFICATION_CONTROLLER)) {
2731 return ERR_ANS_PERMISSION_DENIED;
2732 }
2733
2734 sptr<NotificationBundleOption> bundle = GenerateValidBundleOption(bundleOption);
2735 if (bundle == nullptr) {
2736 return ERR_ANS_INVALID_BUNDLE;
2737 }
2738
2739 bool appInfoEnable = true;
2740 GetDistributedEnableInApplicationInfo(bundle, appInfoEnable);
2741 if (!appInfoEnable) {
2742 ANS_LOGD("Get from bms is %{public}d", appInfoEnable);
2743 enabled = appInfoEnable;
2744 return ERR_OK;
2745 }
2746
2747 ErrCode result = ERR_OK;
2748 handler_->PostSyncTask(std::bind([&]() {
2749 result = DistributedPreferences::GetInstance()->GetDistributedBundleEnable(bundle, enabled);
2750 if (result != ERR_OK) {
2751 result = ERR_OK;
2752 enabled = false;
2753 }
2754 }));
2755 return result;
2756 #else
2757 return ERR_INVALID_OPERATION;
2758 #endif
2759 }
2760
GetDeviceRemindType(NotificationConstant::RemindType & remindType)2761 ErrCode AdvancedNotificationService::GetDeviceRemindType(NotificationConstant::RemindType &remindType)
2762 {
2763 ANS_LOGD("%{public}s", __FUNCTION__);
2764
2765 if (!IsSystemApp()) {
2766 return ERR_ANS_NON_SYSTEM_APP;
2767 }
2768
2769 if (!CheckPermission(OHOS_PERMISSION_NOTIFICATION_CONTROLLER)) {
2770 return ERR_ANS_PERMISSION_DENIED;
2771 }
2772
2773 #ifdef DISTRIBUTED_NOTIFICATION_SUPPORTED
2774 handler_->PostSyncTask(std::bind([&]() { remindType = GetRemindType(); }));
2775 return ERR_OK;
2776 #else
2777 return ERR_INVALID_OPERATION;
2778 #endif
2779 }
2780
SetNotificationRemindType(sptr<Notification> notification,bool isLocal)2781 ErrCode AdvancedNotificationService::SetNotificationRemindType(sptr<Notification> notification, bool isLocal)
2782 {
2783 #ifdef DISTRIBUTED_NOTIFICATION_SUPPORTED
2784 notification->SetRemindType(GetRemindType());
2785 #else
2786 notification->SetRemindType(NotificationConstant::RemindType::NONE);
2787 #endif
2788 return ERR_OK;
2789 }
2790
2791 #ifdef DISTRIBUTED_NOTIFICATION_SUPPORTED
GetLocalNotificationKeys(const sptr<NotificationBundleOption> & bundleOption)2792 std::vector<std::string> AdvancedNotificationService::GetLocalNotificationKeys(
2793 const sptr<NotificationBundleOption> &bundleOption)
2794 {
2795 std::vector<std::string> keys;
2796
2797 for (auto record : notificationList_) {
2798 if ((bundleOption != nullptr) && (record->bundleOption->GetBundleName() != bundleOption->GetBundleName()) &&
2799 (record->bundleOption->GetUid() != bundleOption->GetUid()) && record->deviceId.empty()) {
2800 continue;
2801 }
2802 keys.push_back(record->notification->GetKey());
2803 }
2804
2805 return keys;
2806 }
2807
GetRemindType()2808 NotificationConstant::RemindType AdvancedNotificationService::GetRemindType()
2809 {
2810 bool remind = localScreenOn_;
2811 if (distributedReminderPolicy_ == NotificationConstant::DistributedReminderPolicy::DEFAULT) {
2812 bool remoteUsing = false;
2813 ErrCode result = DistributedScreenStatusManager::GetInstance()->CheckRemoteDevicesIsUsing(remoteUsing);
2814 if (result != ERR_OK) {
2815 remind = true;
2816 }
2817 if (!localScreenOn_ && !remoteUsing) {
2818 remind = true;
2819 }
2820 } else if (distributedReminderPolicy_ == NotificationConstant::DistributedReminderPolicy::ALWAYS_REMIND) {
2821 remind = true;
2822 } else if (distributedReminderPolicy_ == NotificationConstant::DistributedReminderPolicy::DO_NOT_REMIND) {
2823 remind = false;
2824 }
2825
2826 if (localScreenOn_) {
2827 if (remind) {
2828 return NotificationConstant::RemindType::DEVICE_ACTIVE_REMIND;
2829 } else {
2830 return NotificationConstant::RemindType::DEVICE_ACTIVE_DONOT_REMIND;
2831 }
2832 } else {
2833 if (remind) {
2834 return NotificationConstant::RemindType::DEVICE_IDLE_REMIND;
2835 } else {
2836 return NotificationConstant::RemindType::DEVICE_IDLE_DONOT_REMIND;
2837 }
2838 }
2839 }
2840
GetDistributedInfo(const std::string & key,std::string & deviceId,std::string & bundleName)2841 void AdvancedNotificationService::GetDistributedInfo(
2842 const std::string &key, std::string &deviceId, std::string &bundleName)
2843 {
2844 for (auto record : notificationList_) {
2845 if (record->notification->GetKey() == key) {
2846 deviceId = record->deviceId;
2847 bundleName = record->bundleName;
2848 break;
2849 }
2850 }
2851 }
2852
DoDistributedPublish(const sptr<NotificationBundleOption> bundleOption,const std::shared_ptr<NotificationRecord> record)2853 ErrCode AdvancedNotificationService::DoDistributedPublish(
2854 const sptr<NotificationBundleOption> bundleOption, const std::shared_ptr<NotificationRecord> record)
2855 {
2856 bool appInfoEnable = true;
2857 GetDistributedEnableInApplicationInfo(bundleOption, appInfoEnable);
2858 if (!appInfoEnable) {
2859 return ERR_OK;
2860 }
2861
2862 if (!record->request->GetNotificationDistributedOptions().IsDistributed()) {
2863 return ERR_OK;
2864 }
2865
2866 ErrCode result;
2867 bool distributedEnable = false;
2868 result = DistributedPreferences::GetInstance()->GetDistributedEnable(distributedEnable);
2869 if (result != ERR_OK || !distributedEnable) {
2870 return result;
2871 }
2872
2873 bool bundleDistributedEnable = false;
2874 result = DistributedPreferences::GetInstance()->GetDistributedBundleEnable(bundleOption, bundleDistributedEnable);
2875 if (result != ERR_OK || !bundleDistributedEnable) {
2876 return result;
2877 }
2878
2879 return DistributedNotificationManager::GetInstance()->Publish(record->notification->GetBundleName(),
2880 record->notification->GetLabel(),
2881 record->notification->GetId(),
2882 record->request);
2883 }
2884
DoDistributedDelete(const std::string deviceId,const std::string bundleName,const sptr<Notification> notification)2885 ErrCode AdvancedNotificationService::DoDistributedDelete(
2886 const std::string deviceId, const std::string bundleName, const sptr<Notification> notification)
2887 {
2888 HITRACE_METER_NAME(HITRACE_TAG_NOTIFICATION, __PRETTY_FUNCTION__);
2889 if (!notification->GetNotificationRequest().GetNotificationDistributedOptions().IsDistributed()) {
2890 return ERR_OK;
2891 }
2892 if (deviceId.empty()) {
2893 return DistributedNotificationManager::GetInstance()->Delete(
2894 notification->GetBundleName(), notification->GetLabel(), notification->GetId());
2895 } else {
2896 return DistributedNotificationManager::GetInstance()->DeleteRemoteNotification(
2897 deviceId, bundleName, notification->GetLabel(), notification->GetId());
2898 }
2899
2900 return ERR_OK;
2901 }
2902
CheckDistributedNotificationType(const sptr<NotificationRequest> & request)2903 bool AdvancedNotificationService::CheckDistributedNotificationType(const sptr<NotificationRequest> &request)
2904 {
2905 auto deviceTypeList = request->GetNotificationDistributedOptions().GetDevicesSupportDisplay();
2906 if (deviceTypeList.empty()) {
2907 return true;
2908 }
2909
2910 DistributedDatabase::DeviceInfo localDeviceInfo;
2911 DistributedNotificationManager::GetInstance()->GetLocalDeviceInfo(localDeviceInfo);
2912 for (auto device : deviceTypeList) {
2913 if (device == localDeviceInfo.deviceType) {
2914 return true;
2915 }
2916 }
2917 return false;
2918 }
2919
OnDistributedPublish(const std::string & deviceId,const std::string & bundleName,sptr<NotificationRequest> & request)2920 void AdvancedNotificationService::OnDistributedPublish(
2921 const std::string &deviceId, const std::string &bundleName, sptr<NotificationRequest> &request)
2922 {
2923 ANS_LOGD("%{public}s", __FUNCTION__);
2924 int32_t activeUserId = -1;
2925 if (!GetActiveUserId(activeUserId)) {
2926 ANS_LOGE("Failed to get active user id!");
2927 return;
2928 }
2929
2930 handler_->PostTask(std::bind([this, deviceId, bundleName, request, activeUserId]() {
2931 if (!CheckDistributedNotificationType(request)) {
2932 ANS_LOGD("device type not support display.");
2933 return;
2934 }
2935
2936 int32_t uid = BundleManagerHelper::GetInstance()->GetDefaultUidByBundleName(bundleName, activeUserId);
2937 if (uid <= 0) {
2938 if (CheckPublishWithoutApp(activeUserId, request)) {
2939 request->SetOwnerBundleName(FOUNDATION_BUNDLE_NAME);
2940 request->SetCreatorBundleName(FOUNDATION_BUNDLE_NAME);
2941 } else {
2942 ANS_LOGE("bundle does not exit and enable off!");
2943 return;
2944 }
2945 }
2946 std::string bundle = request->GetOwnerBundleName();
2947 request->SetCreatorUid(BundleManagerHelper::GetInstance()->GetDefaultUidByBundleName(bundle, activeUserId));
2948 sptr<NotificationBundleOption> bundleOption =
2949 GenerateValidBundleOption(new NotificationBundleOption(bundle, 0));
2950
2951 std::shared_ptr<NotificationRecord> record = std::make_shared<NotificationRecord>();
2952 if (record == nullptr) {
2953 return;
2954 }
2955 record->request = request;
2956 record->notification = new Notification(deviceId, request);
2957 record->bundleOption = bundleOption;
2958 record->deviceId = deviceId;
2959 record->bundleName = bundleName;
2960 SetNotificationRemindType(record->notification, false);
2961
2962 ErrCode result = AssignValidNotificationSlot(record);
2963 if (result != ERR_OK) {
2964 ANS_LOGE("Can not assign valid slot!");
2965 return;
2966 }
2967
2968 result = Filter(record);
2969 if (result != ERR_OK) {
2970 ANS_LOGE("Reject by filters: %{public}d", result);
2971 return;
2972 }
2973
2974 result = FlowControl(record);
2975 if (result != ERR_OK) {
2976 return;
2977 }
2978
2979 UpdateRecentNotification(record->notification, false, 0);
2980 sptr<NotificationSortingMap> sortingMap = GenerateSortingMap();
2981 NotificationSubscriberManager::GetInstance()->NotifyConsumed(record->notification, sortingMap);
2982 }));
2983 }
2984
OnDistributedUpdate(const std::string & deviceId,const std::string & bundleName,sptr<NotificationRequest> & request)2985 void AdvancedNotificationService::OnDistributedUpdate(
2986 const std::string &deviceId, const std::string &bundleName, sptr<NotificationRequest> &request)
2987 {
2988 ANS_LOGD("%{public}s", __FUNCTION__);
2989 int32_t activeUserId = -1;
2990 if (!GetActiveUserId(activeUserId)) {
2991 ANS_LOGE("Failed to get active user id!");
2992 return;
2993 }
2994
2995 handler_->PostTask(std::bind([this, deviceId, bundleName, request, activeUserId]() {
2996 if (!CheckDistributedNotificationType(request)) {
2997 ANS_LOGD("device type not support display.");
2998 return;
2999 }
3000
3001 int32_t uid = BundleManagerHelper::GetInstance()->GetDefaultUidByBundleName(bundleName, activeUserId);
3002 if (uid <= 0) {
3003 if (CheckPublishWithoutApp(activeUserId, request)) {
3004 request->SetOwnerBundleName(FOUNDATION_BUNDLE_NAME);
3005 request->SetCreatorBundleName(FOUNDATION_BUNDLE_NAME);
3006 } else {
3007 ANS_LOGE("bundle does not exit and enable off!");
3008 return;
3009 }
3010 }
3011 std::string bundle = request->GetOwnerBundleName();
3012 request->SetCreatorUid(BundleManagerHelper::GetInstance()->GetDefaultUidByBundleName(bundle, activeUserId));
3013 sptr<NotificationBundleOption> bundleOption =
3014 GenerateValidBundleOption(new NotificationBundleOption(bundle, 0));
3015
3016 std::shared_ptr<NotificationRecord> record = std::make_shared<NotificationRecord>();
3017 if (record == nullptr) {
3018 return;
3019 }
3020 record->request = request;
3021 record->notification = new Notification(deviceId, request);
3022 record->bundleOption = bundleOption;
3023 record->deviceId = deviceId;
3024 record->bundleName = bundleName;
3025 SetNotificationRemindType(record->notification, false);
3026
3027 ErrCode result = AssignValidNotificationSlot(record);
3028 if (result != ERR_OK) {
3029 ANS_LOGE("Can not assign valid slot!");
3030 return;
3031 }
3032
3033 result = Filter(record);
3034 if (result != ERR_OK) {
3035 ANS_LOGE("Reject by filters: %{public}d", result);
3036 return;
3037 }
3038
3039 if (IsNotificationExists(record->notification->GetKey())) {
3040 if (record->request->IsAlertOneTime()) {
3041 record->notification->SetEnableLight(false);
3042 record->notification->SetEnableSound(false);
3043 record->notification->SetEnableVibration(false);
3044 }
3045 UpdateInNotificationList(record);
3046 }
3047
3048 UpdateRecentNotification(record->notification, false, 0);
3049 sptr<NotificationSortingMap> sortingMap = GenerateSortingMap();
3050 NotificationSubscriberManager::GetInstance()->NotifyConsumed(record->notification, sortingMap);
3051 }));
3052 }
3053
OnDistributedDelete(const std::string & deviceId,const std::string & bundleName,const std::string & label,int32_t id)3054 void AdvancedNotificationService::OnDistributedDelete(
3055 const std::string &deviceId, const std::string &bundleName, const std::string &label, int32_t id)
3056 {
3057 ANS_LOGD("%{public}s", __FUNCTION__);
3058 handler_->PostTask(std::bind([this, deviceId, bundleName, label, id]() {
3059 int32_t activeUserId = -1;
3060 if (!GetActiveUserId(activeUserId)) {
3061 ANS_LOGE("Failed to get active user id!");
3062 return;
3063 }
3064 int32_t uid = BundleManagerHelper::GetInstance()->GetDefaultUidByBundleName(bundleName, activeUserId);
3065 std::string bundle = (uid > 0) ? bundleName : FOUNDATION_BUNDLE_NAME;
3066 sptr<NotificationBundleOption> bundleOption =
3067 GenerateValidBundleOption(new NotificationBundleOption(bundle, 0));
3068
3069 std::string recordDeviceId;
3070 DistributedDatabase::DeviceInfo localDeviceInfo;
3071 if (DistributedNotificationManager::GetInstance()->GetLocalDeviceInfo(localDeviceInfo) == ERR_OK &&
3072 deviceId == localDeviceInfo.deviceId) {
3073 recordDeviceId = "";
3074 } else {
3075 recordDeviceId = deviceId;
3076 }
3077
3078 sptr<Notification> notification = nullptr;
3079 for (auto record : notificationList_) {
3080 if ((record->deviceId == recordDeviceId) &&
3081 ((record->bundleOption->GetBundleName() == bundleOption->GetBundleName()) ||
3082 (record->bundleName == bundleName)) &&
3083 (record->bundleOption->GetUid() == bundleOption->GetUid()) &&
3084 (record->notification->GetLabel() == label) && (record->notification->GetId() == id)) {
3085 notification = record->notification;
3086 notificationList_.remove(record);
3087 break;
3088 }
3089 }
3090
3091 if (notification != nullptr) {
3092 int32_t reason = NotificationConstant::APP_CANCEL_REASON_OTHER;
3093 UpdateRecentNotification(notification, true, reason);
3094 sptr<NotificationSortingMap> sortingMap = GenerateSortingMap();
3095 NotificationSubscriberManager::GetInstance()->NotifyCanceled(notification, sortingMap, reason);
3096 }
3097 }));
3098 }
3099
GetDistributedEnableInApplicationInfo(const sptr<NotificationBundleOption> bundleOption,bool & enable)3100 ErrCode AdvancedNotificationService::GetDistributedEnableInApplicationInfo(
3101 const sptr<NotificationBundleOption> bundleOption, bool &enable)
3102 {
3103 int32_t userId = SUBSCRIBE_USER_INIT;
3104 OHOS::AccountSA::OsAccountManager::GetOsAccountLocalIdFromUid(bundleOption->GetUid(), userId);
3105
3106 if (userId >= SUBSCRIBE_USER_SYSTEM_BEGIN && userId <= SUBSCRIBE_USER_SYSTEM_END) {
3107 enable = true;
3108 } else {
3109 enable = BundleManagerHelper::GetInstance()->GetDistributedNotificationEnabled(
3110 bundleOption->GetBundleName(), userId);
3111 }
3112
3113 return ERR_OK;
3114 }
3115
CheckPublishWithoutApp(const int32_t userId,const sptr<NotificationRequest> & request)3116 bool AdvancedNotificationService::CheckPublishWithoutApp(const int32_t userId, const sptr<NotificationRequest> &request)
3117 {
3118 bool enabled = false;
3119 DistributedPreferences::GetInstance()->GetSyncEnabledWithoutApp(userId, enabled);
3120 if (!enabled) {
3121 ANS_LOGE("enable is false, userId[%{public}d]", userId);
3122 return false;
3123 }
3124
3125 std::shared_ptr<AbilityRuntime::WantAgent::WantAgent> wantAgent = request->GetWantAgent();
3126 if (!wantAgent) {
3127 ANS_LOGE("Failed to get wantAgent!");
3128 return false;
3129 }
3130
3131 std::shared_ptr<AAFwk::Want> want = AbilityRuntime::WantAgent::WantAgentHelper::GetWant(wantAgent);
3132 if (!want || want->GetDeviceId().empty()) {
3133 ANS_LOGE("Failed to get want!");
3134 return false;
3135 }
3136
3137 return true;
3138 }
3139 #endif
3140
PrepareContinuousTaskNotificationRequest(const sptr<NotificationRequest> & request,const int32_t & uid)3141 ErrCode AdvancedNotificationService::PrepareContinuousTaskNotificationRequest(
3142 const sptr<NotificationRequest> &request, const int32_t &uid)
3143 {
3144 int32_t pid = IPCSkeleton::GetCallingPid();
3145 request->SetCreatorUid(uid);
3146 request->SetCreatorPid(pid);
3147
3148 ErrCode result = CheckPictureSize(request);
3149 return result;
3150 }
3151
IsSupportTemplate(const std::string & templateName,bool & support)3152 ErrCode AdvancedNotificationService::IsSupportTemplate(const std::string& templateName, bool &support)
3153 {
3154 ANS_LOGD("%{public}s", __FUNCTION__);
3155 ErrCode result = ERR_OK;
3156 handler_->PostSyncTask(std::bind([&]() {
3157 support = false;
3158 result = NotificationPreferences::GetInstance().GetTemplateSupported(templateName, support);
3159 }));
3160 return result;
3161 }
3162
GetActiveUserId(int & userId)3163 bool AdvancedNotificationService::GetActiveUserId(int& userId)
3164 {
3165 std::vector<int> activeUserId;
3166 OHOS::AccountSA::OsAccountManager::QueryActiveOsAccountIds(activeUserId);
3167 if (activeUserId.size() > 0) {
3168 userId = activeUserId[0];
3169 ANS_LOGD("Return active userId=%{public}d", userId);
3170 return true;
3171 }
3172 return false;
3173 }
3174
TriggerRemoveWantAgent(const sptr<NotificationRequest> & request)3175 void AdvancedNotificationService::TriggerRemoveWantAgent(const sptr<NotificationRequest> &request)
3176 {
3177 HITRACE_METER_NAME(HITRACE_TAG_NOTIFICATION, __PRETTY_FUNCTION__);
3178 ANS_LOGD("%{public}s", __FUNCTION__);
3179
3180 if ((request == nullptr) || (request->GetRemovalWantAgent() == nullptr)) {
3181 return;
3182 }
3183 OHOS::AbilityRuntime::WantAgent::TriggerInfo triggerInfo;
3184 std::shared_ptr<AbilityRuntime::WantAgent::WantAgent> agent = request->GetRemovalWantAgent();
3185 AbilityRuntime::WantAgent::WantAgentHelper::TriggerWantAgent(agent, nullptr, triggerInfo);
3186 }
3187
IsSpecialUserAllowedNotify(const int32_t & userId,bool & allowed)3188 ErrCode AdvancedNotificationService::IsSpecialUserAllowedNotify(const int32_t &userId, bool &allowed)
3189 {
3190 ANS_LOGD("%{public}s", __FUNCTION__);
3191
3192 if (!IsSystemApp()) {
3193 return ERR_ANS_NON_SYSTEM_APP;
3194 }
3195
3196 if (!CheckPermission(OHOS_PERMISSION_NOTIFICATION_CONTROLLER)) {
3197 return ERR_ANS_PERMISSION_DENIED;
3198 }
3199
3200 ErrCode result = ERR_OK;
3201 handler_->PostSyncTask(std::bind([&]() {
3202 allowed = false;
3203 result = NotificationPreferences::GetInstance().GetNotificationsEnabled(userId, allowed);
3204 }));
3205 return result;
3206 }
3207
SetNotificationsEnabledByUser(const int32_t & userId,bool enabled)3208 ErrCode AdvancedNotificationService::SetNotificationsEnabledByUser(const int32_t &userId, bool enabled)
3209 {
3210 ANS_LOGD("%{public}s", __FUNCTION__);
3211
3212 if (!IsSystemApp()) {
3213 return ERR_ANS_NON_SYSTEM_APP;
3214 }
3215
3216 if (!CheckPermission(OHOS_PERMISSION_NOTIFICATION_CONTROLLER)) {
3217 return ERR_ANS_PERMISSION_DENIED;
3218 }
3219
3220 ErrCode result = ERR_OK;
3221 handler_->PostSyncTask(std::bind([&]() {
3222 result = NotificationPreferences::GetInstance().SetNotificationsEnabled(userId, enabled);
3223 }));
3224 return result;
3225 }
3226
DeleteAllByUser(const int32_t & userId)3227 ErrCode AdvancedNotificationService::DeleteAllByUser(const int32_t &userId)
3228 {
3229 ANS_LOGD("%{public}s", __FUNCTION__);
3230
3231 if (!IsSystemApp()) {
3232 return ERR_ANS_NON_SYSTEM_APP;
3233 }
3234
3235 if (userId <= SUBSCRIBE_USER_INIT) {
3236 ANS_LOGE("Input userId is invalid.");
3237 return ERR_ANS_INVALID_PARAM;
3238 }
3239
3240 ErrCode result = ERR_OK;
3241 handler_->PostSyncTask(std::bind([&]() {
3242 std::vector<std::string> keys = GetNotificationKeys(nullptr);
3243 for (auto key : keys) {
3244 #ifdef DISTRIBUTED_NOTIFICATION_SUPPORTED
3245 std::string deviceId;
3246 std::string bundleName;
3247 GetDistributedInfo(key, deviceId, bundleName);
3248 #endif
3249 sptr<Notification> notification = nullptr;
3250
3251 result = RemoveFromNotificationListForDeleteAll(key, userId, notification);
3252 if ((result != ERR_OK) || (notification == nullptr)) {
3253 continue;
3254 }
3255
3256 if (notification->GetUserId() == userId) {
3257 int32_t reason = NotificationConstant::CANCEL_ALL_REASON_DELETE;
3258 UpdateRecentNotification(notification, true, reason);
3259 sptr<NotificationSortingMap> sortingMap = GenerateSortingMap();
3260 NotificationSubscriberManager::GetInstance()->NotifyCanceled(notification, sortingMap, reason);
3261 #ifdef DISTRIBUTED_NOTIFICATION_SUPPORTED
3262 DoDistributedDelete(deviceId, bundleName, notification);
3263 #endif
3264 }
3265 }
3266
3267 result = ERR_OK;
3268 }));
3269
3270 return result;
3271 }
3272
SetDoNotDisturbDate(const int32_t & userId,const sptr<NotificationDoNotDisturbDate> & date)3273 ErrCode AdvancedNotificationService::SetDoNotDisturbDate(const int32_t &userId,
3274 const sptr<NotificationDoNotDisturbDate> &date)
3275 {
3276 ANS_LOGD("%{public}s", __FUNCTION__);
3277
3278 if (userId <= SUBSCRIBE_USER_INIT) {
3279 ANS_LOGE("Input userId is invalid.");
3280 return ERR_ANS_INVALID_PARAM;
3281 }
3282
3283 if (!IsSystemApp()) {
3284 return ERR_ANS_NON_SYSTEM_APP;
3285 }
3286
3287 if (!CheckPermission(OHOS_PERMISSION_NOTIFICATION_CONTROLLER)) {
3288 return ERR_ANS_PERMISSION_DENIED;
3289 }
3290
3291 return SetDoNotDisturbDateByUser(userId, date);
3292 }
3293
GetDoNotDisturbDate(const int32_t & userId,sptr<NotificationDoNotDisturbDate> & date)3294 ErrCode AdvancedNotificationService::GetDoNotDisturbDate(const int32_t &userId,
3295 sptr<NotificationDoNotDisturbDate> &date)
3296 {
3297 ANS_LOGD("%{public}s", __FUNCTION__);
3298
3299 if (userId <= SUBSCRIBE_USER_INIT) {
3300 ANS_LOGE("Input userId is invalid.");
3301 return ERR_ANS_INVALID_PARAM;
3302 }
3303
3304 if (!IsSystemApp()) {
3305 return ERR_ANS_NON_SYSTEM_APP;
3306 }
3307
3308 if (!CheckPermission(OHOS_PERMISSION_NOTIFICATION_CONTROLLER)) {
3309 return ERR_ANS_PERMISSION_DENIED;
3310 }
3311
3312 return GetDoNotDisturbDateByUser(userId, date);
3313 }
3314
SetDoNotDisturbDateByUser(const int32_t & userId,const sptr<NotificationDoNotDisturbDate> & date)3315 ErrCode AdvancedNotificationService::SetDoNotDisturbDateByUser(const int32_t &userId,
3316 const sptr<NotificationDoNotDisturbDate> &date)
3317 {
3318 ANS_LOGD("%{public}s enter, userId = %{public}d", __FUNCTION__, userId);
3319 if (date == nullptr) {
3320 ANS_LOGE("Invalid date param");
3321 return ERR_ANS_INVALID_PARAM;
3322 }
3323
3324 ErrCode result = ERR_OK;
3325
3326 int64_t beginDate = ResetSeconds(date->GetBeginDate());
3327 int64_t endDate = ResetSeconds(date->GetEndDate());
3328 switch (date->GetDoNotDisturbType()) {
3329 case NotificationConstant::DoNotDisturbType::NONE:
3330 beginDate = 0;
3331 endDate = 0;
3332 break;
3333 case NotificationConstant::DoNotDisturbType::ONCE:
3334 AdjustDateForDndTypeOnce(beginDate, endDate);
3335 break;
3336 case NotificationConstant::DoNotDisturbType::CLEARLY:
3337 if (beginDate >= endDate) {
3338 return ERR_ANS_INVALID_PARAM;
3339 }
3340 break;
3341 default:
3342 break;
3343 }
3344 ANS_LOGD("Before set SetDoNotDisturbDate beginDate = %{public}" PRId64 ", endDate = %{public}" PRId64,
3345 beginDate, endDate);
3346 const sptr<NotificationDoNotDisturbDate> newConfig = new NotificationDoNotDisturbDate(
3347 date->GetDoNotDisturbType(),
3348 beginDate,
3349 endDate
3350 );
3351
3352 sptr<NotificationBundleOption> bundleOption = GenerateBundleOption();
3353 if (bundleOption == nullptr) {
3354 ANS_LOGE("Generate invalid bundle option!");
3355 return ERR_ANS_INVALID_BUNDLE;
3356 }
3357
3358 handler_->PostSyncTask(std::bind([&]() {
3359 result = NotificationPreferences::GetInstance().SetDoNotDisturbDate(userId, newConfig);
3360 if (result == ERR_OK) {
3361 NotificationSubscriberManager::GetInstance()->NotifyDoNotDisturbDateChanged(newConfig);
3362 }
3363 }));
3364
3365 return ERR_OK;
3366 }
3367
GetDoNotDisturbDateByUser(const int32_t & userId,sptr<NotificationDoNotDisturbDate> & date)3368 ErrCode AdvancedNotificationService::GetDoNotDisturbDateByUser(const int32_t &userId,
3369 sptr<NotificationDoNotDisturbDate> &date)
3370 {
3371 ErrCode result = ERR_OK;
3372
3373 handler_->PostSyncTask(std::bind([&]() {
3374 sptr<NotificationDoNotDisturbDate> currentConfig = nullptr;
3375 result = NotificationPreferences::GetInstance().GetDoNotDisturbDate(userId, currentConfig);
3376 if (result == ERR_OK) {
3377 int64_t now = GetCurrentTime();
3378 switch (currentConfig->GetDoNotDisturbType()) {
3379 case NotificationConstant::DoNotDisturbType::CLEARLY:
3380 case NotificationConstant::DoNotDisturbType::ONCE:
3381 if (now >= currentConfig->GetEndDate()) {
3382 date = new NotificationDoNotDisturbDate(NotificationConstant::DoNotDisturbType::NONE, 0, 0);
3383 NotificationPreferences::GetInstance().SetDoNotDisturbDate(userId, date);
3384 } else {
3385 date = currentConfig;
3386 }
3387 break;
3388 default:
3389 date = currentConfig;
3390 break;
3391 }
3392 }
3393 }));
3394
3395 return ERR_OK;
3396 }
3397
SetHasPoppedDialog(const sptr<NotificationBundleOption> bundleOption,bool hasPopped)3398 ErrCode AdvancedNotificationService::SetHasPoppedDialog(
3399 const sptr<NotificationBundleOption> bundleOption, bool hasPopped)
3400 {
3401 ANS_LOGD("%{public}s", __FUNCTION__);
3402 ErrCode result = ERR_OK;
3403 handler_->PostSyncTask(std::bind([&]() {
3404 result = NotificationPreferences::GetInstance().SetHasPoppedDialog(bundleOption, hasPopped);
3405 }));
3406 return result;
3407 }
3408
GetHasPoppedDialog(const sptr<NotificationBundleOption> bundleOption,bool & hasPopped)3409 ErrCode AdvancedNotificationService::GetHasPoppedDialog(
3410 const sptr<NotificationBundleOption> bundleOption, bool &hasPopped)
3411 {
3412 ANS_LOGD("%{public}s", __FUNCTION__);
3413 ErrCode result = ERR_OK;
3414 handler_->PostSyncTask(std::bind([&]() {
3415 result = NotificationPreferences::GetInstance().GetHasPoppedDialog(bundleOption, hasPopped);
3416 }));
3417 return result;
3418 }
3419
CheckApiCompatibility(const sptr<NotificationBundleOption> & bundleOption)3420 bool AdvancedNotificationService::CheckApiCompatibility(const sptr<NotificationBundleOption> &bundleOption)
3421 {
3422 ANS_LOGD("%{public}s", __FUNCTION__);
3423 std::shared_ptr<BundleManagerHelper> bundleManager = BundleManagerHelper::GetInstance();
3424 if (bundleManager == nullptr) {
3425 return false;
3426 }
3427 return bundleManager->CheckApiCompatibility(bundleOption);
3428 }
3429
OnResourceRemove(int32_t userId)3430 void AdvancedNotificationService::OnResourceRemove(int32_t userId)
3431 {
3432 DeleteAllByUser(userId);
3433
3434 handler_->PostSyncTask(std::bind([&]() {
3435 NotificationPreferences::GetInstance().RemoveSettings(userId);
3436 }));
3437 }
3438
OnBundleDataCleared(const sptr<NotificationBundleOption> & bundleOption)3439 void AdvancedNotificationService::OnBundleDataCleared(const sptr<NotificationBundleOption> &bundleOption)
3440 {
3441 handler_->PostSyncTask(std::bind([&]() {
3442 std::vector<std::string> keys = GetNotificationKeys(bundleOption);
3443 for (auto key : keys) {
3444 #ifdef DISTRIBUTED_NOTIFICATION_SUPPORTED
3445 std::string deviceId;
3446 std::string bundleName;
3447 GetDistributedInfo(key, deviceId, bundleName);
3448 #endif
3449 sptr<Notification> notification = nullptr;
3450
3451 ErrCode result = RemoveFromNotificationList(key, notification, true,
3452 NotificationConstant::PACKAGE_CHANGED_REASON_DELETE);
3453 if (result != ERR_OK) {
3454 continue;
3455 }
3456
3457 if (notification != nullptr) {
3458 int32_t reason = NotificationConstant::PACKAGE_CHANGED_REASON_DELETE;
3459 UpdateRecentNotification(notification, true, reason);
3460 sptr<NotificationSortingMap> sortingMap = GenerateSortingMap();
3461 NotificationSubscriberManager::GetInstance()->NotifyCanceled(notification, sortingMap, reason);
3462 #ifdef DISTRIBUTED_NOTIFICATION_SUPPORTED
3463 DoDistributedDelete(deviceId, bundleName, notification);
3464 #endif
3465 }
3466 }
3467 }));
3468 }
3469
GetDisplayPosition(int & offsetX,int & offsetY,int & width,int & height,bool & wideScreen)3470 void AdvancedNotificationService::GetDisplayPosition(
3471 int& offsetX, int& offsetY, int& width, int& height, bool& wideScreen)
3472 {
3473 wideScreen = false;
3474 auto display = Rosen::DisplayManager::GetInstance().GetDefaultDisplay();
3475 if (display == nullptr) {
3476 ANS_LOGD("dialog GetDefaultDisplay fail, try again.");
3477 display = Rosen::DisplayManager::GetInstance().GetDefaultDisplay();
3478 }
3479
3480 if (display != nullptr) {
3481 ANS_LOGD("display size: %{public}d x %{public}d",
3482 display->GetWidth(), display->GetHeight());
3483 if (display->GetWidth() < display->GetHeight()) {
3484 float widthRatio = 0.75f;
3485 int32_t heightRatio = 5;
3486 width = static_cast<int32_t>(display->GetWidth() * widthRatio);
3487 height = display->GetHeight() / heightRatio;
3488 } else {
3489 int32_t widthRatio = 3;
3490 int32_t heightRatio = 4;
3491 wideScreen = true;
3492 width = display->GetWidth() / widthRatio;
3493 height = display->GetHeight() / heightRatio;
3494 }
3495 offsetX = (display->GetWidth() - width) / UI_HALF;
3496 offsetY = (display->GetHeight() - height) / UI_HALF;
3497 } else {
3498 ANS_LOGD("dialog get display fail, use default wide.");
3499 width = DIALOG_DEFAULT_WIDTH;
3500 height = DIALOG_DEFAULT_HEIGHT;
3501 offsetX = (WINDOW_DEFAULT_WIDTH - width) / UI_HALF;
3502 offsetY = (WINDOW_DEFAULT_HEIGHT - height) / UI_HALF;
3503 }
3504 ANS_LOGD("GetDisplayPosition: %{public}d, %{public}d (%{public}d x %{public}d)",
3505 offsetX, offsetY, width, height);
3506 }
3507
SetEnabledForBundleSlot(const sptr<NotificationBundleOption> & bundleOption,const NotificationConstant::SlotType & slotType,bool enabled)3508 ErrCode AdvancedNotificationService::SetEnabledForBundleSlot(
3509 const sptr<NotificationBundleOption> &bundleOption, const NotificationConstant::SlotType &slotType, bool enabled)
3510 {
3511 HITRACE_METER_NAME(HITRACE_TAG_NOTIFICATION, __PRETTY_FUNCTION__);
3512 ANS_LOGD("slotType: %{public}d, enabled: %{public}d", slotType, enabled);
3513
3514 if (!IsSystemApp()) {
3515 return ERR_ANS_NON_SYSTEM_APP;
3516 }
3517
3518 if (!CheckPermission(OHOS_PERMISSION_NOTIFICATION_CONTROLLER)) {
3519 return ERR_ANS_PERMISSION_DENIED;
3520 }
3521
3522 sptr<NotificationBundleOption> bundle = GenerateValidBundleOption(bundleOption);
3523 if (bundle == nullptr) {
3524 return ERR_ANS_INVALID_BUNDLE;
3525 }
3526
3527 ErrCode result = ERR_OK;
3528 handler_->PostSyncTask(std::bind([&]() {
3529 sptr<NotificationSlot> slot;
3530 result = NotificationPreferences::GetInstance().GetNotificationSlot(bundle, slotType, slot);
3531 if (result == ERR_ANS_PREFERENCES_NOTIFICATION_SLOT_TYPE_NOT_EXIST ||
3532 result == ERR_ANS_PREFERENCES_NOTIFICATION_BUNDLE_NOT_EXIST) {
3533 slot = new (std::nothrow) NotificationSlot(slotType);
3534 if (slot == nullptr) {
3535 ANS_LOGE("Failed to create NotificationSlot ptr.");
3536 result = ERR_ANS_NO_MEMORY;
3537 return;
3538 }
3539 } else if ((result == ERR_OK) && (slot != nullptr)) {
3540 if (slot->GetEnable() == enabled) {
3541 return;
3542 }
3543 NotificationPreferences::GetInstance().RemoveNotificationSlot(bundle, slotType);
3544 } else {
3545 ANS_LOGE("Set enable slot: GetNotificationSlot failed");
3546 return;
3547 }
3548
3549 slot->SetEnable(enabled);
3550 std::vector<sptr<NotificationSlot>> slots;
3551 slots.push_back(slot);
3552 result = NotificationPreferences::GetInstance().AddNotificationSlots(bundle, slots);
3553 if (result != ERR_OK) {
3554 ANS_LOGE("Set enable slot: AddNotificationSlot failed");
3555 return;
3556 }
3557
3558 PublishSlotChangeCommonEvent(bundle);
3559 }));
3560
3561 SendEnableNotificationSlotHiSysEvent(bundleOption, slotType, enabled, result);
3562 return result;
3563 }
3564
GetEnabledForBundleSlot(const sptr<NotificationBundleOption> & bundleOption,const NotificationConstant::SlotType & slotType,bool & enabled)3565 ErrCode AdvancedNotificationService::GetEnabledForBundleSlot(
3566 const sptr<NotificationBundleOption> &bundleOption, const NotificationConstant::SlotType &slotType, bool &enabled)
3567 {
3568 ANS_LOGD("slotType: %{public}d", slotType);
3569
3570 if (!IsSystemApp()) {
3571 return ERR_ANS_NON_SYSTEM_APP;
3572 }
3573
3574 if (!CheckPermission(OHOS_PERMISSION_NOTIFICATION_CONTROLLER)) {
3575 return ERR_ANS_PERMISSION_DENIED;
3576 }
3577
3578 sptr<NotificationBundleOption> bundle = GenerateValidBundleOption(bundleOption);
3579 if (bundle == nullptr) {
3580 return ERR_ANS_INVALID_BUNDLE;
3581 }
3582
3583 ErrCode result = ERR_OK;
3584 handler_->PostSyncTask(std::bind([&]() {
3585 sptr<NotificationSlot> slot;
3586 result = NotificationPreferences::GetInstance().GetNotificationSlot(bundle, slotType, slot);
3587 if (result != ERR_OK) {
3588 ANS_LOGE("Get enable slot: GetNotificationSlot failed");
3589 return;
3590 }
3591 if (slot == nullptr) {
3592 ANS_LOGW("Get enable slot: object is null, enabled default true");
3593 enabled = true;
3594 result = ERR_OK;
3595 return;
3596 }
3597 enabled = slot->GetEnable();
3598 }));
3599
3600 return result;
3601 }
3602
PublishSlotChangeCommonEvent(const sptr<NotificationBundleOption> & bundleOption)3603 bool AdvancedNotificationService::PublishSlotChangeCommonEvent(const sptr<NotificationBundleOption> &bundleOption)
3604 {
3605 HITRACE_METER_NAME(HITRACE_TAG_NOTIFICATION, __PRETTY_FUNCTION__);
3606 ANS_LOGD("bundle [%{public}s : %{public}d]", bundleOption->GetBundleName().c_str(), bundleOption->GetUid());
3607
3608 EventFwk::Want want;
3609 AppExecFwk::ElementName element;
3610 element.SetBundleName(bundleOption->GetBundleName());
3611 want.SetElement(element);
3612 want.SetParam(AppExecFwk::Constants::UID, bundleOption->GetUid());
3613 want.SetAction(EventFwk::CommonEventSupport::COMMON_EVENT_SLOT_CHANGE);
3614 EventFwk::CommonEventData commonData {want};
3615 if (!EventFwk::CommonEventManager::PublishCommonEvent(commonData)) {
3616 ANS_LOGE("PublishCommonEvent failed");
3617 return false;
3618 }
3619
3620 return true;
3621 }
3622
ShellDump(const std::string & cmd,const std::string & bundle,int32_t userId,std::vector<std::string> & dumpInfo)3623 ErrCode AdvancedNotificationService::ShellDump(const std::string &cmd, const std::string &bundle, int32_t userId,
3624 std::vector<std::string> &dumpInfo)
3625 {
3626 ANS_LOGD("%{public}s", __FUNCTION__);
3627
3628 if (!AccessTokenHelper::VerifyNativeToken(IPCSkeleton::GetCallingTokenID())) {
3629 ANS_LOGE("Not subsystem or shell request");
3630 return ERR_ANS_NON_SYSTEM_APP;
3631 }
3632
3633 ErrCode result = ERR_ANS_NOT_ALLOWED;
3634 handler_->PostSyncTask(std::bind([&]() {
3635 if (cmd == ACTIVE_NOTIFICATION_OPTION) {
3636 result = ActiveNotificationDump(bundle, userId, dumpInfo);
3637 } else if (cmd == RECENT_NOTIFICATION_OPTION) {
3638 result = RecentNotificationDump(bundle, userId, dumpInfo);
3639 #ifdef DISTRIBUTED_NOTIFICATION_SUPPORTED
3640 } else if (cmd == DISTRIBUTED_NOTIFICATION_OPTION) {
3641 result = DistributedNotificationDump(bundle, userId, dumpInfo);
3642 #endif
3643 } else if (cmd.substr(0, cmd.find_first_of(" ", 0)) == SET_RECENT_COUNT_OPTION) {
3644 result = SetRecentNotificationCount(cmd.substr(cmd.find_first_of(" ", 0) + 1));
3645 } else {
3646 result = ERR_ANS_INVALID_PARAM;
3647 }
3648 }));
3649 return result;
3650 }
3651
Dump(int fd,const std::vector<std::u16string> & args)3652 int AdvancedNotificationService::Dump(int fd, const std::vector<std::u16string> &args)
3653 {
3654 ANS_LOGD("enter");
3655 std::string result;
3656 GetDumpInfo(args, result);
3657 int ret = dprintf(fd, "%s\n", result.c_str());
3658 if (ret < 0) {
3659 ANS_LOGE("dprintf error");
3660 return ERR_ANS_INVALID_PARAM;
3661 }
3662 return ERR_OK;
3663 }
3664
GetDumpInfo(const std::vector<std::u16string> & args,std::string & result)3665 void AdvancedNotificationService::GetDumpInfo(const std::vector<std::u16string> &args, std::string &result)
3666 {
3667 if (args.size() != 1) {
3668 result = HIDUMPER_ERR_MSG;
3669 return;
3670 }
3671 std::vector<std::string> dumpInfo;
3672 std::string cmd = Str16ToStr8(args.front());
3673 if (HIDUMPER_CMD_MAP.find(cmd) == HIDUMPER_CMD_MAP.end()) {
3674 result = HIDUMPER_ERR_MSG;
3675 return;
3676 }
3677 std::string cmdValue = HIDUMPER_CMD_MAP.find(cmd)->second;
3678 if (cmdValue == HELP_NOTIFICATION_OPTION) {
3679 result = HIDUMPER_HELP_MSG;
3680 }
3681 ShellDump(cmdValue, "", SUBSCRIBE_USER_INIT, dumpInfo);
3682 if (dumpInfo.empty()) {
3683 result.append("no notification\n");
3684 return;
3685 }
3686 int32_t index = 0;
3687 result.append("notification list:\n");
3688 for (const auto &info: dumpInfo) {
3689 result.append("No." + std::to_string(++index) + "\n");
3690 result.append(info);
3691 }
3692 }
3693
SendSubscribeHiSysEvent(int32_t pid,int32_t uid,const sptr<NotificationSubscribeInfo> & info,ErrCode errCode)3694 void AdvancedNotificationService::SendSubscribeHiSysEvent(int32_t pid, int32_t uid,
3695 const sptr<NotificationSubscribeInfo> &info, ErrCode errCode)
3696 {
3697 EventInfo eventInfo;
3698 eventInfo.pid = pid;
3699 eventInfo.uid = uid;
3700 if (info != nullptr) {
3701 eventInfo.userId = info->GetAppUserId();
3702 std::vector<std::string> appNames = info->GetAppNames();
3703 eventInfo.bundleName = std::accumulate(appNames.begin(), appNames.end(), std::string(""),
3704 [appNames](const std::string &bundleName, const std::string &str) {
3705 return (str == appNames.front()) ? (bundleName + str) : (bundleName + "," + str);
3706 });
3707 }
3708
3709 if (errCode != ERR_OK) {
3710 eventInfo.errCode = errCode;
3711 EventReport::SendHiSysEvent(SUBSCRIBE_ERROR, eventInfo);
3712 } else {
3713 EventReport::SendHiSysEvent(SUBSCRIBE, eventInfo);
3714 }
3715 }
3716
SendUnSubscribeHiSysEvent(int32_t pid,int32_t uid,const sptr<NotificationSubscribeInfo> & info)3717 void AdvancedNotificationService::SendUnSubscribeHiSysEvent(int32_t pid, int32_t uid,
3718 const sptr<NotificationSubscribeInfo> &info)
3719 {
3720 EventInfo eventInfo;
3721 eventInfo.pid = pid;
3722 eventInfo.uid = uid;
3723 if (info != nullptr) {
3724 eventInfo.userId = info->GetAppUserId();
3725 std::vector<std::string> appNames = info->GetAppNames();
3726 eventInfo.bundleName = std::accumulate(appNames.begin(), appNames.end(), std::string(""),
3727 [appNames](const std::string &bundleName, const std::string &str) {
3728 return (str == appNames.front()) ? (bundleName + str) : (bundleName + "," + str);
3729 });
3730 }
3731
3732 EventReport::SendHiSysEvent(UNSUBSCRIBE, eventInfo);
3733 }
3734
SendPublishHiSysEvent(const sptr<NotificationRequest> & request,ErrCode errCode)3735 void AdvancedNotificationService::SendPublishHiSysEvent(const sptr<NotificationRequest> &request, ErrCode errCode)
3736 {
3737 if (request == nullptr) {
3738 return;
3739 }
3740
3741 EventInfo eventInfo;
3742 eventInfo.notificationId = request->GetNotificationId();
3743 eventInfo.contentType = static_cast<int32_t>(request->GetNotificationType());
3744 eventInfo.bundleName = request->GetCreatorBundleName();
3745 eventInfo.userId = request->GetCreatorUserId();
3746 if (errCode != ERR_OK) {
3747 eventInfo.errCode = errCode;
3748 EventReport::SendHiSysEvent(PUBLISH_ERROR, eventInfo);
3749 } else {
3750 EventReport::SendHiSysEvent(PUBLISH, eventInfo);
3751 }
3752 }
3753
SendCancelHiSysEvent(int32_t notificationId,const std::string & label,const sptr<NotificationBundleOption> & bundleOption,ErrCode errCode)3754 void AdvancedNotificationService::SendCancelHiSysEvent(int32_t notificationId, const std::string &label,
3755 const sptr<NotificationBundleOption> &bundleOption, ErrCode errCode)
3756 {
3757 if (bundleOption == nullptr || errCode != ERR_OK) {
3758 return;
3759 }
3760
3761 EventInfo eventInfo;
3762 eventInfo.notificationId = notificationId;
3763 eventInfo.notificationLabel = label;
3764 eventInfo.bundleName = bundleOption->GetBundleName();
3765 eventInfo.uid = bundleOption->GetUid();
3766 EventReport::SendHiSysEvent(CANCEL, eventInfo);
3767 }
3768
SendRemoveHiSysEvent(int32_t notificationId,const std::string & label,const sptr<NotificationBundleOption> & bundleOption,ErrCode errCode)3769 void AdvancedNotificationService::SendRemoveHiSysEvent(int32_t notificationId, const std::string &label,
3770 const sptr<NotificationBundleOption> &bundleOption, ErrCode errCode)
3771 {
3772 if (bundleOption == nullptr || errCode != ERR_OK) {
3773 return;
3774 }
3775
3776 EventInfo eventInfo;
3777 eventInfo.notificationId = notificationId;
3778 eventInfo.notificationLabel = label;
3779 eventInfo.bundleName = bundleOption->GetBundleName();
3780 eventInfo.uid = bundleOption->GetUid();
3781 EventReport::SendHiSysEvent(REMOVE, eventInfo);
3782 }
3783
SendEnableNotificationHiSysEvent(const sptr<NotificationBundleOption> & bundleOption,bool enabled,ErrCode errCode)3784 void AdvancedNotificationService::SendEnableNotificationHiSysEvent(const sptr<NotificationBundleOption> &bundleOption,
3785 bool enabled, ErrCode errCode)
3786 {
3787 if (bundleOption == nullptr) {
3788 return;
3789 }
3790
3791 EventInfo eventInfo;
3792 eventInfo.bundleName = bundleOption->GetBundleName();
3793 eventInfo.uid = bundleOption->GetUid();
3794 eventInfo.enable = enabled;
3795 if (errCode != ERR_OK) {
3796 eventInfo.errCode = errCode;
3797 EventReport::SendHiSysEvent(ENABLE_NOTIFICATION_ERROR, eventInfo);
3798 } else {
3799 EventReport::SendHiSysEvent(ENABLE_NOTIFICATION, eventInfo);
3800 }
3801 }
3802
SendEnableNotificationSlotHiSysEvent(const sptr<NotificationBundleOption> & bundleOption,const NotificationConstant::SlotType & slotType,bool enabled,ErrCode errCode)3803 void AdvancedNotificationService::SendEnableNotificationSlotHiSysEvent(
3804 const sptr<NotificationBundleOption> &bundleOption, const NotificationConstant::SlotType &slotType,
3805 bool enabled, ErrCode errCode)
3806 {
3807 if (bundleOption == nullptr) {
3808 return;
3809 }
3810
3811 EventInfo eventInfo;
3812 eventInfo.bundleName = bundleOption->GetBundleName();
3813 eventInfo.uid = bundleOption->GetUid();
3814 eventInfo.slotType = slotType;
3815 eventInfo.enable = enabled;
3816 if (errCode != ERR_OK) {
3817 eventInfo.errCode = errCode;
3818 EventReport::SendHiSysEvent(ENABLE_NOTIFICATION_SLOT_ERROR, eventInfo);
3819 } else {
3820 EventReport::SendHiSysEvent(ENABLE_NOTIFICATION_SLOT, eventInfo);
3821 }
3822 }
3823
SendFlowControlOccurHiSysEvent(const std::shared_ptr<NotificationRecord> & record)3824 void AdvancedNotificationService::SendFlowControlOccurHiSysEvent(const std::shared_ptr<NotificationRecord> &record)
3825 {
3826 if (record == nullptr || record->request == nullptr || record->bundleOption == nullptr) {
3827 return;
3828 }
3829
3830 EventInfo eventInfo;
3831 eventInfo.notificationId = record->request->GetNotificationId();
3832 eventInfo.bundleName = record->bundleOption->GetBundleName();
3833 eventInfo.uid = record->bundleOption->GetUid();
3834 EventReport::SendHiSysEvent(FLOW_CONTROL_OCCUR, eventInfo);
3835 }
3836
SetSyncNotificationEnabledWithoutApp(const int32_t userId,const bool enabled)3837 ErrCode AdvancedNotificationService::SetSyncNotificationEnabledWithoutApp(const int32_t userId, const bool enabled)
3838 {
3839 ANS_LOGD("userId: %{public}d, enabled: %{public}d", userId, enabled);
3840
3841 #ifdef DISTRIBUTED_NOTIFICATION_SUPPORTED
3842 if (!IsSystemApp()) {
3843 return ERR_ANS_NON_SYSTEM_APP;
3844 }
3845
3846 if (!CheckPermission(OHOS_PERMISSION_NOTIFICATION_CONTROLLER)) {
3847 return ERR_ANS_PERMISSION_DENIED;
3848 }
3849
3850 ErrCode result = ERR_OK;
3851 handler_->PostSyncTask(
3852 std::bind([&]() {
3853 result = DistributedPreferences::GetInstance()->SetSyncEnabledWithoutApp(userId, enabled);
3854 }));
3855 return result;
3856 #else
3857 return ERR_INVALID_OPERATION;
3858 #endif
3859 }
3860
GetSyncNotificationEnabledWithoutApp(const int32_t userId,bool & enabled)3861 ErrCode AdvancedNotificationService::GetSyncNotificationEnabledWithoutApp(const int32_t userId, bool &enabled)
3862 {
3863 ANS_LOGD("userId: %{public}d", userId);
3864
3865 #ifdef DISTRIBUTED_NOTIFICATION_SUPPORTED
3866 if (!IsSystemApp()) {
3867 return ERR_ANS_NON_SYSTEM_APP;
3868 }
3869
3870 if (!CheckPermission(OHOS_PERMISSION_NOTIFICATION_CONTROLLER)) {
3871 return ERR_ANS_PERMISSION_DENIED;
3872 }
3873
3874 ErrCode result = ERR_OK;
3875 handler_->PostSyncTask(
3876 std::bind([&]() {
3877 result = DistributedPreferences::GetInstance()->GetSyncEnabledWithoutApp(userId, enabled);
3878 }));
3879 return result;
3880 #else
3881 return ERR_INVALID_OPERATION;
3882 #endif
3883 }
3884
PublishNotificationBySa(const sptr<NotificationRequest> & request)3885 ErrCode AdvancedNotificationService::PublishNotificationBySa(const sptr<NotificationRequest> &request)
3886 {
3887 ANS_LOGD("%{public}s", __FUNCTION__);
3888
3889 int32_t uid = request->GetCreatorUid();
3890 if (uid <= 0) {
3891 ANS_LOGE("CreatorUid[%{public}d] error", uid);
3892 return ERR_ANS_INVALID_UID;
3893 }
3894
3895 std::shared_ptr<BundleManagerHelper> bundleManager = BundleManagerHelper::GetInstance();
3896 if (bundleManager == nullptr) {
3897 ANS_LOGE("failed to get bundleManager!");
3898 return ERR_ANS_INVALID_BUNDLE;
3899 }
3900 std::string bundle = bundleManager->GetBundleNameByUid(uid);
3901 if (request->GetCreatorBundleName().empty()) {
3902 request->SetCreatorBundleName(bundle);
3903 }
3904 if (request->GetOwnerBundleName().empty()) {
3905 request->SetOwnerBundleName(bundle);
3906 }
3907
3908 request->SetCreatorPid(IPCSkeleton::GetCallingPid());
3909 int32_t userId = SUBSCRIBE_USER_INIT;
3910 OHOS::AccountSA::OsAccountManager::GetOsAccountLocalIdFromUid(IPCSkeleton::GetCallingUid(), userId);
3911 request->SetCreatorUserId(userId);
3912 ANS_LOGD("creator uid=%{public}d, userId=%{public}d, bundleName=%{public}s ", uid, userId, bundle.c_str());
3913
3914 ErrCode result = CheckPictureSize(request);
3915 if (result != ERR_OK) {
3916 ANS_LOGE("Failed to check picture size");
3917 return result;
3918 }
3919
3920 sptr<NotificationBundleOption> bundleOption = new NotificationBundleOption(bundle, uid);
3921 if (bundleOption == nullptr) {
3922 ANS_LOGE("Failed to create bundleOption");
3923 return ERR_ANS_NO_MEMORY;
3924 }
3925
3926 std::shared_ptr<NotificationRecord> record = std::make_shared<NotificationRecord>();
3927 record->request = request;
3928 record->bundleOption = bundleOption;
3929 record->notification = new (std::nothrow) Notification(request);
3930 if (record->notification == nullptr) {
3931 ANS_LOGE("Failed to create notification");
3932 return ERR_ANS_NO_MEMORY;
3933 }
3934
3935 handler_->PostSyncTask([this, &record]() {
3936 if (AssignToNotificationList(record) != ERR_OK) {
3937 ANS_LOGE("Failed to assign notification list");
3938 return;
3939 }
3940
3941 UpdateRecentNotification(record->notification, false, 0);
3942 sptr<NotificationSortingMap> sortingMap = GenerateSortingMap();
3943 NotificationSubscriberManager::GetInstance()->NotifyConsumed(record->notification, sortingMap);
3944 });
3945
3946 return result;
3947 }
3948 } // namespace Notification
3949 } // namespace OHOS
3950