• 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/reminder_common.h"
17 
18 #include "ans_log_wrapper.h"
19 #include "common.h"
20 #include "napi_common.h"
21 #include "ipc_skeleton.h"
22 #include "reminder_request_alarm.h"
23 #include "reminder_request_calendar.h"
24 #include "reminder_request_timer.h"
25 #include "tokenid_kit.h"
26 #include "securec.h"
27 
28 namespace OHOS {
29 namespace ReminderAgentNapi {
30 using namespace OHOS::Notification;
31 const uint32_t ASYNC_CALLBACK_PARAM_NUM = 2;
32 
GetReminderRequest(const napi_env & env,const napi_value & value,std::shared_ptr<ReminderRequest> & reminder)33 napi_value ReminderCommon::GetReminderRequest(
34     const napi_env &env, const napi_value &value, std::shared_ptr<ReminderRequest>& reminder)
35 {
36     napi_valuetype valuetype = napi_undefined;
37     NAPI_CALL(env, napi_typeof(env, value, &valuetype));
38     if (valuetype != napi_object) {
39         ANSR_LOGW("Wrong argument type. Object expected.");
40         return nullptr;
41     }
42 
43     // gen reminder
44     if (GenReminder(env, value, reminder) == nullptr) {
45         return nullptr;
46     }
47     return NotificationNapi::Common::NapiGetNull(env);
48 }
49 
GenActionButtons(const napi_env & env,const napi_value & value,std::shared_ptr<ReminderRequest> & reminder,bool isSysApp)50 bool ReminderCommon::GenActionButtons(
51     const napi_env &env, const napi_value &value, std::shared_ptr<ReminderRequest>& reminder, bool isSysApp)
52 {
53     char str[NotificationNapi::STR_MAX_SIZE] = {0};
54     napi_valuetype valuetype = napi_undefined;
55     napi_value actionButtons = nullptr;
56     if (!GetObject(env, value, ReminderAgentNapi::ACTION_BUTTON, actionButtons)) {
57         return true;
58     }
59     bool isArray = false;
60     napi_is_array(env, actionButtons, &isArray);
61     if (!isArray) {
62         ANSR_LOGW("Wrong argument type:%{public}s. array expected.", ACTION_BUTTON);
63         return false;
64     }
65 
66     uint32_t length = 0;
67     napi_get_array_length(env, actionButtons, &length);
68     for (size_t i = 0; i < length; i++) {
69         napi_value actionButton = nullptr;
70         napi_get_element(env, actionButtons, i, &actionButton);
71         NAPI_CALL_BASE(env, napi_typeof(env, actionButton, &valuetype), false);
72         if (valuetype != napi_object) {
73             ANSR_LOGW("Wrong element type:%{public}s. object expected.", ACTION_BUTTON);
74             return false;
75         }
76 
77         int32_t buttonType = static_cast<int32_t>(ReminderRequest::ActionButtonType::INVALID);
78         if (GetStringUtf8(env, actionButton,
79             ReminderAgentNapi::ACTION_BUTTON_TITLE, str, NotificationNapi::STR_MAX_SIZE) &&
80             GetInt32(env, actionButton, ReminderAgentNapi::ACTION_BUTTON_TYPE, buttonType, false)) {
81             if (!(ReminderRequest::ActionButtonType(buttonType) == ReminderRequest::ActionButtonType::CLOSE ||
82                 ReminderRequest::ActionButtonType(buttonType) == ReminderRequest::ActionButtonType::SNOOZE ||
83                 (ReminderRequest::ActionButtonType(buttonType) == ReminderRequest::ActionButtonType::CUSTOM &&
84                 isSysApp))) {
85                 ANSR_LOGW("Wrong argument type:%{public}s. buttonType not support.", ACTION_BUTTON);
86                 return false;
87             }
88             HandleActionButtonTitle(env, actionButton, reminder, str, buttonType);
89         } else {
90             ANSR_LOGW("Parse action button error.");
91             return false;
92         }
93     }
94     return true;
95 }
96 
HandleActionButtonTitle(const napi_env & env,const napi_value & actionButton,std::shared_ptr<ReminderRequest> & reminder,const char * str,int32_t buttonType)97 void ReminderCommon::HandleActionButtonTitle(const napi_env &env, const napi_value &actionButton,
98     std::shared_ptr<ReminderRequest>& reminder, const char* str, int32_t buttonType)
99 {
100     char res[NotificationNapi::STR_MAX_SIZE] = {0};
101     std::string resource = "";
102     if (GetStringUtf8(env, actionButton, ReminderAgentNapi::ACTION_BUTTON_RESOURCE, res,
103         NotificationNapi::STR_MAX_SIZE)) {
104         resource = std::string(res);
105     }
106 
107     std::string title(str);
108     auto buttonWantAgent = std::make_shared<ReminderRequest::ButtonWantAgent>();
109     if (ReminderRequest::ActionButtonType(buttonType) == ReminderRequest::ActionButtonType::CUSTOM) {
110         GetButtonWantAgent(env, actionButton, reminder, buttonWantAgent);
111     }
112     // gen buttonDataShareUpdate
113     auto buttonDataShareUpdate = std::make_shared<ReminderRequest::ButtonDataShareUpdate>();
114     if (ReminderRequest::ActionButtonType(buttonType) != ReminderRequest::ActionButtonType::INVALID) {
115         GetButtonDataShareUpdate(env, actionButton, buttonDataShareUpdate);
116     }
117     reminder->SetActionButton(title, static_cast<ReminderRequest::ActionButtonType>(buttonType),
118         resource, buttonWantAgent, buttonDataShareUpdate);
119     ANSR_LOGD("button title=%{public}s, type=%{public}d, resource=%{public}s",
120         title.c_str(), buttonType, resource.c_str());
121 }
122 
IsSelfSystemApp()123 bool ReminderCommon::IsSelfSystemApp()
124 {
125     auto selfToken = IPCSkeleton::GetSelfTokenID();
126     if (!Security::AccessToken::TokenIdKit::IsSystemAppByFullTokenID(selfToken)) {
127         ANSR_LOGW("This application is not system-app, can not use system-api");
128         return false;
129     }
130     return true;
131 }
132 
GetButtonWantAgent(const napi_env & env,const napi_value & value,std::shared_ptr<ReminderRequest> & reminder,std::shared_ptr<ReminderRequest::ButtonWantAgent> & buttonWantAgent)133 void ReminderCommon::GetButtonWantAgent(const napi_env &env, const napi_value &value,
134     std::shared_ptr<ReminderRequest>& reminder, std::shared_ptr<ReminderRequest::ButtonWantAgent>& buttonWantAgent)
135 {
136     char str[NotificationNapi::STR_MAX_SIZE] = {0};
137     napi_value wantAgent = nullptr;
138     if (GetObject(env, value, ReminderAgentNapi::BUTTON_WANT_AGENT, wantAgent)) {
139         if (GetStringUtf8(env, wantAgent,
140             ReminderAgentNapi::BUTTON_WANT_AGENT_PKG, str, NotificationNapi::STR_MAX_SIZE)) {
141             buttonWantAgent->pkgName = str;
142         }
143         if (GetStringUtf8(env, wantAgent,
144             ReminderAgentNapi::BUTTON_WANT_AGENT_ABILITY, str, NotificationNapi::STR_MAX_SIZE)) {
145             buttonWantAgent->abilityName = str;
146         }
147         if (GetStringUtf8(env, wantAgent,
148             ReminderAgentNapi::BUTTON_WANT_AGENT_URI, str, NotificationNapi::STR_MAX_SIZE)) {
149             reminder->SetCustomButtonUri(str);
150         }
151     }
152 }
153 
154 // uri:string  equalTo{key:value}  valuesBucket{key:value}
GetButtonDataShareUpdate(const napi_env & env,const napi_value & value,std::shared_ptr<ReminderRequest::ButtonDataShareUpdate> & buttonDataShareUpdate)155 void ReminderCommon::GetButtonDataShareUpdate(const napi_env &env, const napi_value &value,
156     std::shared_ptr<ReminderRequest::ButtonDataShareUpdate>& buttonDataShareUpdate)
157 {
158     napi_value dataShare = nullptr;
159     if (GetObject(env, value, BUTTON_DATA_SHARE_UPDATE, dataShare)) {
160         // dataShare uri
161         char str[NotificationNapi::STR_MAX_SIZE] = {0};
162         if (GetStringUtf8(env, dataShare, BUTTON_DATA_SHARE_UPDATE_URI, str, NotificationNapi::STR_MAX_SIZE)) {
163             ANSR_LOGD("gen dataShareUri success");
164             buttonDataShareUpdate->uri = str;
165         }
166         // dataShare equalTo
167         napi_value equalTo = nullptr;
168         std::string valueBucketString;
169         if (GetObject(env, dataShare, BUTTON_DATA_SHARE_UPDATE_EQUALTO, equalTo)) {
170             if (GetValueBucketObject(valueBucketString, env, equalTo)) {
171                 ANSR_LOGD("gen dataShareEqualTo success");
172                 buttonDataShareUpdate->equalTo = valueBucketString;
173             }
174         }
175         // dataShare valuesBucket
176         napi_value valuesBucket = nullptr;
177         valueBucketString.clear();
178         if (GetObject(env, dataShare, BUTTON_DATA_SHARE_UPDATE_VALUE, valuesBucket)) {
179             if (GetValueBucketObject(valueBucketString, env, valuesBucket)) {
180                 ANSR_LOGD("gen dataShareValuesBucket success");
181                 buttonDataShareUpdate->valuesBucket = valueBucketString;
182             }
183         }
184     }
185 }
186 
187 // get {key:value} to string(key:type:value)
GetValueBucketObject(std::string & valueBucketString,const napi_env & env,const napi_value & arg)188 bool ReminderCommon::GetValueBucketObject(std::string &valueBucketString, const napi_env &env, const napi_value &arg)
189 {
190     // arrary
191     napi_value keys = 0;
192     napi_get_property_names(env, arg, &keys);
193     uint32_t arrlen = 0;
194     napi_status status = napi_get_array_length(env, keys, &arrlen);
195     if (status != napi_ok) {
196         ANSR_LOGW("get the valuesBucket length err");
197         return false;
198     }
199     for (size_t i = 0; i < arrlen; ++i) {
200         // key
201         napi_value key = 0;
202         status = napi_get_element(env, keys, i, &key);
203         if (status != napi_ok) {
204             ANSR_LOGW("get valuesBucket err");
205             continue;
206         }
207         std::string keyStr = GetStringFromJS(env, key);
208         if (!ValidateString(keyStr)) {
209             ANSR_LOGW("The key contains separator");
210             return false;
211         }
212         // value
213         napi_value value = 0;
214         napi_get_property(env, arg, key, &value);
215         bool ret;
216         std::string type;
217         std::string valueObject = Convert2Value(env, value, ret, type);
218         if (!ret) {
219             ANSR_LOGW("parse valuesBucket err");
220             continue;
221         }
222         if (!ValidateString(valueObject)) {
223             ANSR_LOGW("The value contains separator");
224             return false;
225         }
226         valueBucketString += keyStr + ReminderRequest::SEP_BUTTON_VALUE + type
227             + ReminderRequest::SEP_BUTTON_VALUE + valueObject;
228         if (i < arrlen - 1) {
229             valueBucketString += ReminderRequest::SEP_BUTTON_VALUE_TYPE;
230         }
231     }
232     return true;
233 }
234 
235 // get string
GetStringFromJS(const napi_env & env,const napi_value & param,const std::string & defaultValue)236 std::string ReminderCommon::GetStringFromJS(const napi_env &env, const napi_value &param,
237     const std::string &defaultValue)
238 {
239     size_t size = 0;
240     if (napi_get_value_string_utf8(env, param, nullptr, 0, &size) != napi_ok) {
241         return defaultValue;
242     }
243     if (size == 0) {
244         return defaultValue;
245     }
246 
247     char *buf = new (std::nothrow) char[size + 1];
248     std::string value("");
249     if (buf == nullptr) {
250         return value;
251     }
252     (void)memset_s(buf, size + 1, 0, size + 1);
253     bool rev = napi_get_value_string_utf8(env, param, buf, size + 1, &size) == napi_ok;
254     if (rev) {
255         value = buf;
256     } else {
257         value = defaultValue;
258     }
259 
260     if (buf != nullptr) {
261         delete[] buf;
262         buf = nullptr;
263     }
264     return value;
265 }
266 
267 // get type and value
Convert2Value(const napi_env & env,const napi_value & value,bool & status,std::string & type)268 std::string ReminderCommon::Convert2Value(const napi_env &env, const napi_value &value, bool &status, std::string &type)
269 {
270     // array type
271     napi_valuetype valueType = napi_undefined;
272     napi_typeof(env, value, &valueType);
273     status = true;
274     // gen value
275     std::string valueString;
276     std::vector<uint8_t> valueBlob;
277     switch (valueType) {
278         case napi_null: {
279             type = "null";
280             valueString = type;
281             break;
282         }
283         case napi_boolean: {
284             type = "bool";
285             bool valueBool = false;
286             napi_get_value_bool(env, value, &valueBool);
287             valueString = std::to_string(valueBool);
288             break;
289         }
290         case napi_number: {
291             type = "double";
292             double valueNumber = 0;
293             napi_get_value_double(env, value, &valueNumber);
294             valueString = std::to_string(valueNumber);
295             break;
296         }
297         case napi_string: {
298             type = "string";
299             valueString = GetStringFromJS(env, value);
300             break;
301         }
302         case napi_object: {
303             type = "vector";
304             valueBlob = Convert2U8Vector(env, value);
305             for (auto it = valueBlob.begin(); it != valueBlob.end(); ++it) {
306                 valueString += std::to_string(*it);
307                 if ((it + 1) != valueBlob.end()) {
308                     valueString += ReminderRequest::SEP_BUTTON_VALUE_BLOB;
309                 }
310             }
311             break;
312         }
313         default: {
314             ANSR_LOGE("Convert2Value err");
315             status = false;
316             break;
317         }
318     }
319     return valueString;
320 }
321 
322 // get vector<uint8_t>
Convert2U8Vector(const napi_env & env,const napi_value & input_array)323 std::vector<uint8_t> ReminderCommon::Convert2U8Vector(const napi_env &env, const napi_value &input_array)
324 {
325     bool isTypedArray = false;
326     bool isArrayBuffer = false;
327     // type is array?
328     napi_is_typedarray(env, input_array, &isTypedArray);
329     if (!isTypedArray) {
330         // buffer whether or not it exists?
331         napi_is_arraybuffer(env, input_array, &isArrayBuffer);
332         if (!isArrayBuffer) {
333             ANSR_LOGE("unknow type");
334             return {};
335         }
336     }
337     size_t length = 0;
338     void *data = nullptr;
339     // get array
340     if (isTypedArray) {
341         napi_typedarray_type type;
342         napi_value input_buffer = nullptr;
343         size_t byte_offset = 0;
344         napi_get_typedarray_info(env, input_array, &type, &length, &data, &input_buffer, &byte_offset);
345         if (type != napi_uint8_array || data == nullptr) {
346             ANSR_LOGW("napi_get_typedarray_info err");
347             return {};
348         }
349     } else {
350         napi_get_arraybuffer_info(env, input_array, &data, &length);
351         if (data == nullptr || length <= 0) {
352             ANSR_LOGW("napi_get_arraybuffer_info err");
353             return {};
354         }
355     }
356     return std::vector<uint8_t>((uint8_t *)data, ((uint8_t *)data) + length);
357 }
358 
ValidateString(const std::string & str)359 bool ReminderCommon::ValidateString(const std::string &str)
360 {
361     if (str.find(ReminderRequest::SEP_BUTTON_VALUE_TYPE) != std::string::npos) {
362         ANSR_LOGW("The string contains SEP_BUTTON_VALUE_TYPE");
363         return false;
364     }
365     if (str.find(ReminderRequest::SEP_BUTTON_VALUE) != std::string::npos) {
366         ANSR_LOGW("The string contains SEP_BUTTON_VALUE");
367         return false;
368     }
369     if (str.find(ReminderRequest::SEP_BUTTON_VALUE_BLOB) != std::string::npos) {
370         ANSR_LOGW("The string contains SEP_BUTTON_VALUE_BLOB");
371         return false;
372     }
373     return true;
374 }
375 
GenWantAgent(const napi_env & env,const napi_value & value,const char * name,std::shared_ptr<ReminderRequest::WantAgentInfo> & wantAgentInfo)376 bool ReminderCommon::GenWantAgent(
377     const napi_env &env, const napi_value &value, const char* name,
378     std::shared_ptr<ReminderRequest::WantAgentInfo>& wantAgentInfo)
379 {
380     char str[NotificationNapi::STR_MAX_SIZE] = {0};
381     napi_value wantAgent = nullptr;
382     if (GetObject(env, value, name, wantAgent)) {
383         wantAgentInfo = std::make_shared<ReminderRequest::WantAgentInfo>();
384         if (GetStringUtf8(env, wantAgent, ReminderAgentNapi::WANT_AGENT_PKG, str, NotificationNapi::STR_MAX_SIZE)) {
385             wantAgentInfo->pkgName = str;
386         }
387         if (GetStringUtf8(env, wantAgent,
388             ReminderAgentNapi::WANT_AGENT_ABILITY, str, NotificationNapi::STR_MAX_SIZE)) {
389             wantAgentInfo->abilityName = str;
390         }
391         if (GetStringUtf8(env, wantAgent,
392             ReminderAgentNapi::WANT_AGENT_URI, str, NotificationNapi::STR_MAX_SIZE)) {
393             wantAgentInfo->uri = str;
394         }
395         napi_value params = nullptr;
396         if (GetObject(env, wantAgent, ReminderAgentNapi::WANT_AGENT_PARAMETERS, params)) {
397             AAFwk::WantParams wantParams;
398             if (AppExecFwk::UnwrapWantParams(env, params, wantParams)) {
399                 wantAgentInfo->parameters = wantParams;
400             }
401         }
402     }
403     return true;
404 }
405 
GenMaxScreenWantAgent(const napi_env & env,const napi_value & value,std::shared_ptr<ReminderRequest> & reminder)406 void ReminderCommon::GenMaxScreenWantAgent(
407     const napi_env &env, const napi_value &value, std::shared_ptr<ReminderRequest>& reminder)
408 {
409     char str[NotificationNapi::STR_MAX_SIZE] = {0};
410     napi_value maxScreenWantAgent = nullptr;
411     if (GetObject(env, value, ReminderAgentNapi::MAX_SCREEN_WANT_AGENT, maxScreenWantAgent)) {
412         auto maxScreenWantAgentInfo = std::make_shared<ReminderRequest::MaxScreenAgentInfo>();
413         if (GetStringUtf8(env, maxScreenWantAgent,
414             ReminderAgentNapi::MAX_SCREEN_WANT_AGENT_PKG, str, NotificationNapi::STR_MAX_SIZE)) {
415             maxScreenWantAgentInfo->pkgName = str;
416         }
417         if (GetStringUtf8(env, maxScreenWantAgent,
418             ReminderAgentNapi::MAX_SCREEN_WANT_AGENT_ABILITY, str, NotificationNapi::STR_MAX_SIZE)) {
419             maxScreenWantAgentInfo->abilityName = str;
420         }
421         reminder->SetMaxScreenWantAgentInfo(maxScreenWantAgentInfo);
422     }
423 }
CreateReminder(const napi_env & env,const napi_value & value,const bool isSysApp,std::shared_ptr<ReminderRequest> & reminder)424 bool ReminderCommon::CreateReminder(
425     const napi_env &env, const napi_value &value, const bool isSysApp, std::shared_ptr<ReminderRequest>& reminder)
426 {
427     napi_value result = nullptr;
428     napi_get_named_property(env, value, ReminderAgentNapi::REMINDER_TYPE, &result);
429     int32_t reminderType = -1;
430     napi_get_value_int32(env, result, &reminderType);
431     switch (ReminderRequest::ReminderType(reminderType)) {
432         case ReminderRequest::ReminderType::TIMER:
433             CreateReminderTimer(env, value, reminder);
434             break;
435         case ReminderRequest::ReminderType::ALARM:
436             CreateReminderAlarm(env, value, reminder);
437             break;
438         case ReminderRequest::ReminderType::CALENDAR:
439             CreateReminderCalendar(env, value, isSysApp, reminder);
440             break;
441         default:
442             ANSR_LOGW("Reminder type is not support. (type:%{public}d)", reminderType);
443             break;
444     }
445     if (reminder == nullptr) {
446         ANSR_LOGW("Instance of reminder error.");
447         return false;
448     }
449     return true;
450 }
451 
GenReminder(const napi_env & env,const napi_value & value,std::shared_ptr<ReminderRequest> & reminder)452 napi_value ReminderCommon::GenReminder(
453     const napi_env &env, const napi_value &value, std::shared_ptr<ReminderRequest>& reminder)
454 {
455     // reminderType
456     bool hasProperty = false;
457     NAPI_CALL(env, napi_has_named_property(env, value, ReminderAgentNapi::REMINDER_TYPE, &hasProperty));
458     if (!hasProperty) {
459         ANSR_LOGW("Property %{public}s expected.", ReminderAgentNapi::REMINDER_TYPE);
460         return nullptr;
461     }
462 
463     // createReminder
464     bool isSysApp = IsSelfSystemApp();
465     if (!CreateReminder(env, value, isSysApp, reminder)) {
466         return nullptr;
467     }
468     reminder->SetSystemApp(isSysApp);
469     GenReminderStringInner(env, value, reminder);
470     if (!GenReminderIntInner(env, value, reminder)) {
471         return nullptr;
472     }
473     GenReminderBoolInner(env, value, reminder);
474 
475     // snoozeSlotType
476     int32_t snoozeSlotType = 0;
477     if (GetInt32(env, value, ReminderAgentNapi::SNOOZE_SLOT_TYPE, snoozeSlotType, false)) {
478         enum NotificationConstant::SlotType actureSnoozeType = NotificationConstant::SlotType::OTHER;
479         if (!NotificationNapi::AnsEnumUtil::SlotTypeJSToC(
480             NotificationNapi::SlotType(snoozeSlotType), actureSnoozeType)) {
481             ANSR_LOGW("snooze slot type not support.");
482             return nullptr;
483         }
484         reminder->SetSnoozeSlotType(actureSnoozeType);
485     }
486 
487     // wantAgent
488     std::shared_ptr<ReminderRequest::WantAgentInfo> wantAgentInfo;
489     if (!GenWantAgent(env, value, ReminderAgentNapi::WANT_AGENT, wantAgentInfo)) {
490         return nullptr;
491     }
492     reminder->SetWantAgentInfo(wantAgentInfo);
493 
494     // maxScreenWantAgent
495     GenMaxScreenWantAgent(env, value, reminder);
496 
497     // actionButtons
498     if (!GenActionButtons(env, value, reminder, isSysApp)) {
499         return nullptr;
500     }
501 
502     return NotificationNapi::Common::NapiGetNull(env);
503 }
504 
GenReminderStringInner(const napi_env & env,const napi_value & value,std::shared_ptr<ReminderRequest> & reminder)505 void ReminderCommon::GenReminderStringInner(
506     const napi_env &env, const napi_value &value, std::shared_ptr<ReminderRequest>& reminder)
507 {
508     char str[NotificationNapi::STR_MAX_SIZE] = {0};
509 
510     // title
511     if (GetStringUtf8(env, value, ReminderAgentNapi::TITLE, str, NotificationNapi::STR_MAX_SIZE)) {
512         reminder->SetTitle(std::string(str));
513     }
514 
515     // content
516     if (GetStringUtf8(env, value, ReminderAgentNapi::CONTENT, str, NotificationNapi::STR_MAX_SIZE)) {
517         reminder->SetContent(std::string(str));
518     }
519 
520     // expiredContent
521     if (GetStringUtf8(env, value, ReminderAgentNapi::EXPIRED_CONTENT, str, NotificationNapi::STR_MAX_SIZE)) {
522         reminder->SetExpiredContent(std::string(str));
523     }
524 
525     // snoozeContent
526     if (GetStringUtf8(env, value, ReminderAgentNapi::SNOOZE_CONTENT, str, NotificationNapi::STR_MAX_SIZE)) {
527         reminder->SetSnoozeContent(std::string(str));
528     }
529 
530     // group id
531     if (GetStringUtf8(env, value, ReminderAgentNapi::GROUP_ID, str, NotificationNapi::STR_MAX_SIZE)) {
532         reminder->SetGroupId(std::string(str));
533     }
534 
535     // custom ring uri
536     if (GetStringUtf8(env, value, ReminderAgentNapi::CUSTOM_RING_URI, str, NotificationNapi::STR_MAX_SIZE)) {
537         reminder->SetCustomRingUri(std::string(str));
538     }
539 }
540 
GenReminderIntInner(const napi_env & env,const napi_value & value,std::shared_ptr<ReminderRequest> & reminder)541 bool ReminderCommon::GenReminderIntInner(
542     const napi_env &env, const napi_value &value, std::shared_ptr<ReminderRequest>& reminder)
543 {
544     // ringDuration
545     int64_t propVal = 0;
546     if (GetInt64(env, value, ReminderAgentNapi::RING_DURATION, propVal)) {
547         if (propVal < 0 || propVal > static_cast<int64_t>(
548             ReminderRequest::MAX_RING_DURATION / ReminderRequest::MILLI_SECONDS)) {
549             ANSR_LOGE("ring duration value is error!");
550             return false;
551         }
552         uint64_t ringDuration = static_cast<uint64_t>(propVal);
553         reminder->SetRingDuration(ringDuration);
554     }
555 
556     // timeInterval
557     if (GetInt64(env, value, ReminderAgentNapi::TIME_INTERVAL, propVal)) {
558         if (propVal < 0) {
559             reminder->SetTimeInterval(0);
560         } else {
561             uint64_t timeInterval = static_cast<uint64_t>(propVal);
562             reminder->SetTimeInterval(timeInterval);
563         }
564     }
565 
566     // notificationId
567     int32_t propertyVal = 0;
568     if (GetInt32(env, value, ReminderAgentNapi::NOTIFICATION_ID, propertyVal, false)) {
569         reminder->SetNotificationId(propertyVal);
570     }
571 
572     // snoozeTimes
573     if (GetInt32(env, value, ReminderAgentNapi::SNOOZE_TIMES, propertyVal, false)) {
574         if (propertyVal < 0) {
575             reminder->SetSnoozeTimes(0);
576         } else {
577             uint8_t snoozeTimes = propertyVal > UINT8_MAX ? UINT8_MAX : static_cast<uint8_t>(propertyVal);
578             reminder->SetSnoozeTimes(static_cast<uint8_t>(snoozeTimes));
579         }
580     }
581 
582     // slotType
583     int32_t slotType = 0;
584     if (GetInt32(env, value, ReminderAgentNapi::SLOT_TYPE, slotType, false)) {
585         enum NotificationConstant::SlotType actureType = NotificationConstant::SlotType::OTHER;
586         if (!NotificationNapi::AnsEnumUtil::SlotTypeJSToC(NotificationNapi::SlotType(slotType), actureType)) {
587             ANSR_LOGW("slot type not support.");
588             return false;
589         }
590         reminder->SetSlotType(actureType);
591     }
592 
593     //autoDeletedTime
594     int64_t autoDeletedTime = 0;
595     if (GetInt64(env, value, ReminderAgentNapi::AUTODELETEDTIME, autoDeletedTime)) {
596         if (autoDeletedTime > 0) {
597             reminder->SetAutoDeletedTime(autoDeletedTime);
598         }
599     }
600     return true;
601 }
602 
GenReminderBoolInner(const napi_env & env,const napi_value & value,std::shared_ptr<ReminderRequest> & reminder)603 void ReminderCommon::GenReminderBoolInner(
604     const napi_env &env, const napi_value &value, std::shared_ptr<ReminderRequest>& reminder)
605 {
606     // tapDismissed
607     bool tapDismissed = false;
608     if (GetBool(env, value, ReminderAgentNapi::TAPDISMISSED, tapDismissed)) {
609         reminder->SetTapDismissed(tapDismissed);
610     }
611 }
612 
GetStringUtf8(const napi_env & env,const napi_value & value,const char * propertyName,char * propertyVal,const int32_t size)613 bool ReminderCommon::GetStringUtf8(const napi_env &env, const napi_value &value,
614     const char* propertyName, char* propertyVal, const int32_t size)
615 {
616     bool hasProperty = false;
617     napi_value result = nullptr;
618     napi_valuetype valuetype = napi_undefined;
619     size_t strLen = 0;
620 
621     NAPI_CALL_BASE(env, napi_has_named_property(env, value, propertyName, &hasProperty), false);
622     if (hasProperty) {
623         napi_get_named_property(env, value, propertyName, &result);
624         NAPI_CALL_BASE(env, napi_typeof(env, result, &valuetype), false);
625         if (valuetype != napi_string) {
626             ANSR_LOGW("Wrong argument type:%{public}s. string expected.", propertyName);
627             return false;
628         }
629         NAPI_CALL_BASE(env, napi_get_value_string_utf8(env, result, propertyVal, size - 1, &strLen), false);
630     }
631     return hasProperty;
632 }
633 
GetBool(const napi_env & env,const napi_value & value,const char * propertyName,bool & propertyVal)634 bool ReminderCommon::GetBool(const napi_env &env, const napi_value &value,
635     const char* propertyName, bool& propertyVal)
636 {
637     bool hasProperty = false;
638     napi_value result = nullptr;
639     napi_valuetype valuetype = napi_undefined;
640     NAPI_CALL_BASE(env, napi_has_named_property(env, value, propertyName, &hasProperty), false);
641     if (!hasProperty) {
642         ANSR_LOGW("Does not have argument type:%{public}s.", propertyName);
643         return false;
644     }
645     napi_get_named_property(env, value, propertyName, &result);
646     NAPI_CALL_BASE(env, napi_typeof(env, result, &valuetype), false);
647     if (valuetype != napi_boolean) {
648         ANSR_LOGW("Wrong argument type:%{public}s. boolean expected.", propertyName);
649         return false;
650     }
651     napi_get_value_bool(env, result, &propertyVal);
652     return true;
653 }
654 
GetInt32(const napi_env & env,const napi_value & value,const char * propertyName,int32_t & propertyVal,bool isNecessary)655 bool ReminderCommon::GetInt32(const napi_env &env, const napi_value &value,
656     const char* propertyName, int32_t& propertyVal, bool isNecessary)
657 {
658     napi_value result = nullptr;
659     if (!GetPropertyValIfExist(env, value, propertyName, result)) {
660         if (isNecessary) {
661             ANSR_LOGW("Correct property %{public}s expected.", propertyName);
662         }
663         return false;
664     }
665     napi_get_value_int32(env, result, &propertyVal);
666     return true;
667 }
668 
GetInt64(const napi_env & env,const napi_value & value,const char * propertyName,int64_t & propertyVal)669 bool ReminderCommon::GetInt64(const napi_env &env, const napi_value &value,
670     const char* propertyName, int64_t& propertyVal)
671 {
672     napi_value result = nullptr;
673     if (!GetPropertyValIfExist(env, value, propertyName, result)) {
674         return false;
675     }
676     napi_get_value_int64(env, result, &propertyVal);
677     return true;
678 }
679 
GetPropertyValIfExist(const napi_env & env,const napi_value & value,const char * propertyName,napi_value & propertyVal)680 bool ReminderCommon::GetPropertyValIfExist(const napi_env &env, const napi_value &value,
681     const char* propertyName, napi_value& propertyVal)
682 {
683     napi_valuetype valuetype = napi_undefined;
684     if (propertyName == nullptr) {
685         propertyVal = value;
686     } else {
687         bool hasProperty = false;
688         napi_status status = napi_has_named_property(env, value, propertyName, &hasProperty);
689         if (status != napi_ok || !hasProperty) {
690             return false;
691         }
692         napi_get_named_property(env, value, propertyName, &propertyVal);
693     }
694     napi_status status = napi_typeof(env, propertyVal, &valuetype);
695     if (status != napi_ok || valuetype != napi_number) {
696         if (propertyName == nullptr) {
697             ANSR_LOGW("Wrong argument type. number expected.");
698         } else {
699             ANSR_LOGW("Wrong argument type:%{public}s, number expected.", propertyName);
700         }
701         return false;
702     }
703     return true;
704 }
705 
GetObject(const napi_env & env,const napi_value & value,const char * propertyName,napi_value & propertyVal)706 bool ReminderCommon::GetObject(const napi_env &env, const napi_value &value,
707     const char* propertyName, napi_value& propertyVal)
708 {
709     bool hasProperty = false;
710     napi_valuetype valuetype = napi_undefined;
711 
712     NAPI_CALL_BASE(env, napi_has_named_property(env, value, propertyName, &hasProperty), false);
713     if (!hasProperty) {
714         return false;
715     }
716     napi_get_named_property(env, value, propertyName, &propertyVal);
717     NAPI_CALL_BASE(env, napi_typeof(env, propertyVal, &valuetype), false);
718     if (valuetype != napi_object) {
719         ANSR_LOGW("Wrong argument type:%{public}s. object expected.", propertyName);
720         return false;
721     }
722     return true;
723 }
724 
GetDate(const napi_env & env,const napi_value & value,const char * propertyName,double & date)725 bool ReminderCommon::GetDate(const napi_env& env, const napi_value& value,
726     const char* propertyName, double& date)
727 {
728     napi_value propertyValue = nullptr;
729     if (propertyName == nullptr) {
730         propertyValue = value;
731     } else {
732         bool hasProperty = false;
733         NAPI_CALL_BASE(env, napi_has_named_property(env, value, propertyName, &hasProperty), false);
734         if (!hasProperty) {
735             ANSR_LOGE("");
736             return false;
737         }
738         napi_get_named_property(env, value, propertyName, &propertyValue);
739     }
740     bool isDate = false;
741     napi_is_date(env, propertyValue, &isDate);
742     if (!isDate) {
743         ANSR_LOGE("Wrong argument type. Date expected.");
744         return false;
745     }
746     napi_get_date_value(env, propertyValue, &date);
747     return true;
748 }
749 
CreateReminderTimer(const napi_env & env,const napi_value & value,std::shared_ptr<ReminderRequest> & reminder)750 napi_value ReminderCommon::CreateReminderTimer(
751     const napi_env &env, const napi_value &value, std::shared_ptr<ReminderRequest>& reminder)
752 {
753     int64_t propertyCountDownTime = 0;
754     if (!GetInt64(env, value, ReminderAgentNapi::TIMER_COUNT_DOWN_TIME, propertyCountDownTime)) {
755         ANSR_LOGW("Correct property %{public}s expected.", ReminderAgentNapi::TIMER_COUNT_DOWN_TIME);
756         return nullptr;
757     }
758 
759     auto countDownTimeInSeconds = static_cast<uint64_t>(propertyCountDownTime);
760     if (propertyCountDownTime <= 0 || countDownTimeInSeconds >= (UINT64_MAX / ReminderRequest::MILLI_SECONDS)) {
761         ANSR_LOGW("Create countDown reminder fail: designated %{public}s is illegal.",
762             ReminderAgentNapi::TIMER_COUNT_DOWN_TIME);
763         return nullptr;
764     }
765 
766     reminder = std::make_shared<ReminderRequestTimer>(countDownTimeInSeconds);
767     return NotificationNapi::Common::NapiGetNull(env);
768 }
769 
CreateReminderAlarm(const napi_env & env,const napi_value & value,std::shared_ptr<ReminderRequest> & reminder)770 napi_value ReminderCommon::CreateReminderAlarm(
771     const napi_env &env, const napi_value &value, std::shared_ptr<ReminderRequest>& reminder)
772 {
773     // hour
774     int32_t propertyHourVal = 0;
775     const int32_t maxHour = 23;
776     if (!GetInt32(env, value, ReminderAgentNapi::ALARM_HOUR, propertyHourVal, true)) {
777         return nullptr;
778     }
779 
780     // minute
781     int32_t propertyMinuteVal = 0;
782     const int32_t maxMinute = 59;
783     if (!GetInt32(env, value, ReminderAgentNapi::ALARM_MINUTE, propertyMinuteVal, true)) {
784         return nullptr;
785     }
786 
787     if ((propertyHourVal < 0) || (propertyHourVal > maxHour)) {
788         ANSR_LOGW("Create alarm reminder fail: designated %{public}s must between [0, 23].",
789             ReminderAgentNapi::ALARM_HOUR);
790         return nullptr;
791     }
792 
793     if ((propertyMinuteVal < 0) || (propertyMinuteVal > maxMinute)) {
794         ANSR_LOGW("Create alarm reminder fail: designated %{public}s must between [0, 59].",
795             ReminderAgentNapi::ALARM_MINUTE);
796         return nullptr;
797     }
798 
799     // daysOfWeek
800     std::vector<uint8_t> daysOfWeek;
801     uint8_t maxDaysOfWeek = 7;
802     if (ParseInt32Array(env, value, ReminderAgentNapi::REPEAT_DAYS_OF_WEEK, daysOfWeek, maxDaysOfWeek) == nullptr) {
803         return nullptr;
804     }
805     reminder = std::make_shared<ReminderRequestAlarm>(
806         static_cast<uint8_t>(propertyHourVal), static_cast<uint8_t>(propertyMinuteVal), daysOfWeek);
807     return NotificationNapi::Common::NapiGetNull(env);
808 }
809 
CreateReminderCalendar(const napi_env & env,const napi_value & value,const bool isSysApp,std::shared_ptr<ReminderRequest> & reminder)810 napi_value ReminderCommon::CreateReminderCalendar(
811     const napi_env &env, const napi_value &value, const bool isSysApp, std::shared_ptr<ReminderRequest>& reminder)
812 {
813     struct tm dateTime;
814     napi_value dateTimeObj = nullptr;
815     if (!GetObject(env, value, ReminderAgentNapi::CALENDAR_DATE_TIME, dateTimeObj)) {
816         ANSR_LOGW("Create calendar reminder fail: dateTime must be setted.");
817         return nullptr;
818     }
819 
820     if (!ParseLocalDateTime(env, dateTimeObj, dateTime)) {
821         ANSR_LOGW("Parce DateTime failed.");
822         return nullptr;
823     }
824 
825     std::vector<uint8_t> repeatMonths;
826     std::vector<uint8_t> repeatDays;
827     std::vector<uint8_t> daysOfWeek;
828 
829     if (!ParseCalendarParams(env, value, repeatMonths, repeatDays, daysOfWeek)) {
830         return nullptr;
831     }
832 
833     // rruleWantAgent
834     std::shared_ptr<ReminderRequest::WantAgentInfo> wantAgentInfo;
835     if (!GenWantAgent(env, value, ReminderAgentNapi::RRULL_WANT_AGENT, wantAgentInfo)) {
836         return nullptr;
837     }
838     if (!isSysApp && wantAgentInfo != nullptr) {
839         ANS_LOGE("Not system app rrule want info not supported");
840         return nullptr;
841     }
842 
843     auto reminderCalendar = std::make_shared<ReminderRequestCalendar>(dateTime, repeatMonths, repeatDays, daysOfWeek);
844     napi_value endDateTimeObj = nullptr;
845     if (GetObject(env, value, ReminderAgentNapi::CALENDAR_END_DATE_TIME, endDateTimeObj)) {
846         struct tm endDateTime;
847         if (!ParseLocalDateTime(env, endDateTimeObj, endDateTime)) {
848             return nullptr;
849         }
850         time_t endTime = mktime(&endDateTime);
851         if (endTime == -1) {
852             return nullptr;
853         }
854         if (!reminderCalendar->SetEndDateTime(ReminderRequest::GetDurationSinceEpochInMilli(endTime))) {
855             ANSR_LOGW("The end time must be greater than start time");
856             return nullptr;
857         }
858     }
859 
860     if (!(reminderCalendar->InitTriggerTime())) {
861         return nullptr;
862     }
863     reminderCalendar->SetRRuleWantAgentInfo(wantAgentInfo);
864     reminder = reminderCalendar;
865     return NotificationNapi::Common::NapiGetNull(env);
866 }
867 
CheckCalendarParams(const int32_t & year,const int32_t & month,const int32_t & day,const int32_t & hour,const int32_t & min)868 bool ReminderCommon::CheckCalendarParams(const int32_t &year, const int32_t &month, const int32_t &day,
869     const int32_t &hour, const int32_t &min)
870 {
871     if ((year < 0) || (year > UINT16_MAX)) {
872         ANSR_LOGW("Create calendar reminder fail: designated %{public}s must between [0, %{public}d]",
873             ReminderAgentNapi::CALENDAR_YEAR, UINT16_MAX);
874         return false;
875     }
876     if ((month < 1) || (month > ReminderRequestCalendar::MAX_MONTHS_OF_YEAR)) {
877         ANSR_LOGW("Create calendar reminder fail: designated %{public}s must between [1, %{public}hhu]",
878             ReminderAgentNapi::CALENDAR_MONTH, ReminderRequestCalendar::MAX_MONTHS_OF_YEAR);
879         return false;
880     }
881     uint8_t maxDaysOfMonth = ReminderRequestCalendar::GetDaysOfMonth(static_cast<uint16_t>(year), month);
882     if ((day < 1) || (day > maxDaysOfMonth)) {
883         ANSR_LOGW("Create calendar reminder fail: designated %{public}s must between [1, %{public}hhu]",
884             ReminderAgentNapi::CALENDAR_DAY, maxDaysOfMonth);
885         return false;
886     }
887     uint8_t maxHour = 23;
888     if (hour < 0 || hour > maxHour) {
889         ANSR_LOGW("Create calendar reminder fail: designated %{public}s must between [0, %{public}hhu]",
890             ReminderAgentNapi::CALENDAR_HOUR, maxHour);
891         return false;
892     }
893     uint8_t maxMinute = 59;
894     if (min < 0 || min > maxMinute) {
895         ANSR_LOGW("Create calendar reminder fail: designated %{public}s must between [0, %{public}hhu]",
896             ReminderAgentNapi::CALENDAR_MINUTE, maxMinute);
897         return false;
898     }
899     return true;
900 }
901 
ParseCalendarParams(const napi_env & env,const napi_value & value,std::vector<uint8_t> & repeatMonths,std::vector<uint8_t> & repeatDays,std::vector<uint8_t> & daysOfWeek)902 bool ReminderCommon::ParseCalendarParams(const napi_env& env, const napi_value& value,
903     std::vector<uint8_t>& repeatMonths, std::vector<uint8_t>& repeatDays, std::vector<uint8_t>& daysOfWeek)
904 {
905     // repeatMonth
906     if (ParseInt32Array(env, value, ReminderAgentNapi::CALENDAR_REPEAT_MONTHS, repeatMonths,
907         ReminderRequestCalendar::MAX_MONTHS_OF_YEAR) == nullptr) {
908         return false;
909     }
910 
911     // repeatDay
912     if (ParseInt32Array(env, value, ReminderAgentNapi::CALENDAR_REPEAT_DAYS, repeatDays,
913         ReminderRequestCalendar::MAX_DAYS_OF_MONTH) == nullptr) {
914         return false;
915     }
916 
917     // daysOfWeek
918     uint8_t maxDaysOfWeek = 7;
919     if (ParseInt32Array(env, value, ReminderAgentNapi::REPEAT_DAYS_OF_WEEK, daysOfWeek, maxDaysOfWeek) == nullptr) {
920         return false;
921     }
922 
923     return true;
924 }
925 
ParseLocalDateTime(const napi_env & env,const napi_value & dateTimeObj,struct tm & dateTime)926 bool ReminderCommon::ParseLocalDateTime(const napi_env& env, const napi_value& dateTimeObj, struct tm& dateTime)
927 {
928     int32_t propertyYearVal = 0;
929     int32_t propertyMonthVal = 0;
930     int32_t propertyDayVal = 0;
931     int32_t propertyHourVal = 0;
932     int32_t propertyMinteVal = 0;
933     if (!GetInt32(env, dateTimeObj, ReminderAgentNapi::CALENDAR_YEAR, propertyYearVal, true) ||
934         !GetInt32(env, dateTimeObj, ReminderAgentNapi::CALENDAR_MONTH, propertyMonthVal, true) ||
935         !GetInt32(env, dateTimeObj, ReminderAgentNapi::CALENDAR_DAY, propertyDayVal, true) ||
936         !GetInt32(env, dateTimeObj, ReminderAgentNapi::CALENDAR_HOUR, propertyHourVal, true) ||
937         !GetInt32(env, dateTimeObj, ReminderAgentNapi::CALENDAR_MINUTE, propertyMinteVal, true)) {
938         return false;
939     }
940 
941     if (!CheckCalendarParams(propertyYearVal, propertyMonthVal, propertyDayVal,
942         propertyHourVal, propertyMinteVal)) {
943         return false;
944     }
945 
946     dateTime.tm_year = ReminderRequest::GetCTime(ReminderRequest::TimeTransferType::YEAR, propertyYearVal);
947     dateTime.tm_mon = ReminderRequest::GetCTime(ReminderRequest::TimeTransferType::MONTH, propertyMonthVal);
948     dateTime.tm_mday = propertyDayVal;
949     dateTime.tm_hour = propertyHourVal;
950     dateTime.tm_min = propertyMinteVal;
951     dateTime.tm_sec = 0;
952     dateTime.tm_isdst = -1;
953     return true;
954 }
955 
ParseInt32Array(const napi_env & env,const napi_value & value,const char * propertyName,std::vector<uint8_t> & propertyVal,uint8_t maxLen)956 napi_value ReminderCommon::ParseInt32Array(const napi_env &env, const napi_value &value,
957     const char* propertyName, std::vector<uint8_t> &propertyVal, uint8_t maxLen)
958 {
959     napi_value result = nullptr;
960     if (!GetObject(env, value, propertyName, result)) {
961         return NotificationNapi::Common::NapiGetNull(env);
962     }
963     if (result != nullptr) {
964         bool isArray = false;
965         napi_is_array(env, result, &isArray);
966         if (!isArray) {
967             ANSR_LOGW("Property %{public}s is expected to be an array.", propertyName);
968             return nullptr;
969         }
970         uint32_t length = 0;
971         napi_get_array_length(env, result, &length);
972         if (length > maxLen) {
973             ANSR_LOGW("The max length of array of %{public}s is %{public}hhu.", propertyName, maxLen);
974             return nullptr;
975         }
976         napi_valuetype valuetype = napi_undefined;
977         for (size_t i = 0; i < length; i++) {
978             int32_t propertyDayVal = 10;
979             napi_value repeatDayVal = nullptr;
980             napi_get_element(env, result, i, &repeatDayVal);
981             NAPI_CALL(env, napi_typeof(env, repeatDayVal, &valuetype));
982             if (valuetype != napi_number) {
983                 ANSR_LOGW("%{public}s's element is expected to be number.", propertyName);
984                 return nullptr;
985             }
986             napi_get_value_int32(env, repeatDayVal, &propertyDayVal);
987             if (propertyDayVal < 1 || propertyDayVal > static_cast<int32_t>(maxLen)) {
988                 ANSR_LOGW("%{public}s's element must between [1, %{public}d].", propertyName, maxLen);
989                 return nullptr;
990             }
991             propertyVal.push_back(static_cast<uint8_t>(propertyDayVal));
992         }
993     }
994     return NotificationNapi::Common::NapiGetNull(env);
995 }
996 
PaddingCallbackPromiseInfo(const napi_env & env,const napi_ref & callback,CallbackPromiseInfo & info,napi_value & promise)997 void ReminderCommon::PaddingCallbackPromiseInfo(
998     const napi_env &env, const napi_ref &callback, CallbackPromiseInfo &info, napi_value &promise)
999 {
1000     if (callback) {
1001         info.callback = callback;
1002         info.isCallback = true;
1003     } else {
1004         napi_deferred deferred = nullptr;
1005         NAPI_CALL_RETURN_VOID(env, napi_create_promise(env, &deferred, &promise));
1006         info.deferred = deferred;
1007         info.isCallback = false;
1008     }
1009 }
1010 
HandleErrCode(const napi_env & env,int32_t errCode)1011 void ReminderCommon::HandleErrCode(const napi_env &env, int32_t errCode)
1012 {
1013     if (errCode == ERR_OK) {
1014         return;
1015     }
1016     std::string errCodeMsg = reminderErrCodeMsgMap[errCode];
1017     napi_throw_error(env, std::to_string(errCode).c_str(), errCodeMsg.c_str());
1018 }
1019 
FindErrMsg(const napi_env & env,const int32_t errCode)1020 std::string ReminderCommon::FindErrMsg(const napi_env &env, const int32_t errCode)
1021 {
1022     auto findMsg = reminderErrCodeMsgMap.find(errCode);
1023     if (findMsg == reminderErrCodeMsgMap.end()) {
1024         ANSR_LOGI("Inner error.");
1025         return "Inner error.";
1026     }
1027     return reminderErrCodeMsgMap[errCode];
1028 }
1029 
ReturnCallbackPromise(const napi_env & env,const CallbackPromiseInfo & info,const napi_value & result,bool isThrow)1030 void ReminderCommon::ReturnCallbackPromise(const napi_env &env, const CallbackPromiseInfo &info,
1031     const napi_value &result, bool isThrow)
1032 {
1033     ANSR_LOGI("enter errorCode=%{public}d", info.errorCode);
1034     if (info.isCallback) {
1035         if (isThrow) {
1036             SetCallback(env, info.callback, info.errorCode, result);
1037         } else {
1038             NotificationNapi::Common::SetCallback(env, info.callback, info.errorCode, result, false);
1039         }
1040     } else {
1041         SetPromise(env, info, result);
1042     }
1043     ANSR_LOGI("end");
1044 }
1045 
SetCallback(const napi_env & env,const napi_ref & callbackIn,const int32_t & errCode,const napi_value & result)1046 void ReminderCommon::SetCallback(
1047     const napi_env &env, const napi_ref &callbackIn, const int32_t &errCode, const napi_value &result)
1048 {
1049     napi_value undefined = nullptr;
1050     napi_get_undefined(env, &undefined);
1051 
1052     napi_value callback = nullptr;
1053     napi_value resultout = nullptr;
1054     napi_get_reference_value(env, callbackIn, &callback);
1055     napi_value results[ASYNC_CALLBACK_PARAM_NUM] = {nullptr};
1056     if (errCode == ERR_OK) {
1057         results[0] = NotificationNapi::Common::NapiGetNull(env);
1058     } else {
1059         std::string errMsg = FindErrMsg(env, errCode);
1060         results[0] = GetCallbackErrorValue(env, errCode, errMsg);
1061     }
1062     results[1] = result;
1063     NAPI_CALL_RETURN_VOID(env,
1064         napi_call_function(env, undefined, callback, ASYNC_CALLBACK_PARAM_NUM, &results[0], &resultout));
1065 }
1066 
GetCallbackErrorValue(napi_env env,const int32_t errCode,const std::string errMsg)1067 napi_value ReminderCommon::GetCallbackErrorValue(napi_env env, const int32_t errCode, const std::string errMsg)
1068 {
1069     if (errCode == ERR_OK) {
1070         return NotificationNapi::Common::NapiGetNull(env);
1071     }
1072     napi_value error = nullptr;
1073     napi_value eCode = nullptr;
1074     napi_value eMsg = nullptr;
1075     NAPI_CALL(env, napi_create_int32(env, errCode, &eCode));
1076     NAPI_CALL(env, napi_create_string_utf8(env, errMsg.c_str(),
1077         errMsg.length(), &eMsg));
1078     NAPI_CALL(env, napi_create_object(env, &error));
1079     NAPI_CALL(env, napi_set_named_property(env, error, "code", eCode));
1080     NAPI_CALL(env, napi_set_named_property(env, error, "message", eMsg));
1081     return error;
1082 }
1083 
SetPromise(const napi_env & env,const CallbackPromiseInfo & info,const napi_value & result)1084 napi_value  ReminderCommon::SetPromise(
1085     const napi_env &env, const CallbackPromiseInfo &info, const napi_value &result)
1086 {
1087     if (info.errorCode == ERR_OK) {
1088         napi_resolve_deferred(env, info.deferred, result);
1089     } else {
1090         std::string errMsg = FindErrMsg(env, info.errorCode);
1091         if (errMsg == "") {
1092             return nullptr;
1093         }
1094         napi_value error = nullptr;
1095         napi_value eCode = nullptr;
1096         napi_value eMsg = nullptr;
1097         NAPI_CALL(env, napi_create_int32(env, info.errorCode, &eCode));
1098         NAPI_CALL(env, napi_create_string_utf8(env, errMsg.c_str(),
1099             errMsg.length(), &eMsg));
1100         NAPI_CALL(env, napi_create_object(env, &error));
1101         NAPI_CALL(env, napi_set_named_property(env, error, "data", eCode));
1102         NAPI_CALL(env, napi_set_named_property(env, error, "code", eCode));
1103         NAPI_CALL(env, napi_set_named_property(env, error, "message", eMsg));
1104         napi_reject_deferred(env, info.deferred, error);
1105     }
1106     return result;
1107 }
1108 
JSParaError(const napi_env & env,const napi_ref & callback)1109 napi_value ReminderCommon::JSParaError(const napi_env &env, const napi_ref &callback)
1110 {
1111     if (callback) {
1112         SetCallback(env, callback, ERR_REMINDER_INVALID_PARAM, nullptr);
1113         return NotificationNapi::Common::NapiGetNull(env);
1114     } else {
1115         napi_value promise = nullptr;
1116         napi_deferred deferred = nullptr;
1117         napi_create_promise(env, &deferred, &promise);
1118 
1119         napi_value res = nullptr;
1120         napi_value eCode = nullptr;
1121         napi_value eMsg = nullptr;
1122         std::string errMsg = FindErrMsg(env, ERR_REMINDER_INVALID_PARAM);
1123         NAPI_CALL(env, napi_create_int32(env, ERR_REMINDER_INVALID_PARAM, &eCode));
1124         NAPI_CALL(env, napi_create_string_utf8(env, errMsg.c_str(),
1125             errMsg.length(), &eMsg));
1126         NAPI_CALL(env, napi_create_object(env, &res));
1127         NAPI_CALL(env, napi_set_named_property(env, res, "data", eCode));
1128         NAPI_CALL(env, napi_set_named_property(env, res, "code", eCode));
1129         NAPI_CALL(env, napi_set_named_property(env, res, "message", eMsg));
1130         napi_reject_deferred(env, deferred, res);
1131         return promise;
1132     }
1133 }
1134 }
1135 }
1136