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