1 /*
2  * Copyright (c) 2023 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 #include "drm_error_code.h"
16 #include "napi_async_work.h"
17 #include "common_napi.h"
18 
19 namespace OHOS {
20 namespace DrmStandard {
~ContextBase()21 ContextBase::~ContextBase()
22 {
23     DRM_DEBUG_LOG("no memory leak after callback or promise[resolved/rejected]");
24     if (env != nullptr) {
25         if (work != nullptr) {
26             napi_delete_async_work(env, work);
27         }
28         if (callbackRef != nullptr) {
29             napi_delete_reference(env, callbackRef);
30         }
31         napi_delete_reference(env, selfRef);
32         env = nullptr;
33         callbackRef = nullptr;
34         selfRef = nullptr;
35     }
36 }
37 
GetCbInfo(napi_env envi,napi_callback_info info,NapiCbInfoParser parser,bool sync)38 void ContextBase::GetCbInfo(napi_env envi, napi_callback_info info, NapiCbInfoParser parser, bool sync)
39 {
40     env = envi;
41     size_t argc = ARGC_MAX;
42     napi_value argv[ARGC_MAX] = {nullptr};
43     status = napi_get_cb_info(env, info, &argc, argv, &self, nullptr);
44     NAPI_CHECK_STATUS_RETURN_VOID(this, "napi_get_cb_info failed!", DRM_INVALID_PARAM);
45     NAPI_CHECK_ARGS_RETURN_VOID(this, argc <= ARGC_MAX, "too many arguments!", DRM_INVALID_PARAM);
46     NAPI_CHECK_ARGS_RETURN_VOID(this, self != nullptr, "no JavaScript this argument!", DRM_INVALID_PARAM);
47     napi_create_reference(env, self, 1, &selfRef);
48     status = napi_unwrap(env, self, &native);
49     NAPI_CHECK_STATUS_RETURN_VOID(this, "self unwrap failed!", DRM_INVALID_PARAM);
50 
51     if (!sync && (argc > 0)) {
52         // get the last arguments :: <callback>
53         size_t index = argc - 1;
54         napi_valuetype type = napi_undefined;
55         napi_status tyst = napi_typeof(env, argv[index], &type);
56         if ((tyst == napi_ok) && (type == napi_function)) {
57             status = napi_create_reference(env, argv[index], 1, &callbackRef);
58             NAPI_CHECK_STATUS_RETURN_VOID(this, "ref callback failed!", DRM_INVALID_PARAM);
59             argc = index;
60             DRM_DEBUG_LOG("async callback, no promise");
61         } else {
62             DRM_DEBUG_LOG("no callback, async promise");
63         }
64     }
65 
66     if (parser) {
67         parser(argc, argv);
68     } else {
69         NAPI_CHECK_ARGS_RETURN_VOID(this, argc == 0, "required no arguments!", DRM_INVALID_PARAM);
70     }
71 }
72 
SignError(int32_t code)73 void ContextBase::SignError(int32_t code)
74 {
75     status = napi_generic_failure;
76     errCode = code;
77     errMessage = NapiDrmError::GetMessageByCode(errCode);
78 }
79 
Enqueue(napi_env env,std::shared_ptr<ContextBase> ctxt,const std::string & name,NapiAsyncExecute execute,NapiAsyncComplete complete)80 napi_value NapiAsyncWork::Enqueue(napi_env env, std::shared_ptr<ContextBase> ctxt, const std::string &name,
81     NapiAsyncExecute execute, NapiAsyncComplete complete)
82 {
83     DRM_DEBUG_LOG("name=%{public}s", name.c_str());
84     ctxt->execute = std::move(execute);
85     ctxt->complete = std::move(complete);
86     ctxt->taskName = name;
87     napi_value promise = nullptr;
88     if (ctxt->callbackRef == nullptr) {
89         napi_create_promise(ctxt->env, &ctxt->deferred, &promise);
90         DRM_DEBUG_LOG("create deferred promise");
91     } else {
92         napi_get_undefined(ctxt->env, &promise);
93     }
94 
95     napi_value resource = nullptr;
96     napi_create_string_utf8(ctxt->env, name.c_str(), NAPI_AUTO_LENGTH, &resource);
97     napi_create_async_work(
98         ctxt->env, nullptr, resource,
99         [](napi_env env, void* data) {
100             DRM_NAPI_CHECK_AND_RETURN_VOID_LOG(data != nullptr, "napi_async_execute_callback nullptr");
101             auto ctxt = reinterpret_cast<ContextBase*>(data);
102             DRM_DEBUG_LOG("napi_async_execute_callback ctxt->status=%{public}d", ctxt->status);
103             if (ctxt->execute && ctxt->status == napi_ok) {
104                 ctxt->execute();
105             }
106         },
107         [](napi_env env, napi_status status, void* data) {
108             DRM_NAPI_CHECK_AND_RETURN_VOID_LOG(data != nullptr, "napi_async_complete_callback nullptr");
109             auto ctxt = reinterpret_cast<ContextBase*>(data);
110             DRM_DEBUG_LOG("napi_async_complete_callback status=%{public}d, ctxt->status=%{public}d",
111                 status, ctxt->status);
112             if ((status != napi_ok) && (ctxt->status == napi_ok)) {
113                 ctxt->status = status;
114             }
115             if ((ctxt->complete) && (status == napi_ok) && (ctxt->status == napi_ok)) {
116                 ctxt->complete(ctxt->output);
117             }
118             CommonCallbackRoutine(ctxt);
119         },
120         reinterpret_cast<void*>(ctxt.get()), &ctxt->work);
121     napi_queue_async_work_with_qos(ctxt->env, ctxt->work, napi_qos_user_initiated);
122     ctxt->hold = ctxt; // save crossing-thread ctxt.
123     return promise;
124 }
125 
CommonCallbackRoutine(ContextBase * ctxt)126 void NapiAsyncWork::CommonCallbackRoutine(ContextBase *ctxt)
127 {
128     napi_value result[RESULT_ALL] = {nullptr};
129     if (ctxt->status == napi_ok) {
130         napi_get_undefined(ctxt->env, &result[RESULT_ERROR]);
131         if (ctxt->output == nullptr) {
132             napi_get_undefined(ctxt->env, &ctxt->output);
133         }
134         result[RESULT_DATA] = ctxt->output;
135     } else {
136         napi_value message = nullptr;
137         napi_value code = nullptr;
138         napi_create_string_utf8(ctxt->env, ctxt->errMessage.c_str(), NAPI_AUTO_LENGTH, &message);
139         napi_create_error(ctxt->env, nullptr, message, &result[RESULT_ERROR]);
140         napi_create_int32(ctxt->env, ctxt->errCode, &code);
141         napi_set_named_property(ctxt->env, result[RESULT_ERROR], "code", code);
142         napi_get_undefined(ctxt->env, &result[RESULT_DATA]);
143     }
144     if (ctxt->deferred != nullptr) {
145         if (ctxt->status == napi_ok) {
146             DRM_DEBUG_LOG("deferred promise resolved");
147             napi_resolve_deferred(ctxt->env, ctxt->deferred, result[RESULT_DATA]);
148         } else {
149             DRM_DEBUG_LOG("deferred promise rejected");
150             napi_reject_deferred(ctxt->env, ctxt->deferred, result[RESULT_ERROR]);
151         }
152     } else {
153         napi_value callback = nullptr;
154         napi_get_reference_value(ctxt->env, ctxt->callbackRef, &callback);
155         napi_value callbackResult = nullptr;
156         DRM_DEBUG_LOG("call callback function");
157         napi_call_function(ctxt->env, nullptr, callback, RESULT_ALL, result, &callbackResult);
158     }
159     ctxt->hold->execute = nullptr;
160     ctxt->hold->complete = nullptr;
161     ctxt->hold.reset(); // release ctxt.
162 }
163 } // namespace DrmStandard
164 } // namespace OHOS