1 /*
2 * Copyright (C) 2021 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 "jscallback.h"
16 #include "media_log.h"
17
18 namespace {
19 constexpr OHOS::HiviewDFX::HiLogLabel LABEL = {LOG_CORE, LOG_DOMAIN, "JsCallback"};
20 }
21
22 namespace OHOS {
23 namespace Media {
Create(napi_env env,napi_value callback,const std::string & callbackName)24 std::shared_ptr<JsCallback> JsCallback::Create(napi_env env, napi_value callback, const std::string &callbackName)
25 {
26 napi_ref ref = nullptr;
27 napi_status status = napi_create_reference(env, callback, 1, &ref);
28 CHECK_AND_RETURN_RET_LOG(status == napi_ok, nullptr, "create ref failed");
29 std::shared_ptr<JsCallback> jsCallback = std::make_shared<JsCallback>(env, ref, callbackName);
30 CHECK_AND_RETURN_RET_LOG(jsCallback != nullptr, nullptr, "failed to new jsCallback");
31
32 return jsCallback;
33 }
34
JsCallback(napi_env env,napi_ref ref,const std::string & callbackName)35 JsCallback::JsCallback(napi_env env, napi_ref ref, const std::string &callbackName)
36 : env_(env),
37 ref_(ref),
38 name_(callbackName)
39 {
40 MEDIA_LOGD("0x%{public}06" PRIXPTR " Instances create name %{public}s", FAKE_POINTER(this), callbackName.c_str());
41 }
42
~JsCallback()43 JsCallback::~JsCallback()
44 {
45 if (ref_ != nullptr) {
46 napi_delete_reference(env_, ref_);
47 ref_ = nullptr;
48 }
49 env_ = nullptr;
50 }
51
GetCallback() const52 napi_value JsCallback::GetCallback() const
53 {
54 CHECK_AND_RETURN_RET_LOG(ref_ != nullptr, nullptr, "callback ref is nullptr");
55 napi_value callback = nullptr;
56 napi_status status = napi_get_reference_value(env_, ref_, &callback);
57 CHECK_AND_RETURN_RET_LOG(status == napi_ok, nullptr, "get reference value fail");
58 return callback;
59 }
60
GetName() const61 std::string JsCallback::GetName() const
62 {
63 return name_;
64 }
65 } // namespace Media
66 } // namespace OHOS
67