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