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