1 /*
2 * Copyright (c) 2021-2025 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
16 #include "advanced_notification_service.h"
17
18 #include <functional>
19 #include <iomanip>
20 #include <sstream>
21
22 #include "accesstoken_kit.h"
23 #include "ans_const_define.h"
24 #include "ans_inner_errors.h"
25 #include "ans_log_wrapper.h"
26 #include "ans_trace_wrapper.h"
27 #include "errors.h"
28
29 #include "ipc_skeleton.h"
30 #include "notification_bundle_option.h"
31 #include "notification_constant.h"
32 #include "notification_unified_group_Info.h"
33 #include "os_account_manager.h"
34 #ifdef DISTRIBUTED_NOTIFICATION_SUPPORTED
35 #include "distributed_screen_status_manager.h"
36 #endif
37 #include "notification_extension_wrapper.h"
38 #include "notification_local_live_view_subscriber_manager.h"
39 #include "common_event_manager.h"
40 #include "common_event_support.h"
41 #include "common_event_publish_info.h"
42 #include "os_account_manager_helper.h"
43 #include "want_params_wrapper.h"
44 #include "ans_convert_enum.h"
45 #include "notification_analytics_util.h"
46
47 #include "advanced_notification_inline.h"
48 #include "notification_analytics_util.h"
49 #include "advanced_datashare_helper.h"
50 #include "advanced_datashare_helper_ext.h"
51 #include "datashare_result_set.h"
52 #include "parameter.h"
53 #include "parameters.h"
54 #include "system_ability_definition.h"
55 #include "if_system_ability_manager.h"
56 #include "iservice_registry.h"
57 #include "datashare_predicates.h"
58 #include "notification_config_parse.h"
59 #include "advanced_notification_flow_control_service.h"
60 #include "notification_operation_info.h"
61 #include "notification_operation_service.h"
62 #include "bool_wrapper.h"
63 #ifdef ALL_SCENARIO_COLLABORATION
64 #include "distributed_collaboration_service.h"
65 #endif
66
67 namespace OHOS {
68 namespace Notification {
69
70 constexpr uint32_t SECONDS_IN_ONE_DAY = 24 * 60 * 60;
71 const static std::string NOTIFICATION_EVENT_PUSH_AGENT = "notification.event.PUSH_AGENT";
72 const static std::string NOTIFICATION_EVENT_SUBSCRIBER_STATUS = "notification.event.SUBSCRIBER_STATUS";
73 constexpr int32_t RSS_PID = 3051;
74 constexpr int32_t AVSEESAION_PID = 6700;
75 constexpr int32_t TYPE_CODE_DOWNLOAD = 8;
76 constexpr const char *FOCUS_MODE_REPEAT_CALLERS_ENABLE = "1";
77 constexpr const char *CONTACT_DATA = "datashare:///com.ohos.contactsdataability/contacts/contact_data?Proxy=true";
78 constexpr const char *SUPPORT_INTEGELLIGENT_SCENE = "true";
79 constexpr int32_t CLEAR_SLOT_FROM_AVSEESAION = 1;
80 constexpr int32_t CLEAR_SLOT_FROM_RSS = 2;
81 constexpr const char *PERSIST_EDM_NOTIFICATION_DISABLE = "persist.edm.notification_disable";
82
SetDefaultNotificationEnabled(const sptr<NotificationBundleOption> & bundleOption,bool enabled)83 ErrCode AdvancedNotificationService::SetDefaultNotificationEnabled(
84 const sptr<NotificationBundleOption> &bundleOption, bool enabled)
85 {
86 sptr<NotificationBundleOption> bundle = GenerateValidBundleOption(bundleOption);
87 if (bundle == nullptr) {
88 return ERR_ANS_INVALID_BUNDLE;
89 }
90 sptr<EnabledNotificationCallbackData> bundleData =
91 new (std::nothrow) EnabledNotificationCallbackData(bundle->GetBundleName(), bundle->GetUid(), enabled);
92 if (bundleData == nullptr) {
93 ANS_LOGE("Failed to create EnabledNotificationCallbackData instance");
94 return ERR_NO_MEMORY;
95 }
96 SetSlotFlagsTrustlistsAsBundle(bundle);
97 ErrCode result = ERR_OK;
98 NotificationConstant::SWITCH_STATE state = enabled ? NotificationConstant::SWITCH_STATE::SYSTEM_DEFAULT_ON
99 : NotificationConstant::SWITCH_STATE::SYSTEM_DEFAULT_OFF;
100 result = NotificationPreferences::GetInstance()->SetNotificationsEnabledForBundle(bundle, state);
101 if (result == ERR_OK) {
102 NotificationSubscriberManager::GetInstance()->NotifyEnabledNotificationChanged(bundleData);
103 PublishSlotChangeCommonEvent(bundle);
104 }
105
106 SendEnableNotificationHiSysEvent(bundleOption, enabled, result);
107 return result;
108 }
109
SetCollaborateReminderFlag(const sptr<NotificationRequest> & request)110 void AdvancedNotificationService::SetCollaborateReminderFlag(const sptr<NotificationRequest> &request)
111 {
112 ANS_LOGI("Before %{public}s", request->GetKey().c_str());
113 auto flags = std::make_shared<NotificationFlags>();
114 flags->SetReminderFlags(request->GetCollaboratedReminderFlag());
115 request->SetFlags(flags);
116 ANS_LOGI("SetFlags %{public}d %{public}d", flags->GetReminderFlags(),
117 request->GetCollaboratedReminderFlag());
118 }
119
UpdateCollaborateTimerInfo(const std::shared_ptr<NotificationRecord> & record)120 void AdvancedNotificationService::UpdateCollaborateTimerInfo(const std::shared_ptr<NotificationRecord> &record)
121 {
122 if (!record->request->IsCommonLiveView()) {
123 if ((record->request->GetAutoDeletedTime() > GetCurrentTime())) {
124 StartAutoDeletedTimer(record);
125 }
126 return;
127 }
128
129 auto content = record->request->GetContent()->GetNotificationContent();
130 auto liveViewContent = std::static_pointer_cast<NotificationLiveViewContent>(content);
131 auto status = liveViewContent->GetLiveViewStatus();
132 switch (status) {
133 case NotificationLiveViewContent::LiveViewStatus::LIVE_VIEW_CREATE: {
134 if (record->notification->GetFinishTimer() == NotificationConstant::INVALID_TIMER_ID) {
135 SetFinishTimer(record);
136 }
137 if (record->notification->GetUpdateTimer() == NotificationConstant::INVALID_TIMER_ID) {
138 SetUpdateTimer(record);
139 }
140 CancelArchiveTimer(record);
141 return;
142 }
143 case NotificationLiveViewContent::LiveViewStatus::LIVE_VIEW_INCREMENTAL_UPDATE:
144 case NotificationLiveViewContent::LiveViewStatus::LIVE_VIEW_FULL_UPDATE: {
145 if (record->notification->GetFinishTimer() == NotificationConstant::INVALID_TIMER_ID) {
146 int64_t finishedTime = record->request->GetFinishDeadLine();
147 StartFinishTimer(record, finishedTime,
148 NotificationConstant::TRIGGER_EIGHT_HOUR_REASON_DELETE);
149 }
150 CancelUpdateTimer(record);
151 SetUpdateTimer(record);
152 CancelArchiveTimer(record);
153 return;
154 }
155 case NotificationLiveViewContent::LiveViewStatus::LIVE_VIEW_END:
156 CancelUpdateTimer(record);
157 CancelFinishTimer(record);
158 StartArchiveTimer(record);
159 break;
160 default:
161 ANS_LOGE("Invalid status %{public}d.", status);
162 }
163 }
164
SetCollaborateRequest(const sptr<NotificationRequest> & request)165 ErrCode AdvancedNotificationService::SetCollaborateRequest(const sptr<NotificationRequest> &request)
166 {
167 int32_t uid = IPCSkeleton::GetCallingUid();
168 int32_t pid = IPCSkeleton::GetCallingPid();
169 request->SetCreatorUid(uid);
170 if (request->GetCreatorPid() == 0) {
171 request->SetCreatorPid(pid);
172 }
173 if (request->GetOwnerUid() == DEFAULT_UID) {
174 request->SetOwnerUid(uid);
175 }
176
177 int32_t userId = SUBSCRIBE_USER_INIT;
178 OsAccountManagerHelper::GetInstance().GetCurrentActiveUserId(userId);
179 request->SetCreatorUserId(userId);
180 request->SetCreateTime(GetCurrentTime());
181 if (request->GetDeliveryTime() <= 0) {
182 request->SetDeliveryTime(GetCurrentTime());
183 }
184 SetCollaborateReminderFlag(request);
185 return ERR_OK;
186 }
187
CollaborateFilter(const sptr<NotificationRequest> & request)188 ErrCode AdvancedNotificationService::CollaborateFilter(const sptr<NotificationRequest> &request)
189 {
190 auto params = request->GetExtendInfo();
191 if (params == nullptr) {
192 ANS_LOGI("Collaborate filter extend info is null.");
193 return ERR_OK;
194 }
195
196 auto value = params->GetParam("notification_collaboration_check");
197 AAFwk::IBoolean* ao = AAFwk::IBoolean::Query(value);
198 if (ao == nullptr) {
199 ANS_LOGI("Collaborate filter invalid extend info.");
200 return ERR_OK;
201 }
202 if (!AAFwk::Boolean::Unbox(ao)) {
203 ANS_LOGI("Collaborate filter check is false.");
204 return ERR_OK;
205 }
206 bool switchEnabled = false;
207 std::string deviceType = params->GetStringParam("notification_collaboration_deviceType");
208 std::string deviceId = params->GetStringParam("notification_collaboration_deviceId");
209 std::string localType = params->GetStringParam("notification_collaboration_localType");
210 int32_t userId = params->GetIntParam("notification_collaboration_userId", DEFAULT_USER_ID);
211 auto result = NotificationPreferences::GetInstance()->GetDistributedAuthStatus(deviceType,
212 deviceId, userId, switchEnabled);
213 if (result != ERR_OK || !switchEnabled) {
214 ANS_LOGW("Collaborate live view auth %{public}d %{public}d.", result, switchEnabled);
215 return ERR_ANS_NOT_ALLOWED;
216 }
217 switchEnabled = false;
218 NotificationConstant::SlotType slotType = request->GetSlotType();
219 if (slotType == NotificationConstant::SlotType::LIVE_VIEW) {
220 result = NotificationPreferences::GetInstance()->IsDistributedEnabledBySlot(
221 NotificationConstant::SlotType::LIVE_VIEW, localType, switchEnabled);
222 if (result != ERR_OK || !switchEnabled) {
223 ANS_LOGW("Get live view distributed failed %{public}d %{public}d.", result, switchEnabled);
224 return ERR_ANS_NOT_ALLOWED;
225 }
226 return ERR_OK;
227 }
228 NotificationConstant::SWITCH_STATE enable;
229 result = NotificationPreferences::GetInstance()->IsDistributedEnabled(localType, enable);
230 if (result != ERR_OK || enable != NotificationConstant::SWITCH_STATE::USER_MODIFIED_ON) {
231 ANS_LOGW("Get notification distributed failed %{public}d %{public}d.", result, enable);
232 return ERR_ANS_NOT_ALLOWED;
233 }
234 return ERR_OK;
235 }
236
CollaboratePublish(const sptr<NotificationRequest> & request)237 ErrCode AdvancedNotificationService::CollaboratePublish(const sptr<NotificationRequest> &request)
238 {
239 auto tokenCaller = IPCSkeleton::GetCallingTokenID();
240 if (!AccessTokenHelper::VerifyNativeToken(tokenCaller) ||
241 !AccessTokenHelper::VerifyCallerPermission(tokenCaller, OHOS_PERMISSION_NOTIFICATION_CONTROLLER)) {
242 ANS_LOGE("Collaborate publish cheak permission failed.");
243 return ERR_ANS_PERMISSION_DENIED;
244 }
245 std::shared_ptr<NotificationRecord> record = std::make_shared<NotificationRecord>();
246 SetCollaborateRequest(request);
247 record->request = request;
248 sptr<NotificationSlot> slot = new (std::nothrow) NotificationSlot(request->GetSlotType());
249 if (slot == nullptr) {
250 ANS_LOGE("Failed to create NotificationSlot instance");
251 return ERR_NO_MEMORY;
252 }
253 slot->SetAuthorizedStatus(NotificationSlot::AuthorizedStatus::AUTHORIZED);
254 record->slot = slot;
255 record->notification = new (std::nothrow) Notification(request);
256 if (record->notification == nullptr) {
257 ANS_LOGE("Failed to create notification");
258 return ERR_ANS_NO_MEMORY;
259 }
260 record->bundleOption = new (std::nothrow) NotificationBundleOption(request->GetCreatorBundleName(), 0);
261 record->notification->SetKey("ans_distributed" + request->GetDistributedHashCode());
262 if (CollaborateFilter(request) != ERR_OK) {
263 return ERR_ANS_NOT_ALLOWED;
264 }
265 if (notificationSvrQueue_ == nullptr) {
266 return ERR_ANS_INVALID_PARAM;
267 }
268 ffrt::task_handle handler = notificationSvrQueue_->submit_h([&]() {
269 if (DuplicateMsgControl(record->request) == ERR_ANS_DUPLICATE_MSG) {
270 (void)PublishRemoveDuplicateEvent(record);
271 return;
272 }
273 #ifdef ALL_SCENARIO_COLLABORATION
274 if (!DistributedCollaborationService::GetInstance().CheckCollaborativePublish(record->notification)) {
275 return;
276 }
277 #endif
278 if (AssignToNotificationList(record) != ERR_OK) {
279 return;
280 }
281 sptr<NotificationSortingMap> sortingMap = GenerateSortingMap();
282 NotificationSubscriberManager::GetInstance()->NotifyConsumed(record->notification, sortingMap);
283 UpdateCollaborateTimerInfo(record);
284 });
285 notificationSvrQueue_->wait(handler);
286 return ERR_OK;
287 }
288
InitPublishProcess()289 bool AdvancedNotificationService::InitPublishProcess()
290 {
291 if (publishProcess_.size() > 0) {
292 return true;
293 }
294
295 std::shared_ptr<LivePublishProcess> livePublishProcess = LivePublishProcess::GetInstance();
296 if (livePublishProcess == nullptr) {
297 ANS_LOGE("InitPublishProcess fail as livePublishProcess is nullptr.");
298 return false;
299 }
300 publishProcess_.insert_or_assign(NotificationConstant::SlotType::LIVE_VIEW, livePublishProcess);
301 std::shared_ptr<CommonNotificationPublishProcess> commonNotificationPublishProcess =
302 CommonNotificationPublishProcess::GetInstance();
303 if (commonNotificationPublishProcess == nullptr) {
304 ANS_LOGE("InitPublishProcess fail as commonNotificationPublishProcess is nullptr.");
305 publishProcess_.clear();
306 return false;
307 }
308 publishProcess_.insert_or_assign(
309 NotificationConstant::SlotType::SOCIAL_COMMUNICATION, commonNotificationPublishProcess);
310 publishProcess_.insert_or_assign(
311 NotificationConstant::SlotType::SERVICE_REMINDER, commonNotificationPublishProcess);
312 publishProcess_.insert_or_assign(
313 NotificationConstant::SlotType::CONTENT_INFORMATION, commonNotificationPublishProcess);
314 publishProcess_.insert_or_assign(
315 NotificationConstant::SlotType::OTHER, commonNotificationPublishProcess);
316 publishProcess_.insert_or_assign(
317 NotificationConstant::SlotType::CUSTOM, commonNotificationPublishProcess);
318 publishProcess_.insert_or_assign(
319 NotificationConstant::SlotType::CUSTOMER_SERVICE, commonNotificationPublishProcess);
320 publishProcess_.insert_or_assign(
321 NotificationConstant::SlotType::EMERGENCY_INFORMATION, commonNotificationPublishProcess);
322 return true;
323 }
324
IsAllowedNotifyForBundle(const sptr<NotificationBundleOption> & bundleOption,bool & allowed)325 ErrCode AdvancedNotificationService::IsAllowedNotifyForBundle(const sptr<NotificationBundleOption>
326 &bundleOption, bool &allowed)
327 {
328 ANS_LOGD("called");
329 if (bundleOption == nullptr) {
330 return ERR_ANS_INVALID_BUNDLE;
331 }
332
333 int32_t userId = SUBSCRIBE_USER_INIT;
334 if (OsAccountManagerHelper::GetInstance().GetCurrentActiveUserId(userId) != ERR_OK) {
335 ANS_LOGD("GetActiveUserId is false");
336 return ERR_ANS_GET_ACTIVE_USER_FAILED;
337 }
338
339 ErrCode result = ERR_OK;
340 allowed = false;
341 NotificationConstant::SWITCH_STATE state = NotificationConstant::SWITCH_STATE::SYSTEM_DEFAULT_OFF;
342 result = NotificationPreferences::GetInstance()->GetNotificationsEnabled(userId, allowed);
343 if (result == ERR_OK && allowed) {
344 result = NotificationPreferences::GetInstance()->GetNotificationsEnabledForBundle(bundleOption, state);
345 if (result == ERR_OK) {
346 allowed = (state == NotificationConstant::SWITCH_STATE::SYSTEM_DEFAULT_ON ||
347 state == NotificationConstant::SWITCH_STATE::USER_MODIFIED_ON);
348 }
349 if (result == ERR_ANS_PREFERENCES_NOTIFICATION_BUNDLE_NOT_EXIST) {
350 result = ERR_OK;
351 // FA model app can publish notification without user confirm
352 allowed = CheckApiCompatibility(bundleOption);
353 }
354 }
355 return result;
356 }
357
IsNeedSilentInDoNotDisturbMode(const std::string & phoneNumber,int32_t callerType)358 ErrCode AdvancedNotificationService::IsNeedSilentInDoNotDisturbMode(
359 const std::string &phoneNumber, int32_t callerType)
360 {
361 ANS_LOGD("called");
362
363 int32_t callingUid = IPCSkeleton::GetCallingUid();
364 if (callingUid != NotificationConstant::ANS_UID &&
365 !AccessTokenHelper::CheckPermission(OHOS_PERMISSION_NOTIFICATION_CONTROLLER)) {
366 ANS_LOGD("IsNeedSilentInDoNotDisturbMode CheckPermission failed.");
367 return ERR_ANS_PERMISSION_DENIED;
368 }
369
370 int32_t userId = SUBSCRIBE_USER_INIT;
371 if (OsAccountManagerHelper::GetInstance().GetCurrentActiveUserId(userId) != ERR_OK) {
372 ANS_LOGD("GetActiveUserId is false");
373 return ERR_ANS_GET_ACTIVE_USER_FAILED;
374 }
375 return CheckNeedSilent(phoneNumber, callerType, userId);
376 }
377
CheckNeedSilent(const std::string & phoneNumber,int32_t callerType,int32_t userId)378 ErrCode AdvancedNotificationService::CheckNeedSilent(
379 const std::string &phoneNumber, int32_t callerType, int32_t userId)
380 {
381 auto datashareHelper = DelayedSingleton<AdvancedDatashareHelper>::GetInstance();
382 if (datashareHelper == nullptr) {
383 ANS_LOGE("The data share helper is nullptr.");
384 return -1;
385 }
386 int isNeedSilent = 0;
387 std::string policy;
388 Uri policyUri(datashareHelper->GetFocusModeCallPolicyUri(userId));
389 bool ret = datashareHelper->Query(policyUri, KEY_FOCUS_MODE_CALL_MESSAGE_POLICY, policy);
390 if (!ret) {
391 ANS_LOGE("Query focus mode call message policy fail.");
392 return -1;
393 }
394 std::string repeat_call;
395 Uri repeatUri(datashareHelper->GetFocusModeRepeatCallUri(userId));
396 bool repeat_ret = datashareHelper->Query(repeatUri, KEY_FOCUS_MODE_REPEAT_CALLERS_ENABLE, repeat_call);
397 if (!repeat_ret) {
398 ANS_LOGE("Query focus mode repeat callers enable fail.");
399 }
400 ANS_LOGI("IsNeedSilent: policy: %{public}s, repeat: %{public}s, callerType: %{public}d",
401 policy.c_str(), repeat_call.c_str(), callerType);
402 if (repeat_call == FOCUS_MODE_REPEAT_CALLERS_ENABLE && callerType == 0 &&
403 atoi(policy.c_str()) != ContactPolicy::ALLOW_EVERYONE && datashareHelper->isRepeatCall(phoneNumber)) {
404 return 1;
405 }
406 bool isAccountVerified = true;
407 ErrCode account_ret = OHOS::AccountSA::OsAccountManager::IsOsAccountVerified(userId, isAccountVerified);
408 if (account_ret != ERR_OK) {
409 ANS_LOGE("IsOsAccountVerified fail.");
410 }
411 switch (atoi(policy.c_str())) {
412 case ContactPolicy::FORBID_EVERYONE:
413 break;
414 case ContactPolicy::ALLOW_EVERYONE:
415 isNeedSilent = 1;
416 break;
417 case ContactPolicy::ALLOW_EXISTING_CONTACTS:
418 case ContactPolicy::ALLOW_FAVORITE_CONTACTS:
419 case ContactPolicy::ALLOW_SPECIFIED_CONTACTS:
420 isNeedSilent = isAccountVerified ? QueryContactByProfileId(phoneNumber, policy, userId) : 0;
421 break;
422 case ContactPolicy::FORBID_SPECIFIED_CONTACTS:
423 isNeedSilent = isAccountVerified ? QueryContactByProfileId(phoneNumber, policy, userId) : 1;
424 break;
425 }
426 ANS_LOGI("CheckNeedSilent isNeedSilent:%{public}d isAccountVerified:%{public}d", isNeedSilent, isAccountVerified);
427 return isNeedSilent;
428 }
429
QueryContactByProfileId(const std::string & phoneNumber,const std::string & policy,int32_t userId)430 ErrCode AdvancedNotificationService::QueryContactByProfileId(const std::string &phoneNumber,
431 const std::string &policy, int32_t userId)
432 {
433 char buf[256] = { 0 };
434 const std::string ¶mName = "const.intelligentscene.enable";
435 std::string isSupportIntelligentScene = "false";
436 const std::string defaultValue = "false";
437
438 auto res = GetParameter(paramName.c_str(), defaultValue.c_str(), buf, sizeof(buf));
439 if (res <= 0) {
440 ANS_LOGD("isSupportIntelligentScene GetParameter is false");
441 } else {
442 isSupportIntelligentScene = buf;
443 }
444 ANS_LOGI("isSupportIntelligentScene is %{public}s", isSupportIntelligentScene.c_str());
445
446 auto datashareHelper = DelayedSingleton<AdvancedDatashareHelper>::GetInstance();
447 if (datashareHelper == nullptr) {
448 ANS_LOGE("The data share helper is nullptr.");
449 return -1;
450 }
451
452 std::string uri = CONTACT_DATA;
453 if (isSupportIntelligentScene == SUPPORT_INTEGELLIGENT_SCENE &&
454 (atoi(policy.c_str()) == ContactPolicy::ALLOW_SPECIFIED_CONTACTS ||
455 atoi(policy.c_str()) == ContactPolicy::FORBID_SPECIFIED_CONTACTS)) {
456 uri = datashareHelper->GetIntelligentUri();
457 }
458 ANS_LOGI("QueryContactByProfileId uri is %{public}s", uri.c_str());
459
460 std::string profileId;
461 Uri profileIdUri(datashareHelper->GetFocusModeProfileUri(userId));
462 bool profile_ret = datashareHelper->Query(profileIdUri, KEY_FOCUS_MODE_PROFILE, profileId);
463 if (!profile_ret) {
464 ANS_LOGE("Query profile id fail.");
465 return -1;
466 }
467
468 Uri contactUri(uri);
469 return datashareHelper->QueryContact(contactUri, phoneNumber, policy, profileId, isSupportIntelligentScene);
470 }
471
CancelGroup(const std::string & groupName,const std::string & instanceKey)472 ErrCode AdvancedNotificationService::CancelGroup(const std::string &groupName, const std::string &instanceKey)
473 {
474 ANS_LOGD("called");
475
476 int32_t reason = NotificationConstant::APP_CANCEL_GROPU_REASON_DELETE;
477 if (groupName.empty()) {
478 std::string message = "groupName empty.";
479 OHOS::Notification::HaMetaMessage haMetaMessage = HaMetaMessage(3, 1)
480 .ErrorCode(ERR_ANS_INVALID_PARAM);
481 ReportDeleteFailedEventPush(haMetaMessage, reason, message);
482 ANS_LOGE("%{public}s", message.c_str());
483 return ERR_ANS_INVALID_PARAM;
484 }
485
486 sptr<NotificationBundleOption> bundleOption = GenerateBundleOption();
487 if (bundleOption == nullptr) {
488 std::string message = "bundle is nullptr.";
489 OHOS::Notification::HaMetaMessage haMetaMessage = HaMetaMessage(3, 2)
490 .ErrorCode(ERR_ANS_INVALID_BUNDLE);
491 ReportDeleteFailedEventPush(haMetaMessage, reason, message);
492 ANS_LOGE("%{public}s", message.c_str());
493 return ERR_ANS_INVALID_BUNDLE;
494 }
495 bundleOption->SetAppInstanceKey(instanceKey);
496
497 if (notificationSvrQueue_ == nullptr) {
498 std::string message = "Serial queue is invalid.";
499 ANS_LOGE("%{public}s", message.c_str());
500 return ERR_ANS_INVALID_PARAM;
501 }
502
503 ExcuteCancelGroupCancel(bundleOption, groupName, reason);
504 return ERR_OK;
505 }
506
ExcuteCancelGroupCancel(const sptr<NotificationBundleOption> & bundleOption,const std::string & groupName,const int32_t reason)507 void AdvancedNotificationService::ExcuteCancelGroupCancel(
508 const sptr<NotificationBundleOption>& bundleOption,
509 const std::string &groupName, const int32_t reason)
510 {
511 ffrt::task_handle handler = notificationSvrQueue_->submit_h(std::bind([&]() {
512 ANS_LOGD("ffrt enter!");
513 std::vector<std::shared_ptr<NotificationRecord>> removeList;
514 for (auto record : notificationList_) {
515 ANS_LOGD("ExcuteCancelGroupCancel instanceKey(%{public}s, %{public}s).",
516 record->notification->GetInstanceKey().c_str(), bundleOption->GetAppInstanceKey().c_str());
517 if ((record->bundleOption->GetBundleName() == bundleOption->GetBundleName()) &&
518 (record->bundleOption->GetUid() == bundleOption->GetUid()) &&
519 (record->notification->GetInstanceKey() == bundleOption->GetAppInstanceKey()) &&
520 #ifdef DISTRIBUTED_NOTIFICATION_SUPPORTED
521 record->deviceId.empty() &&
522 #endif
523 (record->request->GetGroupName() == groupName)) {
524 removeList.push_back(record);
525 }
526 }
527
528 std::vector<sptr<Notification>> notifications;
529 std::vector<uint64_t> timerIds;
530 for (auto record : removeList) {
531 notificationList_.remove(record);
532 if (record->notification != nullptr) {
533 UpdateRecentNotification(record->notification, true, reason);
534 notifications.emplace_back(record->notification);
535 timerIds.emplace_back(record->notification->GetAutoDeletedTimer());
536 #ifdef DISTRIBUTED_NOTIFICATION_SUPPORTED
537 DoDistributedDelete(record->deviceId, record->bundleName, record->notification);
538 #endif
539 }
540 if (notifications.size() >= MAX_CANCELED_PARCELABLE_VECTOR_NUM) {
541 std::vector<sptr<Notification>> currNotificationList = notifications;
542 NotificationSubscriberManager::GetInstance()->BatchNotifyCanceled(
543 currNotificationList, nullptr, reason);
544 notifications.clear();
545 }
546 }
547
548 if (!notifications.empty()) {
549 NotificationSubscriberManager::GetInstance()->BatchNotifyCanceled(
550 notifications, nullptr, reason);
551 }
552 BatchCancelTimer(timerIds);
553 }));
554 notificationSvrQueue_->wait(handler);
555 }
556
RemoveGroupByBundle(const sptr<NotificationBundleOption> & bundleOption,const std::string & groupName)557 ErrCode AdvancedNotificationService::RemoveGroupByBundle(
558 const sptr<NotificationBundleOption> &bundleOption, const std::string &groupName)
559 {
560 ANS_LOGD("called");
561 const int32_t reason = NotificationConstant::APP_REMOVE_GROUP_REASON_DELETE;
562 bool isSubsystem = AccessTokenHelper::VerifyNativeToken(IPCSkeleton::GetCallingTokenID());
563 if (!isSubsystem && !AccessTokenHelper::IsSystemApp()) {
564 std::string message = "not systemApp.";
565 OHOS::Notification::HaMetaMessage haMetaMessage = HaMetaMessage(5, 1)
566 .ErrorCode(ERR_ANS_NON_SYSTEM_APP);
567 ReportDeleteFailedEventPush(haMetaMessage, reason, message);
568 ANS_LOGE("%{public}s", message.c_str());
569 return ERR_ANS_NON_SYSTEM_APP;
570 }
571
572 if (!AccessTokenHelper::CheckPermission(OHOS_PERMISSION_NOTIFICATION_CONTROLLER)) {
573 std::string message = "no acl permission";
574 OHOS::Notification::HaMetaMessage haMetaMessage = HaMetaMessage(5, 2)
575 .ErrorCode(ERR_ANS_PERMISSION_DENIED);
576 ReportDeleteFailedEventPush(haMetaMessage, reason, message);
577 ANS_LOGE("%{public}s", message.c_str());
578 return ERR_ANS_PERMISSION_DENIED;
579 }
580
581 if (bundleOption == nullptr || groupName.empty()) {
582 std::string message = "groupName empty";
583 OHOS::Notification::HaMetaMessage haMetaMessage = HaMetaMessage(5, 3)
584 .ErrorCode(ERR_ANS_INVALID_PARAM);
585 ReportDeleteFailedEventPush(haMetaMessage, reason, message);
586 ANS_LOGE("%{public}s", message.c_str());
587 return ERR_ANS_INVALID_PARAM;
588 }
589
590 sptr<NotificationBundleOption> bundle = GenerateValidBundleOption(bundleOption);
591 if (bundle == nullptr) {
592 std::string message = "bundle is nullptr";
593 OHOS::Notification::HaMetaMessage haMetaMessage = HaMetaMessage(5, 4)
594 .ErrorCode(ERR_ANS_INVALID_PARAM);
595 ReportDeleteFailedEventPush(haMetaMessage, reason, message);
596 ANS_LOGE("%{public}s", message.c_str());
597 return ERR_ANS_INVALID_BUNDLE;
598 }
599
600 if (notificationSvrQueue_ == nullptr) {
601 std::string message = "Serial queue is invalid.";
602 ANS_LOGE("%{public}s", message.c_str());
603 return ERR_ANS_INVALID_PARAM;
604 }
605 ffrt::task_handle handler = notificationSvrQueue_->submit_h(std::bind([&]() {
606 ANS_LOGD("ffrt enter!");
607 std::vector<std::shared_ptr<NotificationRecord>> removeList;
608 int32_t reason = NotificationConstant::CANCEL_REASON_DELETE;
609 for (auto record : notificationList_) {
610 if (!record->notification->IsRemoveAllowed()) {
611 continue;
612 }
613 if ((record->bundleOption->GetBundleName() == bundle->GetBundleName()) &&
614 (record->bundleOption->GetUid() == bundle->GetUid()) && !record->request->IsUnremovable() &&
615 #ifdef DISTRIBUTED_NOTIFICATION_SUPPORTED
616 record->deviceId.empty() &&
617 #endif
618 (record->request->GetGroupName() == groupName)) {
619 ANS_LOGD("RemoveList push enter.");
620 removeList.push_back(record);
621 }
622 }
623
624 std::vector<sptr<Notification>> notifications;
625 std::vector<uint64_t> timerIds;
626 for (auto record : removeList) {
627 notificationList_.remove(record);
628 ProcForDeleteLiveView(record);
629
630 if (record->notification != nullptr) {
631 UpdateRecentNotification(record->notification, true, reason);
632 notifications.emplace_back(record->notification);
633 timerIds.emplace_back(record->notification->GetAutoDeletedTimer());
634 #ifdef DISTRIBUTED_NOTIFICATION_SUPPORTED
635 DoDistributedDelete(record->deviceId, record->bundleName, record->notification);
636 #endif
637 }
638 if (notifications.size() >= MAX_CANCELED_PARCELABLE_VECTOR_NUM) {
639 SendNotificationsOnCanceled(notifications, nullptr, reason);
640 }
641 }
642
643 if (!notifications.empty()) {
644 NotificationSubscriberManager::GetInstance()->BatchNotifyCanceled(notifications, nullptr, reason);
645 }
646 BatchCancelTimer(timerIds);
647 }));
648 notificationSvrQueue_->wait(handler);
649
650 return ERR_OK;
651 }
652
UpdateUnifiedGroupInfo(const std::string & key,std::shared_ptr<NotificationUnifiedGroupInfo> & groupInfo)653 void AdvancedNotificationService::UpdateUnifiedGroupInfo(const std::string &key,
654 std::shared_ptr<NotificationUnifiedGroupInfo> &groupInfo)
655 {
656 if (notificationSvrQueue_ == nullptr) {
657 ANS_LOGE("Serial queue is invalid.");
658 return;
659 }
660
661 ffrt::task_handle handler = notificationSvrQueue_->submit_h([=]() {
662 for (const auto& item : notificationList_) {
663 if (item->notification->GetKey() == key) {
664 ANS_LOGD("update group info matched key %s", key.c_str());
665 item->notification->GetNotificationRequestPoint()->SetUnifiedGroupInfo(groupInfo);
666
667 CloseAlert(item);
668
669 UpdateRecentNotification(item->notification, false, 0);
670 sptr<NotificationSortingMap> sortingMap = GenerateSortingMap();
671 NotificationSubscriberManager::GetInstance()->NotifyConsumed(item->notification, sortingMap);
672 break;
673 }
674 }
675 });
676 }
677
ClearSlotTypeData(const sptr<NotificationRequest> & request,int32_t callingUid,int32_t sourceType)678 void AdvancedNotificationService::ClearSlotTypeData(const sptr<NotificationRequest> &request, int32_t callingUid,
679 int32_t sourceType)
680 {
681 if (request == nullptr || (sourceType != CLEAR_SLOT_FROM_AVSEESAION && sourceType != CLEAR_SLOT_FROM_RSS)) {
682 return;
683 }
684
685 if (sourceType == CLEAR_SLOT_FROM_AVSEESAION) {
686 if (callingUid != AVSEESAION_PID ||
687 request->GetSlotType() != NotificationConstant::SlotType::LIVE_VIEW) {
688 return;
689 }
690 }
691 if (sourceType == CLEAR_SLOT_FROM_RSS) {
692 if (request->GetCreatorUid() != RSS_PID || !request->IsSystemLiveView()) {
693 return;
694 }
695 }
696
697 int32_t uid = request->GetOwnerUid();
698 std::string bundleName = BundleManagerHelper::GetInstance()->GetBundleNameByUid(uid);
699 sptr<NotificationBundleOption> bundleOption = new (std::nothrow) NotificationBundleOption(bundleName, uid);
700 if (bundleOption == nullptr) {
701 ANS_LOGW("Notification get bundle failed %{public}d", uid);
702 return;
703 }
704
705 if (NotificationPreferences::GetInstance()->GetBundleRemoveFlag(bundleOption,
706 NotificationConstant::SlotType::LIVE_VIEW, sourceType)) {
707 return;
708 }
709 NotificationPreferences::GetInstance()->RemoveNotificationSlot(bundleOption,
710 NotificationConstant::SlotType::LIVE_VIEW);
711 NotificationPreferences::GetInstance()->SetBundleRemoveFlag(bundleOption,
712 NotificationConstant::SlotType::LIVE_VIEW, sourceType);
713 }
714
PublishNotificationBySa(const sptr<NotificationRequest> & request)715 ErrCode AdvancedNotificationService::PublishNotificationBySa(const sptr<NotificationRequest> &request)
716 {
717 ANS_LOGD("called");
718
719 auto tokenCaller = IPCSkeleton::GetCallingTokenID();
720 bool isSystemApp = AccessTokenHelper::IsSystemApp();
721 bool isSubsystem = AccessTokenHelper::VerifyNativeToken(tokenCaller);
722 bool isThirdparty;
723 if (isSystemApp || isSubsystem) {
724 isThirdparty = false;
725 } else {
726 isThirdparty = true;
727 }
728 bool isAgentController = AccessTokenHelper::VerifyCallerPermission(tokenCaller,
729 OHOS_PERMISSION_NOTIFICATION_AGENT_CONTROLLER);
730 HaMetaMessage message = HaMetaMessage(EventSceneId::SCENE_4, EventBranchId::BRANCH_1);
731 int32_t uid = request->GetCreatorUid();
732 if (request->GetOwnerUid() != DEFAULT_UID) {
733 std::shared_ptr<NotificationBundleOption> agentBundle =
734 std::make_shared<NotificationBundleOption>("", uid);
735 request->SetAgentBundle(agentBundle);
736 }
737 bool directAgency = false;
738
739 if (request->IsAgentNotification() || request->GetOwnerUid() != DEFAULT_UID) {
740 uid = request->GetOwnerUid();
741 request->SetIsAgentNotification(false);
742 directAgency = true;
743 }
744 if (uid <= 0) {
745 message.ErrorCode(ERR_ANS_INVALID_UID).Message("createUid failed" + std::to_string(uid), true);
746 NotificationAnalyticsUtil::ReportPublishFailedEvent(request, message);
747 return ERR_ANS_INVALID_UID;
748 }
749 std::string bundle = "";
750 ErrCode result = PrePublishNotificationBySa(request, uid, bundle);
751 if (request->GetCreatorUid() == RSS_PID && request->IsSystemLiveView() &&
752 (std::static_pointer_cast<OHOS::Notification::NotificationLocalLiveViewContent>(
753 request->GetContent()->GetNotificationContent())->GetType() != TYPE_CODE_DOWNLOAD)) {
754 request->SetSlotType(NotificationConstant::SlotType::OTHER);
755 request->GetContent()->ResetToBasicContent();
756 request->SetUnremovable(true);
757 request->SetTapDismissed(false);
758 }
759 if (result != ERR_OK) {
760 return result;
761 }
762
763 // SA not support sound
764 if (!request->GetSound().empty()) {
765 request->SetSound("");
766 }
767 std::shared_ptr<NotificationRecord> record = std::make_shared<NotificationRecord>();
768 record->request = request;
769 record->isThirdparty = isThirdparty;
770 if (directAgency) {
771 record->bundleOption = new (std::nothrow) NotificationBundleOption("", request->GetCreatorUid());
772 } else {
773 #ifdef ENABLE_ANS_ADDITIONAL_CONTROL
774 int32_t ctrlResult = EXTENTION_WRAPPER->LocalControl(request);
775 if (ctrlResult != ERR_OK) {
776 message.ErrorCode(ctrlResult);
777 NotificationAnalyticsUtil::ReportPublishFailedEvent(request, message);
778 return ctrlResult;
779 }
780 #endif
781 record->bundleOption = new (std::nothrow) NotificationBundleOption(bundle, uid);
782 }
783 sptr<NotificationBundleOption> bundleOption = new (std::nothrow) NotificationBundleOption(bundle, uid);
784 if (record->bundleOption == nullptr || bundleOption == nullptr) {
785 ANS_LOGE("Failed to create bundleOption");
786 return ERR_ANS_NO_MEMORY;
787 }
788 record->bundleOption->SetAppInstanceKey(request->GetAppInstanceKey());
789 int32_t ipcUid = IPCSkeleton::GetCallingUid();
790 uint32_t hashCodeGeneratetype = NotificationPreferences::GetInstance()->GetHashCodeRule(ipcUid);
791 request->SetHashCodeGenerateType(hashCodeGeneratetype);
792 record->notification = new (std::nothrow) Notification(request);
793 if (record->notification == nullptr) {
794 ANS_LOGE("Failed to create notification");
795 return ERR_ANS_NO_MEMORY;
796 }
797
798 if (notificationSvrQueue_ == nullptr) {
799 ANS_LOGE("Serial queue is invalid.");
800 return ERR_ANS_INVALID_PARAM;
801 }
802
803 SetRequestBySlotType(record->request, bundleOption);
804 #ifdef ENABLE_ANS_AGGREGATION
805 EXTENTION_WRAPPER->GetUnifiedGroupInfo(request);
806 #endif
807
808 ffrt::task_handle handler = notificationSvrQueue_->submit_h([&]() {
809 if (!bundle.empty() && IsDisableNotification(bundle)) {
810 ANS_LOGE("bundle in Disable Notification list, bundleName=%{public}s", bundle.c_str());
811 result = ERR_ANS_REJECTED_WITH_DISABLE_NOTIFICATION;
812 return;
813 }
814 if (IsDisableNotificationForSaByKiosk(bundle, directAgency)) {
815 ANS_LOGE("bundle not in kiosk trust list, bundleName=%{public}s", bundle.c_str());
816 result = ERR_ANS_REJECTED_WITH_DISABLE_NOTIFICATION;
817 return;
818 }
819 if (!bundleOption->GetBundleName().empty() &&
820 !(request->GetSlotType() == NotificationConstant::SlotType::LIVE_VIEW && directAgency)) {
821 ErrCode ret = AssignValidNotificationSlot(record, bundleOption);
822 if (ret != ERR_OK) {
823 ANS_LOGE("PublishNotificationBySA Can not assign valid slot!");
824 }
825 if (!directAgency) {
826 result = Filter(record);
827 if (result != ERR_OK) {
828 ANS_LOGE("PublishNotificationBySA Reject by filters: %{public}d", result);
829 return;
830 }
831 }
832 }
833
834 NotificationAnalyticsUtil::ReportSAPublishSuccessEvent(record->request, ipcUid);
835 if (!request->IsDoNotDisturbByPassed()) {
836 CheckDoNotDisturbProfile(record);
837 }
838 ChangeNotificationByControlFlags(record, isAgentController);
839 if (IsSaCreateSystemLiveViewAsBundle(record, ipcUid) &&
840 (std::static_pointer_cast<OHOS::Notification::NotificationLocalLiveViewContent>(
841 record->request->GetContent()->GetNotificationContent())->GetType() == TYPE_CODE_DOWNLOAD)) {
842 result = SaPublishSystemLiveViewAsBundle(record);
843 if (result == ERR_OK) {
844 SendLiveViewUploadHiSysEvent(record, UploadStatus::CREATE);
845 }
846 ClearSlotTypeData(record->request, ipcUid, CLEAR_SLOT_FROM_RSS);
847 return;
848 }
849 bool isNotificationExists = IsNotificationExists(record->notification->GetKey());
850 result = FlowControlService::GetInstance().FlowControl(record, ipcUid, isNotificationExists);
851 if (result != ERR_OK) {
852 return;
853 }
854 if (AssignToNotificationList(record) != ERR_OK) {
855 ANS_LOGE("Failed to assign notification list");
856 return;
857 }
858
859 ClearSlotTypeData(record->request, ipcUid, CLEAR_SLOT_FROM_AVSEESAION);
860 UpdateRecentNotification(record->notification, false, 0);
861 sptr<NotificationSortingMap> sortingMap = GenerateSortingMap();
862 NotificationSubscriberManager::GetInstance()->NotifyConsumed(record->notification, sortingMap);
863 if ((record->request->GetAutoDeletedTime() > GetCurrentTime()) && !record->request->IsCommonLiveView()) {
864 StartAutoDeletedTimer(record);
865 }
866 });
867 notificationSvrQueue_->wait(handler);
868 if (result != ERR_OK) {
869 return result;
870 }
871 return ERR_OK;
872 }
873
DuplicateMsgControl(const sptr<NotificationRequest> & request)874 ErrCode AdvancedNotificationService::DuplicateMsgControl(const sptr<NotificationRequest> &request)
875 {
876 if (request->IsCommonLiveView() || request->GetAppMessageId().empty()) {
877 return ERR_OK;
878 }
879
880 RemoveExpiredUniqueKey();
881 RemoveExpiredDistributedUniqueKey();
882 RemoveExpiredLocalUniqueKey();
883 std::string uniqueKey = request->GenerateUniqueKey();
884 std::string distributedUniqueKey = request->GenerateDistributedUniqueKey();
885 std::string localUniqueKey = distributedUniqueKey;
886
887 if (request->GetDistributedCollaborate()) {
888 if (IsDuplicateMsg(distributedUniqueKeyList_, distributedUniqueKey)) {
889 ANS_LOGE("Distributed duplicate msg, no need to notify, key is %{public}s, appmessageId is %{public}s",
890 request->GetKey().c_str(), request->GetAppMessageId().c_str());
891 return ERR_ANS_DUPLICATE_MSG;
892 }
893 localUniqueKeyList_.emplace_back(std::make_pair(std::chrono::system_clock::now(), localUniqueKey));
894 distributedUniqueKeyList_.emplace_back(std::make_pair(std::chrono::system_clock::now(), distributedUniqueKey));
895 } else {
896 if (IsDuplicateMsg(uniqueKeyList_, uniqueKey) || IsDuplicateMsg(localUniqueKeyList_, localUniqueKey)) {
897 ANS_LOGE("Duplicate msg, no need to notify, key is %{public}s, appmessageId is %{public}s",
898 request->GetKey().c_str(), request->GetAppMessageId().c_str());
899 return ERR_ANS_DUPLICATE_MSG;
900 }
901 uniqueKeyList_.emplace_back(std::make_pair(std::chrono::system_clock::now(), uniqueKey));
902 distributedUniqueKeyList_.emplace_back(std::make_pair(std::chrono::system_clock::now(), distributedUniqueKey));
903 }
904 return ERR_OK;
905 }
906
DeleteDuplicateMsgs(const sptr<NotificationBundleOption> & bundleOption)907 void AdvancedNotificationService::DeleteDuplicateMsgs(const sptr<NotificationBundleOption> &bundleOption)
908 {
909 if (bundleOption == nullptr) {
910 ANS_LOGE("bundleOption is nullptr");
911 return;
912 }
913 const char *keySpliter = "_";
914 std::stringstream stream;
915 stream << bundleOption->GetUid() << keySpliter << bundleOption->GetBundleName() << keySpliter;
916 std::string uniqueKeyHead = stream.str();
917 for (auto iter = uniqueKeyList_.begin(); iter != uniqueKeyList_.end();) {
918 if ((*iter).second.find(uniqueKeyHead) == 0) {
919 iter = uniqueKeyList_.erase(iter);
920 } else {
921 ++iter;
922 }
923 }
924
925 stream.str(std::string());
926 stream.clear();
927 stream << bundleOption->GetBundleName() << keySpliter;
928 std::string distributedUniqueKeyHead = stream.str();
929 for (auto iter = distributedUniqueKeyList_.begin(); iter != distributedUniqueKeyList_.end();) {
930 if ((*iter).second.find(distributedUniqueKeyHead) == 0) {
931 iter = distributedUniqueKeyList_.erase(iter);
932 } else {
933 ++iter;
934 }
935 }
936
937 stream.str(std::string());
938 stream.clear();
939 stream << bundleOption->GetBundleName() << keySpliter;
940 std::string localUniqueKeyHead = stream.str();
941 for (auto iter = localUniqueKeyList_.begin(); iter != localUniqueKeyList_.end();) {
942 if ((*iter).second.find(localUniqueKeyHead) == 0) {
943 iter = localUniqueKeyList_.erase(iter);
944 } else {
945 ++iter;
946 }
947 }
948 }
949
RemoveExpiredUniqueKey()950 void AdvancedNotificationService::RemoveExpiredUniqueKey()
951 {
952 std::chrono::system_clock::time_point now = std::chrono::system_clock::now();
953 auto iter = uniqueKeyList_.begin();
954 while (iter != uniqueKeyList_.end()) {
955 uint32_t duration = std::chrono::duration_cast<std::chrono::seconds>(abs(now - (*iter).first)).count();
956 ANS_LOGD("RemoveExpiredUniqueKey duration is %{public}u", duration);
957 if (duration > SECONDS_IN_ONE_DAY) {
958 ANS_LOGI("RemoveExpiredUniqueKey end duration is %{public}u", duration);
959 iter = uniqueKeyList_.erase(iter);
960 } else {
961 break;
962 }
963 }
964 }
965
RemoveExpiredDistributedUniqueKey()966 void AdvancedNotificationService::RemoveExpiredDistributedUniqueKey()
967 {
968 std::chrono::system_clock::time_point now = std::chrono::system_clock::now();
969 auto iter = distributedUniqueKeyList_.begin();
970 while (iter != distributedUniqueKeyList_.end()) {
971 uint32_t duration = std::chrono::duration_cast<std::chrono::seconds>(abs(now - (*iter).first)).count();
972 ANS_LOGD("RemoveExpired distributedUniqueKeyList_ duration is %{public}u", duration);
973 if (duration > SECONDS_IN_ONE_DAY) {
974 ANS_LOGI("RemoveExpired distributedUniqueKeyList_ end duration is %{public}u", duration);
975 iter = distributedUniqueKeyList_.erase(iter);
976 } else {
977 break;
978 }
979 }
980 }
981
RemoveExpiredLocalUniqueKey()982 void AdvancedNotificationService::RemoveExpiredLocalUniqueKey()
983 {
984 std::chrono::system_clock::time_point now = std::chrono::system_clock::now();
985 auto iter = localUniqueKeyList_.begin();
986 while (iter != localUniqueKeyList_.end()) {
987 uint32_t duration = std::chrono::duration_cast<std::chrono::seconds>(abs(now - (*iter).first)).count();
988 ANS_LOGD("RemoveExpired localUniqueKeyList_ duration is %{public}u", duration);
989 if (duration > SECONDS_IN_ONE_DAY) {
990 ANS_LOGI("RemoveExpired localUniqueKeyList_ end duration is %{public}u", duration);
991 iter = localUniqueKeyList_.erase(iter);
992 } else {
993 break;
994 }
995 }
996 }
997
IsDuplicateMsg(const std::list<std::pair<std::chrono::system_clock::time_point,std::string>> & msglist,const std::string & key)998 bool AdvancedNotificationService::IsDuplicateMsg(const std::list<std::pair<std::chrono::system_clock::time_point,
999 std::string>> &msglist, const std::string &key)
1000 {
1001 for (auto record : msglist) {
1002 if (strcmp(record.second.c_str(), key.c_str()) == 0) {
1003 return true;
1004 }
1005 }
1006 return false;
1007 }
1008
1009 #ifdef ENABLE_ANS_PRIVILEGED_MESSAGE_EXT_WRAPPER
SetDialogPoppedUnEnableTime(const sptr<NotificationBundleOption> & bundleOption)1010 void AdvancedNotificationService::SetDialogPoppedUnEnableTime(const sptr<NotificationBundleOption> &bundleOption)
1011 {
1012 ANS_LOGD("SetDialogPoppedRefuseTime called.");
1013 int32_t userId = SUBSCRIBE_USER_INIT;
1014 OHOS::AccountSA::OsAccountManager::GetOsAccountLocalIdFromUid(bundleOption->GetUid(), userId);
1015 EXTENTION_WRAPPER->SetDialogOpenSuccessTimeStamp(bundleOption, userId);
1016 ANS_LOGD("SetDialogPoppedRefuseTime end.");
1017 }
1018 #endif
1019
PublishRemoveDuplicateEvent(const std::shared_ptr<NotificationRecord> & record)1020 ErrCode AdvancedNotificationService::PublishRemoveDuplicateEvent(const std::shared_ptr<NotificationRecord> &record)
1021 {
1022 if (record == nullptr) {
1023 return ERR_ANS_INVALID_PARAM;
1024 }
1025
1026 if (!record->request->IsAgentNotification()) {
1027 ANS_LOGD("Only push agent need remove duplicate event");
1028 return ERR_OK;
1029 }
1030
1031 std::string extraStr;
1032 if (record->request->GetUnifiedGroupInfo() != nullptr) {
1033 auto extraInfo = record->request->GetUnifiedGroupInfo()->GetExtraInfo();
1034 if (extraInfo != nullptr) {
1035 AAFwk::WantParamWrapper wWrapper(*extraInfo);
1036 extraStr = wWrapper.ToString();
1037 }
1038 }
1039
1040 NotificationNapi::SlotType slotType;
1041 NotificationNapi::ContentType contentType;
1042 NotificationNapi::AnsEnumUtil::ContentTypeCToJS(
1043 static_cast<NotificationContent::Type>(record->request->GetNotificationType()), contentType);
1044 NotificationNapi::AnsEnumUtil::SlotTypeCToJS(
1045 static_cast<NotificationConstant::SlotType>(record->request->GetSlotType()), slotType);
1046
1047 EventFwk::Want want;
1048 want.SetParam("bundleName", record->bundleOption->GetBundleName());
1049 want.SetParam("uid", record->request->GetOwnerUid());
1050 want.SetParam("id", record->request->GetNotificationId());
1051 want.SetParam("slotType", static_cast<int32_t>(slotType));
1052 want.SetParam("contentType", static_cast<int32_t>(contentType));
1053 want.SetParam("appMessageId", record->request->GetAppMessageId());
1054 want.SetParam("extraInfo", extraStr);
1055 want.SetAction(NOTIFICATION_EVENT_PUSH_AGENT);
1056 EventFwk::CommonEventData commonData {want, 1, ""};
1057 EventFwk::CommonEventPublishInfo publishInfo;
1058 publishInfo.SetSubscriberPermissions({OHOS_PERMISSION_NOTIFICATION_AGENT_CONTROLLER});
1059 if (!EventFwk::CommonEventManager::PublishCommonEvent(commonData, publishInfo)) {
1060 ANS_LOGE("PublishCommonEvent failed");
1061 return ERR_ANS_TASK_ERR;
1062 }
1063
1064 return ERR_OK;
1065 }
1066
ClearAllNotificationGroupInfo(std::string localSwitch)1067 void AdvancedNotificationService::ClearAllNotificationGroupInfo(std::string localSwitch)
1068 {
1069 ANS_LOGD("ClearNotification enter.");
1070 bool status = (localSwitch == "true");
1071 if (notificationSvrQueue_ == nullptr) {
1072 ANS_LOGE("ClearNotification Serial queue is invalid.");
1073 return;
1074 }
1075
1076 ffrt::task_handle handler = notificationSvrQueue_->submit_h([=]() {
1077 if (aggregateLocalSwitch_ && !status) {
1078 for (const auto& item : notificationList_) {
1079 item->notification->GetNotificationRequestPoint()->SetUnifiedGroupInfo(nullptr);
1080 }
1081 }
1082 aggregateLocalSwitch_ = status;
1083 });
1084 }
1085
IsDisableNotification(const std::string & bundleName)1086 bool AdvancedNotificationService::IsDisableNotification(const std::string &bundleName)
1087 {
1088 if (system::GetBoolParameter(PERSIST_EDM_NOTIFICATION_DISABLE, false)) {
1089 return true;
1090 }
1091 NotificationDisable notificationDisable;
1092 if (NotificationPreferences::GetInstance()->GetDisableNotificationInfo(notificationDisable)) {
1093 if (notificationDisable.GetDisabled()) {
1094 ANS_LOGD("get disabled is open");
1095 std::vector<std::string> bundleList = notificationDisable.GetBundleList();
1096 auto it = std::find(bundleList.begin(), bundleList.end(), bundleName);
1097 if (it != bundleList.end()) {
1098 return true;
1099 }
1100 }
1101 }
1102 int32_t userId = SUBSCRIBE_USER_INIT;
1103 if (OsAccountManagerHelper::GetInstance().GetCurrentActiveUserId(userId) != ERR_OK) {
1104 ANS_LOGD("GetCurrentActiveUserId failed");
1105 return false;
1106 }
1107 if (NotificationPreferences::GetInstance()->GetUserDisableNotificationInfo(userId, notificationDisable)) {
1108 if (notificationDisable.GetDisabled()) {
1109 ANS_LOGD("get disabled is open");
1110 std::vector<std::string> bundleList = notificationDisable.GetBundleList();
1111 auto it = std::find(bundleList.begin(), bundleList.end(), bundleName);
1112 if (it != bundleList.end()) {
1113 return true;
1114 }
1115 }
1116 } else {
1117 ANS_LOGD("no disabled has been set up or set disabled to close");
1118 }
1119 return false;
1120 }
1121
IsDisableNotificationByKiosk(const std::string & bundleName)1122 bool AdvancedNotificationService::IsDisableNotificationByKiosk(const std::string &bundleName)
1123 {
1124 bool isKioskMode = NotificationPreferences::GetInstance()->IsKioskMode();
1125 if (isKioskMode && !IsEnableNotificationByKioskAppTrustList(bundleName)) {
1126 return true;
1127 }
1128 return false;
1129 }
1130
IsDisableNotificationForSaByKiosk(const std::string & bundleName,bool directAgency)1131 bool AdvancedNotificationService::IsDisableNotificationForSaByKiosk(
1132 const std::string &bundleName, bool directAgency)
1133 {
1134 bool isAppAgent = false;
1135 if (!directAgency && !bundleName.empty()) {
1136 isAppAgent = true;
1137 }
1138 bool isKioskMode = NotificationPreferences::GetInstance()->IsKioskMode();
1139 if (isKioskMode && isAppAgent && !IsEnableNotificationByKioskAppTrustList(bundleName)) {
1140 return true;
1141 }
1142 return false;
1143 }
1144
IsEnableNotificationByKioskAppTrustList(const std::string & bundleName)1145 bool AdvancedNotificationService::IsEnableNotificationByKioskAppTrustList(const std::string &bundleName)
1146 {
1147 std::vector<std::string> kioskAppTrustList;
1148 if (NotificationPreferences::GetInstance()->GetkioskAppTrustList(kioskAppTrustList)) {
1149 auto it = std::find(kioskAppTrustList.begin(), kioskAppTrustList.end(), bundleName);
1150 if (it != kioskAppTrustList.end()) {
1151 return true;
1152 }
1153 } else {
1154 ANS_LOGD("no kiosk app trust list has been set up");
1155 }
1156 return false;
1157 }
1158
IsNeedToControllerByDisableNotification(const sptr<NotificationRequest> & request)1159 bool AdvancedNotificationService::IsNeedToControllerByDisableNotification(const sptr<NotificationRequest> &request)
1160 {
1161 if (request == nullptr) {
1162 ANS_LOGE("request is nullptr");
1163 return false;
1164 }
1165 if (request->IsAgentNotification()) {
1166 return true;
1167 }
1168 std::string bundleName = "";
1169 auto agentBundle = request->GetAgentBundle();
1170 if (agentBundle != nullptr) {
1171 bundleName = agentBundle->GetBundleName();
1172 }
1173 if (!(request->GetOwnerBundleName().empty()) && !bundleName.empty() &&
1174 NotificationPreferences::GetInstance()->IsAgentRelationship(bundleName, request->GetOwnerBundleName()) &&
1175 AccessTokenHelper::CheckPermission(OHOS_PERMISSION_NOTIFICATION_AGENT_CONTROLLER)) {
1176 return false;
1177 }
1178 return true;
1179 }
1180
SetAndPublishSubscriberExistFlag(const std::string & deviceType,bool existFlag)1181 void AdvancedNotificationService::SetAndPublishSubscriberExistFlag(const std::string& deviceType, bool existFlag)
1182 {
1183 ANS_LOGD("called");
1184 if (deviceType.empty()) {
1185 ANS_LOGE("deviceType is empty");
1186 return;
1187 }
1188
1189 auto result = NotificationPreferences::GetInstance()->SetSubscriberExistFlag(deviceType, existFlag);
1190 if (result != ERR_OK) {
1191 ANS_LOGE("SetSubscriberExistFlag failed");
1192 return;
1193 }
1194
1195 bool headsetExistFlag = false;
1196 bool wearableExistFlag = false;
1197 if (deviceType == DEVICE_TYPE_HEADSET) {
1198 headsetExistFlag = existFlag;
1199 result =
1200 NotificationPreferences::GetInstance()->GetSubscriberExistFlag(DEVICE_TYPE_WEARABLE, wearableExistFlag);
1201 if (result != ERR_OK) {
1202 ANS_LOGE("GetSubscriberExistFlag failed");
1203 return;
1204 }
1205 } else if (deviceType == DEVICE_TYPE_WEARABLE) {
1206 wearableExistFlag = existFlag;
1207 result = NotificationPreferences::GetInstance()->GetSubscriberExistFlag(DEVICE_TYPE_HEADSET, headsetExistFlag);
1208 if (result != ERR_OK) {
1209 ANS_LOGE("GetSubscriberExistFlag failed");
1210 return;
1211 }
1212 }
1213 PublishSubscriberExistFlagEvent(headsetExistFlag, wearableExistFlag);
1214 }
1215
PublishSubscriberExistFlagEvent(bool headsetExistFlag,bool wearableExistFlag)1216 void AdvancedNotificationService::PublishSubscriberExistFlagEvent(bool headsetExistFlag, bool wearableExistFlag)
1217 {
1218 ANS_LOGD("%{public}s, headsetExistFlag = %{public}d, wearableExistFlag = %{public}d", __FUNCTION__,
1219 headsetExistFlag, wearableExistFlag);
1220 EventFwk::Want want;
1221 want.SetParam("SUBSCRIBER_EXISTED_HEADSET", headsetExistFlag);
1222 want.SetParam("SUBSCRIBER_EXISTED_WEARABLE", wearableExistFlag);
1223 want.SetAction(NOTIFICATION_EVENT_SUBSCRIBER_STATUS);
1224 EventFwk::CommonEventData commonData { want, 0, "" };
1225 EventFwk::CommonEventPublishInfo publishInfo;
1226 publishInfo.SetSticky(true);
1227 publishInfo.SetSubscriberType(EventFwk::SubscriberType::SYSTEM_SUBSCRIBER_TYPE);
1228 int32_t userId = SUBSCRIBE_USER_INIT;
1229 if (OsAccountManagerHelper::GetInstance().GetCurrentActiveUserId(userId) != ERR_OK) {
1230 ANS_LOGD("GetCurrentActiveUserId failed");
1231 return;
1232 }
1233 if (!EventFwk::CommonEventManager::PublishCommonEventAsUser(commonData, publishInfo, userId)) {
1234 ANS_LOGE("PublishCommonEventAsUser failed");
1235 }
1236 }
1237
RemoveAllNotificationsByBundleName(const std::string & bundleName,int32_t reason)1238 ErrCode AdvancedNotificationService::RemoveAllNotificationsByBundleName(const std::string &bundleName, int32_t reason)
1239 {
1240 NOTIFICATION_HITRACE(HITRACE_TAG_NOTIFICATION);
1241 ANS_LOGD("called");
1242
1243 if (bundleName.empty()) {
1244 std::string message = "bundle name is empty.";
1245 OHOS::Notification::HaMetaMessage haMetaMessage = HaMetaMessage(8, 1).ErrorCode(ERR_ANS_INVALID_BUNDLE);
1246 ReportDeleteFailedEventPush(haMetaMessage, reason, message);
1247 ANS_LOGE("%{public}s", message.c_str());
1248 return ERR_ANS_INVALID_BUNDLE;
1249 }
1250
1251 if (notificationSvrQueue_ == nullptr) {
1252 std::string message = "Serial queue is nullptr.";
1253 ANS_LOGE("%{public}s", message.c_str());
1254 return ERR_ANS_INVALID_PARAM;
1255 }
1256 ffrt::task_handle handler = notificationSvrQueue_->submit_h(std::bind([&]() {
1257 std::vector<std::shared_ptr<NotificationRecord>> removeList;
1258 ANS_LOGD("ffrt enter!");
1259 for (auto record : notificationList_) {
1260 if (record == nullptr) {
1261 ANS_LOGE("record is nullptr");
1262 continue;
1263 }
1264 if ((record->bundleOption->GetBundleName() == bundleName)
1265 #ifdef DISTRIBUTED_NOTIFICATION_SUPPORTED
1266 && record->deviceId.empty()
1267 #endif
1268 ) {
1269 ProcForDeleteLiveView(record);
1270 removeList.push_back(record);
1271 }
1272 }
1273
1274 std::vector<sptr<Notification>> notifications;
1275 std::vector<uint64_t> timerIds;
1276 for (auto record : removeList) {
1277 if (record == nullptr) {
1278 ANS_LOGE("record is nullptr");
1279 continue;
1280 }
1281 notificationList_.remove(record);
1282 if (record->notification != nullptr) {
1283 ANS_LOGD("record->notification is not nullptr.");
1284 UpdateRecentNotification(record->notification, true, reason);
1285 notifications.emplace_back(record->notification);
1286 timerIds.emplace_back(record->notification->GetAutoDeletedTimer());
1287 #ifdef DISTRIBUTED_NOTIFICATION_SUPPORTED
1288 DoDistributedDelete(record->deviceId, record->bundleName, record->notification);
1289 #endif
1290 }
1291 if (notifications.size() >= MAX_CANCELED_PARCELABLE_VECTOR_NUM) {
1292 SendNotificationsOnCanceled(notifications, nullptr, reason);
1293 }
1294
1295 TriggerRemoveWantAgent(record->request, reason, record->isThirdparty);
1296 }
1297
1298 if (!notifications.empty()) {
1299 NotificationSubscriberManager::GetInstance()->BatchNotifyCanceled(notifications, nullptr, reason);
1300 }
1301 BatchCancelTimer(timerIds);
1302 }));
1303 notificationSvrQueue_->wait(handler);
1304
1305 return ERR_OK;
1306 }
1307
SetHashCodeRule(const uint32_t type)1308 ErrCode AdvancedNotificationService::SetHashCodeRule(const uint32_t type)
1309 {
1310 ANS_LOGD("called");
1311 HaMetaMessage message = HaMetaMessage(EventSceneId::SCENE_8, EventBranchId::BRANCH_8);
1312 bool isSubsystem = AccessTokenHelper::VerifyNativeToken(IPCSkeleton::GetCallingTokenID());
1313 if (!isSubsystem && !AccessTokenHelper::IsSystemApp()) {
1314 ANS_LOGE("IsSystemApp is false.");
1315 message.ErrorCode(ERR_ANS_NON_SYSTEM_APP).Append("Not SystemApp");
1316 NotificationAnalyticsUtil::ReportModifyEvent(message);
1317 return ERR_ANS_NON_SYSTEM_APP;
1318 }
1319
1320 int32_t uid = IPCSkeleton::GetCallingUid();
1321 if (uid != AVSEESAION_PID) {
1322 ANS_LOGE("Permission Denied.");
1323 message.ErrorCode(ERR_ANS_PERMISSION_DENIED).Append("No permission");
1324 NotificationAnalyticsUtil::ReportModifyEvent(message);
1325 return ERR_ANS_PERMISSION_DENIED;
1326 }
1327 ErrCode result = NotificationPreferences::GetInstance()->SetHashCodeRule(uid, type);
1328 ANS_LOGI("uid = %{public}d type = %{public}d, result = %{public}d", uid, type, result);
1329 message.ErrorCode(result);
1330 NotificationAnalyticsUtil::ReportModifyEvent(message);
1331
1332 return result;
1333 }
1334 } // namespace Notification
1335 } // namespace OHOS
1336