• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright (c) 2021-2022 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_request.h"
17 
18 #include "reminder_table.h"
19 #include "ans_const_define.h"
20 #include "ans_log_wrapper.h"
21 #include "bundle_mgr_interface.h"
22 #include "bundle_mgr_proxy.h"
23 #include "if_system_ability_manager.h"
24 #include "ipc_skeleton.h"
25 #include "iservice_registry.h"
26 #include "locale_config.h"
27 #include "os_account_manager.h"
28 #include "reminder_store.h"
29 #include "system_ability_definition.h"
30 #include "want_agent_helper.h"
31 #include "nlohmann/json.hpp"
32 
33 namespace OHOS {
34 namespace Notification {
35 namespace {
36 const int32_t BASE_YEAR = 1900;
37 const int32_t SINGLE_BUTTON_INVALID = 0;
38 const int32_t SINGLE_BUTTON_JSONSTRING = 0;
39 const int32_t SINGLE_BUTTON_ONLY_ONE = 1;
40 const int32_t SINGLE_BUTTON_MIN_LEN = 2;
41 const int32_t SINGLE_BUTTON_MAX_LEN = 4;
42 const int32_t BUTTON_TYPE_INDEX = 0;
43 const int32_t BUTTON_TITLE_INDEX = 1;
44 const int32_t BUTTON_PKG_INDEX = 2;
45 const int32_t BUTTON_ABILITY_INDEX = 3;
46 const int32_t WANT_AGENT_URI_INDEX = 2;
47 const int32_t INDENT = -1;
48 }
49 
50 int32_t ReminderRequest::GLOBAL_ID = 0;
51 const uint64_t ReminderRequest::INVALID_LONG_LONG_VALUE = 0;
52 const uint16_t ReminderRequest::INVALID_U16_VALUE = 0;
53 const uint16_t ReminderRequest::MILLI_SECONDS = 1000;
54 const uint16_t ReminderRequest::SAME_TIME_DISTINGUISH_MILLISECONDS = 1000;
55 const uint32_t ReminderRequest::MIN_TIME_INTERVAL_IN_MILLI = 5 * 60 * 1000;
56 const uint8_t ReminderRequest::INVALID_U8_VALUE = 0;
57 const uint8_t ReminderRequest::REMINDER_STATUS_INACTIVE = 0;
58 const uint8_t ReminderRequest::REMINDER_STATUS_ACTIVE = 1;
59 const uint8_t ReminderRequest::REMINDER_STATUS_ALERTING = 2;
60 const uint8_t ReminderRequest::REMINDER_STATUS_SHOWING = 4;
61 const uint8_t ReminderRequest::REMINDER_STATUS_SNOOZE = 8;
62 const uint8_t ReminderRequest::TIME_HOUR_OFFSET = 12;
63 const std::string ReminderRequest::NOTIFICATION_LABEL = "REMINDER_AGENT";
64 const std::string ReminderRequest::REMINDER_EVENT_ALARM_ALERT = "ohos.event.notification.reminder.ALARM_ALERT";
65 const std::string ReminderRequest::REMINDER_EVENT_CLOSE_ALERT = "ohos.event.notification.reminder.CLOSE_ALERT";
66 const std::string ReminderRequest::REMINDER_EVENT_SNOOZE_ALERT = "ohos.event.notification.reminder.SNOOZE_ALERT";
67 const std::string ReminderRequest::REMINDER_EVENT_CUSTOM_ALERT = "ohos.event.notification.reminder.COSTUM_ALERT";
68 const std::string ReminderRequest::REMINDER_EVENT_ALERT_TIMEOUT = "ohos.event.notification.reminder.ALERT_TIMEOUT";
69 const std::string ReminderRequest::REMINDER_EVENT_REMOVE_NOTIFICATION =
70     "ohos.event.notification.reminder.REMOVE_NOTIFICATION";
71 const std::string ReminderRequest::PARAM_REMINDER_ID = "REMINDER_ID";
72 const std::string ReminderRequest::SEP_BUTTON_SINGLE = "<SEP,/>";
73 const std::string ReminderRequest::SEP_BUTTON_MULTI = "<SEP#/>";
74 const std::string ReminderRequest::SEP_WANT_AGENT = "<SEP#/>";
75 const std::string ReminderRequest::SEP_BUTTON_VALUE_TYPE = "<SEP;/>";
76 const std::string ReminderRequest::SEP_BUTTON_VALUE = "<SEP:/>";
77 const std::string ReminderRequest::SEP_BUTTON_VALUE_BLOB = "<SEP-/>";
78 const uint8_t ReminderRequest::DAYS_PER_WEEK = 7;
79 const uint8_t ReminderRequest::MONDAY = 1;
80 const uint8_t ReminderRequest::SUNDAY = 7;
81 const uint8_t ReminderRequest::HOURS_PER_DAY = 24;
82 const uint16_t ReminderRequest::SECONDS_PER_HOUR = 3600;
83 
84 std::string ReminderRequest::sqlOfAddColumns = "";
85 std::vector<std::string> ReminderRequest::columns;
86 
ReminderRequest()87 ReminderRequest::ReminderRequest()
88 {
89     InitServerObj();
90 }
91 
ReminderRequest(const ReminderRequest & other)92 ReminderRequest::ReminderRequest(const ReminderRequest &other)
93 {
94     this->content_ = other.content_;
95     this->expiredContent_ = other.expiredContent_;
96     this->snoozeContent_ = other.snoozeContent_;
97     this->displayContent_ = other.displayContent_;
98     this->title_ = other.title_;
99     this->isExpired_ = other.isExpired_;
100     this->isSystemApp_ = other.isSystemApp_;
101     this->snoozeTimes_ = other.snoozeTimes_;
102     this->snoozeTimesDynamic_ = other.snoozeTimesDynamic_;
103     this->state_ = other.state_;
104     this->notificationId_ = other.notificationId_;
105     this->reminderId_ = other.reminderId_;
106     this->reminderTimeInMilli_ = other.reminderTimeInMilli_;
107     this->ringDurationInMilli_ = other.ringDurationInMilli_;
108     this->triggerTimeInMilli_ = other.triggerTimeInMilli_;
109     this->timeIntervalInMilli_ = other.timeIntervalInMilli_;
110     this->reminderType_ = other.reminderType_;
111     this->slotType_ = other.slotType_;
112     this->snoozeSlotType_ = other.snoozeSlotType_;
113     this->notificationRequest_ = other.notificationRequest_;
114     this->wantAgentInfo_ = other.wantAgentInfo_;
115     this->maxScreenWantAgentInfo_ = other.maxScreenWantAgentInfo_;
116     this->actionButtonMap_ = other.actionButtonMap_;
117     this->tapDismissed_= other.tapDismissed_;
118     this->autoDeletedTime_ = other.autoDeletedTime_;
119     this->customButtonUri_ = other.customButtonUri_;
120     this->repeatDaysOfWeek_ = other.repeatDaysOfWeek_;
121     this->groupId_ = other.groupId_;
122     this->customRingUri_ = other.customRingUri_;
123     this->creatorBundleName_ = other.creatorBundleName_;
124 }
125 
ReminderRequest(int32_t reminderId)126 ReminderRequest::ReminderRequest(int32_t reminderId)
127 {
128     reminderId_ = reminderId;
129     InitServerObj();
130 }
131 
ReminderRequest(ReminderType reminderType)132 ReminderRequest::ReminderRequest(ReminderType reminderType)
133 {
134     reminderType_ = reminderType;
135     InitServerObj();
136 }
137 
CanRemove() const138 bool ReminderRequest::CanRemove() const
139 {
140     if ((state_ & (REMINDER_STATUS_SHOWING | REMINDER_STATUS_ALERTING | REMINDER_STATUS_ACTIVE)) == 0) {
141         return true;
142     }
143     return false;
144 }
145 
CanShow() const146 bool ReminderRequest::CanShow() const
147 {
148     // when system time change by user manually, and the reminde is to show immediately,
149     // the show reminder just need to be triggered by ReminderDataManager#RefreshRemindersLocked(uint8_t).
150     // we need to make the REMINDER_EVENT_ALARM_ALERT do nothing.
151     uint64_t nowInstantMilli = GetNowInstantMilli();
152     if (nowInstantMilli == 0) {
153         return false;
154     }
155     if ((nowInstantMilli - GetReminderTimeInMilli()) < MIN_TIME_INTERVAL_IN_MILLI) {
156         return false;
157     }
158     return true;
159 }
160 
Dump() const161 std::string ReminderRequest::Dump() const
162 {
163     const time_t nextTriggerTime = static_cast<time_t>(triggerTimeInMilli_ / MILLI_SECONDS);
164     std::string dateTimeInfo = GetTimeInfoInner(nextTriggerTime, TimeFormat::YMDHMS, true);
165     return "Reminder["
166            "reminderId=" + std::to_string(reminderId_) +
167            ", type=" + std::to_string(static_cast<uint8_t>(reminderType_)) +
168            ", state=" + GetState(state_) +
169            ", nextTriggerTime=" + dateTimeInfo.c_str() +
170            "]";
171 }
172 
SetActionButton(const std::string & title,const ActionButtonType & type,const std::string & resource,const std::shared_ptr<ButtonWantAgent> & buttonWantAgent,const std::shared_ptr<ButtonDataShareUpdate> & buttonDataShareUpdate)173 ReminderRequest& ReminderRequest::SetActionButton(const std::string &title, const ActionButtonType &type,
174     const std::string &resource, const std::shared_ptr<ButtonWantAgent> &buttonWantAgent,
175     const std::shared_ptr<ButtonDataShareUpdate> &buttonDataShareUpdate)
176 {
177     if ((type != ActionButtonType::CLOSE) && (type != ActionButtonType::SNOOZE) && (type != ActionButtonType::CUSTOM)) {
178         ANSR_LOGI("Button type is not support: %{public}d.", static_cast<uint8_t>(type));
179         return *this;
180     }
181     ActionButtonInfo actionButtonInfo;
182     actionButtonInfo.type = type;
183     actionButtonInfo.title = title;
184     actionButtonInfo.resource = resource;
185     actionButtonInfo.wantAgent = buttonWantAgent;
186     actionButtonInfo.dataShareUpdate = buttonDataShareUpdate;
187 
188     actionButtonMap_.insert(std::pair<ActionButtonType, ActionButtonInfo>(type, actionButtonInfo));
189     return *this;
190 }
191 
SetContent(const std::string & content)192 ReminderRequest& ReminderRequest::SetContent(const std::string &content)
193 {
194     content_ = content;
195     return *this;
196 }
197 
SetExpiredContent(const std::string & expiredContent)198 ReminderRequest& ReminderRequest::SetExpiredContent(const std::string &expiredContent)
199 {
200     expiredContent_ = expiredContent;
201     return *this;
202 }
203 
SetExpired(bool isExpired)204 void ReminderRequest::SetExpired(bool isExpired)
205 {
206     isExpired_ = isExpired;
207 }
208 
InitCreatorBundleName(const std::string & creatorBundleName)209 void ReminderRequest::InitCreatorBundleName(const std::string &creatorBundleName)
210 {
211     creatorBundleName_ = creatorBundleName;
212 }
213 
InitReminderId()214 void ReminderRequest::InitReminderId()
215 {
216     std::lock_guard<std::mutex> lock(std::mutex);
217     if (GLOBAL_ID < 0) {
218         ANSR_LOGW("GLOBAL_ID overdule");
219         GLOBAL_ID = 0;
220     }
221     reminderId_ = ++GLOBAL_ID;
222     ANSR_LOGI("reminderId_=%{public}d", reminderId_);
223 }
224 
InitUserId(const int32_t & userId)225 void ReminderRequest::InitUserId(const int32_t &userId)
226 {
227     userId_ = userId;
228 }
229 
InitUid(const int32_t & uid)230 void ReminderRequest::InitUid(const int32_t &uid)
231 {
232     uid_ = uid;
233 }
234 
InitBundleName(const std::string & bundleName)235 void ReminderRequest::InitBundleName(const std::string &bundleName)
236 {
237     bundleName_ = bundleName;
238 }
239 
IsExpired() const240 bool ReminderRequest::IsExpired() const
241 {
242     return isExpired_;
243 }
244 
IsShowing() const245 bool ReminderRequest::IsShowing() const
246 {
247     if ((state_ & REMINDER_STATUS_SHOWING) != 0) {
248         return true;
249     }
250     return false;
251 }
252 
OnClose(bool updateNext)253 void ReminderRequest::OnClose(bool updateNext)
254 {
255     if ((state_ & REMINDER_STATUS_SHOWING) == 0) {
256         ANSR_LOGE("onClose, the state of reminder is incorrect, state:%{public}s", GetState(state_).c_str());
257         return;
258     }
259     SetState(false, REMINDER_STATUS_SHOWING | REMINDER_STATUS_SNOOZE, "onClose()");
260     if ((state_ & REMINDER_STATUS_ALERTING) != 0) {
261         SetState(false, REMINDER_STATUS_ALERTING, "onClose");
262     }
263     if (updateNext) {
264         uint64_t nextTriggerTime = PreGetNextTriggerTimeIgnoreSnooze(true, false);
265         if (nextTriggerTime == INVALID_LONG_LONG_VALUE) {
266             isExpired_ = true;
267         } else {
268             SetTriggerTimeInMilli(nextTriggerTime);
269             snoozeTimesDynamic_ = snoozeTimes_;
270         }
271     }
272 }
273 
OnDateTimeChange()274 bool ReminderRequest::OnDateTimeChange()
275 {
276     uint64_t nextTriggerTime = PreGetNextTriggerTimeIgnoreSnooze(true, false);
277     return HandleSysTimeChange(triggerTimeInMilli_, nextTriggerTime);
278 }
279 
HandleSysTimeChange(uint64_t oriTriggerTime,uint64_t optTriggerTime)280 bool ReminderRequest::HandleSysTimeChange(uint64_t oriTriggerTime, uint64_t optTriggerTime)
281 {
282     if (isExpired_) {
283         return false;
284     }
285     uint64_t now = GetNowInstantMilli();
286     if (now == 0) {
287         ANSR_LOGE("get now time failed.");
288         return false;
289     }
290     if (oriTriggerTime == 0 && optTriggerTime < now) {
291         ANSR_LOGW("trigger time is less than now time.");
292         return false;
293     }
294     bool showImmediately = false;
295     if (optTriggerTime != INVALID_LONG_LONG_VALUE && (optTriggerTime <= oriTriggerTime || oriTriggerTime == 0)) {
296         // case1. switch to a previous time
297         SetTriggerTimeInMilli(optTriggerTime);
298         snoozeTimesDynamic_ = snoozeTimes_;
299     } else {
300         if (oriTriggerTime <= now) {
301             // case2. switch to a future time, trigger time is less than now time.
302             // when the reminder show immediately, trigger time will update in onShow function.
303             snoozeTimesDynamic_ = 0;
304             showImmediately = true;
305         } else {
306             // case3. switch to a future time, trigger time is larger than now time.
307             showImmediately = false;
308         }
309     }
310     return showImmediately;
311 }
312 
HandleTimeZoneChange(uint64_t oldZoneTriggerTime,uint64_t newZoneTriggerTime,uint64_t optTriggerTime)313 bool ReminderRequest::HandleTimeZoneChange(
314     uint64_t oldZoneTriggerTime, uint64_t newZoneTriggerTime, uint64_t optTriggerTime)
315 {
316     if (isExpired_) {
317         return false;
318     }
319     ANSR_LOGD("Handle timezone change, old:%{public}" PRIu64 ", new:%{public}" PRIu64 "",
320         oldZoneTriggerTime, newZoneTriggerTime);
321     if (oldZoneTriggerTime == newZoneTriggerTime) {
322         return false;
323     }
324     bool showImmediately = false;
325     if (optTriggerTime != INVALID_LONG_LONG_VALUE && oldZoneTriggerTime < newZoneTriggerTime) {
326         // case1. timezone change to smaller
327         SetTriggerTimeInMilli(optTriggerTime);
328         snoozeTimesDynamic_ = snoozeTimes_;
329     } else {
330         // case2. timezone change to larger
331         time_t now;
332         (void)time(&now);  // unit is seconds.
333         if (static_cast<int64_t>(now) < 0) {
334             ANSR_LOGE("Get now time error");
335             return false;
336         }
337         if (newZoneTriggerTime <= GetDurationSinceEpochInMilli(now)) {
338             snoozeTimesDynamic_ = 0;
339             showImmediately = true;
340         } else {
341             SetTriggerTimeInMilli(newZoneTriggerTime);
342             showImmediately = false;
343         }
344     }
345     return showImmediately;
346 }
347 
OnSameNotificationIdCovered()348 void ReminderRequest::OnSameNotificationIdCovered()
349 {
350     SetState(false, REMINDER_STATUS_ALERTING | REMINDER_STATUS_SHOWING | REMINDER_STATUS_SNOOZE,
351         "OnSameNotificationIdCovered");
352 }
353 
OnShow(bool isPlaySoundOrVibration,bool isSysTimeChanged,bool allowToNotify)354 void ReminderRequest::OnShow(bool isPlaySoundOrVibration, bool isSysTimeChanged, bool allowToNotify)
355 {
356     if ((state_ & (REMINDER_STATUS_ACTIVE | REMINDER_STATUS_SNOOZE)) != 0) {
357         SetState(false, REMINDER_STATUS_ACTIVE | REMINDER_STATUS_SNOOZE, "onShow()");
358     }
359     if (isSysTimeChanged) {
360         uint64_t nowInstantMilli = GetNowInstantMilli();
361         if (nowInstantMilli == 0) {
362             ANSR_LOGW("Onshow, get now time error");
363         }
364         reminderTimeInMilli_ = nowInstantMilli;
365     } else {
366         reminderTimeInMilli_ = triggerTimeInMilli_;
367     }
368     UpdateNextReminder(false);
369     if (allowToNotify) {
370         SetState(true, REMINDER_STATUS_SHOWING, "OnShow");
371         if (isPlaySoundOrVibration) {
372             SetState(true, REMINDER_STATUS_ALERTING, "OnShow");
373         }
374         UpdateNotificationStateForAlert();
375     }
376 }
377 
OnShowFail()378 void ReminderRequest::OnShowFail()
379 {
380     SetState(false, REMINDER_STATUS_SHOWING, "OnShowFailed()");
381 }
382 
OnSnooze()383 bool ReminderRequest::OnSnooze()
384 {
385     if ((state_ & REMINDER_STATUS_SNOOZE) != 0) {
386         ANSR_LOGW("onSnooze, the state of reminder is incorrect, state: %{public}s", (GetState(state_)).c_str());
387         return false;
388     }
389     if ((state_ & REMINDER_STATUS_ALERTING) != 0) {
390         SetState(false, REMINDER_STATUS_ALERTING, "onSnooze()");
391     }
392     SetSnoozeTimesDynamic(GetSnoozeTimes());
393     if (!UpdateNextReminder(true)) {
394         return false;
395     }
396     UpdateNotificationStateForSnooze();
397     if (timeIntervalInMilli_ > 0) {
398         SetState(true, REMINDER_STATUS_SNOOZE, "onSnooze()");
399     }
400     return true;
401 }
402 
OnStart()403 void ReminderRequest::OnStart()
404 {
405     if ((state_ & REMINDER_STATUS_ACTIVE) != 0) {
406         ANSR_LOGE(
407             "start failed, the state of reminder is incorrect, state: %{public}s", (GetState(state_)).c_str());
408         return;
409     }
410     if (isExpired_) {
411         ANSR_LOGE("start failed, the reminder is expired");
412         return;
413     }
414     SetState(true, REMINDER_STATUS_ACTIVE, "OnStart()");
415 }
416 
OnStop()417 void ReminderRequest::OnStop()
418 {
419     ANSR_LOGI("Stop the previous active reminder, %{public}s", this->Dump().c_str());
420     if ((state_ & REMINDER_STATUS_ACTIVE) == 0) {
421         ANSR_LOGW("onStop, the state of reminder is incorrect, state: %{public}s", (GetState(state_)).c_str());
422         return;
423     }
424     SetState(false, REMINDER_STATUS_ACTIVE, "OnStop");
425 }
426 
OnTerminate()427 bool ReminderRequest::OnTerminate()
428 {
429     if ((state_ & REMINDER_STATUS_ALERTING) == 0) {
430         ANSR_LOGW("onTerminate, the state of reminder is %{public}s", (GetState(state_)).c_str());
431         return false;
432     }
433     SetState(false, REMINDER_STATUS_ALERTING, "onTerminate");
434     UpdateNotificationStateForAlert();
435     return true;
436 }
437 
OnTimeZoneChange()438 bool ReminderRequest::OnTimeZoneChange()
439 {
440     time_t oldZoneTriggerTime = static_cast<time_t>(triggerTimeInMilli_ / MILLI_SECONDS);
441     struct tm oriTime;
442     (void)gmtime_r(&oldZoneTriggerTime, &oriTime);
443     time_t newZoneTriggerTime = mktime(&oriTime);
444     uint64_t nextTriggerTime = PreGetNextTriggerTimeIgnoreSnooze(true, false);
445     return HandleTimeZoneChange(
446         triggerTimeInMilli_, GetDurationSinceEpochInMilli(newZoneTriggerTime), nextTriggerTime);
447 }
448 
RecoverInt64FromDb(const std::shared_ptr<NativeRdb::ResultSet> & resultSet,const std::string & columnName,const DbRecoveryType & columnType)449 int64_t ReminderRequest::RecoverInt64FromDb(const std::shared_ptr<NativeRdb::ResultSet> &resultSet,
450     const std::string &columnName, const DbRecoveryType &columnType)
451 {
452     if (resultSet == nullptr) {
453         ANSR_LOGE("ResultSet is null");
454         return 0;
455     }
456     switch (columnType) {
457         case (DbRecoveryType::INT): {
458             int32_t value;
459             ReminderStore::GetInt32Val(resultSet, columnName, value);
460             return static_cast<int64_t>(value);
461         }
462         case (DbRecoveryType::LONG): {
463             int64_t value;
464             ReminderStore::GetInt64Val(resultSet, columnName, value);
465             return value;
466         }
467         default: {
468             ANSR_LOGD("ColumnType not support.");
469             break;
470         }
471     }
472     ANSR_LOGE("Recover data error");
473     return 0;
474 }
475 
RecoverBasicFromDb(const std::shared_ptr<NativeRdb::ResultSet> & resultSet)476 void ReminderRequest::RecoverBasicFromDb(const std::shared_ptr<NativeRdb::ResultSet>& resultSet)
477 {
478     // reminderId
479     ReminderStore::GetInt32Val(resultSet, ReminderTable::REMINDER_ID, reminderId_);
480 
481     // userId
482     ReminderStore::GetInt32Val(resultSet, ReminderTable::USER_ID, userId_);
483 
484     // bundleName
485     ReminderStore::GetStringVal(resultSet, ReminderTable::PKG_NAME, bundleName_);
486 
487     // uid
488     ReminderStore::GetInt32Val(resultSet, ReminderTable::UID, uid_);
489 
490     // isSystemApp
491     std::string isSysApp;
492     ReminderStore::GetStringVal(resultSet, ReminderTable::SYS_APP, isSysApp);
493     isSystemApp_ = isSysApp == "true" ? true : false;
494 
495     // reminderType
496     int32_t reminderType;
497     ReminderStore::GetInt32Val(resultSet, ReminderTable::REMINDER_TYPE, reminderType);
498     reminderType_ = ReminderType(reminderType);
499 
500     // reminderTime
501     reminderTimeInMilli_ =
502         static_cast<uint64_t>(RecoverInt64FromDb(resultSet, ReminderTable::REMINDER_TIME,
503             DbRecoveryType::LONG));
504 
505     // triggerTime
506     triggerTimeInMilli_ =
507         static_cast<uint64_t>(RecoverInt64FromDb(resultSet, ReminderTable::TRIGGER_TIME,
508             DbRecoveryType::LONG));
509 
510     // timeInterval
511     uint64_t timeIntervalInSecond =
512         static_cast<uint64_t>(RecoverInt64FromDb(resultSet, ReminderTable::TIME_INTERVAL,
513             DbRecoveryType::LONG));
514     SetTimeInterval(timeIntervalInSecond);
515 
516     // snoozeTimes
517     snoozeTimes_ = static_cast<uint8_t>(RecoverInt64FromDb(resultSet, ReminderTable::SNOOZE_TIMES,
518         DbRecoveryType::INT));
519 
520     // dynamicSnoozeTimes
521     snoozeTimesDynamic_ =
522         static_cast<uint8_t>(RecoverInt64FromDb(resultSet, ReminderTable::DYNAMIC_SNOOZE_TIMES,
523             DbRecoveryType::INT));
524 
525     // ringDuration
526     uint64_t ringDurationInSecond =
527         static_cast<uint64_t>(RecoverInt64FromDb(resultSet, ReminderTable::RING_DURATION,
528             DbRecoveryType::LONG));
529     SetRingDuration(ringDurationInSecond);
530 
531     // isExpired
532     std::string isExpired;
533     ReminderStore::GetStringVal(resultSet, ReminderTable::IS_EXPIRED,
534         isExpired);
535     isExpired_ = isExpired == "true" ? true : false;
536 
537     // state
538     state_ = static_cast<uint8_t>(RecoverInt64FromDb(resultSet, ReminderTable::STATE,
539         DbRecoveryType::INT));
540 
541     // repeatDaysOfWeek_
542     repeatDaysOfWeek_ = static_cast<uint8_t>(RecoverInt64FromDb(resultSet, ReminderTable::REPEAT_DAYS_OF_WEEK,
543         DbRecoveryType::INT));
544 
545     // action buttons
546     RecoverActionButton(resultSet);
547 
548     // slotType
549     int32_t slotType;
550     ReminderStore::GetInt32Val(resultSet, ReminderTable::SLOT_ID, slotType);
551     slotType_ = NotificationConstant::SlotType(slotType);
552 
553     // snoozeSlotType
554     int32_t snoozeSlotType;
555     ReminderStore::GetInt32Val(resultSet, ReminderTable::SNOOZE_SLOT_ID, snoozeSlotType);
556     snoozeSlotType_ = NotificationConstant::SlotType(snoozeSlotType);
557 
558     // notification id
559     ReminderStore::GetInt32Val(resultSet, ReminderTable::NOTIFICATION_ID, notificationId_);
560 
561     // title
562     ReminderStore::GetStringVal(resultSet, ReminderTable::TITLE, title_);
563 
564     // content
565     ReminderStore::GetStringVal(resultSet, ReminderTable::CONTENT, content_);
566 
567     // snoozeContent
568     ReminderStore::GetStringVal(resultSet, ReminderTable::SNOOZE_CONTENT, snoozeContent_);
569 
570     // expiredContent
571     ReminderStore::GetStringVal(resultSet, ReminderTable::EXPIRED_CONTENT, expiredContent_);
572 
573     InitNotificationRequest();  // must set before wantAgent & maxScreenWantAgent
574 }
575 
RecoverFromDb(const std::shared_ptr<NativeRdb::ResultSet> & resultSet)576 void ReminderRequest::RecoverFromDb(const std::shared_ptr<NativeRdb::ResultSet> &resultSet)
577 {
578     if (resultSet == nullptr) {
579         ANSR_LOGE("ResultSet is null");
580         return;
581     }
582 
583     RecoverBasicFromDb(resultSet);
584 
585     // wantAgent
586     std::string wantAgent;
587     ReminderStore::GetStringVal(resultSet, ReminderTable::AGENT, wantAgent);
588     RecoverWantAgent(wantAgent, 0);
589 
590     // maxScreenWantAgent
591     std::string maxScreenWantAgent;
592     ReminderStore::GetStringVal(resultSet, ReminderTable::MAX_SCREEN_AGENT, maxScreenWantAgent);
593     RecoverWantAgent(maxScreenWantAgent, 1);
594 
595     // tapDismissed
596     std::string tapDismissed;
597     ReminderStore::GetStringVal(resultSet, ReminderTable::TAP_DISMISSED, tapDismissed);
598     tapDismissed_ = tapDismissed == "true" ? true : false;
599 
600     // autoDeletedTime
601     autoDeletedTime_ =
602         static_cast<int64_t>(RecoverInt64FromDb(resultSet, ReminderTable::AUTO_DELETED_TIME,
603             DbRecoveryType::LONG));
604 
605     // customButtonUri
606     ReminderStore::GetStringVal(resultSet, ReminderTable::CUSTOM_BUTTON_URI, customButtonUri_);
607 
608     // groupId
609     ReminderStore::GetStringVal(resultSet, ReminderTable::GROUP_ID, groupId_);
610 
611     // customRingUri
612     ReminderStore::GetStringVal(resultSet, ReminderTable::CUSTOM_RING_URI, customRingUri_);
613 
614     // creatorBundleName
615     ReminderStore::GetStringVal(resultSet, ReminderTable::CREATOR_BUNDLE_NAME, creatorBundleName_);
616 }
617 
RecoverActionButtonJsonMode(const std::string & jsonString)618 void ReminderRequest::RecoverActionButtonJsonMode(const std::string &jsonString)
619 {
620     nlohmann::json root = nlohmann::json::parse(jsonString);
621     std::string type = root.at("type").get<std::string>();
622     std::string title = root.at("title").get<std::string>();
623     std::string resource = root.at("resource").get<std::string>();
624     auto buttonWantAgent = std::make_shared<ReminderRequest::ButtonWantAgent>();
625     if (!root["wantAgent"].empty()) {
626         nlohmann::json wantAgent = root["wantAgent"];
627         buttonWantAgent->pkgName = wantAgent.at("pkgName").get<std::string>();
628         buttonWantAgent->abilityName = wantAgent.at("abilityName").get<std::string>();
629     }
630     auto buttonDataShareUpdate = std::make_shared<ReminderRequest::ButtonDataShareUpdate>();
631     if (!root["dataShareUpdate"].empty()) {
632         nlohmann::json dataShareUpdate = root["dataShareUpdate"];
633         buttonDataShareUpdate->uri = dataShareUpdate.at("uri").get<std::string>();
634         buttonDataShareUpdate->equalTo = dataShareUpdate.at("equalTo").get<std::string>();
635         buttonDataShareUpdate->valuesBucket = dataShareUpdate.at("valuesBucket").get<std::string>();
636     }
637     SetActionButton(title, ActionButtonType(std::stoi(type, nullptr)),
638         resource, buttonWantAgent, buttonDataShareUpdate);
639 }
640 
RecoverActionButton(const std::shared_ptr<NativeRdb::ResultSet> & resultSet)641 void ReminderRequest::RecoverActionButton(const std::shared_ptr<NativeRdb::ResultSet> &resultSet)
642 {
643     if (resultSet == nullptr) {
644         ANSR_LOGE("ResultSet is null");
645         return;
646     }
647     std::string actionButtonInfo;
648     ReminderStore::GetStringVal(resultSet, ReminderTable::ACTION_BUTTON_INFO, actionButtonInfo);
649     std::vector<std::string> multiButton = StringSplit(actionButtonInfo, SEP_BUTTON_MULTI);
650     for (auto button : multiButton) {
651         std::vector<std::string> singleButton = StringSplit(button, SEP_BUTTON_SINGLE);
652         if (singleButton.size() <= SINGLE_BUTTON_INVALID) {
653             ANSR_LOGW("RecoverButton fail");
654             return;
655         }
656         if (singleButton.size() == SINGLE_BUTTON_ONLY_ONE) {
657             std::string jsonString = singleButton.at(SINGLE_BUTTON_JSONSTRING);
658             RecoverActionButtonJsonMode(jsonString);
659             continue;
660         }
661         // old method Soon to be deleted
662         if (singleButton.size() < SINGLE_BUTTON_MIN_LEN) {
663             ANSR_LOGW("RecoverButton fail");
664             return;
665         }
666         auto buttonWantAgent = std::make_shared<ReminderRequest::ButtonWantAgent>();
667         if (singleButton.size() == SINGLE_BUTTON_MAX_LEN) {
668             buttonWantAgent->pkgName = singleButton.at(BUTTON_PKG_INDEX);
669             buttonWantAgent->abilityName = singleButton.at(BUTTON_ABILITY_INDEX);
670         }
671         std::string resource = "";
672         auto buttonDataShareUpdate = std::make_shared<ReminderRequest::ButtonDataShareUpdate>();
673         SetActionButton(singleButton.at(BUTTON_TITLE_INDEX),
674             ActionButtonType(std::atoi(singleButton.at(BUTTON_TYPE_INDEX).c_str())),
675             resource, buttonWantAgent, buttonDataShareUpdate);
676         ANSR_LOGI("RecoverButton title:%{public}s, pkgName:%{public}s, abilityName:%{public}s",
677             singleButton.at(BUTTON_TITLE_INDEX).c_str(), buttonWantAgent->pkgName.c_str(),
678             buttonWantAgent->abilityName.c_str());
679     }
680 }
681 
StringSplit(std::string source,const std::string & split)682 std::vector<std::string> ReminderRequest::StringSplit(std::string source, const std::string &split)
683 {
684     std::vector<std::string> result;
685     if (source.empty()) {
686         return result;
687     }
688     size_t pos = 0;
689     while ((pos = source.find(split)) != std::string::npos) {
690         std::string token = source.substr(0, pos);
691         if (!token.empty()) {
692             result.push_back(token);
693         }
694         source.erase(0, pos + split.length());
695     }
696     if (!source.empty()) {
697         result.push_back(source);
698     }
699     return result;
700 }
701 
RecoverWantAgent(const std::string & wantAgentInfo,const uint8_t & type)702 void ReminderRequest::RecoverWantAgent(const std::string &wantAgentInfo, const uint8_t &type)
703 {
704     std::vector<std::string> info = StringSplit(wantAgentInfo, ReminderRequest::SEP_WANT_AGENT);
705     uint8_t minLen = 2;
706     if (info.size() < minLen) {
707         ANSR_LOGW("RecoverWantAgent fail");
708         return;
709     }
710     ANSR_LOGD("pkg=%{public}s, ability=%{public}s", info.at(0).c_str(), info.at(1).c_str());
711     switch (type) {
712         case 0: {
713             auto wai = std::make_shared<ReminderRequest::WantAgentInfo>();
714             wai->pkgName = info.at(0);
715             wai->abilityName = info.at(1);
716             if (info.size() > minLen) {
717                 wai->uri = info.at(WANT_AGENT_URI_INDEX);
718             }
719             SetWantAgentInfo(wai);
720             break;
721         }
722         case 1: {
723             auto maxScreenWantAgentInfo = std::make_shared<ReminderRequest::MaxScreenAgentInfo>();
724             maxScreenWantAgentInfo->pkgName = info.at(0);
725             maxScreenWantAgentInfo->abilityName = info.at(1);
726             SetMaxScreenWantAgentInfo(maxScreenWantAgentInfo);
727             break;
728         }
729         default: {
730             ANSR_LOGW("RecoverWantAgent type not support");
731             break;
732         }
733     }
734 }
735 
SetMaxScreenWantAgentInfo(const std::shared_ptr<MaxScreenAgentInfo> & maxScreenWantAgentInfo)736 ReminderRequest& ReminderRequest::SetMaxScreenWantAgentInfo(
737     const std::shared_ptr<MaxScreenAgentInfo> &maxScreenWantAgentInfo)
738 {
739     maxScreenWantAgentInfo_ = maxScreenWantAgentInfo;
740     return *this;
741 }
742 
SetNotificationId(int32_t notificationId)743 ReminderRequest& ReminderRequest::SetNotificationId(int32_t notificationId)
744 {
745     notificationId_ = notificationId;
746     return *this;
747 }
748 
SetGroupId(const std::string & groupId)749 ReminderRequest& ReminderRequest::SetGroupId(const std::string &groupId)
750 {
751     groupId_ = groupId;
752     return *this;
753 }
754 
SetSlotType(const NotificationConstant::SlotType & slotType)755 ReminderRequest& ReminderRequest::SetSlotType(const NotificationConstant::SlotType &slotType)
756 {
757     slotType_ = slotType;
758     return *this;
759 }
760 
SetSnoozeSlotType(const NotificationConstant::SlotType & snoozeSlotType)761 ReminderRequest& ReminderRequest::SetSnoozeSlotType(const NotificationConstant::SlotType &snoozeSlotType)
762 {
763     snoozeSlotType_ = snoozeSlotType;
764     return *this;
765 }
766 
SetSnoozeContent(const std::string & snoozeContent)767 ReminderRequest& ReminderRequest::SetSnoozeContent(const std::string &snoozeContent)
768 {
769     snoozeContent_ = snoozeContent;
770     return *this;
771 }
772 
SetSnoozeTimes(const uint8_t snoozeTimes)773 ReminderRequest& ReminderRequest::SetSnoozeTimes(const uint8_t snoozeTimes)
774 {
775     snoozeTimes_ = snoozeTimes;
776     SetSnoozeTimesDynamic(snoozeTimes);
777     return *this;
778 }
779 
SetSnoozeTimesDynamic(const uint8_t snooziTimes)780 ReminderRequest& ReminderRequest::SetSnoozeTimesDynamic(const uint8_t snooziTimes)
781 {
782     snoozeTimesDynamic_ = snooziTimes;
783     return *this;
784 }
785 
SetTimeInterval(const uint64_t timeIntervalInSeconds)786 ReminderRequest& ReminderRequest::SetTimeInterval(const uint64_t timeIntervalInSeconds)
787 {
788     if (timeIntervalInSeconds > (UINT64_MAX / MILLI_SECONDS)) {
789         ANSR_LOGW("SetTimeInterval, replace to set (0s), for the given is out of legal range");
790         timeIntervalInMilli_ = 0;
791     } else {
792         uint64_t timeIntervalInMilli = timeIntervalInSeconds * MILLI_SECONDS;
793         if (timeIntervalInMilli > 0 && timeIntervalInMilli < MIN_TIME_INTERVAL_IN_MILLI) {
794             ANSR_LOGW("SetTimeInterval, replace to set %{public}u, for the given is 0<%{public}" PRIu64 "<%{public}u",
795                 MIN_TIME_INTERVAL_IN_MILLI / MILLI_SECONDS, timeIntervalInSeconds,
796                 MIN_TIME_INTERVAL_IN_MILLI / MILLI_SECONDS);
797             timeIntervalInMilli_ = MIN_TIME_INTERVAL_IN_MILLI;
798         } else {
799             timeIntervalInMilli_ = timeIntervalInMilli;
800         }
801     }
802     return *this;
803 }
804 
SetTitle(const std::string & title)805 ReminderRequest& ReminderRequest::SetTitle(const std::string &title)
806 {
807     title_ = title;
808     return *this;
809 }
810 
SetTriggerTimeInMilli(uint64_t triggerTimeInMilli)811 void ReminderRequest::SetTriggerTimeInMilli(uint64_t triggerTimeInMilli)
812 {
813     triggerTimeInMilli_ = triggerTimeInMilli;
814 }
815 
SetWantAgentInfo(const std::shared_ptr<WantAgentInfo> & wantAgentInfo)816 ReminderRequest& ReminderRequest::SetWantAgentInfo(const std::shared_ptr<WantAgentInfo> &wantAgentInfo)
817 {
818     wantAgentInfo_ = wantAgentInfo;
819     return *this;
820 }
821 
ShouldShowImmediately() const822 bool ReminderRequest::ShouldShowImmediately() const
823 {
824     uint64_t nowInstantMilli = GetNowInstantMilli();
825     if (nowInstantMilli == 0) {
826         return false;
827     }
828     if (triggerTimeInMilli_ > nowInstantMilli) {
829         return false;
830     }
831     return true;
832 }
833 
GetActionButtons() const834 std::map<ReminderRequest::ActionButtonType, ReminderRequest::ActionButtonInfo> ReminderRequest::GetActionButtons(
835     ) const
836 {
837     return actionButtonMap_;
838 }
839 
GetCreatorBundleName() const840 std::string ReminderRequest::GetCreatorBundleName() const
841 {
842     return creatorBundleName_;
843 }
844 
GetContent() const845 std::string ReminderRequest::GetContent() const
846 {
847     return content_;
848 }
849 
GetExpiredContent() const850 std::string ReminderRequest::GetExpiredContent() const
851 {
852     return expiredContent_;
853 }
854 
GetMaxScreenWantAgentInfo() const855 std::shared_ptr<ReminderRequest::MaxScreenAgentInfo> ReminderRequest::GetMaxScreenWantAgentInfo() const
856 {
857     return maxScreenWantAgentInfo_;
858 }
859 
GetNotificationId() const860 int32_t ReminderRequest::GetNotificationId() const
861 {
862     return notificationId_;
863 }
864 
GetGroupId() const865 std::string ReminderRequest::GetGroupId() const
866 {
867     return groupId_;
868 }
869 
GetNotificationRequest() const870 sptr<NotificationRequest> ReminderRequest::GetNotificationRequest() const
871 {
872     return notificationRequest_;
873 }
874 
GetReminderId() const875 int32_t ReminderRequest::GetReminderId() const
876 {
877     return reminderId_;
878 }
879 
GetReminderTimeInMilli() const880 uint64_t ReminderRequest::GetReminderTimeInMilli() const
881 {
882     return reminderTimeInMilli_;
883 }
884 
SetReminderId(int32_t reminderId)885 void ReminderRequest::SetReminderId(int32_t reminderId)
886 {
887     reminderId_ = reminderId;
888 }
889 
SetReminderTimeInMilli(const uint64_t reminderTimeInMilli)890 void ReminderRequest::SetReminderTimeInMilli(const uint64_t reminderTimeInMilli)
891 {
892     reminderTimeInMilli_ = reminderTimeInMilli;
893 }
894 
SetRingDuration(const uint64_t ringDurationInSeconds)895 ReminderRequest& ReminderRequest::SetRingDuration(const uint64_t ringDurationInSeconds)
896 {
897     if ((ringDurationInSeconds == 0) || (ringDurationInSeconds > (UINT64_MAX / MILLI_SECONDS))) {
898         ANSR_LOGW("setRingDuration, replace to set (1s), for the given is out of legal range");
899         ringDurationInMilli_ = MILLI_SECONDS;
900     } else {
901         ringDurationInMilli_ = ringDurationInSeconds * MILLI_SECONDS;
902     }
903     return *this;
904 }
905 
GetSlotType() const906 NotificationConstant::SlotType ReminderRequest::GetSlotType() const
907 {
908     return slotType_;
909 }
910 
GetSnoozeSlotType() const911 NotificationConstant::SlotType ReminderRequest::GetSnoozeSlotType() const
912 {
913     return snoozeSlotType_;
914 }
915 
GetSnoozeContent() const916 std::string ReminderRequest::GetSnoozeContent() const
917 {
918     return snoozeContent_;
919 }
920 
GetSnoozeTimes() const921 uint8_t ReminderRequest::GetSnoozeTimes() const
922 {
923     return snoozeTimes_;
924 }
925 
GetSnoozeTimesDynamic() const926 uint8_t ReminderRequest::GetSnoozeTimesDynamic() const
927 {
928     return snoozeTimesDynamic_;
929 }
930 
GetState() const931 uint8_t ReminderRequest::GetState() const
932 {
933     return state_;
934 }
935 
GetTimeInterval() const936 uint64_t ReminderRequest::GetTimeInterval() const
937 {
938     return timeIntervalInMilli_ / MILLI_SECONDS;
939 }
940 
GetTitle() const941 std::string ReminderRequest::GetTitle() const
942 {
943     return title_;
944 }
945 
GetTriggerTimeInMilli() const946 uint64_t ReminderRequest::GetTriggerTimeInMilli() const
947 {
948     return triggerTimeInMilli_;
949 }
950 
GetUserId() const951 int32_t ReminderRequest::GetUserId() const
952 {
953     return userId_;
954 }
955 
GetUid() const956 int32_t ReminderRequest::GetUid() const
957 {
958     return uid_;
959 }
960 
GetBundleName() const961 std::string ReminderRequest::GetBundleName() const
962 {
963     return bundleName_;
964 }
965 
SetSystemApp(bool isSystem)966 void ReminderRequest::SetSystemApp(bool isSystem)
967 {
968     isSystemApp_ = isSystem;
969 }
970 
IsSystemApp() const971 bool ReminderRequest::IsSystemApp() const
972 {
973     return isSystemApp_;
974 }
975 
SetTapDismissed(bool tapDismissed)976 void ReminderRequest::SetTapDismissed(bool tapDismissed)
977 {
978     tapDismissed_ = tapDismissed;
979 }
980 
IsTapDismissed() const981 bool ReminderRequest::IsTapDismissed() const
982 {
983     return tapDismissed_;
984 }
985 
SetAutoDeletedTime(int64_t autoDeletedTime)986 void ReminderRequest::SetAutoDeletedTime(int64_t autoDeletedTime)
987 {
988     autoDeletedTime_ = autoDeletedTime;
989 }
990 
GetAutoDeletedTime() const991 int64_t ReminderRequest::GetAutoDeletedTime() const
992 {
993     return autoDeletedTime_;
994 }
995 
SetCustomButtonUri(const std::string & uri)996 void ReminderRequest::SetCustomButtonUri(const std::string &uri)
997 {
998     customButtonUri_ = uri;
999 }
1000 
GetCustomButtonUri() const1001 std::string ReminderRequest::GetCustomButtonUri() const
1002 {
1003     return customButtonUri_;
1004 }
1005 
SetCustomRingUri(const std::string & uri)1006 void ReminderRequest::SetCustomRingUri(const std::string &uri)
1007 {
1008     customRingUri_ = uri;
1009 }
1010 
GetCustomRingUri() const1011 std::string ReminderRequest::GetCustomRingUri() const
1012 {
1013     return customRingUri_;
1014 }
1015 
GetWantAgentInfo() const1016 std::shared_ptr<ReminderRequest::WantAgentInfo> ReminderRequest::GetWantAgentInfo() const
1017 {
1018     return wantAgentInfo_;
1019 }
1020 
GetReminderType() const1021 ReminderRequest::ReminderType ReminderRequest::GetReminderType() const
1022 {
1023     return reminderType_;
1024 }
1025 
GetRingDuration() const1026 uint16_t ReminderRequest::GetRingDuration() const
1027 {
1028     return ringDurationInMilli_ / MILLI_SECONDS;
1029 }
1030 
UpdateNextReminder()1031 bool ReminderRequest::UpdateNextReminder()
1032 {
1033     return false;
1034 }
1035 
SetNextTriggerTime()1036 bool ReminderRequest::SetNextTriggerTime()
1037 {
1038     return false;
1039 }
1040 
UpdateNotificationRequest(UpdateNotificationType type,std::string extra)1041 void ReminderRequest::UpdateNotificationRequest(UpdateNotificationType type, std::string extra)
1042 {
1043     switch (type) {
1044         case UpdateNotificationType::COMMON: {
1045             ANSR_LOGI("UpdateNotification common information");
1046             if (extra == "snooze") {
1047                 UpdateNotificationCommon(true);
1048             } else {
1049                 UpdateNotificationCommon(false);
1050             }
1051             break;
1052         }
1053         case UpdateNotificationType::REMOVAL_WANT_AGENT: {
1054             ANSR_LOGI("UpdateNotification removal_want_agent");
1055             AddRemovalWantAgent();
1056             break;
1057         }
1058         case UpdateNotificationType::WANT_AGENT: {
1059             ANSR_LOGI("UpdateNotification want_agent");
1060             AppExecFwk::ElementName wantAgent("", wantAgentInfo_->pkgName, wantAgentInfo_->abilityName);
1061             SetWantAgent(wantAgent);
1062             break;
1063         }
1064         case UpdateNotificationType::MAX_SCREEN_WANT_AGENT: {
1065             ANSR_LOGI("UpdateNotification max_screen_want_agent");
1066             AppExecFwk::ElementName maxScreenWantAgent(
1067                 "", maxScreenWantAgentInfo_->pkgName, maxScreenWantAgentInfo_->abilityName);
1068             SetMaxScreenWantAgent(maxScreenWantAgent);
1069             break;
1070         }
1071         case UpdateNotificationType::BUNDLE_INFO: {
1072             ANSR_LOGI("UpdateNotification hap information");
1073             UpdateNotificationBundleInfo();
1074             break;
1075         }
1076         case UpdateNotificationType::CONTENT: {
1077             break;
1078         }
1079         default:
1080             break;
1081     }
1082 }
1083 
MarshallingActionButton(Parcel & parcel) const1084 bool ReminderRequest::MarshallingActionButton(Parcel& parcel) const
1085 {
1086     // write map
1087     uint64_t actionButtonMapSize = static_cast<uint64_t>(actionButtonMap_.size());
1088     WRITE_UINT64_RETURN_FALSE_LOG(parcel, actionButtonMapSize, "actionButtonMapSize");
1089     for (auto button : actionButtonMap_) {
1090         uint8_t buttonType = static_cast<uint8_t>(button.first);
1091         WRITE_UINT8_RETURN_FALSE_LOG(parcel, buttonType, "buttonType");
1092         WRITE_STRING_RETURN_FALSE_LOG(parcel, button.second.title, "buttonTitle");
1093         WRITE_STRING_RETURN_FALSE_LOG(parcel, button.second.resource, "buttonResource");
1094 
1095         if (button.second.wantAgent == nullptr) {
1096             ANSR_LOGE("button wantAgent is null");
1097             return false;
1098         }
1099 
1100         WRITE_STRING_RETURN_FALSE_LOG(parcel, button.second.wantAgent->pkgName, "wantAgent's pkgName");
1101         WRITE_STRING_RETURN_FALSE_LOG(parcel, button.second.wantAgent->abilityName, "wantAgent's abilityName");
1102 
1103         if (button.second.dataShareUpdate == nullptr) {
1104             ANSR_LOGE("button dataShareUpdate is null");
1105             return false;
1106         }
1107         WRITE_STRING_RETURN_FALSE_LOG(parcel, button.second.dataShareUpdate->uri,
1108             "dataShareUpdate's uri");
1109         WRITE_STRING_RETURN_FALSE_LOG(parcel, button.second.dataShareUpdate->equalTo,
1110             "dataShareUpdate's equalTo");
1111         WRITE_STRING_RETURN_FALSE_LOG(parcel, button.second.dataShareUpdate->valuesBucket,
1112             "dataShareUpdate's valuesBucket");
1113     }
1114     return true;
1115 }
1116 
Marshalling(Parcel & parcel) const1117 bool ReminderRequest::Marshalling(Parcel &parcel) const
1118 {
1119     // write string
1120     WRITE_STRING_RETURN_FALSE_LOG(parcel, content_, "content");
1121     WRITE_STRING_RETURN_FALSE_LOG(parcel, expiredContent_, "expiredContent");
1122     WRITE_STRING_RETURN_FALSE_LOG(parcel, snoozeContent_, "snoozeContent");
1123     WRITE_STRING_RETURN_FALSE_LOG(parcel, title_, "title");
1124     WRITE_STRING_RETURN_FALSE_LOG(parcel, wantAgentInfo_->abilityName, "wantAgentInfo's abilityName");
1125     WRITE_STRING_RETURN_FALSE_LOG(parcel, wantAgentInfo_->pkgName, "wantAgentInfo's pkgName");
1126     WRITE_STRING_RETURN_FALSE_LOG(parcel, wantAgentInfo_->uri, "wantAgentInfo's uri");
1127     WRITE_STRING_RETURN_FALSE_LOG(parcel, maxScreenWantAgentInfo_->abilityName, "maxScreenWantAgentInfo's abilityName");
1128     WRITE_STRING_RETURN_FALSE_LOG(parcel, maxScreenWantAgentInfo_->pkgName, "maxScreenWantAgentInfo's pkgName");
1129     WRITE_STRING_RETURN_FALSE_LOG(parcel, customButtonUri_, "customButtonUri");
1130     WRITE_STRING_RETURN_FALSE_LOG(parcel, customRingUri_, "customRingUri");
1131     WRITE_STRING_RETURN_FALSE_LOG(parcel, creatorBundleName_, "creatorBundleName");
1132 
1133     // write bool
1134     WRITE_BOOL_RETURN_FALSE_LOG(parcel, isExpired_, "isExpired");
1135     WRITE_BOOL_RETURN_FALSE_LOG(parcel, isSystemApp_, "isSystemApp");
1136     WRITE_BOOL_RETURN_FALSE_LOG(parcel, tapDismissed_, "tapDismissed");
1137 
1138     // write int
1139     WRITE_INT64_RETURN_FALSE_LOG(parcel, autoDeletedTime_, "autoDeletedTime");
1140     WRITE_INT32_RETURN_FALSE_LOG(parcel, reminderId_, "reminderId");
1141     WRITE_INT32_RETURN_FALSE_LOG(parcel, notificationId_, "notificationId");
1142 
1143     WRITE_STRING_RETURN_FALSE_LOG(parcel, groupId_, "groupId");
1144     WRITE_UINT64_RETURN_FALSE_LOG(parcel, triggerTimeInMilli_, "triggerTimeInMilli");
1145     WRITE_UINT64_RETURN_FALSE_LOG(parcel, timeIntervalInMilli_, "timeIntervalInMilli");
1146     WRITE_UINT64_RETURN_FALSE_LOG(parcel, ringDurationInMilli_, "ringDurationInMilli");
1147     WRITE_UINT64_RETURN_FALSE_LOG(parcel, reminderTimeInMilli_, "reminderTimeInMilli");
1148     WRITE_UINT8_RETURN_FALSE_LOG(parcel, snoozeTimes_, "snoozeTimes");
1149     WRITE_UINT8_RETURN_FALSE_LOG(parcel, snoozeTimesDynamic_, "snoozeTimesDynamic");
1150     WRITE_UINT8_RETURN_FALSE_LOG(parcel, state_, "state");
1151     WRITE_UINT8_RETURN_FALSE_LOG(parcel, repeatDaysOfWeek_, "repeatDaysOfWeek");
1152 
1153     // write enum
1154     uint8_t reminderType = static_cast<uint8_t>(reminderType_);
1155     WRITE_UINT8_RETURN_FALSE_LOG(parcel, reminderType, "reminderType");
1156 
1157     int32_t slotType = static_cast<int32_t>(slotType_);
1158     WRITE_INT32_RETURN_FALSE_LOG(parcel, slotType, "slotType");
1159 
1160     int32_t snoozeSlotType = static_cast<int32_t>(snoozeSlotType_);
1161     WRITE_INT32_RETURN_FALSE_LOG(parcel, snoozeSlotType, "snoozeSlotType");
1162 
1163     if (!MarshallingActionButton(parcel)) {
1164         return false;
1165     }
1166     return true;
1167 }
1168 
Unmarshalling(Parcel & parcel)1169 ReminderRequest *ReminderRequest::Unmarshalling(Parcel &parcel)
1170 {
1171     auto objptr = new (std::nothrow) ReminderRequest();
1172     if (objptr == nullptr) {
1173         ANSR_LOGE("Failed to create reminder due to no memory.");
1174         return objptr;
1175     }
1176     if (!objptr->ReadFromParcel(parcel)) {
1177         delete objptr;
1178         objptr = nullptr;
1179     }
1180     return objptr;
1181 }
1182 
ReadActionButtonFromParcel(Parcel & parcel)1183 bool ReminderRequest::ReadActionButtonFromParcel(Parcel& parcel)
1184 {
1185     uint64_t buttonMapSize = 0;
1186     READ_UINT64_RETURN_FALSE_LOG(parcel, buttonMapSize, "actionButtonMapSize");
1187     buttonMapSize = (buttonMapSize < MAX_ACTION_BUTTON_NUM) ? buttonMapSize : MAX_ACTION_BUTTON_NUM;
1188     for (uint64_t i = 0; i < buttonMapSize; i++) {
1189         uint8_t buttonType = static_cast<uint8_t>(ActionButtonType::INVALID);
1190         READ_UINT8_RETURN_FALSE_LOG(parcel, buttonType, "buttonType");
1191         ActionButtonType type = static_cast<ActionButtonType>(buttonType);
1192         std::string title = parcel.ReadString();
1193         std::string resource = parcel.ReadString();
1194         std::string pkgName = parcel.ReadString();
1195         std::string abilityName = parcel.ReadString();
1196         std::string uri = parcel.ReadString();
1197         std::string equalTo = parcel.ReadString();
1198         std::string valuesBucket = parcel.ReadString();
1199         ActionButtonInfo info;
1200         info.type = type;
1201         info.title = title;
1202         info.resource = resource;
1203         info.wantAgent = std::make_shared<ButtonWantAgent>();
1204         if (info.wantAgent == nullptr) {
1205             return false;
1206         }
1207         info.wantAgent->pkgName = pkgName;
1208         info.wantAgent->abilityName = abilityName;
1209         info.dataShareUpdate = std::make_shared<ButtonDataShareUpdate>();
1210         if (info.dataShareUpdate == nullptr) {
1211             return false;
1212         }
1213         info.dataShareUpdate->uri = uri;
1214         info.dataShareUpdate->equalTo = equalTo;
1215         info.dataShareUpdate->valuesBucket = valuesBucket;
1216         actionButtonMap_.insert(std::pair<ActionButtonType, ActionButtonInfo>(type, info));
1217     }
1218     return true;
1219 }
1220 
ReadFromParcel(Parcel & parcel)1221 bool ReminderRequest::ReadFromParcel(Parcel &parcel)
1222 {
1223     READ_STRING_RETURN_FALSE_LOG(parcel, content_, "content");
1224     READ_STRING_RETURN_FALSE_LOG(parcel, expiredContent_, "expiredContent");
1225     READ_STRING_RETURN_FALSE_LOG(parcel, snoozeContent_, "snoozeContent");
1226     READ_STRING_RETURN_FALSE_LOG(parcel, title_, "title");
1227     READ_STRING_RETURN_FALSE_LOG(parcel, wantAgentInfo_->abilityName, "wantAgentInfo's abilityName");
1228     READ_STRING_RETURN_FALSE_LOG(parcel, wantAgentInfo_->pkgName, "wantAgentInfo's pkgName");
1229     READ_STRING_RETURN_FALSE_LOG(parcel, wantAgentInfo_->uri, "wantAgentInfo's uri");
1230     READ_STRING_RETURN_FALSE_LOG(parcel, maxScreenWantAgentInfo_->abilityName, "maxScreenWantAgentInfo's abilityName");
1231     READ_STRING_RETURN_FALSE_LOG(parcel, maxScreenWantAgentInfo_->pkgName, "maxScreenWantAgentInfo's pkgName");
1232     READ_STRING_RETURN_FALSE_LOG(parcel, customButtonUri_, "customButtonUri");
1233     READ_STRING_RETURN_FALSE_LOG(parcel, customRingUri_, "customRingUri");
1234     READ_STRING_RETURN_FALSE_LOG(parcel, creatorBundleName_, "creatorBundleName");
1235 
1236     READ_BOOL_RETURN_FALSE_LOG(parcel, isExpired_, "isExpired");
1237     READ_BOOL_RETURN_FALSE_LOG(parcel, isSystemApp_, "isSystemApp");
1238     READ_BOOL_RETURN_FALSE_LOG(parcel, tapDismissed_, "tapDismissed");
1239 
1240     READ_INT64_RETURN_FALSE_LOG(parcel, autoDeletedTime_, "autoDeletedTime");
1241 
1242     int32_t tempReminderId = -1;
1243     READ_INT32_RETURN_FALSE_LOG(parcel, tempReminderId, "reminderId");
1244     reminderId_ = (tempReminderId == -1) ? reminderId_ : tempReminderId;
1245 
1246     READ_INT32_RETURN_FALSE_LOG(parcel, notificationId_, "notificationId");
1247 
1248     READ_STRING_RETURN_FALSE_LOG(parcel, groupId_, "groupId");
1249     READ_UINT64_RETURN_FALSE_LOG(parcel, triggerTimeInMilli_, "triggerTimeInMilli");
1250     READ_UINT64_RETURN_FALSE_LOG(parcel, timeIntervalInMilli_, "timeIntervalInMilli");
1251     READ_UINT64_RETURN_FALSE_LOG(parcel, ringDurationInMilli_, "ringDurationInMilli");
1252     READ_UINT64_RETURN_FALSE_LOG(parcel, reminderTimeInMilli_, "reminderTimeInMilli");
1253 
1254     READ_UINT8_RETURN_FALSE_LOG(parcel, snoozeTimes_, "snoozeTimes");
1255     READ_UINT8_RETURN_FALSE_LOG(parcel, snoozeTimesDynamic_, "snoozeTimesDynamic");
1256     READ_UINT8_RETURN_FALSE_LOG(parcel, state_, "state");
1257     READ_UINT8_RETURN_FALSE_LOG(parcel, repeatDaysOfWeek_, "repeatDaysOfWeek");
1258 
1259     uint8_t reminderType = static_cast<uint8_t>(ReminderType::INVALID);
1260     READ_UINT8_RETURN_FALSE_LOG(parcel, reminderType, "reminderType");
1261     reminderType_ = static_cast<ReminderType>(reminderType);
1262 
1263     int32_t slotType = static_cast<int32_t>(NotificationConstant::SlotType::OTHER);
1264     READ_INT32_RETURN_FALSE_LOG(parcel, slotType, "slotType");
1265     slotType_ = static_cast<NotificationConstant::SlotType>(slotType);
1266 
1267     int32_t snoozeSlotType = static_cast<int32_t>(NotificationConstant::SlotType::OTHER);
1268     READ_INT32_RETURN_FALSE_LOG(parcel, snoozeSlotType, "snoozeSlotType");
1269     snoozeSlotType_ = static_cast<NotificationConstant::SlotType>(snoozeSlotType);
1270 
1271     if (!ReadActionButtonFromParcel(parcel)) {
1272         return false;
1273     }
1274 
1275     if (!InitNotificationRequest()) {
1276         return false;
1277     }
1278     return true;
1279 }
1280 
InitNotificationRequest()1281 bool ReminderRequest::InitNotificationRequest()
1282 {
1283     ANSR_LOGI("Init notification");
1284     notificationRequest_ = new (std::nothrow) NotificationRequest(notificationId_);
1285     if (notificationRequest_ == nullptr) {
1286         ANSR_LOGE("Failed to create notification.");
1287         return false;
1288     }
1289     displayContent_ = content_;
1290     AddActionButtons(true);
1291     return true;
1292 }
1293 
InitServerObj()1294 void ReminderRequest::InitServerObj()
1295 {
1296     wantAgentInfo_ = wantAgentInfo_ == nullptr ? std::make_shared<WantAgentInfo>() : wantAgentInfo_;
1297     maxScreenWantAgentInfo_ =
1298         maxScreenWantAgentInfo_ == nullptr ? std::make_shared<MaxScreenAgentInfo>() : maxScreenWantAgentInfo_;
1299 }
1300 
IsAlerting() const1301 bool ReminderRequest::IsAlerting() const
1302 {
1303     return (state_ & REMINDER_STATUS_ALERTING) != 0;
1304 }
1305 
GetDurationSinceEpochInMilli(const time_t target)1306 uint64_t ReminderRequest::GetDurationSinceEpochInMilli(const time_t target)
1307 {
1308     auto tarEndTimePoint = std::chrono::system_clock::from_time_t(target);
1309     auto tarDuration = std::chrono::duration_cast<std::chrono::milliseconds>(tarEndTimePoint.time_since_epoch());
1310     int64_t tarDate = tarDuration.count();
1311     if (tarDate < 0) {
1312         ANSR_LOGW("tarDuration is less than 0.");
1313         return INVALID_LONG_LONG_VALUE;
1314     }
1315     return static_cast<uint64_t>(tarDate);
1316 }
1317 
GetDateTimeInfo(const time_t & timeInSecond) const1318 std::string ReminderRequest::GetDateTimeInfo(const time_t &timeInSecond) const
1319 {
1320     return GetTimeInfoInner(timeInSecond, TimeFormat::YMDHMS, true);
1321 }
1322 
GetButtonInfo() const1323 std::string ReminderRequest::GetButtonInfo() const
1324 {
1325     std::string info = "";
1326     bool isFirst = true;
1327     for (auto button : actionButtonMap_) {
1328         if (!isFirst) {
1329             info += SEP_BUTTON_MULTI;
1330         }
1331         ActionButtonInfo buttonInfo = button.second;
1332         nlohmann::json root;
1333         root["type"] = std::to_string(static_cast<uint8_t>(button.first));
1334         root["title"] = buttonInfo.title;
1335         root["resource"] = buttonInfo.resource;
1336         if (buttonInfo.wantAgent != nullptr) {
1337             nlohmann::json wantAgentfriends;
1338             wantAgentfriends["pkgName"] = buttonInfo.wantAgent->pkgName;
1339             wantAgentfriends["abilityName"] = buttonInfo.wantAgent->abilityName;
1340             root["wantAgent"]  = wantAgentfriends;
1341         }
1342 
1343         if (buttonInfo.dataShareUpdate != nullptr) {
1344             nlohmann::json dataShareUpdatefriends;
1345             dataShareUpdatefriends["uri"] = buttonInfo.dataShareUpdate->uri;
1346             dataShareUpdatefriends["equalTo"] = buttonInfo.dataShareUpdate->equalTo;
1347             dataShareUpdatefriends["valuesBucket"] = buttonInfo.dataShareUpdate->valuesBucket;
1348             root["dataShareUpdate"]  = dataShareUpdatefriends;
1349         }
1350         std::string str = root.dump(INDENT, ' ', false, nlohmann::json::error_handler_t::replace);
1351         info += str;
1352         isFirst = false;
1353     }
1354     return info;
1355 }
1356 
GetNowInstantMilli() const1357 uint64_t ReminderRequest::GetNowInstantMilli() const
1358 {
1359     time_t now;
1360     (void)time(&now);  // unit is seconds.
1361     if (static_cast<int64_t>(now) < 0) {
1362         ANSR_LOGE("Get now time error");
1363         return 0;
1364     }
1365     return GetDurationSinceEpochInMilli(now);
1366 }
1367 
GetShowTime(const uint64_t showTime) const1368 std::string ReminderRequest::GetShowTime(const uint64_t showTime) const
1369 {
1370     if (reminderType_ == ReminderType::TIMER) {
1371         return "";
1372     }
1373     return GetTimeInfoInner(static_cast<time_t>(showTime / MILLI_SECONDS), TimeFormat::HM, false);
1374 }
1375 
GetTimeInfoInner(const time_t & timeInSecond,const TimeFormat & format,bool keep24Hour) const1376 std::string ReminderRequest::GetTimeInfoInner(const time_t &timeInSecond, const TimeFormat &format,
1377     bool keep24Hour) const
1378 {
1379     const uint8_t dateTimeLen = 80;
1380     char dateTimeBuffer[dateTimeLen];
1381     struct tm timeInfo;
1382     (void)localtime_r(&timeInSecond, &timeInfo);
1383     bool is24HourClock = OHOS::Global::I18n::LocaleConfig::Is24HourClock();
1384     if (!is24HourClock && timeInfo.tm_hour > TIME_HOUR_OFFSET && !keep24Hour) {
1385         timeInfo.tm_hour -= TIME_HOUR_OFFSET;
1386     }
1387     switch (format) {
1388         case TimeFormat::YMDHMS: {
1389             (void)strftime(dateTimeBuffer, dateTimeLen, "%Y-%m-%d %H:%M:%S", &timeInfo);
1390             break;
1391         }
1392         case TimeFormat::HM: {
1393             (void)strftime(dateTimeBuffer, dateTimeLen, "%H:%M", &timeInfo);
1394             break;
1395         }
1396         default: {
1397             ANSR_LOGW("Time format not support.");
1398             break;
1399         }
1400     }
1401     std::string dateTimeInfo(dateTimeBuffer);
1402     return dateTimeInfo;
1403 }
1404 
GetState(const uint8_t state) const1405 std::string ReminderRequest::GetState(const uint8_t state) const
1406 {
1407     std::string stateInfo = "'";
1408     if (state == REMINDER_STATUS_INACTIVE) {
1409         stateInfo += "Inactive";
1410     } else {
1411         bool hasSeparator = false;
1412         if ((state & REMINDER_STATUS_ACTIVE) != 0) {
1413             stateInfo += "Active";
1414             hasSeparator = true;
1415         }
1416         if ((state & REMINDER_STATUS_ALERTING) != 0) {
1417             if (hasSeparator) {
1418                 stateInfo += ",";
1419             }
1420             stateInfo += "Alerting";
1421             hasSeparator = true;
1422         }
1423         if ((state & REMINDER_STATUS_SHOWING) != 0) {
1424             if (hasSeparator) {
1425                 stateInfo += ",";
1426             }
1427             stateInfo += "Showing";
1428             hasSeparator = true;
1429         }
1430         if ((state & REMINDER_STATUS_SNOOZE) != 0) {
1431             if (hasSeparator) {
1432                 stateInfo += ",";
1433             }
1434             stateInfo += "Snooze";
1435         }
1436     }
1437     stateInfo += "'";
1438     return stateInfo;
1439 }
1440 
AddActionButtons(const bool includeSnooze)1441 void ReminderRequest::AddActionButtons(const bool includeSnooze)
1442 {
1443     int32_t requestCode = 10;
1444     std::vector<AbilityRuntime::WantAgent::WantAgentConstant::Flags> flags;
1445     flags.push_back(AbilityRuntime::WantAgent::WantAgentConstant::Flags::UPDATE_PRESENT_FLAG);
1446     for (auto button : actionButtonMap_) {
1447         auto want = std::make_shared<OHOS::AAFwk::Want>();
1448         auto type = button.first;
1449         switch (type) {
1450             case ActionButtonType::CLOSE:
1451                 want->SetAction(REMINDER_EVENT_CLOSE_ALERT);
1452                 break;
1453             case ActionButtonType::SNOOZE:
1454                 if (includeSnooze) {
1455                     want->SetAction(REMINDER_EVENT_SNOOZE_ALERT);
1456                 } else {
1457                     ANSR_LOGD("Not add action button, type is snooze, as includeSnooze is false");
1458                     continue;
1459                 }
1460                 break;
1461             case ActionButtonType::CUSTOM:
1462                 want->SetAction(REMINDER_EVENT_CUSTOM_ALERT);
1463                 if (button.second.wantAgent == nullptr) {
1464                     return;
1465                 }
1466                 want->SetParam("PkgName", button.second.wantAgent->pkgName);
1467                 want->SetParam("AbilityName", button.second.wantAgent->abilityName);
1468                 break;
1469             default:
1470                 break;
1471         }
1472         want->SetParam(PARAM_REMINDER_ID, reminderId_);
1473         std::vector<std::shared_ptr<AAFwk::Want>> wants;
1474         wants.push_back(want);
1475         auto title = static_cast<std::string>(button.second.title);
1476         AbilityRuntime::WantAgent::WantAgentInfo buttonWantAgentInfo(
1477             requestCode,
1478             AbilityRuntime::WantAgent::WantAgentConstant::OperationType::SEND_COMMON_EVENT,
1479             flags,
1480             wants,
1481             nullptr
1482         );
1483 
1484         std::string identity = IPCSkeleton::ResetCallingIdentity();
1485         std::shared_ptr<AbilityRuntime::WantAgent::WantAgent> buttonWantAgent =
1486             AbilityRuntime::WantAgent::WantAgentHelper::GetWantAgent(buttonWantAgentInfo, userId_);
1487         IPCSkeleton::SetCallingIdentity(identity);
1488 
1489         std::shared_ptr<NotificationActionButton> actionButton
1490             = NotificationActionButton::Create(nullptr, title, buttonWantAgent);
1491         notificationRequest_->AddActionButton(actionButton);
1492     }
1493 }
1494 
AddRemovalWantAgent()1495 void ReminderRequest::AddRemovalWantAgent()
1496 {
1497     int32_t requestCode = 10;
1498     std::vector<AbilityRuntime::WantAgent::WantAgentConstant::Flags> flags;
1499     flags.push_back(AbilityRuntime::WantAgent::WantAgentConstant::Flags::UPDATE_PRESENT_FLAG);
1500     auto want = std::make_shared<OHOS::AAFwk::Want>();
1501     want->SetAction(REMINDER_EVENT_REMOVE_NOTIFICATION);
1502     want->SetParam(PARAM_REMINDER_ID, reminderId_);
1503     std::vector<std::shared_ptr<AAFwk::Want>> wants;
1504     wants.push_back(want);
1505     AbilityRuntime::WantAgent::WantAgentInfo wantAgentInfo(
1506         requestCode,
1507         AbilityRuntime::WantAgent::WantAgentConstant::OperationType::SEND_COMMON_EVENT,
1508         flags,
1509         wants,
1510         nullptr
1511     );
1512 
1513     std::string identity = IPCSkeleton::ResetCallingIdentity();
1514     std::shared_ptr<AbilityRuntime::WantAgent::WantAgent> wantAgent =
1515         AbilityRuntime::WantAgent::WantAgentHelper::GetWantAgent(wantAgentInfo, userId_);
1516     IPCSkeleton::SetCallingIdentity(identity);
1517 
1518     notificationRequest_->SetRemovalWantAgent(wantAgent);
1519 }
1520 
CreateWantAgent(AppExecFwk::ElementName & element,bool isWantAgent) const1521 std::shared_ptr<AbilityRuntime::WantAgent::WantAgent> ReminderRequest::CreateWantAgent(
1522     AppExecFwk::ElementName &element, bool isWantAgent) const
1523 {
1524     int32_t requestCode = 10;
1525     std::vector<AbilityRuntime::WantAgent::WantAgentConstant::Flags> flags;
1526     flags.push_back(AbilityRuntime::WantAgent::WantAgentConstant::Flags::UPDATE_PRESENT_FLAG);
1527     auto want = std::make_shared<OHOS::AAFwk::Want>();
1528     want->SetElement(element);
1529     if (isWantAgent) {
1530         want->SetUri(wantAgentInfo_->uri);
1531     }
1532     std::vector<std::shared_ptr<AAFwk::Want>> wants;
1533     wants.push_back(want);
1534     AbilityRuntime::WantAgent::WantAgentInfo wantAgentInfo(
1535         requestCode,
1536         AbilityRuntime::WantAgent::WantAgentConstant::OperationType::START_ABILITY,
1537         flags,
1538         wants,
1539         nullptr
1540     );
1541     std::string identity = IPCSkeleton::ResetCallingIdentity();
1542     auto wantAgent = AbilityRuntime::WantAgent::WantAgentHelper::GetWantAgent(wantAgentInfo, userId_);
1543     IPCSkeleton::SetCallingIdentity(identity);
1544     return wantAgent;
1545 }
1546 
SetMaxScreenWantAgent(AppExecFwk::ElementName & element)1547 void ReminderRequest::SetMaxScreenWantAgent(AppExecFwk::ElementName &element)
1548 {
1549     std::shared_ptr<AbilityRuntime::WantAgent::WantAgent> wantAgent = CreateWantAgent(element, false);
1550     notificationRequest_->SetMaxScreenWantAgent(wantAgent);
1551 }
1552 
SetWantAgent(AppExecFwk::ElementName & element)1553 void ReminderRequest::SetWantAgent(AppExecFwk::ElementName &element)
1554 {
1555     std::shared_ptr<AbilityRuntime::WantAgent::WantAgent> wantAgent = CreateWantAgent(element, true);
1556     notificationRequest_->SetWantAgent(wantAgent);
1557 }
1558 
SetState(bool deSet,const uint8_t newState,std::string function)1559 void ReminderRequest::SetState(bool deSet, const uint8_t newState, std::string function)
1560 {
1561     uint8_t oldState = state_;
1562     if (deSet) {
1563         state_ |= newState;
1564     } else {
1565         state_ &= static_cast<uint8_t>(~newState);
1566     }
1567     ANSR_LOGI("Switch the reminder(reminderId=%{public}d) state, from %{public}s to %{public}s, called by %{public}s",
1568         reminderId_, GetState(oldState).c_str(), GetState(state_).c_str(), function.c_str());
1569 }
1570 
SetStateToInActive()1571 void ReminderRequest::SetStateToInActive()
1572 {
1573     SetState(false, (REMINDER_STATUS_SHOWING | REMINDER_STATUS_ALERTING | REMINDER_STATUS_ACTIVE),
1574         "SetStateToInActive");
1575 }
1576 
UpdateActionButtons(const bool & setSnooze)1577 void ReminderRequest::UpdateActionButtons(const bool &setSnooze)
1578 {
1579     if (notificationRequest_ == nullptr) {
1580         ANSR_LOGE("updateActionButtons failed, the notificationRequest is null");
1581         return;
1582     }
1583     notificationRequest_->ClearActionButtons();
1584     if (setSnooze) {
1585         AddActionButtons(false);
1586     } else {
1587         AddActionButtons(true);
1588     }
1589 }
1590 
UpdateNextReminder(const bool & force)1591 bool ReminderRequest::UpdateNextReminder(const bool &force)
1592 {
1593     bool result = true;
1594     if (force) {
1595         uint64_t nowInstantMilli = GetNowInstantMilli();
1596         if (nowInstantMilli == 0) {
1597             result = false;
1598         } else {
1599             triggerTimeInMilli_ = nowInstantMilli + timeIntervalInMilli_;
1600             snoozeTimesDynamic_ = snoozeTimes_;
1601             if (timeIntervalInMilli_ != 0) {
1602                 isExpired_ = false;
1603             }
1604         }
1605     } else {
1606         result = UpdateNextReminder();
1607     }
1608     std::string info = result ? "success" : "no next";
1609     ANSR_LOGI("updateNextReminder(id=%{public}d, %{public}s): force=%{public}d, trigger time is: %{public}s",
1610         reminderId_, info.c_str(), force,
1611         GetDateTimeInfo(static_cast<time_t>(triggerTimeInMilli_ / MILLI_SECONDS)).c_str());
1612     return result;
1613 }
1614 
UpdateNotificationCommon(bool isSnooze)1615 void ReminderRequest::UpdateNotificationCommon(bool isSnooze)
1616 {
1617     time_t now;
1618     (void)time(&now);  // unit is seconds.
1619     notificationRequest_->SetDeliveryTime(GetDurationSinceEpochInMilli(now));
1620     notificationRequest_->SetLabel(NOTIFICATION_LABEL);
1621     notificationRequest_->SetShowDeliveryTime(true);
1622     if (isSnooze) {
1623         if (snoozeSlotType_ == NotificationConstant::SlotType::OTHER) {
1624             notificationRequest_->SetSlotType(NotificationConstant::SlotType::CONTENT_INFORMATION);
1625         } else {
1626             notificationRequest_->SetSlotType(snoozeSlotType_);
1627         }
1628     } else {
1629         notificationRequest_->SetSlotType(slotType_);
1630     }
1631     notificationRequest_->SetTapDismissed(tapDismissed_);
1632     notificationRequest_->SetAutoDeletedTime(autoDeletedTime_);
1633     auto notificationNormalContent = std::make_shared<NotificationNormalContent>();
1634     notificationNormalContent->SetText(displayContent_);
1635     notificationNormalContent->SetTitle(title_);
1636     auto notificationContent = std::make_shared<NotificationContent>(notificationNormalContent);
1637     notificationRequest_->SetContent(notificationContent);
1638     if ((reminderType_ == ReminderRequest::ReminderType::TIMER) ||
1639         (reminderType_ == ReminderRequest::ReminderType::ALARM)) {
1640         notificationRequest_->SetUnremovable(true);
1641     }
1642 }
1643 
UpdateNotificationBundleInfo()1644 void ReminderRequest::UpdateNotificationBundleInfo()
1645 {
1646     std::string ownerBundleName = notificationRequest_->GetOwnerBundleName();
1647     if (!(ownerBundleName.empty())) {
1648         return;
1649     }
1650     ANSR_LOGD("ownerBundleName=%{public}s, bundleName_=%{public}s",
1651         ownerBundleName.c_str(), bundleName_.c_str());
1652     notificationRequest_->SetOwnerBundleName(bundleName_);
1653     notificationRequest_->SetCreatorBundleName(bundleName_);
1654     notificationRequest_->SetCreatorUid(uid_);
1655     ErrCode errCode = AccountSA::OsAccountManager::GetOsAccountLocalIdFromUid(uid_, userId_);
1656     if (errCode != ERR_OK) {
1657         ANSR_LOGE("GetOsAccountLocalIdFromUid fail.");
1658         return;
1659     }
1660     notificationRequest_->SetCreatorUserId(userId_);
1661 }
1662 
UpdateNotificationContent(const bool & setSnooze)1663 void ReminderRequest::UpdateNotificationContent(const bool &setSnooze)
1664 {
1665     if (notificationRequest_ == nullptr) {
1666         ANSR_LOGE("updateNotificationContent failed, the notificationRequest is null");
1667         return;
1668     }
1669     std::string extendContent = "";
1670     if (setSnooze) {
1671         if (timeIntervalInMilli_ != 0) {
1672             // snooze the reminder by manual
1673             extendContent = snoozeContent_;
1674             notificationRequest_->SetTapDismissed(false);
1675         } else {
1676             // the reminder is expired now, when timeInterval is 0
1677             extendContent = expiredContent_;
1678         }
1679     } else if (IsAlerting()) {
1680         // the reminder is alerting, or ring duration is 0
1681         extendContent = "";
1682     } else if (snoozeTimesDynamic_ != snoozeTimes_) {
1683         // the reminder is snoozing by period artithmetic, when the ring duration is over.
1684         extendContent = snoozeContent_;
1685         notificationRequest_->SetTapDismissed(false);
1686     } else {
1687         // the reminder has already snoozed by period arithmetic, when the ring duration is over.
1688         extendContent = expiredContent_;
1689     }
1690     if (extendContent == "") {
1691         displayContent_ = content_;
1692     } else {
1693         displayContent_ = extendContent;
1694     }
1695     ANSR_LOGD("Display content=%{public}s", displayContent_.c_str());
1696 }
1697 
UpdateNotificationStateForAlert()1698 void ReminderRequest::UpdateNotificationStateForAlert()
1699 {
1700     ANSR_LOGD("UpdateNotification content and buttons");
1701     UpdateNotificationContent(false);
1702     UpdateActionButtons(false);
1703 }
1704 
UpdateNotificationStateForSnooze()1705 void ReminderRequest::UpdateNotificationStateForSnooze()
1706 {
1707     ANSR_LOGD("UpdateNotification content and buttons");
1708     UpdateNotificationContent(true);
1709     UpdateActionButtons(true);
1710 }
1711 
GetActualTime(const TimeTransferType & type,int32_t cTime)1712 int32_t ReminderRequest::GetActualTime(const TimeTransferType &type, int32_t cTime)
1713 {
1714     switch (type) {
1715         case (TimeTransferType::YEAR):  // year
1716             return BASE_YEAR + cTime;
1717         case (TimeTransferType::MONTH):  // month
1718             return 1 + cTime;
1719         case (TimeTransferType::WEEK): {  // week
1720             return cTime == 0 ? SUNDAY : cTime;
1721         }
1722         default:
1723             return -1;
1724     }
1725 }
1726 
GetCTime(const TimeTransferType & type,int32_t actualTime)1727 int32_t ReminderRequest::GetCTime(const TimeTransferType &type, int32_t actualTime)
1728 {
1729     switch (type) {
1730         case (TimeTransferType::YEAR):  // year
1731             return actualTime - BASE_YEAR;
1732         case (TimeTransferType::MONTH):  // month
1733             return actualTime - 1;
1734         case (TimeTransferType::WEEK): {  // week
1735             return actualTime == SUNDAY ? 0 : actualTime;
1736         }
1737         default:
1738             return -1;
1739     }
1740 }
1741 
GetUid(const int32_t & userId,const std::string & bundleName)1742 int32_t ReminderRequest::GetUid(const int32_t &userId, const std::string &bundleName)
1743 {
1744     AppExecFwk::ApplicationInfo info;
1745     sptr<ISystemAbilityManager> systemAbilityManager
1746         = SystemAbilityManagerClient::GetInstance().GetSystemAbilityManager();
1747     if (systemAbilityManager == nullptr) {
1748         ANSR_LOGE("Failed to get uid due to get systemAbilityManager is null.");
1749         return -1;
1750     }
1751     sptr<IRemoteObject> remoteObject  = systemAbilityManager->GetSystemAbility(BUNDLE_MGR_SERVICE_SYS_ABILITY_ID);
1752     if (remoteObject == nullptr) {
1753         ANSR_LOGE("Fail to get bundle manager proxy");
1754         return -1;
1755     }
1756     sptr<AppExecFwk::IBundleMgr> bundleMgr = iface_cast<AppExecFwk::IBundleMgr>(remoteObject);
1757     if (bundleMgr == nullptr) {
1758         ANSR_LOGE("Bundle mgr proxy is nullptr");
1759         return -1;
1760     }
1761     bundleMgr->GetApplicationInfo(bundleName, AppExecFwk::ApplicationFlag::GET_BASIC_APPLICATION_INFO, userId, info);
1762     ANSR_LOGD("uid=%{public}d", info.uid);
1763     return static_cast<int32_t>(info.uid);
1764 }
1765 
GetUserId(const int32_t & uid)1766 int32_t ReminderRequest::GetUserId(const int32_t &uid)
1767 {
1768     int32_t userId = -1;
1769     AccountSA::OsAccountManager::GetOsAccountLocalIdFromUid(uid, userId);
1770     ANSR_LOGD("userId=%{public}d", userId);
1771     return userId;
1772 }
1773 
AppendWantAgentValuesBucket(const sptr<ReminderRequest> & reminder,NativeRdb::ValuesBucket & values)1774 void ReminderRequest::AppendWantAgentValuesBucket(const sptr<ReminderRequest>& reminder,
1775     NativeRdb::ValuesBucket& values)
1776 {
1777     auto wantAgentInfo = reminder->GetWantAgentInfo();
1778     if (wantAgentInfo == nullptr) {
1779         std::string info = "null" + ReminderRequest::SEP_WANT_AGENT + "null" + ReminderRequest::SEP_WANT_AGENT + "null";
1780         values.PutString(ReminderTable::AGENT, info);
1781     } else {
1782         std::string info = wantAgentInfo->pkgName + ReminderRequest::SEP_WANT_AGENT
1783             + wantAgentInfo->abilityName + ReminderRequest::SEP_WANT_AGENT + wantAgentInfo->uri;
1784         values.PutString(ReminderTable::AGENT, info);
1785     }
1786 
1787     auto maxScreenWantAgentInfo = reminder->GetMaxScreenWantAgentInfo();
1788     if (maxScreenWantAgentInfo == nullptr) {
1789         std::string info = "null" + ReminderRequest::SEP_WANT_AGENT + "null";
1790         values.PutString(ReminderTable::MAX_SCREEN_AGENT, info);
1791     } else {
1792         values.PutString(ReminderTable::MAX_SCREEN_AGENT, maxScreenWantAgentInfo->pkgName
1793             + ReminderRequest::SEP_WANT_AGENT + maxScreenWantAgentInfo->abilityName);
1794     }
1795 }
1796 
AppendValuesBucket(const sptr<ReminderRequest> & reminder,const sptr<NotificationBundleOption> & bundleOption,NativeRdb::ValuesBucket & values)1797 void ReminderRequest::AppendValuesBucket(const sptr<ReminderRequest> &reminder,
1798     const sptr<NotificationBundleOption> &bundleOption, NativeRdb::ValuesBucket &values)
1799 {
1800     values.PutInt(ReminderTable::REMINDER_ID, reminder->GetReminderId());
1801     values.PutString(ReminderTable::PKG_NAME, bundleOption->GetBundleName());
1802     values.PutInt(ReminderTable::USER_ID, reminder->GetUserId());
1803     values.PutInt(ReminderTable::UID, reminder->GetUid());
1804     values.PutString(ReminderTable::SYS_APP, reminder->IsSystemApp() ? "true" : "false");
1805     values.PutString(ReminderTable::APP_LABEL, "");  // no use, compatible with old version.
1806     values.PutInt(ReminderTable::REMINDER_TYPE, static_cast<int32_t>(reminder->GetReminderType()));
1807     values.PutLong(ReminderTable::REMINDER_TIME, reminder->GetReminderTimeInMilli());
1808     values.PutLong(ReminderTable::TRIGGER_TIME, reminder->GetTriggerTimeInMilli());
1809     values.PutLong(
1810         ReminderTable::RTC_TRIGGER_TIME, reminder->GetTriggerTimeInMilli());  // no use, compatible with old version.
1811     values.PutLong(ReminderTable::TIME_INTERVAL, reminder->GetTimeInterval());
1812     values.PutInt(ReminderTable::SNOOZE_TIMES, reminder->GetSnoozeTimes());
1813     values.PutInt(ReminderTable::DYNAMIC_SNOOZE_TIMES, reminder->GetSnoozeTimesDynamic());
1814     values.PutLong(ReminderTable::RING_DURATION, reminder->GetRingDuration());
1815     values.PutString(ReminderTable::IS_EXPIRED, reminder->IsExpired() ? "true" : "false");
1816     values.PutString(ReminderTable::IS_ACTIVE, "");  // no use, compatible with old version.
1817     values.PutInt(ReminderTable::STATE, reminder->GetState());
1818     values.PutString(ReminderTable::ZONE_ID, "");  // no use, compatible with old version.
1819     values.PutString(ReminderTable::HAS_SCHEDULED_TIMEOUT, "");  // no use, compatible with old version.
1820     values.PutString(ReminderTable::ACTION_BUTTON_INFO, reminder->GetButtonInfo());
1821     values.PutString(ReminderTable::CUSTOM_BUTTON_URI, reminder->GetCustomButtonUri());
1822     values.PutInt(ReminderTable::SLOT_ID, reminder->GetSlotType());
1823     values.PutInt(ReminderTable::SNOOZE_SLOT_ID, reminder->GetSnoozeSlotType());
1824     values.PutInt(ReminderTable::NOTIFICATION_ID, reminder->GetNotificationId());
1825     values.PutString(ReminderTable::TITLE, reminder->GetTitle());
1826     values.PutString(ReminderTable::CONTENT, reminder->GetContent());
1827     values.PutString(ReminderTable::SNOOZE_CONTENT, reminder->GetSnoozeContent());
1828     values.PutString(ReminderTable::EXPIRED_CONTENT, reminder->GetExpiredContent());
1829     values.PutInt(ReminderTable::REPEAT_DAYS_OF_WEEK, reminder->GetRepeatDaysOfWeek());
1830     values.PutString(ReminderTable::GROUP_ID, reminder->GetGroupId());
1831     values.PutString(ReminderTable::CUSTOM_RING_URI, reminder->GetCustomRingUri());
1832     values.PutString(ReminderTable::CREATOR_BUNDLE_NAME, reminder->GetCreatorBundleName());
1833 
1834     AppendWantAgentValuesBucket(reminder, values);
1835 
1836     values.PutString(ReminderTable::TAP_DISMISSED, reminder->IsTapDismissed() ? "true" : "false");
1837     values.PutLong(ReminderTable::AUTO_DELETED_TIME, reminder->GetAutoDeletedTime());
1838 }
1839 
GetNextDaysOfWeek(const time_t now,const time_t target) const1840 int64_t ReminderRequest::GetNextDaysOfWeek(const time_t now, const time_t target) const
1841 {
1842     struct tm nowTime;
1843     (void)localtime_r(&now, &nowTime);
1844     int32_t today = GetActualTime(TimeTransferType::WEEK, nowTime.tm_wday);
1845     int32_t dayCount = now >= target ? 1 : 0;
1846     for (; dayCount <= DAYS_PER_WEEK; dayCount++) {
1847         int32_t day = (today + dayCount) % DAYS_PER_WEEK;
1848         day = (day == 0) ? SUNDAY : day;
1849         if (IsRepeatDaysOfWeek(day)) {
1850             break;
1851         }
1852     }
1853     ANSR_LOGI("NextDayInterval is %{public}d", dayCount);
1854     time_t nextTriggerTime = target + dayCount * HOURS_PER_DAY * SECONDS_PER_HOUR;
1855     return GetTriggerTime(now, nextTriggerTime);
1856 }
1857 
IsRepeatDaysOfWeek(int32_t day) const1858 bool ReminderRequest::IsRepeatDaysOfWeek(int32_t day) const
1859 {
1860     return (repeatDaysOfWeek_ & (1 << (day - 1))) > 0;
1861 }
1862 
GetTriggerTimeWithDST(const time_t now,const time_t nextTriggerTime) const1863 time_t ReminderRequest::GetTriggerTimeWithDST(const time_t now, const time_t nextTriggerTime) const
1864 {
1865     time_t triggerTime = nextTriggerTime;
1866     struct tm nowLocal;
1867     struct tm nextLocal;
1868     (void)localtime_r(&now, &nowLocal);
1869     (void)localtime_r(&nextTriggerTime, &nextLocal);
1870     if (nowLocal.tm_isdst == 0 && nextLocal.tm_isdst > 0) {
1871         triggerTime -= SECONDS_PER_HOUR;
1872     } else if (nowLocal.tm_isdst > 0 && nextLocal.tm_isdst == 0) {
1873         triggerTime += SECONDS_PER_HOUR;
1874     }
1875     return triggerTime;
1876 }
1877 
GetRepeatDaysOfWeek() const1878 uint8_t ReminderRequest::GetRepeatDaysOfWeek() const
1879 {
1880     return repeatDaysOfWeek_;
1881 }
1882 
SetRepeatDaysOfWeek(bool set,const std::vector<uint8_t> & daysOfWeek)1883 void ReminderRequest::SetRepeatDaysOfWeek(bool set, const std::vector<uint8_t> &daysOfWeek)
1884 {
1885     if (daysOfWeek.size() == 0) {
1886         return;
1887     }
1888     if (daysOfWeek.size() > DAYS_PER_WEEK) {
1889         ANSR_LOGE("The length of daysOfWeek should not larger than 7");
1890         return;
1891     }
1892     for (auto it = daysOfWeek.begin(); it != daysOfWeek.end(); ++it) {
1893         if (*it < MONDAY || *it > SUNDAY) {
1894             continue;
1895         }
1896         if (set) {
1897             repeatDaysOfWeek_ |= 1 << (*it - 1);
1898         } else {
1899             repeatDaysOfWeek_ &= ~(1 << (*it - 1));
1900         }
1901     }
1902 }
1903 
GetDaysOfWeek() const1904 std::vector<int32_t> ReminderRequest::GetDaysOfWeek() const
1905 {
1906     std::vector<int32_t> repeatDays;
1907     int32_t days[] = {1, 2, 3, 4, 5, 6, 7};
1908     int32_t len = sizeof(days) / sizeof(int32_t);
1909     for (int32_t i = 0; i < len; i++) {
1910         if (IsRepeatDaysOfWeek(days[i])) {
1911             repeatDays.push_back(days[i]);
1912         }
1913     }
1914     return repeatDays;
1915 }
1916 
GetTriggerTime(const time_t now,const time_t nextTriggerTime) const1917 uint64_t ReminderRequest::GetTriggerTime(const time_t now, const time_t nextTriggerTime) const
1918 {
1919     time_t triggerTime = GetTriggerTimeWithDST(now, nextTriggerTime);
1920     struct tm test;
1921     (void)localtime_r(&triggerTime, &test);
1922     ANSR_LOGI("NextTriggerTime: year=%{public}d, mon=%{public}d, day=%{public}d, hour=%{public}d, "
1923         "min=%{public}d, sec=%{public}d, week=%{public}d, nextTriggerTime=%{public}lld",
1924         GetActualTime(TimeTransferType::YEAR, test.tm_year),
1925         GetActualTime(TimeTransferType::MONTH, test.tm_mon),
1926         test.tm_mday, test.tm_hour, test.tm_min, test.tm_sec,
1927         GetActualTime(TimeTransferType::WEEK, test.tm_wday), (long long)triggerTime);
1928 
1929     if (static_cast<int64_t>(triggerTime) <= 0) {
1930         return 0;
1931     }
1932     return GetDurationSinceEpochInMilli(triggerTime);
1933 }
1934 
OnLanguageChange(const std::shared_ptr<Global::Resource::ResourceManager> & resMgr)1935 void ReminderRequest::OnLanguageChange(const std::shared_ptr<Global::Resource::ResourceManager> &resMgr)
1936 {
1937     if (resMgr == nullptr) {
1938         return;
1939     }
1940     // update title
1941     for (auto &button : actionButtonMap_) {
1942         std::string title;
1943         resMgr->GetStringByName(button.second.resource.c_str(), title);
1944         if (title.empty()) {
1945             continue;
1946         }
1947         button.second.title = title;
1948     }
1949     // update action button
1950     UpdateActionButtons(false);
1951 }
1952 
1953 }
1954 }
1955