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