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