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