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