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 ¶m,
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 } else if (!reminder->IsSystemApp()) {
592 reminder->SetSlotType(NotificationConstant::SlotType::OTHER);
593 }
594
595 //autoDeletedTime
596 int64_t autoDeletedTime = 0;
597 if (GetInt64(env, value, ReminderAgentNapi::AUTODELETEDTIME, autoDeletedTime)) {
598 if (autoDeletedTime > 0) {
599 reminder->SetAutoDeletedTime(autoDeletedTime);
600 }
601 }
602 return GenReminderIntInnerOther(env, value, reminder);
603 }
604
GenReminderIntInnerOther(const napi_env & env,const napi_value & value,std::shared_ptr<ReminderRequest> & reminder)605 bool ReminderCommon::GenReminderIntInnerOther(
606 const napi_env &env, const napi_value &value, std::shared_ptr<ReminderRequest>& reminder)
607 {
608 int32_t resourceId = 0;
609 // title
610 if (GetInt32(env, value, ReminderAgentNapi::TITLE_RESOURCE_ID, resourceId, false)) {
611 reminder->SetTitleResourceId(resourceId);
612 }
613
614 // content
615 if (GetInt32(env, value, ReminderAgentNapi::CONTENT_RESOURCE_ID, resourceId, false)) {
616 reminder->SetContentResourceId(resourceId);
617 }
618
619 // expiredContent
620 if (GetInt32(env, value, ReminderAgentNapi::EXPIRED_CONTENT_RESOURCE_ID, resourceId, false)) {
621 reminder->SetExpiredContentResourceId(resourceId);
622 }
623
624 // snoozeContent
625 if (GetInt32(env, value, ReminderAgentNapi::SNOOZE_CONTENT_RESOURCE_ID, resourceId, false)) {
626 reminder->SetSnoozeContentResourceId(resourceId);
627 }
628 return true;
629 }
630
GenReminderBoolInner(const napi_env & env,const napi_value & value,std::shared_ptr<ReminderRequest> & reminder)631 void ReminderCommon::GenReminderBoolInner(
632 const napi_env &env, const napi_value &value, std::shared_ptr<ReminderRequest>& reminder)
633 {
634 // tapDismissed
635 bool tapDismissed = false;
636 if (GetBool(env, value, ReminderAgentNapi::TAPDISMISSED, tapDismissed)) {
637 reminder->SetTapDismissed(tapDismissed);
638 }
639 }
640
GetStringUtf8(const napi_env & env,const napi_value & value,const char * propertyName,char * propertyVal,const int32_t size)641 bool ReminderCommon::GetStringUtf8(const napi_env &env, const napi_value &value,
642 const char* propertyName, char* propertyVal, const int32_t size)
643 {
644 bool hasProperty = false;
645 napi_value result = nullptr;
646 napi_valuetype valuetype = napi_undefined;
647 size_t strLen = 0;
648
649 NAPI_CALL_BASE(env, napi_has_named_property(env, value, propertyName, &hasProperty), false);
650 if (hasProperty) {
651 napi_get_named_property(env, value, propertyName, &result);
652 NAPI_CALL_BASE(env, napi_typeof(env, result, &valuetype), false);
653 if (valuetype != napi_string) {
654 ANSR_LOGW("Wrong argument type:%{public}s. string expected.", propertyName);
655 return false;
656 }
657 NAPI_CALL_BASE(env, napi_get_value_string_utf8(env, result, propertyVal, size - 1, &strLen), false);
658 }
659 return hasProperty;
660 }
661
GetBool(const napi_env & env,const napi_value & value,const char * propertyName,bool & propertyVal)662 bool ReminderCommon::GetBool(const napi_env &env, const napi_value &value,
663 const char* propertyName, bool& propertyVal)
664 {
665 bool hasProperty = false;
666 napi_value result = nullptr;
667 napi_valuetype valuetype = napi_undefined;
668 NAPI_CALL_BASE(env, napi_has_named_property(env, value, propertyName, &hasProperty), false);
669 if (!hasProperty) {
670 ANSR_LOGW("Does not have argument type:%{public}s.", propertyName);
671 return false;
672 }
673 napi_get_named_property(env, value, propertyName, &result);
674 NAPI_CALL_BASE(env, napi_typeof(env, result, &valuetype), false);
675 if (valuetype != napi_boolean) {
676 ANSR_LOGW("Wrong argument type:%{public}s. boolean expected.", propertyName);
677 return false;
678 }
679 napi_get_value_bool(env, result, &propertyVal);
680 return true;
681 }
682
GetInt32(const napi_env & env,const napi_value & value,const char * propertyName,int32_t & propertyVal,bool isNecessary)683 bool ReminderCommon::GetInt32(const napi_env &env, const napi_value &value,
684 const char* propertyName, int32_t& propertyVal, bool isNecessary)
685 {
686 napi_value result = nullptr;
687 if (!GetPropertyValIfExist(env, value, propertyName, result)) {
688 if (isNecessary) {
689 ANSR_LOGW("Correct property %{public}s expected.", propertyName);
690 }
691 return false;
692 }
693 napi_get_value_int32(env, result, &propertyVal);
694 return true;
695 }
696
GetInt64(const napi_env & env,const napi_value & value,const char * propertyName,int64_t & propertyVal)697 bool ReminderCommon::GetInt64(const napi_env &env, const napi_value &value,
698 const char* propertyName, int64_t& propertyVal)
699 {
700 napi_value result = nullptr;
701 if (!GetPropertyValIfExist(env, value, propertyName, result)) {
702 return false;
703 }
704 napi_get_value_int64(env, result, &propertyVal);
705 return true;
706 }
707
GetPropertyValIfExist(const napi_env & env,const napi_value & value,const char * propertyName,napi_value & propertyVal)708 bool ReminderCommon::GetPropertyValIfExist(const napi_env &env, const napi_value &value,
709 const char* propertyName, napi_value& propertyVal)
710 {
711 napi_valuetype valuetype = napi_undefined;
712 if (propertyName == nullptr) {
713 propertyVal = value;
714 } else {
715 bool hasProperty = false;
716 napi_status status = napi_has_named_property(env, value, propertyName, &hasProperty);
717 if (status != napi_ok || !hasProperty) {
718 return false;
719 }
720 napi_get_named_property(env, value, propertyName, &propertyVal);
721 }
722 napi_status status = napi_typeof(env, propertyVal, &valuetype);
723 if (status != napi_ok || valuetype != napi_number) {
724 if (propertyName == nullptr) {
725 ANSR_LOGW("Wrong argument type. number expected.");
726 } else {
727 ANSR_LOGW("Wrong argument type:%{public}s, number expected.", propertyName);
728 }
729 return false;
730 }
731 return true;
732 }
733
GetObject(const napi_env & env,const napi_value & value,const char * propertyName,napi_value & propertyVal)734 bool ReminderCommon::GetObject(const napi_env &env, const napi_value &value,
735 const char* propertyName, napi_value& propertyVal)
736 {
737 bool hasProperty = false;
738 napi_valuetype valuetype = napi_undefined;
739
740 NAPI_CALL_BASE(env, napi_has_named_property(env, value, propertyName, &hasProperty), false);
741 if (!hasProperty) {
742 return false;
743 }
744 napi_get_named_property(env, value, propertyName, &propertyVal);
745 NAPI_CALL_BASE(env, napi_typeof(env, propertyVal, &valuetype), false);
746 if (valuetype != napi_object) {
747 ANSR_LOGW("Wrong argument type:%{public}s. object expected.", propertyName);
748 return false;
749 }
750 return true;
751 }
752
GetDate(const napi_env & env,const napi_value & value,const char * propertyName,double & date)753 bool ReminderCommon::GetDate(const napi_env& env, const napi_value& value,
754 const char* propertyName, double& date)
755 {
756 napi_value propertyValue = nullptr;
757 if (propertyName == nullptr) {
758 propertyValue = value;
759 } else {
760 bool hasProperty = false;
761 NAPI_CALL_BASE(env, napi_has_named_property(env, value, propertyName, &hasProperty), false);
762 if (!hasProperty) {
763 ANSR_LOGE("");
764 return false;
765 }
766 napi_get_named_property(env, value, propertyName, &propertyValue);
767 }
768 bool isDate = false;
769 napi_is_date(env, propertyValue, &isDate);
770 if (!isDate) {
771 ANSR_LOGE("Wrong argument type. Date expected.");
772 return false;
773 }
774 napi_get_date_value(env, propertyValue, &date);
775 return true;
776 }
777
CreateReminderTimer(const napi_env & env,const napi_value & value,std::shared_ptr<ReminderRequest> & reminder)778 napi_value ReminderCommon::CreateReminderTimer(
779 const napi_env &env, const napi_value &value, std::shared_ptr<ReminderRequest>& reminder)
780 {
781 int64_t propertyCountDownTime = 0;
782 if (!GetInt64(env, value, ReminderAgentNapi::TIMER_COUNT_DOWN_TIME, propertyCountDownTime)) {
783 ANSR_LOGW("Correct property %{public}s expected.", ReminderAgentNapi::TIMER_COUNT_DOWN_TIME);
784 return nullptr;
785 }
786
787 auto countDownTimeInSeconds = static_cast<uint64_t>(propertyCountDownTime);
788 if (propertyCountDownTime <= 0 || countDownTimeInSeconds >= (UINT64_MAX / ReminderRequest::MILLI_SECONDS)) {
789 ANSR_LOGW("Create countDown reminder fail: designated %{public}s is illegal.",
790 ReminderAgentNapi::TIMER_COUNT_DOWN_TIME);
791 return nullptr;
792 }
793
794 reminder = std::make_shared<ReminderRequestTimer>(countDownTimeInSeconds);
795 return NotificationNapi::Common::NapiGetNull(env);
796 }
797
CreateReminderAlarm(const napi_env & env,const napi_value & value,std::shared_ptr<ReminderRequest> & reminder)798 napi_value ReminderCommon::CreateReminderAlarm(
799 const napi_env &env, const napi_value &value, std::shared_ptr<ReminderRequest>& reminder)
800 {
801 // hour
802 int32_t propertyHourVal = 0;
803 const int32_t maxHour = 23;
804 if (!GetInt32(env, value, ReminderAgentNapi::ALARM_HOUR, propertyHourVal, true)) {
805 return nullptr;
806 }
807
808 // minute
809 int32_t propertyMinuteVal = 0;
810 const int32_t maxMinute = 59;
811 if (!GetInt32(env, value, ReminderAgentNapi::ALARM_MINUTE, propertyMinuteVal, true)) {
812 return nullptr;
813 }
814
815 if ((propertyHourVal < 0) || (propertyHourVal > maxHour)) {
816 ANSR_LOGW("Create alarm reminder fail: designated %{public}s must between [0, 23].",
817 ReminderAgentNapi::ALARM_HOUR);
818 return nullptr;
819 }
820
821 if ((propertyMinuteVal < 0) || (propertyMinuteVal > maxMinute)) {
822 ANSR_LOGW("Create alarm reminder fail: designated %{public}s must between [0, 59].",
823 ReminderAgentNapi::ALARM_MINUTE);
824 return nullptr;
825 }
826
827 // daysOfWeek
828 std::vector<uint8_t> daysOfWeek;
829 uint8_t maxDaysOfWeek = 7;
830 if (ParseInt32Array(env, value, ReminderAgentNapi::REPEAT_DAYS_OF_WEEK, daysOfWeek, maxDaysOfWeek) == nullptr) {
831 return nullptr;
832 }
833 reminder = std::make_shared<ReminderRequestAlarm>(
834 static_cast<uint8_t>(propertyHourVal), static_cast<uint8_t>(propertyMinuteVal), daysOfWeek);
835 return NotificationNapi::Common::NapiGetNull(env);
836 }
837
CreateReminderCalendar(const napi_env & env,const napi_value & value,const bool isSysApp,std::shared_ptr<ReminderRequest> & reminder)838 napi_value ReminderCommon::CreateReminderCalendar(
839 const napi_env &env, const napi_value &value, const bool isSysApp, std::shared_ptr<ReminderRequest>& reminder)
840 {
841 struct tm dateTime;
842 napi_value dateTimeObj = nullptr;
843 if (!GetObject(env, value, ReminderAgentNapi::CALENDAR_DATE_TIME, dateTimeObj)) {
844 ANSR_LOGW("Create calendar reminder fail: dateTime must be setted.");
845 return nullptr;
846 }
847
848 if (!ParseLocalDateTime(env, dateTimeObj, dateTime)) {
849 ANSR_LOGW("Parce DateTime failed.");
850 return nullptr;
851 }
852
853 std::vector<uint8_t> repeatMonths;
854 std::vector<uint8_t> repeatDays;
855 std::vector<uint8_t> daysOfWeek;
856
857 if (!ParseCalendarParams(env, value, repeatMonths, repeatDays, daysOfWeek)) {
858 return nullptr;
859 }
860
861 // rruleWantAgent
862 std::shared_ptr<ReminderRequest::WantAgentInfo> wantAgentInfo;
863 if (!GenWantAgent(env, value, ReminderAgentNapi::RRULL_WANT_AGENT, wantAgentInfo)) {
864 return nullptr;
865 }
866 if (!isSysApp && wantAgentInfo != nullptr) {
867 ANS_LOGE("Not system app rrule want info not supported");
868 return nullptr;
869 }
870
871 auto reminderCalendar = std::make_shared<ReminderRequestCalendar>(dateTime, repeatMonths, repeatDays, daysOfWeek);
872 napi_value endDateTimeObj = nullptr;
873 if (GetObject(env, value, ReminderAgentNapi::CALENDAR_END_DATE_TIME, endDateTimeObj)) {
874 struct tm endDateTime;
875 if (!ParseLocalDateTime(env, endDateTimeObj, endDateTime)) {
876 return nullptr;
877 }
878 time_t endTime = mktime(&endDateTime);
879 if (endTime == -1) {
880 return nullptr;
881 }
882 if (!reminderCalendar->SetEndDateTime(ReminderRequest::GetDurationSinceEpochInMilli(endTime))) {
883 ANSR_LOGW("The end time must be greater than start time");
884 return nullptr;
885 }
886 }
887
888 if (!(reminderCalendar->InitTriggerTime())) {
889 return nullptr;
890 }
891 reminderCalendar->SetRRuleWantAgentInfo(wantAgentInfo);
892 reminder = reminderCalendar;
893 return NotificationNapi::Common::NapiGetNull(env);
894 }
895
CheckCalendarParams(const int32_t & year,const int32_t & month,const int32_t & day,const int32_t & hour,const int32_t & min)896 bool ReminderCommon::CheckCalendarParams(const int32_t &year, const int32_t &month, const int32_t &day,
897 const int32_t &hour, const int32_t &min)
898 {
899 if ((year < 0) || (year > UINT16_MAX)) {
900 ANSR_LOGW("Create calendar reminder fail: designated %{public}s must between [0, %{public}d]",
901 ReminderAgentNapi::CALENDAR_YEAR, UINT16_MAX);
902 return false;
903 }
904 if ((month < 1) || (month > ReminderRequestCalendar::MAX_MONTHS_OF_YEAR)) {
905 ANSR_LOGW("Create calendar reminder fail: designated %{public}s must between [1, %{public}hhu]",
906 ReminderAgentNapi::CALENDAR_MONTH, ReminderRequestCalendar::MAX_MONTHS_OF_YEAR);
907 return false;
908 }
909 uint8_t maxDaysOfMonth = ReminderRequestCalendar::GetDaysOfMonth(static_cast<uint16_t>(year), month);
910 if ((day < 1) || (day > maxDaysOfMonth)) {
911 ANSR_LOGW("Create calendar reminder fail: designated %{public}s must between [1, %{public}hhu]",
912 ReminderAgentNapi::CALENDAR_DAY, maxDaysOfMonth);
913 return false;
914 }
915 uint8_t maxHour = 23;
916 if (hour < 0 || hour > maxHour) {
917 ANSR_LOGW("Create calendar reminder fail: designated %{public}s must between [0, %{public}hhu]",
918 ReminderAgentNapi::CALENDAR_HOUR, maxHour);
919 return false;
920 }
921 uint8_t maxMinute = 59;
922 if (min < 0 || min > maxMinute) {
923 ANSR_LOGW("Create calendar reminder fail: designated %{public}s must between [0, %{public}hhu]",
924 ReminderAgentNapi::CALENDAR_MINUTE, maxMinute);
925 return false;
926 }
927 return true;
928 }
929
ParseCalendarParams(const napi_env & env,const napi_value & value,std::vector<uint8_t> & repeatMonths,std::vector<uint8_t> & repeatDays,std::vector<uint8_t> & daysOfWeek)930 bool ReminderCommon::ParseCalendarParams(const napi_env& env, const napi_value& value,
931 std::vector<uint8_t>& repeatMonths, std::vector<uint8_t>& repeatDays, std::vector<uint8_t>& daysOfWeek)
932 {
933 // repeatMonth
934 if (ParseInt32Array(env, value, ReminderAgentNapi::CALENDAR_REPEAT_MONTHS, repeatMonths,
935 ReminderRequestCalendar::MAX_MONTHS_OF_YEAR) == nullptr) {
936 return false;
937 }
938
939 // repeatDay
940 if (ParseInt32Array(env, value, ReminderAgentNapi::CALENDAR_REPEAT_DAYS, repeatDays,
941 ReminderRequestCalendar::MAX_DAYS_OF_MONTH) == nullptr) {
942 return false;
943 }
944
945 // daysOfWeek
946 uint8_t maxDaysOfWeek = 7;
947 if (ParseInt32Array(env, value, ReminderAgentNapi::REPEAT_DAYS_OF_WEEK, daysOfWeek, maxDaysOfWeek) == nullptr) {
948 return false;
949 }
950
951 return true;
952 }
953
ParseLocalDateTime(const napi_env & env,const napi_value & dateTimeObj,struct tm & dateTime)954 bool ReminderCommon::ParseLocalDateTime(const napi_env& env, const napi_value& dateTimeObj, struct tm& dateTime)
955 {
956 int32_t propertyYearVal = 0;
957 int32_t propertyMonthVal = 0;
958 int32_t propertyDayVal = 0;
959 int32_t propertyHourVal = 0;
960 int32_t propertyMinteVal = 0;
961 if (!GetInt32(env, dateTimeObj, ReminderAgentNapi::CALENDAR_YEAR, propertyYearVal, true) ||
962 !GetInt32(env, dateTimeObj, ReminderAgentNapi::CALENDAR_MONTH, propertyMonthVal, true) ||
963 !GetInt32(env, dateTimeObj, ReminderAgentNapi::CALENDAR_DAY, propertyDayVal, true) ||
964 !GetInt32(env, dateTimeObj, ReminderAgentNapi::CALENDAR_HOUR, propertyHourVal, true) ||
965 !GetInt32(env, dateTimeObj, ReminderAgentNapi::CALENDAR_MINUTE, propertyMinteVal, true)) {
966 return false;
967 }
968
969 if (!CheckCalendarParams(propertyYearVal, propertyMonthVal, propertyDayVal,
970 propertyHourVal, propertyMinteVal)) {
971 return false;
972 }
973
974 dateTime.tm_year = ReminderRequest::GetCTime(ReminderRequest::TimeTransferType::YEAR, propertyYearVal);
975 dateTime.tm_mon = ReminderRequest::GetCTime(ReminderRequest::TimeTransferType::MONTH, propertyMonthVal);
976 dateTime.tm_mday = propertyDayVal;
977 dateTime.tm_hour = propertyHourVal;
978 dateTime.tm_min = propertyMinteVal;
979 dateTime.tm_sec = 0;
980 dateTime.tm_isdst = -1;
981 return true;
982 }
983
ParseInt32Array(const napi_env & env,const napi_value & value,const char * propertyName,std::vector<uint8_t> & propertyVal,uint8_t maxLen)984 napi_value ReminderCommon::ParseInt32Array(const napi_env &env, const napi_value &value,
985 const char* propertyName, std::vector<uint8_t> &propertyVal, uint8_t maxLen)
986 {
987 napi_value result = nullptr;
988 if (!GetObject(env, value, propertyName, result)) {
989 return NotificationNapi::Common::NapiGetNull(env);
990 }
991 if (result != nullptr) {
992 bool isArray = false;
993 napi_is_array(env, result, &isArray);
994 if (!isArray) {
995 ANSR_LOGW("Property %{public}s is expected to be an array.", propertyName);
996 return nullptr;
997 }
998 uint32_t length = 0;
999 napi_get_array_length(env, result, &length);
1000 if (length > maxLen) {
1001 ANSR_LOGW("The max length of array of %{public}s is %{public}hhu.", propertyName, maxLen);
1002 return nullptr;
1003 }
1004 napi_valuetype valuetype = napi_undefined;
1005 for (size_t i = 0; i < length; i++) {
1006 int32_t propertyDayVal = 10;
1007 napi_value repeatDayVal = nullptr;
1008 napi_get_element(env, result, i, &repeatDayVal);
1009 NAPI_CALL(env, napi_typeof(env, repeatDayVal, &valuetype));
1010 if (valuetype != napi_number) {
1011 ANSR_LOGW("%{public}s's element is expected to be number.", propertyName);
1012 return nullptr;
1013 }
1014 napi_get_value_int32(env, repeatDayVal, &propertyDayVal);
1015 if (propertyDayVal < 1 || propertyDayVal > static_cast<int32_t>(maxLen)) {
1016 ANSR_LOGW("%{public}s's element must between [1, %{public}d].", propertyName, maxLen);
1017 return nullptr;
1018 }
1019 propertyVal.push_back(static_cast<uint8_t>(propertyDayVal));
1020 }
1021 }
1022 return NotificationNapi::Common::NapiGetNull(env);
1023 }
1024
PaddingCallbackPromiseInfo(const napi_env & env,const napi_ref & callback,CallbackPromiseInfo & info,napi_value & promise)1025 void ReminderCommon::PaddingCallbackPromiseInfo(
1026 const napi_env &env, const napi_ref &callback, CallbackPromiseInfo &info, napi_value &promise)
1027 {
1028 if (callback) {
1029 info.callback = callback;
1030 info.isCallback = true;
1031 } else {
1032 napi_deferred deferred = nullptr;
1033 NAPI_CALL_RETURN_VOID(env, napi_create_promise(env, &deferred, &promise));
1034 info.deferred = deferred;
1035 info.isCallback = false;
1036 }
1037 }
1038
HandleErrCode(const napi_env & env,int32_t errCode)1039 void ReminderCommon::HandleErrCode(const napi_env &env, int32_t errCode)
1040 {
1041 if (errCode == ERR_OK) {
1042 return;
1043 }
1044 std::string errCodeMsg = reminderErrCodeMsgMap[errCode];
1045 napi_throw_error(env, std::to_string(errCode).c_str(), errCodeMsg.c_str());
1046 }
1047
FindErrMsg(const napi_env & env,const int32_t errCode)1048 std::string ReminderCommon::FindErrMsg(const napi_env &env, const int32_t errCode)
1049 {
1050 auto findMsg = reminderErrCodeMsgMap.find(errCode);
1051 if (findMsg == reminderErrCodeMsgMap.end()) {
1052 ANSR_LOGI("Inner error.");
1053 return "Inner error.";
1054 }
1055 return reminderErrCodeMsgMap[errCode];
1056 }
1057
ReturnCallbackPromise(const napi_env & env,const CallbackPromiseInfo & info,const napi_value & result,bool isThrow)1058 void ReminderCommon::ReturnCallbackPromise(const napi_env &env, const CallbackPromiseInfo &info,
1059 const napi_value &result, bool isThrow)
1060 {
1061 ANSR_LOGI("enter errorCode=%{public}d", info.errorCode);
1062 if (info.isCallback) {
1063 if (isThrow) {
1064 SetCallback(env, info.callback, info.errorCode, result);
1065 } else {
1066 NotificationNapi::Common::SetCallback(env, info.callback, info.errorCode, result, false);
1067 }
1068 } else {
1069 SetPromise(env, info, result);
1070 }
1071 ANSR_LOGI("end");
1072 }
1073
SetCallback(const napi_env & env,const napi_ref & callbackIn,const int32_t & errCode,const napi_value & result)1074 void ReminderCommon::SetCallback(
1075 const napi_env &env, const napi_ref &callbackIn, const int32_t &errCode, const napi_value &result)
1076 {
1077 napi_value undefined = nullptr;
1078 napi_get_undefined(env, &undefined);
1079
1080 napi_value callback = nullptr;
1081 napi_value resultout = nullptr;
1082 napi_get_reference_value(env, callbackIn, &callback);
1083 napi_value results[ASYNC_CALLBACK_PARAM_NUM] = {nullptr};
1084 if (errCode == ERR_OK) {
1085 results[0] = NotificationNapi::Common::NapiGetNull(env);
1086 } else {
1087 std::string errMsg = FindErrMsg(env, errCode);
1088 results[0] = GetCallbackErrorValue(env, errCode, errMsg);
1089 }
1090 results[1] = result;
1091 NAPI_CALL_RETURN_VOID(env,
1092 napi_call_function(env, undefined, callback, ASYNC_CALLBACK_PARAM_NUM, &results[0], &resultout));
1093 }
1094
GetCallbackErrorValue(napi_env env,const int32_t errCode,const std::string errMsg)1095 napi_value ReminderCommon::GetCallbackErrorValue(napi_env env, const int32_t errCode, const std::string errMsg)
1096 {
1097 if (errCode == ERR_OK) {
1098 return NotificationNapi::Common::NapiGetNull(env);
1099 }
1100 napi_value error = nullptr;
1101 napi_value eCode = nullptr;
1102 napi_value eMsg = nullptr;
1103 NAPI_CALL(env, napi_create_int32(env, errCode, &eCode));
1104 NAPI_CALL(env, napi_create_string_utf8(env, errMsg.c_str(),
1105 errMsg.length(), &eMsg));
1106 NAPI_CALL(env, napi_create_object(env, &error));
1107 NAPI_CALL(env, napi_set_named_property(env, error, "code", eCode));
1108 NAPI_CALL(env, napi_set_named_property(env, error, "message", eMsg));
1109 return error;
1110 }
1111
SetPromise(const napi_env & env,const CallbackPromiseInfo & info,const napi_value & result)1112 napi_value ReminderCommon::SetPromise(
1113 const napi_env &env, const CallbackPromiseInfo &info, const napi_value &result)
1114 {
1115 if (info.errorCode == ERR_OK) {
1116 napi_resolve_deferred(env, info.deferred, result);
1117 } else {
1118 std::string errMsg = FindErrMsg(env, info.errorCode);
1119 if (errMsg == "") {
1120 return nullptr;
1121 }
1122 napi_value error = nullptr;
1123 napi_value eCode = nullptr;
1124 napi_value eMsg = nullptr;
1125 NAPI_CALL(env, napi_create_int32(env, info.errorCode, &eCode));
1126 NAPI_CALL(env, napi_create_string_utf8(env, errMsg.c_str(),
1127 errMsg.length(), &eMsg));
1128 NAPI_CALL(env, napi_create_object(env, &error));
1129 NAPI_CALL(env, napi_set_named_property(env, error, "data", eCode));
1130 NAPI_CALL(env, napi_set_named_property(env, error, "code", eCode));
1131 NAPI_CALL(env, napi_set_named_property(env, error, "message", eMsg));
1132 napi_reject_deferred(env, info.deferred, error);
1133 }
1134 return result;
1135 }
1136
JSParaError(const napi_env & env,const napi_ref & callback)1137 napi_value ReminderCommon::JSParaError(const napi_env &env, const napi_ref &callback)
1138 {
1139 if (callback) {
1140 SetCallback(env, callback, ERR_REMINDER_INVALID_PARAM, nullptr);
1141 return NotificationNapi::Common::NapiGetNull(env);
1142 } else {
1143 napi_value promise = nullptr;
1144 napi_deferred deferred = nullptr;
1145 napi_create_promise(env, &deferred, &promise);
1146
1147 napi_value res = nullptr;
1148 napi_value eCode = nullptr;
1149 napi_value eMsg = nullptr;
1150 std::string errMsg = FindErrMsg(env, ERR_REMINDER_INVALID_PARAM);
1151 NAPI_CALL(env, napi_create_int32(env, ERR_REMINDER_INVALID_PARAM, &eCode));
1152 NAPI_CALL(env, napi_create_string_utf8(env, errMsg.c_str(),
1153 errMsg.length(), &eMsg));
1154 NAPI_CALL(env, napi_create_object(env, &res));
1155 NAPI_CALL(env, napi_set_named_property(env, res, "data", eCode));
1156 NAPI_CALL(env, napi_set_named_property(env, res, "code", eCode));
1157 NAPI_CALL(env, napi_set_named_property(env, res, "message", eMsg));
1158 napi_reject_deferred(env, deferred, res);
1159 return promise;
1160 }
1161 }
1162 }
1163 }
1164