diff --git a/bundle.json b/bundle.json index 6324a153efa948a3f11fc8d93040e541fc053d4d..21052b352624e36ac316a002a589f620a0be6363 100644 --- a/bundle.json +++ b/bundle.json @@ -62,7 +62,7 @@ "//foundation/communication/netmanager_base/sa_profile:net_manager_profile", "//foundation/communication/netmanager_base/frameworks/js/napi/netpolicy:policy", "//foundation/communication/netmanager_base/frameworks/js/napi/netstats:statistics", - "//foundation/communication/netmanager_base/frameworks/js/napi/netconn:connection" + "//foundation/communication/netmanager_base/frameworks/js/napi/connection:connection" ], "inner_kits": [ { diff --git a/frameworks/js/napi/connection/BUILD.gn b/frameworks/js/napi/connection/BUILD.gn new file mode 100644 index 0000000000000000000000000000000000000000..2ebde76593efc21da6330a965bf9b96355a792b2 --- /dev/null +++ b/frameworks/js/napi/connection/BUILD.gn @@ -0,0 +1,88 @@ +# 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. + +import("//build/ohos.gni") + +SUBSYSTEM_DIR = "//foundation/communication" +NETMANAGER_BASE_NAPI_ROOT = "$SUBSYSTEM_DIR/netmanager_base/frameworks/js/napi/" + +utils_source = [ + "$SUBSYSTEM_DIR/netmanager_base/utils/base_context/src/netmanager_base_base_context.cpp", + "$SUBSYSTEM_DIR/netmanager_base/utils/common_utils/src/netmanager_base_common_utils.cpp", + "$SUBSYSTEM_DIR/netmanager_base/utils/event_manager/src/netmanager_base_event_listener.cpp", + "$SUBSYSTEM_DIR/netmanager_base/utils/event_manager/src/netmanager_base_event_manager.cpp", + "$SUBSYSTEM_DIR/netmanager_base/utils/module_template/src/netmanager_base_module_template.cpp", + "$SUBSYSTEM_DIR/netmanager_base/utils/napi_utils/src/netmanager_base_napi_utils.cpp", +] + +utils_include = [ + "$SUBSYSTEM_DIR/netmanager_base/utils/base_async_work/include", + "$SUBSYSTEM_DIR/netmanager_base/utils/base_context/include", + "$SUBSYSTEM_DIR/netmanager_base/utils/common_utils/include", + "$SUBSYSTEM_DIR/netmanager_base/utils/event_manager/include", + "$SUBSYSTEM_DIR/netmanager_base/utils/log/include", + "$SUBSYSTEM_DIR/netmanager_base/utils/module_template/include", + "$SUBSYSTEM_DIR/netmanager_base/utils/napi_utils/include", +] + +common_include = [ + "//foundation/ace/ace_engine/frameworks/base/utils", + "//foundation/ace/napi/interfaces/kits", + "//foundation/ace/napi", + "//third_party/node/src", +] + +common_deps = [ + "//foundation/ace/napi/:ace_napi", + "//utils/native/base:utils", +] + +common_external_deps = [ + "hiviewdfx_hilog_native:libhilog", + "ipc:ipc_core", +] + +common_relative_install_dir = "module/net" +common_part_name = "netmanager_base" +common_subsystem_name = "communication" + +ohos_shared_library("connection") { + include_dirs = [ + "$NETMANAGER_BASE_NAPI_ROOT/connection/async_context/include", + "$NETMANAGER_BASE_NAPI_ROOT/connection/async_work/include", + "$NETMANAGER_BASE_NAPI_ROOT/connection/constant/include", + "$NETMANAGER_BASE_NAPI_ROOT/connection/connection_exec/include", + "$NETMANAGER_BASE_NAPI_ROOT/connection/connection_module/include", + "$NETMANAGER_BASE_NAPI_ROOT/connection/options/include", + ] + include_dirs += utils_include + include_dirs += common_include + + sources = [ + "async_context/src/getaddressbyname_context.cpp", + "async_context/src/getdefaultnet_context.cpp", + "async_work/src/connection_async_work.cpp", + "connection_exec/src/connection_exec.cpp", + "connection_module/src/connection_module.cpp", + "options/src/net_address.cpp", + ] + sources += utils_source + + deps = common_deps + + external_deps = common_external_deps + + relative_install_dir = common_relative_install_dir + part_name = common_part_name + subsystem_name = common_subsystem_name +} diff --git a/frameworks/js/napi/connection/CMakeLists.txt b/frameworks/js/napi/connection/CMakeLists.txt new file mode 100644 index 0000000000000000000000000000000000000000..6065db385d2d008fda667cf70d066e49731ac750 --- /dev/null +++ b/frameworks/js/napi/connection/CMakeLists.txt @@ -0,0 +1,28 @@ +# 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. + +include_directories(connection_module/include) +include_directories(async_work/include) +include_directories(connection_exec/include) +include_directories(async_context/include) +include_directories(options/include) +include_directories(constant/include) + +add_library(connection SHARED + options/src/net_address.cpp + async_context/src/getaddressbyname_context.cpp + async_context/src/getdefaultnet_context.cpp + connection_exec/src/connection_exec.cpp + async_work/src/connection_async_work.cpp + connection_module/src/connection_module.cpp + ) diff --git a/frameworks/js/napi/connection/async_context/include/getaddressbyname_context.h b/frameworks/js/napi/connection/async_context/include/getaddressbyname_context.h new file mode 100644 index 0000000000000000000000000000000000000000..54a7bb55d301df2d51a70fc1a341fe16fca1c539 --- /dev/null +++ b/frameworks/js/napi/connection/async_context/include/getaddressbyname_context.h @@ -0,0 +1,46 @@ +/* + * 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 COMMUNICATIONNETMANAGERBASE_GETADDRESSBYNAME_CONTEXT_H +#define COMMUNICATIONNETMANAGERBASE_GETADDRESSBYNAME_CONTEXT_H + +#include + +#include "napi/native_api.h" +#include "net_address.h" +#include "netmanager_base_base_context.h" +#include "noncopyable.h" + +namespace OHOS::NetManagerBase { +class GetAddressByNameContext final : public BaseContext { +public: + ACE_DISALLOW_COPY_AND_MOVE(GetAddressByNameContext); + + GetAddressByNameContext() = delete; + + explicit GetAddressByNameContext(napi_env env, EventManager *manager); + + void ParseParams(napi_value *params, size_t paramsCount); + + std::string host; + + std::vector addresses; + +private: + bool CheckParamsType(napi_value *params, size_t paramsCount); +}; +} // namespace OHOS::NetManagerBase + +#endif /* COMMUNICATIONNETMANAGERBASE_GETADDRESSBYNAME_CONTEXT_H */ diff --git a/frameworks/js/napi/connection/async_context/include/getdefaultnet_context.h b/frameworks/js/napi/connection/async_context/include/getdefaultnet_context.h new file mode 100644 index 0000000000000000000000000000000000000000..939bf7a686f2e3f43fc9941370b3a3b6826ffa26 --- /dev/null +++ b/frameworks/js/napi/connection/async_context/include/getdefaultnet_context.h @@ -0,0 +1,39 @@ +/* + * 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 COMMUNICATIONNETMANAGERBASE_GETDEFAULTNET_CONTEXT_H +#define COMMUNICATIONNETMANAGERBASE_GETDEFAULTNET_CONTEXT_H + +#include "napi/native_api.h" +#include "netmanager_base_base_context.h" +#include "noncopyable.h" + +namespace OHOS::NetManagerBase { +class GetDefaultNetContext final : public BaseContext { +public: + ACE_DISALLOW_COPY_AND_MOVE(GetDefaultNetContext); + + GetDefaultNetContext() = delete; + + explicit GetDefaultNetContext(napi_env env, EventManager *manager); + + void ParseParams(napi_value *params, size_t paramsCount); + +private: + bool CheckParamsType(napi_value *params, size_t paramsCount); +}; +} // namespace OHOS::NetManagerBase + +#endif /* COMMUNICATIONNETMANAGERBASE_GETDEFAULTNET_CONTEXT_H */ diff --git a/frameworks/js/napi/connection/async_context/src/getaddressbyname_context.cpp b/frameworks/js/napi/connection/async_context/src/getaddressbyname_context.cpp new file mode 100644 index 0000000000000000000000000000000000000000..b39685263b0ed06e46f1cccacdfdd13d00bda9c0 --- /dev/null +++ b/frameworks/js/napi/connection/async_context/src/getaddressbyname_context.cpp @@ -0,0 +1,51 @@ +/* + * 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. + */ + +#include "getaddressbyname_context.h" + +#include "constant.h" +#include "netmanager_base_napi_utils.h" + +namespace OHOS::NetManagerBase { +GetAddressByNameContext::GetAddressByNameContext(napi_env env, EventManager *manager) : BaseContext(env, manager) {} + +void GetAddressByNameContext::ParseParams(napi_value *params, size_t paramsCount) +{ + if (!CheckParamsType(params, paramsCount)) { + return; + } + + host = NapiUtils::GetStringFromValueUtf8(GetEnv(), params[0]); + + if (paramsCount == PARAM_OPTIONS_AND_CALLBACK) { + SetParseOK(SetCallback(params[1]) == napi_ok); + return; + } + SetParseOK(true); +} + +bool GetAddressByNameContext::CheckParamsType(napi_value *params, size_t paramsCount) +{ + if (paramsCount == PARAM_JUST_OPTIONS) { + return NapiUtils::GetValueType(GetEnv(), params[0]) == napi_string; + } + + if (paramsCount == PARAM_OPTIONS_AND_CALLBACK) { + return NapiUtils::GetValueType(GetEnv(), params[0]) == napi_string && + NapiUtils::GetValueType(GetEnv(), params[1]) == napi_function; + } + return false; +} +} // namespace OHOS::NetManagerBase \ No newline at end of file diff --git a/frameworks/js/napi/connection/async_context/src/getdefaultnet_context.cpp b/frameworks/js/napi/connection/async_context/src/getdefaultnet_context.cpp new file mode 100644 index 0000000000000000000000000000000000000000..70f2a5427dc5b625af1c06fcbbc5c73fe0728b06 --- /dev/null +++ b/frameworks/js/napi/connection/async_context/src/getdefaultnet_context.cpp @@ -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. + */ + +#include "getdefaultnet_context.h" + +#include "constant.h" +#include "netmanager_base_napi_utils.h" + +namespace OHOS::NetManagerBase { +GetDefaultNetContext::GetDefaultNetContext(napi_env env, EventManager *manager) : BaseContext(env, manager) {} + +void GetDefaultNetContext::ParseParams(napi_value *params, size_t paramsCount) +{ + if (!CheckParamsType(params, paramsCount)) { + return; + } + + if (paramsCount == PARAM_JUST_CALLBACK) { + SetParseOK(SetCallback(params[0]) == napi_ok); + return; + } + SetParseOK(true); +} + +bool GetDefaultNetContext::CheckParamsType(napi_value *params, size_t paramsCount) +{ + if (paramsCount == PARAM_NONE) { + return true; + } + + if (paramsCount == PARAM_JUST_CALLBACK) { + return NapiUtils::GetValueType(GetEnv(), params[0]) == napi_function; + } + return false; +} +} // namespace OHOS::NetManagerBase \ No newline at end of file diff --git a/frameworks/js/napi/connection/async_work/include/connection_async_work.h b/frameworks/js/napi/connection/async_work/include/connection_async_work.h new file mode 100644 index 0000000000000000000000000000000000000000..9551ea94d28107bda06eea1b334ade9337ff6411 --- /dev/null +++ b/frameworks/js/napi/connection/async_work/include/connection_async_work.h @@ -0,0 +1,55 @@ +/* + * 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 COMMUNICATIONNETMANAGERBASE_CONNECTION_ASYNC_WORK_H +#define COMMUNICATIONNETMANAGERBASE_CONNECTION_ASYNC_WORK_H + +#include "napi/native_api.h" +#include "napi/native_node_api.h" +#include "noncopyable.h" + +namespace OHOS::NetManagerBase { +class ConnectionAsyncWork final { +public: + ACE_DISALLOW_COPY_AND_MOVE(ConnectionAsyncWork); + + ConnectionAsyncWork() = delete; + + ~ConnectionAsyncWork() = delete; + + static void ExecGetDefaultNet(napi_env env, void *data); + + static void GetDefaultNetCallback(napi_env env, napi_status status, void *data); + + class NetHandleAsyncWork final { + public: + ACE_DISALLOW_COPY_AND_MOVE(NetHandleAsyncWork); + + NetHandleAsyncWork() = delete; + + ~NetHandleAsyncWork() = delete; + + static void ExecGetAddressByName(napi_env env, void *data); + + static void GetAddressByNameCallback(napi_env env, napi_status status, void *data); + + static void ExecGetAddressesByName(napi_env env, void *data); + + static void GetAddressesByNameCallback(napi_env env, napi_status status, void *data); + }; +}; +} // namespace OHOS::NetManagerBase + +#endif /* COMMUNICATIONNETMANAGERBASE_CONNECTION_ASYNC_WORK_H */ diff --git a/frameworks/js/napi/connection/async_work/src/connection_async_work.cpp b/frameworks/js/napi/connection/async_work/src/connection_async_work.cpp new file mode 100644 index 0000000000000000000000000000000000000000..570cb688a716dd2223eedc007ce1f2851134fa36 --- /dev/null +++ b/frameworks/js/napi/connection/async_work/src/connection_async_work.cpp @@ -0,0 +1,55 @@ +/* + * 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. + */ + +#include "connection_async_work.h" + +#include "connection_exec.h" +#include "netmanager_base_base_async_work.h" + +namespace OHOS::NetManagerBase { +void ConnectionAsyncWork::ExecGetDefaultNet(napi_env env, void *data) +{ + BaseAsyncWork::ExecAsyncWork(env, data); +} + +void ConnectionAsyncWork::GetDefaultNetCallback(napi_env env, napi_status status, void *data) +{ + BaseAsyncWork::AsyncWorkCallback(env, status, data); +} + +void ConnectionAsyncWork::NetHandleAsyncWork::ExecGetAddressesByName(napi_env env, void *data) +{ + BaseAsyncWork::ExecAsyncWork(env, + data); +} + +void ConnectionAsyncWork::NetHandleAsyncWork::GetAddressesByNameCallback(napi_env env, napi_status status, void *data) +{ + BaseAsyncWork::AsyncWorkCallback(env, status, data); +} + +void ConnectionAsyncWork::NetHandleAsyncWork::ExecGetAddressByName(napi_env env, void *data) +{ + BaseAsyncWork::ExecAsyncWork(env, + data); +} + +void ConnectionAsyncWork::NetHandleAsyncWork::GetAddressByNameCallback(napi_env env, napi_status status, void *data) +{ + BaseAsyncWork::AsyncWorkCallback( + env, status, data); +} +} // namespace OHOS::NetManagerBase \ No newline at end of file diff --git a/frameworks/js/napi/connection/connection_exec/include/connection_exec.h b/frameworks/js/napi/connection/connection_exec/include/connection_exec.h new file mode 100644 index 0000000000000000000000000000000000000000..46e7b9c65875eb6c97b7c8802c13a640b598859a --- /dev/null +++ b/frameworks/js/napi/connection/connection_exec/include/connection_exec.h @@ -0,0 +1,60 @@ +/* + * 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 COMMUNICATIONNETMANAGERBASE_CONNECTION_EXEC_H +#define COMMUNICATIONNETMANAGERBASE_CONNECTION_EXEC_H + +#include "getaddressbyname_context.h" +#include "getdefaultnet_context.h" +#include "napi/native_api.h" +#include "noncopyable.h" + +namespace OHOS::NetManagerBase { +class ConnectionExec final { +public: + ACE_DISALLOW_COPY_AND_MOVE(ConnectionExec); + + ConnectionExec() = delete; + + ~ConnectionExec() = delete; + + static bool ExecGetDefaultNet(GetDefaultNetContext *context); + + static napi_value GetDefaultNetCallback(GetDefaultNetContext *context); + + class NetHandleExec final { + public: + ACE_DISALLOW_COPY_AND_MOVE(NetHandleExec); + + NetHandleExec() = delete; + + ~NetHandleExec() = delete; + + static bool ExecGetAddressByName(GetAddressByNameContext *context); + + static napi_value GetAddressByNameCallback(GetAddressByNameContext *context); + + static bool ExecGetAddressesByName(GetAddressByNameContext *context); + + static napi_value GetAddressesByNameCallback(GetAddressByNameContext *context); + + private: + static napi_value MakeNetAddressJsValue(napi_env env, const NetAddress &address); + }; +}; + +} // namespace OHOS::NetManagerBase + +#endif /* COMMUNICATIONNETMANAGERBASE_CONNECTION_EXEC_H */ diff --git a/frameworks/js/napi/connection/connection_exec/src/connection_exec.cpp b/frameworks/js/napi/connection/connection_exec/src/connection_exec.cpp new file mode 100644 index 0000000000000000000000000000000000000000..a93de68ac95f2ffe95ac9bd5587bcca75f0ae822 --- /dev/null +++ b/frameworks/js/napi/connection/connection_exec/src/connection_exec.cpp @@ -0,0 +1,122 @@ +/* + * 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. + */ + +#include "connection_exec.h" + +#include + +#include "connection_module.h" +#include "constant.h" +#include "netmanager_base_log.h" +#include "netmanager_base_napi_utils.h" +#include "securec.h" + +static constexpr const int MAX_HOST_LEN = 256; + +namespace OHOS::NetManagerBase { +bool ConnectionExec::ExecGetDefaultNet(GetDefaultNetContext *context) +{ + (void)context; + + return true; +} + +napi_value ConnectionExec::GetDefaultNetCallback(GetDefaultNetContext *context) +{ + napi_value netHandle = NapiUtils::CreateObject(context->GetEnv()); + if (NapiUtils::GetValueType(context->GetEnv(), netHandle) != napi_object) { + return NapiUtils::GetUndefined(context->GetEnv()); + } + + std::initializer_list properties = { + DECLARE_NAPI_FUNCTION(ConnectionModule::NetHandle::FUNCTION_GET_ADDRESSES_BY_NAME, + ConnectionModule::NetHandle::GetAddressesByName), + DECLARE_NAPI_FUNCTION(ConnectionModule::NetHandle::FUNCTION_GET_ADDRESS_BY_NAME, + ConnectionModule::NetHandle::GetAddressByName), + }; + NapiUtils::DefineProperties(context->GetEnv(), netHandle, properties); + return netHandle; +} + +bool ConnectionExec::NetHandleExec::ExecGetAddressesByName(GetAddressByNameContext *context) +{ + addrinfo *res = nullptr; + int status = getaddrinfo(context->host.c_str(), nullptr, nullptr, &res); + if (status < 0) { + NETMANAGER_BASE_LOGE("getaddrinfo errno %{public}d %{public}s", errno, strerror(errno)); + return false; + } + + char host[MAX_HOST_LEN] = {0}; + for (addrinfo *tmp = res; tmp != nullptr; tmp = tmp->ai_next) { + (void)memset_s(host, sizeof(host), 0, sizeof(host)); + if (getnameinfo(tmp->ai_addr, tmp->ai_addrlen, host, sizeof(host), nullptr, 0, 0) < 0) { + continue; + } + NETMANAGER_BASE_LOGI("host ip: %{public}s", host); + + NetAddress address; + address.SetAddress(host); + address.SetFamilyBySaFamily(tmp->ai_addr->sa_family); + if (tmp->ai_addr->sa_family == AF_INET) { + auto addr4 = reinterpret_cast(tmp->ai_addr); + address.SetPort(addr4->sin_port); + } else if (tmp->ai_addr->sa_family == AF_INET6) { + auto addr6 = reinterpret_cast(tmp->ai_addr); + address.SetPort(addr6->sin6_port); + } + + context->addresses.emplace_back(address); + } + freeaddrinfo(res); + return true; +} + +napi_value ConnectionExec::NetHandleExec::GetAddressesByNameCallback(GetAddressByNameContext *context) +{ + napi_value addresses = NapiUtils::CreateArray(context->GetEnv(), context->addresses.size()); + for (uint32_t index = 0; index < context->addresses.size(); ++index) { + napi_value obj = MakeNetAddressJsValue(context->GetEnv(), context->addresses[index]); + NapiUtils::SetArrayElement(context->GetEnv(), addresses, index, obj); + } + return addresses; +} + +bool ConnectionExec::NetHandleExec::ExecGetAddressByName(GetAddressByNameContext *context) +{ + return ExecGetAddressesByName(context); +} + +napi_value ConnectionExec::NetHandleExec::GetAddressByNameCallback(GetAddressByNameContext *context) +{ + if (context->addresses.empty()) { + return NapiUtils::GetUndefined(context->GetEnv()); + } + return MakeNetAddressJsValue(context->GetEnv(), context->addresses[0]); +} + +napi_value ConnectionExec::NetHandleExec::MakeNetAddressJsValue(napi_env env, const NetAddress &address) +{ + napi_value obj = NapiUtils::CreateObject(env); + if (NapiUtils::GetValueType(env, obj) != napi_object) { + return NapiUtils::GetUndefined(env); + } + + NapiUtils::SetStringPropertyUtf8(env, obj, KEY_ADDRESS, address.GetAddress()); + NapiUtils::SetUint32Property(env, obj, KEY_FAMILY, address.GetJsValueFamily()); + NapiUtils::SetUint32Property(env, obj, KEY_PORT, address.GetPort()); + return obj; +} +} // namespace OHOS::NetManagerBase diff --git a/frameworks/js/napi/connection/connection_module/include/connection_module.h b/frameworks/js/napi/connection/connection_module/include/connection_module.h new file mode 100644 index 0000000000000000000000000000000000000000..8040c63b0b58534abdd362eb3e0c0fbd4407a5c1 --- /dev/null +++ b/frameworks/js/napi/connection/connection_module/include/connection_module.h @@ -0,0 +1,44 @@ +/* + * 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 COMMUNICATIONNETMANAGERBASE_CONNECTION_MODULE_H +#define COMMUNICATIONNETMANAGERBASE_CONNECTION_MODULE_H + +#include "napi/native_api.h" + +namespace OHOS::NetManagerBase { +class ConnectionModule final { +public: + static constexpr const char *FUNCTION_GET_DEFAULT_NET = "getDefaultNet"; + + static napi_value InitConnectionModule(napi_env env, napi_value exports); + + class NetHandle final { + public: + static constexpr const char *FUNCTION_GET_ADDRESSES_BY_NAME = "getAddressesByName"; + + static constexpr const char *FUNCTION_GET_ADDRESS_BY_NAME = "getAddressByName"; + + static napi_value GetAddressesByName(napi_env env, napi_callback_info info); + + static napi_value GetAddressByName(napi_env env, napi_callback_info info); + }; + +private: + static napi_value GetDefaultNet(napi_env env, napi_callback_info info); +}; +} // namespace OHOS::NetManagerBase + +#endif /* COMMUNICATIONNETMANAGERBASE_CONNECTION_MODULE_H */ diff --git a/frameworks/js/napi/connection/connection_module/src/connection_module.cpp b/frameworks/js/napi/connection/connection_module/src/connection_module.cpp new file mode 100644 index 0000000000000000000000000000000000000000..90fefb5b200c330c86629514a14edb39463b3b2b --- /dev/null +++ b/frameworks/js/napi/connection/connection_module/src/connection_module.cpp @@ -0,0 +1,73 @@ +/* + * 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. + */ + +#include "connection_module.h" + +#include "connection_async_work.h" +#include "getaddressbyname_context.h" +#include "getdefaultnet_context.h" +#include "netmanager_base_module_template.h" + +static constexpr const char *CONNECTION_MODULE_NAME = "net.connection"; + +namespace OHOS::NetManagerBase { +napi_value ConnectionModule::InitConnectionModule(napi_env env, napi_value exports) +{ + std::initializer_list properties = { + DECLARE_NAPI_FUNCTION(FUNCTION_GET_DEFAULT_NET, GetDefaultNet), + }; + NapiUtils::DefineProperties(env, exports, properties); + + return exports; +} + +napi_value ConnectionModule::GetDefaultNet(napi_env env, napi_callback_info info) +{ + return ModuleTemplate::Interface(env, info, FUNCTION_GET_DEFAULT_NET, nullptr, + ConnectionAsyncWork::ExecGetDefaultNet, + ConnectionAsyncWork::GetDefaultNetCallback); +} + +napi_value ConnectionModule::NetHandle::GetAddressesByName(napi_env env, napi_callback_info info) +{ + return ModuleTemplate::Interface( + env, info, FUNCTION_GET_ADDRESSES_BY_NAME, nullptr, + ConnectionAsyncWork::NetHandleAsyncWork::ExecGetAddressesByName, + ConnectionAsyncWork::NetHandleAsyncWork::GetAddressesByNameCallback); +} + +napi_value ConnectionModule::NetHandle::GetAddressByName(napi_env env, napi_callback_info info) +{ + return ModuleTemplate::Interface( + env, info, FUNCTION_GET_ADDRESSES_BY_NAME, nullptr, + ConnectionAsyncWork::NetHandleAsyncWork::ExecGetAddressByName, + ConnectionAsyncWork::NetHandleAsyncWork::GetAddressByNameCallback); +} + +static napi_module g_connectionModule = { + .nm_version = 1, + .nm_flags = 0, + .nm_filename = nullptr, + .nm_register_func = ConnectionModule::InitConnectionModule, + .nm_modname = CONNECTION_MODULE_NAME, + .nm_priv = nullptr, + .reserved = {nullptr}, +}; + +extern "C" __attribute__((constructor)) void RegisterConnectionModule(void) +{ + napi_module_register(&g_connectionModule); +} +} // namespace OHOS::NetManagerBase \ No newline at end of file diff --git a/frameworks/js/napi/connection/constant/include/constant.h b/frameworks/js/napi/connection/constant/include/constant.h new file mode 100644 index 0000000000000000000000000000000000000000..d0d24cf4a0ee9d2146d9affb933f437d201f62f7 --- /dev/null +++ b/frameworks/js/napi/connection/constant/include/constant.h @@ -0,0 +1,28 @@ +/* + * 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 COMMUNICATIONNETMANAGERBASE_CONSTANT_H +#define COMMUNICATIONNETMANAGERBASE_CONSTANT_H + +static constexpr const char *KEY_ADDRESS = "address"; +static constexpr const char *KEY_FAMILY = "family"; +static constexpr const char *KEY_PORT = "port"; + +static constexpr const int PARAM_NONE = 0; +static constexpr const int PARAM_JUST_OPTIONS = 1; +static constexpr const int PARAM_JUST_CALLBACK = 1; +static constexpr const int PARAM_OPTIONS_AND_CALLBACK = 2; + +#endif /* COMMUNICATIONNETMANAGERBASE_CONSTANT_H */ diff --git a/frameworks/js/napi/connection/options/include/net_address.h b/frameworks/js/napi/connection/options/include/net_address.h new file mode 100644 index 0000000000000000000000000000000000000000..4e99c69950c2217c91931f8d6d1e0316a1d325f3 --- /dev/null +++ b/frameworks/js/napi/connection/options/include/net_address.h @@ -0,0 +1,59 @@ +/* + * 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 COMMUNICATIONNETMANAGER_BASE_NET_ADDRESS_H +#define COMMUNICATIONNETMANAGER_BASE_NET_ADDRESS_H + +#include +#include + +namespace OHOS::NetManagerBase { +class NetAddress final { +public: + enum class Family : uint32_t { + IPv4 = 1, + IPv6 = 2, + }; + + NetAddress(); + + ~NetAddress() = default; + + void SetAddress(const std::string &address); + + void SetFamilyByJsValue(uint32_t family); + + void SetFamilyBySaFamily(sa_family_t family); + + void SetPort(uint16_t port); + + [[nodiscard]] const std::string &GetAddress() const; + + [[nodiscard]] uint32_t GetJsValueFamily() const; + + [[nodiscard]] sa_family_t GetSaFamily() const; + + [[nodiscard]] uint16_t GetPort() const; + +private: + std::string address_; + + Family family_; + + uint16_t port_; +}; +} // namespace OHOS::NetManagerBase + +#endif /* COMMUNICATIONNETMANAGER_BASE_NET_ADDRESS_H */ diff --git a/frameworks/js/napi/connection/options/src/net_address.cpp b/frameworks/js/napi/connection/options/src/net_address.cpp new file mode 100644 index 0000000000000000000000000000000000000000..9ad0418164293909452681e8b4c599f55026315e --- /dev/null +++ b/frameworks/js/napi/connection/options/src/net_address.cpp @@ -0,0 +1,67 @@ +/* + * Copyright (C) 2021-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. + */ + +#include "net_address.h" + +namespace OHOS::NetManagerBase { +NetAddress::NetAddress() : family_(Family::IPv4), port_(0) {} + +void NetAddress::SetAddress(const std::string &address) +{ + address_ = address; +} + +void NetAddress::SetFamilyByJsValue(uint32_t family) +{ + if (static_cast(family) == Family::IPv6) { + family_ = Family::IPv6; + } +} + +void NetAddress::SetFamilyBySaFamily(sa_family_t family) +{ + if (family == AF_INET6) { + family_ = Family::IPv6; + } +} + +void NetAddress::SetPort(uint16_t port) +{ + port_ = port; +} + +const std::string &NetAddress::GetAddress() const +{ + return address_; +} + +sa_family_t NetAddress::GetSaFamily() const +{ + if (family_ == Family::IPv6) { + return AF_INET6; + } + return AF_INET; +} + +uint32_t NetAddress::GetJsValueFamily() const +{ + return static_cast(family_); +} + +uint16_t NetAddress::GetPort() const +{ + return port_; +} +} // namespace OHOS::NetManagerBase diff --git a/utils/CMakeLists.txt b/utils/CMakeLists.txt new file mode 100644 index 0000000000000000000000000000000000000000..3522ab324f7b933079ed417a04ffdf8a31b79261 --- /dev/null +++ b/utils/CMakeLists.txt @@ -0,0 +1,23 @@ +# 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. + +add_library( + netmanager_base_utils + SHARED + common_utils/src/netmanager_base_common_utils.cpp + napi_utils/src/netmanager_base_napi_utils.cpp + event_manager/src/netmanager_base_event_listener.cpp + event_manager/src/netmanager_base_event_manager.cpp + base_context/src/netmanager_base_base_context.cpp + module_template/src/netmanager_base_module_template.cpp +) \ No newline at end of file diff --git a/utils/base_async_work/include/netmanager_base_base_async_work.h b/utils/base_async_work/include/netmanager_base_base_async_work.h new file mode 100644 index 0000000000000000000000000000000000000000..9976d5c3e14ca25dacd990b6e8dc4cbfae6d2243 --- /dev/null +++ b/utils/base_async_work/include/netmanager_base_base_async_work.h @@ -0,0 +1,105 @@ +/* + * 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 COMMUNICATIONNETMANAGER_BASE_NETMANAGER_BASE_BASE_ASYNC_WORK_H +#define COMMUNICATIONNETMANAGER_BASE_NETMANAGER_BASE_BASE_ASYNC_WORK_H + +#include + +#include "napi/native_api.h" +#include "napi/native_common.h" +#include "netmanager_base_base_context.h" +#include "netmanager_base_napi_utils.h" +#include "noncopyable.h" + +static constexpr const int PARSE_PARAM_FAILED = -1; + +static constexpr const char *BUSINESS_ERROR_KEY = "code"; + +namespace OHOS::NetManagerBase { +class BaseAsyncWork final { +public: + ACE_DISALLOW_COPY_AND_MOVE(BaseAsyncWork); + + BaseAsyncWork() = delete; + + template static void ExecAsyncWork(napi_env env, void *data) + { + static_assert(std::is_base_of::value); + + (void)env; + + auto context = static_cast(data); + if (!context->IsParseOK()) { + context->SetErrorCode(PARSE_PARAM_FAILED); + return; + } + + if (Executor != nullptr) { + context->SetExecOK(Executor(context)); + } + /* do not have async executor, execOK should be set in sync work */ + } + + template + static void AsyncWorkCallback(napi_env env, napi_status status, void *data) + { + static_assert(std::is_base_of::value); + + if (status != napi_ok) { + return; + } + auto deleter = [](Context *context) { delete context; }; + std::unique_ptr context(static_cast(data), deleter); + size_t argc = 2; + napi_value argv[2] = {nullptr}; + if (context->IsExecOK()) { + argv[0] = NapiUtils::GetUndefined(env); + + if (Callback != nullptr) { + argv[1] = Callback(context.get()); + } else { + argv[1] = NapiUtils::GetUndefined(env); + } + if (argv[1] == nullptr) { + return; + } + } else { + argv[0] = NapiUtils::CreateObject(env); + if (argv[0] == nullptr) { + return; + } + NapiUtils::SetInt32Property(env, argv[0], BUSINESS_ERROR_KEY, context->GetErrorCode()); + + argv[1] = NapiUtils::GetUndefined(env); + } + + if (context->GetDeferred() != nullptr) { + if (context->IsExecOK()) { + napi_resolve_deferred(env, context->GetDeferred(), argv[1]); + } else { + napi_reject_deferred(env, context->GetDeferred(), argv[0]); + } + return; + } + + napi_value func = context->GetCallback(); + napi_value undefined = NapiUtils::GetUndefined(env); + (void)NapiUtils::CallFunction(env, undefined, func, argc, argv); + } +}; +} // namespace OHOS::NetManagerBase + +#endif /* COMMUNICATIONNETMANAGER_BASE_NETMANAGER_BASE_BASE_ASYNC_WORK_H */ diff --git a/utils/base_context/include/netmanager_base_base_context.h b/utils/base_context/include/netmanager_base_base_context.h new file mode 100644 index 0000000000000000000000000000000000000000..8a016952ada8197a5e96f67031cce23fa076372c --- /dev/null +++ b/utils/base_context/include/netmanager_base_base_context.h @@ -0,0 +1,96 @@ +/* + * 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 COMMUNICATIONNETMANAGER_BASE_BASE_CONTEXT_H +#define COMMUNICATIONNETMANAGER_BASE_BASE_CONTEXT_H + +#include + +#include "napi/native_api.h" +#include "napi/native_common.h" +#include "netmanager_base_event_manager.h" +#include "node_api_types.h" +#include "noncopyable.h" + +namespace OHOS::NetManagerBase { +typedef void (*AsyncWorkExecutor)(napi_env env, void *data); + +typedef void (*AsyncWorkCallback)(napi_env env, napi_status status, void *data); + +class BaseContext { +public: + ACE_DISALLOW_COPY_AND_MOVE(BaseContext); + + BaseContext() = delete; + + explicit BaseContext(napi_env env, EventManager *manager); + + virtual ~BaseContext(); + + void SetParseOK(bool parseOK); + + void SetExecOK(bool requestOK); + + void SetErrorCode(int32_t errorCode); + + napi_status SetCallback(napi_value callback); + + void DeleteCallback(); + + void CreateAsyncWork(const std::string &name, AsyncWorkExecutor executor, AsyncWorkCallback callback); + + void DeleteAsyncWork(); + + napi_value CreatePromise(); + + [[nodiscard]] bool IsParseOK() const; + + [[nodiscard]] bool IsExecOK() const; + + [[nodiscard]] napi_env GetEnv() const; + + [[nodiscard]] int32_t GetErrorCode() const; + + [[nodiscard]] napi_value GetCallback() const; + + [[nodiscard]] napi_deferred GetDeferred() const; + + [[nodiscard]] const std::string &GetAsyncWorkName() const; + + void Emit(const std::string &type, const std::pair &argv); + +protected: + EventManager *manager_; + +private: + napi_env env_; + + bool parseOK_; + + bool requestOK_; + + int32_t errorCode_; + + napi_ref callback_; + + napi_async_work asyncWork_; + + napi_deferred deferred_; + + std::string asyncWorkName_; +}; +} // namespace OHOS::NetManagerBase + +#endif /* COMMUNICATIONNETMANAGER_BASE_BASE_CONTEXT_H */ diff --git a/utils/base_context/src/netmanager_base_base_context.cpp b/utils/base_context/src/netmanager_base_base_context.cpp new file mode 100644 index 0000000000000000000000000000000000000000..498f5ee89dfbe0b070bdc840c7dbb7d9d043788e --- /dev/null +++ b/utils/base_context/src/netmanager_base_base_context.cpp @@ -0,0 +1,144 @@ +/* + * 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. + */ + +#include "netmanager_base_base_context.h" + +#include "netmanager_base_napi_utils.h" +#include "node_api.h" + +namespace OHOS::NetManagerBase { +BaseContext::BaseContext(napi_env env, EventManager *manager) + : manager_(manager), + env_(env), + parseOK_(false), + requestOK_(false), + errorCode_(0), + callback_(nullptr), + asyncWork_(nullptr), + deferred_(nullptr) +{ +} + +BaseContext::~BaseContext() +{ + DeleteCallback(); + DeleteAsyncWork(); +} + +void BaseContext::SetParseOK(bool parseOK) +{ + parseOK_ = parseOK; +} + +void BaseContext::SetExecOK(bool requestOK) +{ + requestOK_ = requestOK; +} + +void BaseContext::SetErrorCode(int32_t errorCode) +{ + errorCode_ = errorCode; +} + +napi_status BaseContext::SetCallback(napi_value callback) +{ + if (callback_ != nullptr) { + (void)napi_delete_reference(env_, callback_); + } + return napi_create_reference(env_, callback, 1, &callback_); +} + +void BaseContext::DeleteCallback() +{ + if (callback_ == nullptr) { + return; + } + (void)napi_delete_reference(env_, callback_); + callback_ = nullptr; +} + +void BaseContext::CreateAsyncWork(const std::string &name, AsyncWorkExecutor executor, AsyncWorkCallback callback) +{ + napi_status ret = napi_create_async_work(env_, nullptr, NapiUtils::CreateStringUtf8(env_, name), executor, callback, + this, &asyncWork_); + if (ret != napi_ok) { + return; + } + asyncWorkName_ = name; + (void)napi_queue_async_work(env_, asyncWork_); +} + +void BaseContext::DeleteAsyncWork() +{ + if (asyncWork_ == nullptr) { + return; + } + (void)napi_delete_async_work(env_, asyncWork_); +} + +napi_value BaseContext::CreatePromise() +{ + napi_value result = nullptr; + NAPI_CALL(env_, napi_create_promise(env_, &deferred_, &result)); + return result; +} + +bool BaseContext::IsParseOK() const +{ + return parseOK_; +} + +bool BaseContext::IsExecOK() const +{ + return requestOK_; +} + +napi_env BaseContext::GetEnv() const +{ + return env_; +} + +int32_t BaseContext::GetErrorCode() const +{ + return errorCode_; +} + +napi_value BaseContext::GetCallback() const +{ + if (callback_ == nullptr) { + return nullptr; + } + napi_value callback = nullptr; + NAPI_CALL(env_, napi_get_reference_value(env_, callback_, &callback)); + return callback; +} + +napi_deferred BaseContext::GetDeferred() const +{ + return deferred_; +} + +const std::string &BaseContext::GetAsyncWorkName() const +{ + return asyncWorkName_; +} + +void BaseContext::Emit(const std::string &type, const std::pair &argv) +{ + if (manager_ != nullptr) { + manager_->Emit(type, argv); + } +} +} // namespace OHOS::NetManagerBase diff --git a/utils/common_utils/include/netmanager_base_common_utils.h b/utils/common_utils/include/netmanager_base_common_utils.h new file mode 100644 index 0000000000000000000000000000000000000000..65b37a47e7f28d391072b5f1b5e785d2ef1d0bf8 --- /dev/null +++ b/utils/common_utils/include/netmanager_base_common_utils.h @@ -0,0 +1,30 @@ +/* + * 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 COMMUNICATIONNETMANAGER_BASE_COMMON_UTILS_H +#define COMMUNICATIONNETMANAGER_BASE_COMMON_UTILS_H + +#include +#include + +namespace OHOS::NetManagerBase::CommonUtils { +std::vector Split(const std::string &str, const std::string &sep); + +std::string Strip(const std::string &str, char ch = ' '); + +std::string ToLower(const std::string &s); +} // namespace OHOS::NetManagerBase::CommonUtils + +#endif /* COMMUNICATIONNETMANAGER_BASE_COMMON_UTILS_H */ diff --git a/utils/common_utils/src/netmanager_base_common_utils.cpp b/utils/common_utils/src/netmanager_base_common_utils.cpp new file mode 100644 index 0000000000000000000000000000000000000000..273cd10a9cf15a95034d2a1477f0565bdb957ee5 --- /dev/null +++ b/utils/common_utils/src/netmanager_base_common_utils.cpp @@ -0,0 +1,59 @@ +/* + * 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. + */ + +#include "netmanager_base_common_utils.h" + +#include + +namespace OHOS::NetManagerBase::CommonUtils { +std::vector Split(const std::string &str, const std::string &sep) +{ + std::string s = str; + std::vector res; + while (!s.empty()) { + size_t pos = s.find(sep); + if (pos == std::string::npos) { + res.emplace_back(s); + break; + } + res.emplace_back(s.substr(0, pos)); + s = s.substr(pos + sep.size()); + } + return res; +} + +std::string Strip(const std::string &str, char ch) +{ + int64_t i = 0; + while (i < str.size() && str[i] == ch) { + ++i; + } + int64_t j = static_cast(str.size()) - 1; + while (j > 0 && str[j] == ch) { + --j; + } + if (i >= 0 && i < str.size() && j >= 0 && j < str.size() && j - i + 1 > 0) { + return str.substr(i, j - i + 1); + } + return ""; +} + +std::string ToLower(const std::string &s) +{ + std::string res = s; + std::transform(res.begin(), res.end(), res.begin(), tolower); + return res; +} +} // namespace OHOS::NetManagerBase::CommonUtils \ No newline at end of file diff --git a/utils/event_manager/include/netmanager_base_event_listener.h b/utils/event_manager/include/netmanager_base_event_listener.h new file mode 100644 index 0000000000000000000000000000000000000000..5ce3b17d8ab64ec24978980d4209ac76629c42cf --- /dev/null +++ b/utils/event_manager/include/netmanager_base_event_listener.h @@ -0,0 +1,58 @@ +/* + * 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 COMMUNICATIONNETMANAGER_BASE_EVENT_LISTENER_H +#define COMMUNICATIONNETMANAGER_BASE_EVENT_LISTENER_H + +#include + +#include "napi/native_api.h" +#include "noncopyable.h" + +namespace OHOS::NetManagerBase { +class EventListener { +public: + EventListener() = delete; + + EventListener(const EventListener &listener); + + EventListener(napi_env env, std::string type, napi_value callback, bool once, bool asyncCallback); + + ~EventListener(); + + EventListener &operator=(const EventListener &listener); + + void Emit(const std::string &eventType, size_t argc, napi_value *argv) const; + + [[nodiscard]] bool Match(const std::string &type, napi_value callback) const; + + [[nodiscard]] bool MatchOnce(const std::string &type) const; + + [[nodiscard]] bool IsAsyncCallback() const; + +private: + napi_env env_; + + std::string type_; + + bool once_; + + napi_ref callbackRef_; + + bool asyncCallback_; +}; +} // namespace OHOS::NetManagerBase + +#endif /* COMMUNICATIONNETMANAGER_BASE_EVENT_LISTENER_H */ diff --git a/utils/event_manager/include/netmanager_base_event_manager.h b/utils/event_manager/include/netmanager_base_event_manager.h new file mode 100644 index 0000000000000000000000000000000000000000..b0ae4992b155555583f49966370c6b02bcce8603 --- /dev/null +++ b/utils/event_manager/include/netmanager_base_event_manager.h @@ -0,0 +1,47 @@ +/* + * 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 COMMUNICATIONNETMANAGER_BASE_EVENT_MANAGER_H +#define COMMUNICATIONNETMANAGER_BASE_EVENT_MANAGER_H + +#include +#include + +#include "netmanager_base_event_listener.h" + +namespace OHOS::NetManagerBase { +class EventManager { +public: + EventManager(); + + void AddListener(napi_env env, const std::string &type, napi_value callback, bool once, bool asyncCallback); + + void DeleteListener(const std::string &type, napi_value callback); + + void Emit(const std::string &type, const std::pair &argv); + + void SetData(void *data); + + [[nodiscard]] void *GetData(); + +private: + std::mutex mutex_; + + std::list listeners_; + + void *data_; +}; +} // namespace OHOS::NetManagerBase +#endif /* COMMUNICATIONNETMANAGER_BASE_EVENT_MANAGER_H */ diff --git a/utils/event_manager/src/netmanager_base_event_listener.cpp b/utils/event_manager/src/netmanager_base_event_listener.cpp new file mode 100644 index 0000000000000000000000000000000000000000..288761195985e7299815ba0d7cbc1fa31a6c80fa --- /dev/null +++ b/utils/event_manager/src/netmanager_base_event_listener.cpp @@ -0,0 +1,108 @@ +/* + * 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. + */ + +#include "netmanager_base_event_listener.h" + +#include "netmanager_base_napi_utils.h" + +namespace OHOS::NetManagerBase { +EventListener::EventListener(napi_env env, std::string type, napi_value callback, bool once, bool asyncCallback) + : env_(env), + type_(std::move(type)), + once_(once), + callbackRef_(NapiUtils::CreateReference(env, callback)), + asyncCallback_(asyncCallback) +{ +} + +EventListener::EventListener(const EventListener &listener) +{ + env_ = listener.env_; + type_ = listener.type_; + once_ = listener.once_; + asyncCallback_ = listener.asyncCallback_; + + if (listener.callbackRef_ == nullptr) { + callbackRef_ = nullptr; + return; + } + napi_value callback = NapiUtils::GetReference(listener.env_, listener.callbackRef_); + callbackRef_ = NapiUtils::CreateReference(env_, callback); +} + +EventListener::~EventListener() +{ + if (callbackRef_ != nullptr) { + NapiUtils::DeleteReference(env_, callbackRef_); + } + callbackRef_ = nullptr; +} + +EventListener &EventListener::operator=(const EventListener &listener) +{ + env_ = listener.env_; + type_ = listener.type_; + once_ = listener.once_; + asyncCallback_ = listener.asyncCallback_; + + if (listener.callbackRef_ == nullptr) { + callbackRef_ = nullptr; + return *this; + } + napi_value callback = NapiUtils::GetReference(listener.env_, listener.callbackRef_); + callbackRef_ = NapiUtils::CreateReference(env_, callback); + return *this; +} + +void EventListener::Emit(const std::string &eventType, size_t argc, napi_value *argv) const +{ + if (type_ != eventType) { + return; + } + + if (callbackRef_ == nullptr) { + return; + } + napi_value callback = NapiUtils::GetReference(env_, callbackRef_); + if (NapiUtils::GetValueType(env_, callback) == napi_function) { + (void)NapiUtils::CallFunction(env_, NapiUtils::GetUndefined(env_), callback, argc, argv); + } +} + +bool EventListener::Match(const std::string &type, napi_value callback) const +{ + if (type_ != type) { + return false; + } + + napi_value callback1 = NapiUtils::GetReference(env_, callbackRef_); + bool ret = false; + NAPI_CALL_BASE(env_, napi_strict_equals(env_, callback1, callback, &ret), false); + return ret; +} + +bool EventListener::MatchOnce(const std::string &type) const +{ + if (type_ != type) { + return false; + } + return once_; +} + +bool EventListener::IsAsyncCallback() const +{ + return asyncCallback_; +} +} // namespace OHOS::NetManagerBase diff --git a/utils/event_manager/src/netmanager_base_event_manager.cpp b/utils/event_manager/src/netmanager_base_event_manager.cpp new file mode 100644 index 0000000000000000000000000000000000000000..dca2ff5c6234b085afa021e50d00d1b1e3770789 --- /dev/null +++ b/utils/event_manager/src/netmanager_base_event_manager.cpp @@ -0,0 +1,78 @@ +/* + * 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. + */ + +#include "netmanager_base_event_manager.h" + +#include + +namespace OHOS::NetManagerBase { +static constexpr const int CALLBACK_PARAM_NUM = 1; + +static constexpr const int ASYNC_CALLBACK_PARAM_NUM = 2; + +EventManager::EventManager() : data_(nullptr) {} + +void EventManager::AddListener(napi_env env, + const std::string &type, + napi_value callback, + bool once, + bool asyncCallback) +{ + listeners_.emplace_back(EventListener(env, type, callback, once, asyncCallback)); +} + +void EventManager::DeleteListener(const std::string &type, napi_value callback) +{ + std::lock_guard lock(mutex_); + auto it = + std::remove_if(listeners_.begin(), listeners_.end(), [type, callback](const EventListener &listener) -> bool { + return listener.Match(type, callback); + }); + listeners_.erase(it, listeners_.end()); +} + +void EventManager::Emit(const std::string &type, const std::pair &argv) +{ + std::lock_guard lock(mutex_); + + std::for_each(listeners_.begin(), listeners_.end(), [type, argv](const EventListener &listener) { + if (listener.IsAsyncCallback()) { + /* AsyncCallback(BusinessError error, T data) */ + napi_value arg[ASYNC_CALLBACK_PARAM_NUM] = {argv.first, argv.second}; + listener.Emit(type, ASYNC_CALLBACK_PARAM_NUM, arg); + } else { + /* Callback(T data) */ + napi_value arg[CALLBACK_PARAM_NUM] = {argv.second}; + listener.Emit(type, CALLBACK_PARAM_NUM, arg); + } + }); + + auto it = std::remove_if(listeners_.begin(), listeners_.end(), + [type](const EventListener &listener) -> bool { return listener.MatchOnce(type); }); + listeners_.erase(it, listeners_.end()); +} + +void EventManager::SetData(void *data) +{ + std::lock_guard lock(mutex_); + data_ = data; +} + +void *EventManager::GetData() +{ + std::lock_guard lock(mutex_); + return data_; +} +} // namespace OHOS::NetManagerBase \ No newline at end of file diff --git a/utils/log/include/netmanager_base_log.h b/utils/log/include/netmanager_base_log.h new file mode 100644 index 0000000000000000000000000000000000000000..f6140040412db96a73777c03f85ae1c883901686 --- /dev/null +++ b/utils/log/include/netmanager_base_log.h @@ -0,0 +1,83 @@ +/* + * 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 COMMUNICATIONNETMANAGER_BASE_NETMANAGER_BASE_LOG +#define COMMUNICATIONNETMANAGER_BASE_NETMANAGER_BASE_LOG + +#include +#include + +#define MAKE_FILE_NAME (strrchr(__FILE__, '/') + 1) + +#if !defined(_WIN32) && !defined(__APPLE__) + +#include "hilog/log.h" + +#define NETMANAGER_BASE_LOG_TAG "NetMgrSubsystem" + +#define NETMANAGER_BASE_LOG_DOMAIN 0xD0015B0 + +static constexpr OHOS::HiviewDFX::HiLogLabel NETMANAGER_BASE_LOG_LABEL = {LOG_CORE, NETMANAGER_BASE_LOG_DOMAIN, NETMANAGER_BASE_LOG_TAG}; + +#define NETMANAGER_BASE_HILOG_PRINT(Level, fmt, ...) \ + (void)OHOS::HiviewDFX::HiLog::Level(NETMANAGER_BASE_LOG_LABEL, "NETMANAGER_BASE [%{public}s %{public}d] " fmt, MAKE_FILE_NAME, \ + __LINE__, ##__VA_ARGS__) + +#else + +#include +#include + +#include "securec.h" + +static constexpr uint32_t NETMANAGER_BASE_MAX_BUFFER_SIZE = 4096; + +static void NetManagerBaseStripFormatString(const std::string &prefix, std::string &str) +{ + for (auto pos = str.find(prefix, 0); pos != std::string::npos; pos = str.find(prefix, pos)) { + str.erase(pos, prefix.size()); + } +} + +static void NetManagerBasePrintLog(const char *fmt, ...) +{ + std::string newFmt(fmt); + NetManagerBaseStripFormatString("{public}", newFmt); + NetManagerBaseStripFormatString("{private}", newFmt); + + va_list args; + va_start(args, fmt); + + char buf[NETMANAGER_BASE_MAX_BUFFER_SIZE] = {0}; + int ret = vsnprintf_s(buf, sizeof(buf), sizeof(buf) - 1, newFmt.c_str(), args); + if (ret < 0) { + return; + } + va_end(args); + + printf("%s\r\n", buf); + fflush(stdout); +} + +#define NETMANAGER_BASE_HILOG_PRINT(Level, fmt, ...) \ + NetManagerBasePrintLog("NETMANAGER_BASE %s [%s %d] " fmt, #Level, MAKE_FILE_NAME, __LINE__, ##__VA_ARGS__) + +#endif /* !defined(_WIN32) && !defined(__APPLE__) */ + +#define NETMANAGER_BASE_LOGE(fmt, ...) NETMANAGER_BASE_HILOG_PRINT(Error, fmt, ##__VA_ARGS__) + +#define NETMANAGER_BASE_LOGI(fmt, ...) NETMANAGER_BASE_HILOG_PRINT(Info, fmt, ##__VA_ARGS__) + +#endif /* COMMUNICATIONNETMANAGER_BASE_NETMANAGER_BASE_LOG */ \ No newline at end of file diff --git a/utils/module_template/include/netmanager_base_module_template.h b/utils/module_template/include/netmanager_base_module_template.h new file mode 100644 index 0000000000000000000000000000000000000000..e2f300beabd65120551901a9623b25ec3332c2d4 --- /dev/null +++ b/utils/module_template/include/netmanager_base_module_template.h @@ -0,0 +1,107 @@ +/* + * 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 COMMUNICATIONNETMANAGER_BASE_NETMANAGER_BASE_MODULE_TEMPLATE_H +#define COMMUNICATIONNETMANAGER_BASE_NETMANAGER_BASE_MODULE_TEMPLATE_H + +#include + +#include "netmanager_base_base_async_work.h" +#include "netmanager_base_base_context.h" +#include "netmanager_base_log.h" + +#define MAX_PARAM_NUM 64 + +namespace OHOS::NetManagerBase::ModuleTemplate { +typedef void (*Finalizer)(napi_env, void *data, void *); + +template +napi_value Interface(napi_env env, + napi_callback_info info, + const std::string &asyncWorkName, + bool (*Work)(napi_env, napi_value, Context *), + AsyncWorkExecutor executor, + AsyncWorkCallback callback) +{ + static_assert(std::is_base_of::value); + + napi_value thisVal = nullptr; + size_t paramsCount = MAX_PARAM_NUM; + napi_value params[MAX_PARAM_NUM] = {nullptr}; + NAPI_CALL(env, napi_get_cb_info(env, info, ¶msCount, params, &thisVal, nullptr)); + + EventManager *manager = nullptr; + napi_unwrap(env, thisVal, reinterpret_cast(&manager)); + + auto context = new Context(env, manager); + context->ParseParams(params, paramsCount); + NETMANAGER_BASE_LOGE("js params parse OK ? %{public}d", context->IsParseOK()); + if (Work != nullptr) { + if (!Work(env, thisVal, context)) { + NETMANAGER_BASE_LOGE("work failed error code = %{public}d", context->GetErrorCode()); + } + } + + context->CreateAsyncWork(asyncWorkName, executor, callback); + if (NapiUtils::GetValueType(env, context->GetCallback()) != napi_function) { + return context->CreatePromise(); + } + return NapiUtils::GetUndefined(env); +} + +template +napi_value + InterfaceWithOutAsyncWork(napi_env env, napi_callback_info info, bool (*Work)(napi_env, napi_value, Context *)) +{ + static_assert(std::is_base_of::value); + + napi_value thisVal = nullptr; + size_t paramsCount = MAX_PARAM_NUM; + napi_value params[MAX_PARAM_NUM] = {nullptr}; + NAPI_CALL(env, napi_get_cb_info(env, info, ¶msCount, params, &thisVal, nullptr)); + + EventManager *manager = nullptr; + napi_unwrap(env, thisVal, reinterpret_cast(&manager)); + + auto context = new Context(env, manager); + context->ParseParams(params, paramsCount); + if (Work != nullptr) { + if (!Work(env, thisVal, context)) { + NETMANAGER_BASE_LOGE("work failed error code = %{public}d", context->GetErrorCode()); + } + } + + if (NapiUtils::GetValueType(env, context->GetCallback()) != napi_function) { + return context->CreatePromise(); + } + return NapiUtils::GetUndefined(env); +} + +napi_value + On(napi_env env, napi_callback_info info, const std::initializer_list &events, bool asyncCallback); + +napi_value + Once(napi_env env, napi_callback_info info, const std::initializer_list &events, bool asyncCallback); + +napi_value Off(napi_env env, napi_callback_info info, const std::initializer_list &events); + +void DefineClass(napi_env env, + napi_value exports, + const std::initializer_list &properties, + const std::string &className); + +napi_value NewInstance(napi_env env, napi_callback_info info, const std::string &className, Finalizer finalizer); +} // namespace OHOS::NetManagerBase::ModuleTemplate +#endif /* COMMUNICATIONNETMANAGER_BASE_NETMANAGER_BASE_MODULE_TEMPLATE_H */ diff --git a/utils/module_template/src/netmanager_base_module_template.cpp b/utils/module_template/src/netmanager_base_module_template.cpp new file mode 100644 index 0000000000000000000000000000000000000000..69b95fbb0e6c2172beb983404685cd6f867abb04 --- /dev/null +++ b/utils/module_template/src/netmanager_base_module_template.cpp @@ -0,0 +1,129 @@ +/* + * 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. + */ + +#include "netmanager_base_module_template.h" + +#include + +namespace OHOS::NetManagerBase::ModuleTemplate { +static constexpr const int EVENT_PARAM_NUM = 2; + +napi_value + On(napi_env env, napi_callback_info info, const std::initializer_list &events, bool asyncCallback) +{ + napi_value thisVal = nullptr; + size_t paramsCount = EVENT_PARAM_NUM; + napi_value params[EVENT_PARAM_NUM] = {nullptr}; + NAPI_CALL(env, napi_get_cb_info(env, info, ¶msCount, params, &thisVal, nullptr)); + + std::string event = NapiUtils::GetStringFromValueUtf8(env, params[0]); + if (paramsCount != EVENT_PARAM_NUM || std::find(events.begin(), events.end(), event) == events.end()) { + return NapiUtils::GetUndefined(env); + } + + EventManager *manager = nullptr; + napi_unwrap(env, thisVal, reinterpret_cast(&manager)); + if (manager != nullptr) { + manager->AddListener(env, event, params[1], false, asyncCallback); + } + + return NapiUtils::GetUndefined(env); +} + +napi_value + Once(napi_env env, napi_callback_info info, const std::initializer_list &events, bool asyncCallback) +{ + napi_value thisVal = nullptr; + size_t paramsCount = EVENT_PARAM_NUM; + napi_value params[EVENT_PARAM_NUM] = {nullptr}; + NAPI_CALL(env, napi_get_cb_info(env, info, ¶msCount, params, &thisVal, nullptr)); + + std::string event = NapiUtils::GetStringFromValueUtf8(env, params[0]); + if (paramsCount != EVENT_PARAM_NUM || std::find(events.begin(), events.end(), event) == events.end()) { + return NapiUtils::GetUndefined(env); + } + + EventManager *manager = nullptr; + napi_unwrap(env, thisVal, reinterpret_cast(&manager)); + if (manager != nullptr) { + manager->AddListener(env, event, params[1], true, asyncCallback); + } + + return NapiUtils::GetUndefined(env); +} + +napi_value Off(napi_env env, napi_callback_info info, const std::initializer_list &events) +{ + napi_value thisVal = nullptr; + size_t paramsCount = EVENT_PARAM_NUM; + napi_value params[EVENT_PARAM_NUM] = {nullptr}; + NAPI_CALL(env, napi_get_cb_info(env, info, ¶msCount, params, &thisVal, nullptr)); + + std::string event = NapiUtils::GetStringFromValueUtf8(env, params[0]); + if (paramsCount != EVENT_PARAM_NUM || std::find(events.begin(), events.end(), event) == events.end()) { + return NapiUtils::GetUndefined(env); + } + + EventManager *manager = nullptr; + napi_unwrap(env, thisVal, reinterpret_cast(&manager)); + if (manager != nullptr) { + manager->DeleteListener(event, params[1]); + } + + return NapiUtils::GetUndefined(env); +} + +void DefineClass(napi_env env, + napi_value exports, + const std::initializer_list &properties, + const std::string &className) +{ + auto constructor = [](napi_env env, napi_callback_info info) -> napi_value { + napi_value thisVal = nullptr; + NAPI_CALL(env, napi_get_cb_info(env, info, nullptr, nullptr, &thisVal, nullptr)); + + return thisVal; + }; + + napi_value jsConstructor = nullptr; + + napi_property_descriptor descriptors[properties.size()]; + std::copy(properties.begin(), properties.end(), descriptors); + + NAPI_CALL_RETURN_VOID(env, napi_define_class(env, className.c_str(), NAPI_AUTO_LENGTH, constructor, nullptr, + properties.size(), descriptors, &jsConstructor)); + + NapiUtils::SetNamedProperty(env, exports, className, jsConstructor); +} + +napi_value NewInstance(napi_env env, napi_callback_info info, const std::string &className, Finalizer finalizer) +{ + napi_value thisVal = nullptr; + NAPI_CALL(env, napi_get_cb_info(env, info, nullptr, nullptr, &thisVal, nullptr)); + + napi_value jsConstructor = NapiUtils::GetNamedProperty(env, thisVal, className); + if (NapiUtils::GetValueType(env, jsConstructor) == napi_undefined) { + return nullptr; + } + + napi_value result = nullptr; + NAPI_CALL(env, napi_new_instance(env, jsConstructor, 0, nullptr, &result)); + + auto manager = new EventManager(); + napi_wrap(env, result, reinterpret_cast(manager), finalizer, nullptr, nullptr); + + return result; +} +} // namespace OHOS::NetManagerBase::ModuleTemplate \ No newline at end of file diff --git a/utils/napi_utils/include/netmanager_base_napi_utils.h b/utils/napi_utils/include/netmanager_base_napi_utils.h new file mode 100644 index 0000000000000000000000000000000000000000..0a51cac9e92d35d5afa5d3b1f17bda1a417d9698 --- /dev/null +++ b/utils/napi_utils/include/netmanager_base_napi_utils.h @@ -0,0 +1,105 @@ +/* + * 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 COMMUNICATIONNETMANAGER_BASE_NETMANAGER_BASE_NAPI_UTILS_H +#define COMMUNICATIONNETMANAGER_BASE_NETMANAGER_BASE_NAPI_UTILS_H + +#include +#include + +#include "napi/native_api.h" +#include "napi/native_common.h" + +namespace OHOS::NetManagerBase::NapiUtils { +napi_valuetype GetValueType(napi_env env, napi_value value); + +/* named property */ +bool HasNamedProperty(napi_env env, napi_value object, const std::string &propertyName); + +napi_value GetNamedProperty(napi_env env, napi_value object, const std::string &propertyName); + +void SetNamedProperty(napi_env env, napi_value object, const std::string &name, napi_value value); + +std::vector GetPropertyNames(napi_env env, napi_value object); + +/* UINT32 */ +napi_value CreateUint32(napi_env env, uint32_t code); + +uint32_t GetUint32FromValue(napi_env env, napi_value value); + +uint32_t GetUint32Property(napi_env env, napi_value object, const std::string &propertyName); + +void SetUint32Property(napi_env env, napi_value object, const std::string &name, uint32_t value); + +/* INT32 */ +napi_value CreateInt32(napi_env env, int32_t code); + +int32_t GetInt32FromValue(napi_env env, napi_value value); + +int32_t GetInt32Property(napi_env env, napi_value object, const std::string &propertyName); + +void SetInt32Property(napi_env env, napi_value object, const std::string &name, int32_t value); + +/* String UTF8 */ +napi_value CreateStringUtf8(napi_env env, const std::string &str); + +std::string GetStringFromValueUtf8(napi_env env, napi_value value); + +std::string GetStringPropertyUtf8(napi_env env, napi_value object, const std::string &propertyName); + +void SetStringPropertyUtf8(napi_env env, napi_value object, const std::string &name, const std::string &value); + +/* array buffer */ +bool ValueIsArrayBuffer(napi_env env, napi_value value); + +void *GetInfoFromArrayBufferValue(napi_env env, napi_value value, size_t *length); + +napi_value CreateArrayBuffer(napi_env env, size_t length, void **data); + +/* object */ +napi_value CreateObject(napi_env env); + +/* undefined */ +napi_value GetUndefined(napi_env env); + +/* function */ +napi_value CallFunction(napi_env env, napi_value recv, napi_value func, size_t argc, const napi_value *argv); + +napi_value CreateFunction(napi_env env, const std::string &name, napi_callback func, void *arg); + +/* reference */ +napi_ref CreateReference(napi_env env, napi_value callback); + +napi_value GetReference(napi_env env, napi_ref callbackRef); + +void DeleteReference(napi_env env, napi_ref callbackRef); + +/* boolean */ +bool GetBooleanProperty(napi_env env, napi_value object, const std::string &propertyName); + +void SetBooleanProperty(napi_env env, napi_value object, const std::string &name, bool value); + +/* define properties */ +void DefineProperties(napi_env env, + napi_value object, + const std::initializer_list &properties); + +/* array */ +napi_value CreateArray(napi_env env, size_t length); + +void SetArrayElement(napi_env env, napi_value array, uint32_t index, napi_value value); +} // namespace OHOS::NetManagerBase::NapiUtils + +#endif /* COMMUNICATIONNETMANAGER_BASE_NETMANAGER_BASE_NAPI_UTILS_H */ diff --git a/utils/napi_utils/src/netmanager_base_napi_utils.cpp b/utils/napi_utils/src/netmanager_base_napi_utils.cpp new file mode 100644 index 0000000000000000000000000000000000000000..0ff702fd029743f184b43f9310a558a0c011a694 --- /dev/null +++ b/utils/napi_utils/src/netmanager_base_napi_utils.cpp @@ -0,0 +1,323 @@ +/* + * 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. + */ + +#include "netmanager_base_napi_utils.h" + +#include +#include +#include + +#include "securec.h" + +namespace OHOS::NetManagerBase::NapiUtils { +static constexpr const int MAX_STRING_LENGTH = 65536; + +napi_valuetype GetValueType(napi_env env, napi_value value) +{ + if (value == nullptr) { + return napi_undefined; + } + + napi_valuetype valueType = napi_undefined; + NAPI_CALL_BASE(env, napi_typeof(env, value, &valueType), napi_undefined); + return valueType; +} + +/* named property */ +bool HasNamedProperty(napi_env env, napi_value object, const std::string &propertyName) +{ + bool hasProperty = false; + NAPI_CALL_BASE(env, napi_has_named_property(env, object, propertyName.c_str(), &hasProperty), false); + return hasProperty; +} + +napi_value GetNamedProperty(napi_env env, napi_value object, const std::string &propertyName) +{ + napi_value value = nullptr; + NAPI_CALL(env, napi_get_named_property(env, object, propertyName.c_str(), &value)); + return value; +} + +void SetNamedProperty(napi_env env, napi_value object, const std::string &name, napi_value value) +{ + (void)napi_set_named_property(env, object, name.c_str(), value); +} + +std::vector GetPropertyNames(napi_env env, napi_value object) +{ + std::vector ret; + napi_value names = nullptr; + NAPI_CALL_BASE(env, napi_get_property_names(env, object, &names), ret); + uint32_t length = 0; + NAPI_CALL_BASE(env, napi_get_array_length(env, names, &length), ret); + for (uint32_t index = 0; index < length; ++index) { + napi_value name = nullptr; + if (napi_get_element(env, names, index, &name) != napi_ok) { + continue; + } + if (GetValueType(env, name) != napi_string) { + continue; + } + ret.emplace_back(GetStringFromValueUtf8(env, name)); + } + return ret; +} + +/* UINT32 */ +napi_value CreateUint32(napi_env env, uint32_t code) +{ + napi_value value = nullptr; + if (napi_create_uint32(env, code, &value) != napi_ok) { + return nullptr; + } + return value; +} + +uint32_t GetUint32FromValue(napi_env env, napi_value value) +{ + uint32_t ret = 0; + NAPI_CALL_BASE(env, napi_get_value_uint32(env, value, &ret), 0); + return ret; +} + +uint32_t GetUint32Property(napi_env env, napi_value object, const std::string &propertyName) +{ + if (!HasNamedProperty(env, object, propertyName)) { + return 0; + } + napi_value value = GetNamedProperty(env, object, propertyName); + return GetUint32FromValue(env, value); +} + +void SetUint32Property(napi_env env, napi_value object, const std::string &name, uint32_t value) +{ + napi_value jsValue = CreateUint32(env, value); + if (GetValueType(env, jsValue) != napi_number) { + return; + } + + napi_set_named_property(env, object, name.c_str(), jsValue); +} + +/* INT32 */ +napi_value CreateInt32(napi_env env, int32_t code) +{ + napi_value value = nullptr; + if (napi_create_int32(env, code, &value) != napi_ok) { + return nullptr; + } + return value; +} + +int32_t GetInt32FromValue(napi_env env, napi_value value) +{ + int32_t ret = 0; + NAPI_CALL_BASE(env, napi_get_value_int32(env, value, &ret), 0); + return ret; +} + +int32_t GetInt32Property(napi_env env, napi_value object, const std::string &propertyName) +{ + if (!HasNamedProperty(env, object, propertyName)) { + return 0; + } + napi_value value = GetNamedProperty(env, object, propertyName); + return GetInt32FromValue(env, value); +} + +void SetInt32Property(napi_env env, napi_value object, const std::string &name, int32_t value) +{ + napi_value jsValue = CreateInt32(env, value); + if (GetValueType(env, jsValue) != napi_number) { + return; + } + + napi_set_named_property(env, object, name.c_str(), jsValue); +} + +/* String UTF8 */ +napi_value CreateStringUtf8(napi_env env, const std::string &str) +{ + napi_value value = nullptr; + if (napi_create_string_utf8(env, str.c_str(), strlen(str.c_str()), &value) != napi_ok) { + return nullptr; + } + return value; +} + +std::string GetStringFromValueUtf8(napi_env env, napi_value value) +{ + std::string result; + auto deleter = [](char *s) { free(reinterpret_cast(s)); }; + std::unique_ptr str(static_cast(malloc(MAX_STRING_LENGTH)), deleter); + (void)memset_s(str.get(), MAX_STRING_LENGTH, 0, MAX_STRING_LENGTH); + size_t length = 0; + NAPI_CALL_BASE(env, napi_get_value_string_utf8(env, value, str.get(), MAX_STRING_LENGTH, &length), result); + if (length > 0) { + return result.append(str.get(), length); + } + return result; +} + +std::string GetStringPropertyUtf8(napi_env env, napi_value object, const std::string &propertyName) +{ + if (!HasNamedProperty(env, object, propertyName)) { + return ""; + } + napi_value value = GetNamedProperty(env, object, propertyName); + return GetStringFromValueUtf8(env, value); +} + +void SetStringPropertyUtf8(napi_env env, napi_value object, const std::string &name, const std::string &value) +{ + napi_value jsValue = CreateStringUtf8(env, value); + if (GetValueType(env, jsValue) != napi_string) { + return; + } + napi_set_named_property(env, object, name.c_str(), jsValue); +} + +/* array buffer */ +bool ValueIsArrayBuffer(napi_env env, napi_value value) +{ + bool isArrayBuffer = false; + NAPI_CALL_BASE(env, napi_is_arraybuffer(env, value, &isArrayBuffer), false); + return isArrayBuffer; +} + +void *GetInfoFromArrayBufferValue(napi_env env, napi_value value, size_t *length) +{ + if (length == nullptr) { + return nullptr; + } + + void *data = nullptr; + NAPI_CALL(env, napi_get_arraybuffer_info(env, value, &data, length)); + return data; +} + +napi_value CreateArrayBuffer(napi_env env, size_t length, void **data) +{ + if (length == 0) { + return nullptr; + } + napi_value result = nullptr; + NAPI_CALL(env, napi_create_arraybuffer(env, length, data, &result)); + return result; +} + +/* object */ +napi_value CreateObject(napi_env env) +{ + napi_value object = nullptr; + NAPI_CALL(env, napi_create_object(env, &object)); + return object; +} + +/* undefined */ +napi_value GetUndefined(napi_env env) +{ + napi_value undefined = nullptr; + NAPI_CALL(env, napi_get_undefined(env, &undefined)); + return undefined; +} + +/* function */ +napi_value CallFunction(napi_env env, napi_value recv, napi_value func, size_t argc, const napi_value *argv) +{ + napi_value res = nullptr; + NAPI_CALL(env, napi_call_function(env, recv, func, argc, argv, &res)); + return res; +} + +napi_value CreateFunction(napi_env env, const std::string &name, napi_callback func, void *arg) +{ + napi_value res = nullptr; + NAPI_CALL(env, napi_create_function(env, name.c_str(), strlen(name.c_str()), func, arg, &res)); + return res; +} + +/* reference */ +napi_ref CreateReference(napi_env env, napi_value callback) +{ + napi_ref callbackRef = nullptr; + NAPI_CALL(env, napi_create_reference(env, callback, 1, &callbackRef)); + return callbackRef; +} + +napi_value GetReference(napi_env env, napi_ref callbackRef) +{ + napi_value callback = nullptr; + NAPI_CALL(env, napi_get_reference_value(env, callbackRef, &callback)); + return callback; +} + +void DeleteReference(napi_env env, napi_ref callbackRef) +{ + (void)napi_delete_reference(env, callbackRef); +} + +/* boolean */ +bool GetBooleanProperty(napi_env env, napi_value object, const std::string &propertyName) +{ + if (!HasNamedProperty(env, object, propertyName)) { + return false; + } + napi_value value = GetNamedProperty(env, object, propertyName); + bool ret = false; + NAPI_CALL_BASE(env, napi_get_value_bool(env, value, &ret), false); + return ret; +} + +void SetBooleanProperty(napi_env env, napi_value object, const std::string &name, bool value) +{ + napi_value jsValue = nullptr; + NAPI_CALL_RETURN_VOID(env, napi_get_boolean(env, value, &jsValue)); + if (GetValueType(env, jsValue) != napi_boolean) { + return; + } + + napi_set_named_property(env, object, name.c_str(), jsValue); +} + +/* define properties */ +void DefineProperties(napi_env env, + napi_value object, + const std::initializer_list &properties) +{ + napi_property_descriptor descriptors[properties.size()]; + std::copy(properties.begin(), properties.end(), descriptors); + + (void)napi_define_properties(env, object, properties.size(), descriptors); +} + +/* array */ +napi_value CreateArray(napi_env env, size_t length) +{ + if (length == 0) { + napi_value res = nullptr; + NAPI_CALL(env, napi_create_array(env, &res)); + return res; + } + napi_value res = nullptr; + NAPI_CALL(env, napi_create_array_with_length(env, length, &res)); + return res; +} + +void SetArrayElement(napi_env env, napi_value array, uint32_t index, napi_value value) +{ + (void)napi_set_element(env, array, index, value); +} +} // namespace OHOS::NetManagerBase::NapiUtils \ No newline at end of file