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