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