• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright (c) 2021-2023 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_inner_errors.h"
22 #include "ans_log_wrapper.h"
23 #include "access_token_helper.h"
24 #include "ans_permission_def.h"
25 #include "bundle_manager_helper.h"
26 #include "errors.h"
27 #include "ipc_skeleton.h"
28 #include "notification_constant.h"
29 #include "os_account_manager.h"
30 #include "notification_preferences.h"
31 #include "distributed_database.h"
32 #include "want_agent_helper.h"
33 #include "hitrace_meter.h"
34 #include "notification_timer_info.h"
35 #include "time_service_client.h"
36 
37 #ifdef DISTRIBUTED_NOTIFICATION_SUPPORTED
38 #include "distributed_notification_manager.h"
39 #include "distributed_preferences.h"
40 #include "distributed_screen_status_manager.h"
41 #endif
42 
43 #include "advanced_notification_inline.cpp"
44 
45 #define CHECK_BUNDLE_OPTION_IS_INVALID(option)                              \
46     if (option == nullptr || option->GetBundleName().empty()) {             \
47         ANS_LOGE("Bundle option sptr is null or bundle name is empty!");    \
48         return;                                                             \
49     }
50 
51 #define CHECK_BUNDLE_OPTION_IS_INVALID_WITH_RETURN(option, retVal)          \
52     if (option == nullptr || option->GetBundleName().empty()) {             \
53         ANS_LOGE("Bundle option sptr is null or bundle name is empty!");    \
54         return retVal;                                                      \
55     }
56 
57 namespace OHOS {
58 namespace Notification {
59 namespace {
60 #ifdef DISTRIBUTED_NOTIFICATION_SUPPORTED
61 constexpr char DISTRIBUTED_NOTIFICATION_OPTION[] = "distributed";
62 #endif
63 constexpr int32_t HOURS_IN_ONE_DAY = 24;
64 constexpr char FOUNDATION_BUNDLE_NAME[] = "ohos.global.systemres";
65 constexpr char ACTIVE_NOTIFICATION_OPTION[] = "active";
66 constexpr char SET_RECENT_COUNT_OPTION[] = "setRecentCount";
67 constexpr char HELP_NOTIFICATION_OPTION[] = "help";
68 constexpr char RECENT_NOTIFICATION_OPTION[] = "recent";
69 constexpr char HIDUMPER_ERR_MSG[] =
70     "error: unknown option.\nThe arguments are illegal and you can enter '-h' for help.";
71 constexpr int32_t MAIN_USER_ID = 100;
72 const std::unordered_map<std::string, std::string> HIDUMPER_CMD_MAP = {
73     { "--help", HELP_NOTIFICATION_OPTION },
74     { "--active", ACTIVE_NOTIFICATION_OPTION },
75     { "--recent", RECENT_NOTIFICATION_OPTION },
76     { "-h", HELP_NOTIFICATION_OPTION },
77     { "-a", ACTIVE_NOTIFICATION_OPTION },
78     { "-r", RECENT_NOTIFICATION_OPTION },
79 };
80 
81 constexpr char HIDUMPER_HELP_MSG[] =
82     "Usage:dump <command> [options]\n"
83     "Description::\n"
84     "  --active, -a                 list all active notifications\n"
85     "  --recent, -r                 list recent notifications\n";
86 }
87 
88 
SortNotificationsByLevelAndTime(const std::shared_ptr<NotificationRecord> & first,const std::shared_ptr<NotificationRecord> & second)89 static bool SortNotificationsByLevelAndTime(
90     const std::shared_ptr<NotificationRecord> &first, const std::shared_ptr<NotificationRecord> &second)
91 {
92     if (first->slot->GetLevel() != second->slot->GetLevel()) {
93         return (first->slot->GetLevel() < second->slot->GetLevel());
94     }
95     return (first->request->GetCreateTime() < second->request->GetCreateTime());
96 }
97 
GetNotificationSvrQueue()98 std::shared_ptr<ffrt::queue> AdvancedNotificationService::GetNotificationSvrQueue()
99 {
100     return notificationSvrQueue_;
101 }
102 
GenerateBundleOption()103 sptr<NotificationBundleOption> AdvancedNotificationService::GenerateBundleOption()
104 {
105     sptr<NotificationBundleOption> bundleOption = nullptr;
106     std::string bundle = GetClientBundleName();
107     if (bundle.empty()) {
108         return nullptr;
109     }
110     int32_t uid = IPCSkeleton::GetCallingUid();
111     bundleOption = new (std::nothrow) NotificationBundleOption(bundle, uid);
112     if (bundleOption == nullptr) {
113         ANS_LOGE("Failed to create NotificationBundleOption instance");
114         return nullptr;
115     }
116     return bundleOption;
117 }
118 
GenerateValidBundleOption(const sptr<NotificationBundleOption> & bundleOption)119 sptr<NotificationBundleOption> AdvancedNotificationService::GenerateValidBundleOption(
120     const sptr<NotificationBundleOption> &bundleOption)
121 {
122     if (bundleOption == nullptr) {
123         ANS_LOGE("bundleOption is invalid!");
124         return nullptr;
125     }
126 
127     sptr<NotificationBundleOption> validBundleOption = nullptr;
128     if (bundleOption->GetUid() <= 0) {
129         std::shared_ptr<BundleManagerHelper> bundleManager = BundleManagerHelper::GetInstance();
130         if (bundleManager != nullptr) {
131             int32_t activeUserId = -1;
132             if (!GetActiveUserId(activeUserId)) {
133                 ANS_LOGE("Failed to get active user id!");
134                 return validBundleOption;
135             }
136             int32_t uid = bundleManager->GetDefaultUidByBundleName(bundleOption->GetBundleName(), activeUserId);
137             if (uid > 0) {
138                 validBundleOption = new (std::nothrow) NotificationBundleOption(bundleOption->GetBundleName(), uid);
139                 if (validBundleOption == nullptr) {
140                     ANS_LOGE("Failed to create NotificationBundleOption instance");
141                     return nullptr;
142                 }
143             }
144         }
145     } else {
146         validBundleOption = bundleOption;
147     }
148     return validBundleOption;
149 }
150 
GenerateSortingMap()151 sptr<NotificationSortingMap> AdvancedNotificationService::GenerateSortingMap()
152 {
153     std::vector<NotificationSorting> sortingList;
154     for (auto record : notificationList_) {
155         NotificationSorting sorting;
156         sorting.SetRanking(static_cast<uint64_t>(sortingList.size()));
157         sorting.SetKey(record->notification->GetKey());
158         sorting.SetSlot(record->slot);
159         sortingList.push_back(sorting);
160     }
161 
162     sptr<NotificationSortingMap> sortingMap = new (std::nothrow) NotificationSortingMap(sortingList);
163     if (sortingMap == nullptr) {
164         ANS_LOGE("Failed to create NotificationSortingMap instance");
165         return nullptr;
166     }
167 
168     return sortingMap;
169 }
170 
CheckCommonParams()171 ErrCode AdvancedNotificationService::CheckCommonParams()
172 {
173     if (notificationSvrQueue_ == nullptr) {
174         ANS_LOGE("Serial queue is invalidity.");
175         return ERR_ANS_INVALID_PARAM;
176     }
177 
178     bool isSubsystem = AccessTokenHelper::VerifyNativeToken(IPCSkeleton::GetCallingTokenID());
179     if (!isSubsystem && !AccessTokenHelper::IsSystemApp()) {
180         return ERR_ANS_NON_SYSTEM_APP;
181     }
182 
183     if (!CheckPermission(OHOS_PERMISSION_NOTIFICATION_CONTROLLER)) {
184         ANS_LOGD("Check permission is false.");
185         return ERR_ANS_PERMISSION_DENIED;
186     }
187 
188     return ERR_OK;
189 }
190 
GetAppTargetBundle(const sptr<NotificationBundleOption> & bundleOption,sptr<NotificationBundleOption> & targetBundle)191 ErrCode AdvancedNotificationService::GetAppTargetBundle(const sptr<NotificationBundleOption> &bundleOption,
192     sptr<NotificationBundleOption> &targetBundle)
193 {
194     sptr<NotificationBundleOption> clientBundle = GenerateBundleOption();
195     if (clientBundle == nullptr) {
196         return ERR_ANS_INVALID_BUNDLE;
197     }
198 
199     if (bundleOption == nullptr) {
200         targetBundle = clientBundle;
201     } else {
202         if ((clientBundle->GetBundleName() == bundleOption->GetBundleName()) &&
203             (clientBundle->GetUid() == bundleOption->GetUid())) {
204             targetBundle = bundleOption;
205         } else {
206             bool isSubsystem = AccessTokenHelper::VerifyNativeToken(IPCSkeleton::GetCallingTokenID());
207             if (!isSubsystem && !AccessTokenHelper::IsSystemApp()) {
208                 return ERR_ANS_NON_SYSTEM_APP;
209             }
210             targetBundle = GenerateValidBundleOption(bundleOption);
211         }
212     }
213     return ERR_OK;
214 }
215 
FillRequestByKeys(const sptr<NotificationRequest> & oldRequest,const std::vector<std::string> extraInfoKeys,sptr<NotificationRequest> & newRequest)216 ErrCode AdvancedNotificationService::FillRequestByKeys(const sptr<NotificationRequest> &oldRequest,
217     const std::vector<std::string> extraInfoKeys, sptr<NotificationRequest> &newRequest)
218 {
219     auto liveViewContent = std::static_pointer_cast<NotificationLiveViewContent>(
220         oldRequest->GetContent()->GetNotificationContent());
221     auto liveViewExtraInfo = liveViewContent->GetExtraInfo();
222 
223     newRequest = sptr<NotificationRequest>::MakeSptr(*(oldRequest));
224     auto requestLiveViewContent = std::make_shared<NotificationLiveViewContent>();
225 
226     requestLiveViewContent->SetLiveViewStatus(liveViewContent->GetLiveViewStatus());
227     requestLiveViewContent->SetVersion(liveViewContent->GetVersion());
228 
229     std::shared_ptr<AAFwk::WantParams> requestExtraInfo = std::make_shared<AAFwk::WantParams>();
230     if (requestExtraInfo == nullptr) {
231         ANS_LOGE("Failed to make extraInfos.");
232         return ERR_ANS_TASK_ERR;
233     }
234     for (const auto &extraInfoKey : extraInfoKeys) {
235         auto paramValue = liveViewExtraInfo->GetParam(extraInfoKey);
236         if (paramValue != nullptr) {
237             requestExtraInfo->SetParam(extraInfoKey, paramValue);
238         }
239     }
240     requestLiveViewContent->SetExtraInfo(requestExtraInfo);
241 
242     auto requestContent = std::make_shared<NotificationContent>(requestLiveViewContent);
243     newRequest->SetContent(requestContent);
244     return ERR_OK;
245 }
246 
IsAllowedGetNotificationByFilter(const std::shared_ptr<NotificationRecord> & record)247 ErrCode AdvancedNotificationService::IsAllowedGetNotificationByFilter(
248     const std::shared_ptr<NotificationRecord> &record)
249 {
250     bool isSubsystem = AccessTokenHelper::VerifyNativeToken(IPCSkeleton::GetCallingTokenID());
251     if (isSubsystem || AccessTokenHelper::IsSystemApp()) {
252         if (CheckPermission(OHOS_PERMISSION_NOTIFICATION_CONTROLLER)) {
253             return ERR_OK;
254         }
255 
256         ANS_LOGD("Get live view by filter failed because check permission is false.");
257         return ERR_ANS_PERMISSION_DENIED;
258     }
259 
260     std::string bundle = GetClientBundleName();
261     if (bundle.empty()) {
262         ANS_LOGD("Get live view by filter failed because bundle name is empty.");
263         return ERR_ANS_PERMISSION_DENIED;
264     }
265     int32_t uid = IPCSkeleton::GetCallingUid();
266     if (uid == record->bundleOption->GetUid() && bundle == record->bundleOption->GetBundleName()) {
267         return ERR_OK;
268     }
269 
270     ANS_LOGD("Get live view by filter failed because no permission.");
271     return ERR_ANS_PERMISSION_DENIED;
272 }
273 
GetActiveNotificationByFilter(const sptr<NotificationBundleOption> & bundleOption,const int32_t notificationId,const std::string & label,const std::vector<std::string> extraInfoKeys,sptr<NotificationRequest> & request)274 ErrCode AdvancedNotificationService::GetActiveNotificationByFilter(
275     const sptr<NotificationBundleOption> &bundleOption, const int32_t notificationId, const std::string &label,
276     const std::vector<std::string> extraInfoKeys, sptr<NotificationRequest> &request)
277 {
278     ANS_LOGD("%{public}s", __FUNCTION__);
279 
280     if (notificationSvrQueue_ == nullptr) {
281         ANS_LOGE("Serial queue is invalidity.");
282         return ERR_ANS_INVALID_PARAM;
283     }
284 
285     sptr<NotificationBundleOption> bundle = GenerateValidBundleOption(bundleOption);
286     if (bundle == nullptr) {
287         return ERR_ANS_INVALID_BUNDLE;
288     }
289 
290     ErrCode result = ERR_ANS_NOTIFICATION_NOT_EXISTS;
291     ffrt::task_handle handler = notificationSvrQueue_->submit_h(std::bind([&]() {
292         ANS_LOGD("ffrt enter!");
293 
294         auto record = GetRecordFromNotificationList(notificationId, bundle->GetUid(), label, bundle->GetBundleName());
295         if ((record == nullptr) || (!record->request->IsCommonLiveView())) {
296             return;
297         }
298         result = IsAllowedGetNotificationByFilter(record);
299         if (result != ERR_OK) {
300             return;
301         }
302 
303         if (extraInfoKeys.empty()) {
304             // return all liveViewExtraInfo because no extraInfoKeys
305             request = record->request;
306             return;
307         }
308         // obtain extraInfo by extraInfoKeys
309         if (FillRequestByKeys(record->request, extraInfoKeys, request) != ERR_OK) {
310             return;
311         }
312     }));
313     notificationSvrQueue_->wait(handler);
314 
315     return result;
316 }
317 
SetAgentNotification(sptr<NotificationRequest> & notificationRequest,std::string & bundleName)318 void AdvancedNotificationService::SetAgentNotification(sptr<NotificationRequest>& notificationRequest,
319     std::string& bundleName)
320 {
321     auto bundleManager = BundleManagerHelper::GetInstance();
322     int32_t activeUserId = -1;
323     if (!GetActiveUserId(activeUserId)) {
324         ANSR_LOGW("Failed to get active user id!");
325         return;
326     }
327 
328     notificationRequest->SetIsAgentNotification(true);
329     notificationRequest->SetOwnerUserId(activeUserId);
330     notificationRequest->SetOwnerBundleName(bundleName);
331 }
332 
ActiveNotificationDump(const std::string & bundle,int32_t userId,std::vector<std::string> & dumpInfo)333 ErrCode AdvancedNotificationService::ActiveNotificationDump(const std::string& bundle, int32_t userId,
334     std::vector<std::string> &dumpInfo)
335 {
336     ANS_LOGD("%{public}s", __FUNCTION__);
337     std::stringstream stream;
338     for (const auto &record : notificationList_) {
339         if (record->notification == nullptr || record->request == nullptr) {
340             continue;
341         }
342         if (userId != SUBSCRIBE_USER_INIT && userId != record->notification->GetUserId()) {
343             continue;
344         }
345         if (!bundle.empty() && bundle != record->notification->GetBundleName()) {
346             continue;
347         }
348 #ifdef DISTRIBUTED_NOTIFICATION_SUPPORTED
349         if (!record->deviceId.empty()) {
350             continue;
351         }
352 #endif
353         stream.clear();
354         stream.str("");
355         stream << "\tUserId: " << record->notification->GetUserId() << "\n";
356         stream << "\tCreatePid: " << record->request->GetCreatorPid() << "\n";
357         stream << "\tOwnerBundleName: " << record->notification->GetBundleName() << "\n";
358         if (record->request->GetOwnerUid() > 0) {
359             ANS_LOGD("GetOwnerUid larger than zero.");
360             stream << "\tOwnerUid: " << record->request->GetOwnerUid() << "\n";
361         } else {
362             stream << "\tOwnerUid: " << record->request->GetCreatorUid() << "\n";
363         }
364         stream << "\tDeliveryTime = " << TimeToString(record->request->GetDeliveryTime()) << "\n";
365         stream << "\tNotification:\n";
366         stream << "\t\tId: " << record->notification->GetId() << "\n";
367         stream << "\t\tLabel: " << record->notification->GetLabel() << "\n";
368         stream << "\t\tSlotType = " << record->request->GetSlotType() << "\n";
369         ANS_LOGD("DumpInfo push stream.");
370         dumpInfo.push_back(stream.str());
371     }
372     return ERR_OK;
373 }
374 
RecentNotificationDump(const std::string & bundle,int32_t userId,std::vector<std::string> & dumpInfo)375 ErrCode AdvancedNotificationService::RecentNotificationDump(const std::string& bundle, int32_t userId,
376     std::vector<std::string> &dumpInfo)
377 {
378     ANS_LOGD("%{public}s", __FUNCTION__);
379     std::stringstream stream;
380     for (auto recentNotification : recentInfo_->list) {
381         if (recentNotification->notification == nullptr) {
382             continue;
383         }
384         const auto &notificationRequest = recentNotification->notification->GetNotificationRequest();
385         if (userId != SUBSCRIBE_USER_INIT && userId != notificationRequest.GetOwnerUserId()) {
386             continue;
387         }
388         if (!bundle.empty() && bundle != recentNotification->notification->GetBundleName()) {
389             continue;
390         }
391         stream.clear();
392         stream.str("");
393         stream << "\tUserId: " << notificationRequest.GetCreatorUserId() << "\n";
394         stream << "\tCreatePid: " << notificationRequest.GetCreatorPid() << "\n";
395         stream << "\tBundleName: " << recentNotification->notification->GetBundleName() << "\n";
396         if (notificationRequest.GetOwnerUid() > 0) {
397             stream << "\tOwnerUid: " << notificationRequest.GetOwnerUid() << "\n";
398         } else {
399             stream << "\tOwnerUid: " << notificationRequest.GetCreatorUid() << "\n";
400         }
401         stream << "\tDeliveryTime = " << TimeToString(notificationRequest.GetDeliveryTime()) << "\n";
402         if (!recentNotification->isActive) {
403             stream << "\tDeleteTime: " << TimeToString(recentNotification->deleteTime) << "\n";
404             stream << "\tDeleteReason: " << recentNotification->deleteReason << "\n";
405         }
406         stream << "\tNotification:\n";
407         stream << "\t\tId: " << recentNotification->notification->GetId() << "\n";
408         stream << "\t\tLabel: " << recentNotification->notification->GetLabel() << "\n";
409         stream << "\t\tSlotType = " << notificationRequest.GetSlotType() << "\n";
410         dumpInfo.push_back(stream.str());
411     }
412     return ERR_OK;
413 }
414 
415 #ifdef DISTRIBUTED_NOTIFICATION_SUPPORTED
DistributedNotificationDump(const std::string & bundle,int32_t userId,std::vector<std::string> & dumpInfo)416 ErrCode AdvancedNotificationService::DistributedNotificationDump(const std::string& bundle, int32_t userId,
417     std::vector<std::string> &dumpInfo)
418 {
419     ANS_LOGD("%{public}s", __FUNCTION__);
420     std::stringstream stream;
421     for (auto record : notificationList_) {
422         if (record->notification == nullptr) {
423             continue;
424         }
425         if (userId != SUBSCRIBE_USER_INIT && userId != record->notification->GetUserId()) {
426             continue;
427         }
428         if (!bundle.empty() && bundle != record->notification->GetBundleName()) {
429             continue;
430         }
431         if (record->deviceId.empty()) {
432             continue;
433         }
434         stream.clear();
435         stream.str("");
436         stream << "\tUserId: " << record->notification->GetUserId() << "\n";
437         stream << "\tCreatePid: " << record->request->GetCreatorPid() << "\n";
438         stream << "\tOwnerBundleName: " << record->notification->GetBundleName() << "\n";
439         if (record->request->GetOwnerUid() > 0) {
440             stream << "\tOwnerUid: " << record->request->GetOwnerUid() << "\n";
441         } else {
442             stream << "\tOwnerUid: " << record->request->GetCreatorUid() << "\n";
443         }
444         stream << "\tDeliveryTime = " << TimeToString(record->request->GetDeliveryTime()) << "\n";
445         stream << "\tNotification:\n";
446         stream << "\t\tId: " << record->notification->GetId() << "\n";
447         stream << "\t\tLabel: " << record->notification->GetLabel() << "\n";
448         stream << "\t\tSlotType = " << record->request->GetSlotType() << "\n";
449         dumpInfo.push_back(stream.str());
450     }
451 
452     return ERR_OK;
453 }
454 #endif
455 
TimeToString(int64_t time)456 std::string AdvancedNotificationService::TimeToString(int64_t time)
457 {
458     auto timePoint = std::chrono::time_point<std::chrono::system_clock>(std::chrono::milliseconds(time));
459     auto timeT = std::chrono::system_clock::to_time_t(timePoint);
460 
461     std::stringstream stream;
462     struct tm ret = {0};
463     localtime_r(&timeT, &ret);
464     stream << std::put_time(&ret, "%F, %T");
465     return stream.str();
466 }
467 
GetNowSysTime()468 int64_t AdvancedNotificationService::GetNowSysTime()
469 {
470     std::chrono::time_point<std::chrono::system_clock> nowSys = std::chrono::system_clock::now();
471     auto epoch = nowSys.time_since_epoch();
472     auto value = std::chrono::duration_cast<std::chrono::milliseconds>(epoch);
473     int64_t duration = value.count();
474     return duration;
475 }
476 
OnBundleRemoved(const sptr<NotificationBundleOption> & bundleOption)477 void AdvancedNotificationService::OnBundleRemoved(const sptr<NotificationBundleOption> &bundleOption)
478 {
479     ANS_LOGD("%{public}s", __FUNCTION__);
480     if (notificationSvrQueue_ == nullptr) {
481         ANS_LOGE("Serial queue is invalid.");
482         return;
483     }
484     notificationSvrQueue_->submit(std::bind([this, bundleOption]() {
485         ANS_LOGD("ffrt enter!");
486         ErrCode result = NotificationPreferences::GetInstance().RemoveNotificationForBundle(bundleOption);
487         if (result != ERR_OK) {
488             ANS_LOGW("NotificationPreferences::RemoveNotificationForBundle failed: %{public}d", result);
489         }
490 #ifdef DISTRIBUTED_NOTIFICATION_SUPPORTED
491         DistributedPreferences::GetInstance()->DeleteDistributedBundleInfo(bundleOption);
492         std::vector<std::string> keys = GetLocalNotificationKeys(bundleOption);
493 #else
494         std::vector<std::string> keys = GetNotificationKeys(bundleOption);
495 #endif
496         std::vector<sptr<Notification>> notifications;
497         for (auto key : keys) {
498             sptr<Notification> notification = nullptr;
499             result = RemoveFromNotificationList(key, notification, true,
500                 NotificationConstant::PACKAGE_CHANGED_REASON_DELETE);
501             if (result != ERR_OK) {
502                 continue;
503             }
504 
505             if (notification != nullptr) {
506                 int32_t reason = NotificationConstant::PACKAGE_CHANGED_REASON_DELETE;
507                 UpdateRecentNotification(notification, true, reason);
508                 notifications.emplace_back(notification);
509                 if (notifications.size() >= MAX_CANCELED_PARCELABLE_VECTOR_NUM) {
510                     std::vector<sptr<Notification>> currNotificationList = notifications;
511                     NotificationSubscriberManager::GetInstance()->BatchNotifyCanceled(
512                         currNotificationList, nullptr, reason);
513                     notifications.clear();
514                 }
515 #ifdef DISTRIBUTED_NOTIFICATION_SUPPORTED
516                 DoDistributedDelete("", "", notification);
517 #endif
518             }
519         }
520         if (!notifications.empty()) {
521             NotificationSubscriberManager::GetInstance()->BatchNotifyCanceled(
522                 notifications, nullptr, NotificationConstant::PACKAGE_CHANGED_REASON_DELETE);
523         }
524 
525         NotificationPreferences::GetInstance().RemoveAnsBundleDbInfo(bundleOption);
526     }));
527 }
528 
OnBundleDataAdd(const sptr<NotificationBundleOption> & bundleOption)529 void AdvancedNotificationService::OnBundleDataAdd(const sptr<NotificationBundleOption> &bundleOption)
530 {
531     CHECK_BUNDLE_OPTION_IS_INVALID(bundleOption)
532     auto bundleInstall = [bundleOption]() {
533         CHECK_BUNDLE_OPTION_IS_INVALID(bundleOption)
534         AppExecFwk::BundleInfo bundleInfo;
535         if (!GetBundleInfoByNotificationBundleOption(bundleOption, bundleInfo)) {
536             ANS_LOGE("Failed to get BundleInfo using NotificationBundleOption.");
537             return;
538         }
539 
540         // In order to adapt to the publish reminder interface, currently only the input from the whitelist is written
541         if (bundleInfo.applicationInfo.allowEnableNotification) {
542             auto errCode = NotificationPreferences::GetInstance().SetNotificationsEnabledForBundle(bundleOption, true);
543             if (errCode != ERR_OK) {
544                 ANS_LOGE("Set notification enable error! code: %{public}d", errCode);
545             }
546         }
547     };
548 
549     notificationSvrQueue_ != nullptr ? notificationSvrQueue_->submit(bundleInstall) : bundleInstall();
550 }
551 
OnBundleDataUpdate(const sptr<NotificationBundleOption> & bundleOption)552 void AdvancedNotificationService::OnBundleDataUpdate(const sptr<NotificationBundleOption> &bundleOption)
553 {
554     CHECK_BUNDLE_OPTION_IS_INVALID(bundleOption)
555     auto bundleUpdate = [bundleOption]() {
556         CHECK_BUNDLE_OPTION_IS_INVALID(bundleOption)
557         AppExecFwk::BundleInfo bundleInfo;
558         if (!GetBundleInfoByNotificationBundleOption(bundleOption, bundleInfo)) {
559             ANS_LOGE("Failed to get BundleInfo using NotificationBundleOption.");
560             return;
561         }
562 
563         if (!bundleInfo.applicationInfo.allowEnableNotification) {
564             ANS_LOGE("Current application allowEnableNotification is false, do not record.");
565             return;
566         }
567 
568         bool hasPopped = false;
569         auto errCode = NotificationPreferences::GetInstance().GetHasPoppedDialog(bundleOption, hasPopped);
570         if (errCode != ERR_OK) {
571             ANS_LOGD("Get notification user option fail, need to insert data");
572             errCode = NotificationPreferences::GetInstance().SetNotificationsEnabledForBundle(
573                 bundleOption, bundleInfo.applicationInfo.allowEnableNotification);
574             if (errCode != ERR_OK) {
575                 ANS_LOGE("Set notification enable error! code: %{public}d", errCode);
576             }
577             return;
578         }
579 
580         if (hasPopped) {
581             ANS_LOGI("The user has made changes, subject to the user's selection");
582             return;
583         }
584 
585         errCode = NotificationPreferences::GetInstance().SetNotificationsEnabledForBundle(
586             bundleOption, bundleInfo.applicationInfo.allowEnableNotification);
587         if (errCode != ERR_OK) {
588             ANS_LOGE("Set notification enable error! code: %{public}d", errCode);
589         }
590     };
591 
592     notificationSvrQueue_ != nullptr ? notificationSvrQueue_->submit(bundleUpdate) : bundleUpdate();
593 }
594 
OnBootSystemCompleted()595 void AdvancedNotificationService::OnBootSystemCompleted()
596 {
597     ANS_LOGI("Called.");
598     InitNotificationEnableList();
599 }
600 
601 #ifdef DISTRIBUTED_NOTIFICATION_SUPPORTED
OnScreenOn()602 void AdvancedNotificationService::OnScreenOn()
603 {
604     ANS_LOGI("%{public}s", __FUNCTION__);
605     localScreenOn_ = true;
606     DistributedScreenStatusManager::GetInstance()->SetLocalScreenStatus(true);
607 }
608 
OnScreenOff()609 void AdvancedNotificationService::OnScreenOff()
610 {
611     ANS_LOGI("%{public}s", __FUNCTION__);
612     localScreenOn_ = false;
613     DistributedScreenStatusManager::GetInstance()->SetLocalScreenStatus(false);
614 }
615 #endif
616 
OnDistributedKvStoreDeathRecipient()617 void AdvancedNotificationService::OnDistributedKvStoreDeathRecipient()
618 {
619     ANS_LOGD("%{public}s", __FUNCTION__);
620     if (notificationSvrQueue_ == nullptr) {
621         ANS_LOGE("Serial queue is invalid.");
622         return;
623     }
624     ffrt::task_handle handler = notificationSvrQueue_->submit_h(std::bind([&]() {
625         ANS_LOGD("ffrt enter!");
626 #ifdef DISTRIBUTED_NOTIFICATION_SUPPORTED
627         DistributedNotificationManager::GetInstance()->OnDistributedKvStoreDeathRecipient();
628 #endif
629     }));
630 }
631 
GetTargetRecordList(const std::string & bundleName,NotificationConstant::SlotType slotType,NotificationContent::Type contentType,std::vector<std::shared_ptr<NotificationRecord>> & recordList)632 ErrCode AdvancedNotificationService::GetTargetRecordList(const std::string& bundleName,
633     NotificationConstant::SlotType slotType, NotificationContent::Type contentType,
634     std::vector<std::shared_ptr<NotificationRecord>>& recordList)
635 {
636     for (auto& notification : notificationList_) {
637         if (notification->request != nullptr && notification->request->GetOwnerBundleName() == bundleName &&
638                 notification->request->GetSlotType()== slotType &&
639                 notification->request->GetNotificationType() == contentType) {
640                 recordList.emplace_back(notification);
641         }
642     }
643     if (recordList.empty()) {
644         return ERR_ANS_NOTIFICATION_NOT_EXISTS;
645     }
646     return ERR_OK;
647 }
648 
AdjustDateForDndTypeOnce(int64_t & beginDate,int64_t & endDate)649 void AdvancedNotificationService::AdjustDateForDndTypeOnce(int64_t &beginDate, int64_t &endDate)
650 {
651     std::chrono::system_clock::time_point now = std::chrono::system_clock::now();
652     time_t nowT = std::chrono::system_clock::to_time_t(now);
653     tm nowTm = GetLocalTime(nowT);
654 
655     auto beginDateMilliseconds = std::chrono::milliseconds(beginDate);
656     auto beginDateTimePoint =
657         std::chrono::time_point<std::chrono::system_clock, std::chrono::milliseconds>(beginDateMilliseconds);
658     time_t beginDateT = std::chrono::system_clock::to_time_t(beginDateTimePoint);
659     tm beginDateTm = GetLocalTime(beginDateT);
660 
661     auto endDateMilliseconds = std::chrono::milliseconds(endDate);
662     auto endDateTimePoint =
663         std::chrono::time_point<std::chrono::system_clock, std::chrono::milliseconds>(endDateMilliseconds);
664     time_t endDateT = std::chrono::system_clock::to_time_t(endDateTimePoint);
665     tm endDateTm = GetLocalTime(endDateT);
666 
667     tm todayBeginTm = nowTm;
668     todayBeginTm.tm_sec = 0;
669     todayBeginTm.tm_min = beginDateTm.tm_min;
670     todayBeginTm.tm_hour = beginDateTm.tm_hour;
671 
672     tm todayEndTm = nowTm;
673     todayEndTm.tm_sec = 0;
674     todayEndTm.tm_min = endDateTm.tm_min;
675     todayEndTm.tm_hour = endDateTm.tm_hour;
676 
677     time_t todayBeginT = mktime(&todayBeginTm);
678     if (todayBeginT == -1) {
679         return;
680     }
681     time_t todayEndT = mktime(&todayEndTm);
682     if (todayEndT == -1) {
683         return;
684     }
685 
686     auto newBeginTimePoint = std::chrono::system_clock::from_time_t(todayBeginT);
687     auto newEndTimePoint = std::chrono::system_clock::from_time_t(todayEndT);
688     if (newBeginTimePoint >= newEndTimePoint) {
689         newEndTimePoint += std::chrono::hours(HOURS_IN_ONE_DAY);
690     }
691 
692     if (newEndTimePoint < now) {
693         newBeginTimePoint += std::chrono::hours(HOURS_IN_ONE_DAY);
694         newEndTimePoint += std::chrono::hours(HOURS_IN_ONE_DAY);
695     }
696 
697     auto newBeginDuration = std::chrono::duration_cast<std::chrono::milliseconds>(newBeginTimePoint.time_since_epoch());
698     beginDate = newBeginDuration.count();
699 
700     auto newEndDuration = std::chrono::duration_cast<std::chrono::milliseconds>(newEndTimePoint.time_since_epoch());
701     endDate = newEndDuration.count();
702 }
703 
SetDoNotDisturbDate(const sptr<NotificationDoNotDisturbDate> & date)704 ErrCode AdvancedNotificationService::SetDoNotDisturbDate(const sptr<NotificationDoNotDisturbDate> &date)
705 {
706     ANS_LOGD("%{public}s", __FUNCTION__);
707 
708     bool isSubsystem = AccessTokenHelper::VerifyNativeToken(IPCSkeleton::GetCallingTokenID());
709     if (!isSubsystem && !AccessTokenHelper::IsSystemApp()) {
710         ANS_LOGW("Not system app!");
711         return ERR_ANS_NON_SYSTEM_APP;
712     }
713 
714     if (!CheckPermission(OHOS_PERMISSION_NOTIFICATION_CONTROLLER)) {
715         ANS_LOGW("Check permission denied!");
716         return ERR_ANS_PERMISSION_DENIED;
717     }
718 
719     int32_t userId = SUBSCRIBE_USER_INIT;
720     if (!GetActiveUserId(userId)) {
721         ANS_LOGW("No active user found!");
722         return ERR_ANS_GET_ACTIVE_USER_FAILED;
723     }
724 
725     return SetDoNotDisturbDateByUser(userId, date);
726 }
727 
GetDoNotDisturbDate(sptr<NotificationDoNotDisturbDate> & date)728 ErrCode AdvancedNotificationService::GetDoNotDisturbDate(sptr<NotificationDoNotDisturbDate> &date)
729 {
730     ANS_LOGD("%{public}s", __FUNCTION__);
731 
732     bool isSubsystem = AccessTokenHelper::VerifyNativeToken(IPCSkeleton::GetCallingTokenID());
733     if (!isSubsystem && !AccessTokenHelper::IsSystemApp()) {
734         return ERR_ANS_NON_SYSTEM_APP;
735     }
736 
737     if (!CheckPermission(OHOS_PERMISSION_NOTIFICATION_CONTROLLER)) {
738         return ERR_ANS_PERMISSION_DENIED;
739     }
740 
741     int32_t userId = SUBSCRIBE_USER_INIT;
742     if (!GetActiveUserId(userId)) {
743         return ERR_ANS_GET_ACTIVE_USER_FAILED;
744     }
745 
746     return GetDoNotDisturbDateByUser(userId, date);
747 }
748 
DoesSupportDoNotDisturbMode(bool & doesSupport)749 ErrCode AdvancedNotificationService::DoesSupportDoNotDisturbMode(bool &doesSupport)
750 {
751     ANS_LOGD("%{public}s", __FUNCTION__);
752 
753     bool isSubsystem = AccessTokenHelper::VerifyNativeToken(IPCSkeleton::GetCallingTokenID());
754     if (!isSubsystem && !AccessTokenHelper::IsSystemApp()) {
755         return ERR_ANS_NON_SYSTEM_APP;
756     }
757 
758     if (!CheckPermission(OHOS_PERMISSION_NOTIFICATION_CONTROLLER)) {
759         return ERR_ANS_PERMISSION_DENIED;
760     }
761 
762     doesSupport = SUPPORT_DO_NOT_DISTRUB;
763     return ERR_OK;
764 }
765 
CheckPermission(const std::string & permission)766 bool AdvancedNotificationService::CheckPermission(const std::string &permission)
767 {
768     ANS_LOGD("%{public}s", __FUNCTION__);
769     if (supportCheckSaPermission_.compare("true") != 0) {
770         bool isSubsystem = AccessTokenHelper::VerifyNativeToken(IPCSkeleton::GetCallingTokenID());
771         if (isSubsystem) {
772             return true;
773         }
774     }
775     auto tokenCaller = IPCSkeleton::GetCallingTokenID();
776     bool result = AccessTokenHelper::VerifyCallerPermission(tokenCaller, permission);
777     if (!result) {
778         ANS_LOGE("Permission denied");
779     }
780     return result;
781 }
782 
783 #ifdef DISTRIBUTED_NOTIFICATION_SUPPORTED
OnDistributedPublish(const std::string & deviceId,const std::string & bundleName,sptr<NotificationRequest> & request)784 void AdvancedNotificationService::OnDistributedPublish(
785     const std::string &deviceId, const std::string &bundleName, sptr<NotificationRequest> &request)
786 {
787     ANS_LOGD("%{public}s", __FUNCTION__);
788     int32_t activeUserId = -1;
789     if (!GetActiveUserId(activeUserId)) {
790         ANS_LOGE("Failed to get active user id!");
791         return;
792     }
793 
794     if (notificationSvrQueue_ == nullptr) {
795         ANS_LOGE("notificationSvrQueue_ is nullptr.");
796         return;
797     }
798     notificationSvrQueue_->submit(std::bind([this, deviceId, bundleName, request, activeUserId]() {
799         ANS_LOGD("ffrt enter!");
800         if (!CheckDistributedNotificationType(request)) {
801             ANS_LOGD("CheckDistributedNotificationType is false.");
802             return;
803         }
804 
805         int32_t uid = BundleManagerHelper::GetInstance()->GetDefaultUidByBundleName(bundleName, activeUserId);
806         if (uid <= 0) {
807             if (CheckPublishWithoutApp(activeUserId, request)) {
808                 request->SetOwnerBundleName(FOUNDATION_BUNDLE_NAME);
809                 request->SetCreatorBundleName(FOUNDATION_BUNDLE_NAME);
810             } else {
811                 ANS_LOGE("bundle does not exit and make off!");
812                 return;
813             }
814         }
815         std::string bundle = request->GetOwnerBundleName();
816         request->SetCreatorUid(BundleManagerHelper::GetInstance()->GetDefaultUidByBundleName(bundle, activeUserId));
817         sptr<NotificationBundleOption> bundleOption =
818             GenerateValidBundleOption(new NotificationBundleOption(bundle, 0));
819 
820         std::shared_ptr<NotificationRecord> record = std::make_shared<NotificationRecord>();
821         if (record == nullptr) {
822             ANS_LOGD("record is nullptr.");
823             return;
824         }
825         record->request = request;
826         record->notification = new (std::nothrow) Notification(deviceId, request);
827         if (record->notification == nullptr) {
828             ANS_LOGE("Failed to create Notification instance");
829             return;
830         }
831         record->bundleOption = bundleOption;
832         record->deviceId = deviceId;
833         record->bundleName = bundleName;
834         SetNotificationRemindType(record->notification, false);
835 
836         ErrCode result = AssignValidNotificationSlot(record);
837         if (result != ERR_OK) {
838             ANS_LOGE("Can not assign valid slot!");
839             return;
840         }
841 
842         result = Filter(record);
843         if (result != ERR_OK) {
844             ANS_LOGE("Reject by filters: %{public}d", result);
845             return;
846         }
847 
848         result = FlowControl(record);
849         if (result != ERR_OK) {
850             return;
851         }
852 
853         UpdateRecentNotification(record->notification, false, 0);
854         sptr<NotificationSortingMap> sortingMap = GenerateSortingMap();
855         NotificationSubscriberManager::GetInstance()->NotifyConsumed(record->notification, sortingMap);
856     }));
857 }
858 
OnDistributedUpdate(const std::string & deviceId,const std::string & bundleName,sptr<NotificationRequest> & request)859 void AdvancedNotificationService::OnDistributedUpdate(
860     const std::string &deviceId, const std::string &bundleName, sptr<NotificationRequest> &request)
861 {
862     ANS_LOGD("%{public}s", __FUNCTION__);
863     int32_t activeUserId = -1;
864     if (!GetActiveUserId(activeUserId)) {
865         ANS_LOGE("Failed to get active user id!");
866         return;
867     }
868 
869     if (notificationSvrQueue_ == nullptr) {
870         ANS_LOGE("Serial queue is invalid.");
871         return;
872     }
873     notificationSvrQueue_->submit(std::bind([this, deviceId, bundleName, request, activeUserId]() {
874         ANS_LOGD("ffrt enter!");
875         if (!CheckDistributedNotificationType(request)) {
876             ANS_LOGD("device type not support display.");
877             return;
878         }
879 
880         int32_t uid = BundleManagerHelper::GetInstance()->GetDefaultUidByBundleName(bundleName, activeUserId);
881         if (uid <= 0) {
882             if (CheckPublishWithoutApp(activeUserId, request)) {
883                 request->SetOwnerBundleName(FOUNDATION_BUNDLE_NAME);
884                 request->SetCreatorBundleName(FOUNDATION_BUNDLE_NAME);
885             } else {
886                 ANS_LOGE("bundle does not exit and enable off!");
887                 return;
888             }
889         }
890         std::string bundle = request->GetOwnerBundleName();
891         request->SetCreatorUid(BundleManagerHelper::GetInstance()->GetDefaultUidByBundleName(bundle, activeUserId));
892         sptr<NotificationBundleOption> bundleOption =
893             GenerateValidBundleOption(new NotificationBundleOption(bundle, 0));
894 
895         std::shared_ptr<NotificationRecord> record = std::make_shared<NotificationRecord>();
896         if (record == nullptr) {
897             return;
898         }
899         record->request = request;
900         record->notification = new (std::nothrow) Notification(deviceId, request);
901         if (record->notification == nullptr) {
902             ANS_LOGE("Failed to create Notification instance");
903             return;
904         }
905         record->bundleOption = bundleOption;
906         record->deviceId = deviceId;
907         record->bundleName = bundleName;
908         SetNotificationRemindType(record->notification, false);
909 
910         ErrCode result = AssignValidNotificationSlot(record);
911         if (result != ERR_OK) {
912             ANS_LOGE("Can not assign valid slot!");
913             return;
914         }
915 
916         result = Filter(record);
917         if (result != ERR_OK) {
918             ANS_LOGE("Reject by filters: %{public}d", result);
919             return;
920         }
921 
922         if (IsNotificationExists(record->notification->GetKey())) {
923             if (record->request->IsAlertOneTime()) {
924                 record->notification->SetEnableLight(false);
925                 record->notification->SetEnableSound(false);
926                 record->notification->SetEnableVibration(false);
927             }
928             UpdateInNotificationList(record);
929         }
930 
931         UpdateRecentNotification(record->notification, false, 0);
932         sptr<NotificationSortingMap> sortingMap = GenerateSortingMap();
933         NotificationSubscriberManager::GetInstance()->NotifyConsumed(record->notification, sortingMap);
934     }));
935 }
936 
OnDistributedDelete(const std::string & deviceId,const std::string & bundleName,const std::string & label,int32_t id)937 void AdvancedNotificationService::OnDistributedDelete(
938     const std::string &deviceId, const std::string &bundleName, const std::string &label, int32_t id)
939 {
940     ANS_LOGD("%{public}s", __FUNCTION__);
941     if (notificationSvrQueue_ == nullptr) {
942         ANS_LOGE("Serial queue is invalid.");
943         return;
944     }
945     notificationSvrQueue_->submit(std::bind([this, deviceId, bundleName, label, id]() {
946         ANS_LOGD("ffrt enter!");
947         int32_t activeUserId = -1;
948         if (!GetActiveUserId(activeUserId)) {
949             ANS_LOGE("Failed to get active user id!");
950             return;
951         }
952         int32_t uid = BundleManagerHelper::GetInstance()->GetDefaultUidByBundleName(bundleName, activeUserId);
953         std::string bundle = (uid > 0) ? bundleName : FOUNDATION_BUNDLE_NAME;
954         sptr<NotificationBundleOption> bundleOption =
955             GenerateValidBundleOption(new NotificationBundleOption(bundle, 0));
956 
957         std::string recordDeviceId;
958         DistributedDatabase::DeviceInfo localDeviceInfo;
959         if (DistributedNotificationManager::GetInstance()->GetLocalDeviceInfo(localDeviceInfo) == ERR_OK &&
960             strcmp(deviceId.c_str(), localDeviceInfo.deviceId) == 0) {
961             recordDeviceId = "";
962         } else {
963             recordDeviceId = deviceId;
964         }
965 
966         sptr<Notification> notification = nullptr;
967         for (auto record : notificationList_) {
968             if ((record->deviceId == recordDeviceId) &&
969                 ((record->bundleOption->GetBundleName() == bundleOption->GetBundleName()) ||
970                 (record->bundleName == bundleName)) &&
971                 (record->bundleOption->GetUid() == bundleOption->GetUid()) &&
972                 (record->notification->GetLabel() == label) && (record->notification->GetId() == id)) {
973                 notification = record->notification;
974                 notificationList_.remove(record);
975                 break;
976             }
977         }
978 
979         if (notification != nullptr) {
980             int32_t reason = NotificationConstant::APP_CANCEL_REASON_OTHER;
981             UpdateRecentNotification(notification, true, reason);
982             NotificationSubscriberManager::GetInstance()->NotifyCanceled(notification, nullptr, reason);
983         }
984     }));
985 }
986 
GetDistributedEnableInApplicationInfo(const sptr<NotificationBundleOption> bundleOption,bool & enable)987 ErrCode AdvancedNotificationService::GetDistributedEnableInApplicationInfo(
988     const sptr<NotificationBundleOption> bundleOption, bool &enable)
989 {
990     int32_t userId = SUBSCRIBE_USER_INIT;
991     OHOS::AccountSA::OsAccountManager::GetOsAccountLocalIdFromUid(bundleOption->GetUid(), userId);
992 
993     if (userId >= SUBSCRIBE_USER_SYSTEM_BEGIN && userId <= SUBSCRIBE_USER_SYSTEM_END) {
994         enable = true;
995     } else {
996         enable = BundleManagerHelper::GetInstance()->GetDistributedNotificationEnabled(
997             bundleOption->GetBundleName(), userId);
998     }
999 
1000     return ERR_OK;
1001 }
1002 
CheckDistributedNotificationType(const sptr<NotificationRequest> & request)1003 bool AdvancedNotificationService::CheckDistributedNotificationType(const sptr<NotificationRequest> &request)
1004 {
1005     auto deviceTypeList = request->GetNotificationDistributedOptions().GetDevicesSupportDisplay();
1006     if (deviceTypeList.empty()) {
1007         return true;
1008     }
1009 
1010     DistributedDatabase::DeviceInfo localDeviceInfo;
1011     DistributedNotificationManager::GetInstance()->GetLocalDeviceInfo(localDeviceInfo);
1012     for (auto device : deviceTypeList) {
1013         if (atoi(device.c_str()) == localDeviceInfo.deviceTypeId) {
1014             return true;
1015         }
1016     }
1017     return false;
1018 }
1019 
CheckPublishWithoutApp(const int32_t userId,const sptr<NotificationRequest> & request)1020 bool AdvancedNotificationService::CheckPublishWithoutApp(const int32_t userId, const sptr<NotificationRequest> &request)
1021 {
1022     bool enabled = false;
1023     DistributedPreferences::GetInstance()->GetSyncEnabledWithoutApp(userId, enabled);
1024     if (!enabled) {
1025         ANS_LOGE("enable is false, userId[%{public}d]", userId);
1026         return false;
1027     }
1028 
1029     std::shared_ptr<AbilityRuntime::WantAgent::WantAgent> wantAgent = request->GetWantAgent();
1030     if (!wantAgent) {
1031         ANS_LOGE("Failed to get wantAgent!");
1032         return false;
1033     }
1034 
1035     std::shared_ptr<AAFwk::Want> want = AbilityRuntime::WantAgent::WantAgentHelper::GetWant(wantAgent);
1036     if (!want || want->GetDeviceId().empty()) {
1037         ANS_LOGE("Failed to get want!");
1038         return false;
1039     }
1040 
1041     return true;
1042 }
1043 
GetLocalNotificationKeys(const sptr<NotificationBundleOption> & bundleOption)1044 std::vector<std::string> AdvancedNotificationService::GetLocalNotificationKeys(
1045     const sptr<NotificationBundleOption> &bundleOption)
1046 {
1047     std::vector<std::string> keys;
1048 
1049     for (auto record : notificationList_) {
1050         if ((bundleOption != nullptr) && (record->bundleOption->GetBundleName() != bundleOption->GetBundleName()) &&
1051             (record->bundleOption->GetUid() != bundleOption->GetUid()) && record->deviceId.empty()) {
1052             continue;
1053         }
1054         keys.push_back(record->notification->GetKey());
1055     }
1056 
1057     return keys;
1058 }
1059 
GetDistributedInfo(const std::string & key,std::string & deviceId,std::string & bundleName)1060 void AdvancedNotificationService::GetDistributedInfo(
1061     const std::string &key, std::string &deviceId, std::string &bundleName)
1062 {
1063     for (auto record : notificationList_) {
1064         if (record->notification->GetKey() == key) {
1065             deviceId = record->deviceId;
1066             bundleName = record->bundleName;
1067             break;
1068         }
1069     }
1070 }
1071 
DoDistributedPublish(const sptr<NotificationBundleOption> bundleOption,const std::shared_ptr<NotificationRecord> record)1072 ErrCode AdvancedNotificationService::DoDistributedPublish(
1073     const sptr<NotificationBundleOption> bundleOption, const std::shared_ptr<NotificationRecord> record)
1074 {
1075     bool appInfoEnable = true;
1076     GetDistributedEnableInApplicationInfo(bundleOption, appInfoEnable);
1077     if (!appInfoEnable) {
1078         return ERR_OK;
1079     }
1080 
1081     if (!record->request->GetNotificationDistributedOptions().IsDistributed()) {
1082         return ERR_OK;
1083     }
1084 
1085     ErrCode result;
1086     bool distributedEnable = false;
1087     result = DistributedPreferences::GetInstance()->GetDistributedEnable(distributedEnable);
1088     if (result != ERR_OK || !distributedEnable) {
1089         return result;
1090     }
1091 
1092     bool bundleDistributedEnable = false;
1093     result = DistributedPreferences::GetInstance()->GetDistributedBundleEnable(bundleOption, bundleDistributedEnable);
1094     if (result != ERR_OK || !bundleDistributedEnable) {
1095         return result;
1096     }
1097 
1098     return DistributedNotificationManager::GetInstance()->Publish(record->notification->GetBundleName(),
1099         record->notification->GetLabel(),
1100         record->notification->GetId(),
1101         record->request);
1102 }
1103 
DoDistributedDelete(const std::string deviceId,const std::string bundleName,const sptr<Notification> notification)1104 ErrCode AdvancedNotificationService::DoDistributedDelete(
1105     const std::string deviceId, const std::string bundleName, const sptr<Notification> notification)
1106 {
1107     HITRACE_METER_NAME(HITRACE_TAG_NOTIFICATION, __PRETTY_FUNCTION__);
1108     if (!notification->GetNotificationRequest().GetNotificationDistributedOptions().IsDistributed()) {
1109         return ERR_OK;
1110     }
1111     if (deviceId.empty()) {
1112         return DistributedNotificationManager::GetInstance()->Delete(
1113             notification->GetBundleName(), notification->GetLabel(), notification->GetId());
1114     } else {
1115         return DistributedNotificationManager::GetInstance()->DeleteRemoteNotification(
1116             deviceId, bundleName, notification->GetLabel(), notification->GetId());
1117     }
1118 
1119     return ERR_OK;
1120 }
1121 #endif
1122 
PrepareContinuousTaskNotificationRequest(const sptr<NotificationRequest> & request,const int32_t & uid)1123 ErrCode AdvancedNotificationService::PrepareContinuousTaskNotificationRequest(
1124     const sptr<NotificationRequest> &request, const int32_t &uid)
1125 {
1126     int32_t pid = IPCSkeleton::GetCallingPid();
1127     request->SetCreatorUid(uid);
1128     request->SetCreatorPid(pid);
1129     if (request->GetDeliveryTime() <= 0) {
1130         request->SetDeliveryTime(GetCurrentTime());
1131     }
1132 
1133     ErrCode result = CheckPictureSize(request);
1134     return result;
1135 }
1136 
IsSupportTemplate(const std::string & templateName,bool & support)1137 ErrCode AdvancedNotificationService::IsSupportTemplate(const std::string& templateName, bool &support)
1138 {
1139     ANS_LOGD("%{public}s", __FUNCTION__);
1140     if (notificationSvrQueue_ == nullptr) {
1141         ANS_LOGE("Serial queue is invalid.");
1142         return ERR_ANS_INVALID_PARAM;
1143     }
1144     ErrCode result = ERR_OK;
1145     ffrt::task_handle handler = notificationSvrQueue_->submit_h(std::bind([&]() {
1146         ANS_LOGD("ffrt enter!");
1147         support = false;
1148         result = NotificationPreferences::GetInstance().GetTemplateSupported(templateName, support);
1149     }));
1150     notificationSvrQueue_->wait(handler);
1151     return result;
1152 }
1153 
GetActiveUserId(int & userId)1154 bool AdvancedNotificationService::GetActiveUserId(int& userId)
1155 {
1156     std::vector<int> activeUserId;
1157     OHOS::AccountSA::OsAccountManager::QueryActiveOsAccountIds(activeUserId);
1158     if (activeUserId.size() > 0) {
1159         userId = activeUserId[0];
1160         ANS_LOGD("Return active userId=%{public}d", userId);
1161         return true;
1162     }
1163     return false;
1164 }
1165 
TriggerRemoveWantAgent(const sptr<NotificationRequest> & request)1166 void AdvancedNotificationService::TriggerRemoveWantAgent(const sptr<NotificationRequest> &request)
1167 {
1168     HITRACE_METER_NAME(HITRACE_TAG_NOTIFICATION, __PRETTY_FUNCTION__);
1169     ANS_LOGD("%{public}s", __FUNCTION__);
1170 
1171     if ((request == nullptr) || (request->GetRemovalWantAgent() == nullptr)) {
1172         return;
1173     }
1174     OHOS::AbilityRuntime::WantAgent::TriggerInfo triggerInfo;
1175     std::shared_ptr<AbilityRuntime::WantAgent::WantAgent> agent = request->GetRemovalWantAgent();
1176     AbilityRuntime::WantAgent::WantAgentHelper::TriggerWantAgent(agent, nullptr, triggerInfo);
1177 }
1178 
OnResourceRemove(int32_t userId)1179 void AdvancedNotificationService::OnResourceRemove(int32_t userId)
1180 {
1181     DeleteAllByUser(userId);
1182 
1183     if (notificationSvrQueue_ == nullptr) {
1184         ANS_LOGE("Serial queue is invalid.");
1185         return;
1186     }
1187     ffrt::task_handle handler = notificationSvrQueue_->submit_h(std::bind([&]() {
1188         ANS_LOGD("ffrt enter!");
1189         NotificationPreferences::GetInstance().RemoveSettings(userId);
1190     }));
1191     notificationSvrQueue_->wait(handler);
1192 }
1193 
OnBundleDataCleared(const sptr<NotificationBundleOption> & bundleOption)1194 void AdvancedNotificationService::OnBundleDataCleared(const sptr<NotificationBundleOption> &bundleOption)
1195 {
1196     if (notificationSvrQueue_ == nullptr) {
1197         ANS_LOGE("Serial queue is invalid.");
1198         return;
1199     }
1200     ffrt::task_handle handler = notificationSvrQueue_->submit_h(std::bind([&]() {
1201         ANS_LOGD("ffrt enter!");
1202         std::vector<std::string> keys = GetNotificationKeys(bundleOption);
1203         std::vector<sptr<Notification>> notifications;
1204         for (auto key : keys) {
1205 #ifdef DISTRIBUTED_NOTIFICATION_SUPPORTED
1206             std::string deviceId;
1207             std::string bundleName;
1208             GetDistributedInfo(key, deviceId, bundleName);
1209 #endif
1210             sptr<Notification> notification = nullptr;
1211 
1212             ErrCode result = RemoveFromNotificationList(key, notification, true,
1213                 NotificationConstant::PACKAGE_CHANGED_REASON_DELETE);
1214             if (result != ERR_OK) {
1215                 continue;
1216             }
1217 
1218             if (notification != nullptr) {
1219                 int32_t reason = NotificationConstant::PACKAGE_CHANGED_REASON_DELETE;
1220                 UpdateRecentNotification(notification, true, reason);
1221                 notifications.emplace_back(notification);
1222 #ifdef DISTRIBUTED_NOTIFICATION_SUPPORTED
1223                 DoDistributedDelete(deviceId, bundleName, notification);
1224 #endif
1225             }
1226             if (notifications.size() >= MAX_CANCELED_PARCELABLE_VECTOR_NUM) {
1227                 std::vector<sptr<Notification>> currNotificationList = notifications;
1228                 NotificationSubscriberManager::GetInstance()->BatchNotifyCanceled(
1229                     currNotificationList, nullptr, NotificationConstant::PACKAGE_CHANGED_REASON_DELETE);
1230                 notifications.clear();
1231             }
1232         }
1233 
1234         if (!notifications.empty()) {
1235             NotificationSubscriberManager::GetInstance()->BatchNotifyCanceled(
1236                 notifications, nullptr, NotificationConstant::PACKAGE_CHANGED_REASON_DELETE);
1237         }
1238     }));
1239     notificationSvrQueue_->wait(handler);
1240 }
1241 
CheckApiCompatibility(const sptr<NotificationBundleOption> & bundleOption)1242 bool AdvancedNotificationService::CheckApiCompatibility(const sptr<NotificationBundleOption> &bundleOption)
1243 {
1244     ANS_LOGD("%{public}s", __FUNCTION__);
1245     std::shared_ptr<BundleManagerHelper> bundleManager = BundleManagerHelper::GetInstance();
1246     if (bundleManager == nullptr) {
1247         return false;
1248     }
1249     return bundleManager->CheckApiCompatibility(bundleOption);
1250 }
1251 
DeleteAllByUser(const int32_t & userId)1252 ErrCode AdvancedNotificationService::DeleteAllByUser(const int32_t &userId)
1253 {
1254     ANS_LOGD("%{public}s", __FUNCTION__);
1255 
1256     bool isSubsystem = AccessTokenHelper::VerifyNativeToken(IPCSkeleton::GetCallingTokenID());
1257     if (!isSubsystem && !AccessTokenHelper::IsSystemApp()) {
1258         return ERR_ANS_NON_SYSTEM_APP;
1259     }
1260 
1261     if (userId <= SUBSCRIBE_USER_INIT) {
1262         ANS_LOGE("Input userId is invalid.");
1263         return ERR_ANS_INVALID_PARAM;
1264     }
1265 
1266     if (notificationSvrQueue_ == nullptr) {
1267         ANS_LOGE("Serial queue is invalid.");
1268         return ERR_ANS_INVALID_PARAM;
1269     }
1270     ErrCode result = ERR_OK;
1271     ffrt::task_handle handler = notificationSvrQueue_->submit_h(std::bind([&]() {
1272         ANS_LOGD("ffrt enter!");
1273         std::vector<std::string> keys = GetNotificationKeys(nullptr);
1274         std::vector<sptr<Notification>> notifications;
1275         for (auto key : keys) {
1276 #ifdef DISTRIBUTED_NOTIFICATION_SUPPORTED
1277             std::string deviceId;
1278             std::string bundleName;
1279             GetDistributedInfo(key, deviceId, bundleName);
1280 #endif
1281             sptr<Notification> notification = nullptr;
1282 
1283             result = RemoveFromNotificationListForDeleteAll(key, userId, notification);
1284             if ((result != ERR_OK) || (notification == nullptr)) {
1285                 continue;
1286             }
1287 
1288             if (notification->GetUserId() == userId) {
1289                 int32_t reason = NotificationConstant::CANCEL_ALL_REASON_DELETE;
1290                 UpdateRecentNotification(notification, true, reason);
1291                 notifications.emplace_back(notification);
1292 #ifdef DISTRIBUTED_NOTIFICATION_SUPPORTED
1293                 DoDistributedDelete(deviceId, bundleName, notification);
1294 #endif
1295             }
1296             if (notifications.size() >= MAX_CANCELED_PARCELABLE_VECTOR_NUM) {
1297                 SendNotificationsOnCanceled(notifications, nullptr, NotificationConstant::CANCEL_ALL_REASON_DELETE);
1298             }
1299         }
1300 
1301         if (!notifications.empty()) {
1302             NotificationSubscriberManager::GetInstance()->BatchNotifyCanceled(
1303                 notifications, nullptr, NotificationConstant::CANCEL_ALL_REASON_DELETE);
1304         }
1305 
1306         result = ERR_OK;
1307     }));
1308     notificationSvrQueue_->wait(handler);
1309 
1310     return result;
1311 }
1312 
ShellDump(const std::string & cmd,const std::string & bundle,int32_t userId,std::vector<std::string> & dumpInfo)1313 ErrCode AdvancedNotificationService::ShellDump(const std::string &cmd, const std::string &bundle, int32_t userId,
1314     std::vector<std::string> &dumpInfo)
1315 {
1316     ANS_LOGD("%{public}s", __FUNCTION__);
1317 
1318     auto callerToken = IPCSkeleton::GetCallingTokenID();
1319     if (!AccessTokenHelper::VerifyShellToken(callerToken) && !AccessTokenHelper::VerifyNativeToken(callerToken)) {
1320         ANS_LOGE("Not subsystem or shell request");
1321         return ERR_ANS_PERMISSION_DENIED;
1322     }
1323 
1324     if (notificationSvrQueue_ == nullptr) {
1325         ANS_LOGE("Serial queue is invalid.");
1326         return ERR_ANS_INVALID_PARAM;
1327     }
1328     ErrCode result = ERR_ANS_NOT_ALLOWED;
1329     ffrt::task_handle handler = notificationSvrQueue_->submit_h(std::bind([&]() {
1330         ANS_LOGD("ffrt enter!");
1331         if (cmd == ACTIVE_NOTIFICATION_OPTION) {
1332             result = ActiveNotificationDump(bundle, userId, dumpInfo);
1333         } else if (cmd == RECENT_NOTIFICATION_OPTION) {
1334             result = RecentNotificationDump(bundle, userId, dumpInfo);
1335 #ifdef DISTRIBUTED_NOTIFICATION_SUPPORTED
1336         } else if (cmd == DISTRIBUTED_NOTIFICATION_OPTION) {
1337             result = DistributedNotificationDump(bundle, userId, dumpInfo);
1338 #endif
1339         } else if (cmd.substr(0, cmd.find_first_of(" ", 0)) == SET_RECENT_COUNT_OPTION) {
1340             result = SetRecentNotificationCount(cmd.substr(cmd.find_first_of(" ", 0) + 1));
1341         } else {
1342             result = ERR_ANS_INVALID_PARAM;
1343         }
1344     }));
1345     notificationSvrQueue_->wait(handler);
1346     return result;
1347 }
1348 
Dump(int fd,const std::vector<std::u16string> & args)1349 int AdvancedNotificationService::Dump(int fd, const std::vector<std::u16string> &args)
1350 {
1351     ANS_LOGD("enter");
1352     std::string result;
1353     GetDumpInfo(args, result);
1354     int ret = dprintf(fd, "%s\n", result.c_str());
1355     if (ret < 0) {
1356         ANS_LOGE("dprintf error");
1357         return ERR_ANS_INVALID_PARAM;
1358     }
1359     return ERR_OK;
1360 }
1361 
GetDumpInfo(const std::vector<std::u16string> & args,std::string & result)1362 void AdvancedNotificationService::GetDumpInfo(const std::vector<std::u16string> &args, std::string &result)
1363 {
1364     if (args.size() != 1) {
1365         result = HIDUMPER_ERR_MSG;
1366         return;
1367     }
1368     std::vector<std::string> dumpInfo;
1369     std::string cmd = Str16ToStr8(args.front());
1370     if (HIDUMPER_CMD_MAP.find(cmd) == HIDUMPER_CMD_MAP.end()) {
1371         result = HIDUMPER_ERR_MSG;
1372         return;
1373     }
1374     std::string cmdValue = HIDUMPER_CMD_MAP.find(cmd)->second;
1375     if (cmdValue == HELP_NOTIFICATION_OPTION) {
1376         result = HIDUMPER_HELP_MSG;
1377     }
1378     ShellDump(cmdValue, "", SUBSCRIBE_USER_INIT, dumpInfo);
1379     if (dumpInfo.empty()) {
1380         result.append("no notification\n");
1381         return;
1382     }
1383     int32_t index = 0;
1384     result.append("notification list:\n");
1385     for (const auto &info: dumpInfo) {
1386         result.append("No." + std::to_string(++index) + "\n");
1387         result.append(info);
1388     }
1389 }
1390 
SetDoNotDisturbDateByUser(const int32_t & userId,const sptr<NotificationDoNotDisturbDate> & date)1391 ErrCode AdvancedNotificationService::SetDoNotDisturbDateByUser(const int32_t &userId,
1392     const sptr<NotificationDoNotDisturbDate> &date)
1393 {
1394     ANS_LOGD("%{public}s enter, userId = %{public}d", __FUNCTION__, userId);
1395     if (date == nullptr) {
1396         ANS_LOGE("Invalid date param");
1397         return ERR_ANS_INVALID_PARAM;
1398     }
1399 
1400     ErrCode result = ERR_OK;
1401 
1402     int64_t beginDate = ResetSeconds(date->GetBeginDate());
1403     int64_t endDate = ResetSeconds(date->GetEndDate());
1404     switch (date->GetDoNotDisturbType()) {
1405         case NotificationConstant::DoNotDisturbType::NONE:
1406             beginDate = 0;
1407             endDate = 0;
1408             break;
1409         case NotificationConstant::DoNotDisturbType::ONCE:
1410             AdjustDateForDndTypeOnce(beginDate, endDate);
1411             break;
1412         case NotificationConstant::DoNotDisturbType::CLEARLY:
1413             if (beginDate >= endDate) {
1414                 return ERR_ANS_INVALID_PARAM;
1415             }
1416             break;
1417         default:
1418             break;
1419     }
1420     ANS_LOGD("Before set SetDoNotDisturbDate beginDate = %{public}" PRId64 ", endDate = %{public}" PRId64,
1421              beginDate, endDate);
1422     const sptr<NotificationDoNotDisturbDate> newConfig = new (std::nothrow) NotificationDoNotDisturbDate(
1423         date->GetDoNotDisturbType(),
1424         beginDate,
1425         endDate
1426     );
1427     if (newConfig == nullptr) {
1428         ANS_LOGE("Failed to create NotificationDoNotDisturbDate instance");
1429         return ERR_NO_MEMORY;
1430     }
1431 
1432     sptr<NotificationBundleOption> bundleOption = GenerateBundleOption();
1433     if (bundleOption == nullptr) {
1434         ANS_LOGE("Generate invalid bundle option!");
1435         return ERR_ANS_INVALID_BUNDLE;
1436     }
1437 
1438     if (notificationSvrQueue_ == nullptr) {
1439         ANS_LOGE("Serial queue is invalid.");
1440         return ERR_ANS_INVALID_PARAM;
1441     }
1442     ffrt::task_handle handler = notificationSvrQueue_->submit_h(std::bind([&]() {
1443         ANS_LOGD("ffrt enter!");
1444         result = NotificationPreferences::GetInstance().SetDoNotDisturbDate(userId, newConfig);
1445         if (result == ERR_OK) {
1446             NotificationSubscriberManager::GetInstance()->NotifyDoNotDisturbDateChanged(newConfig);
1447         }
1448     }));
1449     notificationSvrQueue_->wait(handler);
1450 
1451     return ERR_OK;
1452 }
1453 
GetDoNotDisturbDateByUser(const int32_t & userId,sptr<NotificationDoNotDisturbDate> & date)1454 ErrCode AdvancedNotificationService::GetDoNotDisturbDateByUser(const int32_t &userId,
1455     sptr<NotificationDoNotDisturbDate> &date)
1456 {
1457     ErrCode result = ERR_OK;
1458     if (notificationSvrQueue_ == nullptr) {
1459         ANS_LOGE("Serial queue is invalid.");
1460         return ERR_ANS_INVALID_PARAM;
1461     }
1462     ffrt::task_handle handler = notificationSvrQueue_->submit_h(std::bind([&]() {
1463         ANS_LOGD("ffrt enter!");
1464         sptr<NotificationDoNotDisturbDate> currentConfig = nullptr;
1465         result = NotificationPreferences::GetInstance().GetDoNotDisturbDate(userId, currentConfig);
1466         if (result == ERR_OK) {
1467             int64_t now = GetCurrentTime();
1468             switch (currentConfig->GetDoNotDisturbType()) {
1469                 case NotificationConstant::DoNotDisturbType::CLEARLY:
1470                 case NotificationConstant::DoNotDisturbType::ONCE:
1471                     if (now >= currentConfig->GetEndDate()) {
1472                         date = new (std::nothrow) NotificationDoNotDisturbDate(
1473                             NotificationConstant::DoNotDisturbType::NONE, 0, 0);
1474                         if (date == nullptr) {
1475                             ANS_LOGE("Failed to create NotificationDoNotDisturbDate instance");
1476                             return;
1477                         }
1478                         NotificationPreferences::GetInstance().SetDoNotDisturbDate(userId, date);
1479                     } else {
1480                         date = currentConfig;
1481                     }
1482                     break;
1483                 default:
1484                     date = currentConfig;
1485                     break;
1486             }
1487         }
1488     }));
1489     notificationSvrQueue_->wait(handler);
1490 
1491     return ERR_OK;
1492 }
1493 
PrePublishNotificationBySa(const sptr<NotificationRequest> & request,int32_t uid,std::string & bundle)1494 ErrCode AdvancedNotificationService::PrePublishNotificationBySa(const sptr<NotificationRequest> &request,
1495     int32_t uid, std::string &bundle)
1496 {
1497     std::shared_ptr<BundleManagerHelper> bundleManager = BundleManagerHelper::GetInstance();
1498     if (bundleManager == nullptr) {
1499         ANS_LOGE("failed to get bundleManager!");
1500         return ERR_ANS_INVALID_BUNDLE;
1501     }
1502     bundle = bundleManager->GetBundleNameByUid(uid);
1503     if (!bundle.empty()) {
1504         if (request->GetCreatorBundleName().empty()) {
1505             request->SetCreatorBundleName(bundle);
1506         }
1507         if (request->GetOwnerBundleName().empty()) {
1508             request->SetOwnerBundleName(bundle);
1509         }
1510     } else {
1511         if (!request->GetCreatorBundleName().empty()) {
1512             bundle = request->GetCreatorBundleName();
1513         }
1514         if (!request->GetOwnerBundleName().empty()) {
1515             bundle = request->GetOwnerBundleName();
1516         }
1517     }
1518 
1519     request->SetCreatorPid(IPCSkeleton::GetCallingPid());
1520     int32_t userId = SUBSCRIBE_USER_INIT;
1521     if (request->GetCreatorUserId() == SUBSCRIBE_USER_INIT) {
1522         if (request->GetCreatorUid() != 0) {
1523             OHOS::AccountSA::OsAccountManager::GetOsAccountLocalIdFromUid(request->GetCreatorUid(), userId);
1524         } else {
1525             OHOS::AccountSA::OsAccountManager::GetOsAccountLocalIdFromUid(IPCSkeleton::GetCallingUid(), userId);
1526         }
1527         request->SetCreatorUserId(userId);
1528     } else {
1529         userId = request->GetCreatorUserId();
1530     }
1531 
1532     if (request->GetDeliveryTime() <= 0) {
1533         request->SetDeliveryTime(GetCurrentTime());
1534     }
1535     ErrCode result = CheckPictureSize(request);
1536     if (result != ERR_OK) {
1537         ANS_LOGE("Failed to check picture size");
1538         return result;
1539     }
1540     ANS_LOGD("creator uid=%{public}d, userId=%{public}d, bundleName=%{public}s ", uid, userId, bundle.c_str());
1541     return ERR_OK;
1542 }
1543 
StartAutoDelete(const std::string & key,int64_t deleteTimePoint,int32_t reason)1544 uint64_t AdvancedNotificationService::StartAutoDelete(const std::string &key, int64_t deleteTimePoint, int32_t reason)
1545 {
1546     ANS_LOGD("Enter");
1547 
1548     auto triggerFunc = [this, key, reason] { TriggerAutoDelete(key, reason); };
1549     std::shared_ptr<NotificationTimerInfo> notificationTimerInfo = std::make_shared<NotificationTimerInfo>();
1550     notificationTimerInfo->SetCallbackInfo(triggerFunc);
1551 
1552     sptr<MiscServices::TimeServiceClient> timer = MiscServices::TimeServiceClient::GetInstance();
1553     if (timer == nullptr) {
1554         ANS_LOGE("Failed to start timer due to get TimeServiceClient is null.");
1555         return 0;
1556     }
1557     uint64_t timerId = timer->CreateTimer(notificationTimerInfo);
1558     timer->StartTimer(timerId, deleteTimePoint);
1559     return timerId;
1560 }
1561 
CancelAutoDeleteTimer(uint64_t timerId)1562 void AdvancedNotificationService::CancelAutoDeleteTimer(uint64_t timerId)
1563 {
1564     ANS_LOGD("Enter");
1565     if (timerId == NotificationConstant::INVALID_TIMER_ID) {
1566         return;
1567     }
1568     MiscServices::TimeServiceClient::GetInstance()->StopTimer(timerId);
1569     MiscServices::TimeServiceClient::GetInstance()->DestroyTimer(timerId);
1570 }
1571 
SendNotificationsOnCanceled(std::vector<sptr<Notification>> & notifications,const sptr<NotificationSortingMap> & notificationMap,int32_t deleteReason)1572 void AdvancedNotificationService::SendNotificationsOnCanceled(std::vector<sptr<Notification>> &notifications,
1573     const sptr<NotificationSortingMap> &notificationMap, int32_t deleteReason)
1574 {
1575     std::vector<sptr<Notification>> currNotifications;
1576     for (auto notification : notifications) {
1577         currNotifications.emplace_back(notification);
1578     }
1579     NotificationSubscriberManager::GetInstance()->BatchNotifyCanceled(
1580         currNotifications, nullptr, deleteReason);
1581     notifications.clear();
1582 }
1583 
InitNotificationEnableList()1584 void AdvancedNotificationService::InitNotificationEnableList()
1585 {
1586     auto task = []() {
1587         auto bundleMgr = BundleManagerHelper::GetInstance();
1588         if (bundleMgr == nullptr) {
1589             ANS_LOGE("Get bundle mgr error!");
1590             return;
1591         }
1592         std::vector<int32_t> activeUserId;
1593         AccountSA::OsAccountManager::QueryActiveOsAccountIds(activeUserId);
1594         if (activeUserId.empty()) {
1595             activeUserId.push_back(MAIN_USER_ID);
1596         }
1597         AppExecFwk::BundleFlag flag = AppExecFwk::BundleFlag::GET_BUNDLE_DEFAULT;
1598         std::vector<AppExecFwk::BundleInfo> bundleInfos;
1599         for (auto &itemUser: activeUserId) {
1600             std::vector<AppExecFwk::BundleInfo> infos;
1601             if (!bundleMgr->GetBundleInfos(flag, infos, itemUser)) {
1602                 ANS_LOGW("Get bundle infos error");
1603                 continue;
1604             }
1605             bundleInfos.insert(bundleInfos.end(), infos.begin(), infos.end());
1606         }
1607         bool notificationEnable = false;
1608         ErrCode saveRef = ERR_OK;
1609         for (const auto &bundleInfo : bundleInfos) {
1610             // Currently only the input from the whitelist is written
1611             if (!bundleInfo.applicationInfo.allowEnableNotification) {
1612                 continue;
1613             }
1614             sptr<NotificationBundleOption> bundleOption = new (std::nothrow) NotificationBundleOption(
1615                 bundleInfo.applicationInfo.bundleName, bundleInfo.uid);
1616             if (bundleOption == nullptr) {
1617                 ANS_LOGE("New bundle option obj error! bundlename:%{public}s",
1618                     bundleInfo.applicationInfo.bundleName.c_str());
1619                 continue;
1620             }
1621             saveRef = NotificationPreferences::GetInstance().GetNotificationsEnabledForBundle(
1622                 bundleOption, notificationEnable);
1623             // record already exists
1624             if (saveRef == ERR_OK) {
1625                 continue;
1626             }
1627             saveRef = NotificationPreferences::GetInstance().SetNotificationsEnabledForBundle(
1628                 bundleOption, bundleInfo.applicationInfo.allowEnableNotification);
1629             if (saveRef != ERR_OK) {
1630                 ANS_LOGE("Set enable error! code: %{public}d", saveRef);
1631             }
1632         }
1633     };
1634     notificationSvrQueue_ != nullptr ? notificationSvrQueue_->submit(task) : task();
1635 }
1636 
GetBundleInfoByNotificationBundleOption(const sptr<NotificationBundleOption> & bundleOption,AppExecFwk::BundleInfo & bundleInfo)1637 bool AdvancedNotificationService::GetBundleInfoByNotificationBundleOption(
1638     const sptr<NotificationBundleOption> &bundleOption, AppExecFwk::BundleInfo &bundleInfo)
1639 {
1640     CHECK_BUNDLE_OPTION_IS_INVALID_WITH_RETURN(bundleOption, false)
1641     int32_t callingUserId = -1;
1642     AccountSA::OsAccountManager::GetOsAccountLocalIdFromUid(bundleOption->GetUid(), callingUserId);
1643     auto bundleMgr = BundleManagerHelper::GetInstance();
1644     if (bundleMgr == nullptr) {
1645         ANS_LOGE("bundleMgr instance error!");
1646         return false;
1647     }
1648     if (!bundleMgr->GetBundleInfoByBundleName(bundleOption->GetBundleName(), callingUserId, bundleInfo)) {
1649         ANS_LOGE("Get bundle info error!");
1650         return false;
1651     }
1652     return true;
1653 }
1654 
CheckLocalLiveViewSubscribed(const sptr<NotificationRequest> & request)1655 bool AdvancedNotificationService::CheckLocalLiveViewSubscribed(const sptr<NotificationRequest> &request)
1656 {
1657     if (request->GetSlotType() == NotificationConstant::SlotType::LIVE_VIEW &&
1658         request->GetNotificationType() == NotificationContent::Type::LOCAL_LIVE_VIEW &&
1659         !GetLiveViewSubscribeState(GetClientBundleName())) {
1660         ANS_LOGE("Not subscribe local live view.");
1661         return false;
1662     }
1663     return true;
1664 }
1665 
CheckLocalLiveViewAllowed(const sptr<NotificationRequest> & request)1666 bool AdvancedNotificationService::CheckLocalLiveViewAllowed(const sptr<NotificationRequest> &request)
1667 {
1668     if (request->GetSlotType() == NotificationConstant::SlotType::LIVE_VIEW &&
1669         request->GetNotificationType() == NotificationContent::Type::LOCAL_LIVE_VIEW) {
1670             bool isSubsystem = AccessTokenHelper::VerifyNativeToken(IPCSkeleton::GetCallingTokenID());
1671             if (!isSubsystem && !AccessTokenHelper::IsSystemApp()) {
1672                 ANS_LOGE("Client is not a system app or subsystem");
1673                 return false;
1674             } else {
1675                 return true;
1676             }
1677     }
1678     return true;
1679 }
1680 }  // namespace Notification
1681 }  // namespace OHOS
1682