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