diff --git a/bundle.json b/bundle.json index 4a2cca14639c3bbd240ef2c3b14f940c7cd55d3b..481f80f96737fd79ac5c2c810853c0dbbe67f8ea 100644 --- a/bundle.json +++ b/bundle.json @@ -35,7 +35,11 @@ "sub_component": [ "//foundation/filemanagement/user_file_service/services:fms", "//foundation/filemanagement/user_file_service/services/sa_profile:filemanager_service_sa_profile", - "//foundation/filemanagement/user_file_service/interfaces/kits/js:filemanager" + "//foundation/filemanagement/user_file_service/interfaces/kits/js:filemanager", + "//foundation/filemanagement/user_file_service/frameworks/innerkits:frameworks_innerkits", + "//foundation/filemanagement/user_file_service/interfaces/kits/napi/file_access_module:fileaccess", + "//foundation/filemanagement/user_file_service/interfaces/kits/napi/file_access_ext_ability:fileaccessextensionability_napi", + "//foundation/filemanagement/user_file_service/interfaces/kits/napi/file_extension_info_module:fileextensioninfo" ], "test": [ "//foundation/filemanagement/user_file_service/services/test:user_file_manager_test" diff --git a/frameworks/innerkits/BUILD.gn b/frameworks/innerkits/BUILD.gn new file mode 100644 index 0000000000000000000000000000000000000000..832be4c93cd942b7a7a1595787483b4a7d0c7435 --- /dev/null +++ b/frameworks/innerkits/BUILD.gn @@ -0,0 +1,21 @@ +# Copyright (c) 2022 Huawei Device Co., Ltd. +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import("//build/ohos.gni") + +group("frameworks_innerkits") { + deps = [ + "file_access:file_access_extension_ability_kit", + "file_access:file_access_extension_ability_module", + ] +} \ No newline at end of file diff --git a/frameworks/innerkits/file_access/BUILD.gn b/frameworks/innerkits/file_access/BUILD.gn new file mode 100644 index 0000000000000000000000000000000000000000..1f3ec640eb075b5cc6ef1733366853e2fad677e2 --- /dev/null +++ b/frameworks/innerkits/file_access/BUILD.gn @@ -0,0 +1,117 @@ +# Copyright (c) 2022 Huawei Device Co., Ltd. +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import("//build/ohos.gni") +import("//foundation/filemanagement/user_file_service/filemanagement_aafwk.gni") + +BASE_DIR = "//foundation/filemanagement/user_file_service" + +config("ability_config") { + visibility = [ ":*" ] + include_dirs = [ + "include", + "${BASE_DIR}/utils", + "${aafwk_services_path}/common/include", + "${aafwk_kits_path}/ability/native/include/continuation/distributed", + "${aafwk_kits_path}/ability/native/include/continuation/kits", + "${aafwk_kits_path}/appkit/native/app/include", + "${aafwk_path}/frameworks/js/napi/aafwk/inner/napi_common", + "//foundation/appexecfwk/standard/interfaces/innerkits/appexecfwk_base/include", + ] + + cflags = [] + if (target_cpu == "arm") { + cflags += [ "-DBINDER_IPC_32BIT" ] + } +} + +config("ability_public_config") { + visibility = [ ":*" ] + include_dirs = [ + "include", + "${BASE_DIR}/utils", + "${aafwk_kits_path}/appkit/native/ability_runtime/app", + "${aafwk_kits_path}/appkit/native/app/include", + "${aafwk_kits_path}/appkit/native/ability_runtime/context", + ] +} + +ohos_shared_library("file_access_extension_ability_kit") { + include_dirs = [] + + sources = [ + "src/file_access_helper.cpp", + "src/file_access_ext_ability.cpp", + "src/file_access_ext_connection.cpp", + "src/file_access_ext_proxy.cpp", + "src/file_access_ext_stub.cpp", + "src/file_access_ext_stub_impl.cpp", + "src/js_file_access_ext_ability.cpp", + "src/napi_common_fileaccess.cpp" + ] + configs = [ ":ability_config" ] + public_configs = [ + ":ability_public_config", + "${aafwk_path}/frameworks/native/ability:ability_context_public_config", + ] + + deps = [ + "${aafwk_path}/frameworks/native/ability/native:abilitykit_native", + "${aafwk_path}/frameworks/native/appkit:app_context", + ] + + external_deps = [ + "ability_base:want", + "ability_base:zuri", + "ability_runtime:ability_context_native", + "ability_runtime:ability_manager", + "ability_runtime:app_manager", + "ability_runtime:runtime", + "ability_runtime:wantagent_innerkits", + "access_token:libaccesstoken_sdk", + "ipc:ipc_core", + "ipc_js:rpc", + "utils_base:utils", + ] + + public_deps = [ + "//base/hiviewdfx/hilog/interfaces/native/innerkits:libhilog", + "//foundation/arkui/napi:ace_napi", + ] + + subsystem_name = "filemanagement" + part_name = "user_file_service" +} + +ohos_shared_library("file_access_extension_ability_module") { + sources = [ "src/file_access_ext_ability_module_loader.cpp" ] + + configs = [ ":ability_config" ] + public_configs = [ ":ability_public_config" ] + + deps = [ + ":file_access_extension_ability_kit", + "${aafwk_path}/frameworks/native/ability/native:abilitykit_native", + ] + + external_deps = [ + "ability_base:want", + "ability_runtime:runtime", + "hiviewdfx_hilog_native:libhilog", + "utils_base:utils", + ] + + relative_install_dir = "extensionability/" + subsystem_name = "filemanagement" + part_name = "user_file_service" +} diff --git a/frameworks/innerkits/file_access/include/file_access_ext_ability.h b/frameworks/innerkits/file_access/include/file_access_ext_ability.h new file mode 100644 index 0000000000000000000000000000000000000000..709f66c1f0659b2464026824ae4921befaaf4c71 --- /dev/null +++ b/frameworks/innerkits/file_access/include/file_access_ext_ability.h @@ -0,0 +1,63 @@ +/* + * Copyright (c) 2022 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef FILE_EXT_ABILITY_H +#define FILE_EXT_ABILITY_H + +#include "extension_base.h" +#include "file_access_extension_info.h" + +namespace OHOS { +namespace AbilityRuntime { +class Runtime; +} +namespace FileAccessFwk { +using namespace AbilityRuntime; +class FileAccessExtAbility; +using CreatorFunc = std::function& runtime)>; +class FileAccessExtAbility : public ExtensionBase<> { +public: + FileAccessExtAbility() = default; + virtual ~FileAccessExtAbility() = default; + + virtual void Init(const std::shared_ptr &record, + const std::shared_ptr &application, + std::shared_ptr &handler, + const sptr &token) override; + + static FileAccessExtAbility* Create(const std::unique_ptr& runtime); + + virtual int OpenFile(const Uri &uri, int flags); + virtual int CreateFile(const Uri &parent, const std::string &displayName, Uri &newFile); + virtual int Mkdir(const Uri &parent, const std::string &displayName, Uri &newFile); + virtual int Delete(const Uri &sourceFile); + virtual int Move(const Uri &sourceFile, const Uri &targetParent, Uri &newFile); + virtual int Rename(const Uri &sourceFile, const std::string &displayName, Uri &newFile); + + virtual std::vector ListFile(const Uri &sourceFile); + virtual std::vector GetRoots(); + + /** + * @brief Set a creator function. + * + * @param creator The function for create a file extension ability. + */ + static void SetCreator(const CreatorFunc& creator); +private: + static CreatorFunc creator_; +}; +} // namespace FileAccessFwk +} // namespace OHOS +#endif // FILE_EXT_ABILITY_H \ No newline at end of file diff --git a/frameworks/innerkits/file_access/include/file_access_ext_ability_module_loader.h b/frameworks/innerkits/file_access/include/file_access_ext_ability_module_loader.h new file mode 100644 index 0000000000000000000000000000000000000000..598c3bb12e2e371f76d5f8380ff5487d8d63a95f --- /dev/null +++ b/frameworks/innerkits/file_access/include/file_access_ext_ability_module_loader.h @@ -0,0 +1,33 @@ +/* + * Copyright (c) 2022 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef FILE_EXT_ABILITY_MODULE_LOADER_H +#define FILE_EXT_ABILITY_MODULE_LOADER_H + +#include "extension_module_loader.h" +namespace OHOS { +namespace FileAccessFwk { +using namespace AbilityRuntime; +class FileAccessExtAbilityModuleLoader : public ExtensionModuleLoader, + public Singleton { + DECLARE_SINGLETON(FileAccessExtAbilityModuleLoader); + +public: + virtual Extension *Create(const std::unique_ptr& runtime) const override; + virtual std::map GetParams() override; +}; +} // namespace FileAccessFwk +} // namespace OHOS +#endif // FILE_EXT_ABILITY_MODULE_LOADER_H \ No newline at end of file diff --git a/frameworks/innerkits/file_access/include/file_access_ext_connection.h b/frameworks/innerkits/file_access/include/file_access_ext_connection.h new file mode 100644 index 0000000000000000000000000000000000000000..e47b0cffd9a9cd1cb0abdcc1414f3caf827135d0 --- /dev/null +++ b/frameworks/innerkits/file_access/include/file_access_ext_connection.h @@ -0,0 +1,56 @@ +/* + * Copyright (c) 2022 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef FILE_EXT_CONNECTION_H +#define FILE_EXT_CONNECTION_H + +#include + +#include "ability_connect_callback_stub.h" +#include "event_handler.h" +#include "ifile_access_ext_base.h" +#include "want.h" + +namespace OHOS { +namespace FileAccessFwk { +class FileAccessExtConnection : public AAFwk::AbilityConnectionStub { +public: + FileAccessExtConnection() = default; + virtual ~FileAccessExtConnection() = default; + + static sptr GetInstance(); + + void OnAbilityConnectDone( + const AppExecFwk::ElementName &element, const sptr &remoteObject, int resultCode) override; + + void OnAbilityDisconnectDone(const AppExecFwk::ElementName &element, int resultCode) override; + + void ConnectFileExtAbility(const AAFwk::Want &want, const sptr &token); + + void DisconnectFileExtAbility(); + + bool IsExtAbilityConnected(); + + sptr GetFileExtProxy(); + +private: + static sptr instance_; + static std::mutex mutex_; + std::atomic isConnected_ = {false}; + sptr fileExtProxy_; +}; +} // namespace FileAccessFwk +} // namespace OHOS +#endif // FILE_EXT_CONNECTION_H diff --git a/frameworks/innerkits/file_access/include/file_access_ext_proxy.h b/frameworks/innerkits/file_access/include/file_access_ext_proxy.h new file mode 100644 index 0000000000000000000000000000000000000000..51437ecfc4d7ae7b5a5a2a52a244db0a09a8591e --- /dev/null +++ b/frameworks/innerkits/file_access/include/file_access_ext_proxy.h @@ -0,0 +1,47 @@ +/* + * Copyright (c) 2022 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef FILE_EXT_PROXY_H +#define FILE_EXT_PROXY_H + +#include + +#include "file_access_extension_info.h" +#include "ifile_access_ext_base.h" + +namespace OHOS { +namespace FileAccessFwk { +class FileAccessExtProxy : public IRemoteProxy { +public: + explicit FileAccessExtProxy(const sptr& remote) : IRemoteProxy(remote) {} + + virtual ~FileAccessExtProxy() {} + + virtual int OpenFile(const Uri &uri, int flags) override; + virtual int CreateFile(const Uri &parent, const std::string &displayName, Uri &newFile) override; + virtual int Mkdir(const Uri &parent, const std::string &displayName, Uri &newFile) override; + virtual int Delete(const Uri &sourceFile) override; + virtual int Move(const Uri &sourceFile, const Uri &targetParent, Uri &newFile) override; + virtual int Rename(const Uri &sourceFile, const std::string &displayName, Uri &newFile) override; + + virtual std::vector ListFile(const Uri &sourceFile) override; + virtual std::vector GetRoots() override; +private: + static inline BrokerDelegator delegator_; +}; +} // namespace FileAccessFwk +} // namespace OHOS +#endif // FILE_EXT_PROXY_H + diff --git a/frameworks/innerkits/file_access/include/file_access_ext_stub.h b/frameworks/innerkits/file_access/include/file_access_ext_stub.h new file mode 100644 index 0000000000000000000000000000000000000000..ddcb2b7cb7d0f78768f3ff064869715bd10d72d0 --- /dev/null +++ b/frameworks/innerkits/file_access/include/file_access_ext_stub.h @@ -0,0 +1,49 @@ +/* + * Copyright (c) 2022 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef FILE_EXT_STUB_H +#define FILE_EXT_STUB_H + +#include +#include + +#include "file_access_extension_info.h" +#include "ifile_access_ext_base.h" + +namespace OHOS { +namespace FileAccessFwk { +class FileAccessExtStub : public IRemoteStub { +public: + FileAccessExtStub(); + ~FileAccessExtStub(); + int OnRemoteRequest(uint32_t code, MessageParcel& data, MessageParcel& reply, MessageOption& option) override; +private: + ErrCode CmdOpenFile(MessageParcel &data, MessageParcel &reply); + ErrCode CmdCreateFile(MessageParcel &data, MessageParcel &reply); + ErrCode CmdMkdir(MessageParcel &data, MessageParcel &reply); + ErrCode CmdDelete(MessageParcel &data, MessageParcel &reply); + ErrCode CmdMove(MessageParcel &data, MessageParcel &reply); + ErrCode CmdRename(MessageParcel &data, MessageParcel &reply); + + ErrCode CmdListFile(MessageParcel &data, MessageParcel &reply); + ErrCode CmdGetRoots(MessageParcel &data, MessageParcel &reply); + + using RequestFuncType = int (FileAccessExtStub::*)(MessageParcel &data, MessageParcel &reply); + std::map stubFuncMap_; +}; +} // namespace FileAccessFwk +} // namespace OHOS +#endif // FILE_EXT_STUB_H + diff --git a/frameworks/innerkits/file_access/include/file_access_ext_stub_impl.h b/frameworks/innerkits/file_access/include/file_access_ext_stub_impl.h new file mode 100644 index 0000000000000000000000000000000000000000..4abc888f9b55885bca6acdb86bd44c6e96303947 --- /dev/null +++ b/frameworks/innerkits/file_access/include/file_access_ext_stub_impl.h @@ -0,0 +1,51 @@ +/* + * Copyright (c) 2022 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef FILE_EXT_STUB_IMPL_H +#define FILE_EXT_STUB_IMPL_H + +#include +#include "file_access_ext_stub.h" +#include "file_access_extension_info.h" +#include "file_access_ext_ability.h" +#include "native_engine/native_value.h" + +namespace OHOS { +namespace FileAccessFwk { +class FileAccessExtStubImpl : public FileAccessExtStub { +public: + explicit FileAccessExtStubImpl(const std::shared_ptr& extension, napi_env env) + : extension_(extension) {} + + virtual ~FileAccessExtStubImpl() {} + + int OpenFile(const Uri &uri, int flags) override; + int CreateFile(const Uri &parent, const std::string &displayName, Uri &newFile) override; + int Mkdir(const Uri &parent, const std::string &displayName, Uri &newFile) override; + int Delete(const Uri &sourceFile) override; + int Move(const Uri &sourceFile, const Uri &targetParent, Uri &newFile) override; + int Rename(const Uri &sourceFile, const std::string &displayName, Uri &newFile) override; + + std::vector ListFile(const Uri &sourceFileUri) override; + std::vector GetRoots() override; +private: + std::shared_ptr GetOwner(); + +private: + std::shared_ptr extension_; +}; +} // namespace FileAccessFwk +} // namespace OHOS +#endif // FILE_EXT_STUB_IMPL_H diff --git a/frameworks/innerkits/file_access/include/file_access_extension_info.h b/frameworks/innerkits/file_access/include/file_access_extension_info.h new file mode 100644 index 0000000000000000000000000000000000000000..9cd7faaed4bad592e3a1240c2a59133c22eae884 --- /dev/null +++ b/frameworks/innerkits/file_access/include/file_access_extension_info.h @@ -0,0 +1,146 @@ +/* + * Copyright (c) 2022 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +#ifndef FILE_EXTENSION_INFO_H +#define FILE_EXTENSION_INFO_H + +#include +#include + +#include "parcel.h" +#include "uri.h" + +namespace OHOS { +namespace FileAccessFwk { +struct FileInfo : public virtual OHOS::Parcelable { +public: + Uri uri = Uri(""); + std::string fileName; + std::string mode; + int64_t size {0}; + int64_t mtime {0}; + std::string mimiType; + + bool ReadFromParcel(Parcel &parcel) + { + std::unique_ptr uriInfo(parcel.ReadParcelable()); + if (uriInfo == nullptr) { + return false; + } + uri = *uriInfo; + + fileName = parcel.ReadString(); + mode = parcel.ReadString(); + size = parcel.ReadUint64(); + mtime = parcel.ReadInt64(); + mimiType = parcel.ReadString(); + return true; + } + virtual bool Marshalling(Parcel &parcel) const override + { + if (!parcel.WriteParcelable(&uri)) { + return false; + } + if (!parcel.WriteString(fileName)) { + return false; + } + if (!parcel.WriteString(mode)) { + return false; + } + if (!parcel.WriteUint64(size)) { + return false; + } + if (!parcel.WriteInt64(mtime)) { + return false; + } + if (!parcel.WriteString(mimiType)) { + return false; + } + return true; + } + static FileInfo *Unmarshalling(Parcel &parcel) + { + FileInfo *info = new (std::nothrow) FileInfo(); + if (info == nullptr) { + return nullptr; + } + + if (!info->ReadFromParcel(parcel)) { + delete info; + info = nullptr; + } + return info; + } +}; + +struct DeviceInfo : public virtual OHOS::Parcelable { +public: + Uri uri = Uri(""); + std::string displayName; + std::string deviceId; + uint32_t flags {0}; + + bool ReadFromParcel(Parcel &parcel) + { + std::unique_ptr uriInfo(parcel.ReadParcelable()); + if (uriInfo == nullptr) { + return false; + } + uri = *uriInfo; + + displayName = parcel.ReadString(); + deviceId = parcel.ReadString(); + flags = parcel.ReadUint32(); + return true; + } + virtual bool Marshalling(Parcel &parcel) const override + { + if (!parcel.WriteParcelable(&uri)) { + return false; + } + if (!parcel.WriteString(displayName)) { + return false; + } + if (!parcel.WriteString(deviceId)) { + return false; + } + if (!parcel.WriteUint32(flags)) { + return false; + } + return true; + } + static DeviceInfo *Unmarshalling(Parcel &parcel) + { + DeviceInfo *info = new (std::nothrow) DeviceInfo(); + if (info == nullptr) { + return nullptr; + } + + if (!info->ReadFromParcel(parcel)) { + delete info; + info = nullptr; + } + return info; + } +}; + +const uint32_t FLAG_SUPPORTS_THUMBNAIL = 1; +const uint32_t FLAG_SUPPORTS_WRITE = 1 << 1; +const uint32_t FLAG_SUPPORTS_READ = 1 << 2; +const uint32_t FLAG_SUPPORTS_DELETE = 1 << 3; +const uint32_t FLAG_SUPPORTS_RENAME = 1 << 4; +const uint32_t FLAG_SUPPORTS_MOVE = 1 << 5; +} // namespace FileAccessFwk +} // namespace OHOS +#endif // FILE_EXTENSION_INFO_H \ No newline at end of file diff --git a/frameworks/innerkits/file_access/include/file_access_helper.h b/frameworks/innerkits/file_access/include/file_access_helper.h new file mode 100644 index 0000000000000000000000000000000000000000..4b7d424890ce3c051a4a37db95639f19b9da7b91 --- /dev/null +++ b/frameworks/innerkits/file_access/include/file_access_helper.h @@ -0,0 +1,85 @@ +/* + * Copyright (c) 2022 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef FILE_ACCESS_HELPER_H +#define FILE_ACCESS_HELPER_H + +#include +#include +#include + +#include "file_access_ext_connection.h" +#include "foundation/ability/ability_runtime/interfaces/kits/native/appkit/ability_runtime/context/context.h" +#include "ifile_access_ext_base.h" +#include "file_access_extension_info.h" +#include "uri.h" +#include "want.h" +#include "hilog_wrapper.h" + +using Uri = OHOS::Uri; + +namespace OHOS { +namespace FileAccessFwk { +using string = std::string; +class FileAccessHelper final : public std::enable_shared_from_this { +public: + ~FileAccessHelper() = default; + + static std::shared_ptr Creator(const std::shared_ptr &context, + const AAFwk::Want &want); + + static std::shared_ptr Creator(const sptr &token, const AAFwk::Want &want); + bool Release(); + int OpenFile(Uri &uri, int flags); + int CreateFile(Uri &parent, const std::string &displayName, Uri &newFile); + int Mkdir(Uri &parent, const std::string &displayName, Uri &newDir); + int Delete(Uri &selectFile); + int Move(Uri &sourceFile, Uri &targetParent, Uri &newFile); + int Rename(Uri &sourceFile, const std::string &displayName, Uri &newFile); + + std::vector ListFile(Uri &sourceFile); + std::vector GetRoots(); +private: + FileAccessHelper(const std::shared_ptr &context, const AAFwk::Want &want, + const sptr &fileAccessExtProxy); + FileAccessHelper(const sptr &token, + const AAFwk::Want &want, const sptr &fileAccessExtProxy); + void AddFileAccessDeathRecipient(const sptr &token); + void OnSchedulerDied(const wptr &remote); + + sptr token_ = {}; + AAFwk::Want want_ = {}; + sptr fileAccessExtProxy_ = nullptr; + bool isSystemCaller_ = false; + sptr callerDeathRecipient_ = nullptr; + sptr fileAccessExtConnection_ = nullptr; +}; + +class FileAccessDeathRecipient : public IRemoteObject::DeathRecipient { +public: + using RemoteDiedHandler = std::function &)>; + + explicit FileAccessDeathRecipient(RemoteDiedHandler handler); + + virtual ~FileAccessDeathRecipient(); + + virtual void OnRemoteDied(const wptr &remote); + +private: + RemoteDiedHandler handler_; +}; +} // namespace FileAccessFwk +} // namespace OHOS +#endif // FILE_ACCESS_HELPER_H diff --git a/frameworks/innerkits/file_access/include/ifile_access_ext_base.h b/frameworks/innerkits/file_access/include/ifile_access_ext_base.h new file mode 100644 index 0000000000000000000000000000000000000000..5c79a87b62b8fea0fa0cdb801b4171aeacd876d4 --- /dev/null +++ b/frameworks/innerkits/file_access/include/ifile_access_ext_base.h @@ -0,0 +1,56 @@ +/* + * Copyright (c) 2022 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef I_FILE_EXT_BASE_H +#define I_FILE_EXT_BASE_H + +#include +#include +#include +#include + +#include "file_access_extension_info.h" +#include "uri.h" + +namespace OHOS { +namespace FileAccessFwk { +class IFileAccessExtBase : public IRemoteBroker { +public: + DECLARE_INTERFACE_DESCRIPTOR(u"OHOS.FileAccessFwk.IFileAccessExtBase"); + + enum { + CMD_OPEN_FILE = 1, + CMD_CREATE_FILE = 2, + CMD_MKDIR = 3, + CMD_DELETE = 4, + CMD_MOVE = 5, + CMD_RENAME = 6, + CMD_LIST_FILE = 7, + CMD_GET_ROOTS = 8 + }; + + virtual int OpenFile(const Uri &uri, int flags) = 0; + virtual int CreateFile(const Uri &parent, const std::string &displayName, Uri &newFile) = 0; + virtual int Mkdir(const Uri &parent, const std::string &displayName, Uri &newFile) = 0; + virtual int Delete(const Uri &sourceFile) = 0; + virtual int Move(const Uri &sourceFile, const Uri &targetParent, Uri &newFile) = 0; + virtual int Rename(const Uri &sourceFile, const std::string &displayName, Uri &newFile) = 0; + + virtual std::vector ListFile(const Uri &sourceFile) = 0; + virtual std::vector GetRoots() = 0; +}; +} // namespace FileAccessFwk +} // namespace OHOS +#endif // I_FILE_EXT_BASE_H diff --git a/frameworks/innerkits/file_access/include/js_file_access_ext_ability.h b/frameworks/innerkits/file_access/include/js_file_access_ext_ability.h new file mode 100644 index 0000000000000000000000000000000000000000..78ddc4d866a3839a8219638492f8bd355c2238a2 --- /dev/null +++ b/frameworks/innerkits/file_access/include/js_file_access_ext_ability.h @@ -0,0 +1,79 @@ +/* + * Copyright (c) 2022 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef JS_FILE_EXT_ABILITY_H +#define JS_FILE_EXT_ABILITY_H + +#include "file_access_ext_ability.h" + +#include "napi_common_fileaccess.h" +#include "file_access_extension_info.h" +#include "js_runtime.h" +#include "native_engine/native_reference.h" +#include "native_engine/native_value.h" + +namespace OHOS { +namespace FileAccessFwk { +using namespace AbilityRuntime; +class JsFileAccessExtAbility : public FileAccessExtAbility { +public: + JsFileAccessExtAbility(JsRuntime& jsRuntime); + virtual ~JsFileAccessExtAbility() override; + + static JsFileAccessExtAbility* Create(const std::unique_ptr& runtime); + + void Init(const std::shared_ptr &record, + const std::shared_ptr &application, + std::shared_ptr &handler, + const sptr &token) override; + + void OnStart(const AAFwk::Want &want) override; + + sptr OnConnect(const AAFwk::Want &want) override; + + int OpenFile(const Uri &uri, int flags) override; + int CreateFile(const Uri &parent, const std::string &displayName, Uri &newFile) override; + int Mkdir(const Uri &parent, const std::string &displayName, Uri &newFile) override; + int Delete(const Uri &sourceFile) override; + int Move(const Uri &sourceFile, const Uri &targetParent, Uri &newFile) override; + int Rename(const Uri &sourceFile, const std::string &displayName, Uri &newFile) override; + + std::vector ListFile(const Uri &sourceFile) override; + std::vector GetRoots() override; +private: + struct ThreadLockInfo { + std::mutex mutex; + std::condition_variable condition; + bool ready = false; + }; + struct CallbackParam { + ThreadLockInfo *lockInfo; + JsRuntime& jsRuntime; + std::shared_ptr jsObj; + const char* name; + NativeValue* const* argv; + size_t argc; + NativeValue* result; + }; + NativeValue* AsnycCallObjectMethod(const char *name, NativeValue * const *argv = nullptr, size_t argc = 0); + NativeValue* CallObjectMethod(const char *name, NativeValue * const *argv = nullptr, size_t argc = 0); + void GetSrcPath(std::string &srcPath); + + JsRuntime& jsRuntime_; + std::shared_ptr jsObj_; +}; +} // namespace FileAccessFwk +} // namespace OHOS +#endif // JS_FILE_EXT_ABILITY_H \ No newline at end of file diff --git a/frameworks/innerkits/file_access/include/napi_common_fileaccess.h b/frameworks/innerkits/file_access/include/napi_common_fileaccess.h new file mode 100644 index 0000000000000000000000000000000000000000..1051b06d6b55bcc304fcb3bc27f0d2a60bc3d73d --- /dev/null +++ b/frameworks/innerkits/file_access/include/napi_common_fileaccess.h @@ -0,0 +1,54 @@ +/* + * Copyright (c) 2022 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef NAPI_COMMON_FILE_ACCESS_H +#define NAPI_COMMON_FILE_ACCESS_H + +#include +#include +#include + +#include "file_access_extension_info.h" +#include "napi_common_data.h" +#include "napi_common_util.h" + +namespace OHOS { +namespace FileAccessFwk { +bool UnwrapInt64ByPropertyName(napi_env env, napi_value param, const char *propertyName, int64_t &value); + +napi_value WrapUint32ToJS(napi_env env, uint32_t value); +uint32_t UnwrapUint32FromJS(napi_env env, napi_value param, uint32_t defaultValue = 0); +bool UnwrapUint32FromJS2(napi_env env, napi_value param, uint32_t &value); +bool UnwrapUint32ByPropertyName(napi_env env, napi_value param, const char *propertyName, uint32_t &value); + +napi_value WrapBigIntUint64ToJS(napi_env env, uint64_t value); +uint64_t UnwrapBigIntUint64FromJS(napi_env env, napi_value param, uint64_t defaultValue = 0); +bool UnwrapBigIntUint64FromJS2(napi_env env, napi_value param, uint64_t &defaultValue); +bool UnwrapBigIntUint64ByPropertyName(napi_env env, napi_value param, const char *propertyName, uint64_t &value); + +napi_value WrapFileInfo(napi_env env, const FileInfo &fileInfo); +bool UnwrapFileInfo(napi_env env, napi_value param, FileInfo &fileInfo); + +napi_value WrapArrayFileInfoToJS(napi_env env, const std::vector &fileInfoVec); +bool UnwrapArrayFileInfoFromJS(napi_env env, napi_value param, std::vector &fileInfoVec); + +napi_value WrapDeviceInfo(napi_env env, const DeviceInfo &deviceInfo); +bool UnwrapDeviceInfo(napi_env env, napi_value param, DeviceInfo &deviceInfo); + +napi_value WrapArrayDeviceInfoToJS(napi_env env, const std::vector &deviceInfoVec); +bool UnwrapArrayDeviceInfoFromJS(napi_env env, napi_value param, std::vector &deviceInfoVec); +} // namespace FileAccessFwk +} // namespace OHOS +#endif // NAPI_COMMON_FILE_ACCESS_H diff --git a/frameworks/innerkits/file_access/src/file_access_ext_ability.cpp b/frameworks/innerkits/file_access/src/file_access_ext_ability.cpp new file mode 100644 index 0000000000000000000000000000000000000000..0e5dba598649fc870031d9b90db7c75c794f6958 --- /dev/null +++ b/frameworks/innerkits/file_access/src/file_access_ext_ability.cpp @@ -0,0 +1,102 @@ +/* + * Copyright (c) 2022 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "file_access_ext_ability.h" + +#include "ability_loader.h" +#include "connection_manager.h" +#include "extension_context.h" +#include "hilog_wrapper.h" +#include "js_file_access_ext_ability.h" +#include "runtime.h" + +namespace OHOS { +namespace FileAccessFwk { +using namespace OHOS::AppExecFwk; + +CreatorFunc FileAccessExtAbility::creator_ = nullptr; +void FileAccessExtAbility::SetCreator(const CreatorFunc& creator) +{ + creator_ = creator; +} + +FileAccessExtAbility* FileAccessExtAbility::Create(const std::unique_ptr& runtime) +{ + if (!runtime) { + return new FileAccessExtAbility(); + } + if (creator_) { + return creator_(runtime); + } + switch (runtime->GetLanguage()) { + case Runtime::Language::JS: + return JsFileAccessExtAbility::Create(runtime); + + default: + return new FileAccessExtAbility(); + } +} + +void FileAccessExtAbility::Init(const std::shared_ptr &record, + const std::shared_ptr &application, + std::shared_ptr &handler, + const sptr &token) +{ + ExtensionBase<>::Init(record, application, handler, token); +} + +int FileAccessExtAbility::OpenFile(const Uri &uri, int flags) +{ + return 0; +} + +int FileAccessExtAbility::CreateFile(const Uri &parent, const std::string &displayName, Uri &newFile) +{ + return 0; +} + +int FileAccessExtAbility::Mkdir(const Uri &parent, const std::string &displayName, Uri &newFile) +{ + return 0; +} + +int FileAccessExtAbility::Delete(const Uri &sourceFile) +{ + return 0; +} + +int FileAccessExtAbility::Move(const Uri &sourceFile, const Uri &targetParent, Uri &newFile) +{ + return 0; +} + +int FileAccessExtAbility::Rename(const Uri &sourceFile, const std::string &displayName, Uri &newFile) +{ + return 0; +} + +std::vector FileAccessExtAbility::ListFile(const Uri &sourceFile) +{ + std::vector vec; + return vec; +} + +std::vector FileAccessExtAbility::GetRoots() +{ + std::vector vec; + return vec; +} +} // namespace FileAccessFwk +} // namespace OHOS \ No newline at end of file diff --git a/frameworks/innerkits/file_access/src/file_access_ext_ability_module_loader.cpp b/frameworks/innerkits/file_access/src/file_access_ext_ability_module_loader.cpp new file mode 100644 index 0000000000000000000000000000000000000000..2c95fc8c2f194b037e43815a73095f9f43c0beb5 --- /dev/null +++ b/frameworks/innerkits/file_access/src/file_access_ext_ability_module_loader.cpp @@ -0,0 +1,47 @@ +/* + * Copyright (c) 2022 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "file_access_ext_ability_module_loader.h" +#include "file_access_ext_ability.h" + +namespace OHOS { +namespace FileAccessFwk { +FileAccessExtAbilityModuleLoader::FileAccessExtAbilityModuleLoader() = default; +FileAccessExtAbilityModuleLoader::~FileAccessExtAbilityModuleLoader() = default; + +Extension *FileAccessExtAbilityModuleLoader::Create(const std::unique_ptr& runtime) const +{ + return FileAccessExtAbility::Create(runtime); +} + +extern "C" __attribute__((visibility("default"))) void* OHOS_EXTENSION_GetExtensionModule() +{ + return &FileAccessExtAbilityModuleLoader::GetInstance(); +} + +extern "C" __attribute__((visibility("default"))) void SetCreator(const CreatorFunc& creator) +{ + return FileAccessExtAbility::SetCreator(creator); +} + +std::map FileAccessExtAbilityModuleLoader::GetParams() +{ + std::map params; + params.insert(std::pair("type", "11")); + params.insert(std::pair("name", "FileAccessExtension")); + return params; +} +} // namespace FileAccessFwk +} // namespace OHOS \ No newline at end of file diff --git a/frameworks/innerkits/file_access/src/file_access_ext_connection.cpp b/frameworks/innerkits/file_access/src/file_access_ext_connection.cpp new file mode 100644 index 0000000000000000000000000000000000000000..d4430661459d0e4a16879c8e582ea9f99723dc97 --- /dev/null +++ b/frameworks/innerkits/file_access/src/file_access_ext_connection.cpp @@ -0,0 +1,83 @@ +/* + * Copyright (c) 2022 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "file_access_ext_connection.h" + +#include "ability_manager_client.h" +#include "hilog_wrapper.h" +#include "file_access_ext_proxy.h" + +namespace OHOS { +namespace FileAccessFwk { +sptr FileAccessExtConnection::instance_ = nullptr; +std::mutex FileAccessExtConnection::mutex_; + +sptr FileAccessExtConnection::GetInstance() +{ + if (instance_ == nullptr) { + std::lock_guard lock(mutex_); + if (instance_ == nullptr) { + instance_ = sptr(new (std::nothrow) FileAccessExtConnection()); + } + } + return instance_; +} + +void FileAccessExtConnection::OnAbilityConnectDone( + const AppExecFwk::ElementName &element, const sptr &remoteObject, int resultCode) +{ + if (remoteObject == nullptr) { + HILOG_ERROR("%{public}s failed, remote is nullptr", __func__); + return; + } + fileExtProxy_ = iface_cast(remoteObject); + if (fileExtProxy_ == nullptr) { + HILOG_ERROR("%{public}s failed, fileExtProxy_ is nullptr", __func__); + return; + } + isConnected_.store(true); +} + +void FileAccessExtConnection::OnAbilityDisconnectDone(const AppExecFwk::ElementName &element, int resultCode) +{ + fileExtProxy_ = nullptr; + isConnected_.store(false); +} + +void FileAccessExtConnection::ConnectFileExtAbility(const AAFwk::Want &want, const sptr &token) +{ + ErrCode ret = AAFwk::AbilityManagerClient::GetInstance()->ConnectAbility(want, this, token); + HILOG_INFO("%{public}s called end, ret=%{public}d", __func__, ret); +} + +void FileAccessExtConnection::DisconnectFileExtAbility() +{ + fileExtProxy_ = nullptr; + isConnected_.store(false); + ErrCode ret = AAFwk::AbilityManagerClient::GetInstance()->DisconnectAbility(this); + HILOG_INFO("%{public}s called end, ret=%{public}d", __func__, ret); +} + +bool FileAccessExtConnection::IsExtAbilityConnected() +{ + return isConnected_.load(); +} + +sptr FileAccessExtConnection::GetFileExtProxy() +{ + return fileExtProxy_; +} +} // namespace FileAccessFwk +} // namespace OHOS \ No newline at end of file diff --git a/frameworks/innerkits/file_access/src/file_access_ext_proxy.cpp b/frameworks/innerkits/file_access/src/file_access_ext_proxy.cpp new file mode 100644 index 0000000000000000000000000000000000000000..98c95cc300aa1c24f468a71db6510c4de3934abf --- /dev/null +++ b/frameworks/innerkits/file_access/src/file_access_ext_proxy.cpp @@ -0,0 +1,347 @@ +/* + * Copyright (c) 2022 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "file_access_ext_proxy.h" + +#include "hilog_wrapper.h" + +namespace OHOS { +namespace FileAccessFwk { +int FileAccessExtProxy::OpenFile(const Uri &uri, int flags) +{ + int fd = -1; + MessageParcel data; + if (!data.WriteInterfaceToken(FileAccessExtProxy::GetDescriptor())) { + HILOG_ERROR("%{public}s WriteInterfaceToken failed", __func__); + return fd; + } + + if (!data.WriteParcelable(&uri)) { + HILOG_ERROR("%{public}s fail to WriteParcelable uri", __func__); + return fd; + } + + if (!data.WriteInt32(flags)) { + HILOG_ERROR("%{public}s fail to WriteString mode", __func__); + return fd; + } + + MessageParcel reply; + MessageOption option; + int32_t err = Remote()->SendRequest(CMD_OPEN_FILE, data, reply, option); + if (err != NO_ERROR) { + HILOG_ERROR("%{public}s fail to SendRequest. err: %d", __func__, err); + return fd; + } + + fd = reply.ReadFileDescriptor(); + if (fd == -1) { + HILOG_ERROR("%{public}s fail to ReadFileDescriptor fd", __func__); + return fd; + } + return fd; +} + +int FileAccessExtProxy::CreateFile(const Uri &parent, const std::string &displayName, Uri &newFile) +{ + int ret = -1; + MessageParcel data; + if (!data.WriteInterfaceToken(FileAccessExtProxy::GetDescriptor())) { + HILOG_ERROR("%{public}s WriteInterfaceToken failed", __func__); + return ret; + } + + if (!data.WriteParcelable(&parent)) { + HILOG_ERROR("%{public}s fail to WriteParcelable parent", __func__); + return ret; + } + + if (!data.WriteString(displayName)) { + HILOG_ERROR("%{public}s fail to WriteString mode", __func__); + return ret; + } + + if (!data.WriteParcelable(&newFile)) { + HILOG_ERROR("%{public}s fail to WriteParcelable newFile", __func__); + return ret; + } + + MessageParcel reply; + MessageOption option; + int32_t err = Remote()->SendRequest(CMD_CREATE_FILE, data, reply, option); + if (err != NO_ERROR) { + HILOG_ERROR("%{public}s fail to SendRequest. err: %d", __func__, err); + return ret; + } + + ret = reply.ReadInt32(); + if (ret < 0) { + HILOG_ERROR("%{public}s fail to ReadInt32 ret", __func__); + return ret; + } + + std::unique_ptr tempUri(reply.ReadParcelable()); + if (!tempUri) { + HILOG_ERROR("%{public}s ReadParcelable value is nullptr.", __func__); + ret = -1; + return ret; + } + + newFile = Uri(*tempUri); + return ret; +} + +int FileAccessExtProxy::Mkdir(const Uri &parent, const std::string &displayName, Uri &newFile) +{ + int ret = -1; + MessageParcel data; + if (!data.WriteInterfaceToken(FileAccessExtProxy::GetDescriptor())) { + HILOG_ERROR("%{public}s WriteInterfaceToken failed", __func__); + return ret; + } + + if (!data.WriteParcelable(&parent)) { + HILOG_ERROR("%{public}s fail to WriteParcelable parent", __func__); + return ret; + } + + if (!data.WriteString(displayName)) { + HILOG_ERROR("%{public}s fail to WriteString displayName", __func__); + return ret; + } + + if (!data.WriteParcelable(&newFile)) { + HILOG_ERROR("%{public}s fail to WriteParcelable newFile", __func__); + return ret; + } + + MessageParcel reply; + MessageOption option; + int32_t err = Remote()->SendRequest(CMD_MKDIR, data, reply, option); + if (err != NO_ERROR) { + HILOG_ERROR("%{public}s fail to SendRequest. err: %d", __func__, err); + return ret; + } + + ret = reply.ReadInt32(); + if (ret < 0) { + HILOG_ERROR("%{public}s fail to ReadInt32 ret", __func__); + return ret; + } + + std::unique_ptr tempUri(reply.ReadParcelable()); + if (!tempUri) { + HILOG_ERROR("%{public}s ReadParcelable value is nullptr.", __func__); + ret = -1; + return ret; + } + + newFile = Uri(*tempUri); + return ret; +} + +int FileAccessExtProxy::Delete(const Uri &sourceFile) +{ + int ret = -1; + MessageParcel data; + if (!data.WriteInterfaceToken(FileAccessExtProxy::GetDescriptor())) { + HILOG_ERROR("%{public}s WriteInterfaceToken failed", __func__); + return ret; + } + + if (!data.WriteParcelable(&sourceFile)) { + HILOG_ERROR("%{public}s fail to WriteParcelable sourceFile", __func__); + return ret; + } + + MessageParcel reply; + MessageOption option; + int32_t err = Remote()->SendRequest(CMD_DELETE, data, reply, option); + if (err != NO_ERROR) { + HILOG_ERROR("%{public}s fail to SendRequest. err: %d", __func__, err); + return ret; + } + + ret = reply.ReadInt32(); + if (ret < 0) { + HILOG_ERROR("%{public}s fail to ReadInt32 ret", __func__); + return ret; + } + + return ret; +} + +int FileAccessExtProxy::Move(const Uri &sourceFile, const Uri &targetParent, Uri &newFile) +{ + int ret = -1; + MessageParcel data; + if (!data.WriteInterfaceToken(FileAccessExtProxy::GetDescriptor())) { + HILOG_ERROR("tag dsa %{public}s WriteInterfaceToken failed", __func__); + return ret; + } + + if (!data.WriteParcelable(&sourceFile)) { + HILOG_ERROR("tag dsa %{public}s fail to WriteParcelable sourceFile", __func__); + return ret; + } + + if (!data.WriteParcelable(&targetParent)) { + HILOG_ERROR("tag dsa %{public}s fail to WriteParcelable targetParent", __func__); + return ret; + } + + if (!data.WriteParcelable(&newFile)) { + HILOG_ERROR("tag dsa %{public}s fail to WriteParcelable newFile", __func__); + return ret; + } + + MessageParcel reply; + MessageOption option; + int32_t err = Remote()->SendRequest(CMD_MOVE, data, reply, option); + if (err != NO_ERROR) { + HILOG_ERROR("tag dsa %{public}s fail to SendRequest. err: %d", __func__, err); + return ret; + } + + ret = reply.ReadInt32(); + if (ret < 0) { + HILOG_ERROR("tag dsa %{public}s fail to ReadInt32 ret", __func__); + return ret; + } + + std::unique_ptr tempUri(reply.ReadParcelable()); + if (!tempUri) { + HILOG_ERROR("tag dsa %{public}s ReadParcelable value is nullptr.", __func__); + ret = -1; + return ret; + } + + newFile = Uri(*tempUri); + return ret; +} + +int FileAccessExtProxy::Rename(const Uri &sourceFile, const std::string &displayName, Uri &newFile) +{ + int ret = -1; + MessageParcel data; + if (!data.WriteInterfaceToken(FileAccessExtProxy::GetDescriptor())) { + HILOG_ERROR("%{public}s WriteInterfaceToken failed", __func__); + return ret; + } + + if (!data.WriteParcelable(&sourceFile)) { + HILOG_ERROR("%{public}s fail to WriteParcelable sourceFile", __func__); + return ret; + } + + if (!data.WriteString(displayName)) { + HILOG_ERROR("%{public}s fail to WriteString displayName", __func__); + return ret; + } + + if (!data.WriteParcelable(&newFile)) { + HILOG_ERROR("%{public}s fail to WriteParcelable newFile", __func__); + return ret; + } + + MessageParcel reply; + MessageOption option; + int32_t err = Remote()->SendRequest(CMD_RENAME, data, reply, option); + if (err != NO_ERROR) { + HILOG_ERROR("%{public}s fail to SendRequest. err: %d", __func__, err); + return ret; + } + + ret = reply.ReadInt32(); + if (ret < 0) { + HILOG_ERROR("%{public}s fail to ReadInt32 ret", __func__); + return ret; + } + + std::unique_ptr tempUri(reply.ReadParcelable()); + if (!tempUri) { + HILOG_ERROR("%{public}s ReadParcelable value is nullptr.", __func__); + ret = -1; + return ret; + } + + newFile = Uri(*tempUri); + return ret; +} + +std::vector FileAccessExtProxy::ListFile(const Uri &sourceFile) +{ + std::vector vec; + MessageParcel data; + if (!data.WriteInterfaceToken(FileAccessExtProxy::GetDescriptor())) { + HILOG_ERROR("%{public}s WriteInterfaceToken failed", __func__); + return vec; + } + + if (!data.WriteParcelable(&sourceFile)) { + HILOG_ERROR("%{public}s fail to WriteParcelable sourceFileUri", __func__); + return vec; + } + + MessageParcel reply; + MessageOption option; + int32_t err = Remote()->SendRequest(CMD_LIST_FILE, data, reply, option); + if (err != NO_ERROR) { + HILOG_ERROR("%{public}s fail to SendRequest. err: %d", __func__, err); + return vec; + } + + vec.clear(); + int64_t count = reply.ReadInt64(); + for (int32_t i = 0; i < count; i++) { + std::unique_ptr fileInfo(reply.ReadParcelable()); + if (fileInfo != nullptr) { + vec.push_back(*fileInfo); + } + } + + return vec; +} + +std::vector FileAccessExtProxy::GetRoots() +{ + std::vector vec; + MessageParcel data; + if (!data.WriteInterfaceToken(FileAccessExtProxy::GetDescriptor())) { + HILOG_ERROR("%{public}s WriteInterfaceToken failed", __func__); + return vec; + } + + MessageParcel reply; + MessageOption option; + int32_t err = Remote()->SendRequest(CMD_GET_ROOTS, data, reply, option); + if (err != NO_ERROR) { + HILOG_ERROR("%{public}s fail to SendRequest. err: %d", __func__, err); + return vec; + } + + vec.clear(); + uint64_t count = reply.ReadUint64(); + for (uint64_t i = 0; i < count; i++) { + std::unique_ptr deviceInfo(reply.ReadParcelable()); + if (deviceInfo != nullptr) { + vec.push_back(*deviceInfo); + } + } + + return vec; +} +} // namespace FileAccessFwk +} // namespace OHOS diff --git a/frameworks/innerkits/file_access/src/file_access_ext_stub.cpp b/frameworks/innerkits/file_access/src/file_access_ext_stub.cpp new file mode 100644 index 0000000000000000000000000000000000000000..d0a014078fce117db3e41eec5a0977d2ffa9a3ab --- /dev/null +++ b/frameworks/innerkits/file_access/src/file_access_ext_stub.cpp @@ -0,0 +1,290 @@ +/* + * Copyright (c) 2022 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "file_access_ext_stub.h" + +#include "hilog_wrapper.h" + +namespace OHOS { +namespace FileAccessFwk { +FileAccessExtStub::FileAccessExtStub() +{ + stubFuncMap_[CMD_OPEN_FILE] = &FileAccessExtStub::CmdOpenFile; + stubFuncMap_[CMD_CREATE_FILE] = &FileAccessExtStub::CmdCreateFile; + stubFuncMap_[CMD_MKDIR] = &FileAccessExtStub::CmdMkdir; + stubFuncMap_[CMD_DELETE] = &FileAccessExtStub::CmdDelete; + stubFuncMap_[CMD_MOVE] = &FileAccessExtStub::CmdMove; + stubFuncMap_[CMD_RENAME] = &FileAccessExtStub::CmdRename; + stubFuncMap_[CMD_LIST_FILE] = &FileAccessExtStub::CmdListFile; + stubFuncMap_[CMD_GET_ROOTS] = &FileAccessExtStub::CmdGetRoots; +} + +FileAccessExtStub::~FileAccessExtStub() +{ + stubFuncMap_.clear(); +} + +int FileAccessExtStub::OnRemoteRequest(uint32_t code, MessageParcel& data, MessageParcel& reply, + MessageOption& option) +{ + std::u16string descriptor = FileAccessExtStub::GetDescriptor(); + std::u16string remoteDescriptor = data.ReadInterfaceToken(); + if (descriptor != remoteDescriptor) { + return ERR_INVALID_STATE; + } + + const auto &itFunc = stubFuncMap_.find(code); + if (itFunc != stubFuncMap_.end()) { + return (this->*(itFunc->second))(data, reply); + } + + return IPCObjectStub::OnRemoteRequest(code, data, reply, option); +} + +ErrCode FileAccessExtStub::CmdOpenFile(MessageParcel &data, MessageParcel &reply) +{ + std::shared_ptr uri(data.ReadParcelable()); + if (uri == nullptr) { + HILOG_ERROR("%{public}s uri is nullptr", __func__); + return ERR_INVALID_VALUE; + } + int flags = data.ReadInt32(); + if (flags < 0) { + HILOG_ERROR("%{public}s mode is invalid", __func__); + return ERR_INVALID_VALUE; + } + int fd = OpenFile(*uri, flags); + if (fd < 0) { + HILOG_ERROR("%{public}s OpenFile fail, fd is %{pubilc}d", __func__, fd); + return ERR_INVALID_VALUE; + } + + if (!reply.WriteFileDescriptor(fd)) { + HILOG_ERROR("%{public}s fail to WriteFileDescriptor fd", __func__); + return ERR_INVALID_VALUE; + } + return NO_ERROR; +} + +ErrCode FileAccessExtStub::CmdCreateFile(MessageParcel &data, MessageParcel &reply) +{ + std::shared_ptr parent(data.ReadParcelable()); + if (parent == nullptr) { + HILOG_ERROR("%{public}s parent is nullptr", __func__); + return ERR_INVALID_VALUE; + } + std::string displayName = data.ReadString(); + if (displayName.empty()) { + HILOG_ERROR("%{public}s mode is nullptr", __func__); + return ERR_INVALID_VALUE; + } + std::shared_ptr fileNew(data.ReadParcelable()); + if (fileNew == nullptr) { + HILOG_ERROR("%{public}s fileNew is nullptr", __func__); + return ERR_INVALID_VALUE; + } + + int ret = CreateFile(*parent, displayName, *fileNew); + if (ret < 0) { + HILOG_ERROR("%{public}s CreateFile fail, ret is %{pubilc}d", __func__, ret); + return ERR_INVALID_VALUE; + } + + if (!reply.WriteInt32(ret)) { + HILOG_ERROR("%{public}s fail to WriteInt32 ret", __func__); + return ERR_INVALID_VALUE; + } + + if (!reply.WriteParcelable(&(*fileNew))) { + HILOG_ERROR("%{public}s fail to WriteParcelable type", __func__); + return ERR_INVALID_VALUE; + } + return NO_ERROR; +} + +ErrCode FileAccessExtStub::CmdMkdir(MessageParcel &data, MessageParcel &reply) +{ + std::shared_ptr parent(data.ReadParcelable()); + if (parent == nullptr) { + HILOG_ERROR("%{public}s parent is nullptr", __func__); + return ERR_INVALID_VALUE; + } + std::string displayName = data.ReadString(); + if (displayName.empty()) { + HILOG_ERROR("%{public}s mode is nullptr", __func__); + return ERR_INVALID_VALUE; + } + std::shared_ptr fileNew(data.ReadParcelable()); + if (fileNew == nullptr) { + HILOG_ERROR("%{public}s fileNew is nullptr", __func__); + return ERR_INVALID_VALUE; + } + + int ret = Mkdir(*parent, displayName, *fileNew); + if (ret < 0) { + HILOG_ERROR("%{public}s Mkdir fail, ret is %{pubilc}d", __func__, ret); + return ERR_INVALID_VALUE; + } + + if (!reply.WriteInt32(ret)) { + HILOG_ERROR("%{public}s fail to WriteInt32 ret", __func__); + return ERR_INVALID_VALUE; + } + + if (!reply.WriteParcelable(&(*fileNew))) { + HILOG_ERROR("%{public}s fail to WriteParcelable type", __func__); + return ERR_INVALID_VALUE; + } + return NO_ERROR; +} + +ErrCode FileAccessExtStub::CmdDelete(MessageParcel &data, MessageParcel &reply) +{ + std::shared_ptr uri(data.ReadParcelable()); + if (uri == nullptr) { + HILOG_ERROR("%{public}s uri is nullptr", __func__); + return ERR_INVALID_VALUE; + } + + int ret = Delete(*uri); + if (ret < 0) { + HILOG_ERROR("%{public}s Delete fail, ret is %{pubilc}d", __func__, ret); + return ERR_INVALID_VALUE; + } + + if (!reply.WriteInt32(ret)) { + HILOG_ERROR("%{public}s fail to WriteFileDescriptor ret", __func__); + return ERR_INVALID_VALUE; + } + return NO_ERROR; +} + +ErrCode FileAccessExtStub::CmdMove(MessageParcel &data, MessageParcel &reply) +{ + std::shared_ptr sourceFile(data.ReadParcelable()); + if (sourceFile == nullptr) { + HILOG_ERROR("tag dsa %{public}s sourceFile is nullptr", __func__); + return ERR_INVALID_VALUE; + } + std::shared_ptr targetParent(data.ReadParcelable()); + if (targetParent == nullptr) { + HILOG_ERROR("tag dsa %{public}s targetParent is nullptr", __func__); + return ERR_INVALID_VALUE; + } + std::shared_ptr fileNew(data.ReadParcelable()); + if (fileNew == nullptr) { + HILOG_ERROR("tag dsa %{public}s fileNew is nullptr", __func__); + return ERR_INVALID_VALUE; + } + + int ret = Move(*sourceFile, *targetParent, *fileNew); + if (ret < 0) { + HILOG_ERROR("tag dsa %{public}s fail, ret is %{pubilc}d", __func__, ret); + return ERR_INVALID_VALUE; + } + + if (!reply.WriteInt32(ret)) { + HILOG_ERROR("tag dsa %{public}s fail to WriteInt32 ret", __func__); + return ERR_INVALID_VALUE; + } + + if (!reply.WriteParcelable(&(*fileNew))) { + HILOG_ERROR("tag dsa %{public}s fail to WriteParcelable type", __func__); + return ERR_INVALID_VALUE; + } + return NO_ERROR; +} + +ErrCode FileAccessExtStub::CmdRename(MessageParcel &data, MessageParcel &reply) +{ + std::shared_ptr sourceFile(data.ReadParcelable()); + if (sourceFile == nullptr) { + HILOG_ERROR("%{public}s sourceFileUri is nullptr", __func__); + return ERR_INVALID_VALUE; + } + std::string displayName = data.ReadString(); + if (displayName.empty()) { + HILOG_ERROR("%{public}s mode is nullptr", __func__); + return ERR_INVALID_VALUE; + } + std::shared_ptr fileNew(data.ReadParcelable()); + if (fileNew == nullptr) { + HILOG_ERROR("%{public}s fileUriNew is nullptr", __func__); + return ERR_INVALID_VALUE; + } + + int ret = Rename(*sourceFile, displayName, *fileNew); + if (ret < 0) { + HILOG_ERROR("%{public}s Rename fail, ret is %{pubilc}d", __func__, ret); + return ERR_INVALID_VALUE; + } + + if (!reply.WriteInt32(ret)) { + HILOG_ERROR("%{public}s fail to WriteInt32 ret", __func__); + return ERR_INVALID_VALUE; + } + + if (!reply.WriteParcelable(&(*fileNew))) { + HILOG_ERROR("%{public}s fail to WriteParcelable type", __func__); + return ERR_INVALID_VALUE; + } + + return NO_ERROR; +} + +ErrCode FileAccessExtStub::CmdListFile(MessageParcel &data, MessageParcel &reply) +{ + std::shared_ptr uri(data.ReadParcelable()); + if (uri == nullptr) { + HILOG_ERROR("%{public}s uri is nullptr", __func__); + return ERR_INVALID_VALUE; + } + + std::vector vec = ListFile(*uri); + uint64_t count {vec.size()}; + if (!reply.WriteUint64(count)) { + HILOG_ERROR("%{public}s fail to WriteInt32 count", __func__); + return ERR_INVALID_VALUE; + } + for (uint64_t i = 0; i < count; i++) { + if (!reply.WriteParcelable(&vec[i])) { + HILOG_ERROR("%{public}s fail to WriteParcelable vec", __func__); + return ERR_INVALID_VALUE; + } + } + + return NO_ERROR; +} + +ErrCode FileAccessExtStub::CmdGetRoots(MessageParcel &data, MessageParcel &reply) +{ + + std::vector vec = GetRoots(); + uint64_t count {vec.size()}; + if (!reply.WriteUint64(count)) { + HILOG_ERROR("%{public}s fail to WriteInt32 count", __func__); + return ERR_INVALID_VALUE; + } + for (uint64_t i = 0; i < count; i++) { + if (!reply.WriteParcelable(&vec[i])) { + HILOG_ERROR("%{public}s fail to WriteParcelable ret", __func__); + return ERR_INVALID_VALUE; + } + } + + return NO_ERROR; +} +} // namespace FileAccessFwk +} // namespace OHOS diff --git a/frameworks/innerkits/file_access/src/file_access_ext_stub_impl.cpp b/frameworks/innerkits/file_access/src/file_access_ext_stub_impl.cpp new file mode 100644 index 0000000000000000000000000000000000000000..9ffac663a13914ab38180b7212ee8a14f5fb81ab --- /dev/null +++ b/frameworks/innerkits/file_access/src/file_access_ext_stub_impl.cpp @@ -0,0 +1,123 @@ +/* + * Copyright (c) 2022 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "file_access_ext_stub_impl.h" + +#include "hilog_wrapper.h" + +namespace OHOS { +namespace FileAccessFwk { +std::shared_ptr FileAccessExtStubImpl::GetOwner() +{ + return extension_; +} + +int FileAccessExtStubImpl::OpenFile(const Uri &uri, int flags) +{ + int ret = -1; + auto extension = GetOwner(); + if (extension == nullptr) { + HILOG_ERROR("%{public}s end failed.", __func__); + return ret; + } + ret = extension->OpenFile(uri, flags); + return ret; +} + +int FileAccessExtStubImpl::CreateFile(const Uri &parent, const std::string &displayName, Uri &newFile) +{ + int ret = -1; + auto extension = GetOwner(); + if (extension == nullptr) { + HILOG_ERROR("%{public}s end failed.", __func__); + return ret; + } + ret = extension->CreateFile(parent, displayName, newFile); + return ret; +} + +int FileAccessExtStubImpl::Mkdir(const Uri &parent, const std::string &displayName, Uri &newFile) +{ + int ret = -1; + auto extension = GetOwner(); + if (extension == nullptr) { + HILOG_ERROR("%{public}s end failed.", __func__); + return ret; + } + ret = extension->Mkdir(parent, displayName, newFile); + return ret; +} + +int FileAccessExtStubImpl::Delete(const Uri &sourceFile) +{ + int ret = -1; + auto extension = GetOwner(); + if (extension == nullptr) { + HILOG_ERROR("%{public}s end failed.", __func__); + return ret; + } + ret = extension->Delete(sourceFile); + return ret; +} + +int FileAccessExtStubImpl::Move(const Uri &sourceFile, const Uri &targetParent, Uri &newFile) +{ + int ret = -1; + auto extension = GetOwner(); + if (extension == nullptr) { + HILOG_ERROR("%{public}s end failed.", __func__); + return ret; + } + ret = extension->Move(sourceFile, targetParent, newFile); + return ret; +} + +int FileAccessExtStubImpl::Rename(const Uri &sourceFile, const std::string &displayName, Uri &newFile) +{ + int ret = -1; + auto extension = GetOwner(); + if (extension == nullptr) { + HILOG_ERROR("%{public}s end failed.", __func__); + return ret; + } + ret = extension->Rename(sourceFile, displayName, newFile); + return ret; +} + +std::vector FileAccessExtStubImpl::ListFile(const Uri &sourceFile) +{ + std::vector vec; + auto extension = GetOwner(); + if (extension == nullptr) { + HILOG_ERROR("%{public}s end failed.", __func__); + return vec; + } + vec = extension->ListFile(sourceFile); + return vec; +} + +std::vector FileAccessExtStubImpl::GetRoots() +{ + std::vector vec; + auto extension = GetOwner(); + if (extension == nullptr) { + HILOG_ERROR("%{public}s end failed.", __func__); + return vec; + } + vec = extension->GetRoots(); + return vec; +} +} // namespace FileAccessFwk +} // namespace OHOS diff --git a/frameworks/innerkits/file_access/src/file_access_helper.cpp b/frameworks/innerkits/file_access/src/file_access_helper.cpp new file mode 100644 index 0000000000000000000000000000000000000000..28bb8779e1718b4caa204ddc6961dcc33391aa64 --- /dev/null +++ b/frameworks/innerkits/file_access/src/file_access_helper.cpp @@ -0,0 +1,307 @@ +/* + * Copyright (c) 2022 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "file_access_helper.h" + +#include "hilog_wrapper.h" +#include "ifile_access_ext_base.h" + +namespace OHOS { +namespace FileAccessFwk { +FileAccessHelper::FileAccessHelper(const std::shared_ptr &context, + const AAFwk::Want &want, const sptr &fileAccessExtProxy) +{ + token_ = context->GetToken(); + want_ = want; + fileAccessExtProxy_ = fileAccessExtProxy; + fileAccessExtConnection_ = FileAccessExtConnection::GetInstance(); +} + +void FileAccessHelper::AddFileAccessDeathRecipient(const sptr &token) +{ + if (token != nullptr && callerDeathRecipient_ != nullptr) { + HILOG_INFO("token RemoveDeathRecipient."); + token->RemoveDeathRecipient(callerDeathRecipient_); + } + if (callerDeathRecipient_ == nullptr) { + callerDeathRecipient_ = + new FileAccessDeathRecipient(std::bind(&FileAccessHelper::OnSchedulerDied, this, std::placeholders::_1)); + } + if (token != nullptr) { + HILOG_INFO("token AddDeathRecipient."); + token->AddDeathRecipient(callerDeathRecipient_); + } +} + +void FileAccessHelper::OnSchedulerDied(const wptr &remote) +{ + auto object = remote.promote(); + object = nullptr; + fileAccessExtProxy_ = nullptr; +} + +FileAccessHelper::FileAccessHelper(const sptr &token, + const AAFwk::Want &want, const sptr &fileAccessExtProxy) +{ + token_ = token; + want_ = want; + fileAccessExtProxy_ = fileAccessExtProxy; + fileAccessExtConnection_ = FileAccessExtConnection::GetInstance(); +} + +std::shared_ptr FileAccessHelper::Creator( + const sptr &token, const AAFwk::Want &want) +{ + sptr fileAccessExtProxy = nullptr; + + sptr fileAccessExtConnection = FileAccessExtConnection::GetInstance(); + if (!fileAccessExtConnection->IsExtAbilityConnected()) { + fileAccessExtConnection->ConnectFileExtAbility(want, token); + } + fileAccessExtProxy = fileAccessExtConnection->GetFileExtProxy(); + if (fileAccessExtProxy == nullptr) { + HILOG_WARN("FileAccessHelper::Creator get invalid fileAccessExtProxy"); + } + + FileAccessHelper *ptrDataShareHelper = new (std::nothrow) FileAccessHelper(token, want, fileAccessExtProxy); + if (ptrDataShareHelper == nullptr) { + HILOG_ERROR("FileAccessHelper::Creator failed, create FileAccessHelper failed"); + return nullptr; + } + + return std::shared_ptr(ptrDataShareHelper); +} + +std::shared_ptr FileAccessHelper::Creator( + const std::shared_ptr &context, const AAFwk::Want &want) +{ + if (context == nullptr) { + HILOG_ERROR("%{public}s failed, context == nullptr", __func__); + return nullptr; + } + + sptr fileAccessExtProxy = nullptr; + + sptr fileAccessExtConnection = FileAccessExtConnection::GetInstance(); + if (!fileAccessExtConnection->IsExtAbilityConnected()) { + fileAccessExtConnection->ConnectFileExtAbility(want, context->GetToken()); + } + fileAccessExtProxy = fileAccessExtConnection->GetFileExtProxy(); + if (fileAccessExtProxy == nullptr) { + HILOG_WARN("%{public}s get invalid fileAccessExtProxy", __func__); + } + + FileAccessHelper *ptrFileAccessHelper = new (std::nothrow) FileAccessHelper(context, want, fileAccessExtProxy); + if (ptrFileAccessHelper == nullptr) { + HILOG_ERROR("%{public}s failed, create FileAccessHelper failed", __func__); + return nullptr; + } + + return std::shared_ptr(ptrFileAccessHelper); +} + +bool FileAccessHelper::Release() +{ + if (fileAccessExtConnection_->IsExtAbilityConnected()) { + fileAccessExtConnection_->DisconnectFileExtAbility(); + } + fileAccessExtProxy_ = nullptr; + return true; +} + +int FileAccessHelper::OpenFile(Uri &uri, int flags) +{ + int fd = -1; + + if (!fileAccessExtConnection_->IsExtAbilityConnected()) { + fileAccessExtConnection_->ConnectFileExtAbility(want_, token_); + } + fileAccessExtProxy_ = fileAccessExtConnection_->GetFileExtProxy(); + if (isSystemCaller_ && fileAccessExtProxy_) { + AddFileAccessDeathRecipient(fileAccessExtProxy_->AsObject()); + } + + if (fileAccessExtProxy_ == nullptr) { + HILOG_ERROR("%{public}s failed with invalid fileAccessExtProxy_", __func__); + return fd; + } + + fd = fileAccessExtProxy_->OpenFile(uri, flags); + return fd; +} + +int FileAccessHelper::CreateFile(Uri &parent, const std::string &displayName, Uri &newFile) +{ + int index = -1; + + if (!fileAccessExtConnection_->IsExtAbilityConnected()) { + fileAccessExtConnection_->ConnectFileExtAbility(want_, token_); + } + fileAccessExtProxy_ = fileAccessExtConnection_->GetFileExtProxy(); + if (isSystemCaller_ && fileAccessExtProxy_) { + AddFileAccessDeathRecipient(fileAccessExtProxy_->AsObject()); + } + + if (fileAccessExtProxy_ == nullptr) { + HILOG_ERROR("%{public}s failed with invalid fileAccessExtProxy_", __func__); + return index; + } + + index = fileAccessExtProxy_->CreateFile(parent, displayName, newFile); + return index; +} + +int FileAccessHelper::Mkdir(Uri &parent, const std::string &displayName, Uri &newDir) +{ + int index = -1; + + if (!fileAccessExtConnection_->IsExtAbilityConnected()) { + fileAccessExtConnection_->ConnectFileExtAbility(want_, token_); + } + fileAccessExtProxy_ = fileAccessExtConnection_->GetFileExtProxy(); + if (isSystemCaller_ && fileAccessExtProxy_) { + AddFileAccessDeathRecipient(fileAccessExtProxy_->AsObject()); + } + + if (fileAccessExtProxy_ == nullptr) { + HILOG_ERROR("%{public}s failed with invalid fileAccessExtProxy_", __func__); + return index; + } + + index = fileAccessExtProxy_->Mkdir(parent, displayName, newDir); + return index; +} + +int FileAccessHelper::Delete(Uri &selectFile) +{ + int index = -1; + + if (!fileAccessExtConnection_->IsExtAbilityConnected()) { + fileAccessExtConnection_->ConnectFileExtAbility(want_, token_); + } + fileAccessExtProxy_ = fileAccessExtConnection_->GetFileExtProxy(); + if (isSystemCaller_ && fileAccessExtProxy_) { + AddFileAccessDeathRecipient(fileAccessExtProxy_->AsObject()); + } + + if (fileAccessExtProxy_ == nullptr) { + HILOG_ERROR("%{public}s failed with invalid fileAccessExtProxy_", __func__); + return index; + } + + index = fileAccessExtProxy_->Delete(selectFile); + return index; +} + +int FileAccessHelper::Move(Uri &sourceFile, Uri &targetParent, Uri &newFile) +{ + int index = -1; + + if (!fileAccessExtConnection_->IsExtAbilityConnected()) { + fileAccessExtConnection_->ConnectFileExtAbility(want_, token_); + } + fileAccessExtProxy_ = fileAccessExtConnection_->GetFileExtProxy(); + if (isSystemCaller_ && fileAccessExtProxy_) { + AddFileAccessDeathRecipient(fileAccessExtProxy_->AsObject()); + } + + if (fileAccessExtProxy_ == nullptr) { + HILOG_ERROR("%{public}s failed with invalid fileAccessExtProxy_", __func__); + return index; + } + + index = fileAccessExtProxy_->Move(sourceFile, targetParent, newFile); + return index; +} + +int FileAccessHelper::Rename(Uri &sourceFile, const std::string &displayName, Uri &newFile) +{ + int index = -1; + + if (!fileAccessExtConnection_->IsExtAbilityConnected()) { + fileAccessExtConnection_->ConnectFileExtAbility(want_, token_); + } + fileAccessExtProxy_ = fileAccessExtConnection_->GetFileExtProxy(); + if (isSystemCaller_ && fileAccessExtProxy_) { + AddFileAccessDeathRecipient(fileAccessExtProxy_->AsObject()); + } + + if (fileAccessExtProxy_ == nullptr) { + HILOG_ERROR("%{public}s failed with invalid fileAccessExtProxy_", __func__); + return index; + } + + index = fileAccessExtProxy_->Rename(sourceFile, displayName, newFile); + return index; +} + +std::vector FileAccessHelper::ListFile(Uri &sourceFile) +{ + std::vector results; + + if (!fileAccessExtConnection_->IsExtAbilityConnected()) { + fileAccessExtConnection_->ConnectFileExtAbility(want_, token_); + } + fileAccessExtProxy_ = fileAccessExtConnection_->GetFileExtProxy(); + if (isSystemCaller_ && fileAccessExtProxy_) { + AddFileAccessDeathRecipient(fileAccessExtProxy_->AsObject()); + } + + if (fileAccessExtProxy_ == nullptr) { + HILOG_ERROR("%{public}s failed with invalid fileAccessExtProxy_", __func__); + return results; + } + + results = fileAccessExtProxy_->ListFile(sourceFile); + return results; +} + +std::vector FileAccessHelper::GetRoots() +{ + std::vector results; + + if (!fileAccessExtConnection_->IsExtAbilityConnected()) { + fileAccessExtConnection_->ConnectFileExtAbility(want_, token_); + } + fileAccessExtProxy_ = fileAccessExtConnection_->GetFileExtProxy(); + if (isSystemCaller_ && fileAccessExtProxy_) { + AddFileAccessDeathRecipient(fileAccessExtProxy_->AsObject()); + } + + if (fileAccessExtProxy_ == nullptr) { + HILOG_ERROR("%{public}s failed with invalid fileAccessExtProxy_", __func__); + return results; + } + + results = fileAccessExtProxy_->GetRoots(); + return results; +} + +void FileAccessDeathRecipient::OnRemoteDied(const wptr &remote) +{ + if (handler_) { + handler_(remote); + } +} + +FileAccessDeathRecipient::FileAccessDeathRecipient(RemoteDiedHandler handler) : handler_(handler) +{ +} + +FileAccessDeathRecipient::~FileAccessDeathRecipient() +{ +} +} // namespace FileAccessFwk +} // namespace OHOS \ No newline at end of file diff --git a/frameworks/innerkits/file_access/src/js_file_access_ext_ability.cpp b/frameworks/innerkits/file_access/src/js_file_access_ext_ability.cpp new file mode 100644 index 0000000000000000000000000000000000000000..56e1ae155346a8c8addad8b75855789ab53120ba --- /dev/null +++ b/frameworks/innerkits/file_access/src/js_file_access_ext_ability.cpp @@ -0,0 +1,416 @@ +/* + * Copyright (c) 2022 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "js_file_access_ext_ability.h" + +#include "extension_context.h" +#include "ability_info.h" +#include "accesstoken_kit.h" +#include "file_access_ext_stub_impl.h" +#include "hilog_wrapper.h" +#include "ipc_skeleton.h" +#include "js_runtime.h" +#include "js_runtime_utils.h" +#include "napi/native_api.h" +#include "napi/native_node_api.h" +#include "napi_common_fileaccess.h" +#include "napi_common_util.h" +#include "napi_common_want.h" +#include "napi_remote_object.h" + +namespace OHOS { +namespace FileAccessFwk { +namespace { +constexpr size_t ARGC_ZERO = 0; +constexpr size_t ARGC_ONE = 1; +constexpr size_t ARGC_TWO = 2; +} + +using namespace OHOS::AppExecFwk; +using namespace OHOS::AbilityRuntime; +using OHOS::Security::AccessToken::AccessTokenKit; + +JsFileAccessExtAbility* JsFileAccessExtAbility::Create(const std::unique_ptr& runtime) +{ + return new JsFileAccessExtAbility(static_cast(*runtime)); +} + +JsFileAccessExtAbility::JsFileAccessExtAbility(JsRuntime& jsRuntime) : jsRuntime_(jsRuntime) {} +JsFileAccessExtAbility::~JsFileAccessExtAbility() = default; + +void JsFileAccessExtAbility::Init(const std::shared_ptr &record, + const std::shared_ptr &application, std::shared_ptr &handler, + const sptr &token) +{ + FileAccessExtAbility::Init(record, application, handler, token); + std::string srcPath = ""; + GetSrcPath(srcPath); + if (srcPath.empty()) { + HILOG_ERROR("%{public}s Failed to get srcPath", __func__); + return; + } + + std::string moduleName(Extension::abilityInfo_->moduleName); + moduleName.append("::").append(abilityInfo_->name); + HandleScope handleScope(jsRuntime_); + + jsObj_ = jsRuntime_.LoadModule(moduleName, srcPath); + if (jsObj_ == nullptr) { + HILOG_ERROR("%{public}s Failed to get jsObj_", __func__); + return; + } + NativeObject* obj = ConvertNativeValueTo(jsObj_->Get()); + if (obj == nullptr) { + HILOG_ERROR("%{public}s Failed to get JsFileAccessExtAbility object", __func__); + return; + } +} + +void JsFileAccessExtAbility::OnStart(const AAFwk::Want &want) +{ + Extension::OnStart(want); + HandleScope handleScope(jsRuntime_); + napi_env env = reinterpret_cast(&jsRuntime_.GetNativeEngine()); + napi_value napiWant = OHOS::AppExecFwk::WrapWant(env, want); + NativeValue* nativeWant = reinterpret_cast(napiWant); + NativeValue* argv[] = {nativeWant}; + CallObjectMethod("onCreate", argv, ARGC_ONE); +} + +sptr JsFileAccessExtAbility::OnConnect(const AAFwk::Want &want) +{ + Extension::OnConnect(want); + sptr remoteObject = new (std::nothrow) FileAccessExtStubImpl( + std::static_pointer_cast(shared_from_this()), + reinterpret_cast(&jsRuntime_.GetNativeEngine())); + if (remoteObject == nullptr) { + HILOG_ERROR("%{public}s No memory allocated for FileExtStubImpl", __func__); + return nullptr; + } + return remoteObject->AsObject(); +} + +NativeValue* JsFileAccessExtAbility::CallObjectMethod(const char* name, NativeValue* const* argv, size_t argc) +{ + + if (!jsObj_) { + HILOG_WARN("%{public}s Not found FileAccessExtAbility.js", __func__); + return nullptr; + } + + HandleScope handleScope(jsRuntime_); + auto& nativeEngine = jsRuntime_.GetNativeEngine(); + + NativeValue* value = jsObj_->Get(); + NativeObject* obj = ConvertNativeValueTo(value); + if (obj == nullptr) { + HILOG_ERROR("%{public}s Failed to get FileAccessExtAbility object", __func__); + return nullptr; + } + + NativeValue* method = obj->GetProperty(name); + if (method == nullptr) { + HILOG_ERROR("%{public}s Failed to get '%{public}s' from FileAccessExtAbility object", __func__, name); + return nullptr; + } + return handleScope.Escape(nativeEngine.CallFunction(value, method, argv, argc)); +} + +NativeValue* JsFileAccessExtAbility::AsnycCallObjectMethod(const char* name, NativeValue* const* argv, size_t argc) +{ + std::shared_ptr lockInfo = std::make_shared(); + CallbackParam *param = new(std::nothrow) CallbackParam { + .lockInfo = lockInfo.get(), + .jsRuntime = jsRuntime_, + .jsObj = jsObj_, + .name = name, + .argv = argv, + .argc = argc, + .result = nullptr + }; + if (param == nullptr) { + HILOG_ERROR("failed to new param"); + return nullptr; + } + uv_loop_s *loop = nullptr; + napi_get_uv_event_loop(reinterpret_cast(&jsRuntime_.GetNativeEngine()), &loop); + uv_work_t *work = new(std::nothrow) uv_work_t; + if (work == nullptr) { + HILOG_ERROR("failed to new uv_work_t"); + delete param; + return nullptr; + } + work->data = reinterpret_cast(param); + uv_queue_work(loop, work, [](uv_work_t *work) {}, [](uv_work_t *work, int status) { + CallbackParam *param = reinterpret_cast(work->data); + do { + if (!param->jsObj) { + HILOG_ERROR("Not found js file object"); + break; + } + HandleScope handleScope(param->jsRuntime); + NativeValue* value = param->jsObj->Get(); + NativeObject* obj = ConvertNativeValueTo(value); + if (obj == nullptr) { + HILOG_ERROR("%{public}s Failed to get FileAccessExtAbility object", __func__); + break; + } + NativeValue* method = obj->GetProperty(param->name); + if (method == nullptr) { + HILOG_ERROR("%{public}s Failed to get '%{public}s' from FileAccessExtAbility object", __func__, param->name); + break; + } + auto& nativeEngine = param->jsRuntime.GetNativeEngine(); + param->result = handleScope.Escape(nativeEngine.CallFunction(value, method, param->argv, param->argc)); + } while(false); + + std::unique_lock lock(param->lockInfo->mutex); + param->lockInfo->ready = true; + param->lockInfo->condition.notify_all(); + }); + std::unique_lock lock(param->lockInfo->mutex); + param->lockInfo->condition.wait(lock, [¶m] { return param->lockInfo->ready; }); + return param->result; +} + +void JsFileAccessExtAbility::GetSrcPath(std::string &srcPath) +{ + if (!Extension::abilityInfo_->isStageBasedModel) { + /* temporary compatibility api8 + config.json */ + srcPath.append(Extension::abilityInfo_->package); + srcPath.append("/assets/js/"); + if (!Extension::abilityInfo_->srcPath.empty()) { + srcPath.append(Extension::abilityInfo_->srcPath); + } + srcPath.append("/").append(Extension::abilityInfo_->name).append(".abc"); + return; + } + + if (!Extension::abilityInfo_->srcEntrance.empty()) { + srcPath.append(Extension::abilityInfo_->moduleName + "/"); + srcPath.append(Extension::abilityInfo_->srcEntrance); + srcPath.erase(srcPath.rfind('.')); + srcPath.append(".abc"); + } +} + +int JsFileAccessExtAbility::OpenFile(const Uri &uri, int flags) +{ + HandleScope handleScope(jsRuntime_); + napi_env env = reinterpret_cast(&jsRuntime_.GetNativeEngine()); + + napi_value napiUri = nullptr; + napi_create_string_utf8(env, uri.ToString().c_str(), NAPI_AUTO_LENGTH, &napiUri); + napi_value napiFlags = nullptr; + napi_create_int32(env, flags, &napiFlags); + + NativeValue* nativeUri = reinterpret_cast(napiUri); + NativeValue* nativeFlags = reinterpret_cast(napiFlags); + NativeValue* argv[] = {nativeUri, nativeFlags}; + NativeValue* nativeResult = AsnycCallObjectMethod("openFile", argv, ARGC_TWO); + int ret = -1; + if (nativeResult == nullptr) { + HILOG_ERROR("%{public}s call openFile with return null.", __func__); + return ret; + } + ret = OHOS::AppExecFwk::UnwrapInt32FromJS(env, reinterpret_cast(nativeResult)); + return ret; +} + +int JsFileAccessExtAbility::CreateFile(const Uri &parent, const std::string &displayName, Uri &newFile) +{ + HandleScope handleScope(jsRuntime_); + napi_env env = reinterpret_cast(&jsRuntime_.GetNativeEngine()); + + napi_value napiParent = nullptr; + napi_create_string_utf8(env, parent.ToString().c_str(), NAPI_AUTO_LENGTH, &napiParent); + napi_value napiDisplayName = nullptr; + napi_create_string_utf8(env, displayName.c_str(), NAPI_AUTO_LENGTH, &napiDisplayName); + + NativeValue* nativeParent = reinterpret_cast(napiParent); + NativeValue* nativeDisplayName = reinterpret_cast(napiDisplayName); + NativeValue* argv[] = {nativeParent, nativeDisplayName}; + NativeValue* nativeResult = AsnycCallObjectMethod("createFile", argv, ARGC_TWO); + int ret = -1; + if (nativeResult == nullptr) { + HILOG_ERROR("%{public}s call createFile with return null.", __func__); + return ret; + } + std::string uriStr = OHOS::AppExecFwk::UnwrapStringFromJS(env, reinterpret_cast(nativeResult)); + if (uriStr.empty()) { + HILOG_ERROR("%{public}s call Mkdir with return empty.", __func__); + return ret; + } else { + ret = NO_ERROR; + } + newFile = Uri(uriStr); + return ret; +} + +int JsFileAccessExtAbility::Mkdir(const Uri &parent, const std::string &displayName, Uri &newFile) +{ + HandleScope handleScope(jsRuntime_); + napi_env env = reinterpret_cast(&jsRuntime_.GetNativeEngine()); + + napi_value napiParent = nullptr; + napi_create_string_utf8(env, parent.ToString().c_str(), NAPI_AUTO_LENGTH, &napiParent); + napi_value napiDisplayName = nullptr; + napi_create_string_utf8(env, displayName.c_str(), NAPI_AUTO_LENGTH, &napiDisplayName); + + NativeValue* nativeParent = reinterpret_cast(napiParent); + NativeValue* nativeDisplayName = reinterpret_cast(napiDisplayName); + NativeValue* argv[] = {nativeParent, nativeDisplayName}; + NativeValue* nativeResult = AsnycCallObjectMethod("mkdir", argv, ARGC_TWO); + int ret = -1; + if (nativeResult == nullptr) { + HILOG_ERROR("%{public}s call Mkdir with return null.", __func__); + return ret; + } + std::string uriStr = OHOS::AppExecFwk::UnwrapStringFromJS(env, reinterpret_cast(nativeResult)); + if (uriStr.empty()) { + HILOG_ERROR("%{public}s call Mkdir with return empty.", __func__); + return ret; + } else { + ret = NO_ERROR; + } + newFile = Uri(uriStr); + return ret; +} + +int JsFileAccessExtAbility::Delete(const Uri &sourceFile) +{ + HandleScope handleScope(jsRuntime_); + napi_env env = reinterpret_cast(&jsRuntime_.GetNativeEngine()); + + napi_value napiUri = nullptr; + napi_create_string_utf8(env, sourceFile.ToString().c_str(), NAPI_AUTO_LENGTH, &napiUri); + + NativeValue* nativeUri = reinterpret_cast(napiUri); + NativeValue* argv[] = {nativeUri}; + NativeValue* nativeResult = AsnycCallObjectMethod("delete", argv, ARGC_ONE); + int ret = -1; + if (nativeResult == nullptr) { + HILOG_ERROR("%{public}s call delete with return null.", __func__); + return ret; + } + ret = OHOS::AppExecFwk::UnwrapInt32FromJS(env, reinterpret_cast(nativeResult)); + return ret; +} + +int JsFileAccessExtAbility::Move(const Uri &sourceFile, const Uri &targetParent, Uri &newFile) +{ + HandleScope handleScope(jsRuntime_); + napi_env env = reinterpret_cast(&jsRuntime_.GetNativeEngine()); + + napi_value napiSourceFile = nullptr; + napi_create_string_utf8(env, sourceFile.ToString().c_str(), NAPI_AUTO_LENGTH, &napiSourceFile); + napi_value napiTargetParent = nullptr; + napi_create_string_utf8(env, targetParent.ToString().c_str(), NAPI_AUTO_LENGTH, &napiTargetParent); + + NativeValue* nativeSourceFile = reinterpret_cast(napiSourceFile); + NativeValue* nativeTargetParent = reinterpret_cast(napiTargetParent); + NativeValue* argv[] = {nativeSourceFile, nativeTargetParent}; + NativeValue* nativeResult = AsnycCallObjectMethod("move", argv, ARGC_TWO); + int ret = -1; + if (nativeResult == nullptr) { + HILOG_ERROR("tag dsa %{public}s call move with return null.", __func__); + return ret; + } + std::string uriStr = OHOS::AppExecFwk::UnwrapStringFromJS(env, reinterpret_cast(nativeResult)); + if (uriStr.empty()) { + HILOG_ERROR("tag dsa %{public}s call move with return empty.", __func__); + return ret; + } else { + ret = NO_ERROR; + } + newFile = Uri(uriStr); + return ret; +} + +int JsFileAccessExtAbility::Rename(const Uri &sourceFile, const std::string &displayName, Uri &newFile) +{ + HandleScope handleScope(jsRuntime_); + napi_env env = reinterpret_cast(&jsRuntime_.GetNativeEngine()); + + napi_value napiSourceFile = nullptr; + napi_create_string_utf8(env, sourceFile.ToString().c_str(), NAPI_AUTO_LENGTH, &napiSourceFile); + napi_value napiDisplayName = nullptr; + napi_create_string_utf8(env, displayName.c_str(), NAPI_AUTO_LENGTH, &napiDisplayName); + + NativeValue* nativeSourceFile = reinterpret_cast(napiSourceFile); + NativeValue* nativeDisplayName = reinterpret_cast(napiDisplayName); + NativeValue* argv[] = {nativeSourceFile, nativeDisplayName}; + NativeValue* nativeResult = AsnycCallObjectMethod("rename", argv, ARGC_TWO); + int ret = -1; + if (nativeResult == nullptr) { + HILOG_ERROR("%{public}s call rename with return null.", __func__); + return ret; + } + std::string uriStr = OHOS::AppExecFwk::UnwrapStringFromJS(env, reinterpret_cast(nativeResult)); + if (uriStr.empty()) { + HILOG_ERROR("%{public}s call rename with return empty.", __func__); + return ret; + } else { + ret = NO_ERROR; + } + newFile = Uri(uriStr); + return ret; +} + +std::vector JsFileAccessExtAbility::ListFile(const Uri &sourceFile) +{ + HandleScope handleScope(jsRuntime_); + napi_env env = reinterpret_cast(&jsRuntime_.GetNativeEngine()); + + napi_value napiUri = nullptr; + std::vector vec; + napi_create_string_utf8(env, sourceFile.ToString().c_str(), NAPI_AUTO_LENGTH, &napiUri); + + NativeValue* nativeUri = reinterpret_cast(napiUri); + NativeValue* argv[] = {nativeUri}; + NativeValue* nativeResult = AsnycCallObjectMethod("listFile", argv, ARGC_ONE); + if (nativeResult == nullptr) { + HILOG_ERROR("%{public}s call listFile with return null.", __func__); + return vec; + } + if (UnwrapArrayFileInfoFromJS(env, reinterpret_cast(nativeResult), vec)) { + return vec; + } else { + HILOG_ERROR("%{public}s end with faild.", __func__); + return vec; + } +} + +std::vector JsFileAccessExtAbility::GetRoots() +{ + HandleScope handleScope(jsRuntime_); + napi_env env = reinterpret_cast(&jsRuntime_.GetNativeEngine()); + + std::vector vec; + NativeValue* argv[] = {}; + NativeValue* nativeResult = AsnycCallObjectMethod("getRoots", argv, ARGC_ZERO); + if (nativeResult == nullptr) { + HILOG_ERROR("%{public}s call getRoots with return null.", __func__); + return vec; + } + if (UnwrapArrayDeviceInfoFromJS(env, reinterpret_cast(nativeResult), vec)) { + return vec; + } else { + HILOG_ERROR("%{public}s end with faild.", __func__); + return vec; + } +} +} // namespace FileAccessFwk +} // namespace OHOS \ No newline at end of file diff --git a/frameworks/innerkits/file_access/src/napi_common_fileaccess.cpp b/frameworks/innerkits/file_access/src/napi_common_fileaccess.cpp new file mode 100644 index 0000000000000000000000000000000000000000..cd496d44f9c3be10e9fa462b5fbd8236e72530c8 --- /dev/null +++ b/frameworks/innerkits/file_access/src/napi_common_fileaccess.cpp @@ -0,0 +1,322 @@ +/* + * Copyright (c) 2022 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "hilog_wrapper.h" +#include "napi_common_fileaccess.h" + +namespace OHOS { +namespace FileAccessFwk { +using namespace OHOS::AppExecFwk; +bool UnwrapInt64ByPropertyName(napi_env env, napi_value param, const char *propertyName, int64_t &value) +{ + napi_value jsValue = GetPropertyValueByPropertyName(env, param, propertyName, napi_number); + if (jsValue != nullptr) { + return UnwrapInt64FromJS2(env, jsValue, value); + } else { + return false; + } +} + +napi_value WrapUint32ToJS(napi_env env, uint32_t value) +{ + napi_value result = nullptr; + NAPI_CALL(env, napi_create_uint32(env, value, &result)); + return result; +} + +uint32_t UnwrapUint32FromJS(napi_env env, napi_value param, uint32_t defaultValue) +{ + uint32_t value = defaultValue; + if (napi_get_value_uint32(env, param, &value) == napi_ok) { + return value; + } else { + return defaultValue; + } +} + +bool UnwrapUint32FromJS2(napi_env env, napi_value param, uint32_t &value) +{ + bool result = false; + if (napi_get_value_uint32(env, param, &value) == napi_ok) { + result = true; + } + return result; +} + +bool UnwrapUint32ByPropertyName(napi_env env, napi_value param, const char *propertyName, uint32_t &value) +{ + napi_value jsValue = GetPropertyValueByPropertyName(env, param, propertyName, napi_number); + if (jsValue != nullptr) { + return UnwrapUint32FromJS2(env, jsValue, value); + } else { + return false; + } +} + +napi_value WrapBigIntUint64ToJS(napi_env env, uint64_t value) +{ + napi_value result = nullptr; + NAPI_CALL(env, napi_create_bigint_uint64(env, value, &result)); + return result; +} + +uint64_t UnwrapBigIntUint64FromJS(napi_env env, napi_value param, uint64_t defaultValue) +{ + HILOG_INFO("%{public}s,called begin", __func__); + bool lossless = true; + uint64_t value = defaultValue; + if (napi_get_value_bigint_uint64(env, param, &value, &lossless) == napi_ok) { + return value; + } else { + HILOG_INFO("%{public}s,called end with faild.", __func__); + return defaultValue; + } +} + +bool UnwrapBigIntUint64FromJS2(napi_env env, napi_value param, uint64_t &defaultValue) +{ + HILOG_INFO("%{public}s,called begin", __func__); + bool lossless = true; + if (napi_get_value_bigint_uint64(env, param, &defaultValue, &lossless) == napi_ok) { + return true; + } else { + HILOG_INFO("%{public}s,called end with faild.", __func__); + return false; + } +} + +bool UnwrapBigIntUint64ByPropertyName(napi_env env, napi_value param, const char *propertyName, uint64_t &value) +{ + napi_value jsValue = GetPropertyValueByPropertyName(env, param, propertyName, napi_bigint); + if (jsValue != nullptr) { + return UnwrapBigIntUint64FromJS2(env, jsValue, value); + } else { + return false; + } +} + +napi_value WrapFileInfo(napi_env env, const FileInfo &fileInfo) +{ + napi_value jsObject = nullptr; + napi_value jsValue = nullptr; + + NAPI_CALL(env, napi_create_object(env, &jsObject)); + + jsValue = nullptr; + jsValue = OHOS::AppExecFwk::WrapStringToJS(env, fileInfo.uri.ToString()); + SetPropertyValueByPropertyName(env, jsObject, "uri", jsValue); + + jsValue = nullptr; + jsValue = OHOS::AppExecFwk::WrapStringToJS(env, fileInfo.fileName); + SetPropertyValueByPropertyName(env, jsObject, "fileName", jsValue); + + jsValue = nullptr; + jsValue = OHOS::AppExecFwk::WrapStringToJS(env, fileInfo.mode); + SetPropertyValueByPropertyName(env, jsObject, "mode", jsValue); + + jsValue = nullptr; + jsValue = OHOS::AppExecFwk::WrapInt64ToJS(env, fileInfo.size); + SetPropertyValueByPropertyName(env, jsObject, "size", jsValue); + + jsValue = nullptr; + jsValue = OHOS::AppExecFwk::WrapInt64ToJS(env, fileInfo.mtime); + SetPropertyValueByPropertyName(env, jsObject, "mtime", jsValue); + + jsValue = nullptr; + jsValue = OHOS::AppExecFwk::WrapStringToJS(env, fileInfo.mimiType); + SetPropertyValueByPropertyName(env, jsObject, "mimiType", jsValue); + + return jsObject; +} + +bool UnwrapFileInfo(napi_env env, napi_value param, FileInfo &fileInfo) +{ + if (!IsTypeForNapiValue(env, param, napi_object)) { + return false; + } + + std::string natValueString(""); + if (OHOS::AppExecFwk::UnwrapStringByPropertyName(env, param, "uri", natValueString)) { + fileInfo.uri = Uri(natValueString); + } + + natValueString = ""; + if (OHOS::AppExecFwk::UnwrapStringByPropertyName(env, param, "fileName", natValueString)) { + fileInfo.fileName = natValueString; + } + + natValueString = ""; + if (OHOS::AppExecFwk::UnwrapStringByPropertyName(env, param, "mode", natValueString)) { + fileInfo.mode = natValueString; + } + + int64_t natValueInt64 = 0; + if (UnwrapInt64ByPropertyName(env, param, "size", natValueInt64)) { + fileInfo.size = natValueInt64; + } + + natValueInt64 = 0; + if (UnwrapInt64ByPropertyName(env, param, "mtime", natValueInt64)) { + fileInfo.mtime = natValueInt64; + } + + natValueString = ""; + if (OHOS::AppExecFwk::UnwrapStringByPropertyName(env, param, "mimiType", natValueString)) { + fileInfo.mimiType = natValueString; + } + + return true; +} + +napi_value WrapArrayFileInfoToJS(napi_env env, const std::vector &fileInfoVec) +{ + napi_value jsArray = nullptr; + napi_value jsValue = nullptr; + uint32_t index = 0; + + NAPI_CALL(env, napi_create_array(env, &jsArray)); + for (uint32_t i = 0; i < fileInfoVec.size(); i++) { + jsValue = WrapFileInfo(env, fileInfoVec[i]); + if (napi_set_element(env, jsArray, index, jsValue) == napi_ok) { + index++; + } + } + return jsArray; +} + +bool UnwrapArrayFileInfoFromJS(napi_env env, napi_value param, std::vector &fileInfoVec) +{ + uint32_t arraySize = 0; + napi_value jsValue = nullptr; + + if (!IsArrayForNapiValue(env, param, arraySize)) { + return false; + } + + fileInfoVec.clear(); + for (uint32_t i = 0; i < arraySize; i++) { + jsValue = nullptr; + FileInfo fileInfo; + if (napi_get_element(env, param, i, &jsValue) != napi_ok) { + return false; + } + + if (!UnwrapFileInfo(env, jsValue, fileInfo)) { + return false; + } + + fileInfoVec.push_back(fileInfo); + } + return true; +} + +napi_value WrapDeviceInfo(napi_env env, const DeviceInfo &deviceInfo) +{ + napi_value jsObject = nullptr; + napi_value jsValue = nullptr; + + NAPI_CALL(env, napi_create_object(env, &jsObject)); + + jsValue = nullptr; + jsValue = OHOS::AppExecFwk::WrapStringToJS(env, deviceInfo.uri.ToString()); + SetPropertyValueByPropertyName(env, jsObject, "uri", jsValue); + + jsValue = nullptr; + jsValue = OHOS::AppExecFwk::WrapStringToJS(env, deviceInfo.displayName); + SetPropertyValueByPropertyName(env, jsObject, "displayName", jsValue); + + jsValue = nullptr; + jsValue = OHOS::AppExecFwk::WrapStringToJS(env, deviceInfo.deviceId); + SetPropertyValueByPropertyName(env, jsObject, "deviceId", jsValue); + + jsValue = nullptr; + jsValue = WrapUint32ToJS(env, deviceInfo.flags); + SetPropertyValueByPropertyName(env, jsObject, "flags", jsValue); + + HILOG_INFO("%{public}s,called end", __func__); + return jsObject; +} + +bool UnwrapDeviceInfo(napi_env env, napi_value param, DeviceInfo &deviceInfo) +{ + if (!IsTypeForNapiValue(env, param, napi_object)) { + return false; + } + + std::string natValueString(""); + if (OHOS::AppExecFwk::UnwrapStringByPropertyName(env, param, "uri", natValueString)) { + deviceInfo.uri = Uri(natValueString); + } + + natValueString = ""; + if (OHOS::AppExecFwk::UnwrapStringByPropertyName(env, param, "displayName", natValueString)) { + deviceInfo.displayName = natValueString; + } + + natValueString = ""; + if (OHOS::AppExecFwk::UnwrapStringByPropertyName(env, param, "deviceId", natValueString)) { + deviceInfo.deviceId = natValueString; + } + + uint32_t natValueUint32 = 0; + if (UnwrapUint32ByPropertyName(env, param, "flags", natValueUint32)) { + deviceInfo.flags = natValueUint32; + } + return true; +} + +napi_value WrapArrayDeviceInfoToJS(napi_env env, const std::vector &deviceInfoVec) +{ + napi_value jsArray = nullptr; + napi_value jsValue = nullptr; + uint32_t index = 0; + + NAPI_CALL(env, napi_create_array(env, &jsArray)); + for (uint32_t i = 0; i < deviceInfoVec.size(); i++) { + jsValue = WrapDeviceInfo(env, deviceInfoVec[i]); + if (napi_set_element(env, jsArray, index, jsValue) == napi_ok) { + index++; + } + } + return jsArray; +} + +bool UnwrapArrayDeviceInfoFromJS(napi_env env, napi_value param, std::vector &deviceInfoVec) +{ + uint32_t arraySize = 0; + napi_value jsValue = nullptr; + + if (!IsArrayForNapiValue(env, param, arraySize)) { + return false; + } + + deviceInfoVec.clear(); + for (uint32_t i = 0; i < arraySize; i++) { + jsValue = nullptr; + DeviceInfo deviceInfo; + if (napi_get_element(env, param, i, &jsValue) != napi_ok) { + return false; + } + + if (!UnwrapDeviceInfo(env, jsValue, deviceInfo)) { + return false; + } + + deviceInfoVec.push_back(deviceInfo); + } + return true; +} +} // namespace FileAccessFwk +} // namespace OHOS diff --git a/interfaces/kits/napi/common/file_extension_info_napi.cpp b/interfaces/kits/napi/common/file_extension_info_napi.cpp new file mode 100644 index 0000000000000000000000000000000000000000..b495dbf3786198b1630c38b91bb287d62420cc41 --- /dev/null +++ b/interfaces/kits/napi/common/file_extension_info_napi.cpp @@ -0,0 +1,127 @@ +/* + * 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 "file_extension_info_napi.h" + +#include + +#include "file_access_extension_info.h" + +namespace OHOS { +namespace FileAccessFwk { +napi_value CreateStringUtf8(napi_env env, const std::string &str) +{ + napi_value value = nullptr; + if (napi_create_string_utf8(env, str.c_str(), str.length(), &value) != napi_ok) { + return nullptr; + } + return value; +} + +napi_value CreateUint32(napi_env env, uint32_t val) +{ + napi_value value = nullptr; + if (napi_create_uint32(env, val, &value) != napi_ok) { + return nullptr; + } + return value; +} + +napi_value FileInfoConstructor(napi_env env, napi_callback_info info) +{ + size_t argc = 0; + napi_value args[1] = {0}; + napi_value res = nullptr; + void *data = nullptr; + + napi_status status = napi_get_cb_info(env, info, &argc, args, &res, &data); + if (status != napi_ok) { + return nullptr; + } + + return res; +} + +napi_value DeviceInfoConstructor(napi_env env, napi_callback_info info) +{ + size_t argc = 0; + napi_value args[1] = {0}; + napi_value res = nullptr; + void *data = nullptr; + + napi_status status = napi_get_cb_info(env, info, &argc, args, &res, &data); + if (status != napi_ok) { + return nullptr; + } + + return res; +} + +void InitFlag(napi_env env, napi_value exports) +{ + char propertyName[] = "FLAG"; + napi_property_descriptor desc[] = { + DECLARE_NAPI_STATIC_PROPERTY("SUPPORTS_THUMBNAIL", + CreateUint32(env, FLAG_SUPPORTS_THUMBNAIL)), + DECLARE_NAPI_STATIC_PROPERTY("SUPPORTS_WRITE", + CreateUint32(env, FLAG_SUPPORTS_WRITE)), + DECLARE_NAPI_STATIC_PROPERTY("SUPPORTS_READ", + CreateUint32(env, FLAG_SUPPORTS_READ)), + DECLARE_NAPI_STATIC_PROPERTY("SUPPORTS_DELETE", + CreateUint32(env, FLAG_SUPPORTS_DELETE)), + DECLARE_NAPI_STATIC_PROPERTY("SUPPORTS_RENAME", + CreateUint32(env, FLAG_SUPPORTS_RENAME)), + DECLARE_NAPI_STATIC_PROPERTY("SUPPORTS_MOVE", + CreateUint32(env, FLAG_SUPPORTS_MOVE)) + }; + napi_value obj = nullptr; + napi_create_object(env, &obj); + napi_define_properties(env, obj, sizeof(desc) / sizeof(desc[0]), desc); + napi_set_named_property(env, exports, propertyName, obj); +} + +void InitFileInfo(napi_env env, napi_value exports) +{ + char className[] = "FileInfo"; + napi_property_descriptor desc[] = { + { "uri", nullptr, nullptr, nullptr, nullptr, CreateStringUtf8(env, "uri"), napi_writable, nullptr }, + { "fileName", nullptr, nullptr, nullptr, nullptr, CreateStringUtf8(env, "fileName"), napi_writable, nullptr }, + { "mode", nullptr, nullptr, nullptr, nullptr, CreateStringUtf8(env, "mode"), napi_writable, nullptr }, + { "size", nullptr, nullptr, nullptr, nullptr, CreateStringUtf8(env, "size"), napi_writable, nullptr }, + { "mtime", nullptr, nullptr, nullptr, nullptr, CreateStringUtf8(env, "mtime"), napi_writable, nullptr }, + { "mimiType", nullptr, nullptr, nullptr, nullptr, CreateStringUtf8(env, "mimiType"), napi_writable, nullptr } + }; + napi_value obj = nullptr; + napi_define_class(env, className, NAPI_AUTO_LENGTH, FileInfoConstructor, nullptr, + sizeof(desc) / sizeof(*desc), desc, &obj); + napi_set_named_property(env, exports, className, obj); +} + +void InitDeviceInfo(napi_env env, napi_value exports) +{ + char className[] = "DeviceInfo"; + napi_property_descriptor desc[] = { + { "uri", nullptr, nullptr, nullptr, nullptr, CreateStringUtf8(env, "uri"), napi_writable, nullptr }, + { "displayName", nullptr, nullptr, nullptr, nullptr, + CreateStringUtf8(env, "displayName"), napi_writable, nullptr }, + { "deviceId", nullptr, nullptr, nullptr, nullptr, CreateStringUtf8(env, "deviceId"), napi_writable, nullptr }, + { "flags", nullptr, nullptr, nullptr, nullptr, CreateStringUtf8(env, "flags"), napi_writable, nullptr } + }; + napi_value obj = nullptr; + napi_define_class(env, className, NAPI_AUTO_LENGTH, DeviceInfoConstructor, nullptr, + sizeof(desc) / sizeof(*desc), desc, &obj); + napi_set_named_property(env, exports, className, obj); +} +} // namespace FileAccessFwk +} // namespace OHOS \ No newline at end of file diff --git a/interfaces/kits/napi/common/file_extension_info_napi.h b/interfaces/kits/napi/common/file_extension_info_napi.h new file mode 100644 index 0000000000000000000000000000000000000000..3b974f6824b3c2f54addb383b9de857621854640 --- /dev/null +++ b/interfaces/kits/napi/common/file_extension_info_napi.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. + */ + +#ifndef FILE_EXTENSION_INFO_NAPI_H +#define FILE_EXTENSION_INFO_NAPI_H +#include "napi/native_api.h" +#include "napi/native_node_api.h" +namespace OHOS { +namespace FileAccessFwk { +void InitFlag(napi_env env, napi_value exports); +void InitFileInfo(napi_env env, napi_value exports); +void InitDeviceInfo(napi_env env, napi_value exports); +} // namespace FileAccessFwk +} // namespace OHOS +#endif // FILE_EXTENSION_INFO_NAPI_H \ No newline at end of file diff --git a/interfaces/kits/napi/file_access_ext_ability/BUILD.gn b/interfaces/kits/napi/file_access_ext_ability/BUILD.gn new file mode 100644 index 0000000000000000000000000000000000000000..c7879905a31d5d2bd367ecbd172e3e0590a092cc --- /dev/null +++ b/interfaces/kits/napi/file_access_ext_ability/BUILD.gn @@ -0,0 +1,50 @@ +# Copyright (c) 2022 Huawei Device Co., Ltd. +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import("//ark/ts2abc/ts2panda/ts2abc_config.gni") +import("//build/ohos.gni") + +ts2abc_gen_abc("gen_file_access_ext_ability_abc") { + src_js = rebase_path("file_access_ext_ability.js") + dst_file = rebase_path(target_out_dir + "/file_access_ext_ability.abc") + in_puts = [ "file_access_ext_ability.js" ] + out_puts = [ target_out_dir + "/file_access_ext_ability.abc" ] + extra_args = [ "--module" ] +} + +gen_js_obj("file_access_ext_ability_js") { + input = "file_access_ext_ability.js" + output = target_out_dir + "/file_access_ext_ability.o" +} + +gen_js_obj("file_access_ext_ability_abc") { + input = get_label_info(":gen_file_access_ext_ability_abc", "target_out_dir") + + "/file_access_ext_ability.abc" + output = target_out_dir + "/file_access_ext_ability_abc.o" + dep = ":gen_file_access_ext_ability_abc" +} + +ohos_shared_library("fileaccessextensionability_napi") { + sources = [ "file_access_ext_ability_module.cpp" ] + + deps = [ + ":file_access_ext_ability_abc", + ":file_access_ext_ability_js", + ] + + external_deps = [ "napi:ace_napi" ] + + relative_install_dir = "module/application" + subsystem_name = "filemanagement" + part_name = "user_file_service" +} diff --git a/interfaces/kits/napi/file_access_ext_ability/file_access_ext_ability.js b/interfaces/kits/napi/file_access_ext_ability/file_access_ext_ability.js new file mode 100644 index 0000000000000000000000000000000000000000..de65850d8aa2c298447097a90f8ba749c3b76257 --- /dev/null +++ b/interfaces/kits/napi/file_access_ext_ability/file_access_ext_ability.js @@ -0,0 +1,62 @@ +/* + * Copyright (c) 2022 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +class FileAccessExtensionAbility { + onCreate(want) { + console.log('js c++ tag dsa onCreate, want:' + want.abilityName); + } + + openFile(uri, mode) { + console.log('js c++ tag dsa openFile, uri:' + uri + ',flags: ' + flags); + return 0; + } + + createFile(parentUri, displayName) { + console.log('js c++ tag dsa CreateFile, parentUri:' + parentUri + ',displayName:' + displayName ); + return "filetest://fileext.share/temp/test/CreateFile000.txt"; + } + + mkdir(parentUri, displayName) { + console.log('js c++ tag dsa mkdir, parentUri:' + parentUri + ',displayName:' + displayName); + return "filetest://fileext.share/temp/test/Mkdir000"; + } + + delete(sourceFileUri) { + console.log('js c++ tag dsa delete, sourceFileUri:' + sourceFileUri); + return 0; + } + + move(sourceFileUri, targetParentUri) { + console.log('js c++ tag dsa move, sourceFileUri:' + sourceFileUri + ',targetParentUri:' + targetParentUri); + return "filetest://fileext.share/temp/test/move000.xl"; + } + + rename(sourceFileUri, displayName) { + console.log('js c++ tag dsa rename, sourceFileUri:' + sourceFileUri + ',displayName:' + displayName); + return "filetest://fileext.share/temp/test/rename000.ttt"; + } + + listFile(sourceFileUri) { + let infos = []; + return infos; + } + + getRoots() { + let roots = []; + return roots; + } +} + +export default FileAccessExtensionAbility \ No newline at end of file diff --git a/interfaces/kits/napi/file_access_ext_ability/file_access_ext_ability_module.cpp b/interfaces/kits/napi/file_access_ext_ability/file_access_ext_ability_module.cpp new file mode 100644 index 0000000000000000000000000000000000000000..539d60ddf6b3092a0463c45971e153ac7d3225a0 --- /dev/null +++ b/interfaces/kits/napi/file_access_ext_ability/file_access_ext_ability_module.cpp @@ -0,0 +1,57 @@ +/* + * Copyright (c) 2022 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "native_engine/native_engine.h" + +extern const char _binary_file_access_ext_ability_js_start[]; +extern const char _binary_file_access_ext_ability_js_end[]; +extern const char _binary_file_access_ext_ability_abc_start[]; +extern const char _binary_file_access_ext_ability_abc_end[]; + +extern "C" __attribute__((constructor)) +void NAPI_application_FileAccessExtensionAbility_AutoRegister() +{ + auto moduleManager = NativeModuleManager::GetInstance(); + NativeModule newModuleInfo = { + .name = "application.FileAccessExtensionAbility", + .fileName = "application/libfileaccessextensionability_napi.so/FileAccessExtensionAbility.js", + }; + + moduleManager->Register(&newModuleInfo); +} + +extern "C" __attribute__((visibility("default"))) +void NAPI_application_FileAccessExtensionAbility_GetJSCode(const char **buf, int *bufLen) +{ + if (buf != nullptr) { + *buf = _binary_file_access_ext_ability_js_start; + } + + if (bufLen != nullptr) { + *bufLen = _binary_file_access_ext_ability_js_end - _binary_file_access_ext_ability_js_start; + } +} + +// file extension ability JS register +extern "C" __attribute__((visibility("default"))) +void NAPI_application_FileAccessExtensionAbility_GetABCCode(const char **buf, int *buflen) +{ + if (buf != nullptr) { + *buf = _binary_file_access_ext_ability_abc_start; + } + if (buflen != nullptr) { + *buflen = _binary_file_access_ext_ability_abc_end - _binary_file_access_ext_ability_abc_start; + } +} \ No newline at end of file diff --git a/interfaces/kits/napi/file_access_module/BUILD.gn b/interfaces/kits/napi/file_access_module/BUILD.gn new file mode 100644 index 0000000000000000000000000000000000000000..66fe0854caa5fcef545b634541c444fc1aafbc63 --- /dev/null +++ b/interfaces/kits/napi/file_access_module/BUILD.gn @@ -0,0 +1,53 @@ +# Copyright (c) 2022 Huawei Device Co., Ltd. +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import("//build/ohos.gni") +BASE_DIR = "//foundation/filemanagement/user_file_service" + +ohos_shared_library("fileaccess") { + subsystem_name = "filemanagement" + part_name = "user_file_service" + + relative_install_dir = "module/data" + + include_dirs = [ + "./", + "${BASE_DIR}/utils", + "${BASE_DIR}/interfaces/kits/napi/common", + "//foundation/distributeddatamgr/distributedfile/interfaces/kits/js/src/common/napi", + "//foundation/distributeddatamgr/distributedfile/interfaces/kits/js/src/common", + ] + + sources = [ + "napi_fileaccess_helper.cpp", + "native_fileaccess_module.cpp", + "${BASE_DIR}/interfaces/kits/napi/common/file_extension_info_napi.cpp", + ] + + deps = [ + "${BASE_DIR}/frameworks/innerkits/file_access:file_access_extension_ability_kit", + "//foundation/ability/ability_runtime/frameworks/js/napi/aafwk/inner/napi_common:napi_common", + "//foundation/distributeddatamgr/distributedfile/interfaces/kits/js:fileio", + ] + + external_deps = [ + "ability_base:base", + "ability_base:want", + "ability_base:zuri", + "ability_runtime:abilitykit_native", + "ability_runtime:napi_base_context", + "hiviewdfx_hilog_native:libhilog", + "napi:ace_napi", + "utils_base:utils", + ] +} \ No newline at end of file diff --git a/interfaces/kits/napi/file_access_module/file_access_common.h b/interfaces/kits/napi/file_access_module/file_access_common.h new file mode 100644 index 0000000000000000000000000000000000000000..4bc188b4923b44ef2c7ddf3223cb6245511be5a3 --- /dev/null +++ b/interfaces/kits/napi/file_access_module/file_access_common.h @@ -0,0 +1,112 @@ +/* + * Copyright (C) 2022 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +#ifndef FILE_ACCESS_COMMON_H +#define FILE_ACCESS_COMMON_H + +#include "ability.h" +#include "file_access_helper.h" +#include "napi/native_api.h" +#include "napi/native_common.h" +#include "napi/native_node_api.h" +#include "napi_common.h" +#include "napi_common_util.h" + +namespace OHOS { +namespace FileAccessFwk { +struct CBBase { + AppExecFwk::CallbackInfo cbInfo; + napi_async_work asyncWork; + napi_deferred deferred; + Ability *ability = nullptr; + AppExecFwk::AbilityType abilityType = AppExecFwk::AbilityType::UNKNOWN; + int errCode = ERR_OK; +}; + +struct FileAccessHelperCB { + CBBase cbBase; + napi_ref uri = nullptr; + napi_value result = nullptr; +}; + +struct FileAccessHelperOpenFileCB { + CBBase cbBase; + FileAccessHelper *fileAccessHelper = nullptr; + std::string uri; + int flags; + int result = ERR_OK; + int execResult; +}; + +struct FileAccessHelperCreateFileCB { + CBBase cbBase; + FileAccessHelper *fileAccessHelper = nullptr; + std::string parentUri; + std::string name; + std::string result; + int execResult; +}; + +struct FileAccessHelperMkdirCB { + CBBase cbBase; + FileAccessHelper *fileAccessHelper = nullptr; + std::string parentUri; + std::string name; + std::string result; + int execResult; +}; + +struct FileAccessHelperDeleteCB { + CBBase cbBase; + FileAccessHelper *fileAccessHelper = nullptr; + std::string selectFileUri; + int result = ERR_OK; + int execResult; +}; + +struct FileAccessHelperMoveCB { + CBBase cbBase; + FileAccessHelper *fileAccessHelper = nullptr; + std::string sourceFileUri; + std::string targetParentUri; + std::string result; + int execResult; +}; + +struct FileAccessHelperRenameCB { + CBBase cbBase; + FileAccessHelper *fileAccessHelper = nullptr; + std::string sourceFileUri; + std::string displayName; + std::string result; + int execResult; +}; + +struct FileAccessHelperListFileCB { + CBBase cbBase; + FileAccessHelper *fileAccessHelper = nullptr; + std::string sourceFileUri; + std::vector result; + int execResult; +}; + +struct FileAccessHelperGetRootsCB { + CBBase cbBase; + FileAccessHelper *fileAccessHelper = nullptr; + std::vector result; + int execResult; +}; +} +} +#endif \ No newline at end of file diff --git a/interfaces/kits/napi/file_access_module/napi_fileaccess_helper.cpp b/interfaces/kits/napi/file_access_module/napi_fileaccess_helper.cpp new file mode 100644 index 0000000000000000000000000000000000000000..e20649e87098dca6b1b575bd6defa94c2660f504 --- /dev/null +++ b/interfaces/kits/napi/file_access_module/napi_fileaccess_helper.cpp @@ -0,0 +1,1686 @@ +/* + * Copyright (C) 2022 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "napi_fileaccess_helper.h" + +#include +#include + +#include "uri.h" + +#include "hilog_wrapper.h" +#include "n_func_arg.h" +#include "n_val.h" +#include "napi_base_context.h" +#include "securec.h" +#include "napi_common_fileaccess.h" +#include "uni_error.h" + +using namespace OHOS::AAFwk; +using namespace OHOS::AppExecFwk; +using namespace OHOS::DistributedFS; + +namespace OHOS { +namespace FileAccessFwk { +namespace { +const std::string FILEACCESS_CLASS_NAME = "FileAccessHelper"; + +std::string NapiValueToStringUtf8(napi_env env, napi_value value) +{ + std::string result = ""; + return UnwrapStringFromJS(env, value, result); +} + +int NapiValueToInt32Utf8(napi_env env, napi_value value) +{ + int result = 0; + return UnwrapInt32FromJS(env, value, result); +} +} + +std::list> g_fileAccessHelperList; +static napi_ref g_constructorRef = nullptr; + +napi_value AcquireFileAccessHelperWrap(napi_env env, napi_callback_info info, FileAccessHelperCB *fileAccessHelperCB) +{ + if (fileAccessHelperCB == nullptr) { + HILOG_ERROR("%{public}s,fileAccessHelperCB == nullptr", __func__); + return nullptr; + } + + size_t requireArgc = ARGS_THREE; + size_t argc = ARGS_THREE; + napi_value args[ARGS_THREE] = {nullptr}; + NAPI_CALL(env, napi_get_cb_info(env, info, &argc, args, nullptr, nullptr)); + if (argc > requireArgc) { + HILOG_ERROR("%{public}s, Wrong argument count%{public}zu.", __func__, argc); + return nullptr; + } + + napi_value result = nullptr; + napi_value cons = nullptr; + if (napi_get_reference_value(env, g_constructorRef, &cons) != napi_ok) { + return nullptr; + } + NAPI_CALL(env, napi_new_instance(env, cons, ARGS_THREE, args, &result)); + + if (!IsTypeForNapiValue(env, result, napi_object)) { + HILOG_ERROR("%{public}s, IsTypeForNapiValue isn`t object", __func__); + return nullptr; + } + + if (IsTypeForNapiValue(env, result, napi_null)) { + HILOG_ERROR("%{public}s, IsTypeForNapiValue is null", __func__); + return nullptr; + } + + if (IsTypeForNapiValue(env, result, napi_undefined)) { + HILOG_ERROR("%{public}s, IsTypeForNapiValue is undefined", __func__); + return nullptr; + } + + delete fileAccessHelperCB; + fileAccessHelperCB = nullptr; + return result; +} + +napi_value NAPI_AcquireFileAccessHelperCommon(napi_env env, napi_callback_info info, AbilityType abilityType) +{ + FileAccessHelperCB *fileAccessHelperCB = new (std::nothrow) FileAccessHelperCB; + if (fileAccessHelperCB == nullptr) { + HILOG_ERROR("%{public}s, FileAccessHelperCB == nullptr", __func__); + return WrapVoidToJS(env); + } + + fileAccessHelperCB->cbBase.cbInfo.env = env; + fileAccessHelperCB->cbBase.errCode = NAPI_ERR_NO_ERROR; + fileAccessHelperCB->cbBase.abilityType = abilityType; + napi_value ret = AcquireFileAccessHelperWrap(env, info, fileAccessHelperCB); + if (ret == nullptr) { + HILOG_ERROR("%{public}s, ret == nullptr", __func__); + if (fileAccessHelperCB != nullptr) { + delete fileAccessHelperCB; + fileAccessHelperCB = nullptr; + } + ret = WrapVoidToJS(env); + } + return ret; +} + +napi_value NAPI_CreateFileAccessHelper(napi_env env, napi_callback_info info) +{ + return NAPI_AcquireFileAccessHelperCommon(env, info, AbilityType::EXTENSION); +} + +napi_value FileAccessHelperInit(napi_env env, napi_value exports) +{ + napi_property_descriptor properties[] = { + DECLARE_NAPI_FUNCTION("openFile", NAPI_OpenFile), + DECLARE_NAPI_FUNCTION("mkdir", NAPI_Mkdir), + DECLARE_NAPI_FUNCTION("createFile", NAPI_CreateFile), + DECLARE_NAPI_FUNCTION("delete", NAPI_Delete), + DECLARE_NAPI_FUNCTION("move", NAPI_Move), + DECLARE_NAPI_FUNCTION("rename", NAPI_Rename), + DECLARE_NAPI_FUNCTION("listFile", NAPI_ListFile), + DECLARE_NAPI_FUNCTION("getRoots", NAPI_GetRoots), + }; + napi_value cons = nullptr; + NAPI_CALL(env, + napi_define_class(env, + FILEACCESS_CLASS_NAME.c_str(), + NAPI_AUTO_LENGTH, + FileAccessHelperConstructor, + nullptr, + sizeof(properties) / sizeof(*properties), + properties, + &cons)); + g_fileAccessHelperList.clear(); + NAPI_CALL(env, napi_create_reference(env, cons, 1, &g_constructorRef)); + NAPI_CALL(env, napi_set_named_property(env, exports, FILEACCESS_CLASS_NAME.c_str(), cons)); + + napi_property_descriptor export_properties[] = { + DECLARE_NAPI_FUNCTION("createFileAccessHelper", NAPI_CreateFileAccessHelper), + }; + NAPI_CALL(env, napi_define_properties(env, exports, sizeof(export_properties) / sizeof(export_properties[0]), + export_properties)); + return exports; +} + +napi_value FileAccessHelperConstructor(napi_env env, napi_callback_info info) +{ + size_t argc = ARGS_TWO; + napi_value argv[ARGS_TWO] = {nullptr}; + napi_value thisVar = nullptr; + NAPI_CALL(env, napi_get_cb_info(env, info, &argc, argv, &thisVar, nullptr)); + NAPI_ASSERT(env, argc > 0, "Wrong number of arguments"); + AAFwk::Want want; + OHOS::AppExecFwk::UnwrapWant(env, argv[PARAM1], want); + std::shared_ptr fileAccessHelper = nullptr; + bool isStageMode = false; + napi_status status = AbilityRuntime::IsStageContext(env, argv[PARAM0], isStageMode); + if (status != napi_ok || !isStageMode) { + HILOG_INFO(" FA Model"); + return nullptr; + } + + auto context = OHOS::AbilityRuntime::GetStageModeContext(env, argv[PARAM0]); + NAPI_ASSERT(env, context != nullptr, " FileAccessHelperConstructor: failed to get native context"); + HILOG_INFO(" Stage Model"); + fileAccessHelper = FileAccessHelper::Creator(context, want); + + NAPI_ASSERT(env, fileAccessHelper != nullptr, " FileAccessHelperConstructor: fileAccessHelper is nullptr"); + g_fileAccessHelperList.emplace_back(fileAccessHelper); + + napi_wrap(env, thisVar, fileAccessHelper.get(), [](napi_env env, void *data, void *hint) { + FileAccessHelper *objectInfo = static_cast(data); + g_fileAccessHelperList.remove_if([objectInfo](const std::shared_ptr &fileAccessHelper) { + return objectInfo == fileAccessHelper.get(); + }); + }, nullptr, nullptr); + return thisVar; +} + +napi_value NAPI_OpenFile(napi_env env, napi_callback_info info) +{ + HILOG_INFO("%{public}s,called start", __func__); + NFuncArg funcArg(env, info); + if (!funcArg.InitArgs(NARG_CNT::TWO, NARG_CNT::THREE)) { + HILOG_ERROR("%{public}s, Number of arguments unmatched.", __func__); + UniError(EINVAL).ThrowErr(env, "Number of arguments unmatched"); + return nullptr; + } + if (funcArg.GetArgc() == NARG_CNT::THREE && !NVal(env, funcArg[NARG_POS::THIRD]).TypeIs(napi_function)) { + UniError(EINVAL).ThrowErr(env, "Type of arguments unmatched"); + return nullptr; + } + FileAccessHelperOpenFileCB *openFileCB = new (std::nothrow) FileAccessHelperOpenFileCB; + if (openFileCB == nullptr) { + HILOG_ERROR("%{public}s, openFileCB == nullptr.", __func__); + return WrapVoidToJS(env); + } + openFileCB->cbBase.cbInfo.env = env; + openFileCB->cbBase.asyncWork = nullptr; + openFileCB->cbBase.deferred = nullptr; + openFileCB->cbBase.ability = nullptr; + + napi_value ret = OpenFileWrap(env, info, openFileCB); + if (ret == nullptr) { + HILOG_ERROR("%{public}s,ret == nullptr", __func__); + if (openFileCB != nullptr) { + delete openFileCB; + openFileCB = nullptr; + } + ret = WrapVoidToJS(env); + } + return ret; +} + +napi_value OpenFileWrap(napi_env env, napi_callback_info info, FileAccessHelperOpenFileCB *openFileCB) +{ + size_t argcAsync = ARGS_THREE; + const size_t argcPromise = ARGS_TWO; + const size_t argCountWithAsync = argcPromise + ARGS_ASYNC_COUNT; + napi_value args[ARGS_MAX_COUNT] = {nullptr}; + napi_value ret = 0; + napi_value thisVar = nullptr; + + NAPI_CALL(env, napi_get_cb_info(env, info, &argcAsync, args, &thisVar, nullptr)); + if (argcAsync > argCountWithAsync || argcAsync > ARGS_MAX_COUNT) { + HILOG_ERROR("%{public}s, Wrong argument count.", __func__); + return nullptr; + } + + napi_valuetype valueType = napi_undefined; + NAPI_CALL(env, napi_typeof(env, args[PARAM0], &valueType)); + if (valueType == napi_string) { + openFileCB->uri = NapiValueToStringUtf8(env, args[PARAM0]); + } else { + UniError(EINVAL).ThrowErr(env, "Type of arguments unmatched"); + return nullptr; + } + + NAPI_CALL(env, napi_typeof(env, args[PARAM1], &valueType)); + if (valueType == napi_number) { + openFileCB->flags = NapiValueToInt32Utf8(env, args[PARAM1]); + } else { + UniError(EINVAL).ThrowErr(env, "Type of arguments unmatched"); + return nullptr; + } + + FileAccessHelper *objectInfo = nullptr; + napi_unwrap(env, thisVar, (void **)&objectInfo); + openFileCB->fileAccessHelper = objectInfo; + + if (argcAsync > argcPromise) { + ret = OpenFileAsync(env, args, ARGS_TWO, openFileCB); + } else { + ret = OpenFilePromise(env, openFileCB); + } + return ret; +} + +napi_value OpenFileAsync(napi_env env, + napi_value *args, + const size_t argCallback, + FileAccessHelperOpenFileCB *openFileCB) +{ + if (args == nullptr || openFileCB == nullptr) { + HILOG_ERROR("%{public}s, param == nullptr.", __func__); + return nullptr; + } + napi_value resourceName = 0; + NAPI_CALL(env, napi_create_string_latin1(env, __func__, NAPI_AUTO_LENGTH, &resourceName)); + + napi_valuetype valuetype = napi_undefined; + NAPI_CALL(env, napi_typeof(env, args[argCallback], &valuetype)); + if (valuetype == napi_function) { + NAPI_CALL(env, napi_create_reference(env, args[argCallback], 1, &openFileCB->cbBase.cbInfo.callback)); + } + + NAPI_CALL(env, + napi_create_async_work(env, + nullptr, + resourceName, + OpenFileExecuteCB, + OpenFileAsyncCompleteCB, + (void *)openFileCB, + &openFileCB->cbBase.asyncWork)); + NAPI_CALL(env, napi_queue_async_work(env, openFileCB->cbBase.asyncWork)); + napi_value result = 0; + NAPI_CALL(env, napi_get_null(env, &result)); + return result; +} + +napi_value OpenFilePromise(napi_env env, FileAccessHelperOpenFileCB *openFileCB) +{ + if (openFileCB == nullptr) { + HILOG_ERROR("%{public}s, param == nullptr.", __func__); + return nullptr; + } + napi_value resourceName; + NAPI_CALL(env, napi_create_string_latin1(env, __func__, NAPI_AUTO_LENGTH, &resourceName)); + napi_deferred deferred; + napi_value promise = 0; + NAPI_CALL(env, napi_create_promise(env, &deferred, &promise)); + openFileCB->cbBase.deferred = deferred; + + NAPI_CALL(env, + napi_create_async_work(env, + nullptr, + resourceName, + OpenFileExecuteCB, + OpenFilePromiseCompleteCB, + (void *)openFileCB, + &openFileCB->cbBase.asyncWork)); + NAPI_CALL(env, napi_queue_async_work(env, openFileCB->cbBase.asyncWork)); + return promise; +} + +void OpenFileExecuteCB(napi_env env, void *data) +{ + FileAccessHelperOpenFileCB *openFileCB = static_cast(data); + openFileCB->execResult = -1; + if(openFileCB->fileAccessHelper == nullptr) { + HILOG_ERROR(" NAPI_OpenFile, fileAccessHelper uri is empty"); + return ; + } + if(openFileCB->uri.empty()) + { + HILOG_ERROR(" NAPI_OpenFile, fileAccessHelper uri is empty"); + return ; + } + OHOS::Uri uri(openFileCB->uri); + openFileCB->result = openFileCB->fileAccessHelper->OpenFile(uri, openFileCB->flags); + openFileCB->execResult = ERR_OK; +} + +void OpenFileAsyncCompleteCB(napi_env env, napi_status status, void *data) +{ + FileAccessHelperOpenFileCB *openFileCB = static_cast(data); + napi_value callback = nullptr; + napi_value undefined = nullptr; + napi_value result[ARGS_TWO] = {nullptr}; + napi_value callResult = nullptr; + NAPI_CALL_RETURN_VOID(env, napi_get_undefined(env, &undefined)); + NAPI_CALL_RETURN_VOID(env, napi_get_reference_value(env, openFileCB->cbBase.cbInfo.callback, &callback)); + + result[PARAM0] = GetCallbackErrorValue(env, openFileCB->execResult); + napi_create_int32(env, openFileCB->result, &result[PARAM1]); + NAPI_CALL_RETURN_VOID(env, napi_call_function(env, undefined, callback, ARGS_TWO, &result[PARAM0], &callResult)); + + if (openFileCB->cbBase.cbInfo.callback != nullptr) { + NAPI_CALL_RETURN_VOID(env, napi_delete_reference(env, openFileCB->cbBase.cbInfo.callback)); + } + NAPI_CALL_RETURN_VOID(env, napi_delete_async_work(env, openFileCB->cbBase.asyncWork)); + delete openFileCB; + openFileCB = nullptr; +} + +void OpenFilePromiseCompleteCB(napi_env env, napi_status status, void *data) +{ + FileAccessHelperOpenFileCB *openFileCB = static_cast(data); + napi_value result = nullptr; + napi_create_int32(env, openFileCB->result, &result); + NAPI_CALL_RETURN_VOID(env, napi_resolve_deferred(env, openFileCB->cbBase.deferred, result)); + NAPI_CALL_RETURN_VOID(env, napi_delete_async_work(env, openFileCB->cbBase.asyncWork)); + delete openFileCB; + openFileCB = nullptr; +} + +napi_value NAPI_CreateFile(napi_env env, napi_callback_info info) +{ + HILOG_INFO("%{public}s,called", __func__); + NFuncArg funcArg(env, info); + if (!funcArg.InitArgs(NARG_CNT::TWO, NARG_CNT::THREE)) { + HILOG_ERROR("%{public}s, Number of arguments unmatched.", __func__); + UniError(EINVAL).ThrowErr(env, "Number of arguments unmatched"); + return nullptr; + } + if (funcArg.GetArgc() == NARG_CNT::THREE && !NVal(env, funcArg[NARG_POS::THIRD]).TypeIs(napi_function)) { + UniError(EINVAL).ThrowErr(env, "Type of arguments unmatched"); + return nullptr; + } + + FileAccessHelperCreateFileCB *createFileCB = new (std::nothrow) FileAccessHelperCreateFileCB; + if (createFileCB == nullptr) { + HILOG_ERROR("%{public}s, createFileCB == nullptr.", __func__); + return WrapVoidToJS(env); + } + createFileCB->cbBase.cbInfo.env = env; + createFileCB->cbBase.asyncWork = nullptr; + createFileCB->cbBase.deferred = nullptr; + createFileCB->cbBase.ability = nullptr; + + napi_value ret = CreateFileWrap(env, info, createFileCB); + if (ret == nullptr) { + HILOG_ERROR("%{public}s,ret == nullptr", __func__); + if (createFileCB != nullptr) { + delete createFileCB; + createFileCB = nullptr; + } + ret = WrapVoidToJS(env); + } + return ret; +} + +napi_value CreateFileWrap(napi_env env, napi_callback_info info, FileAccessHelperCreateFileCB *createFileCB) +{ + size_t argcAsync = ARGS_THREE; + const size_t argcPromise = ARGS_TWO; + const size_t argCountWithAsync = argcPromise + ARGS_ASYNC_COUNT; + napi_value args[ARGS_MAX_COUNT] = {nullptr}; + napi_value ret = 0; + napi_value thisVar = nullptr; + + NAPI_CALL(env, napi_get_cb_info(env, info, &argcAsync, args, &thisVar, nullptr)); + if (argcAsync > argCountWithAsync || argcAsync > ARGS_MAX_COUNT) { + HILOG_ERROR("%{public}s, Wrong argument count.", __func__); + return nullptr; + } + + napi_valuetype valuetype = napi_undefined; + NAPI_CALL(env, napi_typeof(env, args[PARAM0], &valuetype)); + if (valuetype == napi_string) { + createFileCB->parentUri = NapiValueToStringUtf8(env, args[PARAM0]); + } else { + UniError(EINVAL).ThrowErr(env, "Type of arguments unmatched"); + return nullptr; + } + + NAPI_CALL(env, napi_typeof(env, args[PARAM1], &valuetype)); + if (valuetype == napi_string) { + createFileCB->name = NapiValueToStringUtf8(env, args[PARAM1]); + } else { + UniError(EINVAL).ThrowErr(env, "Type of arguments unmatched"); + return nullptr; + } + + FileAccessHelper *objectInfo = nullptr; + napi_unwrap(env, thisVar, (void **)&objectInfo); + createFileCB->fileAccessHelper = objectInfo; + + if (argcAsync > argcPromise) { + ret = CreateFileAsync(env, args, ARGS_TWO, createFileCB); + } else { + ret = CreateFilePromise(env, createFileCB); + } + return ret; +} + +napi_value CreateFileAsync(napi_env env, + napi_value *args, + const size_t argCallback, + FileAccessHelperCreateFileCB *createFileCB) +{ + if (args == nullptr || createFileCB == nullptr) { + HILOG_ERROR("%{public}s, param == nullptr.", __func__); + return nullptr; + } + napi_value resourceName = 0; + NAPI_CALL(env, napi_create_string_latin1(env, __func__, NAPI_AUTO_LENGTH, &resourceName)); + + napi_valuetype valuetype = napi_undefined; + NAPI_CALL(env, napi_typeof(env, args[argCallback], &valuetype)); + if (valuetype == napi_function) { + NAPI_CALL(env, napi_create_reference(env, args[argCallback], 1, &createFileCB->cbBase.cbInfo.callback)); + } + + NAPI_CALL(env, + napi_create_async_work(env, + nullptr, + resourceName, + CreateFileExecuteCB, + CreateFileAsyncCompleteCB, + (void *)createFileCB, + &createFileCB->cbBase.asyncWork)); + NAPI_CALL(env, napi_queue_async_work(env, createFileCB->cbBase.asyncWork)); + napi_value result = 0; + NAPI_CALL(env, napi_get_null(env, &result)); + return result; +} + +napi_value CreateFilePromise(napi_env env, FileAccessHelperCreateFileCB *createFileCB) +{ + if (createFileCB == nullptr) { + HILOG_ERROR("%{public}s, param == nullptr.", __func__); + return nullptr; + } + napi_value resourceName; + NAPI_CALL(env, napi_create_string_latin1(env, __func__, NAPI_AUTO_LENGTH, &resourceName)); + napi_deferred deferred; + napi_value promise = 0; + NAPI_CALL(env, napi_create_promise(env, &deferred, &promise)); + createFileCB->cbBase.deferred = deferred; + + NAPI_CALL(env, + napi_create_async_work(env, + nullptr, + resourceName, + CreateFileExecuteCB, + CreateFilePromiseCompleteCB, + (void *)createFileCB, + &createFileCB->cbBase.asyncWork)); + NAPI_CALL(env, napi_queue_async_work(env, createFileCB->cbBase.asyncWork)); + return promise; +} + +void CreateFileExecuteCB(napi_env env, void *data) +{ + FileAccessHelperCreateFileCB *createFileCB = static_cast(data); + createFileCB->execResult = -1; + if(createFileCB->fileAccessHelper == nullptr) { + HILOG_ERROR(" NAPI_OpenFile, fileAccessHelper uri is empty"); + return ; + } + if(createFileCB->parentUri.empty()) + { + HILOG_ERROR(" NAPI_OpenFile, fileAccessHelper uri is empty"); + return ; + } + OHOS::Uri parentUri(createFileCB->parentUri); + std::string newFile = ""; + OHOS::Uri newFileUri(newFile); + int err = createFileCB->fileAccessHelper->CreateFile(parentUri, createFileCB->name, newFileUri); + createFileCB->result = newFileUri.ToString(); + createFileCB->execResult = err; +} + +void CreateFileAsyncCompleteCB(napi_env env, napi_status status, void *data) +{ + FileAccessHelperCreateFileCB *createFileCB = static_cast(data); + napi_value callback = nullptr; + napi_value undefined = nullptr; + napi_value result[ARGS_TWO] = {nullptr}; + napi_value callResult = nullptr; + NAPI_CALL_RETURN_VOID(env, napi_get_undefined(env, &undefined)); + NAPI_CALL_RETURN_VOID(env, napi_get_reference_value(env, createFileCB->cbBase.cbInfo.callback, &callback)); + + result[PARAM0] = GetCallbackErrorValue(env, createFileCB->execResult); + NAPI_CALL_RETURN_VOID( + env, napi_create_string_utf8(env, createFileCB->result.c_str(), NAPI_AUTO_LENGTH, &result[PARAM1])); + NAPI_CALL_RETURN_VOID(env, napi_call_function(env, undefined, callback, ARGS_TWO, &result[PARAM0], &callResult)); + + if (createFileCB->cbBase.cbInfo.callback != nullptr) { + NAPI_CALL_RETURN_VOID(env, napi_delete_reference(env, createFileCB->cbBase.cbInfo.callback)); + } + NAPI_CALL_RETURN_VOID(env, napi_delete_async_work(env, createFileCB->cbBase.asyncWork)); + delete createFileCB; + createFileCB = nullptr; +} + +void CreateFilePromiseCompleteCB(napi_env env, napi_status status, void *data) +{ + FileAccessHelperCreateFileCB *createFileCB = static_cast(data); + napi_value result = nullptr; + NAPI_CALL_RETURN_VOID(env, napi_create_string_utf8(env, createFileCB->result.c_str(), NAPI_AUTO_LENGTH, &result)); + NAPI_CALL_RETURN_VOID(env, napi_resolve_deferred(env, createFileCB->cbBase.deferred, result)); + NAPI_CALL_RETURN_VOID(env, napi_delete_async_work(env, createFileCB->cbBase.asyncWork)); + delete createFileCB; + createFileCB = nullptr; +} + +napi_value NAPI_Mkdir(napi_env env, napi_callback_info info) +{ + HILOG_INFO("%{public}s,called", __func__); + NFuncArg funcArg(env, info); + if (!funcArg.InitArgs(NARG_CNT::TWO, NARG_CNT::THREE)) { + HILOG_ERROR("%{public}s, Number of arguments unmatched-------2-----------.", __func__); + UniError(EINVAL).ThrowErr(env, "Number of arguments unmatched"); + return nullptr; + } + if (funcArg.GetArgc() == NARG_CNT::THREE && !NVal(env, funcArg[NARG_POS::THIRD]).TypeIs(napi_function)) { + HILOG_INFO("%{public}s,-------------2-------------arguments check", __func__); + UniError(EINVAL).ThrowErr(env, "Type of arguments unmatched"); + return nullptr; + } + + FileAccessHelperMkdirCB *mkdirCB = new (std::nothrow) FileAccessHelperMkdirCB; + if (mkdirCB == nullptr) { + HILOG_ERROR("%{public}s, mkdirCB == nullptr.", __func__); + return WrapVoidToJS(env); + } + mkdirCB->cbBase.cbInfo.env = env; + mkdirCB->cbBase.asyncWork = nullptr; + mkdirCB->cbBase.deferred = nullptr; + mkdirCB->cbBase.ability = nullptr; + + napi_value ret = MkdirWrap(env, info, mkdirCB); + if (ret == nullptr) { + HILOG_ERROR("%{public}s,ret == nullptr", __func__); + if (mkdirCB != nullptr) { + delete mkdirCB; + mkdirCB = nullptr; + } + ret = WrapVoidToJS(env); + } + return ret; +} + +napi_value MkdirWrap(napi_env env, napi_callback_info info, FileAccessHelperMkdirCB *mkdirCB) +{ + size_t argcAsync = ARGS_THREE; + const size_t argcPromise = ARGS_TWO; + const size_t argCountWithAsync = argcPromise + ARGS_ASYNC_COUNT; + napi_value args[ARGS_MAX_COUNT] = {nullptr}; + napi_value ret = 0; + napi_value thisVar = nullptr; + + NAPI_CALL(env, napi_get_cb_info(env, info, &argcAsync, args, &thisVar, nullptr)); + if (argcAsync > argCountWithAsync || argcAsync > ARGS_MAX_COUNT) { + HILOG_ERROR("%{public}s, Wrong argument count.", __func__); + return nullptr; + } + + napi_valuetype valuetype = napi_undefined; + NAPI_CALL(env, napi_typeof(env, args[PARAM0], &valuetype)); + if (valuetype == napi_string) { + mkdirCB->parentUri = NapiValueToStringUtf8(env, args[PARAM0]); + HILOG_INFO("%{public}s,parentUri= %{public}s", __func__, mkdirCB->parentUri.c_str()); + } else { + UniError(EINVAL).ThrowErr(env, "Type of arguments unmatched"); + return nullptr; + } + + NAPI_CALL(env, napi_typeof(env, args[PARAM1], &valuetype)); + if (valuetype == napi_string) { + mkdirCB->name = NapiValueToStringUtf8(env, args[PARAM1]); + HILOG_INFO("%{public}s,name= %{public}s", __func__, mkdirCB->name.c_str()); + } else { + UniError(EINVAL).ThrowErr(env, "Type of arguments unmatched"); + return nullptr; + } + + FileAccessHelper *objectInfo = nullptr; + napi_unwrap(env, thisVar, (void **)&objectInfo); + mkdirCB->fileAccessHelper = objectInfo; + + if (argcAsync > argcPromise) { + ret = MkdirAsync(env, args, ARGS_TWO, mkdirCB); + } else { + ret = MkdirPromise(env, mkdirCB); + } + return ret; +} + +napi_value MkdirAsync(napi_env env, napi_value *args, const size_t argCallback, FileAccessHelperMkdirCB *mkdirCB) +{ + if (args == nullptr || mkdirCB == nullptr) { + HILOG_ERROR("%{public}s, param == nullptr.", __func__); + return nullptr; + } + napi_value resourceName = 0; + NAPI_CALL(env, napi_create_string_latin1(env, __func__, NAPI_AUTO_LENGTH, &resourceName)); + + napi_valuetype valuetype = napi_undefined; + NAPI_CALL(env, napi_typeof(env, args[argCallback], &valuetype)); + if (valuetype == napi_function) { + NAPI_CALL(env, napi_create_reference(env, args[argCallback], 1, &mkdirCB->cbBase.cbInfo.callback)); + } + + NAPI_CALL(env, + napi_create_async_work(env, + nullptr, + resourceName, + MkdirExecuteCB, + MkdirAsyncCompleteCB, + (void *)mkdirCB, + &mkdirCB->cbBase.asyncWork)); + NAPI_CALL(env, napi_queue_async_work(env, mkdirCB->cbBase.asyncWork)); + napi_value result = 0; + NAPI_CALL(env, napi_get_null(env, &result)); + return result; +} + +napi_value MkdirPromise(napi_env env, FileAccessHelperMkdirCB *mkdirCB) +{ + if (mkdirCB == nullptr) { + HILOG_ERROR("%{public}s, param == nullptr.", __func__); + return nullptr; + } + napi_value resourceName; + NAPI_CALL(env, napi_create_string_latin1(env, __func__, NAPI_AUTO_LENGTH, &resourceName)); + napi_deferred deferred; + napi_value promise = 0; + NAPI_CALL(env, napi_create_promise(env, &deferred, &promise)); + mkdirCB->cbBase.deferred = deferred; + + NAPI_CALL(env, + napi_create_async_work(env, + nullptr, + resourceName, + MkdirExecuteCB, + MkdirPromiseCompleteCB, + (void *)mkdirCB, + &mkdirCB->cbBase.asyncWork)); + NAPI_CALL(env, napi_queue_async_work(env, mkdirCB->cbBase.asyncWork)); + return promise; +} + +void MkdirExecuteCB(napi_env env, void *data) +{ + FileAccessHelperMkdirCB *mkdirCB = static_cast(data); + mkdirCB->execResult = -1; + if(mkdirCB->fileAccessHelper == nullptr) { + HILOG_ERROR(" NAPI_mkdirCB, fileAccessHelper uri is empty"); + return ; + } + if(mkdirCB->parentUri.empty()) + { + HILOG_ERROR(" NAPI_mkdirCB, fileAccessHelper uri is empty"); + return ; + } + OHOS::Uri parentUri(mkdirCB->parentUri); + std::string newDir = ""; + OHOS::Uri newDirUri(newDir); + int err = mkdirCB->fileAccessHelper->Mkdir(parentUri, mkdirCB->name, newDirUri); + mkdirCB->result = newDirUri.ToString(); + mkdirCB->execResult = err; + return ; +} + +void MkdirAsyncCompleteCB(napi_env env, napi_status status, void *data) +{ + FileAccessHelperMkdirCB *mkdirCB = static_cast(data); + napi_value callback = nullptr; + napi_value undefined = nullptr; + napi_value result[ARGS_TWO] = {nullptr}; + napi_value callResult = nullptr; + NAPI_CALL_RETURN_VOID(env, napi_get_undefined(env, &undefined)); + NAPI_CALL_RETURN_VOID(env, napi_get_reference_value(env, mkdirCB->cbBase.cbInfo.callback, &callback)); + + result[PARAM0] = GetCallbackErrorValue(env, mkdirCB->execResult); + NAPI_CALL_RETURN_VOID( + env, napi_create_string_utf8(env, mkdirCB->result.c_str(), NAPI_AUTO_LENGTH, &result[PARAM1])); + NAPI_CALL_RETURN_VOID(env, napi_call_function(env, undefined, callback, ARGS_TWO, &result[PARAM0], &callResult)); + + if (mkdirCB->cbBase.cbInfo.callback != nullptr) { + NAPI_CALL_RETURN_VOID(env, napi_delete_reference(env, mkdirCB->cbBase.cbInfo.callback)); + } + NAPI_CALL_RETURN_VOID(env, napi_delete_async_work(env, mkdirCB->cbBase.asyncWork)); + delete mkdirCB; + mkdirCB = nullptr; +} + +void MkdirPromiseCompleteCB(napi_env env, napi_status status, void *data) +{ + FileAccessHelperMkdirCB *mkdirCB = static_cast(data); + napi_value result = nullptr; + NAPI_CALL_RETURN_VOID(env, napi_create_string_utf8(env, mkdirCB->result.c_str(), NAPI_AUTO_LENGTH, &result)); + NAPI_CALL_RETURN_VOID(env, napi_resolve_deferred(env, mkdirCB->cbBase.deferred, result)); + NAPI_CALL_RETURN_VOID(env, napi_delete_async_work(env, mkdirCB->cbBase.asyncWork)); + delete mkdirCB; + mkdirCB = nullptr; +} + +napi_value NAPI_Delete(napi_env env, napi_callback_info info) +{ + HILOG_INFO("%{public}s,called", __func__); + NFuncArg funcArg(env, info); + if (!funcArg.InitArgs(NARG_CNT::ONE, NARG_CNT::TWO)) { + HILOG_ERROR("%{public}s, Number of arguments unmatched-------2-----------.", __func__); + UniError(EINVAL).ThrowErr(env, "Number of arguments unmatched"); + return nullptr; + } + if (funcArg.GetArgc() == NARG_CNT::TWO && !NVal(env, funcArg[NARG_POS::SECOND]).TypeIs(napi_function)) { + HILOG_INFO("%{public}s,-------------2-------------arguments check", __func__); + UniError(EINVAL).ThrowErr(env, "Type of arguments unmatched"); + return nullptr; + } + + FileAccessHelperDeleteCB *deleteCB = new (std::nothrow) FileAccessHelperDeleteCB; + if (deleteCB == nullptr) { + HILOG_ERROR("%{public}s, deleteCB == nullptr.", __func__); + return WrapVoidToJS(env); + } + deleteCB->cbBase.cbInfo.env = env; + deleteCB->cbBase.asyncWork = nullptr; + deleteCB->cbBase.deferred = nullptr; + deleteCB->cbBase.ability = nullptr; + + napi_value ret = DeleteWrap(env, info, deleteCB); + if (ret == nullptr) { + HILOG_ERROR("%{public}s,ret == nullptr", __func__); + if (deleteCB != nullptr) { + delete deleteCB; + deleteCB = nullptr; + } + ret = WrapVoidToJS(env); + } + return ret; +} + +napi_value DeleteWrap(napi_env env, napi_callback_info info, FileAccessHelperDeleteCB *deleteCB) +{ + size_t argcAsync = ARGS_TWO; + const size_t argcPromise = ARGS_ONE; + const size_t argCountWithAsync = argcPromise + ARGS_ASYNC_COUNT; + napi_value args[ARGS_MAX_COUNT] = {nullptr}; + napi_value ret = 0; + napi_value thisVar = nullptr; + + NAPI_CALL(env, napi_get_cb_info(env, info, &argcAsync, args, &thisVar, nullptr)); + if (argcAsync > argCountWithAsync || argcAsync > ARGS_MAX_COUNT) { + HILOG_ERROR("%{public}s, Wrong argument count.", __func__); + return nullptr; + } + + napi_valuetype valuetype = napi_undefined; + NAPI_CALL(env, napi_typeof(env, args[PARAM0], &valuetype)); + if (valuetype == napi_string) { + deleteCB->selectFileUri = NapiValueToStringUtf8(env, args[PARAM0]); + } else { + UniError(EINVAL).ThrowErr(env, "Type of arguments unmatched"); + return nullptr; + } + + FileAccessHelper *objectInfo = nullptr; + napi_unwrap(env, thisVar, (void **)&objectInfo); + deleteCB->fileAccessHelper = objectInfo; + + if (argcAsync > argcPromise) { + ret = DeleteAsync(env, args, ARGS_ONE, deleteCB); + } else { + ret = DeletePromise(env, deleteCB); + } + return ret; +} + +napi_value DeleteAsync(napi_env env, napi_value *args, const size_t argCallback, FileAccessHelperDeleteCB *deleteCB) +{ + if (args == nullptr || deleteCB == nullptr) { + HILOG_ERROR("%{public}s, param == nullptr.", __func__); + return nullptr; + } + napi_value resourceName = 0; + NAPI_CALL(env, napi_create_string_latin1(env, __func__, NAPI_AUTO_LENGTH, &resourceName)); + + napi_valuetype valuetype = napi_undefined; + NAPI_CALL(env, napi_typeof(env, args[argCallback], &valuetype)); + if (valuetype == napi_function) { + NAPI_CALL(env, napi_create_reference(env, args[argCallback], 1, &deleteCB->cbBase.cbInfo.callback)); + } + + NAPI_CALL(env, + napi_create_async_work(env, + nullptr, + resourceName, + DeleteExecuteCB, + DeleteAsyncCompleteCB, + (void *)deleteCB, + &deleteCB->cbBase.asyncWork)); + NAPI_CALL(env, napi_queue_async_work(env, deleteCB->cbBase.asyncWork)); + napi_value result = 0; + NAPI_CALL(env, napi_get_null(env, &result)); + return result; +} + +napi_value DeletePromise(napi_env env, FileAccessHelperDeleteCB *deleteCB) +{ + if (deleteCB == nullptr) { + HILOG_ERROR("%{public}s, param == nullptr.", __func__); + return nullptr; + } + napi_value resourceName; + NAPI_CALL(env, napi_create_string_latin1(env, __func__, NAPI_AUTO_LENGTH, &resourceName)); + napi_deferred deferred; + napi_value promise = 0; + NAPI_CALL(env, napi_create_promise(env, &deferred, &promise)); + deleteCB->cbBase.deferred = deferred; + + NAPI_CALL(env, + napi_create_async_work(env, + nullptr, + resourceName, + DeleteExecuteCB, + DeletePromiseCompleteCB, + (void *)deleteCB, + &deleteCB->cbBase.asyncWork)); + NAPI_CALL(env, napi_queue_async_work(env, deleteCB->cbBase.asyncWork)); + return promise; +} + +void DeleteExecuteCB(napi_env env, void *data) +{ + FileAccessHelperDeleteCB *deleteCB = static_cast(data); + deleteCB->execResult = -1; + if(deleteCB->fileAccessHelper == nullptr) { + HILOG_ERROR(" NAPI_deleteCB, fileAccessHelper uri is empty"); + return ; + } + if(deleteCB->selectFileUri.empty()) + { + HILOG_ERROR(" NAPI_deleteCB, fileAccessHelper uri is empty"); + return ; + } + + OHOS::Uri selectFileUri(deleteCB->selectFileUri); + deleteCB->result = deleteCB->fileAccessHelper->Delete(selectFileUri); + deleteCB->execResult = ERR_OK; + return ; +} + +void DeleteAsyncCompleteCB(napi_env env, napi_status status, void *data) +{ + FileAccessHelperDeleteCB *deleteCB = static_cast(data); + napi_value callback = nullptr; + napi_value undefined = nullptr; + napi_value result[ARGS_TWO] = {nullptr}; + napi_value callResult = nullptr; + NAPI_CALL_RETURN_VOID(env, napi_get_undefined(env, &undefined)); + NAPI_CALL_RETURN_VOID(env, napi_get_reference_value(env, deleteCB->cbBase.cbInfo.callback, &callback)); + + result[PARAM0] = GetCallbackErrorValue(env, deleteCB->execResult); + napi_create_int32(env, deleteCB->result, &result[PARAM1]); + NAPI_CALL_RETURN_VOID(env, napi_call_function(env, undefined, callback, ARGS_TWO, &result[PARAM0], &callResult)); + + if (deleteCB->cbBase.cbInfo.callback != nullptr) { + NAPI_CALL_RETURN_VOID(env, napi_delete_reference(env, deleteCB->cbBase.cbInfo.callback)); + } + NAPI_CALL_RETURN_VOID(env, napi_delete_async_work(env, deleteCB->cbBase.asyncWork)); + delete deleteCB; + deleteCB = nullptr; +} + +void DeletePromiseCompleteCB(napi_env env, napi_status status, void *data) +{ + FileAccessHelperDeleteCB *deleteCB = static_cast(data); + napi_value result = nullptr; + napi_create_int32(env, deleteCB->result, &result); + NAPI_CALL_RETURN_VOID(env, napi_resolve_deferred(env, deleteCB->cbBase.deferred, result)); + NAPI_CALL_RETURN_VOID(env, napi_delete_async_work(env, deleteCB->cbBase.asyncWork)); + delete deleteCB; + deleteCB = nullptr; +} + +napi_value NAPI_Move(napi_env env, napi_callback_info info) +{ + HILOG_INFO("%{public}s,called", __func__); + NFuncArg funcArg(env, info); + if (!funcArg.InitArgs(NARG_CNT::TWO, NARG_CNT::THREE)) { + HILOG_ERROR("%{public}s, Number of arguments unmatched-------2-----------.", __func__); + UniError(EINVAL).ThrowErr(env, "Number of arguments unmatched"); + return nullptr; + } + if (funcArg.GetArgc() == NARG_CNT::THREE && !NVal(env, funcArg[NARG_POS::THIRD]).TypeIs(napi_function)) { + HILOG_INFO("%{public}s,-------------2-------------arguments check", __func__); + UniError(EINVAL).ThrowErr(env, "Type of arguments unmatched"); + return nullptr; + } + + FileAccessHelperMoveCB *moveCB = new (std::nothrow) FileAccessHelperMoveCB; + if (moveCB == nullptr) { + HILOG_ERROR("%{public}s, moveCB == nullptr.", __func__); + return WrapVoidToJS(env); + } + moveCB->cbBase.cbInfo.env = env; + moveCB->cbBase.asyncWork = nullptr; + moveCB->cbBase.deferred = nullptr; + moveCB->cbBase.ability = nullptr; + + napi_value ret = MoveWrap(env, info, moveCB); + if (ret == nullptr) { + HILOG_ERROR("%{public}s,ret == nullptr", __func__); + if (moveCB != nullptr) { + delete moveCB; + moveCB = nullptr; + } + ret = WrapVoidToJS(env); + } + return ret; +} + +napi_value MoveWrap(napi_env env, napi_callback_info info, FileAccessHelperMoveCB *moveCB) +{ + size_t argcAsync = ARGS_THREE; + const size_t argcPromise = ARGS_TWO; + const size_t argCountWithAsync = argcPromise + ARGS_ASYNC_COUNT; + napi_value args[ARGS_MAX_COUNT] = {nullptr}; + napi_value ret = 0; + napi_value thisVar = nullptr; + + NAPI_CALL(env, napi_get_cb_info(env, info, &argcAsync, args, &thisVar, nullptr)); + if (argcAsync > argCountWithAsync || argcAsync > ARGS_MAX_COUNT) { + HILOG_ERROR("%{public}s, Wrong argument count.", __func__); + return nullptr; + } + + napi_valuetype valuetype = napi_undefined; + NAPI_CALL(env, napi_typeof(env, args[PARAM0], &valuetype)); + if (valuetype == napi_string) { + moveCB->sourceFileUri = NapiValueToStringUtf8(env, args[PARAM0]); + HILOG_INFO("%{public}s,sourceFileUri=%{public}s", __func__, moveCB->sourceFileUri.c_str()); + } else { + UniError(EINVAL).ThrowErr(env, "Type of arguments unmatched"); + return nullptr; + } + + NAPI_CALL(env, napi_typeof(env, args[PARAM1], &valuetype)); + if (valuetype == napi_string) { + moveCB->targetParentUri = NapiValueToStringUtf8(env, args[PARAM1]); + HILOG_INFO("%{public}s,targetParentUri=%{public}s", __func__, moveCB->targetParentUri.c_str()); + } else { + UniError(EINVAL).ThrowErr(env, "Type of arguments unmatched"); + return nullptr; + } + + FileAccessHelper *objectInfo = nullptr; + napi_unwrap(env, thisVar, (void **)&objectInfo); + moveCB->fileAccessHelper = objectInfo; + + if (argcAsync > argcPromise) { + ret = MoveAsync(env, args, ARGS_TWO, moveCB); + } else { + ret = MovePromise(env, moveCB); + } + return ret; +} + +napi_value MoveAsync(napi_env env, napi_value *args, const size_t argCallback, FileAccessHelperMoveCB *moveCB) +{ + if (args == nullptr || moveCB == nullptr) { + HILOG_ERROR("%{public}s, param == nullptr.", __func__); + return nullptr; + } + napi_value resourceName = 0; + NAPI_CALL(env, napi_create_string_latin1(env, __func__, NAPI_AUTO_LENGTH, &resourceName)); + + napi_valuetype valuetype = napi_undefined; + NAPI_CALL(env, napi_typeof(env, args[argCallback], &valuetype)); + if (valuetype == napi_function) { + NAPI_CALL(env, napi_create_reference(env, args[argCallback], 1, &moveCB->cbBase.cbInfo.callback)); + } + + NAPI_CALL(env, + napi_create_async_work(env, + nullptr, + resourceName, + MoveExecuteCB, + MoveAsyncCompleteCB, + (void *)moveCB, + &moveCB->cbBase.asyncWork)); + NAPI_CALL(env, napi_queue_async_work(env, moveCB->cbBase.asyncWork)); + napi_value result = 0; + NAPI_CALL(env, napi_get_null(env, &result)); + return result; +} + +napi_value MovePromise(napi_env env, FileAccessHelperMoveCB *moveCB) +{ + if (moveCB == nullptr) { + HILOG_ERROR("%{public}s, param == nullptr.", __func__); + return nullptr; + } + napi_value resourceName; + NAPI_CALL(env, napi_create_string_latin1(env, __func__, NAPI_AUTO_LENGTH, &resourceName)); + napi_deferred deferred; + napi_value promise = 0; + NAPI_CALL(env, napi_create_promise(env, &deferred, &promise)); + moveCB->cbBase.deferred = deferred; + + NAPI_CALL(env, + napi_create_async_work(env, + nullptr, + resourceName, + MoveExecuteCB, + MovePromiseCompleteCB, + (void *)moveCB, + &moveCB->cbBase.asyncWork)); + NAPI_CALL(env, napi_queue_async_work(env, moveCB->cbBase.asyncWork)); + return promise; +} + +void MoveExecuteCB(napi_env env, void *data) +{ + FileAccessHelperMoveCB *moveCB = static_cast(data); + moveCB->execResult = -1; + if(moveCB->fileAccessHelper == nullptr) { + HILOG_ERROR("NAPI_move, fileAccessHelper is nullptr"); + return ; + } + if(moveCB->sourceFileUri.empty()) + { + HILOG_ERROR("NAPI_move, fileAccessHelper uri is empty"); + return ; + } + OHOS::Uri sourceFileUri(moveCB->sourceFileUri); + OHOS::Uri targetParentUri(moveCB->targetParentUri); + std::string newFile = ""; + OHOS::Uri newFileUri(newFile); + int err = moveCB->fileAccessHelper->Move(sourceFileUri, targetParentUri, newFileUri); + moveCB->result = newFileUri.ToString(); + moveCB->execResult = err; + return ; +} + +void MoveAsyncCompleteCB(napi_env env, napi_status status, void *data) +{ + FileAccessHelperMoveCB *moveCB = static_cast(data); + if (moveCB == nullptr) { + return ; + } + napi_value callback = nullptr; + napi_value undefined = nullptr; + napi_value result[ARGS_TWO] = {nullptr}; + napi_value callResult = nullptr; + NAPI_CALL_RETURN_VOID(env, napi_get_undefined(env, &undefined)); + NAPI_CALL_RETURN_VOID(env, napi_get_reference_value(env, moveCB->cbBase.cbInfo.callback, &callback)); + + result[PARAM0] = GetCallbackErrorValue(env, moveCB->execResult); + NAPI_CALL_RETURN_VOID( + env, napi_create_string_utf8(env, moveCB->result.c_str(), NAPI_AUTO_LENGTH, &result[PARAM1])); + NAPI_CALL_RETURN_VOID(env, napi_call_function(env, undefined, callback, ARGS_TWO, &result[PARAM0], &callResult)); + + if (moveCB->cbBase.cbInfo.callback != nullptr) { + NAPI_CALL_RETURN_VOID(env, napi_delete_reference(env, moveCB->cbBase.cbInfo.callback)); + } + NAPI_CALL_RETURN_VOID(env, napi_delete_async_work(env, moveCB->cbBase.asyncWork)); + delete moveCB; + moveCB = nullptr; +} + +void MovePromiseCompleteCB(napi_env env, napi_status status, void *data) +{ + FileAccessHelperMoveCB *moveCB = static_cast(data); + napi_value result = nullptr; + NAPI_CALL_RETURN_VOID(env, napi_create_string_utf8(env, moveCB->result.c_str(), NAPI_AUTO_LENGTH, &result)); + NAPI_CALL_RETURN_VOID(env, napi_resolve_deferred(env, moveCB->cbBase.deferred, result)); + NAPI_CALL_RETURN_VOID(env, napi_delete_async_work(env, moveCB->cbBase.asyncWork)); + delete moveCB; + moveCB = nullptr; +} + +napi_value NAPI_Rename(napi_env env, napi_callback_info info) +{ + HILOG_INFO("%{public}s,called", __func__); + NFuncArg funcArg(env, info); + if (!funcArg.InitArgs(NARG_CNT::TWO, NARG_CNT::THREE)) { + HILOG_ERROR("%{public}s, Number of arguments unmatched-------2-----------.", __func__); + UniError(EINVAL).ThrowErr(env, "Number of arguments unmatched"); + return nullptr; + } + if (funcArg.GetArgc() == NARG_CNT::THREE && !NVal(env, funcArg[NARG_POS::THIRD]).TypeIs(napi_function)) { + HILOG_INFO("%{public}s,-------------2-------------arguments check", __func__); + UniError(EINVAL).ThrowErr(env, "Type of arguments unmatched"); + return nullptr; + } + FileAccessHelperRenameCB *renameCB = new (std::nothrow) FileAccessHelperRenameCB; + if (renameCB == nullptr) { + HILOG_ERROR("%{public}s, renameCB == nullptr.", __func__); + return WrapVoidToJS(env); + } + renameCB->cbBase.cbInfo.env = env; + renameCB->cbBase.asyncWork = nullptr; + renameCB->cbBase.deferred = nullptr; + renameCB->cbBase.ability = nullptr; + + napi_value ret = RenameWrap(env, info, renameCB); + if (ret == nullptr) { + HILOG_ERROR("%{public}s,ret == nullptr", __func__); + if (renameCB != nullptr) { + delete renameCB; + renameCB = nullptr; + } + ret = WrapVoidToJS(env); + } + return ret; +} + +napi_value RenameWrap(napi_env env, napi_callback_info info, FileAccessHelperRenameCB *renameCB) +{ + size_t argcAsync = ARGS_THREE; + const size_t argcPromise = ARGS_TWO; + const size_t argCountWithAsync = argcPromise + ARGS_ASYNC_COUNT; + napi_value args[ARGS_MAX_COUNT] = {nullptr}; + napi_value ret = 0; + napi_value thisVar = nullptr; + + NAPI_CALL(env, napi_get_cb_info(env, info, &argcAsync, args, &thisVar, nullptr)); + if (argcAsync > argCountWithAsync || argcAsync > ARGS_MAX_COUNT) { + HILOG_ERROR("%{public}s, Wrong argument count.", __func__); + return nullptr; + } + + napi_valuetype valuetype = napi_undefined; + NAPI_CALL(env, napi_typeof(env, args[PARAM0], &valuetype)); + if (valuetype == napi_string) { + renameCB->sourceFileUri = NapiValueToStringUtf8(env, args[PARAM0]); + HILOG_INFO("%{public}s,sourceFileUri= %{public}s", __func__, renameCB->sourceFileUri.c_str()); + } else { + UniError(EINVAL).ThrowErr(env, "Type of arguments unmatched"); + return nullptr; + } + + NAPI_CALL(env, napi_typeof(env, args[PARAM1], &valuetype)); + if (valuetype == napi_string) { + renameCB->displayName = NapiValueToStringUtf8(env, args[PARAM1]); + HILOG_INFO("%{public}s,displayName= %{public}s", __func__, renameCB->displayName.c_str()); + } else { + UniError(EINVAL).ThrowErr(env, "Type of arguments unmatched"); + return nullptr; + } + + FileAccessHelper *objectInfo = nullptr; + napi_unwrap(env, thisVar, (void **)&objectInfo); + renameCB->fileAccessHelper = objectInfo; + + if (argcAsync > argcPromise) { + ret = RenameAsync(env, args, ARGS_TWO, renameCB); + } else { + ret = RenamePromise(env, renameCB); + } + return ret; +} + +napi_value RenameAsync(napi_env env, napi_value *args, const size_t argCallback, FileAccessHelperRenameCB *renameCB) +{ + if (args == nullptr || renameCB == nullptr) { + HILOG_ERROR("%{public}s, param == nullptr.", __func__); + return nullptr; + } + napi_value resourceName = 0; + NAPI_CALL(env, napi_create_string_latin1(env, __func__, NAPI_AUTO_LENGTH, &resourceName)); + + napi_valuetype valuetype = napi_undefined; + NAPI_CALL(env, napi_typeof(env, args[argCallback], &valuetype)); + if (valuetype == napi_function) { + NAPI_CALL(env, napi_create_reference(env, args[argCallback], 1, &renameCB->cbBase.cbInfo.callback)); + } + + NAPI_CALL(env, + napi_create_async_work(env, + nullptr, + resourceName, + RenameExecuteCB, + RenameAsyncCompleteCB, + (void *)renameCB, + &renameCB->cbBase.asyncWork)); + NAPI_CALL(env, napi_queue_async_work(env, renameCB->cbBase.asyncWork)); + napi_value result = 0; + NAPI_CALL(env, napi_get_null(env, &result)); + return result; +} + +napi_value RenamePromise(napi_env env, FileAccessHelperRenameCB *renameCB) +{ + if (renameCB == nullptr) { + HILOG_ERROR("%{public}s, param == nullptr.", __func__); + return nullptr; + } + napi_value resourceName; + NAPI_CALL(env, napi_create_string_latin1(env, __func__, NAPI_AUTO_LENGTH, &resourceName)); + napi_deferred deferred; + napi_value promise = 0; + NAPI_CALL(env, napi_create_promise(env, &deferred, &promise)); + renameCB->cbBase.deferred = deferred; + + NAPI_CALL(env, + napi_create_async_work(env, + nullptr, + resourceName, + RenameExecuteCB, + RenamePromiseCompleteCB, + (void *)renameCB, + &renameCB->cbBase.asyncWork)); + NAPI_CALL(env, napi_queue_async_work(env, renameCB->cbBase.asyncWork)); + return promise; +} + +void RenameExecuteCB(napi_env env, void *data) +{ + FileAccessHelperRenameCB *renameCB = static_cast(data); + renameCB->execResult = -1; + if (renameCB->fileAccessHelper == nullptr) { + HILOG_ERROR("NAPI_Rename, fileAccessHelper == nullptr"); + return ; + } + if (renameCB->sourceFileUri.empty()) { + HILOG_ERROR("NAPI_Rename, fileAccessHelper sourceFileUri is empty"); + return ; + } + OHOS::Uri sourceFileUri(renameCB->sourceFileUri); + std::string newFile = ""; + OHOS::Uri newFileUri(newFile); + int err = renameCB->fileAccessHelper->Rename(sourceFileUri, renameCB->displayName, newFileUri); + renameCB->result = newFileUri.ToString(); + renameCB->execResult = err; +} + +void RenameAsyncCompleteCB(napi_env env, napi_status status, void *data) +{ + FileAccessHelperRenameCB *renameCB = static_cast(data); + napi_value callback = nullptr; + napi_value undefined = nullptr; + napi_value result[ARGS_TWO] = {nullptr}; + napi_value callResult = nullptr; + NAPI_CALL_RETURN_VOID(env, napi_get_undefined(env, &undefined)); + NAPI_CALL_RETURN_VOID(env, napi_get_reference_value(env, renameCB->cbBase.cbInfo.callback, &callback)); + + result[PARAM0] = GetCallbackErrorValue(env, renameCB->execResult); + NAPI_CALL_RETURN_VOID( + env, napi_create_string_utf8(env, renameCB->result.c_str(), NAPI_AUTO_LENGTH, &result[PARAM1])); + NAPI_CALL_RETURN_VOID(env, napi_call_function(env, undefined, callback, ARGS_TWO, &result[PARAM0], &callResult)); + + if (renameCB->cbBase.cbInfo.callback != nullptr) { + NAPI_CALL_RETURN_VOID(env, napi_delete_reference(env, renameCB->cbBase.cbInfo.callback)); + } + NAPI_CALL_RETURN_VOID(env, napi_delete_async_work(env, renameCB->cbBase.asyncWork)); + delete renameCB; + renameCB = nullptr; +} + +void RenamePromiseCompleteCB(napi_env env, napi_status status, void *data) +{ + FileAccessHelperRenameCB *renameCB = static_cast(data); + napi_value result = nullptr; + NAPI_CALL_RETURN_VOID(env, napi_create_string_utf8(env, renameCB->result.c_str(), NAPI_AUTO_LENGTH, &result)); + NAPI_CALL_RETURN_VOID(env, napi_resolve_deferred(env, renameCB->cbBase.deferred, result)); + NAPI_CALL_RETURN_VOID(env, napi_delete_async_work(env, renameCB->cbBase.asyncWork)); + delete renameCB; + renameCB = nullptr; +} + +napi_value NAPI_ListFile(napi_env env, napi_callback_info info) +{ + HILOG_INFO("%{public}s,called", __func__); + + + NFuncArg funcArg(env, info); + if (!funcArg.InitArgs(NARG_CNT::ONE, NARG_CNT::TWO)) { + HILOG_ERROR("%{public}s, Number of arguments unmatched-------2-----------.", __func__); + UniError(EINVAL).ThrowErr(env, "Number of arguments unmatched"); + return nullptr; + } + if (funcArg.GetArgc() == NARG_CNT::TWO && !NVal(env, funcArg[NARG_POS::SECOND]).TypeIs(napi_function)) { + UniError(EINVAL).ThrowErr(env, "Type of arguments unmatched"); + return nullptr; + } + + + FileAccessHelperListFileCB *listFileCB = new (std::nothrow) FileAccessHelperListFileCB; + if (listFileCB == nullptr) { + HILOG_ERROR("%{public}s, listFileCB == nullptr.", __func__); + return WrapVoidToJS(env); + } + listFileCB->cbBase.cbInfo.env = env; + listFileCB->cbBase.asyncWork = nullptr; + listFileCB->cbBase.deferred = nullptr; + listFileCB->cbBase.ability = nullptr; + + napi_value ret = ListFileWrap(env, info, listFileCB); + if (ret == nullptr) { + HILOG_ERROR("%{public}s,ret == nullptr", __func__); + if (listFileCB != nullptr) { + delete listFileCB; + listFileCB = nullptr; + } + ret = WrapVoidToJS(env); + } + return ret; +} + +napi_value ListFileWrap(napi_env env, napi_callback_info info, FileAccessHelperListFileCB *listFileCB) +{ + size_t argcAsync = ARGS_TWO; + const size_t argcPromise = ARGS_ONE; + const size_t argCountWithAsync = argcPromise + ARGS_ASYNC_COUNT; + napi_value args[ARGS_MAX_COUNT] = {nullptr}; + napi_value ret = 0; + napi_value thisVar = nullptr; + + NAPI_CALL(env, napi_get_cb_info(env, info, &argcAsync, args, &thisVar, nullptr)); + if (argcAsync > argCountWithAsync || argcAsync > ARGS_MAX_COUNT) { + HILOG_ERROR("%{public}s, Wrong argument count.", __func__); + return nullptr; + } + + napi_valuetype valuetype = napi_undefined; + NAPI_CALL(env, napi_typeof(env, args[PARAM0], &valuetype)); + if (valuetype == napi_string) { + listFileCB->sourceFileUri = NapiValueToStringUtf8(env, args[PARAM0]); + HILOG_INFO("%{public}s,sourceFileUri=%{public}s", __func__, listFileCB->sourceFileUri.c_str()); + } else { + UniError(EINVAL).ThrowErr(env, "Type of arguments unmatched"); + return nullptr; + } + + FileAccessHelper *objectInfo = nullptr; + napi_unwrap(env, thisVar, (void **)&objectInfo); + listFileCB->fileAccessHelper = objectInfo; + + if (argcAsync > argcPromise) { + ret = ListFileAsync(env, args, ARGS_ONE, listFileCB); + } else { + ret = ListFilePromise(env, listFileCB); + } + return ret; +} + +napi_value ListFileAsync(napi_env env, + napi_value *args, + const size_t argCallback, + FileAccessHelperListFileCB *listFileCB) +{ + if (args == nullptr || listFileCB == nullptr) { + HILOG_ERROR("%{public}s, param == nullptr.", __func__); + return nullptr; + } + napi_value resourceName = 0; + NAPI_CALL(env, napi_create_string_latin1(env, __func__, NAPI_AUTO_LENGTH, &resourceName)); + + napi_valuetype valuetype = napi_undefined; + NAPI_CALL(env, napi_typeof(env, args[argCallback], &valuetype)); + if (valuetype == napi_function) { + NAPI_CALL(env, napi_create_reference(env, args[argCallback], 1, &listFileCB->cbBase.cbInfo.callback)); + } + + NAPI_CALL(env, + napi_create_async_work(env, + nullptr, + resourceName, + ListFileExecuteCB, + ListFileAsyncCompleteCB, + (void *)listFileCB, + &listFileCB->cbBase.asyncWork)); + NAPI_CALL(env, napi_queue_async_work(env, listFileCB->cbBase.asyncWork)); + napi_value result = 0; + NAPI_CALL(env, napi_get_null(env, &result)); + return result; +} + +napi_value ListFilePromise(napi_env env, FileAccessHelperListFileCB *listFileCB) +{ + if (listFileCB == nullptr) { + HILOG_ERROR("%{public}s, param == nullptr.", __func__); + return nullptr; + } + napi_value resourceName; + NAPI_CALL(env, napi_create_string_latin1(env, __func__, NAPI_AUTO_LENGTH, &resourceName)); + napi_deferred deferred; + napi_value promise = 0; + NAPI_CALL(env, napi_create_promise(env, &deferred, &promise)); + listFileCB->cbBase.deferred = deferred; + + NAPI_CALL(env, + napi_create_async_work(env, + nullptr, + resourceName, + ListFileExecuteCB, + ListFilePromiseCompleteCB, + (void *)listFileCB, + &listFileCB->cbBase.asyncWork)); + NAPI_CALL(env, napi_queue_async_work(env, listFileCB->cbBase.asyncWork)); + return promise; +} + +void ListFileExecuteCB(napi_env env, void *data) +{ + FileAccessHelperListFileCB *listFileCB = static_cast(data); + listFileCB->execResult = -1; + if (listFileCB->fileAccessHelper != nullptr) { + HILOG_ERROR(" NAPI_ListFile, fileAccessHelper == nullptr"); + return ; + } + if (!listFileCB->sourceFileUri.empty()) { + HILOG_ERROR(" NAPI_ListFile, fileAccessHelper sourceFileUri is empty"); + return ; + } + OHOS::Uri sourceFileUri(listFileCB->sourceFileUri); + listFileCB->result = listFileCB->fileAccessHelper->ListFile(sourceFileUri); + listFileCB->execResult = ERR_OK; +} + +void ListFileAsyncCompleteCB(napi_env env, napi_status status, void *data) +{ + FileAccessHelperListFileCB *listFileCB = static_cast(data); + napi_value callback = nullptr; + napi_value undefined = nullptr; + napi_value result[ARGS_TWO] = {nullptr}; + napi_value callResult = nullptr; + NAPI_CALL_RETURN_VOID(env, napi_get_undefined(env, &undefined)); + NAPI_CALL_RETURN_VOID(env, napi_get_reference_value(env, listFileCB->cbBase.cbInfo.callback, &callback)); + + result[PARAM0] = GetCallbackErrorValue(env, listFileCB->execResult); + result[PARAM1] = WrapArrayFileInfoToJS(env, listFileCB->result); + NAPI_CALL_RETURN_VOID(env, napi_call_function(env, undefined, callback, ARGS_TWO, &result[PARAM0], &callResult)); + + if (listFileCB->cbBase.cbInfo.callback != nullptr) { + NAPI_CALL_RETURN_VOID(env, napi_delete_reference(env, listFileCB->cbBase.cbInfo.callback)); + } + NAPI_CALL_RETURN_VOID(env, napi_delete_async_work(env, listFileCB->cbBase.asyncWork)); + delete listFileCB; + listFileCB = nullptr; +} + +void ListFilePromiseCompleteCB(napi_env env, napi_status status, void *data) +{ + FileAccessHelperListFileCB *listFileCB = static_cast(data); + napi_value result = nullptr; + result = WrapArrayFileInfoToJS(env, listFileCB->result); + NAPI_CALL_RETURN_VOID(env, napi_resolve_deferred(env, listFileCB->cbBase.deferred, result)); + NAPI_CALL_RETURN_VOID(env, napi_delete_async_work(env, listFileCB->cbBase.asyncWork)); + delete listFileCB; + listFileCB = nullptr; +} + +napi_value NAPI_GetRoots(napi_env env, napi_callback_info info) +{ + HILOG_INFO("%{public}s,called", __func__); + + //-----------------------------------��������У�飬��������У��-------------------- + NFuncArg funcArg(env, info); + if (!funcArg.InitArgs(NARG_CNT::ZERO, NARG_CNT::ONE)) { + HILOG_ERROR("%{public}s, Number of arguments unmatched-------2-----------.", __func__); + UniError(EINVAL).ThrowErr(env, "Number of arguments unmatched"); + return nullptr; + } + if (funcArg.GetArgc() == NARG_CNT::ONE && !NVal(env, funcArg[NARG_POS::FIRST]).TypeIs(napi_function)) { + HILOG_INFO("%{public}s,-------------1-------------arguments check", __func__); + UniError(EINVAL).ThrowErr(env, "Type of arguments unmatched"); + return nullptr; + } + + FileAccessHelperGetRootsCB *getRootsCB = new (std::nothrow) FileAccessHelperGetRootsCB; + if (getRootsCB == nullptr) { + HILOG_ERROR("%{public}s, getRootsCB == nullptr.", __func__); + return WrapVoidToJS(env); + } + getRootsCB->cbBase.cbInfo.env = env; + getRootsCB->cbBase.asyncWork = nullptr; + getRootsCB->cbBase.deferred = nullptr; + getRootsCB->cbBase.ability = nullptr; + + napi_value ret = GetRootsWrap(env, info, getRootsCB); + if (ret == nullptr) { + HILOG_ERROR("%{public}s,ret == nullptr", __func__); + if (getRootsCB != nullptr) { + delete getRootsCB; + getRootsCB = nullptr; + } + ret = WrapVoidToJS(env); + } + return ret; +} + +napi_value GetRootsWrap(napi_env env, napi_callback_info info, FileAccessHelperGetRootsCB *getRootsCB) +{ + size_t argcAsync = ARGS_ONE; + const size_t argcPromise = ARGS_ZERO; + const size_t argCountWithAsync = argcPromise + ARGS_ASYNC_COUNT; + napi_value args[ARGS_MAX_COUNT] = {nullptr}; + napi_value ret = 0; + napi_value thisVar = nullptr; + + NAPI_CALL(env, napi_get_cb_info(env, info, &argcAsync, args, &thisVar, nullptr)); + if (argcAsync > argCountWithAsync || argcAsync > ARGS_MAX_COUNT) { + HILOG_ERROR("%{public}s, Wrong argument count.", __func__); + return nullptr; + } + + FileAccessHelper *objectInfo = nullptr; + napi_unwrap(env, thisVar, (void **)&objectInfo); + HILOG_INFO("%{public}s,FileAccessHelper objectInfo", __func__); + getRootsCB->fileAccessHelper = objectInfo; + + if (argcAsync > argcPromise) { + ret = GetRootsAsync(env, args, ARGS_ZERO, getRootsCB); + } else { + ret = GetRootsPromise(env, getRootsCB); + } + return ret; +} + +napi_value GetRootsAsync(napi_env env, + napi_value *args, + const size_t argCallback, + FileAccessHelperGetRootsCB *getRootsCB) +{ + if (args == nullptr || getRootsCB == nullptr) { + HILOG_ERROR("%{public}s, param == nullptr.", __func__); + return nullptr; + } + napi_value resourceName = 0; + NAPI_CALL(env, napi_create_string_latin1(env, __func__, NAPI_AUTO_LENGTH, &resourceName)); + + napi_valuetype valuetype = napi_undefined; + NAPI_CALL(env, napi_typeof(env, args[argCallback], &valuetype)); + if (valuetype == napi_function) { + NAPI_CALL(env, napi_create_reference(env, args[argCallback], 1, &getRootsCB->cbBase.cbInfo.callback)); + } + + NAPI_CALL(env, + napi_create_async_work(env, + nullptr, + resourceName, + GetRootsExecuteCB, + GetRootsAsyncCompleteCB, + (void *)getRootsCB, + &getRootsCB->cbBase.asyncWork)); + NAPI_CALL(env, napi_queue_async_work(env, getRootsCB->cbBase.asyncWork)); + napi_value result = 0; + NAPI_CALL(env, napi_get_null(env, &result)); + return result; +} + +napi_value GetRootsPromise(napi_env env, FileAccessHelperGetRootsCB *getRootsCB) +{ + if (getRootsCB == nullptr) { + HILOG_ERROR("%{public}s, param == nullptr.", __func__); + return nullptr; + } + napi_value resourceName; + NAPI_CALL(env, napi_create_string_latin1(env, __func__, NAPI_AUTO_LENGTH, &resourceName)); + napi_deferred deferred; + napi_value promise = 0; + NAPI_CALL(env, napi_create_promise(env, &deferred, &promise)); + getRootsCB->cbBase.deferred = deferred; + + NAPI_CALL(env, + napi_create_async_work(env, + nullptr, + resourceName, + GetRootsExecuteCB, + GetRootsPromiseCompleteCB, + (void *)getRootsCB, + &getRootsCB->cbBase.asyncWork)); + NAPI_CALL(env, napi_queue_async_work(env, getRootsCB->cbBase.asyncWork)); + return promise; +} + +void GetRootsExecuteCB(napi_env env, void *data) +{ + FileAccessHelperGetRootsCB *getRootsCB = static_cast(data); + getRootsCB->execResult = -1; + if (getRootsCB->fileAccessHelper == nullptr) { + HILOG_ERROR(" NAPI_GetRoots, fileAccessHelper == nullptr"); + return ; + } + getRootsCB->result = getRootsCB->fileAccessHelper->GetRoots(); + getRootsCB->execResult = ERR_OK; +} + +void GetRootsAsyncCompleteCB(napi_env env, napi_status status, void *data) +{ + FileAccessHelperGetRootsCB *getRootsCB = static_cast(data); + napi_value callback = nullptr; + napi_value undefined = nullptr; + napi_value result[ARGS_TWO] = {nullptr}; + napi_value callResult = nullptr; + NAPI_CALL_RETURN_VOID(env, napi_get_undefined(env, &undefined)); + NAPI_CALL_RETURN_VOID(env, napi_get_reference_value(env, getRootsCB->cbBase.cbInfo.callback, &callback)); + + result[PARAM0] = GetCallbackErrorValue(env, getRootsCB->execResult); + result[PARAM1] = WrapArrayDeviceInfoToJS(env, getRootsCB->result); + NAPI_CALL_RETURN_VOID(env, napi_call_function(env, undefined, callback, ARGS_TWO, &result[PARAM0], &callResult)); + + if (getRootsCB->cbBase.cbInfo.callback != nullptr) { + NAPI_CALL_RETURN_VOID(env, napi_delete_reference(env, getRootsCB->cbBase.cbInfo.callback)); + } + NAPI_CALL_RETURN_VOID(env, napi_delete_async_work(env, getRootsCB->cbBase.asyncWork)); + delete getRootsCB; + getRootsCB = nullptr; +} + +void GetRootsPromiseCompleteCB(napi_env env, napi_status status, void *data) +{ + FileAccessHelperGetRootsCB *getRootsCB = static_cast(data); + napi_value result = nullptr; + result = WrapArrayDeviceInfoToJS(env, getRootsCB->result); + NAPI_CALL_RETURN_VOID(env, napi_resolve_deferred(env, getRootsCB->cbBase.deferred, result)); + NAPI_CALL_RETURN_VOID(env, napi_delete_async_work(env, getRootsCB->cbBase.asyncWork)); + delete getRootsCB; + getRootsCB = nullptr; +} +} // namespace AppExecFwk +} // namespace OHOS \ No newline at end of file diff --git a/interfaces/kits/napi/file_access_module/napi_fileaccess_helper.h b/interfaces/kits/napi/file_access_module/napi_fileaccess_helper.h new file mode 100644 index 0000000000000000000000000000000000000000..0f4fb297a43a3810d577db169ed8674d12607294 --- /dev/null +++ b/interfaces/kits/napi/file_access_module/napi_fileaccess_helper.h @@ -0,0 +1,114 @@ +/* + * Copyright (C) 2022 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef NAPI_FILEACCESS_HELPER_H +#define NAPI_FILEACCESS_HELPER_H + +#include "file_access_common.h" + +namespace OHOS { +namespace FileAccessFwk { + napi_value FileAccessHelperInit(napi_env env, napi_value exports); + napi_value FileAccessHelperConstructor(napi_env env, napi_callback_info info); + napi_value NAPI_OpenFile(napi_env env, napi_callback_info info); + napi_value OpenFileWrap(napi_env env, napi_callback_info info, FileAccessHelperOpenFileCB *openFileCB); + napi_value OpenFileAsync(napi_env env, + napi_value *args, + const size_t argCallback, + FileAccessHelperOpenFileCB *openFileCB); + napi_value OpenFilePromise(napi_env env, FileAccessHelperOpenFileCB *openFileCB); + void OpenFileExecuteCB(napi_env env, void *data); + void OpenFileAsyncCompleteCB(napi_env env, napi_status status, void *data); + void OpenFilePromiseCompleteCB(napi_env env, napi_status status, void *data); + + napi_value NAPI_CreateFile(napi_env env, napi_callback_info info); + napi_value CreateFileWrap(napi_env env, napi_callback_info info, FileAccessHelperCreateFileCB *createFileCB); + napi_value CreateFileAsync(napi_env env, + napi_value *args, + const size_t argCallback, + FileAccessHelperCreateFileCB *createFileCB); + napi_value CreateFilePromise(napi_env env, FileAccessHelperCreateFileCB *createFileCB); + void CreateFileExecuteCB(napi_env env, void *data); + void CreateFileAsyncCompleteCB(napi_env env, napi_status status, void *data); + void CreateFilePromiseCompleteCB(napi_env env, napi_status status, void *data); + + napi_value NAPI_Mkdir(napi_env env, napi_callback_info info); + napi_value MkdirWrap(napi_env env, napi_callback_info info, FileAccessHelperMkdirCB *mkdirCB); + napi_value MkdirAsync(napi_env env, + napi_value *args, + const size_t argCallback, + FileAccessHelperMkdirCB *mkdirCB); + napi_value MkdirPromise(napi_env env, FileAccessHelperMkdirCB *mkdirCB); + void MkdirExecuteCB(napi_env env, void *data); + void MkdirAsyncCompleteCB(napi_env env, napi_status status, void *data); + void MkdirPromiseCompleteCB(napi_env env, napi_status status, void *data); + + napi_value NAPI_Delete(napi_env env, napi_callback_info info); + napi_value DeleteWrap(napi_env env, napi_callback_info info, FileAccessHelperDeleteCB *deleteCB); + napi_value DeleteAsync(napi_env env, + napi_value *args, + const size_t argCallback, + FileAccessHelperDeleteCB *deleteCB); + napi_value DeletePromise(napi_env env, FileAccessHelperDeleteCB *deleteCB); + void DeleteExecuteCB(napi_env env, void *data); + void DeleteAsyncCompleteCB(napi_env env, napi_status status, void *data); + void DeletePromiseCompleteCB(napi_env env, napi_status status, void *data); + + napi_value NAPI_Move(napi_env env, napi_callback_info info); + napi_value MoveWrap(napi_env env, napi_callback_info info, FileAccessHelperMoveCB *moveCB); + napi_value MoveAsync(napi_env env, + napi_value *args, + const size_t argCallback, + FileAccessHelperMoveCB *moveCB); + napi_value MovePromise(napi_env env, FileAccessHelperMoveCB *moveCB); + void MoveExecuteCB(napi_env env, void *data); + void MoveAsyncCompleteCB(napi_env env, napi_status status, void *data); + void MovePromiseCompleteCB(napi_env env, napi_status status, void *data); + + napi_value NAPI_Rename(napi_env env, napi_callback_info info); + napi_value RenameWrap(napi_env env, napi_callback_info info, FileAccessHelperRenameCB *renameCB); + napi_value RenameAsync(napi_env env, + napi_value *args, + const size_t argCallback, + FileAccessHelperRenameCB *renameCB); + napi_value RenamePromise(napi_env env, FileAccessHelperRenameCB *renameCB); + void RenameExecuteCB(napi_env env, void *data); + void RenameAsyncCompleteCB(napi_env env, napi_status status, void *data); + void RenamePromiseCompleteCB(napi_env env, napi_status status, void *data); + + napi_value NAPI_ListFile(napi_env env, napi_callback_info info); + napi_value ListFileWrap(napi_env env, napi_callback_info info, FileAccessHelperListFileCB *listFileCB); + napi_value ListFileAsync(napi_env env, + napi_value *args, + const size_t argCallback, + FileAccessHelperListFileCB *listFileCB); + napi_value ListFilePromise(napi_env env, FileAccessHelperListFileCB *listFileCB); + void ListFileExecuteCB(napi_env env, void *data); + void ListFileAsyncCompleteCB(napi_env env, napi_status status, void *data); + void ListFilePromiseCompleteCB(napi_env env, napi_status status, void *data); + + napi_value NAPI_GetRoots(napi_env env, napi_callback_info info); + napi_value GetRootsWrap(napi_env env, napi_callback_info info, FileAccessHelperGetRootsCB *getRootsCB); + napi_value GetRootsAsync(napi_env env, + napi_value *args, + const size_t argCallback, + FileAccessHelperGetRootsCB *getRootsCB); + napi_value GetRootsPromise(napi_env env, FileAccessHelperGetRootsCB *getRootsCB); + void GetRootsExecuteCB(napi_env env, void *data); + void GetRootsAsyncCompleteCB(napi_env env, napi_status status, void *data); + void GetRootsPromiseCompleteCB(napi_env env, napi_status status, void *data); +} +} // namespace FileAccessFwk +#endif // FILE_ACCESS_NAPI_H \ No newline at end of file diff --git a/interfaces/kits/napi/file_access_module/native_fileaccess_module.cpp b/interfaces/kits/napi/file_access_module/native_fileaccess_module.cpp new file mode 100644 index 0000000000000000000000000000000000000000..fb78160cf9dbec783f60df5014183824a5a737bd --- /dev/null +++ b/interfaces/kits/napi/file_access_module/native_fileaccess_module.cpp @@ -0,0 +1,65 @@ +/* + * Copyright (C) 2022 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include +#include + +#include "napi_fileaccess_helper.h" +#include "napi/native_api.h" +#include "napi/native_node_api.h" +#include "hilog_wrapper.h" +#include "file_extension_info_napi.h" +using namespace std; + +namespace OHOS { +namespace FileAccessFwk { +EXTERN_C_START +/* + * The module initialization. + */ +static napi_value Init(napi_env env, napi_value exports) +{ + HILOG_INFO("tag dsa %{public}s,called", __func__); + FileAccessHelperInit(env, exports); + InitFlag(env, exports); + InitFileInfo(env, exports); + InitDeviceInfo(env, exports); + return exports; +} +EXTERN_C_END + +/* + * The module definition. + */ +static napi_module _module = { + .nm_version = 1, + .nm_flags = 0, + .nm_filename = nullptr, + .nm_register_func = Init, + .nm_modname = "data.fileAccess", + .nm_priv = ((void *)0), + .reserved = {0} +}; + +/* + * The module registration. + */ +extern "C" __attribute__((constructor)) void RegisterModule(void) +{ + HILOG_INFO("tag dsa %{public}s,called", __func__); + napi_module_register(&_module); +} +} // namespace FileAccessFwk +} // namespace OHOS \ No newline at end of file diff --git a/interfaces/kits/napi/file_extension_info_module/BUILD.gn b/interfaces/kits/napi/file_extension_info_module/BUILD.gn new file mode 100644 index 0000000000000000000000000000000000000000..ac54d7d630c3e9b4790c2ecfdf156ca67fd38ce9 --- /dev/null +++ b/interfaces/kits/napi/file_extension_info_module/BUILD.gn @@ -0,0 +1,42 @@ +# 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") + +UFS_BASE_PATH = "//foundation/filemanagement/user_file_service" +FRAMEWORK_PATH = "${UFS_BASE_PATH}/frameworks" + +ohos_shared_library("fileextensioninfo") { + subsystem_name = "filemanagement" + part_name = "user_file_service" + relative_install_dir = "module" + + include_dirs = [ + ".", + "${UFS_BASE_PATH}/interfaces/kits/napi/common", + "${FRAMEWORK_PATH}/innerkits/file_access/include", + ] + + sources = [ + "${UFS_BASE_PATH}/interfaces/kits/napi/common/file_extension_info_napi.cpp", + "module_export_napi.cpp", + ] + + deps = [ "//foundation/arkui/napi:ace_napi" ] + + external_deps = [ + "hiviewdfx_hilog_native:libhilog", + "ability_base:zuri", + "utils_base:utils", + ] +} \ No newline at end of file diff --git a/interfaces/kits/napi/file_extension_info_module/module_export_napi.cpp b/interfaces/kits/napi/file_extension_info_module/module_export_napi.cpp new file mode 100644 index 0000000000000000000000000000000000000000..543a32cf753cb16a5717145ae8d9643d1642114c --- /dev/null +++ b/interfaces/kits/napi/file_extension_info_module/module_export_napi.cpp @@ -0,0 +1,37 @@ +/* + * 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 "module_export_napi.h" + +#include + +#include "file_extension_info_napi.h" +#include "napi/native_api.h" +#include "napi/native_node_api.h" + +namespace OHOS { +namespace FileAccessFwk { +napi_value FileExtensionInfoExport(napi_env env, napi_value exports) +{ + InitFlag(env, exports); + InitFileInfo(env, exports); + InitDeviceInfo(env, exports); + + return exports; +} + +NAPI_MODULE(fileExtensionInfo, FileExtensionInfoExport) +} // namespace FileAccessFwk +} // namespace OHOS \ No newline at end of file diff --git a/interfaces/kits/napi/file_extension_info_module/module_export_napi.h b/interfaces/kits/napi/file_extension_info_module/module_export_napi.h new file mode 100644 index 0000000000000000000000000000000000000000..c49f3b0ae3779596e47069ecc2b2524041f4ae53 --- /dev/null +++ b/interfaces/kits/napi/file_extension_info_module/module_export_napi.h @@ -0,0 +1,22 @@ +/* + * 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 MODULE_EXPORT_NAPI_H +#define MODULE_EXPORT_NAPI_H +namespace OHOS { +namespace FileAccessFwk { +} // namespace FileAccessFwk +} // namespace OHOS +#endif // MODULE_EXPORT_NAPI_H \ No newline at end of file diff --git a/services/file_extension_hap/AppScope/app.json b/services/file_extension_hap/AppScope/app.json new file mode 100644 index 0000000000000000000000000000000000000000..9ed7e1acf9559e97986f90dcbbec33f3cfc6bd63 --- /dev/null +++ b/services/file_extension_hap/AppScope/app.json @@ -0,0 +1,11 @@ +{ + "app": { + "bundleName": "com.ohos.UserFile.ExternalFileManager", + "versionCode": 100, + "versionName": "1.0.0", + "minAPIVersion": 9, + "targetAPIVersion": 9, + "icon": "$media:app_icon", + "label": "$string:app_name" + } +} diff --git a/services/file_extension_hap/AppScope/resources/base/element/string.json b/services/file_extension_hap/AppScope/resources/base/element/string.json new file mode 100644 index 0000000000000000000000000000000000000000..bdb9ac3627d877c9908763446d259fc514e50c41 --- /dev/null +++ b/services/file_extension_hap/AppScope/resources/base/element/string.json @@ -0,0 +1,8 @@ +{ + "string": [ + { + "name": "app_name", + "value": "ExternalFileManager" + } + ] +} diff --git a/services/file_extension_hap/AppScope/resources/base/media/app_icon.png b/services/file_extension_hap/AppScope/resources/base/media/app_icon.png new file mode 100644 index 0000000000000000000000000000000000000000..ce307a8827bd75456441ceb57d530e4c8d45d36c Binary files /dev/null and b/services/file_extension_hap/AppScope/resources/base/media/app_icon.png differ diff --git a/services/file_extension_hap/build-profile.json5 b/services/file_extension_hap/build-profile.json5 new file mode 100644 index 0000000000000000000000000000000000000000..8fac20813cb081694e75ab50d19a5faac524c66c --- /dev/null +++ b/services/file_extension_hap/build-profile.json5 @@ -0,0 +1,40 @@ +/* + * Copyright (c) 2022 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +{ + "app": { + "compileSdkVersion": 9, + "compatibleSdkVersion": 9, + "products": [ + { + "name": "default", + "signingConfig": "default", + } + ] + }, + "modules": [ + { + "name": "entry", + "srcPath": "./entry", + "targets": [ + { + "name": "default", + "applyToProducts": [ + "default" + ] + } + ] + } + ] +} \ No newline at end of file diff --git a/services/file_extension_hap/entry/build-profile.json5 b/services/file_extension_hap/entry/build-profile.json5 new file mode 100644 index 0000000000000000000000000000000000000000..d3089f7ba484c6385983234a1f147c161a5d9cdd --- /dev/null +++ b/services/file_extension_hap/entry/build-profile.json5 @@ -0,0 +1,24 @@ +/* + * Copyright (c) 2022 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +{ + "apiType": 'stageMode', + "buildOption": { + }, + "targets": [ + { + "name": "default", + } + ] +} \ No newline at end of file diff --git a/services/file_extension_hap/entry/hvigorfile.js b/services/file_extension_hap/entry/hvigorfile.js new file mode 100644 index 0000000000000000000000000000000000000000..d7720ee6a7aad5c617d1fd2f6fc8c87067bfa32c --- /dev/null +++ b/services/file_extension_hap/entry/hvigorfile.js @@ -0,0 +1,2 @@ +// Script for compiling build behavior. It is built in the build plug-in and cannot be modified currently. +module.exports = require('@ohos/hvigor-ohos-plugin').hapTasks diff --git a/services/file_extension_hap/entry/src/main/ets/Application/AbilityStage.ts b/services/file_extension_hap/entry/src/main/ets/Application/AbilityStage.ts new file mode 100644 index 0000000000000000000000000000000000000000..c4851529e91e899ca93c1f43cbbd1259decafd1f --- /dev/null +++ b/services/file_extension_hap/entry/src/main/ets/Application/AbilityStage.ts @@ -0,0 +1,20 @@ +/* + * Copyright (c) 2022 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import AbilityStage from "@ohos.application.AbilityStage" + +export default class MyAbilityStage extends AbilityStage { + onCreate() { + } +} \ No newline at end of file diff --git a/services/file_extension_hap/entry/src/main/ets/FileExtensionAbility/FileExtensionAbility.ts b/services/file_extension_hap/entry/src/main/ets/FileExtensionAbility/FileExtensionAbility.ts new file mode 100644 index 0000000000000000000000000000000000000000..d46b79224af15fa139e784acbb563bf622c80b0d --- /dev/null +++ b/services/file_extension_hap/entry/src/main/ets/FileExtensionAbility/FileExtensionAbility.ts @@ -0,0 +1,282 @@ +/* + * Copyright (c) 2022 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import Extension from '@ohos.application.FileAccessExtensionAbility' +import fileio from '@ohos.fileio' +import hilog from '@ohos.hilog' +import { init, addVolumeInfo, delVolumeInfo, path2uri, getVolumeInfoList } from './VolumeManager' +import { onReceiveEvent } from './Subcriber' +import fileExtensionInfo from "@ohos.fileExtensionInfo" + +const FLAG = fileExtensionInfo.FLAG; + +export default class FileExtAbility extends Extension { + onCreate(want) { + init(); + onReceiveEvent(function (data) { + let parameters = data.parameters; + let flag = FLAG.SUPPORTS_WRITE | FLAG.SUPPORTS_DELETE | FLAG.SUPPORTS_RENAME | FLAG.SUPPORTS_COPY + | FLAG.SUPPORTS_MOVE | FLAG.SUPPORTS_REMOVE | FLAG.DIR_SUPPORTS_CREATE | FLAG.DIR_PREFERS_LAST_MODIFIED; + if (data.event == 'usual.event.data.VOLUME_MOUNTED') { + let volumeInfo = { + 'volumeId': parameters.id, + 'fsUuid': parameters.fsUuid, + 'path': parameters.path, + 'uri': path2uri(parameters.id, parameters.path), + 'flags': flag, + 'deviceId': '', + 'displayName': parameters.id, + 'type': 'SD' + } + addVolumeInfo(volumeInfo); + } else { + delVolumeInfo(parameters.id); + } + }); + } + + getPath(uri) { + let sep = '://'; + let arr = uri.split(sep); + if (arr.length < 2) { + return uri; + } + let path = uri.replace(arr[0] + sep, ''); + if (arr[1].indexOf('/') > 0) { + path = path.replace(arr[1].split('/')[0], ''); + } + return path; + } + + genNewFileUri(uri, displayName) { + let arr = uri.split('/'); + let newFileUri = uri; + if (arr.pop() == '') { + newFileUri += displayName; + } else { + newFileUri += '/' + displayName; + } + return newFileUri; + } + + getFileName(uri) { + let arr = uri.split('/'); + let name = arr.pop(); + if (name == '') { + name = arr.pop(); + } + return name; + } + + renameUri(uri, displayName) { + let arr = uri.split('/'); + let newFileUri = ''; + if (arr.pop() == '') { + arr.pop(); + arr.push(displayName) + arr.push(''); + } else { + arr.push(displayName) + } + for (var index = 0; index < arr.length; index++) { + if (arr[index] == '') { + newFileUri += '/'; + } else if (index == arr.length - 1) { + newFileUri += arr[index]; + } else { + newFileUri += arr[index] + '/'; + } + } + return newFileUri; + } + + listDir(path, cb) { + try { + let stat = fileio.statSync(path); + if (stat.isDirectory()) { + let dir = fileio.opendirSync(path); + let hasNextFile = true; + while (hasNextFile) { + try { + let dirent = dir.readSync(); + this.listDir(path + '/' + dirent.name, cb); + } catch (e) { + hilog.debug(0x0001, 'jsserver', 'listDir dir.readSync catch' + e); + hasNextFile = false; + cb(path, true); + } + } + } else { + cb(path, false); + } + } catch (e) { + hilog.debug(0x0001, 'jsserver', 'listDir catch ' + e + ' ' + path); + cb(path, true); + } + } + + openFile(sourceFileUri, flags) { + let fd = 0; + try { + let path = this.getPath(sourceFileUri); + fd = fileio.openSync(path, flags, 0o666); + } catch (e) { + hilog.debug(0x0001, 'jsserver', 'openFile catch' + e); + fd = -1; + } + + return fd; + } + + closeFile(fd, uri) { + try { + fileio.closeSync(fd); + return true; + } catch (e) { + hilog.debug(0x0001, 'jsserver', 'closeFile catch' + e); + return false; + } + } + + createFile(parentUri, displayName) { + try { + let newFileUri = this.genNewFileUri(parentUri, displayName); + let path = this.getPath(newFileUri); + fileio.openSync(path, 0o100, 0o666); + return newFileUri; + } catch (e) { + hilog.debug(0x0001, 'jsserver', 'createFile catch' + e); + return ''; + } + } + + mkdir(parentUri, displayName) { + try { + let newFileUri = this.genNewFileUri(parentUri, displayName); + let path = this.getPath(newFileUri); + fileio.mkdirSync(path); + return newFileUri; + } catch (e) { + hilog.debug(0x0001, 'jsserver', 'mkdir catch' + e); + return ''; + } + } + + delete(selectFileUri) { + let path = this.getPath(selectFileUri); + let code = 0; + this.listDir(path, function (filePath, isDirectory) { + try { + if (isDirectory) { + fileio.rmdirSync(filePath); + + } else { + fileio.unlinkSync(filePath); + } + } catch (e) { + hilog.debug(0x0001, 'jsserver', 'delete catch' + e); + code = -1; + } + }); + + return code; + } + + move(sourceFileUri, targetParentUri) { + try { + let displayName = this.getFileName(sourceFileUri); + let newFileUri = this.genNewFileUri(targetParentUri, displayName); + let oldPath = this.getPath(sourceFileUri); + let newPath = this.getPath(newFileUri); + fileio.renameSync(oldPath, newPath); + return newFileUri; + } catch (e) { + hilog.debug(0x0001, 'jsserver', 'rename catch' + e); + return ''; + } + } + + rename(sourceFileUri, displayName) { + try { + let newFileUri = this.renameUri(sourceFileUri, displayName); + let oldPath = this.getPath(sourceFileUri); + let newPath = this.getPath(newFileUri); + fileio.renameSync(oldPath, newPath); + return newFileUri; + } catch (e) { + hilog.debug(0x0001, 'jsserver', 'rename catch' + e); + return ''; + } + } + + query(sourceFileUri) { + try { + let path = this.getPath(sourceFileUri); + let stat = fileio.statSync(path); + return { + uri: sourceFileUri, + fileName: this.getFileName(sourceFileUri), + mode: stat.mode, + size: stat.size, + mtime: stat.mtime, + mimiType: '', + }; + } catch (e) { + hilog.debug(0x0001, 'jsserver', 'query catch' + e); + return null; + } + } + + listFile(sourceFileUri) { + + let infos = []; + try { + let path = this.getPath(sourceFileUri); + let dir = fileio.opendirSync(path); + let hasNextFile = true; + while (hasNextFile) { + try { + let dirent = dir.readSync(); + let stat = fileio.statSync(path + '/' + dirent.name); + infos.push({ + uri: this.genNewFileUri(sourceFileUri, dirent.name), + fileName: dirent.name, + mode: '' + stat.mode, + size: stat.size, + mtime: stat.mtime, + mimiType: '', + }); + } catch (e) { + hilog.debug(0x0001, 'jsserver', 'dir.readSync catch' + e); + hasNextFile = false; + } + } + } catch (e) { + hilog.debug(0x0001, 'jsserver', 'listFile catch' + e); + } + + return infos; + } + + getRoots() { + let roots = getVolumeInfoList().concat({ + uri: 'fileAccess:///data/storage/el1/bundle/storage_daemon', + displayName: 'storage_daemon', + deviceId: '', + flags: FLAG.SUPPORTS_WRITE | FLAG.SUPPORTS_DELETE | FLAG.SUPPORTS_RENAME | FLAG.SUPPORTS_COPY + | FLAG.SUPPORTS_MOVE | FLAG.SUPPORTS_REMOVE | FLAG.DIR_SUPPORTS_CREATE | FLAG.DIR_PREFERS_LAST_MODIFIED, + }); + return roots; + } +}; \ No newline at end of file diff --git a/services/file_extension_hap/entry/src/main/ets/FileExtensionAbility/Subcriber.ts b/services/file_extension_hap/entry/src/main/ets/FileExtensionAbility/Subcriber.ts new file mode 100644 index 0000000000000000000000000000000000000000..a2e8acec2c7f994d5fc3b806ba862065901f984d --- /dev/null +++ b/services/file_extension_hap/entry/src/main/ets/FileExtensionAbility/Subcriber.ts @@ -0,0 +1,32 @@ +/* +* Copyright (c) 2022 Huawei Device Co., Ltd. +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ +import CommonEvent from '@ohos.commonevent' +async function onReceiveEvent(callBack) { + var subscribeInfo = { + events: [ + "usual.event.data.VOLUME_REMOVED", + "usual.event.data.VOLUME_UNMOUNTED", + "usual.event.data.VOLUME_MOUNTED", + "usual.event.data.VOLUME_BAD_REMOVAL", + "usual.event.data.VOLUME_EJECT" + ] + }; + let subscriber = await CommonEvent.createSubscriber(subscribeInfo); + CommonEvent.subscribe(subscriber, function (err, data) { + callBack(data) + }) +} + +export { onReceiveEvent } \ No newline at end of file diff --git a/services/file_extension_hap/entry/src/main/ets/FileExtensionAbility/VolumeManager.ts b/services/file_extension_hap/entry/src/main/ets/FileExtensionAbility/VolumeManager.ts new file mode 100644 index 0000000000000000000000000000000000000000..10100910d3d3dd18de8ea0860c04ad81a8ef0363 --- /dev/null +++ b/services/file_extension_hap/entry/src/main/ets/FileExtensionAbility/VolumeManager.ts @@ -0,0 +1,74 @@ +/* + * Copyright (c) 2022 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import volumeManager from '@ohos.volumeManager' +import hilog from '@ohos.hilog' +import fileExtensionInfo from "@ohos.fileExtensionInfo" +if (!globalThis.volumeInfoList) { + globalThis.volumeInfoList = []; +} + +const FLAG = fileExtensionInfo.FLAG; + +function init() { + try { + volumeManager.getAllVolumes().then((volumes) => { + let flag = FLAG.SUPPORTS_WRITE | FLAG.SUPPORTS_DELETE | FLAG.SUPPORTS_RENAME | FLAG.SUPPORTS_COPY + | FLAG.SUPPORTS_MOVE | FLAG.SUPPORTS_REMOVE | FLAG.DIR_SUPPORTS_CREATE | FLAG.DIR_PREFERS_LAST_MODIFIED; + for (let i = 0; i < volumes.length; i++) { + let volume = volumes[i]; + let volumeInfo = { + 'volumeId': volume.id, + 'fsUuid': volume.uuid, + 'path': volume.path, + 'uri': path2uri(volume.id, volume.path), + 'displayName': volume.id, + 'deviceId': '', + 'flags': flag, + 'type': 'SD' + } + globalThis.volumeInfoList.push(volumeInfo); + } + }); + + } catch (err) { + hilog.debug(0x0001, 'jsserver', "err============>" + err); + } +} + +function addVolumeInfo(volumeInfo) { + globalThis.volumeInfoList.push(volumeInfo); +} + +function path2uri(id, path) { + return `fileAccess://${id}/${path}`; +} + +function delVolumeInfo(volumeId) { + globalThis.volumeInfoList = globalThis.volumeInfoList.filter((volume) => volume.volumeId !== volumeId); +} + +function getVolumeInfo(volumeId) { + let volumeInfo = globalThis.volumeInfoList.filter((volume) => volume.volumeId === volumeId); + return volumeInfo; +} + +function getVolumeInfoList() { + return globalThis.volumeInfoList; +} + +function notifyChange() { + +} +export { init, addVolumeInfo, delVolumeInfo, getVolumeInfoList, path2uri } \ No newline at end of file diff --git a/services/file_extension_hap/entry/src/main/module.json b/services/file_extension_hap/entry/src/main/module.json new file mode 100644 index 0000000000000000000000000000000000000000..20916b6afa6dc19b9080114a6bceaf8c1be1d94e --- /dev/null +++ b/services/file_extension_hap/entry/src/main/module.json @@ -0,0 +1,25 @@ +{ + "module": { + "name": "entry", + "type": "entry", + "srcEntrance": "./ets/Application/AbilityStage.ts", + "mainElement": "FileExtensionAbility", + "deviceTypes": [ + "phone", + "tablet" + ], + "deliveryWithInstall": true, + "installationFree": false, + "pages": "$profile:main_pages", + "uiSyntax": "ets", + "abilities": [], + "extensionAbilities": [ + { + "srcEntrance": "./ets/FileExtensionAbility/FileExtensionAbility.ts", + "name": "FileExtensionAbility", + "type": "fileAccess", + "visible": true + } + ] + } +} \ No newline at end of file diff --git a/services/file_extension_hap/entry/src/main/resources/base/element/string.json b/services/file_extension_hap/entry/src/main/resources/base/element/string.json new file mode 100644 index 0000000000000000000000000000000000000000..c4e8611bfbd8bb3177924f05e7e22a7ca3dcf5dd --- /dev/null +++ b/services/file_extension_hap/entry/src/main/resources/base/element/string.json @@ -0,0 +1,12 @@ +{ + "string": [ + { + "name": "entry_desc", + "value": "description" + }, + { + "name": "description_serviceability", + "value": "description_serviceability" + } + ] +} \ No newline at end of file diff --git a/services/file_extension_hap/entry/src/main/resources/base/media/icon.png b/services/file_extension_hap/entry/src/main/resources/base/media/icon.png new file mode 100644 index 0000000000000000000000000000000000000000..ce307a8827bd75456441ceb57d530e4c8d45d36c Binary files /dev/null and b/services/file_extension_hap/entry/src/main/resources/base/media/icon.png differ diff --git a/services/file_extension_hap/entry/src/main/resources/base/profile/main_pages.json b/services/file_extension_hap/entry/src/main/resources/base/profile/main_pages.json new file mode 100644 index 0000000000000000000000000000000000000000..b12d9e9faa33835d362c73333632d70b7c61328a --- /dev/null +++ b/services/file_extension_hap/entry/src/main/resources/base/profile/main_pages.json @@ -0,0 +1,3 @@ +{ + "src": [] +} \ No newline at end of file diff --git a/services/file_extension_hap/hvigorfile.js b/services/file_extension_hap/hvigorfile.js new file mode 100644 index 0000000000000000000000000000000000000000..5f2735e3deeaf655828407544bbed9365c258278 --- /dev/null +++ b/services/file_extension_hap/hvigorfile.js @@ -0,0 +1,2 @@ +// Script for compiling build behavior. It is built in the build plug-in and cannot be modified currently. +module.exports = require('@ohos/hvigor-ohos-plugin').appTasks \ No newline at end of file diff --git a/services/signature/fileextension.p7b b/services/signature/fileextension.p7b new file mode 100644 index 0000000000000000000000000000000000000000..ddb74239918c96a341ee6dc7d118aba46355e5d0 Binary files /dev/null and b/services/signature/fileextension.p7b differ diff --git a/utils/hilog_wrapper.h b/utils/hilog_wrapper.h new file mode 100644 index 0000000000000000000000000000000000000000..6df10f624e65248de8e4e2500cbced940b26e1e5 --- /dev/null +++ b/utils/hilog_wrapper.h @@ -0,0 +1,81 @@ +/* + * Copyright (c) 2022 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef HILOG_WRAPPER_H +#define HILOG_WRAPPER_H + +#define CONFIG_HILOG +#ifdef CONFIG_HILOG +#include "hilog/log.h" + +#ifdef HILOG_FATAL +#undef HILOG_FATAL +#endif + +#ifdef HILOG_ERROR +#undef HILOG_ERROR +#endif + +#ifdef HILOG_WARN +#undef HILOG_WARN +#endif + +#ifdef HILOG_INFO +#undef HILOG_INFO +#endif + +#ifdef HILOG_DEBUG +#undef HILOG_DEBUG +#endif + +#ifndef FAF_LOG_DOMAIN +#define FAF_LOG_DOMAIN 0xD00430A +#endif + +#ifndef FAF_LOG_TAG +#define FAF_LOG_TAG "FileAccessFwk" +#endif + +#ifdef LOG_LABEL +#undef LOG_LABEL +#endif + +static constexpr OHOS::HiviewDFX::HiLogLabel LOG_LABEL = {LOG_CORE, FAF_LOG_DOMAIN, FAF_LOG_TAG}; + +#define HILOG_FATAL(fmt, ...) \ + (void)OHOS::HiviewDFX::HiLog::Fatal( \ + LOG_LABEL, "[(%{public}s:%{public}d)]" fmt, __FUNCTION__, __LINE__, ##__VA_ARGS__) +#define HILOG_ERROR(fmt, ...) \ + (void)OHOS::HiviewDFX::HiLog::Error( \ + LOG_LABEL, "[(%{public}s:%{public}d)]" fmt, __FUNCTION__, __LINE__, ##__VA_ARGS__) +#define HILOG_WARN(fmt, ...) \ + (void)OHOS::HiviewDFX::HiLog::Warn( \ + LOG_LABEL, "[(%{public}s:%{public}d)]" fmt, __FUNCTION__, __LINE__, ##__VA_ARGS__) +#define HILOG_INFO(fmt, ...) \ + (void)OHOS::HiviewDFX::HiLog::Info( \ + LOG_LABEL, "[(%{public}s:%{public}d)]" fmt, __FUNCTION__, __LINE__, ##__VA_ARGS__) +#define HILOG_DEBUG(fmt, ...) \ + (void)OHOS::HiviewDFX::HiLog::Debug( \ + LOG_LABEL, "[(%{public}s:%{public}d)]" fmt, __FUNCTION__, __LINE__, ##__VA_ARGS__) +#else + +#define HILOG_FATAL(...) +#define HILOG_ERROR(...) +#define HILOG_WARN(...) +#define HILOG_INFO(...) +#define HILOG_DEBUG(...) +#endif // CONFIG_HILOG + +#endif // HILOG_WRAPPER_H \ No newline at end of file