• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright (c) 2021-2023 Huawei Device Co., Ltd.
3  * Licensed under the Apache License, Version 2.0 (the "License");
4  * you may not use this file except in compliance with the License.
5  * You may obtain a copy of the License at
6  *
7  *     http://www.apache.org/licenses/LICENSE-2.0
8  *
9  * Unless required by applicable law or agreed to in writing, software
10  * distributed under the License is distributed on an "AS IS" BASIS,
11  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12  * See the License for the specific language governing permissions and
13  * limitations under the License.
14  */
15 
16 #include "reminder_data_manager.h"
17 
18 #include "ability_manager_client.h"
19 #include "access_token_helper.h"
20 #include "ans_log_wrapper.h"
21 #include "ans_const_define.h"
22 #include "common_event_support.h"
23 #include "common_event_manager.h"
24 #include "reminder_request_calendar.h"
25 #include "in_process_call_wrapper.h"
26 #ifdef DEVICE_STANDBY_ENABLE
27 #include "standby_service_client.h"
28 #include "allow_type.h"
29 #endif
30 #include "ipc_skeleton.h"
31 #include "notification_slot.h"
32 #include "os_account_manager.h"
33 #include "os_account_manager_helper.h"
34 #include "reminder_event_manager.h"
35 #include "time_service_client.h"
36 #include "singleton.h"
37 #include "locale_config.h"
38 #include "bundle_manager_helper.h"
39 #include "datashare_predicates_object.h"
40 #include "datashare_value_object.h"
41 #include "datashare_helper.h"
42 #include "data_share_permission.h"
43 #include "datashare_errno.h"
44 #include "datashare_template.h"
45 #include "system_ability_definition.h"
46 #include "app_mgr_constants.h"
47 #include "iservice_registry.h"
48 #include "config_policy_utils.h"
49 #include "hitrace_meter_adapter.h"
50 #ifdef HAS_HISYSEVENT_PART
51 #include "hisysevent.h"
52 #endif
53 
54 namespace OHOS {
55 namespace Notification {
56 namespace {
57 const std::string ALL_PACKAGES = "allPackages";
58 const int32_t MAIN_USER_ID = 100;
59 #ifdef DEVICE_STANDBY_ENABLE
60 const int REASON_APP_API = 1;
61 #endif
62 const int INDEX_KEY = 0;
63 const int INDEX_TYPE = 1;
64 const int INDEX_VALUE = 2;
65 }
66 
67 /**
68  * Default reminder sound.
69  */
70 const std::string DEFAULT_REMINDER_SOUND_1 = "/system/etc/capture.ogg";
71 const std::string DEFAULT_REMINDER_SOUND_2 = "resource/media/audio/alarms/Aegean_Sea.ogg";
72 
73 std::shared_ptr<ReminderDataManager> ReminderDataManager::REMINDER_DATA_MANAGER = nullptr;
74 std::mutex ReminderDataManager::MUTEX;
75 std::mutex ReminderDataManager::SHOW_MUTEX;
76 std::mutex ReminderDataManager::ALERT_MUTEX;
77 std::mutex ReminderDataManager::TIMER_MUTEX;
78 std::mutex ReminderDataManager::ACTIVE_MUTEX;
79 constexpr int32_t CONNECT_EXTENSION_INTERVAL = 100;
80 constexpr int32_t CONNECT_EXTENSION_MAX_RETRY_TIMES = 3;
81 std::shared_ptr<ffrt::queue> ReminderDataManager::serviceQueue_ = nullptr;
82 ReminderDataManager::~ReminderDataManager() = default;
83 
PublishReminder(const sptr<ReminderRequest> & reminder,const sptr<NotificationBundleOption> & bundleOption)84 ErrCode ReminderDataManager::PublishReminder(const sptr<ReminderRequest> &reminder,
85     const sptr<NotificationBundleOption> &bundleOption)
86 {
87     HITRACE_METER_NAME(HITRACE_TAG_OHOS, __PRETTY_FUNCTION__);
88     uint32_t callerTokenId = IPCSkeleton::GetCallingTokenID();
89     if (callerTokenId == 0) {
90         ANSR_LOGE("pushlish failed, callerTokenId is 0");
91         return ERR_REMINDER_CALLER_TOKEN_INVALID;
92     }
93 
94     if (!IsActionButtonDataShareValid(reminder, callerTokenId)) {
95         return ERR_REMINDER_DATA_SHARE_PERMISSION_DENIED;
96     }
97 
98     if (CheckReminderLimitExceededLocked(bundleOption, reminder)) {
99         return ERR_REMINDER_NUMBER_OVERLOAD;
100     }
101     UpdateAndSaveReminderLocked(reminder, bundleOption);
102     queue_->submit([this, reminder]() {
103         StartRecentReminder();
104     });
105     return ERR_OK;
106 }
107 
CancelReminder(const int32_t & reminderId,const sptr<NotificationBundleOption> & bundleOption)108 ErrCode ReminderDataManager::CancelReminder(
109     const int32_t &reminderId, const sptr<NotificationBundleOption> &bundleOption)
110 {
111     HITRACE_METER_NAME(HITRACE_TAG_OHOS, __PRETTY_FUNCTION__);
112     ANSR_LOGI("cancel reminder id: %{public}d", reminderId);
113     sptr<ReminderRequest> reminder = FindReminderRequestLocked(reminderId, bundleOption->GetBundleName());
114     if (reminder == nullptr) {
115         ANSR_LOGW("Cancel reminder, not find the reminder");
116         return ERR_REMINDER_NOT_EXIST;
117     }
118     if (!CheckIsSameApp(reminder, bundleOption)) {
119         ANSR_LOGW("Not find the reminder due to not match");
120         return ERR_REMINDER_NOT_EXIST;
121     }
122     if (activeReminderId_ == reminderId) {
123         ANSR_LOGD("Cancel active reminder, id=%{public}d", reminderId);
124         {
125             std::lock_guard<std::mutex> locker(ReminderDataManager::ACTIVE_MUTEX);
126             activeReminder_->OnStop();
127         }
128         StopTimerLocked(TimerType::TRIGGER_TIMER);
129     }
130     if (alertingReminderId_ == reminderId) {
131         StopSoundAndVibrationLocked(reminder);
132         StopTimerLocked(TimerType::ALERTING_TIMER);
133     }
134     CancelNotification(reminder);
135     RemoveReminderLocked(reminderId);
136     StartRecentReminder();
137     return ERR_OK;
138 }
139 
CancelAllReminders(const std::string & packageName,const int32_t userId,const int32_t uid)140 ErrCode ReminderDataManager::CancelAllReminders(const std::string& packageName, const int32_t userId,
141     const int32_t uid)
142 {
143     HITRACE_METER_NAME(HITRACE_TAG_OHOS, __PRETTY_FUNCTION__);
144     ANSR_LOGD("CancelAllReminders, userId=%{private}d, pkgName=%{public}s", userId, packageName.c_str());
145     CancelRemindersImplLocked(packageName, userId, uid);
146     return ERR_OK;
147 }
148 
CheckExcludeDateParam(const int32_t reminderId,const sptr<NotificationBundleOption> & bundleOption)149 sptr<ReminderRequest> ReminderDataManager::CheckExcludeDateParam(const int32_t reminderId,
150     const sptr<NotificationBundleOption> &bundleOption)
151 {
152     sptr<ReminderRequest> reminder = FindReminderRequestLocked(reminderId);
153     if (reminder == nullptr) {
154         ANSR_LOGW("Check reminder failed, not find the reminder");
155         return nullptr;
156     }
157     if (!CheckIsSameApp(reminder, bundleOption)) {
158         ANSR_LOGW("Check reminder failed, due to not match");
159         return nullptr;
160     }
161     if (reminder->GetReminderType() != ReminderRequest::ReminderType::CALENDAR
162         || !reminder->IsRepeat()) {
163         ANSR_LOGW("Check reminder failed, due to type not match or not repeat");
164         return nullptr;
165     }
166     return reminder;
167 }
168 
AddExcludeDate(const int32_t reminderId,const uint64_t date,const sptr<NotificationBundleOption> & bundleOption)169 ErrCode ReminderDataManager::AddExcludeDate(const int32_t reminderId, const uint64_t date,
170     const sptr<NotificationBundleOption> &bundleOption)
171 {
172     HITRACE_METER_NAME(HITRACE_TAG_OHOS, __PRETTY_FUNCTION__);
173     sptr<ReminderRequest> reminder = CheckExcludeDateParam(reminderId, bundleOption);
174     if (reminder == nullptr) {
175         return ERR_REMINDER_NOT_EXIST;
176     }
177     {
178         std::lock_guard<std::mutex> locker(ReminderDataManager::MUTEX);
179         ReminderRequestCalendar* calendar = static_cast<ReminderRequestCalendar*>(reminder.GetRefPtr());
180         calendar->AddExcludeDate(date);
181         store_->UpdateOrInsert(reminder, bundleOption);
182     }
183     return ERR_OK;
184 }
185 
DelExcludeDates(const int32_t reminderId,const sptr<NotificationBundleOption> & bundleOption)186 ErrCode ReminderDataManager::DelExcludeDates(const int32_t reminderId,
187     const sptr<NotificationBundleOption> &bundleOption)
188 {
189     HITRACE_METER_NAME(HITRACE_TAG_OHOS, __PRETTY_FUNCTION__);
190     sptr<ReminderRequest> reminder = CheckExcludeDateParam(reminderId, bundleOption);
191     if (reminder == nullptr) {
192         return ERR_REMINDER_NOT_EXIST;
193     }
194     {
195         std::lock_guard<std::mutex> locker(ReminderDataManager::MUTEX);
196         ReminderRequestCalendar* calendar = static_cast<ReminderRequestCalendar*>(reminder.GetRefPtr());
197         calendar->DelExcludeDates();
198         store_->UpdateOrInsert(reminder, bundleOption);
199     }
200     return ERR_OK;
201 }
202 
GetExcludeDates(const int32_t reminderId,const sptr<NotificationBundleOption> & bundleOption,std::vector<uint64_t> & dates)203 ErrCode ReminderDataManager::GetExcludeDates(const int32_t reminderId,
204     const sptr<NotificationBundleOption> &bundleOption, std::vector<uint64_t>& dates)
205 {
206     HITRACE_METER_NAME(HITRACE_TAG_OHOS, __PRETTY_FUNCTION__);
207     sptr<ReminderRequest> reminder = CheckExcludeDateParam(reminderId, bundleOption);
208     if (reminder == nullptr) {
209         return ERR_REMINDER_NOT_EXIST;
210     }
211     {
212         std::lock_guard<std::mutex> locker(ReminderDataManager::MUTEX);
213         ReminderRequestCalendar* calendar = static_cast<ReminderRequestCalendar*>(reminder.GetRefPtr());
214         dates = calendar->GetExcludeDates();
215     }
216     return ERR_OK;
217 }
218 
GetValidReminders(const sptr<NotificationBundleOption> & bundleOption,std::vector<sptr<ReminderRequest>> & reminders)219 void ReminderDataManager::GetValidReminders(
220     const sptr<NotificationBundleOption> &bundleOption, std::vector<sptr<ReminderRequest>> &reminders)
221 {
222     HITRACE_METER_NAME(HITRACE_TAG_OHOS, __PRETTY_FUNCTION__);
223     std::lock_guard<std::mutex> lock(ReminderDataManager::MUTEX);
224     for (auto& eachReminder : reminderVector_) {
225         if (eachReminder->IsExpired()) {
226             continue;
227         }
228 
229         if (CheckIsSameApp(eachReminder, bundleOption)) {
230             reminders.push_back(eachReminder);
231         }
232     }
233 }
234 
CancelAllReminders(const int32_t userId)235 void ReminderDataManager::CancelAllReminders(const int32_t userId)
236 {
237     ANSR_LOGD("CancelAllReminders, userId=%{private}d", userId);
238     CancelRemindersImplLocked(ALL_PACKAGES, userId, -1);
239 }
240 
CancelRemindersImplLocked(const std::string & packageName,const int32_t userId,const int32_t uid)241 void ReminderDataManager::CancelRemindersImplLocked(const std::string &packageName, const int32_t userId,
242     const int32_t uid)
243 {
244     MUTEX.lock();
245     {
246         std::lock_guard<std::mutex> locker(ReminderDataManager::ACTIVE_MUTEX);
247         if (activeReminderId_ != -1 && IsMatched(activeReminder_, packageName, userId, uid)) {
248             activeReminder_->OnStop();
249             StopTimer(TimerType::TRIGGER_TIMER);
250             ANSR_LOGD("Stop active reminder, reminderId=%{public}d", activeReminderId_.load());
251         }
252     }
253     for (auto vit = reminderVector_.begin(); vit != reminderVector_.end();) {
254         if (IsMatched(*vit, packageName, userId, uid)) {
255             if ((*vit)->IsAlerting()) {
256                 StopAlertingReminder(*vit);
257             }
258             CancelNotification(*vit);
259             RemoveFromShowedReminders(*vit);
260             vit = reminderVector_.erase(vit);
261             totalCount_--;
262             continue;
263         }
264         ++vit;
265     }
266     if (packageName == ALL_PACKAGES) {
267         store_->DeleteUser(userId);
268     } else {
269         store_->Delete(packageName, userId, uid);
270     }
271     MUTEX.unlock();
272     StartRecentReminder();
273 }
274 
IsMatchedForGroupIdAndPkgName(const sptr<ReminderRequest> & reminder,const std::string & packageName,const std::string & groupId) const275 bool ReminderDataManager::IsMatchedForGroupIdAndPkgName(const sptr<ReminderRequest> &reminder,
276     const std::string &packageName, const std::string &groupId) const
277 {
278     std::string packageNameTemp = reminder->GetBundleName();
279     if (packageNameTemp.empty()) {
280         ANSR_LOGW("reminder package name is null");
281         return false;
282     }
283     if (packageNameTemp == packageName && reminder->GetGroupId() == groupId) {
284         return true;
285     }
286     return false;
287 }
288 
IsMatched(const sptr<ReminderRequest> & reminder,const std::string & packageName,const int32_t userId,const int32_t uid) const289 bool ReminderDataManager::IsMatched(const sptr<ReminderRequest> &reminder,
290     const std::string &packageName, const int32_t userId, const int32_t uid) const
291 {
292     if (reminder->GetUserId() != userId) {
293         return false;
294     }
295     if (packageName == ALL_PACKAGES) {
296         return true;
297     }
298     if (reminder->GetBundleName() != packageName) {
299         return false;
300     }
301     if (uid != -1 && reminder->GetUid() == uid) {
302         return true;
303     }
304     return false;
305 }
306 
CancelNotification(const sptr<ReminderRequest> & reminder) const307 void ReminderDataManager::CancelNotification(const sptr<ReminderRequest> &reminder) const
308 {
309     if (!(reminder->IsShowing())) {
310         ANSR_LOGD("No need to cancel notification");
311         return;
312     }
313     sptr<NotificationRequest> notification = reminder->GetNotificationRequest();
314     if (notification == nullptr) {
315         ANSR_LOGW("Cancel notification fail");
316         return;
317     }
318     ANSR_LOGD("Cancel notification");
319     if (advancedNotificationService_ == nullptr) {
320         ANSR_LOGE("Cancel notification fail");
321         return;
322     }
323     sptr<NotificationBundleOption> bundleOption = reminder->GetNotificationBundleOption();
324     advancedNotificationService_->CancelPreparedNotification(notification->GetNotificationId(),
325         ReminderRequest::NOTIFICATION_LABEL, bundleOption, NotificationConstant::APP_CANCEL_REMINDER_REASON_DELETE);
326 }
327 
CheckReminderLimitExceededLocked(const sptr<NotificationBundleOption> & bundleOption,const sptr<ReminderRequest> & reminder) const328 bool ReminderDataManager::CheckReminderLimitExceededLocked(const sptr<NotificationBundleOption> &bundleOption,
329     const sptr<ReminderRequest> &reminder) const
330 {
331     std::lock_guard<std::mutex> lock(ReminderDataManager::MUTEX);
332     if (totalCount_ >= ReminderDataManager::MAX_NUM_REMINDER_LIMIT_SYSTEM) {
333         ANSR_LOGW("The number of validate reminders exceeds the system upper limit:%{public}d, \
334             and new reminder can not be published", MAX_NUM_REMINDER_LIMIT_SYSTEM);
335         return true;
336     }
337     int32_t count = 0;
338     for (const auto& eachReminder : reminderVector_) {
339         if (eachReminder->IsExpired()) {
340             continue;
341         }
342         if (CheckIsSameApp(eachReminder, bundleOption)) {
343             count++;
344         }
345     }
346     auto maxReminderNum = reminder->IsSystemApp() ? MAX_NUM_REMINDER_LIMIT_SYS_APP : MAX_NUM_REMINDER_LIMIT_APP;
347     if (count >= maxReminderNum) {
348         ANSR_LOGW("The number of validate reminders exceeds the application upper limit:%{public}d, and new \
349             reminder can not be published", maxReminderNum);
350         return true;
351     }
352     return false;
353 }
354 
AddToShowedReminders(const sptr<ReminderRequest> & reminder)355 void ReminderDataManager::AddToShowedReminders(const sptr<ReminderRequest> &reminder)
356 {
357     std::lock_guard<std::mutex> lock(ReminderDataManager::SHOW_MUTEX);
358     for (auto it = showedReminderVector_.begin(); it != showedReminderVector_.end(); ++it) {
359         if (reminder->GetReminderId() == (*it)->GetReminderId()) {
360             ANSR_LOGD("Showed reminder is already exist");
361             return;
362         }
363     }
364     showedReminderVector_.push_back(reminder);
365 }
366 
OnUserRemove(const int32_t & userId)367 void ReminderDataManager::OnUserRemove(const int32_t& userId)
368 {
369     if (!IsReminderAgentReady()) {
370         ANSR_LOGW("Give up to remove user id: %{private}d for reminderAgent is not ready", userId);
371         return;
372     }
373     CancelAllReminders(userId);
374 }
375 
OnUserSwitch(const int32_t & userId)376 void ReminderDataManager::OnUserSwitch(const int32_t& userId)
377 {
378     ANSR_LOGD("Switch user id from %{private}d to %{private}d", currentUserId_, userId);
379     currentUserId_ = userId;
380     std::lock_guard<std::mutex> lock(ReminderDataManager::MUTEX);
381     if ((alertingReminderId_ != -1) && IsReminderAgentReady()) {
382         TerminateAlerting(alertingReminder_, "OnUserSwitch");
383     }
384 }
385 
OnProcessDiedLocked(const sptr<NotificationBundleOption> & bundleOption)386 void ReminderDataManager::OnProcessDiedLocked(const sptr<NotificationBundleOption> &bundleOption)
387 {
388     std::string bundleName = bundleOption->GetBundleName();
389     int32_t uid = bundleOption->GetUid();
390     ANSR_LOGD("OnProcessDiedLocked, bundleName=%{public}s, uid=%{public}d", bundleName.c_str(), uid);
391     std::lock_guard<std::mutex> locker(ReminderDataManager::MUTEX);
392     std::lock_guard<std::mutex> lock(ReminderDataManager::SHOW_MUTEX);
393     for (auto it = showedReminderVector_.begin(); it != showedReminderVector_.end(); ++it) {
394         if ((*it)->GetBundleName() != bundleName || (*it)->GetUid() != uid) {
395             continue;
396         }
397         if ((*it)->IsAlerting()) {
398             TerminateAlerting((*it), "onProcessDied");
399         } else {
400             CancelNotification(*it);
401             (*it)->OnClose(false);
402             showedReminderVector_.erase(it);
403             --it;
404         }
405         store_->UpdateOrInsert((*it), bundleOption);
406     }
407 }
408 
InitTimerInfo(std::shared_ptr<ReminderTimerInfo> & sharedTimerInfo,const sptr<ReminderRequest> & reminderRequest,TimerType reminderType) const409 void ReminderDataManager::InitTimerInfo(std::shared_ptr<ReminderTimerInfo> &sharedTimerInfo,
410     const sptr<ReminderRequest> &reminderRequest, TimerType reminderType) const
411 {
412     uint8_t timerTypeWakeup = static_cast<uint8_t>(sharedTimerInfo->TIMER_TYPE_WAKEUP);
413     uint8_t timerTypeExact = static_cast<uint8_t>(sharedTimerInfo->TIMER_TYPE_EXACT);
414     sharedTimerInfo->SetRepeat(false);
415     sharedTimerInfo->SetInterval(0);
416 
417     sharedTimerInfo->SetBundleName(reminderRequest->GetBundleName());
418     sharedTimerInfo->SetUid(reminderRequest->GetUid());
419 
420     int32_t timerType = static_cast<int32_t>(timerTypeWakeup | timerTypeExact);
421     sharedTimerInfo->SetType(timerType);
422 }
423 
CreateTimerInfo(TimerType type,const sptr<ReminderRequest> & reminderRequest) const424 std::shared_ptr<ReminderTimerInfo> ReminderDataManager::CreateTimerInfo(TimerType type,
425     const sptr<ReminderRequest> &reminderRequest) const
426 {
427     auto sharedTimerInfo = std::make_shared<ReminderTimerInfo>();
428     if ((sharedTimerInfo->TIMER_TYPE_WAKEUP > UINT8_MAX) || (sharedTimerInfo->TIMER_TYPE_EXACT > UINT8_MAX)) {
429         ANSR_LOGE("Failed to set timer type.");
430         return nullptr;
431     }
432     InitTimerInfo(sharedTimerInfo, reminderRequest, type);
433 
434     int32_t requestCode = 10;
435     std::vector<AbilityRuntime::WantAgent::WantAgentConstant::Flags> flags;
436     flags.push_back(AbilityRuntime::WantAgent::WantAgentConstant::Flags::UPDATE_PRESENT_FLAG);
437 
438     auto want = std::make_shared<OHOS::AAFwk::Want>();
439     switch (type) {
440         case (TimerType::TRIGGER_TIMER): {
441             want->SetAction(ReminderRequest::REMINDER_EVENT_ALARM_ALERT);
442             sharedTimerInfo->SetAction(ReminderRequest::REMINDER_EVENT_ALARM_ALERT);
443             want->SetParam(ReminderRequest::PARAM_REMINDER_ID, activeReminderId_);
444             break;
445         }
446         case (TimerType::ALERTING_TIMER): {
447             if (alertingReminderId_ == -1) {
448                 ANSR_LOGE("Create alerting time out timer Illegal.");
449                 return sharedTimerInfo;
450             }
451             want->SetAction(ReminderRequest::REMINDER_EVENT_ALERT_TIMEOUT);
452             sharedTimerInfo->SetAction(ReminderRequest::REMINDER_EVENT_ALERT_TIMEOUT);
453             want->SetParam(ReminderRequest::PARAM_REMINDER_ID, alertingReminderId_);
454             break;
455         }
456         default:
457             ANSR_LOGE("TimerType not support");
458             break;
459     }
460     std::vector<std::shared_ptr<AAFwk::Want>> wants;
461     wants.push_back(want);
462     AbilityRuntime::WantAgent::WantAgentInfo wantAgentInfo(
463         requestCode,
464         AbilityRuntime::WantAgent::WantAgentConstant::OperationType::SEND_COMMON_EVENT,
465         flags, wants, nullptr);
466 
467     std::string identity = IPCSkeleton::ResetCallingIdentity();
468     std::shared_ptr<AbilityRuntime::WantAgent::WantAgent> wantAgent =
469         AbilityRuntime::WantAgent::WantAgentHelper::GetWantAgent(wantAgentInfo, 0);
470     IPCSkeleton::SetCallingIdentity(identity);
471 
472     sharedTimerInfo->SetWantAgent(wantAgent);
473     return sharedTimerInfo;
474 }
475 
FindReminderRequestLocked(const int32_t & reminderId)476 sptr<ReminderRequest> ReminderDataManager::FindReminderRequestLocked(const int32_t &reminderId)
477 {
478     std::lock_guard<std::mutex> lock(ReminderDataManager::MUTEX);
479     for (auto it = reminderVector_.begin(); it != reminderVector_.end(); ++it) {
480         if (reminderId == (*it)->GetReminderId()) {
481             return *it;
482         }
483     }
484     ANSR_LOGD("Not find the reminder");
485     return nullptr;
486 }
487 
FindReminderRequestLocked(const int32_t & reminderId,const std::string & pkgName)488 sptr<ReminderRequest> ReminderDataManager::FindReminderRequestLocked(
489     const int32_t &reminderId, const std::string &pkgName)
490 {
491     sptr<ReminderRequest> reminder = FindReminderRequestLocked(reminderId);
492     std::lock_guard<std::mutex> lock(ReminderDataManager::MUTEX);
493     if (reminder == nullptr) {
494         return nullptr;
495     }
496     if (reminder->GetCreatorBundleName() != pkgName) {
497         ANSR_LOGW("Not find the reminder due to package name not match");
498         return nullptr;
499     }
500     return reminder;
501 }
502 
cmp(sptr<ReminderRequest> & reminderRequest,sptr<ReminderRequest> & other)503 bool ReminderDataManager::cmp(sptr<ReminderRequest> &reminderRequest, sptr<ReminderRequest> &other)
504 {
505     return reminderRequest->GetTriggerTimeInMilli() < other->GetTriggerTimeInMilli();
506 }
507 
CloseReminder(const OHOS::EventFwk::Want & want,bool cancelNotification)508 void ReminderDataManager::CloseReminder(const OHOS::EventFwk::Want &want, bool cancelNotification)
509 {
510     int32_t reminderId = static_cast<int32_t>(want.GetIntParam(ReminderRequest::PARAM_REMINDER_ID, -1));
511     sptr<ReminderRequest> reminder = FindReminderRequestLocked(reminderId);
512     if (reminder == nullptr) {
513         ANSR_LOGW("Invalid reminder id: %{public}d", reminderId);
514         return;
515     }
516     std::string packageName = reminder->GetBundleName();
517     std::string groupId = reminder->GetGroupId();
518     if (!(packageName.empty() || groupId.empty())) {
519         ANSR_LOGD("this reminder can close by groupId");
520         CloseRemindersByGroupId(reminderId, packageName, groupId);
521     }
522     CloseReminder(reminder, cancelNotification);
523     UpdateAppDatabase(reminder, ReminderRequest::ActionButtonType::CLOSE);
524     CheckNeedNotifyStatus(reminder, ReminderRequest::ActionButtonType::CLOSE);
525     StartRecentReminder();
526 }
527 
CloseRemindersByGroupId(const int32_t & oldReminderId,const std::string & packageName,const std::string & groupId)528 void ReminderDataManager::CloseRemindersByGroupId(const int32_t &oldReminderId, const std::string &packageName,
529     const std::string &groupId)
530 {
531     if (packageName == "") {
532         ANSR_LOGD("packageName is empty");
533         return;
534     }
535     std::lock_guard<std::mutex> lock(ReminderDataManager::MUTEX);
536     for (auto vit = reminderVector_.begin(); vit != reminderVector_.end(); vit++) {
537         sptr<ReminderRequest> reminder = *vit;
538         if (reminder == nullptr) {
539             ANSR_LOGD("reminder is null");
540             continue;
541         }
542         int32_t reminderId = reminder->GetReminderId();
543         if (reminderId == oldReminderId) {
544             ANSR_LOGD("The old and new reminder are the same");
545             continue;
546         }
547         if (IsMatchedForGroupIdAndPkgName(reminder, packageName, groupId)) {
548             reminder->SetExpired(true);
549             reminder->SetStateToInActive();
550             store_->UpdateOrInsert(reminder, reminder->GetNotificationBundleOption());
551             ResetStates(TimerType::TRIGGER_TIMER);
552             ANSR_LOGD("Cancel reminders by groupid, reminder is %{public}s", reminder->Dump().c_str());
553         }
554     }
555 }
556 
CloseReminder(const sptr<ReminderRequest> & reminder,bool cancelNotification)557 void ReminderDataManager::CloseReminder(const sptr<ReminderRequest> &reminder, bool cancelNotification)
558 {
559     int32_t reminderId = reminder->GetReminderId();
560     if (activeReminderId_ == reminderId) {
561         ANSR_LOGD("Stop active reminder due to CloseReminder");
562         {
563             std::lock_guard<std::mutex> locker(ReminderDataManager::ACTIVE_MUTEX);
564             activeReminder_->OnStop();
565         }
566         StopTimerLocked(TimerType::TRIGGER_TIMER);
567     }
568     if (alertingReminderId_ == reminderId) {
569         StopSoundAndVibrationLocked(reminder);
570         StopTimerLocked(TimerType::ALERTING_TIMER);
571     }
572     reminder->OnClose(true);
573     RemoveFromShowedReminders(reminder);
574     store_->UpdateOrInsert(reminder, reminder->GetNotificationBundleOption());
575     if (cancelNotification) {
576         CancelNotification(reminder);
577     }
578 }
579 
GetInstance()580 std::shared_ptr<ReminderDataManager> ReminderDataManager::GetInstance()
581 {
582     return REMINDER_DATA_MANAGER;
583 }
584 
InitInstance(const sptr<AdvancedNotificationService> & advancedNotificationService)585 std::shared_ptr<ReminderDataManager> ReminderDataManager::InitInstance(
586     const sptr<AdvancedNotificationService> &advancedNotificationService)
587 {
588     if (REMINDER_DATA_MANAGER == nullptr) {
589         REMINDER_DATA_MANAGER = std::make_shared<ReminderDataManager>();
590         REMINDER_DATA_MANAGER->advancedNotificationService_ = advancedNotificationService;
591         ReminderEventManager reminderEventManager(REMINDER_DATA_MANAGER);
592     }
593     return REMINDER_DATA_MANAGER;
594 }
595 
CheckUpdateConditions(const sptr<ReminderRequest> & reminder,const ReminderRequest::ActionButtonType & actionButtonType,const std::map<ReminderRequest::ActionButtonType,ReminderRequest::ActionButtonInfo> & actionButtonMap)596 bool ReminderDataManager::CheckUpdateConditions(const sptr<ReminderRequest> &reminder,
597     const ReminderRequest::ActionButtonType &actionButtonType,
598     const std::map<ReminderRequest::ActionButtonType, ReminderRequest::ActionButtonInfo> &actionButtonMap)
599 {
600     if (!reminder->IsSystemApp()) {
601         ANSR_LOGI("UpdateAppDatabase faild, is not SystemApp");
602         return false;
603     }
604     if (actionButtonType == ReminderRequest::ActionButtonType::INVALID) {
605         ANSR_LOGI("actionButtonType is NVALID");
606         return false;
607     }
608     if (!actionButtonMap.count(actionButtonType)) {
609         ANSR_LOGI("actionButtonType does not exist");
610         return false;
611     }
612     if (actionButtonMap.at(actionButtonType).dataShareUpdate == nullptr) {
613         ANSR_LOGI("dataShareUpdate is null");
614         return false;
615     }
616     if (actionButtonMap.at(actionButtonType).dataShareUpdate->uri == "" ||
617         actionButtonMap.at(actionButtonType).dataShareUpdate->equalTo == "" ||
618         actionButtonMap.at(actionButtonType).dataShareUpdate->valuesBucket == "") {
619         ANSR_LOGI("datashare parameter is invalid");
620         return false;
621     }
622     return true;
623 }
624 
UpdateAppDatabase(const sptr<ReminderRequest> & reminder,const ReminderRequest::ActionButtonType & actionButtonType)625 void ReminderDataManager::UpdateAppDatabase(const sptr<ReminderRequest> &reminder,
626     const ReminderRequest::ActionButtonType &actionButtonType)
627 {
628     std::lock_guard<std::mutex> lock(ReminderDataManager::MUTEX);
629     auto actionButtonMap = reminder->GetActionButtons();
630     if (!CheckUpdateConditions(reminder, actionButtonType, actionButtonMap)) {
631         return;
632     }
633     // init default dstBundleName
634     std::string dstBundleName = reminder->GetBundleName();
635     GenDstBundleName(dstBundleName, actionButtonMap.at(actionButtonType).dataShareUpdate->uri);
636 
637     DataShare::CreateOptions options;
638     options.enabled_ = true;
639     auto userID = reminder->GetUserId();
640     auto tokenID = IPCSkeleton::GetSelfTokenID();
641     std::string uriStr = actionButtonMap.at(actionButtonType).dataShareUpdate->uri + "?user=" + std::to_string(userID) +
642         "&srcToken=" + std::to_string(tokenID) + "&dstBundleName=" + dstBundleName;
643 
644     // create datashareHelper
645     std::shared_ptr<DataShare::DataShareHelper> dataShareHelper = DataShare::DataShareHelper::Creator(uriStr, options);
646     if (dataShareHelper == nullptr) {
647         ANSR_LOGE("create datashareHelper failed");
648         return;
649     }
650     // gen uri equalTo valuesBucket
651     Uri uri(uriStr);
652 
653     DataShare::DataSharePredicates predicates;
654     std::vector<std::string> equalToVector = ReminderRequest::StringSplit(
655         actionButtonMap.at(actionButtonType).dataShareUpdate->equalTo, ReminderRequest::SEP_BUTTON_VALUE_TYPE);
656     GenPredicates(predicates, equalToVector);
657 
658     DataShare::DataShareValuesBucket valuesBucket;
659     std::vector<std::string> valuesBucketVector = ReminderRequest::StringSplit(
660         actionButtonMap.at(actionButtonType).dataShareUpdate->valuesBucket, ReminderRequest::SEP_BUTTON_VALUE_TYPE);
661     GenValuesBucket(valuesBucket, valuesBucketVector);
662 
663     // update app store
664     int retVal = dataShareHelper->Update(uri, predicates, valuesBucket);
665     if (retVal > 0) {
666         // update success
667         ANSR_LOGI("update app store success retval:%{public}d", retVal);
668     }
669 }
670 
GenPredicates(DataShare::DataSharePredicates & predicates,const std::vector<std::string> & equalToVector)671 void ReminderDataManager::GenPredicates(DataShare::DataSharePredicates &predicates,
672     const std::vector<std::string> &equalToVector)
673 {
674     // predicates
675     for (auto &it : equalToVector) {
676         std::vector<std::string> temp = ReminderRequest::StringSplit(it, ReminderRequest::SEP_BUTTON_VALUE);
677         if (temp.size() <= INDEX_VALUE) {
678             continue;
679         }
680         if (temp[INDEX_TYPE] == "string") {
681             predicates.EqualTo(temp[INDEX_KEY], temp[INDEX_VALUE]);
682         } else if (temp[INDEX_TYPE] == "double") {
683             predicates.EqualTo(temp[INDEX_KEY], std::stod(temp[INDEX_VALUE]));
684         } else if (temp[INDEX_TYPE] == "bool") {
685             bool valueBool = false;
686             if (temp[INDEX_VALUE] == "1" || temp[INDEX_VALUE] == "true" || temp[INDEX_VALUE] == "True") {
687                 valueBool = true;
688             }
689             predicates.EqualTo(temp[INDEX_KEY], valueBool);
690         }
691     }
692 }
693 
GenValuesBucket(DataShare::DataShareValuesBucket & valuesBucket,const std::vector<std::string> & valuesBucketVector)694 void ReminderDataManager::GenValuesBucket(DataShare::DataShareValuesBucket & valuesBucket,
695     const std::vector<std::string> &valuesBucketVector)
696 {
697     // valuesBucket
698     for (auto &it : valuesBucketVector) {
699         std::vector<std::string> temp = ReminderRequest::StringSplit(it, ReminderRequest::SEP_BUTTON_VALUE);
700         if (temp.size() <= INDEX_VALUE) {
701             continue;
702         }
703         if (temp[INDEX_TYPE] == "string") {
704             valuesBucket.Put(temp[INDEX_KEY], temp[INDEX_VALUE]);
705         } else if (temp[INDEX_TYPE] == "double") {
706             valuesBucket.Put(temp[INDEX_KEY], std::stod(temp[INDEX_VALUE]));
707         } else if (temp[INDEX_TYPE] == "bool") {
708             bool valueBool = false;
709             if (temp[INDEX_VALUE] == "1" || temp[INDEX_VALUE] == "true") {
710                 valueBool = true;
711             }
712             valuesBucket.Put(temp[INDEX_KEY], valueBool);
713         } else if (temp[INDEX_TYPE] == "null") {
714             valuesBucket.Put(temp[INDEX_KEY]);
715         } else if (temp[INDEX_TYPE] == "vector") {
716             std::vector<std::string> arr = ReminderRequest::StringSplit(temp[INDEX_VALUE],
717                 ReminderRequest::SEP_BUTTON_VALUE_BLOB);
718             std::vector<uint8_t> value;
719             for (auto &num : arr) {
720                 value.emplace_back(static_cast<uint8_t>(std::atoi(num.c_str())));
721             }
722             valuesBucket.Put(temp[INDEX_KEY], value);
723         }
724     }
725 }
726 
GenDstBundleName(std::string & dstBundleName,const std::string & uri) const727 void ReminderDataManager::GenDstBundleName(std::string &dstBundleName, const std::string &uri) const
728 {
729     size_t left = 0;
730     size_t right = 0;
731     left = uri.find("/", left);
732     right = uri.find("/", left + 1);
733     while (right != std::string::npos && right - left <= 1) {
734         left = right + 1;
735         right = uri.find("/", left);
736     }
737     if (left == std::string::npos) {
738         return;
739     }
740     if (right != std::string::npos) {
741         dstBundleName = uri.substr(left, right - left);
742     } else {
743         dstBundleName = uri.substr(left);
744     }
745 }
746 
RefreshRemindersDueToSysTimeChange(uint8_t type)747 void ReminderDataManager::RefreshRemindersDueToSysTimeChange(uint8_t type)
748 {
749     if (!IsSystemReady()) {
750         ANSR_LOGW("bundle service or ability service not ready.");
751         return;
752     }
753     std::string typeInfo = type == TIME_ZONE_CHANGE ? "timeZone" : "dateTime";
754     ANSR_LOGI("Refresh all reminders due to %{public}s changed by user", typeInfo.c_str());
755     if (activeReminderId_ != -1) {
756         ANSR_LOGD("Stop active reminder due to date/time or timeZone change");
757         {
758             std::lock_guard<std::mutex> locker(ReminderDataManager::ACTIVE_MUTEX);
759             activeReminder_->OnStop();
760         }
761         StopTimerLocked(TimerType::TRIGGER_TIMER);
762     }
763     std::vector<sptr<ReminderRequest>> showImmediately;
764     std::vector<sptr<ReminderRequest>> extensionReminders;
765     RefreshRemindersLocked(type, showImmediately, extensionReminders);
766     HandleImmediatelyShow(showImmediately, true);
767     HandleExtensionReminder(extensionReminders);
768     StartRecentReminder();
769 }
770 
TerminateAlerting(const OHOS::EventFwk::Want & want)771 void ReminderDataManager::TerminateAlerting(const OHOS::EventFwk::Want &want)
772 {
773     int32_t reminderId = static_cast<int32_t>(want.GetIntParam(ReminderRequest::PARAM_REMINDER_ID, -1));
774     sptr<ReminderRequest> reminder = FindReminderRequestLocked(reminderId);
775     if (reminder == nullptr) {
776         ANSR_LOGE("Invalid reminder id: %{public}d", reminderId);
777         return;
778     }
779     TerminateAlerting(reminder, "timeOut");
780 }
781 
TerminateAlerting(const uint16_t waitInSecond,const sptr<ReminderRequest> & reminder)782 void ReminderDataManager::TerminateAlerting(const uint16_t waitInSecond, const sptr<ReminderRequest> &reminder)
783 {
784     sleep(waitInSecond);
785     TerminateAlerting(reminder, "waitInMillis");
786 }
787 
TerminateAlerting(const sptr<ReminderRequest> & reminder,const std::string & reason)788 void ReminderDataManager::TerminateAlerting(const sptr<ReminderRequest> &reminder, const std::string &reason)
789 {
790     if (reminder == nullptr) {
791         ANSR_LOGE("TerminateAlerting illegal.");
792         return;
793     }
794     ANSR_LOGI("Terminate the alerting reminder, %{public}s, called by %{public}s",
795         reminder->Dump().c_str(), reason.c_str());
796     StopAlertingReminder(reminder);
797 
798     if (!reminder->OnTerminate()) {
799         return;
800     }
801     int32_t reminderId = reminder->GetReminderId();
802     sptr<NotificationBundleOption> bundleOption = reminder->GetNotificationBundleOption();
803     sptr<NotificationRequest> notificationRequest = reminder->GetNotificationRequest();
804     if (bundleOption == nullptr) {
805         ANSR_LOGE("Get bundle option fail, reminderId=%{public}d", reminderId);
806         return;
807     }
808     ANSR_LOGD("publish(update) notification.(reminderId=%{public}d)", reminder->GetReminderId());
809     UpdateNotification(reminder, false);
810     if (advancedNotificationService_ == nullptr) {
811         ANSR_LOGE("Ans instance is null.");
812         return;
813     }
814     // Set the notification SoundEnabled and VibrationEnabled by soltType
815     advancedNotificationService_->SetRequestBySlotType(notificationRequest, bundleOption);
816     advancedNotificationService_->PublishPreparedNotification(notificationRequest, bundleOption);
817     store_->UpdateOrInsert(reminder, bundleOption);
818 }
819 
UpdateAndSaveReminderLocked(const sptr<ReminderRequest> & reminder,const sptr<NotificationBundleOption> & bundleOption)820 void ReminderDataManager::UpdateAndSaveReminderLocked(
821     const sptr<ReminderRequest> &reminder, const sptr<NotificationBundleOption> &bundleOption)
822 {
823     std::lock_guard<std::mutex> lock(ReminderDataManager::MUTEX);
824     reminder->InitReminderId();
825     int32_t userId = -1;
826     OsAccountManagerHelper::GetInstance().GetOsAccountLocalIdFromUid(bundleOption->GetUid(), userId);
827     reminder->InitUserId(userId);
828     reminder->InitUid(bundleOption->GetUid());
829     reminder->InitBundleName(bundleOption->GetBundleName());
830 
831     if (reminder->GetTriggerTimeInMilli() == ReminderRequest::INVALID_LONG_LONG_VALUE) {
832         ANSR_LOGW("now publish reminder is expired. reminder is =%{public}s", reminder->Dump().c_str());
833         reminder->SetExpired(true);
834     }
835     reminder->SetNotificationBundleOption(bundleOption);
836     reminderVector_.push_back(reminder);
837     totalCount_++;
838     store_->UpdateOrInsert(reminder, bundleOption);
839 }
840 
SetService(sptr<AdvancedNotificationService> & advancedNotificationService)841 void ReminderDataManager::SetService(sptr<AdvancedNotificationService> &advancedNotificationService)
842 {
843     advancedNotificationService_ = advancedNotificationService;
844 }
845 
ShouldAlert(const sptr<ReminderRequest> & reminder) const846 bool ReminderDataManager::ShouldAlert(const sptr<ReminderRequest> &reminder) const
847 {
848     if (reminder == nullptr) {
849         return false;
850     }
851     int32_t reminderId = reminder->GetReminderId();
852     sptr<NotificationBundleOption> bundleOption = reminder->GetNotificationBundleOption();
853     if (bundleOption == nullptr) {
854         ANSR_LOGD("The reminder (reminderId=%{public}d) is silent", reminderId);
855         return false;
856     }
857     int32_t userId = -1;
858     OsAccountManagerHelper::GetInstance().GetOsAccountLocalIdFromUid(bundleOption->GetUid(), userId);
859     if (currentUserId_ != userId) {
860         ANSR_LOGD("The reminder (reminderId=%{public}d) is silent for not in active user, " \
861             "current user id: %{private}d, reminder user id: %{private}d", reminderId, currentUserId_, userId);
862         return false;
863     }
864 
865     sptr<NotificationDoNotDisturbDate> date;
866     ErrCode errCode = advancedNotificationService_->GetDoNotDisturbDate(date);
867     if (errCode != ERR_OK) {
868         ANSR_LOGE("The reminder (reminderId=%{public}d) is silent for get disturbDate error", reminderId);
869         return true;
870     }
871     if (date->GetDoNotDisturbType() == NotificationConstant::DoNotDisturbType::NONE) {
872         return true;
873     }
874     std::vector<sptr<NotificationSlot>> slots;
875     errCode = advancedNotificationService_->GetSlotsByBundle(bundleOption, slots);
876     if (errCode != ERR_OK) {
877         ANSR_LOGE("The reminder (reminderId=%{public}d) is silent for get slots error", reminderId);
878         return false;
879     }
880     for (auto slot : slots) {
881         if (slot->GetType() != reminder->GetSlotType()) {
882             continue;
883         }
884         if (slot->IsEnableBypassDnd()) {
885             ANSR_LOGD("Not silent for enable by pass Dnd, reminderId=%{public}d", reminderId);
886             return true;
887         }
888     }
889     ANSR_LOGD("The reminder (reminderId=%{public}d) is silent for Dnd", reminderId);
890     return false;
891 }
892 
ShowActiveReminder(const EventFwk::Want & want)893 void ReminderDataManager::ShowActiveReminder(const EventFwk::Want &want)
894 {
895     int32_t reminderId = static_cast<int32_t>(want.GetIntParam(ReminderRequest::PARAM_REMINDER_ID, -1));
896     ANSR_LOGI("Begin to show reminder(reminderId=%{public}d)", reminderId);
897     if (reminderId == activeReminderId_) {
898         ResetStates(TimerType::TRIGGER_TIMER);
899     }
900     sptr<ReminderRequest> reminder = FindReminderRequestLocked(reminderId);
901     if (reminder == nullptr) {
902         ANSR_LOGW("Invalid reminder id: %{public}d", reminderId);
903         return;
904     }
905     if (HandleSysTimeChange(reminder)) {
906         return;
907     }
908     ShowActiveReminderExtendLocked(reminder);
909     StartRecentReminder();
910 }
911 
HandleSysTimeChange(const sptr<ReminderRequest> reminder) const912 bool ReminderDataManager::HandleSysTimeChange(const sptr<ReminderRequest> reminder) const
913 {
914     if (reminder->CanShow()) {
915         return false;
916     } else {
917         ANSR_LOGI("handleSystimeChange, no need to show reminder again.");
918         return true;
919     }
920 }
921 
SetActiveReminder(const sptr<ReminderRequest> & reminder)922 void ReminderDataManager::SetActiveReminder(const sptr<ReminderRequest> &reminder)
923 {
924     if (reminder == nullptr) {
925         // activeReminder_ should not be set with null as it point to actual object.
926         activeReminderId_ = -1;
927     } else {
928         activeReminderId_ = reminder->GetReminderId();
929         std::lock_guard<std::mutex> locker(ReminderDataManager::ACTIVE_MUTEX);
930         activeReminder_ = reminder;
931     }
932     ANSR_LOGD("Set activeReminderId=%{public}d", activeReminderId_.load());
933 }
934 
SetAlertingReminder(const sptr<ReminderRequest> & reminder)935 void ReminderDataManager::SetAlertingReminder(const sptr<ReminderRequest> &reminder)
936 {
937     if (reminder == nullptr) {
938         // alertingReminder_ should not be set with null as it point to actual object.
939         alertingReminderId_ = -1;
940     } else {
941         alertingReminderId_ = reminder->GetReminderId();
942         alertingReminder_ = reminder;
943     }
944     ANSR_LOGD("Set alertingReminderId=%{public}d", alertingReminderId_.load());
945 }
946 
ShowActiveReminderExtendLocked(sptr<ReminderRequest> & reminder)947 void ReminderDataManager::ShowActiveReminderExtendLocked(sptr<ReminderRequest> &reminder)
948 {
949     std::lock_guard<std::mutex> lock(ReminderDataManager::MUTEX);
950     uint64_t triggerTime = reminder->GetTriggerTimeInMilli();
951     bool isAlerting = false;
952     sptr<ReminderRequest> playSoundReminder = nullptr;
953     for (auto it = reminderVector_.begin(); it != reminderVector_.end(); ++it) {
954         if ((*it)->IsExpired()) {
955             continue;
956         }
957         uint64_t tempTriggerTime = (*it)->GetTriggerTimeInMilli();
958         if (tempTriggerTime < triggerTime) {
959             ANSR_LOGE("this reminder triggerTime is less than target triggerTime.");
960             continue;
961         }
962         if (tempTriggerTime - triggerTime > ReminderRequest::SAME_TIME_DISTINGUISH_MILLISECONDS) {
963             continue;
964         }
965         if (!(*it)->IsNeedNotification()) {
966             continue;
967         }
968         ReminderDataManager::AsyncStartExtensionAbility((*it), CONNECT_EXTENSION_MAX_RETRY_TIMES);
969         if ((*it)->CheckExcludeDate()) {
970             ANSR_LOGI("reminder[%{public}d] trigger time is in exclude date", (*it)->GetReminderId());
971             continue;
972         }
973         if (((*it)->GetRingDuration() > 0) && !isAlerting) {
974             playSoundReminder = (*it);
975             isAlerting = true;
976         } else {
977             ShowReminder((*it), false, false, false, false);
978         }
979     }
980     if (playSoundReminder != nullptr) {
981         ShowReminder(playSoundReminder, true, false, false, true);
982     }
983 }
984 
StartExtensionAbility(const sptr<ReminderRequest> & reminder)985 bool ReminderDataManager::StartExtensionAbility(const sptr<ReminderRequest> &reminder)
986 {
987     ANSR_LOGD("StartExtensionAbility");
988     if (reminder->GetReminderType() == ReminderRequest::ReminderType::CALENDAR) {
989         ReminderRequestCalendar* calendar = static_cast<ReminderRequestCalendar*>(reminder.GetRefPtr());
990         std::shared_ptr<ReminderRequest::WantAgentInfo> wantInfo = calendar->GetRRuleWantAgentInfo();
991         if (wantInfo != nullptr && wantInfo->pkgName.size() != 0 && wantInfo->abilityName.size() != 0) {
992             AAFwk::Want want;
993             want.SetElementName(wantInfo->pkgName, wantInfo->abilityName);
994             want.SetParam(ReminderRequest::PARAM_REMINDER_ID, reminder->GetReminderId());
995             int32_t result = IN_PROCESS_CALL(
996                 AAFwk::AbilityManagerClient::GetInstance()->StartExtensionAbility(want, nullptr));
997             if (result != ERR_OK) {
998                 ANSR_LOGE("StartExtensionAbility failed[%{public}d]", result);
999                 return false;
1000             }
1001         }
1002     }
1003     return true;
1004 }
1005 
AsyncStartExtensionAbility(const sptr<ReminderRequest> & reminder,int32_t times)1006 void ReminderDataManager::AsyncStartExtensionAbility(const sptr<ReminderRequest> &reminder, int32_t times)
1007 {
1008     auto manager = ReminderDataManager::GetInstance();
1009     if (manager == nullptr) {
1010         ANSR_LOGW("ReminderDataManager is nullptr.");
1011         return;
1012     }
1013     if (!manager->IsSystemReady()) {
1014         ANSR_LOGW("bundle service or ability service not ready.");
1015         return;
1016     }
1017     if (!reminder->IsSystemApp()) {
1018         ANSR_LOGI("Start extension ability failed, is not system app");
1019         return;
1020     }
1021     times--;
1022     bool ret = ReminderDataManager::StartExtensionAbility(reminder);
1023     if (!ret && times > 0 && serviceQueue_ != nullptr) {
1024         ANSR_LOGD("StartExtensionAbilty failed, reminder times: %{public}d", times);
1025         ffrt::task_attr taskAttr;
1026         taskAttr.delay(CONNECT_EXTENSION_INTERVAL);
1027         auto callback = [reminder, times]() { ReminderDataManager::AsyncStartExtensionAbility(reminder, times); };
1028         serviceQueue_->submit(callback, taskAttr);
1029     }
1030 }
1031 
ShowReminder(const sptr<ReminderRequest> & reminder,const bool & isNeedToPlaySound,const bool & isNeedToStartNext,const bool & isSysTimeChanged,const bool & needScheduleTimeout)1032 void ReminderDataManager::ShowReminder(const sptr<ReminderRequest> &reminder, const bool &isNeedToPlaySound,
1033     const bool &isNeedToStartNext, const bool &isSysTimeChanged, const bool &needScheduleTimeout)
1034 {
1035     ANSR_LOGD("Show the reminder(Play sound: %{public}d), %{public}s",
1036         static_cast<int32_t>(isNeedToPlaySound), reminder->Dump().c_str());
1037     int32_t reminderId = reminder->GetReminderId();
1038     sptr<NotificationBundleOption> bundleOption = reminder->GetNotificationBundleOption();
1039     sptr<NotificationRequest> notificationRequest = reminder->GetNotificationRequest();
1040     if (bundleOption == nullptr) {
1041         ANSR_LOGE("Get bundle option fail, reminderId=%{public}d", reminderId);
1042         return;
1043     }
1044     if (advancedNotificationService_ == nullptr) {
1045         ANSR_LOGE("ShowReminder fail");
1046         reminder->OnShow(false, isSysTimeChanged, false);
1047         store_->UpdateOrInsert(reminder, bundleOption);
1048         return;
1049     }
1050     if (!IsAllowedNotify(reminder)) {
1051         ANSR_LOGE("Not allow to notify.");
1052         reminder->OnShow(false, isSysTimeChanged, false);
1053         store_->UpdateOrInsert(reminder, bundleOption);
1054         return;
1055     }
1056     ReportSysEvent(reminder);
1057     bool toPlaySound = isNeedToPlaySound && ShouldAlert(reminder) ? true : false;
1058     reminder->OnShow(toPlaySound, isSysTimeChanged, true);
1059     AddToShowedReminders(reminder);
1060     UpdateNotification(reminder, false);  // this should be called after OnShow
1061 
1062     if (alertingReminderId_ != -1) {
1063         TerminateAlerting(alertingReminder_, "PlaySoundAndVibration");
1064     }
1065     // Set the notification SoundEnabled and VibrationEnabled by soltType
1066     advancedNotificationService_->SetRequestBySlotType(notificationRequest, bundleOption);
1067     ErrCode errCode = advancedNotificationService_->PublishPreparedNotification(notificationRequest, bundleOption);
1068     if (errCode != ERR_OK) {
1069         reminder->OnShowFail();
1070         RemoveFromShowedReminders(reminder);
1071     } else {
1072         if (toPlaySound) {
1073             PlaySoundAndVibration(reminder);  // play sound and vibration
1074             if (needScheduleTimeout) {
1075                 StartTimer(reminder, TimerType::ALERTING_TIMER);
1076             } else {
1077                 TerminateAlerting(1, reminder);
1078             }
1079         }
1080         HandleSameNotificationIdShowing(reminder);
1081     }
1082     store_->UpdateOrInsert(reminder, bundleOption);
1083 
1084     if (isNeedToStartNext) {
1085         StartRecentReminder();
1086     }
1087 }
1088 
UpdateNotification(const sptr<ReminderRequest> & reminder,bool isSnooze)1089 void ReminderDataManager::UpdateNotification(const sptr<ReminderRequest> &reminder, bool isSnooze)
1090 {
1091     if (isSnooze) {
1092         reminder->UpdateNotificationRequest(ReminderRequest::UpdateNotificationType::COMMON, "snooze");
1093     } else {
1094         reminder->UpdateNotificationRequest(ReminderRequest::UpdateNotificationType::COMMON, "");
1095     }
1096     reminder->UpdateNotificationRequest(ReminderRequest::UpdateNotificationType::REMOVAL_WANT_AGENT, "");
1097     reminder->UpdateNotificationRequest(ReminderRequest::UpdateNotificationType::WANT_AGENT, "");
1098     reminder->UpdateNotificationRequest(ReminderRequest::UpdateNotificationType::MAX_SCREEN_WANT_AGENT, "");
1099     reminder->UpdateNotificationRequest(ReminderRequest::UpdateNotificationType::BUNDLE_INFO, "");
1100 }
1101 
SnoozeReminder(const OHOS::EventFwk::Want & want)1102 void ReminderDataManager::SnoozeReminder(const OHOS::EventFwk::Want &want)
1103 {
1104     int32_t reminderId = static_cast<int32_t>(want.GetIntParam(ReminderRequest::PARAM_REMINDER_ID, -1));
1105     sptr<ReminderRequest> reminder = FindReminderRequestLocked(reminderId);
1106     if (reminder == nullptr) {
1107         ANSR_LOGW("Invalid reminder id: %{public}d", reminderId);
1108         return;
1109     }
1110     SnoozeReminderImpl(reminder);
1111     UpdateAppDatabase(reminder, ReminderRequest::ActionButtonType::SNOOZE);
1112     CheckNeedNotifyStatus(reminder, ReminderRequest::ActionButtonType::SNOOZE);
1113 }
1114 
SnoozeReminderImpl(sptr<ReminderRequest> & reminder)1115 void ReminderDataManager::SnoozeReminderImpl(sptr<ReminderRequest> &reminder)
1116 {
1117     ANSR_LOGI("Snooze the reminder request, %{public}s", reminder->Dump().c_str());
1118     int32_t reminderId = reminder->GetReminderId();
1119     if (activeReminderId_ == reminderId) {
1120         ANSR_LOGD("Cancel active reminder, id=%{public}d", activeReminderId_.load());
1121         {
1122             std::lock_guard<std::mutex> locker(ReminderDataManager::ACTIVE_MUTEX);
1123             activeReminder_->OnStop();
1124         }
1125         StopTimerLocked(TimerType::TRIGGER_TIMER);
1126     }
1127 
1128     // 1) Snooze the reminder by manual
1129     if (alertingReminderId_ == reminder->GetReminderId()) {
1130         StopSoundAndVibrationLocked(reminder);
1131         StopTimerLocked(TimerType::ALERTING_TIMER);
1132     }
1133     reminder->OnSnooze();
1134     store_->UpdateOrInsert(reminder, reminder->GetNotificationBundleOption());
1135 
1136     // 2) Show the notification dialog in the systemUI
1137     sptr<NotificationBundleOption> bundleOption = reminder->GetNotificationBundleOption();
1138     sptr<NotificationRequest> notificationRequest = reminder->GetNotificationRequest();
1139     if (bundleOption == nullptr) {
1140         ANSR_LOGW("snoozeReminder, invalid bundle option");
1141         return;
1142     }
1143     ANSR_LOGD("publish(update) notification.(reminderId=%{public}d)", reminder->GetReminderId());
1144     UpdateNotification(reminder, true);
1145     if (advancedNotificationService_ == nullptr) {
1146         ANSR_LOGE("Ans instance is null");
1147         return;
1148     }
1149     // Set the notification SoundEnabled and VibrationEnabled by soltType
1150     advancedNotificationService_->SetRequestBySlotType(notificationRequest, bundleOption);
1151     advancedNotificationService_->PublishPreparedNotification(notificationRequest, bundleOption);
1152     StartRecentReminder();
1153 }
1154 
StartRecentReminder()1155 void ReminderDataManager::StartRecentReminder()
1156 {
1157     sptr<ReminderRequest> reminder = GetRecentReminderLocked();
1158     if (reminder == nullptr) {
1159         ANSR_LOGI("No reminder need to start");
1160         SetActiveReminder(reminder);
1161         return;
1162     }
1163     if (activeReminderId_ == reminder->GetReminderId()) {
1164         ANSR_LOGI("Recent reminder has already run, no need to start again.");
1165         return;
1166     }
1167     if (activeReminderId_ != -1) {
1168         {
1169             std::lock_guard<std::mutex> locker(ReminderDataManager::ACTIVE_MUTEX);
1170             activeReminder_->OnStop();
1171             store_->UpdateOrInsert(activeReminder_, activeReminder_->GetNotificationBundleOption());
1172         }
1173         StopTimerLocked(TimerType::TRIGGER_TIMER);
1174     }
1175     ANSR_LOGI("Start recent reminder");
1176     StartTimerLocked(reminder, TimerType::TRIGGER_TIMER);
1177     reminder->OnStart();
1178     store_->UpdateOrInsert(reminder, reminder->GetNotificationBundleOption());
1179 }
1180 
StopAlertingReminder(const sptr<ReminderRequest> & reminder)1181 void ReminderDataManager::StopAlertingReminder(const sptr<ReminderRequest> &reminder)
1182 {
1183     if (reminder == nullptr) {
1184         ANSR_LOGE("StopAlertingReminder illegal.");
1185         return;
1186     }
1187     if ((alertingReminderId_ == -1) || (reminder->GetReminderId() != alertingReminderId_)) {
1188         ANSR_LOGE("StopAlertingReminder is illegal.");
1189         return;
1190     }
1191     StopSoundAndVibration(alertingReminder_);
1192     StopTimer(TimerType::ALERTING_TIMER);
1193 }
1194 
Dump() const1195 std::string ReminderDataManager::Dump() const
1196 {
1197     std::lock_guard<std::mutex> lock(ReminderDataManager::MUTEX);
1198     std::map<std::string, std::vector<sptr<ReminderRequest>>> bundleNameMap;
1199     for (auto it = reminderVector_.begin(); it != reminderVector_.end(); ++it) {
1200         if ((*it)->IsExpired()) {
1201             continue;
1202         }
1203         std::string bundleName = (*it)->GetBundleName();
1204         auto val = bundleNameMap.find(bundleName);
1205         if (val == bundleNameMap.end()) {
1206             std::vector<sptr<ReminderRequest>> reminders;
1207             reminders.push_back(*it);
1208             bundleNameMap.insert(std::pair<std::string, std::vector<sptr<ReminderRequest>>>(bundleName, reminders));
1209         } else {
1210             val->second.push_back(*it);
1211         }
1212     }
1213 
1214     std::string allReminders = "";
1215     for (auto it = bundleNameMap.begin(); it != bundleNameMap.end(); ++it) {
1216         std::string bundleName = it->first;
1217         std::vector<sptr<ReminderRequest>> reminders = it->second;
1218         sort(reminders.begin(), reminders.end(), cmp);
1219         std::string oneBundleReminders = bundleName + ":{\n";
1220         oneBundleReminders += "    totalCount:" + std::to_string(reminders.size()) + ",\n";
1221         oneBundleReminders += "    reminders:{\n";
1222         for (auto vit = reminders.begin(); vit != reminders.end(); ++vit) {
1223             oneBundleReminders += "        [\n";
1224             std::string reminderInfo = (*vit)->Dump();
1225             oneBundleReminders += "            " + reminderInfo + "\n";
1226             oneBundleReminders += "        ],\n";
1227         }
1228         oneBundleReminders += "    },\n";
1229         oneBundleReminders += "},\n";
1230         allReminders += oneBundleReminders;
1231     }
1232 
1233     return "ReminderDataManager{ totalCount:" + std::to_string(totalCount_) + ",\n" +
1234            "timerId:" + std::to_string(timerId_) + ",\n" +
1235            "activeReminderId:" + std::to_string(activeReminderId_) + ",\n" +
1236            allReminders + "}";
1237 }
1238 
GetRecentReminderLocked()1239 sptr<ReminderRequest> ReminderDataManager::GetRecentReminderLocked()
1240 {
1241     std::lock_guard<std::mutex> lock(ReminderDataManager::MUTEX);
1242     sort(reminderVector_.begin(), reminderVector_.end(), cmp);
1243     for (auto it = reminderVector_.begin(); it != reminderVector_.end();) {
1244         if (!(*it)->IsExpired()) {
1245             ANSR_LOGI("GetRecentReminderLocked: %{public}s", (*it)->Dump().c_str());
1246             time_t now;
1247             (void)time(&now);  // unit is seconds.
1248             if (now < 0
1249                 || ReminderRequest::GetDurationSinceEpochInMilli(now) > (*it)->GetTriggerTimeInMilli()) {
1250                 ANSR_LOGE("Get recent reminder while the trigger time is overdue.");
1251                 it++;
1252                 continue;
1253             }
1254             return *it;
1255         }
1256         if (!(*it)->CanRemove()) {
1257             ANSR_LOGD("Reminder has been expired: %{public}s", (*it)->Dump().c_str());
1258             it++;
1259             continue;
1260         }
1261         int32_t reminderId = (*it)->GetReminderId();
1262         ANSR_LOGD("Containers(vector) remove. reminderId=%{public}d", reminderId);
1263         it = reminderVector_.erase(it);
1264         totalCount_--;
1265         store_->Delete(reminderId);
1266     }
1267     return nullptr;
1268 }
1269 
HandleImmediatelyShow(std::vector<sptr<ReminderRequest>> & showImmediately,bool isSysTimeChanged)1270 void ReminderDataManager::HandleImmediatelyShow(
1271     std::vector<sptr<ReminderRequest>> &showImmediately, bool isSysTimeChanged)
1272 {
1273     bool isAlerting = false;
1274     for (auto it = showImmediately.begin(); it != showImmediately.end(); ++it) {
1275         if ((*it)->IsShowing()) {
1276             continue;
1277         }
1278         if (((*it)->GetRingDuration() > 0) && !isAlerting) {
1279             std::lock_guard<std::mutex> lock(ReminderDataManager::MUTEX);
1280             ShowReminder((*it), true, false, isSysTimeChanged, true);
1281             isAlerting = true;
1282         } else {
1283             std::lock_guard<std::mutex> lock(ReminderDataManager::MUTEX);
1284             ShowReminder((*it), false, false, isSysTimeChanged, false);
1285         }
1286     }
1287 }
1288 
HandleExtensionReminder(std::vector<sptr<ReminderRequest>> & extensionReminders)1289 void ReminderDataManager::HandleExtensionReminder(std::vector<sptr<ReminderRequest>>& extensionReminders)
1290 {
1291     for (auto& reminder : extensionReminders) {
1292         ReminderDataManager::AsyncStartExtensionAbility(reminder, CONNECT_EXTENSION_MAX_RETRY_TIMES);
1293     }
1294 }
1295 
HandleRefreshReminder(const uint8_t & type,sptr<ReminderRequest> & reminder)1296 sptr<ReminderRequest> ReminderDataManager::HandleRefreshReminder(const uint8_t &type, sptr<ReminderRequest> &reminder)
1297 {
1298     reminder->SetReminderTimeInMilli(ReminderRequest::INVALID_LONG_LONG_VALUE);
1299     uint64_t triggerTimeBefore = reminder->GetTriggerTimeInMilli();
1300     bool needShowImmediately = false;
1301     if (type == TIME_ZONE_CHANGE) {
1302         needShowImmediately = reminder->OnTimeZoneChange();
1303     }
1304     if (type == DATE_TIME_CHANGE) {
1305         needShowImmediately = reminder->OnDateTimeChange();
1306     }
1307     if (!needShowImmediately) {
1308         uint64_t triggerTimeAfter = reminder->GetTriggerTimeInMilli();
1309         if (triggerTimeBefore != triggerTimeAfter || reminder->GetReminderId() == alertingReminderId_) {
1310             CloseReminder(reminder, true);
1311         }
1312         store_->UpdateOrInsert(reminder, reminder->GetNotificationBundleOption());
1313         return nullptr;
1314     }
1315     store_->UpdateOrInsert(reminder, reminder->GetNotificationBundleOption());
1316     return reminder;
1317 }
1318 
HandleSameNotificationIdShowing(const sptr<ReminderRequest> reminder)1319 void ReminderDataManager::HandleSameNotificationIdShowing(const sptr<ReminderRequest> reminder)
1320 {
1321     // not add ReminderDataManager::MUTEX, as ShowActiveReminderExtendLocked has locked
1322     int32_t notificationId = reminder->GetNotificationId();
1323     ANSR_LOGD("HandleSameNotificationIdShowing notificationId=%{public}d", notificationId);
1324     int32_t curReminderId = reminder->GetReminderId();
1325     sptr<NotificationBundleOption> option1 = reminder->GetNotificationBundleOption();
1326     if (option1 == nullptr) {
1327         ANSR_LOGE("Error occur when get bundle option, reminderId=%{public}d", curReminderId);
1328         return;
1329     }
1330 
1331     for (auto it = reminderVector_.begin(); it != reminderVector_.end(); ++it) {
1332         int32_t tmpId = (*it)->GetReminderId();
1333         if (tmpId == curReminderId) {
1334             continue;
1335         }
1336         if (!(*it)->IsShowing()) {
1337             continue;
1338         }
1339         sptr<NotificationBundleOption>  bundleOption = (*it)->GetNotificationBundleOption();
1340         if (bundleOption == nullptr) {
1341             ANSR_LOGW("Get notificationBundleOption(reminderId=%{public}d) fail", tmpId);
1342             continue;
1343         }
1344         if (notificationId == (*it)->GetNotificationId() && IsBelongToSameApp(bundleOption, option1)) {
1345             if ((*it)->IsAlerting()) {
1346                 StopAlertingReminder(*it);
1347             }
1348             (*it)->OnSameNotificationIdCovered();
1349             RemoveFromShowedReminders(*it);
1350             store_->UpdateOrInsert((*it), bundleOption);
1351         }
1352     }
1353 }
1354 
Init(bool isFromBootComplete)1355 void ReminderDataManager::Init(bool isFromBootComplete)
1356 {
1357     ANSR_LOGD("ReminderDataManager Init, isFromBootComplete:%{public}d", isFromBootComplete);
1358     if (isFromBootComplete) {
1359         std::vector<sptr<ReminderRequest>> immediatelyReminders;
1360         std::vector<sptr<ReminderRequest>> extensionReminders;
1361         CheckReminderTime(immediatelyReminders, extensionReminders);
1362         HandleImmediatelyShow(immediatelyReminders, false);
1363         HandleExtensionReminder(extensionReminders);
1364         StartRecentReminder();
1365     }
1366     if (IsReminderAgentReady()) {
1367         return;
1368     }
1369     // Register config observer for language change
1370     if (!RegisterConfigurationObserver()) {
1371         ANSR_LOGW("Register configuration observer failed.");
1372         return;
1373     }
1374     if (queue_ == nullptr) {
1375         queue_ = std::make_shared<ffrt::queue>("ReminderDataManager");
1376         if (queue_ == nullptr) {
1377             ANSR_LOGE("create ffrt queue failed!");
1378             return;
1379         }
1380     }
1381     if (store_ == nullptr) {
1382         store_ = std::make_shared<ReminderStore>();
1383     }
1384     if (store_->Init() != ReminderStore::STATE_OK) {
1385         ANSR_LOGW("Db init fail.");
1386         return;
1387     }
1388     InitServiceHandler();
1389     LoadReminderFromDb();
1390     InitUserId();
1391     isReminderAgentReady_ = true;
1392     ANSR_LOGD("ReminderAgent is ready.");
1393 }
1394 
InitServiceHandler()1395 void ReminderDataManager::InitServiceHandler()
1396 {
1397     ANSR_LOGD("InitServiceHandler started");
1398     if (serviceQueue_ != nullptr) {
1399         ANSR_LOGD("InitServiceHandler already init.");
1400         return;
1401     }
1402     serviceQueue_ = std::make_shared<ffrt::queue>("ReminderService");
1403 
1404     ANSR_LOGD("InitServiceHandler suceeded.");
1405 }
1406 
CheckReminderTime(std::vector<sptr<ReminderRequest>> & immediatelyReminders,std::vector<sptr<ReminderRequest>> & extensionReminders)1407 void ReminderDataManager::CheckReminderTime(std::vector<sptr<ReminderRequest>>& immediatelyReminders,
1408     std::vector<sptr<ReminderRequest>>& extensionReminders)
1409 {
1410     std::lock_guard<std::mutex> lock(ReminderDataManager::MUTEX);
1411     for (auto reminder : reminderVector_) {
1412         if (reminder->GetReminderType() != ReminderRequest::ReminderType::CALENDAR) {
1413             continue;
1414         }
1415 
1416         if (reminder->IsPullUpService()) {
1417             extensionReminders.push_back(reminder);
1418         }
1419 
1420         if (reminder->OnDateTimeChange()) {
1421             immediatelyReminders.push_back(reminder);
1422         }
1423     }
1424 }
1425 
InitUserId()1426 void ReminderDataManager::InitUserId()
1427 {
1428     std::vector<int32_t> activeUserId;
1429     AccountSA::OsAccountManager::QueryActiveOsAccountIds(activeUserId);
1430     if (activeUserId.size() > 0) {
1431         currentUserId_ = activeUserId[0];
1432         ANSR_LOGD("Init user id=%{private}d", currentUserId_);
1433     } else {
1434         currentUserId_ = MAIN_USER_ID;
1435         ANSR_LOGE("Failed to get active user id.");
1436     }
1437 }
1438 
RegisterConfigurationObserver()1439 bool ReminderDataManager::RegisterConfigurationObserver()
1440 {
1441     if (configChangeObserver_ != nullptr) {
1442         return true;
1443     }
1444 
1445     auto appMgrClient = std::make_shared<AppExecFwk::AppMgrClient>();
1446     if (appMgrClient->ConnectAppMgrService() != ERR_OK) {
1447         ANSR_LOGW("Connect to app mgr service failed.");
1448         return false;
1449     }
1450 
1451     configChangeObserver_ = sptr<AppExecFwk::IConfigurationObserver>(
1452         new (std::nothrow) ReminderConfigChangeObserver());
1453     if (appMgrClient->RegisterConfigurationObserver(configChangeObserver_) != ERR_OK) {
1454         ANSR_LOGE("Register configuration observer failed.");
1455         return false;
1456     }
1457     return true;
1458 }
1459 
GetImmediatelyShowRemindersLocked(std::vector<sptr<ReminderRequest>> & reminders) const1460 void ReminderDataManager::GetImmediatelyShowRemindersLocked(std::vector<sptr<ReminderRequest>> &reminders) const
1461 {
1462     std::lock_guard<std::mutex> lock(ReminderDataManager::MUTEX);
1463     for (auto reminderSptr : reminderVector_) {
1464         if (!(reminderSptr->ShouldShowImmediately())) {
1465             break;
1466         }
1467         if (reminderSptr->GetReminderType() != ReminderRequest::ReminderType::TIMER) {
1468             reminderSptr->SetSnoozeTimesDynamic(0);
1469         }
1470         reminders.push_back(reminderSptr);
1471     }
1472 }
1473 
IsAllowedNotify(const sptr<ReminderRequest> & reminder) const1474 bool ReminderDataManager::IsAllowedNotify(const sptr<ReminderRequest> &reminder) const
1475 {
1476     if (reminder == nullptr) {
1477         return false;
1478     }
1479     auto option = reminder->GetNotificationBundleOption();
1480     if (option == nullptr) {
1481         ANSR_LOGE("Get bundle option occur error, reminderId=%{public}d", reminder->GetReminderId());
1482         return false;
1483     }
1484     bool isAllowed = false;
1485     ErrCode errCode = advancedNotificationService_->IsSpecialBundleAllowedNotify(option, isAllowed);
1486     if (errCode != ERR_OK) {
1487         ANSR_LOGE("Failed to call IsSpecialBundleAllowedNotify, errCode=%{public}d", errCode);
1488         return false;
1489     }
1490     return isAllowed;
1491 }
1492 
IsReminderAgentReady() const1493 bool ReminderDataManager::IsReminderAgentReady() const
1494 {
1495     return isReminderAgentReady_;
1496 }
1497 
CheckIsSameApp(const sptr<ReminderRequest> & reminder,const sptr<NotificationBundleOption> & other) const1498 bool ReminderDataManager::CheckIsSameApp(const sptr<ReminderRequest> &reminder,
1499     const sptr<NotificationBundleOption> &other) const
1500 {
1501     std::string bundleName = reminder->GetCreatorBundleName();
1502     int32_t uid = reminder->GetCreatorUid();
1503     if (uid == -1) {
1504         uid = BundleManagerHelper::GetInstance()->GetDefaultUidByBundleName(bundleName, reminder->GetUserId());
1505     }
1506     return bundleName == other->GetBundleName() && uid == other->GetUid();
1507 }
1508 
IsBelongToSameApp(const sptr<NotificationBundleOption> & bundleOption,const sptr<NotificationBundleOption> & other) const1509 bool ReminderDataManager::IsBelongToSameApp(const sptr<NotificationBundleOption> &bundleOption,
1510     const sptr<NotificationBundleOption> &other) const
1511 {
1512     int32_t uidSrc = bundleOption->GetUid();
1513     int32_t uidTar = other->GetUid();
1514     bool result = uidSrc == uidTar;
1515     int32_t userIdSrc = -1;
1516     OsAccountManagerHelper::GetInstance().GetOsAccountLocalIdFromUid(uidSrc, userIdSrc);
1517     int32_t userIdTar = -1;
1518     OsAccountManagerHelper::GetInstance().GetOsAccountLocalIdFromUid(uidTar, userIdTar);
1519     result = result && (userIdSrc == userIdTar);
1520     result = result && (bundleOption->GetBundleName() == other->GetBundleName());
1521     return result;
1522 }
1523 
LoadReminderFromDb()1524 void ReminderDataManager::LoadReminderFromDb()
1525 {
1526     std::lock_guard<std::mutex> lock(ReminderDataManager::MUTEX);
1527     std::vector<sptr<ReminderRequest>> existReminders = store_->GetAllValidReminders();
1528     reminderVector_ = existReminders;
1529     ANSR_LOGD("LoadReminderFromDb, reminder size=%{public}zu", reminderVector_.size());
1530     for (auto it = reminderVector_.begin(); it != reminderVector_.end(); ++it) {
1531         sptr<NotificationBundleOption> bundleOption = new (std::nothrow) NotificationBundleOption();
1532         if (bundleOption == nullptr) {
1533             ANS_LOGE("Failed to create bundle option due to low memory.");
1534             return;
1535         }
1536         bundleOption->SetBundleName((*it)->GetBundleName());
1537         bundleOption->SetUid((*it)->GetUid());
1538         (*it)->SetNotificationBundleOption(bundleOption);
1539     }
1540     totalCount_ = static_cast<int16_t>(reminderVector_.size());
1541     ReminderRequest::GLOBAL_ID = store_->GetMaxId() + 1;
1542 }
1543 
PlaySoundAndVibrationLocked(const sptr<ReminderRequest> & reminder)1544 void ReminderDataManager::PlaySoundAndVibrationLocked(const sptr<ReminderRequest> &reminder)
1545 {
1546     std::lock_guard<std::mutex> lock(ReminderDataManager::ALERT_MUTEX);
1547     PlaySoundAndVibration(reminder);
1548 }
1549 
GetCustomRingUri(const sptr<ReminderRequest> & reminder)1550 std::string ReminderDataManager::GetCustomRingUri(const sptr<ReminderRequest> &reminder)
1551 {
1552     if (reminder == nullptr) {
1553         return "";
1554     }
1555     return reminder->GetCustomRingUri();
1556 }
1557 
GetFullPath(const std::string & oriPath)1558 std::string ReminderDataManager::GetFullPath(const std::string& oriPath)
1559 {
1560     char buf[MAX_PATH_LEN] = {0};
1561     char* path = GetOneCfgFile(oriPath.c_str(), buf, MAX_PATH_LEN);
1562     if (path == nullptr || *path == '\0') {
1563         ANSR_LOGE("GetOneCfgFile failed");
1564         return "";
1565     }
1566     std::string filePath = path;
1567     return filePath;
1568 }
1569 
PlaySoundAndVibration(const sptr<ReminderRequest> & reminder)1570 void ReminderDataManager::PlaySoundAndVibration(const sptr<ReminderRequest> &reminder)
1571 {
1572     if (reminder == nullptr) {
1573         ANSR_LOGE("Play sound and vibration failed as reminder is null.");
1574         return;
1575     }
1576     if (alertingReminderId_ != -1) {
1577         TerminateAlerting(alertingReminder_, "PlaySoundAndVibration");
1578     }
1579     ANSR_LOGD("Play sound and vibration, reminderId=%{public}d", reminder->GetReminderId());
1580 #ifdef PLAYER_FRAMEWORK_ENABLE
1581     if (soundPlayer_ == nullptr) {
1582         soundPlayer_ = Media::PlayerFactory::CreatePlayer();
1583         if (soundPlayer_ == nullptr) {
1584             ANSR_LOGE("Fail to creat player.");
1585             return;
1586         }
1587     }
1588     std::string customRingUri = reminder->GetCustomRingUri();
1589     if (customRingUri.empty()) {
1590         // use default ring
1591         std::string defaultPath;
1592         if (access(DEFAULT_REMINDER_SOUND_1.c_str(), F_OK) == 0) {
1593             defaultPath = "file:/" + DEFAULT_REMINDER_SOUND_1;
1594         } else {
1595             defaultPath = "file:/" + GetFullPath(DEFAULT_REMINDER_SOUND_2);
1596         }
1597         Uri defaultSound(defaultPath);
1598         soundPlayer_->SetSource(defaultSound.GetSchemeSpecificPart());
1599         ANSR_LOGI("Play default sound.");
1600     } else {
1601         Global::Resource::ResourceManager::RawFileDescriptor desc;
1602         if (GetCustomRingFileDesc(reminder, desc)) {
1603             soundPlayer_->SetSource(desc.fd, desc.offset, desc.length);
1604         }
1605         ANSR_LOGI("Play custom sound, reminderId:[%{public}d].", reminder->GetReminderId());
1606     }
1607     soundPlayer_->SetLooping(true);
1608     soundPlayer_->PrepareAsync();
1609     soundPlayer_->Play();
1610 #endif
1611     SetAlertingReminder(reminder);
1612 }
1613 
GetSoundUri(const sptr<ReminderRequest> & reminder)1614 std::string ReminderDataManager::GetSoundUri(const sptr<ReminderRequest> &reminder)
1615 {
1616     Uri uri = DEFAULT_NOTIFICATION_SOUND;
1617     if (advancedNotificationService_ == nullptr) {
1618         ANSR_LOGE("Ans instance is null.");
1619         return uri.GetSchemeSpecificPart();
1620     }
1621     sptr<NotificationBundleOption> bundle = reminder->GetNotificationBundleOption();
1622     std::vector<sptr<NotificationSlot>> slots;
1623     ErrCode errCode = advancedNotificationService_->GetSlotsByBundle(bundle, slots);
1624     if (errCode != ERR_OK) {
1625         ANSR_LOGW("Get sound uri fail, use default sound instead.");
1626         return uri.GetSchemeSpecificPart();
1627     }
1628     for (auto it = slots.begin(); it != slots.end(); ++it) {
1629         if ((*it)->GetType() == reminder->GetSlotType()) {
1630             uri = (*it)->GetSound();
1631             break;
1632         }
1633     }
1634     return uri.GetSchemeSpecificPart();
1635 }
1636 
StopSoundAndVibrationLocked(const sptr<ReminderRequest> & reminder)1637 void ReminderDataManager::StopSoundAndVibrationLocked(const sptr<ReminderRequest> &reminder)
1638 {
1639     std::lock_guard<std::mutex> lock(ReminderDataManager::ALERT_MUTEX);
1640     StopSoundAndVibration(reminder);
1641 }
1642 
StopSoundAndVibration(const sptr<ReminderRequest> & reminder)1643 void ReminderDataManager::StopSoundAndVibration(const sptr<ReminderRequest> &reminder)
1644 {
1645     if (reminder == nullptr) {
1646         ANSR_LOGE("Stop sound and vibration failed as reminder is null.");
1647         return;
1648     }
1649     if ((alertingReminderId_ == -1) || (reminder->GetReminderId() != alertingReminderId_)) {
1650         ANSR_LOGE("Stop sound and vibration failed as alertingReminder is illegal, alertingReminderId_=" \
1651             "%{public}d, tarReminderId=%{public}d", alertingReminderId_.load(), reminder->GetReminderId());
1652         return;
1653     }
1654     ANSR_LOGD("Stop sound and vibration, reminderId=%{public}d", reminder->GetReminderId());
1655 #ifdef PLAYER_FRAMEWORK_ENABLE
1656     if (soundPlayer_ == nullptr) {
1657         ANSR_LOGW("Sound player is null");
1658     } else {
1659         std::string customRingUri = reminder->GetCustomRingUri();
1660         if (customRingUri.empty()) {
1661             ANSR_LOGI("Stop default sound.");
1662         } else {
1663             CloseCustomRingFileDesc(reminder->GetReminderId(), customRingUri);
1664         }
1665         soundPlayer_->Stop();
1666         soundPlayer_->Release();
1667         soundPlayer_ = nullptr;
1668     }
1669 #endif
1670     sptr<ReminderRequest> nullReminder = nullptr;
1671     SetAlertingReminder(nullReminder);
1672 }
1673 
RemoveFromShowedReminders(const sptr<ReminderRequest> & reminder)1674 void ReminderDataManager::RemoveFromShowedReminders(const sptr<ReminderRequest> &reminder)
1675 {
1676     std::lock_guard<std::mutex> lock(ReminderDataManager::SHOW_MUTEX);
1677     for (auto it = showedReminderVector_.begin(); it != showedReminderVector_.end(); ++it) {
1678         if ((*it)->GetReminderId() == reminder->GetReminderId()) {
1679             ANSR_LOGD("Containers(shownVector) remove. reminderId=%{public}d", reminder->GetReminderId());
1680             showedReminderVector_.erase(it);
1681             break;
1682         }
1683     }
1684 }
1685 
RefreshRemindersLocked(uint8_t type,std::vector<sptr<ReminderRequest>> & immediatelyReminders,std::vector<sptr<ReminderRequest>> & extensionReminders)1686 void ReminderDataManager::RefreshRemindersLocked(uint8_t type,
1687     std::vector<sptr<ReminderRequest>>& immediatelyReminders, std::vector<sptr<ReminderRequest>>& extensionReminders)
1688 {
1689     std::lock_guard<std::mutex> lock(ReminderDataManager::MUTEX);
1690     for (auto it = reminderVector_.begin(); it != reminderVector_.end(); ++it) {
1691         if ((*it)->IsPullUpService()) {
1692             extensionReminders.push_back((*it));
1693         }
1694 
1695         sptr<ReminderRequest> reminder = HandleRefreshReminder(type, (*it));
1696         if (reminder != nullptr) {
1697             immediatelyReminders.push_back(reminder);
1698         }
1699     }
1700 }
1701 
RemoveReminderLocked(const int32_t & reminderId)1702 void ReminderDataManager::RemoveReminderLocked(const int32_t &reminderId)
1703 {
1704     std::lock_guard<std::mutex> lock(ReminderDataManager::MUTEX);
1705     for (auto it = reminderVector_.begin(); it != reminderVector_.end();) {
1706         if (reminderId == (*it)->GetReminderId()) {
1707             ANSR_LOGD("Containers(vector) remove. reminderId=%{public}d", reminderId);
1708             it = reminderVector_.erase(it);
1709             totalCount_--;
1710             store_->Delete(reminderId);
1711             break;
1712         } else {
1713             ++it;
1714         }
1715     }
1716 }
1717 
StartTimerLocked(const sptr<ReminderRequest> & reminderRequest,TimerType type)1718 void ReminderDataManager::StartTimerLocked(const sptr<ReminderRequest> &reminderRequest, TimerType type)
1719 {
1720     std::lock_guard<std::mutex> lock(ReminderDataManager::TIMER_MUTEX);
1721     StartTimer(reminderRequest, type);
1722 }
1723 
StartTimer(const sptr<ReminderRequest> & reminderRequest,TimerType type)1724 void ReminderDataManager::StartTimer(const sptr<ReminderRequest> &reminderRequest, TimerType type)
1725 {
1726     sptr<MiscServices::TimeServiceClient> timer = MiscServices::TimeServiceClient::GetInstance();
1727     if (timer == nullptr) {
1728         ANS_LOGE("Failed to start timer due to get TimeServiceClient is null.");
1729         return;
1730     }
1731     time_t now;
1732     (void)time(&now);  // unit is seconds.
1733     if (now < 0) {
1734         ANSR_LOGE("Get now time error");
1735         return;
1736     }
1737     uint64_t triggerTime = 0;
1738     switch (type) {
1739         case TimerType::TRIGGER_TIMER: {
1740             if (timerId_ != 0) {
1741                 ANSR_LOGE("Trigger timer has already started.");
1742                 break;
1743             }
1744             triggerTime = HandleTriggerTimeInner(reminderRequest, type, timer);
1745             break;
1746         }
1747         case TimerType::ALERTING_TIMER: {
1748             if (timerIdAlerting_ != 0) {
1749                 ANSR_LOGE("Alerting time out timer has already started.");
1750                 break;
1751             }
1752             triggerTime = HandleAlertingTimeInner(reminderRequest, type, timer, now);
1753             break;
1754         }
1755         default: {
1756             ANSR_LOGE("TimerType not support");
1757             break;
1758         }
1759     }
1760     if (triggerTime == 0) {
1761         ANSR_LOGW("Start timer fail");
1762     } else {
1763         ANSR_LOGD("Timing info: now:(%{public}" PRIu64 "), tar:(%{public}" PRIu64 ")",
1764             ReminderRequest::GetDurationSinceEpochInMilli(now), triggerTime);
1765     }
1766 }
1767 
HandleTriggerTimeInner(const sptr<ReminderRequest> & reminderRequest,TimerType type,const sptr<MiscServices::TimeServiceClient> & timer)1768 uint64_t ReminderDataManager::HandleTriggerTimeInner(const sptr<ReminderRequest> &reminderRequest, TimerType type,
1769     const sptr<MiscServices::TimeServiceClient> &timer)
1770 {
1771     uint64_t triggerTime = 0;
1772     SetActiveReminder(reminderRequest);
1773     timerId_ = timer->CreateTimer(REMINDER_DATA_MANAGER->CreateTimerInfo(type, reminderRequest));
1774     triggerTime = reminderRequest->GetTriggerTimeInMilli();
1775     timer->StartTimer(timerId_, triggerTime);
1776     ANSR_LOGD("Start timing (next triggerTime), timerId=%{public}" PRIu64 "", timerId_);
1777     return triggerTime;
1778 }
1779 
HandleAlertingTimeInner(const sptr<ReminderRequest> & reminderRequest,TimerType type,const sptr<MiscServices::TimeServiceClient> & timer,time_t now)1780 uint64_t ReminderDataManager::HandleAlertingTimeInner(const sptr<ReminderRequest> &reminderRequest, TimerType type,
1781     const sptr<MiscServices::TimeServiceClient> &timer, time_t now)
1782 {
1783     uint64_t triggerTime = 0;
1784     triggerTime = ReminderRequest::GetDurationSinceEpochInMilli(now)
1785         + static_cast<uint64_t>(reminderRequest->GetRingDuration() * ReminderRequest::MILLI_SECONDS);
1786     timerIdAlerting_ = timer->CreateTimer(REMINDER_DATA_MANAGER->CreateTimerInfo(type, reminderRequest));
1787     timer->StartTimer(timerIdAlerting_, triggerTime);
1788     ANSR_LOGD("Start timing (alerting time out), timerId=%{public}" PRIu64 "", timerIdAlerting_.load());
1789     return triggerTime;
1790 }
1791 
StopTimerLocked(TimerType type)1792 void ReminderDataManager::StopTimerLocked(TimerType type)
1793 {
1794     std::lock_guard<std::mutex> lock(ReminderDataManager::TIMER_MUTEX);
1795     StopTimer(type);
1796 }
1797 
StopTimer(TimerType type)1798 void ReminderDataManager::StopTimer(TimerType type)
1799 {
1800     sptr<MiscServices::TimeServiceClient> timer = MiscServices::TimeServiceClient::GetInstance();
1801     if (timer == nullptr) {
1802         ANSR_LOGE("Failed to stop timer due to get TimeServiceClient is null.");
1803         return;
1804     }
1805     uint64_t timerId = 0;
1806     switch (type) {
1807         case TimerType::TRIGGER_TIMER: {
1808             timerId = timerId_;
1809             ANSR_LOGD("Stop timing (next triggerTime)");
1810             break;
1811         }
1812         case TimerType::ALERTING_TIMER: {
1813             timerId = timerIdAlerting_;
1814             ANSR_LOGD("Stop timing (alerting time out)");
1815             break;
1816         }
1817         default: {
1818             ANSR_LOGE("TimerType not support");
1819             break;
1820         }
1821     }
1822     if (timerId == 0) {
1823         ANSR_LOGD("Timer is not running");
1824         return;
1825     }
1826     ANSR_LOGD("Stop timer id=%{public}" PRIu64 "", timerId);
1827     timer->StopTimer(timerId);
1828     ResetStates(type);
1829 }
1830 
ResetStates(TimerType type)1831 void ReminderDataManager::ResetStates(TimerType type)
1832 {
1833     switch (type) {
1834         case TimerType::TRIGGER_TIMER: {
1835             ANSR_LOGD("ResetStates(activeReminderId, timerId(next triggerTime))");
1836             timerId_ = 0;
1837             activeReminderId_ = -1;
1838             break;
1839         }
1840         case TimerType::ALERTING_TIMER: {
1841             ANSR_LOGD("ResetStates(alertingReminderId, timeId(alerting time out))");
1842             timerIdAlerting_ = 0;
1843             alertingReminderId_ = -1;
1844             break;
1845         }
1846         default: {
1847             ANSR_LOGE("TimerType not support");
1848             break;
1849         }
1850     }
1851 }
1852 
HandleCustomButtonClick(const OHOS::EventFwk::Want & want)1853 void ReminderDataManager::HandleCustomButtonClick(const OHOS::EventFwk::Want &want)
1854 {
1855     int32_t reminderId = static_cast<int32_t>(want.GetIntParam(ReminderRequest::PARAM_REMINDER_ID, -1));
1856     sptr<ReminderRequest> reminder = FindReminderRequestLocked(reminderId);
1857     if (reminder == nullptr) {
1858         ANSR_LOGE("Invalid reminder id: %{public}d", reminderId);
1859         return;
1860     }
1861     if (!reminder->IsSystemApp()) {
1862         ANSR_LOGI("Custom button click, is not system app");
1863         return;
1864     }
1865     CloseReminder(reminder, false);
1866     UpdateAppDatabase(reminder, ReminderRequest::ActionButtonType::CUSTOM);
1867     std::string buttonPkgName = want.GetStringParam("PkgName");
1868     std::string buttonAbilityName = want.GetStringParam("AbilityName");
1869 
1870     AAFwk::Want abilityWant;
1871     abilityWant.SetElementName(buttonPkgName, buttonAbilityName);
1872     abilityWant.SetUri(reminder->GetCustomButtonUri());
1873     auto client = AppExecFwk::AbilityManagerClient::GetInstance();
1874     if (client == nullptr) {
1875         return;
1876     }
1877     uint32_t specifyTokenId = static_cast<uint32_t>(IPCSkeleton::GetSelfTokenID());
1878     int32_t result = client->StartAbilityOnlyUIAbility(abilityWant, nullptr, specifyTokenId);
1879     if (result != 0) {
1880         ANSR_LOGE("Start ability failed, result = %{public}d", result);
1881         return;
1882     }
1883 }
1884 
ClickReminder(const OHOS::EventFwk::Want & want)1885 void ReminderDataManager::ClickReminder(const OHOS::EventFwk::Want &want)
1886 {
1887     int32_t reminderId = static_cast<int32_t>(want.GetIntParam(ReminderRequest::PARAM_REMINDER_ID, -1));
1888     ANSR_LOGI("click reminder[%{public}d] start", reminderId);
1889     sptr<ReminderRequest> reminder = FindReminderRequestLocked(reminderId);
1890     if (reminder == nullptr) {
1891         ANSR_LOGW("Invalid reminder id: %{public}d", reminderId);
1892         return;
1893     }
1894     CloseReminder(reminder, true);
1895     UpdateAppDatabase(reminder, ReminderRequest::ActionButtonType::CLOSE);
1896     CheckNeedNotifyStatus(reminder, ReminderRequest::ActionButtonType::CLOSE);
1897     StartRecentReminder();
1898 
1899     auto wantInfo = reminder->GetWantAgentInfo();
1900     if (wantInfo == nullptr || (wantInfo->pkgName.empty() && wantInfo->abilityName.empty())) {
1901         ANSR_LOGW("want info is nullptr or no pkg name");
1902         return;
1903     }
1904     AAFwk::Want abilityWant;
1905     AppExecFwk::ElementName element("", wantInfo->pkgName, wantInfo->abilityName);
1906     abilityWant.SetElement(element);
1907     abilityWant.SetUri(wantInfo->uri);
1908     abilityWant.SetParams(wantInfo->parameters);
1909     int32_t appIndex = BundleManagerHelper::GetInstance()->GetAppIndexByUid(reminder->GetUid());
1910     abilityWant.SetParam("ohos.extra.param.key.appCloneIndex", appIndex);
1911 
1912     auto client = AppExecFwk::AbilityManagerClient::GetInstance();
1913     if (client == nullptr) {
1914         ANSR_LOGE("start ability failed, due to ability mgr client is nullptr.");
1915         return;
1916     }
1917     uint32_t specifyTokenId = static_cast<uint32_t>(IPCSkeleton::GetSelfTokenID());
1918     int32_t result = client->StartAbilityOnlyUIAbility(abilityWant, nullptr, specifyTokenId);
1919     if (result != 0) {
1920         ANSR_LOGE("Start ability failed, result = %{public}d", result);
1921     }
1922 }
1923 
GetResourceMgr(const std::string & bundleName,const int32_t uid)1924 std::shared_ptr<Global::Resource::ResourceManager> ReminderDataManager::GetResourceMgr(const std::string& bundleName,
1925     const int32_t uid)
1926 {
1927     AppExecFwk::BundleInfo bundleInfo;
1928     if (!BundleManagerHelper::GetInstance()->GetBundleInfo(bundleName,
1929         AppExecFwk::BundleFlag::GET_BUNDLE_WITH_ABILITIES, uid, bundleInfo)) {
1930         ANSR_LOGE("GetBundleInfo[%{public}s][%{public}d] fail.", bundleName.c_str(), uid);
1931         return nullptr;
1932     }
1933     // obtains the resource manager
1934     std::shared_ptr<Global::Resource::ResourceManager> resourceManager(Global::Resource::CreateResourceManager());
1935     if (!resourceManager) {
1936         ANSR_LOGE("CreateResourceManager fail.");
1937         return nullptr;
1938     }
1939     // obtains the resource path.
1940     for (const auto &hapModuleInfo : bundleInfo.hapModuleInfos) {
1941         std::string moduleResPath = hapModuleInfo.hapPath.empty() ? hapModuleInfo.resourcePath : hapModuleInfo.hapPath;
1942         if (moduleResPath.empty()) {
1943             continue;
1944         }
1945         if (!resourceManager->AddResource(moduleResPath.c_str())) {
1946             ANSR_LOGW("AddResource fail.");
1947         }
1948     }
1949     // obtains the current system language.
1950     std::unique_ptr<Global::Resource::ResConfig> resConfig(Global::Resource::CreateResConfig());
1951     UErrorCode status = U_ZERO_ERROR;
1952     icu::Locale locale = icu::Locale::forLanguageTag(Global::I18n::LocaleConfig::GetSystemLanguage(), status);
1953     resConfig->SetLocaleInfo(locale);
1954     resourceManager->UpdateResConfig(*resConfig);
1955     return resourceManager;
1956 }
1957 
UpdateReminderLanguageLocked(const int32_t uid,const std::vector<sptr<ReminderRequest>> & reminders)1958 void ReminderDataManager::UpdateReminderLanguageLocked(const int32_t uid,
1959     const std::vector<sptr<ReminderRequest>>& reminders)
1960 {
1961     // obtains the bundle info by bundle name
1962     if (reminders.empty()) {
1963         return;
1964     }
1965 
1966     std::string bundleName = reminders[0]->GetBundleName();
1967     // obtains the resource manager
1968     auto resourceMgr = GetResourceMgr(bundleName, uid);
1969     if (resourceMgr == nullptr) {
1970         ANSR_LOGE("Get reminder request[%{public}d][%{public}s] resource manager failed.",
1971             uid, bundleName.c_str());
1972         return;
1973     }
1974     // update action button title
1975     for (auto reminder : reminders) {
1976         std::lock_guard<std::mutex> lock(ReminderDataManager::MUTEX);
1977         reminder->OnLanguageChange(resourceMgr);
1978     }
1979 }
1980 
OnLanguageChanged()1981 void ReminderDataManager::OnLanguageChanged()
1982 {
1983     ANSR_LOGI("System language config changed start.");
1984     std::unordered_map<int32_t, std::vector<sptr<ReminderRequest>>> reminders;
1985     {
1986         std::lock_guard<std::mutex> lock(ReminderDataManager::MUTEX);
1987         for (auto it = reminderVector_.begin(); it != reminderVector_.end(); ++it) {
1988             reminders[(*it)->GetUid()].push_back((*it));
1989         }
1990     }
1991     for (auto& each : reminders) {
1992         UpdateReminderLanguageLocked(each.first, each.second);
1993     }
1994     std::vector<sptr<ReminderRequest>> showedReminder;
1995     {
1996         std::lock_guard<std::mutex> lock(ReminderDataManager::SHOW_MUTEX);
1997         showedReminder = showedReminderVector_;
1998     }
1999     for (auto it = showedReminder.begin(); it != showedReminder.end(); ++it) {
2000         std::lock_guard<std::mutex> lock(ReminderDataManager::MUTEX);
2001         ShowReminder((*it), false, false, false, false);
2002     }
2003     ANSR_LOGI("System language config changed end.");
2004 }
2005 
OnRemoveAppMgr()2006 void ReminderDataManager::OnRemoveAppMgr()
2007 {
2008     std::lock_guard<std::mutex> lock(appMgrMutex_);
2009     appMgrProxy_ = nullptr;
2010 }
2011 
ConnectAppMgr()2012 bool ReminderDataManager::ConnectAppMgr()
2013 {
2014     if (appMgrProxy_ != nullptr) {
2015         return true;
2016     }
2017 
2018     sptr<ISystemAbilityManager> systemAbilityManager =
2019         SystemAbilityManagerClient::GetInstance().GetSystemAbilityManager();
2020     if (systemAbilityManager == nullptr) {
2021         ANSR_LOGE("get SystemAbilityManager failed");
2022         return false;
2023     }
2024 
2025     sptr<IRemoteObject> remoteObject = systemAbilityManager->GetSystemAbility(APP_MGR_SERVICE_ID);
2026     if (remoteObject == nullptr) {
2027         ANSR_LOGE("get app manager service failed");
2028         return false;
2029     }
2030 
2031     appMgrProxy_ = iface_cast<AppExecFwk::IAppMgr>(remoteObject);
2032     if (!appMgrProxy_ || !appMgrProxy_->AsObject()) {
2033         ANSR_LOGE("get app mgr proxy failed!");
2034         return false;
2035     }
2036     return true;
2037 }
2038 
CheckNeedNotifyStatus(const sptr<ReminderRequest> & reminder,const ReminderRequest::ActionButtonType buttonType)2039 void ReminderDataManager::CheckNeedNotifyStatus(const sptr<ReminderRequest> &reminder,
2040     const ReminderRequest::ActionButtonType buttonType)
2041 {
2042     const std::string bundleName = reminder->GetBundleName();
2043     if (bundleName.empty()) {
2044         return;
2045     }
2046     bool isRunning = false;
2047     {
2048         std::lock_guard<std::mutex> lock(appMgrMutex_);
2049         if (!ConnectAppMgr()) {
2050             return;
2051         }
2052         isRunning = appMgrProxy_->GetAppRunningStateByBundleName(bundleName);
2053     }
2054     if (!isRunning) {
2055         return;
2056     }
2057 
2058     EventFwk::Want want;
2059     // common event not add COMMON_EVENT_REMINDER_STATUS_CHANGE, Temporary use of string
2060     want.SetAction("usual.event.REMINDER_STATUS_CHANGE");
2061     EventFwk::CommonEventData eventData(want);
2062 
2063     std::string data;
2064     data.append(std::to_string(static_cast<int>(buttonType))).append(",");
2065     data.append(std::to_string(reminder->GetReminderId()));
2066     eventData.SetData(data);
2067 
2068     EventFwk::CommonEventPublishInfo info;
2069     info.SetBundleName(bundleName);
2070     if (EventFwk::CommonEventManager::PublishCommonEvent(eventData, info)) {
2071         ANSR_LOGI("notify reminder status change %{public}s", bundleName.c_str());
2072     }
2073 }
2074 }
2075 }
2076