1 /*
2 * Copyright (c) 2021-2024 Huawei Device Co., Ltd.
3 * Licensed under the Apache License, Version 2.0 (the "License");
4 * you may not use this file except in compliance with the License.
5 * You may obtain a copy of the License at
6 *
7 * http://www.apache.org/licenses/LICENSE-2.0
8 *
9 * Unless required by applicable law or agreed to in writing, software
10 * distributed under the License is distributed on an "AS IS" BASIS,
11 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 * See the License for the specific language governing permissions and
13 * limitations under the License.
14 */
15 #include "advanced_notification_service.h"
16
17 #include <functional>
18 #include <iomanip>
19 #include <sstream>
20
21 #include "ans_const_define.h"
22 #include "ans_inner_errors.h"
23 #include "ans_log_wrapper.h"
24 #include "access_token_helper.h"
25 #include "ans_permission_def.h"
26 #include "bundle_manager_helper.h"
27 #include "errors.h"
28 #include "ipc_skeleton.h"
29 #include "notification_bundle_option.h"
30 #include "notification_constant.h"
31 #include "notification_trust_list.h"
32 #include "os_account_manager.h"
33 #include "notification_preferences.h"
34 #include "distributed_database.h"
35 #include "singleton.h"
36 #include "want_agent_helper.h"
37 #include "hitrace_meter.h"
38 #include "notification_timer_info.h"
39 #include "time_service_client.h"
40 #include "notification_extension_wrapper.h"
41 #include "string_utils.h"
42
43 #ifdef DISTRIBUTED_NOTIFICATION_SUPPORTED
44 #include "distributed_notification_manager.h"
45 #include "distributed_preferences.h"
46 #include "distributed_screen_status_manager.h"
47 #endif
48
49 #include "advanced_notification_inline.cpp"
50 #include "notification_analytics_util.h"
51 #include "notification_clone_disturb_service.h"
52 #include "notification_clone_bundle_service.h"
53
54 #define CHECK_BUNDLE_OPTION_IS_INVALID(option) \
55 if (option == nullptr || option->GetBundleName().empty()) { \
56 ANS_LOGE("Bundle option sptr is null or bundle name is empty!"); \
57 return; \
58 }
59
60 #define CHECK_BUNDLE_OPTION_IS_INVALID_WITH_RETURN(option, retVal) \
61 if (option == nullptr || option->GetBundleName().empty()) { \
62 ANS_LOGE("Bundle option sptr is null or bundle name is empty!"); \
63 return retVal; \
64 }
65
66 namespace OHOS {
67 namespace Notification {
68 namespace {
69 #ifdef DISTRIBUTED_NOTIFICATION_SUPPORTED
70 constexpr char DISTRIBUTED_NOTIFICATION_OPTION[] = "distributed";
71 #endif
72 constexpr int32_t HOURS_IN_ONE_DAY = 24;
73 constexpr char FOUNDATION_BUNDLE_NAME[] = "ohos.global.systemres";
74 constexpr char ACTIVE_NOTIFICATION_OPTION[] = "active";
75 constexpr char SET_RECENT_COUNT_OPTION[] = "setRecentCount";
76 constexpr char HELP_NOTIFICATION_OPTION[] = "help";
77 constexpr char RECENT_NOTIFICATION_OPTION[] = "recent";
78 constexpr char HIDUMPER_ERR_MSG[] =
79 "error: unknown option.\nThe arguments are illegal and you can enter '-h' for help.";
80 constexpr int32_t MAIN_USER_ID = 100;
81 constexpr int32_t FIRST_USERID = 0;
82 constexpr char OLD_KEY_BUNDLE_DISTRIBUTED_ENABLE_NOTIFICATION[] = "enabledNotificationDistributed";
83 constexpr char KEY_TABLE_VERSION[] = "tableVersion";
84 constexpr char SPLIT_FLAG[] = "-";
85 constexpr int32_t KEYWORD_SIZE = 4;
86 constexpr int32_t MIN_VERSION = 1;
87 const std::unordered_map<std::string, std::string> HIDUMPER_CMD_MAP = {
88 { "--help", HELP_NOTIFICATION_OPTION },
89 { "--active", ACTIVE_NOTIFICATION_OPTION },
90 { "--recent", RECENT_NOTIFICATION_OPTION },
91 { "-h", HELP_NOTIFICATION_OPTION },
92 { "-a", ACTIVE_NOTIFICATION_OPTION },
93 { "-r", RECENT_NOTIFICATION_OPTION },
94 };
95
96 constexpr char HIDUMPER_HELP_MSG[] =
97 "Usage:dump <command> [options]\n"
98 "Description::\n"
99 " --active, -a list all active notifications\n"
100 " --recent, -r list recent notifications\n";
101 }
102
GetNotificationSvrQueue()103 std::shared_ptr<ffrt::queue> AdvancedNotificationService::GetNotificationSvrQueue()
104 {
105 return notificationSvrQueue_;
106 }
107
GenerateBundleOption()108 sptr<NotificationBundleOption> AdvancedNotificationService::GenerateBundleOption()
109 {
110 sptr<NotificationBundleOption> bundleOption = nullptr;
111 std::string bundle = "";
112 if (!AccessTokenHelper::VerifyNativeToken(IPCSkeleton::GetCallingTokenID())) {
113 bundle = GetClientBundleName();
114 if (bundle.empty()) {
115 return nullptr;
116 }
117 }
118
119 int32_t uid = IPCSkeleton::GetCallingUid();
120 bundleOption = new (std::nothrow) NotificationBundleOption(bundle, uid);
121 if (bundleOption == nullptr) {
122 return nullptr;
123 }
124 return bundleOption;
125 }
126
GenerateValidBundleOption(const sptr<NotificationBundleOption> & bundleOption)127 sptr<NotificationBundleOption> AdvancedNotificationService::GenerateValidBundleOption(
128 const sptr<NotificationBundleOption> &bundleOption)
129 {
130 if (bundleOption == nullptr) {
131 ANS_LOGE("bundleOption is invalid!");
132 return nullptr;
133 }
134
135 sptr<NotificationBundleOption> validBundleOption = nullptr;
136 if (bundleOption->GetUid() <= 0) {
137 std::shared_ptr<BundleManagerHelper> bundleManager = BundleManagerHelper::GetInstance();
138 if (bundleManager != nullptr) {
139 int32_t activeUserId = -1;
140 if (!GetActiveUserId(activeUserId)) {
141 ANS_LOGE("Failed to get active user id!");
142 return validBundleOption;
143 }
144 int32_t uid = bundleManager->GetDefaultUidByBundleName(bundleOption->GetBundleName(), activeUserId);
145 if (uid > 0) {
146 validBundleOption = new (std::nothrow) NotificationBundleOption(bundleOption->GetBundleName(), uid);
147 if (validBundleOption == nullptr) {
148 ANS_LOGE("Failed to create NotificationBundleOption instance");
149 return nullptr;
150 }
151 }
152 }
153 } else {
154 validBundleOption = bundleOption;
155 }
156 return validBundleOption;
157 }
158
GenerateSortingMap()159 sptr<NotificationSortingMap> AdvancedNotificationService::GenerateSortingMap()
160 {
161 std::vector<NotificationSorting> sortingList;
162 for (auto record : notificationList_) {
163 NotificationSorting sorting;
164 sorting.SetRanking(static_cast<uint64_t>(sortingList.size()));
165 sorting.SetKey(record->notification->GetKey());
166 sorting.SetSlot(record->slot);
167 sortingList.push_back(sorting);
168 }
169
170 sptr<NotificationSortingMap> sortingMap = new (std::nothrow) NotificationSortingMap(sortingList);
171 if (sortingMap == nullptr) {
172 ANS_LOGE("Failed to create NotificationSortingMap instance");
173 return nullptr;
174 }
175
176 return sortingMap;
177 }
178
CheckCommonParams()179 ErrCode AdvancedNotificationService::CheckCommonParams()
180 {
181 if (notificationSvrQueue_ == nullptr) {
182 ANS_LOGE("Serial queue is invalidity.");
183 return ERR_ANS_INVALID_PARAM;
184 }
185
186 bool isSubsystem = AccessTokenHelper::VerifyNativeToken(IPCSkeleton::GetCallingTokenID());
187 if (!isSubsystem && !AccessTokenHelper::IsSystemApp()) {
188 return ERR_ANS_NON_SYSTEM_APP;
189 }
190
191 if (!AccessTokenHelper::CheckPermission(OHOS_PERMISSION_NOTIFICATION_CONTROLLER)) {
192 ANS_LOGD("Check permission is false.");
193 return ERR_ANS_PERMISSION_DENIED;
194 }
195
196 return ERR_OK;
197 }
198
GetAppTargetBundle(const sptr<NotificationBundleOption> & bundleOption,sptr<NotificationBundleOption> & targetBundle)199 ErrCode AdvancedNotificationService::GetAppTargetBundle(const sptr<NotificationBundleOption> &bundleOption,
200 sptr<NotificationBundleOption> &targetBundle)
201 {
202 sptr<NotificationBundleOption> clientBundle = GenerateBundleOption();
203 if (clientBundle == nullptr) {
204 return ERR_ANS_INVALID_BUNDLE;
205 }
206
207 if (bundleOption == nullptr) {
208 targetBundle = clientBundle;
209 } else {
210 if ((clientBundle->GetBundleName() == bundleOption->GetBundleName()) &&
211 (clientBundle->GetUid() == bundleOption->GetUid())) {
212 targetBundle = bundleOption;
213 } else {
214 bool isSubsystem = AccessTokenHelper::VerifyNativeToken(IPCSkeleton::GetCallingTokenID());
215 if (!isSubsystem && !AccessTokenHelper::IsSystemApp()) {
216 return ERR_ANS_NON_SYSTEM_APP;
217 }
218 targetBundle = GenerateValidBundleOption(bundleOption);
219 }
220 }
221 return ERR_OK;
222 }
223
FillRequestByKeys(const sptr<NotificationRequest> & oldRequest,const std::vector<std::string> extraInfoKeys,sptr<NotificationRequest> & newRequest)224 ErrCode AdvancedNotificationService::FillRequestByKeys(const sptr<NotificationRequest> &oldRequest,
225 const std::vector<std::string> extraInfoKeys, sptr<NotificationRequest> &newRequest)
226 {
227 auto liveViewContent = std::static_pointer_cast<NotificationLiveViewContent>(
228 oldRequest->GetContent()->GetNotificationContent());
229 auto liveViewExtraInfo = liveViewContent->GetExtraInfo();
230
231 newRequest = sptr<NotificationRequest>::MakeSptr(*(oldRequest));
232 auto requestLiveViewContent = std::make_shared<NotificationLiveViewContent>();
233
234 requestLiveViewContent->SetLiveViewStatus(liveViewContent->GetLiveViewStatus());
235 requestLiveViewContent->SetVersion(liveViewContent->GetVersion());
236 requestLiveViewContent->SetLockScreenPicture(liveViewContent->GetLockScreenPicture());
237
238 std::shared_ptr<AAFwk::WantParams> requestExtraInfo = std::make_shared<AAFwk::WantParams>();
239 if (requestExtraInfo == nullptr) {
240 ANS_LOGE("Failed to make extraInfos.");
241 return ERR_ANS_TASK_ERR;
242 }
243 for (const auto &extraInfoKey : extraInfoKeys) {
244 auto paramValue = liveViewExtraInfo->GetParam(extraInfoKey);
245 if (paramValue != nullptr) {
246 requestExtraInfo->SetParam(extraInfoKey, paramValue);
247 }
248 }
249 requestLiveViewContent->SetExtraInfo(requestExtraInfo);
250
251 auto requestContent = std::make_shared<NotificationContent>(requestLiveViewContent);
252 newRequest->SetContent(requestContent);
253 return ERR_OK;
254 }
255
IsAllowedGetNotificationByFilter(const std::shared_ptr<NotificationRecord> & record,const sptr<NotificationBundleOption> & bundleOption)256 ErrCode AdvancedNotificationService::IsAllowedGetNotificationByFilter(
257 const std::shared_ptr<NotificationRecord> &record, const sptr<NotificationBundleOption> &bundleOption)
258 {
259 if (bundleOption->GetUid() == record->bundleOption->GetUid() &&
260 bundleOption->GetBundleName() == record->bundleOption->GetBundleName()) {
261 return ERR_OK;
262 }
263 ANS_LOGE("Get live view by filter failed because no permission.");
264 return ERR_ANS_PERMISSION_DENIED;
265 }
266
GetActiveNotificationByFilter(const sptr<NotificationBundleOption> & bundleOption,const int32_t notificationId,const std::string & label,const std::vector<std::string> extraInfoKeys,sptr<NotificationRequest> & request)267 ErrCode AdvancedNotificationService::GetActiveNotificationByFilter(
268 const sptr<NotificationBundleOption> &bundleOption, const int32_t notificationId, const std::string &label,
269 const std::vector<std::string> extraInfoKeys, sptr<NotificationRequest> &request)
270 {
271 ANS_LOGD("%{public}s", __FUNCTION__);
272 sptr<NotificationBundleOption> bundle = GenerateValidBundleOption(bundleOption);
273 if (bundle == nullptr) {
274 return ERR_ANS_INVALID_BUNDLE;
275 }
276 // get other bundle notification need controller permission
277 if (bundle->GetUid() == IPCSkeleton::GetCallingUid()) {
278 ANS_LOGI("Get self notification uid: %{public}d, curUid: %{public}d.",
279 bundle->GetUid(), IPCSkeleton::GetCallingUid());
280 } else {
281 if (!AccessTokenHelper::CheckPermission(OHOS_PERMISSION_NOTIFICATION_CONTROLLER)) {
282 ANS_LOGW("Get live view by filter failed because check permission is false.");
283 return ERR_ANS_PERMISSION_DENIED;
284 }
285 }
286
287 if (notificationSvrQueue_ == nullptr) {
288 ANS_LOGE("Serial queue is invalidity.");
289 return ERR_ANS_INVALID_PARAM;
290 }
291
292 ErrCode result = ERR_ANS_NOTIFICATION_NOT_EXISTS;
293 ffrt::task_handle handler = notificationSvrQueue_->submit_h(std::bind([&]() {
294 ANS_LOGD("ffrt enter!");
295
296 auto record = GetRecordFromNotificationList(notificationId, bundle->GetUid(), label, bundle->GetBundleName());
297 if ((record == nullptr) || (!record->request->IsCommonLiveView())) {
298 return;
299 }
300 result = IsAllowedGetNotificationByFilter(record, bundle);
301 if (result != ERR_OK) {
302 return;
303 }
304
305 if (extraInfoKeys.empty()) {
306 // return all liveViewExtraInfo because no extraInfoKeys
307 request = record->request;
308 return;
309 }
310 // obtain extraInfo by extraInfoKeys
311 if (FillRequestByKeys(record->request, extraInfoKeys, request) != ERR_OK) {
312 return;
313 }
314 }));
315 notificationSvrQueue_->wait(handler);
316
317 return result;
318 }
319
SetAgentNotification(sptr<NotificationRequest> & notificationRequest,std::string & bundleName)320 void AdvancedNotificationService::SetAgentNotification(sptr<NotificationRequest>& notificationRequest,
321 std::string& bundleName)
322 {
323 auto bundleManager = BundleManagerHelper::GetInstance();
324 int32_t activeUserId = -1;
325 if (!GetActiveUserId(activeUserId)) {
326 ANSR_LOGW("Failed to get active user id!");
327 return;
328 }
329
330 notificationRequest->SetIsAgentNotification(true);
331 notificationRequest->SetOwnerUserId(activeUserId);
332 notificationRequest->SetOwnerBundleName(bundleName);
333 }
334
ActiveNotificationDump(const std::string & bundle,int32_t userId,int32_t recvUserId,std::vector<std::string> & dumpInfo)335 ErrCode AdvancedNotificationService::ActiveNotificationDump(const std::string& bundle, int32_t userId,
336 int32_t recvUserId, std::vector<std::string> &dumpInfo)
337 {
338 ANS_LOGD("%{public}s", __FUNCTION__);
339 std::stringstream stream;
340 for (const auto &record : notificationList_) {
341 if (record->notification == nullptr || record->request == nullptr) {
342 continue;
343 }
344 if (userId != SUBSCRIBE_USER_INIT && userId != record->notification->GetUserId()) {
345 continue;
346 }
347 if (recvUserId != SUBSCRIBE_USER_INIT && recvUserId != record->notification->GetRecvUserId()) {
348 continue;
349 }
350 if (!bundle.empty() && bundle != record->notification->GetBundleName()) {
351 continue;
352 }
353 #ifdef DISTRIBUTED_NOTIFICATION_SUPPORTED
354 if (!record->deviceId.empty()) {
355 continue;
356 }
357 #endif
358 stream.clear();
359 stream.str("");
360 stream << "\tUserId: " << record->notification->GetUserId() << "\n";
361 stream << "\tCreatePid: " << record->request->GetCreatorPid() << "\n";
362 stream << "\tOwnerBundleName: " << record->notification->GetBundleName() << "\n";
363 if (record->request->GetOwnerUid() > 0) {
364 ANS_LOGD("GetOwnerUid larger than zero.");
365 stream << "\tOwnerUid: " << record->request->GetOwnerUid() << "\n";
366 } else {
367 stream << "\tOwnerUid: " << record->request->GetCreatorUid() << "\n";
368 }
369 stream << "\tReceiverUserId: " << record->request->GetReceiverUserId() << "\n";
370 stream << "\tDeliveryTime = " << TimeToString(record->request->GetDeliveryTime()) << "\n";
371 stream << "\tNotification:\n";
372 stream << "\t\tId: " << record->notification->GetId() << "\n";
373 stream << "\t\tLabel: " << record->notification->GetLabel() << "\n";
374 stream << "\t\tSlotType = " << record->request->GetSlotType() << "\n";
375 ANS_LOGD("DumpInfo push stream.");
376 dumpInfo.push_back(stream.str());
377 }
378 return ERR_OK;
379 }
380
RecentNotificationDump(const std::string & bundle,int32_t userId,int32_t recvUserId,std::vector<std::string> & dumpInfo)381 ErrCode AdvancedNotificationService::RecentNotificationDump(const std::string& bundle, int32_t userId,
382 int32_t recvUserId, std::vector<std::string> &dumpInfo)
383 {
384 ANS_LOGD("%{public}s", __FUNCTION__);
385 std::stringstream stream;
386 for (auto recentNotification : recentInfo_->list) {
387 if (recentNotification->notification == nullptr) {
388 continue;
389 }
390 const auto ¬ificationRequest = recentNotification->notification->GetNotificationRequest();
391 if (userId != SUBSCRIBE_USER_INIT && userId != notificationRequest.GetOwnerUserId()) {
392 continue;
393 }
394 if (recvUserId != SUBSCRIBE_USER_INIT && recvUserId != recentNotification->notification->GetRecvUserId()) {
395 continue;
396 }
397 if (!bundle.empty() && bundle != recentNotification->notification->GetBundleName()) {
398 continue;
399 }
400 stream.clear();
401 stream.str("");
402 stream << "\tUserId: " << notificationRequest.GetCreatorUserId() << "\n";
403 stream << "\tCreatePid: " << notificationRequest.GetCreatorPid() << "\n";
404 stream << "\tBundleName: " << recentNotification->notification->GetBundleName() << "\n";
405 if (notificationRequest.GetOwnerUid() > 0) {
406 stream << "\tOwnerUid: " << notificationRequest.GetOwnerUid() << "\n";
407 } else {
408 stream << "\tOwnerUid: " << notificationRequest.GetCreatorUid() << "\n";
409 }
410 stream << "\tReceiverUserId: " << notificationRequest.GetReceiverUserId() << "\n";
411 stream << "\tDeliveryTime = " << TimeToString(notificationRequest.GetDeliveryTime()) << "\n";
412 if (!recentNotification->isActive) {
413 stream << "\tDeleteTime: " << TimeToString(recentNotification->deleteTime) << "\n";
414 stream << "\tDeleteReason: " << recentNotification->deleteReason << "\n";
415 }
416 stream << "\tNotification:\n";
417 stream << "\t\tId: " << recentNotification->notification->GetId() << "\n";
418 stream << "\t\tLabel: " << recentNotification->notification->GetLabel() << "\n";
419 stream << "\t\tSlotType = " << notificationRequest.GetSlotType() << "\n";
420 dumpInfo.push_back(stream.str());
421 }
422 return ERR_OK;
423 }
424
425 #ifdef DISTRIBUTED_NOTIFICATION_SUPPORTED
DistributedNotificationDump(const std::string & bundle,int32_t userId,int32_t recvUserId,std::vector<std::string> & dumpInfo)426 ErrCode AdvancedNotificationService::DistributedNotificationDump(const std::string& bundle, int32_t userId,
427 int32_t recvUserId, std::vector<std::string> &dumpInfo)
428 {
429 ANS_LOGD("%{public}s", __FUNCTION__);
430 std::stringstream stream;
431 for (auto record : notificationList_) {
432 if (record->notification == nullptr) {
433 continue;
434 }
435 if (userId != SUBSCRIBE_USER_INIT && userId != record->notification->GetUserId()) {
436 continue;
437 }
438 if (recvUserId != SUBSCRIBE_USER_INIT && recvUserId != record->notification->GetRecvUserId()) {
439 continue;
440 }
441 if (!bundle.empty() && bundle != record->notification->GetBundleName()) {
442 continue;
443 }
444 if (record->deviceId.empty()) {
445 continue;
446 }
447 stream.clear();
448 stream.str("");
449 stream << "\tUserId: " << record->notification->GetUserId() << "\n";
450 stream << "\tCreatePid: " << record->request->GetCreatorPid() << "\n";
451 stream << "\tOwnerBundleName: " << record->notification->GetBundleName() << "\n";
452 if (record->request->GetOwnerUid() > 0) {
453 stream << "\tOwnerUid: " << record->request->GetOwnerUid() << "\n";
454 } else {
455 stream << "\tOwnerUid: " << record->request->GetCreatorUid() << "\n";
456 }
457 stream << "\tReceiverUserId: " << record->request->GetReceiverUserId() << "\n";
458 stream << "\tDeliveryTime = " << TimeToString(record->request->GetDeliveryTime()) << "\n";
459 stream << "\tNotification:\n";
460 stream << "\t\tId: " << record->notification->GetId() << "\n";
461 stream << "\t\tLabel: " << record->notification->GetLabel() << "\n";
462 stream << "\t\tSlotType = " << record->request->GetSlotType() << "\n";
463 dumpInfo.push_back(stream.str());
464 }
465
466 return ERR_OK;
467 }
468 #endif
469
TimeToString(int64_t time)470 std::string AdvancedNotificationService::TimeToString(int64_t time)
471 {
472 auto timePoint = std::chrono::time_point<std::chrono::system_clock>(std::chrono::milliseconds(time));
473 auto timeT = std::chrono::system_clock::to_time_t(timePoint);
474
475 std::stringstream stream;
476 struct tm ret = {0};
477 localtime_r(&timeT, &ret);
478 stream << std::put_time(&ret, "%F, %T");
479 return stream.str();
480 }
481
GetNowSysTime()482 int64_t AdvancedNotificationService::GetNowSysTime()
483 {
484 std::chrono::time_point<std::chrono::system_clock> nowSys = std::chrono::system_clock::now();
485 auto epoch = nowSys.time_since_epoch();
486 auto value = std::chrono::duration_cast<std::chrono::milliseconds>(epoch);
487 int64_t duration = value.count();
488 return duration;
489 }
490
OnBundleRemoved(const sptr<NotificationBundleOption> & bundleOption)491 void AdvancedNotificationService::OnBundleRemoved(const sptr<NotificationBundleOption> &bundleOption)
492 {
493 ANS_LOGD("%{public}s", __FUNCTION__);
494 if (notificationSvrQueue_ == nullptr) {
495 ANS_LOGE("Serial queue is invalid.");
496 return;
497 }
498 notificationSvrQueue_->submit(std::bind([this, bundleOption]() {
499 ANS_LOGD("ffrt enter!");
500 ErrCode result = NotificationPreferences::GetInstance()->RemoveNotificationForBundle(bundleOption);
501 if (result != ERR_OK) {
502 ANS_LOGW("NotificationPreferences::RemoveNotificationForBundle failed: %{public}d", result);
503 }
504 #ifdef DISTRIBUTED_NOTIFICATION_SUPPORTED
505 DistributedPreferences::GetInstance()->DeleteDistributedBundleInfo(bundleOption);
506 std::vector<std::string> keys = GetLocalNotificationKeys(bundleOption);
507 #else
508 std::vector<std::string> keys = GetNotificationKeys(bundleOption);
509 #endif
510 std::vector<sptr<Notification>> notifications;
511 std::vector<uint64_t> timerIds;
512 for (auto key : keys) {
513 sptr<Notification> notification = nullptr;
514 result = RemoveFromNotificationList(key, notification, true,
515 NotificationConstant::PACKAGE_REMOVE_REASON_DELETE);
516 if (result != ERR_OK) {
517 continue;
518 }
519
520 if (notification != nullptr) {
521 int32_t reason = NotificationConstant::PACKAGE_REMOVE_REASON_DELETE;
522 UpdateRecentNotification(notification, true, reason);
523 notifications.emplace_back(notification);
524 timerIds.emplace_back(notification->GetAutoDeletedTimer());
525 ExecBatchCancel(notifications, reason);
526 #ifdef DISTRIBUTED_NOTIFICATION_SUPPORTED
527 DoDistributedDelete("", "", notification);
528 #endif
529 }
530 }
531 if (!notifications.empty()) {
532 NotificationSubscriberManager::GetInstance()->BatchNotifyCanceled(
533 notifications, nullptr, NotificationConstant::PACKAGE_REMOVE_REASON_DELETE);
534 }
535 BatchCancelTimer(timerIds);
536 NotificationPreferences::GetInstance()->RemoveAnsBundleDbInfo(bundleOption);
537 RemoveDoNotDisturbProfileTrustList(bundleOption);
538 DeleteDuplicateMsgs(bundleOption);
539 }));
540 NotificationPreferences::GetInstance()->RemoveEnabledDbByBundle(bundleOption);
541 #ifdef ENABLE_ANS_EXT_WRAPPER
542 EXTENTION_WRAPPER->UpdateByBundle(bundleOption->GetBundleName(),
543 NotificationConstant::PACKAGE_REMOVE_REASON_DELETE);
544 #endif
545 }
546
ExecBatchCancel(std::vector<sptr<Notification>> & notifications,int32_t & reason)547 void AdvancedNotificationService::ExecBatchCancel(std::vector<sptr<Notification>> ¬ifications,
548 int32_t &reason)
549 {
550 if (notifications.size() >= MAX_CANCELED_PARCELABLE_VECTOR_NUM) {
551 std::vector<sptr<Notification>> currNotificationList = notifications;
552 NotificationSubscriberManager::GetInstance()->BatchNotifyCanceled(
553 currNotificationList, nullptr, reason);
554 notifications.clear();
555 }
556 }
557
RemoveDoNotDisturbProfileTrustList(const sptr<NotificationBundleOption> & bundleOption)558 void AdvancedNotificationService::RemoveDoNotDisturbProfileTrustList(
559 const sptr<NotificationBundleOption> &bundleOption)
560 {
561 ANS_LOGD("Called.");
562 int32_t userId = 0;
563 if (AccountSA::OsAccountManager::GetOsAccountLocalIdFromUid(bundleOption->GetUid(), userId) != ERR_OK) {
564 ANS_LOGE("Failed to get active user id.");
565 return;
566 }
567 NotificationPreferences::GetInstance()->RemoveDoNotDisturbProfileTrustList(userId, bundleOption);
568 }
569
OnBundleDataAdd(const sptr<NotificationBundleOption> & bundleOption)570 void AdvancedNotificationService::OnBundleDataAdd(const sptr<NotificationBundleOption> &bundleOption)
571 {
572 CHECK_BUNDLE_OPTION_IS_INVALID(bundleOption)
573 auto bundleInstall = [bundleOption, this]() {
574 CHECK_BUNDLE_OPTION_IS_INVALID(bundleOption)
575 AppExecFwk::BundleInfo bundleInfo;
576 if (!GetBundleInfoByNotificationBundleOption(bundleOption, bundleInfo)) {
577 ANS_LOGE("Failed to get BundleInfo using NotificationBundleOption.");
578 return;
579 }
580
581 // In order to adapt to the publish reminder interface, currently only the input from the whitelist is written
582 if (bundleInfo.applicationInfo.allowEnableNotification) {
583 auto errCode = NotificationPreferences::GetInstance()->SetNotificationsEnabledForBundle(bundleOption, true);
584 if (errCode != ERR_OK) {
585 ANS_LOGE("Set notification enable error! code: %{public}d", errCode);
586 }
587 SetSlotFlagsTrustlistsAsBundle(bundleOption);
588 errCode = NotificationPreferences::GetInstance()->SetShowBadge(bundleOption, true);
589 if (errCode != ERR_OK) {
590 ANS_LOGE("Set badge enable error! code: %{public}d", errCode);
591 }
592 }
593 NotificationCloneBundle::GetInstance()->OnBundleDataAdd(bundleOption);
594 };
595
596 NotificationCloneDisturb::GetInstance()->OnBundleDataAdd(bundleOption);
597 notificationSvrQueue_ != nullptr ? notificationSvrQueue_->submit(bundleInstall) : bundleInstall();
598 }
599
OnBundleDataUpdate(const sptr<NotificationBundleOption> & bundleOption)600 void AdvancedNotificationService::OnBundleDataUpdate(const sptr<NotificationBundleOption> &bundleOption)
601 {
602 CHECK_BUNDLE_OPTION_IS_INVALID(bundleOption)
603 AppExecFwk::BundleInfo bundleInfo;
604 if (!GetBundleInfoByNotificationBundleOption(bundleOption, bundleInfo)) {
605 ANS_LOGE("Failed to get BundleInfo using NotificationBundleOption.");
606 return;
607 }
608
609 if (!bundleInfo.applicationInfo.allowEnableNotification) {
610 ANS_LOGE("Current application allowEnableNotification is false, do not record.");
611 return;
612 }
613 auto bundleUpdate = [bundleOption, bundleInfo, this]() {
614 bool enabled = false;
615 auto errCode = NotificationPreferences::GetInstance()->GetNotificationsEnabledForBundle(
616 bundleOption, enabled);
617 if (errCode != ERR_OK) {
618 ANS_LOGD("Get notification user option fail, need to insert data");
619 OnBundleDataAdd(bundleOption);
620 return;
621 }
622 };
623
624 NotificationCloneDisturb::GetInstance()->OnBundleDataUpdate(bundleOption);
625 notificationSvrQueue_ != nullptr ? notificationSvrQueue_->submit(bundleUpdate) : bundleUpdate();
626 }
627
OnBootSystemCompleted()628 void AdvancedNotificationService::OnBootSystemCompleted()
629 {
630 ANS_LOGI("Called.");
631 InitNotificationEnableList();
632 }
633
634 #ifdef DISTRIBUTED_NOTIFICATION_SUPPORTED
OnScreenOn()635 void AdvancedNotificationService::OnScreenOn()
636 {
637 ANS_LOGI("%{public}s", __FUNCTION__);
638 localScreenOn_ = true;
639 DistributedScreenStatusManager::GetInstance()->SetLocalScreenStatus(true);
640 }
641
OnScreenOff()642 void AdvancedNotificationService::OnScreenOff()
643 {
644 ANS_LOGI("%{public}s", __FUNCTION__);
645 localScreenOn_ = false;
646 DistributedScreenStatusManager::GetInstance()->SetLocalScreenStatus(false);
647 }
648 #endif
649
OnDistributedKvStoreDeathRecipient()650 void AdvancedNotificationService::OnDistributedKvStoreDeathRecipient()
651 {
652 ANS_LOGD("%{public}s", __FUNCTION__);
653 if (notificationSvrQueue_ == nullptr) {
654 ANS_LOGE("Serial queue is invalid.");
655 return;
656 }
657 ffrt::task_handle handler = notificationSvrQueue_->submit_h(std::bind([&]() {
658 ANS_LOGD("ffrt enter!");
659 #ifdef DISTRIBUTED_NOTIFICATION_SUPPORTED
660 DistributedNotificationManager::GetInstance()->OnDistributedKvStoreDeathRecipient();
661 #endif
662 }));
663 }
664
GetTargetRecordList(const int32_t uid,NotificationConstant::SlotType slotType,NotificationContent::Type contentType,std::vector<std::shared_ptr<NotificationRecord>> & recordList)665 ErrCode AdvancedNotificationService::GetTargetRecordList(const int32_t uid,
666 NotificationConstant::SlotType slotType, NotificationContent::Type contentType,
667 std::vector<std::shared_ptr<NotificationRecord>>& recordList)
668 {
669 for (auto& notification : notificationList_) {
670 if (notification->request != nullptr && notification->request->GetSlotType()== slotType &&
671 notification->request->GetNotificationType() == contentType &&
672 notification->request->GetCreatorUid() == uid) {
673 recordList.emplace_back(notification);
674 }
675 }
676 if (recordList.empty()) {
677 return ERR_ANS_NOTIFICATION_NOT_EXISTS;
678 }
679 return ERR_OK;
680 }
681
GetCommonTargetRecordList(const int32_t uid,NotificationConstant::SlotType slotType,NotificationContent::Type contentType,std::vector<std::shared_ptr<NotificationRecord>> & recordList)682 ErrCode AdvancedNotificationService::GetCommonTargetRecordList(const int32_t uid,
683 NotificationConstant::SlotType slotType, NotificationContent::Type contentType,
684 std::vector<std::shared_ptr<NotificationRecord>>& recordList)
685 {
686 for (auto& notification : notificationList_) {
687 if (notification->request != nullptr && notification->request->IsCommonLiveView()) {
688 auto liveViewContent = std::static_pointer_cast<NotificationLiveViewContent>(
689 notification->request->GetContent()->GetNotificationContent());
690 if (notification->request->GetCreatorUid() == uid &&
691 notification->request->GetSlotType()== slotType &&
692 notification->request->GetNotificationType() == contentType &&
693 liveViewContent->GetIsOnlyLocalUpdate()) {
694 recordList.emplace_back(notification);
695 }
696 }
697 }
698 if (recordList.empty()) {
699 return ERR_ANS_NOTIFICATION_NOT_EXISTS;
700 }
701 return ERR_OK;
702 }
703
AdjustDateForDndTypeOnce(int64_t & beginDate,int64_t & endDate)704 void AdvancedNotificationService::AdjustDateForDndTypeOnce(int64_t &beginDate, int64_t &endDate)
705 {
706 std::chrono::system_clock::time_point now = std::chrono::system_clock::now();
707 time_t nowT = std::chrono::system_clock::to_time_t(now);
708 tm nowTm = GetLocalTime(nowT);
709
710 auto beginDateMilliseconds = std::chrono::milliseconds(beginDate);
711 auto beginDateTimePoint =
712 std::chrono::time_point<std::chrono::system_clock, std::chrono::milliseconds>(beginDateMilliseconds);
713 time_t beginDateT = std::chrono::system_clock::to_time_t(beginDateTimePoint);
714 tm beginDateTm = GetLocalTime(beginDateT);
715
716 auto endDateMilliseconds = std::chrono::milliseconds(endDate);
717 auto endDateTimePoint =
718 std::chrono::time_point<std::chrono::system_clock, std::chrono::milliseconds>(endDateMilliseconds);
719 time_t endDateT = std::chrono::system_clock::to_time_t(endDateTimePoint);
720 tm endDateTm = GetLocalTime(endDateT);
721
722 tm todayBeginTm = nowTm;
723 todayBeginTm.tm_sec = 0;
724 todayBeginTm.tm_min = beginDateTm.tm_min;
725 todayBeginTm.tm_hour = beginDateTm.tm_hour;
726
727 tm todayEndTm = nowTm;
728 todayEndTm.tm_sec = 0;
729 todayEndTm.tm_min = endDateTm.tm_min;
730 todayEndTm.tm_hour = endDateTm.tm_hour;
731
732 time_t todayBeginT = mktime(&todayBeginTm);
733 if (todayBeginT == -1) {
734 return;
735 }
736 time_t todayEndT = mktime(&todayEndTm);
737 if (todayEndT == -1) {
738 return;
739 }
740
741 auto newBeginTimePoint = std::chrono::system_clock::from_time_t(todayBeginT);
742 auto newEndTimePoint = std::chrono::system_clock::from_time_t(todayEndT);
743 if (newBeginTimePoint >= newEndTimePoint) {
744 newEndTimePoint += std::chrono::hours(HOURS_IN_ONE_DAY);
745 }
746
747 if (newEndTimePoint < now) {
748 newBeginTimePoint += std::chrono::hours(HOURS_IN_ONE_DAY);
749 newEndTimePoint += std::chrono::hours(HOURS_IN_ONE_DAY);
750 }
751
752 auto newBeginDuration = std::chrono::duration_cast<std::chrono::milliseconds>(newBeginTimePoint.time_since_epoch());
753 beginDate = newBeginDuration.count();
754
755 auto newEndDuration = std::chrono::duration_cast<std::chrono::milliseconds>(newEndTimePoint.time_since_epoch());
756 endDate = newEndDuration.count();
757 }
758
SetDoNotDisturbDate(const sptr<NotificationDoNotDisturbDate> & date)759 ErrCode AdvancedNotificationService::SetDoNotDisturbDate(const sptr<NotificationDoNotDisturbDate> &date)
760 {
761 ANS_LOGD("%{public}s", __FUNCTION__);
762
763 bool isSubsystem = AccessTokenHelper::VerifyNativeToken(IPCSkeleton::GetCallingTokenID());
764 if (!isSubsystem && !AccessTokenHelper::IsSystemApp()) {
765 ANS_LOGW("Not system app!");
766 return ERR_ANS_NON_SYSTEM_APP;
767 }
768
769 if (!AccessTokenHelper::CheckPermission(OHOS_PERMISSION_NOTIFICATION_CONTROLLER)) {
770 ANS_LOGW("Check permission denied!");
771 return ERR_ANS_PERMISSION_DENIED;
772 }
773
774 int32_t userId = SUBSCRIBE_USER_INIT;
775 if (!GetActiveUserId(userId)) {
776 ANS_LOGW("No active user found!");
777 return ERR_ANS_GET_ACTIVE_USER_FAILED;
778 }
779
780 return SetDoNotDisturbDateByUser(userId, date);
781 }
782
GetDoNotDisturbDate(sptr<NotificationDoNotDisturbDate> & date)783 ErrCode AdvancedNotificationService::GetDoNotDisturbDate(sptr<NotificationDoNotDisturbDate> &date)
784 {
785 ANS_LOGD("%{public}s", __FUNCTION__);
786
787 bool isSubsystem = AccessTokenHelper::VerifyNativeToken(IPCSkeleton::GetCallingTokenID());
788 if (!isSubsystem && !AccessTokenHelper::IsSystemApp()) {
789 return ERR_ANS_NON_SYSTEM_APP;
790 }
791
792 if (!AccessTokenHelper::CheckPermission(OHOS_PERMISSION_NOTIFICATION_CONTROLLER)) {
793 return ERR_ANS_PERMISSION_DENIED;
794 }
795
796 int32_t userId = SUBSCRIBE_USER_INIT;
797 if (!GetActiveUserId(userId)) {
798 return ERR_ANS_GET_ACTIVE_USER_FAILED;
799 }
800
801 return GetDoNotDisturbDateByUser(userId, date);
802 }
803
AddDoNotDisturbProfiles(const std::vector<sptr<NotificationDoNotDisturbProfile>> & profiles)804 ErrCode AdvancedNotificationService::AddDoNotDisturbProfiles(
805 const std::vector<sptr<NotificationDoNotDisturbProfile>> &profiles)
806 {
807 ANS_LOGD("Called.");
808 bool isSubsystem = AccessTokenHelper::VerifyNativeToken(IPCSkeleton::GetCallingTokenID());
809 if (!isSubsystem && !AccessTokenHelper::IsSystemApp()) {
810 return ERR_ANS_NON_SYSTEM_APP;
811 }
812 if (!AccessTokenHelper::CheckPermission(OHOS_PERMISSION_NOTIFICATION_CONTROLLER)) {
813 return ERR_ANS_PERMISSION_DENIED;
814 }
815 if (notificationSvrQueue_ == nullptr) {
816 ANS_LOGE("Serial queue is invalid.");
817 return ERR_ANS_INVALID_PARAM;
818 }
819 int32_t userId = SUBSCRIBE_USER_INIT;
820 if (!GetActiveUserId(userId)) {
821 ANS_LOGW("No active user found.");
822 return ERR_ANS_GET_ACTIVE_USER_FAILED;
823 }
824 ffrt::task_handle handler =
825 notificationSvrQueue_->submit_h(std::bind([copyUserId = userId, copyProfiles = profiles]() {
826 ANS_LOGD("The ffrt enter.");
827 NotificationPreferences::GetInstance()->AddDoNotDisturbProfiles(copyUserId, copyProfiles);
828 }));
829 notificationSvrQueue_->wait(handler);
830 return ERR_OK;
831 }
832
RemoveDoNotDisturbProfiles(const std::vector<sptr<NotificationDoNotDisturbProfile>> & profiles)833 ErrCode AdvancedNotificationService::RemoveDoNotDisturbProfiles(
834 const std::vector<sptr<NotificationDoNotDisturbProfile>> &profiles)
835 {
836 ANS_LOGD("Called.");
837 bool isSubsystem = AccessTokenHelper::VerifyNativeToken(IPCSkeleton::GetCallingTokenID());
838 if (!isSubsystem && !AccessTokenHelper::IsSystemApp()) {
839 return ERR_ANS_NON_SYSTEM_APP;
840 }
841 if (!AccessTokenHelper::CheckPermission(OHOS_PERMISSION_NOTIFICATION_CONTROLLER)) {
842 return ERR_ANS_PERMISSION_DENIED;
843 }
844 if (notificationSvrQueue_ == nullptr) {
845 ANS_LOGE("Serial queue is invalid.");
846 return ERR_ANS_INVALID_PARAM;
847 }
848 int32_t userId = SUBSCRIBE_USER_INIT;
849 if (!GetActiveUserId(userId)) {
850 ANS_LOGW("No active user found.");
851 return ERR_ANS_GET_ACTIVE_USER_FAILED;
852 }
853 ffrt::task_handle handler =
854 notificationSvrQueue_->submit_h(std::bind([copyUserId = userId, copyProfiles = profiles]() {
855 ANS_LOGD("The ffrt enter.");
856 NotificationPreferences::GetInstance()->RemoveDoNotDisturbProfiles(copyUserId, copyProfiles);
857 }));
858 notificationSvrQueue_->wait(handler);
859 return ERR_OK;
860 }
861
GetDoNotDisturbProfile(int32_t id,sptr<NotificationDoNotDisturbProfile> & profile)862 ErrCode AdvancedNotificationService::GetDoNotDisturbProfile(int32_t id, sptr<NotificationDoNotDisturbProfile> &profile)
863 {
864 ANS_LOGD("Called.");
865 bool isSubsystem = AccessTokenHelper::VerifyNativeToken(IPCSkeleton::GetCallingTokenID());
866 if (!isSubsystem && !AccessTokenHelper::IsSystemApp()) {
867 return ERR_ANS_NON_SYSTEM_APP;
868 }
869 if (!AccessTokenHelper::CheckPermission(OHOS_PERMISSION_NOTIFICATION_CONTROLLER)) {
870 return ERR_ANS_PERMISSION_DENIED;
871 }
872 int32_t userId = SUBSCRIBE_USER_INIT;
873 if (!GetActiveUserId(userId)) {
874 ANS_LOGW("No active user found.");
875 return ERR_ANS_GET_ACTIVE_USER_FAILED;
876 }
877
878 profile = new (std::nothrow) NotificationDoNotDisturbProfile();
879 ErrCode result = NotificationPreferences::GetInstance()->GetDoNotDisturbProfile(id, userId, profile);
880 if (result != ERR_OK) {
881 ANS_LOGE("profile failed id: %{public}d, userid: %{public}d", id, userId);
882 }
883 return result;
884 }
885
DoesSupportDoNotDisturbMode(bool & doesSupport)886 ErrCode AdvancedNotificationService::DoesSupportDoNotDisturbMode(bool &doesSupport)
887 {
888 ANS_LOGD("%{public}s", __FUNCTION__);
889
890 bool isSubsystem = AccessTokenHelper::VerifyNativeToken(IPCSkeleton::GetCallingTokenID());
891 if (!isSubsystem && !AccessTokenHelper::IsSystemApp()) {
892 return ERR_ANS_NON_SYSTEM_APP;
893 }
894
895 if (!AccessTokenHelper::CheckPermission(OHOS_PERMISSION_NOTIFICATION_CONTROLLER)) {
896 return ERR_ANS_PERMISSION_DENIED;
897 }
898
899 doesSupport = SUPPORT_DO_NOT_DISTRUB;
900 return ERR_OK;
901 }
902
903 #ifdef DISTRIBUTED_NOTIFICATION_SUPPORTED
OnDistributedPublish(const std::string & deviceId,const std::string & bundleName,sptr<NotificationRequest> & request)904 void AdvancedNotificationService::OnDistributedPublish(
905 const std::string &deviceId, const std::string &bundleName, sptr<NotificationRequest> &request)
906 {
907 ANS_LOGD("%{public}s", __FUNCTION__);
908 int32_t activeUserId = -1;
909 if (!GetActiveUserId(activeUserId)) {
910 ANS_LOGE("Failed to get active user id!");
911 return;
912 }
913
914 if (notificationSvrQueue_ == nullptr) {
915 ANS_LOGE("notificationSvrQueue_ is nullptr.");
916 return;
917 }
918 notificationSvrQueue_->submit(std::bind([this, deviceId, bundleName, request, activeUserId]() {
919 ANS_LOGD("ffrt enter!");
920 if (!CheckDistributedNotificationType(request)) {
921 ANS_LOGD("CheckDistributedNotificationType is false.");
922 return;
923 }
924
925 int32_t uid = BundleManagerHelper::GetInstance()->GetDefaultUidByBundleName(bundleName, activeUserId);
926 if (uid <= 0) {
927 if (CheckPublishWithoutApp(activeUserId, request)) {
928 request->SetOwnerBundleName(FOUNDATION_BUNDLE_NAME);
929 request->SetCreatorBundleName(FOUNDATION_BUNDLE_NAME);
930 } else {
931 ANS_LOGE("bundle does not exit and make off!");
932 return;
933 }
934 }
935 std::string bundle = request->GetOwnerBundleName();
936 request->SetCreatorUid(BundleManagerHelper::GetInstance()->GetDefaultUidByBundleName(bundle, activeUserId));
937 sptr<NotificationBundleOption> bundleOption =
938 GenerateValidBundleOption(new NotificationBundleOption(bundle, 0));
939
940 std::shared_ptr<NotificationRecord> record = std::make_shared<NotificationRecord>();
941 if (record == nullptr) {
942 ANS_LOGD("record is nullptr.");
943 return;
944 }
945 record->request = request;
946 record->notification = new (std::nothrow) Notification(deviceId, request);
947 if (record->notification == nullptr) {
948 ANS_LOGE("Failed to create Notification instance");
949 return;
950 }
951 record->bundleOption = bundleOption;
952 record->deviceId = deviceId;
953 record->bundleName = bundleName;
954 SetNotificationRemindType(record->notification, false);
955
956 ErrCode result = AssignValidNotificationSlot(record, bundleOption);
957 if (result != ERR_OK) {
958 ANS_LOGE("Can not assign valid slot!");
959 return;
960 }
961
962 result = Filter(record);
963 if (result != ERR_OK) {
964 ANS_LOGE("Reject by filters: %{public}d", result);
965 return;
966 }
967
968 result = PublishFlowControl(record);
969 if (result != ERR_OK) {
970 return;
971 }
972
973 UpdateRecentNotification(record->notification, false, 0);
974 sptr<NotificationSortingMap> sortingMap = GenerateSortingMap();
975 NotificationSubscriberManager::GetInstance()->NotifyConsumed(record->notification, sortingMap);
976 }));
977 }
978
OnDistributedUpdate(const std::string & deviceId,const std::string & bundleName,sptr<NotificationRequest> & request)979 void AdvancedNotificationService::OnDistributedUpdate(
980 const std::string &deviceId, const std::string &bundleName, sptr<NotificationRequest> &request)
981 {
982 ANS_LOGD("%{public}s", __FUNCTION__);
983 int32_t activeUserId = -1;
984 if (!GetActiveUserId(activeUserId)) {
985 ANS_LOGE("Failed to get active user id!");
986 return;
987 }
988
989 if (notificationSvrQueue_ == nullptr) {
990 ANS_LOGE("Serial queue is invalid.");
991 return;
992 }
993 notificationSvrQueue_->submit(std::bind([this, deviceId, bundleName, request, activeUserId]() {
994 ANS_LOGD("ffrt enter!");
995 if (!CheckDistributedNotificationType(request)) {
996 ANS_LOGD("device type not support display.");
997 return;
998 }
999
1000 int32_t uid = BundleManagerHelper::GetInstance()->GetDefaultUidByBundleName(bundleName, activeUserId);
1001 if (uid <= 0) {
1002 if (CheckPublishWithoutApp(activeUserId, request)) {
1003 request->SetOwnerBundleName(FOUNDATION_BUNDLE_NAME);
1004 request->SetCreatorBundleName(FOUNDATION_BUNDLE_NAME);
1005 } else {
1006 ANS_LOGE("bundle does not exit and enable off!");
1007 return;
1008 }
1009 }
1010 std::string bundle = request->GetOwnerBundleName();
1011 request->SetCreatorUid(BundleManagerHelper::GetInstance()->GetDefaultUidByBundleName(bundle, activeUserId));
1012 sptr<NotificationBundleOption> bundleOption =
1013 GenerateValidBundleOption(new NotificationBundleOption(bundle, 0));
1014
1015 std::shared_ptr<NotificationRecord> record = std::make_shared<NotificationRecord>();
1016 if (record == nullptr) {
1017 return;
1018 }
1019 record->request = request;
1020 record->notification = new (std::nothrow) Notification(deviceId, request);
1021 if (record->notification == nullptr) {
1022 ANS_LOGE("Failed to create Notification instance");
1023 return;
1024 }
1025 record->bundleOption = bundleOption;
1026 record->deviceId = deviceId;
1027 record->bundleName = bundleName;
1028 SetNotificationRemindType(record->notification, false);
1029
1030 ErrCode result = AssignValidNotificationSlot(record, bundleOption);
1031 if (result != ERR_OK) {
1032 ANS_LOGE("Can not assign valid slot!");
1033 return;
1034 }
1035
1036 result = Filter(record);
1037 if (result != ERR_OK) {
1038 ANS_LOGE("Reject by filters: %{public}d", result);
1039 return;
1040 }
1041
1042 if (IsNotificationExists(record->notification->GetKey())) {
1043 if (record->request->IsAlertOneTime()) {
1044 CloseAlert(record);
1045 }
1046 UpdateInNotificationList(record);
1047 }
1048
1049 UpdateRecentNotification(record->notification, false, 0);
1050 sptr<NotificationSortingMap> sortingMap = GenerateSortingMap();
1051 NotificationSubscriberManager::GetInstance()->NotifyConsumed(record->notification, sortingMap);
1052 }));
1053 }
1054
OnDistributedDelete(const std::string & deviceId,const std::string & bundleName,const std::string & label,int32_t id)1055 void AdvancedNotificationService::OnDistributedDelete(
1056 const std::string &deviceId, const std::string &bundleName, const std::string &label, int32_t id)
1057 {
1058 ANS_LOGD("%{public}s", __FUNCTION__);
1059 if (notificationSvrQueue_ == nullptr) {
1060 ANS_LOGE("Serial queue is invalid.");
1061 return;
1062 }
1063 notificationSvrQueue_->submit(std::bind([this, deviceId, bundleName, label, id]() {
1064 ANS_LOGD("ffrt enter!");
1065 int32_t activeUserId = -1;
1066 if (!GetActiveUserId(activeUserId)) {
1067 ANS_LOGE("Failed to get active user id!");
1068 return;
1069 }
1070 int32_t uid = BundleManagerHelper::GetInstance()->GetDefaultUidByBundleName(bundleName, activeUserId);
1071 std::string bundle = (uid > 0) ? bundleName : FOUNDATION_BUNDLE_NAME;
1072 sptr<NotificationBundleOption> bundleOption =
1073 GenerateValidBundleOption(new NotificationBundleOption(bundle, 0));
1074
1075 std::string recordDeviceId;
1076 DistributedDatabase::DeviceInfo localDeviceInfo;
1077 if (DistributedNotificationManager::GetInstance()->GetLocalDeviceInfo(localDeviceInfo) == ERR_OK &&
1078 strcmp(deviceId.c_str(), localDeviceInfo.deviceId) == 0) {
1079 recordDeviceId = "";
1080 } else {
1081 recordDeviceId = deviceId;
1082 }
1083
1084 if (bundleOption == nullptr) {
1085 ANS_LOGE("Failed to get bundleOption!");
1086 return;
1087 }
1088
1089 sptr<Notification> notification = nullptr;
1090 for (auto record : notificationList_) {
1091 if ((record->deviceId == recordDeviceId) &&
1092 ((record->bundleOption->GetBundleName() == bundleOption->GetBundleName()) ||
1093 (record->bundleName == bundleName)) &&
1094 (record->bundleOption->GetUid() == bundleOption->GetUid()) &&
1095 (record->notification->GetLabel() == label) && (record->notification->GetId() == id)) {
1096 notification = record->notification;
1097 notificationList_.remove(record);
1098 break;
1099 }
1100 }
1101
1102 if (notification != nullptr) {
1103 int32_t reason = NotificationConstant::APP_CANCEL_REASON_OTHER;
1104 UpdateRecentNotification(notification, true, reason);
1105 CancelTimer(notification->GetAutoDeletedTimer());
1106 NotificationSubscriberManager::GetInstance()->NotifyCanceled(notification, nullptr, reason);
1107 }
1108 }));
1109 }
1110
GetDistributedEnableInApplicationInfo(const sptr<NotificationBundleOption> bundleOption,bool & enable)1111 ErrCode AdvancedNotificationService::GetDistributedEnableInApplicationInfo(
1112 const sptr<NotificationBundleOption> bundleOption, bool &enable)
1113 {
1114 int32_t userId = SUBSCRIBE_USER_INIT;
1115 OHOS::AccountSA::OsAccountManager::GetOsAccountLocalIdFromUid(bundleOption->GetUid(), userId);
1116
1117 if (userId >= SUBSCRIBE_USER_SYSTEM_BEGIN && userId <= SUBSCRIBE_USER_SYSTEM_END) {
1118 enable = true;
1119 } else {
1120 enable = BundleManagerHelper::GetInstance()->GetDistributedNotificationEnabled(
1121 bundleOption->GetBundleName(), userId);
1122 }
1123
1124 return ERR_OK;
1125 }
1126
CheckDistributedNotificationType(const sptr<NotificationRequest> & request)1127 bool AdvancedNotificationService::CheckDistributedNotificationType(const sptr<NotificationRequest> &request)
1128 {
1129 auto deviceTypeList = request->GetNotificationDistributedOptions().GetDevicesSupportDisplay();
1130 if (deviceTypeList.empty()) {
1131 return true;
1132 }
1133
1134 DistributedDatabase::DeviceInfo localDeviceInfo;
1135 DistributedNotificationManager::GetInstance()->GetLocalDeviceInfo(localDeviceInfo);
1136 for (auto device : deviceTypeList) {
1137 if (atoi(device.c_str()) == localDeviceInfo.deviceTypeId) {
1138 return true;
1139 }
1140 }
1141 return false;
1142 }
1143
CheckPublishWithoutApp(const int32_t userId,const sptr<NotificationRequest> & request)1144 bool AdvancedNotificationService::CheckPublishWithoutApp(const int32_t userId, const sptr<NotificationRequest> &request)
1145 {
1146 bool enabled = false;
1147 DistributedPreferences::GetInstance()->GetSyncEnabledWithoutApp(userId, enabled);
1148 if (!enabled) {
1149 ANS_LOGE("enable is false, userId[%{public}d]", userId);
1150 return false;
1151 }
1152
1153 std::shared_ptr<AbilityRuntime::WantAgent::WantAgent> wantAgent = request->GetWantAgent();
1154 if (!wantAgent) {
1155 ANS_LOGE("Failed to get wantAgent!");
1156 return false;
1157 }
1158
1159 std::shared_ptr<AAFwk::Want> want = AbilityRuntime::WantAgent::WantAgentHelper::GetWant(wantAgent);
1160 if (!want || want->GetDeviceId().empty()) {
1161 ANS_LOGE("Failed to get want!");
1162 return false;
1163 }
1164
1165 return true;
1166 }
1167
GetLocalNotificationKeys(const sptr<NotificationBundleOption> & bundleOption)1168 std::vector<std::string> AdvancedNotificationService::GetLocalNotificationKeys(
1169 const sptr<NotificationBundleOption> &bundleOption)
1170 {
1171 std::vector<std::string> keys;
1172
1173 for (auto record : notificationList_) {
1174 if ((bundleOption != nullptr) &&
1175 ((record->bundleOption->GetBundleName() != bundleOption->GetBundleName()) ||
1176 (record->bundleOption->GetUid() != bundleOption->GetUid())) &&
1177 record->deviceId.empty()) {
1178 continue;
1179 }
1180 keys.push_back(record->notification->GetKey());
1181 }
1182
1183 return keys;
1184 }
1185
GetDistributedInfo(const std::string & key,std::string & deviceId,std::string & bundleName)1186 void AdvancedNotificationService::GetDistributedInfo(
1187 const std::string &key, std::string &deviceId, std::string &bundleName)
1188 {
1189 for (auto record : notificationList_) {
1190 if (record->notification->GetKey() == key) {
1191 deviceId = record->deviceId;
1192 bundleName = record->bundleName;
1193 break;
1194 }
1195 }
1196 }
1197
DoDistributedPublish(const sptr<NotificationBundleOption> bundleOption,const std::shared_ptr<NotificationRecord> record)1198 ErrCode AdvancedNotificationService::DoDistributedPublish(
1199 const sptr<NotificationBundleOption> bundleOption, const std::shared_ptr<NotificationRecord> record)
1200 {
1201 bool appInfoEnable = true;
1202 GetDistributedEnableInApplicationInfo(bundleOption, appInfoEnable);
1203 if (!appInfoEnable) {
1204 return ERR_OK;
1205 }
1206
1207 if (!record->request->GetNotificationDistributedOptions().IsDistributed()) {
1208 return ERR_OK;
1209 }
1210
1211 ErrCode result;
1212 bool distributedEnable = false;
1213 result = DistributedPreferences::GetInstance()->GetDistributedEnable(distributedEnable);
1214 if (result != ERR_OK || !distributedEnable) {
1215 return result;
1216 }
1217
1218 bool bundleDistributedEnable = false;
1219 result = DistributedPreferences::GetInstance()->GetDistributedBundleEnable(bundleOption, bundleDistributedEnable);
1220 if (result != ERR_OK || !bundleDistributedEnable) {
1221 return result;
1222 }
1223
1224 return DistributedNotificationManager::GetInstance()->Publish(record->notification->GetBundleName(),
1225 record->notification->GetLabel(),
1226 record->notification->GetId(),
1227 record->request);
1228 }
1229
DoDistributedDelete(const std::string deviceId,const std::string bundleName,const sptr<Notification> notification)1230 ErrCode AdvancedNotificationService::DoDistributedDelete(
1231 const std::string deviceId, const std::string bundleName, const sptr<Notification> notification)
1232 {
1233 HITRACE_METER_NAME(HITRACE_TAG_NOTIFICATION, __PRETTY_FUNCTION__);
1234 if (!notification->GetNotificationRequestPoint()->GetNotificationDistributedOptions().IsDistributed()) {
1235 return ERR_OK;
1236 }
1237 if (deviceId.empty()) {
1238 return DistributedNotificationManager::GetInstance()->Delete(
1239 notification->GetBundleName(), notification->GetLabel(), notification->GetId());
1240 } else {
1241 return DistributedNotificationManager::GetInstance()->DeleteRemoteNotification(
1242 deviceId, bundleName, notification->GetLabel(), notification->GetId());
1243 }
1244
1245 return ERR_OK;
1246 }
1247 #endif
1248
PrepareContinuousTaskNotificationRequest(const sptr<NotificationRequest> & request,const int32_t & uid)1249 ErrCode AdvancedNotificationService::PrepareContinuousTaskNotificationRequest(
1250 const sptr<NotificationRequest> &request, const int32_t &uid)
1251 {
1252 int32_t pid = IPCSkeleton::GetCallingPid();
1253 request->SetCreatorUid(uid);
1254 request->SetCreatorPid(pid);
1255 if (request->GetDeliveryTime() <= 0) {
1256 request->SetDeliveryTime(GetCurrentTime());
1257 }
1258
1259 ErrCode result = CheckPictureSize(request);
1260 return result;
1261 }
1262
IsSupportTemplate(const std::string & templateName,bool & support)1263 ErrCode AdvancedNotificationService::IsSupportTemplate(const std::string& templateName, bool &support)
1264 {
1265 ANS_LOGD("%{public}s", __FUNCTION__);
1266 if (notificationSvrQueue_ == nullptr) {
1267 ANS_LOGE("Serial queue is invalid.");
1268 return ERR_ANS_INVALID_PARAM;
1269 }
1270 ErrCode result = ERR_OK;
1271 ffrt::task_handle handler = notificationSvrQueue_->submit_h(std::bind([&]() {
1272 ANS_LOGD("ffrt enter!");
1273 support = false;
1274 result = NotificationPreferences::GetInstance()->GetTemplateSupported(templateName, support);
1275 }));
1276 notificationSvrQueue_->wait(handler);
1277 return result;
1278 }
1279
GetActiveUserId(int & userId)1280 bool AdvancedNotificationService::GetActiveUserId(int& userId)
1281 {
1282 std::vector<int> activeUserId;
1283 OHOS::AccountSA::OsAccountManager::QueryActiveOsAccountIds(activeUserId);
1284 if (activeUserId.size() > 0) {
1285 userId = activeUserId[0];
1286 ANS_LOGD("Return active userId=%{public}d", userId);
1287 return true;
1288 }
1289 return false;
1290 }
1291
TriggerRemoveWantAgent(const sptr<NotificationRequest> & request)1292 void AdvancedNotificationService::TriggerRemoveWantAgent(const sptr<NotificationRequest> &request)
1293 {
1294 HITRACE_METER_NAME(HITRACE_TAG_NOTIFICATION, __PRETTY_FUNCTION__);
1295 ANS_LOGD("%{public}s", __FUNCTION__);
1296
1297 if ((request == nullptr) || (request->GetRemovalWantAgent() == nullptr)) {
1298 return;
1299 }
1300 OHOS::AbilityRuntime::WantAgent::TriggerInfo triggerInfo;
1301 std::shared_ptr<AbilityRuntime::WantAgent::WantAgent> agent = request->GetRemovalWantAgent();
1302 AbilityRuntime::WantAgent::WantAgentHelper::TriggerWantAgent(agent, nullptr, triggerInfo);
1303 }
1304
OnResourceRemove(int32_t userId)1305 void AdvancedNotificationService::OnResourceRemove(int32_t userId)
1306 {
1307 OnUserRemoved(userId);
1308
1309 if (notificationSvrQueue_ == nullptr) {
1310 ANS_LOGE("Serial queue is invalid.");
1311 return;
1312 }
1313 ffrt::task_handle handler = notificationSvrQueue_->submit_h(std::bind([=]() {
1314 ANS_LOGD("ffrt enter!");
1315 NotificationPreferences::GetInstance()->RemoveSettings(userId);
1316 }));
1317 }
1318
OnBundleDataCleared(const sptr<NotificationBundleOption> & bundleOption)1319 void AdvancedNotificationService::OnBundleDataCleared(const sptr<NotificationBundleOption> &bundleOption)
1320 {
1321 if (notificationSvrQueue_ == nullptr) {
1322 ANS_LOGE("Serial queue is invalid.");
1323 return;
1324 }
1325 ffrt::task_handle handler = notificationSvrQueue_->submit_h(std::bind([=]() {
1326 ANS_LOGD("ffrt enter!");
1327 std::vector<std::string> keys = GetNotificationKeys(bundleOption);
1328 std::vector<sptr<Notification>> notifications;
1329 std::vector<uint64_t> timerIds;
1330 for (auto key : keys) {
1331 #ifdef DISTRIBUTED_NOTIFICATION_SUPPORTED
1332 std::string deviceId;
1333 std::string bundleName;
1334 GetDistributedInfo(key, deviceId, bundleName);
1335 #endif
1336 sptr<Notification> notification = nullptr;
1337
1338 ErrCode result = RemoveFromNotificationList(key, notification, true,
1339 NotificationConstant::PACKAGE_CHANGED_REASON_DELETE);
1340 if (result != ERR_OK) {
1341 continue;
1342 }
1343
1344 if (notification != nullptr) {
1345 int32_t reason = NotificationConstant::PACKAGE_CHANGED_REASON_DELETE;
1346 UpdateRecentNotification(notification, true, reason);
1347 notifications.emplace_back(notification);
1348 timerIds.emplace_back(notification->GetAutoDeletedTimer());
1349 #ifdef DISTRIBUTED_NOTIFICATION_SUPPORTED
1350 DoDistributedDelete(deviceId, bundleName, notification);
1351 #endif
1352 }
1353 if (notifications.size() >= MAX_CANCELED_PARCELABLE_VECTOR_NUM) {
1354 std::vector<sptr<Notification>> currNotificationList = notifications;
1355 NotificationSubscriberManager::GetInstance()->BatchNotifyCanceled(
1356 currNotificationList, nullptr, NotificationConstant::PACKAGE_CHANGED_REASON_DELETE);
1357 notifications.clear();
1358 }
1359 }
1360
1361 if (!notifications.empty()) {
1362 NotificationSubscriberManager::GetInstance()->BatchNotifyCanceled(
1363 notifications, nullptr, NotificationConstant::PACKAGE_CHANGED_REASON_DELETE);
1364 }
1365 BatchCancelTimer(timerIds);
1366 }));
1367 }
1368
CheckApiCompatibility(const sptr<NotificationBundleOption> & bundleOption)1369 bool AdvancedNotificationService::CheckApiCompatibility(const sptr<NotificationBundleOption> &bundleOption)
1370 {
1371 #ifdef ANS_ENABLE_FA_MODEL
1372 ANS_LOGD("%{public}s", __FUNCTION__);
1373 std::shared_ptr<BundleManagerHelper> bundleManager = BundleManagerHelper::GetInstance();
1374 if (bundleManager == nullptr) {
1375 return false;
1376 }
1377 return bundleManager->CheckApiCompatibility(bundleOption);
1378 #else
1379 return false;
1380 #endif
1381 }
1382
OnUserRemoved(const int32_t & userId)1383 void AdvancedNotificationService::OnUserRemoved(const int32_t &userId)
1384 {
1385 DeleteAllByUserInner(userId, NotificationConstant::USER_REMOVED_REASON_DELETE, true);
1386 }
1387
DeleteAllByUser(const int32_t & userId)1388 ErrCode AdvancedNotificationService::DeleteAllByUser(const int32_t &userId)
1389 {
1390 return DeleteAllByUserInner(userId, NotificationConstant::APP_REMOVE_ALL_USER_REASON_DELETE);
1391 }
1392
DeleteAllByUserInner(const int32_t & userId,int32_t deleteReason,bool isAsync)1393 ErrCode AdvancedNotificationService::DeleteAllByUserInner(const int32_t &userId, int32_t deleteReason,
1394 bool isAsync)
1395 {
1396 ANS_LOGD("%{public}s", __FUNCTION__);
1397
1398 bool isSubsystem = AccessTokenHelper::VerifyNativeToken(IPCSkeleton::GetCallingTokenID());
1399 if (!isSubsystem && !AccessTokenHelper::IsSystemApp()) {
1400 std::string message = "not system app.";
1401 OHOS::Notification::HaMetaMessage haMetaMessage = HaMetaMessage(6, 5)
1402 .ErrorCode(ERR_ANS_NON_SYSTEM_APP);
1403 ReportDeleteFailedEventPush(haMetaMessage, deleteReason, message);
1404 ANS_LOGE("%{public}s", message.c_str());
1405 return ERR_ANS_NON_SYSTEM_APP;
1406 }
1407
1408 if (userId <= SUBSCRIBE_USER_INIT) {
1409 std::string message = "userId is error.";
1410 OHOS::Notification::HaMetaMessage haMetaMessage = HaMetaMessage(6, 6)
1411 .ErrorCode(ERR_ANS_INVALID_PARAM);
1412 ReportDeleteFailedEventPush(haMetaMessage, deleteReason, message);
1413 ANS_LOGE("%{public}s", message.c_str());
1414 return ERR_ANS_INVALID_PARAM;
1415 }
1416
1417 if (notificationSvrQueue_ == nullptr) {
1418 std::string message = "Serial queue is invalid.";
1419 ANS_LOGE("%{public}s", message.c_str());
1420 return ERR_ANS_INVALID_PARAM;
1421 }
1422 std::shared_ptr<ErrCode> result = std::make_shared<ErrCode>(ERR_OK);
1423 ffrt::task_handle handler = notificationSvrQueue_->submit_h(std::bind([=]() {
1424 ANS_LOGD("ffrt enter!");
1425 std::vector<std::string> keys = GetNotificationKeys(nullptr);
1426 std::vector<sptr<Notification>> notifications;
1427 std::vector<uint64_t> timerIds;
1428 for (auto key : keys) {
1429 #ifdef DISTRIBUTED_NOTIFICATION_SUPPORTED
1430 std::string deviceId;
1431 std::string bundleName;
1432 GetDistributedInfo(key, deviceId, bundleName);
1433 #endif
1434 sptr<Notification> notification = nullptr;
1435
1436 *result = RemoveFromNotificationListForDeleteAll(key, userId, notification);
1437 if ((*result != ERR_OK) || (notification == nullptr)) {
1438 continue;
1439 }
1440
1441 if (notification->GetUserId() == userId) {
1442 UpdateRecentNotification(notification, true, deleteReason);
1443 notifications.emplace_back(notification);
1444 timerIds.emplace_back(notification->GetAutoDeletedTimer());
1445 #ifdef DISTRIBUTED_NOTIFICATION_SUPPORTED
1446 DoDistributedDelete(deviceId, bundleName, notification);
1447 #endif
1448 }
1449 if (notifications.size() >= MAX_CANCELED_PARCELABLE_VECTOR_NUM) {
1450 SendNotificationsOnCanceled(notifications, nullptr, deleteReason);
1451 }
1452 }
1453
1454 if (!notifications.empty()) {
1455 NotificationSubscriberManager::GetInstance()->BatchNotifyCanceled(
1456 notifications, nullptr, deleteReason);
1457 }
1458 BatchCancelTimer(timerIds);
1459 *result = ERR_OK;
1460 }));
1461
1462 if (!isAsync) {
1463 notificationSvrQueue_->wait(handler);
1464 return *result;
1465 }
1466 return ERR_OK;
1467 }
1468
ShellDump(const std::string & cmd,const std::string & bundle,int32_t userId,int32_t recvUserId,std::vector<std::string> & dumpInfo)1469 ErrCode AdvancedNotificationService::ShellDump(const std::string &cmd, const std::string &bundle, int32_t userId,
1470 int32_t recvUserId, std::vector<std::string> &dumpInfo)
1471 {
1472 ANS_LOGD("%{public}s", __FUNCTION__);
1473
1474 auto callerToken = IPCSkeleton::GetCallingTokenID();
1475 if (!AccessTokenHelper::VerifyShellToken(callerToken) && !AccessTokenHelper::VerifyNativeToken(callerToken)) {
1476 ANS_LOGE("Not subsystem or shell request");
1477 return ERR_ANS_PERMISSION_DENIED;
1478 }
1479
1480 if (notificationSvrQueue_ == nullptr) {
1481 ANS_LOGE("Serial queue is invalid.");
1482 return ERR_ANS_INVALID_PARAM;
1483 }
1484 ErrCode result = ERR_ANS_NOT_ALLOWED;
1485 ffrt::task_handle handler = notificationSvrQueue_->submit_h(std::bind([&]() {
1486 ANS_LOGD("ffrt enter!");
1487 if (cmd == ACTIVE_NOTIFICATION_OPTION) {
1488 result = ActiveNotificationDump(bundle, userId, recvUserId, dumpInfo);
1489 } else if (cmd == RECENT_NOTIFICATION_OPTION) {
1490 result = RecentNotificationDump(bundle, userId, recvUserId, dumpInfo);
1491 #ifdef DISTRIBUTED_NOTIFICATION_SUPPORTED
1492 } else if (cmd == DISTRIBUTED_NOTIFICATION_OPTION) {
1493 result = DistributedNotificationDump(bundle, userId, recvUserId, dumpInfo);
1494 #endif
1495 } else if (cmd.substr(0, cmd.find_first_of(" ", 0)) == SET_RECENT_COUNT_OPTION) {
1496 result = SetRecentNotificationCount(cmd.substr(cmd.find_first_of(" ", 0) + 1));
1497 } else {
1498 result = ERR_ANS_INVALID_PARAM;
1499 }
1500 }));
1501 notificationSvrQueue_->wait(handler);
1502 return result;
1503 }
1504
Dump(int fd,const std::vector<std::u16string> & args)1505 int AdvancedNotificationService::Dump(int fd, const std::vector<std::u16string> &args)
1506 {
1507 ANS_LOGD("enter");
1508 std::string result;
1509 GetDumpInfo(args, result);
1510 int ret = dprintf(fd, "%s\n", result.c_str());
1511 if (ret < 0) {
1512 ANS_LOGE("dprintf error");
1513 return ERR_ANS_INVALID_PARAM;
1514 }
1515 return ERR_OK;
1516 }
1517
GetDumpInfo(const std::vector<std::u16string> & args,std::string & result)1518 void AdvancedNotificationService::GetDumpInfo(const std::vector<std::u16string> &args, std::string &result)
1519 {
1520 if (args.size() != 1) {
1521 result = HIDUMPER_ERR_MSG;
1522 return;
1523 }
1524 std::vector<std::string> dumpInfo;
1525 std::string cmd = Str16ToStr8(args.front());
1526 if (HIDUMPER_CMD_MAP.find(cmd) == HIDUMPER_CMD_MAP.end()) {
1527 result = HIDUMPER_ERR_MSG;
1528 return;
1529 }
1530 std::string cmdValue = HIDUMPER_CMD_MAP.find(cmd)->second;
1531 if (cmdValue == HELP_NOTIFICATION_OPTION) {
1532 result = HIDUMPER_HELP_MSG;
1533 }
1534 ShellDump(cmdValue, "", SUBSCRIBE_USER_INIT, SUBSCRIBE_USER_INIT, dumpInfo);
1535 if (dumpInfo.empty()) {
1536 result.append("no notification\n");
1537 return;
1538 }
1539 int32_t index = 0;
1540 result.append("notification list:\n");
1541 for (const auto &info: dumpInfo) {
1542 result.append("No." + std::to_string(++index) + "\n");
1543 result.append(info);
1544 }
1545 }
1546
SetDoNotDisturbDateByUser(const int32_t & userId,const sptr<NotificationDoNotDisturbDate> & date)1547 ErrCode AdvancedNotificationService::SetDoNotDisturbDateByUser(const int32_t &userId,
1548 const sptr<NotificationDoNotDisturbDate> &date)
1549 {
1550 ANS_LOGD("%{public}s enter, userId = %{public}d", __FUNCTION__, userId);
1551 if (date == nullptr) {
1552 ANS_LOGE("Invalid date param");
1553 return ERR_ANS_INVALID_PARAM;
1554 }
1555
1556 ErrCode result = ERR_OK;
1557
1558 int64_t beginDate = ResetSeconds(date->GetBeginDate());
1559 int64_t endDate = ResetSeconds(date->GetEndDate());
1560 switch (date->GetDoNotDisturbType()) {
1561 case NotificationConstant::DoNotDisturbType::NONE:
1562 beginDate = 0;
1563 endDate = 0;
1564 break;
1565 case NotificationConstant::DoNotDisturbType::ONCE:
1566 AdjustDateForDndTypeOnce(beginDate, endDate);
1567 break;
1568 case NotificationConstant::DoNotDisturbType::CLEARLY:
1569 if (beginDate >= endDate) {
1570 return ERR_ANS_INVALID_PARAM;
1571 }
1572 break;
1573 default:
1574 break;
1575 }
1576 ANS_LOGD("Before set SetDoNotDisturbDate beginDate = %{public}" PRId64 ", endDate = %{public}" PRId64,
1577 beginDate, endDate);
1578 const sptr<NotificationDoNotDisturbDate> newConfig = new (std::nothrow) NotificationDoNotDisturbDate(
1579 date->GetDoNotDisturbType(),
1580 beginDate,
1581 endDate
1582 );
1583 if (newConfig == nullptr) {
1584 ANS_LOGE("Failed to create NotificationDoNotDisturbDate instance");
1585 return ERR_NO_MEMORY;
1586 }
1587
1588 sptr<NotificationBundleOption> bundleOption = GenerateBundleOption();
1589 if (bundleOption == nullptr) {
1590 ANS_LOGE("Generate invalid bundle option!");
1591 return ERR_ANS_INVALID_BUNDLE;
1592 }
1593
1594 if (notificationSvrQueue_ == nullptr) {
1595 ANS_LOGE("Serial queue is invalid.");
1596 return ERR_ANS_INVALID_PARAM;
1597 }
1598 ffrt::task_handle handler = notificationSvrQueue_->submit_h(std::bind([&]() {
1599 ANS_LOGD("ffrt enter!");
1600 result = NotificationPreferences::GetInstance()->SetDoNotDisturbDate(userId, newConfig);
1601 if (result == ERR_OK) {
1602 NotificationSubscriberManager::GetInstance()->NotifyDoNotDisturbDateChanged(userId, newConfig);
1603 }
1604 }));
1605 notificationSvrQueue_->wait(handler);
1606
1607 return ERR_OK;
1608 }
1609
GetDoNotDisturbDateByUser(const int32_t & userId,sptr<NotificationDoNotDisturbDate> & date)1610 ErrCode AdvancedNotificationService::GetDoNotDisturbDateByUser(const int32_t &userId,
1611 sptr<NotificationDoNotDisturbDate> &date)
1612 {
1613 ErrCode result = ERR_OK;
1614 if (notificationSvrQueue_ == nullptr) {
1615 ANS_LOGE("Serial queue is invalid.");
1616 return ERR_ANS_INVALID_PARAM;
1617 }
1618 ffrt::task_handle handler = notificationSvrQueue_->submit_h(std::bind([&]() {
1619 ANS_LOGD("ffrt enter!");
1620 sptr<NotificationDoNotDisturbDate> currentConfig = nullptr;
1621 result = NotificationPreferences::GetInstance()->GetDoNotDisturbDate(userId, currentConfig);
1622 if (result == ERR_OK) {
1623 int64_t now = GetCurrentTime();
1624 switch (currentConfig->GetDoNotDisturbType()) {
1625 case NotificationConstant::DoNotDisturbType::CLEARLY:
1626 case NotificationConstant::DoNotDisturbType::ONCE:
1627 if (now >= currentConfig->GetEndDate()) {
1628 date = new (std::nothrow) NotificationDoNotDisturbDate(
1629 NotificationConstant::DoNotDisturbType::NONE, 0, 0);
1630 if (date == nullptr) {
1631 ANS_LOGE("Failed to create NotificationDoNotDisturbDate instance");
1632 return;
1633 }
1634 NotificationPreferences::GetInstance()->SetDoNotDisturbDate(userId, date);
1635 } else {
1636 date = currentConfig;
1637 }
1638 break;
1639 default:
1640 date = currentConfig;
1641 break;
1642 }
1643 }
1644 }));
1645 notificationSvrQueue_->wait(handler);
1646
1647 return ERR_OK;
1648 }
1649
SetRequestBundleInfo(const sptr<NotificationRequest> & request,int32_t uid,std::string & bundle)1650 ErrCode AdvancedNotificationService::SetRequestBundleInfo(const sptr<NotificationRequest> &request,
1651 int32_t uid, std::string &bundle)
1652 {
1653 if (!bundle.empty()) {
1654 if (request->GetCreatorBundleName().empty()) {
1655 request->SetCreatorBundleName(bundle);
1656 }
1657 if (request->GetOwnerBundleName().empty()) {
1658 request->SetOwnerBundleName(bundle);
1659 }
1660 } else {
1661 if (!request->GetCreatorBundleName().empty()) {
1662 bundle = request->GetCreatorBundleName();
1663 }
1664 if (!request->GetOwnerBundleName().empty()) {
1665 bundle = request->GetOwnerBundleName();
1666 }
1667 }
1668 return ERR_OK;
1669 }
1670
PrePublishNotificationBySa(const sptr<NotificationRequest> & request,int32_t uid,std::string & bundle)1671 ErrCode AdvancedNotificationService::PrePublishNotificationBySa(const sptr<NotificationRequest> &request,
1672 int32_t uid, std::string &bundle)
1673 {
1674 HaMetaMessage message = HaMetaMessage(EventSceneId::SCENE_4, EventBranchId::BRANCH_2);
1675 std::shared_ptr<BundleManagerHelper> bundleManager = BundleManagerHelper::GetInstance();
1676 if (bundleManager == nullptr) {
1677 ANS_LOGE("failed to get bundleManager!");
1678 return ERR_ANS_INVALID_BUNDLE;
1679 }
1680 bundle = bundleManager->GetBundleNameByUid(uid);
1681 ErrCode result = SetRequestBundleInfo(request, uid, bundle);
1682 if (result != ERR_OK) {
1683 message.ErrorCode(result);
1684 NotificationAnalyticsUtil::ReportPublishFailedEvent(request, message);
1685 return result;
1686 }
1687
1688 request->SetCreatorPid(IPCSkeleton::GetCallingPid());
1689 int32_t userId = SUBSCRIBE_USER_INIT;
1690 if (request->GetCreatorUserId() == SUBSCRIBE_USER_INIT) {
1691 if (request->GetCreatorUid() != 0) {
1692 OHOS::AccountSA::OsAccountManager::GetOsAccountLocalIdFromUid(request->GetCreatorUid(), userId);
1693 } else {
1694 OHOS::AccountSA::OsAccountManager::GetOsAccountLocalIdFromUid(IPCSkeleton::GetCallingUid(), userId);
1695 }
1696 request->SetCreatorUserId(userId);
1697 } else {
1698 userId = request->GetCreatorUserId();
1699 }
1700
1701 if (request->GetOwnerUserId() == SUBSCRIBE_USER_INIT && request->GetOwnerUid() != DEFAULT_UID) {
1702 int32_t ownerUserId = SUBSCRIBE_USER_INIT;
1703 OsAccountManagerHelper::GetInstance().GetOsAccountLocalIdFromUid(request->GetOwnerUid(), ownerUserId);
1704 request->SetOwnerUserId(ownerUserId);
1705 }
1706
1707 if (request->GetDeliveryTime() <= 0) {
1708 request->SetDeliveryTime(GetCurrentTime());
1709 }
1710 result = CheckPictureSize(request);
1711 if (result != ERR_OK) {
1712 message.ErrorCode(result).Message("Failed to check picture size", true);
1713 NotificationAnalyticsUtil::ReportPublishFailedEvent(request, message);
1714 return result;
1715 }
1716 ANS_LOGD("creator uid=%{public}d, userId=%{public}d, bundleName=%{public}s ", uid,
1717 userId, bundle.c_str());
1718 return ERR_OK;
1719 }
1720
PrePublishRequest(const sptr<NotificationRequest> & request)1721 ErrCode AdvancedNotificationService::PrePublishRequest(const sptr<NotificationRequest> &request)
1722 {
1723 HaMetaMessage message = HaMetaMessage(EventSceneId::SCENE_9, EventBranchId::BRANCH_0);
1724 if (!InitPublishProcess()) {
1725 return ERR_ANS_NO_MEMORY;
1726 }
1727 ErrCode result = publishProcess_[request->GetSlotType()]->PublishPreWork(request, false);
1728 if (result != ERR_OK) {
1729 message.BranchId(EventBranchId::BRANCH_0).ErrorCode(result).Message("publish prework failed", true);
1730 NotificationAnalyticsUtil::ReportPublishFailedEvent(request, message);
1731 return result;
1732 }
1733 result = CheckUserIdParams(request->GetReceiverUserId());
1734 if (result != ERR_OK) {
1735 message.BranchId(EventBranchId::BRANCH_1).ErrorCode(result).Message("User is invalid", true);
1736 NotificationAnalyticsUtil::ReportPublishFailedEvent(request, message);
1737 return result;
1738 }
1739
1740 if (request->GetCreatorUid() <= 0) {
1741 message.BranchId(EventBranchId::BRANCH_2).ErrorCode(ERR_ANS_INVALID_UID)
1742 .Message("createUid failed" + std::to_string(request->GetCreatorUid()), true);
1743 NotificationAnalyticsUtil::ReportPublishFailedEvent(request, message);
1744 return ERR_ANS_INVALID_UID;
1745 }
1746 std::shared_ptr<BundleManagerHelper> bundleManager = BundleManagerHelper::GetInstance();
1747 if (bundleManager == nullptr) {
1748 ANS_LOGE("failed to get bundleManager!");
1749 return ERR_ANS_INVALID_BUNDLE;
1750 }
1751 request->SetCreatorPid(IPCSkeleton::GetCallingPid());
1752 int32_t userId = SUBSCRIBE_USER_INIT;
1753 if (request->GetCreatorUserId() == SUBSCRIBE_USER_INIT) {
1754 OHOS::AccountSA::OsAccountManager::GetOsAccountLocalIdFromUid(request->GetCreatorUid(), userId);
1755 request->SetCreatorUserId(userId);
1756 }
1757
1758 if (request->GetDeliveryTime() <= 0) {
1759 request->SetDeliveryTime(GetCurrentTime());
1760 }
1761 result = CheckPictureSize(request);
1762 if (result != ERR_OK) {
1763 message.ErrorCode(result).Message("Failed to check picture size", true);
1764 NotificationAnalyticsUtil::ReportPublishFailedEvent(request, message);
1765 return result;
1766 }
1767 return ERR_OK;
1768 }
1769
StartAutoDelete(const std::shared_ptr<NotificationRecord> & record,int64_t deleteTimePoint,int32_t reason)1770 uint64_t AdvancedNotificationService::StartAutoDelete(const std::shared_ptr<NotificationRecord> &record,
1771 int64_t deleteTimePoint, int32_t reason)
1772 {
1773 ANS_LOGD("Enter");
1774 wptr<AdvancedNotificationService> wThis = this;
1775 auto triggerFunc = [wThis, record, reason, deleteTimePoint] {
1776 sptr<AdvancedNotificationService> sThis = wThis.promote();
1777 if (sThis != nullptr) {
1778 sThis->TriggerAutoDelete(record->notification->GetKey(), reason);
1779 if (record->finish_status != NotificationConstant::DEFAULT_FINISH_STATUS) {
1780 sThis->SendLiveViewUploadHiSysEvent(record, record->finish_status);
1781 }
1782 }
1783 };
1784 std::shared_ptr<NotificationTimerInfo> notificationTimerInfo = std::make_shared<NotificationTimerInfo>();
1785 notificationTimerInfo->SetCallbackInfo(triggerFunc);
1786
1787 sptr<MiscServices::TimeServiceClient> timer = MiscServices::TimeServiceClient::GetInstance();
1788 if (timer == nullptr) {
1789 ANS_LOGE("Failed to start timer due to get TimeServiceClient is null.");
1790 return 0;
1791 }
1792 uint64_t timerId = timer->CreateTimer(notificationTimerInfo);
1793 timer->StartTimer(timerId, deleteTimePoint);
1794 return timerId;
1795 }
1796
CancelTimer(uint64_t timerId)1797 void AdvancedNotificationService::CancelTimer(uint64_t timerId)
1798 {
1799 ANS_LOGD("Enter");
1800 if (timerId == NotificationConstant::INVALID_TIMER_ID) {
1801 return;
1802 }
1803 MiscServices::TimeServiceClient::GetInstance()->StopTimer(timerId);
1804 MiscServices::TimeServiceClient::GetInstance()->DestroyTimer(timerId);
1805 }
1806
BatchCancelTimer(std::vector<uint64_t> timerIds)1807 void AdvancedNotificationService::BatchCancelTimer(std::vector<uint64_t> timerIds)
1808 {
1809 ANS_LOGD("Enter");
1810 for (uint64_t timerId : timerIds) {
1811 CancelTimer(timerId);
1812 }
1813 }
1814
SendNotificationsOnCanceled(std::vector<sptr<Notification>> & notifications,const sptr<NotificationSortingMap> & notificationMap,int32_t deleteReason)1815 void AdvancedNotificationService::SendNotificationsOnCanceled(std::vector<sptr<Notification>> ¬ifications,
1816 const sptr<NotificationSortingMap> ¬ificationMap, int32_t deleteReason)
1817 {
1818 std::vector<sptr<Notification>> currNotifications;
1819 for (auto notification : notifications) {
1820 currNotifications.emplace_back(notification);
1821 }
1822 NotificationSubscriberManager::GetInstance()->BatchNotifyCanceled(
1823 currNotifications, nullptr, deleteReason);
1824 notifications.clear();
1825 }
1826
SetSlotFlagsTrustlistsAsBundle(const sptr<NotificationBundleOption> & bundleOption)1827 void AdvancedNotificationService::SetSlotFlagsTrustlistsAsBundle(const sptr<NotificationBundleOption> &bundleOption)
1828 {
1829 if (!NotificationPreferences::GetInstance()->IsNotificationSlotFlagsExists(bundleOption) &&
1830 DelayedSingleton<NotificationTrustList>::GetInstance()->IsSlotFlagsTrustlistAsBundle(bundleOption)) {
1831 uint32_t slotFlags = 0b111111;
1832 ErrCode saveRef = NotificationPreferences::GetInstance()->SetNotificationSlotFlagsForBundle(
1833 bundleOption, slotFlags);
1834 if (saveRef != ERR_OK) {
1835 ANS_LOGE("Set slotflags error! code: %{public}d", saveRef);
1836 }
1837 UpdateSlotReminderModeBySlotFlags(bundleOption, slotFlags);
1838 }
1839 }
1840
InitNotificationEnableList()1841 void AdvancedNotificationService::InitNotificationEnableList()
1842 {
1843 auto task = [&]() {
1844 std::vector<AppExecFwk::BundleInfo> bundleInfos = GetBundlesOfActiveUser();
1845 bool notificationEnable = false;
1846 for (const auto &bundleInfo : bundleInfos) {
1847 // Currently only the input from the whitelist is written
1848 if (!bundleInfo.applicationInfo.allowEnableNotification) {
1849 continue;
1850 }
1851 sptr<NotificationBundleOption> bundleOption = new (std::nothrow) NotificationBundleOption(
1852 bundleInfo.applicationInfo.bundleName, bundleInfo.uid);
1853 if (bundleOption == nullptr) {
1854 ANS_LOGE("New bundle option obj error! bundlename:%{public}s",
1855 bundleInfo.applicationInfo.bundleName.c_str());
1856 continue;
1857 }
1858 ErrCode saveRef = NotificationPreferences::GetInstance()->GetNotificationsEnabledForBundle(
1859 bundleOption, notificationEnable);
1860 // record already exists
1861 if (saveRef == ERR_OK) {
1862 continue;
1863 }
1864 saveRef = NotificationPreferences::GetInstance()->SetNotificationsEnabledForBundle(bundleOption, true);
1865 if (saveRef != ERR_OK) {
1866 ANS_LOGE("Set enable error! code: %{public}d", saveRef);
1867 }
1868 saveRef = NotificationPreferences::GetInstance()->SetShowBadge(bundleOption, true);
1869 if (saveRef != ERR_OK) {
1870 ANS_LOGE("Set badge enable error! code: %{public}d", saveRef);
1871 }
1872 SetSlotFlagsTrustlistsAsBundle(bundleOption);
1873 }
1874 };
1875 notificationSvrQueue_ != nullptr ? notificationSvrQueue_->submit(task) : task();
1876 }
1877
GetBundleInfoByNotificationBundleOption(const sptr<NotificationBundleOption> & bundleOption,AppExecFwk::BundleInfo & bundleInfo)1878 bool AdvancedNotificationService::GetBundleInfoByNotificationBundleOption(
1879 const sptr<NotificationBundleOption> &bundleOption, AppExecFwk::BundleInfo &bundleInfo)
1880 {
1881 CHECK_BUNDLE_OPTION_IS_INVALID_WITH_RETURN(bundleOption, false)
1882 int32_t callingUserId = -1;
1883 AccountSA::OsAccountManager::GetOsAccountLocalIdFromUid(bundleOption->GetUid(), callingUserId);
1884 auto bundleMgr = BundleManagerHelper::GetInstance();
1885 if (bundleMgr == nullptr) {
1886 ANS_LOGE("bundleMgr instance error!");
1887 return false;
1888 }
1889 if (!bundleMgr->GetBundleInfoByBundleName(bundleOption->GetBundleName(), callingUserId, bundleInfo)) {
1890 ANS_LOGE("Get bundle info error!");
1891 return false;
1892 }
1893 return true;
1894 }
1895
CheckBundleOptionValid(sptr<NotificationBundleOption> & bundleOption)1896 ErrCode AdvancedNotificationService::CheckBundleOptionValid(sptr<NotificationBundleOption> &bundleOption)
1897 {
1898 if (bundleOption == nullptr || bundleOption->GetBundleName().empty()) {
1899 ANS_LOGE("Bundle option is invalid.");
1900 return ERR_ANS_INVALID_PARAM;
1901 }
1902
1903 int32_t activeUserId = 0;
1904 if (!GetActiveUserId(activeUserId)) {
1905 ANS_LOGE("Failed to get active user id.");
1906 return ERR_ANS_INVALID_BUNDLE;
1907 }
1908 std::shared_ptr<BundleManagerHelper> bundleManager = BundleManagerHelper::GetInstance();
1909 if (bundleManager == nullptr) {
1910 ANS_LOGE("Failed to get bundle manager.");
1911 return ERR_ANS_INVALID_BUNDLE;
1912 }
1913 int32_t uid = bundleManager->GetDefaultUidByBundleName(bundleOption->GetBundleName(), activeUserId);
1914 if (uid == -1) {
1915 ANS_LOGE("The specified bundle name was not found.");
1916 return ERR_ANS_INVALID_BUNDLE;
1917 }
1918
1919 if (bundleOption->GetUid() > 0) {
1920 return ERR_OK;
1921 }
1922
1923 bundleOption->SetUid(uid);
1924 return ERR_OK;
1925 }
1926
GetBundlesOfActiveUser()1927 std::vector<AppExecFwk::BundleInfo> AdvancedNotificationService::GetBundlesOfActiveUser()
1928 {
1929 std::vector<AppExecFwk::BundleInfo> bundleInfos;
1930 auto bundleMgr = BundleManagerHelper::GetInstance();
1931 if (bundleMgr == nullptr) {
1932 ANS_LOGE("Get bundle mgr error!");
1933 return bundleInfos;
1934 }
1935
1936 std::vector<int32_t> activeUserId;
1937 AccountSA::OsAccountManager::QueryActiveOsAccountIds(activeUserId);
1938 if (activeUserId.empty()) {
1939 activeUserId.push_back(MAIN_USER_ID);
1940 }
1941 AppExecFwk::BundleFlag flag = AppExecFwk::BundleFlag::GET_BUNDLE_DEFAULT;
1942 for (auto &itemUser: activeUserId) {
1943 std::vector<AppExecFwk::BundleInfo> infos;
1944 if (!bundleMgr->GetBundleInfos(flag, infos, itemUser)) {
1945 ANS_LOGW("Get bundle infos error");
1946 continue;
1947 }
1948 bundleInfos.insert(bundleInfos.end(), infos.begin(), infos.end());
1949 }
1950
1951 return bundleInfos;
1952 }
1953
CloseAlert(const std::shared_ptr<NotificationRecord> & record)1954 void AdvancedNotificationService::CloseAlert(const std::shared_ptr<NotificationRecord> &record)
1955 {
1956 record->notification->SetEnableLight(false);
1957 record->notification->SetEnableSound(false);
1958 record->notification->SetEnableVibration(false);
1959 auto flag = record->request->GetFlags();
1960 flag->SetSoundEnabled(NotificationConstant::FlagStatus::CLOSE);
1961 flag->SetLightScreenEnabled(false);
1962 flag->SetVibrationEnabled(NotificationConstant::FlagStatus::CLOSE);
1963 record->request->SetFlags(flag);
1964 ANS_LOGI("SetFlags-CloseAlert, notificationKey = %{public}s flags = %{public}d",
1965 record->request->GetKey().c_str(), flag->GetReminderFlags());
1966 }
1967
AllowUseReminder(const std::string & bundleName)1968 bool AdvancedNotificationService::AllowUseReminder(const std::string& bundleName)
1969 {
1970 if (DelayedSingleton<NotificationTrustList>::GetInstance()->IsReminderTrustList(bundleName)) {
1971 return true;
1972 }
1973 #ifdef ENABLE_ANS_EXT_WRAPPER
1974 int32_t ctrlResult = EXTENTION_WRAPPER->ReminderControl(bundleName);
1975 return (ctrlResult == ERR_OK) ? true : false;
1976 #else
1977 return true;
1978 #endif
1979 }
1980
ResetDistributedEnabled()1981 void AdvancedNotificationService::ResetDistributedEnabled()
1982 {
1983 if (notificationSvrQueue_ == nullptr) {
1984 ANS_LOGE("notificationSvrQueue is nullptr");
1985 }
1986 ffrt::task_handle handler = notificationSvrQueue_->submit_h(std::bind([=]() {
1987 std::string value;
1988 NotificationPreferences::GetInstance()->GetKvFromDb(KEY_TABLE_VERSION, value, FIRST_USERID);
1989 if (!value.empty()) {
1990 return;
1991 }
1992 ANS_LOGI("start ResetDistributedEnabled");
1993 std::unordered_map<std::string, std::string> oldValues;
1994 NotificationPreferences::GetInstance()->GetBatchKvsFromDb(
1995 OLD_KEY_BUNDLE_DISTRIBUTED_ENABLE_NOTIFICATION, oldValues, FIRST_USERID);
1996 if (oldValues.empty()) {
1997 NotificationPreferences::GetInstance()->SetKvToDb(
1998 KEY_TABLE_VERSION, std::to_string(MIN_VERSION), FIRST_USERID);
1999 return;
2000 }
2001 std::shared_ptr<BundleManagerHelper> bundleManager = BundleManagerHelper::GetInstance();
2002 std::vector<std::string> delKeys;
2003 for (auto iter : oldValues) {
2004 std::vector<std::string> keywordVector;
2005 StringUtils::Split(iter.first, SPLIT_FLAG, keywordVector);
2006 delKeys.push_back(iter.first);
2007 if (keywordVector.size() != KEYWORD_SIZE) {
2008 continue;
2009 }
2010 std::string bundleName = keywordVector[1];
2011 int32_t activeUserId = atoi(keywordVector[2].c_str());
2012 std::string deviceType = keywordVector[3];
2013 bool enabled = atoi(iter.second.c_str());
2014 int32_t uid = bundleManager->GetDefaultUidByBundleName(bundleName, activeUserId);
2015 if (uid <= 0) {
2016 continue;
2017 }
2018 sptr<NotificationBundleOption> bundleOption =
2019 new NotificationBundleOption(bundleName, uid);
2020 ErrCode result = NotificationPreferences::GetInstance()->SetDistributedEnabledByBundle(
2021 bundleOption, deviceType, enabled);
2022 if (result != ERR_OK) {
2023 ANS_LOGE("SetDistributeEnabled failed! key:%{public}s, uid:%{public}d",
2024 iter.first.c_str(), uid);
2025 }
2026 }
2027 NotificationPreferences::GetInstance()->DeleteBatchKvFromDb(delKeys, FIRST_USERID);
2028 NotificationPreferences::GetInstance()->SetKvToDb(
2029 KEY_TABLE_VERSION, std::to_string(MIN_VERSION), FIRST_USERID);
2030 }));
2031 }
2032
OnRecoverLiveView(const std::vector<std::string> & keys)2033 ErrCode AdvancedNotificationService::OnRecoverLiveView(
2034 const std::vector<std::string> &keys)
2035 {
2036 ANS_LOGD("enter");
2037
2038 if (notificationSvrQueue_ == nullptr) {
2039 ANS_LOGE("NotificationSvrQueue is nullptr.");
2040 return ERR_ANS_INVALID_PARAM;
2041 }
2042
2043 std::vector<sptr<Notification>> notifications;
2044 int32_t removeReason = NotificationConstant::RECOVER_LIVE_VIEW_DELETE;
2045 std::vector<uint64_t> timerIds;
2046 for (auto key : keys) {
2047 ANS_LOGI("BatchRemoveByKeys key = %{public}s", key.c_str());
2048 sptr<Notification> notification = nullptr;
2049 #ifdef DISTRIBUTED_NOTIFICATION_SUPPORTED
2050 std::string deviceId;
2051 std::string bundleName;
2052 GetDistributedInfo(key, deviceId, bundleName);
2053 #endif
2054 ErrCode result = RemoveFromNotificationList(key, notification, true, removeReason);
2055 if (result != ERR_OK) {
2056 continue;
2057 }
2058 if (notification != nullptr) {
2059 notifications.emplace_back(notification);
2060 timerIds.emplace_back(notification->GetAutoDeletedTimer());
2061 #ifdef DISTRIBUTED_NOTIFICATION_SUPPORTED
2062 DoDistributedDelete(deviceId, bundleName, notification);
2063 #endif
2064 }
2065 if (notifications.size() >= MAX_CANCELED_PARCELABLE_VECTOR_NUM) {
2066 std::vector<sptr<Notification>> currNotificationList = notifications;
2067 NotificationSubscriberManager::GetInstance()->BatchNotifyCanceled(
2068 currNotificationList, nullptr, removeReason);
2069 notifications.clear();
2070 }
2071 }
2072
2073 if (!notifications.empty()) {
2074 NotificationSubscriberManager::GetInstance()->BatchNotifyCanceled(notifications, nullptr, removeReason);
2075 }
2076 BatchCancelTimer(timerIds);
2077 return ERR_OK;
2078 }
2079 } // namespace Notification
2080 } // namespace OHOS
2081