diff --git a/interfaces/kits/js4.0/BUILD.gn b/interfaces/kits/js4.0/BUILD.gn new file mode 100644 index 0000000000000000000000000000000000000000..00eb98bafffb5ce56bebd88c95f115571fcc2a6c --- /dev/null +++ b/interfaces/kits/js4.0/BUILD.gn @@ -0,0 +1,53 @@ +# Copyright (c) 2022-2023 Huawei Device Co., Ltd. +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import("//build/ohos.gni") +import("//foundation/distributedhardware/device_manager/device_manager.gni") + +ohos_shared_library("distributeddevicemanager") { + include_dirs = [ + "include", + "${common_path}/include", + "${common_path}/include/ipc", + "${innerkits_path}/native_cpp/include", + "${innerkits_path}/native_cpp/include/ipc", + "${innerkits_path}/native_cpp/include/ipc/standard", + "//third_party/node/src", + "//third_party/json/include", + ] + + sources = [ + "${common_path}/src/dm_error_message.cpp", + "src/dm_native_event.cpp", + "src/native_devicemanager_js.cpp", + ] + + deps = [ "${innerkits_path}/native_cpp:devicemanagersdk" ] + + defines = [ + "HI_LOG_ENABLE", + "DH_LOG_TAG=\"devicemanagerkit_js\"", + "LOG_DOMAIN=0xD004100", + ] + + external_deps = [ + "access_token:libtokenid_sdk", + "bundle_framework:appexecfwk_base", + "ipc:ipc_core", + "napi:ace_napi", + ] + + subsystem_name = "distributedhardware" + relative_install_dir = "module" + part_name = "device_manager" +} diff --git a/interfaces/kits/js4.0/include/dm_native_event.h b/interfaces/kits/js4.0/include/dm_native_event.h new file mode 100644 index 0000000000000000000000000000000000000000..da0915df85078553f0ce8ffd090e3cc45bd1f352 --- /dev/null +++ b/interfaces/kits/js4.0/include/dm_native_event.h @@ -0,0 +1,48 @@ +/* + * Copyright (c) 2022 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef OHOS_DM_NATIVE_EVENT_H +#define OHOS_DM_NATIVE_EVENT_H + +#include +#include +#include +#include + +#include "napi/native_api.h" + +struct DmEventListener { + std::string eventType; + napi_ref handlerRef = nullptr; +}; + +class DmNativeEvent { +public: + DmNativeEvent(napi_env env, napi_value thisVar); + virtual ~DmNativeEvent(); + + virtual void On(std::string &eventType, napi_value handler); + virtual void Off(std::string &eventType); + virtual void OnEvent(const std::string &eventType, size_t argc, const napi_value *argv); + +protected: + napi_env env_; + napi_ref thisVarRef_; + std::map> eventMap_; +#if !defined(__LITEOS_M__) + std::mutex lock_; +#endif +}; +#endif // OHOS_DM_NATIVE_EVENT_H diff --git a/interfaces/kits/js4.0/include/native_devicemanager_js.h b/interfaces/kits/js4.0/include/native_devicemanager_js.h new file mode 100644 index 0000000000000000000000000000000000000000..56b3d5437835948969323faf32085864d64dbd00 --- /dev/null +++ b/interfaces/kits/js4.0/include/native_devicemanager_js.h @@ -0,0 +1,375 @@ +/* + * Copyright (c) 2022-2023 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef OHOS_DM_NATIVE_DEVICEMANAGER_JS_H +#define OHOS_DM_NATIVE_DEVICEMANAGER_JS_H + +#include +#include +#include + +#include "device_manager_callback.h" +#include "dm_app_image_info.h" +#include "dm_device_info.h" +#include "dm_native_event.h" +#include "dm_subscribe_info.h" +#include "dm_publish_info.h" +#include "dm_anonymous.h" +#include "dm_error_message.h" +#include "napi/native_api.h" +#include "napi/native_node_api.h" +#include "nlohmann/json.hpp" +#define DM_NAPI_BUF_LENGTH (256) +#define DM_NAPI_CREDENTIAL_BUF_LENGTH (6000) +#define DM_NAPI_DESCRIPTION_BUF_LENGTH (16384) + +struct AsyncCallbackInfo { + napi_env env = nullptr; + napi_async_work asyncWork = nullptr; + + char bundleName[DM_NAPI_BUF_LENGTH] = {0}; + size_t bundleNameLen = 0; + + napi_ref callback = nullptr; + int32_t status = -1; + int32_t ret = 0; +}; + +struct CredentialAsyncCallbackInfo { + napi_env env = nullptr; + napi_async_work asyncWork = nullptr; + + std::string bundleName; + std::string reqInfo; + std::string returnJsonStr; + int32_t status = -1; + int32_t ret = 0; + napi_ref callback = nullptr; +}; + +struct DeviceBasicInfoListAsyncCallbackInfo { + napi_env env = nullptr; + napi_async_work asyncWork = nullptr; + + std::string bundleName; + size_t bundleNameLen = 0; + std::vector devList; + std::string extra; + // OHOS::DistributedHardware::DmFilterOptions filter; + napi_ref callback = nullptr; + napi_value thisVar = nullptr; + napi_deferred deferred = nullptr; + int32_t status = -1; + int32_t ret = 0; +}; + +struct AuthAsyncCallbackInfo { + napi_env env = nullptr; + + char bundleName[DM_NAPI_BUF_LENGTH] = {0}; + size_t bundleNameLen = 0; + + napi_ref callback = nullptr; + int32_t authType = -1; +}; + +struct DmNapiStatusJsCallback { + std::string bundleName_; + uint16_t subscribeId_; + int32_t reason_; + OHOS::DistributedHardware::DmDeviceBasicInfo deviceBasicInfo_; + + DmNapiStatusJsCallback(std::string bundleName, uint16_t subscribeId, int32_t reason, + OHOS::DistributedHardware::DmDeviceBasicInfo deviceBasicInfo_) + : bundleName_(bundleName), subscribeId_(subscribeId), reason_(reason), deviceBasicInfo_(deviceBasicInfo_) {} +}; + +struct DmNapiPublishJsCallback { + std::string bundleName_; + int32_t publishId_; + int32_t reason_; + + DmNapiPublishJsCallback(std::string bundleName, int32_t publishId, int32_t reason) + : bundleName_(bundleName), publishId_(publishId), reason_(reason) {} +}; + +struct DmNapiCredentialJsCallback { + std::string bundleName_; + int32_t action_; + std::string credentialResult_; + + DmNapiCredentialJsCallback(std::string bundleName, int32_t action, std::string credentialResult) + : bundleName_(bundleName), action_(action), credentialResult_(credentialResult) {} +}; + +struct DmNapiAuthJsCallback { + std::string bundleName_; + std::string deviceId_; + std::string token_; + int32_t status_; + int32_t reason_; + + DmNapiAuthJsCallback(std::string bundleName, std::string deviceId, std::string token, int32_t status, + int32_t reason) + : bundleName_(bundleName), deviceId_(deviceId), token_(token), status_(status), reason_(reason) {} +}; + +struct DmNapiVerifyJsCallback { + std::string bundleName_; + std::string deviceId_; + int32_t resultCode_; + int32_t flag_; + + DmNapiVerifyJsCallback(std::string bundleName, std::string deviceId, int32_t resultCode, int32_t flag) + : bundleName_(bundleName), deviceId_(deviceId), resultCode_(resultCode), flag_(flag) {} +}; + +enum DmNapiDevStatusChange { UNKNOWN = 0, AVAILABLE = 1, UNAVAILABLE = 2, CHANGE = 3}; + +class DmNapiInitCallback : public OHOS::DistributedHardware::DmInitCallback { +public: + explicit DmNapiInitCallback(napi_env env, std::string &bundleName) : env_(env), bundleName_(bundleName) + { + } + ~DmNapiInitCallback() override {} + void OnRemoteDied() override; + +private: + napi_env env_; + std::string bundleName_; +}; + +class DmNapiDeviceStatusCallback : public OHOS::DistributedHardware::DeviceStatusCallback { +public: + explicit DmNapiDeviceStatusCallback(napi_env env, std::string &bundleName) : env_(env), bundleName_(bundleName) + { + } + ~DmNapiDeviceStatusCallback() override {}; + void OnDeviceOnline(const OHOS::DistributedHardware::DmDeviceBasicInfo &deviceBasicInfo) override; + void OnDeviceReady(const OHOS::DistributedHardware::DmDeviceBasicInfo &deviceBasicInfo) override; + void OnDeviceOffline(const OHOS::DistributedHardware::DmDeviceBasicInfo &deviceBasicInfo) override; + void OnDeviceChanged(const OHOS::DistributedHardware::DmDeviceBasicInfo &deviceBasicInfo) override; +private: + napi_env env_; + std::string bundleName_; +}; + +class DmNapiDiscoveryCallback : public OHOS::DistributedHardware::DiscoveryCallback { +public: + explicit DmNapiDiscoveryCallback(napi_env env, std::string &bundleName) + : env_(env), refCount_(0), bundleName_(bundleName) + { + } + ~DmNapiDiscoveryCallback() override {}; + void OnDeviceFound(uint16_t subscribeId, + const OHOS::DistributedHardware::DmDeviceBasicInfo &deviceBasicInfo) override; + void OnDiscoveryFailed(uint16_t subscribeId, int32_t failedReason) override; + void OnDiscoverySuccess(uint16_t subscribeId) override; + void IncreaseRefCount(); + void DecreaseRefCount(); + int32_t GetRefCount(); + +private: + napi_env env_; + std::atomic refCount_; + std::string bundleName_; +}; + +class DmNapiPublishCallback : public OHOS::DistributedHardware::PublishCallback { +public: + explicit DmNapiPublishCallback(napi_env env, std::string &bundleName) + : env_(env), refCount_(0), bundleName_(bundleName) + { + } + ~DmNapiPublishCallback() override {}; + void OnPublishResult(int32_t publishId, int32_t publishResult) override; + void IncreaseRefCount(); + void DecreaseRefCount(); + int32_t GetRefCount(); + +private: + napi_env env_; + std::atomic refCount_; + std::string bundleName_; +}; + +class DmNapiDeviceManagerUiCallback : public OHOS::DistributedHardware::DeviceManagerUiCallback { +public: + explicit DmNapiDeviceManagerUiCallback(napi_env env, std::string &bundleName) : env_(env), bundleName_(bundleName) + { + } + ~DmNapiDeviceManagerUiCallback() override {}; + void OnCall(const std::string ¶mJson) override; + +private: + napi_env env_; + std::string bundleName_; +}; + +class DmNapiCredentialCallback : public OHOS::DistributedHardware::CredentialCallback { +public: + explicit DmNapiCredentialCallback(napi_env env, const std::string &bundleName) : env_(env), bundleName_(bundleName) + { + } + ~DmNapiCredentialCallback() override {}; + void OnCredentialResult(int32_t &action, const std::string &credentialResult) override; + +private: + napi_env env_; + std::string bundleName_; +}; + +class DmNapiAuthenticateCallback : public OHOS::DistributedHardware::AuthenticateCallback { +public: + explicit DmNapiAuthenticateCallback(napi_env env, std::string &bundleName) : env_(env), bundleName_(bundleName) + { + } + ~DmNapiAuthenticateCallback() override {}; + void OnAuthResult(const std::string &deviceId, const std::string &token, int32_t status, int32_t reason) override; + +private: + napi_env env_; + std::string bundleName_; +}; + +class DmNapiVerifyAuthCallback : public OHOS::DistributedHardware::VerifyAuthCallback { +public: + explicit DmNapiVerifyAuthCallback(napi_env env, std::string &bundleName) : env_(env), bundleName_(bundleName) + { + } + ~DmNapiVerifyAuthCallback() override {}; + void OnVerifyAuthResult(const std::string &deviceId, int32_t resultCode, int32_t flag) override; + +private: + napi_env env_; + std::string bundleName_; +}; + +class DeviceManagerNapi : public DmNativeEvent { +public: + explicit DeviceManagerNapi(napi_env env, napi_value thisVar); + ~DeviceManagerNapi() override; + static napi_value Init(napi_env env, napi_value exports); + static napi_value Constructor(napi_env env, napi_callback_info info); + static napi_value EnumTypeConstructor(napi_env env, napi_callback_info info); + static napi_value InitDeviceTypeEnum(napi_env env, napi_value exports); + static napi_value InitDeviceStateChangeActionEnum(napi_env env, napi_value exports); + static napi_value InitDiscoverModeEnum(napi_env env, napi_value exports); + static napi_value InitExchangeMediumEnum(napi_env env, napi_value exports); + static napi_value InitExchangeFreqEnum(napi_env env, napi_value exports); + static napi_value InitSubscribeCapEnum(napi_env env, napi_value exports); + static napi_value CreateDeviceManager(napi_env env, napi_callback_info info); + static napi_value ReleaseDeviceManager(napi_env env, napi_callback_info info); + static napi_value SetUserOperationSync(napi_env env, napi_callback_info info); + static napi_value GetAvailableDeviceListSync(napi_env env, napi_callback_info info); + static napi_value GetAvailableDeviceList(napi_env env, napi_callback_info info); + static napi_value GetLocalDeviceNetworkId(napi_env env, napi_callback_info info); + static napi_value GetLocalDeviceId(napi_env env, napi_callback_info info); + static napi_value GetLocalDeviceName(napi_env env, napi_callback_info info); + static napi_value GetLocalDeviceType(napi_env env, napi_callback_info info); + static napi_value GetDeviceName(napi_env env, napi_callback_info info); + static napi_value GetDeviceType(napi_env env, napi_callback_info info); + static napi_value StartDeviceDiscoverSync(napi_env env, napi_callback_info info); + static napi_value StopDeviceDiscoverSync(napi_env env, napi_callback_info info); + static napi_value PublishDeviceDiscoverySync(napi_env env, napi_callback_info info); + static napi_value UnPublishDeviceDiscoverySync(napi_env env, napi_callback_info info); + static napi_value GetAuthenticationParamSync(napi_env env, napi_callback_info info); + static napi_value BindDevice(napi_env env, napi_callback_info info); + static napi_value UnBindDevice(napi_env env, napi_callback_info info); + static napi_value VerifyAuthInfo(napi_env env, napi_callback_info info); + static napi_value RequestCredential(napi_env env, napi_callback_info info); + static napi_value ImportCredential(napi_env env, napi_callback_info info); + static napi_value DeleteCredential(napi_env env, napi_callback_info info); + static napi_value JsOn(napi_env env, napi_callback_info info); + static napi_value JsOff(napi_env env, napi_callback_info info); + static void HandleCreateDmCallBack(const napi_env &env, AsyncCallbackInfo *asCallbackInfo); + static DeviceManagerNapi *GetDeviceManagerNapi(std::string &bundleName); + static void CreateDmCallback(napi_env env, std::string &bundleName, std::string &eventType); + static void CreateDmCallback(napi_env env, std::string &bundleName, std::string &eventType, std::string &extra); + static void ReleaseDmCallback(std::string &bundleName, std::string &eventType); + static void DeviceBasicInfoToJsArray(const napi_env &env, + const std::vector &vecDevInfo, + const int32_t idx, napi_value &arrayResult); + static bool DmAuthParamDetection(const OHOS::DistributedHardware::DmAuthParam &authParam); + static void DmAuthParamToJsAuthParam(const napi_env &env, const OHOS::DistributedHardware::DmAuthParam &authParam, + napi_value ¶mResult); + static void SetValueInt32(const napi_env &env, const std::string &fieldStr, const int32_t intValue, + napi_value &result); + static void SetValueUtf8String(const napi_env &env, const std::string &fieldStr, const std::string &str, + napi_value &result); + static void JsObjectToString(const napi_env &env, const napi_value &object, const std::string &fieldStr, char *dest, + const int32_t destLen); + static void JsObjectToBool(const napi_env &env, const napi_value &object, const std::string &fieldStr, + bool &fieldRef); + static void JsObjectToInt(const napi_env &env, const napi_value &object, const std::string &fieldStr, + int32_t &fieldRef); + static std::string JsObjectToString(const napi_env &env, const napi_value ¶m); + static void JsToDmPublishInfo(const napi_env &env, const napi_value &object, + OHOS::DistributedHardware::DmPublishInfo &info); + static void JsToDmExtra(const napi_env &env, const napi_value &object, std::string &extra, int32_t &authType); + static void JsToBindParam(const napi_env &env, const napi_value &object, std::string &bindParam, int32_t &bindType); + static void JsToDmAuthInfo(const napi_env &env, const napi_value &object, std::string &extra); + static void JsToDmBuffer(const napi_env &env, const napi_value &object, const std::string &fieldStr, + uint8_t **bufferPtr, int32_t &bufferLen); + static void JsToJsonObject(const napi_env &env, const napi_value &object, const std::string &fieldStr, + nlohmann::json &jsonObj); + static void JsToDmTokenInfo(const napi_env &env, const napi_value &object, const std::string &fieldStr, + nlohmann::json &jsonObj); + static void JsToDmAuthExtra(const napi_env &env, const napi_value ¶m, nlohmann::json &jsonObj); + static void JsToDmDiscoveryExtra(const napi_env &env, const napi_value &object, std::string &extra); + static int32_t RegisterCredentialCallback(napi_env env, const std::string &pkgName); + static void AsyncAfterTaskCallback(napi_env env, napi_status status, void *data); + static void AsyncTaskCallback(napi_env env, void *data); + void OnDeviceStatusChange(DmNapiDevStatusChange action, + const OHOS::DistributedHardware::DmDeviceBasicInfo &deviceBasicInfo); + void OnDeviceFound(uint16_t subscribeId, const OHOS::DistributedHardware::DmDeviceBasicInfo &deviceBasicInfo); + void OnDiscoveryFailed(uint16_t subscribeId, int32_t failedReason); + void OnPublishResult(int32_t publishId, int32_t publishResult); + void OnAuthResult(const std::string &deviceId, const std::string &token, int32_t status, int32_t reason); + void OnCredentialResult(int32_t &action, const std::string &credentialResult); + void OnVerifyResult(const std::string &deviceId, int32_t resultCode, int32_t flag); + void OnDmUiCall(const std::string ¶mJson); + +private: + static void ReleasePublishCallback(std::string &bundleName); + static napi_value JsOffFrench(napi_env env, int32_t num, napi_value thisVar, napi_value argv[]); + static napi_value JsOnFrench(napi_env env, int32_t num, napi_value thisVar, napi_value argv[]); + static void CallAsyncWorkSync(napi_env env, + DeviceBasicInfoListAsyncCallbackInfo *deviceBasicInfoListAsyncCallbackInfo); + static void CallAsyncWork(napi_env env, DeviceBasicInfoListAsyncCallbackInfo *deviceBasicInfoListAsyncCallbackInfo); + static void CallCredentialAsyncWork(napi_env env, CredentialAsyncCallbackInfo *creAsyncCallbackInfo); + static void CallRequestCreInfoStatus(napi_env env, napi_status &status, + CredentialAsyncCallbackInfo *creAsyncCallbackInfo); + static void CallGetAvailableDeviceListStatusSync(napi_env env, napi_status &status, + DeviceBasicInfoListAsyncCallbackInfo *deviceBasicInfoListAsyncCallbackInfo); + static void CallGetAvailableDeviceListStatus(napi_env env, napi_status &status, + DeviceBasicInfoListAsyncCallbackInfo *deviceInfoListAsyncCallbackInfo); + static napi_value CallDeviceList(napi_env env, napi_callback_info info, + DeviceBasicInfoListAsyncCallbackInfo *deviceBasicInfoListAsyncCallbackInfo); + static napi_value GetAvailableDeviceListPromise(napi_env env, + DeviceBasicInfoListAsyncCallbackInfo *deviceInfoListAsyncCallbackInfo); + static bool StartNumArgCheck(napi_env env, napi_value &argv, int32_t &subscribeId); + static void HandleCreateDmCallBackCompletedCB(napi_env env, napi_status status, void *data); + static bool IsSystemApp(); +private: + napi_env env_; + static thread_local napi_ref sConstructor_; + std::string bundleName_; + static std::mutex creMapLocks_; + static AuthAsyncCallbackInfo authAsyncCallbackInfo_; + static AuthAsyncCallbackInfo verifyAsyncCallbackInfo_; + static CredentialAsyncCallbackInfo creAsyncCallbackInfo_; +}; +#endif // OHOS_DM_NATIVE_DEVICEMANAGER_JS_H diff --git a/interfaces/kits/js4.0/src/dm_native_event.cpp b/interfaces/kits/js4.0/src/dm_native_event.cpp new file mode 100644 index 0000000000000000000000000000000000000000..3538000bd2240182268a61a716e43ac4e23f315b --- /dev/null +++ b/interfaces/kits/js4.0/src/dm_native_event.cpp @@ -0,0 +1,114 @@ +/* + * Copyright (c) 2022-2023 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "dm_native_event.h" + +#include "dm_log.h" + +using namespace OHOS::DistributedHardware; + +DmNativeEvent::DmNativeEvent(napi_env env, napi_value thisVar) +{ + env_ = env; + thisVarRef_ = nullptr; + napi_create_reference(env, thisVar, 1, &thisVarRef_); +} + +DmNativeEvent::~DmNativeEvent() +{ + for (auto iter = eventMap_.begin(); iter != eventMap_.end(); iter++) { + auto listener = iter->second; + napi_delete_reference(env_, listener->handlerRef); + } + eventMap_.clear(); + napi_delete_reference(env_, thisVarRef_); +} + +void DmNativeEvent::On(std::string &eventType, napi_value handler) +{ + LOGI("DmNativeEvent On in for event: %s", eventType.c_str()); + std::lock_guard autoLock(lock_); + auto listener = std::make_shared(); + listener->eventType = eventType; + napi_create_reference(env_, handler, 1, &listener->handlerRef); + eventMap_[eventType] = listener; +} + +void DmNativeEvent::Off(std::string &eventType) +{ + LOGI("DmNativeEvent Off in for event: %s", eventType.c_str()); + napi_handle_scope scope = nullptr; + napi_open_handle_scope(env_, &scope); + if (scope == nullptr) { + LOGE("scope is nullptr"); + return; + } + + std::lock_guard autoLock(lock_); + auto iter = eventMap_.find(eventType); + if (iter == eventMap_.end()) { + LOGE("eventType %s not find", eventType.c_str()); + napi_close_handle_scope(env_, scope); + return; + } + auto listener = iter->second; + napi_delete_reference(env_, listener->handlerRef); + eventMap_.erase(eventType); + napi_close_handle_scope(env_, scope); +} + +void DmNativeEvent::OnEvent(const std::string &eventType, size_t argc, const napi_value *argv) +{ + LOGI("OnEvent for %s", eventType.c_str()); + napi_handle_scope scope = nullptr; + napi_open_handle_scope(env_, &scope); + if (scope == nullptr) { + LOGE("scope is nullptr"); + return; + } + + std::lock_guard autoLock(lock_); + auto iter = eventMap_.find(eventType); + if (iter == eventMap_.end()) { + LOGE("eventType %s not find", eventType.c_str()); + napi_close_handle_scope(env_, scope); + return; + } + auto listener = iter->second; + napi_value thisVar = nullptr; + napi_status status = napi_get_reference_value(env_, thisVarRef_, &thisVar); + if (status != napi_ok) { + LOGE("napi_get_reference_value thisVar for %s failed, status = %d", eventType.c_str(), status); + napi_close_handle_scope(env_, scope); + return; + } + + napi_value handler = nullptr; + status = napi_get_reference_value(env_, listener->handlerRef, &handler); + if (status != napi_ok) { + LOGE("napi_get_reference_value handler for %s failed, status = %d", eventType.c_str(), status); + napi_close_handle_scope(env_, scope); + return; + } + + napi_value callResult = nullptr; + status = napi_call_function(env_, thisVar, handler, argc, argv, &callResult); + if (status != napi_ok) { + LOGE("napi_call_function for %s failed, status = %d", eventType.c_str(), status); + napi_close_handle_scope(env_, scope); + return; + } + napi_close_handle_scope(env_, scope); +} diff --git a/interfaces/kits/js4.0/src/native_devicemanager_js.cpp b/interfaces/kits/js4.0/src/native_devicemanager_js.cpp new file mode 100644 index 0000000000000000000000000000000000000000..b818ce2485d526e1b63a8b3e243b45468d5dd9bc --- /dev/null +++ b/interfaces/kits/js4.0/src/native_devicemanager_js.cpp @@ -0,0 +1,253 @@ +/* + * Copyright (c) 2022-2023 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "native_devicemanager_js.h" + +#include +#include +#include + +#include "device_manager.h" +#include "dm_constants.h" +#include "dm_device_info.h" +#include "dm_log.h" +#include "ipc_skeleton.h" +#include "js_native_api.h" +#include "tokenid_kit.h" +#include "nlohmann/json.hpp" + +using namespace OHOS::DistributedHardware; + +namespace { +#define GET_PARAMS(env, info, num) \ + size_t argc = num; \ + napi_value argv[num] = {nullptr}; \ + napi_value thisVar = nullptr; \ + NAPI_CALL(env, napi_get_cb_info(env, info, &argc, argv, &thisVar, nullptr)) + +const std::string DM_NAPI_EVENT_DEVICE_STATUS_CHANGE = "deviceStatusChange"; +const std::string DM_NAPI_EVENT_DEVICE_DISCOVERY_SUCCESS = "discoverySuccess"; +const std::string DM_NAPI_EVENT_DEVICE_DISCOVERY_FAIL = "discoveryFail"; +const std::string DM_NAPI_EVENT_DEVICE_PUBLISH_SUCCESS = "publishSuccess"; +const std::string DM_NAPI_EVENT_DEVICE_PUBLISH_FAIL = "publishFail"; +const std::string DM_NAPI_EVENT_DEVICE_SERVICE_DIE = "serviceDie"; +const std::string DEVICE_MANAGER_NAPI_CLASS_NAME = "DeviceManager"; +const std::string DM_NAPI_EVENT_UI_STATE_CHANGE = "uiStateChange"; +const std::string DM_NAPI_EVENT_DEVICE_NAME_CHANGE = "deviceNameChange"; + + +const int32_t DM_NAPI_ARGS_ZERO = 0; +const int32_t DM_NAPI_ARGS_ONE = 1; +const int32_t DM_NAPI_ARGS_TWO = 2; +const int32_t DM_NAPI_ARGS_THREE = 3; +const int32_t DM_NAPI_SUB_ID_MAX = 65535; +const int32_t DM_AUTH_DIRECTION_CLIENT = 1; +const int32_t DM_AUTH_REQUEST_SUCCESS_STATUS = 7; + +const int32_t DM_NAPI_SUBSCRIBE_CAPABILITY_DDMP = 0; +const int32_t DM_NAPI_SUBSCRIBE_CAPABILITY_OSD = 1; + +napi_ref deviceTypeEnumConstructor_ = nullptr; +napi_ref deviceStateChangeActionEnumConstructor_ = nullptr; +napi_ref discoverModeEnumConstructor_ = nullptr; +napi_ref exchangeMediumEnumConstructor_ = nullptr; +napi_ref exchangeFreqEnumConstructor_ = nullptr; +napi_ref subscribeCapEnumConstructor_ = nullptr; + +std::map g_deviceManagerMap; +std::map> g_initCallbackMap; +std::map> g_deviceStatusCallbackMap; +std::map> g_DiscoveryCallbackMap; +std::map> g_publishCallbackMap; +std::map> g_authCallbackMap; +std::map> g_verifyAuthCallbackMap; +std::map> g_dmUiCallbackMap; +std::map> g_creCallbackMap; + +std::mutex g_initCallbackMapMutex; +std::mutex g_deviceManagerMapMutex; + +enum DMBussinessErrorCode { + // Permission verify failed. + ERR_NO_PERMISSION = 201, + //The caller is not a system application. + ERR_NOT_SYSTEM_APP = 202, + // Input parameter error. + ERR_INVALID_PARAMS = 401, + // Failed to execute the function. + DM_ERR_FAILED = 11600101, + // Failed to obtain the service. + DM_ERR_OBTAIN_SERVICE = 11600102, + // Authentication invalid. + DM_ERR_AUTHENTICALTION_INVALID = 11600103, + // Discovery invalid. + DM_ERR_DISCOVERY_INVALID = 11600104, + // Publish invalid. + DM_ERR_PUBLISH_INVALID = 11600105, +}; + +const std::string ERR_MESSAGE_NO_PERMISSION = "Permission verify failed."; +const std::string ERR_MESSAGE_NOT_SYSTEM_APP = "The caller is not a system application."; +const std::string ERR_MESSAGE_INVALID_PARAMS = "Input parameter error."; +const std::string ERR_MESSAGE_FAILED = "Failed to execute the function."; +const std::string ERR_MESSAGE_OBTAIN_SERVICE = "Failed to obtain the service."; +const std::string ERR_MESSAGE_AUTHENTICALTION_INVALID = "Authentication invalid."; +const std::string ERR_MESSAGE_DISCOVERY_INVALID = "Discovery invalid."; +const std::string ERR_MESSAGE_PUBLISH_INVALID = "Publish invalid."; + +napi_value GenerateBusinessError(napi_env env, int32_t err, const std::string &msg) +{ + napi_value businessError = nullptr; + NAPI_CALL(env, napi_create_object(env, &businessError)); + napi_value errorCode = nullptr; + NAPI_CALL(env, napi_create_int32(env, err, &errorCode)); + napi_value errorMessage = nullptr; + NAPI_CALL(env, napi_create_string_utf8(env, msg.c_str(), NAPI_AUTO_LENGTH, &errorMessage)); + NAPI_CALL(env, napi_set_named_property(env, businessError, "code", errorCode)); + NAPI_CALL(env, napi_set_named_property(env, businessError, "message", errorMessage)); + + return businessError; +} + +bool CheckArgsVal(napi_env env, bool assertion, const std::string ¶m, const std::string &msg) +{ + if (!(assertion)) { + std::string errMsg = ERR_MESSAGE_INVALID_PARAMS + "The value of " + param + ": " + msg; + napi_throw_error(env, std::to_string(ERR_INVALID_PARAMS).c_str(), errMsg.c_str()); + return false; + } + return true; +} + +bool CheckArgsCount(napi_env env, bool assertion, const std::string &message) +{ + if (!(assertion)) { + std::string errMsg = ERR_MESSAGE_INVALID_PARAMS + message; + napi_throw_error(env, std::to_string(ERR_INVALID_PARAMS).c_str(), errMsg.c_str()); + return false; + } + return true; +} + +bool CheckArgsType(napi_env env, bool assertion, const std::string ¶mName, const std::string &type) +{ + if (!(assertion)) { + std::string errMsg = ERR_MESSAGE_INVALID_PARAMS + "The type of " + paramName + + " must be " + type; + napi_throw_error(env, std::to_string(ERR_INVALID_PARAMS).c_str(), errMsg.c_str()); + return false; + } + return true; +} + +napi_value CreateErrorForCall(napi_env env, int32_t code, const std::string &errMsg, bool isAsync = true) +{ + LOGI("CreateErrorForCall code:%d, message:%s", code, errMsg.c_str()); + napi_value error = nullptr; + if (isAsync) { + napi_throw_error(env, std::to_string(code).c_str(), errMsg.c_str()); + } else { + error = GenerateBusinessError(env, code, errMsg); + } + return error; +} + +napi_value CreateBusinessError(napi_env env, int32_t errCode, bool isAsync = true) +{ + napi_value error = nullptr; + switch (errCode) { + case ERR_DM_NO_PERMISSION: + error = CreateErrorForCall(env, ERR_NO_PERMISSION, ERR_MESSAGE_NO_PERMISSION, isAsync); + break; + case ERR_DM_DISCOVERY_REPEATED: + error = CreateErrorForCall(env, DM_ERR_DISCOVERY_INVALID, ERR_MESSAGE_DISCOVERY_INVALID, isAsync); + break; + case ERR_DM_PUBLISH_REPEATED: + error = CreateErrorForCall(env, DM_ERR_PUBLISH_INVALID, ERR_MESSAGE_PUBLISH_INVALID, isAsync); + break; + case ERR_DM_AUTH_BUSINESS_BUSY: + error = CreateErrorForCall(env, DM_ERR_AUTHENTICALTION_INVALID, + ERR_MESSAGE_AUTHENTICALTION_INVALID, isAsync); + break; + case ERR_DM_INPUT_PARA_INVALID: + case ERR_DM_UNSUPPORTED_AUTH_TYPE: + error = CreateErrorForCall(env, ERR_INVALID_PARAMS, ERR_MESSAGE_INVALID_PARAMS, isAsync); + break; + case ERR_DM_INIT_FAILED: + error = CreateErrorForCall(env, DM_ERR_OBTAIN_SERVICE, ERR_MESSAGE_OBTAIN_SERVICE, isAsync); + break; + case ERR_NOT_SYSTEM_APP: + error = CreateErrorForCall(env, ERR_NOT_SYSTEM_APP, ERR_MESSAGE_NOT_SYSTEM_APP, isAsync); + break; + default: + error = CreateErrorForCall(env, DM_ERR_FAILED, ERR_MESSAGE_FAILED, isAsync); + break; + } + return error; +} + +void DeleteUvWork(uv_work_t *work) +{ + if (work == nullptr) { + return; + } + delete work; + work = nullptr; + LOGI("delete work!"); +} + +void DeleteDmNapiStatusJsCallbackPtr(DmNapiStatusJsCallback *pJsCallbackPtr) +{ + if (pJsCallbackPtr == nullptr) { + return; + } + delete pJsCallbackPtr; + pJsCallbackPtr = nullptr; + LOGI("delete DmNapiStatusJsCallback callbackPtr!"); +} + +void DeleteAsyncCallbackInfo(DeviceBasicInfoListAsyncCallbackInfo *pAsynCallbackInfo) +{ + if (pAsynCallbackInfo == nullptr) { + return; + } + delete pAsynCallbackInfo; + pAsynCallbackInfo = nullptr; +} + +bool IsFunctionType(napi_env env, napi_value value) +{ + napi_valuetype eventHandleType = napi_undefined; + napi_typeof(env, value, &eventHandleType); + return CheckArgsType(env, eventHandleType == napi_function, "callback", "function"); +} + +bool IsDeviceManagerNapiNull(napi_env env, napi_value thisVar, DeviceManagerNapi **pDeviceManagerWrapper) +{ + napi_unwrap(env, thisVar, reinterpret_cast(pDeviceManagerWrapper)); + if (pDeviceManagerWrapper != nullptr && *pDeviceManagerWrapper != nullptr) { + return false; + } + CreateBusinessError(env, ERR_DM_POINT_NULL); + LOGE(" DeviceManagerNapi object is nullptr!"); + return true; +} +} // namespace + +thread_local napi_ref DeviceManagerNapi::sConstructor_ = nullptr; +AuthAsyncCallbackInfo DeviceManagerNapi::authAsyncCallbackInfo_; +AuthAsyncCallbackInfo DeviceManagerNapi::verifyAsyncCallbackInfo_; +CredentialAsyncCallbackInfo DeviceManagerNapi::creAsyncCallbackInfo_; +std::mutex DeviceManagerNapi::creMapLocks_; \ No newline at end of file