From 1c3365da2fbfdf28294796ad0f64e09cd64ec1df Mon Sep 17 00:00:00 2001 From: x00456388 Date: Fri, 17 Dec 2021 17:00:20 +0800 Subject: [PATCH 01/14] sendfile feature Signed-off-by: x00456388 --- .../include/device/device_manager_agent.h | 76 +++++++++++++++++ .../include/network/base_session.h | 40 +++++++++ .../include/network/network_agent_template.h | 83 +++++++++++++++++++ .../include/network/session_pool.h | 49 +++++++++++ .../include/network/softbus/softbus_agent.h | 49 +++++++++++ .../include/network/softbus/softbus_session.h | 46 ++++++++++ .../softbus/softbus_session_dispatcher.h | 45 ++++++++++ .../network/softbus/softbus_session_name.h | 40 +++++++++ 8 files changed, 428 insertions(+) create mode 100644 services/distributedfileservice/include/device/device_manager_agent.h create mode 100644 services/distributedfileservice/include/network/base_session.h create mode 100644 services/distributedfileservice/include/network/network_agent_template.h create mode 100644 services/distributedfileservice/include/network/session_pool.h create mode 100644 services/distributedfileservice/include/network/softbus/softbus_agent.h create mode 100644 services/distributedfileservice/include/network/softbus/softbus_session.h create mode 100644 services/distributedfileservice/include/network/softbus/softbus_session_dispatcher.h create mode 100644 services/distributedfileservice/include/network/softbus/softbus_session_name.h diff --git a/services/distributedfileservice/include/device/device_manager_agent.h b/services/distributedfileservice/include/device/device_manager_agent.h new file mode 100644 index 000000000..4f9932224 --- /dev/null +++ b/services/distributedfileservice/include/device/device_manager_agent.h @@ -0,0 +1,76 @@ +/* + * Copyright (c) 2021 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 DEVICE_MANAGER_AGENT_H +#define DEVICE_MANAGER_AGENT_H + +#include +#include +#include +#include +#include + +#include "device_info.h" +#include "device_manager.h" +#include "network/network_agent_template.h" +#include "nlohmann/json.hpp" +#include "utils_singleton.h" + +namespace OHOS { +namespace Storage { +namespace DistributedFile { +class DeviceManagerAgent final : public DistributedHardware::DmInitCallback, + public DistributedHardware::DeviceStateCallback, + public std::enable_shared_from_this, + public Utils::Singleton { + DECLARE_SINGLETON(DeviceManagerAgent); + +public: + void Start() override; + void Stop() override; + void JoinGroup(std::weak_ptr mp); + void QuitGroup(std::weak_ptr mp); + + void OnDeviceOnline(const DistributedHardware::DmDeviceInfo &deviceInfo) override; + void OnDeviceOffline(const DistributedHardware::DmDeviceInfo &deviceInfo) override; + void OnDeviceChanged(const DistributedHardware::DmDeviceInfo &deviceInfo) override; + void OnDeviceReady(const DistributedHardware::DmDeviceInfo &deviceInfo) override {} + + void OfflineAllDevice(); + void ReconnectOnlineDevices(); + void AuthGroupOnlineProc(const DeviceInfo info); + void OnRemoteDied() override; + + DeviceInfo &GetLocalDeviceInfo(); + std::vector GetRemoteDevicesInfo(); + +private: + void StartInstance() override; + void StopInstance() override; + + void RegisterToExternalDm(); + void UnregisterFromExternalDm(); + + void AuthGroupOfflineProc(const DeviceInfo &info); + void QueryRelatedGroups(const std::string &networkId, std::vector &groupList); + bool CheckIsAuthGroup(const GroupInfo &group); + void AllAuthGroupsOfflineProc(); + // We use a mutex instead of a shared_mutex to serialize online/offline procedures + std::mutex mpToNetworksMutex_; + std::map> mpToNetworks_; +}; +} // namespace DistributedFile +} // namespace Storage +} // namespace OHOS +#endif // DEVICE_MANAGER_AGENT_H \ No newline at end of file diff --git a/services/distributedfileservice/include/network/base_session.h b/services/distributedfileservice/include/network/base_session.h new file mode 100644 index 000000000..1568d0089 --- /dev/null +++ b/services/distributedfileservice/include/network/base_session.h @@ -0,0 +1,40 @@ +/* + * Copyright (c) 2021 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 BASE_SESSION_H +#define BASE_SESSION_H + +#include +#include + +namespace OHOS { +namespace Storage { +namespace DistributedFile { +constexpr int KEY_SIZE_MAX = 32; + +class BaseSession { +public: + virtual ~BaseSession() = default; + virtual bool IsFromServer() const = 0; + virtual std::string GetCid() const = 0; + virtual int32_t GetHandle() const = 0; + virtual std::array GetKey() const = 0; + virtual void Release() const = 0; + virtual void DisableSessionListener() const = 0; +}; +} // namespace DistributedFile +} // namespace Storage +} // namespace OHOS +#endif // BASE_SESSION_H \ No newline at end of file diff --git a/services/distributedfileservice/include/network/network_agent_template.h b/services/distributedfileservice/include/network/network_agent_template.h new file mode 100644 index 000000000..d878472cb --- /dev/null +++ b/services/distributedfileservice/include/network/network_agent_template.h @@ -0,0 +1,83 @@ +/* + * Copyright (c) 2021 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 NETWORK_AGENT_TEMPLATE_H +#define NETWORK_AGENT_TEMPLATE_H + +#include +#include +#include +#include + +#include "device/device_info.h" +#include "mountpoint/mount_point.h" +#include "network/kernel_talker.h" +#include "network/session_pool.h" +#include "utils_actor.h" +#include "utils_dfs_thread.h" +#include "utils_startable.h" + +namespace OHOS { +namespace Storage { +namespace DistributedFile { +class NetworkAgentTemplate : public Startable, public Actor { +public: + explicit NetworkAgentTemplate(std::weak_ptr mountPoint) + : Actor(this), + mountPoint_(mountPoint), + kernerlTalker_( + mountPoint, + [&](NotifyParam ¶m) { GetSessionProcess(param); }, + [&](const std::string &cid) { CloseSessionForOneDevice(cid); }), + sessionPool_(kernerlTalker_) + { + } + virtual ~NetworkAgentTemplate() {} + void Start(); + void Stop(); + void ConnectOnlineDevices(); + void DisconnectAllDevices(); + void ConnectDeviceAsync(const DeviceInfo info); + void DisconnectDevice(const DeviceInfo info); + void AcceptSession(std::shared_ptr session); + +protected: + virtual void JoinDomain() = 0; + virtual void QuitDomain() = 0; + virtual void StopTopHalf() = 0; + virtual void StopBottomHalf() = 0; + virtual void OpenSession(const DeviceInfo &info) = 0; + virtual void CloseSession(std::shared_ptr session) = 0; + + std::weak_ptr mountPoint_; + +private: + void HandleAllNotify(int fd); + void NotifyHandler(NotifyParam ¶m); + void GetSessionProcess(NotifyParam ¶m); + void GetSession(const std::string &cid); + void CloseSessionForOneDevice(const std::string &cid); + void AcceptSessionInner(std::shared_ptr session); + void GetSessionProcessInner(NotifyParam param); + + std::mutex taskMut_; + std::list tasks_; + KernelTalker kernerlTalker_; + SessionPool sessionPool_; +}; +} // namespace DistributedFile +} // namespace Storage +} // namespace OHOS +#endif // NETWORK_AGENT_TEMPLATE_H \ No newline at end of file diff --git a/services/distributedfileservice/include/network/session_pool.h b/services/distributedfileservice/include/network/session_pool.h new file mode 100644 index 000000000..b8ff96a83 --- /dev/null +++ b/services/distributedfileservice/include/network/session_pool.h @@ -0,0 +1,49 @@ +/* + * Copyright (c) 2021 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 SESSION_POOL_H +#define SESSION_POOL_H + +#include +#include +#include +#include + +#include "network/base_session.h" +#include "network/kernel_talker.h" + +namespace OHOS { +namespace Storage { +namespace DistributedFile { +class SessionPool final : protected NoCopyable { +public: + explicit SessionPool(KernelTalker &talker) : talker_(talker) {} + ~SessionPool() = default; + void HoldSession(std::shared_ptr session); + void ReleaseSession(const int32_t fd); + void ReleaseSession(const std::string &cid); + void ReleaseAllSession(); + +private: + std::recursive_mutex sessionPoolLock_; + std::list> usrSpaceSessionPool_; + KernelTalker &talker_; + + void AddSessionToPool(std::shared_ptr session); +}; +} // namespace DistributedFile +} // namespace Storage +} // namespace OHOS +#endif // SESSION_POOL_H \ No newline at end of file diff --git a/services/distributedfileservice/include/network/softbus/softbus_agent.h b/services/distributedfileservice/include/network/softbus/softbus_agent.h new file mode 100644 index 000000000..28d88c4b7 --- /dev/null +++ b/services/distributedfileservice/include/network/softbus/softbus_agent.h @@ -0,0 +1,49 @@ +/* + * Copyright (c) 2021 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 SOFTBUS_AGENT_H +#define SOFTBUS_AGENT_H + +#include "network/network_agent_template.h" +#include + +namespace OHOS { +namespace Storage { +namespace DistributedFile { +class SoftbusAgent final : public NetworkAgentTemplate, public std::enable_shared_from_this { +public: + explicit SoftbusAgent(std::weak_ptr mountPoint); + ~SoftbusAgent() = default; + int OnSessionOpened(const int sessionId, const int result); + void OnSessionClosed(int sessionId); + +protected: + void JoinDomain() override; + void QuitDomain() override; + void StopTopHalf() override; + void StopBottomHalf() override; + void OpenSession(const DeviceInfo &info) override; + void CloseSession(std::shared_ptr session) override; + +private: + bool IsContinueRetry(const std::string &cid); + std::map OpenSessionRetriedTimesMap_; + + std::string sessionName_; +}; +} // namespace DistributedFile +} // namespace Storage +} // namespace OHOS +#endif // SOFTBUS_AGENT_H \ No newline at end of file diff --git a/services/distributedfileservice/include/network/softbus/softbus_session.h b/services/distributedfileservice/include/network/softbus/softbus_session.h new file mode 100644 index 000000000..4816c3ead --- /dev/null +++ b/services/distributedfileservice/include/network/softbus/softbus_session.h @@ -0,0 +1,46 @@ +/* + * Copyright (c) 2021 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 SOFTBUS_SESSION_H +#define SOFTBUS_SESSION_H + +#include "network/base_session.h" + +namespace OHOS { +namespace Storage { +namespace DistributedFile { +constexpr int32_t INVALID_SOCKET_FD = -1; +class SoftbusSession final : public BaseSession { +public: + explicit SoftbusSession(int sessionId); + ~SoftbusSession() = default; + bool IsFromServer() const override; + std::string GetCid() const override; + int32_t GetHandle() const override; + std::array GetKey() const override; + void Release() const override; + void DisableSessionListener() const override; + +private: + int sessionId_; + std::string cid_; + int32_t socketFd_{INVALID_SOCKET_FD}; + std::array key_; + bool IsServerSide_; +}; +} // namespace DistributedFile +} // namespace Storage +} // namespace OHOS +#endif // SOFTBUS_SESSION_H \ No newline at end of file diff --git a/services/distributedfileservice/include/network/softbus/softbus_session_dispatcher.h b/services/distributedfileservice/include/network/softbus/softbus_session_dispatcher.h new file mode 100644 index 000000000..fc7e1d9cd --- /dev/null +++ b/services/distributedfileservice/include/network/softbus/softbus_session_dispatcher.h @@ -0,0 +1,45 @@ +/* + * Copyright (c) 2021 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 SOFTBUS_SESSION_DISPATCHER_H +#define SOFTBUS_SESSION_DISPATCHER_H + +#include +#include +#include +#include + +namespace OHOS { +namespace Storage { +namespace DistributedFile { +class SoftbusAgent; +class SoftbusSessionDispatcher final { +public: + SoftbusSessionDispatcher() = delete; + ~SoftbusSessionDispatcher() = delete; + static void RegisterSessionListener(const std::string busName, std::weak_ptr); + static void UnregisterSessionListener(const std::string busName); + static std::weak_ptr GetAgent(int sessionId); + static int OnSessionOpened(int sessionId, int result); + static void OnSessionClosed(int sessionId); + +private: + static std::mutex softbusAgentMutex_; + static std::map> busNameToAgent_; +}; +} // namespace DistributedFile +} // namespace Storage +} // namespace OHOS +#endif // SOFTBUS_SESSION_DISPATCHER_H \ No newline at end of file diff --git a/services/distributedfileservice/include/network/softbus/softbus_session_name.h b/services/distributedfileservice/include/network/softbus/softbus_session_name.h new file mode 100644 index 000000000..87d3b4de3 --- /dev/null +++ b/services/distributedfileservice/include/network/softbus/softbus_session_name.h @@ -0,0 +1,40 @@ +/* + * Copyright (c) 2021 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 SOFTBUS_SESSION_NAME_H +#define SOFTBUS_SESSION_NAME_H + +#include + +namespace OHOS { +namespace Storage { +namespace DistributedFile { +class SoftbusSessionName final { +public: + explicit SoftbusSessionName(std::string path) : path_(path) {} + ~SoftbusSessionName() = default; + std::string ToString() + { + return prefix + path_; + } + +private: + const std::string prefix = "DistributedFileService"; + std::string path_; +}; +} // namespace DistributedFile +} // namespace Storage +} // namespace OHOS +#endif // SOFTBUS_SESSION_NAME_H \ No newline at end of file -- Gitee From 4b0e0afca8d351dfd4467e15c67a9274e0912079 Mon Sep 17 00:00:00 2001 From: x00456388 Date: Mon, 20 Dec 2021 16:12:52 +0800 Subject: [PATCH 02/14] update readme and test case Signed-off-by: x00456388 --- README.md | 32 +- .../test/unittest/BUILD.gn | 3 + test/moduletest/BUILD.gn | 26 +- .../distributedfiledaemon_service_test.cpp | 598 ++++++++++++++++++ 4 files changed, 641 insertions(+), 18 deletions(-) diff --git a/README.md b/README.md index 5c911bb93..b1b425c28 100644 --- a/README.md +++ b/README.md @@ -12,9 +12,9 @@ 其包括如下几个核心模块: -- distributedfiledeamon:分布式文件管理常驻用户态服务,负责接入设备组网、数据传输能力,并负责挂载hmdfs -- distributedfileservice:分布式文件管理按需启动用户态服务,负责为应用在hmdfs中创建专属跨设备文件目录 -- hmdfs(HarMony Didstributed File System):分布式文件管理核心模块,是一种面向移动分布式场景的、高性能的、基于内核实现的、堆叠式文件系统。 +- distributedfiledaemon:分布式文件管理常驻用户态服务,负责接入设备组网、数据传输能力,并负责挂载hmdfs +- distributedfileservice:分布式文件管理服务进程,对应用提供分布式扩展能力 +- hmdfs(Harmony Distributed File System):分布式文件管理核心模块,是一种面向移动分布式场景的、高性能的、基于内核实现的、堆叠式文件系统。 ## 目录 @@ -25,7 +25,15 @@ ├── interfaces // 接口声明 │ └── innerkits // 对内接口声明 ├── services // 服务实现 -│ └── distributedfiledeamon // 常驻服务实现 +│ └── distributedfiledaemon // 常驻服务实现 +| └── include +| └── src + └── device // 设备上下线管理 + └── ipc // daemon进程拉起退出流程以及ipc接口实现 + └── mountpoint // hmdfs挂载管理 + └── network // 软总线和内核会话session交互相关 +| └── test +| └── BUILD.gn | └── distributedfileservice // 三方应用调用流程服务实现 └── utils // 公共组件 ├── log // 日志组件 @@ -54,25 +62,15 @@ - 单目录下最大目录项数 取决于被堆叠文件系统单文件大小。当堆叠f2fs时,假设平均目录长度放大系数为3,则为`3.94TB/4KB*85/3=29,966,344,738`个。 -### 时延 - -多数操作的默认超时时间均为4秒种,以下操作除外: - -- TODO - ## 说明 ### 使用说明 可以使用终端调试分布式文件管理能力。 -在两台设备已经组网的情况下,通过 hdc 进入 `/mnt/hmdfs/0/` 目录,即可看见形如下方所述的目录结构: - -``` -/mnt/hmdfs/0/device_view/local -/mnt/hmdfs/0/device_view/7914943294a41be79c2c4f1f3cb4773c46674c86305cc05b0245dc74f99e0c8d -/mnt/hmdfs/0/merge_view -``` +在多台设备已经组网(同一局域网)的情况下, 并且在经过hichian模块可信认证的设备间,可以建立设备间分布式文件互相访问的能力。 +可以在应用内通过```Context.distributedFileDir()```接口获取本应用沙箱内的分布式路径,然后在此目录下可以进行创建、删除、读写文件和目录。 +在此目录下有```device_view```和```merge_view```两个目录。 device_view 的含义是分设备视图,其下的 local 对应被堆叠的本地文件系统,`79xxx0c8d` 对应相应设备上的本地文件系统。如果在 local 中进行文件系统操作,其影响也将体现在 hmdfs 的源目录,即 `/data/misc_ce/0/hmdfs/storage` 中。如果在 `79xxx0c8d` 中进行文件系统操作,其影响也将体现在对应设备的 hmdfs 的源目录中。 diff --git a/services/distributedfiledaemon/test/unittest/BUILD.gn b/services/distributedfiledaemon/test/unittest/BUILD.gn index e6df95ed9..a76085157 100644 --- a/services/distributedfiledaemon/test/unittest/BUILD.gn +++ b/services/distributedfiledaemon/test/unittest/BUILD.gn @@ -21,6 +21,8 @@ config("module_private_config") { include_dirs = [ "${services_path}/distributedfiledaemon/include", "//foundation/distributedhardware/devicemanager/interfaces/inner_kits/native_cpp/include", + "//base/security/deviceauth/interfaces/innerkits", + "//third_party/json/include", ] } @@ -41,6 +43,7 @@ ohos_unittest("DeviceManagerAgentTest") { "//third_party/googletest:gtest_main", "${utils_path}:libdistributedfileutils", "//foundation/distributedhardware/devicemanager/interfaces/inner_kits/native_cpp:devicemanagersdk", + "//base/security/deviceauth/services:deviceauth_sdk", ] defines = [ diff --git a/test/moduletest/BUILD.gn b/test/moduletest/BUILD.gn index 26350e2a5..d7ff046b9 100644 --- a/test/moduletest/BUILD.gn +++ b/test/moduletest/BUILD.gn @@ -21,6 +21,11 @@ config("module_private_config") { include_dirs = [ "${services_path}/distributedfiledaemon/include", "//foundation/distributedhardware/devicemanager/interfaces/inner_kits/native_cpp/include", + "//foundation/communication/ipc/interfaces/innerkits/ipc_core/include", + "//foundation/communication/dsoftbus/interfaces/kits/bus_center", + "//foundation/communication/dsoftbus/interfaces/kits/common", + "//base/security/deviceauth/interfaces/innerkits", + "//third_party/json/include", ] } @@ -28,7 +33,18 @@ ohos_moduletest("DistributedFileDaemonServiceTest") { module_out_path = module_output_path sources = [ - "${services_path}/distributedfiledaemon/src/mountpoint/mount_point.cpp" + "${services_path}/distributedfiledaemon/src/mountpoint/mount_point.cpp", + "${services_path}/distributedfiledaemon/src/mountpoint/mount_manager.cpp", + "${services_path}/distributedfiledaemon/src/device/device_manager_agent.cpp", + "${services_path}/distributedfiledaemon/src/device/device_info.cpp", + "${services_path}/distributedfiledaemon/src/ipc/daemon_stub.cpp", + "${services_path}/distributedfiledaemon/src/ipc/daemon.cpp", + "${services_path}/distributedfiledaemon/src/network/network_agent_template.cpp", + "${services_path}/distributedfiledaemon/src/network/kernel_talker.cpp", + "${services_path}/distributedfiledaemon/src/network/session_pool.cpp", + "${services_path}/distributedfiledaemon/src/network/softbus/softbus_agent.cpp", + "${services_path}/distributedfiledaemon/src/network/softbus/softbus_session_dispatcher.cpp", + "${services_path}/distributedfiledaemon/src/network/softbus/softbus_session.cpp", ] sources += [ "src/distributedfiledaemon_service_test.cpp" ] @@ -47,6 +63,14 @@ ohos_moduletest("DistributedFileDaemonServiceTest") { "//third_party/googletest:gmock", "${utils_path}:libdistributedfileutils", "//foundation/distributedhardware/devicemanager/interfaces/inner_kits/native_cpp:devicemanagersdk", + "//foundation/storage/distributed_file_manager/services/distributedfiledaemon:libdistributedfiledaemon", + "//base/security/deviceauth/services:deviceauth_sdk", + ] + + external_deps = [ + "dsoftbus_standard:softbus_client", + "ipc:ipc_core", + "safwk:system_ability_fwk", ] } diff --git a/test/moduletest/src/distributedfiledaemon_service_test.cpp b/test/moduletest/src/distributedfiledaemon_service_test.cpp index 14bf160c6..9f29c2907 100644 --- a/test/moduletest/src/distributedfiledaemon_service_test.cpp +++ b/test/moduletest/src/distributedfiledaemon_service_test.cpp @@ -15,13 +15,23 @@ #include #include +#include +#include +#include #include #include +#include +#include "device/device_info.h" #include "device/device_manager_agent.h" #include "mountpoint/mount_point.h" +#include "network/kernel_talker.h" +#include "network/session_pool.h" +#include "network/softbus/softbus_session.h" +#include "securec.h" #include "utils_directory.h" #include "utils_log.h" + namespace OHOS { namespace Storage { namespace DistributedFile { @@ -29,6 +39,26 @@ namespace Test { using namespace testing::ext; using namespace std; +static const string srcHead = "/data/misc_ce/"; +static const string dstHead = "/mnt/hmdfs/"; +static const string cacheHead = "/data/misc_ce/"; +std::mutex cmdMutex_; + +const int KEY_MAX_LEN = 32; +const int CID_MAX_LEN = 64; +struct UpdateSocketParam { + int32_t cmd; + int32_t newfd; + uint8_t status; + uint8_t protocol; + uint16_t udpPort; + uint8_t deviceType; + uint8_t masterKey[KEY_MAX_LEN]; + char cid[CID_MAX_LEN]; + int32_t linkType; + int32_t binderFd; +} __attribute__((packed)); + class DistributedFileDaemonServiceTest : public testing::Test { public: static void SetUpTestCase(void); @@ -80,6 +110,574 @@ HWTEST_F(DistributedFileDaemonServiceTest, mount_umount_test_001, TestSize.Level } EXPECT_EQ(0, 0); } + +/** + * @tc.name: distributedFileDaemon_service_test_001_mount + * @tc.desc: Verify the mount/umount function. + * @tc.type: FUNC + * @tc.require: Issue Number + */ +HWTEST_F(DistributedFileDaemonServiceTest, distributedFileDaemon_service_test_001_mount, TestSize.Level1) +{ + const int userId = 3333; + + auto mountArgument = OHOS::Storage::DistributedFile::Utils::MountArgumentDescriptors::Alpha(userId); + auto mp = make_unique(mountArgument); + + shared_ptr smp = move(mp); + + try { + smp->Mount(); + + const string src = mountArgument.GetFullSrc(); + const char *srcPath = src.data(); + int ret = access(srcPath, F_OK); + EXPECT_EQ(0, ret); + + const string dst = mountArgument.GetFullDst(); + const char *dstPath = dst.data(); + ret = access(dstPath, F_OK); + EXPECT_EQ(0, ret); + + const string cache = mountArgument.GetCachePath(); + const char *cachePath = cache.data(); + ret = access(cachePath, F_OK); + EXPECT_EQ(0, ret); + + stringstream srcTest; + srcTest << src << "/test"; + Utils::ForceCreateDirectory(srcTest.str(), S_IRWXU | S_IRWXG | S_IXOTH); + + stringstream dstTest; + dstTest << dst << "/device_view/local" + << "/test"; + const string pathStr = dstTest.str(); + const char *dstPathTest = pathStr.data(); + ret = access(dstPathTest, F_OK); + EXPECT_EQ(0, ret); + + Utils::ForceRemoveDirectory(dstPathTest); + + const string strTestStr = srcTest.str(); + ret = access(strTestStr.data(), F_OK); + EXPECT_EQ(-1, ret); + + smp->Umount(); + + stringstream srcStream; + srcStream << srcHead << userId; + Utils::ForceRemoveDirectory(srcStream.str()); + + ret = access(srcStream.str().data(), F_OK); + EXPECT_EQ(-1, ret); + + LOGE("testcase distributedFileDaemon_service_test_001_mount run end"); + } catch (const exception &e) { + LOGE("Error:%{public}s", e.what()); + EXPECT_EQ(0, 1); + } + EXPECT_EQ(0, 0); +} + +/** + * @tc.name: distributedFileDaemon_service_test_002_multiple_mount + * @tc.desc: Verify the mount/umount function. + * @tc.type: FUNC + * @tc.require: Issue Number + */ +HWTEST_F(DistributedFileDaemonServiceTest, distributedFileDaemon_service_test_002_multiple_mount, TestSize.Level1) +{ + const int userId[2] = {3335, 3336}; + Utils::MountArgument mountArgument[2]; + shared_ptr smpArr[2]; + + const int len = sizeof(userId) / sizeof(userId[0]); + for (int i = 0; i < len; i++) { + mountArgument[i] = OHOS::Storage::DistributedFile::Utils::MountArgumentDescriptors::Alpha(userId[i]); + auto mp = make_unique(mountArgument[i]); + smpArr[i] = move(mp); + } + + try { + for (int j = 0; j < len; j++) { + smpArr[j]->Mount(); + } + + for (int k = 0; k < len; k++) { + const string src = mountArgument[k].GetFullSrc(); + const char *srcPath = src.data(); + int ret = access(srcPath, F_OK); + EXPECT_EQ(0, ret); + + const string dst = mountArgument[k].GetFullDst(); + const char *dstPath = dst.data(); + ret = access(dstPath, F_OK); + EXPECT_EQ(0, ret); + + const string cache = mountArgument[k].GetCachePath(); + const char *cachePath = cache.data(); + ret = access(cachePath, F_OK); + EXPECT_EQ(0, ret); + + stringstream srcTest; + srcTest << src << "/test"; + Utils::ForceCreateDirectory(srcTest.str(), S_IRWXU | S_IRWXG | S_IXOTH); + + stringstream dstTest; + dstTest << dst << "/device_view/local" + << "/test"; + const string pathStr = dstTest.str(); + const char *dstPathTest = pathStr.data(); + ret = access(dstPathTest, F_OK); + EXPECT_EQ(0, ret); + + Utils::ForceRemoveDirectory(dstPathTest); + + const string strTestStr = srcTest.str(); + ret = access(strTestStr.data(), F_OK); + EXPECT_EQ(-1, ret); + + smpArr[k]->Umount(); + + stringstream srcStream; + srcStream << srcHead << userId[k]; + Utils::ForceRemoveDirectory(srcStream.str()); + + ret = access(srcStream.str().data(), F_OK); + EXPECT_EQ(-1, ret); + } + + LOGE("testcase distributedFileDaemon_service_test_002_mount run end"); + } catch (const exception &e) { + LOGE("Error:%{public}s", e.what()); + EXPECT_EQ(0, 1); + } + EXPECT_EQ(0, 0); +} + +/** + * @tc.name: distributedFileDaemon_service_test_003_unmount + * @tc.desc: Verify the mount/umount function. + * @tc.type: FUNC + * @tc.require: Issue Number + */ +HWTEST_F(DistributedFileDaemonServiceTest, distributedFileDaemon_service_test_003_unmount, TestSize.Level1) +{ + const int userId = 3337; + + auto mountArgument = OHOS::Storage::DistributedFile::Utils::MountArgumentDescriptors::Alpha(userId); + auto mp = make_unique(mountArgument); + + shared_ptr smp = move(mp); + + try { + smp->Mount(); + + const string dst = mountArgument.GetFullDst(); + const char *dstPath = dst.data(); + stringstream dstTest1, dstTest2; + dstTest1 << dst << "/device_view/local" + << "/test1"; + dstTest2 << dst << "/device_view/local" + << "/test2"; + Utils::ForceCreateDirectory(dstTest1.str(), S_IRWXU | S_IRWXG | S_IXOTH); + Utils::ForceCreateDirectory(dstTest2.str(), S_IRWXU | S_IRWXG | S_IXOTH); + + const string src = mountArgument.GetFullSrc(); + const string srcTest1 = src + "/test1"; + int ret = access(srcTest1.data(), F_OK); + EXPECT_EQ(0, ret); + + Utils::ForceRemoveDirectory(srcTest1); + + ret = access(dstTest1.str().data(), F_OK); + EXPECT_EQ(-1, ret); + + smp->Umount(); + + ret = access(dstPath, F_OK); + EXPECT_EQ(-1, ret); + + const string srcTest2 = src + "/test2"; + const char *srcPathTest2 = srcTest2.data(); + ret = access(srcTest2.data(), F_OK); + EXPECT_EQ(0, ret); + + Utils::ForceRemoveDirectory(srcPathTest2); + + stringstream srcStream; + srcStream << srcHead << userId; + Utils::ForceRemoveDirectory(srcStream.str()); + + ret = access(srcStream.str().data(), F_OK); + EXPECT_EQ(-1, ret); + + LOGE("testcase distributedFileDaemon_service_test_003_unmount run end"); + } catch (const exception &e) { + LOGE("Error:%{public}s", e.what()); + EXPECT_EQ(0, 1); + } + EXPECT_EQ(0, 0); +} + +/** + * @tc.name: distributedFileDaemon_service_test_004_repeats_mount + * @tc.desc: Verify the mount/umount function. + * @tc.type: FUNC + * @tc.require: Issue Number + */ +HWTEST_F(DistributedFileDaemonServiceTest, distributedFileDaemon_service_test_004_repeats_mount, TestSize.Level1) +{ + const int userId = 3338; + + auto mountArgument = OHOS::Storage::DistributedFile::Utils::MountArgumentDescriptors::Alpha(userId); + auto mp = make_unique(mountArgument); + + shared_ptr smp = move(mp); + + try { + smp->Mount(); + smp->Mount(); + + const string src = mountArgument.GetFullSrc(); + const char *srcPath = src.data(); + int ret = access(srcPath, F_OK); + EXPECT_EQ(0, ret); + + const string dst = mountArgument.GetFullDst(); + const char *dstPath = dst.data(); + ret = access(dstPath, F_OK); + EXPECT_EQ(0, ret); + + const string cache = mountArgument.GetCachePath(); + const char *cachePath = cache.data(); + ret = access(cachePath, F_OK); + EXPECT_EQ(0, ret); + + stringstream srcTest; + srcTest << src << "/test"; + Utils::ForceCreateDirectory(srcTest.str(), S_IRWXU | S_IRWXG | S_IXOTH); + + stringstream dstTest; + dstTest << dst << "/device_view/local" + << "/test"; + const string pathStr = dstTest.str(); + const char *dstPathTest = pathStr.data(); + ret = access(dstPathTest, F_OK); + EXPECT_EQ(0, ret); + + Utils::ForceRemoveDirectory(dstPathTest); + + const string strTestStr = srcTest.str(); + ret = access(strTestStr.data(), F_OK); + EXPECT_EQ(-1, ret); + + smp->Umount(); + + stringstream srcStream; + srcStream << srcHead << userId; + Utils::ForceRemoveDirectory(srcStream.str()); + + ret = access(srcStream.str().data(), F_OK); + EXPECT_EQ(-1, ret); + + LOGE("testcase distributedFileDaemon_service_test_004_repeats_mount run end"); + } catch (const exception &e) { + LOGE("Error:%{public}s", e.what()); + EXPECT_EQ(0, 1); + } + EXPECT_EQ(0, 0); +} + +/** + * @tc.name: distributedFileDaemon_service_test_005_repeats_unmount + * @tc.desc: Verify the mount/umount function. + * @tc.type: FUNC + * @tc.require: Issue Number + */ +HWTEST_F(DistributedFileDaemonServiceTest, distributedFileDaemon_service_test_005_repeats_unmount, TestSize.Level1) +{ + const int userId = 3339; + + auto mountArgument = OHOS::Storage::DistributedFile::Utils::MountArgumentDescriptors::Alpha(userId); + auto mp = make_unique(mountArgument); + + shared_ptr smp = move(mp); + + try { + smp->Mount(); + + const string dst = mountArgument.GetFullDst(); + const char *dstPath = dst.data(); + stringstream dstTest1, dstTest2; + dstTest1 << dst << "/device_view/local" + << "/test1"; + dstTest2 << dst << "/device_view/local" + << "/test2"; + Utils::ForceCreateDirectory(dstTest1.str(), S_IRWXU | S_IRWXG | S_IXOTH); + Utils::ForceCreateDirectory(dstTest2.str(), S_IRWXU | S_IRWXG | S_IXOTH); + + const string src = mountArgument.GetFullSrc(); + const string srcTest1 = src + "/test1"; + const char *srcPathTest1 = srcTest1.data(); + int ret = access(srcPathTest1, F_OK); + EXPECT_EQ(0, ret); + + Utils::ForceRemoveDirectory(srcPathTest1); + + ret = access(dstTest1.str().data(), F_OK); + EXPECT_EQ(-1, ret); + + smp->Umount(); + try { + smp->Umount(); + } catch (const exception &e) { + string err = e.what(); + string out = "No such file or directory"; + + if (err.find(out) == string::npos) { + LOGE("005-Error:%{public}s", e.what()); + EXPECT_EQ(0, 1); + } + } + + ret = access(dstPath, F_OK); + EXPECT_EQ(-1, ret); + + const string srcTest2 = src + "/test2"; + const char *srcPathTest2 = srcTest2.data(); + printf("005ck--7--info:%s\n", srcPathTest2); + ret = access(srcPathTest2, F_OK); + EXPECT_EQ(0, ret); + + Utils::ForceRemoveDirectory(srcPathTest2); + + stringstream srcStream; + srcStream << srcHead << userId; + Utils::ForceRemoveDirectory(srcStream.str()); + + ret = access(srcStream.str().data(), F_OK); + EXPECT_EQ(-1, ret); + + LOGE("testcase distributedFileDaemon_service_test_005_unmount run end"); + } catch (const exception &e) { + LOGE("Error:%{public}s", e.what()); + EXPECT_EQ(0, 1); + } + EXPECT_EQ(0, 0); +} + +/** + * @tc.name: distributedFileDaemon_service_test_006_repeats_init_register + * @tc.desc: Verify the Start/Stop function. + * @tc.type: FUNC + * @tc.require: Issue Number + */ +HWTEST_F(DistributedFileDaemonServiceTest, + distributedFileDaemon_service_test_006_repeats_init_register, + TestSize.Level1) +{ + auto dm = DeviceManagerAgent::GetInstance(); + shared_ptr sdm = move(dm); + + try { + sdm->Start(); + sdm->Stop(); + LOGE("testcase distributedFileDaemon_service_test_006_repeats_init_register run end"); + } catch (const exception &e) { + LOGE("Error:%{public}s", e.what()); + EXPECT_EQ(0, 1); + } + EXPECT_EQ(0, 0); +} +/** + * @tc.name: distributedFileDaemon_service_test_007_repeats_create_net_instance + * @tc.desc: Verify the JoinGroup/QuitGroup function. + * @tc.type: FUNC + * @tc.require: Issue Number + */ +HWTEST_F(DistributedFileDaemonServiceTest, + distributedFileDaemon_service_test_007_repeats_create_net_instance, + TestSize.Level1) +{ + const int userId = 4200; + auto mountArgument = OHOS::Storage::DistributedFile::Utils::MountArgumentDescriptors::Alpha(userId); + auto mp = make_unique(mountArgument); + shared_ptr smp = move(mp); + + try { + auto sdm = DeviceManagerAgent::GetInstance(); + + smp->Mount(); + sdm->Start(); + sdm->JoinGroup(smp); + smp->Umount(); + sdm->QuitGroup(smp); + sdm->Stop(); + LOGE("testcase distributedFileDaemon_service_test_007_repeats_create_net_instance run end"); + } catch (const exception &e) { + LOGE("Error:%{public}s", e.what()); + EXPECT_EQ(0, 1); + } + EXPECT_EQ(0, 0); +} +/** + * @tc.name: distributedFileDaemon_service_test_008_repeats_repeat_create_net_instance + * @tc.desc: Verify the JoinGroup/QuitGroup function. + * @tc.type: FUNC + * @tc.require: Issue Number + */ +HWTEST_F(DistributedFileDaemonServiceTest, + distributedFileDaemon_service_test_008_repeats_repeat_create_net_instance, + TestSize.Level1) +{ + const int userId = 4201; + auto mountArgument = OHOS::Storage::DistributedFile::Utils::MountArgumentDescriptors::Alpha(userId); + auto mp = make_unique(mountArgument); + shared_ptr smp = move(mp); + + try { + auto sdm = DeviceManagerAgent::GetInstance(); + + smp->Mount(); + sdm->Start(); + sdm->JoinGroup(smp); + try { + sdm->JoinGroup(smp); + } catch (const exception &e) { + string err = e.what(); + string out = "Mountpoint existed"; + + if (err.find(out) == string::npos) { + LOGE("008-Error:%{public}s", e.what()); + EXPECT_EQ(0, 1); + } + } + smp->Umount(); + sdm->QuitGroup(smp); + sdm->Stop(); + LOGE("testcase distributedFileDaemon_service_test_008_repeats_repeat_create_net_instance run end"); + } catch (const exception &e) { + LOGE("Error:%{public}s", e.what()); + EXPECT_EQ(0, 1); + } + EXPECT_EQ(0, 0); +} +/** + * @tc.name: distributedFileDaemon_service_test_009_repeats_create_multipe_net_instance + * @tc.desc: Verify the JoinGroup/QuitGroup function. + * @tc.type: FUNC + * @tc.require: Issue Number + */ +HWTEST_F(DistributedFileDaemonServiceTest, + distributedFileDaemon_service_test_009_repeats_create_multipe_net_instance, + TestSize.Level1) +{ + const int userId1 = 4202; + const int userId2 = 4203; + auto mountArgument1 = OHOS::Storage::DistributedFile::Utils::MountArgumentDescriptors::Alpha(userId1); + auto mountArgument2 = OHOS::Storage::DistributedFile::Utils::MountArgumentDescriptors::Alpha(userId2); + auto mp1 = make_unique(mountArgument1); + auto mp2 = make_unique(mountArgument2); + shared_ptr smp1 = move(mp1); + shared_ptr smp2 = move(mp2); + + try { + auto sdm = DeviceManagerAgent::GetInstance(); + + smp1->Mount(); + smp2->Mount(); + sdm->Start(); + sdm->JoinGroup(smp1); + sdm->JoinGroup(smp2); + smp1->Umount(); + smp2->Umount(); + sdm->QuitGroup(smp1); + sdm->QuitGroup(smp2); + sdm->Stop(); + LOGE("testcase distributedFileDaemon_service_test_009_repeats_create_multipe_net_instance run end"); + } catch (const exception &e) { + LOGE("Error:%{public}s", e.what()); + EXPECT_EQ(0, 1); + } + EXPECT_EQ(0, 0); +} +/** + * @tc.name: distributedFileDaemon_service_test_010_repeats_repeat_del_net_instance + * @tc.desc: Verify the JoinGroup/QuitGroup function. + * @tc.type: FUNC + * @tc.require: Issue Number + */ +HWTEST_F(DistributedFileDaemonServiceTest, + distributedFileDaemon_service_test_010_repeats_repeat_del_net_instance, + TestSize.Level1) +{ + const int userId = 4204; + auto mountArgument = OHOS::Storage::DistributedFile::Utils::MountArgumentDescriptors::Alpha(userId); + auto mp = make_unique(mountArgument); + shared_ptr smp = move(mp); + + try { + auto sdm = DeviceManagerAgent::GetInstance(); + + smp->Mount(); + sdm->Start(); + sdm->JoinGroup(smp); + smp->Umount(); + sdm->QuitGroup(smp); + try { + sdm->QuitGroup(smp); + } catch (const exception &e) { + string err = e.what(); + string out = "Mountpoint didn't exist"; + + if (err.find(out) == string::npos) { + LOGE("010-Error:%{public}s", e.what()); + EXPECT_EQ(0, 1); + } + } + sdm->Stop(); + LOGE("testcase distributedFileDaemon_service_test_010_repeats_repeat_del_net_instance run end"); + } catch (const exception &e) { + LOGE("Error:%{public}s", e.what()); + EXPECT_EQ(0, 1); + } + EXPECT_EQ(0, 0); +} + +/** + * @tc.name: distributedFileDaemon_service_test_015_kernel_notify_deal + * @tc.desc: Verify the JoinGroup/QuitGroup function. + * @tc.type: FUNC + * @tc.require: Issue Number + */ +HWTEST_F(DistributedFileDaemonServiceTest, distributedFileDaemon_service_test_015_kernel_notify_deal, TestSize.Level1) +{ + const int userId = 4500; + auto mountArgument = OHOS::Storage::DistributedFile::Utils::MountArgumentDescriptors::Alpha(userId); + auto mp = make_unique(mountArgument); + shared_ptr smp = move(mp); + + KernelTalker kt( + smp, + [&](NotifyParam ¶m) { + EXPECT_EQ(param.notify, 2); + }, + [&](const std::string &cid) { + string str = "remoteCid-1"; + EXPECT_TRUE(strcmp(cid.data(), str.data()) == 0); + }); + + for (int i = 0; i < 7; i++) { + std::string str = "remoteCid-" + to_string(i); + NotifyParam param = {i, 72, 16, 8, 336, 326}; + strcpy_s(param.remoteCid, CID_MAX_LEN, str.data()); + kt.NotifyHandler(param); + } + + EXPECT_EQ(0, 0); +} + } // namespace Test } // namespace DistributedFile } // namespace Storage -- Gitee From feee2941861e5b5ec116c866e17698fcd492292a Mon Sep 17 00:00:00 2001 From: x00456388 Date: Sat, 18 Dec 2021 18:51:03 +0800 Subject: [PATCH 03/14] del service getdistributeddir etc and code review modify Signed-off-by: x00456388 --- frameworks/native/service_proxy.cpp | 50 ------------ frameworks/native/service_proxy.h | 3 - .../native/i_distributedfile_service.h | 9 --- services/4902.xml | 2 +- services/distributedfile.cfg | 12 +-- .../include/device/device_manager_agent.h | 12 +-- .../src/device/device_manager_agent.cpp | 20 ++--- .../src/mountpoint/mount_manager.cpp | 4 +- .../src/mountpoint/mount_point.cpp | 4 +- .../include/ipc/distributedfile_service.h | 3 - .../ipc/distributedfile_service_stub.h | 3 - .../src/ipc/distributedfile_service.cpp | 77 ------------------- .../src/ipc/distributedfile_service_stub.cpp | 37 --------- utils/system/include/utils_mount_argument.h | 2 +- utils/system/src/utils_mount_argument.cpp | 24 +++--- 15 files changed, 43 insertions(+), 219 deletions(-) diff --git a/frameworks/native/service_proxy.cpp b/frameworks/native/service_proxy.cpp index 0cbb1c08e..ac73e3dfd 100644 --- a/frameworks/native/service_proxy.cpp +++ b/frameworks/native/service_proxy.cpp @@ -22,56 +22,6 @@ namespace DistributedFile { ServiceProxy::ServiceProxy(const sptr &impl) : IRemoteProxy(impl) {} ServiceProxy::~ServiceProxy() {} -int32_t ServiceProxy::GetBundleDistributedDir(const std::string &dirName) -{ - int32_t error = GET_DISTRIBUTEDFILE_DISTRIBUTED_DIR_FAIL; - - MessageOption option; - MessageParcel dataParcel; - MessageParcel replyParcel; - if (!dataParcel.WriteInterfaceToken(ServiceProxy::GetDescriptor())) { - LOGE("write descriptor failed"); - return DISTRIBUTEDFILE_WRITE_DESCRIPTOR_TOKEN_FAIL; - } - dataParcel.WriteString(dirName); - if (Remote() == nullptr) { - LOGE("Remote object address is null"); - return DISTRIBUTEDFILE_REMOTE_ADDRESS_IS_NULL; - } - error = Remote()->SendRequest(GET_BUNDLE_DISTRIBUTED_DIR, dataParcel, replyParcel, option); - if (error != DISTRIBUTEDFILE_NO_ERROR) { - LOGE("Function GetBundleDistributedDir! errCode:%{public}d", error); - return DISTRIBUTEDFILE_CONNECT_SYSTEM_ABILITY_STUB_FAIL; - } - - return replyParcel.ReadInt32(); -} - -int32_t ServiceProxy::RemoveBundleDistributedDirs(const std::string &dirName) -{ - int32_t error = REMOVE_DISTRIBUTEDFILE_DISTRIBUTEDDIRS_FAIL; - MessageOption option; - MessageParcel dataParcel; - MessageParcel replyParcel; - if (!dataParcel.WriteInterfaceToken(ServiceProxy::GetDescriptor())) { - LOGE("write descriptor failed"); - return DISTRIBUTEDFILE_WRITE_DESCRIPTOR_TOKEN_FAIL; - } - - dataParcel.WriteString(dirName); - if (Remote() == nullptr) { - LOGE("Remote object address is null"); - return DISTRIBUTEDFILE_REMOTE_ADDRESS_IS_NULL; - } - - error = Remote()->SendRequest(REMOVE_BUNDLE_DISTRIBUTED_DIRS, dataParcel, replyParcel, option); - if (error != DISTRIBUTEDFILE_NO_ERROR) { - LOGE("Function RemoveBundleDistributedDirs! errCode:%{public}d", error); - return DISTRIBUTEDFILE_CONNECT_SYSTEM_ABILITY_STUB_FAIL; - } - - return replyParcel.ReadInt32(); -} } // namespace DistributedFile } // namespace Storage } // namespace OHOS \ No newline at end of file diff --git a/frameworks/native/service_proxy.h b/frameworks/native/service_proxy.h index 46c6044bb..5b510e969 100644 --- a/frameworks/native/service_proxy.h +++ b/frameworks/native/service_proxy.h @@ -34,9 +34,6 @@ public: virtual ~ServiceProxy(); - int32_t GetBundleDistributedDir(const std::string &dirName) override; - int32_t RemoveBundleDistributedDirs(const std::string &dirName) override; - private: static inline BrokerDelegator delegator_; }; diff --git a/interfaces/innerkits/native/i_distributedfile_service.h b/interfaces/innerkits/native/i_distributedfile_service.h index 0b283ff54..878461cbd 100644 --- a/interfaces/innerkits/native/i_distributedfile_service.h +++ b/interfaces/innerkits/native/i_distributedfile_service.h @@ -25,15 +25,9 @@ class IDistributedFileService : public IRemoteBroker { public: DECLARE_INTERFACE_DESCRIPTOR(u"OHOS.DistributedFile.IDistributedFileService"); // define the message code - enum DistributedFileSurfaceCode { - INTERFACE1 = 0, - GET_BUNDLE_DISTRIBUTED_DIR, - REMOVE_BUNDLE_DISTRIBUTED_DIRS, - }; // define the error code enum { DISTRIBUTEDFILE_SUCCESS = 0, - GET_DISTRIBUTEDFILE_DISTRIBUTED_DIR_FAIL = 1, DISTRIBUTEDFILE_WRITE_DESCRIPTOR_TOKEN_FAIL, ERR_FLATTEN_OBJECT, DISTRIBUTEDFILE_NO_ERROR, @@ -49,9 +43,6 @@ public: ROOT_UID, SYSTEM_SERVICE_UID, }; - // define business functions - virtual int32_t GetBundleDistributedDir(const std::string &dirName) = 0; - virtual int32_t RemoveBundleDistributedDirs(const std::string &dirName) = 0; }; } // namespace DistributedFile } // namespace Storage diff --git a/services/4902.xml b/services/4902.xml index 6b8b2cf56..a7428c63c 100644 --- a/services/4902.xml +++ b/services/4902.xml @@ -14,7 +14,7 @@ * limitations under the License. --> - distributedfile + distributedfileservice libdistributedfileservice.z.so diff --git a/services/distributedfile.cfg b/services/distributedfile.cfg index 44e648c2e..e2e31e540 100644 --- a/services/distributedfile.cfg +++ b/services/distributedfile.cfg @@ -3,7 +3,7 @@ "name": "boot", "cmds": [ "start distributedfiledaemon", - "start distributedfile" + "start distributedfileservice" ] },{ "name" : "init", @@ -12,16 +12,16 @@ ] }], "services": [{ - "name": "distributedfile", - "path": ["/system/bin/sa_main", "/system/profile/distributedfile.xml"], - "uid": "root", - "gid": ["root", "system", "shell", "readproc", "media_rw", "inet"], + "name": "distributedfileservice", + "path": ["/system/bin/sa_main", "/system/profile/distributedfileservice.xml"], + "uid": "system", + "gid": ["system"], "caps": ["SYS_PTRACE", "KILL"] },{ "name": "distributedfiledaemon", "path": ["/system/bin/sa_main", "/system/profile/distributedfiledaemon.xml"], "uid": "root", - "gid": ["root", "system", "shell", "readproc", "media_rw", "inet"], + "gid": ["root"], "caps": ["SYS_PTRACE", "KILL"] }] } diff --git a/services/distributedfiledaemon/include/device/device_manager_agent.h b/services/distributedfiledaemon/include/device/device_manager_agent.h index 76052c492..ad9ae0c36 100644 --- a/services/distributedfiledaemon/include/device/device_manager_agent.h +++ b/services/distributedfiledaemon/include/device/device_manager_agent.h @@ -35,13 +35,13 @@ namespace OHOS { namespace Storage { namespace DistributedFile { struct GroupInfo { - std::string groupName_; - std::string groupId_; - std::string groupOwner_; - int32_t groupType_; - GroupInfo() : groupType_(0) {} + std::string groupName; + std::string groupId; + std::string groupOwner; + int32_t groupType; + GroupInfo() : groupType(0) {} GroupInfo(std::string name, std::string id, std::string owner, int32_t type) - : groupName_(name), groupId_(id), groupOwner_(owner), groupType_(type) + : groupName(name), groupId(id), groupOwner(owner), groupType(type) { } }; diff --git a/services/distributedfiledaemon/src/device/device_manager_agent.cpp b/services/distributedfiledaemon/src/device/device_manager_agent.cpp index 002e7063c..d5129fae1 100644 --- a/services/distributedfiledaemon/src/device/device_manager_agent.cpp +++ b/services/distributedfiledaemon/src/device/device_manager_agent.cpp @@ -177,19 +177,19 @@ void DeviceManagerAgent::OnDeviceOffline(const DistributedHardware::DmDeviceInfo void from_json(const nlohmann::json &jsonObject, GroupInfo &groupInfo) { if (jsonObject.find(FIELD_GROUP_NAME) != jsonObject.end()) { - groupInfo.groupName_ = jsonObject.at(FIELD_GROUP_NAME).get(); + groupInfo.groupName = jsonObject.at(FIELD_GROUP_NAME).get(); } if (jsonObject.find(FIELD_GROUP_ID) != jsonObject.end()) { - groupInfo.groupId_ = jsonObject.at(FIELD_GROUP_ID).get(); + groupInfo.groupId = jsonObject.at(FIELD_GROUP_ID).get(); } if (jsonObject.find(FIELD_GROUP_OWNER) != jsonObject.end()) { - groupInfo.groupOwner_ = jsonObject.at(FIELD_GROUP_OWNER).get(); + groupInfo.groupOwner = jsonObject.at(FIELD_GROUP_OWNER).get(); } if (jsonObject.find(FIELD_GROUP_TYPE) != jsonObject.end()) { - groupInfo.groupType_ = jsonObject.at(FIELD_GROUP_TYPE).get(); + groupInfo.groupType = jsonObject.at(FIELD_GROUP_TYPE).get(); } } @@ -210,15 +210,15 @@ void DeviceManagerAgent::AuthGroupOnlineProc(const DeviceInfo info) if (!CheckIsAuthGroup(group)) { continue; } - if (authGroupMap_.find(group.groupId_) == authGroupMap_.end()) { - LOGI("groupId %{public}s not exist, then mount", group.groupId_.c_str()); + if (authGroupMap_.find(group.groupId) == authGroupMap_.end()) { + LOGI("groupId %{public}s not exist, then mount", group.groupId.c_str()); MountManager::GetInstance()->Mount(make_unique( - Utils::MountArgumentDescriptors::SetAuthGroupMountArgument(group.groupId_, group.groupOwner_, true))); + Utils::MountArgumentDescriptors::SetAuthGroupMountArgument(group.groupId, group.groupOwner, true))); } - auto [iter, status] = authGroupMap_[group.groupId_].insert(info.GetCid()); + auto [iter, status] = authGroupMap_[group.groupId].insert(info.GetCid()); if (status == false) { LOGI("cid %{public}s has already inserted into groupId %{public}s", info.GetCid().c_str(), - group.groupId_.c_str()); + group.groupId.c_str()); continue; } } @@ -261,7 +261,7 @@ void DeviceManagerAgent::AllAuthGroupsOfflineProc() bool DeviceManagerAgent::CheckIsAuthGroup(const GroupInfo &group) { - if (group.groupType_ == PEER_TO_PEER_GROUP || group.groupType_ == ACROSS_ACCOUNT_AUTHORIZE_GROUP) { + if (group.groupType == PEER_TO_PEER_GROUP || group.groupType == ACROSS_ACCOUNT_AUTHORIZE_GROUP) { return true; } return false; diff --git a/services/distributedfiledaemon/src/mountpoint/mount_manager.cpp b/services/distributedfiledaemon/src/mountpoint/mount_manager.cpp index 917ea77b0..8e9792f5d 100644 --- a/services/distributedfiledaemon/src/mountpoint/mount_manager.cpp +++ b/services/distributedfiledaemon/src/mountpoint/mount_manager.cpp @@ -79,12 +79,12 @@ void MountManager::Umount(weak_ptr wmp) LOGE("%{public}s", ss.str().c_str()); throw runtime_error(ss.str()); } - LOGE("Umount begin"); + LOGI("Umount begin"); smp->Umount(); auto dm = DeviceManagerAgent::GetInstance(); dm->Recv(make_unique>>(&DeviceManagerAgent::QuitGroup, smp)); mountPoints_.erase(it); - LOGE("Umount end"); + LOGI("Umount end"); } void MountManager::Umount(const std::string &groupId) diff --git a/services/distributedfiledaemon/src/mountpoint/mount_point.cpp b/services/distributedfiledaemon/src/mountpoint/mount_point.cpp index ec7e45498..91755a469 100644 --- a/services/distributedfiledaemon/src/mountpoint/mount_point.cpp +++ b/services/distributedfiledaemon/src/mountpoint/mount_point.cpp @@ -32,7 +32,7 @@ MountPoint::MountPoint(const Utils::MountArgument &mountArg) : mountArg_(mountAr { id_ = idGen_++; if (mountArg.accountless_) { - authGroupId_ = mountArg.account_; + authGroupId_ = mountArg.groupId_; } } @@ -57,7 +57,7 @@ void MountPoint::Mount() const LOGE("Failed to mount: %{public}d %{public}s", cond.value(), cond.message().c_str()); throw system_error(errno, system_category()); } - LOGE("mount sucess: src %{public}s --> dst %{public}s", src.c_str(), dst.c_str()); + LOGI("mount sucess: src %{public}s --> dst %{public}s", src.c_str(), dst.c_str()); if (mntArg.accountless_) { Utils::ForceCreateDirectory(dst + "/device_view/local/data/" + mntArg.packageName_, diff --git a/services/distributedfileservice/include/ipc/distributedfile_service.h b/services/distributedfileservice/include/ipc/distributedfile_service.h index 7c6449e47..2ed0ef60f 100644 --- a/services/distributedfileservice/include/ipc/distributedfile_service.h +++ b/services/distributedfileservice/include/ipc/distributedfile_service.h @@ -35,9 +35,6 @@ public: void OnDump() override; void OnStart() override; void OnStop() override; - - int32_t GetBundleDistributedDir(const std::string &dirName) override; - int32_t RemoveBundleDistributedDirs(const std::string &dirName) override; }; } // namespace DistributedFile } // namespace Storage diff --git a/services/distributedfileservice/include/ipc/distributedfile_service_stub.h b/services/distributedfileservice/include/ipc/distributedfile_service_stub.h index 0b5218b58..419f6782b 100644 --- a/services/distributedfileservice/include/ipc/distributedfile_service_stub.h +++ b/services/distributedfileservice/include/ipc/distributedfile_service_stub.h @@ -36,9 +36,6 @@ private: using DistributedFileServiceFunc = int32_t (DistributedFileServiceStub::*)(MessageParcel &data, MessageParcel &reply); std::map memberFuncMap_; - - int32_t GetBundleDistributedDirInner(MessageParcel &data, MessageParcel &reply); - int32_t RemoveBundleDistributedDirsInner(MessageParcel &data, MessageParcel &reply); }; } // namespace DistributedFile } // namespace Storage diff --git a/services/distributedfileservice/src/ipc/distributedfile_service.cpp b/services/distributedfileservice/src/ipc/distributedfile_service.cpp index a2840d1e4..e09d7636e 100644 --- a/services/distributedfileservice/src/ipc/distributedfile_service.cpp +++ b/services/distributedfileservice/src/ipc/distributedfile_service.cpp @@ -30,8 +30,6 @@ namespace OHOS { namespace Storage { namespace DistributedFile { using namespace std; -const bool g_registerResult = - SystemAbility::MakeAndRegisterAbility(DelayedSingleton::GetInstance().get()); DistributedFileService::DistributedFileService() : SystemAbility(STORAGE_DISTRIBUTED_FILE_SERVICE_SA_ID, false) {} @@ -55,81 +53,6 @@ void DistributedFileService::OnStop() { LOGI("DistributedFileService::OnStop start"); } - -int32_t DistributedFileService::GetBundleDistributedDir(const std::string &dirName) -{ - std::string path = dirName; - if (path.empty()) { - LOGE("DistributedFileService-%{public}s: Failed to get app dir, error: invalid app name", __func__); - return DISTRIBUTEDFILE_DIR_NAME_IS_EMPTY; - } - - sptr systemAbilityMgr = SystemAbilityManagerClient::GetInstance().GetSystemAbilityManager(); - if (systemAbilityMgr == nullptr) { - LOGE("BundleService Get ISystemAbilityManager failed ... \n"); - return DISTRIBUTEDFILE_REMOTE_ADDRESS_IS_NULL; - } - - sptr remote = systemAbilityMgr->GetSystemAbility(BUNDLE_MGR_SERVICE_SYS_ABILITY_ID); - if (remote == nullptr) { - LOGE("BundleService Get IRemoteObject failed ... \n"); - return DISTRIBUTEDFILE_REMOTE_ADDRESS_IS_NULL; - } - - int callingUid = IPCSkeleton::GetCallingUid(); - auto BundleMgrService = std::make_unique(remote); - if (BundleMgrService.get() == nullptr) { - LOGE("remote iface_cast BundleMgrService failed ... %{public}s\n", strerror(errno)); - return DISTRIBUTEDFILE_REMOTE_ADDRESS_IS_NULL; - } - - int32_t uid = BundleMgrService->GetUidByBundleName(path, callingUid); - if (uid < 0) { - LOGE("DistributedFileService-%{public}s: Failed to get uid", __func__); - return DISTRIBUTEDFILE_NAME_NOT_FOUND; - } - - if (callingUid != 0) { - if (uid != callingUid) { - LOGE("DistributedFileService-%{public}s: Bundle failed to create dir", __func__); - return DISTRIBUTEDFILE_PERMISSION_DENIED; - } - } - - LOGI("DistributedFileService::GetBundleDistributedDir path : %{public}s", path.c_str()); - Utils::ForceCreateDirectory(path); - return DISTRIBUTEDFILE_SUCCESS; -} - -int32_t DistributedFileService::RemoveBundleDistributedDirs(const std::string &dirName) -{ - std::string path = dirName; - if (path.empty()) { - LOGE("DistributedFileService-%{public}s: Failed to get app dir, error: invalid app name", __func__); - return DISTRIBUTEDFILE_DIR_NAME_IS_EMPTY; - } - - sptr systemAbilityMgr = SystemAbilityManagerClient::GetInstance().GetSystemAbilityManager(); - if (systemAbilityMgr == nullptr) { - LOGE("BundleService Get ISystemAbilityManager failed ... \n"); - return DISTRIBUTEDFILE_REMOTE_ADDRESS_IS_NULL; - } - - sptr remote = systemAbilityMgr->CheckSystemAbility(BUNDLE_MGR_SERVICE_SYS_ABILITY_ID); - if (remote == nullptr) { - LOGE("BundleService Get IRemoteObject failed ... \n"); - return DISTRIBUTEDFILE_REMOTE_ADDRESS_IS_NULL; - } - - auto BundleMgrService = std::make_unique(remote); - if (BundleMgrService.get() == nullptr) { - LOGE("remote iface_cast BundleMgrService failed ... \n"); - return DISTRIBUTEDFILE_REMOTE_ADDRESS_IS_NULL; - } - - Utils::ForceRemoveDirectory(path); - return DISTRIBUTEDFILE_SUCCESS; -} } // namespace DistributedFile } // namespace Storage } // namespace OHOS diff --git a/services/distributedfileservice/src/ipc/distributedfile_service_stub.cpp b/services/distributedfileservice/src/ipc/distributedfile_service_stub.cpp index b0ad8d0d9..08c7f202f 100644 --- a/services/distributedfileservice/src/ipc/distributedfile_service_stub.cpp +++ b/services/distributedfileservice/src/ipc/distributedfile_service_stub.cpp @@ -25,8 +25,6 @@ namespace Storage { namespace DistributedFile { DistributedFileServiceStub::DistributedFileServiceStub() { - memberFuncMap_[GET_BUNDLE_DISTRIBUTED_DIR] = &DistributedFileServiceStub::GetBundleDistributedDirInner; - memberFuncMap_[REMOVE_BUNDLE_DISTRIBUTED_DIRS] = &DistributedFileServiceStub::RemoveBundleDistributedDirsInner; } DistributedFileServiceStub::~DistributedFileServiceStub() @@ -55,41 +53,6 @@ int DistributedFileServiceStub::OnRemoteRequest(uint32_t code, return IPCObjectStub::OnRemoteRequest(code, data, reply, option); } - -int32_t DistributedFileServiceStub::GetBundleDistributedDirInner(MessageParcel &data, MessageParcel &reply) -{ - std::string dirName = data.ReadString(); - if (dirName.empty()) { - LOGE("DistributedFileService-%{public}s: Failed to get app dir, error: invalid app name", __func__); - return DISTRIBUTEDFILE_DIR_NAME_IS_EMPTY; - } - - int32_t result = GetBundleDistributedDir(dirName); - LOGD("DistributedFileServiceStub : GetBundleDistributedDir result = %{public}d", result); - if (!reply.WriteInt32(result)) { - LOGE("fail to write parcel"); - return DISTRIBUTEDFILE_WRITE_REPLY_FAIL; - } - - return result; -} - -int32_t DistributedFileServiceStub::RemoveBundleDistributedDirsInner(MessageParcel &data, MessageParcel &reply) -{ - std::string dirName = data.ReadString(); - if (dirName.empty()) { - LOGE("DistributedFileServiceStub : Failed to get app dir, error: invalid dir name"); - return DISTRIBUTEDFILE_DIR_NAME_IS_EMPTY; - } - - int32_t result = RemoveBundleDistributedDirs(dirName); - if (!reply.WriteInt32(result)) { - LOGE("fail to write parcel"); - return DISTRIBUTEDFILE_WRITE_REPLY_FAIL; - } - - return result; -} } // namespace DistributedFile } // namespace Storage } // namespace OHOS \ No newline at end of file diff --git a/utils/system/include/utils_mount_argument.h b/utils/system/include/utils_mount_argument.h index 6b36132e3..f68fbc18d 100644 --- a/utils/system/include/utils_mount_argument.h +++ b/utils/system/include/utils_mount_argument.h @@ -25,7 +25,7 @@ namespace Utils { struct MountArgument final { int userId_{0}; bool accountless_{false}; - std::string account_; + std::string groupId_; bool needInitDir_{false}; bool useCache_{false}; bool caseSensitive_{true}; diff --git a/utils/system/src/utils_mount_argument.cpp b/utils/system/src/utils_mount_argument.cpp index cc29e3fab..01a4f8ab0 100644 --- a/utils/system/src/utils_mount_argument.cpp +++ b/utils/system/src/utils_mount_argument.cpp @@ -23,14 +23,20 @@ namespace Storage { namespace DistributedFile { namespace Utils { using namespace std; +namespace { +static const std::string DATA_POINT = "/data/service/el2/"; +static const std::string BASE_MOUNT_POINT = "/mnt/hmdfs/"; +static const std::string AUTH_GROUP_MOUNT_POINT = "/mnt/hmdfs/auth_groups/"; +static const std::string SYSFS_HMDFS_PATH = "sys/fs/hmdfs/"; +} // namespace string MountArgument::GetFullSrc() const { stringstream ss; if (!accountless_) { - ss << "/data/misc_ce/" << userId_ << "/hmdfs/storage"; + ss << DATA_POINT << userId_ << "/hmdfs/storage"; } else { - ss << "/data/misc_ce/" << userId_ << "/hmdfs/auth_groups/" << account_; + ss << DATA_POINT << userId_ << "/hmdfs/auth_groups/" << groupId_; } return ss.str(); } @@ -39,9 +45,9 @@ string MountArgument::GetFullDst() const { stringstream ss; if (!accountless_) { - ss << "/mnt/hmdfs/" << userId_ << "/"; + ss << BASE_MOUNT_POINT << userId_ << "/"; } else { - ss << "/mnt/hmdfs/auth_groups/" << account_ << "/"; + ss << AUTH_GROUP_MOUNT_POINT << groupId_ << "/"; } return ss.str(); } @@ -50,9 +56,9 @@ string MountArgument::GetCachePath() const { stringstream ss; if (!accountless_) { - ss << "/data/misc_ce/" << userId_ << "/hmdfs/cache/"; + ss << DATA_POINT << userId_ << "/hmdfs/cache/"; } else { - ss << "/data/misc_ce/" << userId_ << "/hmdfs/auth_groups/" << account_ << "/cache/"; + ss << DATA_POINT << userId_ << "/hmdfs/auth_groups/" << groupId_ << "/cache/"; } return ss.str(); } @@ -73,7 +79,7 @@ string MountArgument::GetCtrlPath() const auto dst = GetFullDst(); auto res = MocklispHash(dst); stringstream ss; - ss << "/sys/fs/hmdfs/" << res << "/cmd"; + ss << SYSFS_HMDFS_PATH << res << "/cmd"; return ss.str(); } @@ -110,7 +116,7 @@ unsigned long MountArgument::GetFlags() const MountArgument MountArgumentDescriptors::Alpha(int userId) { MountArgument mountArgument = { - .account_ = "default", + .groupId_ = "default", .needInitDir_ = true, .useCache_ = true, .enableMergeView_ = true, @@ -128,7 +134,7 @@ MountArgument MountArgumentDescriptors::SetAuthGroupMountArgument(const std::str { MountArgument mountArgument = { .accountless_ = accountless, - .account_ = groupId, + .groupId_ = groupId, .needInitDir_ = true, .useCache_ = true, .enableMergeView_ = true, -- Gitee From 49a63af4f897c72e0498c623b41e8e87f797bd05 Mon Sep 17 00:00:00 2001 From: hhchinasoft Date: Tue, 4 Jan 2022 18:31:03 +0800 Subject: [PATCH 04/14] add senfile js code Signed-off-by: hhchinasoft --- frameworks/native/service_proxy.cpp | 29 ++ frameworks/native/service_proxy.h | 5 +- interfaces/innerkits/js/@ohos.sendfile.d.ts | 34 ++ interfaces/innerkits/js/BUILD.gn | 79 +++++ .../innerkits/js/common/ability_helper.cpp | 54 ++++ .../innerkits/js/common/ability_helper.h | 27 ++ interfaces/innerkits/js/common/fd_guard.cpp | 46 +++ interfaces/innerkits/js/common/fd_guard.h | 34 ++ interfaces/innerkits/js/common/log.h | 90 ++++++ .../js/common/napi/n_async/n_async_context.h | 69 +++++ .../napi/n_async/n_async_work_callback.cpp | 94 ++++++ .../napi/n_async/n_async_work_callback.h | 35 +++ .../napi/n_async/n_async_work_factory.h | 33 ++ .../napi/n_async/n_async_work_promise.cpp | 88 ++++++ .../napi/n_async/n_async_work_promise.h | 35 +++ .../js/common/napi/n_async/n_ref.cpp | 53 ++++ .../innerkits/js/common/napi/n_async/n_ref.h | 38 +++ .../innerkits/js/common/napi/n_class.cpp | 99 ++++++ interfaces/innerkits/js/common/napi/n_class.h | 82 +++++ .../innerkits/js/common/napi/n_exporter.h | 39 +++ .../innerkits/js/common/napi/n_func_arg.cpp | 111 +++++++ .../innerkits/js/common/napi/n_func_arg.h | 74 +++++ interfaces/innerkits/js/common/napi/n_val.cpp | 291 ++++++++++++++++++ interfaces/innerkits/js/common/napi/n_val.h | 80 +++++ .../innerkits/js/common/napi/uni_header.h | 23 ++ interfaces/innerkits/js/common/uni_error.cpp | 118 +++++++ interfaces/innerkits/js/common/uni_error.h | 64 ++++ .../innerkits/js/mod_sendfile/sendfile.cpp | 143 +++++++++ .../innerkits/js/mod_sendfile/sendfile.h | 31 ++ .../js/mod_sendfile/sendfile_napi.cpp | 40 +++ .../innerkits/js/mod_sendfile/sendfile_napi.h | 25 ++ .../native/i_distributedfile_service.h | 12 +- ohos.build | 3 +- .../include/ipc/distributedfile_service.h | 2 + .../ipc/distributedfile_service_stub.h | 2 +- .../src/ipc/distributedfile_service.cpp | 35 +++ .../src/ipc/distributedfile_service_stub.cpp | 21 ++ 37 files changed, 2132 insertions(+), 6 deletions(-) create mode 100644 interfaces/innerkits/js/@ohos.sendfile.d.ts create mode 100644 interfaces/innerkits/js/BUILD.gn create mode 100644 interfaces/innerkits/js/common/ability_helper.cpp create mode 100644 interfaces/innerkits/js/common/ability_helper.h create mode 100644 interfaces/innerkits/js/common/fd_guard.cpp create mode 100644 interfaces/innerkits/js/common/fd_guard.h create mode 100644 interfaces/innerkits/js/common/log.h create mode 100644 interfaces/innerkits/js/common/napi/n_async/n_async_context.h create mode 100644 interfaces/innerkits/js/common/napi/n_async/n_async_work_callback.cpp create mode 100644 interfaces/innerkits/js/common/napi/n_async/n_async_work_callback.h create mode 100644 interfaces/innerkits/js/common/napi/n_async/n_async_work_factory.h create mode 100644 interfaces/innerkits/js/common/napi/n_async/n_async_work_promise.cpp create mode 100644 interfaces/innerkits/js/common/napi/n_async/n_async_work_promise.h create mode 100644 interfaces/innerkits/js/common/napi/n_async/n_ref.cpp create mode 100644 interfaces/innerkits/js/common/napi/n_async/n_ref.h create mode 100644 interfaces/innerkits/js/common/napi/n_class.cpp create mode 100644 interfaces/innerkits/js/common/napi/n_class.h create mode 100644 interfaces/innerkits/js/common/napi/n_exporter.h create mode 100644 interfaces/innerkits/js/common/napi/n_func_arg.cpp create mode 100644 interfaces/innerkits/js/common/napi/n_func_arg.h create mode 100644 interfaces/innerkits/js/common/napi/n_val.cpp create mode 100644 interfaces/innerkits/js/common/napi/n_val.h create mode 100644 interfaces/innerkits/js/common/napi/uni_header.h create mode 100644 interfaces/innerkits/js/common/uni_error.cpp create mode 100644 interfaces/innerkits/js/common/uni_error.h create mode 100644 interfaces/innerkits/js/mod_sendfile/sendfile.cpp create mode 100644 interfaces/innerkits/js/mod_sendfile/sendfile.h create mode 100644 interfaces/innerkits/js/mod_sendfile/sendfile_napi.cpp create mode 100644 interfaces/innerkits/js/mod_sendfile/sendfile_napi.h mode change 100755 => 100644 ohos.build diff --git a/frameworks/native/service_proxy.cpp b/frameworks/native/service_proxy.cpp index ac73e3dfd..2339d8441 100644 --- a/frameworks/native/service_proxy.cpp +++ b/frameworks/native/service_proxy.cpp @@ -22,6 +22,35 @@ namespace DistributedFile { ServiceProxy::ServiceProxy(const sptr &impl) : IRemoteProxy(impl) {} ServiceProxy::~ServiceProxy() {} +int32_t ServiceProxy::SendFile(int32_t sessionId, const std::string &sourceFileList, + const std::string &destinationFileList, uint32_t fileCount) +{ + int32_t error = SEND_FILE_FAIL; + MessageOption option; + MessageParcel dataParcel; + MessageParcel replyParcel; + if (!dataParcel.WriteInterfaceToken(ServiceProxy::GetDescriptor())) { + LOGE("write descriptor failed"); + return SEND_FILE_DISTRIBUTED_DESCRIPTION_FAIL; + } + + dataParcel.WriteInt32(sessionId); + dataParcel.WriteString(sourceFileList); + dataParcel.WriteString(destinationFileList); + dataParcel.WriteUint32(fileCount); + if (Remote() == nullptr) { + LOGE("Remote object address is null"); + return DISTRIBUTEDFILE_REMOTE_ADDRESS_IS_NULL; + } + + error = Remote()->SendRequest(SEND_FILE_DISTRIBUTED, dataParcel, replyParcel, option); + if (error != DISTRIBUTEDFILE_NO_ERROR) { + LOGE("Function RemoveBundleDistributedDirs! errCode:%{public}d", error); + return DISTRIBUTEDFILE_CONNECT_SYSTEM_ABILITY_STUB_FAIL; + } + + return replyParcel.ReadInt32(); +} } // namespace DistributedFile } // namespace Storage } // namespace OHOS \ No newline at end of file diff --git a/frameworks/native/service_proxy.h b/frameworks/native/service_proxy.h index 5b510e969..2347c0fe2 100644 --- a/frameworks/native/service_proxy.h +++ b/frameworks/native/service_proxy.h @@ -34,11 +34,12 @@ public: virtual ~ServiceProxy(); + int32_t SendFile(int32_t sessionId, const std::string &sourceFileList, + const std::string &destinationFileList, uint32_t fileCount) override; private: static inline BrokerDelegator delegator_; }; } // namespace DistributedFile } // namespace Storage } // namespace OHOS - -#endif \ No newline at end of file +#endif // DISTRIBUTEDFILE_SERVICE_PROXY_H \ No newline at end of file diff --git a/interfaces/innerkits/js/@ohos.sendfile.d.ts b/interfaces/innerkits/js/@ohos.sendfile.d.ts new file mode 100644 index 000000000..35deda138 --- /dev/null +++ b/interfaces/innerkits/js/@ohos.sendfile.d.ts @@ -0,0 +1,34 @@ +/* +* Copyright (C) 2021 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 {AsyncCallback, Callback} from "./basic"; + +declare namespace SendFile { + function SendFile(deviceId: number, sourPath: Array, destPath: Array, fileCount: number, callback: AsyncCallback); + function SendFile(deviceId: number, sourPath: Array, destPath: Array, fileCount: number): Promise; + + /** + * Send and recv file event loop type + */ + export interface CloseOptions { + sendFile: number; + recvFile: number; + }; + + on(type: 'finished', CloseOptions: options, callback: AsyncCallback): void; + off(type: 'finished', callback?: AsyncCallback): void; +} + +export default SendFile; \ No newline at end of file diff --git a/interfaces/innerkits/js/BUILD.gn b/interfaces/innerkits/js/BUILD.gn new file mode 100644 index 000000000..066a85fad --- /dev/null +++ b/interfaces/innerkits/js/BUILD.gn @@ -0,0 +1,79 @@ +# Copyright (c) 2021 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") + +file_common_src = [ + "//foundation/storage/distributed_file_manager/interfaces/innerkits/js/common/fd_guard.cpp", + "//foundation/storage/distributed_file_manager/interfaces/innerkits/js/common/uni_error.cpp", + + "//foundation/storage/distributed_file_manager/interfaces/innerkits/js/common/napi/n_class.cpp", + "//foundation/storage/distributed_file_manager/interfaces/innerkits/js/common/napi/n_func_arg.cpp", + "//foundation/storage/distributed_file_manager/interfaces/innerkits/js/common/napi/n_val.cpp", + + "//foundation/storage/distributed_file_manager/interfaces/innerkits/js/common/napi/n_async/n_async_work_callback.cpp", + "//foundation/storage/distributed_file_manager/interfaces/innerkits/js/common/napi/n_async/n_async_work_promise.cpp", + "//foundation/storage/distributed_file_manager/interfaces/innerkits/js/common/napi/n_async/n_ref.cpp", +] + +ohos_shared_library("sendfile") { + relative_install_dir = "module" + subsystem_name = "storage" + part_name = "storage_distributed_file_manager" + + cflags_cc = [ + "-Wno-unused-function" + ] + + include_dirs = [ + ".", + "//foundation/storage/distributed_file_manager/interfaces/innerkits/js/common/napi/n_async", + "//foundation/storage/distributed_file_manager/services/distributedfileservice/include/ipc", + "//foundation/storage/distributed_file_manager/services/distributedfileservice/include", + "//foundation/storage/distributed_file_manager/interfaces/innerkits/native", + "//foundation/storage/distributed_file_manager/frameworks/native", + "//foundation/communication/ipc/interfaces/innerkits/libdbinder/include", + "//foundation/distributedschedule/samgr/services/samgr/native/include", + "//foundation/distributedschedule/samgr/interfaces/innerkits/samgr_proxy/include", + + "//base/hiviewdfx/hilog/interfaces/native/innerkits/include", + "//foundation/ace/napi/interfaces/kits", + "//utils/system/safwk/native/include", + "//utils/native/base/include", + ] + + sources = file_common_src + sources += [ + "//foundation/storage/distributed_file_manager/interfaces/innerkits/js/mod_sendfile/sendfile.cpp", + "//foundation/storage/distributed_file_manager/interfaces/innerkits/js/mod_sendfile/sendfile_napi.cpp", + ] + + deps = [ + "//foundation/ace/napi:ace_napi", + "//utils/native/base:utils", + "//foundation/storage/distributed_file_manager/interfaces/innerkits/native:libdistributedfile_innerkits", + "//foundation/aafwk/standard/frameworks/kits/ability/native:abilitykit_native", + ] + + external_deps = [ + "ipc:ipc_core", + "samgr_standard:samgr_proxy", + "hiviewdfx_hilog_native:libhilog", + ] +} + +group("build_kits_js") { + deps = [ + ":sendfile", + ] +} diff --git a/interfaces/innerkits/js/common/ability_helper.cpp b/interfaces/innerkits/js/common/ability_helper.cpp new file mode 100644 index 000000000..c5aae1548 --- /dev/null +++ b/interfaces/innerkits/js/common/ability_helper.cpp @@ -0,0 +1,54 @@ +/* + * Copyright (c) 2021 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 "ability_helper.h" + +#include "log.h" +#include "napi/n_func_arg.h" +#include "napi/uni_header.h" + +namespace OHOS { +namespace DistributedFS { +using namespace std; +using OHOS::AppExecFwk::Ability; +using OHOS::AppExecFwk::AbilityContext; + +Ability* AbilityHelper::GetJsAbility(napi_env env) +{ + napi_value global = nullptr; + napi_value abilityContext = nullptr; + + napi_status status = napi_get_global(env, &global); + if (status != napi_ok || global == nullptr) { + HILOGE("Cannot get global instance for %{public}d", status); + return nullptr; + } + + status = napi_get_named_property(env, global, "ability", &abilityContext); + if (status != napi_ok || abilityContext == nullptr) { + HILOGE("Cannot get ability context for %{public}d", status); + return nullptr; + } + + Ability *ability = nullptr; + status = napi_get_value_external(env, abilityContext, (void **)&ability); + if (status != napi_ok || ability == nullptr) { + HILOGE("Get ability form property failed for %{public}d", status); + } + + return ability; +} +} // namespace DistributedFS +} // namespace OHOS \ No newline at end of file diff --git a/interfaces/innerkits/js/common/ability_helper.h b/interfaces/innerkits/js/common/ability_helper.h new file mode 100644 index 000000000..e998027c0 --- /dev/null +++ b/interfaces/innerkits/js/common/ability_helper.h @@ -0,0 +1,27 @@ +/* + * Copyright (c) 2021 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. + */ + +#pragma once + +#include "../common/napi/uni_header.h" +#include "ability.h" + +namespace OHOS { +namespace DistributedFS { +struct AbilityHelper { + static AppExecFwk::Ability *GetJsAbility(napi_env env); +}; +} // namespace DistributedFS +} // namespace OHOS \ No newline at end of file diff --git a/interfaces/innerkits/js/common/fd_guard.cpp b/interfaces/innerkits/js/common/fd_guard.cpp new file mode 100644 index 000000000..fa4594573 --- /dev/null +++ b/interfaces/innerkits/js/common/fd_guard.cpp @@ -0,0 +1,46 @@ +/* + * Copyright (c) 2021 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 "fd_guard.h" + +#include + +namespace OHOS { +namespace DistributedFS { +FDGuard::FDGuard(int fd) : fd_(fd) {} + +FDGuard::~FDGuard() +{ + if (fd_ > 0) { + close(fd_); + } +} + +int FDGuard::GetFD() const +{ + return fd_; +} + +void FDGuard::SetFD(int fd) +{ + fd_ = fd; +} + +void FDGuard::ClearFD() +{ + fd_ = -1; +} +} // namespace DistributedFS +} // namespace OHOS \ No newline at end of file diff --git a/interfaces/innerkits/js/common/fd_guard.h b/interfaces/innerkits/js/common/fd_guard.h new file mode 100644 index 000000000..2db743831 --- /dev/null +++ b/interfaces/innerkits/js/common/fd_guard.h @@ -0,0 +1,34 @@ +/* + * Copyright (c) 2021 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. + */ + +#pragma once + +namespace OHOS { +namespace DistributedFS { +class FDGuard { +public: + FDGuard() = default; + explicit FDGuard(int fd); + ~FDGuard(); + + int GetFD() const; + void SetFD(int fd); + void ClearFD(); + +private: + int fd_ = -1; +}; +} // namespace DistributedFS +} // namespace OHOS diff --git a/interfaces/innerkits/js/common/log.h b/interfaces/innerkits/js/common/log.h new file mode 100644 index 000000000..32a09a751 --- /dev/null +++ b/interfaces/innerkits/js/common/log.h @@ -0,0 +1,90 @@ +/* + * Copyright (c) 2021 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. + */ + +#pragma once + +#include +#include +#include + +#ifndef FILE_SUBSYSTEM_DEV_ON_PC +#include "hilog/log.h" +#endif + +namespace OHOS { +namespace DistributedFS { +#ifndef FILE_SUBSYSTEM_DEV_ON_PC +static constexpr int FILEIO_DOMAIN_ID = 0; +static constexpr OHOS::HiviewDFX::HiLogLabel FILEIO_LABEL = { LOG_CORE, FILEIO_DOMAIN_ID, "distributedfilejs" }; + +#ifdef HILOGD +#undef HILOGD +#endif + +#ifdef HILOGF +#undef HILOGF +#endif + +#ifdef HILOGE +#undef HILOGE +#endif + +#ifdef HILOGW +#undef HILOGW +#endif + +#ifdef HILOGI +#undef HILOGI +#endif + +#define HILOGD(fmt, ...) \ + (void)OHOS::HiviewDFX::HiLog::Debug(OHOS::DistributedFS::FILEIO_LABEL, "%{public}s: " fmt, __func__, ##__VA_ARGS__) +#define HILOGI(fmt, ...) \ + (void)OHOS::HiviewDFX::HiLog::Info(OHOS::DistributedFS::FILEIO_LABEL, "%{public}s: " fmt, __func__, ##__VA_ARGS__) +#define HILOGW(fmt, ...) \ + (void)OHOS::HiviewDFX::HiLog::Warn(OHOS::DistributedFS::FILEIO_LABEL, "%{public}s: " fmt, __func__, ##__VA_ARGS__) +#define HILOGE(fmt, ...) \ + (void)OHOS::HiviewDFX::HiLog::Error(OHOS::DistributedFS::FILEIO_LABEL, "%{public}s: " fmt, __func__, ##__VA_ARGS__) +#define HILOGF(fmt, ...) \ + (void)OHOS::HiviewDFX::HiLog::Fatal(OHOS::DistributedFS::FILEIO_LABEL, "%{public}s: " fmt, __func__, ##__VA_ARGS__) + +#else + +#define PCLOG(fmt, ...) \ + do { \ + const std::vector filter = { \ + "{public}", \ + "{private}", \ + }; \ + std::string str____(fmt); \ + for (auto &&pattern : filter) { \ + size_t pos = 0; \ + while (std::string::npos != (pos = str____.find(pattern))) { \ + str____.erase(pos, pattern.length()); \ + } \ + } \ + str____ += "\n"; \ + printf(str____.c_str(), ##__VA_ARGS__); \ + } while (0); + +#define HILOGD(fmt, ...) PCLOG("%{public}s: " fmt, __func__, ##__VA_ARGS__) +#define HILOGI(fmt, ...) PCLOG("%{public}s: " fmt, __func__, ##__VA_ARGS__) +#define HILOGW(fmt, ...) PCLOG("%{public}s: " fmt, __func__, ##__VA_ARGS__) +#define HILOGE(fmt, ...) PCLOG("%{public}s: " fmt, __func__, ##__VA_ARGS__) +#define HILOGF(fmt, ...) PCLOG("%{public}s: " fmt, __func__, ##__VA_ARGS__) + +#endif +} // namespace DistributedFS +} // namespace OHOS \ No newline at end of file diff --git a/interfaces/innerkits/js/common/napi/n_async/n_async_context.h b/interfaces/innerkits/js/common/napi/n_async/n_async_context.h new file mode 100644 index 000000000..e62c43669 --- /dev/null +++ b/interfaces/innerkits/js/common/napi/n_async/n_async_context.h @@ -0,0 +1,69 @@ +/* + * Copyright (c) 2021 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 N_ASYNC_CONTEXT_H +#define N_ASYNC_CONTEXT_H + +#include + +#include "../../uni_error.h" +#include "../n_val.h" +#include "n_ref.h" + +namespace OHOS { +namespace DistributedFS { +using NContextCBExec = std::function; +using NContextCBComplete = std::function; + +class NAsyncContext { +public: + UniError err_; + NVal res_; + NContextCBExec cbExec_; + NContextCBComplete cbComplete_; + napi_async_work awork_; + NRef thisPtr_; + + explicit NAsyncContext(NVal thisPtr) : thisPtr_(thisPtr) {} + ~NAsyncContext() = default; +}; + +class NAsyncContextPromise : public NAsyncContext { +public: + napi_deferred deferred_; + explicit NAsyncContextPromise(NVal thisPtr) : NAsyncContext(thisPtr) {} + ~NAsyncContextPromise() = default; +}; + +class NAsyncContextCallback : public NAsyncContext { +public: + NRef cb_; + NAsyncContextCallback(NVal thisPtr, NVal cb) : NAsyncContext(thisPtr), cb_(cb) {} + ~NAsyncContextCallback() = default; +}; + +class NAsyncContextLegacy : public NAsyncContext { +public: + NRef cbSucc_; + NRef cbFail_; + NRef cbFinal_; + NAsyncContextLegacy(NVal thisPtr, NVal cbSucc, NVal cbFail, NVal cbFinal) + : NAsyncContext(thisPtr), cbSucc_(cbSucc), cbFail_(cbFail), cbFinal_(cbFinal) + {} + ~NAsyncContextLegacy() = default; +}; +} // namespace DistributedFS +} // namespace OHOS +#endif // N_ASYNC_CONTEXT_H \ No newline at end of file diff --git a/interfaces/innerkits/js/common/napi/n_async/n_async_work_callback.cpp b/interfaces/innerkits/js/common/napi/n_async/n_async_work_callback.cpp new file mode 100644 index 000000000..f3d4874a2 --- /dev/null +++ b/interfaces/innerkits/js/common/napi/n_async/n_async_work_callback.cpp @@ -0,0 +1,94 @@ +/* + * Copyright (c) 2021 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 "n_async_work_callback.h" +#include "../../log.h" + +namespace OHOS { +namespace DistributedFS { +using namespace std; + +NAsyncWorkCallback::NAsyncWorkCallback(napi_env env, NVal thisPtr, NVal cb) : NAsyncWorkFactory(env) +{ + ctx_ = new NAsyncContextCallback(thisPtr, cb); +} + +static void CallbackExecute(napi_env env, void *data) +{ + auto ctx = static_cast(data); + if (ctx->cbExec_) { + ctx->err_ = ctx->cbExec_(env); + } +} +static void CallbackComplete(napi_env env, napi_status status, void *data) +{ + napi_handle_scope scope = nullptr; + napi_open_handle_scope(env, &scope); + auto ctx = static_cast(data); + if (ctx->cbComplete_) { + ctx->res_ = ctx->cbComplete_(env, ctx->err_); + ctx->cbComplete_ = nullptr; + } + + vector argv; + if (!ctx->res_.TypeIsError(true)) { + argv = { UniError(ERRNO_NOERR).GetNapiErr(env), ctx->res_.val_ }; + } else { + argv = { ctx->res_.val_ }; + } + + napi_value global = nullptr; + napi_value callback = ctx->cb_.Deref(env).val_; + napi_value tmp = nullptr; + napi_get_global(env, &global); + napi_status stat = napi_call_function(env, global, callback, argv.size(), argv.data(), &tmp); + if (stat != napi_ok) { + HILOGE("Failed to call function for %{public}d", stat); + } + napi_close_handle_scope(env, scope); + napi_delete_async_work(env, ctx->awork_); + delete ctx; +} + +NVal NAsyncWorkCallback::Schedule(string procedureName, NContextCBExec cbExec, NContextCBComplete cbComplete) +{ + if (!ctx_->cb_ || !ctx_->cb_.Deref(env_).TypeIs(napi_function)) { + UniError(EINVAL).ThrowErr(env_, "The callback shall be a funciton"); + return NVal(); + } + + ctx_->cbExec_ = move(cbExec); + ctx_->cbComplete_ = move(cbComplete); + + napi_value resource = NVal::CreateUTF8String(env_, procedureName).val_; + + napi_status status = + napi_create_async_work(env_, nullptr, resource, CallbackExecute, CallbackComplete, ctx_, &ctx_->awork_); + if (status != napi_ok) { + HILOGE("INNER BUG. Failed to create async work for %{public}d", status); + return NVal(); + } + + status = napi_queue_async_work(env_, ctx_->awork_); + if (status != napi_ok) { + HILOGE("INNER BUG. Failed to queue async work for %{public}d", status); + return NVal(); + } + + ctx_ = nullptr; // The ownership of ctx_ has been transfered + return NVal::CreateUndefined(env_); +} +} // namespace DistributedFS +} // namespace OHOS diff --git a/interfaces/innerkits/js/common/napi/n_async/n_async_work_callback.h b/interfaces/innerkits/js/common/napi/n_async/n_async_work_callback.h new file mode 100644 index 000000000..9bc6d5f3d --- /dev/null +++ b/interfaces/innerkits/js/common/napi/n_async/n_async_work_callback.h @@ -0,0 +1,35 @@ +/* + * Copyright (c) 2021 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 N_ASYNC_WORK_CALLBACK_H +#define N_ASYNC_WORK_CALLBACK_H + +#include "n_async_work_factory.h" + +namespace OHOS { +namespace DistributedFS { +class NAsyncWorkCallback : public NAsyncWorkFactory { +public: + NAsyncWorkCallback(napi_env env, NVal thisPtr, NVal cb); + ~NAsyncWorkCallback() = default; + + NVal Schedule(std::string procedureName, NContextCBExec cbExec, NContextCBComplete cbComplete) final; + +private: + NAsyncContextCallback *ctx_ = nullptr; +}; +} // namespace DistributedFS +} // namespace OHOS +#endif // N_ASYNC_WORK_CALLBACK_H \ No newline at end of file diff --git a/interfaces/innerkits/js/common/napi/n_async/n_async_work_factory.h b/interfaces/innerkits/js/common/napi/n_async/n_async_work_factory.h new file mode 100644 index 000000000..deb664548 --- /dev/null +++ b/interfaces/innerkits/js/common/napi/n_async/n_async_work_factory.h @@ -0,0 +1,33 @@ +/* + * Copyright (c) 2021 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 N_ASYNC_WORK_FACTORY_H +#define N_ASYNC_WORK_FACTORY_H + +#include "n_async_context.h" + +namespace OHOS { +namespace DistributedFS { +class NAsyncWorkFactory { +public: + explicit NAsyncWorkFactory(napi_env env) : env_(env) {} + ~NAsyncWorkFactory() = default; + virtual NVal Schedule(std::string procedureName, NContextCBExec cbExec, NContextCBComplete cbComplete) = 0; + + napi_env env_ = nullptr; +}; +} // namespace DistributedFS +} // namespace OHOS +#endif // N_ASYNC_WORK_FACTORY_H \ No newline at end of file diff --git a/interfaces/innerkits/js/common/napi/n_async/n_async_work_promise.cpp b/interfaces/innerkits/js/common/napi/n_async/n_async_work_promise.cpp new file mode 100644 index 000000000..443cb2f01 --- /dev/null +++ b/interfaces/innerkits/js/common/napi/n_async/n_async_work_promise.cpp @@ -0,0 +1,88 @@ +/* + * Copyright (c) 2021 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 "n_async_work_promise.h" +#include "../../log.h" + +namespace OHOS { +namespace DistributedFS { +using namespace std; + +NAsyncWorkPromise::NAsyncWorkPromise(napi_env env, NVal thisPtr) : NAsyncWorkFactory(env) +{ + ctx_ = new NAsyncContextPromise(thisPtr); +} + +static void PromiseOnExec(napi_env env, void *data) +{ + auto ctx = static_cast(data); + if (ctx->cbExec_) { + ctx->err_ = ctx->cbExec_(env); + } +} +static void PromiseOnComplete(napi_env env, napi_status status, void *data) +{ + auto ctx = static_cast(data); + if (ctx->cbComplete_) { + ctx->res_ = ctx->cbComplete_(env, ctx->err_); + } + if (!ctx->res_.TypeIsError(true)) { + napi_status status = napi_resolve_deferred(env, ctx->deferred_, ctx->res_.val_); + if (status != napi_ok) { + HILOGE("Internal BUG, cannot resolve promise for %{public}d", status); + } + } else { + napi_status status = napi_reject_deferred(env, ctx->deferred_, ctx->res_.val_); + if (status != napi_ok) { + HILOGE("Internal BUG, cannot reject promise for %{public}d", status); + } + } + ctx->deferred_ = nullptr; + napi_delete_async_work(env, ctx->awork_); + delete ctx; +} + + +NVal NAsyncWorkPromise::Schedule(string procedureName, NContextCBExec cbExec, NContextCBComplete cbComplete) +{ + ctx_->cbExec_ = move(cbExec); + ctx_->cbComplete_ = move(cbComplete); + + napi_status status; + napi_value result = nullptr; + status = napi_create_promise(env_, &ctx_->deferred_, &result); + if (status != napi_ok) { + HILOGE("INNER BUG. Cannot create promise for %{public}d", status); + return NVal(); + } + + napi_value resource = NVal::CreateUTF8String(env_, procedureName).val_; + status = napi_create_async_work(env_, nullptr, resource, PromiseOnExec, PromiseOnComplete, ctx_, &ctx_->awork_); + if (status != napi_ok) { + HILOGE("INNER BUG. Failed to create async work for %{public}d", status); + return NVal(); + } + + status = napi_queue_async_work(env_, ctx_->awork_); + if (status != napi_ok) { + HILOGE("INNER BUG. Failed to queue async work for %{public}d", status); + return NVal(); + } + + ctx_ = nullptr; // The ownership of ctx_ has been transfered + return { env_, result }; +} +} // namespace DistributedFS +} // namespace OHOS diff --git a/interfaces/innerkits/js/common/napi/n_async/n_async_work_promise.h b/interfaces/innerkits/js/common/napi/n_async/n_async_work_promise.h new file mode 100644 index 000000000..8a049de65 --- /dev/null +++ b/interfaces/innerkits/js/common/napi/n_async/n_async_work_promise.h @@ -0,0 +1,35 @@ +/* + * Copyright (c) 2021 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 N_ASYNC_WORK_PROMISE_H +#define N_ASYNC_WORK_PROMISE_H + +#include "n_async_work_factory.h" + +namespace OHOS { +namespace DistributedFS { +class NAsyncWorkPromise : public NAsyncWorkFactory { +public: + NAsyncWorkPromise(napi_env env, NVal thisPtr); + ~NAsyncWorkPromise() = default; + + NVal Schedule(std::string procedureName, NContextCBExec cbExec, NContextCBComplete cbComplete) final; + +private: + NAsyncContextPromise *ctx_; +}; +} // namespace DistributedFS +} // namespace OHOS +#endif // N_ASYNC_WORK_PROMISE_H \ No newline at end of file diff --git a/interfaces/innerkits/js/common/napi/n_async/n_ref.cpp b/interfaces/innerkits/js/common/napi/n_async/n_ref.cpp new file mode 100644 index 000000000..8b78ac9c8 --- /dev/null +++ b/interfaces/innerkits/js/common/napi/n_async/n_ref.cpp @@ -0,0 +1,53 @@ +/* + * Copyright (c) 2021 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 "n_ref.h" + +namespace OHOS { +namespace DistributedFS { +NRef::NRef() {} + +NRef::NRef(NVal val) +{ + if (val) { + env_ = val.env_; + napi_create_reference(val.env_, val.val_, 1, &ref_); + } +} + +NRef::~NRef() +{ + if (ref_) { + napi_delete_reference(env_, ref_); + } +} + +NRef::operator bool() const +{ + return ref_ != nullptr; +} + +NVal NRef::Deref(napi_env env) +{ + if (!ref_) { + return NVal(); + } + + napi_value val = nullptr; + napi_get_reference_value(env, ref_, &val); + return { env, val }; +} +} // namespace DistributedFS +} // namespace OHOS diff --git a/interfaces/innerkits/js/common/napi/n_async/n_ref.h b/interfaces/innerkits/js/common/napi/n_async/n_ref.h new file mode 100644 index 000000000..a9f166cfc --- /dev/null +++ b/interfaces/innerkits/js/common/napi/n_async/n_ref.h @@ -0,0 +1,38 @@ +/* + * Copyright (c) 2021 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 N_REF_H +#define N_REF_H + +#include "../n_val.h" + +namespace OHOS { +namespace DistributedFS { +class NRef { +public: + NRef(); + explicit NRef(NVal val); + ~NRef(); + + explicit operator bool() const; + NVal Deref(napi_env env); + +private: + napi_env env_ = nullptr; + napi_ref ref_ = nullptr; +}; +} // namespace DistributedFS +} // namespace OHOS +#endif // N_REF_H \ No newline at end of file diff --git a/interfaces/innerkits/js/common/napi/n_class.cpp b/interfaces/innerkits/js/common/napi/n_class.cpp new file mode 100644 index 000000000..0e9028b02 --- /dev/null +++ b/interfaces/innerkits/js/common/napi/n_class.cpp @@ -0,0 +1,99 @@ +/* + * Copyright (c) 2021 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 "n_class.h" + +#include +#include + +#include "../log.h" + +namespace OHOS { +namespace DistributedFS { +using namespace std; +NClass &NClass::GetInstance() +{ + static NClass nClass; + return nClass; +} + +tuple NClass::DefineClass(napi_env env, + string className, + napi_callback constructor, + vector &&properties) +{ + napi_value classVal = nullptr; + napi_status stat = napi_define_class(env, + className.c_str(), + className.length(), + constructor, + nullptr, + properties.size(), + properties.data(), + &classVal); + if (stat != napi_ok) { + HILOGE("INNER BUG. Cannot define class %{public}s because of %{public}d", className.c_str(), stat); + } + return { stat == napi_ok, classVal }; +} + +bool NClass::SaveClass(napi_env env, string className, napi_value exClass) +{ + NClass &nClass = NClass::GetInstance(); + lock_guard(nClass.exClassMapLock); + + if (nClass.exClassMap.find(className) != nClass.exClassMap.end()) { + return true; + } + + napi_ref constructor; + napi_status res = napi_create_reference(env, exClass, 1, &constructor); + if (res == napi_ok) { + nClass.exClassMap.insert({ className, constructor }); + HILOGI("Class %{public}s has been saved", className.c_str()); + } else { + HILOGE("INNER BUG. Cannot ref class constructor %{public}s because of %{public}d", className.c_str(), res); + } + return res == napi_ok; +} + +napi_value NClass::InstantiateClass(napi_env env, string className, vector args) +{ + NClass &nClass = NClass::GetInstance(); + lock_guard(nClass.exClassMapLock); + + auto it = nClass.exClassMap.find(className); + if (it == nClass.exClassMap.end()) { + HILOGE("Class %{public}s hasn't been saved yet", className.c_str()); + return nullptr; + } + + napi_value cons = nullptr; + napi_status status = napi_get_reference_value(env, it->second, &cons); + if (status != napi_ok) { + HILOGE("INNER BUG. Cannot deref class %{public}s because of %{public}d", className.c_str(), status); + return nullptr; + } + + napi_value instance = nullptr; + status = napi_new_instance(env, cons, args.size(), args.data(), &instance); + if (status != napi_ok) { + HILOGE("INNER BUG. Cannot instantiate the class %{public}s because of %{public}d", className.c_str(), status); + return nullptr; + } + return instance; +} +} // namespace DistributedFS +} // namespace OHOS \ No newline at end of file diff --git a/interfaces/innerkits/js/common/napi/n_class.h b/interfaces/innerkits/js/common/napi/n_class.h new file mode 100644 index 000000000..db9a90ca0 --- /dev/null +++ b/interfaces/innerkits/js/common/napi/n_class.h @@ -0,0 +1,82 @@ +/* + * Copyright (c) 2021 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. + */ + +#pragma once + +#include "uni_header.h" + +#include +#include +#include +#include +#include +#include + +#include "../log.h" + +namespace OHOS { +namespace DistributedFS { +class NClass final { +public: + NClass(const NClass &) = delete; + NClass &operator = (const NClass &) = delete; + static NClass &GetInstance(); + + static std::tuple DefineClass(napi_env env, + std::string className, + napi_callback constructor, + std::vector &&properties); + static bool SaveClass(napi_env env, std::string className, napi_value exClass); + static napi_value InstantiateClass(napi_env env, std::string className, std::vector args); + + template static T *GetEntityOf(napi_env env, napi_value objStat) + { + if (!env || !objStat) { + HILOGE("Empty input: env %d, obj %d", env == nullptr, objStat == nullptr); + return nullptr; + } + T *t = nullptr; + napi_status status = napi_unwrap(env, objStat, (void **)&t); + if (status != napi_ok) { + HILOGE("Cannot umwarp for pointer: %d", status); + return nullptr; + } + return t; + } + + template static bool SetEntityFor(napi_env env, napi_value obj, std::unique_ptr entity) + { + napi_status status = napi_wrap( + env, + obj, + entity.get(), + [](napi_env env, void *data, void *hint) { + auto entity = static_cast(data); + delete entity; + }, + nullptr, + nullptr); + entity.release(); + return status == napi_ok; + } + +private: + NClass() = default; + ~NClass() = default; + std::map exClassMap; + std::mutex exClassMapLock; +}; +} // namespace DistributedFS +} // namespace OHOS \ No newline at end of file diff --git a/interfaces/innerkits/js/common/napi/n_exporter.h b/interfaces/innerkits/js/common/napi/n_exporter.h new file mode 100644 index 000000000..2ade0c076 --- /dev/null +++ b/interfaces/innerkits/js/common/napi/n_exporter.h @@ -0,0 +1,39 @@ +/* + * Copyright (c) 2021 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. + */ + +#pragma once + +#include "uni_header.h" + +#include +#include + +#include "n_val.h" + +namespace OHOS { +namespace DistributedFS { +class NExporter { +public: + NExporter(napi_env env, napi_value exports) : exports_(env, exports) {}; + virtual ~NExporter() = default; + + virtual bool Export() = 0; + virtual std::string GetClassName() = 0; + +protected: + NVal exports_; +}; +} // namespace DistributedFS +} // namespace OHOS \ No newline at end of file diff --git a/interfaces/innerkits/js/common/napi/n_func_arg.cpp b/interfaces/innerkits/js/common/napi/n_func_arg.cpp new file mode 100644 index 000000000..123ef8d0a --- /dev/null +++ b/interfaces/innerkits/js/common/napi/n_func_arg.cpp @@ -0,0 +1,111 @@ +/* + * Copyright (c) 2021 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 "n_func_arg.h" + +#include +#include + +#include "../log.h" +#include "../uni_error.h" + +namespace OHOS { +namespace DistributedFS { +using namespace std; + +NFuncArg::NFuncArg(napi_env env, napi_callback_info info) : env_(env), info_(info) {} + +NFuncArg::~NFuncArg() {} + +void NFuncArg::SetArgc(size_t argc) +{ + argc_ = argc; +} +void NFuncArg::SetThisVar(napi_value thisVar) +{ + thisVar_ = thisVar; +} + +size_t NFuncArg::GetArgc(void) const +{ + return argc_; +} + +napi_value NFuncArg::GetThisVar(void) const +{ + return thisVar_; +} + +napi_value NFuncArg::GetArg(size_t argPos) const +{ + return (argPos < GetArgc()) ? argv_[argPos] : nullptr; +} + +napi_value NFuncArg::operator[](size_t argPos) const +{ + return GetArg(argPos); +} + +bool NFuncArg::InitArgs(std::function argcChecker) +{ + SetArgc(0); + argv_.reset(); + + size_t argc; + napi_value thisVar; + napi_status status = napi_get_cb_info(env_, info_, &argc, nullptr, &thisVar, nullptr); + if (status != napi_ok) { + HILOGE("Cannot get num of func args for %{public}d", status); + return false; + } + if (argc) { + argv_ = make_unique(argc); + status = napi_get_cb_info(env_, info_, &argc, argv_.get(), &thisVar, nullptr); + if (status != napi_ok) { + HILOGE("Cannot get func args for %{public}d", status); + return false; + } + } + SetArgc(argc); + SetThisVar(thisVar); + + return argcChecker(); +} + +bool NFuncArg::InitArgs(size_t argc) +{ + return InitArgs([argc, this]() { + size_t realArgc = GetArgc(); + if (argc != realArgc) { + HILOGE("Num of args recved eq %zu while expecting %{public}zu", realArgc, argc); + return false; + } + return true; + }); +} + +bool NFuncArg::InitArgs(size_t minArgc, size_t maxArgc) +{ + return InitArgs([minArgc, maxArgc, this]() { + size_t realArgc = GetArgc(); + if (minArgc > realArgc || maxArgc < realArgc) { + HILOGE("Num of args recved eq %zu while expecting %{public}zu ~ %{public}zu", realArgc, minArgc, maxArgc); + return false; + } + return true; + }); +} +} // namespace DistributedFS +} // namespace OHOS diff --git a/interfaces/innerkits/js/common/napi/n_func_arg.h b/interfaces/innerkits/js/common/napi/n_func_arg.h new file mode 100644 index 000000000..ba7a7dd5a --- /dev/null +++ b/interfaces/innerkits/js/common/napi/n_func_arg.h @@ -0,0 +1,74 @@ +/* + * Copyright (c) 2021 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. + */ + +#pragma once + +#include +#include +#include +#include + +#include "n_val.h" +#include "uni_header.h" + +namespace OHOS { +namespace DistributedFS { +enum NARG_CNT { + ZERO = 0, + ONE = 1, + TWO = 2, + THREE = 3, + FOUR = 4, + FIVE = 5 +}; + +enum NARG_POS { + FIRST = 0, + SECOND = 1, + THIRD = 2, + FOURTH = 3, + FIFTH = 4, + SIXTH = 5 +}; + +class NFuncArg final { +public: + NFuncArg(napi_env env, napi_callback_info info); + virtual ~NFuncArg(); + + bool InitArgs(size_t argc); + bool InitArgs(size_t minArgc, size_t maxArgc); + + size_t GetArgc() const; + napi_value GetThisVar() const; + + napi_value operator[](size_t idx) const; + napi_value GetArg(size_t argPos) const; + +private: + napi_env env_ = nullptr; + napi_callback_info info_ = nullptr; + + size_t argc_ = 0; + std::unique_ptr argv_ = { nullptr }; + napi_value thisVar_ = nullptr; + + bool InitArgs(std::function argcChecker); + + void SetArgc(size_t argc); + void SetThisVar(napi_value thisVar); +}; +} // namespace DistributedFS +} // namespace OHOS \ No newline at end of file diff --git a/interfaces/innerkits/js/common/napi/n_val.cpp b/interfaces/innerkits/js/common/napi/n_val.cpp new file mode 100644 index 000000000..90aeab48e --- /dev/null +++ b/interfaces/innerkits/js/common/napi/n_val.cpp @@ -0,0 +1,291 @@ +/* + * Copyright (c) 2021 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 "n_val.h" + +#include +#include + +#include "../log.h" +#include "../uni_error.h" + +namespace OHOS { +namespace DistributedFS { +using namespace std; + +NVal::NVal(napi_env nEnv, napi_value nVal = nullptr) : env_(nEnv), val_(nVal) {} + +NVal::operator bool() const +{ + return env_ && val_; +} + +bool NVal::TypeIs(napi_valuetype expType) const +{ + if (!*this) + return false; + + napi_valuetype valueType; + napi_typeof(env_, val_, &valueType); + + if (expType != valueType) { + return false; + } + return true; +} + +bool NVal::TypeIsError(bool checkErrno) const +{ + if (!*this) { + return false; + } + + bool res = false; + napi_is_error(env_, val_, &res); + + return res; +} + +tuple, size_t> NVal::ToUTF8String() const +{ + size_t strLen = 0; + napi_status status = napi_get_value_string_utf8(env_, val_, nullptr, -1, &strLen); + if (status != napi_ok) { + return { false, nullptr, 0 }; + } + + size_t bufLen = strLen + 1; + unique_ptr str = make_unique(bufLen); + status = napi_get_value_string_utf8(env_, val_, str.get(), bufLen, &strLen); + return make_tuple(status == napi_ok, move(str), strLen); +} + +tuple, size_t> NVal::ToUTF16String() const +{ +#ifdef FILE_SUBSYSTEM_DEV_ON_PC + size_t strLen = 0; + napi_status status = napi_get_value_string_utf16(env_, val_, nullptr, -1, &strLen); + if (status != napi_ok) { + return { false, nullptr, 0 }; + } + + auto str = make_unique(++strLen); + status = napi_get_value_string_utf16(env_, val_, str.get(), strLen, nullptr); + if (status != napi_ok) { + return { false, nullptr, 0 }; + } + + strLen = reinterpret_cast(str.get() + strLen) - reinterpret_cast(str.get()); + auto strRet = unique_ptr(reinterpret_cast(str.release())); + return { true, move(strRet), strLen }; +#else + // Note that quickjs doesn't support utf16 + return ToUTF8String(); +#endif +} + +tuple NVal::ToPointer() const +{ + void *res = nullptr; + napi_status status = napi_get_value_external(env_, val_, &res); + return make_tuple(status == napi_ok, res); +} + +tuple NVal::ToBool() const +{ + bool flag = false; + napi_status status = napi_get_value_bool(env_, val_, &flag); + return make_tuple(status == napi_ok, flag); +} + +tuple NVal::ToInt32() const +{ + int32_t res = 0; + napi_status status = napi_get_value_int32(env_, val_, &res); + return make_tuple(status == napi_ok, res); +} + +tuple NVal::ToInt64() const +{ + int64_t res = 0; + napi_status status = napi_get_value_int64(env_, val_, &res); + return make_tuple(status == napi_ok, res); +} + +tuple NVal::ToArraybuffer() const +{ + void *buf = nullptr; + size_t bufLen = 0; + bool status = napi_get_arraybuffer_info(env_, val_, &buf, &bufLen); + return make_tuple(status == napi_ok, buf, bufLen); +} + +tuple NVal::ToTypedArray() const +{ + napi_typedarray_type type; + napi_value in_array_buffer = nullptr; + size_t byte_offset; + size_t length; + void *data = nullptr; + napi_status status = + napi_get_typedarray_info(env_, val_, &type, &length, (void **)&data, &in_array_buffer, &byte_offset); + return make_tuple(status == napi_ok, data, length); +} + +bool NVal::HasProp(string propName) const +{ + bool res = false; + + if (!env_ || !val_ || !TypeIs(napi_object)) + return false; + napi_status status = napi_has_named_property(env_, val_, propName.c_str(), &res); + return (status == napi_ok) && res; +} + +NVal NVal::GetProp(string propName) const +{ + if (!HasProp(propName)) { + return { env_, nullptr }; + } + napi_value prop = nullptr; + napi_status status = napi_get_named_property(env_, val_, propName.c_str(), &prop); + if (status != napi_ok) { + return { env_, nullptr }; + } + return NVal(env_, prop); +} + +bool NVal::AddProp(vector &&propVec) const +{ + if (!TypeIs(napi_valuetype::napi_object)) { + HILOGE("INNER BUG. Prop should only be added to objects"); + return false; + } + napi_status status = napi_define_properties(env_, val_, propVec.size(), propVec.data()); + if (status != napi_ok) { + HILOGE("INNER BUG. Cannot define properties because of %{public}d", status); + return false; + } + return true; +} + +bool NVal::AddProp(string propName, napi_value val) const +{ + if (!TypeIs(napi_valuetype::napi_object) || HasProp(propName)) { + HILOGE("INNER BUG. Prop should only be added to objects"); + return false; + } + + napi_status status = napi_set_named_property(env_, val_, propName.c_str(), val); + if (status != napi_ok) { + HILOGE("INNER BUG. Cannot set named property because of %{public}d", status); + return false; + } + return true; +} + +NVal NVal::CreateUndefined(napi_env env) +{ + napi_value res = nullptr; + napi_get_undefined(env, &res); + return { env, res }; +} + +NVal NVal::CreateInt64(napi_env env, int64_t val) +{ + napi_value res = nullptr; + napi_create_int64(env, val, &res); + return { env, res }; +} + +NVal NVal::CreateInt32(napi_env env, int32_t val) +{ + napi_value res = nullptr; + napi_create_int32(env, val, &res); + return { env, res }; +} + +NVal NVal::CreateObject(napi_env env) +{ + napi_value res = nullptr; + napi_create_object(env, &res); + return { env, res }; +} + +NVal NVal::CreateBool(napi_env env, bool val) +{ + napi_value res = nullptr; + napi_get_boolean(env, val, &res); + return { env, res }; +} + +NVal NVal::CreateUTF8String(napi_env env, std::string str) +{ + napi_value res = nullptr; + napi_create_string_utf8(env, str.c_str(), str.length(), &res); + return { env, res }; +} + +NVal NVal::CreateUint8Array(napi_env env, void *buf, size_t bufLen) +{ + napi_value output_buffer = nullptr; + napi_create_external_arraybuffer( + env, + buf, + bufLen, + [](napi_env env, void *finalize_data, void *finalize_hint) { free(finalize_data); }, + NULL, + &output_buffer); + napi_value output_array = nullptr; + napi_create_typedarray(env, napi_uint8_array, bufLen, output_buffer, 0, &output_array); + return { env, output_array }; +} + +napi_property_descriptor NVal::DeclareNapiProperty(const char *name, napi_value val) +{ + return { (name), nullptr, nullptr, nullptr, nullptr, val, napi_default, nullptr }; +} + +napi_property_descriptor NVal::DeclareNapiStaticProperty(const char *name, napi_value val) +{ + return { (name), nullptr, nullptr, nullptr, nullptr, val, napi_static, nullptr }; +} + +napi_property_descriptor NVal::DeclareNapiFunction(const char *name, napi_callback func) +{ + return { (name), nullptr, (func), nullptr, nullptr, nullptr, napi_default, nullptr }; +} + +napi_property_descriptor NVal::DeclareNapiStaticFunction(const char *name, napi_callback func) +{ + return { (name), nullptr, (func), nullptr, nullptr, nullptr, napi_static, nullptr }; +} + +napi_property_descriptor NVal::DeclareNapiGetter(const char *name, napi_callback getter) +{ + return { (name), nullptr, nullptr, (getter), nullptr, nullptr, napi_default, nullptr }; +} + +napi_property_descriptor NVal::DeclareNapiSetter(const char *name, napi_callback setter) +{ + return { (name), nullptr, nullptr, nullptr, (setter), nullptr, napi_default, nullptr }; +} + +napi_property_descriptor NVal::DeclareNapiGetterSetter(const char *name, napi_callback getter, napi_callback setter) +{ + return { (name), nullptr, nullptr, (getter), (setter), nullptr, napi_default, nullptr }; +} +} // namespace DistributedFS +} // namespace OHOS \ No newline at end of file diff --git a/interfaces/innerkits/js/common/napi/n_val.h b/interfaces/innerkits/js/common/napi/n_val.h new file mode 100644 index 000000000..1dd808f2e --- /dev/null +++ b/interfaces/innerkits/js/common/napi/n_val.h @@ -0,0 +1,80 @@ +/* + * Copyright (c) 2021 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 N_VAL_H +#define N_VAL_H + +#include +#include +#include + +#include "uni_header.h" + +namespace OHOS { +namespace DistributedFS { +class NVal final { +public: + NVal() = default; + NVal(napi_env nEnv, napi_value nVal); + NVal &operator = (const NVal &) = default; + virtual ~NVal() = default; + + // NOTE! env_ and val_ is LIKELY to be null + napi_env env_ = nullptr; + napi_value val_ = nullptr; + + explicit operator bool() const; + bool TypeIs(napi_valuetype expType) const; + bool TypeIsError(bool checkErrno = false) const; + + /* SHOULD ONLY BE USED FOR EXPECTED TYPE */ + std::tuple, size_t> ToUTF8String() const; + std::tuple, size_t> ToUTF16String() const; + std::tuple ToPointer() const; + std::tuple ToBool() const; + std::tuple ToInt32() const; + std::tuple ToInt64() const; + std::tuple ToArraybuffer() const; + std::tuple ToTypedArray() const; + + /* Static helpers to create js objects */ + static NVal CreateUndefined(napi_env env); + static NVal CreateInt64(napi_env env, int64_t val); + static NVal CreateInt32(napi_env env, int32_t val); + static NVal CreateObject(napi_env env); + static NVal CreateBool(napi_env env, bool val); + static NVal CreateUTF8String(napi_env env, std::string str); + static NVal CreateUint8Array(napi_env env, void *buf, size_t bufLen); + + /* SHOULD ONLY BE USED FOR OBJECT */ + bool HasProp(std::string propName) const; + NVal GetProp(std::string propName) const; + bool AddProp(std::vector &&propVec) const; + bool AddProp(std::string propName, napi_value nVal) const; + + /* Static helpers to create prop of js objects */ + static napi_property_descriptor DeclareNapiProperty(const char *name, napi_value val); + static napi_property_descriptor DeclareNapiStaticProperty(const char *name, napi_value val); + static napi_property_descriptor DeclareNapiFunction(const char *name, napi_callback func); + static napi_property_descriptor DeclareNapiStaticFunction(const char *name, napi_callback func); + static napi_property_descriptor DeclareNapiGetter(const char *name, napi_callback getter); + static napi_property_descriptor DeclareNapiSetter(const char *name, napi_callback setter); + static inline napi_property_descriptor DeclareNapiGetterSetter(const char *name, + napi_callback getter, + napi_callback setter); +}; +} // namespace DistributedFS +} // namespace OHOS +#endif // N_VAL_H \ No newline at end of file diff --git a/interfaces/innerkits/js/common/napi/uni_header.h b/interfaces/innerkits/js/common/napi/uni_header.h new file mode 100644 index 000000000..a79d4e1ed --- /dev/null +++ b/interfaces/innerkits/js/common/napi/uni_header.h @@ -0,0 +1,23 @@ +/* + * Copyright (c) 2021 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. + */ + +#pragma once + +#ifdef FILE_SUBSYSTEM_DEV_ON_PC +#include +#else +#include "napi/native_api.h" +#include "napi/native_node_api.h" +#endif diff --git a/interfaces/innerkits/js/common/uni_error.cpp b/interfaces/innerkits/js/common/uni_error.cpp new file mode 100644 index 000000000..010aa3dad --- /dev/null +++ b/interfaces/innerkits/js/common/uni_error.cpp @@ -0,0 +1,118 @@ +/* + * Copyright (c) 2021 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 "uni_error.h" + +#include +#include + +#include "log.h" +#include "napi/n_val.h" + +namespace OHOS { +namespace DistributedFS { +using namespace std; + +UniError::UniError() {} + +UniError::UniError(ELegacy eLegacy) : errno_(eLegacy), codingSystem_(ERR_CODE_SYSTEM_LEGACY) {} + +UniError::UniError(int ePosix) : errno_(ePosix), codingSystem_(ERR_CODE_SYSTEM_POSIX) {} + +UniError::operator bool() const +{ + return errno_ != ERRNO_NOERR; +} + +int UniError::GetErrno(ErrCodeSystem cs) +{ + if (errno_ == ERRNO_NOERR) { + return ERRNO_NOERR; + } + if (cs == codingSystem_) { + return errno_; + } + + if (cs == ERR_CODE_SYSTEM_POSIX) { + // Note that we should support more codes here + return EINVAL; + } + + // Note that this shall be done properly + return ELEGACY_INVAL; +} + +void UniError::SetErrno(ELegacy eLegacy) +{ + errno_ = eLegacy; + codingSystem_ = ERR_CODE_SYSTEM_LEGACY; +} + +void UniError::SetErrno(int ePosix) +{ + errno_ = ePosix; + codingSystem_ = ERR_CODE_SYSTEM_POSIX; +} + +std::string UniError::GetDefaultErrstr() +{ + if (codingSystem_ != ERR_CODE_SYSTEM_POSIX && codingSystem_ != ERR_CODE_SYSTEM_LEGACY) { + return "BUG: Curious coding system"; + } + return strerror(GetErrno(ERR_CODE_SYSTEM_POSIX)); +} + +napi_value UniError::GetNapiErr(napi_env env) +{ + return GetNapiErr(env, GetDefaultErrstr()); +} + +napi_value UniError::GetNapiErr(napi_env env, string errMsg) +{ + napi_value code = NVal::CreateUTF8String(env, to_string(GetErrno(codingSystem_))).val_; + napi_value msg = NVal::CreateUTF8String(env, errMsg).val_; + + napi_value res = nullptr; + napi_status createRes = napi_create_error(env, code, msg, &res); + if (createRes) { + HILOGE("Failed to create an exception, msg = %{public}s", errMsg.c_str()); + } + return res; +} + +void UniError::ThrowErr(napi_env env) +{ + string msg = GetDefaultErrstr(); + napi_value tmp = nullptr; + napi_get_and_clear_last_exception(env, &tmp); + // Note that ace engine cannot thow errors created by napi_create_error so far + napi_status throwStatus = napi_throw_error(env, nullptr, msg.c_str()); + if (throwStatus != napi_ok) { + HILOGE("Failed to throw an exception, %{public}d, code = %{public}s", throwStatus, msg.c_str()); + } +} + +void UniError::ThrowErr(napi_env env, string errMsg) +{ + napi_value tmp = nullptr; + napi_get_and_clear_last_exception(env, &tmp); + // Note that ace engine cannot thow errors created by napi_create_error so far + napi_status throwStatus = napi_throw_error(env, nullptr, errMsg.c_str()); + if (throwStatus != napi_ok) { + HILOGE("Failed to throw an exception, %{public}d, code = %{public}s", throwStatus, errMsg.c_str()); + } +} +} // namespace DistributedFS +} // namespace OHOS \ No newline at end of file diff --git a/interfaces/innerkits/js/common/uni_error.h b/interfaces/innerkits/js/common/uni_error.h new file mode 100644 index 000000000..a4183986d --- /dev/null +++ b/interfaces/innerkits/js/common/uni_error.h @@ -0,0 +1,64 @@ +/* + * Copyright (c) 2021 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. + */ + +#pragma once + +#include +#include + +#include "napi/uni_header.h" + +namespace OHOS { +namespace DistributedFS { +constexpr int ERRNO_NOERR = 0; + +enum ELegacy { + ELEGACY_INVAL = 202, + ELEGACY_IO = 300, + ELEGACY_NOENT = 301, +}; + +enum ErrCodeSystem { + ERR_CODE_SYSTEM_LEGACY, + ERR_CODE_SYSTEM_POSIX, +}; + +class UniError { +public: + UniError(); + explicit UniError(ELegacy eLegacy); + explicit UniError(int ePosix); + ~UniError() = default; + + UniError &operator = (const UniError &) = default; + + explicit operator bool() const; + + void SetErrno(ELegacy eLegacy); + void SetErrno(int ePosix); + int GetErrno(ErrCodeSystem cs); + + std::string GetDefaultErrstr(); + napi_value GetNapiErr(napi_env env); + napi_value GetNapiErr(napi_env env, std::string errMsg); + void ThrowErr(napi_env env); + void ThrowErr(napi_env env, std::string errMsg); + +private: + int errno_ = ERRNO_NOERR; + ErrCodeSystem codingSystem_ = ERR_CODE_SYSTEM_POSIX; +}; +} // namespace DistributedFS +} // namespace OHOS \ No newline at end of file diff --git a/interfaces/innerkits/js/mod_sendfile/sendfile.cpp b/interfaces/innerkits/js/mod_sendfile/sendfile.cpp new file mode 100644 index 000000000..bac76883a --- /dev/null +++ b/interfaces/innerkits/js/mod_sendfile/sendfile.cpp @@ -0,0 +1,143 @@ +/* + * Copyright (c) 2021 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 "sendfile.h" + +#include + +#include "../common/napi/n_class.h" +#include "../common/napi/n_func_arg.h" +#include "../common/napi/n_val.h" +#include "../common/uni_error.h" + +#include "../common/napi/n_async/n_async_work_callback.h" +#include "../common/napi/n_async/n_async_work_promise.h" + +#include "system_ability_definition.h" +#include "i_distributedfile_service.h" +#include "service_proxy.h" + +#include +#include + +namespace OHOS { +namespace DistributedFS { +namespace ModuleSendFile { +// using namespace OHOS::DistributedFile; +using namespace OHOS::Storage::DistributedFile; + +napi_value SendFile(napi_env env, napi_callback_info info) +{ + HILOGI("napi_value SendFile Start"); + NFuncArg funcArg(env, info); + if (!funcArg.InitArgs(NARG_CNT::FOUR, NARG_CNT::FIVE)) { + UniError(EINVAL).ThrowErr(env, "Number of arguments unmatched"); + return nullptr; + } + + HILOGI("napi_value SendFile parse params"); + bool succ = false; + auto resultCode = std::make_shared(); + + std::unique_ptr deviceId; + std::vector sourPath; + std::vector destPath; + + uint32_t fileCount = 0; + + std::tie(succ, deviceId, std::ignore) = NVal(env, funcArg[NARG_POS::FIRST]).ToUTF8String(); + napi_get_value_uint32(env, funcArg[NARG_POS::FOURTH], &fileCount); + + HILOGI("SendFile::deviceId :%{public}s", deviceId.get()); + + napi_value result; + napi_status status; + for (uint32_t i=0; i < fileCount; i++) { + status = napi_get_element(env, funcArg[NARG_POS::SECOND], i, &result); + if (napi_ok != status) { + return nullptr; + } + std::unique_ptr path; + std::tie(succ, path, std::ignore) = NVal(env, result).ToUTF8String(); + sourPath.push_back(path.get()); + HILOGI("SendFile::JS_SendFile src[%{public}d]:%{public}s", i, sourPath.at(i).c_str()); + + status = napi_get_element(env, funcArg[NARG_POS::THIRD], i, &result); + if (napi_ok != status) { + return nullptr; + } + std::tie(succ, path, std::ignore) = NVal(env, result).ToUTF8String(); + destPath.push_back(path.get()); + HILOGI("SendFile::JS_SendFile src[%{public}d]:%{public}s", i, destPath.at(i).c_str()); + } + + HILOGI("napi_value source: %{public}d, dest: %{public}d", sourPath.size(), destPath.size()); + std::string deviceIdString(deviceId.get()); + auto cbExec = [deviceIdString, sourPath, destPath, fileCount, resultCode](napi_env env) -> UniError { + *resultCode = ExecSendFile(deviceIdString.c_str(), sourPath, destPath, fileCount); + HILOGI("cbExec resultCode : %{public}d", *resultCode); + return UniError(ERRNO_NOERR); + }; + + auto cbComplete = [resultCode](napi_env env, UniError err) -> NVal { + if (err) { + return { env, err.GetNapiErr(env) }; + } + HILOGI("cbComplete resultCode : %{public}d", *resultCode); + return { NVal::CreateInt64(env, *resultCode) }; + }; + + HILOGI("napi_value SendFile created thread params count %{public}d", funcArg.GetArgc()); + std::string procedureName = "SendFile"; + NVal thisVar(env, funcArg.GetThisVar()); + if (funcArg.GetArgc() == NARG_CNT::FOUR) { + HILOGI("promise function"); + return NAsyncWorkPromise(env, thisVar).Schedule(procedureName, cbExec, cbComplete).val_; + } else if (funcArg.GetArgc() == NARG_CNT::FIVE) { + HILOGI("callback function"); + NVal cb(env, funcArg[NARG_POS::FIFTH]); + return NAsyncWorkCallback(env, thisVar, cb).Schedule(procedureName, cbExec, cbComplete).val_; + } + HILOGI("napi_value SendFile End"); + return NVal::CreateUndefined(env).val_; +} + +int32_t ExecSendFile(const std::string deviceId, const std::vector& srcList, const std::vector& dstList, uint32_t num) +{ + sptr systemAbilityMgr = + SystemAbilityManagerClient::GetInstance().GetSystemAbilityManager(); + if (systemAbilityMgr == nullptr) { + HILOGE("BundleService Get ISystemAbilityManager failed ... \n"); + return -1; + } + sptr remote = systemAbilityMgr->CheckSystemAbility(STORAGE_DISTRIBUTED_FILE_SERVICE_SA_ID); + if (remote == nullptr) { + HILOGE("DistributedFileService Get STORAGE_DISTRIBUTED_FILE_SERVICE_SA_ID = %d fail ... \n", STORAGE_DISTRIBUTED_FILE_SERVICE_SA_ID); + return -1; + } + + sptr distributedFileService = iface_cast(remote); + if (distributedFileService == nullptr) { + HILOGE("DistributedFileService == nullptr\n"); + return -1; + } + + HILOGE("DistributedFileService == distributedFileService"); + int32_t result = 0;//distributedFileService->SendDistributedFile(deviceId, sessionID, srcList, dstList, num); + return result; +} +} // namespace ModuleSendFile +} // namespace DistributedFS +} // namespace OHOS \ No newline at end of file diff --git a/interfaces/innerkits/js/mod_sendfile/sendfile.h b/interfaces/innerkits/js/mod_sendfile/sendfile.h new file mode 100644 index 000000000..7484ec686 --- /dev/null +++ b/interfaces/innerkits/js/mod_sendfile/sendfile.h @@ -0,0 +1,31 @@ +/* + * Copyright (c) 2021 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 SENDFILE_H +#define SENDFILE_H + +#include +#include "../common/napi/n_exporter.h" + +namespace OHOS { +namespace DistributedFS { +namespace ModuleSendFile { +napi_value SendFile(napi_env env, napi_callback_info info); + +static int32_t ExecSendFile(const std::string deviceId, const std::vector& srcList, const std::vector& dstList, uint32_t num); +} // namespace ModuleSendFile +} // namespace DistributedFS +} // namespace OHOS +#endif // SENDFILE_H \ No newline at end of file diff --git a/interfaces/innerkits/js/mod_sendfile/sendfile_napi.cpp b/interfaces/innerkits/js/mod_sendfile/sendfile_napi.cpp new file mode 100644 index 000000000..b15ede648 --- /dev/null +++ b/interfaces/innerkits/js/mod_sendfile/sendfile_napi.cpp @@ -0,0 +1,40 @@ +/* + * Copyright (c) 2021 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 "napi/native_api.h" +#include "napi/native_node_api.h" + +#include "sendfile.h" +#include "sendfile_napi.h" + +namespace OHOS { +namespace DistributedFS { +namespace ModuleSendFile { +/*********************************************** + * Module export and register + ***********************************************/ +napi_value SendFileExport(napi_env env, napi_value exports) +{ + static napi_property_descriptor desc[] = { + DECLARE_NAPI_FUNCTION("sendFile", SendFile), + }; + NAPI_CALL(env, napi_define_properties(env, exports, sizeof(desc) / sizeof(desc[0]), desc)); + return exports; +} + +NAPI_MODULE(sendfile, SendFileExport) +} // namespace ModuleSendFile +} // namespace DistributedFS +} // namespace OHOS \ No newline at end of file diff --git a/interfaces/innerkits/js/mod_sendfile/sendfile_napi.h b/interfaces/innerkits/js/mod_sendfile/sendfile_napi.h new file mode 100644 index 000000000..01b395d45 --- /dev/null +++ b/interfaces/innerkits/js/mod_sendfile/sendfile_napi.h @@ -0,0 +1,25 @@ +/* + * Copyright (c) 2021 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 SENDFILE_NAPI_H +#define SENDFILE_NAPI_H + +namespace OHOS { +namespace DistributedFS { +namespace ModuleSendFile { +} // namespace ModuleSendFile +} // namespace DistributedFS +} // namespace OHOS +#endif // SENDFILE_NAPI_H \ No newline at end of file diff --git a/interfaces/innerkits/native/i_distributedfile_service.h b/interfaces/innerkits/native/i_distributedfile_service.h index 878461cbd..a547e4193 100644 --- a/interfaces/innerkits/native/i_distributedfile_service.h +++ b/interfaces/innerkits/native/i_distributedfile_service.h @@ -25,9 +25,14 @@ class IDistributedFileService : public IRemoteBroker { public: DECLARE_INTERFACE_DESCRIPTOR(u"OHOS.DistributedFile.IDistributedFileService"); // define the message code + enum DistributedFileSurfaceCode { + INTERFACE1 = 0, + SEND_FILE_DISTRIBUTED + }; // define the error code enum { DISTRIBUTEDFILE_SUCCESS = 0, + GET_DISTRIBUTEDFILE_DISTRIBUTED_DIR_FAIL = 1, DISTRIBUTEDFILE_WRITE_DESCRIPTOR_TOKEN_FAIL, ERR_FLATTEN_OBJECT, DISTRIBUTEDFILE_NO_ERROR, @@ -42,10 +47,13 @@ public: DISTRIBUTEDFILE_PERMISSION_DENIED, ROOT_UID, SYSTEM_SERVICE_UID, + SEND_FILE_FAIL, + SEND_FILE_DISTRIBUTED_DESCRIPTION_FAIL }; + virtual int32_t SendFile(int32_t sessionId, const std::string &sourceFileList, + const std::string &destinationFileList, uint32_t fileCount) = 0; }; } // namespace DistributedFile } // namespace Storage } // namespace OHOS - -#endif // I_YANGHU_TESt_SERVICE_H \ No newline at end of file +#endif // I_DISTRIBUTEDFILE_SERVICE_H \ No newline at end of file diff --git a/ohos.build b/ohos.build old mode 100755 new mode 100644 index 50e5a679c..463e45d55 --- a/ohos.build +++ b/ohos.build @@ -7,7 +7,8 @@ "phone" ], "module_list": [ - "//foundation/storage/distributed_file_manager/services/:services_target" + "//foundation/storage/distributed_file_manager/services/:services_target", + "//foundation/storage/distributed_file_manager/interfaces/innerkits/js:build_kits_js" ], "inner_kits":[ { diff --git a/services/distributedfileservice/include/ipc/distributedfile_service.h b/services/distributedfileservice/include/ipc/distributedfile_service.h index 2ed0ef60f..7753eeddc 100644 --- a/services/distributedfileservice/include/ipc/distributedfile_service.h +++ b/services/distributedfileservice/include/ipc/distributedfile_service.h @@ -35,6 +35,8 @@ public: void OnDump() override; void OnStart() override; void OnStop() override; + int32_t SendFile(int32_t sessionId, const std::string &sourceFileList, + const std::string &destinationFileList, uint32_t fileCount) override; }; } // namespace DistributedFile } // namespace Storage diff --git a/services/distributedfileservice/include/ipc/distributedfile_service_stub.h b/services/distributedfileservice/include/ipc/distributedfile_service_stub.h index 419f6782b..643258274 100644 --- a/services/distributedfileservice/include/ipc/distributedfile_service_stub.h +++ b/services/distributedfileservice/include/ipc/distributedfile_service_stub.h @@ -36,9 +36,9 @@ private: using DistributedFileServiceFunc = int32_t (DistributedFileServiceStub::*)(MessageParcel &data, MessageParcel &reply); std::map memberFuncMap_; + int32_t GetSendFileInner(MessageParcel &data,MessageParcel &reply); }; } // namespace DistributedFile } // namespace Storage } // namespace OHOS - #endif // DISTRIBUTEDFILE_SERVICE_STUB_H \ No newline at end of file diff --git a/services/distributedfileservice/src/ipc/distributedfile_service.cpp b/services/distributedfileservice/src/ipc/distributedfile_service.cpp index e09d7636e..5635cc7be 100644 --- a/services/distributedfileservice/src/ipc/distributedfile_service.cpp +++ b/services/distributedfileservice/src/ipc/distributedfile_service.cpp @@ -53,6 +53,41 @@ void DistributedFileService::OnStop() { LOGI("DistributedFileService::OnStop start"); } + +int32_t DistributedFileService::SendFile(int32_t sessionId, const std::string &sourceFileList, + const std::string &destinationFileList, uint32_t fileCount) +{ + // DistributedFileInfo metaBase; + // metaBase.name = dirName; + // if (metaBase.name.empty()) { + // LOGE("DistributedFileService-%{public}s: Failed to get app dir, error: invalid app name", __func__); + // return DISTRIBUTEDFILE_DIR_NAME_IS_EMPTY; + // } + + // sptr systemAbilityMgr = + // SystemAbilityManagerClient::GetInstance().GetSystemAbilityManager(); + // if (systemAbilityMgr == nullptr) { + // LOGE("BundleService Get ISystemAbilityManager failed ... \n"); + // return DISTRIBUTEDFILE_REMOTE_ADDRESS_IS_NULL; + // } + + // sptr remote = systemAbilityMgr->CheckSystemAbility(BUNDLE_MGR_SERVICE_SYS_ABILITY_ID); + // if (remote == nullptr) { + // LOGE("BundleService Get IRemoteObject failed ... \n"); + // return DISTRIBUTEDFILE_REMOTE_ADDRESS_IS_NULL; + // } + + // auto BundleMgrService = std::make_unique(remote); + // if (BundleMgrService.get() == nullptr) { + // LOGE("remote iface_cast BundleMgrService failed ... \n"); + // return DISTRIBUTEDFILE_REMOTE_ADDRESS_IS_NULL; + // } + + // Utils::ForceRemoveDirectory(metaBase.name); + //OpenSession(nullptr, nullptr, nullptr, nullptr, nullptr); + LOGD("DistributedFileService::SendFile"); + return DISTRIBUTEDFILE_SUCCESS; +} } // namespace DistributedFile } // namespace Storage } // namespace OHOS diff --git a/services/distributedfileservice/src/ipc/distributedfile_service_stub.cpp b/services/distributedfileservice/src/ipc/distributedfile_service_stub.cpp index 08c7f202f..8836e87a8 100644 --- a/services/distributedfileservice/src/ipc/distributedfile_service_stub.cpp +++ b/services/distributedfileservice/src/ipc/distributedfile_service_stub.cpp @@ -53,6 +53,27 @@ int DistributedFileServiceStub::OnRemoteRequest(uint32_t code, return IPCObjectStub::OnRemoteRequest(code, data, reply, option); } + +int32_t DistributedFileServiceStub::GetSendFileInner(MessageParcel &data, MessageParcel &reply) +{ + std::string dirName = data.ReadString(); + if (dirName.empty()) { + LOGE("DistributedFileService: Failed to get app dir, error: invalid app name"); + return DISTRIBUTEDFILE_DIR_NAME_IS_EMPTY; + } + int32_t sessionId = 0; + std::string sourceFileList{}; + std::string destinationFileList{}; + uint32_t fileCount = 0; + int32_t result = SendFile(sessionId, sourceFileList, destinationFileList, fileCount); + LOGD("DistributedFileServiceStub : GetBundleDistributedDir result = %{public}d", result); + if (!reply.WriteInt32(result)) { + LOGE("fail to write parcel"); + return DISTRIBUTEDFILE_WRITE_REPLY_FAIL; + } + + return result; +} } // namespace DistributedFile } // namespace Storage } // namespace OHOS \ No newline at end of file -- Gitee From 4b56313fb59b9a7852ba9cf90835f8c6cb7bde6e Mon Sep 17 00:00:00 2001 From: x00456388 Date: Thu, 23 Dec 2021 16:37:24 +0800 Subject: [PATCH 05/14] send_file interacting with DM and Softbus Signed-off-by: xianghengliang --- services/distributedfileservice/BUILD.gn | 8 + .../include/device/device_manager_agent.h | 50 ++-- .../include/ipc/distributedfile_service.h | 12 +- .../include/network/base_session.h | 40 --- .../include/network/network_agent_template.h | 83 ------ .../include/network/softbus/softbus_session.h | 46 ---- .../network/softbus/softbus_session_name.h | 40 --- .../network/{softbus => }/softbus_agent.h | 50 ++-- ...sion_dispatcher.h => softbus_dispatcher.h} | 27 +- .../src/device/device_manager_agent.cpp | 102 +++++++ .../src/ipc/distributedfile_service.cpp | 43 ++- .../src/network/softbus_agent.cpp | 260 ++++++++++++++++++ .../network/softbus_dispatcher.cpp} | 59 ++-- utils/system/include/utils_singleton.h | 15 +- 14 files changed, 515 insertions(+), 320 deletions(-) delete mode 100644 services/distributedfileservice/include/network/base_session.h delete mode 100644 services/distributedfileservice/include/network/network_agent_template.h delete mode 100644 services/distributedfileservice/include/network/softbus/softbus_session.h delete mode 100644 services/distributedfileservice/include/network/softbus/softbus_session_name.h rename services/distributedfileservice/include/network/{softbus => }/softbus_agent.h (35%) rename services/distributedfileservice/include/network/{softbus/softbus_session_dispatcher.h => softbus_dispatcher.h} (64%) create mode 100644 services/distributedfileservice/src/device/device_manager_agent.cpp create mode 100644 services/distributedfileservice/src/network/softbus_agent.cpp rename services/distributedfileservice/{include/network/session_pool.h => src/network/softbus_dispatcher.cpp} (46%) diff --git a/services/distributedfileservice/BUILD.gn b/services/distributedfileservice/BUILD.gn index d54c88a0c..399eb2272 100644 --- a/services/distributedfileservice/BUILD.gn +++ b/services/distributedfileservice/BUILD.gn @@ -16,11 +16,17 @@ import("//foundation/storage/distributed_file_manager/distributedfile.gni") ohos_shared_library("libdistributedfileservice") { include_dirs = [ "include/ipc", + "include/device", + "include/network", + "//foundation/distributedhardware/devicemanager/interfaces/inner_kits/native_cpp/include" ] sources = [ "src/ipc/distributedfile_service_stub.cpp", "src/ipc/distributedfile_service.cpp", + "src/device/device_manager_agent.cpp", + "src/network/softbus_agent.cpp", + "src/network/softbus_dispatcher.cpp" ] configs = [ "${utils_path}:compiler_configs" ] @@ -32,11 +38,13 @@ ohos_shared_library("libdistributedfileservice") { "aafwk_standard:want", "appexecfwk_standard:appexecfwk_base", "appexecfwk_standard:appexecfwk_core", + "dsoftbus_standard:softbus_client" ] deps = [ "${utils_path}:libdistributedfileutils", "../../interfaces/innerkits/native:libdistributedfile_innerkits", + "//foundation/distributedhardware/devicemanager/interfaces/inner_kits/native_cpp:devicemanagersdk" ] part_name = "storage_distributed_file_manager" diff --git a/services/distributedfileservice/include/device/device_manager_agent.h b/services/distributedfileservice/include/device/device_manager_agent.h index 4f9932224..c50c781cb 100644 --- a/services/distributedfileservice/include/device/device_manager_agent.h +++ b/services/distributedfileservice/include/device/device_manager_agent.h @@ -12,65 +12,57 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -#ifndef DEVICE_MANAGER_AGENT_H -#define DEVICE_MANAGER_AGENT_H +#ifndef DFS_DEVICE_MANAGER_AGENT_H +#define DFS_DEVICE_MANAGER_AGENT_H +#include #include #include #include +#include #include #include -#include "device_info.h" #include "device_manager.h" -#include "network/network_agent_template.h" -#include "nlohmann/json.hpp" #include "utils_singleton.h" namespace OHOS { namespace Storage { namespace DistributedFile { -class DeviceManagerAgent final : public DistributedHardware::DmInitCallback, +class DeviceManagerAgent : public DistributedHardware::DmInitCallback, public DistributedHardware::DeviceStateCallback, public std::enable_shared_from_this, public Utils::Singleton { DECLARE_SINGLETON(DeviceManagerAgent); public: - void Start() override; - void Stop() override; - void JoinGroup(std::weak_ptr mp); - void QuitGroup(std::weak_ptr mp); - - void OnDeviceOnline(const DistributedHardware::DmDeviceInfo &deviceInfo) override; - void OnDeviceOffline(const DistributedHardware::DmDeviceInfo &deviceInfo) override; - void OnDeviceChanged(const DistributedHardware::DmDeviceInfo &deviceInfo) override; + void OnDeviceOnline(const DistributedHardware::DmDeviceInfo &deviceInfo) + override; // 加入set,创建softbus 各种监听,需要标志位,注册过就不需要重复注册 + void OnDeviceOffline( + const DistributedHardware::DmDeviceInfo &deviceInfo) override; // 从set中删除此cid, 若set为空则解注册softbus + void OnDeviceChanged(const DistributedHardware::DmDeviceInfo &deviceInfo) override {} void OnDeviceReady(const DistributedHardware::DmDeviceInfo &deviceInfo) override {} - void OfflineAllDevice(); - void ReconnectOnlineDevices(); - void AuthGroupOnlineProc(const DeviceInfo info); void OnRemoteDied() override; - - DeviceInfo &GetLocalDeviceInfo(); - std::vector GetRemoteDevicesInfo(); + std::set getOnlineDevs() const + { + return alreadyOnlineDev_; + } + // std::vector GetRemoteDevicesInfo(); private: - void StartInstance() override; + void StartInstance() override; // 注册dm监听 void StopInstance() override; void RegisterToExternalDm(); void UnregisterFromExternalDm(); - void AuthGroupOfflineProc(const DeviceInfo &info); - void QueryRelatedGroups(const std::string &networkId, std::vector &groupList); - bool CheckIsAuthGroup(const GroupInfo &group); - void AllAuthGroupsOfflineProc(); - // We use a mutex instead of a shared_mutex to serialize online/offline procedures - std::mutex mpToNetworksMutex_; - std::map> mpToNetworks_; + std::atomic alreadyRegis_{false}; + std::set alreadyOnlineDev_; + + std::string pkgName_{"ohos.storage.distributedfile.service"}; }; } // namespace DistributedFile } // namespace Storage } // namespace OHOS -#endif // DEVICE_MANAGER_AGENT_H \ No newline at end of file +#endif // DFS_DEVICE_MANAGER_AGENT_H \ No newline at end of file diff --git a/services/distributedfileservice/include/ipc/distributedfile_service.h b/services/distributedfileservice/include/ipc/distributedfile_service.h index 7753eeddc..056b514b9 100644 --- a/services/distributedfileservice/include/ipc/distributedfile_service.h +++ b/services/distributedfileservice/include/ipc/distributedfile_service.h @@ -18,25 +18,29 @@ #include "distributedfile_service_stub.h" #include "iremote_stub.h" -#include "singleton.h" #include "system_ability.h" - -#include +#include "utils_singleton.h" namespace OHOS { namespace Storage { namespace DistributedFile { class DistributedFileService : public SystemAbility, public DistributedFileServiceStub, + public Utils::Singleton, public std::enable_shared_from_this { - DECLARE_DELAYED_SINGLETON(DistributedFileService) + DECLARE_SINGLETON(DistributedFileService); DECLARE_SYSTEM_ABILITY(DistributedFileService) public: void OnDump() override; void OnStart() override; void OnStop() override; + int32_t SendFile(int32_t sessionId, const std::string &sourceFileList, const std::string &destinationFileList, uint32_t fileCount) override; +private: + void PublishSA(); + void StartManagers(); + }; } // namespace DistributedFile } // namespace Storage diff --git a/services/distributedfileservice/include/network/base_session.h b/services/distributedfileservice/include/network/base_session.h deleted file mode 100644 index 1568d0089..000000000 --- a/services/distributedfileservice/include/network/base_session.h +++ /dev/null @@ -1,40 +0,0 @@ -/* - * Copyright (c) 2021 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 BASE_SESSION_H -#define BASE_SESSION_H - -#include -#include - -namespace OHOS { -namespace Storage { -namespace DistributedFile { -constexpr int KEY_SIZE_MAX = 32; - -class BaseSession { -public: - virtual ~BaseSession() = default; - virtual bool IsFromServer() const = 0; - virtual std::string GetCid() const = 0; - virtual int32_t GetHandle() const = 0; - virtual std::array GetKey() const = 0; - virtual void Release() const = 0; - virtual void DisableSessionListener() const = 0; -}; -} // namespace DistributedFile -} // namespace Storage -} // namespace OHOS -#endif // BASE_SESSION_H \ No newline at end of file diff --git a/services/distributedfileservice/include/network/network_agent_template.h b/services/distributedfileservice/include/network/network_agent_template.h deleted file mode 100644 index d878472cb..000000000 --- a/services/distributedfileservice/include/network/network_agent_template.h +++ /dev/null @@ -1,83 +0,0 @@ -/* - * Copyright (c) 2021 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 NETWORK_AGENT_TEMPLATE_H -#define NETWORK_AGENT_TEMPLATE_H - -#include -#include -#include -#include - -#include "device/device_info.h" -#include "mountpoint/mount_point.h" -#include "network/kernel_talker.h" -#include "network/session_pool.h" -#include "utils_actor.h" -#include "utils_dfs_thread.h" -#include "utils_startable.h" - -namespace OHOS { -namespace Storage { -namespace DistributedFile { -class NetworkAgentTemplate : public Startable, public Actor { -public: - explicit NetworkAgentTemplate(std::weak_ptr mountPoint) - : Actor(this), - mountPoint_(mountPoint), - kernerlTalker_( - mountPoint, - [&](NotifyParam ¶m) { GetSessionProcess(param); }, - [&](const std::string &cid) { CloseSessionForOneDevice(cid); }), - sessionPool_(kernerlTalker_) - { - } - virtual ~NetworkAgentTemplate() {} - void Start(); - void Stop(); - void ConnectOnlineDevices(); - void DisconnectAllDevices(); - void ConnectDeviceAsync(const DeviceInfo info); - void DisconnectDevice(const DeviceInfo info); - void AcceptSession(std::shared_ptr session); - -protected: - virtual void JoinDomain() = 0; - virtual void QuitDomain() = 0; - virtual void StopTopHalf() = 0; - virtual void StopBottomHalf() = 0; - virtual void OpenSession(const DeviceInfo &info) = 0; - virtual void CloseSession(std::shared_ptr session) = 0; - - std::weak_ptr mountPoint_; - -private: - void HandleAllNotify(int fd); - void NotifyHandler(NotifyParam ¶m); - void GetSessionProcess(NotifyParam ¶m); - void GetSession(const std::string &cid); - void CloseSessionForOneDevice(const std::string &cid); - void AcceptSessionInner(std::shared_ptr session); - void GetSessionProcessInner(NotifyParam param); - - std::mutex taskMut_; - std::list tasks_; - KernelTalker kernerlTalker_; - SessionPool sessionPool_; -}; -} // namespace DistributedFile -} // namespace Storage -} // namespace OHOS -#endif // NETWORK_AGENT_TEMPLATE_H \ No newline at end of file diff --git a/services/distributedfileservice/include/network/softbus/softbus_session.h b/services/distributedfileservice/include/network/softbus/softbus_session.h deleted file mode 100644 index 4816c3ead..000000000 --- a/services/distributedfileservice/include/network/softbus/softbus_session.h +++ /dev/null @@ -1,46 +0,0 @@ -/* - * Copyright (c) 2021 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 SOFTBUS_SESSION_H -#define SOFTBUS_SESSION_H - -#include "network/base_session.h" - -namespace OHOS { -namespace Storage { -namespace DistributedFile { -constexpr int32_t INVALID_SOCKET_FD = -1; -class SoftbusSession final : public BaseSession { -public: - explicit SoftbusSession(int sessionId); - ~SoftbusSession() = default; - bool IsFromServer() const override; - std::string GetCid() const override; - int32_t GetHandle() const override; - std::array GetKey() const override; - void Release() const override; - void DisableSessionListener() const override; - -private: - int sessionId_; - std::string cid_; - int32_t socketFd_{INVALID_SOCKET_FD}; - std::array key_; - bool IsServerSide_; -}; -} // namespace DistributedFile -} // namespace Storage -} // namespace OHOS -#endif // SOFTBUS_SESSION_H \ No newline at end of file diff --git a/services/distributedfileservice/include/network/softbus/softbus_session_name.h b/services/distributedfileservice/include/network/softbus/softbus_session_name.h deleted file mode 100644 index 87d3b4de3..000000000 --- a/services/distributedfileservice/include/network/softbus/softbus_session_name.h +++ /dev/null @@ -1,40 +0,0 @@ -/* - * Copyright (c) 2021 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 SOFTBUS_SESSION_NAME_H -#define SOFTBUS_SESSION_NAME_H - -#include - -namespace OHOS { -namespace Storage { -namespace DistributedFile { -class SoftbusSessionName final { -public: - explicit SoftbusSessionName(std::string path) : path_(path) {} - ~SoftbusSessionName() = default; - std::string ToString() - { - return prefix + path_; - } - -private: - const std::string prefix = "DistributedFileService"; - std::string path_; -}; -} // namespace DistributedFile -} // namespace Storage -} // namespace OHOS -#endif // SOFTBUS_SESSION_NAME_H \ No newline at end of file diff --git a/services/distributedfileservice/include/network/softbus/softbus_agent.h b/services/distributedfileservice/include/network/softbus_agent.h similarity index 35% rename from services/distributedfileservice/include/network/softbus/softbus_agent.h rename to services/distributedfileservice/include/network/softbus_agent.h index 28d88c4b7..1bef6b18e 100644 --- a/services/distributedfileservice/include/network/softbus/softbus_agent.h +++ b/services/distributedfileservice/include/network/softbus_agent.h @@ -13,37 +13,51 @@ * limitations under the License. */ -#ifndef SOFTBUS_AGENT_H -#define SOFTBUS_AGENT_H +#ifndef DFS_SOFTBUS_AGENT_H +#define DFS_SOFTBUS_AGENT_H -#include "network/network_agent_template.h" -#include +#include "utils_singleton.h" +#include +#include +#include namespace OHOS { namespace Storage { namespace DistributedFile { -class SoftbusAgent final : public NetworkAgentTemplate, public std::enable_shared_from_this { +class SoftbusAgent : public std::enable_shared_from_this, public Utils::Singleton { + DECLARE_SINGLETON(SoftbusAgent); + public: - explicit SoftbusAgent(std::weak_ptr mountPoint); - ~SoftbusAgent() = default; - int OnSessionOpened(const int sessionId, const int result); + void RegisterSessionListener(); + void RegisterFileListener(); + void UnRegisterSessionListener(); + void UnRegisterFileListener(); + + void OnDeviceOffline(const std::string &cid); + void AllDevicesOffline(); + void OnSessionOpened(const int sessionId, const int result); void OnSessionClosed(int sessionId); + int SendFile(std::string &cid, const char *sFileList[], const char *dFileList[], uint32_t fileCnt); + int OnSendFileFinished(const int sessionId, const std::string firstFile); + int OnFileTransError(const int sessionId); + void OnReceiveFileFinished(const int sessionId, const std::string files, int fileCnt); protected: - void JoinDomain() override; - void QuitDomain() override; - void StopTopHalf() override; - void StopBottomHalf() override; - void OpenSession(const DeviceInfo &info) override; - void CloseSession(std::shared_ptr session) override; + void StartInstance() override; // 第一次调用GetInstance时,注册softbus监听 + void StopInstance() override;; // 解注册 + void OpenSession(const std::string &cid); + void CloseSession(const std::string &cid); + std::string GetPeerDevId(const int sessionId); private: - bool IsContinueRetry(const std::string &cid); - std::map OpenSessionRetriedTimesMap_; + std::string sessionName_ {"DistributedFileService"}; + std::string pkgName_ {"ohos.storage.distributedfile.service"}; + std::unordered_map> cidToSessionID_; - std::string sessionName_; + std::mutex getSessionCVMut_; + std::condition_variable getSessionCV_; }; } // namespace DistributedFile } // namespace Storage } // namespace OHOS -#endif // SOFTBUS_AGENT_H \ No newline at end of file +#endif // DFS_SOFTBUS_AGENT_H \ No newline at end of file diff --git a/services/distributedfileservice/include/network/softbus/softbus_session_dispatcher.h b/services/distributedfileservice/include/network/softbus_dispatcher.h similarity index 64% rename from services/distributedfileservice/include/network/softbus/softbus_session_dispatcher.h rename to services/distributedfileservice/include/network/softbus_dispatcher.h index fc7e1d9cd..1639a5413 100644 --- a/services/distributedfileservice/include/network/softbus/softbus_session_dispatcher.h +++ b/services/distributedfileservice/include/network/softbus_dispatcher.h @@ -13,8 +13,8 @@ * limitations under the License. */ -#ifndef SOFTBUS_SESSION_DISPATCHER_H -#define SOFTBUS_SESSION_DISPATCHER_H +#ifndef DFS_SOFTBUS_SESSION_DISPATCHER_H +#define DFS_SOFTBUS_SESSION_DISPATCHER_H #include #include @@ -24,22 +24,25 @@ namespace OHOS { namespace Storage { namespace DistributedFile { -class SoftbusAgent; -class SoftbusSessionDispatcher final { + +class SoftbusDispatcher final { public: - SoftbusSessionDispatcher() = delete; - ~SoftbusSessionDispatcher() = delete; - static void RegisterSessionListener(const std::string busName, std::weak_ptr); + SoftbusDispatcher() = delete; + ~SoftbusDispatcher() = delete; + static void RegisterSessionListener(); static void UnregisterSessionListener(const std::string busName); - static std::weak_ptr GetAgent(int sessionId); + static int OnSessionOpened(int sessionId, int result); static void OnSessionClosed(int sessionId); -private: - static std::mutex softbusAgentMutex_; - static std::map> busNameToAgent_; + // IFileSendListener + static int OnSendFileFinished(int sessionId, const char *firstFile); + static void OnFileTransError(int sessionId); + + // IFileReceiveListener + static void OnReceiveFileFinished(int sessionId, const char *files, int fileCnt); }; } // namespace DistributedFile } // namespace Storage } // namespace OHOS -#endif // SOFTBUS_SESSION_DISPATCHER_H \ No newline at end of file +#endif // DFS_SOFTBUS_SESSION_DISPATCHER_H \ No newline at end of file diff --git a/services/distributedfileservice/src/device/device_manager_agent.cpp b/services/distributedfileservice/src/device/device_manager_agent.cpp new file mode 100644 index 000000000..2b52387ca --- /dev/null +++ b/services/distributedfileservice/src/device/device_manager_agent.cpp @@ -0,0 +1,102 @@ +/* + * Copyright (c) 2021 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 "device_manager_agent.h" +#include "softbus_agent.h" +#include "utils_exception.h" +#include "utils_log.h" + +namespace OHOS { +namespace Storage { +namespace DistributedFile { +using namespace std; +DeviceManagerAgent::DeviceManagerAgent() {} + +DeviceManagerAgent::~DeviceManagerAgent() +{ + StopInstance(); +} +void DeviceManagerAgent::StartInstance() +{ + alreadyOnlineDev_.clear(); + RegisterToExternalDm(); +} + +void DeviceManagerAgent::StopInstance() +{ + UnregisterFromExternalDm(); +} + +void DeviceManagerAgent::OnDeviceOnline(const DistributedHardware::DmDeviceInfo &deviceInfo) +{ + std::string cid = std::string(deviceInfo.deviceId); + alreadyOnlineDev_.insert(cid); + if (alreadyRegis_) { + return; + } + + auto softBusAgent = SoftbusAgent::GetInstance(); + alreadyRegis_ = true; +} + +void DeviceManagerAgent::OnDeviceOffline(const DistributedHardware::DmDeviceInfo &deviceInfo) +{ + std::string cid = std::string(deviceInfo.deviceId); + auto softBusAgent = SoftbusAgent::GetInstance(); + softBusAgent->OnDeviceOffline(cid); + + alreadyOnlineDev_.erase(cid); + if (alreadyOnlineDev_.size() == 0) { + alreadyRegis_ = false; + } + LOGI("cid %s offline, left online devices num %d", cid.c_str(), alreadyOnlineDev_.size()); +} + +void DeviceManagerAgent::OnRemoteDied() +{ + LOGI("device manager service died"); +} + +void DeviceManagerAgent::RegisterToExternalDm() +{ + auto &deviceManager = DistributedHardware::DeviceManager::GetInstance(); + int errCode = deviceManager.InitDeviceManager(pkgName_, shared_from_this()); + if (errCode != 0) { + ThrowException(errCode, "Failed to InitDeviceManager"); + } + string extra = ""; + errCode = deviceManager.RegisterDevStateCallback(pkgName_, extra, shared_from_this()); + if (errCode != 0) { + ThrowException(errCode, "Failed to RegisterDevStateCallback"); + } + LOGI("RegisterToExternalDm Succeed"); +} + +void DeviceManagerAgent::UnregisterFromExternalDm() +{ + auto &deviceManager = DistributedHardware::DeviceManager::GetInstance(); + int errCode = deviceManager.UnRegisterDevStateCallback(pkgName_); + if (errCode != 0) { + ThrowException(errCode, "Failed to UnRegisterDevStateCallback"); + } + errCode = deviceManager.UnInitDeviceManager(pkgName_); + if (errCode != 0) { + ThrowException(errCode, "Failed to UnInitDeviceManager"); + } + LOGI("UnregisterFromExternalDm Succeed"); +} +} // namespace DistributedFile +} // namespace Storage +} // namespace OHOS \ No newline at end of file diff --git a/services/distributedfileservice/src/ipc/distributedfile_service.cpp b/services/distributedfileservice/src/ipc/distributedfile_service.cpp index 5635cc7be..91c66708b 100644 --- a/services/distributedfileservice/src/ipc/distributedfile_service.cpp +++ b/services/distributedfileservice/src/ipc/distributedfile_service.cpp @@ -14,17 +14,10 @@ */ #include "distributedfile_service.h" -#include #include - -#include "bundle_mgr_interface.h" -#include "bundle_mgr_proxy.h" -#include "ipc_skeleton.h" -#include "iservice_registry.h" -#include "message_parcel.h" -#include "parcel.h" -#include "utils_directory.h" +#include "device_manager_agent.h" #include "utils_log.h" +#include "utils_exception.h" namespace OHOS { namespace Storage { @@ -40,18 +33,40 @@ void DistributedFileService::OnDump() LOGI("OnDump"); } -void DistributedFileService::OnStart() +void DistributedFileService::PublishSA() { - bool ret = SystemAbility::Publish(DelayedSingleton::GetInstance().get()); + LOGI("Begin to init, pull the service"); // todo: 看一下ipc使用方法;是否必须使用单例?; 是否需要加flag?; 抛异常处理? + bool ret = SystemAbility::Publish(this); // DelayedSingleton::GetInstance().get() if (!ret) { - LOGE("Leave, publishing DistributedFileService failed!"); - return; + throw runtime_error("publishing DistributedFileService failed"); + } + // if (!registerToService_) { + // bool ret = SystemAbility::Publish(this); + // if (!ret) { + // throw runtime_error("Failed to publish the daemon"); + // } + // registerToService_ = true; + // } + LOGI("Init finished successfully"); +} +void DistributedFileService::StartManagers() +{ + DeviceManagerAgent::GetInstance(); +} + +void DistributedFileService::OnStart() +{ + try { + PublishSA(); + StartManagers(); + } catch (const Exception &e) { + LOGE("%{public}s", e.what()); } } void DistributedFileService::OnStop() { - LOGI("DistributedFileService::OnStop start"); + LOGI("DistributedFileService::OnStop"); } int32_t DistributedFileService::SendFile(int32_t sessionId, const std::string &sourceFileList, diff --git a/services/distributedfileservice/src/network/softbus_agent.cpp b/services/distributedfileservice/src/network/softbus_agent.cpp new file mode 100644 index 000000000..15d8b94f1 --- /dev/null +++ b/services/distributedfileservice/src/network/softbus_agent.cpp @@ -0,0 +1,260 @@ +/* + * Copyright (c) 2021 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 "softbus_agent.h" + +#include "session.h" +#include "softbus_dispatcher.h" +#include "utils_exception.h" +#include "utils_log.h" +#include "device_manager_agent.h" +#include + +namespace OHOS { +namespace Storage { +namespace DistributedFile { +using namespace std; +constexpr int32_t SOFTBUS_OK = 0; +constexpr int32_t DEVICE_ID_SIZE_MAX = 65; +constexpr int32_t IS_CLIENT = 0; + +SoftbusAgent::SoftbusAgent() {} + +SoftbusAgent::~SoftbusAgent() +{ + StopInstance(); +} +void SoftbusAgent::StartInstance() +{ + RegisterSessionListener(); + RegisterFileListener(); +} + +void SoftbusAgent::StopInstance() +{ + // sessionId的释放,clossSession + for (auto iter = cidToSessionID_.begin(); iter != cidToSessionID_.end();) { + CloseSession(iter->first); + iter = cidToSessionID_.erase(iter); + } + // 变量 cidToSessionID_, 依次释放 + getSessionCV_.notify_all(); + // 解注册 + UnRegisterSessionListener(); + UnRegisterFileListener(); +} + +int SoftbusAgent::SendFile(std::string &cid, const char *sFileList[], const char *dFileList[], uint32_t fileCnt) +{ + // first check whether the sessionId available + auto alreadyOnliceDev = DeviceManagerAgent::GetInstance()->getOnlineDevs(); + if (alreadyOnliceDev.find(cid) == alreadyOnliceDev.end()) { + LOGE("cid:%{public}s has not been online yet", cid.c_str()); + return -1; + } + int sessionId = -1; + if (cidToSessionID_.find(cid) != cidToSessionID_.end() && + cidToSessionID_[cid].begin() != cidToSessionID_[cid].end()) { // to avoid list is empty + sessionId = cidToSessionID_[cid].front(); + } + // build socket synchronously + if (sessionId == -1) { + OpenSession(cid); + + // wait for get sessionId + std::unique_lock lock(getSessionCVMut_); + getSessionCV_.wait(lock, [this, cid]() { return !cidToSessionID_[cid].empty(); }); + } + if (cidToSessionID_[cid].empty()) { // todo 唤醒检查 + LOGE("there is no sessionId of cid:%{public}s", cid.c_str()); + return -1; + } + sessionId = cidToSessionID_[cid].front(); + int ret = + ::SendFile(sessionId, sFileList, dFileList, fileCnt); // todo:const string ==> const char * ==> const char ** + LOGD("sendfile is processing, cid:%{public}s, sessionId:%{publid}d, ret %{public}d", cid.c_str(), sessionId, ret); + return ret; +} + +void SoftbusAgent::OpenSession(const std::string &cid) +{ + SessionAttribute attr; + attr.dataType = TYPE_BYTES; + + LOGD("Start to Open Session, cid:%{public}s", cid.c_str()); + int sessionId = ::OpenSession(sessionName_.c_str(), sessionName_.c_str(), cid.c_str(), "DFS_wifiGroup", &attr); + if (sessionId < 0) { + LOGE("Failed to open session, cid:%{public}s, sessionId:%{public}d", cid.c_str(), sessionId); + ThrowException(ERR_SOFTBUS_AGENT_ON_SESSION_OPENED_FAIL, "Open Session failed"); + } + LOGD("Open Session SUCCESS, cid:%{public}s", cid.c_str()); +} + +void SoftbusAgent::OnSessionOpened(const int sessionId, const int result) +{ + if (result != 0) { // 增加重试? + LOGE("open failed, result:%{public}d, sessionId:%{public}d", result, sessionId); + return; + } + std::string cid = GetPeerDevId(sessionId); + if (cid == "") { + LOGE("get peer device id failed"); + return; + } + + // client session priority use, so insert list head + if (::GetSessionSide(sessionId) == IS_CLIENT) { + cidToSessionID_[cid].push_front(sessionId); + } else { + cidToSessionID_[cid].push_back(sessionId); + } + + // cv 唤醒等待的sendfile流程 + getSessionCV_.notify_one(); + LOGD("get session SUCCESS, sessionId:%{public}d", sessionId); +} + +int SoftbusAgent::OnSendFileFinished(const int sessionId, const std::string firstFile) +{ + // todo:待和js联调 + LOGD("send file finish, sessionId:%{public}d, firstFile %{public}s", sessionId, firstFile.c_str()); + return 0; +} + +int SoftbusAgent::OnFileTransError(const int sessionId) +{ + // todo:待和js联调 + LOGD("file trans error, sessionId:%{public}d", sessionId); + return 0; +} + +void SoftbusAgent::OnReceiveFileFinished(const int sessionId, const std::string files, int fileCnt) +{ + // todo:待和js联调 + LOGD("recv file finish, sessionId:%{public}d, files %{public}s, cnt %{public}d", sessionId, files.c_str(), fileCnt); +} + +void SoftbusAgent::OnSessionClosed(int sessionId) +{ + std::string cid = GetPeerDevId(sessionId); + if (cid == "") { + LOGE("get peer device id failed"); + return; + } + if (cidToSessionID_.find(cid) != cidToSessionID_.end()) { + cidToSessionID_[cid].remove(sessionId); + } + // 可能list链表为空, 是否要删除此map信息? + if (cidToSessionID_[cid].empty()) { + // cidToSessionID_.erase(cid); + } + return; +} + +std::string SoftbusAgent::GetPeerDevId(const int sessionId) // 确认是否需要返回引用? +{ + std::string cid; + char peerDevId[DEVICE_ID_SIZE_MAX] = ""; + int ret = ::GetPeerDeviceId(sessionId, peerDevId, sizeof(peerDevId)); + if (ret != SOFTBUS_OK) { + LOGE("get my peer device id failed, errno:%{public}d, sessionId:%{public}d", ret, sessionId); + cid = ""; + } else { + cid = string(peerDevId); + } + return cid; +} + +void SoftbusAgent::CloseSession(const std::string &cid) +{ + if (cidToSessionID_.find(cid) == cidToSessionID_.end()) { + LOGE("not find this dev-cid:%{public}s", cid.c_str()); + return; + } + for (auto sessionId : cidToSessionID_[cid]) { + ::CloseSession(sessionId); + } + LOGD("Close Session done, cid:%{public}s", cid.c_str()); +} + +void SoftbusAgent::OnDeviceOffline(const std::string &cid) +{ + CloseSession(cid); + cidToSessionID_.erase(cid); +} + +void SoftbusAgent::RegisterSessionListener() +{ + ISessionListener sessionListener = { + .OnSessionOpened = SoftbusDispatcher::OnSessionOpened, + .OnSessionClosed = SoftbusDispatcher::OnSessionClosed, + }; + int ret = ::CreateSessionServer(pkgName_.c_str(), sessionName_.c_str(), &sessionListener); + if (ret != 0) { + stringstream ss; + ss << "Failed to CreateSessionServer, errno:" << ret; + LOGE("%{public}s, sessionName:%{public}s", ss.str().c_str(), sessionName_.c_str()); + throw runtime_error(ss.str()); + } + LOGD("Succeed to CreateSessionServer, pkgName %{public}s, sbusName:%{public}s", pkgName_.c_str(), + sessionName_.c_str()); +} + +void SoftbusAgent::RegisterFileListener() +{ + IFileSendListener fileSendListener = { + .OnSendFileFinished = SoftbusDispatcher::OnSendFileFinished, + .OnFileTransError = SoftbusDispatcher::OnFileTransError, + }; + int ret = ::SetFileSendListener(pkgName_.c_str(), sessionName_.c_str(), &fileSendListener); + if (ret != 0) { + stringstream ss; + ss << "Failed to SetFileSendListener, errno:" << ret; + LOGE("%{public}s, sessionName:%{public}s", ss.str().c_str(), sessionName_.c_str()); + throw runtime_error(ss.str()); + } + LOGD("Succeed to SetFileSendListener, pkgName %{public}s, sbusName:%{public}s", pkgName_.c_str(), + sessionName_.c_str()); + + IFileReceiveListener fileRecvListener = { + .OnReceiveFileFinished = SoftbusDispatcher::OnReceiveFileFinished, + .OnFileTransError = SoftbusDispatcher::OnFileTransError, + }; + ret = ::SetFileReceiveListener(pkgName_.c_str(), sessionName_.c_str(), &fileRecvListener, + "/data/tmp/"); // rootDir TODO + if (ret != 0) { + stringstream ss; + ss << "Failed to SetFileReceiveListener, errno:" << ret; + LOGE("%{public}s, sessionName:%{public}s", ss.str().c_str(), sessionName_.c_str()); + throw runtime_error(ss.str()); + } + LOGD("Succeed to SetFileReceiveListener, pkgName %{public}s, sbusName:%{public}s", pkgName_.c_str(), + sessionName_.c_str()); +} +void SoftbusAgent::UnRegisterSessionListener() +{ + int ret = ::RemoveSessionServer(pkgName_.c_str(), sessionName_.c_str()); + if (ret != 0) { + stringstream ss; + ss << "Failed to RemoveSessionServer, errno:" << ret; + LOGE("%{public}s", ss.str().c_str()); + throw runtime_error(ss.str()); + } + LOGD("RemoveSessionServer success!"); +} +void SoftbusAgent::UnRegisterFileListener() {} +} // namespace DistributedFile +} // namespace Storage +} // namespace OHOS \ No newline at end of file diff --git a/services/distributedfileservice/include/network/session_pool.h b/services/distributedfileservice/src/network/softbus_dispatcher.cpp similarity index 46% rename from services/distributedfileservice/include/network/session_pool.h rename to services/distributedfileservice/src/network/softbus_dispatcher.cpp index b8ff96a83..5a4dc948c 100644 --- a/services/distributedfileservice/include/network/session_pool.h +++ b/services/distributedfileservice/src/network/softbus_dispatcher.cpp @@ -13,37 +13,40 @@ * limitations under the License. */ -#ifndef SESSION_POOL_H -#define SESSION_POOL_H - -#include -#include -#include -#include - -#include "network/base_session.h" -#include "network/kernel_talker.h" +#include "softbus_dispatcher.h" +#include "softbus_agent.h" namespace OHOS { namespace Storage { namespace DistributedFile { -class SessionPool final : protected NoCopyable { -public: - explicit SessionPool(KernelTalker &talker) : talker_(talker) {} - ~SessionPool() = default; - void HoldSession(std::shared_ptr session); - void ReleaseSession(const int32_t fd); - void ReleaseSession(const std::string &cid); - void ReleaseAllSession(); - -private: - std::recursive_mutex sessionPoolLock_; - std::list> usrSpaceSessionPool_; - KernelTalker &talker_; - - void AddSessionToPool(std::shared_ptr session); -}; + +int SoftbusDispatcher::OnSessionOpened(int sessionId, int result) +{ + SoftbusAgent::GetInstance()->OnSessionOpened(sessionId, result); + return 0; +} + +void SoftbusDispatcher::OnSessionClosed(int sessionId) +{ + SoftbusAgent::GetInstance()->OnSessionClosed(sessionId); +} + +int SoftbusDispatcher::OnSendFileFinished(int sessionId, const char *firstFile) +{ + SoftbusAgent::GetInstance()->OnSendFileFinished(sessionId, std::string(firstFile)); + return 0; +} + +void SoftbusDispatcher::OnFileTransError(int sessionId) +{ + SoftbusAgent::GetInstance()->OnFileTransError(sessionId); +} + +void SoftbusDispatcher::OnReceiveFileFinished(int sessionId, const char *files, int fileCnt) +{ + SoftbusAgent::GetInstance()->OnReceiveFileFinished(sessionId, std::string(files), fileCnt); +} + } // namespace DistributedFile } // namespace Storage -} // namespace OHOS -#endif // SESSION_POOL_H \ No newline at end of file +} // namespace OHOS \ No newline at end of file diff --git a/utils/system/include/utils_singleton.h b/utils/system/include/utils_singleton.h index 14c9dd03e..d5a3c2c72 100644 --- a/utils/system/include/utils_singleton.h +++ b/utils/system/include/utils_singleton.h @@ -25,12 +25,14 @@ namespace OHOS { namespace Storage { namespace DistributedFile { namespace Utils { -#define DECLARE_SINGLETON(MyClass) \ -public: \ - ~MyClass(); \ - \ -private: \ - friend Singleton; \ +#define DECLARE_SINGLETON(MyClass) \ +public: \ + ~MyClass(); \ + MyClass(const MyClass&) = delete; \ + MyClass& operator=(const MyClass&) = delete; \ + \ +private: \ + friend Singleton; \ MyClass(); template @@ -65,6 +67,7 @@ std::shared_ptr Singleton::GetInstance() static std::shared_ptr *dummy = nullptr; static std::once_flag once; std::call_once(once, []() mutable { + // dummy = std::make_shared(); dummy = new std::shared_ptr(new T()); (*dummy)->StartInstance(); }); -- Gitee From b915bbf64254725772013a30dc1f0dd69e12cb92 Mon Sep 17 00:00:00 2001 From: x00456388 Date: Sat, 25 Dec 2021 16:53:15 +0800 Subject: [PATCH 06/14] only for self_test:add sendfile and sa Signed-off-by: xianghengliang --- .../include/device/device_manager_agent.h | 19 +++---- .../include/ipc/distributedfile_service.h | 1 - .../include/network/softbus_agent.h | 15 +++-- .../src/device/device_manager_agent.cpp | 14 ++--- .../src/ipc/distributedfile_service.cpp | 11 ++-- .../src/network/softbus_agent.cpp | 55 +++++++++++++------ .../src/network/softbus_dispatcher.cpp | 6 ++ 7 files changed, 69 insertions(+), 52 deletions(-) diff --git a/services/distributedfileservice/include/device/device_manager_agent.h b/services/distributedfileservice/include/device/device_manager_agent.h index c50c781cb..2dc232ad5 100644 --- a/services/distributedfileservice/include/device/device_manager_agent.h +++ b/services/distributedfileservice/include/device/device_manager_agent.h @@ -30,34 +30,31 @@ namespace OHOS { namespace Storage { namespace DistributedFile { class DeviceManagerAgent : public DistributedHardware::DmInitCallback, - public DistributedHardware::DeviceStateCallback, - public std::enable_shared_from_this, - public Utils::Singleton { + public DistributedHardware::DeviceStateCallback, + public std::enable_shared_from_this, + public Utils::Singleton { DECLARE_SINGLETON(DeviceManagerAgent); public: - void OnDeviceOnline(const DistributedHardware::DmDeviceInfo &deviceInfo) - override; // 加入set,创建softbus 各种监听,需要标志位,注册过就不需要重复注册 - void OnDeviceOffline( - const DistributedHardware::DmDeviceInfo &deviceInfo) override; // 从set中删除此cid, 若set为空则解注册softbus + void OnDeviceOnline(const DistributedHardware::DmDeviceInfo &deviceInfo) override; + void OnDeviceOffline(const DistributedHardware::DmDeviceInfo &deviceInfo) override; void OnDeviceChanged(const DistributedHardware::DmDeviceInfo &deviceInfo) override {} void OnDeviceReady(const DistributedHardware::DmDeviceInfo &deviceInfo) override {} void OfflineAllDevice(); void OnRemoteDied() override; - std::set getOnlineDevs() const + std::set getOnlineDevs() const { return alreadyOnlineDev_; } - // std::vector GetRemoteDevicesInfo(); + std::vector GetRemoteDevicesInfo(); private: - void StartInstance() override; // 注册dm监听 + void StartInstance() override; void StopInstance() override; void RegisterToExternalDm(); void UnregisterFromExternalDm(); - std::atomic alreadyRegis_{false}; std::set alreadyOnlineDev_; std::string pkgName_{"ohos.storage.distributedfile.service"}; diff --git a/services/distributedfileservice/include/ipc/distributedfile_service.h b/services/distributedfileservice/include/ipc/distributedfile_service.h index 056b514b9..48fa9685c 100644 --- a/services/distributedfileservice/include/ipc/distributedfile_service.h +++ b/services/distributedfileservice/include/ipc/distributedfile_service.h @@ -40,7 +40,6 @@ public: private: void PublishSA(); void StartManagers(); - }; } // namespace DistributedFile } // namespace Storage diff --git a/services/distributedfileservice/include/network/softbus_agent.h b/services/distributedfileservice/include/network/softbus_agent.h index 1bef6b18e..8e9032853 100644 --- a/services/distributedfileservice/include/network/softbus_agent.h +++ b/services/distributedfileservice/include/network/softbus_agent.h @@ -17,9 +17,9 @@ #define DFS_SOFTBUS_AGENT_H #include "utils_singleton.h" -#include -#include #include +#include +#include namespace OHOS { namespace Storage { @@ -31,27 +31,26 @@ public: void RegisterSessionListener(); void RegisterFileListener(); void UnRegisterSessionListener(); - void UnRegisterFileListener(); void OnDeviceOffline(const std::string &cid); void AllDevicesOffline(); void OnSessionOpened(const int sessionId, const int result); void OnSessionClosed(int sessionId); - int SendFile(std::string &cid, const char *sFileList[], const char *dFileList[], uint32_t fileCnt); + int SendFile(const std::string &cid, const char *sFileList[], const char *dFileList[], uint32_t fileCnt); int OnSendFileFinished(const int sessionId, const std::string firstFile); int OnFileTransError(const int sessionId); void OnReceiveFileFinished(const int sessionId, const std::string files, int fileCnt); protected: - void StartInstance() override; // 第一次调用GetInstance时,注册softbus监听 - void StopInstance() override;; // 解注册 + void StartInstance() override; + void StopInstance() override; void OpenSession(const std::string &cid); void CloseSession(const std::string &cid); std::string GetPeerDevId(const int sessionId); private: - std::string sessionName_ {"DistributedFileService"}; - std::string pkgName_ {"ohos.storage.distributedfile.service"}; + std::string sessionName_{"DistributedFileService"}; + std::string pkgName_{"ohos.storage.distributedfile.service"}; std::unordered_map> cidToSessionID_; std::mutex getSessionCVMut_; diff --git a/services/distributedfileservice/src/device/device_manager_agent.cpp b/services/distributedfileservice/src/device/device_manager_agent.cpp index 2b52387ca..a144b3a4d 100644 --- a/services/distributedfileservice/src/device/device_manager_agent.cpp +++ b/services/distributedfileservice/src/device/device_manager_agent.cpp @@ -43,12 +43,7 @@ void DeviceManagerAgent::OnDeviceOnline(const DistributedHardware::DmDeviceInfo { std::string cid = std::string(deviceInfo.deviceId); alreadyOnlineDev_.insert(cid); - if (alreadyRegis_) { - return; - } - - auto softBusAgent = SoftbusAgent::GetInstance(); - alreadyRegis_ = true; + SoftbusAgent::GetInstance(); } void DeviceManagerAgent::OnDeviceOffline(const DistributedHardware::DmDeviceInfo &deviceInfo) @@ -58,15 +53,14 @@ void DeviceManagerAgent::OnDeviceOffline(const DistributedHardware::DmDeviceInfo softBusAgent->OnDeviceOffline(cid); alreadyOnlineDev_.erase(cid); - if (alreadyOnlineDev_.size() == 0) { - alreadyRegis_ = false; - } - LOGI("cid %s offline, left online devices num %d", cid.c_str(), alreadyOnlineDev_.size()); + LOGI("cid %{public}s offline, left online devices num %{public}d", cid.c_str(), alreadyOnlineDev_.size()); } void DeviceManagerAgent::OnRemoteDied() { LOGI("device manager service died"); + UnregisterFromExternalDm(); + RegisterToExternalDm(); } void DeviceManagerAgent::RegisterToExternalDm() diff --git a/services/distributedfileservice/src/ipc/distributedfile_service.cpp b/services/distributedfileservice/src/ipc/distributedfile_service.cpp index 91c66708b..22c880d7d 100644 --- a/services/distributedfileservice/src/ipc/distributedfile_service.cpp +++ b/services/distributedfileservice/src/ipc/distributedfile_service.cpp @@ -24,7 +24,9 @@ namespace Storage { namespace DistributedFile { using namespace std; -DistributedFileService::DistributedFileService() : SystemAbility(STORAGE_DISTRIBUTED_FILE_SERVICE_SA_ID, false) {} +const bool g_registerResult = SystemAbility::MakeAndRegisterAbility(DistributedFileService::GetInstance().get()); + +DistributedFileService::DistributedFileService() : SystemAbility(STORAGE_DISTRIBUTED_FILE_SERVICE_SA_ID, true) {} DistributedFileService::~DistributedFileService() {} @@ -35,7 +37,7 @@ void DistributedFileService::OnDump() void DistributedFileService::PublishSA() { - LOGI("Begin to init, pull the service"); // todo: 看一下ipc使用方法;是否必须使用单例?; 是否需要加flag?; 抛异常处理? + LOGI("xhl Begin to init, pull the service"); // todo: 看一下ipc使用方法;是否必须使用单例?; 是否需要加flag?; 抛异常处理? bool ret = SystemAbility::Publish(this); // DelayedSingleton::GetInstance().get() if (!ret) { throw runtime_error("publishing DistributedFileService failed"); @@ -47,7 +49,7 @@ void DistributedFileService::PublishSA() // } // registerToService_ = true; // } - LOGI("Init finished successfully"); + LOGI("xhl Init finished successfully"); } void DistributedFileService::StartManagers() { @@ -56,11 +58,12 @@ void DistributedFileService::StartManagers() void DistributedFileService::OnStart() { + LOGI("DistributedFileService::OnStart"); try { PublishSA(); StartManagers(); } catch (const Exception &e) { - LOGE("%{public}s", e.what()); + LOGE("xhl %{public}s", e.what()); } } diff --git a/services/distributedfileservice/src/network/softbus_agent.cpp b/services/distributedfileservice/src/network/softbus_agent.cpp index 15d8b94f1..50fe1625c 100644 --- a/services/distributedfileservice/src/network/softbus_agent.cpp +++ b/services/distributedfileservice/src/network/softbus_agent.cpp @@ -15,12 +15,15 @@ #include "softbus_agent.h" +#include "device_manager_agent.h" #include "session.h" #include "softbus_dispatcher.h" +#include "utils_directory.h" #include "utils_exception.h" #include "utils_log.h" -#include "device_manager_agent.h" +#include #include +#include namespace OHOS { namespace Storage { @@ -40,23 +43,25 @@ void SoftbusAgent::StartInstance() { RegisterSessionListener(); RegisterFileListener(); + + // todo:测试接口SendFile + auto alreadyOnliceDev = DeviceManagerAgent::GetInstance()->getOnlineDevs(); + auto iter = alreadyOnliceDev.begin(); + OpenSession((*iter)); + LOGE("OpenSession done"); } void SoftbusAgent::StopInstance() { - // sessionId的释放,clossSession for (auto iter = cidToSessionID_.begin(); iter != cidToSessionID_.end();) { CloseSession(iter->first); iter = cidToSessionID_.erase(iter); } - // 变量 cidToSessionID_, 依次释放 getSessionCV_.notify_all(); - // 解注册 UnRegisterSessionListener(); - UnRegisterFileListener(); } -int SoftbusAgent::SendFile(std::string &cid, const char *sFileList[], const char *dFileList[], uint32_t fileCnt) +int SoftbusAgent::SendFile(const std::string &cid, const char *sFileList[], const char *dFileList[], uint32_t fileCnt) { // first check whether the sessionId available auto alreadyOnliceDev = DeviceManagerAgent::GetInstance()->getOnlineDevs(); @@ -74,37 +79,41 @@ int SoftbusAgent::SendFile(std::string &cid, const char *sFileList[], const char OpenSession(cid); // wait for get sessionId + LOGD("openSession, wait"); std::unique_lock lock(getSessionCVMut_); getSessionCV_.wait(lock, [this, cid]() { return !cidToSessionID_[cid].empty(); }); } + LOGD("openSession success, wakeup"); if (cidToSessionID_[cid].empty()) { // todo 唤醒检查 LOGE("there is no sessionId of cid:%{public}s", cid.c_str()); return -1; } sessionId = cidToSessionID_[cid].front(); + int ret = ::SendFile(sessionId, sFileList, dFileList, fileCnt); // todo:const string ==> const char * ==> const char ** - LOGD("sendfile is processing, cid:%{public}s, sessionId:%{publid}d, ret %{public}d", cid.c_str(), sessionId, ret); + LOGE("sendfile is processing, sessionId:%{publid}d, ret %{public}d", sessionId, ret); return ret; } void SoftbusAgent::OpenSession(const std::string &cid) { SessionAttribute attr; - attr.dataType = TYPE_BYTES; + attr.dataType = TYPE_FILE; // files use UDP, CHANNEL_TYPE_UDP LOGD("Start to Open Session, cid:%{public}s", cid.c_str()); int sessionId = ::OpenSession(sessionName_.c_str(), sessionName_.c_str(), cid.c_str(), "DFS_wifiGroup", &attr); if (sessionId < 0) { LOGE("Failed to open session, cid:%{public}s, sessionId:%{public}d", cid.c_str(), sessionId); - ThrowException(ERR_SOFTBUS_AGENT_ON_SESSION_OPENED_FAIL, "Open Session failed"); + return; } - LOGD("Open Session SUCCESS, cid:%{public}s", cid.c_str()); + LOGD("Open Session SUCCESS, cid:%{public}s, sessionId %{public}d", cid.c_str(), sessionId); } void SoftbusAgent::OnSessionOpened(const int sessionId, const int result) { - if (result != 0) { // 增加重试? + LOGD("get session res:%{public}d, sessionId:%{public}d", result, sessionId); + if (result != 0) { // todo:增加重试? LOGE("open failed, result:%{public}d, sessionId:%{public}d", result, sessionId); return; } @@ -124,6 +133,21 @@ void SoftbusAgent::OnSessionOpened(const int sessionId, const int result) // cv 唤醒等待的sendfile流程 getSessionCV_.notify_one(); LOGD("get session SUCCESS, sessionId:%{public}d", sessionId); + + // todo:测试接口SendFile + auto alreadyOnliceDev = DeviceManagerAgent::GetInstance()->getOnlineDevs(); + auto iter = alreadyOnliceDev.begin(); + + const char *sFileList[1] = {"/data/user/0/xhl_sendfile_test/1.txt"}; + + static int sendfile_cnt = 0; + // int ret = SendFile((*iter), sFileList, dFileList, 1); + int ret = SendFile((*iter), sFileList, nullptr, 1); + if (ret != 0) { + LOGE("sendfile failed, ret %{public}d", ret); + return; + } + LOGE("sendfile... ret %{public}d, sendfile_cnt %{public}d", ret, sendfile_cnt); } int SoftbusAgent::OnSendFileFinished(const int sessionId, const std::string firstFile) @@ -156,10 +180,6 @@ void SoftbusAgent::OnSessionClosed(int sessionId) if (cidToSessionID_.find(cid) != cidToSessionID_.end()) { cidToSessionID_[cid].remove(sessionId); } - // 可能list链表为空, 是否要删除此map信息? - if (cidToSessionID_[cid].empty()) { - // cidToSessionID_.erase(cid); - } return; } @@ -206,7 +226,7 @@ void SoftbusAgent::RegisterSessionListener() stringstream ss; ss << "Failed to CreateSessionServer, errno:" << ret; LOGE("%{public}s, sessionName:%{public}s", ss.str().c_str(), sessionName_.c_str()); - throw runtime_error(ss.str()); + return throw runtime_error(ss.str()); } LOGD("Succeed to CreateSessionServer, pkgName %{public}s, sbusName:%{public}s", pkgName_.c_str(), sessionName_.c_str()); @@ -233,7 +253,7 @@ void SoftbusAgent::RegisterFileListener() .OnFileTransError = SoftbusDispatcher::OnFileTransError, }; ret = ::SetFileReceiveListener(pkgName_.c_str(), sessionName_.c_str(), &fileRecvListener, - "/data/tmp/"); // rootDir TODO + "/data/user/0/"); // rootDir TODO if (ret != 0) { stringstream ss; ss << "Failed to SetFileReceiveListener, errno:" << ret; @@ -254,7 +274,6 @@ void SoftbusAgent::UnRegisterSessionListener() } LOGD("RemoveSessionServer success!"); } -void SoftbusAgent::UnRegisterFileListener() {} } // namespace DistributedFile } // namespace Storage } // namespace OHOS \ No newline at end of file diff --git a/services/distributedfileservice/src/network/softbus_dispatcher.cpp b/services/distributedfileservice/src/network/softbus_dispatcher.cpp index 5a4dc948c..464ae4de5 100644 --- a/services/distributedfileservice/src/network/softbus_dispatcher.cpp +++ b/services/distributedfileservice/src/network/softbus_dispatcher.cpp @@ -15,6 +15,7 @@ #include "softbus_dispatcher.h" #include "softbus_agent.h" +#include "utils_log.h" namespace OHOS { namespace Storage { @@ -22,28 +23,33 @@ namespace DistributedFile { int SoftbusDispatcher::OnSessionOpened(int sessionId, int result) { + LOGD("get session res:%{public}d, sessionId:%{public}d", result, sessionId); SoftbusAgent::GetInstance()->OnSessionOpened(sessionId, result); return 0; } void SoftbusDispatcher::OnSessionClosed(int sessionId) { + LOGD("sessionId:%{public}d", sessionId); SoftbusAgent::GetInstance()->OnSessionClosed(sessionId); } int SoftbusDispatcher::OnSendFileFinished(int sessionId, const char *firstFile) { + LOGD("sessionId:%{public}d", sessionId); SoftbusAgent::GetInstance()->OnSendFileFinished(sessionId, std::string(firstFile)); return 0; } void SoftbusDispatcher::OnFileTransError(int sessionId) { + LOGD("sessionId:%{public}d", sessionId); SoftbusAgent::GetInstance()->OnFileTransError(sessionId); } void SoftbusDispatcher::OnReceiveFileFinished(int sessionId, const char *files, int fileCnt) { + LOGD("sessionId:%{public}d", sessionId); SoftbusAgent::GetInstance()->OnReceiveFileFinished(sessionId, std::string(files), fileCnt); } -- Gitee From 2389605ad8f925c9b2e01a524ad75a7b7e34a4a2 Mon Sep 17 00:00:00 2001 From: x00456388 Date: Thu, 30 Dec 2021 12:19:39 +0800 Subject: [PATCH 07/14] add softbut online to openssion Signed-off-by: x00456388 --- .../include/network/softbus_agent.h | 2 +- .../src/device/device_manager_agent.cpp | 2 +- .../src/network/softbus_agent.cpp | 11 +++++------ 3 files changed, 7 insertions(+), 8 deletions(-) diff --git a/services/distributedfileservice/include/network/softbus_agent.h b/services/distributedfileservice/include/network/softbus_agent.h index 8e9032853..496ff7d28 100644 --- a/services/distributedfileservice/include/network/softbus_agent.h +++ b/services/distributedfileservice/include/network/softbus_agent.h @@ -31,7 +31,7 @@ public: void RegisterSessionListener(); void RegisterFileListener(); void UnRegisterSessionListener(); - + void OnDeviceOnline(const std::string &cid); void OnDeviceOffline(const std::string &cid); void AllDevicesOffline(); void OnSessionOpened(const int sessionId, const int result); diff --git a/services/distributedfileservice/src/device/device_manager_agent.cpp b/services/distributedfileservice/src/device/device_manager_agent.cpp index a144b3a4d..d15be3711 100644 --- a/services/distributedfileservice/src/device/device_manager_agent.cpp +++ b/services/distributedfileservice/src/device/device_manager_agent.cpp @@ -43,7 +43,7 @@ void DeviceManagerAgent::OnDeviceOnline(const DistributedHardware::DmDeviceInfo { std::string cid = std::string(deviceInfo.deviceId); alreadyOnlineDev_.insert(cid); - SoftbusAgent::GetInstance(); + SoftbusAgent::GetInstance()->OnDeviceOnline(cid); } void DeviceManagerAgent::OnDeviceOffline(const DistributedHardware::DmDeviceInfo &deviceInfo) diff --git a/services/distributedfileservice/src/network/softbus_agent.cpp b/services/distributedfileservice/src/network/softbus_agent.cpp index 50fe1625c..285c2914d 100644 --- a/services/distributedfileservice/src/network/softbus_agent.cpp +++ b/services/distributedfileservice/src/network/softbus_agent.cpp @@ -43,12 +43,6 @@ void SoftbusAgent::StartInstance() { RegisterSessionListener(); RegisterFileListener(); - - // todo:测试接口SendFile - auto alreadyOnliceDev = DeviceManagerAgent::GetInstance()->getOnlineDevs(); - auto iter = alreadyOnliceDev.begin(); - OpenSession((*iter)); - LOGE("OpenSession done"); } void SoftbusAgent::StopInstance() @@ -61,6 +55,11 @@ void SoftbusAgent::StopInstance() UnRegisterSessionListener(); } +void SoftbusAgent::OnDeviceOnline(const std::string &cid) +{ + OpenSession(cid); +} + int SoftbusAgent::SendFile(const std::string &cid, const char *sFileList[], const char *dFileList[], uint32_t fileCnt) { // first check whether the sessionId available -- Gitee From 34a0cd7834b4d2b8f87cbe45b72d6ad49227a9d6 Mon Sep 17 00:00:00 2001 From: xianghengliang Date: Tue, 4 Jan 2022 14:48:32 +0800 Subject: [PATCH 08/14] distributedfileservice sa register code refactoring Signed-off-by: xianghengliang --- .../include/ipc/distributedfile_service.h | 6 +++--- .../src/ipc/distributedfile_service.cpp | 6 +----- 2 files changed, 4 insertions(+), 8 deletions(-) diff --git a/services/distributedfileservice/include/ipc/distributedfile_service.h b/services/distributedfileservice/include/ipc/distributedfile_service.h index 48fa9685c..af065ad0e 100644 --- a/services/distributedfileservice/include/ipc/distributedfile_service.h +++ b/services/distributedfileservice/include/ipc/distributedfile_service.h @@ -19,18 +19,18 @@ #include "distributedfile_service_stub.h" #include "iremote_stub.h" #include "system_ability.h" -#include "utils_singleton.h" namespace OHOS { namespace Storage { namespace DistributedFile { class DistributedFileService : public SystemAbility, public DistributedFileServiceStub, - public Utils::Singleton, public std::enable_shared_from_this { - DECLARE_SINGLETON(DistributedFileService); DECLARE_SYSTEM_ABILITY(DistributedFileService) public: + DistributedFileService(int32_t saID, bool runOnCreate) : SystemAbility(saID, runOnCreate){}; + ~DistributedFileService() {}; + void OnDump() override; void OnStart() override; void OnStop() override; diff --git a/services/distributedfileservice/src/ipc/distributedfile_service.cpp b/services/distributedfileservice/src/ipc/distributedfile_service.cpp index 22c880d7d..accc3e420 100644 --- a/services/distributedfileservice/src/ipc/distributedfile_service.cpp +++ b/services/distributedfileservice/src/ipc/distributedfile_service.cpp @@ -24,11 +24,7 @@ namespace Storage { namespace DistributedFile { using namespace std; -const bool g_registerResult = SystemAbility::MakeAndRegisterAbility(DistributedFileService::GetInstance().get()); - -DistributedFileService::DistributedFileService() : SystemAbility(STORAGE_DISTRIBUTED_FILE_SERVICE_SA_ID, true) {} - -DistributedFileService::~DistributedFileService() {} +REGISTER_SYSTEM_ABILITY_BY_ID(DistributedFileService, STORAGE_DISTRIBUTED_FILE_SERVICE_SA_ID, false); void DistributedFileService::OnDump() { -- Gitee From f115631cf6aee716c9249ac19f21206debc58ff4 Mon Sep 17 00:00:00 2001 From: xianghengliang Date: Tue, 4 Jan 2022 17:18:14 +0800 Subject: [PATCH 09/14] open session triggered by sendfile,and add mutex Signed-off-by: xianghengliang --- .../include/device/device_manager_agent.h | 1 + .../include/network/softbus_agent.h | 3 +- .../src/device/device_manager_agent.cpp | 3 + .../src/ipc/distributedfile_service.cpp | 15 +--- .../src/network/softbus_agent.cpp | 76 ++++++++++--------- 5 files changed, 50 insertions(+), 48 deletions(-) diff --git a/services/distributedfileservice/include/device/device_manager_agent.h b/services/distributedfileservice/include/device/device_manager_agent.h index 2dc232ad5..051a3d4fc 100644 --- a/services/distributedfileservice/include/device/device_manager_agent.h +++ b/services/distributedfileservice/include/device/device_manager_agent.h @@ -55,6 +55,7 @@ private: void RegisterToExternalDm(); void UnregisterFromExternalDm(); + std::mutex devsRecordMutex_; std::set alreadyOnlineDev_; std::string pkgName_{"ohos.storage.distributedfile.service"}; diff --git a/services/distributedfileservice/include/network/softbus_agent.h b/services/distributedfileservice/include/network/softbus_agent.h index 496ff7d28..a3e078d45 100644 --- a/services/distributedfileservice/include/network/softbus_agent.h +++ b/services/distributedfileservice/include/network/softbus_agent.h @@ -45,12 +45,13 @@ protected: void StartInstance() override; void StopInstance() override; void OpenSession(const std::string &cid); - void CloseSession(const std::string &cid); + int CloseSession(const std::string &cid); std::string GetPeerDevId(const int sessionId); private: std::string sessionName_{"DistributedFileService"}; std::string pkgName_{"ohos.storage.distributedfile.service"}; + std::mutex sessionMapMux_; std::unordered_map> cidToSessionID_; std::mutex getSessionCVMut_; diff --git a/services/distributedfileservice/src/device/device_manager_agent.cpp b/services/distributedfileservice/src/device/device_manager_agent.cpp index d15be3711..e73efb8e4 100644 --- a/services/distributedfileservice/src/device/device_manager_agent.cpp +++ b/services/distributedfileservice/src/device/device_manager_agent.cpp @@ -30,6 +30,7 @@ DeviceManagerAgent::~DeviceManagerAgent() } void DeviceManagerAgent::StartInstance() { + // the time sequence can ensure there is no resource competition alreadyOnlineDev_.clear(); RegisterToExternalDm(); } @@ -41,6 +42,7 @@ void DeviceManagerAgent::StopInstance() void DeviceManagerAgent::OnDeviceOnline(const DistributedHardware::DmDeviceInfo &deviceInfo) { + std::unique_lock lock(devsRecordMutex_); std::string cid = std::string(deviceInfo.deviceId); alreadyOnlineDev_.insert(cid); SoftbusAgent::GetInstance()->OnDeviceOnline(cid); @@ -48,6 +50,7 @@ void DeviceManagerAgent::OnDeviceOnline(const DistributedHardware::DmDeviceInfo void DeviceManagerAgent::OnDeviceOffline(const DistributedHardware::DmDeviceInfo &deviceInfo) { + std::unique_lock lock(devsRecordMutex_); std::string cid = std::string(deviceInfo.deviceId); auto softBusAgent = SoftbusAgent::GetInstance(); softBusAgent->OnDeviceOffline(cid); diff --git a/services/distributedfileservice/src/ipc/distributedfile_service.cpp b/services/distributedfileservice/src/ipc/distributedfile_service.cpp index accc3e420..9ce0978fd 100644 --- a/services/distributedfileservice/src/ipc/distributedfile_service.cpp +++ b/services/distributedfileservice/src/ipc/distributedfile_service.cpp @@ -33,19 +33,12 @@ void DistributedFileService::OnDump() void DistributedFileService::PublishSA() { - LOGI("xhl Begin to init, pull the service"); // todo: 看一下ipc使用方法;是否必须使用单例?; 是否需要加flag?; 抛异常处理? - bool ret = SystemAbility::Publish(this); // DelayedSingleton::GetInstance().get() + LOGI("Begin to init, pull the service SA"); + bool ret = SystemAbility::Publish(this); if (!ret) { throw runtime_error("publishing DistributedFileService failed"); } - // if (!registerToService_) { - // bool ret = SystemAbility::Publish(this); - // if (!ret) { - // throw runtime_error("Failed to publish the daemon"); - // } - // registerToService_ = true; - // } - LOGI("xhl Init finished successfully"); + LOGI("Init finished successfully"); } void DistributedFileService::StartManagers() { @@ -59,7 +52,7 @@ void DistributedFileService::OnStart() PublishSA(); StartManagers(); } catch (const Exception &e) { - LOGE("xhl %{public}s", e.what()); + LOGE("%{public}s", e.what()); } } diff --git a/services/distributedfileservice/src/network/softbus_agent.cpp b/services/distributedfileservice/src/network/softbus_agent.cpp index 285c2914d..48857cb3d 100644 --- a/services/distributedfileservice/src/network/softbus_agent.cpp +++ b/services/distributedfileservice/src/network/softbus_agent.cpp @@ -18,7 +18,6 @@ #include "device_manager_agent.h" #include "session.h" #include "softbus_dispatcher.h" -#include "utils_directory.h" #include "utils_exception.h" #include "utils_log.h" #include @@ -57,7 +56,17 @@ void SoftbusAgent::StopInstance() void SoftbusAgent::OnDeviceOnline(const std::string &cid) { - OpenSession(cid); + // todo:测试接口SendFile + const char *sFileList[1] = {"/data/user/0/xhl_sendfile_test/1.txt"}; + + static int sendfile_cnt = 0; + // int ret = SendFile((*iter), sFileList, dFileList, 1); + int ret = SendFile(cid, sFileList, nullptr, 1); + if (ret != 0) { + LOGE("sendfile failed, ret %{public}d", ret); + return; + } + LOGE("sendfile... ret %{public}d, sendfile_cnt %{public}d", ret, sendfile_cnt); } int SoftbusAgent::SendFile(const std::string &cid, const char *sFileList[], const char *dFileList[], uint32_t fileCnt) @@ -69,28 +78,30 @@ int SoftbusAgent::SendFile(const std::string &cid, const char *sFileList[], cons return -1; } int sessionId = -1; - if (cidToSessionID_.find(cid) != cidToSessionID_.end() && - cidToSessionID_[cid].begin() != cidToSessionID_[cid].end()) { // to avoid list is empty - sessionId = cidToSessionID_[cid].front(); + { + std::unique_lock lock(sessionMapMux_); + if (cidToSessionID_.find(cid) != cidToSessionID_.end() && + cidToSessionID_[cid].empty() == false) { // to avoid list is empty + sessionId = cidToSessionID_[cid].front(); + } } + // build socket synchronously if (sessionId == -1) { OpenSession(cid); - // wait for get sessionId LOGD("openSession, wait"); std::unique_lock lock(getSessionCVMut_); getSessionCV_.wait(lock, [this, cid]() { return !cidToSessionID_[cid].empty(); }); + LOGD("openSession success, wakeup"); + if (cidToSessionID_[cid].empty()) { // wakeup check + LOGE("there is no sessionId of cid:%{public}s", cid.c_str()); + return -1; + } + sessionId = cidToSessionID_[cid].front(); } - LOGD("openSession success, wakeup"); - if (cidToSessionID_[cid].empty()) { // todo 唤醒检查 - LOGE("there is no sessionId of cid:%{public}s", cid.c_str()); - return -1; - } - sessionId = cidToSessionID_[cid].front(); - int ret = - ::SendFile(sessionId, sFileList, dFileList, fileCnt); // todo:const string ==> const char * ==> const char ** + int ret = ::SendFile(sessionId, sFileList, dFileList, fileCnt); LOGE("sendfile is processing, sessionId:%{publid}d, ret %{public}d", sessionId, ret); return ret; } @@ -123,30 +134,18 @@ void SoftbusAgent::OnSessionOpened(const int sessionId, const int result) } // client session priority use, so insert list head - if (::GetSessionSide(sessionId) == IS_CLIENT) { - cidToSessionID_[cid].push_front(sessionId); - } else { - cidToSessionID_[cid].push_back(sessionId); + { + std::unique_lock lock(sessionMapMux_); + if (::GetSessionSide(sessionId) == IS_CLIENT) { + cidToSessionID_[cid].push_front(sessionId); + } else { + cidToSessionID_[cid].push_back(sessionId); + } } // cv 唤醒等待的sendfile流程 getSessionCV_.notify_one(); LOGD("get session SUCCESS, sessionId:%{public}d", sessionId); - - // todo:测试接口SendFile - auto alreadyOnliceDev = DeviceManagerAgent::GetInstance()->getOnlineDevs(); - auto iter = alreadyOnliceDev.begin(); - - const char *sFileList[1] = {"/data/user/0/xhl_sendfile_test/1.txt"}; - - static int sendfile_cnt = 0; - // int ret = SendFile((*iter), sFileList, dFileList, 1); - int ret = SendFile((*iter), sFileList, nullptr, 1); - if (ret != 0) { - LOGE("sendfile failed, ret %{public}d", ret); - return; - } - LOGE("sendfile... ret %{public}d, sendfile_cnt %{public}d", ret, sendfile_cnt); } int SoftbusAgent::OnSendFileFinished(const int sessionId, const std::string firstFile) @@ -176,6 +175,7 @@ void SoftbusAgent::OnSessionClosed(int sessionId) LOGE("get peer device id failed"); return; } + std::unique_lock lock(sessionMapMux_); if (cidToSessionID_.find(cid) != cidToSessionID_.end()) { cidToSessionID_[cid].remove(sessionId); } @@ -196,21 +196,25 @@ std::string SoftbusAgent::GetPeerDevId(const int sessionId) // 确认是否需 return cid; } -void SoftbusAgent::CloseSession(const std::string &cid) +int SoftbusAgent::CloseSession(const std::string &cid) { if (cidToSessionID_.find(cid) == cidToSessionID_.end()) { LOGE("not find this dev-cid:%{public}s", cid.c_str()); - return; + return -1; } for (auto sessionId : cidToSessionID_[cid]) { ::CloseSession(sessionId); } LOGD("Close Session done, cid:%{public}s", cid.c_str()); + return 0; } void SoftbusAgent::OnDeviceOffline(const std::string &cid) { - CloseSession(cid); + if (CloseSession(cid) == -1){ + return; + } + std::unique_lock lock(sessionMapMux_); cidToSessionID_.erase(cid); } -- Gitee From 3a987bed73a66f9029429b338a4f989568e77dac Mon Sep 17 00:00:00 2001 From: xianghengliang Date: Thu, 6 Jan 2022 20:39:52 +0800 Subject: [PATCH 10/14] ipc bugfix and build test bin,and todo:later del test bin code Signed-off-by: xianghengliang --- executable/BUILD.gn | 45 +++++++++++++++ executable/main.cpp | 56 +++++++++++++++++++ frameworks/native/service_proxy.cpp | 47 +++++++--------- frameworks/native/service_proxy.h | 13 +++-- .../innerkits/js/mod_sendfile/sendfile.cpp | 13 ++--- .../native/i_distributedfile_service.h | 12 ++-- ohos.build | 3 +- .../include/ipc/distributedfile_service.h | 10 +++- .../ipc/distributedfile_service_stub.h | 3 +- .../src/ipc/distributedfile_service.cpp | 47 +++++----------- .../src/ipc/distributedfile_service_stub.cpp | 34 +++++------ 11 files changed, 182 insertions(+), 101 deletions(-) create mode 100644 executable/BUILD.gn create mode 100644 executable/main.cpp diff --git a/executable/BUILD.gn b/executable/BUILD.gn new file mode 100644 index 000000000..c80d48bf6 --- /dev/null +++ b/executable/BUILD.gn @@ -0,0 +1,45 @@ +# Copyright (c) 2021 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") + +ohos_executable("xhl_test-sa") { + include_dirs = [ + "../frameworks/native", + "../utils/log/include" + ] + + sources = [ "main.cpp" ] + + defines = [ + "LOG_DOMAIN=0xD001600", + "LOG_TAG=\"xhl_test_exec\"", + ] + + external_deps = [ + "aafwk_standard:want", + "appexecfwk_standard:appexecfwk_base", + "appexecfwk_standard:appexecfwk_core", + "ipc:ipc_core", + "safwk:system_ability_fwk", + "samgr_standard:samgr_proxy", + ] + + deps = [ + "../utils:libdistributedfileutils", + "../interfaces/innerkits/native:libdistributedfile_innerkits", + ] + + install_enable = true + part_name = "storage_distributed_file_manager" + subsystem_name = "storage" +} diff --git a/executable/main.cpp b/executable/main.cpp new file mode 100644 index 000000000..6c6582784 --- /dev/null +++ b/executable/main.cpp @@ -0,0 +1,56 @@ +/* + * Copyright (c) 2021 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 +#include +#include +#include "bundle_mgr_interface.h" +#include "bundle_mgr_proxy.h" +#include "service_proxy.h" +#include "iservice_registry.h" +#include "system_ability_definition.h" +#include "utils_log.h" + +using namespace OHOS; +using namespace OHOS::Storage::DistributedFile; + +static void TestTutorial() +{ + auto samgr = SystemAbilityManagerClient::GetInstance().GetSystemAbilityManager(); + LOGE("xhl Get samgr %{public}p", samgr.GetRefPtr()); + + auto remote = samgr->GetSystemAbility(STORAGE_DISTRIBUTED_FILE_SERVICE_SA_ID); + LOGE("xhl Get remote %{public}p", remote.GetRefPtr()); + + auto proxy = iface_cast(remote); + LOGE("xhl Get proxy %{public}p", proxy.GetRefPtr()); + + std::string cid{"123"}; + std::vector srcList; + std::vector dstList; + uint32_t fileCount = 2; + LOGE("xhl prepare to sendfile"); + int ret = proxy->SendFile(cid, srcList, dstList, fileCount); + LOGE("xhl sendfile finish ret %{public}d", ret); + ret = proxy->sendTest(); + LOGE("xhl sendTest finish ret %{public}d", ret); +} + +int main(int argc, char const *argv[]) +{ + TestTutorial(); + LOGE("xhl main finish"); + return 0; +} \ No newline at end of file diff --git a/frameworks/native/service_proxy.cpp b/frameworks/native/service_proxy.cpp index 2339d8441..57857ad1a 100644 --- a/frameworks/native/service_proxy.cpp +++ b/frameworks/native/service_proxy.cpp @@ -19,37 +19,30 @@ namespace OHOS { namespace Storage { namespace DistributedFile { -ServiceProxy::ServiceProxy(const sptr &impl) : IRemoteProxy(impl) {} -ServiceProxy::~ServiceProxy() {} -int32_t ServiceProxy::SendFile(int32_t sessionId, const std::string &sourceFileList, - const std::string &destinationFileList, uint32_t fileCount) +int32_t ServiceProxy::SendFile(const std::string &cid, + const std::vector &sourceFileList, + const std::vector &destinationFileList, + const uint32_t fileCount) { - int32_t error = SEND_FILE_FAIL; + LOGE("xhl sendFile enter"); + MessageParcel data; + MessageParcel reply; MessageOption option; - MessageParcel dataParcel; - MessageParcel replyParcel; - if (!dataParcel.WriteInterfaceToken(ServiceProxy::GetDescriptor())) { - LOGE("write descriptor failed"); - return SEND_FILE_DISTRIBUTED_DESCRIPTION_FAIL; - } - - dataParcel.WriteInt32(sessionId); - dataParcel.WriteString(sourceFileList); - dataParcel.WriteString(destinationFileList); - dataParcel.WriteUint32(fileCount); - if (Remote() == nullptr) { - LOGE("Remote object address is null"); - return DISTRIBUTEDFILE_REMOTE_ADDRESS_IS_NULL; - } - - error = Remote()->SendRequest(SEND_FILE_DISTRIBUTED, dataParcel, replyParcel, option); - if (error != DISTRIBUTEDFILE_NO_ERROR) { - LOGE("Function RemoveBundleDistributedDirs! errCode:%{public}d", error); - return DISTRIBUTEDFILE_CONNECT_SYSTEM_ABILITY_STUB_FAIL; - } + int ret = Remote()->SendRequest(SEND_FILE_DISTRIBUTED, data, reply, option); + LOGE("xhl sendfile sendRequest done %{public}d", ret); + return ret; +} - return replyParcel.ReadInt32(); +int32_t ServiceProxy::sendTest() +{ + LOGE("xhl sendTest enter"); + MessageParcel data; + MessageParcel reply; + MessageOption option; + int ret = Remote()->SendRequest(TEST_CODE, data, reply, option); + LOGE("xhl sendTest sendrequest done %{public}d", ret); + return ret; } } // namespace DistributedFile } // namespace Storage diff --git a/frameworks/native/service_proxy.h b/frameworks/native/service_proxy.h index 2347c0fe2..1cfcc8ac1 100644 --- a/frameworks/native/service_proxy.h +++ b/frameworks/native/service_proxy.h @@ -16,9 +16,9 @@ #ifndef DISTRIBUTEDFILE_SERVICE_PROXY_H #define DISTRIBUTEDFILE_SERVICE_PROXY_H -#include #include "i_distributedfile_service.h" #include "message_parcel.h" +#include namespace OHOS { namespace Storage { @@ -30,12 +30,15 @@ public: * * @param impl */ - explicit ServiceProxy(const sptr &impl); + explicit ServiceProxy(const sptr &impl) : IRemoteProxy(impl) {} - virtual ~ServiceProxy(); + virtual ~ServiceProxy() = default; - int32_t SendFile(int32_t sessionId, const std::string &sourceFileList, - const std::string &destinationFileList, uint32_t fileCount) override; + int32_t SendFile(const std::string &cid, + const std::vector &sourceFileList, + const std::vector &destinationFileList, + const uint32_t fileCount) override; + int32_t sendTest() override; private: static inline BrokerDelegator delegator_; }; diff --git a/interfaces/innerkits/js/mod_sendfile/sendfile.cpp b/interfaces/innerkits/js/mod_sendfile/sendfile.cpp index bac76883a..87d0ac3ad 100644 --- a/interfaces/innerkits/js/mod_sendfile/sendfile.cpp +++ b/interfaces/innerkits/js/mod_sendfile/sendfile.cpp @@ -114,7 +114,7 @@ napi_value SendFile(napi_env env, napi_callback_info info) return NVal::CreateUndefined(env).val_; } -int32_t ExecSendFile(const std::string deviceId, const std::vector& srcList, const std::vector& dstList, uint32_t num) +int32_t ExecSendFile(const std::string deviceId, const std::vector& srcList, const std::vector& dstList, uint32_t fileCnt) { sptr systemAbilityMgr = SystemAbilityManagerClient::GetInstance().GetSystemAbilityManager(); @@ -122,20 +122,19 @@ int32_t ExecSendFile(const std::string deviceId, const std::vector& HILOGE("BundleService Get ISystemAbilityManager failed ... \n"); return -1; } - sptr remote = systemAbilityMgr->CheckSystemAbility(STORAGE_DISTRIBUTED_FILE_SERVICE_SA_ID); + sptr remote = systemAbilityMgr->GetSystemAbility(STORAGE_DISTRIBUTED_FILE_SERVICE_SA_ID); if (remote == nullptr) { HILOGE("DistributedFileService Get STORAGE_DISTRIBUTED_FILE_SERVICE_SA_ID = %d fail ... \n", STORAGE_DISTRIBUTED_FILE_SERVICE_SA_ID); return -1; } - sptr distributedFileService = iface_cast(remote); - if (distributedFileService == nullptr) { + sptr proxy = iface_cast(remote); + if (proxy == nullptr) { HILOGE("DistributedFileService == nullptr\n"); return -1; } - - HILOGE("DistributedFileService == distributedFileService"); - int32_t result = 0;//distributedFileService->SendDistributedFile(deviceId, sessionID, srcList, dstList, num); + HILOGE("test: get SA proxy, call sendfile"); + int32_t result = proxy->SendFile(deviceId, srcList, dstList, fileCnt); return result; } } // namespace ModuleSendFile diff --git a/interfaces/innerkits/native/i_distributedfile_service.h b/interfaces/innerkits/native/i_distributedfile_service.h index a547e4193..725725020 100644 --- a/interfaces/innerkits/native/i_distributedfile_service.h +++ b/interfaces/innerkits/native/i_distributedfile_service.h @@ -25,10 +25,7 @@ class IDistributedFileService : public IRemoteBroker { public: DECLARE_INTERFACE_DESCRIPTOR(u"OHOS.DistributedFile.IDistributedFileService"); // define the message code - enum DistributedFileSurfaceCode { - INTERFACE1 = 0, - SEND_FILE_DISTRIBUTED - }; + enum DistributedFileSurfaceCode { INTERFACE1 = 0, SEND_FILE_DISTRIBUTED, TEST_CODE }; // define the error code enum { DISTRIBUTEDFILE_SUCCESS = 0, @@ -50,8 +47,11 @@ public: SEND_FILE_FAIL, SEND_FILE_DISTRIBUTED_DESCRIPTION_FAIL }; - virtual int32_t SendFile(int32_t sessionId, const std::string &sourceFileList, - const std::string &destinationFileList, uint32_t fileCount) = 0; + virtual int32_t SendFile(const std::string &cid, + const std::vector &sourceFileList, + const std::vector &destinationFileList, + const uint32_t fileCount) = 0; + virtual int32_t sendTest() = 0; }; } // namespace DistributedFile } // namespace Storage diff --git a/ohos.build b/ohos.build index 463e45d55..df6eed8d8 100644 --- a/ohos.build +++ b/ohos.build @@ -8,7 +8,8 @@ ], "module_list": [ "//foundation/storage/distributed_file_manager/services/:services_target", - "//foundation/storage/distributed_file_manager/interfaces/innerkits/js:build_kits_js" + "//foundation/storage/distributed_file_manager/interfaces/innerkits/js:build_kits_js", + "//foundation/storage/distributed_file_manager/executable:xhl_test-sa" ], "inner_kits":[ { diff --git a/services/distributedfileservice/include/ipc/distributedfile_service.h b/services/distributedfileservice/include/ipc/distributedfile_service.h index af065ad0e..22dc36073 100644 --- a/services/distributedfileservice/include/ipc/distributedfile_service.h +++ b/services/distributedfileservice/include/ipc/distributedfile_service.h @@ -29,14 +29,18 @@ class DistributedFileService : public SystemAbility, DECLARE_SYSTEM_ABILITY(DistributedFileService) public: DistributedFileService(int32_t saID, bool runOnCreate) : SystemAbility(saID, runOnCreate){}; - ~DistributedFileService() {}; + ~DistributedFileService(){}; void OnDump() override; void OnStart() override; void OnStop() override; - int32_t SendFile(int32_t sessionId, const std::string &sourceFileList, - const std::string &destinationFileList, uint32_t fileCount) override; + int32_t SendFile(const std::string &cid, + const std::vector &sourceFileList, + const std::vector &destinationFileList, + const uint32_t fileCount) override; + int32_t sendTest() override; + private: void PublishSA(); void StartManagers(); diff --git a/services/distributedfileservice/include/ipc/distributedfile_service_stub.h b/services/distributedfileservice/include/ipc/distributedfile_service_stub.h index 643258274..a4c18bb51 100644 --- a/services/distributedfileservice/include/ipc/distributedfile_service_stub.h +++ b/services/distributedfileservice/include/ipc/distributedfile_service_stub.h @@ -36,7 +36,8 @@ private: using DistributedFileServiceFunc = int32_t (DistributedFileServiceStub::*)(MessageParcel &data, MessageParcel &reply); std::map memberFuncMap_; - int32_t GetSendFileInner(MessageParcel &data,MessageParcel &reply); + int32_t SendFileStub(MessageParcel &data, MessageParcel &reply); + int test(MessageParcel &data, MessageParcel &reply); }; } // namespace DistributedFile } // namespace Storage diff --git a/services/distributedfileservice/src/ipc/distributedfile_service.cpp b/services/distributedfileservice/src/ipc/distributedfile_service.cpp index 9ce0978fd..ab48a3ff3 100644 --- a/services/distributedfileservice/src/ipc/distributedfile_service.cpp +++ b/services/distributedfileservice/src/ipc/distributedfile_service.cpp @@ -14,10 +14,10 @@ */ #include "distributedfile_service.h" -#include #include "device_manager_agent.h" -#include "utils_log.h" #include "utils_exception.h" +#include "utils_log.h" +#include namespace OHOS { namespace Storage { @@ -61,39 +61,18 @@ void DistributedFileService::OnStop() LOGI("DistributedFileService::OnStop"); } -int32_t DistributedFileService::SendFile(int32_t sessionId, const std::string &sourceFileList, - const std::string &destinationFileList, uint32_t fileCount) +int32_t DistributedFileService::sendTest() { - // DistributedFileInfo metaBase; - // metaBase.name = dirName; - // if (metaBase.name.empty()) { - // LOGE("DistributedFileService-%{public}s: Failed to get app dir, error: invalid app name", __func__); - // return DISTRIBUTEDFILE_DIR_NAME_IS_EMPTY; - // } - - // sptr systemAbilityMgr = - // SystemAbilityManagerClient::GetInstance().GetSystemAbilityManager(); - // if (systemAbilityMgr == nullptr) { - // LOGE("BundleService Get ISystemAbilityManager failed ... \n"); - // return DISTRIBUTEDFILE_REMOTE_ADDRESS_IS_NULL; - // } - - // sptr remote = systemAbilityMgr->CheckSystemAbility(BUNDLE_MGR_SERVICE_SYS_ABILITY_ID); - // if (remote == nullptr) { - // LOGE("BundleService Get IRemoteObject failed ... \n"); - // return DISTRIBUTEDFILE_REMOTE_ADDRESS_IS_NULL; - // } - - // auto BundleMgrService = std::make_unique(remote); - // if (BundleMgrService.get() == nullptr) { - // LOGE("remote iface_cast BundleMgrService failed ... \n"); - // return DISTRIBUTEDFILE_REMOTE_ADDRESS_IS_NULL; - // } - - // Utils::ForceRemoveDirectory(metaBase.name); - //OpenSession(nullptr, nullptr, nullptr, nullptr, nullptr); - LOGD("DistributedFileService::SendFile"); - return DISTRIBUTEDFILE_SUCCESS; + LOGI("xhl DistributedFileService::sendTest"); + return 0; +} +int32_t DistributedFileService::SendFile(const std::string &cid, + const std::vector &sourceFileList, + const std::vector &destinationFileList, + const uint32_t fileCount) +{ + LOGD("xhl DistributedFileService::SendFile, sessionId %{public}s, fileCount %{public}d", cid.c_str(), fileCount); + return 0; } } // namespace DistributedFile } // namespace Storage diff --git a/services/distributedfileservice/src/ipc/distributedfile_service_stub.cpp b/services/distributedfileservice/src/ipc/distributedfile_service_stub.cpp index 8836e87a8..bc7e6bdd3 100644 --- a/services/distributedfileservice/src/ipc/distributedfile_service_stub.cpp +++ b/services/distributedfileservice/src/ipc/distributedfile_service_stub.cpp @@ -25,6 +25,8 @@ namespace Storage { namespace DistributedFile { DistributedFileServiceStub::DistributedFileServiceStub() { + memberFuncMap_[SEND_FILE_DISTRIBUTED] = &DistributedFileServiceStub::SendFileStub; + memberFuncMap_[TEST_CODE] = &DistributedFileServiceStub::test; } DistributedFileServiceStub::~DistributedFileServiceStub() @@ -37,11 +39,7 @@ int DistributedFileServiceStub::OnRemoteRequest(uint32_t code, MessageParcel &reply, MessageOption &option) { - std::u16string myDescriptor = DistributedFileServiceStub::GetDescriptor(); - std::u16string remoteDescriptor = data.ReadInterfaceToken(); - if (myDescriptor != remoteDescriptor) { - return DISTRIBUTEDFILE_BAD_TYPE; - } + LOGD("xhl DistributedFileServiceStub : OnRemoteRequest enter, code %{public}d ", code); auto itFunc = memberFuncMap_.find(code); if (itFunc != memberFuncMap_.end()) { @@ -53,20 +51,22 @@ int DistributedFileServiceStub::OnRemoteRequest(uint32_t code, return IPCObjectStub::OnRemoteRequest(code, data, reply, option); } +int DistributedFileServiceStub::test(MessageParcel &data, MessageParcel &reply) +{ + LOGD("xhl DistributedFileServiceStub : sendTest enter"); + sendTest(); + return 3; +} -int32_t DistributedFileServiceStub::GetSendFileInner(MessageParcel &data, MessageParcel &reply) +int32_t DistributedFileServiceStub::SendFileStub(MessageParcel &data, MessageParcel &reply) { - std::string dirName = data.ReadString(); - if (dirName.empty()) { - LOGE("DistributedFileService: Failed to get app dir, error: invalid app name"); - return DISTRIBUTEDFILE_DIR_NAME_IS_EMPTY; - } - int32_t sessionId = 0; - std::string sourceFileList{}; - std::string destinationFileList{}; - uint32_t fileCount = 0; - int32_t result = SendFile(sessionId, sourceFileList, destinationFileList, fileCount); - LOGD("DistributedFileServiceStub : GetBundleDistributedDir result = %{public}d", result); + LOGD("xhl DistributedFileServiceStub : SendFileStub enter"); + std::string cid = "123"; + std::vector srcList; + std::vector dstList; + uint32_t fileCount = 3; + int32_t result = SendFile(cid, srcList, dstList, fileCount); + LOGD("xhl DistributedFileServiceStub : SendFileStub result = %{public}d", result); if (!reply.WriteInt32(result)) { LOGE("fail to write parcel"); return DISTRIBUTEDFILE_WRITE_REPLY_FAIL; -- Gitee From d53b03bc8bbe32f2122de9e6b38370c5166378f5 Mon Sep 17 00:00:00 2001 From: hhchinasoft Date: Mon, 10 Jan 2022 12:09:46 +0800 Subject: [PATCH 11/14] sendfile interface napi code Signed-off-by: hhchinasoft --- frameworks/native/service_proxy.cpp | 37 ++++++++++++++++--- interfaces/innerkits/js/BUILD.gn | 3 +- .../innerkits/js/mod_sendfile/sendfile.cpp | 25 +++++++------ .../innerkits/js/mod_sendfile/sendfile.h | 5 ++- services/distributedfileservice/BUILD.gn | 1 + .../src/ipc/distributedfile_service.cpp | 31 ++++++++++++++++ .../src/ipc/distributedfile_service_stub.cpp | 24 ++++++++++-- 7 files changed, 100 insertions(+), 26 deletions(-) diff --git a/frameworks/native/service_proxy.cpp b/frameworks/native/service_proxy.cpp index 57857ad1a..afbaef669 100644 --- a/frameworks/native/service_proxy.cpp +++ b/frameworks/native/service_proxy.cpp @@ -25,13 +25,38 @@ int32_t ServiceProxy::SendFile(const std::string &cid, const std::vector &destinationFileList, const uint32_t fileCount) { - LOGE("xhl sendFile enter"); - MessageParcel data; - MessageParcel reply; + LOGI("xhl sendFile enter"); + int32_t result = SEND_FILE_FAIL; MessageOption option; - int ret = Remote()->SendRequest(SEND_FILE_DISTRIBUTED, data, reply, option); - LOGE("xhl sendfile sendRequest done %{public}d", ret); - return ret; + MessageParcel dataParcel; + MessageParcel replyParcel; + + dataParcel.WriteString(cid); + int32_t sourceListNumber = sourceFileList.size(); + dataParcel.WriteInt32(sourceListNumber); + for (int32_t index = 0; index < sourceListNumber; ++index) { + dataParcel.WriteString(sourceFileList.at(index)); + } + int32_t destinationListNumber = destinationFileList.size(); + dataParcel.WriteInt32(destinationListNumber); + for (int32_t index = 0; index < destinationListNumber; ++index) { + dataParcel.WriteString(destinationFileList.at(index)); + } + dataParcel.WriteUint32(fileCount); + + if (Remote() == nullptr) { + LOGE("Remote object address is null"); + return DISTRIBUTEDFILE_REMOTE_ADDRESS_IS_NULL; + } + + result = Remote()->SendRequest(SEND_FILE_DISTRIBUTED, dataParcel, replyParcel, option); + if (result != DISTRIBUTEDFILE_NO_ERROR) { + LOGE("Function RemoveBundleDistributedDirs! errCode:%{public}d", result); + return DISTRIBUTEDFILE_CONNECT_SYSTEM_ABILITY_STUB_FAIL; + } + LOGE("xhl sendfile sendRequest done %{public}d", result); + + return replyParcel.ReadInt32(); } int32_t ServiceProxy::sendTest() diff --git a/interfaces/innerkits/js/BUILD.gn b/interfaces/innerkits/js/BUILD.gn index 066a85fad..b246a537d 100644 --- a/interfaces/innerkits/js/BUILD.gn +++ b/interfaces/innerkits/js/BUILD.gn @@ -36,7 +36,6 @@ ohos_shared_library("sendfile") { ] include_dirs = [ - ".", "//foundation/storage/distributed_file_manager/interfaces/innerkits/js/common/napi/n_async", "//foundation/storage/distributed_file_manager/services/distributedfileservice/include/ipc", "//foundation/storage/distributed_file_manager/services/distributedfileservice/include", @@ -45,7 +44,7 @@ ohos_shared_library("sendfile") { "//foundation/communication/ipc/interfaces/innerkits/libdbinder/include", "//foundation/distributedschedule/samgr/services/samgr/native/include", "//foundation/distributedschedule/samgr/interfaces/innerkits/samgr_proxy/include", - + "//foundation/storage/distributed_file_manager/interfaces/innerkits/js/common", "//base/hiviewdfx/hilog/interfaces/native/innerkits/include", "//foundation/ace/napi/interfaces/kits", "//utils/system/safwk/native/include", diff --git a/interfaces/innerkits/js/mod_sendfile/sendfile.cpp b/interfaces/innerkits/js/mod_sendfile/sendfile.cpp index 87d0ac3ad..5a52ed9d3 100644 --- a/interfaces/innerkits/js/mod_sendfile/sendfile.cpp +++ b/interfaces/innerkits/js/mod_sendfile/sendfile.cpp @@ -17,13 +17,13 @@ #include -#include "../common/napi/n_class.h" -#include "../common/napi/n_func_arg.h" -#include "../common/napi/n_val.h" -#include "../common/uni_error.h" +#include "napi/n_class.h" +#include "napi/n_func_arg.h" +#include "napi/n_val.h" +#include "uni_error.h" -#include "../common/napi/n_async/n_async_work_callback.h" -#include "../common/napi/n_async/n_async_work_promise.h" +#include "napi/n_async/n_async_work_callback.h" +#include "napi/n_async/n_async_work_promise.h" #include "system_ability_definition.h" #include "i_distributedfile_service.h" @@ -35,19 +35,16 @@ namespace OHOS { namespace DistributedFS { namespace ModuleSendFile { -// using namespace OHOS::DistributedFile; using namespace OHOS::Storage::DistributedFile; napi_value SendFile(napi_env env, napi_callback_info info) { - HILOGI("napi_value SendFile Start"); NFuncArg funcArg(env, info); if (!funcArg.InitArgs(NARG_CNT::FOUR, NARG_CNT::FIVE)) { UniError(EINVAL).ThrowErr(env, "Number of arguments unmatched"); return nullptr; } - HILOGI("napi_value SendFile parse params"); bool succ = false; auto resultCode = std::make_shared(); @@ -114,7 +111,8 @@ napi_value SendFile(napi_env env, napi_callback_info info) return NVal::CreateUndefined(env).val_; } -int32_t ExecSendFile(const std::string deviceId, const std::vector& srcList, const std::vector& dstList, uint32_t fileCnt) +int32_t ExecSendFile(const std::string &deviceId, const std::vector& srcList, + const std::vector& dstList, uint32_t fileCnt) { sptr systemAbilityMgr = SystemAbilityManagerClient::GetInstance().GetSystemAbilityManager(); @@ -124,16 +122,19 @@ int32_t ExecSendFile(const std::string deviceId, const std::vector& } sptr remote = systemAbilityMgr->GetSystemAbility(STORAGE_DISTRIBUTED_FILE_SERVICE_SA_ID); if (remote == nullptr) { - HILOGE("DistributedFileService Get STORAGE_DISTRIBUTED_FILE_SERVICE_SA_ID = %d fail ... \n", STORAGE_DISTRIBUTED_FILE_SERVICE_SA_ID); + HILOGE("DistributedFileService Get STORAGE_DISTRIBUTED_FILE_SERVICE_SA_ID = %{public}d fail ... \n", + STORAGE_DISTRIBUTED_FILE_SERVICE_SA_ID); return -1; } + HILOGI("ExecSendFile remote %{public}p", remote.GetRefPtr()); sptr proxy = iface_cast(remote); if (proxy == nullptr) { HILOGE("DistributedFileService == nullptr\n"); return -1; } - HILOGE("test: get SA proxy, call sendfile"); + HILOGI("ExecSendFile distributedFileService %{public}p", proxy.GetRefPtr()); + int32_t result = proxy->SendFile(deviceId, srcList, dstList, fileCnt); return result; } diff --git a/interfaces/innerkits/js/mod_sendfile/sendfile.h b/interfaces/innerkits/js/mod_sendfile/sendfile.h index 7484ec686..5123ee49b 100644 --- a/interfaces/innerkits/js/mod_sendfile/sendfile.h +++ b/interfaces/innerkits/js/mod_sendfile/sendfile.h @@ -17,14 +17,15 @@ #define SENDFILE_H #include -#include "../common/napi/n_exporter.h" +#include "napi/n_exporter.h" namespace OHOS { namespace DistributedFS { namespace ModuleSendFile { napi_value SendFile(napi_env env, napi_callback_info info); -static int32_t ExecSendFile(const std::string deviceId, const std::vector& srcList, const std::vector& dstList, uint32_t num); +static int32_t ExecSendFile(const std::string &deviceId, const std::vector& srcList, + const std::vector& dstList, uint32_t fileCnt); } // namespace ModuleSendFile } // namespace DistributedFS } // namespace OHOS diff --git a/services/distributedfileservice/BUILD.gn b/services/distributedfileservice/BUILD.gn index 399eb2272..867d5ed21 100644 --- a/services/distributedfileservice/BUILD.gn +++ b/services/distributedfileservice/BUILD.gn @@ -24,6 +24,7 @@ ohos_shared_library("libdistributedfileservice") { sources = [ "src/ipc/distributedfile_service_stub.cpp", "src/ipc/distributedfile_service.cpp", + "//foundation/storage/distributed_file_manager/frameworks/native/service_proxy.cpp", "src/device/device_manager_agent.cpp", "src/network/softbus_agent.cpp", "src/network/softbus_dispatcher.cpp" diff --git a/services/distributedfileservice/src/ipc/distributedfile_service.cpp b/services/distributedfileservice/src/ipc/distributedfile_service.cpp index ab48a3ff3..7808db9c8 100644 --- a/services/distributedfileservice/src/ipc/distributedfile_service.cpp +++ b/services/distributedfileservice/src/ipc/distributedfile_service.cpp @@ -17,6 +17,7 @@ #include "device_manager_agent.h" #include "utils_exception.h" #include "utils_log.h" +#include "softbus_agent.h" #include namespace OHOS { @@ -40,6 +41,7 @@ void DistributedFileService::PublishSA() } LOGI("Init finished successfully"); } + void DistributedFileService::StartManagers() { DeviceManagerAgent::GetInstance(); @@ -66,12 +68,41 @@ int32_t DistributedFileService::sendTest() LOGI("xhl DistributedFileService::sendTest"); return 0; } + int32_t DistributedFileService::SendFile(const std::string &cid, const std::vector &sourceFileList, const std::vector &destinationFileList, const uint32_t fileCount) { + char **sFileList = new char*[fileCount]; LOGD("xhl DistributedFileService::SendFile, sessionId %{public}s, fileCount %{public}d", cid.c_str(), fileCount); + for (int index = 0; index < sourceFileList.size(); ++index) { + int32_t length = sourceFileList.at(index).length(); + sFileList[index] = new char[length + 1]; + memset_s(sFileList[index], length + 1, '\0', length + 1); + memcpy_s(sFileList[index], length + 1, sourceFileList.at(index).c_str(), length); + sFileList[index][length] = '\0'; + } + char **dFileList = new char*[fileCount]; + for (int index = 0; index < destinationFileList.size(); ++index) { + int32_t length = destinationFileList.at(index).length(); + dFileList[index] = new char[length + 1]; + memset_s(dFileList[index], length + 1, '\0', length + 1); + memcpy_s(dFileList[index], length + 1, destinationFileList.at(index).c_str(), length); + dFileList[index][length] = '\0'; + } + + auto softBusAgent = SoftbusAgent::GetInstance(); + int result = softBusAgent->SendFile(cid, (const char **)sFileList, (const char **)dFileList, fileCount); + LOGI("softBusAgent::SendFile result %{public}d", result); + + for (uint32_t index = 0; index < fileCount; ++index) { + delete[] sFileList[index]; + delete[] dFileList[index]; + } + delete[] sFileList; + delete[] dFileList; + return 0; } } // namespace DistributedFile diff --git a/services/distributedfileservice/src/ipc/distributedfile_service_stub.cpp b/services/distributedfileservice/src/ipc/distributedfile_service_stub.cpp index bc7e6bdd3..8645172ec 100644 --- a/services/distributedfileservice/src/ipc/distributedfile_service_stub.cpp +++ b/services/distributedfileservice/src/ipc/distributedfile_service_stub.cpp @@ -40,7 +40,6 @@ int DistributedFileServiceStub::OnRemoteRequest(uint32_t code, MessageOption &option) { LOGD("xhl DistributedFileServiceStub : OnRemoteRequest enter, code %{public}d ", code); - auto itFunc = memberFuncMap_.find(code); if (itFunc != memberFuncMap_.end()) { auto memberFunc = itFunc->second; @@ -51,6 +50,7 @@ int DistributedFileServiceStub::OnRemoteRequest(uint32_t code, return IPCObjectStub::OnRemoteRequest(code, data, reply, option); } + int DistributedFileServiceStub::test(MessageParcel &data, MessageParcel &reply) { LOGD("xhl DistributedFileServiceStub : sendTest enter"); @@ -60,11 +60,27 @@ int DistributedFileServiceStub::test(MessageParcel &data, MessageParcel &reply) int32_t DistributedFileServiceStub::SendFileStub(MessageParcel &data, MessageParcel &reply) { - LOGD("xhl DistributedFileServiceStub : SendFileStub enter"); - std::string cid = "123"; + std::string cid = data.ReadString(); + if (cid.empty()) { + LOGE("DistributedFileServiceStub : Failed to get app device id, error: invalid device id"); + return DISTRIBUTEDFILE_DIR_NAME_IS_EMPTY; + } + + int32_t sourceListNumber = data.ReadInt32(); std::vector srcList; + for (int32_t index = 0; index < sourceListNumber; ++index) { + srcList.push_back(data.ReadString()); + } std::vector dstList; - uint32_t fileCount = 3; + int32_t destinationListNumber = data.ReadInt32(); + for (int32_t index = 0; index < destinationListNumber; ++index) { + dstList.push_back(data.ReadString()); + } + uint32_t fileCount = data.ReadUint32(); + + LOGI("DistributedFileServiceStub : cid %{public}s, srcList size %{public}d, dstList size %{public}d," + "fileCout %{public}d", cid.c_str(), sourceListNumber, destinationListNumber, fileCount); + int32_t result = SendFile(cid, srcList, dstList, fileCount); LOGD("xhl DistributedFileServiceStub : SendFileStub result = %{public}d", result); if (!reply.WriteInt32(result)) { -- Gitee From dc0627e225e7d65fe1b35b0f99f32f30d97e4f08 Mon Sep 17 00:00:00 2001 From: xianghengliang Date: Fri, 11 Feb 2022 17:07:50 +0800 Subject: [PATCH 12/14] delete uncorrelated code with distributedfileservice Signed-off-by: xianghengliang --- distributedfile.gni | 2 +- executable/BUILD.gn | 45 --- executable/main.cpp | 56 ---- frameworks/native/service_proxy.cpp | 37 +-- frameworks/native/service_proxy.h | 2 +- interfaces/innerkits/js/@ohos.sendfile.d.ts | 34 -- interfaces/innerkits/js/BUILD.gn | 78 ----- .../innerkits/js/common/ability_helper.cpp | 54 ---- .../innerkits/js/common/ability_helper.h | 27 -- interfaces/innerkits/js/common/fd_guard.cpp | 46 --- interfaces/innerkits/js/common/fd_guard.h | 34 -- interfaces/innerkits/js/common/log.h | 90 ------ .../js/common/napi/n_async/n_async_context.h | 69 ----- .../napi/n_async/n_async_work_callback.cpp | 94 ------ .../napi/n_async/n_async_work_callback.h | 35 --- .../napi/n_async/n_async_work_factory.h | 33 -- .../napi/n_async/n_async_work_promise.cpp | 88 ------ .../napi/n_async/n_async_work_promise.h | 35 --- .../js/common/napi/n_async/n_ref.cpp | 53 ---- .../innerkits/js/common/napi/n_async/n_ref.h | 38 --- .../innerkits/js/common/napi/n_class.cpp | 99 ------ interfaces/innerkits/js/common/napi/n_class.h | 82 ----- .../innerkits/js/common/napi/n_exporter.h | 39 --- .../innerkits/js/common/napi/n_func_arg.cpp | 111 ------- .../innerkits/js/common/napi/n_func_arg.h | 74 ----- interfaces/innerkits/js/common/napi/n_val.cpp | 291 ------------------ interfaces/innerkits/js/common/napi/n_val.h | 80 ----- .../innerkits/js/common/napi/uni_header.h | 23 -- interfaces/innerkits/js/common/uni_error.cpp | 118 ------- interfaces/innerkits/js/common/uni_error.h | 64 ---- .../innerkits/js/mod_sendfile/sendfile.cpp | 143 --------- .../innerkits/js/mod_sendfile/sendfile.h | 32 -- .../js/mod_sendfile/sendfile_napi.cpp | 40 --- .../innerkits/js/mod_sendfile/sendfile_napi.h | 25 -- ohos.build | 31 -- services/distributedfileservice/BUILD.gn | 5 +- .../include/ipc/distributedfile_service.h | 4 +- .../include/network/softbus_agent.h | 6 +- .../include/network/softbus_dispatcher.h | 1 - .../src/ipc/distributedfile_service.cpp | 33 +- .../src/ipc/distributedfile_service_stub.cpp | 34 +- .../src/network/softbus_agent.cpp | 22 +- .../src/network/softbus_dispatcher.cpp | 1 - utils/system/include/utils_singleton.h | 1 - 44 files changed, 25 insertions(+), 2284 deletions(-) delete mode 100644 executable/BUILD.gn delete mode 100644 executable/main.cpp delete mode 100644 interfaces/innerkits/js/@ohos.sendfile.d.ts delete mode 100644 interfaces/innerkits/js/BUILD.gn delete mode 100644 interfaces/innerkits/js/common/ability_helper.cpp delete mode 100644 interfaces/innerkits/js/common/ability_helper.h delete mode 100644 interfaces/innerkits/js/common/fd_guard.cpp delete mode 100644 interfaces/innerkits/js/common/fd_guard.h delete mode 100644 interfaces/innerkits/js/common/log.h delete mode 100644 interfaces/innerkits/js/common/napi/n_async/n_async_context.h delete mode 100644 interfaces/innerkits/js/common/napi/n_async/n_async_work_callback.cpp delete mode 100644 interfaces/innerkits/js/common/napi/n_async/n_async_work_callback.h delete mode 100644 interfaces/innerkits/js/common/napi/n_async/n_async_work_factory.h delete mode 100644 interfaces/innerkits/js/common/napi/n_async/n_async_work_promise.cpp delete mode 100644 interfaces/innerkits/js/common/napi/n_async/n_async_work_promise.h delete mode 100644 interfaces/innerkits/js/common/napi/n_async/n_ref.cpp delete mode 100644 interfaces/innerkits/js/common/napi/n_async/n_ref.h delete mode 100644 interfaces/innerkits/js/common/napi/n_class.cpp delete mode 100644 interfaces/innerkits/js/common/napi/n_class.h delete mode 100644 interfaces/innerkits/js/common/napi/n_exporter.h delete mode 100644 interfaces/innerkits/js/common/napi/n_func_arg.cpp delete mode 100644 interfaces/innerkits/js/common/napi/n_func_arg.h delete mode 100644 interfaces/innerkits/js/common/napi/n_val.cpp delete mode 100644 interfaces/innerkits/js/common/napi/n_val.h delete mode 100644 interfaces/innerkits/js/common/napi/uni_header.h delete mode 100644 interfaces/innerkits/js/common/uni_error.cpp delete mode 100644 interfaces/innerkits/js/common/uni_error.h delete mode 100644 interfaces/innerkits/js/mod_sendfile/sendfile.cpp delete mode 100644 interfaces/innerkits/js/mod_sendfile/sendfile.h delete mode 100644 interfaces/innerkits/js/mod_sendfile/sendfile_napi.cpp delete mode 100644 interfaces/innerkits/js/mod_sendfile/sendfile_napi.h delete mode 100644 ohos.build diff --git a/distributedfile.gni b/distributedfile.gni index ecea88b2e..8e358c0e5 100755 --- a/distributedfile.gni +++ b/distributedfile.gni @@ -15,4 +15,4 @@ distributedfile_path = "//foundation/filemanagement/dfs_service" utils_path = "${distributedfile_path}/utils" services_path = "${distributedfile_path}/services" -innerkits_native_path = "${distributedfile_path}/interfaces/innerkits/native" \ No newline at end of file +innerkits_native_path = "${distributedfile_path}/interfaces/innerkits/native" diff --git a/executable/BUILD.gn b/executable/BUILD.gn deleted file mode 100644 index c80d48bf6..000000000 --- a/executable/BUILD.gn +++ /dev/null @@ -1,45 +0,0 @@ -# Copyright (c) 2021 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") - -ohos_executable("xhl_test-sa") { - include_dirs = [ - "../frameworks/native", - "../utils/log/include" - ] - - sources = [ "main.cpp" ] - - defines = [ - "LOG_DOMAIN=0xD001600", - "LOG_TAG=\"xhl_test_exec\"", - ] - - external_deps = [ - "aafwk_standard:want", - "appexecfwk_standard:appexecfwk_base", - "appexecfwk_standard:appexecfwk_core", - "ipc:ipc_core", - "safwk:system_ability_fwk", - "samgr_standard:samgr_proxy", - ] - - deps = [ - "../utils:libdistributedfileutils", - "../interfaces/innerkits/native:libdistributedfile_innerkits", - ] - - install_enable = true - part_name = "storage_distributed_file_manager" - subsystem_name = "storage" -} diff --git a/executable/main.cpp b/executable/main.cpp deleted file mode 100644 index 6c6582784..000000000 --- a/executable/main.cpp +++ /dev/null @@ -1,56 +0,0 @@ -/* - * Copyright (c) 2021 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 -#include -#include -#include "bundle_mgr_interface.h" -#include "bundle_mgr_proxy.h" -#include "service_proxy.h" -#include "iservice_registry.h" -#include "system_ability_definition.h" -#include "utils_log.h" - -using namespace OHOS; -using namespace OHOS::Storage::DistributedFile; - -static void TestTutorial() -{ - auto samgr = SystemAbilityManagerClient::GetInstance().GetSystemAbilityManager(); - LOGE("xhl Get samgr %{public}p", samgr.GetRefPtr()); - - auto remote = samgr->GetSystemAbility(STORAGE_DISTRIBUTED_FILE_SERVICE_SA_ID); - LOGE("xhl Get remote %{public}p", remote.GetRefPtr()); - - auto proxy = iface_cast(remote); - LOGE("xhl Get proxy %{public}p", proxy.GetRefPtr()); - - std::string cid{"123"}; - std::vector srcList; - std::vector dstList; - uint32_t fileCount = 2; - LOGE("xhl prepare to sendfile"); - int ret = proxy->SendFile(cid, srcList, dstList, fileCount); - LOGE("xhl sendfile finish ret %{public}d", ret); - ret = proxy->sendTest(); - LOGE("xhl sendTest finish ret %{public}d", ret); -} - -int main(int argc, char const *argv[]) -{ - TestTutorial(); - LOGE("xhl main finish"); - return 0; -} \ No newline at end of file diff --git a/frameworks/native/service_proxy.cpp b/frameworks/native/service_proxy.cpp index afbaef669..8d9ae8239 100644 --- a/frameworks/native/service_proxy.cpp +++ b/frameworks/native/service_proxy.cpp @@ -25,48 +25,17 @@ int32_t ServiceProxy::SendFile(const std::string &cid, const std::vector &destinationFileList, const uint32_t fileCount) { - LOGI("xhl sendFile enter"); - int32_t result = SEND_FILE_FAIL; - MessageOption option; - MessageParcel dataParcel; - MessageParcel replyParcel; - - dataParcel.WriteString(cid); - int32_t sourceListNumber = sourceFileList.size(); - dataParcel.WriteInt32(sourceListNumber); - for (int32_t index = 0; index < sourceListNumber; ++index) { - dataParcel.WriteString(sourceFileList.at(index)); - } - int32_t destinationListNumber = destinationFileList.size(); - dataParcel.WriteInt32(destinationListNumber); - for (int32_t index = 0; index < destinationListNumber; ++index) { - dataParcel.WriteString(destinationFileList.at(index)); - } - dataParcel.WriteUint32(fileCount); - - if (Remote() == nullptr) { - LOGE("Remote object address is null"); - return DISTRIBUTEDFILE_REMOTE_ADDRESS_IS_NULL; - } - - result = Remote()->SendRequest(SEND_FILE_DISTRIBUTED, dataParcel, replyParcel, option); - if (result != DISTRIBUTEDFILE_NO_ERROR) { - LOGE("Function RemoveBundleDistributedDirs! errCode:%{public}d", result); - return DISTRIBUTEDFILE_CONNECT_SYSTEM_ABILITY_STUB_FAIL; - } - LOGE("xhl sendfile sendRequest done %{public}d", result); - - return replyParcel.ReadInt32(); + return 0; } int32_t ServiceProxy::sendTest() { - LOGE("xhl sendTest enter"); + LOGE("sendTest enter"); MessageParcel data; MessageParcel reply; MessageOption option; int ret = Remote()->SendRequest(TEST_CODE, data, reply, option); - LOGE("xhl sendTest sendrequest done %{public}d", ret); + LOGE("sendTest sendrequest done %{public}d", ret); return ret; } } // namespace DistributedFile diff --git a/frameworks/native/service_proxy.h b/frameworks/native/service_proxy.h index 1cfcc8ac1..d5a2d52c4 100644 --- a/frameworks/native/service_proxy.h +++ b/frameworks/native/service_proxy.h @@ -16,9 +16,9 @@ #ifndef DISTRIBUTEDFILE_SERVICE_PROXY_H #define DISTRIBUTEDFILE_SERVICE_PROXY_H +#include #include "i_distributedfile_service.h" #include "message_parcel.h" -#include namespace OHOS { namespace Storage { diff --git a/interfaces/innerkits/js/@ohos.sendfile.d.ts b/interfaces/innerkits/js/@ohos.sendfile.d.ts deleted file mode 100644 index 35deda138..000000000 --- a/interfaces/innerkits/js/@ohos.sendfile.d.ts +++ /dev/null @@ -1,34 +0,0 @@ -/* -* Copyright (C) 2021 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 {AsyncCallback, Callback} from "./basic"; - -declare namespace SendFile { - function SendFile(deviceId: number, sourPath: Array, destPath: Array, fileCount: number, callback: AsyncCallback); - function SendFile(deviceId: number, sourPath: Array, destPath: Array, fileCount: number): Promise; - - /** - * Send and recv file event loop type - */ - export interface CloseOptions { - sendFile: number; - recvFile: number; - }; - - on(type: 'finished', CloseOptions: options, callback: AsyncCallback): void; - off(type: 'finished', callback?: AsyncCallback): void; -} - -export default SendFile; \ No newline at end of file diff --git a/interfaces/innerkits/js/BUILD.gn b/interfaces/innerkits/js/BUILD.gn deleted file mode 100644 index b246a537d..000000000 --- a/interfaces/innerkits/js/BUILD.gn +++ /dev/null @@ -1,78 +0,0 @@ -# Copyright (c) 2021 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") - -file_common_src = [ - "//foundation/storage/distributed_file_manager/interfaces/innerkits/js/common/fd_guard.cpp", - "//foundation/storage/distributed_file_manager/interfaces/innerkits/js/common/uni_error.cpp", - - "//foundation/storage/distributed_file_manager/interfaces/innerkits/js/common/napi/n_class.cpp", - "//foundation/storage/distributed_file_manager/interfaces/innerkits/js/common/napi/n_func_arg.cpp", - "//foundation/storage/distributed_file_manager/interfaces/innerkits/js/common/napi/n_val.cpp", - - "//foundation/storage/distributed_file_manager/interfaces/innerkits/js/common/napi/n_async/n_async_work_callback.cpp", - "//foundation/storage/distributed_file_manager/interfaces/innerkits/js/common/napi/n_async/n_async_work_promise.cpp", - "//foundation/storage/distributed_file_manager/interfaces/innerkits/js/common/napi/n_async/n_ref.cpp", -] - -ohos_shared_library("sendfile") { - relative_install_dir = "module" - subsystem_name = "storage" - part_name = "storage_distributed_file_manager" - - cflags_cc = [ - "-Wno-unused-function" - ] - - include_dirs = [ - "//foundation/storage/distributed_file_manager/interfaces/innerkits/js/common/napi/n_async", - "//foundation/storage/distributed_file_manager/services/distributedfileservice/include/ipc", - "//foundation/storage/distributed_file_manager/services/distributedfileservice/include", - "//foundation/storage/distributed_file_manager/interfaces/innerkits/native", - "//foundation/storage/distributed_file_manager/frameworks/native", - "//foundation/communication/ipc/interfaces/innerkits/libdbinder/include", - "//foundation/distributedschedule/samgr/services/samgr/native/include", - "//foundation/distributedschedule/samgr/interfaces/innerkits/samgr_proxy/include", - "//foundation/storage/distributed_file_manager/interfaces/innerkits/js/common", - "//base/hiviewdfx/hilog/interfaces/native/innerkits/include", - "//foundation/ace/napi/interfaces/kits", - "//utils/system/safwk/native/include", - "//utils/native/base/include", - ] - - sources = file_common_src - sources += [ - "//foundation/storage/distributed_file_manager/interfaces/innerkits/js/mod_sendfile/sendfile.cpp", - "//foundation/storage/distributed_file_manager/interfaces/innerkits/js/mod_sendfile/sendfile_napi.cpp", - ] - - deps = [ - "//foundation/ace/napi:ace_napi", - "//utils/native/base:utils", - "//foundation/storage/distributed_file_manager/interfaces/innerkits/native:libdistributedfile_innerkits", - "//foundation/aafwk/standard/frameworks/kits/ability/native:abilitykit_native", - ] - - external_deps = [ - "ipc:ipc_core", - "samgr_standard:samgr_proxy", - "hiviewdfx_hilog_native:libhilog", - ] -} - -group("build_kits_js") { - deps = [ - ":sendfile", - ] -} diff --git a/interfaces/innerkits/js/common/ability_helper.cpp b/interfaces/innerkits/js/common/ability_helper.cpp deleted file mode 100644 index c5aae1548..000000000 --- a/interfaces/innerkits/js/common/ability_helper.cpp +++ /dev/null @@ -1,54 +0,0 @@ -/* - * Copyright (c) 2021 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 "ability_helper.h" - -#include "log.h" -#include "napi/n_func_arg.h" -#include "napi/uni_header.h" - -namespace OHOS { -namespace DistributedFS { -using namespace std; -using OHOS::AppExecFwk::Ability; -using OHOS::AppExecFwk::AbilityContext; - -Ability* AbilityHelper::GetJsAbility(napi_env env) -{ - napi_value global = nullptr; - napi_value abilityContext = nullptr; - - napi_status status = napi_get_global(env, &global); - if (status != napi_ok || global == nullptr) { - HILOGE("Cannot get global instance for %{public}d", status); - return nullptr; - } - - status = napi_get_named_property(env, global, "ability", &abilityContext); - if (status != napi_ok || abilityContext == nullptr) { - HILOGE("Cannot get ability context for %{public}d", status); - return nullptr; - } - - Ability *ability = nullptr; - status = napi_get_value_external(env, abilityContext, (void **)&ability); - if (status != napi_ok || ability == nullptr) { - HILOGE("Get ability form property failed for %{public}d", status); - } - - return ability; -} -} // namespace DistributedFS -} // namespace OHOS \ No newline at end of file diff --git a/interfaces/innerkits/js/common/ability_helper.h b/interfaces/innerkits/js/common/ability_helper.h deleted file mode 100644 index e998027c0..000000000 --- a/interfaces/innerkits/js/common/ability_helper.h +++ /dev/null @@ -1,27 +0,0 @@ -/* - * Copyright (c) 2021 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. - */ - -#pragma once - -#include "../common/napi/uni_header.h" -#include "ability.h" - -namespace OHOS { -namespace DistributedFS { -struct AbilityHelper { - static AppExecFwk::Ability *GetJsAbility(napi_env env); -}; -} // namespace DistributedFS -} // namespace OHOS \ No newline at end of file diff --git a/interfaces/innerkits/js/common/fd_guard.cpp b/interfaces/innerkits/js/common/fd_guard.cpp deleted file mode 100644 index fa4594573..000000000 --- a/interfaces/innerkits/js/common/fd_guard.cpp +++ /dev/null @@ -1,46 +0,0 @@ -/* - * Copyright (c) 2021 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 "fd_guard.h" - -#include - -namespace OHOS { -namespace DistributedFS { -FDGuard::FDGuard(int fd) : fd_(fd) {} - -FDGuard::~FDGuard() -{ - if (fd_ > 0) { - close(fd_); - } -} - -int FDGuard::GetFD() const -{ - return fd_; -} - -void FDGuard::SetFD(int fd) -{ - fd_ = fd; -} - -void FDGuard::ClearFD() -{ - fd_ = -1; -} -} // namespace DistributedFS -} // namespace OHOS \ No newline at end of file diff --git a/interfaces/innerkits/js/common/fd_guard.h b/interfaces/innerkits/js/common/fd_guard.h deleted file mode 100644 index 2db743831..000000000 --- a/interfaces/innerkits/js/common/fd_guard.h +++ /dev/null @@ -1,34 +0,0 @@ -/* - * Copyright (c) 2021 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. - */ - -#pragma once - -namespace OHOS { -namespace DistributedFS { -class FDGuard { -public: - FDGuard() = default; - explicit FDGuard(int fd); - ~FDGuard(); - - int GetFD() const; - void SetFD(int fd); - void ClearFD(); - -private: - int fd_ = -1; -}; -} // namespace DistributedFS -} // namespace OHOS diff --git a/interfaces/innerkits/js/common/log.h b/interfaces/innerkits/js/common/log.h deleted file mode 100644 index 32a09a751..000000000 --- a/interfaces/innerkits/js/common/log.h +++ /dev/null @@ -1,90 +0,0 @@ -/* - * Copyright (c) 2021 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. - */ - -#pragma once - -#include -#include -#include - -#ifndef FILE_SUBSYSTEM_DEV_ON_PC -#include "hilog/log.h" -#endif - -namespace OHOS { -namespace DistributedFS { -#ifndef FILE_SUBSYSTEM_DEV_ON_PC -static constexpr int FILEIO_DOMAIN_ID = 0; -static constexpr OHOS::HiviewDFX::HiLogLabel FILEIO_LABEL = { LOG_CORE, FILEIO_DOMAIN_ID, "distributedfilejs" }; - -#ifdef HILOGD -#undef HILOGD -#endif - -#ifdef HILOGF -#undef HILOGF -#endif - -#ifdef HILOGE -#undef HILOGE -#endif - -#ifdef HILOGW -#undef HILOGW -#endif - -#ifdef HILOGI -#undef HILOGI -#endif - -#define HILOGD(fmt, ...) \ - (void)OHOS::HiviewDFX::HiLog::Debug(OHOS::DistributedFS::FILEIO_LABEL, "%{public}s: " fmt, __func__, ##__VA_ARGS__) -#define HILOGI(fmt, ...) \ - (void)OHOS::HiviewDFX::HiLog::Info(OHOS::DistributedFS::FILEIO_LABEL, "%{public}s: " fmt, __func__, ##__VA_ARGS__) -#define HILOGW(fmt, ...) \ - (void)OHOS::HiviewDFX::HiLog::Warn(OHOS::DistributedFS::FILEIO_LABEL, "%{public}s: " fmt, __func__, ##__VA_ARGS__) -#define HILOGE(fmt, ...) \ - (void)OHOS::HiviewDFX::HiLog::Error(OHOS::DistributedFS::FILEIO_LABEL, "%{public}s: " fmt, __func__, ##__VA_ARGS__) -#define HILOGF(fmt, ...) \ - (void)OHOS::HiviewDFX::HiLog::Fatal(OHOS::DistributedFS::FILEIO_LABEL, "%{public}s: " fmt, __func__, ##__VA_ARGS__) - -#else - -#define PCLOG(fmt, ...) \ - do { \ - const std::vector filter = { \ - "{public}", \ - "{private}", \ - }; \ - std::string str____(fmt); \ - for (auto &&pattern : filter) { \ - size_t pos = 0; \ - while (std::string::npos != (pos = str____.find(pattern))) { \ - str____.erase(pos, pattern.length()); \ - } \ - } \ - str____ += "\n"; \ - printf(str____.c_str(), ##__VA_ARGS__); \ - } while (0); - -#define HILOGD(fmt, ...) PCLOG("%{public}s: " fmt, __func__, ##__VA_ARGS__) -#define HILOGI(fmt, ...) PCLOG("%{public}s: " fmt, __func__, ##__VA_ARGS__) -#define HILOGW(fmt, ...) PCLOG("%{public}s: " fmt, __func__, ##__VA_ARGS__) -#define HILOGE(fmt, ...) PCLOG("%{public}s: " fmt, __func__, ##__VA_ARGS__) -#define HILOGF(fmt, ...) PCLOG("%{public}s: " fmt, __func__, ##__VA_ARGS__) - -#endif -} // namespace DistributedFS -} // namespace OHOS \ No newline at end of file diff --git a/interfaces/innerkits/js/common/napi/n_async/n_async_context.h b/interfaces/innerkits/js/common/napi/n_async/n_async_context.h deleted file mode 100644 index e62c43669..000000000 --- a/interfaces/innerkits/js/common/napi/n_async/n_async_context.h +++ /dev/null @@ -1,69 +0,0 @@ -/* - * Copyright (c) 2021 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 N_ASYNC_CONTEXT_H -#define N_ASYNC_CONTEXT_H - -#include - -#include "../../uni_error.h" -#include "../n_val.h" -#include "n_ref.h" - -namespace OHOS { -namespace DistributedFS { -using NContextCBExec = std::function; -using NContextCBComplete = std::function; - -class NAsyncContext { -public: - UniError err_; - NVal res_; - NContextCBExec cbExec_; - NContextCBComplete cbComplete_; - napi_async_work awork_; - NRef thisPtr_; - - explicit NAsyncContext(NVal thisPtr) : thisPtr_(thisPtr) {} - ~NAsyncContext() = default; -}; - -class NAsyncContextPromise : public NAsyncContext { -public: - napi_deferred deferred_; - explicit NAsyncContextPromise(NVal thisPtr) : NAsyncContext(thisPtr) {} - ~NAsyncContextPromise() = default; -}; - -class NAsyncContextCallback : public NAsyncContext { -public: - NRef cb_; - NAsyncContextCallback(NVal thisPtr, NVal cb) : NAsyncContext(thisPtr), cb_(cb) {} - ~NAsyncContextCallback() = default; -}; - -class NAsyncContextLegacy : public NAsyncContext { -public: - NRef cbSucc_; - NRef cbFail_; - NRef cbFinal_; - NAsyncContextLegacy(NVal thisPtr, NVal cbSucc, NVal cbFail, NVal cbFinal) - : NAsyncContext(thisPtr), cbSucc_(cbSucc), cbFail_(cbFail), cbFinal_(cbFinal) - {} - ~NAsyncContextLegacy() = default; -}; -} // namespace DistributedFS -} // namespace OHOS -#endif // N_ASYNC_CONTEXT_H \ No newline at end of file diff --git a/interfaces/innerkits/js/common/napi/n_async/n_async_work_callback.cpp b/interfaces/innerkits/js/common/napi/n_async/n_async_work_callback.cpp deleted file mode 100644 index f3d4874a2..000000000 --- a/interfaces/innerkits/js/common/napi/n_async/n_async_work_callback.cpp +++ /dev/null @@ -1,94 +0,0 @@ -/* - * Copyright (c) 2021 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 "n_async_work_callback.h" -#include "../../log.h" - -namespace OHOS { -namespace DistributedFS { -using namespace std; - -NAsyncWorkCallback::NAsyncWorkCallback(napi_env env, NVal thisPtr, NVal cb) : NAsyncWorkFactory(env) -{ - ctx_ = new NAsyncContextCallback(thisPtr, cb); -} - -static void CallbackExecute(napi_env env, void *data) -{ - auto ctx = static_cast(data); - if (ctx->cbExec_) { - ctx->err_ = ctx->cbExec_(env); - } -} -static void CallbackComplete(napi_env env, napi_status status, void *data) -{ - napi_handle_scope scope = nullptr; - napi_open_handle_scope(env, &scope); - auto ctx = static_cast(data); - if (ctx->cbComplete_) { - ctx->res_ = ctx->cbComplete_(env, ctx->err_); - ctx->cbComplete_ = nullptr; - } - - vector argv; - if (!ctx->res_.TypeIsError(true)) { - argv = { UniError(ERRNO_NOERR).GetNapiErr(env), ctx->res_.val_ }; - } else { - argv = { ctx->res_.val_ }; - } - - napi_value global = nullptr; - napi_value callback = ctx->cb_.Deref(env).val_; - napi_value tmp = nullptr; - napi_get_global(env, &global); - napi_status stat = napi_call_function(env, global, callback, argv.size(), argv.data(), &tmp); - if (stat != napi_ok) { - HILOGE("Failed to call function for %{public}d", stat); - } - napi_close_handle_scope(env, scope); - napi_delete_async_work(env, ctx->awork_); - delete ctx; -} - -NVal NAsyncWorkCallback::Schedule(string procedureName, NContextCBExec cbExec, NContextCBComplete cbComplete) -{ - if (!ctx_->cb_ || !ctx_->cb_.Deref(env_).TypeIs(napi_function)) { - UniError(EINVAL).ThrowErr(env_, "The callback shall be a funciton"); - return NVal(); - } - - ctx_->cbExec_ = move(cbExec); - ctx_->cbComplete_ = move(cbComplete); - - napi_value resource = NVal::CreateUTF8String(env_, procedureName).val_; - - napi_status status = - napi_create_async_work(env_, nullptr, resource, CallbackExecute, CallbackComplete, ctx_, &ctx_->awork_); - if (status != napi_ok) { - HILOGE("INNER BUG. Failed to create async work for %{public}d", status); - return NVal(); - } - - status = napi_queue_async_work(env_, ctx_->awork_); - if (status != napi_ok) { - HILOGE("INNER BUG. Failed to queue async work for %{public}d", status); - return NVal(); - } - - ctx_ = nullptr; // The ownership of ctx_ has been transfered - return NVal::CreateUndefined(env_); -} -} // namespace DistributedFS -} // namespace OHOS diff --git a/interfaces/innerkits/js/common/napi/n_async/n_async_work_callback.h b/interfaces/innerkits/js/common/napi/n_async/n_async_work_callback.h deleted file mode 100644 index 9bc6d5f3d..000000000 --- a/interfaces/innerkits/js/common/napi/n_async/n_async_work_callback.h +++ /dev/null @@ -1,35 +0,0 @@ -/* - * Copyright (c) 2021 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 N_ASYNC_WORK_CALLBACK_H -#define N_ASYNC_WORK_CALLBACK_H - -#include "n_async_work_factory.h" - -namespace OHOS { -namespace DistributedFS { -class NAsyncWorkCallback : public NAsyncWorkFactory { -public: - NAsyncWorkCallback(napi_env env, NVal thisPtr, NVal cb); - ~NAsyncWorkCallback() = default; - - NVal Schedule(std::string procedureName, NContextCBExec cbExec, NContextCBComplete cbComplete) final; - -private: - NAsyncContextCallback *ctx_ = nullptr; -}; -} // namespace DistributedFS -} // namespace OHOS -#endif // N_ASYNC_WORK_CALLBACK_H \ No newline at end of file diff --git a/interfaces/innerkits/js/common/napi/n_async/n_async_work_factory.h b/interfaces/innerkits/js/common/napi/n_async/n_async_work_factory.h deleted file mode 100644 index deb664548..000000000 --- a/interfaces/innerkits/js/common/napi/n_async/n_async_work_factory.h +++ /dev/null @@ -1,33 +0,0 @@ -/* - * Copyright (c) 2021 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 N_ASYNC_WORK_FACTORY_H -#define N_ASYNC_WORK_FACTORY_H - -#include "n_async_context.h" - -namespace OHOS { -namespace DistributedFS { -class NAsyncWorkFactory { -public: - explicit NAsyncWorkFactory(napi_env env) : env_(env) {} - ~NAsyncWorkFactory() = default; - virtual NVal Schedule(std::string procedureName, NContextCBExec cbExec, NContextCBComplete cbComplete) = 0; - - napi_env env_ = nullptr; -}; -} // namespace DistributedFS -} // namespace OHOS -#endif // N_ASYNC_WORK_FACTORY_H \ No newline at end of file diff --git a/interfaces/innerkits/js/common/napi/n_async/n_async_work_promise.cpp b/interfaces/innerkits/js/common/napi/n_async/n_async_work_promise.cpp deleted file mode 100644 index 443cb2f01..000000000 --- a/interfaces/innerkits/js/common/napi/n_async/n_async_work_promise.cpp +++ /dev/null @@ -1,88 +0,0 @@ -/* - * Copyright (c) 2021 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 "n_async_work_promise.h" -#include "../../log.h" - -namespace OHOS { -namespace DistributedFS { -using namespace std; - -NAsyncWorkPromise::NAsyncWorkPromise(napi_env env, NVal thisPtr) : NAsyncWorkFactory(env) -{ - ctx_ = new NAsyncContextPromise(thisPtr); -} - -static void PromiseOnExec(napi_env env, void *data) -{ - auto ctx = static_cast(data); - if (ctx->cbExec_) { - ctx->err_ = ctx->cbExec_(env); - } -} -static void PromiseOnComplete(napi_env env, napi_status status, void *data) -{ - auto ctx = static_cast(data); - if (ctx->cbComplete_) { - ctx->res_ = ctx->cbComplete_(env, ctx->err_); - } - if (!ctx->res_.TypeIsError(true)) { - napi_status status = napi_resolve_deferred(env, ctx->deferred_, ctx->res_.val_); - if (status != napi_ok) { - HILOGE("Internal BUG, cannot resolve promise for %{public}d", status); - } - } else { - napi_status status = napi_reject_deferred(env, ctx->deferred_, ctx->res_.val_); - if (status != napi_ok) { - HILOGE("Internal BUG, cannot reject promise for %{public}d", status); - } - } - ctx->deferred_ = nullptr; - napi_delete_async_work(env, ctx->awork_); - delete ctx; -} - - -NVal NAsyncWorkPromise::Schedule(string procedureName, NContextCBExec cbExec, NContextCBComplete cbComplete) -{ - ctx_->cbExec_ = move(cbExec); - ctx_->cbComplete_ = move(cbComplete); - - napi_status status; - napi_value result = nullptr; - status = napi_create_promise(env_, &ctx_->deferred_, &result); - if (status != napi_ok) { - HILOGE("INNER BUG. Cannot create promise for %{public}d", status); - return NVal(); - } - - napi_value resource = NVal::CreateUTF8String(env_, procedureName).val_; - status = napi_create_async_work(env_, nullptr, resource, PromiseOnExec, PromiseOnComplete, ctx_, &ctx_->awork_); - if (status != napi_ok) { - HILOGE("INNER BUG. Failed to create async work for %{public}d", status); - return NVal(); - } - - status = napi_queue_async_work(env_, ctx_->awork_); - if (status != napi_ok) { - HILOGE("INNER BUG. Failed to queue async work for %{public}d", status); - return NVal(); - } - - ctx_ = nullptr; // The ownership of ctx_ has been transfered - return { env_, result }; -} -} // namespace DistributedFS -} // namespace OHOS diff --git a/interfaces/innerkits/js/common/napi/n_async/n_async_work_promise.h b/interfaces/innerkits/js/common/napi/n_async/n_async_work_promise.h deleted file mode 100644 index 8a049de65..000000000 --- a/interfaces/innerkits/js/common/napi/n_async/n_async_work_promise.h +++ /dev/null @@ -1,35 +0,0 @@ -/* - * Copyright (c) 2021 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 N_ASYNC_WORK_PROMISE_H -#define N_ASYNC_WORK_PROMISE_H - -#include "n_async_work_factory.h" - -namespace OHOS { -namespace DistributedFS { -class NAsyncWorkPromise : public NAsyncWorkFactory { -public: - NAsyncWorkPromise(napi_env env, NVal thisPtr); - ~NAsyncWorkPromise() = default; - - NVal Schedule(std::string procedureName, NContextCBExec cbExec, NContextCBComplete cbComplete) final; - -private: - NAsyncContextPromise *ctx_; -}; -} // namespace DistributedFS -} // namespace OHOS -#endif // N_ASYNC_WORK_PROMISE_H \ No newline at end of file diff --git a/interfaces/innerkits/js/common/napi/n_async/n_ref.cpp b/interfaces/innerkits/js/common/napi/n_async/n_ref.cpp deleted file mode 100644 index 8b78ac9c8..000000000 --- a/interfaces/innerkits/js/common/napi/n_async/n_ref.cpp +++ /dev/null @@ -1,53 +0,0 @@ -/* - * Copyright (c) 2021 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 "n_ref.h" - -namespace OHOS { -namespace DistributedFS { -NRef::NRef() {} - -NRef::NRef(NVal val) -{ - if (val) { - env_ = val.env_; - napi_create_reference(val.env_, val.val_, 1, &ref_); - } -} - -NRef::~NRef() -{ - if (ref_) { - napi_delete_reference(env_, ref_); - } -} - -NRef::operator bool() const -{ - return ref_ != nullptr; -} - -NVal NRef::Deref(napi_env env) -{ - if (!ref_) { - return NVal(); - } - - napi_value val = nullptr; - napi_get_reference_value(env, ref_, &val); - return { env, val }; -} -} // namespace DistributedFS -} // namespace OHOS diff --git a/interfaces/innerkits/js/common/napi/n_async/n_ref.h b/interfaces/innerkits/js/common/napi/n_async/n_ref.h deleted file mode 100644 index a9f166cfc..000000000 --- a/interfaces/innerkits/js/common/napi/n_async/n_ref.h +++ /dev/null @@ -1,38 +0,0 @@ -/* - * Copyright (c) 2021 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 N_REF_H -#define N_REF_H - -#include "../n_val.h" - -namespace OHOS { -namespace DistributedFS { -class NRef { -public: - NRef(); - explicit NRef(NVal val); - ~NRef(); - - explicit operator bool() const; - NVal Deref(napi_env env); - -private: - napi_env env_ = nullptr; - napi_ref ref_ = nullptr; -}; -} // namespace DistributedFS -} // namespace OHOS -#endif // N_REF_H \ No newline at end of file diff --git a/interfaces/innerkits/js/common/napi/n_class.cpp b/interfaces/innerkits/js/common/napi/n_class.cpp deleted file mode 100644 index 0e9028b02..000000000 --- a/interfaces/innerkits/js/common/napi/n_class.cpp +++ /dev/null @@ -1,99 +0,0 @@ -/* - * Copyright (c) 2021 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 "n_class.h" - -#include -#include - -#include "../log.h" - -namespace OHOS { -namespace DistributedFS { -using namespace std; -NClass &NClass::GetInstance() -{ - static NClass nClass; - return nClass; -} - -tuple NClass::DefineClass(napi_env env, - string className, - napi_callback constructor, - vector &&properties) -{ - napi_value classVal = nullptr; - napi_status stat = napi_define_class(env, - className.c_str(), - className.length(), - constructor, - nullptr, - properties.size(), - properties.data(), - &classVal); - if (stat != napi_ok) { - HILOGE("INNER BUG. Cannot define class %{public}s because of %{public}d", className.c_str(), stat); - } - return { stat == napi_ok, classVal }; -} - -bool NClass::SaveClass(napi_env env, string className, napi_value exClass) -{ - NClass &nClass = NClass::GetInstance(); - lock_guard(nClass.exClassMapLock); - - if (nClass.exClassMap.find(className) != nClass.exClassMap.end()) { - return true; - } - - napi_ref constructor; - napi_status res = napi_create_reference(env, exClass, 1, &constructor); - if (res == napi_ok) { - nClass.exClassMap.insert({ className, constructor }); - HILOGI("Class %{public}s has been saved", className.c_str()); - } else { - HILOGE("INNER BUG. Cannot ref class constructor %{public}s because of %{public}d", className.c_str(), res); - } - return res == napi_ok; -} - -napi_value NClass::InstantiateClass(napi_env env, string className, vector args) -{ - NClass &nClass = NClass::GetInstance(); - lock_guard(nClass.exClassMapLock); - - auto it = nClass.exClassMap.find(className); - if (it == nClass.exClassMap.end()) { - HILOGE("Class %{public}s hasn't been saved yet", className.c_str()); - return nullptr; - } - - napi_value cons = nullptr; - napi_status status = napi_get_reference_value(env, it->second, &cons); - if (status != napi_ok) { - HILOGE("INNER BUG. Cannot deref class %{public}s because of %{public}d", className.c_str(), status); - return nullptr; - } - - napi_value instance = nullptr; - status = napi_new_instance(env, cons, args.size(), args.data(), &instance); - if (status != napi_ok) { - HILOGE("INNER BUG. Cannot instantiate the class %{public}s because of %{public}d", className.c_str(), status); - return nullptr; - } - return instance; -} -} // namespace DistributedFS -} // namespace OHOS \ No newline at end of file diff --git a/interfaces/innerkits/js/common/napi/n_class.h b/interfaces/innerkits/js/common/napi/n_class.h deleted file mode 100644 index db9a90ca0..000000000 --- a/interfaces/innerkits/js/common/napi/n_class.h +++ /dev/null @@ -1,82 +0,0 @@ -/* - * Copyright (c) 2021 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. - */ - -#pragma once - -#include "uni_header.h" - -#include -#include -#include -#include -#include -#include - -#include "../log.h" - -namespace OHOS { -namespace DistributedFS { -class NClass final { -public: - NClass(const NClass &) = delete; - NClass &operator = (const NClass &) = delete; - static NClass &GetInstance(); - - static std::tuple DefineClass(napi_env env, - std::string className, - napi_callback constructor, - std::vector &&properties); - static bool SaveClass(napi_env env, std::string className, napi_value exClass); - static napi_value InstantiateClass(napi_env env, std::string className, std::vector args); - - template static T *GetEntityOf(napi_env env, napi_value objStat) - { - if (!env || !objStat) { - HILOGE("Empty input: env %d, obj %d", env == nullptr, objStat == nullptr); - return nullptr; - } - T *t = nullptr; - napi_status status = napi_unwrap(env, objStat, (void **)&t); - if (status != napi_ok) { - HILOGE("Cannot umwarp for pointer: %d", status); - return nullptr; - } - return t; - } - - template static bool SetEntityFor(napi_env env, napi_value obj, std::unique_ptr entity) - { - napi_status status = napi_wrap( - env, - obj, - entity.get(), - [](napi_env env, void *data, void *hint) { - auto entity = static_cast(data); - delete entity; - }, - nullptr, - nullptr); - entity.release(); - return status == napi_ok; - } - -private: - NClass() = default; - ~NClass() = default; - std::map exClassMap; - std::mutex exClassMapLock; -}; -} // namespace DistributedFS -} // namespace OHOS \ No newline at end of file diff --git a/interfaces/innerkits/js/common/napi/n_exporter.h b/interfaces/innerkits/js/common/napi/n_exporter.h deleted file mode 100644 index 2ade0c076..000000000 --- a/interfaces/innerkits/js/common/napi/n_exporter.h +++ /dev/null @@ -1,39 +0,0 @@ -/* - * Copyright (c) 2021 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. - */ - -#pragma once - -#include "uni_header.h" - -#include -#include - -#include "n_val.h" - -namespace OHOS { -namespace DistributedFS { -class NExporter { -public: - NExporter(napi_env env, napi_value exports) : exports_(env, exports) {}; - virtual ~NExporter() = default; - - virtual bool Export() = 0; - virtual std::string GetClassName() = 0; - -protected: - NVal exports_; -}; -} // namespace DistributedFS -} // namespace OHOS \ No newline at end of file diff --git a/interfaces/innerkits/js/common/napi/n_func_arg.cpp b/interfaces/innerkits/js/common/napi/n_func_arg.cpp deleted file mode 100644 index 123ef8d0a..000000000 --- a/interfaces/innerkits/js/common/napi/n_func_arg.cpp +++ /dev/null @@ -1,111 +0,0 @@ -/* - * Copyright (c) 2021 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 "n_func_arg.h" - -#include -#include - -#include "../log.h" -#include "../uni_error.h" - -namespace OHOS { -namespace DistributedFS { -using namespace std; - -NFuncArg::NFuncArg(napi_env env, napi_callback_info info) : env_(env), info_(info) {} - -NFuncArg::~NFuncArg() {} - -void NFuncArg::SetArgc(size_t argc) -{ - argc_ = argc; -} -void NFuncArg::SetThisVar(napi_value thisVar) -{ - thisVar_ = thisVar; -} - -size_t NFuncArg::GetArgc(void) const -{ - return argc_; -} - -napi_value NFuncArg::GetThisVar(void) const -{ - return thisVar_; -} - -napi_value NFuncArg::GetArg(size_t argPos) const -{ - return (argPos < GetArgc()) ? argv_[argPos] : nullptr; -} - -napi_value NFuncArg::operator[](size_t argPos) const -{ - return GetArg(argPos); -} - -bool NFuncArg::InitArgs(std::function argcChecker) -{ - SetArgc(0); - argv_.reset(); - - size_t argc; - napi_value thisVar; - napi_status status = napi_get_cb_info(env_, info_, &argc, nullptr, &thisVar, nullptr); - if (status != napi_ok) { - HILOGE("Cannot get num of func args for %{public}d", status); - return false; - } - if (argc) { - argv_ = make_unique(argc); - status = napi_get_cb_info(env_, info_, &argc, argv_.get(), &thisVar, nullptr); - if (status != napi_ok) { - HILOGE("Cannot get func args for %{public}d", status); - return false; - } - } - SetArgc(argc); - SetThisVar(thisVar); - - return argcChecker(); -} - -bool NFuncArg::InitArgs(size_t argc) -{ - return InitArgs([argc, this]() { - size_t realArgc = GetArgc(); - if (argc != realArgc) { - HILOGE("Num of args recved eq %zu while expecting %{public}zu", realArgc, argc); - return false; - } - return true; - }); -} - -bool NFuncArg::InitArgs(size_t minArgc, size_t maxArgc) -{ - return InitArgs([minArgc, maxArgc, this]() { - size_t realArgc = GetArgc(); - if (minArgc > realArgc || maxArgc < realArgc) { - HILOGE("Num of args recved eq %zu while expecting %{public}zu ~ %{public}zu", realArgc, minArgc, maxArgc); - return false; - } - return true; - }); -} -} // namespace DistributedFS -} // namespace OHOS diff --git a/interfaces/innerkits/js/common/napi/n_func_arg.h b/interfaces/innerkits/js/common/napi/n_func_arg.h deleted file mode 100644 index ba7a7dd5a..000000000 --- a/interfaces/innerkits/js/common/napi/n_func_arg.h +++ /dev/null @@ -1,74 +0,0 @@ -/* - * Copyright (c) 2021 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. - */ - -#pragma once - -#include -#include -#include -#include - -#include "n_val.h" -#include "uni_header.h" - -namespace OHOS { -namespace DistributedFS { -enum NARG_CNT { - ZERO = 0, - ONE = 1, - TWO = 2, - THREE = 3, - FOUR = 4, - FIVE = 5 -}; - -enum NARG_POS { - FIRST = 0, - SECOND = 1, - THIRD = 2, - FOURTH = 3, - FIFTH = 4, - SIXTH = 5 -}; - -class NFuncArg final { -public: - NFuncArg(napi_env env, napi_callback_info info); - virtual ~NFuncArg(); - - bool InitArgs(size_t argc); - bool InitArgs(size_t minArgc, size_t maxArgc); - - size_t GetArgc() const; - napi_value GetThisVar() const; - - napi_value operator[](size_t idx) const; - napi_value GetArg(size_t argPos) const; - -private: - napi_env env_ = nullptr; - napi_callback_info info_ = nullptr; - - size_t argc_ = 0; - std::unique_ptr argv_ = { nullptr }; - napi_value thisVar_ = nullptr; - - bool InitArgs(std::function argcChecker); - - void SetArgc(size_t argc); - void SetThisVar(napi_value thisVar); -}; -} // namespace DistributedFS -} // namespace OHOS \ No newline at end of file diff --git a/interfaces/innerkits/js/common/napi/n_val.cpp b/interfaces/innerkits/js/common/napi/n_val.cpp deleted file mode 100644 index 90aeab48e..000000000 --- a/interfaces/innerkits/js/common/napi/n_val.cpp +++ /dev/null @@ -1,291 +0,0 @@ -/* - * Copyright (c) 2021 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 "n_val.h" - -#include -#include - -#include "../log.h" -#include "../uni_error.h" - -namespace OHOS { -namespace DistributedFS { -using namespace std; - -NVal::NVal(napi_env nEnv, napi_value nVal = nullptr) : env_(nEnv), val_(nVal) {} - -NVal::operator bool() const -{ - return env_ && val_; -} - -bool NVal::TypeIs(napi_valuetype expType) const -{ - if (!*this) - return false; - - napi_valuetype valueType; - napi_typeof(env_, val_, &valueType); - - if (expType != valueType) { - return false; - } - return true; -} - -bool NVal::TypeIsError(bool checkErrno) const -{ - if (!*this) { - return false; - } - - bool res = false; - napi_is_error(env_, val_, &res); - - return res; -} - -tuple, size_t> NVal::ToUTF8String() const -{ - size_t strLen = 0; - napi_status status = napi_get_value_string_utf8(env_, val_, nullptr, -1, &strLen); - if (status != napi_ok) { - return { false, nullptr, 0 }; - } - - size_t bufLen = strLen + 1; - unique_ptr str = make_unique(bufLen); - status = napi_get_value_string_utf8(env_, val_, str.get(), bufLen, &strLen); - return make_tuple(status == napi_ok, move(str), strLen); -} - -tuple, size_t> NVal::ToUTF16String() const -{ -#ifdef FILE_SUBSYSTEM_DEV_ON_PC - size_t strLen = 0; - napi_status status = napi_get_value_string_utf16(env_, val_, nullptr, -1, &strLen); - if (status != napi_ok) { - return { false, nullptr, 0 }; - } - - auto str = make_unique(++strLen); - status = napi_get_value_string_utf16(env_, val_, str.get(), strLen, nullptr); - if (status != napi_ok) { - return { false, nullptr, 0 }; - } - - strLen = reinterpret_cast(str.get() + strLen) - reinterpret_cast(str.get()); - auto strRet = unique_ptr(reinterpret_cast(str.release())); - return { true, move(strRet), strLen }; -#else - // Note that quickjs doesn't support utf16 - return ToUTF8String(); -#endif -} - -tuple NVal::ToPointer() const -{ - void *res = nullptr; - napi_status status = napi_get_value_external(env_, val_, &res); - return make_tuple(status == napi_ok, res); -} - -tuple NVal::ToBool() const -{ - bool flag = false; - napi_status status = napi_get_value_bool(env_, val_, &flag); - return make_tuple(status == napi_ok, flag); -} - -tuple NVal::ToInt32() const -{ - int32_t res = 0; - napi_status status = napi_get_value_int32(env_, val_, &res); - return make_tuple(status == napi_ok, res); -} - -tuple NVal::ToInt64() const -{ - int64_t res = 0; - napi_status status = napi_get_value_int64(env_, val_, &res); - return make_tuple(status == napi_ok, res); -} - -tuple NVal::ToArraybuffer() const -{ - void *buf = nullptr; - size_t bufLen = 0; - bool status = napi_get_arraybuffer_info(env_, val_, &buf, &bufLen); - return make_tuple(status == napi_ok, buf, bufLen); -} - -tuple NVal::ToTypedArray() const -{ - napi_typedarray_type type; - napi_value in_array_buffer = nullptr; - size_t byte_offset; - size_t length; - void *data = nullptr; - napi_status status = - napi_get_typedarray_info(env_, val_, &type, &length, (void **)&data, &in_array_buffer, &byte_offset); - return make_tuple(status == napi_ok, data, length); -} - -bool NVal::HasProp(string propName) const -{ - bool res = false; - - if (!env_ || !val_ || !TypeIs(napi_object)) - return false; - napi_status status = napi_has_named_property(env_, val_, propName.c_str(), &res); - return (status == napi_ok) && res; -} - -NVal NVal::GetProp(string propName) const -{ - if (!HasProp(propName)) { - return { env_, nullptr }; - } - napi_value prop = nullptr; - napi_status status = napi_get_named_property(env_, val_, propName.c_str(), &prop); - if (status != napi_ok) { - return { env_, nullptr }; - } - return NVal(env_, prop); -} - -bool NVal::AddProp(vector &&propVec) const -{ - if (!TypeIs(napi_valuetype::napi_object)) { - HILOGE("INNER BUG. Prop should only be added to objects"); - return false; - } - napi_status status = napi_define_properties(env_, val_, propVec.size(), propVec.data()); - if (status != napi_ok) { - HILOGE("INNER BUG. Cannot define properties because of %{public}d", status); - return false; - } - return true; -} - -bool NVal::AddProp(string propName, napi_value val) const -{ - if (!TypeIs(napi_valuetype::napi_object) || HasProp(propName)) { - HILOGE("INNER BUG. Prop should only be added to objects"); - return false; - } - - napi_status status = napi_set_named_property(env_, val_, propName.c_str(), val); - if (status != napi_ok) { - HILOGE("INNER BUG. Cannot set named property because of %{public}d", status); - return false; - } - return true; -} - -NVal NVal::CreateUndefined(napi_env env) -{ - napi_value res = nullptr; - napi_get_undefined(env, &res); - return { env, res }; -} - -NVal NVal::CreateInt64(napi_env env, int64_t val) -{ - napi_value res = nullptr; - napi_create_int64(env, val, &res); - return { env, res }; -} - -NVal NVal::CreateInt32(napi_env env, int32_t val) -{ - napi_value res = nullptr; - napi_create_int32(env, val, &res); - return { env, res }; -} - -NVal NVal::CreateObject(napi_env env) -{ - napi_value res = nullptr; - napi_create_object(env, &res); - return { env, res }; -} - -NVal NVal::CreateBool(napi_env env, bool val) -{ - napi_value res = nullptr; - napi_get_boolean(env, val, &res); - return { env, res }; -} - -NVal NVal::CreateUTF8String(napi_env env, std::string str) -{ - napi_value res = nullptr; - napi_create_string_utf8(env, str.c_str(), str.length(), &res); - return { env, res }; -} - -NVal NVal::CreateUint8Array(napi_env env, void *buf, size_t bufLen) -{ - napi_value output_buffer = nullptr; - napi_create_external_arraybuffer( - env, - buf, - bufLen, - [](napi_env env, void *finalize_data, void *finalize_hint) { free(finalize_data); }, - NULL, - &output_buffer); - napi_value output_array = nullptr; - napi_create_typedarray(env, napi_uint8_array, bufLen, output_buffer, 0, &output_array); - return { env, output_array }; -} - -napi_property_descriptor NVal::DeclareNapiProperty(const char *name, napi_value val) -{ - return { (name), nullptr, nullptr, nullptr, nullptr, val, napi_default, nullptr }; -} - -napi_property_descriptor NVal::DeclareNapiStaticProperty(const char *name, napi_value val) -{ - return { (name), nullptr, nullptr, nullptr, nullptr, val, napi_static, nullptr }; -} - -napi_property_descriptor NVal::DeclareNapiFunction(const char *name, napi_callback func) -{ - return { (name), nullptr, (func), nullptr, nullptr, nullptr, napi_default, nullptr }; -} - -napi_property_descriptor NVal::DeclareNapiStaticFunction(const char *name, napi_callback func) -{ - return { (name), nullptr, (func), nullptr, nullptr, nullptr, napi_static, nullptr }; -} - -napi_property_descriptor NVal::DeclareNapiGetter(const char *name, napi_callback getter) -{ - return { (name), nullptr, nullptr, (getter), nullptr, nullptr, napi_default, nullptr }; -} - -napi_property_descriptor NVal::DeclareNapiSetter(const char *name, napi_callback setter) -{ - return { (name), nullptr, nullptr, nullptr, (setter), nullptr, napi_default, nullptr }; -} - -napi_property_descriptor NVal::DeclareNapiGetterSetter(const char *name, napi_callback getter, napi_callback setter) -{ - return { (name), nullptr, nullptr, (getter), (setter), nullptr, napi_default, nullptr }; -} -} // namespace DistributedFS -} // namespace OHOS \ No newline at end of file diff --git a/interfaces/innerkits/js/common/napi/n_val.h b/interfaces/innerkits/js/common/napi/n_val.h deleted file mode 100644 index 1dd808f2e..000000000 --- a/interfaces/innerkits/js/common/napi/n_val.h +++ /dev/null @@ -1,80 +0,0 @@ -/* - * Copyright (c) 2021 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 N_VAL_H -#define N_VAL_H - -#include -#include -#include - -#include "uni_header.h" - -namespace OHOS { -namespace DistributedFS { -class NVal final { -public: - NVal() = default; - NVal(napi_env nEnv, napi_value nVal); - NVal &operator = (const NVal &) = default; - virtual ~NVal() = default; - - // NOTE! env_ and val_ is LIKELY to be null - napi_env env_ = nullptr; - napi_value val_ = nullptr; - - explicit operator bool() const; - bool TypeIs(napi_valuetype expType) const; - bool TypeIsError(bool checkErrno = false) const; - - /* SHOULD ONLY BE USED FOR EXPECTED TYPE */ - std::tuple, size_t> ToUTF8String() const; - std::tuple, size_t> ToUTF16String() const; - std::tuple ToPointer() const; - std::tuple ToBool() const; - std::tuple ToInt32() const; - std::tuple ToInt64() const; - std::tuple ToArraybuffer() const; - std::tuple ToTypedArray() const; - - /* Static helpers to create js objects */ - static NVal CreateUndefined(napi_env env); - static NVal CreateInt64(napi_env env, int64_t val); - static NVal CreateInt32(napi_env env, int32_t val); - static NVal CreateObject(napi_env env); - static NVal CreateBool(napi_env env, bool val); - static NVal CreateUTF8String(napi_env env, std::string str); - static NVal CreateUint8Array(napi_env env, void *buf, size_t bufLen); - - /* SHOULD ONLY BE USED FOR OBJECT */ - bool HasProp(std::string propName) const; - NVal GetProp(std::string propName) const; - bool AddProp(std::vector &&propVec) const; - bool AddProp(std::string propName, napi_value nVal) const; - - /* Static helpers to create prop of js objects */ - static napi_property_descriptor DeclareNapiProperty(const char *name, napi_value val); - static napi_property_descriptor DeclareNapiStaticProperty(const char *name, napi_value val); - static napi_property_descriptor DeclareNapiFunction(const char *name, napi_callback func); - static napi_property_descriptor DeclareNapiStaticFunction(const char *name, napi_callback func); - static napi_property_descriptor DeclareNapiGetter(const char *name, napi_callback getter); - static napi_property_descriptor DeclareNapiSetter(const char *name, napi_callback setter); - static inline napi_property_descriptor DeclareNapiGetterSetter(const char *name, - napi_callback getter, - napi_callback setter); -}; -} // namespace DistributedFS -} // namespace OHOS -#endif // N_VAL_H \ No newline at end of file diff --git a/interfaces/innerkits/js/common/napi/uni_header.h b/interfaces/innerkits/js/common/napi/uni_header.h deleted file mode 100644 index a79d4e1ed..000000000 --- a/interfaces/innerkits/js/common/napi/uni_header.h +++ /dev/null @@ -1,23 +0,0 @@ -/* - * Copyright (c) 2021 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. - */ - -#pragma once - -#ifdef FILE_SUBSYSTEM_DEV_ON_PC -#include -#else -#include "napi/native_api.h" -#include "napi/native_node_api.h" -#endif diff --git a/interfaces/innerkits/js/common/uni_error.cpp b/interfaces/innerkits/js/common/uni_error.cpp deleted file mode 100644 index 010aa3dad..000000000 --- a/interfaces/innerkits/js/common/uni_error.cpp +++ /dev/null @@ -1,118 +0,0 @@ -/* - * Copyright (c) 2021 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 "uni_error.h" - -#include -#include - -#include "log.h" -#include "napi/n_val.h" - -namespace OHOS { -namespace DistributedFS { -using namespace std; - -UniError::UniError() {} - -UniError::UniError(ELegacy eLegacy) : errno_(eLegacy), codingSystem_(ERR_CODE_SYSTEM_LEGACY) {} - -UniError::UniError(int ePosix) : errno_(ePosix), codingSystem_(ERR_CODE_SYSTEM_POSIX) {} - -UniError::operator bool() const -{ - return errno_ != ERRNO_NOERR; -} - -int UniError::GetErrno(ErrCodeSystem cs) -{ - if (errno_ == ERRNO_NOERR) { - return ERRNO_NOERR; - } - if (cs == codingSystem_) { - return errno_; - } - - if (cs == ERR_CODE_SYSTEM_POSIX) { - // Note that we should support more codes here - return EINVAL; - } - - // Note that this shall be done properly - return ELEGACY_INVAL; -} - -void UniError::SetErrno(ELegacy eLegacy) -{ - errno_ = eLegacy; - codingSystem_ = ERR_CODE_SYSTEM_LEGACY; -} - -void UniError::SetErrno(int ePosix) -{ - errno_ = ePosix; - codingSystem_ = ERR_CODE_SYSTEM_POSIX; -} - -std::string UniError::GetDefaultErrstr() -{ - if (codingSystem_ != ERR_CODE_SYSTEM_POSIX && codingSystem_ != ERR_CODE_SYSTEM_LEGACY) { - return "BUG: Curious coding system"; - } - return strerror(GetErrno(ERR_CODE_SYSTEM_POSIX)); -} - -napi_value UniError::GetNapiErr(napi_env env) -{ - return GetNapiErr(env, GetDefaultErrstr()); -} - -napi_value UniError::GetNapiErr(napi_env env, string errMsg) -{ - napi_value code = NVal::CreateUTF8String(env, to_string(GetErrno(codingSystem_))).val_; - napi_value msg = NVal::CreateUTF8String(env, errMsg).val_; - - napi_value res = nullptr; - napi_status createRes = napi_create_error(env, code, msg, &res); - if (createRes) { - HILOGE("Failed to create an exception, msg = %{public}s", errMsg.c_str()); - } - return res; -} - -void UniError::ThrowErr(napi_env env) -{ - string msg = GetDefaultErrstr(); - napi_value tmp = nullptr; - napi_get_and_clear_last_exception(env, &tmp); - // Note that ace engine cannot thow errors created by napi_create_error so far - napi_status throwStatus = napi_throw_error(env, nullptr, msg.c_str()); - if (throwStatus != napi_ok) { - HILOGE("Failed to throw an exception, %{public}d, code = %{public}s", throwStatus, msg.c_str()); - } -} - -void UniError::ThrowErr(napi_env env, string errMsg) -{ - napi_value tmp = nullptr; - napi_get_and_clear_last_exception(env, &tmp); - // Note that ace engine cannot thow errors created by napi_create_error so far - napi_status throwStatus = napi_throw_error(env, nullptr, errMsg.c_str()); - if (throwStatus != napi_ok) { - HILOGE("Failed to throw an exception, %{public}d, code = %{public}s", throwStatus, errMsg.c_str()); - } -} -} // namespace DistributedFS -} // namespace OHOS \ No newline at end of file diff --git a/interfaces/innerkits/js/common/uni_error.h b/interfaces/innerkits/js/common/uni_error.h deleted file mode 100644 index a4183986d..000000000 --- a/interfaces/innerkits/js/common/uni_error.h +++ /dev/null @@ -1,64 +0,0 @@ -/* - * Copyright (c) 2021 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. - */ - -#pragma once - -#include -#include - -#include "napi/uni_header.h" - -namespace OHOS { -namespace DistributedFS { -constexpr int ERRNO_NOERR = 0; - -enum ELegacy { - ELEGACY_INVAL = 202, - ELEGACY_IO = 300, - ELEGACY_NOENT = 301, -}; - -enum ErrCodeSystem { - ERR_CODE_SYSTEM_LEGACY, - ERR_CODE_SYSTEM_POSIX, -}; - -class UniError { -public: - UniError(); - explicit UniError(ELegacy eLegacy); - explicit UniError(int ePosix); - ~UniError() = default; - - UniError &operator = (const UniError &) = default; - - explicit operator bool() const; - - void SetErrno(ELegacy eLegacy); - void SetErrno(int ePosix); - int GetErrno(ErrCodeSystem cs); - - std::string GetDefaultErrstr(); - napi_value GetNapiErr(napi_env env); - napi_value GetNapiErr(napi_env env, std::string errMsg); - void ThrowErr(napi_env env); - void ThrowErr(napi_env env, std::string errMsg); - -private: - int errno_ = ERRNO_NOERR; - ErrCodeSystem codingSystem_ = ERR_CODE_SYSTEM_POSIX; -}; -} // namespace DistributedFS -} // namespace OHOS \ No newline at end of file diff --git a/interfaces/innerkits/js/mod_sendfile/sendfile.cpp b/interfaces/innerkits/js/mod_sendfile/sendfile.cpp deleted file mode 100644 index 5a52ed9d3..000000000 --- a/interfaces/innerkits/js/mod_sendfile/sendfile.cpp +++ /dev/null @@ -1,143 +0,0 @@ -/* - * Copyright (c) 2021 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 "sendfile.h" - -#include - -#include "napi/n_class.h" -#include "napi/n_func_arg.h" -#include "napi/n_val.h" -#include "uni_error.h" - -#include "napi/n_async/n_async_work_callback.h" -#include "napi/n_async/n_async_work_promise.h" - -#include "system_ability_definition.h" -#include "i_distributedfile_service.h" -#include "service_proxy.h" - -#include -#include - -namespace OHOS { -namespace DistributedFS { -namespace ModuleSendFile { -using namespace OHOS::Storage::DistributedFile; - -napi_value SendFile(napi_env env, napi_callback_info info) -{ - NFuncArg funcArg(env, info); - if (!funcArg.InitArgs(NARG_CNT::FOUR, NARG_CNT::FIVE)) { - UniError(EINVAL).ThrowErr(env, "Number of arguments unmatched"); - return nullptr; - } - - bool succ = false; - auto resultCode = std::make_shared(); - - std::unique_ptr deviceId; - std::vector sourPath; - std::vector destPath; - - uint32_t fileCount = 0; - - std::tie(succ, deviceId, std::ignore) = NVal(env, funcArg[NARG_POS::FIRST]).ToUTF8String(); - napi_get_value_uint32(env, funcArg[NARG_POS::FOURTH], &fileCount); - - HILOGI("SendFile::deviceId :%{public}s", deviceId.get()); - - napi_value result; - napi_status status; - for (uint32_t i=0; i < fileCount; i++) { - status = napi_get_element(env, funcArg[NARG_POS::SECOND], i, &result); - if (napi_ok != status) { - return nullptr; - } - std::unique_ptr path; - std::tie(succ, path, std::ignore) = NVal(env, result).ToUTF8String(); - sourPath.push_back(path.get()); - HILOGI("SendFile::JS_SendFile src[%{public}d]:%{public}s", i, sourPath.at(i).c_str()); - - status = napi_get_element(env, funcArg[NARG_POS::THIRD], i, &result); - if (napi_ok != status) { - return nullptr; - } - std::tie(succ, path, std::ignore) = NVal(env, result).ToUTF8String(); - destPath.push_back(path.get()); - HILOGI("SendFile::JS_SendFile src[%{public}d]:%{public}s", i, destPath.at(i).c_str()); - } - - HILOGI("napi_value source: %{public}d, dest: %{public}d", sourPath.size(), destPath.size()); - std::string deviceIdString(deviceId.get()); - auto cbExec = [deviceIdString, sourPath, destPath, fileCount, resultCode](napi_env env) -> UniError { - *resultCode = ExecSendFile(deviceIdString.c_str(), sourPath, destPath, fileCount); - HILOGI("cbExec resultCode : %{public}d", *resultCode); - return UniError(ERRNO_NOERR); - }; - - auto cbComplete = [resultCode](napi_env env, UniError err) -> NVal { - if (err) { - return { env, err.GetNapiErr(env) }; - } - HILOGI("cbComplete resultCode : %{public}d", *resultCode); - return { NVal::CreateInt64(env, *resultCode) }; - }; - - HILOGI("napi_value SendFile created thread params count %{public}d", funcArg.GetArgc()); - std::string procedureName = "SendFile"; - NVal thisVar(env, funcArg.GetThisVar()); - if (funcArg.GetArgc() == NARG_CNT::FOUR) { - HILOGI("promise function"); - return NAsyncWorkPromise(env, thisVar).Schedule(procedureName, cbExec, cbComplete).val_; - } else if (funcArg.GetArgc() == NARG_CNT::FIVE) { - HILOGI("callback function"); - NVal cb(env, funcArg[NARG_POS::FIFTH]); - return NAsyncWorkCallback(env, thisVar, cb).Schedule(procedureName, cbExec, cbComplete).val_; - } - HILOGI("napi_value SendFile End"); - return NVal::CreateUndefined(env).val_; -} - -int32_t ExecSendFile(const std::string &deviceId, const std::vector& srcList, - const std::vector& dstList, uint32_t fileCnt) -{ - sptr systemAbilityMgr = - SystemAbilityManagerClient::GetInstance().GetSystemAbilityManager(); - if (systemAbilityMgr == nullptr) { - HILOGE("BundleService Get ISystemAbilityManager failed ... \n"); - return -1; - } - sptr remote = systemAbilityMgr->GetSystemAbility(STORAGE_DISTRIBUTED_FILE_SERVICE_SA_ID); - if (remote == nullptr) { - HILOGE("DistributedFileService Get STORAGE_DISTRIBUTED_FILE_SERVICE_SA_ID = %{public}d fail ... \n", - STORAGE_DISTRIBUTED_FILE_SERVICE_SA_ID); - return -1; - } - HILOGI("ExecSendFile remote %{public}p", remote.GetRefPtr()); - - sptr proxy = iface_cast(remote); - if (proxy == nullptr) { - HILOGE("DistributedFileService == nullptr\n"); - return -1; - } - HILOGI("ExecSendFile distributedFileService %{public}p", proxy.GetRefPtr()); - - int32_t result = proxy->SendFile(deviceId, srcList, dstList, fileCnt); - return result; -} -} // namespace ModuleSendFile -} // namespace DistributedFS -} // namespace OHOS \ No newline at end of file diff --git a/interfaces/innerkits/js/mod_sendfile/sendfile.h b/interfaces/innerkits/js/mod_sendfile/sendfile.h deleted file mode 100644 index 5123ee49b..000000000 --- a/interfaces/innerkits/js/mod_sendfile/sendfile.h +++ /dev/null @@ -1,32 +0,0 @@ -/* - * Copyright (c) 2021 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 SENDFILE_H -#define SENDFILE_H - -#include -#include "napi/n_exporter.h" - -namespace OHOS { -namespace DistributedFS { -namespace ModuleSendFile { -napi_value SendFile(napi_env env, napi_callback_info info); - -static int32_t ExecSendFile(const std::string &deviceId, const std::vector& srcList, - const std::vector& dstList, uint32_t fileCnt); -} // namespace ModuleSendFile -} // namespace DistributedFS -} // namespace OHOS -#endif // SENDFILE_H \ No newline at end of file diff --git a/interfaces/innerkits/js/mod_sendfile/sendfile_napi.cpp b/interfaces/innerkits/js/mod_sendfile/sendfile_napi.cpp deleted file mode 100644 index b15ede648..000000000 --- a/interfaces/innerkits/js/mod_sendfile/sendfile_napi.cpp +++ /dev/null @@ -1,40 +0,0 @@ -/* - * Copyright (c) 2021 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 "napi/native_api.h" -#include "napi/native_node_api.h" - -#include "sendfile.h" -#include "sendfile_napi.h" - -namespace OHOS { -namespace DistributedFS { -namespace ModuleSendFile { -/*********************************************** - * Module export and register - ***********************************************/ -napi_value SendFileExport(napi_env env, napi_value exports) -{ - static napi_property_descriptor desc[] = { - DECLARE_NAPI_FUNCTION("sendFile", SendFile), - }; - NAPI_CALL(env, napi_define_properties(env, exports, sizeof(desc) / sizeof(desc[0]), desc)); - return exports; -} - -NAPI_MODULE(sendfile, SendFileExport) -} // namespace ModuleSendFile -} // namespace DistributedFS -} // namespace OHOS \ No newline at end of file diff --git a/interfaces/innerkits/js/mod_sendfile/sendfile_napi.h b/interfaces/innerkits/js/mod_sendfile/sendfile_napi.h deleted file mode 100644 index 01b395d45..000000000 --- a/interfaces/innerkits/js/mod_sendfile/sendfile_napi.h +++ /dev/null @@ -1,25 +0,0 @@ -/* - * Copyright (c) 2021 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 SENDFILE_NAPI_H -#define SENDFILE_NAPI_H - -namespace OHOS { -namespace DistributedFS { -namespace ModuleSendFile { -} // namespace ModuleSendFile -} // namespace DistributedFS -} // namespace OHOS -#endif // SENDFILE_NAPI_H \ No newline at end of file diff --git a/ohos.build b/ohos.build deleted file mode 100644 index df6eed8d8..000000000 --- a/ohos.build +++ /dev/null @@ -1,31 +0,0 @@ -{ - "subsystem": "storage", - "parts": { - "storage_distributed_file_manager": { - "variants": [ - "wearable", - "phone" - ], - "module_list": [ - "//foundation/storage/distributed_file_manager/services/:services_target", - "//foundation/storage/distributed_file_manager/interfaces/innerkits/js:build_kits_js", - "//foundation/storage/distributed_file_manager/executable:xhl_test-sa" - ], - "inner_kits":[ - { - "name": "//foundation/storage/distributed_file_manager/interfaces/innerkits/native:libdistributedfile_innerkits", - "header": { - "header_files": [ - "i_distributedfile_service.h" - ], - "header_base": "//foundation/storage/distributed_file_manager/interfaces/innerkits/native" - } - } - ], - "test_list": [ - "//foundation/storage/distributed_file_manager/services/distributedfiledaemon/test/unittest:unittest", - "//foundation/storage/distributed_file_manager/test/moduletest:moduletest" - ] - } - } -} diff --git a/services/distributedfileservice/BUILD.gn b/services/distributedfileservice/BUILD.gn index 4713e9d23..7fad09192 100644 --- a/services/distributedfileservice/BUILD.gn +++ b/services/distributedfileservice/BUILD.gn @@ -32,10 +32,7 @@ ohos_shared_library("libdistributedfileservice") { configs = [ "${utils_path}:compiler_configs" ] external_deps = [ - "ability_runtime:want", - "bundle_framework:appexecfwk_base", - "bundle_framework:appexecfwk_core", - "dsoftbus_standard:softbus_client" + "dsoftbus_standard:softbus_client", "ipc:ipc_core", "safwk:system_ability_fwk", "samgr_standard:samgr_proxy", diff --git a/services/distributedfileservice/include/ipc/distributedfile_service.h b/services/distributedfileservice/include/ipc/distributedfile_service.h index 22dc36073..3b9d13dab 100644 --- a/services/distributedfileservice/include/ipc/distributedfile_service.h +++ b/services/distributedfileservice/include/ipc/distributedfile_service.h @@ -28,8 +28,8 @@ class DistributedFileService : public SystemAbility, public std::enable_shared_from_this { DECLARE_SYSTEM_ABILITY(DistributedFileService) public: - DistributedFileService(int32_t saID, bool runOnCreate) : SystemAbility(saID, runOnCreate){}; - ~DistributedFileService(){}; + DistributedFileService(int32_t saID, bool runOnCreate) : SystemAbility(saID, runOnCreate) {}; + ~DistributedFileService() {}; void OnDump() override; void OnStart() override; diff --git a/services/distributedfileservice/include/network/softbus_agent.h b/services/distributedfileservice/include/network/softbus_agent.h index a3e078d45..4387a0550 100644 --- a/services/distributedfileservice/include/network/softbus_agent.h +++ b/services/distributedfileservice/include/network/softbus_agent.h @@ -16,10 +16,10 @@ #ifndef DFS_SOFTBUS_AGENT_H #define DFS_SOFTBUS_AGENT_H -#include "utils_singleton.h" #include #include #include +#include "utils_singleton.h" namespace OHOS { namespace Storage { @@ -49,8 +49,8 @@ protected: std::string GetPeerDevId(const int sessionId); private: - std::string sessionName_{"DistributedFileService"}; - std::string pkgName_{"ohos.storage.distributedfile.service"}; + std::string sessionName_ { "DistributedFileService" }; + std::string pkgName_ { "ohos.storage.distributedfile.service" }; std::mutex sessionMapMux_; std::unordered_map> cidToSessionID_; diff --git a/services/distributedfileservice/include/network/softbus_dispatcher.h b/services/distributedfileservice/include/network/softbus_dispatcher.h index 1639a5413..79a14a61e 100644 --- a/services/distributedfileservice/include/network/softbus_dispatcher.h +++ b/services/distributedfileservice/include/network/softbus_dispatcher.h @@ -18,7 +18,6 @@ #include #include -#include #include namespace OHOS { diff --git a/services/distributedfileservice/src/ipc/distributedfile_service.cpp b/services/distributedfileservice/src/ipc/distributedfile_service.cpp index 7808db9c8..8bb1fb7d4 100644 --- a/services/distributedfileservice/src/ipc/distributedfile_service.cpp +++ b/services/distributedfileservice/src/ipc/distributedfile_service.cpp @@ -14,11 +14,11 @@ */ #include "distributedfile_service.h" +#include #include "device_manager_agent.h" #include "utils_exception.h" #include "utils_log.h" #include "softbus_agent.h" -#include namespace OHOS { namespace Storage { @@ -65,7 +65,7 @@ void DistributedFileService::OnStop() int32_t DistributedFileService::sendTest() { - LOGI("xhl DistributedFileService::sendTest"); + LOGI("DistributedFileService::sendTest"); return 0; } @@ -74,35 +74,6 @@ int32_t DistributedFileService::SendFile(const std::string &cid, const std::vector &destinationFileList, const uint32_t fileCount) { - char **sFileList = new char*[fileCount]; - LOGD("xhl DistributedFileService::SendFile, sessionId %{public}s, fileCount %{public}d", cid.c_str(), fileCount); - for (int index = 0; index < sourceFileList.size(); ++index) { - int32_t length = sourceFileList.at(index).length(); - sFileList[index] = new char[length + 1]; - memset_s(sFileList[index], length + 1, '\0', length + 1); - memcpy_s(sFileList[index], length + 1, sourceFileList.at(index).c_str(), length); - sFileList[index][length] = '\0'; - } - char **dFileList = new char*[fileCount]; - for (int index = 0; index < destinationFileList.size(); ++index) { - int32_t length = destinationFileList.at(index).length(); - dFileList[index] = new char[length + 1]; - memset_s(dFileList[index], length + 1, '\0', length + 1); - memcpy_s(dFileList[index], length + 1, destinationFileList.at(index).c_str(), length); - dFileList[index][length] = '\0'; - } - - auto softBusAgent = SoftbusAgent::GetInstance(); - int result = softBusAgent->SendFile(cid, (const char **)sFileList, (const char **)dFileList, fileCount); - LOGI("softBusAgent::SendFile result %{public}d", result); - - for (uint32_t index = 0; index < fileCount; ++index) { - delete[] sFileList[index]; - delete[] dFileList[index]; - } - delete[] sFileList; - delete[] dFileList; - return 0; } } // namespace DistributedFile diff --git a/services/distributedfileservice/src/ipc/distributedfile_service_stub.cpp b/services/distributedfileservice/src/ipc/distributedfile_service_stub.cpp index 8645172ec..ad5649921 100644 --- a/services/distributedfileservice/src/ipc/distributedfile_service_stub.cpp +++ b/services/distributedfileservice/src/ipc/distributedfile_service_stub.cpp @@ -39,7 +39,7 @@ int DistributedFileServiceStub::OnRemoteRequest(uint32_t code, MessageParcel &reply, MessageOption &option) { - LOGD("xhl DistributedFileServiceStub : OnRemoteRequest enter, code %{public}d ", code); + LOGD("DistributedFileServiceStub : OnRemoteRequest enter, code %{public}d ", code); auto itFunc = memberFuncMap_.find(code); if (itFunc != memberFuncMap_.end()) { auto memberFunc = itFunc->second; @@ -53,42 +53,14 @@ int DistributedFileServiceStub::OnRemoteRequest(uint32_t code, int DistributedFileServiceStub::test(MessageParcel &data, MessageParcel &reply) { - LOGD("xhl DistributedFileServiceStub : sendTest enter"); + LOGD(" DistributedFileServiceStub : sendTest enter"); sendTest(); return 3; } int32_t DistributedFileServiceStub::SendFileStub(MessageParcel &data, MessageParcel &reply) { - std::string cid = data.ReadString(); - if (cid.empty()) { - LOGE("DistributedFileServiceStub : Failed to get app device id, error: invalid device id"); - return DISTRIBUTEDFILE_DIR_NAME_IS_EMPTY; - } - - int32_t sourceListNumber = data.ReadInt32(); - std::vector srcList; - for (int32_t index = 0; index < sourceListNumber; ++index) { - srcList.push_back(data.ReadString()); - } - std::vector dstList; - int32_t destinationListNumber = data.ReadInt32(); - for (int32_t index = 0; index < destinationListNumber; ++index) { - dstList.push_back(data.ReadString()); - } - uint32_t fileCount = data.ReadUint32(); - - LOGI("DistributedFileServiceStub : cid %{public}s, srcList size %{public}d, dstList size %{public}d," - "fileCout %{public}d", cid.c_str(), sourceListNumber, destinationListNumber, fileCount); - - int32_t result = SendFile(cid, srcList, dstList, fileCount); - LOGD("xhl DistributedFileServiceStub : SendFileStub result = %{public}d", result); - if (!reply.WriteInt32(result)) { - LOGE("fail to write parcel"); - return DISTRIBUTEDFILE_WRITE_REPLY_FAIL; - } - - return result; + return 0; } } // namespace DistributedFile } // namespace Storage diff --git a/services/distributedfileservice/src/network/softbus_agent.cpp b/services/distributedfileservice/src/network/softbus_agent.cpp index 48857cb3d..d2416ede7 100644 --- a/services/distributedfileservice/src/network/softbus_agent.cpp +++ b/services/distributedfileservice/src/network/softbus_agent.cpp @@ -15,14 +15,14 @@ #include "softbus_agent.h" +#include +#include +#include #include "device_manager_agent.h" #include "session.h" #include "softbus_dispatcher.h" #include "utils_exception.h" #include "utils_log.h" -#include -#include -#include namespace OHOS { namespace Storage { @@ -31,6 +31,7 @@ using namespace std; constexpr int32_t SOFTBUS_OK = 0; constexpr int32_t DEVICE_ID_SIZE_MAX = 65; constexpr int32_t IS_CLIENT = 0; +const std::string DEFAULT_ROOT_PATH = "/data/service/el2/100/hmdfs/non_account/data/"; SoftbusAgent::SoftbusAgent() {} @@ -60,7 +61,6 @@ void SoftbusAgent::OnDeviceOnline(const std::string &cid) const char *sFileList[1] = {"/data/user/0/xhl_sendfile_test/1.txt"}; static int sendfile_cnt = 0; - // int ret = SendFile((*iter), sFileList, dFileList, 1); int ret = SendFile(cid, sFileList, nullptr, 1); if (ret != 0) { LOGE("sendfile failed, ret %{public}d", ret); @@ -74,8 +74,7 @@ int SoftbusAgent::SendFile(const std::string &cid, const char *sFileList[], cons // first check whether the sessionId available auto alreadyOnliceDev = DeviceManagerAgent::GetInstance()->getOnlineDevs(); if (alreadyOnliceDev.find(cid) == alreadyOnliceDev.end()) { - LOGE("cid:%{public}s has not been online yet", cid.c_str()); - return -1; + LOGE("cid:%{public}s has not been online yet, sendfile maybe will fail, try", cid.c_str()); } int sessionId = -1; { @@ -123,7 +122,7 @@ void SoftbusAgent::OpenSession(const std::string &cid) void SoftbusAgent::OnSessionOpened(const int sessionId, const int result) { LOGD("get session res:%{public}d, sessionId:%{public}d", result, sessionId); - if (result != 0) { // todo:增加重试? + if (result != 0) { LOGE("open failed, result:%{public}d, sessionId:%{public}d", result, sessionId); return; } @@ -150,21 +149,18 @@ void SoftbusAgent::OnSessionOpened(const int sessionId, const int result) int SoftbusAgent::OnSendFileFinished(const int sessionId, const std::string firstFile) { - // todo:待和js联调 LOGD("send file finish, sessionId:%{public}d, firstFile %{public}s", sessionId, firstFile.c_str()); return 0; } int SoftbusAgent::OnFileTransError(const int sessionId) { - // todo:待和js联调 LOGD("file trans error, sessionId:%{public}d", sessionId); return 0; } void SoftbusAgent::OnReceiveFileFinished(const int sessionId, const std::string files, int fileCnt) { - // todo:待和js联调 LOGD("recv file finish, sessionId:%{public}d, files %{public}s, cnt %{public}d", sessionId, files.c_str(), fileCnt); } @@ -182,7 +178,7 @@ void SoftbusAgent::OnSessionClosed(int sessionId) return; } -std::string SoftbusAgent::GetPeerDevId(const int sessionId) // 确认是否需要返回引用? +std::string SoftbusAgent::GetPeerDevId(const int sessionId) { std::string cid; char peerDevId[DEVICE_ID_SIZE_MAX] = ""; @@ -211,7 +207,7 @@ int SoftbusAgent::CloseSession(const std::string &cid) void SoftbusAgent::OnDeviceOffline(const std::string &cid) { - if (CloseSession(cid) == -1){ + if (CloseSession(cid) == -1) { return; } std::unique_lock lock(sessionMapMux_); @@ -256,7 +252,7 @@ void SoftbusAgent::RegisterFileListener() .OnFileTransError = SoftbusDispatcher::OnFileTransError, }; ret = ::SetFileReceiveListener(pkgName_.c_str(), sessionName_.c_str(), &fileRecvListener, - "/data/user/0/"); // rootDir TODO + DEFAULT_ROOT_PATH.c_str()); if (ret != 0) { stringstream ss; ss << "Failed to SetFileReceiveListener, errno:" << ret; diff --git a/services/distributedfileservice/src/network/softbus_dispatcher.cpp b/services/distributedfileservice/src/network/softbus_dispatcher.cpp index 464ae4de5..542f089c0 100644 --- a/services/distributedfileservice/src/network/softbus_dispatcher.cpp +++ b/services/distributedfileservice/src/network/softbus_dispatcher.cpp @@ -52,7 +52,6 @@ void SoftbusDispatcher::OnReceiveFileFinished(int sessionId, const char *files, LOGD("sessionId:%{public}d", sessionId); SoftbusAgent::GetInstance()->OnReceiveFileFinished(sessionId, std::string(files), fileCnt); } - } // namespace DistributedFile } // namespace Storage } // namespace OHOS \ No newline at end of file diff --git a/utils/system/include/utils_singleton.h b/utils/system/include/utils_singleton.h index d5a3c2c72..ffa1b58b5 100644 --- a/utils/system/include/utils_singleton.h +++ b/utils/system/include/utils_singleton.h @@ -67,7 +67,6 @@ std::shared_ptr Singleton::GetInstance() static std::shared_ptr *dummy = nullptr; static std::once_flag once; std::call_once(once, []() mutable { - // dummy = std::make_shared(); dummy = new std::shared_ptr(new T()); (*dummy)->StartInstance(); }); -- Gitee From e166b46de10f7a4723678b0fea93faac9b64d7f7 Mon Sep 17 00:00:00 2001 From: xianghengliang Date: Fri, 11 Feb 2022 20:23:40 +0800 Subject: [PATCH 13/14] unify distributedfileservice pkgname Signed-off-by: xianghengliang --- .../include/device/device_manager_agent.h | 2 -- .../include/ipc/distributedfile_service.h | 1 + .../include/network/softbus_agent.h | 1 - .../src/device/device_manager_agent.cpp | 9 +++++---- .../src/ipc/distributedfile_service_stub.cpp | 2 +- .../src/network/softbus_agent.cpp | 18 ++++++++++-------- 6 files changed, 17 insertions(+), 16 deletions(-) diff --git a/services/distributedfileservice/include/device/device_manager_agent.h b/services/distributedfileservice/include/device/device_manager_agent.h index 051a3d4fc..b2a11da1a 100644 --- a/services/distributedfileservice/include/device/device_manager_agent.h +++ b/services/distributedfileservice/include/device/device_manager_agent.h @@ -57,8 +57,6 @@ private: std::mutex devsRecordMutex_; std::set alreadyOnlineDev_; - - std::string pkgName_{"ohos.storage.distributedfile.service"}; }; } // namespace DistributedFile } // namespace Storage diff --git a/services/distributedfileservice/include/ipc/distributedfile_service.h b/services/distributedfileservice/include/ipc/distributedfile_service.h index 3b9d13dab..8bca0a920 100644 --- a/services/distributedfileservice/include/ipc/distributedfile_service.h +++ b/services/distributedfileservice/include/ipc/distributedfile_service.h @@ -41,6 +41,7 @@ public: const uint32_t fileCount) override; int32_t sendTest() override; + static inline const std::string pkgName_ { "ohos.storage.distributedfile.service" }; private: void PublishSA(); void StartManagers(); diff --git a/services/distributedfileservice/include/network/softbus_agent.h b/services/distributedfileservice/include/network/softbus_agent.h index 4387a0550..ec93ec966 100644 --- a/services/distributedfileservice/include/network/softbus_agent.h +++ b/services/distributedfileservice/include/network/softbus_agent.h @@ -50,7 +50,6 @@ protected: private: std::string sessionName_ { "DistributedFileService" }; - std::string pkgName_ { "ohos.storage.distributedfile.service" }; std::mutex sessionMapMux_; std::unordered_map> cidToSessionID_; diff --git a/services/distributedfileservice/src/device/device_manager_agent.cpp b/services/distributedfileservice/src/device/device_manager_agent.cpp index e73efb8e4..11bb75834 100644 --- a/services/distributedfileservice/src/device/device_manager_agent.cpp +++ b/services/distributedfileservice/src/device/device_manager_agent.cpp @@ -14,6 +14,7 @@ */ #include "device_manager_agent.h" +#include "distributedfile_service.h" #include "softbus_agent.h" #include "utils_exception.h" #include "utils_log.h" @@ -69,12 +70,12 @@ void DeviceManagerAgent::OnRemoteDied() void DeviceManagerAgent::RegisterToExternalDm() { auto &deviceManager = DistributedHardware::DeviceManager::GetInstance(); - int errCode = deviceManager.InitDeviceManager(pkgName_, shared_from_this()); + int errCode = deviceManager.InitDeviceManager(DistributedFileService::pkgName_, shared_from_this()); if (errCode != 0) { ThrowException(errCode, "Failed to InitDeviceManager"); } string extra = ""; - errCode = deviceManager.RegisterDevStateCallback(pkgName_, extra, shared_from_this()); + errCode = deviceManager.RegisterDevStateCallback(DistributedFileService::pkgName_, extra, shared_from_this()); if (errCode != 0) { ThrowException(errCode, "Failed to RegisterDevStateCallback"); } @@ -84,11 +85,11 @@ void DeviceManagerAgent::RegisterToExternalDm() void DeviceManagerAgent::UnregisterFromExternalDm() { auto &deviceManager = DistributedHardware::DeviceManager::GetInstance(); - int errCode = deviceManager.UnRegisterDevStateCallback(pkgName_); + int errCode = deviceManager.UnRegisterDevStateCallback(DistributedFileService::pkgName_); if (errCode != 0) { ThrowException(errCode, "Failed to UnRegisterDevStateCallback"); } - errCode = deviceManager.UnInitDeviceManager(pkgName_); + errCode = deviceManager.UnInitDeviceManager(DistributedFileService::pkgName_); if (errCode != 0) { ThrowException(errCode, "Failed to UnInitDeviceManager"); } diff --git a/services/distributedfileservice/src/ipc/distributedfile_service_stub.cpp b/services/distributedfileservice/src/ipc/distributedfile_service_stub.cpp index ad5649921..793918816 100644 --- a/services/distributedfileservice/src/ipc/distributedfile_service_stub.cpp +++ b/services/distributedfileservice/src/ipc/distributedfile_service_stub.cpp @@ -55,7 +55,7 @@ int DistributedFileServiceStub::test(MessageParcel &data, MessageParcel &reply) { LOGD(" DistributedFileServiceStub : sendTest enter"); sendTest(); - return 3; + return 0; } int32_t DistributedFileServiceStub::SendFileStub(MessageParcel &data, MessageParcel &reply) diff --git a/services/distributedfileservice/src/network/softbus_agent.cpp b/services/distributedfileservice/src/network/softbus_agent.cpp index d2416ede7..da2acb13d 100644 --- a/services/distributedfileservice/src/network/softbus_agent.cpp +++ b/services/distributedfileservice/src/network/softbus_agent.cpp @@ -19,6 +19,7 @@ #include #include #include "device_manager_agent.h" +#include "distributedfile_service.h" #include "session.h" #include "softbus_dispatcher.h" #include "utils_exception.h" @@ -220,15 +221,15 @@ void SoftbusAgent::RegisterSessionListener() .OnSessionOpened = SoftbusDispatcher::OnSessionOpened, .OnSessionClosed = SoftbusDispatcher::OnSessionClosed, }; - int ret = ::CreateSessionServer(pkgName_.c_str(), sessionName_.c_str(), &sessionListener); + int ret = ::CreateSessionServer(DistributedFileService::pkgName_.c_str(), sessionName_.c_str(), &sessionListener); if (ret != 0) { stringstream ss; ss << "Failed to CreateSessionServer, errno:" << ret; LOGE("%{public}s, sessionName:%{public}s", ss.str().c_str(), sessionName_.c_str()); return throw runtime_error(ss.str()); } - LOGD("Succeed to CreateSessionServer, pkgName %{public}s, sbusName:%{public}s", pkgName_.c_str(), - sessionName_.c_str()); + LOGD("Succeed to CreateSessionServer, pkgName %{public}s, sbusName:%{public}s", + DistributedFileService::pkgName_.c_str(), sessionName_.c_str()); } void SoftbusAgent::RegisterFileListener() @@ -237,21 +238,22 @@ void SoftbusAgent::RegisterFileListener() .OnSendFileFinished = SoftbusDispatcher::OnSendFileFinished, .OnFileTransError = SoftbusDispatcher::OnFileTransError, }; - int ret = ::SetFileSendListener(pkgName_.c_str(), sessionName_.c_str(), &fileSendListener); + std::string pkgName = DistributedFileService::pkgName_; + int ret = ::SetFileSendListener(pkgName.c_str(), sessionName_.c_str(), &fileSendListener); if (ret != 0) { stringstream ss; ss << "Failed to SetFileSendListener, errno:" << ret; LOGE("%{public}s, sessionName:%{public}s", ss.str().c_str(), sessionName_.c_str()); throw runtime_error(ss.str()); } - LOGD("Succeed to SetFileSendListener, pkgName %{public}s, sbusName:%{public}s", pkgName_.c_str(), + LOGD("Succeed to SetFileSendListener, pkgName %{public}s, sbusName:%{public}s", pkgName.c_str(), sessionName_.c_str()); IFileReceiveListener fileRecvListener = { .OnReceiveFileFinished = SoftbusDispatcher::OnReceiveFileFinished, .OnFileTransError = SoftbusDispatcher::OnFileTransError, }; - ret = ::SetFileReceiveListener(pkgName_.c_str(), sessionName_.c_str(), &fileRecvListener, + ret = ::SetFileReceiveListener(pkgName.c_str(), sessionName_.c_str(), &fileRecvListener, DEFAULT_ROOT_PATH.c_str()); if (ret != 0) { stringstream ss; @@ -259,12 +261,12 @@ void SoftbusAgent::RegisterFileListener() LOGE("%{public}s, sessionName:%{public}s", ss.str().c_str(), sessionName_.c_str()); throw runtime_error(ss.str()); } - LOGD("Succeed to SetFileReceiveListener, pkgName %{public}s, sbusName:%{public}s", pkgName_.c_str(), + LOGD("Succeed to SetFileReceiveListener, pkgName %{public}s, sbusName:%{public}s", pkgName.c_str(), sessionName_.c_str()); } void SoftbusAgent::UnRegisterSessionListener() { - int ret = ::RemoveSessionServer(pkgName_.c_str(), sessionName_.c_str()); + int ret = ::RemoveSessionServer(DistributedFileService::pkgName_.c_str(), sessionName_.c_str()); if (ret != 0) { stringstream ss; ss << "Failed to RemoveSessionServer, errno:" << ret; -- Gitee From 32d49090c6b9de92a25cbfdc030c71bb859701e2 Mon Sep 17 00:00:00 2001 From: nzb Date: Fri, 11 Feb 2022 22:34:40 +0800 Subject: [PATCH 14/14] format fix Signed-off-by: nzb --- services/distributedfileservice/BUILD.gn | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/services/distributedfileservice/BUILD.gn b/services/distributedfileservice/BUILD.gn index 7fad09192..a98b9383f 100644 --- a/services/distributedfileservice/BUILD.gn +++ b/services/distributedfileservice/BUILD.gn @@ -18,15 +18,15 @@ ohos_shared_library("libdistributedfileservice") { "include/ipc", "include/device", "include/network", - "//foundation/distributedhardware/devicemanager/interfaces/inner_kits/native_cpp/include" + "//foundation/distributedhardware/devicemanager/interfaces/inner_kits/native_cpp/include", ] sources = [ + "src/device/device_manager_agent.cpp", "src/ipc/distributedfile_service.cpp", "src/ipc/distributedfile_service_stub.cpp", - "src/device/device_manager_agent.cpp", "src/network/softbus_agent.cpp", - "src/network/softbus_dispatcher.cpp" + "src/network/softbus_dispatcher.cpp", ] configs = [ "${utils_path}:compiler_configs" ] @@ -41,7 +41,7 @@ ohos_shared_library("libdistributedfileservice") { deps = [ "${utils_path}:libdistributedfileutils", "../../interfaces/innerkits/native:libdistributedfile_innerkits", - "//foundation/distributedhardware/devicemanager/interfaces/inner_kits/native_cpp:devicemanagersdk" + "//foundation/distributedhardware/devicemanager/interfaces/inner_kits/native_cpp:devicemanagersdk", ] part_name = "dfs_service" -- Gitee