diff --git a/distributedfile_aafwk.gni b/distributedfile_aafwk.gni deleted file mode 100644 index 5acb812..0000000 --- a/distributedfile_aafwk.gni +++ /dev/null @@ -1,15 +0,0 @@ -# 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. - -ability_runtime_path = "//foundation/ability/ability_runtime" -ability_runtime_kits_path = "${ability_runtime_path}/frameworks/kits" diff --git a/figures/distributed-file-subsystem-architecture.png b/figures/distributed-file-subsystem-architecture.png deleted file mode 100644 index d36a4b1..0000000 Binary files a/figures/distributed-file-subsystem-architecture.png and /dev/null differ diff --git a/figures/分布式文件子系统架构图.png b/figures/分布式文件子系统架构图.png deleted file mode 100644 index e3763b7..0000000 Binary files a/figures/分布式文件子系统架构图.png and /dev/null differ diff --git a/interfaces/kits/js/BUILD.gn b/interfaces/kits/js/BUILD.gn deleted file mode 100644 index a9fc320..0000000 --- a/interfaces/kits/js/BUILD.gn +++ /dev/null @@ -1,243 +0,0 @@ -# Copyright (c) 2021-2022 Huawei Device Co., Ltd. -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -import("//build/ohos.gni") -import( - "//foundation/distributeddatamgr/distributedfile/distributedfile_aafwk.gni") - -file_common_src = [ - "src/common/file_helper/fd_guard.cpp", - "src/common/napi/n_async/n_async_work_callback.cpp", - "src/common/napi/n_async/n_async_work_promise.cpp", - "src/common/napi/n_async/n_ref.cpp", - "src/common/napi/n_class.cpp", - "src/common/napi/n_func_arg.cpp", - "src/common/napi/n_val.cpp", - "src/common/uni_error.cpp", -] - -ohos_shared_library("fileio") { - subsystem_name = "distributeddatamgr" - part_name = "distributedfilejs" - - relative_install_dir = "module" - - include_dirs = [ - "//third_party/node/src", - "//foundation/arkui/napi/interfaces/kits", - "//third_party/bounds_checking_function/include", - "//third_party/libuv/include", - "//third_party/openssl/include", - "//foundation/distributeddatamgr/distributedfile/interfaces/kits/js/src/common/napi", - "//foundation/distributeddatamgr/distributedfile/interfaces/kits/js/src/common/napi/n_async", - "//foundation/distributeddatamgr/distributedfile/interfaces/kits/js/src/common/file_helper", - "//foundation/distributeddatamgr/distributedfile/interfaces/kits/native/remote_uri", - ] - - sources = file_common_src - sources += [ - "src/common/file_helper/hash_file.cpp", - "src/mod_fileio/class_constants/constants.cpp", - "src/mod_fileio/class_dir/dir_n_exporter.cpp", - "src/mod_fileio/class_dirent/dirent_n_exporter.cpp", - "src/mod_fileio/class_randomaccessfile/randomaccessfile_n_exporter.cpp", - "src/mod_fileio/class_stat/stat_n_exporter.cpp", - "src/mod_fileio/class_stream/flush.cpp", - "src/mod_fileio/class_stream/stream_n_exporter.cpp", - "src/mod_fileio/class_watcher/watcher_n_exporter.cpp", - "src/mod_fileio/common_func.cpp", - "src/mod_fileio/module.cpp", - "src/mod_fileio/properties/chmod.cpp", - "src/mod_fileio/properties/chown.cpp", - "src/mod_fileio/properties/close.cpp", - "src/mod_fileio/properties/copy_file.cpp", - "src/mod_fileio/properties/create_randomaccessfile.cpp", - "src/mod_fileio/properties/create_stream.cpp", - "src/mod_fileio/properties/fchmod.cpp", - "src/mod_fileio/properties/fchown.cpp", - "src/mod_fileio/properties/fdatasync.cpp", - "src/mod_fileio/properties/fdopen_stream.cpp", - "src/mod_fileio/properties/fstat.cpp", - "src/mod_fileio/properties/fsync.cpp", - "src/mod_fileio/properties/ftruncate.cpp", - "src/mod_fileio/properties/hash.cpp", - "src/mod_fileio/properties/lchown.cpp", - "src/mod_fileio/properties/link.cpp", - "src/mod_fileio/properties/lseek.cpp", - "src/mod_fileio/properties/lstat.cpp", - "src/mod_fileio/properties/mkdtemp.cpp", - "src/mod_fileio/properties/open.cpp", - "src/mod_fileio/properties/open_dir.cpp", - "src/mod_fileio/properties/posix_fallocate.cpp", - "src/mod_fileio/properties/prop_n_exporter.cpp", - "src/mod_fileio/properties/read_dir.cpp", - "src/mod_fileio/properties/read_text.cpp", - "src/mod_fileio/properties/rename.cpp", - "src/mod_fileio/properties/rmdir.cpp", - "src/mod_fileio/properties/rmdirent.cpp", - "src/mod_fileio/properties/stat.cpp", - "src/mod_fileio/properties/symlink.cpp", - "src/mod_fileio/properties/truncate.cpp", - "src/mod_fileio/properties/watcher.cpp", - ] - - deps = [ - "//foundation/arkui/napi:ace_napi", - "//third_party/bounds_checking_function:libsec_static", - "//third_party/openssl:libcrypto_static", - ] - - external_deps = [ "hilog:libhilog" ] -} - -ohos_shared_library("file") { - subsystem_name = "distributeddatamgr" - part_name = "distributedfilejs" - - relative_install_dir = "module" - - include_dirs = [ - "//third_party/node/src", - "//foundation/arkui/napi/interfaces/kits", - "//third_party/bounds_checking_function/include", - "//foundation/distributeddatamgr/distributedfile/interfaces/kits/js/src/common/napi", - "//foundation/distributeddatamgr/distributedfile/interfaces/kits/js/src/common/napi/n_async", - "//foundation/distributeddatamgr/distributedfile/interfaces/kits/js/src/common/file_helper", - ] - - sources = file_common_src - sources += [ - "src/common/ability_helper.cpp", - "src/mod_file/class_file/file_n_exporter.cpp", - "src/mod_file/common_func.cpp", - "src/mod_file/module.cpp", - ] - - deps = [ - "${ability_runtime_path}/frameworks/native/ability/native:abilitykit_native", - "//foundation/arkui/napi:ace_napi", - "//third_party/bounds_checking_function:libsec_static", - ] - - external_deps = [ "hilog:libhilog" ] -} - -ohos_shared_library("statfs") { - subsystem_name = "distributeddatamgr" - part_name = "distributedfilejs" - - relative_install_dir = "module" - - sources = [ - "src/mod_statfs/statfs_n_exporter.cpp", - "src/mod_statfs/statfs_napi.cpp", - ] - - deps = [ - "//foundation/distributeddatamgr/distributedfile/utils/filemgmt_libhilog", - "//foundation/distributeddatamgr/distributedfile/utils/filemgmt_libn", - ] -} - -ohos_shared_library("environment") { - subsystem_name = "distributeddatamgr" - part_name = "distributedfilejs" - - relative_install_dir = "module" - - include_dirs = [ - "//third_party/node/src", - "//foundation/arkui/napi/interfaces/kits", - "//foundation/distributeddatamgr/distributedfile/interfaces/kits/js/src/common/napi/n_async", - ] - - sources = [ - "src/common/napi/n_async/n_async_work_callback.cpp", - "src/common/napi/n_async/n_async_work_promise.cpp", - "src/common/napi/n_async/n_ref.cpp", - "src/common/napi/n_func_arg.cpp", - "src/common/napi/n_val.cpp", - "src/common/uni_error.cpp", - "src/mod_environment/environment_n_exporter.cpp", - "src/mod_environment/environment_napi.cpp", - ] - - deps = [ "//foundation/arkui/napi:ace_napi" ] - - external_deps = [ "hilog:libhilog" ] -} - -ohos_shared_library("securitylabel") { - subsystem_name = "distributeddatamgr" - part_name = "distributedfilejs" - - relative_install_dir = "module" - - cflags = [ "-Wno-format" ] - - include_dirs = [ - "//foundation/arkui/napi/interfaces/kits", - "//foundation/arkui/ace_engine/frameworks/base/utils", - "//foundation/arkui/ace_engine/frameworks", - "//foundation/distributeddatamgr/distributedfile/interfaces/kits/js/src/common/napi/n_async", - ] - - sources = file_common_src - sources += [ - "src/mod_securitylabel/securitylabel_n_exporter.cpp", - "src/mod_securitylabel/securitylabel_napi.cpp", - ] - - deps = [ "//foundation/arkui/napi:ace_napi" ] - - external_deps = [ "hilog:libhilog" ] -} - -ohos_shared_library("document") { - subsystem_name = "distributeddatamgr" - part_name = "distributedfilejs" - - relative_install_dir = "module" - - include_dirs = [ - "//third_party/node/src", - "//foundation/arkui/napi/interfaces/kits", - "//foundation/distributeddatamgr/distributedfile/interfaces/kits/js/src/common/napi/n_async", - ] - - sources = [ - "src/common/napi/n_async/n_async_work_callback.cpp", - "src/common/napi/n_async/n_async_work_promise.cpp", - "src/common/napi/n_async/n_ref.cpp", - "src/common/napi/n_func_arg.cpp", - "src/common/napi/n_val.cpp", - "src/common/uni_error.cpp", - "src/mod_document/document_n_exporter.cpp", - "src/mod_document/document_napi.cpp", - ] - - deps = [ "//foundation/arkui/napi:ace_napi" ] - - external_deps = [ "hilog:libhilog" ] -} - -group("build_kits_js") { - deps = [ - ":document", - ":environment", - ":file", - ":fileio", - ":securitylabel", - ":statfs", - ] -} diff --git a/interfaces/kits/js/src/common/ability_helper.cpp b/interfaces/kits/js/src/common/ability_helper.cpp deleted file mode 100644 index 595bee6..0000000 --- a/interfaces/kits/js/src/common/ability_helper.cpp +++ /dev/null @@ -1,54 +0,0 @@ -/* - * Copyright (c) 2021 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#include "ability_helper.h" - -#include "log.h" -#include "napi/n_func_arg.h" -#include "napi/uni_header.h" - -namespace OHOS { -namespace DistributedFS { -using namespace std; -using OHOS::AppExecFwk::Ability; -using OHOS::AppExecFwk::AbilityContext; - -Ability* AbilityHelper::GetJsAbility(napi_env env) -{ - napi_value global = nullptr; - napi_value abilityContext = nullptr; - - napi_status status = napi_get_global(env, &global); - if (status != napi_ok || global == nullptr) { - HILOGE("Cannot get global instance for %{public}d", status); - return nullptr; - } - - status = napi_get_named_property(env, global, "ability", &abilityContext); - if (status != napi_ok || abilityContext == nullptr) { - HILOGE("Cannot get ability context for %{public}d", status); - return nullptr; - } - - Ability *ability = nullptr; - status = napi_get_value_external(env, abilityContext, (void **)&ability); - if (status != napi_ok || ability == nullptr) { - HILOGE("Get ability form property failed for %{public}d", status); - } - - return ability; -} -} // namespace DistributedFS -} // namespace OHOS \ No newline at end of file diff --git a/interfaces/kits/js/src/common/ability_helper.h b/interfaces/kits/js/src/common/ability_helper.h deleted file mode 100644 index 36c69cb..0000000 --- a/interfaces/kits/js/src/common/ability_helper.h +++ /dev/null @@ -1,28 +0,0 @@ -/* - * Copyright (c) 2021 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#ifndef INTERFACES_KITS_NAPI_COMMON_ABILITY_HELPER_H -#define INTERFACES_KITS_NAPI_COMMON_ABILITY_HELPER_H - -#include "ability.h" - -namespace OHOS { -namespace DistributedFS { -struct AbilityHelper { - static AppExecFwk::Ability *GetJsAbility(napi_env env); -}; -} // namespace DistributedFS -} // namespace OHOS -#endif \ No newline at end of file diff --git a/interfaces/kits/js/src/common/file_filter.h b/interfaces/kits/js/src/common/file_filter.h deleted file mode 100644 index 694b6f0..0000000 --- a/interfaces/kits/js/src/common/file_filter.h +++ /dev/null @@ -1,174 +0,0 @@ -/* - * 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_FILTER_H -#define FILE_FILTER_H - -#include -#include - -#include "parcel.h" - -namespace OHOS { -namespace DistributedFS { -class FileFilter : public Parcelable { -public: - FileFilter() = default; - ~FileFilter() = default; - - FileFilter(std::vector suffix, std::vector displayName, - std::vector mimeType, int64_t fileSizeOver, - double lastModifiedAfter, bool excludeMedia, bool hasFilter) - : suffix_(suffix), displayName_(displayName), mimeType_(mimeType), fileSizeOver_(fileSizeOver), - lastModifiedAfter_(lastModifiedAfter), excludeMedia_(excludeMedia), hasFilter_(hasFilter) {} - explicit FileFilter(std::vector suffix): suffix_(suffix) {} - FileFilter(const FileFilter &filter) = default; - FileFilter &operator=(const FileFilter& filter) = default; - - void SetSuffix(const std::vector &suffix) - { - suffix_ = suffix; - } - - std::vector GetSuffix() const - { - return suffix_; - } - - void SetDisplayName(const std::vector &displayName) - { - displayName_ = displayName; - } - - std::vector GetDisplayName() const - { - return displayName_; - } - - void SetMimeType(const std::vector &mimeType) - { - mimeType_ = mimeType; - } - - std::vector GetMimeType() const - { - return mimeType_; - } - - void SetFileSizeOver(const int64_t &fileSizeOver) - { - fileSizeOver_ = fileSizeOver; - } - - int64_t GetFileSizeOver() const - { - return fileSizeOver_; - } - - void SetLastModifiedAfter(const double &lastModifiedAfter) - { - lastModifiedAfter_ = lastModifiedAfter; - } - - double GetLastModifiedAfter() const - { - return lastModifiedAfter_; - } - - void SetExcludeMedia(const bool &excludeMedia) - { - excludeMedia_ = excludeMedia; - } - - bool GetExcludeMedia() const - { - return excludeMedia_; - } - - void SetHasFilter(const bool &hasFilter) - { - hasFilter_ = hasFilter; - } - - bool GetHasFilter() const - { - return hasFilter_; - } - - bool Marshalling(Parcel &parcel) const - { - if (!parcel.WriteStringVector(suffix_)) { - return false; - } - if (!parcel.WriteStringVector(displayName_)) { - return false; - } - if (!parcel.WriteStringVector(mimeType_)) { - return false; - } - if (!parcel.WriteInt64(fileSizeOver_)) { - return false; - } - if (!parcel.WriteDouble(lastModifiedAfter_)) { - return false; - } - if (!parcel.WriteBool(excludeMedia_)) { - return false; - } - if (!parcel.WriteBool(hasFilter_)) { - return false; - } - return true; - } - - static FileFilter* Unmarshalling(Parcel &parcel) - { - auto obj = new (std::nothrow) FileFilter(); - if (obj != nullptr && !obj->ReadFromParcel(parcel)) { - delete obj; - obj = nullptr; - } - return obj; - } - - bool ReadFromParcel(Parcel &parcel) - { - if (!parcel.ReadStringVector(&suffix_)) { - return false; - } - if (!parcel.ReadStringVector(&displayName_)) { - return false; - } - if (!parcel.ReadStringVector(&mimeType_)) { - return false; - } - fileSizeOver_ = parcel.ReadInt64(); - lastModifiedAfter_ = parcel.ReadDouble(); - excludeMedia_ = parcel.ReadBool(); - hasFilter_ = parcel.ReadBool(); - return true; - } - -private: - std::vector suffix_ = std::vector(); - std::vector displayName_ = std::vector(); - std::vector mimeType_ = std::vector(); - int64_t fileSizeOver_ = 0; - double lastModifiedAfter_ = 0; - bool excludeMedia_ = false; - bool hasFilter_ = false; -}; -} // namespace DistributedFS -} // namespace OHOS -#endif // FILE_FILTER_H \ No newline at end of file diff --git a/interfaces/kits/js/src/common/file_helper/fd_guard.cpp b/interfaces/kits/js/src/common/file_helper/fd_guard.cpp deleted file mode 100644 index 6959b45..0000000 --- a/interfaces/kits/js/src/common/file_helper/fd_guard.cpp +++ /dev/null @@ -1,75 +0,0 @@ -/* - * Copyright (c) 2021 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#include "fd_guard.h" - -#include - -#include "../log.h" - -namespace OHOS { -namespace DistributedFS { -FDGuard::FDGuard(int fd) : fd_(fd) {} - -FDGuard::FDGuard(int fd, bool autoClose) : fd_(fd), autoClose_(autoClose) {} - -FDGuard::FDGuard(FDGuard &&fdg) : fd_(fdg.fd_), autoClose_(fdg.autoClose_) -{ - fdg.fd_ = -1; -} - -FDGuard &FDGuard::operator=(FDGuard &&fdg) -{ - if (this == &fdg) { - return *this; - } - this->fd_ = fdg.fd_; - this->autoClose_ = fdg.autoClose_; - fdg.fd_ = -1; - return *this; -} - -FDGuard::~FDGuard() -{ - if (fd_ >= 0 && fd_ <= STDERR_FILENO) { - HILOGI("~FDGuard, fd_ = %{public}d", fd_); - } - if (fd_ >= 0 && autoClose_) { - close(fd_); - } -} - -FDGuard::operator bool() const -{ - return fd_ >= 0; -} - -int FDGuard::GetFD() const -{ - return fd_; -} - -void FDGuard::SetFD(int fd, bool autoClose) -{ - fd_ = fd; - autoClose_ = autoClose; -} - -void FDGuard::ClearFD() -{ - fd_ = -1; -} -} // namespace DistributedFS -} // namespace OHOS diff --git a/interfaces/kits/js/src/common/file_helper/fd_guard.h b/interfaces/kits/js/src/common/file_helper/fd_guard.h deleted file mode 100644 index 07c27b1..0000000 --- a/interfaces/kits/js/src/common/file_helper/fd_guard.h +++ /dev/null @@ -1,47 +0,0 @@ -/* - * Copyright (c) 2021 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#ifndef FD_GUARD_H -#define FD_GUARD_H - -namespace OHOS { -namespace DistributedFS { -class FDGuard final { -public: - FDGuard() = default; - explicit FDGuard(int fd); - FDGuard(int fd, bool autoClose); - - FDGuard(const FDGuard &fdg) = delete; - FDGuard &operator=(const FDGuard &fdg) = delete; - - FDGuard(FDGuard &&fdg); - FDGuard &operator=(FDGuard &&fdg); - - operator bool() const; - - ~FDGuard(); - - int GetFD() const; - void SetFD(int fd, bool autoClose = true); - void ClearFD(); - -private: - int fd_ = -1; - bool autoClose_ = true; -}; -} // namespace DistributedFS -} // namespace OHOS -#endif \ No newline at end of file diff --git a/interfaces/kits/js/src/common/file_helper/hash_file.cpp b/interfaces/kits/js/src/common/file_helper/hash_file.cpp deleted file mode 100644 index 2bd54cc..0000000 --- a/interfaces/kits/js/src/common/file_helper/hash_file.cpp +++ /dev/null @@ -1,106 +0,0 @@ -/* - * Copyright (c) 2021 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#include "hash_file.h" - -#include -#include -#include -#include -#include -#include -#include -#include - -namespace OHOS { -namespace DistributedFS { -using namespace std; - -static tuple HashFinal(int err, const unique_ptr &hashBuf, size_t hashLen) -{ - if (err) { - return { err, "" }; - } - - stringstream ss; - for (size_t i = 0; i < hashLen; ++i) { - const int hexPerByte = 2; - ss << std::uppercase << std::setfill('0') << std::setw(hexPerByte) << std::hex << - static_cast(hashBuf[i]); - } - - return { err, ss.str() }; -} - -static int ForEachFileSegment(const string &fpath, function executor) -{ - unique_ptr filp = { fopen(fpath.c_str(), "r"), fclose }; - if (!filp) { - return errno; - } - - const size_t pageSize { getpagesize() }; - auto buf = make_unique(pageSize); - size_t actLen; - do { - actLen = fread(buf.get(), 1, pageSize, filp.get()); - if (actLen > 0) { - executor(buf.get(), actLen); - } - } while (actLen == pageSize); - - return ferror(filp.get()) ? errno : 0; -} - -tuple HashFile::HashWithMD5(const string &fpath) -{ - auto res = make_unique(MD5_DIGEST_LENGTH); - MD5_CTX ctx; - MD5_Init(&ctx); - auto md5Update = [ctx = &ctx](char *buf, size_t len) { - MD5_Update(ctx, buf, len); - }; - int err = ForEachFileSegment(fpath, md5Update); - MD5_Final(res.get(), &ctx); - return HashFinal(err, res, MD5_DIGEST_LENGTH); -} - -tuple HashFile::HashWithSHA1(const string &fpath) -{ - auto res = make_unique(SHA_DIGEST_LENGTH); - SHA_CTX ctx; - SHA1_Init(&ctx); - auto sha1Update = [ctx = &ctx](char *buf, size_t len) { - SHA1_Update(ctx, buf, len); - }; - int err = ForEachFileSegment(fpath, sha1Update); - SHA1_Final(res.get(), &ctx); - return HashFinal(err, res, SHA_DIGEST_LENGTH); -} - -tuple HashFile::HashWithSHA256(const string &fpath) -{ - auto res = make_unique(SHA256_DIGEST_LENGTH); - SHA256_CTX ctx; - SHA256_Init(&ctx); - auto sha256Update = [ctx = &ctx](char *buf, size_t len) { - SHA256_Update(ctx, buf, len); - }; - int err = ForEachFileSegment(fpath, sha256Update); - SHA256_Final(res.get(), &ctx); - return HashFinal(err, res, SHA256_DIGEST_LENGTH); -} -} // namespace DistributedFS -} // namespace OHOS \ No newline at end of file diff --git a/interfaces/kits/js/src/common/file_helper/hash_file.h b/interfaces/kits/js/src/common/file_helper/hash_file.h deleted file mode 100644 index 81d68a2..0000000 --- a/interfaces/kits/js/src/common/file_helper/hash_file.h +++ /dev/null @@ -1,32 +0,0 @@ -/* - * Copyright (c) 2021 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#ifndef HASH_FILE_H -#define HASH_FILE_H - -#include -#include - -namespace OHOS { -namespace DistributedFS { -class HashFile { -public: - static std::tuple HashWithMD5(const std::string &fpath); - static std::tuple HashWithSHA1(const std::string &fpath); - static std::tuple HashWithSHA256(const std::string &fpath); -}; -} // namespace DistributedFS -} // namespace OHOS -#endif \ No newline at end of file diff --git a/interfaces/kits/js/src/common/log.h b/interfaces/kits/js/src/common/log.h deleted file mode 100644 index 412b5f6..0000000 --- a/interfaces/kits/js/src/common/log.h +++ /dev/null @@ -1,92 +0,0 @@ -/* - * Copyright (c) 2021 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#ifndef INTERFACES_KITS_NAPI_COMMON_LOG_H -#define INTERFACES_KITS_NAPI_COMMON_LOG_H - -#include -#include -#include - -#ifndef FILE_SUBSYSTEM_DEBUG_LOCAL -#include "hilog/log.h" -#endif - -namespace OHOS { -namespace DistributedFS { -#ifndef FILE_SUBSYSTEM_DEBUG_LOCAL -static constexpr int FILEIO_DOMAIN_ID = 0; -static constexpr OHOS::HiviewDFX::HiLogLabel FILEIO_LABEL = { LOG_CORE, FILEIO_DOMAIN_ID, "distributedfilejs" }; - -#ifdef HILOGD -#undef HILOGD -#endif - -#ifdef HILOGF -#undef HILOGF -#endif - -#ifdef HILOGE -#undef HILOGE -#endif - -#ifdef HILOGW -#undef HILOGW -#endif - -#ifdef HILOGI -#undef HILOGI -#endif - -#define HILOGD(fmt, ...) \ - (void)OHOS::HiviewDFX::HiLog::Debug(OHOS::DistributedFS::FILEIO_LABEL, "%{public}s: " fmt, __func__, ##__VA_ARGS__) -#define HILOGI(fmt, ...) \ - (void)OHOS::HiviewDFX::HiLog::Info(OHOS::DistributedFS::FILEIO_LABEL, "%{public}s: " fmt, __func__, ##__VA_ARGS__) -#define HILOGW(fmt, ...) \ - (void)OHOS::HiviewDFX::HiLog::Warn(OHOS::DistributedFS::FILEIO_LABEL, "%{public}s: " fmt, __func__, ##__VA_ARGS__) -#define HILOGE(fmt, ...) \ - (void)OHOS::HiviewDFX::HiLog::Error(OHOS::DistributedFS::FILEIO_LABEL, "%{public}s: " fmt, __func__, ##__VA_ARGS__) -#define HILOGF(fmt, ...) \ - (void)OHOS::HiviewDFX::HiLog::Fatal(OHOS::DistributedFS::FILEIO_LABEL, "%{public}s: " fmt, __func__, ##__VA_ARGS__) - -#else - -#define PCLOG(fmt, ...) \ - do { \ - const std::vector filter = { \ - "{public}", \ - "{private}", \ - }; \ - std::string str____(fmt); \ - for (auto &&pattern : filter) { \ - size_t pos = 0; \ - while (std::string::npos != (pos = str____.find(pattern))) { \ - str____.erase(pos, pattern.length()); \ - } \ - } \ - str____ += "\n"; \ - printf(str____.c_str(), ##__VA_ARGS__); \ - } while (0) \ - -#define HILOGD(fmt, ...) PCLOG("%{public}s: " fmt, __func__, ##__VA_ARGS__) -#define HILOGI(fmt, ...) PCLOG("%{public}s: " fmt, __func__, ##__VA_ARGS__) -#define HILOGW(fmt, ...) PCLOG("%{public}s: " fmt, __func__, ##__VA_ARGS__) -#define HILOGE(fmt, ...) PCLOG("%{public}s: " fmt, __func__, ##__VA_ARGS__) -#define HILOGF(fmt, ...) PCLOG("%{public}s: " fmt, __func__, ##__VA_ARGS__) - -#endif -} // namespace DistributedFS -} // namespace OHOS -#endif \ No newline at end of file diff --git a/interfaces/kits/js/src/common/napi/n_async/n_async_context.h b/interfaces/kits/js/src/common/napi/n_async/n_async_context.h deleted file mode 100644 index 87339bb..0000000 --- a/interfaces/kits/js/src/common/napi/n_async/n_async_context.h +++ /dev/null @@ -1,68 +0,0 @@ -/* - * Copyright (c) 2021 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#ifndef N_ASYNC_CONTEXT_H -#define N_ASYNC_CONTEXT_H - -#include "../../uni_error.h" -#include "../n_val.h" -#include "n_ref.h" - -namespace OHOS { -namespace DistributedFS { -using NContextCBExec = std::function; -using NContextCBComplete = std::function; - -class NAsyncContext { -public: - UniError err_; - NVal res_; - NContextCBExec cbExec_; - NContextCBComplete cbComplete_; - napi_async_work awork_; - NRef thisPtr_; - - explicit NAsyncContext(NVal thisPtr) : err_(0), res_(NVal()), cbExec_(nullptr), - cbComplete_(nullptr), awork_(nullptr), thisPtr_(thisPtr) {} - virtual ~NAsyncContext() = default; -}; - -class NAsyncContextPromise : public NAsyncContext { -public: - napi_deferred deferred_ = nullptr; - explicit NAsyncContextPromise(NVal thisPtr) : NAsyncContext(thisPtr) {} - ~NAsyncContextPromise() = default; -}; - -class NAsyncContextCallback : public NAsyncContext { -public: - NRef cb_; - NAsyncContextCallback(NVal thisPtr, NVal cb) : NAsyncContext(thisPtr), cb_(cb) {} - ~NAsyncContextCallback() = default; -}; - -class NAsyncContextLegacy : public NAsyncContext { -public: - NRef cbSucc_; - NRef cbFail_; - NRef cbFinal_; - NAsyncContextLegacy(NVal thisPtr, NVal cbSucc, NVal cbFail, NVal cbFinal) - : NAsyncContext(thisPtr), cbSucc_(cbSucc), cbFail_(cbFail), cbFinal_(cbFinal) - {} - ~NAsyncContextLegacy() = default; -}; -} // namespace DistributedFS -} // namespace OHOS -#endif // N_ASYNC_CONTEXT_H \ No newline at end of file diff --git a/interfaces/kits/js/src/common/napi/n_async/n_async_work_callback.cpp b/interfaces/kits/js/src/common/napi/n_async/n_async_work_callback.cpp deleted file mode 100644 index 71acd0c..0000000 --- a/interfaces/kits/js/src/common/napi/n_async/n_async_work_callback.cpp +++ /dev/null @@ -1,111 +0,0 @@ -/* - * Copyright (c) 2021 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#include "n_async_work_callback.h" - -#include - -#include -#include -#include -#include -#include - -#include "../../log.h" -#include "../../uni_error.h" -#include "js_native_api.h" -#include "n_ref.h" -#include "node_api.h" - -namespace OHOS { -namespace DistributedFS { -using namespace std; - -NAsyncWorkCallback::NAsyncWorkCallback(napi_env env, NVal thisPtr, NVal cb) : NAsyncWorkFactory(env) -{ - ctx_ = new NAsyncContextCallback(thisPtr, cb); -} - -static void CallbackExecute(napi_env env, void *data) -{ - auto ctx = static_cast(data); - if (ctx != nullptr && ctx->cbExec_ != nullptr) { - ctx->err_ = ctx->cbExec_(env); - } -} - -static void CallbackComplete(napi_env env, napi_status status, void *data) -{ - napi_handle_scope scope = nullptr; - napi_open_handle_scope(env, &scope); - auto ctx = static_cast(data); - if (ctx == nullptr) { - return; - } - if (ctx->cbComplete_ != nullptr) { - ctx->res_ = ctx->cbComplete_(env, ctx->err_); - ctx->cbComplete_ = nullptr; - } - - vector argv; - if (!ctx->res_.TypeIsError(true)) { - argv = { UniError(ERRNO_NOERR).GetNapiErr(env), ctx->res_.val_ }; - } else { - argv = { ctx->res_.val_ }; - } - - napi_value global = nullptr; - napi_value callback = ctx->cb_.Deref(env).val_; - napi_value tmp = nullptr; - napi_get_global(env, &global); - napi_status stat = napi_call_function(env, global, callback, argv.size(), argv.data(), &tmp); - if (stat != napi_ok) { - HILOGE("Failed to call function for %{public}d", stat); - } - napi_close_handle_scope(env, scope); - napi_delete_async_work(env, ctx->awork_); - delete ctx; -} - -NVal NAsyncWorkCallback::Schedule(string procedureName, NContextCBExec cbExec, NContextCBComplete cbComplete) -{ - if (!ctx_->cb_ || !ctx_->cb_.Deref(env_).TypeIs(napi_function)) { - UniError(EINVAL).ThrowErr(env_, "The callback shall be a function"); - return NVal(); - } - - ctx_->cbExec_ = move(cbExec); - ctx_->cbComplete_ = move(cbComplete); - - napi_value resource = NVal::CreateUTF8String(env_, procedureName).val_; - - napi_status status = - napi_create_async_work(env_, nullptr, resource, CallbackExecute, CallbackComplete, ctx_, &ctx_->awork_); - if (status != napi_ok) { - HILOGE("INNER BUG. Failed to create async work for %{public}d", status); - return NVal(); - } - - status = napi_queue_async_work(env_, ctx_->awork_); - if (status != napi_ok) { - HILOGE("INNER BUG. Failed to queue async work for %{public}d", status); - return NVal(); - } - - ctx_ = nullptr; // The ownership of ctx_ has been transferred - return NVal::CreateUndefined(env_); -} -} // namespace DistributedFS -} // namespace OHOS diff --git a/interfaces/kits/js/src/common/napi/n_async/n_async_work_callback.h b/interfaces/kits/js/src/common/napi/n_async/n_async_work_callback.h deleted file mode 100644 index 59a55d9..0000000 --- a/interfaces/kits/js/src/common/napi/n_async/n_async_work_callback.h +++ /dev/null @@ -1,40 +0,0 @@ -/* - * Copyright (c) 2021 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#ifndef N_ASYNC_WORK_CALLBACK_H -#define N_ASYNC_WORK_CALLBACK_H - -#include - -#include "../n_val.h" -#include "js_native_api_types.h" -#include "n_async_context.h" -#include "n_async_work_factory.h" - -namespace OHOS { -namespace DistributedFS { -class NAsyncWorkCallback : public NAsyncWorkFactory { -public: - NAsyncWorkCallback(napi_env env, NVal thisPtr, NVal cb); - ~NAsyncWorkCallback() = default; - - NVal Schedule(std::string procedureName, NContextCBExec cbExec, NContextCBComplete cbComplete) final; - -private: - NAsyncContextCallback *ctx_ = nullptr; -}; -} // namespace DistributedFS -} // namespace OHOS -#endif // N_ASYNC_WORK_CALLBACK_H \ No newline at end of file diff --git a/interfaces/kits/js/src/common/napi/n_async/n_async_work_factory.h b/interfaces/kits/js/src/common/napi/n_async/n_async_work_factory.h deleted file mode 100644 index 7b11546..0000000 --- a/interfaces/kits/js/src/common/napi/n_async/n_async_work_factory.h +++ /dev/null @@ -1,33 +0,0 @@ -/* - * Copyright (c) 2021 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#ifndef N_ASYNC_WORK_FACTORY_H -#define N_ASYNC_WORK_FACTORY_H - -#include "n_async_context.h" - -namespace OHOS { -namespace DistributedFS { -class NAsyncWorkFactory { -public: - explicit NAsyncWorkFactory(napi_env env) : env_(env) {} - virtual ~NAsyncWorkFactory() = default; - virtual NVal Schedule(std::string procedureName, NContextCBExec cbExec, NContextCBComplete cbComplete) = 0; - - napi_env env_ = nullptr; -}; -} // namespace DistributedFS -} // namespace OHOS -#endif // N_ASYNC_WORK_FACTORY_H \ No newline at end of file diff --git a/interfaces/kits/js/src/common/napi/n_async/n_async_work_promise.cpp b/interfaces/kits/js/src/common/napi/n_async/n_async_work_promise.cpp deleted file mode 100644 index c0db483..0000000 --- a/interfaces/kits/js/src/common/napi/n_async/n_async_work_promise.cpp +++ /dev/null @@ -1,100 +0,0 @@ -/* - * Copyright (c) 2021 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#include "n_async_work_promise.h" - -#include -#include -#include -#include - -#include "../../log.h" -#include "../../uni_error.h" -#include "js_native_api.h" -#include "node_api.h" - -namespace OHOS { -namespace DistributedFS { -using namespace std; - -NAsyncWorkPromise::NAsyncWorkPromise(napi_env env, NVal thisPtr) : NAsyncWorkFactory(env) -{ - ctx_ = new NAsyncContextPromise(thisPtr); -} - -static void PromiseOnExec(napi_env env, void *data) -{ - auto ctx = static_cast(data); - if (ctx != nullptr && ctx->cbExec_ != nullptr) { - ctx->err_ = ctx->cbExec_(env); - } -} - -static void PromiseOnComplete(napi_env env, napi_status status, void *data) -{ - auto ctx = static_cast(data); - if (ctx == nullptr) { - return; - } - if (ctx->cbComplete_ != nullptr) { - ctx->res_ = ctx->cbComplete_(env, ctx->err_); - } - if (!ctx->res_.TypeIsError(true)) { - napi_status status = napi_resolve_deferred(env, ctx->deferred_, ctx->res_.val_); - if (status != napi_ok) { - HILOGE("Internal BUG, cannot resolve promise for %{public}d", status); - } - } else { - napi_status status = napi_reject_deferred(env, ctx->deferred_, ctx->res_.val_); - if (status != napi_ok) { - HILOGE("Internal BUG, cannot reject promise for %{public}d", status); - } - } - ctx->deferred_ = nullptr; - napi_delete_async_work(env, ctx->awork_); - delete ctx; -} - -NVal NAsyncWorkPromise::Schedule(string procedureName, NContextCBExec cbExec, NContextCBComplete cbComplete) -{ - ctx_->cbExec_ = move(cbExec); - ctx_->cbComplete_ = move(cbComplete); - - napi_status status; - napi_value result = nullptr; - status = napi_create_promise(env_, &ctx_->deferred_, &result); - if (status != napi_ok) { - HILOGE("INNER BUG. Cannot create promise for %{public}d", status); - return NVal(); - } - - napi_value resource = NVal::CreateUTF8String(env_, procedureName).val_; - status = napi_create_async_work(env_, nullptr, resource, PromiseOnExec, PromiseOnComplete, ctx_, &ctx_->awork_); - if (status != napi_ok) { - HILOGE("INNER BUG. Failed to create async work for %{public}d", status); - return NVal(); - } - - status = napi_queue_async_work(env_, ctx_->awork_); - if (status != napi_ok) { - HILOGE("INNER BUG. Failed to queue async work for %{public}d", status); - return NVal(); - } - - ctx_ = nullptr; // The ownership of ctx_ has been transferred - return { env_, result }; -} -} // namespace DistributedFS -} // namespace OHOS diff --git a/interfaces/kits/js/src/common/napi/n_async/n_async_work_promise.h b/interfaces/kits/js/src/common/napi/n_async/n_async_work_promise.h deleted file mode 100644 index 3ed8045..0000000 --- a/interfaces/kits/js/src/common/napi/n_async/n_async_work_promise.h +++ /dev/null @@ -1,40 +0,0 @@ -/* - * Copyright (c) 2021 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#ifndef N_ASYNC_WORK_PROMISE_H -#define N_ASYNC_WORK_PROMISE_H - -#include - -#include "../n_val.h" -#include "js_native_api_types.h" -#include "n_async_context.h" -#include "n_async_work_factory.h" - -namespace OHOS { -namespace DistributedFS { -class NAsyncWorkPromise : public NAsyncWorkFactory { -public: - NAsyncWorkPromise(napi_env env, NVal thisPtr); - ~NAsyncWorkPromise() = default; - - NVal Schedule(std::string procedureName, NContextCBExec cbExec, NContextCBComplete cbComplete) final; - -private: - NAsyncContextPromise *ctx_; -}; -} // namespace DistributedFS -} // namespace OHOS -#endif // N_ASYNC_WORK_PROMISE_H \ No newline at end of file diff --git a/interfaces/kits/js/src/common/napi/n_async/n_ref.cpp b/interfaces/kits/js/src/common/napi/n_async/n_ref.cpp deleted file mode 100644 index 10c3ae0..0000000 --- a/interfaces/kits/js/src/common/napi/n_async/n_ref.cpp +++ /dev/null @@ -1,56 +0,0 @@ -/* - * Copyright (c) 2021 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#include "n_ref.h" - -#include "../n_val.h" -#include "js_native_api.h" - -namespace OHOS { -namespace DistributedFS { -NRef::NRef() {} - -NRef::NRef(NVal val) -{ - if (val) { - env_ = val.env_; - napi_create_reference(val.env_, val.val_, 1, &ref_); - } -} - -NRef::~NRef() -{ - if (ref_) { - napi_delete_reference(env_, ref_); - } -} - -NRef::operator bool() const -{ - return ref_ != nullptr; -} - -NVal NRef::Deref(napi_env env) -{ - if (!ref_) { - return NVal(); - } - - napi_value val = nullptr; - napi_get_reference_value(env, ref_, &val); - return { env, val }; -} -} // namespace DistributedFS -} // namespace OHOS diff --git a/interfaces/kits/js/src/common/napi/n_async/n_ref.h b/interfaces/kits/js/src/common/napi/n_async/n_ref.h deleted file mode 100644 index e0068db..0000000 --- a/interfaces/kits/js/src/common/napi/n_async/n_ref.h +++ /dev/null @@ -1,39 +0,0 @@ -/* - * Copyright (c) 2021 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#ifndef N_REF_H -#define N_REF_H - -#include "../n_val.h" -#include "js_native_api_types.h" - -namespace OHOS { -namespace DistributedFS { -class NRef { -public: - NRef(); - explicit NRef(NVal val); - ~NRef(); - - explicit operator bool() const; - NVal Deref(napi_env env); - -private: - napi_env env_ = nullptr; - napi_ref ref_ = nullptr; -}; -} // namespace DistributedFS -} // namespace OHOS -#endif // N_REF_H \ No newline at end of file diff --git a/interfaces/kits/js/src/common/napi/n_class.cpp b/interfaces/kits/js/src/common/napi/n_class.cpp deleted file mode 100644 index dbda702..0000000 --- a/interfaces/kits/js/src/common/napi/n_class.cpp +++ /dev/null @@ -1,99 +0,0 @@ -/* - * Copyright (c) 2021 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#include "n_class.h" - -#include -#include - -#include "../log.h" - -namespace OHOS { -namespace DistributedFS { -using namespace std; -NClass &NClass::GetInstance() -{ - static thread_local NClass nClass; - return nClass; -} - -tuple NClass::DefineClass(napi_env env, - string className, - napi_callback constructor, - vector &&properties) -{ - napi_value classVal = nullptr; - napi_status stat = napi_define_class(env, - className.c_str(), - className.length(), - constructor, - nullptr, - properties.size(), - properties.data(), - &classVal); - if (stat != napi_ok) { - HILOGE("INNER BUG. Cannot define class %{public}s because of %{public}d", className.c_str(), stat); - } - return { stat == napi_ok, classVal }; -} - -bool NClass::SaveClass(napi_env env, string className, napi_value exClass) -{ - NClass &nClass = NClass::GetInstance(); - lock_guard(nClass.exClassMapLock); - - if (nClass.exClassMap.find(className) != nClass.exClassMap.end()) { - return true; - } - - napi_ref constructor; - napi_status res = napi_create_reference(env, exClass, 1, &constructor); - if (res == napi_ok) { - nClass.exClassMap.insert({ className, constructor }); - HILOGI("Class %{public}s has been saved", className.c_str()); - } else { - HILOGE("INNER BUG. Cannot ref class constructor %{public}s because of %{public}d", className.c_str(), res); - } - return res == napi_ok; -} - -napi_value NClass::InstantiateClass(napi_env env, const string& className, const vector& args) -{ - NClass &nClass = NClass::GetInstance(); - lock_guard(nClass.exClassMapLock); - - auto it = nClass.exClassMap.find(className); - if (it == nClass.exClassMap.end()) { - HILOGE("Class %{public}s hasn't been saved yet", className.c_str()); - return nullptr; - } - - napi_value cons = nullptr; - napi_status status = napi_get_reference_value(env, it->second, &cons); - if (status != napi_ok) { - HILOGE("INNER BUG. Cannot deref class %{public}s because of %{public}d", className.c_str(), status); - return nullptr; - } - - napi_value instance = nullptr; - status = napi_new_instance(env, cons, args.size(), args.data(), &instance); - if (status != napi_ok) { - HILOGE("INNER BUG. Cannot instantiate the class %{public}s because of %{public}d", className.c_str(), status); - return nullptr; - } - return instance; -} -} // namespace DistributedFS -} // namespace OHOS diff --git a/interfaces/kits/js/src/common/napi/n_class.h b/interfaces/kits/js/src/common/napi/n_class.h deleted file mode 100644 index c5dd805..0000000 --- a/interfaces/kits/js/src/common/napi/n_class.h +++ /dev/null @@ -1,78 +0,0 @@ -/* - * Copyright (c) 2021 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#ifndef INTERFACES_KITS_NAPI_COMMON_NAPI_N_CLASS_H -#define INTERFACES_KITS_NAPI_COMMON_NAPI_N_CLASS_H - -#include - -#include "../log.h" -#include "uni_header.h" - -namespace OHOS { -namespace DistributedFS { -class NClass final { -public: - NClass(const NClass &) = delete; - NClass &operator = (const NClass &) = delete; - static NClass &GetInstance(); - - static std::tuple DefineClass(napi_env env, - std::string className, - napi_callback constructor, - std::vector &&properties); - static bool SaveClass(napi_env env, std::string className, napi_value exClass); - static napi_value InstantiateClass(napi_env env, const std::string& className, const std::vector& args); - - template static T *GetEntityOf(napi_env env, napi_value objStat) - { - if (!env || !objStat) { - HILOGE("Empty input: env %d, obj %d", env == nullptr, objStat == nullptr); - return nullptr; - } - T *t = nullptr; - napi_status status = napi_unwrap(env, objStat, (void **)&t); - if (status != napi_ok) { - HILOGE("Cannot umwarp for pointer: %d", status); - return nullptr; - } - return t; - } - - template static bool SetEntityFor(napi_env env, napi_value obj, std::unique_ptr entity) - { - napi_status status = napi_wrap( - env, - obj, - entity.get(), - [](napi_env env, void *data, void *hint) { - auto entity = static_cast(data); - delete entity; - }, - nullptr, - nullptr); - entity.release(); - return status == napi_ok; - } - -private: - NClass() = default; - ~NClass() = default; - std::map exClassMap; - std::mutex exClassMapLock; -}; -} // namespace DistributedFS -} // namespace OHOS -#endif \ No newline at end of file diff --git a/interfaces/kits/js/src/common/napi/n_exporter.h b/interfaces/kits/js/src/common/napi/n_exporter.h deleted file mode 100644 index db5563f..0000000 --- a/interfaces/kits/js/src/common/napi/n_exporter.h +++ /dev/null @@ -1,36 +0,0 @@ -/* - * Copyright (c) 2021 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#ifndef INTERFACES_KITS_NAPI_COMMON_NAPI_N_EXPORTER_H -#define INTERFACES_KITS_NAPI_COMMON_NAPI_N_EXPORTER_H - -#include "n_val.h" - -namespace OHOS { -namespace DistributedFS { -class NExporter { -public: - NExporter(napi_env env, napi_value exports) : exports_(env, exports) {}; - virtual ~NExporter() = default; - - virtual bool Export() = 0; - virtual std::string GetClassName() = 0; - -protected: - NVal exports_; -}; -} // namespace DistributedFS -} // namespace OHOS -#endif \ No newline at end of file diff --git a/interfaces/kits/js/src/common/napi/n_func_arg.cpp b/interfaces/kits/js/src/common/napi/n_func_arg.cpp deleted file mode 100644 index 8f7e4e3..0000000 --- a/interfaces/kits/js/src/common/napi/n_func_arg.cpp +++ /dev/null @@ -1,109 +0,0 @@ -/* - * Copyright (c) 2021 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#include "n_func_arg.h" - -#include "js_native_api.h" -#include "../log.h" - -namespace OHOS { -namespace DistributedFS { -using namespace std; - -NFuncArg::NFuncArg(napi_env env, napi_callback_info info) : env_(env), info_(info) {} - -NFuncArg::~NFuncArg() {} - -void NFuncArg::SetArgc(size_t argc) -{ - argc_ = argc; -} - -void NFuncArg::SetThisVar(napi_value thisVar) -{ - thisVar_ = thisVar; -} - -size_t NFuncArg::GetArgc(void) const -{ - return argc_; -} - -napi_value NFuncArg::GetThisVar(void) const -{ - return thisVar_; -} - -napi_value NFuncArg::GetArg(size_t argPos) const -{ - return (argPos < GetArgc()) ? argv_[argPos] : nullptr; -} - -napi_value NFuncArg::operator[](size_t argPos) const -{ - return GetArg(argPos); -} - -bool NFuncArg::InitArgs(std::function argcChecker) -{ - SetArgc(0); - argv_.reset(); - - size_t argc; - napi_value thisVar; - napi_status status = napi_get_cb_info(env_, info_, &argc, nullptr, &thisVar, nullptr); - if (status != napi_ok) { - HILOGE("Cannot get num of func args for %{public}d", status); - return false; - } - if (argc) { - argv_ = make_unique(argc); - status = napi_get_cb_info(env_, info_, &argc, argv_.get(), &thisVar, nullptr); - if (status != napi_ok) { - HILOGE("Cannot get func args for %{public}d", status); - return false; - } - } - SetArgc(argc); - SetThisVar(thisVar); - - return argcChecker(); -} - -bool NFuncArg::InitArgs(size_t argc) -{ - return InitArgs([argc, this]() { - size_t realArgc = GetArgc(); - if (argc != realArgc) { - HILOGE("Num of args recved eq %zu while expecting %{public}zu", realArgc, argc); - return false; - } - return true; - }); -} - -bool NFuncArg::InitArgs(size_t minArgc, size_t maxArgc) -{ - return InitArgs([minArgc, maxArgc, this]() { - size_t realArgc = GetArgc(); - if (minArgc > realArgc || maxArgc < realArgc) { - HILOGE("Num of args recved eq %zu while expecting %{public}zu ~ %{public}zu", realArgc, minArgc, maxArgc); - return false; - } - return true; - }); -} -} // namespace DistributedFS -} // namespace OHOS diff --git a/interfaces/kits/js/src/common/napi/n_func_arg.h b/interfaces/kits/js/src/common/napi/n_func_arg.h deleted file mode 100644 index 490bada..0000000 --- a/interfaces/kits/js/src/common/napi/n_func_arg.h +++ /dev/null @@ -1,71 +0,0 @@ -/* - * Copyright (c) 2021 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#ifndef INTERFACES_KITS_NAPI_COMMON_NAPI_N_FUNC_ARG_H -#define INTERFACES_KITS_NAPI_COMMON_NAPI_N_FUNC_ARG_H - -#include -#include - -#include "node_api.h" -#include "js_native_api_types.h" - -namespace OHOS { -namespace DistributedFS { -enum NARG_CNT { - ZERO = 0, - ONE = 1, - TWO = 2, - THREE = 3, - FOUR = 4, -}; - -enum NARG_POS { - FIRST = 0, - SECOND = 1, - THIRD = 2, - FOURTH = 3, -}; - -class NFuncArg final { -public: - NFuncArg(napi_env env, napi_callback_info info); - virtual ~NFuncArg(); - - bool InitArgs(size_t argc); - bool InitArgs(size_t minArgc, size_t maxArgc); - - size_t GetArgc() const; - napi_value GetThisVar() const; - - napi_value operator[](size_t idx) const; - napi_value GetArg(size_t argPos) const; - -private: - napi_env env_ = nullptr; - napi_callback_info info_ = nullptr; - - size_t argc_ = 0; - std::unique_ptr argv_ = { nullptr }; - napi_value thisVar_ = nullptr; - - bool InitArgs(std::function argcChecker); - - void SetArgc(size_t argc); - void SetThisVar(napi_value thisVar); -}; -} // namespace DistributedFS -} // namespace OHOS -#endif \ No newline at end of file diff --git a/interfaces/kits/js/src/common/napi/n_val.cpp b/interfaces/kits/js/src/common/napi/n_val.cpp deleted file mode 100644 index d1f6dfe..0000000 --- a/interfaces/kits/js/src/common/napi/n_val.cpp +++ /dev/null @@ -1,348 +0,0 @@ -/* - * Copyright (c) 2021-2022 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#include "n_val.h" - -#include -#include - -#include "../log.h" -#include "js_native_api.h" - -namespace OHOS { -namespace DistributedFS { -using namespace std; - -NVal::NVal(napi_env nEnv, napi_value nVal = nullptr) : env_(nEnv), val_(nVal) {} - -NVal::operator bool() const -{ - return env_ && val_; -} - -bool NVal::TypeIs(napi_valuetype expType) const -{ - if (!*this) { - return false; - } - napi_valuetype valueType; - napi_typeof(env_, val_, &valueType); - - if (expType != valueType) { - return false; - } - return true; -} - -bool NVal::TypeIsError(bool checkErrno) const -{ - if (!*this) { - return false; - } - - bool res = false; - napi_is_error(env_, val_, &res); - - return res; -} - -tuple, size_t> NVal::ToUTF8String() const -{ - size_t strLen = 0; - napi_status status = napi_get_value_string_utf8(env_, val_, nullptr, -1, &strLen); - if (status != napi_ok) { - return { false, nullptr, 0 }; - } - - size_t bufLen = strLen + 1; - unique_ptr str = make_unique(bufLen); - status = napi_get_value_string_utf8(env_, val_, str.get(), bufLen, &strLen); - return make_tuple(status == napi_ok, move(str), strLen); -} - -tuple, size_t> NVal::ToUTF16String() const -{ -#ifdef FILE_SUBSYSTEM_DEBUG_LOCAL - size_t strLen = 0; - napi_status status = napi_get_value_string_utf16(env_, val_, nullptr, -1, &strLen); - if (status != napi_ok) { - return { false, nullptr, 0 }; - } - - auto str = make_unique(++strLen); - status = napi_get_value_string_utf16(env_, val_, str.get(), strLen, nullptr); - if (status != napi_ok) { - return { false, nullptr, 0 }; - } - - strLen = reinterpret_cast(str.get() + strLen) - reinterpret_cast(str.get()); - auto strRet = unique_ptr(reinterpret_cast(str.release())); - return { true, move(strRet), strLen }; -#else - // Note that quickjs doesn't support utf16 - return ToUTF8String(); -#endif -} - -tuple NVal::ToPointer() const -{ - void *res = nullptr; - napi_status status = napi_get_value_external(env_, val_, &res); - return make_tuple(status == napi_ok, res); -} - -tuple NVal::ToBool() const -{ - bool flag = false; - napi_status status = napi_get_value_bool(env_, val_, &flag); - return make_tuple(status == napi_ok, flag); -} - -tuple NVal::ToInt32() const -{ - int32_t res = 0; - napi_status status = napi_get_value_int32(env_, val_, &res); - return make_tuple(status == napi_ok, res); -} - -tuple NVal::ToInt64() const -{ - int64_t res = 0; - napi_status status = napi_get_value_int64(env_, val_, &res); - return make_tuple(status == napi_ok, res); -} - -tuple NVal::ToDouble() const -{ - double res = 0; - napi_status status = napi_get_value_double(env_, val_, &res); - return make_tuple(status == napi_ok, res); -} - -tuple NVal::ToUint64() const -{ - uint64_t res = 0; - bool lossless = false; - napi_status status = napi_get_value_bigint_uint64(env_, val_, &res, &lossless); - return make_tuple(status == napi_ok, res, lossless); -} - -tuple, uint32_t> NVal::ToStringArray() -{ - napi_status status; - uint32_t size; - status = napi_get_array_length(env_, val_, &size); - vector stringArray; - napi_value result; - for (uint32_t i = 0; i < size; i++) { - status = napi_get_element(env_, val_, i, &result); - auto [succ, str, ignore] = NVal(env_, result).ToUTF8String(); - stringArray.push_back(string(str.get())); - } - return make_tuple(status == napi_ok, stringArray, size); -} - -tuple NVal::ToArraybuffer() const -{ - void *buf = nullptr; - size_t bufLen = 0; - bool status = napi_get_arraybuffer_info(env_, val_, &buf, &bufLen); - return make_tuple(status == napi_ok, buf, bufLen); -} - -tuple NVal::ToTypedArray() const -{ - napi_typedarray_type type; - napi_value in_array_buffer = nullptr; - size_t byte_offset; - size_t length; - void *data = nullptr; - napi_status status = - napi_get_typedarray_info(env_, val_, &type, &length, (void **)&data, &in_array_buffer, &byte_offset); - return make_tuple(status == napi_ok, data, length); -} - -bool NVal::HasProp(string propName) const -{ - bool res = false; - - if (!env_ || !val_ || !TypeIs(napi_object)) - return false; - napi_status status = napi_has_named_property(env_, val_, propName.c_str(), &res); - return (status == napi_ok) && res; -} - -NVal NVal::GetProp(string propName) const -{ - if (!HasProp(propName)) { - return { env_, nullptr }; - } - napi_value prop = nullptr; - napi_status status = napi_get_named_property(env_, val_, propName.c_str(), &prop); - if (status != napi_ok) { - return { env_, nullptr }; - } - return NVal(env_, prop); -} - -bool NVal::AddProp(vector &&propVec) const -{ - if (!TypeIs(napi_valuetype::napi_object)) { - HILOGE("INNER BUG. Prop should only be added to objects"); - return false; - } - napi_status status = napi_define_properties(env_, val_, propVec.size(), propVec.data()); - if (status != napi_ok) { - HILOGE("INNER BUG. Cannot define properties because of %{public}d", status); - return false; - } - return true; -} - -bool NVal::AddProp(string propName, napi_value val) const -{ - if (!TypeIs(napi_valuetype::napi_object) || HasProp(propName)) { - HILOGE("INNER BUG. Prop should only be added to objects"); - return false; - } - - napi_status status = napi_set_named_property(env_, val_, propName.c_str(), val); - if (status != napi_ok) { - HILOGE("INNER BUG. Cannot set named property because of %{public}d", status); - return false; - } - return true; -} - -NVal NVal::CreateUndefined(napi_env env) -{ - napi_value res = nullptr; - napi_get_undefined(env, &res); - return { env, res }; -} - -NVal NVal::CreateInt64(napi_env env, int64_t val) -{ - napi_value res = nullptr; - napi_create_int64(env, val, &res); - return { env, res }; -} - -NVal NVal::CreateInt32(napi_env env, int32_t val) -{ - napi_value res = nullptr; - napi_create_int32(env, val, &res); - return { env, res }; -} - -NVal NVal::CreateObject(napi_env env) -{ - napi_value res = nullptr; - napi_create_object(env, &res); - return { env, res }; -} - -NVal NVal::CreateBool(napi_env env, bool val) -{ - napi_value res = nullptr; - napi_get_boolean(env, val, &res); - return { env, res }; -} - -NVal NVal::CreateUTF8String(napi_env env, std::string str) -{ - napi_value res = nullptr; - napi_create_string_utf8(env, str.c_str(), str.length(), &res); - return { env, res }; -} - -NVal NVal::CreateUTF8String(napi_env env, const char* str, ssize_t len) -{ - napi_value res = nullptr; - napi_create_string_utf8(env, str, len, &res); - return { env, res }; -} - -NVal NVal::CreateUint8Array(napi_env env, void *buf, size_t bufLen) -{ - napi_value output_buffer = nullptr; - napi_create_external_arraybuffer( - env, - buf, - bufLen, - [](napi_env env, void *finalize_data, void *finalize_hint) { free(finalize_data); }, - NULL, - &output_buffer); - napi_value output_array = nullptr; - napi_create_typedarray(env, napi_uint8_array, bufLen, output_buffer, 0, &output_array); - return { env, output_array }; -} - -NVal NVal::CreateArrayString(napi_env env, vector strs) -{ - napi_value res = nullptr; - napi_create_array(env, &res); - for (size_t i = 0; i < strs.size(); i++) { - napi_value filename; - napi_create_string_utf8(env, strs[i].c_str(), strs[i].length(), &filename); - napi_set_element(env, res, i, filename); - } - return {env, res}; -} - -tuple NVal::CreateArrayBuffer(napi_env env, size_t len) -{ - napi_value val; - void *buf = nullptr; - napi_create_arraybuffer(env, len, &buf, &val); - return { { env, val }, { buf } }; -} - -napi_property_descriptor NVal::DeclareNapiProperty(const char *name, napi_value val) -{ - return { (name), nullptr, nullptr, nullptr, nullptr, val, napi_default, nullptr }; -} - -napi_property_descriptor NVal::DeclareNapiStaticProperty(const char *name, napi_value val) -{ - return { (name), nullptr, nullptr, nullptr, nullptr, val, napi_static, nullptr }; -} - -napi_property_descriptor NVal::DeclareNapiFunction(const char *name, napi_callback func) -{ - return { (name), nullptr, (func), nullptr, nullptr, nullptr, napi_default, nullptr }; -} - -napi_property_descriptor NVal::DeclareNapiStaticFunction(const char *name, napi_callback func) -{ - return { (name), nullptr, (func), nullptr, nullptr, nullptr, napi_static, nullptr }; -} - -napi_property_descriptor NVal::DeclareNapiGetter(const char *name, napi_callback getter) -{ - return { (name), nullptr, nullptr, (getter), nullptr, nullptr, napi_default, nullptr }; -} - -napi_property_descriptor NVal::DeclareNapiSetter(const char *name, napi_callback setter) -{ - return { (name), nullptr, nullptr, nullptr, (setter), nullptr, napi_default, nullptr }; -} - -napi_property_descriptor NVal::DeclareNapiGetterSetter(const char *name, napi_callback getter, napi_callback setter) -{ - return { (name), nullptr, nullptr, (getter), (setter), nullptr, napi_default, nullptr }; -} -} // namespace DistributedFS -} // namespace OHOS \ No newline at end of file diff --git a/interfaces/kits/js/src/common/napi/n_val.h b/interfaces/kits/js/src/common/napi/n_val.h deleted file mode 100644 index 19d015c..0000000 --- a/interfaces/kits/js/src/common/napi/n_val.h +++ /dev/null @@ -1,89 +0,0 @@ -/* - * Copyright (c) 2021-2022 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#ifndef N_VAL_H -#define N_VAL_H - -#include -#include -#include -#include - -#include "node_api.h" -#include "js_native_api_types.h" -#include "napi/native_node_api.h" - -namespace OHOS { -namespace DistributedFS { -class NVal final { -public: - NVal() = default; - NVal(napi_env nEnv, napi_value nVal); - NVal(const NVal &) = default; - NVal &operator = (const NVal &) = default; - virtual ~NVal() = default; - - // NOTE! env_ and val_ is LIKELY to be null - napi_env env_ = nullptr; - napi_value val_ = nullptr; - - explicit operator bool() const; - bool TypeIs(napi_valuetype expType) const; - bool TypeIsError(bool checkErrno = false) const; - - /* SHOULD ONLY BE USED FOR EXPECTED TYPE */ - std::tuple, size_t> ToUTF8String() const; - std::tuple, size_t> ToUTF16String() const; - std::tuple ToPointer() const; - std::tuple ToBool() const; - std::tuple ToInt32() const; - std::tuple ToInt64() const; - std::tuple ToArraybuffer() const; - std::tuple ToTypedArray() const; - std::tuple, uint32_t> ToStringArray(); - std::tuple ToUint64() const; - std::tuple ToDouble() const; - - /* Static helpers to create js objects */ - static NVal CreateUndefined(napi_env env); - static NVal CreateInt64(napi_env env, int64_t val); - static NVal CreateInt32(napi_env env, int32_t val); - static NVal CreateObject(napi_env env); - static NVal CreateBool(napi_env env, bool val); - static NVal CreateUTF8String(napi_env env, std::string str); - static NVal CreateUTF8String(napi_env env, const char* str, ssize_t len); - static NVal CreateUint8Array(napi_env env, void *buf, size_t bufLen); - static NVal CreateArrayString(napi_env env, std::vector strs); - static std::tuple CreateArrayBuffer(napi_env env, size_t len); - /* SHOULD ONLY BE USED FOR OBJECT */ - bool HasProp(std::string propName) const; - NVal GetProp(std::string propName) const; - bool AddProp(std::vector &&propVec) const; - bool AddProp(std::string propName, napi_value nVal) const; - - /* Static helpers to create prop of js objects */ - static napi_property_descriptor DeclareNapiProperty(const char *name, napi_value val); - static napi_property_descriptor DeclareNapiStaticProperty(const char *name, napi_value val); - static napi_property_descriptor DeclareNapiFunction(const char *name, napi_callback func); - static napi_property_descriptor DeclareNapiStaticFunction(const char *name, napi_callback func); - static napi_property_descriptor DeclareNapiGetter(const char *name, napi_callback getter); - static napi_property_descriptor DeclareNapiSetter(const char *name, napi_callback setter); - static inline napi_property_descriptor DeclareNapiGetterSetter(const char *name, - napi_callback getter, - napi_callback setter); -}; -} // namespace DistributedFS -} // namespace OHOS -#endif // N_VAL_H \ No newline at end of file diff --git a/interfaces/kits/js/src/common/napi/uni_header.h b/interfaces/kits/js/src/common/napi/uni_header.h deleted file mode 100644 index 0816211..0000000 --- a/interfaces/kits/js/src/common/napi/uni_header.h +++ /dev/null @@ -1,25 +0,0 @@ -/* - * Copyright (c) 2021 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#ifndef N_UNI_HEADER_H -#define N_UNI_HEADER_H - -#ifdef FILE_SUBSYSTEM_DEBUG_LOCAL -#include -#else -#include "napi/native_api.h" -#include "napi/native_node_api.h" -#endif -#endif \ No newline at end of file diff --git a/interfaces/kits/js/src/common/uni_error.cpp b/interfaces/kits/js/src/common/uni_error.cpp deleted file mode 100644 index 8be97a7..0000000 --- a/interfaces/kits/js/src/common/uni_error.cpp +++ /dev/null @@ -1,123 +0,0 @@ -/* - * Copyright (c) 2021-2022 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#include "uni_error.h" - -#include -#include - -#include "js_native_api.h" -#include "log.h" -#include "napi/n_val.h" - -namespace OHOS { -namespace DistributedFS { -using namespace std; - -UniError::UniError() {} - -UniError::UniError(ELegacy eLegacy) : errno_(eLegacy), codingSystem_(ERR_CODE_SYSTEM_LEGACY) {} - -UniError::UniError(int ePosix) : errno_(ePosix), codingSystem_(ERR_CODE_SYSTEM_POSIX) {} - -UniError::operator bool() const -{ - return errno_ != ERRNO_NOERR; -} - -int UniError::GetErrno(ErrCodeSystem cs) -{ - if (errno_ == ERRNO_NOERR) { - return ERRNO_NOERR; - } - if (cs == codingSystem_) { - return errno_; - } - - if (cs == ERR_CODE_SYSTEM_POSIX) { - // Note that we should support more codes here - return EINVAL; - } - - // Note that this shall be done properly - return ELEGACY_INVAL; -} - -void UniError::SetErrno(ELegacy eLegacy) -{ - errno_ = eLegacy; - codingSystem_ = ERR_CODE_SYSTEM_LEGACY; -} - -void UniError::SetErrno(int ePosix) -{ - errno_ = ePosix; - codingSystem_ = ERR_CODE_SYSTEM_POSIX; -} - -std::string UniError::GetDefaultErrstr() -{ - if (codingSystem_ != ERR_CODE_SYSTEM_POSIX && codingSystem_ != ERR_CODE_SYSTEM_LEGACY) { - return "BUG: Curious coding system"; - } - return strerror(GetErrno(ERR_CODE_SYSTEM_POSIX)); -} - -napi_value UniError::GetNapiErr(napi_env env) -{ - return GetNapiErr(env, GetDefaultErrstr()); -} - -napi_value UniError::GetNapiErr(napi_env env, string errMsg) -{ - int errCode = GetErrno(codingSystem_); - if (errCode == ERRNO_NOERR) { - return nullptr; - } - napi_value code = NVal::CreateUTF8String(env, to_string(errCode)).val_; - napi_value msg = NVal::CreateUTF8String(env, errMsg).val_; - - napi_value res = nullptr; - napi_status createRes = napi_create_error(env, code, msg, &res); - if (createRes) { - HILOGE("Failed to create an exception, msg = %{public}s", errMsg.c_str()); - } - return res; -} - -void UniError::ThrowErr(napi_env env) -{ - string msg = GetDefaultErrstr(); - napi_value tmp = nullptr; - napi_get_and_clear_last_exception(env, &tmp); - // Note that ace engine cannot throw errors created by napi_create_error so far - napi_status throwStatus = napi_throw_error(env, nullptr, msg.c_str()); - if (throwStatus != napi_ok) { - HILOGE("Failed to throw an exception, %{public}d, code = %{public}s", throwStatus, msg.c_str()); - } -} - -void UniError::ThrowErr(napi_env env, string errMsg) -{ - napi_value tmp = nullptr; - napi_get_and_clear_last_exception(env, &tmp); - // Note that ace engine cannot throw errors created by napi_create_error so far - napi_status throwStatus = napi_throw_error(env, nullptr, errMsg.c_str()); - if (throwStatus != napi_ok) { - HILOGE("Failed to throw an exception, %{public}d, code = %{public}s", throwStatus, errMsg.c_str()); - } -} -} // namespace DistributedFS -} // namespace OHOS \ No newline at end of file diff --git a/interfaces/kits/js/src/common/uni_error.h b/interfaces/kits/js/src/common/uni_error.h deleted file mode 100644 index 5371300..0000000 --- a/interfaces/kits/js/src/common/uni_error.h +++ /dev/null @@ -1,67 +0,0 @@ -/* - * Copyright (c) 2021 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#ifndef INTERFACES_KITS_NAPI_COMMON_UNI_ERROR_H -#define INTERFACES_KITS_NAPI_COMMON_UNI_ERROR_H - -#include - -#include "node_api.h" -#include "js_native_api_types.h" - -namespace OHOS { -namespace DistributedFS { -constexpr int ERRNO_NOERR = 0; - -enum ELegacy { - ELEGACY_INVAL = 202, - ELEGACY_IO = 300, - ELEGACY_NOENT = 301, -}; - -enum ErrCodeSystem { - ERR_CODE_SYSTEM_LEGACY, - ERR_CODE_SYSTEM_POSIX, -}; - -class UniError { -public: - UniError(); - explicit UniError(ELegacy eLegacy); - explicit UniError(int ePosix); - UniError(const UniError &) = default; - ~UniError() = default; - - UniError &operator = (const UniError &) = default; - - explicit operator bool() const; - - void SetErrno(ELegacy eLegacy); - void SetErrno(int ePosix); - int GetErrno(ErrCodeSystem cs); - - std::string GetDefaultErrstr(); - napi_value GetNapiErr(napi_env env); - napi_value GetNapiErr(napi_env env, std::string errMsg); - void ThrowErr(napi_env env); - void ThrowErr(napi_env env, std::string errMsg); - -private: - int errno_ = ERRNO_NOERR; - ErrCodeSystem codingSystem_ = ERR_CODE_SYSTEM_POSIX; -}; -} // namespace DistributedFS -} // namespace OHOS -#endif \ No newline at end of file diff --git a/interfaces/kits/js/src/mod_document/document_n_exporter.cpp b/interfaces/kits/js/src/mod_document/document_n_exporter.cpp deleted file mode 100644 index f8bd903..0000000 --- a/interfaces/kits/js/src/mod_document/document_n_exporter.cpp +++ /dev/null @@ -1,39 +0,0 @@ -/* - * Copyright (c) 2021 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#include "document_n_exporter.h" - -#include - -#include "../common/uni_error.h" -#include "napi/native_node_api.h" - -namespace OHOS { -namespace DistributedFS { -namespace ModuleDocument { -napi_value Choose(napi_env env, napi_callback_info info) -{ - UniError(EINVAL).ThrowErr(env, "error"); - return nullptr; -} - -napi_value Show(napi_env env, napi_callback_info info) -{ - UniError(EINVAL).ThrowErr(env, "error"); - return nullptr; -} -} // namespace ModuleDocument -} // namespace DistributedFS -} // namespace OHOS \ No newline at end of file diff --git a/interfaces/kits/js/src/mod_document/document_n_exporter.h b/interfaces/kits/js/src/mod_document/document_n_exporter.h deleted file mode 100644 index 19ba62d..0000000 --- a/interfaces/kits/js/src/mod_document/document_n_exporter.h +++ /dev/null @@ -1,30 +0,0 @@ -/* - * Copyright (c) 2021 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#ifndef DOCUMENT_N_EXPORTER_H -#define DOCUMENT_N_EXPORTER_H - -#include "node_api.h" -#include "js_native_api_types.h" - -namespace OHOS { -namespace DistributedFS { -namespace ModuleDocument { -napi_value Choose(napi_env env, napi_callback_info info); -napi_value Show(napi_env env, napi_callback_info info); -} // namespace ModuleDocument -} // namespace DistributedFS -} // namespace OHOS -#endif // DOCUMENT_N_EXPORTER_H \ No newline at end of file diff --git a/interfaces/kits/js/src/mod_document/document_napi.cpp b/interfaces/kits/js/src/mod_document/document_napi.cpp deleted file mode 100644 index 91289a9..0000000 --- a/interfaces/kits/js/src/mod_document/document_napi.cpp +++ /dev/null @@ -1,44 +0,0 @@ -/* - * Copyright (c) 2021 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#include "document_napi.h" - -#include "document_n_exporter.h" -#include "js_native_api.h" -#include "js_native_api_types.h" -#include "napi/native_api.h" -#include "napi/native_common.h" -#include "node_api.h" - -namespace OHOS { -namespace DistributedFS { -namespace ModuleDocument { -/*********************************************** - * Module export and register - ***********************************************/ -napi_value DocumentExport(napi_env env, napi_value exports) -{ - static napi_property_descriptor desc[] = { - DECLARE_NAPI_FUNCTION("choose", Choose), - DECLARE_NAPI_FUNCTION("show", Show), - }; - NAPI_CALL(env, napi_define_properties(env, exports, sizeof(desc) / sizeof(desc[0]), desc)); - return exports; -} - -NAPI_MODULE(document, DocumentExport) -} // namespace ModuleDocument -} // namespace DistributedFS -} // namespace OHOS \ No newline at end of file diff --git a/interfaces/kits/js/src/mod_document/document_napi.h b/interfaces/kits/js/src/mod_document/document_napi.h deleted file mode 100644 index 80cdd7c..0000000 --- a/interfaces/kits/js/src/mod_document/document_napi.h +++ /dev/null @@ -1,27 +0,0 @@ -/* - * Copyright (c) 2021 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#ifndef DOCUMENT_NAPI_H -#define DOCUMENT_NAPI_H - -#include "napi/native_api.h" - -namespace OHOS { -namespace DistributedFS { -namespace ModuleDocument { -} // namespace ModuleDocument -} // namespace DistributedFS -} // namespace OHOS -#endif // DOCUMENT_NAPI_H \ No newline at end of file diff --git a/interfaces/kits/js/src/mod_environment/environment_n_exporter.cpp b/interfaces/kits/js/src/mod_environment/environment_n_exporter.cpp deleted file mode 100644 index a702f8b..0000000 --- a/interfaces/kits/js/src/mod_environment/environment_n_exporter.cpp +++ /dev/null @@ -1,101 +0,0 @@ -/* - * Copyright (c) 2021 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#include "environment_n_exporter.h" - -#include - -#include "../common/napi/n_class.h" -#include "../common/napi/n_func_arg.h" -#include "../common/napi/n_val.h" -#include "../common/uni_error.h" - -#include "../common/napi/n_async/n_async_work_callback.h" -#include "../common/napi/n_async/n_async_work_promise.h" - -namespace OHOS { -namespace DistributedFS { -namespace ModuleEnvironment { -namespace { - const std::string STORAGE_DATA_PATH = "/data"; - const std::string USER_DATA_PATH = "/data/storage/0"; -} -napi_value GetStorageDataDir(napi_env env, napi_callback_info info) -{ - NFuncArg funcArg(env, info); - if (!funcArg.InitArgs(NARG_CNT::ZERO, NARG_CNT::ONE)) { - UniError(EINVAL).ThrowErr(env, "Number of arguments unmatched"); - return nullptr; - } - - auto cbExec = [](napi_env env) -> UniError { - return UniError(ERRNO_NOERR); - }; - auto cbComplete = [](napi_env env, UniError err) -> NVal { - if (err) { - return { env, err.GetNapiErr(env) }; - } - return NVal::CreateUTF8String(env, STORAGE_DATA_PATH); - }; - - std::string procedureName = "GetStorageDataDir"; - NVal thisVar(env, funcArg.GetThisVar()); - if (funcArg.GetArgc() == NARG_CNT::ZERO) { - return NAsyncWorkPromise(env, thisVar).Schedule(procedureName, cbExec, cbComplete).val_; - } else { - NVal cb(env, funcArg[NARG_POS::FIRST]); - return NAsyncWorkCallback(env, thisVar, cb).Schedule(procedureName, cbExec, cbComplete).val_; - } - return NVal::CreateUndefined(env).val_; -} - -int GetUserId() -{ - return 0; -} - -napi_value GetUserDataDir(napi_env env, napi_callback_info info) -{ - NFuncArg funcArg(env, info); - if (!funcArg.InitArgs(NARG_CNT::ZERO, NARG_CNT::ONE)) { - UniError(EINVAL).ThrowErr(env, "Number of arguments unmatched"); - return nullptr; - } - - auto userDataPath = std::make_shared(); - auto cbExec = [userDataPath](napi_env env) -> UniError { - (*userDataPath).append("/storage/media/").append(std::to_string(GetUserId())).append("/local"); - return UniError(ERRNO_NOERR); - }; - auto cbComplete = [userDataPath](napi_env env, UniError err) -> NVal { - if (err) { - return { env, err.GetNapiErr(env) }; - } - return NVal::CreateUTF8String(env, *userDataPath); - }; - - std::string procedureName = "GetUserDataDir"; - NVal thisVar(env, funcArg.GetThisVar()); - if (funcArg.GetArgc() == NARG_CNT::ZERO) { - return NAsyncWorkPromise(env, thisVar).Schedule(procedureName, cbExec, cbComplete).val_; - } else { - NVal cb(env, funcArg[NARG_POS::FIRST]); - return NAsyncWorkCallback(env, thisVar, cb).Schedule(procedureName, cbExec, cbComplete).val_; - } - return NVal::CreateUndefined(env).val_; -} -} // namespace ModuleEnvironment -} // namespace DistributedFS -} // namespace OHOS \ No newline at end of file diff --git a/interfaces/kits/js/src/mod_environment/environment_n_exporter.h b/interfaces/kits/js/src/mod_environment/environment_n_exporter.h deleted file mode 100644 index 1b46a7b..0000000 --- a/interfaces/kits/js/src/mod_environment/environment_n_exporter.h +++ /dev/null @@ -1,29 +0,0 @@ -/* - * Copyright (c) 2021 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#ifndef ENVIRONMENT_N_EXPORTER_H -#define ENVIRONMENT_N_EXPORTER_H - -#include "../common/napi/n_exporter.h" - -namespace OHOS { -namespace DistributedFS { -namespace ModuleEnvironment { -napi_value GetStorageDataDir(napi_env env, napi_callback_info info); -napi_value GetUserDataDir(napi_env env, napi_callback_info info); -} // namespace ModuleEnvironment -} // namespace DistributedFS -} // namespace OHOS -#endif // ENVIRONMENT_N_EXPORTER_H \ No newline at end of file diff --git a/interfaces/kits/js/src/mod_environment/environment_napi.cpp b/interfaces/kits/js/src/mod_environment/environment_napi.cpp deleted file mode 100644 index 5a58805..0000000 --- a/interfaces/kits/js/src/mod_environment/environment_napi.cpp +++ /dev/null @@ -1,43 +0,0 @@ -/* - * Copyright (c) 2021 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#include "environment_napi.h" - -#include "environment_n_exporter.h" -#include "js_native_api.h" -#include "js_native_api_types.h" -#include "napi/native_common.h" -#include "node_api.h" - -namespace OHOS { -namespace DistributedFS { -namespace ModuleEnvironment { -/*********************************************** - * Module export and register - ***********************************************/ -napi_value EnvironmentExport(napi_env env, napi_value exports) -{ - static napi_property_descriptor desc[] = { - DECLARE_NAPI_FUNCTION("getStorageDataDir", GetStorageDataDir), - DECLARE_NAPI_FUNCTION("getUserDataDir", GetUserDataDir), - }; - NAPI_CALL(env, napi_define_properties(env, exports, sizeof(desc) / sizeof(desc[0]), desc)); - return exports; -} - -NAPI_MODULE(environment, EnvironmentExport) -} // namespace ModuleEnvironment -} // namespace DistributedFS -} // namespace OHOS \ No newline at end of file diff --git a/interfaces/kits/js/src/mod_environment/environment_napi.h b/interfaces/kits/js/src/mod_environment/environment_napi.h deleted file mode 100644 index 788a237..0000000 --- a/interfaces/kits/js/src/mod_environment/environment_napi.h +++ /dev/null @@ -1,25 +0,0 @@ -/* - * Copyright (c) 2021 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#ifndef ENVIRONMENT_NAPI_H -#define ENVIRONMENT_NAPI_H - -namespace OHOS { -namespace DistributedFS { -namespace ModuleEnvironment { -} // namespace ModuleEnvironment -} // namespace DistributedFS -} // namespace OHOS -#endif // ENVIRONMENT_NAPI_H \ No newline at end of file diff --git a/interfaces/kits/js/src/mod_file/class_file/file_n_exporter.cpp b/interfaces/kits/js/src/mod_file/class_file/file_n_exporter.cpp deleted file mode 100644 index 3453650..0000000 --- a/interfaces/kits/js/src/mod_file/class_file/file_n_exporter.cpp +++ /dev/null @@ -1,1443 +0,0 @@ -/* - * Copyright (c) 2021 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#include "file_n_exporter.h" - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -#include "../../common/ability_helper.h" -#include "../../common/file_helper/fd_guard.h" -#include "../../common/napi/n_class.h" -#include "../../common/napi/n_func_arg.h" -#include "../../common/napi/n_val.h" -#include "../../common/uni_error.h" -#include "../common_func.h" - -namespace OHOS { -namespace DistributedFS { -namespace ModuleFile { -using namespace std; - -constexpr int SUCCESS = 0; -constexpr int FAILED = -1; -constexpr int URI_PARAMER_ERROR = 202; -constexpr int FILE_IO_ERROR = 300; -constexpr int FILE_PATH_ERROR = 301; -constexpr int DIR_FAULT_PERM = 0775; -constexpr int SPLITE_ZERO = 0; -const string TYPE_FILE = "file"; -const string TYPE_DIR = "dir"; -const string ENCODING_UTF8 = "utf-8"; - -void CallBackSuccess(napi_env env, napi_ref successFuncRef, int32_t count, napi_value obj) -{ - napi_value results = nullptr; - napi_value successFunc = nullptr; - napi_value global = nullptr; - napi_get_global(env, &global); - napi_get_reference_value(env, successFuncRef, &successFunc); - if (successFunc == nullptr) { - return; - } - napi_call_function(env, global, successFunc, count, &obj, &results); -} - -void CallBackError(napi_env env, napi_ref failFuncRef, string errorProp, int errorCode) -{ - napi_value argvFail[2] = { 0 }; - napi_value results = nullptr; - napi_value failFunc = nullptr; - napi_value global = nullptr; - napi_get_global(env, &global); - argvFail[0] = NVal::CreateUTF8String(env, errorProp).val_; - argvFail[1] = NVal::CreateInt32(env, errorCode).val_; - napi_get_reference_value(env, failFuncRef, &failFunc); - if (failFunc == nullptr) { - return; - } - napi_call_function(env, global, failFunc, COMMON_NUM::TWO, argvFail, &results); -} - -void CallComplete(napi_env env, napi_ref completeFuncRef) -{ - napi_value completeFunc = nullptr; - napi_value results = nullptr; - napi_value global = nullptr; - napi_get_global(env, &global); - napi_get_reference_value(env, completeFuncRef, &completeFunc); - if (completeFunc == nullptr) { - return; - } - napi_call_function(env, global, completeFunc, COMMON_NUM::ZERO, nullptr, &results); -} - -bool CheckUri(napi_env env, string &path) -{ - constexpr int spilteOne = 1; - constexpr int spilteTwo = 2; - constexpr int spilteThree = 3; - string pathOrigin = path; - vector uriSplit; - string pattern = "/"; - if (path == "") { - return false; - } - string pathTmp = pathOrigin + pattern; - size_t pos = pathTmp.find(pattern); - while (pos != pathTmp.npos) { - string temp = pathTmp.substr(SPLITE_ZERO, pos); - uriSplit.push_back(temp); - pathTmp = pathTmp.substr(pos + 1, pathTmp.size()); - pos = pathTmp.find(pattern); - } - if (uriSplit[SPLITE_ZERO] != "internal:" || uriSplit[spilteOne] != "" || uriSplit.size() <= spilteThree) { - return false; - } - AppExecFwk::Ability *ability = AbilityHelper::GetJsAbility(env); - if (!ability) { - return false; - } - auto abilityContext = ability->GetAbilityContext(); - if (abilityContext && uriSplit[spilteTwo] == "app") { - path = abilityContext->GetFilesDir(); - } else if (abilityContext && uriSplit[spilteTwo] == "cache") { - path = abilityContext->GetCacheDir(); - } else { - return false; - } - for (size_t i = spilteThree; i < uriSplit.size(); ++i) { - path = path + "/" + uriSplit[i]; - } - return true; -} - -int GetRealPath(string &path) -{ - unique_ptr absPath = make_unique(PATH_MAX + 1); - if (realpath(path.c_str(), absPath.get()) == nullptr) { - return errno; - } - path = absPath.get(); - return 0; -} - -string UriToAbsolute(string path) -{ - stack uriResult; - vector uriSplit; - string pattern = "/"; - - string pathTmp = path + pattern; - size_t pos = pathTmp.find(pattern); - while (pos != pathTmp.npos) { - string temp = pathTmp.substr(SPLITE_ZERO, pos); - uriSplit.push_back(temp); - pathTmp = pathTmp.substr(pos + 1, pathTmp.size()); - pos = pathTmp.find(pattern); - } - for (auto urisp : uriSplit) { - if (urisp == "." || urisp == "") { - continue; - } else if (urisp == ".." && !uriResult.empty()) { - uriResult.pop(); - } else { - uriResult.push(urisp); - } - } - path = ""; - while (!uriResult.empty()) { - path = "/" + uriResult.top() + path; - uriResult.pop(); - } - return path; -} - -bool GetFileNames(string path, vector &filenames, bool rec, bool isList) -{ - DIR *pDir; - struct dirent *ptr = nullptr; - if (!(pDir = opendir(path.c_str()))) { - return false; - } - while ((ptr = readdir(pDir)) != nullptr) { - if (strcmp(ptr->d_name, ".") != 0 && strcmp(ptr->d_name, "..") != 0) { - if (isList) { - filenames.push_back(path + "/" + ptr->d_name); - } else if (ptr->d_type == DT_DIR && rec && - GetFileNames(path + "/" + ptr->d_name, filenames, rec, isList) == false) { - break; - } else if (ptr->d_type == DT_REG) { - filenames.push_back(path + "/" + ptr->d_name); - } - } - } - closedir(pDir); - return true; -} - -bool Mkdirs(string path) -{ - for (size_t i = 1; i < path.length(); ++i) { - if (path[i] == '/') { - path[i] = '\0'; - if (access(path.c_str(), 0) != 0 && mkdir(path.c_str(), DIR_FAULT_PERM) == FAILED) { - return false; - } - path[i] = '/'; - } - } - if (path.length() <= 0 || access(path.c_str(), 0) == 0 || mkdir(path.c_str(), DIR_FAULT_PERM) == FAILED) { - return false; - } - return true; -} - -bool Rmdirs(string path) -{ - DIR *pDir; - struct dirent *ptr = nullptr; - if (!(pDir = opendir(path.c_str()))) { - return false; - } - while ((ptr = readdir(pDir)) != nullptr) { - if (strcmp(ptr->d_name, ".") != 0 && strcmp(ptr->d_name, "..") != 0) { - if ((ptr->d_type == DT_DIR && Rmdirs(path + "/" + ptr->d_name)) || - remove((path + "/" + ptr->d_name).c_str()) == 0) { - } else { - closedir(pDir); - return false; - } - } - } - closedir(pDir); - if (rmdir(path.c_str()) != 0) { - return false; - } - return true; -} - -string ConvertUri(string path, string originPath, string originUri) -{ - if (path.find(originPath) != path.npos) { - if (originUri[originUri.length() - 1] == '/') { - originUri = originUri.substr(0, originUri.length() - 1); - } - path.replace(0, originPath.length(), originUri); - } else { - return "error"; - } - return path; -} - -void MkdirExec(napi_env env, void *data) -{ - auto *asyncCallbackInfo = (AsyncMkdirCallbackInfo *)data; - string path = asyncCallbackInfo->url; - asyncCallbackInfo->result = FAILED; - asyncCallbackInfo->errorType = FILE_IO_ERROR; - if (GetRealPath(path) == ENOENT) { - path = UriToAbsolute(path); - if (asyncCallbackInfo->recursive && Mkdirs(path)) { - asyncCallbackInfo->result = SUCCESS; - } else if (mkdir((char *)path.c_str(), DIR_FAULT_PERM) != FAILED) { - asyncCallbackInfo->result = SUCCESS; - } - } -} - -void MkdirComp(napi_env env, napi_status status, void *data) -{ - auto *asyncCallbackInfo = (AsyncMkdirCallbackInfo *)data; - - if (asyncCallbackInfo->result == SUCCESS) { - CallBackSuccess(env, asyncCallbackInfo->callback[COMMON_NUM::ZERO], COMMON_NUM::ZERO, nullptr); - } else if (asyncCallbackInfo->result == FAILED) { - CallBackError(env, asyncCallbackInfo->callback[COMMON_NUM::ONE], "make directory failed", FILE_IO_ERROR); - } - CallComplete(env, asyncCallbackInfo->callback[COMMON_NUM::TWO]); - napi_delete_reference(env, asyncCallbackInfo->callback[COMMON_NUM::ZERO]); - napi_delete_reference(env, asyncCallbackInfo->callback[COMMON_NUM::ONE]); - napi_delete_reference(env, asyncCallbackInfo->callback[COMMON_NUM::TWO]); - napi_delete_async_work(env, asyncCallbackInfo->asyncWork); - delete asyncCallbackInfo; -} - -void RmdirExec(napi_env env, void *data) -{ - auto *asyncCallbackInfo = (AsyncRmdirCallbackInfo *)data; - string path = asyncCallbackInfo->url; - asyncCallbackInfo->result = FAILED; - asyncCallbackInfo->errorType = FILE_IO_ERROR; - int statPath = GetRealPath(path); - if (statPath == COMMON_NUM::ZERO) { - if (asyncCallbackInfo->recursive && Rmdirs(path)) { - asyncCallbackInfo->result = SUCCESS; - } else if (remove((char *)path.c_str()) != FAILED) { - asyncCallbackInfo->result = SUCCESS; - } - } else if (statPath == ENOENT) { - asyncCallbackInfo->errorType = FILE_PATH_ERROR; - } -} - -void RmdirComp(napi_env env, napi_status status, void *data) -{ - auto *asyncCallbackInfo = (AsyncRmdirCallbackInfo *)data; - if (asyncCallbackInfo->result == SUCCESS) { - CallBackSuccess(env, asyncCallbackInfo->callback[COMMON_NUM::ZERO], COMMON_NUM::ZERO, nullptr); - } else if (asyncCallbackInfo->errorType == FILE_IO_ERROR) { - CallBackError(env, asyncCallbackInfo->callback[COMMON_NUM::ONE], "remove directory failed", FILE_IO_ERROR); - } else if (asyncCallbackInfo->errorType == FILE_PATH_ERROR) { - CallBackError(env, asyncCallbackInfo->callback[COMMON_NUM::ONE], "file not exist", FILE_PATH_ERROR); - } - CallComplete(env, asyncCallbackInfo->callback[COMMON_NUM::TWO]); - napi_delete_reference(env, asyncCallbackInfo->callback[COMMON_NUM::ZERO]); - napi_delete_reference(env, asyncCallbackInfo->callback[COMMON_NUM::ONE]); - napi_delete_reference(env, asyncCallbackInfo->callback[COMMON_NUM::TWO]); - napi_delete_async_work(env, asyncCallbackInfo->asyncWork); - delete asyncCallbackInfo; -} - -void GetExec(napi_env env, void *data) -{ - auto *asyncCallbackInfo = (AsyncGetCallbackInfo *)data; - string path = asyncCallbackInfo->url; - asyncCallbackInfo->result = FAILED; - asyncCallbackInfo->errorType = FILE_IO_ERROR; - struct stat buf; - int statPath = GetRealPath(path); - if (statPath == COMMON_NUM::ZERO && stat((char *)path.c_str(), &buf) == COMMON_NUM::ZERO) { - asyncCallbackInfo->length = buf.st_size; - asyncCallbackInfo->lastMT = buf.st_mtime * COMMON_NUM::THOUSAND + - (int64_t)((buf.st_mtim).tv_nsec / COMMON_NUM::MILLION); - asyncCallbackInfo->url = path; - std::vector subFiles; - bool rec = asyncCallbackInfo->recursive; - if ((buf.st_mode & S_IFMT) == S_IFDIR && GetFileNames(path, subFiles, rec, false)) { - (asyncCallbackInfo->subFiles).assign(subFiles.begin(), subFiles.end()); - asyncCallbackInfo->type = TYPE_DIR; - asyncCallbackInfo->result = SUCCESS; - } else if ((buf.st_mode & S_IFMT) == S_IFREG) { - asyncCallbackInfo->type = TYPE_FILE; - asyncCallbackInfo->result = SUCCESS; - } - } else if (statPath == ENOENT) { - asyncCallbackInfo->errorType = FILE_PATH_ERROR; - } -} - -void GetComp(napi_env env, napi_status status, void *data) -{ - auto *asyncCallbackInfo = (AsyncGetCallbackInfo *)data; - if (asyncCallbackInfo->result == SUCCESS) { - napi_value subFilesNapi = nullptr; - napi_create_array(env, &subFilesNapi); - int32_t i = 0; - for (auto filename : asyncCallbackInfo->subFiles) { - napi_set_property( - env, subFilesNapi, NVal::CreateInt32(env, i).val_, - NVal::CreateUTF8String( - env, ConvertUri(filename, asyncCallbackInfo->url, asyncCallbackInfo->originUri).c_str()) - .val_); - i = i + 1; - } - NVal objn = NVal::CreateObject(env); - objn.AddProp("lastModifiedTime", NVal::CreateInt64(env, asyncCallbackInfo->lastMT).val_); - objn.AddProp("length", NVal::CreateInt32(env, asyncCallbackInfo->length).val_); - objn.AddProp("uri", NVal::CreateUTF8String(env, asyncCallbackInfo->originUri).val_); - objn.AddProp("type", NVal::CreateUTF8String(env, asyncCallbackInfo->type).val_); - objn.AddProp("subFiles", subFilesNapi); - - CallBackSuccess(env, asyncCallbackInfo->callback[COMMON_NUM::ZERO], COMMON_NUM::ONE, objn.val_); - } else if (asyncCallbackInfo->errorType == FILE_PATH_ERROR) { - CallBackError(env, asyncCallbackInfo->callback[COMMON_NUM::ONE], "file not exist", FILE_PATH_ERROR); - } else if (asyncCallbackInfo->errorType == FILE_IO_ERROR) { - CallBackError(env, asyncCallbackInfo->callback[COMMON_NUM::ONE], "get file failed", FILE_IO_ERROR); - } - CallComplete(env, asyncCallbackInfo->callback[COMMON_NUM::TWO]); - napi_delete_reference(env, asyncCallbackInfo->callback[COMMON_NUM::ZERO]); - napi_delete_reference(env, asyncCallbackInfo->callback[COMMON_NUM::ONE]); - napi_delete_reference(env, asyncCallbackInfo->callback[COMMON_NUM::TWO]); - napi_delete_async_work(env, asyncCallbackInfo->asyncWork); - delete asyncCallbackInfo; -} - -void ListExec(napi_env env, void *data) -{ - auto *asyncCallbackInfo = (AsyncListCallbackInfo *)data; - string path = asyncCallbackInfo->url; - asyncCallbackInfo->result = FAILED; - std::vector fileNames; - struct stat buf; - int statPath = GetRealPath(path); - if (statPath == ENOENT) { - asyncCallbackInfo->errorType = FILE_PATH_ERROR; - } else if (statPath != COMMON_NUM::ZERO || stat((char *)path.c_str(), &buf) != COMMON_NUM::ZERO) { - asyncCallbackInfo->errorType = FILE_IO_ERROR; - } else if ((buf.st_mode & S_IFMT) == S_IFREG) { - asyncCallbackInfo->result = SUCCESS; - } else { - asyncCallbackInfo->url = path; - bool getStat = GetFileNames(path, fileNames, false, true); - if (!getStat) { - asyncCallbackInfo->errorType = FILE_IO_ERROR; - } else { - vector fileList; - for (auto ph : fileNames) { - struct stat tmp; - int r = stat(ph.c_str(), &tmp); - FileInfo fi; - if (r == 0 && S_ISDIR(tmp.st_mode)) { - fi.type = TYPE_DIR; - } else if (r == 0 && (tmp.st_mode & S_IFMT) == S_IFREG) { - fi.type = TYPE_FILE; - } - fi.length = tmp.st_size; - fi.lastModifiedTime = tmp.st_mtime * COMMON_NUM::THOUSAND + - (int64_t)((tmp.st_mtim).tv_nsec / COMMON_NUM::MILLION); - fi.uri = ph; - fileList.push_back(fi); - } - (asyncCallbackInfo->fileList).assign(fileList.begin(), fileList.end()); - asyncCallbackInfo->result = SUCCESS; - } - } -} - -void ListComp(napi_env env, napi_status status, void *data) -{ - auto *asyncCallbackInfo = (AsyncListCallbackInfo *)data; - if (asyncCallbackInfo->result == SUCCESS) { - napi_value fileListNapi; - napi_create_array(env, &fileListNapi); - int32_t i = 0; - for (auto fileInfo : asyncCallbackInfo->fileList) { - NVal objt = NVal::CreateObject(env); - objt.AddProp("lastModifiedTime", NVal::CreateInt64(env, fileInfo.lastModifiedTime).val_); - objt.AddProp("length", NVal::CreateInt32(env, fileInfo.length).val_); - string uriTojs = ConvertUri(fileInfo.uri, asyncCallbackInfo->url, asyncCallbackInfo->originUri); - objt.AddProp("uri", NVal::CreateUTF8String(env, uriTojs).val_); - objt.AddProp("type", NVal::CreateUTF8String(env, fileInfo.type).val_); - - napi_set_property(env, fileListNapi, NVal::CreateInt32(env, i).val_, objt.val_); - i = i + 1; - } - NVal objn = NVal::CreateObject(env); - objn.AddProp("fileList", fileListNapi); - CallBackSuccess(env, asyncCallbackInfo->callback[COMMON_NUM::ZERO], COMMON_NUM::ONE, objn.val_); - } else if (asyncCallbackInfo->errorType == FILE_PATH_ERROR) { - CallBackError(env, asyncCallbackInfo->callback[COMMON_NUM::ONE], "file not exist", FILE_PATH_ERROR); - } else if (asyncCallbackInfo->errorType == FILE_IO_ERROR) { - CallBackError(env, asyncCallbackInfo->callback[COMMON_NUM::ONE], "list file failed", FILE_IO_ERROR); - } - CallComplete(env, asyncCallbackInfo->callback[COMMON_NUM::TWO]); - napi_delete_reference(env, asyncCallbackInfo->callback[COMMON_NUM::ZERO]); - napi_delete_reference(env, asyncCallbackInfo->callback[COMMON_NUM::ONE]); - napi_delete_reference(env, asyncCallbackInfo->callback[COMMON_NUM::TWO]); - napi_delete_async_work(env, asyncCallbackInfo->asyncWork); - delete asyncCallbackInfo; -} - -int FileCopy(const string& srcPath, const string& dstPath) -{ - bool ret = FILE_IO_ERROR; - string src = srcPath; - string dest = dstPath; - if (GetRealPath(src) == 0) { - if (GetRealPath(dest) == ENOENT) { - FDGuard sfd; - sfd.SetFD(open((char *)src.c_str(), O_RDONLY)); - struct stat attrSrc; - if (stat((char *)src.c_str(), &attrSrc) == FAILED) { - return FILE_IO_ERROR; - } - dest = UriToAbsolute(dest); - FDGuard ofd; - ofd.SetFD(open((char *)dest.c_str(), O_WRONLY | O_CREAT, attrSrc.st_mode)); - if (sfd.GetFD() == FAILED || ofd.GetFD() == FAILED) { - return FILE_IO_ERROR; - } - - if (sendfile(ofd.GetFD(), sfd.GetFD(), nullptr, attrSrc.st_size) != FAILED) { - ret = SUCCESS; - } else { - remove((char *)dest.c_str()); - } - } else if (GetRealPath(dest) == 0) { - return (dest == src) ? SUCCESS : FILE_IO_ERROR; - } - } - return ret; -} - -int DirCopy(const string& srcPath, const string& dstPath) -{ - string src = srcPath; - string dest = dstPath; - if (GetRealPath(src) == ENOENT) { - return FILE_PATH_ERROR; - } - if (GetRealPath(dest) == ENOENT) { - struct stat attrSrc; - if (stat((char *)src.c_str(), &attrSrc) == FAILED || !S_ISDIR(attrSrc.st_mode)) { - return FILE_IO_ERROR; - } - dest = UriToAbsolute(dest); - if (mkdir(dest.c_str(), attrSrc.st_mode) == FAILED) { - return FILE_IO_ERROR; - } - } else { - return (dest == src) ? SUCCESS : FILE_IO_ERROR; - } - return SUCCESS; -} - -void CopyExec(napi_env env, void *data) -{ - auto *asyncCallbackInfo = (AsyncCopyCallbackInfo *)data; - string path = asyncCallbackInfo->url; - string pathDst = asyncCallbackInfo->urlDst; - asyncCallbackInfo->result = FAILED; - asyncCallbackInfo->errorType = FILE_IO_ERROR; - if (GetRealPath(path) == ENOENT) { - asyncCallbackInfo->errorType = FILE_PATH_ERROR; - return; - } - - struct stat statbf; - if (stat((char *)path.c_str(), &statbf) == FAILED) { - asyncCallbackInfo->errorType = FILE_IO_ERROR; - return; - } - - int retval; - if (S_ISREG(statbf.st_mode)) { - retval = FileCopy(path, pathDst); - if (retval == SUCCESS) { - asyncCallbackInfo->result = SUCCESS; - } else { - asyncCallbackInfo->errorType = retval; - } - } else if (S_ISDIR(statbf.st_mode)) { - retval = DirCopy(path, pathDst); - if (retval == SUCCESS) { - asyncCallbackInfo->result = SUCCESS; - } else { - asyncCallbackInfo->errorType = retval; - } - } -} - -void CopyComp(napi_env env, napi_status status, void *data) -{ - auto *asyncCallbackInfo = (AsyncCopyCallbackInfo *)data; - if (asyncCallbackInfo->result == SUCCESS) { - CallBackSuccess(env, asyncCallbackInfo->callback[COMMON_NUM::ZERO], COMMON_NUM::ONE, - NVal::CreateUTF8String(env, asyncCallbackInfo->originDst).val_); - } else if (asyncCallbackInfo->errorType == FILE_IO_ERROR) { - CallBackError(env, asyncCallbackInfo->callback[COMMON_NUM::ONE], "copy file failed", FILE_IO_ERROR); - } else if (asyncCallbackInfo->errorType == FILE_PATH_ERROR) { - CallBackError(env, asyncCallbackInfo->callback[COMMON_NUM::ONE], "file not exist", FILE_PATH_ERROR); - } - CallComplete(env, asyncCallbackInfo->callback[COMMON_NUM::TWO]); - napi_delete_reference(env, asyncCallbackInfo->callback[COMMON_NUM::ZERO]); - napi_delete_reference(env, asyncCallbackInfo->callback[COMMON_NUM::ONE]); - napi_delete_reference(env, asyncCallbackInfo->callback[COMMON_NUM::TWO]); - napi_delete_async_work(env, asyncCallbackInfo->asyncWork); - delete asyncCallbackInfo; -} - -int DirMove(const string& srcPath, const string& dstPath) -{ - string src = srcPath; - string dest = dstPath; - if (GetRealPath(src) == ENOENT) { - return FILE_PATH_ERROR; - } - - auto res = GetRealPath(dest); - if (res == 0 && dest == src) { - return SUCCESS; - } else if (res != ENOENT) { - return FILE_PATH_ERROR; - } - - struct stat attrSrc; - if (stat((char *)src.c_str(), &attrSrc) == FAILED || !S_ISDIR(attrSrc.st_mode)) { - return FILE_IO_ERROR; - } - dest = UriToAbsolute(dest); - if (FAILED == mkdir(dest.c_str(), attrSrc.st_mode)) { - return FILE_IO_ERROR; - } - DIR *dirp = opendir(src.c_str()); - if (dirp == nullptr) { - return FILE_IO_ERROR; - } - struct dirent *entp; - while ((entp = readdir(dirp)) != nullptr) { - if (string(entp->d_name) == "." || string(entp->d_name) == "..") { - continue; - } - string srcBuf = src + "/" + string(entp->d_name); - string dstBuf = dest + "/" + string(entp->d_name); - if (entp->d_type == DT_DIR && DirMove(srcBuf.c_str(), dstBuf.c_str()) != SUCCESS) { - closedir(dirp); - return FILE_IO_ERROR; - } - - if (entp->d_type == DT_REG) { - if (FileCopy(srcBuf.c_str(), dstBuf.c_str()) != SUCCESS) { - closedir(dirp); - return FILE_IO_ERROR; - } else { - remove(srcBuf.c_str()); - } - } - } - closedir(dirp); - rmdir(src.c_str()); - - return SUCCESS; -} - -void MoveExec(napi_env env, void *data) -{ - auto *asyncCallbackInfo = (AsyncMoveCallbackInfo *)data; - string path = asyncCallbackInfo->url; - string pathDst = asyncCallbackInfo->urlDst; - asyncCallbackInfo->result = FAILED; - asyncCallbackInfo->errorType = FILE_IO_ERROR; - if (GetRealPath(path) == ENOENT) { - asyncCallbackInfo->errorType = FILE_PATH_ERROR; - return; - } - - struct stat statbf; - if (stat((char *)path.c_str(), &statbf) == FAILED) { - asyncCallbackInfo->errorType = FILE_IO_ERROR; - return; - } - - if (S_ISREG(statbf.st_mode)) { - int retval = FileCopy(path, pathDst); - if (retval == SUCCESS) { - asyncCallbackInfo->result = SUCCESS; - remove((char *)path.c_str()); - } else { - asyncCallbackInfo->errorType = retval; - } - } else if (S_ISDIR(statbf.st_mode)) { - int retval = DirMove(path, pathDst); - if (retval == SUCCESS) { - asyncCallbackInfo->result = SUCCESS; - } else { - asyncCallbackInfo->errorType = retval; - } - } -} - -void MoveComp(napi_env env, napi_status status, void *data) -{ - auto *asyncCallbackInfo = (AsyncMoveCallbackInfo *)data; - if (asyncCallbackInfo->result == SUCCESS) { - CallBackSuccess(env, asyncCallbackInfo->callback[COMMON_NUM::ZERO], COMMON_NUM::ONE, - NVal::CreateUTF8String(env, asyncCallbackInfo->originDst).val_); - } else if (asyncCallbackInfo->errorType == FILE_IO_ERROR) { - CallBackError(env, asyncCallbackInfo->callback[COMMON_NUM::ONE], "move file failed", FILE_IO_ERROR); - } else if (asyncCallbackInfo->errorType == FILE_PATH_ERROR) { - CallBackError(env, asyncCallbackInfo->callback[COMMON_NUM::ONE], "file not exist", FILE_PATH_ERROR); - } - CallComplete(env, asyncCallbackInfo->callback[COMMON_NUM::TWO]); - napi_delete_reference(env, asyncCallbackInfo->callback[COMMON_NUM::ZERO]); - napi_delete_reference(env, asyncCallbackInfo->callback[COMMON_NUM::ONE]); - napi_delete_reference(env, asyncCallbackInfo->callback[COMMON_NUM::TWO]); - napi_delete_async_work(env, asyncCallbackInfo->asyncWork); - delete asyncCallbackInfo; -} - -void DeleteExec(napi_env env, void *data) -{ - auto *asyncCallbackInfo = (AsyncDeleteCallbackInfo *)data; - string path = asyncCallbackInfo->url; - asyncCallbackInfo->result = FAILED; - int statPath = GetRealPath(path); - if (statPath == ENOENT) { - asyncCallbackInfo->errorType = FILE_PATH_ERROR; - } else if (statPath == COMMON_NUM::ZERO && remove((char *)path.c_str()) != FAILED) { - asyncCallbackInfo->result = SUCCESS; - } else { - asyncCallbackInfo->errorType = FILE_IO_ERROR; - } -} - -void DeleteComp(napi_env env, napi_status status, void *data) -{ - auto *asyncCallbackInfo = (AsyncDeleteCallbackInfo *)data; - if (asyncCallbackInfo->result == SUCCESS) { - CallBackSuccess(env, asyncCallbackInfo->callback[COMMON_NUM::ZERO], COMMON_NUM::ZERO, nullptr); - } else if (asyncCallbackInfo->errorType == FILE_IO_ERROR) { - CallBackError(env, asyncCallbackInfo->callback[COMMON_NUM::ONE], "delete file failed", FILE_IO_ERROR); - } else if (asyncCallbackInfo->errorType == FILE_PATH_ERROR) { - CallBackError(env, asyncCallbackInfo->callback[COMMON_NUM::ONE], "file not exist", FILE_PATH_ERROR); - } - CallComplete(env, asyncCallbackInfo->callback[COMMON_NUM::TWO]); - napi_delete_reference(env, asyncCallbackInfo->callback[COMMON_NUM::ZERO]); - napi_delete_reference(env, asyncCallbackInfo->callback[COMMON_NUM::ONE]); - napi_delete_reference(env, asyncCallbackInfo->callback[COMMON_NUM::TWO]); - napi_delete_async_work(env, asyncCallbackInfo->asyncWork); - delete asyncCallbackInfo; -} - -void AccessExec(napi_env env, void *data) -{ - auto *asyncCallbackInfo = (AsyncAccessCallbackInfo *)data; - string path = asyncCallbackInfo->url; - asyncCallbackInfo->result = FAILED; - int statPath = GetRealPath(path); - if (statPath == ENOENT) { - asyncCallbackInfo->errorType = FILE_PATH_ERROR; - } else if (statPath == COMMON_NUM::ZERO) { - asyncCallbackInfo->result = SUCCESS; - } else { - asyncCallbackInfo->errorType = FILE_IO_ERROR; - } -} - -void AccessComp(napi_env env, napi_status status, void *data) -{ - auto *asyncCallbackInfo = (AsyncAccessCallbackInfo *)data; - if (asyncCallbackInfo->result == SUCCESS) { - CallBackSuccess(env, asyncCallbackInfo->callback[COMMON_NUM::ZERO], COMMON_NUM::ZERO, nullptr); - } else if (asyncCallbackInfo->errorType == FILE_IO_ERROR) { - CallBackError(env, asyncCallbackInfo->callback[COMMON_NUM::ONE], "access file failed", FILE_IO_ERROR); - } else if (asyncCallbackInfo->errorType == FILE_PATH_ERROR) { - CallBackError(env, asyncCallbackInfo->callback[COMMON_NUM::ONE], "file not exist", FILE_PATH_ERROR); - } - CallComplete(env, asyncCallbackInfo->callback[COMMON_NUM::TWO]); - napi_delete_reference(env, asyncCallbackInfo->callback[COMMON_NUM::ZERO]); - napi_delete_reference(env, asyncCallbackInfo->callback[COMMON_NUM::ONE]); - napi_delete_reference(env, asyncCallbackInfo->callback[COMMON_NUM::TWO]); - napi_delete_async_work(env, asyncCallbackInfo->asyncWork); - delete asyncCallbackInfo; -} - -void WriteTextExec(napi_env env, void *data) -{ - auto *asyncCallbackInfo = (AsyncWriteCallbackInfo *)data; - string path = asyncCallbackInfo->url; - string text = asyncCallbackInfo->text; - asyncCallbackInfo->result = FAILED; - asyncCallbackInfo->errorType = FILE_IO_ERROR; - int fd = -1; - int statPath = GetRealPath(path); - if (statPath == COMMON_NUM::ZERO || statPath == ENOENT) { - if (asyncCallbackInfo->append) { - fd = open(path.c_str(), O_WRONLY | O_APPEND | O_CREAT, S_IRUSR | S_IWUSR); - } else { - fd = open(path.c_str(), O_WRONLY | O_TRUNC | O_CREAT, S_IRUSR | S_IWUSR); - } - if (fd != FAILED) { - if (write(fd, text.c_str(), text.length()) != FAILED) { - asyncCallbackInfo->result = SUCCESS; - } - close(fd); - } - } -} - -void WriteTextComp(napi_env env, napi_status status, void *data) -{ - auto *asyncCallbackInfo = (AsyncWriteCallbackInfo *)data; - if (asyncCallbackInfo->result == SUCCESS) { - CallBackSuccess(env, asyncCallbackInfo->callback[COMMON_NUM::ZERO], COMMON_NUM::ZERO, nullptr); - } else if (asyncCallbackInfo->errorType == FILE_IO_ERROR) { - CallBackError(env, asyncCallbackInfo->callback[COMMON_NUM::ONE], "write file failed", FILE_IO_ERROR); - } - CallComplete(env, asyncCallbackInfo->callback[COMMON_NUM::TWO]); - napi_delete_reference(env, asyncCallbackInfo->callback[COMMON_NUM::ZERO]); - napi_delete_reference(env, asyncCallbackInfo->callback[COMMON_NUM::ONE]); - napi_delete_reference(env, asyncCallbackInfo->callback[COMMON_NUM::TWO]); - napi_delete_async_work(env, asyncCallbackInfo->asyncWork); - delete asyncCallbackInfo; -} - -void WriteArrayBufferExec(napi_env env, void *data) -{ - auto *asyncCallbackInfo = (AsyncWriteBufferCallbackInfo *)data; - string path = asyncCallbackInfo->url; - asyncCallbackInfo->result = FAILED; - asyncCallbackInfo->errorType = FILE_IO_ERROR; - int fd = -1; - int statPath = GetRealPath(path); - if (statPath == COMMON_NUM::ZERO || statPath == ENOENT) { - if (asyncCallbackInfo->append) { - fd = open(path.c_str(), O_WRONLY | O_APPEND | O_CREAT, S_IRUSR | S_IWUSR); - if (fd == FAILED) { - return; - } - } else { - fd = open(path.c_str(), O_WRONLY | O_TRUNC | O_CREAT, S_IRUSR | S_IWUSR); - if (fd == FAILED) { - return; - } - lseek(fd, asyncCallbackInfo->position, SEEK_CUR); - } - if (write(fd, asyncCallbackInfo->buf, asyncCallbackInfo->length) != FAILED) { - asyncCallbackInfo->result = SUCCESS; - } - close(fd); - } -} - -void WriteArrayBufferComp(napi_env env, napi_status status, void *data) -{ - auto *asyncCallbackInfo = (AsyncWriteBufferCallbackInfo *)data; - if (asyncCallbackInfo->result == SUCCESS) { - CallBackSuccess(env, asyncCallbackInfo->callback[COMMON_NUM::ZERO], COMMON_NUM::ZERO, nullptr); - } else if (asyncCallbackInfo->errorType == FILE_IO_ERROR) { - CallBackError(env, asyncCallbackInfo->callback[COMMON_NUM::ONE], "write file failed", FILE_IO_ERROR); - } - CallComplete(env, asyncCallbackInfo->callback[COMMON_NUM::TWO]); - napi_delete_reference(env, asyncCallbackInfo->callback[COMMON_NUM::ZERO]); - napi_delete_reference(env, asyncCallbackInfo->callback[COMMON_NUM::ONE]); - napi_delete_reference(env, asyncCallbackInfo->callback[COMMON_NUM::TWO]); - napi_delete_reference(env, asyncCallbackInfo->bufferAddress); - napi_delete_async_work(env, asyncCallbackInfo->asyncWork); - delete asyncCallbackInfo; -} - -void ReadTextExec(napi_env env, void *data) -{ - auto *asyncCallbackInfo = (AsyncReadCallbackInfo *)data; - string path = asyncCallbackInfo->url; - asyncCallbackInfo->result = FAILED; - asyncCallbackInfo->errorType = FILE_IO_ERROR; - int statPath = GetRealPath(path); - if (statPath == COMMON_NUM::ZERO) { - FDGuard fdg; - fdg.SetFD(open(path.c_str(), O_RDONLY)); - struct stat buf; - int result = stat((char *)path.c_str(), &buf); - if (fdg.GetFD() != FAILED && result != FAILED) { - auto buffer = std::make_unique(buf.st_size + 1); - if (buffer == nullptr) { - UniError(ENOMEM).ThrowErr(env); - return; - } - if (read(fdg.GetFD(), buffer.get(), buf.st_size) != FAILED) { - asyncCallbackInfo->result = SUCCESS; - asyncCallbackInfo->contents = std::string(buffer.get()); - } - } - } else if (statPath == ENOENT) { - asyncCallbackInfo->errorType = FILE_PATH_ERROR; - } -} - -void ReadTextComp(napi_env env, napi_status status, void *data) -{ - auto *asyncCallbackInfo = (AsyncReadCallbackInfo *)data; - if (asyncCallbackInfo->result == SUCCESS) { - NVal objn = NVal::CreateObject(env); - objn.AddProp("text", NVal::CreateUTF8String(env, asyncCallbackInfo->contents).val_); - CallBackSuccess(env, asyncCallbackInfo->callback[COMMON_NUM::ZERO], COMMON_NUM::ONE, objn.val_); - } else if (asyncCallbackInfo->errorType == FILE_IO_ERROR) { - CallBackError(env, asyncCallbackInfo->callback[COMMON_NUM::ONE], "read file failed", FILE_IO_ERROR); - } else if (asyncCallbackInfo->errorType == FILE_PATH_ERROR) { - CallBackError(env, asyncCallbackInfo->callback[COMMON_NUM::ONE], "file not exist", FILE_PATH_ERROR); - } - CallComplete(env, asyncCallbackInfo->callback[COMMON_NUM::TWO]); - napi_delete_reference(env, asyncCallbackInfo->callback[COMMON_NUM::ZERO]); - napi_delete_reference(env, asyncCallbackInfo->callback[COMMON_NUM::ONE]); - napi_delete_reference(env, asyncCallbackInfo->callback[COMMON_NUM::TWO]); - napi_delete_async_work(env, asyncCallbackInfo->asyncWork); - delete asyncCallbackInfo; -} - -void ReadArrayBufferExec(napi_env env, void *data) -{ - auto *asyncCallbackInfo = (AsyncReadBufferCallbackInfo *)data; - string path = asyncCallbackInfo->url; - asyncCallbackInfo->result = FAILED; - asyncCallbackInfo->errorType = FILE_IO_ERROR; - int statPath = GetRealPath(path); - if (statPath == COMMON_NUM::ZERO) { - FDGuard fdg; - fdg.SetFD(open(path.c_str(), O_RDONLY)); - struct stat buf; - int result = stat((char *)path.c_str(), &buf); - if (fdg.GetFD() != FAILED && result != FAILED) { - int32_t begin = (buf.st_size < asyncCallbackInfo->position) ? buf.st_size : asyncCallbackInfo->position; - int32_t len = - (asyncCallbackInfo->length == COMMON_NUM::ZERO) ? (buf.st_size - begin) : asyncCallbackInfo->length; - auto buffer = std::make_unique(len + 1); - if (buffer == nullptr) { - UniError(ENOMEM).ThrowErr(env); - return; - } - lseek(fdg.GetFD(), begin, SEEK_CUR); - if (read(fdg.GetFD(), buffer.get(), len) != FAILED) { - asyncCallbackInfo->result = SUCCESS; - asyncCallbackInfo->len = len; - asyncCallbackInfo->contents = std::string(buffer.get()); - } - } - } else if (statPath == ENOENT) { - asyncCallbackInfo->errorType = FILE_PATH_ERROR; - } -} - -void ReadArrayBufferComp(napi_env env, napi_status status, void *data) -{ - auto *asyncCallbackInfo = (AsyncReadBufferCallbackInfo *)data; - if (asyncCallbackInfo->result == SUCCESS) { - napi_value typeArr = nullptr; - napi_create_array(env, &typeArr); - for (int32_t i = 0; i < asyncCallbackInfo->len; ++i) { - napi_set_property(env, typeArr, NVal::CreateInt32(env, i).val_, - NVal::CreateInt32(env, (int32_t)(asyncCallbackInfo->contents)[i]).val_); - } - NVal objn = NVal::CreateObject(env); - objn.AddProp("buffer", typeArr); - CallBackSuccess(env, asyncCallbackInfo->callback[COMMON_NUM::ZERO], COMMON_NUM::ONE, objn.val_); - } else if (asyncCallbackInfo->errorType == FILE_IO_ERROR) { - CallBackError(env, asyncCallbackInfo->callback[COMMON_NUM::ONE], "read file failed", FILE_IO_ERROR); - } else if (asyncCallbackInfo->errorType == FILE_PATH_ERROR) { - CallBackError(env, asyncCallbackInfo->callback[COMMON_NUM::ONE], "file not exist", FILE_PATH_ERROR); - } - CallComplete(env, asyncCallbackInfo->callback[COMMON_NUM::TWO]); - napi_delete_reference(env, asyncCallbackInfo->callback[COMMON_NUM::ZERO]); - napi_delete_reference(env, asyncCallbackInfo->callback[COMMON_NUM::ONE]); - napi_delete_reference(env, asyncCallbackInfo->callback[COMMON_NUM::TWO]); - napi_delete_async_work(env, asyncCallbackInfo->asyncWork); - delete asyncCallbackInfo; -} - -napi_value FileNExporter::Mkdir(napi_env env, napi_callback_info info) -{ - NFuncArg funcArg(env, info); - if (!funcArg.InitArgs(NARG_CNT::ONE)) { - UniError(EINVAL).ThrowErr(env, "Number of arguments unmatched"); - return nullptr; - } - bool succ = false; - auto *asyncCallbackInfo = new AsyncMkdirCallbackInfo { - .env = env, - .asyncWork = nullptr, - }; - tie(succ, asyncCallbackInfo->callback[COMMON_NUM::ZERO], asyncCallbackInfo->callback[COMMON_NUM::ONE], - asyncCallbackInfo->callback[COMMON_NUM::TWO]) = CommonFunc::GetCallbackHandles(env, funcArg[NARG_POS::FIRST]); - - unique_ptr uri; - tie(succ, uri, ignore) = NVal(env, funcArg[NARG_POS::FIRST]).GetProp("uri").ToUTF8String(); - - bool recursive = false; - tie(succ, recursive) = NVal(env, funcArg[NARG_POS::FIRST]).GetProp("recursive").ToBool(); - - string path = (uri == nullptr) ? "" : uri.get(); - if (!CheckUri(env, path)) { - CallBackError(env, asyncCallbackInfo->callback[COMMON_NUM::ONE], "illegal uri", URI_PARAMER_ERROR); - CallComplete(env, asyncCallbackInfo->callback[COMMON_NUM::TWO]); - delete asyncCallbackInfo; - return nullptr; - } - asyncCallbackInfo->recursive = recursive; - asyncCallbackInfo->url = path; - - napi_create_async_work(env, nullptr, NVal::CreateUTF8String(env, "ResourceName").val_, MkdirExec, MkdirComp, - (void *)asyncCallbackInfo, &asyncCallbackInfo->asyncWork); - napi_queue_async_work(env, asyncCallbackInfo->asyncWork); - return NVal::CreateUndefined(env).val_; -} - -napi_value FileNExporter::Rmdir(napi_env env, napi_callback_info info) -{ - NFuncArg funcArg(env, info); - if (!funcArg.InitArgs(NARG_CNT::ONE)) { - UniError(EINVAL).ThrowErr(env, "Number of arguments unmatched"); - return nullptr; - } - bool succ = false; - auto *asyncCallbackInfo = new AsyncRmdirCallbackInfo { - .env = env, - .asyncWork = nullptr, - }; - tie(succ, asyncCallbackInfo->callback[COMMON_NUM::ZERO], asyncCallbackInfo->callback[COMMON_NUM::ONE], - asyncCallbackInfo->callback[COMMON_NUM::TWO]) = CommonFunc::GetCallbackHandles(env, funcArg[NARG_POS::FIRST]); - - unique_ptr uri; - tie(succ, uri, ignore) = NVal(env, funcArg[NARG_POS::FIRST]).GetProp("uri").ToUTF8String(); - - bool recursive = false; - tie(succ, recursive) = NVal(env, funcArg[NARG_POS::FIRST]).GetProp("recursive").ToBool(); - - string path = (uri == nullptr) ? "" : uri.get(); - if (!CheckUri(env, path)) { - CallBackError(env, asyncCallbackInfo->callback[COMMON_NUM::ONE], "illegal uri", URI_PARAMER_ERROR); - CallComplete(env, asyncCallbackInfo->callback[COMMON_NUM::TWO]); - delete asyncCallbackInfo; - return nullptr; - } - asyncCallbackInfo->recursive = recursive; - asyncCallbackInfo->url = path; - - napi_create_async_work(env, nullptr, NVal::CreateUTF8String(env, "ResourceName").val_, RmdirExec, RmdirComp, - (void *)asyncCallbackInfo, &asyncCallbackInfo->asyncWork); - napi_queue_async_work(env, asyncCallbackInfo->asyncWork); - - return NVal::CreateUndefined(env).val_; -} - -napi_value FileNExporter::Get(napi_env env, napi_callback_info info) -{ - NFuncArg funcArg(env, info); - if (!funcArg.InitArgs(NARG_CNT::ONE)) { - UniError(EINVAL).ThrowErr(env, "Number of arguments unmatched"); - return nullptr; - } - auto *asyncCallbackInfo = new AsyncGetCallbackInfo { - .env = env, - .asyncWork = nullptr, - }; - bool succ = false; - tie(succ, asyncCallbackInfo->callback[COMMON_NUM::ZERO], asyncCallbackInfo->callback[COMMON_NUM::ONE], - asyncCallbackInfo->callback[COMMON_NUM::TWO]) = CommonFunc::GetCallbackHandles(env, funcArg[NARG_POS::FIRST]); - unique_ptr uri = nullptr; - tie(succ, uri, ignore) = NVal(env, funcArg[NARG_POS::FIRST]).GetProp("uri").ToUTF8String(); - - bool recursive = false; - tie(succ, recursive) = NVal(env, funcArg[NARG_POS::FIRST]).GetProp("recursive").ToBool(); - string path = (uri == nullptr) ? "" : uri.get(); - asyncCallbackInfo->originUri = path; - if (!CheckUri(env, path)) { - CallBackError(env, asyncCallbackInfo->callback[COMMON_NUM::ONE], "illegal uri", URI_PARAMER_ERROR); - CallComplete(env, asyncCallbackInfo->callback[COMMON_NUM::TWO]); - delete asyncCallbackInfo; - return nullptr; - } - asyncCallbackInfo->recursive = recursive; - asyncCallbackInfo->url = path; - - napi_create_async_work(env, nullptr, NVal::CreateUTF8String(env, "ResourceName").val_, GetExec, GetComp, - (void *)asyncCallbackInfo, &asyncCallbackInfo->asyncWork); - napi_queue_async_work(env, asyncCallbackInfo->asyncWork); - - return NVal::CreateUndefined(env).val_; -} - -napi_value FileNExporter::List(napi_env env, napi_callback_info info) -{ - NFuncArg funcArg(env, info); - if (!funcArg.InitArgs(NARG_CNT::ONE)) { - UniError(EINVAL).ThrowErr(env, "Number of arguments unmatched"); - return nullptr; - } - auto *asyncCallbackInfo = new AsyncListCallbackInfo { - .env = env, - .asyncWork = nullptr, - }; - bool succ = false; - tie(succ, asyncCallbackInfo->callback[COMMON_NUM::ZERO], asyncCallbackInfo->callback[COMMON_NUM::ONE], - asyncCallbackInfo->callback[COMMON_NUM::TWO]) = CommonFunc::GetCallbackHandles(env, funcArg[NARG_POS::FIRST]); - - unique_ptr uri = nullptr; - tie(succ, uri, ignore) = NVal(env, funcArg[NARG_POS::FIRST]).GetProp("uri").ToUTF8String(); - - string path = (uri == nullptr) ? "" : uri.get(); - asyncCallbackInfo->originUri = path; - if (!CheckUri(env, path)) { - CallBackError(env, asyncCallbackInfo->callback[COMMON_NUM::ONE], "illegal uri", URI_PARAMER_ERROR); - CallComplete(env, asyncCallbackInfo->callback[COMMON_NUM::TWO]); - delete asyncCallbackInfo; - return nullptr; - } - asyncCallbackInfo->url = path; - - napi_create_async_work(env, nullptr, NVal::CreateUTF8String(env, "ResourceName").val_, ListExec, ListComp, - (void *)asyncCallbackInfo, &asyncCallbackInfo->asyncWork); - napi_queue_async_work(env, asyncCallbackInfo->asyncWork); - - return NVal::CreateUndefined(env).val_; -} - -napi_value FileNExporter::Copy(napi_env env, napi_callback_info info) -{ - NFuncArg funcArg(env, info); - if (!funcArg.InitArgs(NARG_CNT::ONE)) { - UniError(EINVAL).ThrowErr(env, "Number of arguments unmatched"); - return nullptr; - } - bool succ = false; - auto *asyncCallbackInfo = new AsyncCopyCallbackInfo { - .env = env, - .asyncWork = nullptr, - }; - tie(succ, asyncCallbackInfo->callback[COMMON_NUM::ZERO], asyncCallbackInfo->callback[COMMON_NUM::ONE], - asyncCallbackInfo->callback[COMMON_NUM::TWO]) = CommonFunc::GetCallbackHandles(env, funcArg[NARG_POS::FIRST]); - - unique_ptr srcUri, dstUri; - tie(succ, srcUri, ignore) = NVal(env, funcArg[NARG_POS::FIRST]).GetProp("srcUri").ToUTF8String(); - tie(succ, dstUri, ignore) = NVal(env, funcArg[NARG_POS::FIRST]).GetProp("dstUri").ToUTF8String(); - string srcPath = ((srcUri == nullptr) ? "" : (srcUri.get())); - string dstPath = ((dstUri == nullptr) ? "" : (dstUri.get())); - asyncCallbackInfo->originDst = dstPath; - if (!CheckUri(env, srcPath) || !CheckUri(env, dstPath)) { - CallBackError(env, asyncCallbackInfo->callback[COMMON_NUM::ONE], "illegal uri", URI_PARAMER_ERROR); - CallComplete(env, asyncCallbackInfo->callback[COMMON_NUM::TWO]); - delete asyncCallbackInfo; - return nullptr; - } - asyncCallbackInfo->url = srcPath; - asyncCallbackInfo->urlDst = dstPath; - - napi_create_async_work(env, nullptr, NVal::CreateUTF8String(env, "ResourceName").val_, CopyExec, CopyComp, - (void *)asyncCallbackInfo, &asyncCallbackInfo->asyncWork); - napi_queue_async_work(env, asyncCallbackInfo->asyncWork); - return NVal::CreateUndefined(env).val_; -} - -napi_value FileNExporter::Move(napi_env env, napi_callback_info info) -{ - NFuncArg funcArg(env, info); - if (!funcArg.InitArgs(NARG_CNT::ONE)) { - UniError(EINVAL).ThrowErr(env, "Number of arguments unmatched"); - return nullptr; - } - bool succ = false; - auto *asyncCallbackInfo = new AsyncMoveCallbackInfo { - .env = env, - .asyncWork = nullptr, - }; - tie(succ, asyncCallbackInfo->callback[COMMON_NUM::ZERO], asyncCallbackInfo->callback[COMMON_NUM::ONE], - asyncCallbackInfo->callback[COMMON_NUM::TWO]) = CommonFunc::GetCallbackHandles(env, funcArg[NARG_POS::FIRST]); - - unique_ptr srcUri, dstUri; - tie(succ, srcUri, ignore) = NVal(env, funcArg[NARG_POS::FIRST]).GetProp("srcUri").ToUTF8String(); - tie(succ, dstUri, ignore) = NVal(env, funcArg[NARG_POS::FIRST]).GetProp("dstUri").ToUTF8String(); - - string srcPath = ((srcUri == nullptr) ? "" : (srcUri.get())); - string dstPath = ((dstUri == nullptr) ? "" : (dstUri.get())); - asyncCallbackInfo->originDst = dstPath; - if (!CheckUri(env, srcPath) || !CheckUri(env, dstPath)) { - CallBackError(env, asyncCallbackInfo->callback[COMMON_NUM::ONE], "illegal uri", URI_PARAMER_ERROR); - CallComplete(env, asyncCallbackInfo->callback[COMMON_NUM::TWO]); - delete asyncCallbackInfo; - return nullptr; - } - asyncCallbackInfo->url = srcPath; - asyncCallbackInfo->urlDst = dstPath; - - napi_create_async_work(env, nullptr, NVal::CreateUTF8String(env, "ResourceName").val_, MoveExec, MoveComp, - (void *)asyncCallbackInfo, &asyncCallbackInfo->asyncWork); - napi_queue_async_work(env, asyncCallbackInfo->asyncWork); - return NVal::CreateUndefined(env).val_; -} - -napi_value FileNExporter::Delete(napi_env env, napi_callback_info info) -{ - NFuncArg funcArg(env, info); - if (!funcArg.InitArgs(NARG_CNT::ONE)) { - UniError(EINVAL).ThrowErr(env, "Number of arguments unmatched"); - return nullptr; - } - bool succ = false; - auto *asyncCallbackInfo = new AsyncDeleteCallbackInfo { - .env = env, - .asyncWork = nullptr, - }; - tie(succ, asyncCallbackInfo->callback[COMMON_NUM::ZERO], asyncCallbackInfo->callback[COMMON_NUM::ONE], - asyncCallbackInfo->callback[COMMON_NUM::TWO]) = CommonFunc::GetCallbackHandles(env, funcArg[NARG_POS::FIRST]); - - unique_ptr uri; - tie(succ, uri, ignore) = NVal(env, funcArg[NARG_POS::FIRST]).GetProp("uri").ToUTF8String(); - - string path = (uri == nullptr) ? "" : uri.get(); - if (!CheckUri(env, path)) { - CallBackError(env, asyncCallbackInfo->callback[COMMON_NUM::ONE], "illegal uri", URI_PARAMER_ERROR); - CallComplete(env, asyncCallbackInfo->callback[COMMON_NUM::TWO]); - delete asyncCallbackInfo; - return nullptr; - } - asyncCallbackInfo->url = path; - - napi_create_async_work(env, nullptr, NVal::CreateUTF8String(env, "ResourceName").val_, DeleteExec, DeleteComp, - (void *)asyncCallbackInfo, &asyncCallbackInfo->asyncWork); - napi_queue_async_work(env, asyncCallbackInfo->asyncWork); - - return NVal::CreateUndefined(env).val_; -} - -napi_value FileNExporter::Access(napi_env env, napi_callback_info info) -{ - NFuncArg funcArg(env, info); - if (!funcArg.InitArgs(NARG_CNT::ONE)) { - UniError(EINVAL).ThrowErr(env, "Number of arguments unmatched"); - return nullptr; - } - bool succ = false; - AsyncAccessCallbackInfo *asyncCallbackInfo = new AsyncAccessCallbackInfo { - .env = env, - .asyncWork = nullptr, - }; - tie(succ, asyncCallbackInfo->callback[COMMON_NUM::ZERO], asyncCallbackInfo->callback[COMMON_NUM::ONE], - asyncCallbackInfo->callback[COMMON_NUM::TWO]) = CommonFunc::GetCallbackHandles(env, funcArg[NARG_POS::FIRST]); - - unique_ptr uri; - tie(succ, uri, ignore) = NVal(env, funcArg[NARG_POS::FIRST]).GetProp("uri").ToUTF8String(); - - string path = (uri == nullptr) ? "" : uri.get(); - if (!CheckUri(env, path)) { - CallBackError(env, asyncCallbackInfo->callback[COMMON_NUM::ONE], "illegal uri", URI_PARAMER_ERROR); - CallComplete(env, asyncCallbackInfo->callback[COMMON_NUM::TWO]); - delete asyncCallbackInfo; - return nullptr; - } - asyncCallbackInfo->url = path; - - napi_create_async_work(env, nullptr, NVal::CreateUTF8String(env, "ResourceName").val_, AccessExec, AccessComp, - (void *)asyncCallbackInfo, &asyncCallbackInfo->asyncWork); - napi_queue_async_work(env, asyncCallbackInfo->asyncWork); - return NVal::CreateUndefined(env).val_; -} - -napi_value FileNExporter::WriteText(napi_env env, napi_callback_info info) -{ - NFuncArg funcArg(env, info); - if (!funcArg.InitArgs(NARG_CNT::ONE)) { - UniError(EINVAL).ThrowErr(env, "Number of arguments unmatched"); - return nullptr; - } - auto *asyncCallbackInfo = new AsyncWriteCallbackInfo { - .env = env, - .asyncWork = nullptr, - }; - bool succ = false; - tie(succ, asyncCallbackInfo->callback[COMMON_NUM::ZERO], asyncCallbackInfo->callback[COMMON_NUM::ONE], - asyncCallbackInfo->callback[COMMON_NUM::TWO]) = CommonFunc::GetCallbackHandles(env, funcArg[NARG_POS::FIRST]); - - unique_ptr uri, text, encoding; - tie(succ, uri, ignore) = NVal(env, funcArg[NARG_POS::FIRST]).GetProp("uri").ToUTF8String(); - tie(succ, text, ignore) = NVal(env, funcArg[NARG_POS::FIRST]).GetProp("text").ToUTF8String(); - tie(succ, encoding, ignore) = NVal(env, funcArg[NARG_POS::FIRST]).GetProp("encoding").ToUTF8String(); - - bool append = false; - tie(succ, append) = NVal(env, funcArg[NARG_POS::FIRST]).GetProp("append").ToBool(); - - string path = (uri == nullptr) ? "" : uri.get(); - string encode = (encoding == nullptr) ? ENCODING_UTF8 : encoding.get(); - transform(encode.begin(), encode.end(), encode.begin(), ::tolower); - if (!CheckUri(env, path)) { - CallBackError(env, asyncCallbackInfo->callback[COMMON_NUM::ONE], "illegal uri", URI_PARAMER_ERROR); - CallComplete(env, asyncCallbackInfo->callback[COMMON_NUM::TWO]); - delete asyncCallbackInfo; - return nullptr; - } - if (encode != ENCODING_UTF8) { - CallBackError(env, asyncCallbackInfo->callback[COMMON_NUM::ONE], "write file failed", FILE_IO_ERROR); - CallComplete(env, asyncCallbackInfo->callback[COMMON_NUM::TWO]); - delete asyncCallbackInfo; - return nullptr; - } - string content = text.get(); - asyncCallbackInfo->url = path; - asyncCallbackInfo->text = content; - asyncCallbackInfo->append = append; - - napi_create_async_work(env, nullptr, NVal::CreateUTF8String(env, "ResourceName").val_, WriteTextExec, WriteTextComp, - (void *)asyncCallbackInfo, &asyncCallbackInfo->asyncWork); - napi_queue_async_work(env, asyncCallbackInfo->asyncWork); - return NVal::CreateUndefined(env).val_; -} - -napi_value FileNExporter::WriteArrayBuffer(napi_env env, napi_callback_info info) -{ - NFuncArg funcArg(env, info); - if (!funcArg.InitArgs(NARG_CNT::ONE)) { - UniError(EINVAL).ThrowErr(env, "Number of arguments unmatched"); - return nullptr; - } - bool succ = false; - auto *asyncCallbackInfo = new AsyncWriteBufferCallbackInfo { - .env = env, - .asyncWork = nullptr, - }; - tie(succ, asyncCallbackInfo->callback[COMMON_NUM::ZERO], asyncCallbackInfo->callback[COMMON_NUM::ONE], - asyncCallbackInfo->callback[COMMON_NUM::TWO]) = CommonFunc::GetCallbackHandles(env, funcArg[NARG_POS::FIRST]); - - unique_ptr uri; - tie(succ, uri, ignore) = NVal(env, funcArg[NARG_POS::FIRST]).GetProp("uri").ToUTF8String(); - - int32_t position = 0; - tie(succ, position) = NVal(env, funcArg[NARG_POS::FIRST]).GetProp("position").ToInt32(); - - bool append = false; - tie(succ, append) = NVal(env, funcArg[NARG_POS::FIRST]).GetProp("append").ToBool(); - - void *buffer = nullptr; - size_t bufLength = 0; - napi_ref bufferRef = nullptr; - NVal bufNapi = NVal(env, funcArg[NARG_POS::FIRST]).GetProp("buffer"); - tie(succ, buffer, bufLength) = bufNapi.ToTypedArray(); - napi_create_reference(env, bufNapi.val_, 1, &bufferRef); - - string path = (uri == nullptr) ? "" : uri.get(); - if (!CheckUri(env, path)) { - CallBackError(env, asyncCallbackInfo->callback[COMMON_NUM::ONE], "illegal uri", URI_PARAMER_ERROR); - CallComplete(env, asyncCallbackInfo->callback[COMMON_NUM::TWO]); - delete asyncCallbackInfo; - return nullptr; - } - int32_t bufLen { bufLength }; - asyncCallbackInfo->url = path; - asyncCallbackInfo->position = position; - asyncCallbackInfo->append = append; - asyncCallbackInfo->buf = buffer; - asyncCallbackInfo->length = bufLen; - asyncCallbackInfo->bufferAddress = bufferRef; - - napi_create_async_work(env, nullptr, NVal::CreateUTF8String(env, "ResourceName").val_, WriteArrayBufferExec, - WriteArrayBufferComp, (void *)asyncCallbackInfo, &asyncCallbackInfo->asyncWork); - napi_queue_async_work(env, asyncCallbackInfo->asyncWork); - return NVal::CreateUndefined(env).val_; -} - -napi_value FileNExporter::ReadText(napi_env env, napi_callback_info info) -{ - NFuncArg funcArg(env, info); - if (!funcArg.InitArgs(NARG_CNT::ONE)) { - UniError(EINVAL).ThrowErr(env, "Number of arguments unmatched"); - return nullptr; - } - bool succ = false; - auto *asyncCallbackInfo = new AsyncReadCallbackInfo { - .env = env, - .asyncWork = nullptr, - }; - tie(succ, asyncCallbackInfo->callback[COMMON_NUM::ZERO], asyncCallbackInfo->callback[COMMON_NUM::ONE], - asyncCallbackInfo->callback[COMMON_NUM::TWO]) = CommonFunc::GetCallbackHandles(env, funcArg[NARG_POS::FIRST]); - - unique_ptr uri, encoding; - tie(succ, uri, ignore) = NVal(env, funcArg[NARG_POS::FIRST]).GetProp("uri").ToUTF8String(); - tie(succ, encoding, ignore) = NVal(env, funcArg[NARG_POS::FIRST]).GetProp("encoding").ToUTF8String(); - - string path = (uri == nullptr) ? "" : uri.get(); - string encode = (encoding == nullptr) ? ENCODING_UTF8 : encoding.get(); - transform(encode.begin(), encode.end(), encode.begin(), ::tolower); - if (!CheckUri(env, path)) { - CallBackError(env, asyncCallbackInfo->callback[COMMON_NUM::ONE], "illegal uri", URI_PARAMER_ERROR); - CallComplete(env, asyncCallbackInfo->callback[COMMON_NUM::TWO]); - delete asyncCallbackInfo; - return nullptr; - } - if (encode != ENCODING_UTF8) { - CallBackError(env, asyncCallbackInfo->callback[COMMON_NUM::ONE], "read file failed", FILE_IO_ERROR); - CallComplete(env, asyncCallbackInfo->callback[COMMON_NUM::TWO]); - delete asyncCallbackInfo; - return nullptr; - } - asyncCallbackInfo->url = path; - - napi_create_async_work(env, nullptr, NVal::CreateUTF8String(env, "ResourceName").val_, ReadTextExec, ReadTextComp, - (void *)asyncCallbackInfo, &asyncCallbackInfo->asyncWork); - napi_queue_async_work(env, asyncCallbackInfo->asyncWork); - return NVal::CreateUndefined(env).val_; -} - -napi_value FileNExporter::ReadArrayBuffer(napi_env env, napi_callback_info info) -{ - NFuncArg funcArg(env, info); - if (!funcArg.InitArgs(NARG_CNT::ONE)) { - UniError(EINVAL).ThrowErr(env, "Number of arguments unmatched"); - return nullptr; - } - auto *asyncCallbackInfo = new AsyncReadBufferCallbackInfo { - .env = env, - .asyncWork = nullptr, - }; - bool succ = false; - tie(succ, asyncCallbackInfo->callback[COMMON_NUM::ZERO], asyncCallbackInfo->callback[COMMON_NUM::ONE], - asyncCallbackInfo->callback[COMMON_NUM::TWO]) = CommonFunc::GetCallbackHandles(env, funcArg[NARG_POS::FIRST]); - - unique_ptr uri; - tie(succ, uri, ignore) = NVal(env, funcArg[NARG_POS::FIRST]).GetProp("uri").ToUTF8String(); - - int position = 0; - tie(succ, position) = NVal(env, funcArg[NARG_POS::FIRST]).GetProp("position").ToInt32(); - - int length = 0; - tie(succ, length) = NVal(env, funcArg[NARG_POS::FIRST]).GetProp("length").ToInt32(); - - string path = (uri == nullptr) ? "" : uri.get(); - if (!CheckUri(env, path)) { - CallBackError(env, asyncCallbackInfo->callback[COMMON_NUM::ONE], "illegal uri", URI_PARAMER_ERROR); - CallComplete(env, asyncCallbackInfo->callback[COMMON_NUM::TWO]); - delete asyncCallbackInfo; - return nullptr; - } - asyncCallbackInfo->url = path; - asyncCallbackInfo->length = length; - asyncCallbackInfo->position = position; - - napi_create_async_work(env, nullptr, NVal::CreateUTF8String(env, "ResourceName").val_, ReadArrayBufferExec, - ReadArrayBufferComp, (void *)asyncCallbackInfo, &asyncCallbackInfo->asyncWork); - napi_queue_async_work(env, asyncCallbackInfo->asyncWork); - return NVal::CreateUndefined(env).val_; -} - -bool FileNExporter::Export() -{ - return exports_.AddProp({ - NVal::DeclareNapiFunction("mkdir", Mkdir), - NVal::DeclareNapiFunction("rmdir", Rmdir), - NVal::DeclareNapiFunction("get", Get), - NVal::DeclareNapiFunction("list", List), - NVal::DeclareNapiFunction("copy", Copy), - NVal::DeclareNapiFunction("move", Move), - NVal::DeclareNapiFunction("delete", Delete), - NVal::DeclareNapiFunction("access", Access), - NVal::DeclareNapiFunction("writeText", WriteText), - NVal::DeclareNapiFunction("writeArrayBuffer", WriteArrayBuffer), - NVal::DeclareNapiFunction("readText", ReadText), - NVal::DeclareNapiFunction("readArrayBuffer", ReadArrayBuffer), - }); -} - -string FileNExporter::GetClassName() -{ - return FileNExporter::className_; -} - -FileNExporter::FileNExporter(napi_env env, napi_value exports) - : NExporter(env, exports) -{} - -FileNExporter::~FileNExporter() {} -} // namespace ModuleFile -} // namespace DistributedFS -} // namespace OHOS \ No newline at end of file diff --git a/interfaces/kits/js/src/mod_file/class_file/file_n_exporter.h b/interfaces/kits/js/src/mod_file/class_file/file_n_exporter.h deleted file mode 100644 index 050f277..0000000 --- a/interfaces/kits/js/src/mod_file/class_file/file_n_exporter.h +++ /dev/null @@ -1,198 +0,0 @@ -/* - * Copyright (c) 2021 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#pragma once - -#include "../../common/napi/n_exporter.h" - -namespace OHOS { -namespace DistributedFS { -namespace ModuleFile { -enum COMMON_NUM { - ZERO = 0, - ONE = 1, - TWO = 2, - THOUSAND = 1000, - MILLION = 1000000, -}; - -struct FileInfo { - int32_t length = 0; - int64_t lastModifiedTime = 0; - std::string type = ""; - std::string uri = ""; -}; - -struct AsyncAccessCallbackInfo { - napi_env env = nullptr; - napi_async_work asyncWork = nullptr; - napi_ref callback[3] = { 0 }; - std::string url = ""; - int errorType = -1; - int result = -100; -}; - -struct AsyncMkdirCallbackInfo { - napi_env env = nullptr; - napi_async_work asyncWork = nullptr; - napi_ref callback[3] = { 0 }; - bool recursive = false; - std::string url = ""; - int result = -100; - int errorType = -1; -}; - -struct AsyncRmdirCallbackInfo { - napi_env env = nullptr; - napi_async_work asyncWork = nullptr; - napi_ref callback[3] = { 0 }; - bool recursive = false; - std::string url = ""; - int result = -100; - int errorType = -1; -}; - -struct AsyncGetCallbackInfo { - napi_env env = nullptr; - napi_async_work asyncWork = nullptr; - napi_ref callback[3] = { 0 }; - bool recursive = false; - std::string url = ""; - std::string originUri = ""; - int result = -100; - int errorType = -1; - int32_t length = 0; - int64_t lastMT = 0; - std::string type = ""; - std::vector subFiles; -}; - -struct AsyncListCallbackInfo { - napi_env env = nullptr; - napi_async_work asyncWork = nullptr; - napi_ref callback[3] = { 0 }; - bool recursive = false; - std::string url = ""; - std::string originUri = ""; - int result = -100; - int errorType = -1; - std::vector fileList; -}; - -struct AsyncCopyCallbackInfo { - napi_env env = nullptr; - napi_async_work asyncWork = nullptr; - napi_ref callback[3] = { 0 }; - std::string url = ""; - std::string urlDst = ""; - std::string originDst = ""; - int result = -100; - int errorType = -1; -}; - -struct AsyncMoveCallbackInfo { - napi_env env = nullptr; - napi_async_work asyncWork = nullptr; - napi_ref callback[3] = { 0 }; - std::string url = ""; - std::string urlDst = ""; - std::string originDst = ""; - int result = -100; - int errorType = -1; -}; - -struct AsyncDeleteCallbackInfo { - napi_env env = nullptr; - napi_async_work asyncWork = nullptr; - napi_ref callback[3] = { 0 }; - std::string url = ""; - int result = -100; - int errorType = -1; -}; - -struct AsyncWriteCallbackInfo { - napi_env env = nullptr; - napi_async_work asyncWork = nullptr; - napi_ref callback[3] = { 0 }; - std::string url = ""; - std::string text = ""; - bool append = false; - int result = -100; - int errorType = -1; -}; - -struct AsyncWriteBufferCallbackInfo { - napi_env env = nullptr; - napi_async_work asyncWork = nullptr; - napi_ref callback[3] = { 0 }; - std::string url = ""; - bool append = false; - int result = -100; - int errorType = -1; - int32_t length = 0; - int32_t position = 0; - void* buf = nullptr; - napi_ref bufferAddress = nullptr; -}; - -struct AsyncReadCallbackInfo { - napi_env env = nullptr; - napi_async_work asyncWork = nullptr; - napi_ref callback[3] = { 0 }; - std::string url = ""; - int result = -100; - int errorType = -1; - std::string contents = ""; -}; - -struct AsyncReadBufferCallbackInfo { - napi_env env = nullptr; - napi_async_work asyncWork = nullptr; - napi_ref callback[3] = { 0 }; - std::string url = ""; - int length = 0; - int position = 0; - int result = -100; - int errorType = -1; - int32_t len = 0; - std::string contents = ""; -}; - -class FileNExporter final : public NExporter { -public: - inline static const std::string className_ = "File"; - static napi_value Mkdir(napi_env env, napi_callback_info info); - static napi_value Rmdir(napi_env env, napi_callback_info info); - static napi_value Get(napi_env env, napi_callback_info info); - static napi_value List(napi_env env, napi_callback_info info); - static napi_value Copy(napi_env env, napi_callback_info info); - static napi_value Move(napi_env env, napi_callback_info info); - static napi_value Delete(napi_env env, napi_callback_info info); - static napi_value Access(napi_env env, napi_callback_info info); - static napi_value WriteText(napi_env env, napi_callback_info info); - static napi_value WriteArrayBuffer(napi_env env, napi_callback_info info); - static napi_value ReadText(napi_env env, napi_callback_info info); - static napi_value ReadArrayBuffer(napi_env env, napi_callback_info info); - - bool Export() override; - - std::string GetClassName() override; - - FileNExporter(napi_env env, napi_value exports); - ~FileNExporter() override; -}; -} // namespace ModuleFile -} // namespace DistributedFS -} // namespace OHOS \ No newline at end of file diff --git a/interfaces/kits/js/src/mod_file/common_func.cpp b/interfaces/kits/js/src/mod_file/common_func.cpp deleted file mode 100644 index 71b76d3..0000000 --- a/interfaces/kits/js/src/mod_file/common_func.cpp +++ /dev/null @@ -1,59 +0,0 @@ -/* - * Copyright (c) 2021 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#include "common_func.h" - -#include "../common/napi/n_func_arg.h" - -namespace OHOS { -namespace DistributedFS { -namespace ModuleFile { -using namespace std; - -tuple CommonFunc::GetCallbackHandles(napi_env env, napi_value object) -{ - bool succ = false; - NVal prop = NVal(env, object); - napi_value successProp, failProp, completeProp; - napi_ref successHandle = nullptr; - napi_ref failHandle = nullptr; - napi_ref completeHandle = nullptr; - string success = "success"; - string fail = "fail"; - string complete = "complete"; - - successProp = prop.GetProp(success).val_; - if (successProp != nullptr) { - napi_create_reference(env, successProp, 1, &successHandle); - succ = true; - } - - failProp = prop.GetProp(fail).val_; - if (succ && failProp != nullptr) { - napi_create_reference(env, failProp, 1, &failHandle); - succ = true; - } - - completeProp = prop.GetProp(complete).val_; - if (succ && completeProp != nullptr) { - napi_create_reference(env, completeProp, 1, &completeHandle); - succ = true; - } - - return { succ, successHandle, failHandle, completeHandle }; -} -} // namespace ModuleFile -} // namespace DistributedFS -} // namespace OHOS diff --git a/interfaces/kits/js/src/mod_file/common_func.h b/interfaces/kits/js/src/mod_file/common_func.h deleted file mode 100644 index 19924c5..0000000 --- a/interfaces/kits/js/src/mod_file/common_func.h +++ /dev/null @@ -1,33 +0,0 @@ -/* - * Copyright (c) 2021 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#pragma once - -#include "../common/napi/n_val.h" - -namespace OHOS { -namespace DistributedFS { -namespace ModuleFile { -const std::string FUNC_PROP_SUCCESS = "success"; -const std::string FUNC_PROP_FAIL = "fail"; -const std::string FUNC_PROP_COMPLETE = "complete"; - -struct CommonFunc { - static std::tuple GetCallbackHandles(napi_env env, - napi_value object); -}; -} // namespace ModuleFile -} // namespace DistributedFS -} // namespace OHOS \ No newline at end of file diff --git a/interfaces/kits/js/src/mod_file/module.cpp b/interfaces/kits/js/src/mod_file/module.cpp deleted file mode 100644 index 9b0c026..0000000 --- a/interfaces/kits/js/src/mod_file/module.cpp +++ /dev/null @@ -1,46 +0,0 @@ -/* - * Copyright (c) 2021 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#include -#include - -#include "../common/log.h" -#include "class_file/file_n_exporter.h" - -using namespace std; - -namespace OHOS { -namespace DistributedFS { -namespace ModuleFile { -static napi_value Export(napi_env env, napi_value exports) -{ - std::vector > products; - products.emplace_back(make_unique(env, exports)); - - for (auto &&product : products) { - if (!product->Export()) { - HILOGE("INNER BUG. Failed to export class %{public}s for module file", product->GetClassName().c_str()); - return nullptr; - } else { - HILOGE("Class %{public}s for module file has been exported", product->GetClassName().c_str()); - } - } - return exports; -} - -NAPI_MODULE(file, Export) -} // namespace ModuleFile -} // namespace DistributedFS -} // namespace OHOS \ No newline at end of file diff --git a/interfaces/kits/js/src/mod_fileio/class_constants/constants.cpp b/interfaces/kits/js/src/mod_fileio/class_constants/constants.cpp deleted file mode 100644 index 0cde079..0000000 --- a/interfaces/kits/js/src/mod_fileio/class_constants/constants.cpp +++ /dev/null @@ -1,189 +0,0 @@ -/* - * Copyright (c) 2021 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#include "constants.h" -#include -#include -#include -#include -#include -#include -#include -#include -#include "securec.h" - -#include "../../common/log.h" -#include "../../common/napi/n_class.h" -#include "../../common/napi/n_func_arg.h" -#include "../../common/uni_error.h" - -namespace OHOS { -namespace DistributedFS { -namespace ModuleFileIO { -using namespace std; - -napi_value Constants::Constructor(napi_env env, napi_callback_info info) -{ - NFuncArg funcArg(env, info); - - if (!funcArg.InitArgs(NARG_CNT::ZERO)) { - UniError(EINVAL).ThrowErr(env, "Number of arguments unmatched"); - return nullptr; - } - return funcArg.GetThisVar(); -} - -bool Constants::Export() -{ - // access - napi_value F_OK_ = nullptr; - napi_create_int32(exports_.env_, F_OK, &F_OK_); // 0 F_OK - napi_value R_OK_ = nullptr; - napi_create_int32(exports_.env_, R_OK, &R_OK_); // 4 R_OK - napi_value W_OK_ = nullptr; - napi_create_int32(exports_.env_, W_OK, &W_OK_); // 2 W_OK - napi_value X_OK_ = nullptr; - napi_create_int32(exports_.env_, X_OK, &X_OK_); // 1 X_OK - // open - napi_value O_RDONLY_ = nullptr; - napi_create_int32(exports_.env_, O_RDONLY, &O_RDONLY_); // 0 O_RDONLY - napi_value O_WRONLY_ = nullptr; - napi_create_int32(exports_.env_, O_WRONLY, &O_WRONLY_); // 1 O_WRONLY - napi_value O_RDWR_ = nullptr; - napi_create_int32(exports_.env_, O_RDWR, &O_RDWR_); // 2 O_RDWR - napi_value O_CREAT_ = nullptr; - napi_create_int32(exports_.env_, O_CREAT, &O_CREAT_); // 0o100 O_CREAT - napi_value O_EXCL_ = nullptr; - napi_create_int32(exports_.env_, O_EXCL, &O_EXCL_); // 0o200 O_EXCL - napi_value O_TRUNC_ = nullptr; - napi_create_int32(exports_.env_, O_TRUNC, &O_TRUNC_); // 0o1000 O_TRUNC - napi_value O_APPEND_ = nullptr; - napi_create_int32(exports_.env_, O_APPEND, &O_APPEND_); // 0o2000 O_APPEND - napi_value O_NONBLOCK_ = nullptr; - napi_create_int32(exports_.env_, O_NONBLOCK, &O_NONBLOCK_); // 0o4000 O_NONBLOCK - napi_value O_DIRECTORY_ = nullptr; - napi_create_int32(exports_.env_, O_DIRECTORY, &O_DIRECTORY_); // 0o200000 O_DIRECTORY - napi_value O_NOFOLLOW_ = nullptr; - napi_create_int32(exports_.env_, O_NOFOLLOW, &O_NOFOLLOW_); // 0o400000 O_NOFOLLOW - napi_value O_SYNC_ = nullptr; - napi_create_int32(exports_.env_, O_SYNC, &O_SYNC_); // 0o4010000 O_SYNC - - // stat - napi_value S_IFMT_ = nullptr; - napi_create_int32(exports_.env_, S_IFMT, &S_IFMT_); // 0o170000 S_IFMT - napi_value S_IFSOCK_ = nullptr; - napi_create_int32(exports_.env_, S_IFSOCK, &S_IFSOCK_); // 0o140000 S_IFSOCK - napi_value S_IFLNK_ = nullptr; - napi_create_int32(exports_.env_, S_IFLNK, &S_IFLNK_); // 0o120000 S_IFLNK - napi_value S_IFREG_ = nullptr; - napi_create_int32(exports_.env_, S_IFREG, &S_IFREG_); // 0o100000 S_IFREG - napi_value S_IFBLK_ = nullptr; - napi_create_int32(exports_.env_, S_IFBLK, &S_IFBLK_); // 0o060000 S_IFBLK - napi_value S_IFDIR_ = nullptr; - napi_create_int32(exports_.env_, S_IFDIR, &S_IFDIR_); // 0o040000 S_IFDIR - napi_value S_IFCHR_ = nullptr; - napi_create_int32(exports_.env_, S_IFCHR, &S_IFCHR_); // 0o020000 S_IFCHR - napi_value S_IFIFO_ = nullptr; - napi_create_int32(exports_.env_, S_IFIFO, &S_IFIFO_); // 0o010000 S_IFIFO - napi_value S_IRWXU_ = nullptr; - napi_create_int32(exports_.env_, S_IRWXU, &S_IRWXU_); // 0o0700 S_IRWXU - napi_value S_IRUSR_ = nullptr; - napi_create_int32(exports_.env_, S_IRUSR, &S_IRUSR_); // 0o0400 S_IRUSR - napi_value S_IWUSR_ = nullptr; - napi_create_int32(exports_.env_, S_IWUSR, &S_IWUSR_); // 0o0200 S_IWUSR - napi_value S_IXUSR_ = nullptr; - napi_create_int32(exports_.env_, S_IXUSR, &S_IXUSR_); // 0o0100 S_IXUSR - napi_value S_IRWXG_ = nullptr; - napi_create_int32(exports_.env_, S_IRWXG, &S_IRWXG_); // 0o0070 S_IRWXG - napi_value S_IRGRP_ = nullptr; - napi_create_int32(exports_.env_, S_IRGRP, &S_IRGRP_); // 0o0040 S_IRGRP - napi_value S_IWGRP_ = nullptr; - napi_create_int32(exports_.env_, S_IWGRP, &S_IWGRP_); // 0o0020 S_IWGRP - napi_value S_IXGRP_ = nullptr; - napi_create_int32(exports_.env_, S_IXGRP, &S_IXGRP_); // 0o0010 S_IXGRP - napi_value S_IRWXO_ = nullptr; - napi_create_int32(exports_.env_, S_IRWXO, &S_IRWXO_); // 0o0007 S_IRWXO - napi_value S_IROTH_ = nullptr; - napi_create_int32(exports_.env_, S_IROTH, &S_IROTH_); // 0o0004 S_IROTH - napi_value S_IWOTH_ = nullptr; - napi_create_int32(exports_.env_, S_IWOTH, &S_IWOTH_); // 0o0002 S_IWOTH - napi_value S_IXOTH_ = nullptr; - napi_create_int32(exports_.env_, S_IXOTH, &S_IXOTH_); // 0o0001 S_IXOTH - - vector props = { - NVal::DeclareNapiStaticProperty("F_OK", F_OK_), - NVal::DeclareNapiStaticProperty("R_OK", R_OK_), - NVal::DeclareNapiStaticProperty("W_OK", W_OK_), - NVal::DeclareNapiStaticProperty("X_OK", X_OK_), - NVal::DeclareNapiStaticProperty("O_RDONLY", O_RDONLY_), - NVal::DeclareNapiStaticProperty("O_WRONLY", O_WRONLY_), - NVal::DeclareNapiStaticProperty("O_RDWR", O_RDWR_), - NVal::DeclareNapiStaticProperty("O_CREAT", O_CREAT_), - NVal::DeclareNapiStaticProperty("O_EXCL", O_EXCL_), - NVal::DeclareNapiStaticProperty("O_TRUNC", O_TRUNC_), - NVal::DeclareNapiStaticProperty("O_APPEND", O_APPEND_), - NVal::DeclareNapiStaticProperty("O_NONBLOCK", O_NONBLOCK_), - NVal::DeclareNapiStaticProperty("O_DIRECTORY", O_DIRECTORY_), - NVal::DeclareNapiStaticProperty("O_NOFOLLOW", O_NOFOLLOW_), - NVal::DeclareNapiStaticProperty("O_SYNC", O_SYNC_), - NVal::DeclareNapiStaticProperty("S_IFMT", S_IFMT_), - NVal::DeclareNapiStaticProperty("S_IFSOCK", S_IFSOCK_), - NVal::DeclareNapiStaticProperty("S_IFLNK", S_IFLNK_), - NVal::DeclareNapiStaticProperty("S_IFREG", S_IFREG_), - NVal::DeclareNapiStaticProperty("S_IFBLK", S_IFBLK_), - NVal::DeclareNapiStaticProperty("S_IFDIR", S_IFDIR_), - NVal::DeclareNapiStaticProperty("S_IFCHR", S_IFCHR_), - NVal::DeclareNapiStaticProperty("S_IFIFO", S_IFIFO_), - NVal::DeclareNapiStaticProperty("S_IRWXU", S_IRWXU_), - NVal::DeclareNapiStaticProperty("S_IRUSR", S_IRUSR_), - NVal::DeclareNapiStaticProperty("S_IWUSR", S_IWUSR_), - NVal::DeclareNapiStaticProperty("S_IXUSR", S_IXUSR_), - NVal::DeclareNapiStaticProperty("S_IRWXG", S_IRWXG_), - NVal::DeclareNapiStaticProperty("S_IRGRP", S_IRGRP_), - NVal::DeclareNapiStaticProperty("S_IWGRP", S_IWGRP_), - NVal::DeclareNapiStaticProperty("S_IXGRP", S_IXGRP_), - NVal::DeclareNapiStaticProperty("S_IRWXO", S_IRWXO_), - NVal::DeclareNapiStaticProperty("S_IROTH", S_IROTH_), - NVal::DeclareNapiStaticProperty("S_IWOTH", S_IWOTH_), - NVal::DeclareNapiStaticProperty("S_IXOTH", S_IXOTH_), - }; - - string className = GetClassName(); - bool succ = false; - napi_value classValue = nullptr; - tie(succ, classValue) = NClass::DefineClass(exports_.env_, className, Constants::Constructor, std::move(props)); - if (!succ) { - UniError(EIO).ThrowErr(exports_.env_, "INNER BUG. Failed to define class"); - return false; - } - succ = NClass::SaveClass(exports_.env_, className, classValue); - if (!succ) { - UniError(EIO).ThrowErr(exports_.env_, "INNER BUG. Failed to save class"); - return false; - } - - return exports_.AddProp(className, classValue); -} - -string Constants::GetClassName() -{ - return Constants::className_; -} - -Constants::Constants(napi_env env, napi_value exports) : NExporter(env, exports) {} -Constants::~Constants() {} -} // namespace ModuleFileIO -} // namespace DistributedFS -} // namespace OHOS diff --git a/interfaces/kits/js/src/mod_fileio/class_constants/constants.h b/interfaces/kits/js/src/mod_fileio/class_constants/constants.h deleted file mode 100644 index 63033a7..0000000 --- a/interfaces/kits/js/src/mod_fileio/class_constants/constants.h +++ /dev/null @@ -1,38 +0,0 @@ -/* - * Copyright (c) 2021 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#ifndef INTERFACES_KITS1_BAD_JS_SRC_MOD_FILEIO_CLASS_CONSTANTS_CONSTANTS_H -#define INTERFACES_KITS1_BAD_JS_SRC_MOD_FILEIO_CLASS_CONSTANTS_CONSTANTS_H - -#include "../../common/napi/n_exporter.h" - -namespace OHOS { -namespace DistributedFS { -namespace ModuleFileIO { -class Constants final : public NExporter { -public: - inline static const std::string className_ = "constants"; - bool Export() override; - std::string GetClassName() override; - - static napi_value Constructor(napi_env env, napi_callback_info info); - - Constants(napi_env env, napi_value exports); - ~Constants() override; -}; -} // namespace ModuleFileIO -} // namespace DistributedFS -} // namespace OHOS -#endif \ No newline at end of file diff --git a/interfaces/kits/js/src/mod_fileio/class_dir/dir_entity.h b/interfaces/kits/js/src/mod_fileio/class_dir/dir_entity.h deleted file mode 100644 index b6b2eb7..0000000 --- a/interfaces/kits/js/src/mod_fileio/class_dir/dir_entity.h +++ /dev/null @@ -1,32 +0,0 @@ -/* - * Copyright (c) 2021 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#ifndef INTERFACES_KITS_JS_SRC_MOD_FILEIO_CLASS_DIR_DIR_ENTITY_H -#define INTERFACES_KITS_JS_SRC_MOD_FILEIO_CLASS_DIR_DIR_ENTITY_H - -#include -#include - -namespace OHOS { -namespace DistributedFS { -namespace ModuleFileIO { -struct DirEntity { - std::mutex lock_; - std::unique_ptr > dir_ = { nullptr, closedir }; -}; -} // namespace ModuleFileIO -} // namespace DistributedFS -} // namespace OHOS -#endif // INTERFACES_KITS_JS_SRC_MOD_FILEIO_CLASS_DIR_DIR_ENTITY_H \ No newline at end of file diff --git a/interfaces/kits/js/src/mod_fileio/class_dir/dir_n_exporter.cpp b/interfaces/kits/js/src/mod_fileio/class_dir/dir_n_exporter.cpp deleted file mode 100644 index 9faeb77..0000000 --- a/interfaces/kits/js/src/mod_fileio/class_dir/dir_n_exporter.cpp +++ /dev/null @@ -1,463 +0,0 @@ -/* - * Copyright (c) 2021-2022 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#include "dir_n_exporter.h" - -#include -#include -#include -#include -#include -#include "securec.h" - -#include "../../common/napi/n_async/n_async_work_callback.h" -#include "../../common/napi/n_async/n_async_work_promise.h" -#include "../../common/napi/n_class.h" -#include "../../common/napi/n_func_arg.h" -#include "../class_dirent/dirent_entity.h" -#include "../class_dirent/dirent_n_exporter.h" -#include "../common_func.h" -#include "dir_entity.h" - -namespace OHOS { -namespace DistributedFS { -namespace ModuleFileIO { -using namespace std; - -static DirEntity *GetDirEntity(napi_env env, napi_callback_info info) -{ - NFuncArg funcArg(env, info); - if (!funcArg.InitArgs(NARG_CNT::ZERO)) { - UniError(EINVAL).ThrowErr(env, "Number of arguments unmatched"); - return nullptr; - } - - auto dirEntity = NClass::GetEntityOf(env, funcArg.GetThisVar()); - if (!dirEntity) { - UniError(EIO).ThrowErr(env, "Cannot get entity of Dir"); - return nullptr; - } - return dirEntity; -} - -napi_value DirNExporter::CloseSync(napi_env env, napi_callback_info info) -{ - DirEntity *dirEntity = GetDirEntity(env, info); - if (!dirEntity || !dirEntity->dir_) { - UniError(EBADF).ThrowErr(env, "Dir has been closed yet"); - return nullptr; - } - - dirEntity->dir_.reset(); - return nullptr; -} - -napi_value DirNExporter::Close(napi_env env, napi_callback_info info) -{ - NFuncArg funcArg(env, info); - if (!funcArg.InitArgs(NARG_CNT::ZERO, NARG_CNT::ONE)) { - UniError(EINVAL).ThrowErr(env, "Number of arguments unmatched"); - return nullptr; - } - - auto dirEntity = NClass::GetEntityOf(env, funcArg.GetThisVar()); - if (!dirEntity) { - UniError(EIO).ThrowErr(env, "Cannot get entity of Dir"); - return nullptr; - } - - if (!dirEntity || !dirEntity->dir_) { - UniError(EBADF).ThrowErr(env, "Dir has been closed yet"); - return nullptr; - } - - auto cbExec = [dirEntity](napi_env env) -> UniError { - DIR *dir = dirEntity->dir_.release(); - int ret = closedir(dir); - if (ret == -1) { - return UniError(errno); - } else { - return UniError(ERRNO_NOERR); - } - }; - auto cbCompl = [](napi_env env, UniError err) -> NVal { - if (err) { - return { env, err.GetNapiErr(env) }; - } else { - return NVal::CreateUndefined(env); - } - }; - - NVal thisVar(env, funcArg.GetThisVar()); - string procedureName = "fileioDirClose"; - if (funcArg.GetArgc() == NARG_CNT::ZERO) { - return NAsyncWorkPromise(env, thisVar).Schedule(procedureName, cbExec, cbCompl).val_; - } else { - NVal cb(env, funcArg[NARG_POS::FIRST]); - return NAsyncWorkCallback(env, thisVar, cb).Schedule(procedureName, cbExec, cbCompl).val_; - } -} - -struct DirReadArgs { - NRef thisptrRef_; - struct dirent dirRes = { - .d_ino = 0, - .d_off = 0, - .d_reclen = 0, - .d_type = 0, - .d_name = { '\0' }, - }; - explicit DirReadArgs(NVal obj) : thisptrRef_(obj) {} -}; - -static NVal DoReadCompile(napi_env env, UniError err, shared_ptr arg) -{ - if (err) { - return { env, err.GetNapiErr(env) }; - } else { - napi_value objDirent = NClass::InstantiateClass(env, DirentNExporter::className_, {}); - if (!objDirent) { - return { env, UniError(EINVAL).GetNapiErr(env) }; - } - auto direntEntity = NClass::GetEntityOf(env, objDirent); - if (!direntEntity) { - return { env, UniError(EINVAL).GetNapiErr(env) }; - } - - if (strlen(arg->dirRes.d_name) == 0) { - return { env, NVal::CreateUndefined(env).val_ }; - } else { - direntEntity->dirent_ = arg->dirRes; - return { env, objDirent }; - } - } -} - -napi_value DirNExporter::Read(napi_env env, napi_callback_info info) -{ - NFuncArg funcArg(env, info); - if (!funcArg.InitArgs(NARG_CNT::ZERO, NARG_CNT::ONE)) { - UniError(EINVAL).ThrowErr(env, "Number of arguments unmatched"); - return nullptr; - } - - auto dirEntity = NClass::GetEntityOf(env, funcArg.GetThisVar()); - if (!dirEntity) { - UniError(EIO).ThrowErr(env, "Cannot get entity of Dir"); - return nullptr; - } - - if (!dirEntity || !dirEntity->dir_) { - UniError(EBADF).ThrowErr(env, "Dir has been closed yet"); - return nullptr; - } - - DIR *dir = dirEntity->dir_.get(); - auto arg = make_shared(NVal(env, funcArg.GetThisVar())); - auto cbExec = [arg, dir, dirEntity](napi_env env) -> UniError { - struct dirent tmpDirent; - lock_guard(dirEntity->lock_); - errno = 0; - dirent *res = nullptr; - do { - res = readdir(dir); - if (res == nullptr && errno) { - return UniError(errno); - } else if (res == nullptr) { - return UniError(ERRNO_NOERR); - } else if (string(res->d_name) == "." || string(res->d_name) == "..") { - continue; - } else { - tmpDirent = *res; - break; - } - } while (true); - - arg->dirRes = tmpDirent; - return UniError(ERRNO_NOERR); - }; - auto cbCompl = [arg](napi_env env, UniError err) -> NVal { - return DoReadCompile(env, err, arg); - }; - NVal thisVar(env, funcArg.GetThisVar()); - if (funcArg.GetArgc() == NARG_CNT::ZERO) { - return NAsyncWorkPromise(env, thisVar).Schedule("fileioDirRead", cbExec, cbCompl).val_; - } else { - NVal cb(env, funcArg[NARG_POS::FIRST]); - return NAsyncWorkCallback(env, thisVar, cb).Schedule("fileioDirRead", cbExec, cbCompl).val_; - } -} - -napi_value DirNExporter::ReadSync(napi_env env, napi_callback_info info) -{ - NFuncArg funcArg(env, info); - if (!funcArg.InitArgs(NARG_CNT::ZERO)) { - UniError(EINVAL).ThrowErr(env, "Number of arguments unmatched"); - return nullptr; - } - - DirEntity *dirEntity = GetDirEntity(env, info); - if (!dirEntity || !dirEntity->dir_) { - UniError(EBADF).ThrowErr(env, "Dir has been closed yet"); - return nullptr; - } - - struct dirent tmpDirent; - { - lock_guard(dirEntity->lock_); - errno = 0; - dirent *res = nullptr; - do { - res = readdir(dirEntity->dir_.get()); - if (res == nullptr && errno) { - UniError(errno).ThrowErr(env); - return nullptr; - } else if (res == nullptr) { - return NVal::CreateUndefined(env).val_; - } else if (string(res->d_name) == "." || string(res->d_name) == "..") { - continue; - } else { - tmpDirent = *res; - break; - } - } while (true); - } - - napi_value objDirent = NClass::InstantiateClass(env, DirentNExporter::className_, {}); - if (!objDirent) { - return nullptr; - } - - auto direntEntity = NClass::GetEntityOf(env, objDirent); - if (!direntEntity) { - return nullptr; - } - direntEntity->dirent_ = tmpDirent; - - return objDirent; -} - -struct DirListFileArgs { - vector dirents; - explicit DirListFileArgs() - { - dirents = vector(); - } - ~DirListFileArgs() = default; -}; - -static DirEntity *CheckDirEntity(napi_env env, napi_value dir_entity) -{ - auto dirEntity = NClass::GetEntityOf(env, dir_entity); - if (!dirEntity) { - UniError(EIO).ThrowErr(env, "Cannot get entity of Dir"); - return nullptr; - } - - if (!dirEntity || !dirEntity->dir_) { - UniError(EBADF).ThrowErr(env, "Dir has been closed yet"); - return nullptr; - } - return dirEntity; -} - -static tuple ParseJsListNum(napi_env env, napi_value listNumFromJs) -{ - auto [succ, listNum] = NVal(env, listNumFromJs).ToInt32(); - return {succ, listNum}; -} - -static napi_value DoListFileVector2NV(napi_env env, vector dirents) -{ - napi_value res = nullptr; - napi_create_array(env, &res); - for (size_t i = 0; i < dirents.size(); i++) { - napi_value objDirent = NClass::InstantiateClass(env, DirentNExporter::className_, {}); - if (!objDirent) { - UniError(EINVAL).ThrowErr(env); - return nullptr; - } - auto direntEntity = NClass::GetEntityOf(env, objDirent); - if (!direntEntity) { - UniError(EINVAL).ThrowErr(env); - return nullptr; - } - direntEntity->dirent_ = dirents[i]; - napi_set_element(env, res, i, objDirent); - } - return res; -} - -static NVal DoListFileCompile(napi_env env, UniError err, shared_ptr arg) -{ - if (err) { - return { env, err.GetNapiErr(env) }; - } else { - return { env, DoListFileVector2NV(env, arg->dirents) }; - } -} - -napi_value DirNExporter::ListFile(napi_env env, napi_callback_info info) -{ - NFuncArg funcArg(env, info); - if (!funcArg.InitArgs(NARG_CNT::ONE, NARG_CNT::TWO)) { - UniError(EINVAL).ThrowErr(env, "Number of arguments unmatched"); - return nullptr; - } - auto dirEntity = CheckDirEntity(env, funcArg.GetThisVar()); - if (!dirEntity) { - return nullptr; - } - auto [succ, num] = ParseJsListNum(env, funcArg[NARG_POS::FIRST]); - if (!succ) { - UniError(EINVAL).ThrowErr(env, "Invalid listNum"); - return nullptr; - } - - DIR *dir = dirEntity->dir_.get(); - auto arg = make_shared(); - int listNum = num; - auto cbExec = [arg, dir, dirEntity, listNum](napi_env env) -> UniError { - lock_guard(dirEntity->lock_); - errno = 0; - dirent *res = nullptr; - int listCount = 0; - do { - res = readdir(dir); - if (res == nullptr && errno) { - return UniError(errno); - } else if (res == nullptr) { - return UniError(ERRNO_NOERR); - } else if (string(res->d_name) == "." || string(res->d_name) == "..") { - continue; - } else { - arg->dirents.push_back(*res); - listCount++; - } - } while (listCount < listNum || listNum == 0); - return UniError(ERRNO_NOERR); - }; - auto cbCompl = [arg](napi_env env, UniError err) -> NVal { - return DoListFileCompile(env, err, arg); - }; - NVal thisVar(env, funcArg.GetThisVar()); - - if (funcArg.GetArgc() == NARG_CNT::ONE) { - return NAsyncWorkPromise(env, thisVar).Schedule(listfileProcedureName, cbExec, cbCompl).val_; - } else { - NVal cb(env, funcArg[NARG_POS::SECOND]); - return NAsyncWorkCallback(env, thisVar, cb).Schedule(listfileProcedureName, cbExec, cbCompl).val_; - } -} - -napi_value DirNExporter::ListFileSync(napi_env env, napi_callback_info info) -{ - NFuncArg funcArg(env, info); - if (!funcArg.InitArgs(NARG_CNT::ONE)) { - UniError(EINVAL).ThrowErr(env, "Number of arguments unmatched"); - return nullptr; - } - auto dirEntity = CheckDirEntity(env, funcArg.GetThisVar()); - if (!dirEntity) { - return nullptr; - } - auto [succ, listNum] = ParseJsListNum(env, funcArg[NARG_POS::FIRST]); - if (!succ) { - UniError(EINVAL).ThrowErr(env, "Invalid listNum"); - return nullptr; - } - - vector dirents; - { - lock_guard(dirEntity->lock_); - errno = 0; - dirent *res = nullptr; - int listCount = 0; - auto dir = dirEntity->dir_.get(); - do { - res = readdir(dir); - if (res == nullptr && errno) { - UniError(errno).ThrowErr(env); - return nullptr; - } else if (res == nullptr) { - break; - } else if (string(res->d_name) == "." || string(res->d_name) == "..") { - continue; - } else { - dirents.push_back(*res); - listCount++; - } - } while (listCount < listNum || listNum == 0); - } - return DoListFileVector2NV(env, dirents); -} - -napi_value DirNExporter::Constructor(napi_env env, napi_callback_info info) -{ - NFuncArg funcArg(env, info); - if (!funcArg.InitArgs(NARG_CNT::ZERO)) { - UniError(EINVAL).ThrowErr(env, "Number of arguments unmatched"); - return nullptr; - } - - auto dirEntity = make_unique(); - if (!NClass::SetEntityFor(env, funcArg.GetThisVar(), move(dirEntity))) { - UniError(EIO).ThrowErr(env, "INNER BUG. Failed to wrap entity for obj dir"); - return nullptr; - } - return funcArg.GetThisVar(); -} - -bool DirNExporter::Export() -{ - vector props = { - NVal::DeclareNapiFunction("readSync", ReadSync), - NVal::DeclareNapiFunction("closeSync", CloseSync), - NVal::DeclareNapiFunction("listfileSync", ListFileSync), - NVal::DeclareNapiFunction("read", Read), - NVal::DeclareNapiFunction("close", Close), - NVal::DeclareNapiFunction("listfile", ListFile), - }; - - string className = GetClassName(); - - bool succ = false; - napi_value classValue = nullptr; - tie(succ, classValue) = NClass::DefineClass(exports_.env_, className, DirNExporter::Constructor, std::move(props)); - if (!succ) { - UniError(EIO).ThrowErr(exports_.env_, "INNER BUG. Failed to define class Dirent"); - return false; - } - - succ = NClass::SaveClass(exports_.env_, className, classValue); - if (!succ) { - UniError(EIO).ThrowErr(exports_.env_, "INNER BUG. Failed to save class Dirent"); - return false; - } - - return exports_.AddProp(className, classValue); -} - -string DirNExporter::GetClassName() -{ - return DirNExporter::className_; -} - -DirNExporter::DirNExporter(napi_env env, napi_value exports) : NExporter(env, exports) {} - -DirNExporter::~DirNExporter() {} -} // namespace ModuleFileIO -} // namespace DistributedFS -} // namespace OHOS \ No newline at end of file diff --git a/interfaces/kits/js/src/mod_fileio/class_dir/dir_n_exporter.h b/interfaces/kits/js/src/mod_fileio/class_dir/dir_n_exporter.h deleted file mode 100644 index 66f1ddc..0000000 --- a/interfaces/kits/js/src/mod_fileio/class_dir/dir_n_exporter.h +++ /dev/null @@ -1,48 +0,0 @@ -/* - * Copyright (c) 2021-2022 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#ifndef INTERFACES_KITS1_BAD_JS_SRC_MOD_FILEIO_CLASS_DIR_DIR_N_EXPORTER_H -#define INTERFACES_KITS1_BAD_JS_SRC_MOD_FILEIO_CLASS_DIR_DIR_N_EXPORTER_H - -#include - -#include "../../common/napi/n_exporter.h" - -namespace OHOS { -namespace DistributedFS { -namespace ModuleFileIO { -class DirNExporter final : public NExporter { -public: - inline static const std::string className_ = "Dir"; - - bool Export() override; - std::string GetClassName() override; - - static napi_value Constructor(napi_env env, napi_callback_info info); - - static napi_value CloseSync(napi_env env, napi_callback_info info); - static napi_value ReadSync(napi_env env, napi_callback_info info); - static napi_value ListFileSync(napi_env env, napi_callback_info info); - static napi_value Read(napi_env env, napi_callback_info info); - static napi_value Close(napi_env env, napi_callback_info info); - static napi_value ListFile(napi_env env, napi_callback_info info); - DirNExporter(napi_env env, napi_value exports); - ~DirNExporter() override; -}; -const std::string listfileProcedureName = "fileioDirListFile"; -} // namespace ModuleFileIO -} // namespace DistributedFS -} // namespace OHOS -#endif \ No newline at end of file diff --git a/interfaces/kits/js/src/mod_fileio/class_dirent/dirent_entity.h b/interfaces/kits/js/src/mod_fileio/class_dirent/dirent_entity.h deleted file mode 100644 index d92fa69..0000000 --- a/interfaces/kits/js/src/mod_fileio/class_dirent/dirent_entity.h +++ /dev/null @@ -1,30 +0,0 @@ -/* - * Copyright (c) 2021 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#ifndef INTERFACES_KITS_JS_SRC_MOD_FILEIO_CLASS_DIRENT_DIRENT_ENTITY_H -#define INTERFACES_KITS_JS_SRC_MOD_FILEIO_CLASS_DIRENT_DIRENT_ENTITY_H - -#include - -namespace OHOS { -namespace DistributedFS { -namespace ModuleFileIO { -struct DirentEntity { - struct dirent dirent_; -}; -} // namespace ModuleFileIO -} // namespace DistributedFS -} // namespace OHOS -#endif // INTERFACES_KITS_JS_SRC_MOD_FILEIO_CLASS_DIRENT_DIRENT_ENTITY_H \ No newline at end of file diff --git a/interfaces/kits/js/src/mod_fileio/class_dirent/dirent_n_exporter.cpp b/interfaces/kits/js/src/mod_fileio/class_dirent/dirent_n_exporter.cpp deleted file mode 100644 index ac671f5..0000000 --- a/interfaces/kits/js/src/mod_fileio/class_dirent/dirent_n_exporter.cpp +++ /dev/null @@ -1,170 +0,0 @@ -/* - * Copyright (c) 2021-2022 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#include "dirent_n_exporter.h" - -#include -#include -#include -#include -#include - -#include "securec.h" - -#include "../../common/log.h" -#include "../../common/napi/n_class.h" -#include "../../common/napi/n_func_arg.h" -#include "../../common/uni_error.h" -#include "../common_func.h" -#include "dirent_entity.h" - -namespace OHOS { -namespace DistributedFS { -namespace ModuleFileIO { -using namespace std; - -static DirentEntity *GetDirentEntity(napi_env env, napi_callback_info info) -{ - NFuncArg funcArg(env, info); - if (!funcArg.InitArgs(NARG_CNT::ZERO)) { - UniError(EINVAL).ThrowErr(env, "Number of arguments unmatched"); - return nullptr; - } - - auto direntEntity = NClass::GetEntityOf(env, funcArg.GetThisVar()); - if (!direntEntity) { - UniError(EIO).ThrowErr(env, "Cannot get entity of Dirent"); - return nullptr; - } - return direntEntity; -} - -static napi_value CheckDirentDType(napi_env env, napi_callback_info info, unsigned char dType) -{ - DirentEntity *direntEntity = GetDirentEntity(env, info); - if (!direntEntity) { - return nullptr; - } - - return NVal::CreateBool(env, direntEntity->dirent_.d_type == dType).val_; -} - -napi_value DirentNExporter::isBlockDevice(napi_env env, napi_callback_info info) -{ - return CheckDirentDType(env, info, DT_BLK); -} - -napi_value DirentNExporter::isCharacterDevice(napi_env env, napi_callback_info info) -{ - return CheckDirentDType(env, info, DT_CHR); -} - -napi_value DirentNExporter::isDirectory(napi_env env, napi_callback_info info) -{ - return CheckDirentDType(env, info, DT_DIR); -} - -napi_value DirentNExporter::isFIFO(napi_env env, napi_callback_info info) -{ - return CheckDirentDType(env, info, DT_FIFO); -} - -napi_value DirentNExporter::isFile(napi_env env, napi_callback_info info) -{ - return CheckDirentDType(env, info, DT_REG); -} - -napi_value DirentNExporter::isSocket(napi_env env, napi_callback_info info) -{ - return CheckDirentDType(env, info, DT_SOCK); -} - -napi_value DirentNExporter::isSymbolicLink(napi_env env, napi_callback_info info) -{ - return CheckDirentDType(env, info, DT_LNK); -} - -napi_value DirentNExporter::GetName(napi_env env, napi_callback_info info) -{ - DirentEntity *direntEntity = GetDirentEntity(env, info); - if (!direntEntity) { - return nullptr; - } - return NVal::CreateUTF8String(env, direntEntity->dirent_.d_name).val_; -} - -napi_value DirentNExporter::Constructor(napi_env env, napi_callback_info info) -{ - NFuncArg funcArg(env, info); - if (!funcArg.InitArgs(NARG_CNT::ZERO)) { - UniError(EINVAL).ThrowErr(env, "Number of arguments unmatched"); - return nullptr; - } - - auto direntEntity = make_unique(); - if (!NClass::SetEntityFor(env, funcArg.GetThisVar(), move(direntEntity))) { - UniError(EIO).ThrowErr(env, "INNER BUG. Failed to wrap entity for obj dirent"); - return nullptr; - } - return funcArg.GetThisVar(); -} - -bool DirentNExporter::Export() -{ - vector props = { - NVal::DeclareNapiFunction("isBlockDevice", isBlockDevice), - NVal::DeclareNapiFunction("isCharacterDevice", isCharacterDevice), - NVal::DeclareNapiFunction("isDirectory", isDirectory), - NVal::DeclareNapiFunction("isFIFO", isFIFO), - NVal::DeclareNapiFunction("isFile", isFile), - NVal::DeclareNapiFunction("isSocket", isSocket), - NVal::DeclareNapiFunction("isSymbolicLink", isSymbolicLink), - - NVal::DeclareNapiGetter("name", GetName), - }; - - string className = GetClassName(); - - bool succ = false; - napi_value classValue = nullptr; - tie(succ, classValue) = NClass::DefineClass(exports_.env_, - className, - DirentNExporter::Constructor, - std::move(props)); - if (!succ) { - UniError(EIO).ThrowErr(exports_.env_, "INNER BUG. Failed to define class Dirent"); - return false; - } - - succ = NClass::SaveClass(exports_.env_, className, classValue); - if (!succ) { - UniError(EIO).ThrowErr(exports_.env_, "INNER BUG. Failed to save class Dirent"); - return false; - } - - return exports_.AddProp(className, classValue); -} - -string DirentNExporter::GetClassName() -{ - return DirentNExporter::className_; -} - -DirentNExporter::DirentNExporter(napi_env env, napi_value exports) : NExporter(env, exports) {} - -DirentNExporter::~DirentNExporter() {} -} // namespace ModuleFileIO -} // namespace DistributedFS -} // namespace OHOS \ No newline at end of file diff --git a/interfaces/kits/js/src/mod_fileio/class_dirent/dirent_n_exporter.h b/interfaces/kits/js/src/mod_fileio/class_dirent/dirent_n_exporter.h deleted file mode 100644 index 0f60629..0000000 --- a/interfaces/kits/js/src/mod_fileio/class_dirent/dirent_n_exporter.h +++ /dev/null @@ -1,49 +0,0 @@ -/* - * Copyright (c) 2021 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#ifndef INTERFACES_KITS_JS_SRC_MOD_FILEIO_CLASS_DIRENT_DIRENT_N_EXPORTER_H -#define INTERFACES_KITS_JS_SRC_MOD_FILEIO_CLASS_DIRENT_DIRENT_N_EXPORTER_H - -#include "../../common/napi/n_exporter.h" - -namespace OHOS { -namespace DistributedFS { -namespace ModuleFileIO { -class DirentNExporter final : public NExporter { -public: - inline static const std::string className_ = "Dirent"; - - bool Export() override; - std::string GetClassName() override; - - static napi_value Constructor(napi_env env, napi_callback_info cbinfo); - - static napi_value isBlockDevice(napi_env env, napi_callback_info cbinfo); - static napi_value isCharacterDevice(napi_env env, napi_callback_info cbinfo); - static napi_value isDirectory(napi_env env, napi_callback_info cbinfo); - static napi_value isFIFO(napi_env env, napi_callback_info cbinfo); - static napi_value isFile(napi_env env, napi_callback_info cbinfo); - static napi_value isSocket(napi_env env, napi_callback_info cbinfo); - static napi_value isSymbolicLink(napi_env env, napi_callback_info cbinfo); - - static napi_value GetName(napi_env env, napi_callback_info cbinfo); - - DirentNExporter(napi_env env, napi_value exports); - ~DirentNExporter() override; -}; -} // namespace ModuleFileIO -} // namespace DistributedFS -} // namespace OHOS -#endif // INTERFACES_KITS_JS_SRC_MOD_FILEIO_CLASS_DIRENT_DIRENT_N_EXPORTER_H \ No newline at end of file diff --git a/interfaces/kits/js/src/mod_fileio/class_randomaccessfile/randomaccessfile_entity.h b/interfaces/kits/js/src/mod_fileio/class_randomaccessfile/randomaccessfile_entity.h deleted file mode 100644 index 2a7dcea..0000000 --- a/interfaces/kits/js/src/mod_fileio/class_randomaccessfile/randomaccessfile_entity.h +++ /dev/null @@ -1,33 +0,0 @@ -/* - * 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 INTERFACES_KITS_JS_SRC_MOD_FILEIO_CLASS_RANDOMACCESSFILE_RANDOMACCESSFILE_ENTITY_H -#define INTERFACES_KITS_JS_SRC_MOD_FILEIO_CLASS_RANDOMACCESSFILE_RANDOMACCESSFILE_ENTITY_H - -#include - -#include "../../common/file_helper/fd_guard.h" - -namespace OHOS { -namespace DistributedFS { -namespace ModuleFileIO { -struct RandomAccessFileEntity { - std::unique_ptr fd_ = { nullptr }; - size_t fpointer; -}; -} // namespace ModuleFileIO -} // namespace DistributedFS -} // namespace OHOS -#endif \ No newline at end of file diff --git a/interfaces/kits/js/src/mod_fileio/class_randomaccessfile/randomaccessfile_n_exporter.cpp b/interfaces/kits/js/src/mod_fileio/class_randomaccessfile/randomaccessfile_n_exporter.cpp deleted file mode 100644 index e27a1fe..0000000 --- a/interfaces/kits/js/src/mod_fileio/class_randomaccessfile/randomaccessfile_n_exporter.cpp +++ /dev/null @@ -1,416 +0,0 @@ -/* - * 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 "randomaccessfile_n_exporter.h" - -#include -#include -#include -#include -#include -#include - -#include "../../common/log.h" -#include "../../common/napi/n_async/n_async_work_callback.h" -#include "../../common/napi/n_async/n_async_work_promise.h" -#include "../../common/napi/n_class.h" -#include "../../common/napi/n_func_arg.h" -#include "../../common/uni_error.h" -#include "../common_func.h" -#include "randomaccessfile_entity.h" - -namespace OHOS { -namespace DistributedFS { -namespace ModuleFileIO { -using namespace std; - -static RandomAccessFileEntity *GetRAFEntity(napi_env env, napi_value raf_entity) -{ - auto rafEntity = NClass::GetEntityOf(env, raf_entity); - if (!rafEntity) { - UniError(EINVAL).ThrowErr(env, "Cannot get entity of RandomAccessFile"); - return nullptr; - } - if (!rafEntity->fd_) { - UniError(EINVAL).ThrowErr(env, "RandomAccessFile has been closed yet"); - return nullptr; - } - return rafEntity; -} - -static tuple ParseJsFP(napi_env env, napi_value FPFromJs) -{ - auto [succ, fp] = NVal(env, FPFromJs).ToInt32(); - return { succ, fp }; -} - -static tuple GetRAFReadArg(napi_env env, - napi_value ReadBuf, napi_value option) -{ - bool succ = false, hasPos = false; - void *buf = nullptr; - size_t len, pos, offset; - tie(succ, buf, len, hasPos, pos, offset) = CommonFunc::GetReadArg(env, ReadBuf, option); - if (!succ) { - return { false, nullptr, 0, false, 0, 0 }; - } - return { succ, buf, len, hasPos, pos, offset }; -} - -static tuple GetRAFWriteArg(napi_env env, - napi_value WriteBuf, napi_value option) -{ - bool succ = false, hasPos = false; - void *buf = nullptr; - size_t len, pos; - tie(succ, ignore, buf, len, hasPos, pos) = CommonFunc::GetWriteArg(env, WriteBuf, option); - if (!succ) { - return { false, nullptr, 0, false, 0 }; - } - return { succ, buf, len, hasPos, pos }; -} - -static size_t DoReadRAF(napi_env env, void* buf, size_t len, int fd, size_t pos) -{ - uv_loop_s *loop = nullptr; - uv_fs_t read_req; - napi_get_uv_event_loop(env, &loop); - uv_buf_t iov = uv_buf_init((char *)buf, len); - size_t ret = uv_fs_read(loop, &read_req, fd, &iov, 1, pos, NULL); - uv_fs_req_cleanup(&read_req); - return ret; -} - -static size_t DoWriteRAF(napi_env env, void* buf, size_t len, int fd, size_t pos) -{ - uv_loop_s *loop = nullptr; - uv_fs_t write_req; - napi_get_uv_event_loop(env, &loop); - uv_buf_t iov = uv_buf_init((char *)buf, len); - size_t ret = uv_fs_write(loop, &write_req, fd, &iov, 1, pos, NULL); - uv_fs_req_cleanup(&write_req); - return ret; -} - -napi_value RandomAccessFileNExporter::GetFD(napi_env env, napi_callback_info info) -{ - NFuncArg funcArg(env, info); - if (!funcArg.InitArgs(NARG_CNT::ZERO)) { - UniError(EINVAL).ThrowErr(env, "Number of arguments unmatched"); - return nullptr; - } - auto rafEntity = GetRAFEntity(env, funcArg.GetThisVar()); - if (!rafEntity) { - return nullptr; - } - return NVal::CreateInt32(env, rafEntity->fd_.get()->GetFD()).val_; -} - -napi_value RandomAccessFileNExporter::GetFPointer(napi_env env, napi_callback_info info) -{ - NFuncArg funcArg(env, info); - if (!funcArg.InitArgs(NARG_CNT::ZERO)) { - UniError(EINVAL).ThrowErr(env, "Number of arguments unmatched"); - return nullptr; - } - auto rafEntity = GetRAFEntity(env, funcArg.GetThisVar()); - if (!rafEntity) { - return nullptr; - } - return NVal::CreateInt64(env, rafEntity->fpointer).val_; -} - -napi_value RandomAccessFileNExporter::SetFilePointerSync(napi_env env, napi_callback_info info) -{ - NFuncArg funcArg(env, info); - if (!funcArg.InitArgs(NARG_CNT::ONE)) { - UniError(EINVAL).ThrowErr(env, "Number of arguments unmatched"); - return nullptr; - } - auto rafEntity = GetRAFEntity(env, funcArg.GetThisVar()); - if (!rafEntity) { - return nullptr; - } - auto [succ, fp] = ParseJsFP(env, funcArg[NARG_POS::FIRST]); - if (!succ) { - UniError(EINVAL).ThrowErr(env, "Invalid fpointer"); - } - rafEntity->fpointer = fp; - return NVal::CreateUndefined(env).val_; -} - -napi_value RandomAccessFileNExporter::ReadSync(napi_env env, napi_callback_info info) -{ - NFuncArg funcArg(env, info); - if (!funcArg.InitArgs(NARG_CNT::ONE, NARG_CNT::TWO)) { - UniError(EINVAL).ThrowErr(env, "Number of arguments unmatched"); - return nullptr; - } - auto rafEntity = GetRAFEntity(env, funcArg.GetThisVar()); - if (!rafEntity) { - return nullptr; - } - auto [succ, buf, len, hasPos, pos, ignore] = - GetRAFReadArg(env, funcArg[NARG_POS::FIRST], funcArg[NARG_POS::SECOND]); - if (!succ) { - UniError(EINVAL).ThrowErr(env, "Invalid buffer/options"); - } - ssize_t actLen = DoReadRAF(env, buf, len, rafEntity->fd_.get()->GetFD(), rafEntity->fpointer + pos); - if (actLen < 0) { - UniError(errno).ThrowErr(env); - return nullptr; - } - rafEntity->fpointer += actLen; - return NVal::CreateInt64(env, actLen).val_; -} - -struct AsyncIOReadArg { - ssize_t lenRead { 0 }; - int offset { 0 }; - NRef refReadBuf; - - explicit AsyncIOReadArg(NVal jsReadBuf) : refReadBuf(jsReadBuf) {} - ~AsyncIOReadArg() = default; -}; - -napi_value RandomAccessFileNExporter::Read(napi_env env, napi_callback_info info) -{ - NFuncArg funcArg(env, info); - if (!funcArg.InitArgs(NARG_CNT::ONE, NARG_CNT::THREE)) { - UniError(EINVAL).ThrowErr(env, "Number of arguments unmatched"); - return nullptr; - } - auto rafEntity = GetRAFEntity(env, funcArg.GetThisVar()); - if (!rafEntity) { - return nullptr; - } - bool succ = false, hasPos = false; - size_t len, pos, offset; - void* buf = nullptr; - tie(succ, buf, len, hasPos, pos, offset) = GetRAFReadArg(env, funcArg[NARG_POS::FIRST], funcArg[NARG_POS::SECOND]); - if (!succ) { - UniError(EINVAL).ThrowErr(env, "Invalid buffer/options"); - return nullptr; - } - - auto arg = make_shared(NVal(env, funcArg[NARG_POS::FIRST])); - auto cbExec = [arg, buf, len, hasPos, pos, offset, rafEntity](napi_env env) -> UniError { - ssize_t actLen = DoReadRAF(env, buf, len, rafEntity->fd_.get()->GetFD(), rafEntity->fpointer + pos); - if (actLen < 0) { - return UniError(errno); - } - arg->lenRead = actLen; - arg->offset = offset; - rafEntity->fpointer += actLen; - return UniError(ERRNO_NOERR); - }; - - auto cbCompl = [arg](napi_env env, UniError err) -> NVal { - if (err) { - return { env, err.GetNapiErr(env) }; - } - NVal obj = NVal::CreateObject(env); - obj.AddProp( - { NVal::DeclareNapiProperty("bytesRead", NVal::CreateInt64(env, arg->lenRead).val_), - NVal::DeclareNapiProperty("buffer", arg->refReadBuf.Deref(env).val_), - NVal::DeclareNapiProperty("offset", NVal::CreateInt64(env, arg->offset).val_) - }); - return { obj }; - }; - - NVal thisVar(env, funcArg.GetThisVar()); - if (funcArg.GetArgc() == NARG_CNT::ONE || (funcArg.GetArgc() == NARG_CNT::TWO && - !NVal(env, funcArg[NARG_POS::SECOND]).TypeIs(napi_function))) { - return NAsyncWorkPromise(env, thisVar).Schedule(readProcedureName, cbExec, cbCompl).val_; - } else { - int cbIdx = ((funcArg.GetArgc() == NARG_CNT::TWO) ? NARG_POS::SECOND : NARG_POS::THIRD); - NVal cb(env, funcArg[cbIdx]); - return NAsyncWorkCallback(env, thisVar, cb).Schedule(readProcedureName, cbExec, cbCompl).val_; - } - return NVal::CreateUndefined(env).val_; -} - -napi_value RandomAccessFileNExporter::WriteSync(napi_env env, napi_callback_info info) -{ - NFuncArg funcArg(env, info); - if (!funcArg.InitArgs(NARG_CNT::ONE, NARG_CNT::TWO)) { - UniError(EINVAL).ThrowErr(env, "Number of arguments unmatched"); - return nullptr; - } - - auto rafEntity = GetRAFEntity(env, funcArg.GetThisVar()); - if (!rafEntity) { - return nullptr; - } - - bool succ = false, hasPos = false; - void *buf = nullptr; - size_t len, pos; - tie(succ, buf, len, hasPos, pos) = GetRAFWriteArg(env, funcArg[NARG_POS::FIRST], funcArg[NARG_POS::SECOND]); - if (!succ) { - UniError(EINVAL).ThrowErr(env, "Invalid buffer/options"); - return nullptr; - } - if (hasPos) { - pos = rafEntity->fpointer + pos; - } else { - pos = rafEntity->fpointer; - } - ssize_t writeLen = DoWriteRAF(env, buf, len, rafEntity->fd_.get()->GetFD(), pos); - if (writeLen < 0) { - UniError(errno).ThrowErr(env); - return nullptr; - } - rafEntity->fpointer += writeLen; - return NVal::CreateInt64(env, writeLen).val_; -} - -struct AsyncIOWriteArg { - NRef refWriteArrayBuf_; - size_t actLen = 0; - explicit AsyncIOWriteArg(NVal refWriteArrayBuf) : refWriteArrayBuf_(refWriteArrayBuf) {} - ~AsyncIOWriteArg() = default; -}; - -napi_value RandomAccessFileNExporter::Write(napi_env env, napi_callback_info info) -{ - NFuncArg funcArg(env, info); - if (!funcArg.InitArgs(NARG_CNT::ONE, NARG_CNT::THREE)) { - UniError(EINVAL).ThrowErr(env, "Number of arguments unmatched"); - return nullptr; - } - - auto rafEntity = GetRAFEntity(env, funcArg.GetThisVar()); - if (!rafEntity) { - return nullptr; - } - bool succ = false, hasPos = false; - void *buf = nullptr; - size_t len, pos; - tie(succ, buf, len, hasPos, pos) = GetRAFWriteArg(env, funcArg[NARG_POS::FIRST], funcArg[NARG_POS::SECOND]); - if (!succ) { - UniError(EINVAL).ThrowErr(env, "Invalid buffer/options"); - return nullptr; - } - if (hasPos) { - pos = rafEntity->fpointer + pos; - } else { - pos = rafEntity->fpointer; - } - - auto arg = make_shared(NVal(env, funcArg[NARG_POS::FIRST])); - auto cbExec = [arg, buf, len, fd = rafEntity->fd_.get()->GetFD(), pos, rafEntity](napi_env env) -> UniError { - size_t writeLen = DoWriteRAF(env, buf, len, fd, pos); - if (writeLen < 0) { - return UniError(errno); - } - arg->actLen = writeLen; - rafEntity->fpointer += writeLen; - return UniError(ERRNO_NOERR); - }; - - auto cbCompl = [arg](napi_env env, UniError err) -> NVal { - if (err) { - return { env, err.GetNapiErr(env) }; - } else { - return { NVal::CreateInt64(env, arg->actLen) }; - } - }; - - NVal thisVar(env, funcArg.GetThisVar()); - if (funcArg.GetArgc() == NARG_CNT::ONE || (funcArg.GetArgc() == NARG_CNT::TWO && - !NVal(env, funcArg[NARG_POS::SECOND]).TypeIs(napi_function))) { - return NAsyncWorkPromise(env, thisVar).Schedule(writeProcedureName, cbExec, cbCompl).val_; - } else { - int cbIdx = ((funcArg.GetArgc() == NARG_CNT::TWO) ? NARG_POS::SECOND : NARG_POS::THIRD); - NVal cb(env, funcArg[cbIdx]); - return NAsyncWorkCallback(env, thisVar, cb).Schedule(writeProcedureName, cbExec, cbCompl).val_; - } - return NVal::CreateUndefined(env).val_; -} - -napi_value RandomAccessFileNExporter::CloseSync(napi_env env, napi_callback_info info) -{ - NFuncArg funcArg(env, info); - if (!funcArg.InitArgs(NARG_CNT::ZERO)) { - UniError(EINVAL).ThrowErr(env, "Number of arguments unmatched"); - return nullptr; - } - auto rafEntity = GetRAFEntity(env, funcArg.GetThisVar()); - if (!rafEntity) { - return nullptr; - } - rafEntity->fd_.reset(); - return NVal::CreateUndefined(env).val_; -} - -napi_value RandomAccessFileNExporter::Constructor(napi_env env, napi_callback_info info) -{ - NFuncArg funcArg(env, info); - if (!funcArg.InitArgs(NARG_CNT::ZERO)) { - UniError(EINVAL).ThrowErr(env, "Number of arguments unmatched"); - return nullptr; - } - - auto rafEntity = make_unique(); - if (!NClass::SetEntityFor(env, funcArg.GetThisVar(), move(rafEntity))) { - UniError(EIO).ThrowErr(env, "INNER BUG. Failed to wrap entity for obj RandomAccessFile"); - return nullptr; - } - return funcArg.GetThisVar(); -} - -bool RandomAccessFileNExporter::Export() -{ - vector props = { - NVal::DeclareNapiFunction("read", Read), - NVal::DeclareNapiFunction("readSync", ReadSync), - NVal::DeclareNapiFunction("write", Write), - NVal::DeclareNapiFunction("writeSync", WriteSync), - NVal::DeclareNapiFunction("setFilePointerSync", SetFilePointerSync), - NVal::DeclareNapiFunction("closeSync", CloseSync), - NVal::DeclareNapiGetter("fd", GetFD), - NVal::DeclareNapiGetter("fpointer", GetFPointer), - }; - - string className = GetClassName(); - bool succ = false; - napi_value classValue = nullptr; - tie(succ, classValue) = NClass::DefineClass(exports_.env_, className, - RandomAccessFileNExporter::Constructor, move(props)); - if (!succ) { - UniError(EIO).ThrowErr(exports_.env_, "INNER BUG. Failed to define class"); - return false; - } - succ = NClass::SaveClass(exports_.env_, className, classValue); - if (!succ) { - UniError(EIO).ThrowErr(exports_.env_, "INNER BUG. Failed to save class"); - return false; - } - - return exports_.AddProp(className, classValue); -} - -string RandomAccessFileNExporter::GetClassName() -{ - return RandomAccessFileNExporter::className_; -} - -RandomAccessFileNExporter::RandomAccessFileNExporter(napi_env env, napi_value exports) : NExporter(env, exports) {} - -RandomAccessFileNExporter::~RandomAccessFileNExporter() {} -} // namespace ModuleFileIO -} // namespace DistributedFS -} // namespace OHOS \ No newline at end of file diff --git a/interfaces/kits/js/src/mod_fileio/class_randomaccessfile/randomaccessfile_n_exporter.h b/interfaces/kits/js/src/mod_fileio/class_randomaccessfile/randomaccessfile_n_exporter.h deleted file mode 100644 index bd89a1b..0000000 --- a/interfaces/kits/js/src/mod_fileio/class_randomaccessfile/randomaccessfile_n_exporter.h +++ /dev/null @@ -1,52 +0,0 @@ -/* - * 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 INTERFACES_KITS_JS_SRC_MOD_FILEIO_CLASS_RANDOMACCESSFILE_RANDOMACCESSFILE_N_EXPORTER_H -#define INTERFACES_KITS_JS_SRC_MOD_FILEIO_CLASS_RANDOMACCESSFILE_RANDOMACCESSFILE_N_EXPORTER_H - -#include "../../common/napi/n_exporter.h" - -namespace OHOS { -namespace DistributedFS { -namespace ModuleFileIO { -class RandomAccessFileNExporter final : public NExporter { -public: - inline static const std::string className_ = "RandomAccessFile"; - - bool Export() override; - std::string GetClassName() override; - - static napi_value Constructor(napi_env env, napi_callback_info cbinfo); - - static napi_value SetFilePointerSync(napi_env env, napi_callback_info cbinfo); - static napi_value WriteSync(napi_env env, napi_callback_info cbinfo); - static napi_value ReadSync(napi_env env, napi_callback_info cbinfo); - static napi_value CloseSync(napi_env env, napi_callback_info cbinfo); - - static napi_value Write(napi_env env, napi_callback_info cbinfo); - static napi_value Read(napi_env env, napi_callback_info cbinfo); - - static napi_value GetFD(napi_env env, napi_callback_info cbinfo); - static napi_value GetFPointer(napi_env env, napi_callback_info cbinfo); - - RandomAccessFileNExporter(napi_env env, napi_value exports); - ~RandomAccessFileNExporter() override; -}; -const std::string readProcedureName = "FileIORandomAccessFileRead"; -const std::string writeProcedureName = "FileIORandomAccessFileWrite"; -} // namespace ModuleFileIO -} // namespace DistributedFS -} // namespace OHOS -#endif \ No newline at end of file diff --git a/interfaces/kits/js/src/mod_fileio/class_stat/stat_entity.h b/interfaces/kits/js/src/mod_fileio/class_stat/stat_entity.h deleted file mode 100644 index a82c30f..0000000 --- a/interfaces/kits/js/src/mod_fileio/class_stat/stat_entity.h +++ /dev/null @@ -1,30 +0,0 @@ -/* - * Copyright (c) 2021 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#ifndef INTERFACES_KITS_JS_SRC_MOD_FILEIO_CLASS_STAT_STAT_ENTITY_H -#define INTERFACES_KITS_JS_SRC_MOD_FILEIO_CLASS_STAT_STAT_ENTITY_H - -#include - -namespace OHOS { -namespace DistributedFS { -namespace ModuleFileIO { -struct StatEntity { - struct stat stat_; -}; -} // namespace ModuleFileIO -} // namespace DistributedFS -} // namespace OHOS -#endif \ No newline at end of file diff --git a/interfaces/kits/js/src/mod_fileio/class_stat/stat_n_exporter.cpp b/interfaces/kits/js/src/mod_fileio/class_stat/stat_n_exporter.cpp deleted file mode 100644 index 26dfa59..0000000 --- a/interfaces/kits/js/src/mod_fileio/class_stat/stat_n_exporter.cpp +++ /dev/null @@ -1,368 +0,0 @@ -/* - * Copyright (c) 2021-2022 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#include "stat_n_exporter.h" -#include "../../common/napi/n_async/n_async_work_callback.h" -#include "../../common/napi/n_async/n_async_work_promise.h" - -#include -#include -#include -#include -#include - -#include "securec.h" - -#include "../../common/log.h" -#include "../../common/napi/n_class.h" -#include "../../common/napi/n_func_arg.h" -#include "../../common/uni_error.h" -#include "stat_entity.h" - -namespace OHOS { -namespace DistributedFS { -namespace ModuleFileIO { -using namespace std; - -static napi_value CheckStatMode(napi_env env, napi_callback_info info, mode_t mode) -{ - NFuncArg funcArg(env, info); - if (!funcArg.InitArgs(NARG_CNT::ZERO)) { - UniError(EINVAL).ThrowErr(env, "Number of arguments unmatched"); - return nullptr; - } - - auto statEntity = NClass::GetEntityOf(env, funcArg.GetThisVar()); - if (!statEntity) { - return nullptr; - } - - bool check = (statEntity->stat_.st_mode & S_IFMT) == mode; - return NVal::CreateBool(env, check).val_; -} - -napi_value StatNExporter::IsBlockDevice(napi_env env, napi_callback_info info) -{ - return CheckStatMode(env, info, S_IFBLK); -} - -napi_value StatNExporter::IsCharacterDevice(napi_env env, napi_callback_info info) -{ - return CheckStatMode(env, info, S_IFCHR); -} - -napi_value StatNExporter::IsDirectory(napi_env env, napi_callback_info info) -{ - return CheckStatMode(env, info, S_IFDIR); -} - -napi_value StatNExporter::IsFIFO(napi_env env, napi_callback_info info) -{ - return CheckStatMode(env, info, S_IFIFO); -} - -napi_value StatNExporter::IsFile(napi_env env, napi_callback_info info) -{ - return CheckStatMode(env, info, S_IFREG); -} - -napi_value StatNExporter::IsSocket(napi_env env, napi_callback_info info) -{ - return CheckStatMode(env, info, S_IFSOCK); -} - -napi_value StatNExporter::IsSymbolicLink(napi_env env, napi_callback_info info) -{ - return CheckStatMode(env, info, S_IFLNK); -} - -napi_value StatNExporter::GetDev(napi_env env, napi_callback_info info) -{ - NFuncArg funcArg(env, info); - if (!funcArg.InitArgs(NARG_CNT::ZERO)) { - UniError(EINVAL).ThrowErr(env, "Number of arguments unmatched"); - return nullptr; - } - - auto statEntity = NClass::GetEntityOf(env, funcArg.GetThisVar()); - if (!statEntity) { - return nullptr; - } - - return NVal::CreateInt64(env, statEntity->stat_.st_dev).val_; -} - -napi_value StatNExporter::GetIno(napi_env env, napi_callback_info info) -{ - NFuncArg funcArg(env, info); - if (!funcArg.InitArgs(NARG_CNT::ZERO)) { - UniError(EINVAL).ThrowErr(env, "Number of arguments unmatched"); - return nullptr; - } - - auto statEntity = NClass::GetEntityOf(env, funcArg.GetThisVar()); - if (!statEntity) { - return nullptr; - } - - return NVal::CreateInt64(env, statEntity->stat_.st_ino).val_; -} - -napi_value StatNExporter::GetMode(napi_env env, napi_callback_info info) -{ - NFuncArg funcArg(env, info); - if (!funcArg.InitArgs(NARG_CNT::ZERO)) { - UniError(EINVAL).ThrowErr(env, "Number of arguments unmatched"); - return nullptr; - } - - auto statEntity = NClass::GetEntityOf(env, funcArg.GetThisVar()); - if (!statEntity) { - return nullptr; - } - - return NVal::CreateInt64(env, statEntity->stat_.st_mode).val_; -} - -napi_value StatNExporter::GetNlink(napi_env env, napi_callback_info info) -{ - NFuncArg funcArg(env, info); - if (!funcArg.InitArgs(NARG_CNT::ZERO)) { - UniError(EINVAL).ThrowErr(env, "Number of arguments unmatched"); - return nullptr; - } - - auto statEntity = NClass::GetEntityOf(env, funcArg.GetThisVar()); - if (!statEntity) { - return nullptr; - } - - return NVal::CreateInt64(env, statEntity->stat_.st_nlink).val_; -} - -napi_value StatNExporter::GetUid(napi_env env, napi_callback_info info) -{ - NFuncArg funcArg(env, info); - if (!funcArg.InitArgs(NARG_CNT::ZERO)) { - UniError(EINVAL).ThrowErr(env, "Number of arguments unmatched"); - return nullptr; - } - - auto statEntity = NClass::GetEntityOf(env, funcArg.GetThisVar()); - if (!statEntity) { - return nullptr; - } - - return NVal::CreateInt64(env, statEntity->stat_.st_uid).val_; -} - -napi_value StatNExporter::GetGid(napi_env env, napi_callback_info info) -{ - NFuncArg funcArg(env, info); - if (!funcArg.InitArgs(NARG_CNT::ZERO)) { - UniError(EINVAL).ThrowErr(env, "Number of arguments unmatched"); - return nullptr; - } - - auto statEntity = NClass::GetEntityOf(env, funcArg.GetThisVar()); - if (!statEntity) { - return nullptr; - } - - return NVal::CreateInt64(env, statEntity->stat_.st_gid).val_; -} - -napi_value StatNExporter::GetRdev(napi_env env, napi_callback_info info) -{ - NFuncArg funcArg(env, info); - if (!funcArg.InitArgs(NARG_CNT::ZERO)) { - UniError(EINVAL).ThrowErr(env, "Number of arguments unmatched"); - return nullptr; - } - - auto statEntity = NClass::GetEntityOf(env, funcArg.GetThisVar()); - if (!statEntity) { - return nullptr; - } - - return NVal::CreateInt64(env, statEntity->stat_.st_rdev).val_; -} - -napi_value StatNExporter::GetSize(napi_env env, napi_callback_info info) -{ - NFuncArg funcArg(env, info); - if (!funcArg.InitArgs(NARG_CNT::ZERO)) { - UniError(EINVAL).ThrowErr(env, "Number of arguments unmatched"); - return nullptr; - } - - auto statEntity = NClass::GetEntityOf(env, funcArg.GetThisVar()); - if (!statEntity) { - return nullptr; - } - - return NVal::CreateInt64(env, statEntity->stat_.st_size).val_; -} - -napi_value StatNExporter::GetBlksize(napi_env env, napi_callback_info info) -{ - NFuncArg funcArg(env, info); - if (!funcArg.InitArgs(NARG_CNT::ZERO)) { - UniError(EINVAL).ThrowErr(env, "Number of arguments unmatched"); - return nullptr; - } - - auto statEntity = NClass::GetEntityOf(env, funcArg.GetThisVar()); - if (!statEntity) { - return nullptr; - } - - return NVal::CreateInt64(env, statEntity->stat_.st_blksize).val_; -} - -napi_value StatNExporter::GetBlocks(napi_env env, napi_callback_info info) -{ - NFuncArg funcArg(env, info); - if (!funcArg.InitArgs(NARG_CNT::ZERO)) { - UniError(EINVAL).ThrowErr(env, "Number of arguments unmatched"); - return nullptr; - } - - auto statEntity = NClass::GetEntityOf(env, funcArg.GetThisVar()); - if (!statEntity) { - return nullptr; - } - - return NVal::CreateInt64(env, statEntity->stat_.st_blocks).val_; -} - -napi_value StatNExporter::GetAtime(napi_env env, napi_callback_info info) -{ - NFuncArg funcArg(env, info); - if (!funcArg.InitArgs(NARG_CNT::ZERO)) { - UniError(EINVAL).ThrowErr(env, "Number of arguments unmatched"); - return nullptr; - } - - auto statEntity = NClass::GetEntityOf(env, funcArg.GetThisVar()); - if (!statEntity) { - return nullptr; - } - - return NVal::CreateInt64(env, statEntity->stat_.st_atim.tv_sec).val_; -} - -napi_value StatNExporter::GetMtime(napi_env env, napi_callback_info info) -{ - NFuncArg funcArg(env, info); - if (!funcArg.InitArgs(NARG_CNT::ZERO)) { - UniError(EINVAL).ThrowErr(env, "Number of arguments unmatched"); - return nullptr; - } - - auto statEntity = NClass::GetEntityOf(env, funcArg.GetThisVar()); - if (!statEntity) { - return nullptr; - } - - return NVal::CreateInt64(env, statEntity->stat_.st_mtim.tv_sec).val_; -} - -napi_value StatNExporter::GetCtime(napi_env env, napi_callback_info info) -{ - NFuncArg funcArg(env, info); - if (!funcArg.InitArgs(NARG_CNT::ZERO)) { - UniError(EINVAL).ThrowErr(env, "Number of arguments unmatched"); - return nullptr; - } - - auto statEntity = NClass::GetEntityOf(env, funcArg.GetThisVar()); - if (!statEntity) { - return nullptr; - } - - return NVal::CreateInt64(env, statEntity->stat_.st_ctim.tv_sec).val_; -} - -napi_value StatNExporter::Constructor(napi_env env, napi_callback_info info) -{ - NFuncArg funcArg(env, info); - if (!funcArg.InitArgs(NARG_CNT::ZERO)) { - UniError(EINVAL).ThrowErr(env, "Number of arguments unmatched"); - return nullptr; - } - - unique_ptr statEntity = make_unique(); - if (!NClass::SetEntityFor(env, funcArg.GetThisVar(), move(statEntity))) { - UniError(EIO).ThrowErr(env, "INNER BUG. Failed to wrap entity for obj stat"); - return nullptr; - } - return funcArg.GetThisVar(); -} - -bool StatNExporter::Export() -{ - vector props = { - NVal::DeclareNapiFunction("isBlockDevice", IsBlockDevice), - NVal::DeclareNapiFunction("isCharacterDevice", IsCharacterDevice), - NVal::DeclareNapiFunction("isDirectory", IsDirectory), - NVal::DeclareNapiFunction("isFIFO", IsFIFO), - NVal::DeclareNapiFunction("isFile", IsFile), - NVal::DeclareNapiFunction("isSocket", IsSocket), - NVal::DeclareNapiFunction("isSymbolicLink", IsSymbolicLink), - - NVal::DeclareNapiGetter("dev", GetDev), - NVal::DeclareNapiGetter("ino", GetIno), - NVal::DeclareNapiGetter("mode", GetMode), - NVal::DeclareNapiGetter("nlink", GetNlink), - NVal::DeclareNapiGetter("uid", GetUid), - NVal::DeclareNapiGetter("gid", GetGid), - NVal::DeclareNapiGetter("rdev", GetRdev), - NVal::DeclareNapiGetter("size", GetSize), - NVal::DeclareNapiGetter("blksize", GetBlksize), - NVal::DeclareNapiGetter("blocks", GetBlocks), - NVal::DeclareNapiGetter("atime", GetAtime), - NVal::DeclareNapiGetter("mtime", GetMtime), - NVal::DeclareNapiGetter("ctime", GetCtime), - }; - - string className = GetClassName(); - bool succ = false; - napi_value classValue = nullptr; - tie(succ, classValue) = NClass::DefineClass(exports_.env_, className, StatNExporter::Constructor, std::move(props)); - if (!succ) { - UniError(EIO).ThrowErr(exports_.env_, "INNER BUG. Failed to define class"); - return false; - } - succ = NClass::SaveClass(exports_.env_, className, classValue); - if (!succ) { - UniError(EIO).ThrowErr(exports_.env_, "INNER BUG. Failed to save class"); - return false; - } - - return exports_.AddProp(className, classValue); -} - -string StatNExporter::GetClassName() -{ - return StatNExporter::className_; -} - -StatNExporter::StatNExporter(napi_env env, napi_value exports) : NExporter(env, exports) {} - -StatNExporter::~StatNExporter() {} -} // namespace ModuleFileIO -} // namespace DistributedFS -} // namespace OHOS \ No newline at end of file diff --git a/interfaces/kits/js/src/mod_fileio/class_stat/stat_n_exporter.h b/interfaces/kits/js/src/mod_fileio/class_stat/stat_n_exporter.h deleted file mode 100644 index 4304856..0000000 --- a/interfaces/kits/js/src/mod_fileio/class_stat/stat_n_exporter.h +++ /dev/null @@ -1,61 +0,0 @@ -/* - * Copyright (c) 2021 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#ifndef INTERFACES_KITS_JS_SRC_MOD_FILEIO_CLASS_STAT_N_EXPORTER_H -#define INTERFACES_KITS_JS_SRC_MOD_FILEIO_CLASS_STAT_N_EXPORTER_H - -#include "../../common/napi/n_exporter.h" - -namespace OHOS { -namespace DistributedFS { -namespace ModuleFileIO { -class StatNExporter final : public NExporter { -public: - inline static const std::string className_ = "Stat"; - - bool Export() override; - std::string GetClassName() override; - - static napi_value Constructor(napi_env env, napi_callback_info cbinfo); - - static napi_value IsBlockDevice(napi_env env, napi_callback_info cbinfo); - static napi_value IsCharacterDevice(napi_env env, napi_callback_info cbinfo); - static napi_value IsDirectory(napi_env env, napi_callback_info cbinfo); - static napi_value IsFIFO(napi_env env, napi_callback_info cbinfo); - static napi_value IsFile(napi_env env, napi_callback_info cbinfo); - static napi_value IsSocket(napi_env env, napi_callback_info cbinfo); - static napi_value IsSymbolicLink(napi_env env, napi_callback_info cbinfo); - - static napi_value GetDev(napi_env env, napi_callback_info cbinfo); - static napi_value GetIno(napi_env env, napi_callback_info cbinfo); - static napi_value GetMode(napi_env env, napi_callback_info cbinfo); - static napi_value GetNlink(napi_env env, napi_callback_info cbinfo); - static napi_value GetUid(napi_env env, napi_callback_info cbinfo); - static napi_value GetGid(napi_env env, napi_callback_info cbinfo); - static napi_value GetRdev(napi_env env, napi_callback_info cbinfo); - static napi_value GetSize(napi_env env, napi_callback_info cbinfo); - static napi_value GetBlksize(napi_env env, napi_callback_info cbinfo); - static napi_value GetBlocks(napi_env env, napi_callback_info cbinfo); - static napi_value GetAtime(napi_env env, napi_callback_info cbinfo); - static napi_value GetMtime(napi_env env, napi_callback_info cbinfo); - static napi_value GetCtime(napi_env env, napi_callback_info cbinfo); - - StatNExporter(napi_env env, napi_value exports); - ~StatNExporter() override; -}; -} // namespace ModuleFileIO -} // namespace DistributedFS -} // namespace OHOS -#endif // INTERFACES_KITS_JS_SRC_MOD_FILEIO_CLASS_STAT_N_EXPORTER_H \ No newline at end of file diff --git a/interfaces/kits/js/src/mod_fileio/class_stream/flush.cpp b/interfaces/kits/js/src/mod_fileio/class_stream/flush.cpp deleted file mode 100644 index 590b47e..0000000 --- a/interfaces/kits/js/src/mod_fileio/class_stream/flush.cpp +++ /dev/null @@ -1,101 +0,0 @@ -/* - * Copyright (c) 2021 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -#include "flush.h" - -#include -#include - -#include "../../common/napi/n_async/n_async_work_callback.h" -#include "../../common/napi/n_async/n_async_work_promise.h" -#include "../../common/napi/n_class.h" -#include "../../common/napi/n_func_arg.h" -#include "../../common/napi/n_val.h" -#include "../../common/uni_error.h" - -#include "../class_stat/stat_entity.h" -#include "../class_stat/stat_n_exporter.h" - -namespace OHOS { -namespace DistributedFS { -namespace ModuleFileIO { -using namespace std; - -struct StreamEntity { - std::unique_ptr fp = { nullptr, fclose }; -}; - -napi_value Flush::Sync(napi_env env, napi_callback_info info) -{ - NFuncArg funcArg(env, info); - if (!funcArg.InitArgs(NARG_CNT::ZERO)) { - UniError(EINVAL).ThrowErr(env, "Number of arguments unmatched"); - return nullptr; - } - - auto streamEntity = NClass::GetEntityOf(env, funcArg.GetThisVar()); - if (!streamEntity || !streamEntity->fp) { - UniError(EBADF).ThrowErr(env, "Stream may has been closed"); - return nullptr; - } - - int ret = fflush(streamEntity->fp.get()); - if (ret == -1) { - UniError(errno).ThrowErr(env); - return nullptr; - } - return NVal::CreateUndefined(env).val_; -} - -napi_value Flush::Async(napi_env env, napi_callback_info info) -{ - NFuncArg funcArg(env, info); - if (!funcArg.InitArgs(NARG_CNT::ZERO, NARG_CNT::ONE)) { - UniError(EINVAL).ThrowErr(env, "Number of arguments unmatched"); - return nullptr; - } - - auto streamEntity = NClass::GetEntityOf(env, funcArg.GetThisVar()); - if (!streamEntity || !streamEntity->fp) { - UniError(EBADF).ThrowErr(env, "Stream may has been closed"); - return nullptr; - } - - auto cbExec = [streamEntity](napi_env env) -> UniError { - int ret = fflush(streamEntity->fp.get()); - if (ret == -1) { - return UniError(errno); - } else { - return UniError(ERRNO_NOERR); - } - }; - auto cbCompl = [](napi_env env, UniError err) -> NVal { - if (err) { - return { env, err.GetNapiErr(env) }; - } - return { NVal::CreateUndefined(env) }; - }; - - NVal thisVar(env, funcArg.GetThisVar()); - string procedureName = "fileIOFlush"; - if (funcArg.GetArgc() == NARG_CNT::ZERO) { - return NAsyncWorkPromise(env, thisVar).Schedule(procedureName, cbExec, cbCompl).val_; - } else { - NVal cb(env, funcArg[NARG_POS::FIRST]); - return NAsyncWorkCallback(env, thisVar, cb).Schedule(procedureName, cbExec, cbCompl).val_; - } -} -} // namespace ModuleFileIO -} // namespace DistributedFS -} // namespace OHOS \ No newline at end of file diff --git a/interfaces/kits/js/src/mod_fileio/class_stream/flush.h b/interfaces/kits/js/src/mod_fileio/class_stream/flush.h deleted file mode 100644 index c616571..0000000 --- a/interfaces/kits/js/src/mod_fileio/class_stream/flush.h +++ /dev/null @@ -1,32 +0,0 @@ -/* - * Copyright (c) 2021 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#ifndef INTERFACES_KITS_JS_SRC_MOD_FILEIO_CLASS_STREAM_FLUSH_H -#define INTERFACES_KITS_JS_SRC_MOD_FILEIO_CLASS_STREAM_FLUSH_H - -#include "../../common/napi/uni_header.h" - -namespace OHOS { -namespace DistributedFS { -namespace ModuleFileIO { -class Flush final { -public: - static napi_value Async(napi_env env, napi_callback_info info); - static napi_value Sync(napi_env env, napi_callback_info info); -}; -} // namespace ModuleFileIO -} // namespace DistributedFS -} // namespace OHOS -#endif \ No newline at end of file diff --git a/interfaces/kits/js/src/mod_fileio/class_stream/stream_entity.h b/interfaces/kits/js/src/mod_fileio/class_stream/stream_entity.h deleted file mode 100644 index 1c010e0..0000000 --- a/interfaces/kits/js/src/mod_fileio/class_stream/stream_entity.h +++ /dev/null @@ -1,28 +0,0 @@ -/* - * Copyright (c) 2021 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#ifndef INTERFACES_KITS_JS_SRC_MOD_FILEIO_CLASS_STREAM_STREAM_ENTITY_H -#define INTERFACES_KITS_JS_SRC_MOD_FILEIO_CLASS_STREAM_STREAM_ENTITY_H - -namespace OHOS { -namespace DistributedFS { -namespace ModuleFileIO { -struct StreamEntity { - std::unique_ptr fp = { nullptr, fclose }; -}; -} // namespace ModuleFileIO -} // namespace DistributedFS -} // namespace OHOS -#endif // INTERFACES_KITS_JS_SRC_MOD_FILEIO_CLASS_STREAM_STREAM_ENTITY_H \ No newline at end of file diff --git a/interfaces/kits/js/src/mod_fileio/class_stream/stream_n_exporter.cpp b/interfaces/kits/js/src/mod_fileio/class_stream/stream_n_exporter.cpp deleted file mode 100644 index ce47893..0000000 --- a/interfaces/kits/js/src/mod_fileio/class_stream/stream_n_exporter.cpp +++ /dev/null @@ -1,399 +0,0 @@ -/* - * Copyright (c) 2021-2022 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#include "stream_n_exporter.h" - -#include -#include -#include -#include -#include -#include -#include "flush.h" -#include "securec.h" - -#include "../../common/log.h" -#include "../../common/napi/n_async/n_async_work_callback.h" -#include "../../common/napi/n_async/n_async_work_promise.h" -#include "../../common/napi/n_class.h" -#include "../../common/napi/n_func_arg.h" -#include "../../common/uni_error.h" -#include "../common_func.h" -#include "stream_entity.h" - -namespace OHOS { -namespace DistributedFS { -namespace ModuleFileIO { -using namespace std; - -napi_value StreamNExporter::ReadSync(napi_env env, napi_callback_info info) -{ - NFuncArg funcArg(env, info); - - if (!funcArg.InitArgs(NARG_CNT::ONE, NARG_CNT::TWO)) { - UniError(EINVAL).ThrowErr(env, "Number of arguments unmatched"); - return nullptr; - } - - /* To get entity */ - bool succ = false; - FILE *filp = nullptr; - auto streamEntity = NClass::GetEntityOf(env, funcArg.GetThisVar()); - if (!streamEntity || !streamEntity->fp) { - UniError(EBADF).ThrowErr(env, "Stream may have been closed"); - return nullptr; - } else { - filp = streamEntity->fp.get(); - } - - void *buf = nullptr; - int64_t len; - bool hasPos = false; - int64_t pos; - tie(succ, buf, len, hasPos, pos, ignore) = - CommonFunc::GetReadArg(env, funcArg[NARG_POS::FIRST], funcArg[NARG_POS::SECOND]); - if (!succ) { - return nullptr; - } - - if (hasPos && (fseek(filp, pos, SEEK_SET) == -1)) { - UniError(errno).ThrowErr(env); - return nullptr; - } - - size_t actLen = fread(buf, 1, len, filp); - if (actLen != static_cast(len) && ferror(filp)) { - UniError(errno).ThrowErr(env); - } - - return NVal::CreateInt64(env, actLen).val_; -} - -napi_value StreamNExporter::CloseSync(napi_env env, napi_callback_info info) -{ - NFuncArg funcArg(env, info); - - if (!funcArg.InitArgs(NARG_CNT::ZERO)) { - UniError(EINVAL).ThrowErr(env, "Number of arguments unmatched"); - return nullptr; - } - - auto streamEntity = NClass::GetEntityOf(env, funcArg.GetThisVar()); - if (!streamEntity || !streamEntity->fp) { - UniError(EINVAL).ThrowErr(env, "Stream may have been closed yet"); - return nullptr; - } - streamEntity->fp.reset(); - return NVal::CreateUndefined(env).val_; -} - -napi_value StreamNExporter::WriteSync(napi_env env, napi_callback_info info) -{ - NFuncArg funcArg(env, info); - if (!funcArg.InitArgs(NARG_CNT::ONE, NARG_CNT::TWO)) { - UniError(EINVAL).ThrowErr(env, "Number of arguments unmatched"); - return nullptr; - } - - bool succ = false; - FILE *filp = nullptr; - auto streamEntity = NClass::GetEntityOf(env, funcArg.GetThisVar()); - if (!streamEntity || !streamEntity->fp) { - UniError(EBADF).ThrowErr(env, "Stream may has been closed"); - return nullptr; - } else { - filp = streamEntity->fp.get(); - } - - void *buf = nullptr; - size_t len; - size_t position; - unique_ptr bufGuard; - bool hasPos = false; - tie(succ, bufGuard, buf, len, hasPos, position) = - CommonFunc::GetWriteArg(env, funcArg[NARG_POS::FIRST], funcArg[NARG_POS::SECOND]); - if (!succ) { - return nullptr; - } - if (hasPos && (fseek(filp, position, SEEK_SET) == -1)) { - UniError(errno).ThrowErr(env); - return nullptr; - } - - size_t writeLen = fwrite(buf, 1, len, filp); - if (writeLen != len) { - UniError(errno).ThrowErr(env); - return nullptr; - } - - return NVal::CreateInt64(env, writeLen).val_; -} - -struct AsyncWrtieArg { - NRef refWriteArrayBuf; - unique_ptr guardWriteStr; - size_t actLen { 0 }; - - explicit AsyncWrtieArg(NVal refWriteArrayBuf) : refWriteArrayBuf(refWriteArrayBuf) {} - explicit AsyncWrtieArg(unique_ptr &&guardWriteStr) : guardWriteStr(move(guardWriteStr)) {} - ~AsyncWrtieArg() = default; -}; - -napi_value StreamNExporter::Write(napi_env env, napi_callback_info info) -{ - NFuncArg funcArg(env, info); - if (!funcArg.InitArgs(NARG_CNT::ONE, NARG_CNT::THREE)) { - UniError(EINVAL).ThrowErr(env, "Number of arguments unmatched"); - return nullptr; - } - - bool succ = false; - FILE *filp = nullptr; - bool hasPosition = false; - size_t position; - auto streamEntity = NClass::GetEntityOf(env, funcArg.GetThisVar()); - if (!streamEntity || !streamEntity->fp) { - UniError(EBADF).ThrowErr(env, "Stream may has been closed"); - return nullptr; - } - filp = streamEntity->fp.get(); - - unique_ptr bufGuard; - void *buf = nullptr; - size_t len; - tie(succ, bufGuard, buf, len, hasPosition, position) = - CommonFunc::GetWriteArg(env, funcArg[NARG_POS::FIRST], funcArg[NARG_POS::SECOND]); - if (!succ) { - return nullptr; - } - - shared_ptr arg; - if (bufGuard) { - arg = make_shared(move(bufGuard)); - } else { - arg = make_shared(NVal(env, funcArg[NARG_POS::FIRST])); - } - - auto cbExec = [arg, buf, len, filp, hasPosition, position](napi_env env) -> UniError { - if (hasPosition && (fseek(filp, position, SEEK_SET) == -1)) { - UniError(errno).ThrowErr(env); - return UniError(errno); - } - arg->actLen = fwrite(buf, 1, len, filp); - if (arg->actLen != static_cast(len) && ferror(filp)) { - return UniError(errno); - } - return UniError(ERRNO_NOERR); - }; - - auto cbCompl = [arg](napi_env env, UniError err) -> NVal { - if (err) { - return { env, err.GetNapiErr(env) }; - } - return { NVal::CreateInt64(env, arg->actLen) }; - }; - - NVal thisVar(env, funcArg.GetThisVar()); - if (funcArg.GetArgc() != NARG_CNT::THREE) { - return NAsyncWorkPromise(env, thisVar).Schedule("FileIOStreamWrite", cbExec, cbCompl).val_; - } else { - NVal cb(env, funcArg[NARG_POS::THIRD]); - return NAsyncWorkCallback(env, thisVar, cb).Schedule("FileIOStreamWrite", cbExec, cbCompl).val_; - } - - return NVal::CreateUndefined(env).val_; -} - -struct AsyncReadArg { - size_t lenRead { 0 }; - NRef refReadBuf; - int offset { 0 }; - - explicit AsyncReadArg(NVal jsReadBuf) : refReadBuf(jsReadBuf) {} - ~AsyncReadArg() = default; -}; - -napi_value StreamNExporter::Read(napi_env env, napi_callback_info info) -{ - NFuncArg funcArg(env, info); - if (!funcArg.InitArgs(NARG_CNT::ONE, NARG_CNT::THREE)) { - UniError(EINVAL).ThrowErr(env, "Number of arguments unmatched"); - return nullptr; - } - - /* To get entity */ - FILE *filp = nullptr; - auto streamEntity = NClass::GetEntityOf(env, funcArg.GetThisVar()); - if (!streamEntity || !streamEntity->fp) { - UniError(EBADF).ThrowErr(env, "Stream may have been closed"); - return nullptr; - } else { - filp = streamEntity->fp.get(); - } - - bool succ = false; - void *buf = nullptr; - int64_t len; - bool hasPosition = false; - size_t position; - int offset; - tie(succ, buf, len, hasPosition, position, offset) = - CommonFunc::GetReadArg(env, funcArg[NARG_POS::FIRST], funcArg[NARG_POS::SECOND]); - if (!succ) { - UniError(EINVAL).ThrowErr(env, "Failed GetReadArg"); - return nullptr; - } - - auto arg = make_shared(NVal(env, funcArg[NARG_POS::FIRST])); - auto cbExec = [arg, buf, position, filp, len, hasPosition, offset](napi_env env) -> UniError { - if (hasPosition && (fseek(filp, position, SEEK_SET) == -1)) { - UniError(errno).ThrowErr(env); - return UniError(errno); - } - size_t actLen = fread(buf, 1, len, filp); - if (actLen != static_cast(len) && ferror(filp)) { - return UniError(errno); - } else { - arg->lenRead = actLen; - arg->offset = offset; - return UniError(ERRNO_NOERR); - } - }; - - auto cbCompl = [arg](napi_env env, UniError err) -> NVal { - if (err) { - return { env, err.GetNapiErr(env) }; - } - NVal obj = NVal::CreateObject(env); - obj.AddProp({ - NVal::DeclareNapiProperty("bytesRead", NVal::CreateInt64(env, arg->lenRead).val_), - NVal::DeclareNapiProperty("buffer", arg->refReadBuf.Deref(env).val_), - NVal::DeclareNapiProperty("offset", NVal::CreateInt64(env, arg->offset).val_) - }); - return { obj }; - }; - - NVal thisVar(env, funcArg.GetThisVar()); - if (funcArg.GetArgc() != NARG_CNT::THREE) { - return NAsyncWorkPromise(env, thisVar).Schedule("FileIOStreamRead", cbExec, cbCompl).val_; - } else { - NVal cb(env, funcArg[NARG_POS::THIRD]); - return NAsyncWorkCallback(env, thisVar, cb).Schedule("FileIOStreamRead", cbExec, cbCompl).val_; - } - - return NVal::CreateUndefined(env).val_; -} - -napi_value StreamNExporter::Close(napi_env env, napi_callback_info info) -{ - NFuncArg funcArg(env, info); - if (!funcArg.InitArgs(NARG_CNT::ZERO, NARG_CNT::ONE)) { - UniError(EINVAL).ThrowErr(env, "Number of arguments unmatched"); - return nullptr; - } - - auto streamEntity = NClass::GetEntityOf(env, funcArg.GetThisVar()); - if (!streamEntity || !streamEntity->fp) { - UniError(EBADF).ThrowErr(env, "Stream may has been closed"); - return nullptr; - } - - auto cbExec = [streamEntity](napi_env env) -> UniError { - auto filp = streamEntity->fp.release(); - if (!fclose(filp)) { - return UniError(ERRNO_NOERR); - } else { - return UniError(errno); - } - }; - - auto cbCompl = [](napi_env env, UniError err) -> NVal { - if (err) { - return { env, err.GetNapiErr(env) }; - } else { - return NVal::CreateUndefined(env); - } - }; - - string procedureName = "FileIOStreamClose"; - NVal thisVar(env, funcArg.GetThisVar()); - if (funcArg.GetArgc() == NARG_CNT::ZERO) { - return NAsyncWorkPromise(env, thisVar).Schedule(procedureName, cbExec, cbCompl).val_; - } else { - NVal cb(env, funcArg[NARG_POS::FIRST]); - return NAsyncWorkCallback(env, thisVar, cb).Schedule(procedureName, cbExec, cbCompl).val_; - } - - return NVal::CreateUndefined(env).val_; -} - -napi_value StreamNExporter::Constructor(napi_env env, napi_callback_info info) -{ - NFuncArg funcArg(env, info); - - if (!funcArg.InitArgs(NARG_CNT::ZERO)) { - UniError(EINVAL).ThrowErr(env, "Number of arguments unmatched"); - return nullptr; - } - - unique_ptr streamEntity = make_unique(); - if (!NClass::SetEntityFor(env, funcArg.GetThisVar(), move(streamEntity))) { - UniError(EIO).ThrowErr(env, "INNER BUG. Failed to wrap entity for obj stream"); - return nullptr; - } - return funcArg.GetThisVar(); -} - -bool StreamNExporter::Export() -{ - vector props = { - NVal::DeclareNapiFunction("writeSync", WriteSync), - NVal::DeclareNapiFunction("flush", Flush::Async), - NVal::DeclareNapiFunction("flushSync", Flush::Sync), - NVal::DeclareNapiFunction("readSync", ReadSync), - NVal::DeclareNapiFunction("closeSync", CloseSync), - NVal::DeclareNapiFunction("write", Write), - NVal::DeclareNapiFunction("read", Read), - NVal::DeclareNapiFunction("close", Close), - }; - - string className = GetClassName(); - bool succ = false; - napi_value cls = nullptr; - tie(succ, cls) = NClass::DefineClass(exports_.env_, className, StreamNExporter::Constructor, move(props)); - if (!succ) { - UniError(EIO).ThrowErr(exports_.env_, "INNER BUG. Failed to define class"); - return false; - } - succ = NClass::SaveClass(exports_.env_, className, cls); - if (!succ) { - UniError(EIO).ThrowErr(exports_.env_, "INNER BUG. Failed to save class"); - return false; - } - - return exports_.AddProp(className, cls); -} - -string StreamNExporter::GetClassName() -{ - return StreamNExporter::className_; -} - -StreamNExporter::StreamNExporter(napi_env env, napi_value exports) : NExporter(env, exports) {} - -StreamNExporter::~StreamNExporter() {} -} // namespace ModuleFileIO -} // namespace DistributedFS -} // namespace OHOS \ No newline at end of file diff --git a/interfaces/kits/js/src/mod_fileio/class_stream/stream_n_exporter.h b/interfaces/kits/js/src/mod_fileio/class_stream/stream_n_exporter.h deleted file mode 100644 index 3cfe4d2..0000000 --- a/interfaces/kits/js/src/mod_fileio/class_stream/stream_n_exporter.h +++ /dev/null @@ -1,48 +0,0 @@ -/* - * Copyright (c) 2021 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#ifndef INTERFACES_KITS_JS_SRC_MOD_FILEIO_CLASS_STREAM_STREAM_N_EXPORTER_H -#define INTERFACES_KITS_JS_SRC_MOD_FILEIO_CLASS_STREAM_STREAM_N_EXPORTER_H - -#include "../../common/napi/n_exporter.h" - -namespace OHOS { -namespace DistributedFS { -namespace ModuleFileIO { -class StreamNExporter final : public NExporter { -public: - inline static const std::string className_ = "Stream"; - - bool Export() override; - std::string GetClassName() override; - - static napi_value Constructor(napi_env env, napi_callback_info cbinfo); - - static napi_value WriteSync(napi_env env, napi_callback_info cbinfo); - static napi_value FlushSync(napi_env env, napi_callback_info cbinfo); - static napi_value ReadSync(napi_env env, napi_callback_info cbinfo); - static napi_value CloseSync(napi_env env, napi_callback_info cbinfo); - - static napi_value Write(napi_env env, napi_callback_info cbinfo); - static napi_value Read(napi_env env, napi_callback_info cbinfo); - static napi_value Close(napi_env env, napi_callback_info cbinfo); - - StreamNExporter(napi_env env, napi_value exports); - ~StreamNExporter() override; -}; -} // namespace ModuleFileIO -} // namespace DistributedFS -} // namespace OHOS -#endif \ No newline at end of file diff --git a/interfaces/kits/js/src/mod_fileio/class_watcher/watcher_entity.h b/interfaces/kits/js/src/mod_fileio/class_watcher/watcher_entity.h deleted file mode 100644 index 29a2c20..0000000 --- a/interfaces/kits/js/src/mod_fileio/class_watcher/watcher_entity.h +++ /dev/null @@ -1,47 +0,0 @@ -/* - * Copyright (c) 2021 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#ifndef INTERFACES_KITS_JS_SRC_MOD_FILEIO_CLASS_WATCHER_WATCHER_ENTITY_H -#define INTERFACES_KITS_JS_SRC_MOD_FILEIO_CLASS_WATCHER_WATCHER_ENTITY_H - -#include "../../common/napi/uni_header.h" - -namespace OHOS { -namespace DistributedFS { -namespace ModuleFileIO { -class WatcherHandleDeleter { -public: - void operator()(uv_fs_event_t *ptr) - { - uv_fs_event_stop(ptr); - uv_handle_t *handle = reinterpret_cast(ptr); - uv_close(handle, [](uv_handle_t *handle) { delete handle; }); - } -}; - -struct WatcherInforArg { - int events = 0; - napi_env env = nullptr; - napi_ref ref = nullptr; -}; - -struct WatcherEntity { - std::unique_ptr data_; - std::unique_ptr fsEventReq_; -}; -} // namespace ModuleFileIO -} // namespace DistributedFS -} // namespace OHOS -#endif \ No newline at end of file diff --git a/interfaces/kits/js/src/mod_fileio/class_watcher/watcher_n_exporter.cpp b/interfaces/kits/js/src/mod_fileio/class_watcher/watcher_n_exporter.cpp deleted file mode 100644 index a4e27d4..0000000 --- a/interfaces/kits/js/src/mod_fileio/class_watcher/watcher_n_exporter.cpp +++ /dev/null @@ -1,146 +0,0 @@ -/* - * Copyright (c) 2021-2022 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#include "watcher_n_exporter.h" - -#include -#include -#include -#include -#include - -#include "securec.h" - -#include "../../common/log.h" -#include "../../common/napi/n_async/n_async_work_callback.h" -#include "../../common/napi/n_async/n_async_work_promise.h" -#include "../../common/napi/n_class.h" -#include "../../common/napi/n_func_arg.h" -#include "../../common/uni_error.h" -#include "watcher_entity.h" - -namespace OHOS { -namespace DistributedFS { -namespace ModuleFileIO { -using namespace std; - -napi_value WatcherNExporter::Constructor(napi_env env, napi_callback_info info) -{ - NFuncArg funcArg(env, info); - if (!funcArg.InitArgs(NARG_CNT::ZERO)) { - UniError(EINVAL).ThrowErr(env, "Number of arguments unmatched"); - return nullptr; - } - - unique_ptr watcherEntity = make_unique(); - if (!NClass::SetEntityFor(env, funcArg.GetThisVar(), move(watcherEntity))) { - UniError(EIO).ThrowErr(env, "INNER BUG. Failed to wrap entity for obj watcher"); - return nullptr; - } - return funcArg.GetThisVar(); -} - -napi_value WatcherNExporter::StopSync(napi_env env, napi_callback_info info) -{ - NFuncArg funcArg(env, info); - if (!funcArg.InitArgs(NARG_CNT::ZERO)) { - UniError(EINVAL).ThrowErr(env, "Number of arguments unmatched"); - return nullptr; - } - - auto watchEntity = NClass::GetEntityOf(env, funcArg.GetThisVar()); - if (!watchEntity) { - UniError(EINVAL).ThrowErr(env, "get watcherEntity fail"); - return nullptr; - } - - watchEntity->fsEventReq_.reset(); - return NVal::CreateUndefined(env).val_; -} - -napi_value WatcherNExporter::Stop(napi_env env, napi_callback_info info) -{ - NFuncArg funcArg(env, info); - if (!funcArg.InitArgs(NARG_CNT::ZERO, NARG_CNT::ONE)) { - UniError(EINVAL).ThrowErr(env, "Number of arguments unmatched"); - return nullptr; - } - - auto watchEntity = NClass::GetEntityOf(env, funcArg.GetThisVar()); - if (!watchEntity) { - UniError(EINVAL).ThrowErr(env, "get watcherEntity fail"); - return nullptr; - } - - auto cbExec = [watchEntity](napi_env env) -> UniError { - watchEntity->fsEventReq_.reset(); - return UniError(ERRNO_NOERR); - }; - - auto cbCompl = [](napi_env env, UniError err) -> NVal { - if (err) { - return { env, err.GetNapiErr(env) }; - } - return { NVal::CreateUndefined(env) }; - }; - - string procedureName = "FileIOCreaterWatcher"; - NVal thisVar(env, funcArg.GetThisVar()); - if (funcArg.GetArgc() == NARG_CNT::ZERO) { - return NAsyncWorkPromise(env, thisVar).Schedule(procedureName, cbExec, cbCompl).val_; - } else { - NVal cb(env, funcArg[NARG_POS::FIRST]); - return NAsyncWorkCallback(env, thisVar, cb).Schedule(procedureName, cbExec, cbCompl).val_; - } -} - -bool WatcherNExporter::Export() -{ - vector props = { - NVal::DeclareNapiFunction("stop", Stop), - NVal::DeclareNapiFunction("stopSync", StopSync), - }; - - string className = GetClassName(); - bool succ = false; - napi_value classValue = nullptr; - tie(succ, classValue) = NClass::DefineClass(exports_.env_, - className, - WatcherNExporter::Constructor, - std::move(props)); - if (!succ) { - UniError(EIO).ThrowErr(exports_.env_, "INNER BUG. Failed to define class"); - return false; - } - succ = NClass::SaveClass(exports_.env_, className, classValue); - if (!succ) { - UniError(EIO).ThrowErr(exports_.env_, "INNER BUG. Failed to save class"); - return false; - } - - return exports_.AddProp(className, classValue); -} - -string WatcherNExporter::GetClassName() -{ - return WatcherNExporter::className_; -} - -WatcherNExporter::WatcherNExporter(napi_env env, napi_value exports) : NExporter(env, exports) {} - -WatcherNExporter::~WatcherNExporter() {} -} // namespace ModuleFileIO -} // namespace DistributedFS -} // namespace OHOS \ No newline at end of file diff --git a/interfaces/kits/js/src/mod_fileio/class_watcher/watcher_n_exporter.h b/interfaces/kits/js/src/mod_fileio/class_watcher/watcher_n_exporter.h deleted file mode 100644 index d5492cd..0000000 --- a/interfaces/kits/js/src/mod_fileio/class_watcher/watcher_n_exporter.h +++ /dev/null @@ -1,43 +0,0 @@ -/* - * Copyright (c) 2021 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#ifndef INTERFACES_KITS_JS_SRC_MOD_FILEIO_CLASS_WATCHER_WATCHER_N_EXPORTER_H -#define INTERFACES_KITS_JS_SRC_MOD_FILEIO_CLASS_WATCHER_WATCHER_N_EXPORTER_H - -#include - -#include "../../common/napi/n_exporter.h" - -namespace OHOS { -namespace DistributedFS { -namespace ModuleFileIO { -class WatcherNExporter final : public NExporter { -public: - inline static const std::string className_ = "Watcher"; - - bool Export() override; - std::string GetClassName() override; - - static napi_value Constructor(napi_env env, napi_callback_info info); - static napi_value Stop(napi_env env, napi_callback_info info); - static napi_value StopSync(napi_env env, napi_callback_info info); - - WatcherNExporter(napi_env env, napi_value exports); - ~WatcherNExporter() override; -}; -} // namespace ModuleFileIO -} // namespace DistributedFS -} // namespace OHOS -#endif \ No newline at end of file diff --git a/interfaces/kits/js/src/mod_fileio/common_func.cpp b/interfaces/kits/js/src/mod_fileio/common_func.cpp deleted file mode 100644 index 2a97a5d..0000000 --- a/interfaces/kits/js/src/mod_fileio/common_func.cpp +++ /dev/null @@ -1,262 +0,0 @@ -/* - * Copyright (c) 2021 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#include "common_func.h" - -#include -#include -#include -#include -#include - -#include "../common/log.h" -#include "../common/napi/n_class.h" -#include "../common/napi/n_func_arg.h" -#include "../common/napi/n_val.h" -#include "../common/uni_error.h" - -namespace OHOS { -namespace DistributedFS { -namespace ModuleFileIO { -using namespace std; - -static tuple GetActualBuf(napi_env env, void *rawBuf, int64_t bufLen, NVal op) -{ - bool succ = false; - void *realBuf = nullptr; - int64_t opOffset = 0; - if (op.HasProp("offset")) { - tie(succ, opOffset) = op.GetProp("offset").ToInt64(); - if (!succ || opOffset < 0) { - UniError(EINVAL).ThrowErr(env, "Invalid option.offset, positive integer is desired"); - return { false, nullptr, opOffset }; - } else if (opOffset > bufLen) { - UniError(EINVAL).ThrowErr(env, "Invalid option.offset, buffer limit exceeded"); - return { false, nullptr, opOffset }; - } else { - realBuf = static_cast(rawBuf) + opOffset; - } - } else { - realBuf = rawBuf; - } - - return { true, realBuf, opOffset }; -} - -static tuple GetActualLen(napi_env env, int64_t bufLen, int64_t bufOff, NVal op) -{ - bool succ = false; - int64_t retLen; - - if (op.HasProp("length")) { - int64_t opLength; - tie(succ, opLength) = op.GetProp("length").ToInt64(); - if (!succ) { - UniError(EINVAL).ThrowErr(env, "Invalid option.length, expect integer"); - return { false, 0 }; - } - if (opLength < 0) { - retLen = bufLen - bufOff; - } else if (opLength + bufOff > bufLen) { - UniError(EINVAL).ThrowErr(env, "Invalid option.length, buffer limit exceeded"); - return { false, 0 }; - } else { - retLen = opLength; - } - } else { - retLen = bufLen - bufOff; - } - - return { true, retLen }; -} - -int CommonFunc::ConvertJsFlags(int &flags) -{ - static constexpr int USR_O_RDONLY = 00; - static constexpr int USR_O_WRONLY = 01; - static constexpr int USR_O_RDWR = 02; - static constexpr int USR_O_CREAT = 0100; - static constexpr int USR_O_EXCL = 0200; - static constexpr int USR_O_TRUNC = 01000; - static constexpr int USR_O_APPEND = 02000; - static constexpr int USR_O_NONBLOCK = 04000; - static constexpr int USR_O_DIRECTORY = 0200000; - static constexpr int USR_O_NOFOLLOW = 0400000; - static constexpr int USR_O_SYNC = 04010000; - - int flagsABI = 0; - flagsABI |= ((flags & USR_O_RDONLY) == USR_O_RDONLY) ? O_RDONLY : 0; - flagsABI |= ((flags & USR_O_WRONLY) == USR_O_WRONLY) ? O_WRONLY : 0; - flagsABI |= ((flags & USR_O_RDWR) == USR_O_RDWR) ? O_RDWR : 0; - flagsABI |= ((flags & USR_O_CREAT) == USR_O_CREAT) ? O_CREAT : 0; - flagsABI |= ((flags & USR_O_EXCL) == USR_O_EXCL) ? O_EXCL : 0; - flagsABI |= ((flags & USR_O_TRUNC) == USR_O_TRUNC) ? O_TRUNC : 0; - flagsABI |= ((flags & USR_O_APPEND) == USR_O_APPEND) ? O_APPEND : 0; - flagsABI |= ((flags & USR_O_NONBLOCK) == USR_O_NONBLOCK) ? O_NONBLOCK : 0; - flagsABI |= ((flags & USR_O_DIRECTORY) == USR_O_DIRECTORY) ? O_DIRECTORY : 0; - flagsABI |= ((flags & USR_O_NOFOLLOW) == USR_O_NOFOLLOW) ? O_NOFOLLOW : 0; - flagsABI |= ((flags & USR_O_SYNC) == USR_O_SYNC) ? O_SYNC : 0; - flags = flagsABI; - return flagsABI; -} - -tuple, unique_ptr> CommonFunc::GetCopyPathArg(napi_env env, - napi_value srcPath, - napi_value dstPath) -{ - bool succ = false; - unique_ptr src; - tie(succ, src, ignore) = NVal(env, srcPath).ToUTF8String(); - if (!succ) { - return { false, nullptr, nullptr }; - } - - unique_ptr dest; - tie(succ, dest, ignore) = NVal(env, dstPath).ToUTF8String(); - if (!succ) { - return { false, nullptr, nullptr }; - } - return make_tuple(succ, move(src), move(dest)); -} - -tuple CommonFunc::GetReadArg(napi_env env, - napi_value readBuf, - napi_value option) -{ - bool succ = false; - void *retBuf = nullptr; - int64_t retLen; - bool posAssigned = false; - int64_t position; - - NVal txt(env, readBuf); - void *buf = nullptr; - int64_t bufLen; - int offset = 0; - tie(succ, buf, bufLen) = txt.ToArraybuffer(); - if (!succ) { - UniError(EINVAL).ThrowErr(env, "Invalid read buffer, expect arraybuffer"); - return { false, nullptr, 0, posAssigned, position, offset }; - } - - NVal op = NVal(env, option); - tie(succ, retBuf, offset) = GetActualBuf(env, buf, bufLen, op); - if (!succ) { - return { false, nullptr, 0, posAssigned, position, offset }; - } - - int64_t bufOff = static_cast(retBuf) - static_cast(buf); - tie(succ, retLen) = GetActualLen(env, bufLen, bufOff, op); - if (!succ) { - return { false, nullptr, 0, posAssigned, position, offset }; - } - - if (op.HasProp("position")) { - tie(succ, position) = op.GetProp("position").ToInt64(); - if (succ && position >= 0) { - posAssigned = true; - } else { - UniError(EINVAL).ThrowErr(env, "option.position shall be positive number"); - return { false, nullptr, 0, posAssigned, position, offset }; - } - } - - return { true, retBuf, retLen, posAssigned, position, offset }; -} - -static tuple, int64_t> DecodeString(napi_env env, NVal jsStr, NVal encoding) -{ - unique_ptr buf; - if (!jsStr.TypeIs(napi_string)) { - return { false, nullptr, 0 }; - } - - bool succ = false; - if (!encoding) { - return jsStr.ToUTF8String(); - } - - unique_ptr encodingBuf; - tie(succ, encodingBuf, ignore) = encoding.ToUTF8String(); - if (!succ) { - return { false, nullptr, 0 }; - } - string encodingStr(encodingBuf.release()); - if (encodingStr == "utf-8") { - return jsStr.ToUTF8String(); - } else if (encodingStr == "utf-16") { - return jsStr.ToUTF16String(); - } else { - return { false, nullptr, 0 }; - } -} - -// Is everything ok? Do we need to free memory? What's the three args required by fwrite? Where to start writing? -tuple, void *, int64_t, bool, int64_t> CommonFunc::GetWriteArg(napi_env env, - napi_value argWBuf, - napi_value argOption) -{ - void *retBuf = nullptr; - int64_t retLen; - bool hasPos = false; - int64_t retPos; - - /* To get write buffer */ - bool succ = false; - void *buf = nullptr; - int64_t bufLen; - NVal op(env, argOption); - NVal jsBuffer(env, argWBuf); - unique_ptr bufferGuard; - tie(succ, bufferGuard, bufLen) = DecodeString(env, jsBuffer, op.GetProp("encoding")); - if (!succ) { - tie(succ, buf, bufLen) = NVal(env, argWBuf).ToArraybuffer(); - if (!succ) { - UniError(EINVAL).ThrowErr(env, "Illegal write buffer or encoding"); - return { false, nullptr, nullptr, 0, hasPos, retPos }; - } - } else { - buf = bufferGuard.get(); - } - - tie(succ, retBuf, ignore) = GetActualBuf(env, buf, bufLen, op); - if (!succ) { - return { false, nullptr, nullptr, 0, hasPos, retPos }; - } - - int64_t bufOff = static_cast(retBuf) - static_cast(buf); - tie(succ, retLen) = GetActualLen(env, bufLen, bufOff, op); - if (!succ) { - return { false, nullptr, nullptr, 0, hasPos, retPos }; - } - - /* To parse options - Where to begin writing */ - if (op.HasProp("position")) { - int32_t position = 0; - tie(succ, position) = op.GetProp("position").ToInt32(); - if (!succ || position < 0) { - UniError(EINVAL).ThrowErr(env, "option.position shall be positive number"); - return { false, nullptr, nullptr, 0, hasPos, retPos }; - } - hasPos = true; - retPos = position; - } else { - retPos = INVALID_POSITION; - } - return { true, move(bufferGuard), retBuf, retLen, hasPos, retPos }; -} -} // namespace ModuleFileIO -} // namespace DistributedFS -} // namespace OHOS diff --git a/interfaces/kits/js/src/mod_fileio/common_func.h b/interfaces/kits/js/src/mod_fileio/common_func.h deleted file mode 100644 index a4ea80f..0000000 --- a/interfaces/kits/js/src/mod_fileio/common_func.h +++ /dev/null @@ -1,41 +0,0 @@ -/* - * Copyright (c) 2021 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#ifndef INTERFACES_KITS_JS_SRC_MOD_FILEIO_COMMON_FUNC_H -#define INTERFACES_KITS_JS_SRC_MOD_FILEIO_COMMON_FUNC_H - -#include "../common/napi/uni_header.h" - -namespace OHOS { -namespace DistributedFS { -namespace ModuleFileIO { -constexpr int64_t INVALID_POSITION = std::numeric_limits::max(); - -struct CommonFunc { - static int ConvertJsFlags(int &flags); - static std::tuple GetReadArg(napi_env env, - napi_value readBuf, - napi_value option); - static std::tuple, void *, int64_t, bool, int64_t> GetWriteArg(napi_env env, - napi_value argWBuf, - napi_value argOption); - static std::tuple, std::unique_ptr> GetCopyPathArg(napi_env env, - napi_value srcPath, - napi_value dstPath); -}; -} // namespace ModuleFileIO -} // namespace DistributedFS -} // namespace OHOS -#endif \ No newline at end of file diff --git a/interfaces/kits/js/src/mod_fileio/module.cpp b/interfaces/kits/js/src/mod_fileio/module.cpp deleted file mode 100644 index e8bfcaf..0000000 --- a/interfaces/kits/js/src/mod_fileio/module.cpp +++ /dev/null @@ -1,60 +0,0 @@ -/* - * Copyright (c) 2021 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#include -#include - -#include "../common/log.h" -#include "class_constants/constants.h" -#include "class_dir/dir_n_exporter.h" -#include "class_dirent/dirent_n_exporter.h" -#include "class_randomaccessfile/randomaccessfile_n_exporter.h" -#include "class_stat/stat_n_exporter.h" -#include "class_stream/stream_n_exporter.h" -#include "class_watcher/watcher_n_exporter.h" -#include "properties/prop_n_exporter.h" - -using namespace std; - -namespace OHOS { -namespace DistributedFS { -namespace ModuleFileIO { -static napi_value Export(napi_env env, napi_value exports) -{ - std::vector> products; - products.emplace_back(make_unique(env, exports)); - products.emplace_back(make_unique(env, exports)); - products.emplace_back(make_unique(env, exports)); - products.emplace_back(make_unique(env, exports)); - products.emplace_back(make_unique(env, exports)); - products.emplace_back(make_unique(env, exports)); - products.emplace_back(make_unique(env, exports)); - products.emplace_back(make_unique(env, exports)); - - for (auto &&product : products) { - if (!product->Export()) { - HILOGE("INNER BUG. Failed to export class %{public}s for module fileio", product->GetClassName().c_str()); - return nullptr; - } else { - HILOGE("Class %{public}s for module fileio has been exported", product->GetClassName().c_str()); - } - } - return exports; -} - -NAPI_MODULE(fileio, Export) -} // namespace ModuleFileIO -} // namespace DistributedFS -} // namespace OHOS \ No newline at end of file diff --git a/interfaces/kits/js/src/mod_fileio/properties/chmod.cpp b/interfaces/kits/js/src/mod_fileio/properties/chmod.cpp deleted file mode 100644 index 781dcc5..0000000 --- a/interfaces/kits/js/src/mod_fileio/properties/chmod.cpp +++ /dev/null @@ -1,112 +0,0 @@ -/* - * Copyright (c) 2021 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#include "chmod.h" -#include -#include -#include -#include -#include "../../common/napi/n_async/n_async_work_callback.h" -#include "../../common/napi/n_async/n_async_work_promise.h" -#include "../../common/napi/n_func_arg.h" -namespace OHOS { -namespace DistributedFS { -namespace ModuleFileIO { -using namespace std; - -napi_value Chmod::Sync(napi_env env, napi_callback_info info) -{ - NFuncArg funcArg(env, info); - - if (!funcArg.InitArgs(NARG_CNT::TWO)) { - UniError(EINVAL).ThrowErr(env, "Number of arguments unmatched"); - return nullptr; - } - - bool succ = false; - unique_ptr path; - tie(succ, path, ignore) = NVal(env, funcArg[NARG_POS::FIRST]).ToUTF8String(); - if (!succ) { - UniError(EINVAL).ThrowErr(env, "Invalid path"); - return nullptr; - } - - int mode; - tie(succ, mode) = NVal(env, funcArg[NARG_POS::SECOND]).ToInt32(); - if (!succ) { - UniError(EINVAL).ThrowErr(env, "Invalid mode"); - return nullptr; - } - - if (chmod(path.get(), mode) == -1) { - UniError(errno).ThrowErr(env); - return nullptr; - } - return NVal::CreateUndefined(env).val_; -} - -napi_value Chmod::Async(napi_env env, napi_callback_info info) -{ - NFuncArg funcArg(env, info); - - if (!funcArg.InitArgs(NARG_CNT::TWO, NARG_CNT::THREE)) { - UniError(EINVAL).ThrowErr(env, "Number of arguments unmatched"); - return nullptr; - } - - string path; - unique_ptr tmp; - bool succ = false; - tie(succ, tmp, ignore) = NVal(env, funcArg[NARG_POS::FIRST]).ToUTF8String(); - if (!succ) { - UniError(EINVAL).ThrowErr(env, "Invalid path"); - return nullptr; - } - - path = tmp.get(); - int mode; - size_t argc = funcArg.GetArgc(); - tie(succ, mode) = NVal(env, funcArg[NARG_POS::SECOND]).ToInt32(); - if (!succ) { - UniError(EINVAL).ThrowErr(env, "Invalid mode"); - } - - auto cbExec = [path, mode](napi_env env) -> UniError { - if (chmod(path.c_str(), mode) == -1) { - return UniError(errno); - } else { - return UniError(ERRNO_NOERR); - } - }; - auto cbComplete = [](napi_env env, UniError err) -> NVal { - if (err) { - return { env, err.GetNapiErr(env) }; - } - return { NVal::CreateUndefined(env) }; - }; - NVal thisVar(env, funcArg.GetThisVar()); - - string procedureName = "FileIOChmod"; - if (argc == NARG_CNT::TWO) { - return NAsyncWorkPromise(env, thisVar).Schedule(procedureName, cbExec, cbComplete).val_; - } else { - NVal cb(env, funcArg[NARG_POS::THIRD]); - return NAsyncWorkCallback(env, thisVar, cb).Schedule(procedureName, cbExec, cbComplete).val_; - } - return nullptr; -} -} // namespace ModuleFileIO -} // namespace DistributedFS -} // namespace OHOS \ No newline at end of file diff --git a/interfaces/kits/js/src/mod_fileio/properties/chmod.h b/interfaces/kits/js/src/mod_fileio/properties/chmod.h deleted file mode 100644 index 8252891..0000000 --- a/interfaces/kits/js/src/mod_fileio/properties/chmod.h +++ /dev/null @@ -1,32 +0,0 @@ -/* - * Copyright (c) 2021 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#ifndef INTERFACES_KITS_JS_SRC_MOD_FILEIO_PROPERTIES_CHMOD_H -#define INTERFACES_KITS_JS_SRC_MOD_FILEIO_PROPERTIES_CHMOD_H - -#include "../../common/napi/n_val.h" - -namespace OHOS { -namespace DistributedFS { -namespace ModuleFileIO { -class Chmod final { -public: - static napi_value Sync(napi_env env, napi_callback_info info); - static napi_value Async(napi_env env, napi_callback_info info); -}; -} // namespace ModuleFileIO -} // namespace DistributedFS -} // namespace OHOS -#endif \ No newline at end of file diff --git a/interfaces/kits/js/src/mod_fileio/properties/chown.cpp b/interfaces/kits/js/src/mod_fileio/properties/chown.cpp deleted file mode 100644 index dfffbb8..0000000 --- a/interfaces/kits/js/src/mod_fileio/properties/chown.cpp +++ /dev/null @@ -1,126 +0,0 @@ -/* - * Copyright (c) 2021 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#include "chown.h" - -#include -#include -#include - -#include "../../common/napi/n_async/n_async_work_callback.h" -#include "../../common/napi/n_async/n_async_work_promise.h" -#include "../../common/napi/n_func_arg.h" -namespace OHOS { -namespace DistributedFS { -namespace ModuleFileIO { -using namespace std; - -static tuple GetChownArg(napi_env env, const NFuncArg &funcArg) -{ - bool succ = false; - unique_ptr path; - tie(succ, path, ignore) = NVal(env, funcArg[NARG_POS::FIRST]).ToUTF8String(); - if (!succ) { - UniError(EINVAL).ThrowErr(env, "Invalid path"); - return { false, "", -1, -1 }; - } - - int owner; - tie(succ, owner) = NVal(env, funcArg[NARG_POS::SECOND]).ToInt32(); - if (!succ) { - UniError(EINVAL).ThrowErr(env, "Invalid owner"); - return { false, "", -1, -1 }; - } - - int group; - tie(succ, group) = NVal(env, funcArg[NARG_POS::THIRD]).ToInt32(); - if (!succ) { - UniError(EINVAL).ThrowErr(env, "Invalid group"); - return { false, "", -1, -1 }; - } - return { succ, path.get(), owner, group }; -} - -napi_value Chown::Sync(napi_env env, napi_callback_info info) -{ - NFuncArg funcArg(env, info); - - if (!funcArg.InitArgs(NARG_CNT::THREE)) { - UniError(EINVAL).ThrowErr(env, "Number of arguments unmatched"); - return nullptr; - } - - bool succ = false; - int owner; - int group; - string path; - tie(succ, path, owner, group) = GetChownArg(env, funcArg); - if (!succ) { - return nullptr; - } - - if (chown(path.c_str(), owner, group) == -1) { - UniError(errno).ThrowErr(env); - return nullptr; - } - - return NVal::CreateUndefined(env).val_; -} - -napi_value Chown::Async(napi_env env, napi_callback_info info) -{ - NFuncArg funcArg(env, info); - if (!funcArg.InitArgs(NARG_CNT::THREE, NARG_CNT::FOUR)) { - UniError(EINVAL).ThrowErr(env, "Number of arguments unmatched"); - return nullptr; - } - - bool succ = false; - int owner; - int group; - string path; - tie(succ, path, owner, group) = GetChownArg(env, funcArg); - if (!succ) { - return nullptr; - } - - auto cbExec = [path, owner, group](napi_env env) -> UniError { - if (chown(path.c_str(), owner, group) == -1) { - return UniError(errno); - } else { - return UniError(ERRNO_NOERR); - } - }; - - auto cbCompl = [](napi_env env, UniError err) -> NVal { - if (err) { - return { env, err.GetNapiErr(env) }; - } - return { NVal::CreateUndefined(env) }; - }; - - string procedureName = "FileIOChown"; - NVal thisVar(env, funcArg.GetThisVar()); - if (funcArg.GetArgc() == NARG_CNT::THREE) { - return NAsyncWorkPromise(env, thisVar).Schedule(procedureName, cbExec, cbCompl).val_; - } else { - int cbIdx = NARG_POS::FOURTH; - NVal cb(env, funcArg[cbIdx]); - return NAsyncWorkCallback(env, thisVar, cb).Schedule(procedureName, cbExec, cbCompl).val_; - } -} -} // namespace ModuleFileIO -} // namespace DistributedFS -} // namespace OHOS diff --git a/interfaces/kits/js/src/mod_fileio/properties/chown.h b/interfaces/kits/js/src/mod_fileio/properties/chown.h deleted file mode 100644 index 5ac00ec..0000000 --- a/interfaces/kits/js/src/mod_fileio/properties/chown.h +++ /dev/null @@ -1,32 +0,0 @@ -/* - * Copyright (c) 2021 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#ifndef INTERFACES_KITS_JS_SRC_MOD_FILEIO_PROPERTIES_CHOWN_H -#define INTERFACES_KITS_JS_SRC_MOD_FILEIO_PROPERTIES_CHOWN_H - -#include "../../common/napi/n_val.h" - -namespace OHOS { -namespace DistributedFS { -namespace ModuleFileIO { -class Chown final { -public: - static napi_value Sync(napi_env env, napi_callback_info info); - static napi_value Async(napi_env env, napi_callback_info info); -}; -} // namespace ModuleFileIO -} // namespace DistributedFS -} // namespace OHOS -#endif \ No newline at end of file diff --git a/interfaces/kits/js/src/mod_fileio/properties/close.cpp b/interfaces/kits/js/src/mod_fileio/properties/close.cpp deleted file mode 100644 index 32865b6..0000000 --- a/interfaces/kits/js/src/mod_fileio/properties/close.cpp +++ /dev/null @@ -1,96 +0,0 @@ -/* - * Copyright (c) 2021 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#include "close.h" - -#include -#include -#include - -#include "../../common/napi/n_async/n_async_work_callback.h" -#include "../../common/napi/n_async/n_async_work_promise.h" -#include "../../common/napi/n_func_arg.h" -namespace OHOS { -namespace DistributedFS { -namespace ModuleFileIO { -using namespace std; - -napi_value Close::Sync(napi_env env, napi_callback_info info) -{ - NFuncArg funcArg(env, info); - if (!funcArg.InitArgs(NARG_CNT::ONE)) { - UniError(EINVAL).ThrowErr(env, "Number of arguments unmatched"); - return nullptr; - } - - bool succ = false; - int fd; - tie(succ, fd) = NVal(env, funcArg[NARG_POS::FIRST]).ToInt32(); - if (!succ) { - UniError(EINVAL).ThrowErr(env, "Invalid fd"); - return nullptr; - } - - if (close(fd) == -1) { - UniError(errno).ThrowErr(env); - return nullptr; - } - - return NVal::CreateUndefined(env).val_; -} - -napi_value Close::Async(napi_env env, napi_callback_info info) -{ - NFuncArg funcArg(env, info); - if (!funcArg.InitArgs(NARG_CNT::ONE, NARG_CNT::TWO)) { - UniError(EINVAL).ThrowErr(env, "Number of arguments unmatched"); - return nullptr; - } - bool succ = false; - int fd; - tie(succ, fd) = NVal(env, funcArg[NARG_POS::FIRST]).ToInt32(); - if (!succ) { - UniError(EINVAL).ThrowErr(env, "Invalid fd"); - return nullptr; - } - - auto cbExec = [fd](napi_env env) -> UniError { - int ret = close(fd); - if (ret == -1) { - return UniError(errno); - } else { - return UniError(ERRNO_NOERR); - } - }; - auto cbComplete = [](napi_env env, UniError err) -> NVal { - if (err) { - return { env, err.GetNapiErr(env) }; - } else { - return NVal::CreateUndefined(env); - } - }; - string procedureName = "FileIOClose"; - size_t argc = funcArg.GetArgc(); - NVal thisVar(env, funcArg.GetThisVar()); - if (argc == NARG_CNT::ONE) { - return NAsyncWorkPromise(env, thisVar).Schedule(procedureName, cbExec, cbComplete).val_; - } else { - NVal cb(env, funcArg[NARG_POS::SECOND]); - return NAsyncWorkCallback(env, thisVar, cb).Schedule(procedureName, cbExec, cbComplete).val_; - } -} -} // namespace ModuleFileIO -} // namespace DistributedFS -} // namespace OHOS \ No newline at end of file diff --git a/interfaces/kits/js/src/mod_fileio/properties/close.h b/interfaces/kits/js/src/mod_fileio/properties/close.h deleted file mode 100644 index 6d6a396..0000000 --- a/interfaces/kits/js/src/mod_fileio/properties/close.h +++ /dev/null @@ -1,32 +0,0 @@ -/* - * Copyright (c) 2021 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#ifndef INTERFACES_KITS_JS_SRC_MOD_FILEIO_PROPERTIES_CLOSE_H -#define INTERFACES_KITS_JS_SRC_MOD_FILEIO_PROPERTIES_CLOSE_H - -#include "../../common/napi/n_val.h" - -namespace OHOS { -namespace DistributedFS { -namespace ModuleFileIO { -class Close final { -public: - static napi_value Sync(napi_env env, napi_callback_info info); - static napi_value Async(napi_env env, napi_callback_info info); -}; -} // namespace ModuleFileIO -} // namespace DistributedFS -} // namespace OHOS -#endif \ No newline at end of file diff --git a/interfaces/kits/js/src/mod_fileio/properties/copy_file.cpp b/interfaces/kits/js/src/mod_fileio/properties/copy_file.cpp deleted file mode 100644 index 6466a52..0000000 --- a/interfaces/kits/js/src/mod_fileio/properties/copy_file.cpp +++ /dev/null @@ -1,211 +0,0 @@ -/* - * Copyright (c) 2021 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#include "copy_file.h" - -#include -#include -#include -#include -#include -#include -#include - -#include "../../common/file_helper/fd_guard.h" -#include "../../common/napi/n_async/n_async_work_callback.h" -#include "../../common/napi/n_async/n_async_work_promise.h" -#include "../../common/napi/n_func_arg.h" - -namespace OHOS { -namespace DistributedFS { -namespace ModuleFileIO { -using namespace std; - -struct FileInfo { - bool isPath = false; - unique_ptr path; - FDGuard fdg; -}; - -static UniError CopyFileCore(FileInfo &srcFile, FileInfo &destFile) -{ - int res = EINVAL; - if (srcFile.isPath) { - srcFile.fdg.SetFD(open(srcFile.path.get(), O_RDONLY), true); - res = errno; - } - if (!srcFile.fdg) { - return UniError(res); - } - struct stat statbf; - if (fstat(srcFile.fdg.GetFD(), &statbf) == -1) { - return UniError(errno); - } - - if (destFile.isPath) { - destFile.fdg.SetFD(open(destFile.path.get(), O_WRONLY | O_CREAT, statbf.st_mode), true); - res = errno; - } - if (!destFile.fdg) { - return UniError(res); - } - - int block = 4096; - auto copyBuf = make_unique(block); - do { - ssize_t readSize = read(srcFile.fdg.GetFD(), copyBuf.get(), block); - if (readSize == -1) { - return UniError(errno); - } else if (readSize == 0) { - break; - } - ssize_t writeSize = write(destFile.fdg.GetFD(), copyBuf.get(), readSize); - if (writeSize != readSize) { - return UniError(errno); - } - if (readSize != block) { - break; - } - } while (true); - - return UniError(ERRNO_NOERR); -} - -static tuple ParseJsModeAndProm(napi_env env, const NFuncArg &funcArg) -{ - bool succ = false; - bool promise = false; - bool hasMode = false; - int mode = 0; - if (funcArg.GetArgc() == NARG_CNT::THREE && NVal(env, funcArg[NARG_POS::THIRD]).TypeIs(napi_number)) { - promise = true; - hasMode = true; - } else if (funcArg.GetArgc() == NARG_CNT::FOUR) { - hasMode = true; - } - if (hasMode) { - tie(succ, mode) = NVal(env, funcArg[NARG_POS::THIRD]).ToInt32(); - if (!succ) { - return {false, mode, promise}; - } - } - return {true, mode, promise}; -} - -static tuple ParseJsOperand(napi_env env, NVal pathOrFdFromJsArg) -{ - auto [isPath, path, ignore] = pathOrFdFromJsArg.ToUTF8String(); - if (isPath) { - return {true, FileInfo{true, move(path), {}}}; - } - - auto [isFd, fd] = pathOrFdFromJsArg.ToInt32(); - if (isFd) { - return {true, FileInfo{false, {}, {fd, false}}}; - } - - return {false, FileInfo{false, {}, {}}}; -}; - -napi_value CopyFile::Sync(napi_env env, napi_callback_info info) -{ - NFuncArg funcArg(env, info); - if (!funcArg.InitArgs(NARG_CNT::TWO, NARG_CNT::THREE)) { - UniError(EINVAL).ThrowErr(env, "Number of arguments unmatched"); - return nullptr; - } - - auto [succSrc, src] = ParseJsOperand(env, {env, funcArg[NARG_POS::FIRST]}); - auto [succDest, dest] = ParseJsOperand(env, {env, funcArg[NARG_POS::SECOND]}); - if (!succSrc || !succDest) { - UniError(EINVAL).ThrowErr(env, "The first/second argument requires filepath/fd"); - return nullptr; - } - - auto [succMode, mode, ignore] = ParseJsModeAndProm(env, funcArg); - if (!succMode) { - UniError(EINVAL).ThrowErr(env, "Invalid mode"); - return nullptr; - } - - auto err = CopyFileCore(src, dest); - if (err) { - if (err.GetErrno(ERR_CODE_SYSTEM_POSIX) == ENAMETOOLONG) { - UniError(EINVAL).ThrowErr(env, "Filename too long"); - return nullptr; - } - - err.ThrowErr(env); - return nullptr; - } - - return NVal::CreateUndefined(env).val_; -} - -class Para { -public: - FileInfo src_; - FileInfo dest_; - - Para(FileInfo src, FileInfo dest) : src_(move(src)), dest_(move(dest)) {}; -}; - -napi_value CopyFile::Async(napi_env env, napi_callback_info info) -{ - NFuncArg funcArg(env, info); - if (!funcArg.InitArgs(NARG_CNT::TWO, NARG_CNT::FOUR)) { - UniError(EINVAL).ThrowErr(env, "Number of arguments unmatched"); - return nullptr; - } - - auto [succSrc, src] = ParseJsOperand(env, {env, funcArg[NARG_POS::FIRST]}); - auto [succDest, dest] = ParseJsOperand(env, {env, funcArg[NARG_POS::SECOND]}); - if (!succSrc || !succDest) { - UniError(EINVAL).ThrowErr(env, "The first/second argument requires filepath/fd"); - return nullptr; - } - - auto [succMode, mode, promise] = ParseJsModeAndProm(env, funcArg); - if (!succMode) { - UniError(EINVAL).ThrowErr(env, "Invalid mode"); - return nullptr; - } - - auto cbExec = [para = make_shared(move(src), move(dest))](napi_env env) -> UniError { - return CopyFileCore(para->src_, para->dest_); - }; - - auto cbCompl = [](napi_env env, UniError err) -> NVal { - if (err) { - if (err.GetErrno(ERR_CODE_SYSTEM_POSIX) == ENAMETOOLONG) { - return {env, err.GetNapiErr(env, "Filename too long")}; - } - return {env, err.GetNapiErr(env)}; - } - return {NVal::CreateUndefined(env)}; - }; - - string procedureName = "FileIOCopyFile"; - NVal thisVar(env, funcArg.GetThisVar()); - if (funcArg.GetArgc() == NARG_CNT::TWO || promise) { - return NAsyncWorkPromise(env, thisVar).Schedule(procedureName, cbExec, cbCompl).val_; - } else { - NVal cb(env, funcArg[((funcArg.GetArgc() == NARG_CNT::THREE) ? NARG_POS::THIRD : NARG_POS::FOURTH)]); - return NAsyncWorkCallback(env, thisVar, cb).Schedule(procedureName, cbExec, cbCompl).val_; - } -} -} // namespace ModuleFileIO -} // namespace DistributedFS -} // namespace OHOS diff --git a/interfaces/kits/js/src/mod_fileio/properties/copy_file.h b/interfaces/kits/js/src/mod_fileio/properties/copy_file.h deleted file mode 100644 index bef01ef..0000000 --- a/interfaces/kits/js/src/mod_fileio/properties/copy_file.h +++ /dev/null @@ -1,32 +0,0 @@ -/* - * Copyright (c) 2021 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#ifndef INTERFACES_KITS_JS_SRC_MOD_FILEIO_PROPERTIES_COPY_FILE_H -#define INTERFACES_KITS_JS_SRC_MOD_FILEIO_PROPERTIES_COPY_FILE_H - -#include "../../common/napi/n_val.h" - -namespace OHOS { -namespace DistributedFS { -namespace ModuleFileIO { -class CopyFile final { -public: - static napi_value Async(napi_env env, napi_callback_info info); - static napi_value Sync(napi_env env, napi_callback_info info); -}; -} // namespace ModuleFileIO -} // namespace DistributedFS -} // namespace OHOS -#endif \ No newline at end of file diff --git a/interfaces/kits/js/src/mod_fileio/properties/create_randomaccessfile.cpp b/interfaces/kits/js/src/mod_fileio/properties/create_randomaccessfile.cpp deleted file mode 100644 index 8fa4fba..0000000 --- a/interfaces/kits/js/src/mod_fileio/properties/create_randomaccessfile.cpp +++ /dev/null @@ -1,213 +0,0 @@ -/* - * 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 "create_randomaccessfile.h" - -#include -#include -#include -#include -#include -#include - -#include "../../common/log.h" -#include "../../common/napi/n_async/n_async_work_callback.h" -#include "../../common/napi/n_async/n_async_work_promise.h" -#include "../../common/napi/n_class.h" -#include "../../common/napi/n_func_arg.h" -#include "../../common/uni_error.h" -#include "../common_func.h" - -#include "../class_randomaccessfile/randomaccessfile_entity.h" -#include "../class_randomaccessfile/randomaccessfile_n_exporter.h" - -namespace OHOS { -namespace DistributedFS { -namespace ModuleFileIO { -using namespace std; - -struct FileInfo { - bool isPath = false; - unique_ptr path; - FDGuard fdg; -}; - -static bool CheckFilePath(napi_env env, string path) -{ - if (access(path.c_str(), 0) == 0) { - struct stat fileStat; - int ret = stat(path.c_str(), &fileStat); - if (ret != 0) { - UniError(errno).ThrowErr(env, "Cannot stat filepath"); - return false; - } - if ((fileStat.st_mode & S_IFMT) != S_IFREG) { - UniError(EINVAL).ThrowErr(env, "Invalid filepath"); - return false; - } - } - return true; -} - -static tuple ParseJsFileAndFP(napi_env env, napi_value pathOrFdFromJsArg, napi_value FPFromJs) -{ - auto [succ, fp] = NVal(env, FPFromJs).ToInt32(); - if (succ) { - auto [isPath, path, ignore] = NVal(env, pathOrFdFromJsArg).ToUTF8String(); - if (isPath) { - if (CheckFilePath(env, string(path.get()))) { - return { true, FileInfo { true, move(path), {} }, fp }; - } - return { false, FileInfo { false, {}, {} }, -1 }; - } - auto [isFd, fd] = NVal(env, pathOrFdFromJsArg).ToInt32(); - if (isFd) { - if (fd < 0) { - UniError(EINVAL).ThrowErr(env, "Invalid fd"); - return { false, FileInfo { false, {}, {} }, -1 }; - } - return { true, FileInfo { false, {}, { fd, false } }, fp }; - } - UniError(EINVAL).ThrowErr(env, "The first argument requires filepath/fd"); - } - UniError(EINVAL).ThrowErr(env, "Invalid fp"); - return { false, FileInfo { false, {}, {} }, -1 }; -}; - -static tuple GetJsFlags(napi_env env, const NFuncArg &funcArg, FileInfo &fileInfo) -{ - int flags = O_RDONLY; - bool succ = false; - if (fileInfo.isPath) { - if (funcArg.GetArgc() >= NARG_CNT::THREE && !NVal(env, funcArg[NARG_POS::THIRD]).TypeIs(napi_function)) { - tie(succ, flags) = NVal(env, funcArg[NARG_POS::THIRD]).ToInt32(); - if (!succ) { - UniError(EINVAL).ThrowErr(env, "Invalid flags"); - return { false, flags }; - } - (void)CommonFunc::ConvertJsFlags(flags); - } - } - return { true, flags }; -} - -static NVal InstantiateRandomAccessFile(napi_env env, int fd, size_t fp) -{ - napi_value objRAF = NClass::InstantiateClass(env, RandomAccessFileNExporter::className_, {}); - if (!objRAF) { - UniError(EIO).ThrowErr(env, "Cannot instantiate randomaccessfile"); - return NVal(); - } - - auto rafEntity = NClass::GetEntityOf(env, objRAF); - if (!rafEntity) { - UniError(EIO).ThrowErr(env, "Cannot instantiate randomaccessfile because of void entity"); - return NVal(); - } - auto fdg = make_unique(fd); - rafEntity->fd_.swap(fdg); - rafEntity->fpointer = fp; - return { env, objRAF }; -} - -napi_value CreateRandomAccessFile::Sync(napi_env env, napi_callback_info info) -{ - NFuncArg funcArg(env, info); - if (!funcArg.InitArgs(NARG_CNT::TWO, NARG_CNT::THREE)) { - UniError(EINVAL).ThrowErr(env, "Number of arguments unmatched"); - return nullptr; - } - auto [succ, fileInfo, fp] = ParseJsFileAndFP(env, funcArg[NARG_POS::FIRST], funcArg[NARG_POS::SECOND]); - if (!succ) { - return nullptr; - } - - if (fileInfo.isPath) { - auto [succFlags, flags] = GetJsFlags(env, funcArg, fileInfo); - if (!succFlags) { - return nullptr; - } - uv_loop_s *loop = nullptr; - napi_get_uv_event_loop(env, &loop); - uv_fs_t open_req; - int ret = uv_fs_open(loop, &open_req, fileInfo.path.get(), flags, S_IRUSR | - S_IWUSR | S_IRGRP | S_IWGRP, NULL); - if (ret < 0) { - UniError(errno).ThrowErr(env); - return nullptr; - } - fileInfo.fdg.SetFD(open_req.result, false); - uv_fs_req_cleanup(&open_req); - } - return InstantiateRandomAccessFile(env, fileInfo.fdg.GetFD(), fp).val_; -} - -struct AsyncCreateRandomAccessFileArg { - int fd; - size_t fp; -}; - -napi_value CreateRandomAccessFile::Async(napi_env env, napi_callback_info info) -{ - NFuncArg funcArg(env, info); - if (!funcArg.InitArgs(NARG_CNT::TWO, NARG_CNT::FOUR)) { - UniError(EINVAL).ThrowErr(env, "Number of arguments unmatched"); - return nullptr; - } - auto [succ, fileInfo, fp] = ParseJsFileAndFP(env, funcArg[NARG_POS::FIRST], funcArg[NARG_POS::SECOND]); - if (!succ) { - return nullptr; - } - auto [succFlags, flags] = GetJsFlags(env, funcArg, fileInfo); - if (!succFlags) { - return nullptr; - } - auto arg = make_shared(); - auto cbExec = [arg, fileInfo = make_shared(move(fileInfo)), fp = fp, flags = - flags](napi_env env) -> UniError { - if (fileInfo->isPath) { - uv_loop_s *loop = nullptr; - napi_get_uv_event_loop(env, &loop); - uv_fs_t open_req; - int ret = uv_fs_open(loop, &open_req, fileInfo->path.get(), flags, S_IRUSR | - S_IWUSR | S_IRGRP | S_IWGRP, NULL); - if (ret < 0) { - return UniError(errno); - } - fileInfo->fdg.SetFD(open_req.result, false); - uv_fs_req_cleanup(&open_req); - } - arg->fd = fileInfo->fdg.GetFD(); - arg->fp = fp; - return UniError(ERRNO_NOERR); - }; - auto cbCompl = [arg](napi_env env, UniError err) -> NVal { - if (err) { - return { env, err.GetNapiErr(env) }; - } - return InstantiateRandomAccessFile(env, arg->fd, arg->fp); - }; - NVal thisVar(env, funcArg.GetThisVar()); - if (funcArg.GetArgc() == NARG_CNT::TWO || (funcArg.GetArgc() == NARG_CNT::THREE && - NVal(env, funcArg[NARG_POS::THIRD]).TypeIs(napi_number))) { - return NAsyncWorkPromise(env, thisVar).Schedule(createRAFProcedureName, cbExec, cbCompl).val_; - } else { - int cbIdx = ((funcArg.GetArgc() == NARG_CNT::FOUR) ? NARG_POS::FOURTH : NARG_POS::THIRD); - NVal cb(env, funcArg[cbIdx]); - return NAsyncWorkCallback(env, thisVar, cb).Schedule(createRAFProcedureName, cbExec, cbCompl).val_; - } -} -} // namespace ModuleFileIO -} // namespace DistributedFS -} // namespace OHOS \ No newline at end of file diff --git a/interfaces/kits/js/src/mod_fileio/properties/create_randomaccessfile.h b/interfaces/kits/js/src/mod_fileio/properties/create_randomaccessfile.h deleted file mode 100644 index f4a9b36..0000000 --- a/interfaces/kits/js/src/mod_fileio/properties/create_randomaccessfile.h +++ /dev/null @@ -1,33 +0,0 @@ -/* - * 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 INTERFACES_KITS_JS_SRC_MOD_FILEIO_PROPERTIES_CREATE_RANDOMACCESSFILE_H -#define INTERFACES_KITS_JS_SRC_MOD_FILEIO_PROPERTIES_CREATE_RANDOMACCESSFILE_H - -#include "../../common/napi/uni_header.h" - -namespace OHOS { -namespace DistributedFS { -namespace ModuleFileIO { -class CreateRandomAccessFile final { -public: - static napi_value Async(napi_env env, napi_callback_info info); - static napi_value Sync(napi_env env, napi_callback_info info); -}; -const std::string createRAFProcedureName = "FileIOCreateRandomAccessFile"; -} // namespace ModuleFileIO -} // namespace DistributedFS -} // namespace OHOS -#endif \ No newline at end of file diff --git a/interfaces/kits/js/src/mod_fileio/properties/create_stream.cpp b/interfaces/kits/js/src/mod_fileio/properties/create_stream.cpp deleted file mode 100644 index 18c0372..0000000 --- a/interfaces/kits/js/src/mod_fileio/properties/create_stream.cpp +++ /dev/null @@ -1,144 +0,0 @@ -/* - * Copyright (c) 2021 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -#include "create_stream.h" - -#include -#include - -#include "../../common/napi/n_async/n_async_work_callback.h" -#include "../../common/napi/n_async/n_async_work_promise.h" -#include "../../common/napi/n_class.h" -#include "../../common/napi/n_func_arg.h" -#include "../../common/napi/n_val.h" -#include "../../common/uni_error.h" - -#include "../class_stream/stream_entity.h" -#include "../class_stream/stream_n_exporter.h" - -namespace OHOS { -namespace DistributedFS { -namespace ModuleFileIO { -using namespace std; - -static NVal InstantiateStream(napi_env env, unique_ptr fp) -{ - napi_value objStream = NClass::InstantiateClass(env, StreamNExporter::className_, {}); - if (!objStream) { - UniError(EIO).ThrowErr(env, "INNER BUG. Cannot instantiate stream"); - return NVal(); - } - - auto streamEntity = NClass::GetEntityOf(env, objStream); - if (!streamEntity) { - UniError(EIO).ThrowErr(env, "Cannot instantiate stream because of void entity"); - return NVal(); - } - - streamEntity->fp.swap(fp); - return { env, objStream }; -} - -static tuple GetCreateStreamArgs(napi_env env, const NFuncArg &funcArg) -{ - bool succ = false; - unique_ptr path; - tie(succ, path, ignore) = NVal(env, funcArg[NARG_POS::FIRST]).ToUTF8String(); - if (!succ) { - UniError(EINVAL).ThrowErr(env, "Invalid path"); - return { false, "", "" }; - } - - unique_ptr mode; - tie(succ, mode, ignore) = NVal(env, funcArg[NARG_POS::SECOND]).ToUTF8String(); - if (!succ) { - UniError(EINVAL).ThrowErr(env, "Invalid mode"); - return { false, "", "" }; - } - - return { true, path.get(), mode.get() }; -} - -napi_value CreateStream::Sync(napi_env env, napi_callback_info info) -{ - NFuncArg funcArg(env, info); - if (!funcArg.InitArgs(NARG_CNT::TWO)) { - UniError(EINVAL).ThrowErr(env, "Number of arguments unmatched"); - return nullptr; - } - - bool succ = false; - string argPath; - string argMode; - tie(succ, argPath, argMode) = GetCreateStreamArgs(env, funcArg); - if (!succ) { - return nullptr; - } - - unique_ptr fp = { fopen(argPath.c_str(), argMode.c_str()), fclose }; - if (!fp) { - UniError(errno).ThrowErr(env); - return nullptr; - } - return InstantiateStream(env, move(fp)).val_; -} - -struct AsyncCreateStreamArg { - unique_ptr fp = { nullptr, fclose }; -}; - -napi_value CreateStream::Async(napi_env env, napi_callback_info info) -{ - NFuncArg funcArg(env, info); - if (!funcArg.InitArgs(NARG_CNT::TWO, NARG_CNT::THREE)) { - UniError(EINVAL).ThrowErr(env, "Number of arguments unmatched"); - return nullptr; - } - - bool succ = false; - string argPath; - string argMode; - tie(succ, argPath, argMode) = GetCreateStreamArgs(env, funcArg); - if (!succ) { - return nullptr; - } - - auto arg = make_shared(); - auto cbExec = [arg, argPath = move(argPath), argMode = move(argMode)](napi_env env) -> UniError { - arg->fp = { fopen(argPath.c_str(), argMode.c_str()), fclose }; - if (!arg->fp) { - return UniError(errno); - } else { - return UniError(ERRNO_NOERR); - } - }; - auto cbCompl = [arg](napi_env env, UniError err) -> NVal { - if (err) { - return { env, err.GetNapiErr(env) }; - } - return InstantiateStream(env, move(arg->fp)); - }; - - string procedureName = "FileIOCreateStream"; - NVal thisVar(env, funcArg.GetThisVar()); - if (funcArg.GetArgc() == NARG_CNT::TWO) { - return NAsyncWorkPromise(env, thisVar).Schedule(procedureName, cbExec, cbCompl).val_; - } else { - NVal cb(env, funcArg[NARG_POS::THIRD]); - return NAsyncWorkCallback(env, thisVar, cb).Schedule(procedureName, cbExec, cbCompl).val_; - } -} -} // namespace ModuleFileIO -} // namespace DistributedFS -} // namespace OHOS \ No newline at end of file diff --git a/interfaces/kits/js/src/mod_fileio/properties/create_stream.h b/interfaces/kits/js/src/mod_fileio/properties/create_stream.h deleted file mode 100644 index 7c58fa7..0000000 --- a/interfaces/kits/js/src/mod_fileio/properties/create_stream.h +++ /dev/null @@ -1,32 +0,0 @@ -/* - * Copyright (c) 2021 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#ifndef INTERFACES_KITS_JS_SRC_MOD_FILEIO_PROPERTIES_CREATE_STREAM_H -#define INTERFACES_KITS_JS_SRC_MOD_FILEIO_PROPERTIES_CREATE_STREAM_H - -#include "../../common/napi/uni_header.h" - -namespace OHOS { -namespace DistributedFS { -namespace ModuleFileIO { -class CreateStream final { -public: - static napi_value Async(napi_env env, napi_callback_info info); - static napi_value Sync(napi_env env, napi_callback_info info); -}; -} // namespace ModuleFileIO -} // namespace DistributedFS -} // namespace OHOS -#endif \ No newline at end of file diff --git a/interfaces/kits/js/src/mod_fileio/properties/fchmod.cpp b/interfaces/kits/js/src/mod_fileio/properties/fchmod.cpp deleted file mode 100644 index 304268d..0000000 --- a/interfaces/kits/js/src/mod_fileio/properties/fchmod.cpp +++ /dev/null @@ -1,115 +0,0 @@ -/* - * Copyright (c) 2021 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#include "fchmod.h" -#include -#include -#include -#include -#include - -#include "../../common/napi/n_async/n_async_work_callback.h" -#include "../../common/napi/n_async/n_async_work_promise.h" -#include "../../common/napi/n_func_arg.h" -namespace OHOS { -namespace DistributedFS { -namespace ModuleFileIO { -using namespace std; - -napi_value Fchmod::Sync(napi_env env, napi_callback_info info) -{ - NFuncArg funcArg(env, info); - - if (!funcArg.InitArgs(NARG_CNT::TWO)) { - UniError(EINVAL).ThrowErr(env, "Number of arguments unmatched"); - return nullptr; - } - - bool succ = false; - int fd; - tie(succ, fd) = NVal(env, funcArg[NARG_POS::FIRST]).ToInt32(); - if (!succ) { - UniError(EINVAL).ThrowErr(env, "Invalid fd"); - return nullptr; - } - - int mode; - tie(succ, mode) = NVal(env, funcArg[NARG_POS::SECOND]).ToInt32(); - if (!succ) { - UniError(EINVAL).ThrowErr(env, "Invalid mode"); - return nullptr; - } - - int ret = fchmod(fd, mode); - if (ret == -1) { - UniError(errno).ThrowErr(env); - return nullptr; - } - - return NVal::CreateUndefined(env).val_; -} - - -napi_value Fchmod::Async(napi_env env, napi_callback_info info) -{ - NFuncArg funcArg(env, info); - if (!funcArg.InitArgs(NARG_CNT::TWO, NARG_CNT::THREE)) { - UniError(EINVAL).ThrowErr(env, "Number of arguments unmatched"); - return nullptr; - } - - size_t argc = funcArg.GetArgc(); - bool succ = false; - int fd; - tie(succ, fd) = NVal(env, funcArg[NARG_POS::FIRST]).ToInt32(); - if (!succ) { - UniError(EINVAL).ThrowErr(env, "Invalid fd"); - return nullptr; - } - - int mode; - tie(succ, mode) = NVal(env, funcArg[NARG_POS::SECOND]).ToInt32(); - if (!succ) { - UniError(EINVAL).ThrowErr(env, "Invalid owner"); - } - - auto cbExec = [fd, mode](napi_env env) -> UniError { - int ret = fchmod(fd, mode); - if (ret == -1) { - return UniError(errno); - } else { - return UniError(ERRNO_NOERR); - } - }; - - auto cbComplCallback = [](napi_env env, UniError err) -> NVal { - if (err) { - return { env, err.GetNapiErr(env) }; - } - return { NVal::CreateUndefined(env) }; - }; - - string procedureName = "FileIOFchmod"; - NVal thisVar(env, funcArg.GetThisVar()); - if (argc == NARG_CNT::TWO) { - return NAsyncWorkPromise(env, thisVar).Schedule(procedureName, cbExec, cbComplCallback).val_; - } else { - NVal cb(env, funcArg[NARG_POS::THIRD]); - return NAsyncWorkCallback(env, thisVar, cb).Schedule(procedureName, cbExec, cbComplCallback).val_; - } -} -} // namespace ModuleFileIO -} // namespace DistributedFS -} // namespace OHOS \ No newline at end of file diff --git a/interfaces/kits/js/src/mod_fileio/properties/fchmod.h b/interfaces/kits/js/src/mod_fileio/properties/fchmod.h deleted file mode 100644 index eb77118..0000000 --- a/interfaces/kits/js/src/mod_fileio/properties/fchmod.h +++ /dev/null @@ -1,32 +0,0 @@ -/* - * Copyright (c) 2021 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#ifndef INTERFACES_KITS_JS_SRC_MOD_FILEIO_PROPERTIES_FCHMOD_H -#define INTERFACES_KITS_JS_SRC_MOD_FILEIO_PROPERTIES_FCHMOD_H - -#include "../../common/napi/n_val.h" - -namespace OHOS { -namespace DistributedFS { -namespace ModuleFileIO { -class Fchmod final { -public: - static napi_value Sync(napi_env env, napi_callback_info info); - static napi_value Async(napi_env env, napi_callback_info info); -}; -} // namespace ModuleFileIO -} // namespace DistributedFS -} // namespace OHOS -#endif \ No newline at end of file diff --git a/interfaces/kits/js/src/mod_fileio/properties/fchown.cpp b/interfaces/kits/js/src/mod_fileio/properties/fchown.cpp deleted file mode 100644 index bbc2c8e..0000000 --- a/interfaces/kits/js/src/mod_fileio/properties/fchown.cpp +++ /dev/null @@ -1,123 +0,0 @@ -/* - * Copyright (c) 2021 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#include "fchown.h" -#include -#include -#include -#include - -#include "../../common/napi/n_async/n_async_work_callback.h" -#include "../../common/napi/n_async/n_async_work_promise.h" -#include "../../common/napi/n_func_arg.h" -namespace OHOS { -namespace DistributedFS { -namespace ModuleFileIO { -using namespace std; - -napi_value Fchown::Sync(napi_env env, napi_callback_info info) -{ - NFuncArg funcArg(env, info); - if (!funcArg.InitArgs(NARG_CNT::THREE)) { - UniError(EINVAL).ThrowErr(env, "Number of arguments unmatched"); - return nullptr; - } - - bool succ = false; - int fd; - tie(succ, fd) = NVal(env, funcArg[NARG_POS::FIRST]).ToInt32(); - if (!succ) { - UniError(EINVAL).ThrowErr(env, "Invalid fd"); - return nullptr; - } - - int owner; - tie(succ, owner) = NVal(env, funcArg[NARG_POS::SECOND]).ToInt32(); - if (!succ) { - UniError(EINVAL).ThrowErr(env, "Invalid owner"); - } - - int group; - tie(succ, group) = NVal(env, funcArg[NARG_POS::THIRD]).ToInt32(); - if (!succ) { - UniError(EINVAL).ThrowErr(env, "Invalid group"); - } - - int ret = fchown(fd, owner, group); - if (ret == -1) { - UniError(errno).ThrowErr(env); - return nullptr; - } - - return NVal::CreateUndefined(env).val_; -} - -napi_value Fchown::Async(napi_env env, napi_callback_info info) -{ - NFuncArg funcArg(env, info); - if (!funcArg.InitArgs(NARG_CNT::THREE, NARG_CNT::FOUR)) { - UniError(EINVAL).ThrowErr(env, "Number of arguments unmatched"); - return nullptr; - } - - size_t argc = funcArg.GetArgc(); - bool succ = false; - int fd; - tie(succ, fd) = NVal(env, funcArg[NARG_POS::FIRST]).ToInt32(); - if (!succ) { - UniError(EINVAL).ThrowErr(env, "Invalid fd"); - return nullptr; - } - - int owner; - tie(succ, owner) = NVal(env, funcArg[NARG_POS::SECOND]).ToInt32(); - if (!succ) { - UniError(EINVAL).ThrowErr(env, "Invalid owner"); - } - - int group; - tie(succ, group) = NVal(env, funcArg[NARG_POS::THIRD]).ToInt32(); - if (!succ) { - UniError(EINVAL).ThrowErr(env, "Invalid group"); - } - - auto cbExec = [fd, owner, group](napi_env env) -> UniError { - int ret = fchown(fd, owner, group); - if (ret == -1) { - return UniError(errno); - } else { - return UniError(ERRNO_NOERR); - } - }; - - auto cbComplCallback = [](napi_env env, UniError err) -> NVal { - if (err) { - return { env, err.GetNapiErr(env) }; - } - return { NVal::CreateUndefined(env) }; - }; - - string procedureName = "FileIOFchown"; - NVal thisVar(env, funcArg.GetThisVar()); - if (argc == NARG_CNT::THREE) { - return NAsyncWorkPromise(env, thisVar).Schedule(procedureName, cbExec, cbComplCallback).val_; - } else { - NVal cb(env, funcArg[NARG_POS::FOURTH]); - return NAsyncWorkCallback(env, thisVar, cb).Schedule(procedureName, cbExec, cbComplCallback).val_; - } -} -} // namespace ModuleFileIO -} // namespace DistributedFS -} // namespace OHOS \ No newline at end of file diff --git a/interfaces/kits/js/src/mod_fileio/properties/fchown.h b/interfaces/kits/js/src/mod_fileio/properties/fchown.h deleted file mode 100644 index 7439f2e..0000000 --- a/interfaces/kits/js/src/mod_fileio/properties/fchown.h +++ /dev/null @@ -1,32 +0,0 @@ -/* - * Copyright (c) 2021 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#ifndef INTERFACES_KITS_JS_SRC_MOD_FILEIO_PROPERTIES_FCHOWN_H -#define INTERFACES_KITS_JS_SRC_MOD_FILEIO_PROPERTIES_FCHOWN_H - -#include "../../common/napi/n_val.h" - -namespace OHOS { -namespace DistributedFS { -namespace ModuleFileIO { -class Fchown final { -public: - static napi_value Sync(napi_env env, napi_callback_info info); - static napi_value Async(napi_env env, napi_callback_info info); -}; -} // namespace ModuleFileIO -} // namespace DistributedFS -} // namespace OHOS -#endif \ No newline at end of file diff --git a/interfaces/kits/js/src/mod_fileio/properties/fdatasync.cpp b/interfaces/kits/js/src/mod_fileio/properties/fdatasync.cpp deleted file mode 100644 index 9592838..0000000 --- a/interfaces/kits/js/src/mod_fileio/properties/fdatasync.cpp +++ /dev/null @@ -1,102 +0,0 @@ -/* - * Copyright (c) 2021 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#include "fdatasync.h" -#include -#include -#include -#include -#include - -#include "../../common/napi/n_async/n_async_work_callback.h" -#include "../../common/napi/n_async/n_async_work_promise.h" -#include "../../common/napi/n_func_arg.h" -namespace OHOS { -namespace DistributedFS { -namespace ModuleFileIO { -using namespace std; - -napi_value Fdatasync::Sync(napi_env env, napi_callback_info info) -{ - NFuncArg funcArg(env, info); - - if (!funcArg.InitArgs(NARG_CNT::ONE)) { - UniError(EINVAL).ThrowErr(env, "Number of arguments unmatched"); - return nullptr; - } - - bool succ = false; - int fd; - tie(succ, fd) = NVal(env, funcArg[NARG_POS::FIRST]).ToInt32(); - if (!succ) { - UniError(EINVAL).ThrowErr(env, "Invalid fd"); - return nullptr; - } - - int ret = fdatasync(fd); - if (ret == -1) { - UniError(errno).ThrowErr(env); - return nullptr; - } - - return NVal::CreateUndefined(env).val_; -} - - -napi_value Fdatasync::Async(napi_env env, napi_callback_info info) -{ - NFuncArg funcArg(env, info); - if (!funcArg.InitArgs(NARG_CNT::ONE, NARG_CNT::TWO)) { - UniError(EINVAL).ThrowErr(env, "Number of arguments unmatched"); - return nullptr; - } - - size_t argc = funcArg.GetArgc(); - bool succ = false; - int fd; - tie(succ, fd) = NVal(env, funcArg[NARG_POS::FIRST]).ToInt32(); - if (!succ) { - UniError(EINVAL).ThrowErr(env, "Invalid fd"); - return nullptr; - } - - auto cbExec = [fd](napi_env env) -> UniError { - int ret = fdatasync(fd); - if (ret == -1) { - return UniError(errno); - } else { - return UniError(ERRNO_NOERR); - } - }; - - auto cbComplCallback = [](napi_env env, UniError err) -> NVal { - if (err) { - return { env, err.GetNapiErr(env) }; - } - return { NVal::CreateUndefined(env) }; - }; - - string procedureName = "FileIOFdatasync"; - NVal thisVar(env, funcArg.GetThisVar()); - if (argc == NARG_CNT::ONE) { - return NAsyncWorkPromise(env, thisVar).Schedule(procedureName, cbExec, cbComplCallback).val_; - } else { - NVal cb(env, funcArg[NARG_POS::SECOND]); - return NAsyncWorkCallback(env, thisVar, cb).Schedule(procedureName, cbExec, cbComplCallback).val_; - } -} -} // namespace ModuleFileIO -} // namespace DistributedFS -} // namespace OHOS \ No newline at end of file diff --git a/interfaces/kits/js/src/mod_fileio/properties/fdatasync.h b/interfaces/kits/js/src/mod_fileio/properties/fdatasync.h deleted file mode 100644 index f10fcbd..0000000 --- a/interfaces/kits/js/src/mod_fileio/properties/fdatasync.h +++ /dev/null @@ -1,32 +0,0 @@ -/* - * Copyright (c) 2021 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#ifndef INTERFACES_KITS_JS_SRC_MOD_FILEIO_PROPERTIES_FDATASYNC_H -#define INTERFACES_KITS_JS_SRC_MOD_FILEIO_PROPERTIES_FDATASYNC_H - -#include "../../common/napi/n_val.h" - -namespace OHOS { -namespace DistributedFS { -namespace ModuleFileIO { -class Fdatasync final { -public: - static napi_value Sync(napi_env env, napi_callback_info info); - static napi_value Async(napi_env env, napi_callback_info info); -}; -} // namespace ModuleFileIO -} // namespace DistributedFS -} // namespace OHOS -#endif \ No newline at end of file diff --git a/interfaces/kits/js/src/mod_fileio/properties/fdopen_stream.cpp b/interfaces/kits/js/src/mod_fileio/properties/fdopen_stream.cpp deleted file mode 100644 index 2baf393..0000000 --- a/interfaces/kits/js/src/mod_fileio/properties/fdopen_stream.cpp +++ /dev/null @@ -1,146 +0,0 @@ -/* - * Copyright (c) 2021 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#include "fdopen_stream.h" -#include -#include - -#include "../../common/napi/n_async/n_async_work_callback.h" -#include "../../common/napi/n_async/n_async_work_promise.h" -#include "../../common/napi/n_class.h" -#include "../../common/napi/n_func_arg.h" -#include "../../common/napi/n_val.h" -#include "../../common/uni_error.h" -#include "../class_stream/stream_entity.h" -#include "../class_stream/stream_n_exporter.h" - -namespace OHOS { -namespace DistributedFS { -namespace ModuleFileIO { -using namespace std; - -static NVal InstantiateStream(napi_env env, unique_ptr fp) -{ - napi_value objStream = NClass::InstantiateClass(env, StreamNExporter::className_, {}); - if (!objStream) { - UniError(EIO).ThrowErr(env, "INNER BUG. Cannot instantiate stream"); - return NVal(); - } - - auto streamEntity = NClass::GetEntityOf(env, objStream); - if (!streamEntity) { - UniError(EIO).ThrowErr(env, "Cannot instantiate stream because of void entity"); - return NVal(); - } - - streamEntity->fp.swap(fp); - return { env, objStream }; -} - -static tuple GetFdopenStreamArgs(napi_env env, const NFuncArg &funcArg) -{ - bool succ = false; - int fd; - tie(succ, fd) = NVal(env, funcArg[NARG_POS::FIRST]).ToInt32(); - if (!succ) { - UniError(EINVAL).ThrowErr(env, "Arg fd is required to be type integer"); - return { false, -1, "" }; - } - - unique_ptr mode; - tie(succ, mode, ignore) = NVal(env, funcArg[NARG_POS::SECOND]).ToUTF8String(); - if (!succ) { - UniError(EINVAL).ThrowErr(env, "Arg mode is required to be type string"); - return { false, -1, "" }; - } - return { true, fd, mode.get() }; -} - -napi_value FdopenStream::Sync(napi_env env, napi_callback_info info) -{ - NFuncArg funcArg(env, info); - - if (!funcArg.InitArgs(NARG_CNT::TWO)) { - UniError(EINVAL).ThrowErr(env, "Number of arguments unmatched"); - return nullptr; - } - - bool succ = false; - int fd; - string mode; - - tie(succ, fd, mode) = GetFdopenStreamArgs(env, funcArg); - if (!succ) { - return nullptr; - } - - unique_ptr fp = { fdopen(fd, mode.c_str()), fclose }; - if (!fp) { - UniError(errno).ThrowErr(env); - return nullptr; - } - - return InstantiateStream(env, move(fp)).val_; -} - -struct AsyncFdopenStreamArg { - unique_ptr fp = { nullptr, fclose }; -}; - -napi_value FdopenStream::Async(napi_env env, napi_callback_info info) -{ - NFuncArg funcArg(env, info); - if (!funcArg.InitArgs(NARG_CNT::TWO, NARG_CNT::THREE)) { - UniError(EINVAL).ThrowErr(env, "Number of arguments unmatched"); - return nullptr; - } - - bool success = false; - int fd; - string mode; - tie(success, fd, mode) = GetFdopenStreamArgs(env, funcArg); - if (!success) { - return nullptr; - } - - auto arg = make_shared(); - auto cbExec = [arg, fd, mode = move(mode)](napi_env env) -> UniError { - arg->fp = { fdopen(fd, mode.c_str()), fclose }; - if (!arg->fp) { - return UniError(errno); - } else { - return UniError(ERRNO_NOERR); - } - }; - - auto cbCompl = [arg](napi_env env, UniError err) -> NVal { - if (err) { - return { env, err.GetNapiErr(env) }; - } - return InstantiateStream(env, move(arg->fp)); - }; - - string procedureName = "FileIOFdopenStream"; - NVal thisVar(env, funcArg.GetThisVar()); - if (funcArg.GetArgc() == NARG_CNT::TWO) { - return NAsyncWorkPromise(env, thisVar).Schedule(procedureName, cbExec, cbCompl).val_; - } else { - NVal cb(env, funcArg[NARG_POS::THIRD]); - return NAsyncWorkCallback(env, thisVar, cb).Schedule(procedureName, cbExec, cbCompl).val_; - } -} -} // namespace ModuleFileIO -} // namespace DistributedFS -} // namespace OHOS \ No newline at end of file diff --git a/interfaces/kits/js/src/mod_fileio/properties/fdopen_stream.h b/interfaces/kits/js/src/mod_fileio/properties/fdopen_stream.h deleted file mode 100644 index 195369e..0000000 --- a/interfaces/kits/js/src/mod_fileio/properties/fdopen_stream.h +++ /dev/null @@ -1,32 +0,0 @@ -/* - * Copyright (c) 2021 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#ifndef INTERFACES_KITS_JS_SRC_MOD_FILEIO_PROPERTIES_FDOPEN_STREAM_H -#define INTERFACES_KITS_JS_SRC_MOD_FILEIO_PROPERTIES_FDOPEN_STREAM_H - -#include "../../common/napi/uni_header.h" - -namespace OHOS { -namespace DistributedFS { -namespace ModuleFileIO { -class FdopenStream final { -public: - static napi_value Async(napi_env env, napi_callback_info info); - static napi_value Sync(napi_env env, napi_callback_info info); -}; -} // namespace ModuleFileIO -} // namespace DistributedFS -} // namespace OHOS -#endif \ No newline at end of file diff --git a/interfaces/kits/js/src/mod_fileio/properties/fstat.cpp b/interfaces/kits/js/src/mod_fileio/properties/fstat.cpp deleted file mode 100644 index 6479cdf..0000000 --- a/interfaces/kits/js/src/mod_fileio/properties/fstat.cpp +++ /dev/null @@ -1,128 +0,0 @@ -/* - * Copyright (c) 2021 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -#include "fstat.h" - -#include -#include - -#include "../../common/napi/n_async/n_async_work_callback.h" -#include "../../common/napi/n_async/n_async_work_promise.h" -#include "../../common/napi/n_class.h" -#include "../../common/napi/n_func_arg.h" -#include "../../common/napi/n_val.h" -#include "../../common/uni_error.h" - -#include "../class_stat/stat_entity.h" -#include "../class_stat/stat_n_exporter.h" - -namespace OHOS { -namespace DistributedFS { -namespace ModuleFileIO { -using namespace std; - -napi_value Fstat::Sync(napi_env env, napi_callback_info info) -{ - NFuncArg funcArg(env, info); - if (!funcArg.InitArgs(NARG_CNT::ONE)) { - UniError(EINVAL).ThrowErr(env, "Number of arguments unmatched"); - return nullptr; - } - - bool succ = false; - - int fd; - tie(succ, fd) = NVal(env, funcArg[NARG_POS::FIRST]).ToInt32(); - if (!succ) { - UniError(EINVAL).ThrowErr(env, "Invalid fd"); - return nullptr; - } - - struct stat buf; - if (fstat(fd, &buf) == -1) { - UniError(errno).ThrowErr(env); - return nullptr; - } - - napi_value objStat = NClass::InstantiateClass(env, StatNExporter::className_, {}); - if (!objStat) { - UniError(EINVAL).ThrowErr(env, "Cannot instantiate class"); - return nullptr; - } - - auto statEntity = NClass::GetEntityOf(env, objStat); - if (!statEntity) { - UniError(EINVAL).ThrowErr(env, "Cannot get the entity of objStat"); - return nullptr; - } - statEntity->stat_ = buf; - - return objStat; -} - -struct AsyncStatArg { - struct stat stat_; -}; - -napi_value Fstat::Async(napi_env env, napi_callback_info info) -{ - NFuncArg funcArg(env, info); - if (!funcArg.InitArgs(NARG_CNT::ONE, NARG_CNT::TWO)) { - UniError(EINVAL).ThrowErr(env, "Number of arguments unmatched"); - return nullptr; - } - - bool succ = false; - int fd; - tie(succ, fd) = NVal(env, funcArg[NARG_POS::FIRST]).ToInt32(); - if (!succ) { - UniError(EINVAL).ThrowErr(env, "Invalid fd"); - return nullptr; - } - - auto arg = make_shared(); - auto cbExec = [fd, arg](napi_env env) -> UniError { - if (fstat(fd, &arg->stat_)) { - return UniError(errno); - } else { - return UniError(ERRNO_NOERR); - } - }; - auto cbCompl = [arg](napi_env env, UniError err) -> NVal { - if (err) { - return { env, err.GetNapiErr(env) }; - } - napi_value objStat = NClass::InstantiateClass(env, StatNExporter::className_, {}); - if (!objStat) { - return { env, UniError(EIO).GetNapiErr(env) }; - } - auto statEntity = NClass::GetEntityOf(env, objStat); - if (!statEntity) { - return { env, UniError(EIO).GetNapiErr(env) }; - } - statEntity->stat_ = arg->stat_; - return { env, objStat }; - }; - NVal thisVar(env, funcArg.GetThisVar()); - string procedureName = "fileIOFstat"; - if (funcArg.GetArgc() == NARG_CNT::ONE) { - return NAsyncWorkPromise(env, thisVar).Schedule(procedureName, cbExec, cbCompl).val_; - } else { - NVal cb(env, funcArg[NARG_POS::SECOND]); - return NAsyncWorkCallback(env, thisVar, cb).Schedule(procedureName, cbExec, cbCompl).val_; - } -} -} // namespace ModuleFileIO -} // namespace DistributedFS -} // namespace OHOS \ No newline at end of file diff --git a/interfaces/kits/js/src/mod_fileio/properties/fstat.h b/interfaces/kits/js/src/mod_fileio/properties/fstat.h deleted file mode 100644 index 27395df..0000000 --- a/interfaces/kits/js/src/mod_fileio/properties/fstat.h +++ /dev/null @@ -1,32 +0,0 @@ -/* - * Copyright (c) 2021 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#ifndef INTERFACES_KITS_JS_SRC_MOD_FILEIO_PROPERTIES_FSTAT_H -#define INTERFACES_KITS_JS_SRC_MOD_FILEIO_PROPERTIES_FSTAT_H - -#include "../../common/napi/uni_header.h" - -namespace OHOS { -namespace DistributedFS { -namespace ModuleFileIO { -class Fstat final { -public: - static napi_value Async(napi_env env, napi_callback_info info); - static napi_value Sync(napi_env env, napi_callback_info info); -}; -} // namespace ModuleFileIO -} // namespace DistributedFS -} // namespace OHOS -#endif \ No newline at end of file diff --git a/interfaces/kits/js/src/mod_fileio/properties/fsync.cpp b/interfaces/kits/js/src/mod_fileio/properties/fsync.cpp deleted file mode 100644 index 9e4afdc..0000000 --- a/interfaces/kits/js/src/mod_fileio/properties/fsync.cpp +++ /dev/null @@ -1,97 +0,0 @@ -/* - * Copyright (c) 2021 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#include "fsync.h" - -#include -#include -#include - -#include "../../common/napi/n_async/n_async_work_callback.h" -#include "../../common/napi/n_async/n_async_work_promise.h" -#include "../../common/napi/n_func_arg.h" -namespace OHOS { -namespace DistributedFS { -namespace ModuleFileIO { -using namespace std; - -napi_value Fsync::Sync(napi_env env, napi_callback_info info) -{ - NFuncArg funcArg(env, info); - - if (!funcArg.InitArgs(NARG_CNT::ONE)) { - UniError(EINVAL).ThrowErr(env, "Number of arguments unmatched"); - return nullptr; - } - - bool succ = false; - int fd; - tie(succ, fd) = NVal(env, funcArg[NARG_POS::FIRST]).ToInt32(); - if (!succ) { - UniError(EINVAL).ThrowErr(env, "Invalid fd"); - return nullptr; - } - - if (fsync(fd) == -1) { - UniError(errno).ThrowErr(env); - return nullptr; - } - return NVal::CreateUndefined(env).val_; -} - -napi_value Fsync::Async(napi_env env, napi_callback_info info) -{ - NFuncArg funcArg(env, info); - - if (!funcArg.InitArgs(NARG_CNT::ONE, NARG_CNT::TWO)) { - UniError(EINVAL).ThrowErr(env, "Number of arguments unmatched"); - return nullptr; - } - - bool succ = false; - int fd; - tie(succ, fd) = NVal(env, funcArg[NARG_POS::FIRST]).ToInt32(); - if (!succ) { - UniError(EINVAL).ThrowErr(env, "Invalid fd"); - return nullptr; - } - - auto cbExec = [fd](napi_env env) -> UniError { - if (fsync(fd) == -1) { - return UniError(errno); - } else { - return UniError(ERRNO_NOERR); - } - }; - auto cbComplete = [](napi_env env, UniError err) -> NVal { - if (err) { - return { env, err.GetNapiErr(env) }; - } else { - return NVal::CreateUndefined(env); - } - }; - string procedureName = "FileIOFsync"; - size_t argc = funcArg.GetArgc(); - NVal thisVar(env, funcArg.GetThisVar()); - if (argc == NARG_CNT::ONE) { - return NAsyncWorkPromise(env, thisVar).Schedule(procedureName, cbExec, cbComplete).val_; - } else { - NVal cb(env, funcArg[NARG_POS::SECOND]); - return NAsyncWorkCallback(env, thisVar, cb).Schedule(procedureName, cbExec, cbComplete).val_; - } -} -} // namespace ModuleFileIO -} // namespace DistributedFS -} // namespace OHOS diff --git a/interfaces/kits/js/src/mod_fileio/properties/fsync.h b/interfaces/kits/js/src/mod_fileio/properties/fsync.h deleted file mode 100644 index 0e2a54e..0000000 --- a/interfaces/kits/js/src/mod_fileio/properties/fsync.h +++ /dev/null @@ -1,32 +0,0 @@ -/* - * Copyright (c) 2021 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#ifndef INTERFACES_KITS_JS_SRC_MOD_FILEIO_PROPERTIES_FSYNC_H -#define INTERFACES_KITS_JS_SRC_MOD_FILEIO_PROPERTIES_FSYNC_H - -#include "../../common/napi/n_val.h" - -namespace OHOS { -namespace DistributedFS { -namespace ModuleFileIO { -class Fsync final { -public: - static napi_value Sync(napi_env env, napi_callback_info info); - static napi_value Async(napi_env env, napi_callback_info info); -}; -} // namespace ModuleFileIO -} // namespace DistributedFS -} // namespace OHOS -#endif \ No newline at end of file diff --git a/interfaces/kits/js/src/mod_fileio/properties/ftruncate.cpp b/interfaces/kits/js/src/mod_fileio/properties/ftruncate.cpp deleted file mode 100644 index 49e2039..0000000 --- a/interfaces/kits/js/src/mod_fileio/properties/ftruncate.cpp +++ /dev/null @@ -1,119 +0,0 @@ -/* - * Copyright (c) 2021 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#include "ftruncate.h" - -#include -#include -#include - -#include "../../common/napi/n_async/n_async_work_callback.h" -#include "../../common/napi/n_async/n_async_work_promise.h" -#include "../../common/napi/n_func_arg.h" - -namespace OHOS { -namespace DistributedFS { -namespace ModuleFileIO { -using namespace std; - -napi_value Ftruncate::Sync(napi_env env, napi_callback_info info) -{ - NFuncArg funcArg(env, info); - if (!funcArg.InitArgs(NARG_CNT::ONE, NARG_CNT::TWO)) { - UniError(EINVAL).ThrowErr(env, "Number of arguments unmatched"); - return nullptr; - } - - bool succ = false; - - int fd; - tie(succ, fd) = NVal(env, funcArg[NARG_POS::FIRST]).ToInt32(); - if (!succ) { - UniError(EINVAL).ThrowErr(env, "Invalid fd"); - return nullptr; - } - - size_t argc = funcArg.GetArgc(); - int ret = -1; - if (argc == NARG_CNT::ONE) { - ret = ftruncate(fd, 0); - } else { - int len; - tie(succ, len) = NVal(env, funcArg[NARG_POS::SECOND]).ToInt32(); - if (!succ) { - UniError(EINVAL).ThrowErr(env, "Invalid len"); - return nullptr; - } - ret = ftruncate(fd, len); - } - - if (ret == -1) { - UniError(errno).ThrowErr(env); - return nullptr; - } - - return NVal::CreateUndefined(env).val_; -} -napi_value Ftruncate::Async(napi_env env, napi_callback_info info) -{ - NFuncArg funcArg(env, info); - if (!funcArg.InitArgs(NARG_CNT::ONE, NARG_CNT::THREE)) { - UniError(EINVAL).ThrowErr(env, "Number of arguments unmatched"); - return nullptr; - } - bool succ = false; - int fd; - int len = 0; - tie(succ, fd) = NVal(env, funcArg[NARG_POS::FIRST]).ToInt32(); - if (!succ) { - UniError(EINVAL).ThrowErr(env, "Invalid fd"); - return nullptr; - } - size_t argc = funcArg.GetArgc(); - if (argc > NARG_CNT::ONE) { - tie(succ, len) = NVal(env, funcArg[NARG_POS::SECOND]).ToInt32(); - if (!succ) { - UniError(EINVAL).ThrowErr(env, "Invalid len"); - return nullptr; - } - } - - auto cbExec = [fd, len](napi_env env) -> UniError { - int ret = ftruncate(fd, len); - if (ret == -1) { - return UniError(errno); - } else { - return UniError(ERRNO_NOERR); - } - }; - auto cbComplete = [](napi_env env, UniError err) -> NVal { - if (err) { - return { env, err.GetNapiErr(env) }; - } else { - return NVal::CreateUndefined(env); - } - }; - string procedureName = "fileIOFtruncate"; - NVal thisVar(env, funcArg.GetThisVar()); - if (argc == NARG_CNT::ONE || (argc == NARG_CNT::TWO && NVal(env, funcArg[NARG_POS::SECOND]).TypeIs(napi_number))) { - return NAsyncWorkPromise(env, thisVar).Schedule(procedureName, cbExec, cbComplete).val_; - } else { - NVal cb(env, funcArg[NARG_POS::THIRD]); - return NAsyncWorkCallback(env, thisVar, cb).Schedule(procedureName, cbExec, cbComplete).val_; - } -} -} // namespace ModuleFileIO -} // namespace DistributedFS -} // namespace OHOS \ No newline at end of file diff --git a/interfaces/kits/js/src/mod_fileio/properties/ftruncate.h b/interfaces/kits/js/src/mod_fileio/properties/ftruncate.h deleted file mode 100644 index f9d076e..0000000 --- a/interfaces/kits/js/src/mod_fileio/properties/ftruncate.h +++ /dev/null @@ -1,32 +0,0 @@ -/* - * Copyright (c) 2021 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#ifndef INTERFACES_KITS_JS_SRC_MOD_FILEIO_PROPERTIES_FTRUNCATE_H -#define INTERFACES_KITS_JS_SRC_MOD_FILEIO_PROPERTIES_FTRUNCATE_H - -#include "../../common/napi/n_val.h" - -namespace OHOS { -namespace DistributedFS { -namespace ModuleFileIO { -class Ftruncate final { -public: - static napi_value Sync(napi_env env, napi_callback_info info); - static napi_value Async(napi_env env, napi_callback_info info); -}; -} // namespace ModuleFileIO -} // namespace DistributedFS -} // namespace OHOS -#endif \ No newline at end of file diff --git a/interfaces/kits/js/src/mod_fileio/properties/hash.cpp b/interfaces/kits/js/src/mod_fileio/properties/hash.cpp deleted file mode 100644 index 8497c26..0000000 --- a/interfaces/kits/js/src/mod_fileio/properties/hash.cpp +++ /dev/null @@ -1,131 +0,0 @@ -/* - * Copyright (c) 2021 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#include "hash.h" - -#include -#include - -#include "../../common/file_helper/hash_file.h" - -namespace OHOS { -namespace DistributedFS { -namespace ModuleFileIO { -using namespace std; - -enum HASH_ALGORITHM_TYPE { - HASH_ALGORITHM_TYPE_MD5, - HASH_ALGORITHM_TYPE_SHA1, - HASH_ALGORITHM_TYPE_SHA256, - HASH_ALGORITHM_TYPE_UNSUPPORTED, -}; - -static HASH_ALGORITHM_TYPE GetHashAlgorithm(const unique_ptr &alg, const size_t algLen) -{ - if (algLen == ((sizeof("md5") - 1)) && !strncmp(alg.get(), "md5", algLen)) { - return HASH_ALGORITHM_TYPE_MD5; - } else if (algLen == ((sizeof("sha1") - 1)) && !strncmp(alg.get(), "sha1", algLen)) { - return HASH_ALGORITHM_TYPE_SHA1; - } else if (algLen == ((sizeof("sha256") - 1)) && !strncmp(alg.get(), "sha256", algLen)) { - return HASH_ALGORITHM_TYPE_SHA256; - } else { - return HASH_ALGORITHM_TYPE_UNSUPPORTED; - } -} - -static tuple, HASH_ALGORITHM_TYPE, bool> GetHashArgs(napi_env env, const NFuncArg &funcArg) -{ - bool isPromise = false; - bool succ = false; - unique_ptr path; - tie(succ, path, ignore) = NVal(env, funcArg[NARG_POS::FIRST]).ToUTF8String(); - if (!succ) { - UniError(EINVAL).ThrowErr(env, "Invalid path"); - return { false, nullptr, HASH_ALGORITHM_TYPE_UNSUPPORTED, isPromise }; - } - - unique_ptr alg; - size_t algLen; - tie(succ, alg, algLen) = NVal(env, funcArg[NARG_POS::SECOND]).ToUTF8String(); - if (!succ) { - UniError(EINVAL).ThrowErr(env, "Invalid algorithm"); - return { false, nullptr, HASH_ALGORITHM_TYPE_UNSUPPORTED, isPromise }; - } - - HASH_ALGORITHM_TYPE algType = GetHashAlgorithm(alg, algLen); - if (algType == HASH_ALGORITHM_TYPE_UNSUPPORTED) { - UniError(EINVAL).ThrowErr(env, "Invalid algorithm"); - return { false, nullptr, HASH_ALGORITHM_TYPE_UNSUPPORTED, isPromise }; - } - - if (funcArg.GetArgc() == NARG_CNT::THREE && !NVal(env, funcArg[NARG_POS::SECOND]).TypeIs(napi_function)) { - UniError(EINVAL).ThrowErr(env, "Invalid callback"); - return { false, nullptr, HASH_ALGORITHM_TYPE_UNSUPPORTED, isPromise }; - } - - isPromise = funcArg.GetArgc() == NARG_CNT::TWO; - return { true, move(path), algType, isPromise }; -} - -napi_value Hash::Async(napi_env env, napi_callback_info info) -{ - NFuncArg funcArg(env, info); - if (!funcArg.InitArgs(NARG_CNT::TWO, NARG_CNT::THREE)) { - UniError(EINVAL).ThrowErr(env, "Number of arguments unmatched"); - return nullptr; - } - - bool succ = false; - unique_ptr fpath; - HASH_ALGORITHM_TYPE algType; - bool isPromise = false; - tie(succ, fpath, algType, isPromise) = GetHashArgs(env, funcArg); - if (!succ) { - return nullptr; - } - - auto arg = make_shared(); - auto cbExec = [fpath = string(fpath.release()), arg, algType](napi_env env) -> UniError { - int ret = EIO; - string &res = *arg; - if (algType == HASH_ALGORITHM_TYPE_MD5) { - tie(ret, res) = HashFile::HashWithMD5(fpath); - } else if (algType == HASH_ALGORITHM_TYPE_SHA1) { - tie(ret, res) = HashFile::HashWithSHA1(fpath); - } else if (algType == HASH_ALGORITHM_TYPE_SHA256) { - tie(ret, res) = HashFile::HashWithSHA256(fpath); - } - return UniError(ret); - }; - - auto cbComplete = [arg](napi_env env, UniError err) -> NVal { - if (err) { - return { NVal(env, err.GetNapiErr(env)) }; - } - - return { NVal::CreateUTF8String(env, *arg) }; - }; - string procedureName = "FileIOHash"; - NVal thisVar(env, funcArg.GetThisVar()); - if (isPromise) { - return NAsyncWorkPromise(env, thisVar).Schedule(procedureName, cbExec, cbComplete).val_; - } else { - NVal cb(env, funcArg[NARG_POS::THIRD]); - return NAsyncWorkCallback(env, thisVar, cb).Schedule(procedureName, cbExec, cbComplete).val_; - } -} -} // namespace ModuleFileIO -} // namespace DistributedFS -} // namespace OHOS \ No newline at end of file diff --git a/interfaces/kits/js/src/mod_fileio/properties/hash.h b/interfaces/kits/js/src/mod_fileio/properties/hash.h deleted file mode 100644 index 8aca34c..0000000 --- a/interfaces/kits/js/src/mod_fileio/properties/hash.h +++ /dev/null @@ -1,34 +0,0 @@ -/* - * Copyright (c) 2021 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#ifndef INTERFACES_KITS_JS_SRC_MOD_FILEIO_PROPERTIES_HASH_H -#define INTERFACES_KITS_JS_SRC_MOD_FILEIO_PROPERTIES_HASH_H - -#include "../../common/log.h" -#include "../../common/napi/n_async/n_async_work_callback.h" -#include "../../common/napi/n_async/n_async_work_promise.h" -#include "../../common/napi/n_func_arg.h" - -namespace OHOS { -namespace DistributedFS { -namespace ModuleFileIO { -class Hash final { -public: - static napi_value Async(napi_env env, napi_callback_info info); -}; -} // namespace ModuleFileIO -} // namespace DistributedFS -} // namespace OHOS -#endif \ No newline at end of file diff --git a/interfaces/kits/js/src/mod_fileio/properties/lchown.cpp b/interfaces/kits/js/src/mod_fileio/properties/lchown.cpp deleted file mode 100644 index 61ed53d..0000000 --- a/interfaces/kits/js/src/mod_fileio/properties/lchown.cpp +++ /dev/null @@ -1,125 +0,0 @@ -/* - * Copyright (c) 2021 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#include "lchown.h" - -#include -#include -#include - -#include "../../common/napi/n_async/n_async_work_callback.h" -#include "../../common/napi/n_async/n_async_work_promise.h" -#include "../../common/napi/n_func_arg.h" -namespace OHOS { -namespace DistributedFS { -namespace ModuleFileIO { -using namespace std; - -static tuple GetLchownArg(napi_env env, const NFuncArg &funcArg) -{ - bool succ = false; - unique_ptr path; - tie(succ, path, ignore) = NVal(env, funcArg[NARG_POS::FIRST]).ToUTF8String(); - if (!succ) { - UniError(EINVAL).ThrowErr(env, "Invalid path"); - return { false, "", -1, -1 }; - } - - int owner; - tie(succ, owner) = NVal(env, funcArg[NARG_POS::SECOND]).ToInt32(); - if (!succ) { - UniError(EINVAL).ThrowErr(env, "Invalid owner"); - return { false, "", -1, -1 }; - } - - int group; - tie(succ, group) = NVal(env, funcArg[NARG_POS::THIRD]).ToInt32(); - if (!succ) { - UniError(EINVAL).ThrowErr(env, "Invalid group"); - return { false, "", -1, -1 }; - } - return { succ, path.get(), owner, group }; -} - -napi_value Lchown::Sync(napi_env env, napi_callback_info info) -{ - NFuncArg funcArg(env, info); - - if (!funcArg.InitArgs(NARG_CNT::THREE)) { - UniError(EINVAL).ThrowErr(env, "Number of arguments unmatched"); - return nullptr; - } - - bool succ = false; - int owner; - int group; - string path; - tie(succ, path, owner, group) = GetLchownArg(env, funcArg); - if (!succ) { - return nullptr; - } - - if (lchown(path.c_str(), owner, group) == -1) { - UniError(errno).ThrowErr(env); - return nullptr; - } - - return NVal::CreateUndefined(env).val_; -} - -napi_value Lchown::Async(napi_env env, napi_callback_info info) -{ - NFuncArg funcArg(env, info); - if (!funcArg.InitArgs(NARG_CNT::THREE, NARG_CNT::FOUR)) { - UniError(EINVAL).ThrowErr(env, "Number of arguments unmatched"); - return nullptr; - } - - bool succ = false; - int owner; - int group; - string path; - tie(succ, path, owner, group) = GetLchownArg(env, funcArg); - if (!succ) { - return nullptr; - } - - auto cbExec = [path, owner, group](napi_env env) -> UniError { - if (lchown(path.c_str(), owner, group) == -1) { - return UniError(errno); - } else { - return UniError(ERRNO_NOERR); - } - }; - - auto cbCompl = [](napi_env env, UniError err) -> NVal { - if (err) { - return { env, err.GetNapiErr(env) }; - } - return { NVal::CreateUndefined(env) }; - }; - - string procedureName = "FileIOLchown"; - NVal thisVar(env, funcArg.GetThisVar()); - if (funcArg.GetArgc() == NARG_CNT::THREE) { - return NAsyncWorkPromise(env, thisVar).Schedule(procedureName, cbExec, cbCompl).val_; - } else { - NVal cb(env, funcArg[NARG_POS::FOURTH]); - return NAsyncWorkCallback(env, thisVar, cb).Schedule(procedureName, cbExec, cbCompl).val_; - } -} -} // namespace ModuleFileIO -} // namespace DistributedFS -} // namespace OHOS diff --git a/interfaces/kits/js/src/mod_fileio/properties/lchown.h b/interfaces/kits/js/src/mod_fileio/properties/lchown.h deleted file mode 100644 index c13ad09..0000000 --- a/interfaces/kits/js/src/mod_fileio/properties/lchown.h +++ /dev/null @@ -1,32 +0,0 @@ -/* - * Copyright (c) 2021 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#ifndef INTERFACES_KITS_JS_SRC_MOD_FILEIO_PROPERTIES_LCHOWN_H -#define INTERFACES_KITS_JS_SRC_MOD_FILEIO_PROPERTIES_LCHOWN_H - -#include "../../common/napi/n_val.h" - -namespace OHOS { -namespace DistributedFS { -namespace ModuleFileIO { -class Lchown final { -public: - static napi_value Sync(napi_env env, napi_callback_info info); - static napi_value Async(napi_env env, napi_callback_info info); -}; -} // namespace ModuleFileIO -} // namespace DistributedFS -} // namespace OHOS -#endif \ No newline at end of file diff --git a/interfaces/kits/js/src/mod_fileio/properties/link.cpp b/interfaces/kits/js/src/mod_fileio/properties/link.cpp deleted file mode 100644 index 8b2cacd..0000000 --- a/interfaces/kits/js/src/mod_fileio/properties/link.cpp +++ /dev/null @@ -1,117 +0,0 @@ -/* - * Copyright (c) 2021 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -#include "link.h" - -#include -#include -#include -#include - -#include "../../common/napi/n_async/n_async_work_callback.h" -#include "../../common/napi/n_async/n_async_work_promise.h" -#include "../../common/napi/n_func_arg.h" - -namespace OHOS { -namespace DistributedFS { -namespace ModuleFileIO { -using namespace std; - -static tuple GetLinkArg(napi_env env, const NFuncArg &funcArg) -{ - bool succ = false; - unique_ptr src; - tie(succ, src, ignore) = NVal(env, funcArg[NARG_POS::FIRST]).ToUTF8String(); - if (!succ) { - UniError(EINVAL).ThrowErr(env, "Invalid src"); - return { false, "", "" }; - } - - unique_ptr dest; - tie(succ, dest, ignore) = NVal(env, funcArg[NARG_POS::SECOND]).ToUTF8String(); - if (!succ) { - UniError(EINVAL).ThrowErr(env, "Invalid dest"); - return { false, "", "" }; - } - return { true, src.get(), dest.get() }; -} - -napi_value Link::Sync(napi_env env, napi_callback_info info) -{ - NFuncArg funcArg(env, info); - if (!funcArg.InitArgs(NARG_CNT::TWO)) { - UniError(EINVAL).ThrowErr(env, "Number of arguments unmatched"); - return nullptr; - } - - bool succ = false; - string oldPath; - string newPath; - tie(succ, oldPath, newPath) = GetLinkArg(env, funcArg); - if (!succ) { - return nullptr; - } - if (link(oldPath.c_str(), newPath.c_str()) == -1) { - UniError(errno).ThrowErr(env); - return nullptr; - } - return NVal::CreateUndefined(env).val_; -} - -napi_value Link::Async(napi_env env, napi_callback_info info) -{ - NFuncArg funcArg(env, info); - - if (!funcArg.InitArgs(NARG_CNT::TWO, NARG_CNT::THREE)) { - UniError(EINVAL).ThrowErr(env, "Number of arguments unmatched"); - return nullptr; - } - - bool succ = false; - string oldPath; - string newPath; - tie(succ, oldPath, newPath) = GetLinkArg(env, funcArg); - if (!succ) { - return nullptr; - } - - auto cbExec = [oldPath = move(oldPath), newPath = move(newPath)](napi_env env) -> UniError { - int ret = link(oldPath.c_str(), newPath.c_str()); - if (ret == -1) { - return UniError(errno); - } else { - return UniError(ERRNO_NOERR); - } - }; - - auto cbComplCallback = [](napi_env env, UniError err) -> NVal { - if (err) { - return { env, err.GetNapiErr(env) }; - } - return { NVal::CreateUndefined(env) }; - }; - - string procedureName = "FileIOLink"; - NVal thisVar(env, funcArg.GetThisVar()); - size_t argc = funcArg.GetArgc(); - if (argc == NARG_CNT::TWO) { - return NAsyncWorkPromise(env, thisVar).Schedule(procedureName, cbExec, cbComplCallback).val_; - } else { - NVal cb(env, funcArg[NARG_POS::THIRD]); - return NAsyncWorkCallback(env, thisVar, cb).Schedule(procedureName, cbExec, cbComplCallback).val_; - } -} -} // namespace ModuleFileIO -} // namespace DistributedFS -} // namespace OHOS \ No newline at end of file diff --git a/interfaces/kits/js/src/mod_fileio/properties/link.h b/interfaces/kits/js/src/mod_fileio/properties/link.h deleted file mode 100644 index f287a24..0000000 --- a/interfaces/kits/js/src/mod_fileio/properties/link.h +++ /dev/null @@ -1,32 +0,0 @@ -/* - * Copyright (c) 2021 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#ifndef INTERFACES_KITS_JS_SRC_MOD_FILEIO_PROPERTIES_LINK_H -#define INTERFACES_KITS_JS_SRC_MOD_FILEIO_PROPERTIES_LINK_H - -#include "../../common/napi/n_val.h" - -namespace OHOS { -namespace DistributedFS { -namespace ModuleFileIO { -class Link final { -public: - static napi_value Sync(napi_env env, napi_callback_info info); - static napi_value Async(napi_env env, napi_callback_info info); -}; -} // namespace ModuleFileIO -} // namespace DistributedFS -} // namespace OHOS -#endif \ No newline at end of file diff --git a/interfaces/kits/js/src/mod_fileio/properties/lseek.cpp b/interfaces/kits/js/src/mod_fileio/properties/lseek.cpp deleted file mode 100644 index 6081a68..0000000 --- a/interfaces/kits/js/src/mod_fileio/properties/lseek.cpp +++ /dev/null @@ -1,128 +0,0 @@ -/* - * Copyright (c) 2021 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -#include "lseek.h" -#include -#include -#include - -#include "../../common/napi/n_async/n_async_work_callback.h" -#include "../../common/napi/n_async/n_async_work_promise.h" -#include "../../common/napi/n_func_arg.h" -namespace OHOS { -namespace DistributedFS { -namespace ModuleFileIO { -using namespace std; - -static tuple GetLseekArg(napi_env env, const NFuncArg &funcArg) -{ - bool succ = false; - int fd; - tie(succ, fd) = NVal(env, funcArg[NARG_POS::FIRST]).ToInt32(); - if (!succ) { - UniError(EINVAL).ThrowErr(env, "Invalid fd"); - return { false, -1, -1, -1 }; - } - - int offset; - tie(succ, offset) = NVal(env, funcArg[NARG_POS::SECOND]).ToInt32(); - if (!succ) { - UniError(EINVAL).ThrowErr(env, "Invalid offset"); - return { false, -1, -1, -1 }; - } - - int whence; - tie(succ, whence) = NVal(env, funcArg[NARG_POS::THIRD]).ToInt32(); - if (!succ) { - UniError(EINVAL).ThrowErr(env, "Invalid whence"); - return { false, -1, -1, -1 }; - } - - return { succ, fd, offset, whence }; -} - -napi_value Lseek::Sync(napi_env env, napi_callback_info info) -{ - NFuncArg funcArg(env, info); - if (!funcArg.InitArgs(NARG_CNT::THREE)) { - UniError(EINVAL).ThrowErr(env, "Number of arguments unmatched"); - return nullptr; - } - - bool succ = false; - int fd; - int offset; - int whence; - tie(succ, fd, offset, whence) = GetLseekArg(env, funcArg); - if (!succ) { - return nullptr; - } - - int ret = lseek(fd, offset, whence); - if (ret == -1) { - UniError(errno).ThrowErr(env); - return nullptr; - } - - return NVal::CreateInt64(env, ret).val_; -} - -napi_value Lseek::Async(napi_env env, napi_callback_info info) -{ - NFuncArg funcArg(env, info); - if (!funcArg.InitArgs(NARG_CNT::THREE, NARG_CNT::FOUR)) { - UniError(EINVAL).ThrowErr(env, "Number of arguments unmatched"); - return nullptr; - } - - size_t argc = funcArg.GetArgc(); - bool succ = false; - int fd; - int offset; - int whence; - tie(succ, fd, offset, whence) = GetLseekArg(env, funcArg); - if (!succ) { - return nullptr; - } - - auto arg = make_shared(); - auto cbExec = [fd, offset, whence, arg](napi_env env) -> UniError { - int ret = lseek(fd, offset, whence); - *arg = ret; - if (ret == -1) { - return UniError(errno); - } else { - return UniError(ERRNO_NOERR); - } - }; - - auto cbComplCallback = [arg](napi_env env, UniError err) -> NVal { - if (err) { - return { env, err.GetNapiErr(env) }; - } - return { NVal::CreateInt64(env, *arg) }; - }; - - string procedureName = "FileIOLseek"; - NVal thisVar(env, funcArg.GetThisVar()); - if (argc == NARG_CNT::THREE) { - return NAsyncWorkPromise(env, thisVar).Schedule(procedureName, cbExec, cbComplCallback).val_; - } else { - NVal cb(env, funcArg[NARG_POS::FOURTH]); - return NAsyncWorkCallback(env, thisVar, cb).Schedule(procedureName, cbExec, cbComplCallback).val_; - } -} -} // namespace ModuleFileIO -} // namespace DistributedFS -} // namespace OHOS \ No newline at end of file diff --git a/interfaces/kits/js/src/mod_fileio/properties/lseek.h b/interfaces/kits/js/src/mod_fileio/properties/lseek.h deleted file mode 100644 index b8ffb86..0000000 --- a/interfaces/kits/js/src/mod_fileio/properties/lseek.h +++ /dev/null @@ -1,32 +0,0 @@ -/* - * Copyright (c) 2021 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#ifndef INTERFACES_KITS_JS_SRC_MOD_FILEIO_PROPERTIES_LSEEK_H -#define INTERFACES_KITS_JS_SRC_MOD_FILEIO_PROPERTIES_LSEEK_H - -#include "../../common/napi/n_val.h" - -namespace OHOS { -namespace DistributedFS { -namespace ModuleFileIO { -class Lseek final { -public: - static napi_value Sync(napi_env env, napi_callback_info info); - static napi_value Async(napi_env env, napi_callback_info info); -}; -} // namespace ModuleFileIO -} // namespace DistributedFS -} // namespace OHOS -#endif \ No newline at end of file diff --git a/interfaces/kits/js/src/mod_fileio/properties/lstat.cpp b/interfaces/kits/js/src/mod_fileio/properties/lstat.cpp deleted file mode 100644 index b74502a..0000000 --- a/interfaces/kits/js/src/mod_fileio/properties/lstat.cpp +++ /dev/null @@ -1,127 +0,0 @@ -/* - * Copyright (c) 2021 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -#include "lstat.h" - -#include -#include - -#include "../../common/napi/n_async/n_async_work_callback.h" -#include "../../common/napi/n_async/n_async_work_promise.h" -#include "../../common/napi/n_class.h" -#include "../../common/napi/n_func_arg.h" -#include "../../common/napi/n_val.h" -#include "../../common/uni_error.h" - -#include "../class_stat/stat_entity.h" -#include "../class_stat/stat_n_exporter.h" - -namespace OHOS { -namespace DistributedFS { -namespace ModuleFileIO { -using namespace std; - -napi_value Lstat::Sync(napi_env env, napi_callback_info info) -{ - NFuncArg funcArg(env, info); - if (!funcArg.InitArgs(NARG_CNT::ONE)) { - UniError(EINVAL).ThrowErr(env, "Number of arguments unmatched"); - return nullptr; - } - - bool succ = false; - unique_ptr pathPtr; - tie(succ, pathPtr, ignore) = NVal(env, funcArg[NARG_POS::FIRST]).ToUTF8String(); - if (!succ) { - UniError(EINVAL).ThrowErr(env, "The first argument requires type string"); - return nullptr; - } - - struct stat buf; - int ret = lstat(pathPtr.get(), &buf); - if (ret == -1) { - UniError(errno).ThrowErr(env); - return nullptr; - } - - napi_value objStat = NClass::InstantiateClass(env, StatNExporter::className_, {}); - if (!objStat) { - return nullptr; - } - - auto statEntity = NClass::GetEntityOf(env, objStat); - if (!statEntity) { - return nullptr; - } - - statEntity->stat_ = buf; - return objStat; -} - -struct AsyncStatArg { - struct stat stat_; -}; - -napi_value Lstat::Async(napi_env env, napi_callback_info info) -{ - NFuncArg funcArg(env, info); - if (!funcArg.InitArgs(NARG_CNT::ONE, NARG_CNT::TWO)) { - UniError(EINVAL).ThrowErr(env, "Number of arguments unmatched"); - return nullptr; - } - string path; - unique_ptr tmp; - bool succ = false; - tie(succ, tmp, ignore) = NVal(env, funcArg[NARG_POS::FIRST]).ToUTF8String(); - if (!succ) { - UniError(EINVAL).ThrowErr(env, "Invalid path"); - return nullptr; - } - path = tmp.get(); - - auto arg = make_shared(); - auto cbExec = [arg, path](napi_env env) -> UniError { - if (lstat(path.c_str(), &arg->stat_)) { - return UniError(errno); - } else { - return UniError(ERRNO_NOERR); - } - }; - auto cbCompl = [arg](napi_env env, UniError err) -> NVal { - if (err) { - return { env, err.GetNapiErr(env) }; - } - napi_value objStat = NClass::InstantiateClass(env, StatNExporter::className_, {}); - if (!objStat) { - return { env, UniError(EIO).GetNapiErr(env) }; - } - auto statEntity = NClass::GetEntityOf(env, objStat); - if (!statEntity) { - return { env, UniError(EIO).GetNapiErr(env) }; - } - statEntity->stat_ = arg->stat_; - return { env, objStat }; - }; - NVal thisVar(env, funcArg.GetThisVar()); - string procedureName = "fileIOLstat"; - if (funcArg.GetArgc() == NARG_CNT::ONE) { - return NAsyncWorkPromise(env, thisVar).Schedule(procedureName, cbExec, cbCompl).val_; - } else { - NVal cb(env, funcArg[NARG_POS::SECOND]); - return NAsyncWorkCallback(env, thisVar, cb).Schedule(procedureName, cbExec, cbCompl).val_; - } -} -} // namespace ModuleFileIO -} // namespace DistributedFS -} // namespace OHOS \ No newline at end of file diff --git a/interfaces/kits/js/src/mod_fileio/properties/lstat.h b/interfaces/kits/js/src/mod_fileio/properties/lstat.h deleted file mode 100644 index 6bd24be..0000000 --- a/interfaces/kits/js/src/mod_fileio/properties/lstat.h +++ /dev/null @@ -1,32 +0,0 @@ -/* - * Copyright (c) 2021 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#ifndef INTERFACES_KITS_JS_SRC_MOD_FILEIO_PROPERTIES_LSTAT_H -#define INTERFACES_KITS_JS_SRC_MOD_FILEIO_PROPERTIES_LSTAT_H - -#include "../../common/napi/uni_header.h" - -namespace OHOS { -namespace DistributedFS { -namespace ModuleFileIO { -class Lstat final { -public: - static napi_value Async(napi_env env, napi_callback_info info); - static napi_value Sync(napi_env env, napi_callback_info info); -}; -} // namespace ModuleFileIO -} // namespace DistributedFS -} // namespace OHOS -#endif \ No newline at end of file diff --git a/interfaces/kits/js/src/mod_fileio/properties/mkdtemp.cpp b/interfaces/kits/js/src/mod_fileio/properties/mkdtemp.cpp deleted file mode 100644 index 6faee34..0000000 --- a/interfaces/kits/js/src/mod_fileio/properties/mkdtemp.cpp +++ /dev/null @@ -1,95 +0,0 @@ -/* - * Copyright (c) 2021-2022 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#include "mkdtemp.h" - -#include "../../common/napi/n_async/n_async_work_callback.h" -#include "../../common/napi/n_async/n_async_work_promise.h" -#include "../../common/napi/n_func_arg.h" - -namespace OHOS { -namespace DistributedFS { -namespace ModuleFileIO { -using namespace std; -napi_value Mkdtemp::Sync(napi_env env, napi_callback_info info) -{ - NFuncArg funcArg(env, info); - if (!funcArg.InitArgs(NARG_CNT::ONE)) { - UniError(EINVAL).ThrowErr(env, "Number of arguments unmatched"); - return nullptr; - } - - unique_ptr tmp; - bool succ = false; - tie(succ, tmp, ignore) = NVal(env, funcArg[NARG_POS::FIRST]).ToUTF8String(); - if (!succ) { - UniError(EINVAL).ThrowErr(env, "Invalid path"); - return nullptr; - } - - if (mkdtemp(tmp.get()) == nullptr) { - UniError(errno).ThrowErr(env); - return nullptr; - } - - return NVal::CreateUTF8String(env, tmp.get()).val_; -} - -napi_value Mkdtemp::Async(napi_env env, napi_callback_info info) -{ - NFuncArg funcArg(env, info); - if (!funcArg.InitArgs(NARG_CNT::ONE, NARG_CNT::TWO)) { - UniError(EINVAL).ThrowErr(env, "Number of arguments unmatched"); - return nullptr; - } - - unique_ptr tmp; - bool succ = false; - tie(succ, tmp, ignore) = NVal(env, funcArg[NARG_POS::FIRST]).ToUTF8String(); - if (!succ) { - UniError(EINVAL).ThrowErr(env, "Invalid path"); - return nullptr; - } - - string path = tmp.get(); - auto arg = make_shared(); - auto cbExec = [path, arg](napi_env env) -> UniError { - if (mkdtemp(const_cast(path.c_str())) == nullptr) { - return UniError(errno); - } else { - *arg = path; - return UniError(ERRNO_NOERR); - } - }; - auto cbComplete = [arg](napi_env env, UniError err) -> NVal { - if (err) { - return { env, err.GetNapiErr(env) }; - } else { - return NVal::CreateUTF8String(env, *arg); - } - }; - string procedureName = "FileIOmkdtemp"; - size_t argc = funcArg.GetArgc(); - NVal thisVar(env, funcArg.GetThisVar()); - if (argc == NARG_CNT::ONE) { - return NAsyncWorkPromise(env, thisVar).Schedule(procedureName, cbExec, cbComplete).val_; - } else { - NVal cb(env, funcArg[NARG_POS::SECOND]); - return NAsyncWorkCallback(env, thisVar, cb).Schedule(procedureName, cbExec, cbComplete).val_; - } -} -} // namespace ModuleFileIO -} // namespace DistributedFS -} // namespace OHOS diff --git a/interfaces/kits/js/src/mod_fileio/properties/mkdtemp.h b/interfaces/kits/js/src/mod_fileio/properties/mkdtemp.h deleted file mode 100644 index de9a7ae..0000000 --- a/interfaces/kits/js/src/mod_fileio/properties/mkdtemp.h +++ /dev/null @@ -1,32 +0,0 @@ -/* - * Copyright (c) 2021 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#ifndef INTERFACES_KITS_JS_SRC_MOD_FILEIO_PROPERTIES_MKDTEMP_H -#define INTERFACES_KITS_JS_SRC_MOD_FILEIO_PROPERTIES_MKDTEMP_H - -#include "../../common/napi/n_val.h" - -namespace OHOS { -namespace DistributedFS { -namespace ModuleFileIO { -class Mkdtemp final { -public: - static napi_value Sync(napi_env env, napi_callback_info info); - static napi_value Async(napi_env env, napi_callback_info info); -}; -} // namespace ModuleFileIO -} // namespace DistributedFS -} // namespace OHOS -#endif \ No newline at end of file diff --git a/interfaces/kits/js/src/mod_fileio/properties/open.cpp b/interfaces/kits/js/src/mod_fileio/properties/open.cpp deleted file mode 100644 index a024642..0000000 --- a/interfaces/kits/js/src/mod_fileio/properties/open.cpp +++ /dev/null @@ -1,197 +0,0 @@ -/* - * Copyright (c) 2021 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#include "open.h" -#include -#include -#include -#include -#include "remote_uri.h" - -#include "../../common/napi/n_async/n_async_work_callback.h" -#include "../../common/napi/n_async/n_async_work_promise.h" -#include "../../common/napi/n_func_arg.h" - -namespace OHOS { -namespace DistributedFS { -namespace ModuleFileIO { -using namespace std; - -int AdaptToAbi(int &flags) -{ - static constexpr int USR_O_RDONLY = 00; - static constexpr int USR_O_WRONLY = 01; - static constexpr int USR_O_RDWR = 02; - static constexpr int USR_O_CREAT = 0100; - static constexpr int USR_O_EXCL = 0200; - static constexpr int USR_O_TRUNC = 01000; - static constexpr int USR_O_APPEND = 02000; - static constexpr int USR_O_NONBLOCK = 04000; - static constexpr int USR_O_DIRECTORY = 0200000; - static constexpr int USR_O_NOFOLLOW = 0400000; - static constexpr int USR_O_SYNC = 04010000; - - int flagsABI = 0; - flagsABI |= ((flags & USR_O_RDONLY) == USR_O_RDONLY) ? O_RDONLY : 0; - flagsABI |= ((flags & USR_O_WRONLY) == USR_O_WRONLY) ? O_WRONLY : 0; - flagsABI |= ((flags & USR_O_RDWR) == USR_O_RDWR) ? O_RDWR : 0; - flagsABI |= ((flags & USR_O_CREAT) == USR_O_CREAT) ? O_CREAT : 0; - flagsABI |= ((flags & USR_O_EXCL) == USR_O_EXCL) ? O_EXCL : 0; - flagsABI |= ((flags & USR_O_TRUNC) == USR_O_TRUNC) ? O_TRUNC : 0; - flagsABI |= ((flags & USR_O_APPEND) == USR_O_APPEND) ? O_APPEND : 0; - flagsABI |= ((flags & USR_O_NONBLOCK) == USR_O_NONBLOCK) ? O_NONBLOCK : 0; - flagsABI |= ((flags & USR_O_DIRECTORY) == USR_O_DIRECTORY) ? O_DIRECTORY : 0; - flagsABI |= ((flags & USR_O_NOFOLLOW) == USR_O_NOFOLLOW) ? O_NOFOLLOW : 0; - flagsABI |= ((flags & USR_O_SYNC) == USR_O_SYNC) ? O_SYNC : 0; - flags = flagsABI; - return flagsABI; -} - -napi_value Open::Sync(napi_env env, napi_callback_info info) -{ - NFuncArg funcArg(env, info); - if (!funcArg.InitArgs(NARG_CNT::ONE, NARG_CNT::THREE)) { - UniError(EINVAL).ThrowErr(env, "Number of arguments unmatched"); - return nullptr; - } - - bool succ = false; - unique_ptr path; - tie(succ, path, ignore) = NVal(env, funcArg[NARG_POS::FIRST]).ToUTF8String(); - if (!succ) { - UniError(EINVAL).ThrowErr(env, "Invalid path"); - return nullptr; - } - - int flags = O_RDONLY; - if (funcArg.GetArgc() >= NARG_CNT::TWO) { - tie(succ, flags) = NVal(env, funcArg[NARG_POS::SECOND]).ToInt32(); - if (!succ) { - UniError(EINVAL).ThrowErr(env, "Invalid flags"); - return nullptr; - } - } - (void)AdaptToAbi(flags); - int fd = -1; - if (ModuleRemoteUri::RemoteUri::IsRemoteUri(path.get(), fd, flags)) { - return NVal::CreateInt64(env, fd).val_; - } - - size_t argc = funcArg.GetArgc(); - if (argc != NARG_CNT::THREE) { - size_t flagsFirst { flags }; - if ((flagsFirst & O_CREAT) || (flagsFirst & O_TMPFILE)) { - UniError(EINVAL).ThrowErr(env, "called with O_CREAT/O_TMPFILE but no mode"); - return nullptr; - } - fd = open(path.get(), flags); - } else { - int mode; - tie(succ, mode) = NVal(env, funcArg.GetArg(NARG_POS::THIRD)).ToInt32(); - if (!succ) { - UniError(EINVAL).ThrowErr(env, "Invalid mode"); - return nullptr; - } - fd = open(path.get(), flags, mode); - } - - if (fd == -1) { - if (errno == ENAMETOOLONG) { - UniError(errno).ThrowErr(env, "Filename too long"); - return nullptr; - } - UniError(errno).ThrowErr(env); - return nullptr; - } - - return NVal::CreateInt64(env, fd).val_; -} - -static UniError DoOpenExec(const std::string& path, const int flags, const int mode, shared_ptr arg) -{ - int fd = -1; - if (!ModuleRemoteUri::RemoteUri::IsRemoteUri(path, fd, flags)) { - fd = open(path.c_str(), flags, mode); - } - *arg = fd; - if (fd == -1) { - return UniError(errno); - } else { - return UniError(ERRNO_NOERR); - } -} - -napi_value Open::Async(napi_env env, napi_callback_info info) -{ - NFuncArg funcArg(env, info); - if (!funcArg.InitArgs(NARG_CNT::ONE, NARG_CNT::FOUR)) { - UniError(EINVAL).ThrowErr(env, "Number of arguments unmatched"); - return nullptr; - } - - auto [succ, path, unuse] = NVal(env, funcArg[NARG_POS::FIRST]).ToUTF8String(); - if (!succ) { - UniError(EINVAL).ThrowErr(env, "Invalid path"); - return nullptr; - } - - int flags = O_RDONLY; - if (funcArg.GetArgc() >= NARG_CNT::TWO && !NVal(env, funcArg[NARG_POS::SECOND]).TypeIs(napi_function)) { - tie(succ, flags) = NVal(env, funcArg[NARG_POS::SECOND]).ToInt32(); - if (!succ) { - UniError(EINVAL).ThrowErr(env, "Invalid flags"); - return nullptr; - } - (void)AdaptToAbi(flags); - } - - int mode = 0; - size_t argc = funcArg.GetArgc(); - if (argc == NARG_CNT::FOUR || - (argc == NARG_CNT::THREE && NVal(env, funcArg[NARG_POS::THIRD]).TypeIs(napi_number))) { - tie(succ, mode) = NVal(env, funcArg[NARG_POS::THIRD]).ToInt32(); - if (!succ) { - UniError(EINVAL).ThrowErr(env, "Invalid mode"); - return nullptr; - } - } - - auto arg = make_shared(); - auto cbExec = [path = string(path.get()), flags, mode, arg](napi_env env) -> UniError { - return DoOpenExec(path, flags, mode, arg); - }; - - auto cbComplCallback = [arg](napi_env env, UniError err) -> NVal { - if (err) { - if (err.GetErrno(ERR_CODE_SYSTEM_POSIX) == ENAMETOOLONG) { - return {env, err.GetNapiErr(env, "Filename too long")}; - } - return { env, err.GetNapiErr(env) }; - } - return { NVal::CreateInt64(env, *arg) }; - }; - - NVal thisVar(env, funcArg.GetThisVar()); - if (argc == NARG_CNT::ONE || (argc == NARG_CNT::TWO && NVal(env, funcArg[NARG_POS::SECOND]).TypeIs(napi_number)) || - (argc == NARG_CNT::THREE && (NVal(env, funcArg[NARG_POS::THIRD]).TypeIs(napi_number)))) { - return NAsyncWorkPromise(env, thisVar).Schedule("FileIOOpen", cbExec, cbComplCallback).val_; - } else { - NVal cb(env, funcArg[argc - 1]); - return NAsyncWorkCallback(env, thisVar, cb).Schedule("FileIOOpen", cbExec, cbComplCallback).val_; - } -} -} // namespace ModuleFileIO -} // namespace DistributedFS -} // namespace OHOS \ No newline at end of file diff --git a/interfaces/kits/js/src/mod_fileio/properties/open.h b/interfaces/kits/js/src/mod_fileio/properties/open.h deleted file mode 100644 index f6b6d71..0000000 --- a/interfaces/kits/js/src/mod_fileio/properties/open.h +++ /dev/null @@ -1,32 +0,0 @@ -/* - * Copyright (c) 2021 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#ifndef INTERFACES_KITS_JS_SRC_MOD_FILEIO_PROPERTIES_OPEN_H -#define INTERFACES_KITS_JS_SRC_MOD_FILEIO_PROPERTIES_OPEN_H - -#include "../../common/napi/n_val.h" - -namespace OHOS { -namespace DistributedFS { -namespace ModuleFileIO { -class Open final { -public: - static napi_value Sync(napi_env env, napi_callback_info info); - static napi_value Async(napi_env env, napi_callback_info info); -}; -} // namespace ModuleFileIO -} // namespace DistributedFS -} // namespace OHOS -#endif \ No newline at end of file diff --git a/interfaces/kits/js/src/mod_fileio/properties/open_dir.cpp b/interfaces/kits/js/src/mod_fileio/properties/open_dir.cpp deleted file mode 100644 index 8dedf72..0000000 --- a/interfaces/kits/js/src/mod_fileio/properties/open_dir.cpp +++ /dev/null @@ -1,137 +0,0 @@ -/* - * Copyright (c) 2021 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#include "open_dir.h" -#include -#include -#include - -#include "../../common/napi/n_async/n_async_work_callback.h" -#include "../../common/napi/n_async/n_async_work_promise.h" -#include "../../common/napi/n_class.h" -#include "../../common/napi/n_func_arg.h" -#include "../../common/napi/n_val.h" -#include "../../common/uni_error.h" -#include "../class_dir/dir_entity.h" -#include "../class_dir/dir_n_exporter.h" - -namespace OHOS { -namespace DistributedFS { -namespace ModuleFileIO { -using namespace std; - -napi_value OpenDir::Sync(napi_env env, napi_callback_info info) -{ - NFuncArg funcArg(env, info); - if (!funcArg.InitArgs(NARG_CNT::ONE)) { - return nullptr; - } - - bool succ = false; - unique_ptr path; - tie(succ, path, ignore) = NVal(env, funcArg[NARG_POS::FIRST]).ToUTF8String(); - if (!succ) { - UniError(EINVAL).ThrowErr(env, "Invalid path"); - return nullptr; - } - - std::unique_ptr> dir = { opendir(path.get()), closedir }; - if (!dir) { - UniError(errno).ThrowErr(env); - return nullptr; - } - - napi_value objDir = NClass::InstantiateClass(env, DirNExporter::className_, {}); - if (!objDir) { - UniError(EINVAL).ThrowErr(env, "Cannot instantiate class DirSync"); - return nullptr; - } - - auto dirEntity = NClass::GetEntityOf(env, objDir); - if (!dirEntity) { - UniError(EINVAL).ThrowErr(env, "Cannot get the entity of objDir"); - return nullptr; - } - dirEntity->dir_.swap(dir); - return objDir; -} - -struct OpenDirArgs { - NRef dirPtr_; - DIR *dir = nullptr; - explicit OpenDirArgs(NVal dirPtr) : dirPtr_(dirPtr) {} - ~OpenDirArgs() = default; -}; - -napi_value OpenDir::Async(napi_env env, napi_callback_info info) -{ - NFuncArg funcArg(env, info); - if (!funcArg.InitArgs(NARG_CNT::ONE, NARG_CNT::TWO)) { - UniError(EINVAL).ThrowErr(env, "Number of arguments unmatched"); - return nullptr; - } - string path; - unique_ptr tmp; - bool succ = false; - tie(succ, tmp, ignore) = NVal(env, funcArg[NARG_POS::FIRST]).ToUTF8String(); - if (!succ) { - UniError(EINVAL).ThrowErr(env, "Invalid path"); - return nullptr; - } - - path = tmp.get(); - auto arg = make_shared(NVal(env, funcArg.GetThisVar())); - auto cbExec = [arg, path](napi_env env) -> UniError { - DIR *dir = nullptr; - dir = opendir(path.c_str()); - if (dir == nullptr) { - return UniError(errno); - } - arg->dir = dir; - return UniError(ERRNO_NOERR); - }; - auto cbCompl = [arg](napi_env env, UniError err) -> NVal { - if (err) { - return { env, err.GetNapiErr(env) }; - } - std::unique_ptr> dir = { arg->dir, closedir }; - if (!dir) { - return { env, UniError(errno).GetNapiErr(env) }; - } - - napi_value objDir = NClass::InstantiateClass(env, DirNExporter::className_, {}); - if (!objDir) { - return { env, UniError(EINVAL).GetNapiErr(env) }; - } - - auto dirEntity = NClass::GetEntityOf(env, objDir); - if (!dirEntity) { - return { env, UniError(EINVAL).GetNapiErr(env) }; - } - dirEntity->dir_.swap(dir); - return { env, objDir }; - }; - - NVal thisVar(env, funcArg.GetThisVar()); - if (funcArg.GetArgc() == NARG_CNT::ONE) { - return NAsyncWorkPromise(env, thisVar).Schedule("fileIOOpenDir", cbExec, cbCompl).val_; - } else { - NVal cb(env, funcArg[NARG_POS::SECOND]); - return NAsyncWorkCallback(env, thisVar, cb).Schedule("fileIOOpenDir", cbExec, cbCompl).val_; - } -} -} // namespace ModuleFileIO -} // namespace DistributedFS -} // namespace OHOS \ No newline at end of file diff --git a/interfaces/kits/js/src/mod_fileio/properties/open_dir.h b/interfaces/kits/js/src/mod_fileio/properties/open_dir.h deleted file mode 100644 index e2e07d3..0000000 --- a/interfaces/kits/js/src/mod_fileio/properties/open_dir.h +++ /dev/null @@ -1,32 +0,0 @@ -/* - * Copyright (c) 2021 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#ifndef INTERFACES_KITS_JS_SRC_MOD_FILEIO_PROPERTIES_OPEN_DIR_H -#define INTERFACES_KITS_JS_SRC_MOD_FILEIO_PROPERTIES_OPEN_DIR_H - -#include "../../common/napi/uni_header.h" - -namespace OHOS { -namespace DistributedFS { -namespace ModuleFileIO { -class OpenDir final { -public: - static napi_value Async(napi_env env, napi_callback_info info); - static napi_value Sync(napi_env env, napi_callback_info info); -}; -} // namespace ModuleFileIO -} // namespace DistributedFS -} // namespace OHOS -#endif \ No newline at end of file diff --git a/interfaces/kits/js/src/mod_fileio/properties/posix_fallocate.cpp b/interfaces/kits/js/src/mod_fileio/properties/posix_fallocate.cpp deleted file mode 100644 index 84a86dc..0000000 --- a/interfaces/kits/js/src/mod_fileio/properties/posix_fallocate.cpp +++ /dev/null @@ -1,118 +0,0 @@ -/* - * Copyright (c) 2021 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -#include "posix_fallocate.h" -#include -#include -#include -#include - -#include "../../common/napi/n_async/n_async_work_callback.h" -#include "../../common/napi/n_async/n_async_work_promise.h" -#include "../../common/napi/n_func_arg.h" - -namespace OHOS { -namespace DistributedFS { -namespace ModuleFileIO { -using namespace std; - -static tuple GetPosixFallocateArg(napi_env env, const NFuncArg &funcArg) -{ - bool succ = false; - int fd; - tie(succ, fd) = NVal(env, funcArg[NARG_POS::FIRST]).ToInt32(); - if (!succ) { - UniError(EINVAL).ThrowErr(env, "Invalid fd"); - return { false, -1, -1, -1 }; - } - int offset; - tie(succ, offset) = NVal(env, funcArg[NARG_POS::SECOND]).ToInt32(); - if (!succ) { - UniError(EINVAL).ThrowErr(env, "Invalid offset"); - return { false, -1, -1, -1 }; - } - int len; - tie(succ, len) = NVal(env, funcArg[NARG_POS::THIRD]).ToInt32(); - if (!succ) { - UniError(EINVAL).ThrowErr(env, "Invalid len"); - return { false, -1, -1, -1 }; - } - return { succ, fd, offset, len }; -} - -napi_value PosixFallocate::Sync(napi_env env, napi_callback_info info) -{ - NFuncArg funcArg(env, info); - if (!funcArg.InitArgs(NARG_CNT::THREE)) { - UniError(EINVAL).ThrowErr(env, "Number of arguments unmatched"); - return nullptr; - } - bool succ = false; - int fd; - int offset; - int len; - tie(succ, fd, offset, len) = GetPosixFallocateArg(env, funcArg); - if (!succ) { - return nullptr; - } - int ret = posix_fallocate(fd, offset, len); - if (ret == -1) { - UniError(errno).ThrowErr(env); - return nullptr; - } - return NVal::CreateUndefined(env).val_; -} - -napi_value PosixFallocate::Async(napi_env env, napi_callback_info info) -{ - NFuncArg funcArg(env, info); - if (!funcArg.InitArgs(NARG_CNT::THREE, NARG_CNT::FOUR)) { - UniError(EINVAL).ThrowErr(env, "Number of arguments unmatched"); - return nullptr; - } - bool succ = false; - int fd; - int offset; - int len; - tie(succ, fd, offset, len) = GetPosixFallocateArg(env, funcArg); - if (!succ) { - return nullptr; - } - auto cbExec = [fd, offset, len](napi_env env) -> UniError { - if (posix_fallocate(fd, offset, len) == -1) { - return UniError(errno); - } else { - return UniError(ERRNO_NOERR); - } - }; - auto cbCompl = [](napi_env env, UniError err) -> NVal { - if (err) { - return { env, err.GetNapiErr(env) }; - } - return { NVal::CreateUndefined(env) }; - }; - NVal thisVar(env, funcArg.GetThisVar()); - string procedureName = "fileioPosixFallocate"; - size_t argc = funcArg.GetArgc(); - if (argc == NARG_CNT::THREE) { - return NAsyncWorkPromise(env, thisVar).Schedule(procedureName, cbExec, cbCompl).val_; - } else { - NVal cb(env, funcArg[NARG_POS::FOURTH]); - return NAsyncWorkCallback(env, thisVar, cb).Schedule(procedureName, cbExec, cbCompl).val_; - } - return NVal::CreateUndefined(env).val_; -} -} // namespace ModuleFileIO -} // namespace DistributedFS -} // namespace OHOS \ No newline at end of file diff --git a/interfaces/kits/js/src/mod_fileio/properties/posix_fallocate.h b/interfaces/kits/js/src/mod_fileio/properties/posix_fallocate.h deleted file mode 100644 index c26c704..0000000 --- a/interfaces/kits/js/src/mod_fileio/properties/posix_fallocate.h +++ /dev/null @@ -1,32 +0,0 @@ -/* - * Copyright (c) 2021 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#ifndef INTERFACES_KITS_JS_SRC_MOD_FILEIO_PROPERTIES_POSIX_FALLOCATE_H -#define INTERFACES_KITS_JS_SRC_MOD_FILEIO_PROPERTIES_POSIX_FALLOCATE_H - -#include "../../common/napi/n_val.h" - -namespace OHOS { -namespace DistributedFS { -namespace ModuleFileIO { -class PosixFallocate final { -public: - static napi_value Async(napi_env env, napi_callback_info info); - static napi_value Sync(napi_env env, napi_callback_info info); -}; -} // namespace ModuleFileIO -} // namespace DistributedFS -} // namespace OHOS -#endif \ No newline at end of file diff --git a/interfaces/kits/js/src/mod_fileio/properties/prop_n_exporter.cpp b/interfaces/kits/js/src/mod_fileio/properties/prop_n_exporter.cpp deleted file mode 100644 index b44d67c..0000000 --- a/interfaces/kits/js/src/mod_fileio/properties/prop_n_exporter.cpp +++ /dev/null @@ -1,765 +0,0 @@ -/* - * Copyright (c) 2021-2022 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#include "prop_n_exporter.h" - -#include -#include -#include -#include -#include - -#include "../common_func.h" -#include "chmod.h" -#include "chown.h" -#include "close.h" -#include "copy_file.h" -#include "create_randomaccessfile.h" -#include "create_stream.h" -#include "fchmod.h" -#include "fchown.h" -#include "fdatasync.h" -#include "fdopen_stream.h" -#include "fstat.h" -#include "fsync.h" -#include "ftruncate.h" -#include "hash.h" -#include "lchown.h" -#include "link.h" -#include "lseek.h" -#include "lstat.h" -#include "mkdtemp.h" -#include "open.h" -#include "open_dir.h" -#include "posix_fallocate.h" -#include "read_dir.h" -#include "read_text.h" -#include "rename.h" -#include "rmdir.h" -#include "rmdirent.h" -#include "stat.h" -#include "symlink.h" -#include "truncate.h" -#include "watcher.h" - -namespace OHOS { -namespace DistributedFS { -namespace ModuleFileIO { -using namespace std; - -napi_value PropNExporter::AccessSync(napi_env env, napi_callback_info info) -{ - NFuncArg funcArg(env, info); - - if (!funcArg.InitArgs(NARG_CNT::ONE, NARG_CNT::TWO)) { - UniError(EINVAL).ThrowErr(env, "Number of arguments unmatched"); - return nullptr; - } - - bool succ = false; - unique_ptr path; - tie(succ, path, ignore) = NVal(env, funcArg[NARG_POS::FIRST]).ToUTF8String(); - if (!succ) { - UniError(EINVAL).ThrowErr(env, "Invalid path"); - return nullptr; - } - - size_t argc = funcArg.GetArgc(); - int ret = -1; - if (argc == NARG_CNT::ONE) { - ret = access(path.get(), 0); - } else { - int mode; - tie(succ, mode) = NVal(env, funcArg[NARG_POS::SECOND]).ToInt32(); - if (!succ) { - UniError(EINVAL).ThrowErr(env, "Invalid mode"); - return nullptr; - } - ret = access(path.get(), mode); - } - if (ret == -1) { - UniError(errno).ThrowErr(env); - return nullptr; - } - - return NVal::CreateUndefined(env).val_; -} - -static tuple GetAccessArgs(napi_env env, const NFuncArg &funcArg) -{ - bool succ = false; - unique_ptr path; - tie(succ, path, ignore) = NVal(env, funcArg[NARG_POS::FIRST]).ToUTF8String(); - if (!succ) { - UniError(EINVAL).ThrowErr(env, "Invalid path"); - return { false, nullptr, 0, false }; - } - - size_t argc = funcArg.GetArgc(); - bool promise = true; - bool hasMode = false; - if (argc == NARG_CNT::ONE) { - hasMode = false; - promise = true; - } else if (argc == NARG_CNT::TWO) { - if (NVal(env, funcArg[NARG_POS::SECOND]).TypeIs(napi_function)) { - hasMode = false; - promise = false; - } else { - hasMode = true; - promise = true; - } - } else { - hasMode = true; - promise = false; - } - - int mode = 0; - if (hasMode) { - tie(succ, mode) = NVal(env, funcArg[NARG_POS::SECOND]).ToInt32(); - if (!succ) { - UniError(EINVAL).ThrowErr(env, "Invalid mode"); - return { false, nullptr, 0, false }; - } - } - - return { true, path.get(), mode, promise }; -} - -struct AsyncAccessArg { - unique_ptr fp = nullptr; -}; - -napi_value PropNExporter::Access(napi_env env, napi_callback_info info) -{ - NFuncArg funcArg(env, info); - if (!funcArg.InitArgs(NARG_CNT::ONE, NARG_CNT::THREE)) { - UniError(EINVAL).ThrowErr(env, "Number of arguments unmatched"); - return nullptr; - } - - string path; - bool succ = false; - bool promise = false; - int mode; - tie(succ, path, mode, promise) = GetAccessArgs(env, funcArg); - if (!succ) { - UniError(EINVAL).ThrowErr(env, "Invalid path"); - return nullptr; - } - size_t argc = funcArg.GetArgc(); - - auto cbExec = [path = move(path), mode](napi_env env) -> UniError { - int ret = access(path.c_str(), mode); - if (ret == -1) { - return UniError(errno); - } else { - return UniError(ERRNO_NOERR); - } - }; - - auto cbComplete = [](napi_env env, UniError err) -> NVal { - if (err) { - return { env, err.GetNapiErr(env) }; - } else { - return NVal::CreateUndefined(env); - } - }; - string procedureName = "FileIOAccess"; - NVal thisVar(env, funcArg.GetThisVar()); - if (promise) { - return NAsyncWorkPromise(env, thisVar).Schedule(procedureName, cbExec, cbComplete).val_; - } else { - int cbInd = ((argc == NARG_CNT::TWO) ? NARG_POS::SECOND : NARG_POS::THIRD); - NVal cb(env, funcArg[cbInd]); - return NAsyncWorkCallback(env, thisVar, cb).Schedule(procedureName, cbExec, cbComplete).val_; - } - - return NVal::CreateUndefined(env).val_; -} - -napi_value PropNExporter::Unlink(napi_env env, napi_callback_info info) -{ - NFuncArg funcArg(env, info); - - if (!funcArg.InitArgs(NARG_CNT::ONE, NARG_CNT::TWO)) { - UniError(EINVAL).ThrowErr(env, "Number of Arguments Unmatched"); - return nullptr; - } - - string path; - unique_ptr tmp; - bool succ = false; - tie(succ, tmp, ignore) = NVal(env, funcArg[NARG_POS::FIRST]).ToUTF8String(); - if (!succ) { - UniError(EINVAL).ThrowErr(env, "invalid path"); - return nullptr; - } - path = tmp.get(); - - auto cbExec = [path](napi_env env) -> UniError { - if (unlink(path.c_str()) == -1) { - return UniError(errno); - } else { - return UniError(ERRNO_NOERR); - } - }; - auto cbCompl = [](napi_env env, UniError err) -> NVal { - if (err) { - return { env, err.GetNapiErr(env) }; - } - return { NVal::CreateUndefined(env) }; - }; - - NVal thisVar(env, funcArg.GetThisVar()); - string procedureName = "FileIOStreamUnlink"; - if (funcArg.GetArgc() == NARG_CNT::ONE) { - return NAsyncWorkPromise(env, thisVar).Schedule(procedureName, cbExec, cbCompl).val_; - } else { - NVal cb(env, funcArg[NARG_POS::SECOND]); - return NAsyncWorkCallback(env, thisVar, cb).Schedule(procedureName, cbExec, cbCompl).val_; - } - return NVal::CreateUndefined(env).val_; -} - -napi_value PropNExporter::Mkdir(napi_env env, napi_callback_info info) -{ - NFuncArg funcArg(env, info); - if (!funcArg.InitArgs(NARG_CNT::ONE, NARG_CNT::THREE)) { - UniError(EINVAL).ThrowErr(env, "Number of arguments unmatched"); - return nullptr; - } - - string path; - unique_ptr tmp; - bool succ = false; - tie(succ, tmp, ignore) = NVal(env, funcArg[NARG_POS::FIRST]).ToUTF8String(); - if (!succ) { - UniError(EINVAL).ThrowErr(env, "Invalid path"); - return nullptr; - } - path = tmp.get(); - int mode = 0775; - size_t argc = funcArg.GetArgc(); - if ((argc == NARG_CNT::TWO && NVal(env, funcArg[NARG_POS::SECOND]).TypeIs(napi_number)) || - argc == NARG_CNT::THREE) { - tie(succ, mode) = NVal(env, funcArg[NARG_POS::SECOND]).ToInt32(); - if (!succ) { - UniError(EINVAL).ThrowErr(env, "Invalid mode"); - return nullptr; - } - } - auto cbExec = [path, mode](napi_env env) -> UniError { - if (mkdir(path.c_str(), mode) == -1) { - return UniError(errno); - } else { - return UniError(ERRNO_NOERR); - } - }; - - auto cbCompl = [](napi_env env, UniError err) -> NVal { - if (err) { - return { env, err.GetNapiErr(env) }; - } - return { NVal::CreateUndefined(env) }; - }; - NVal thisVar(env, funcArg.GetThisVar()); - string procedureName = "fileioMkdir"; - if ((argc == NARG_CNT::TWO && NVal(env, funcArg[NARG_POS::SECOND]).TypeIs(napi_number)) || argc == NARG_CNT::ONE) { - return NAsyncWorkPromise(env, thisVar).Schedule(procedureName, cbExec, cbCompl).val_; - } else { - int cbIdx = ((argc == NARG_CNT::TWO) ? NARG_POS::SECOND : NARG_POS::THIRD); - NVal cb(env, funcArg[cbIdx]); - return NAsyncWorkCallback(env, thisVar, cb).Schedule(procedureName, cbExec, cbCompl).val_; - } - - return nullptr; -} - -napi_value PropNExporter::MkdirSync(napi_env env, napi_callback_info info) -{ - NFuncArg funcArg(env, info); - - if (!funcArg.InitArgs(NARG_CNT::ONE, NARG_CNT::TWO)) { - UniError(EINVAL).ThrowErr(env, "Number of arguments unmatched"); - return nullptr; - } - - bool succ = false; - unique_ptr path; - tie(succ, path, ignore) = NVal(env, funcArg[NARG_POS::FIRST]).ToUTF8String(); - if (!succ) { - UniError(EINVAL).ThrowErr(env, "Invalid path"); - return nullptr; - } - - int ret = -1; - size_t argc = funcArg.GetArgc(); - if (argc == NARG_CNT::ONE) { - ret = mkdir(path.get(), 0775); - } else { - int mode; - tie(succ, mode) = NVal(env, funcArg[NARG_POS::SECOND]).ToInt32(); - if (!succ) { - UniError(EINVAL).ThrowErr(env, "Invalid mode"); - return nullptr; - } - ret = mkdir(path.get(), mode); - } - - if (ret == -1) { - HILOGE("errno = %{public}d", errno); - UniError(errno).ThrowErr(env); - return nullptr; - } - - return NVal::CreateUndefined(env).val_; -} - -napi_value PropNExporter::FchmodSync(napi_env env, napi_callback_info info) -{ - NFuncArg funcArg(env, info); - - if (!funcArg.InitArgs(NARG_CNT::TWO)) { - UniError(EINVAL).ThrowErr(env, "Number of arguments unmatched"); - return nullptr; - } - - bool succ = false; - int fd; - tie(succ, fd) = NVal(env, funcArg[NARG_POS::FIRST]).ToInt32(); - if (!succ) { - UniError(EINVAL).ThrowErr(env, "Invalid fd"); - return nullptr; - } - - int mode; - tie(succ, mode) = NVal(env, funcArg[NARG_POS::SECOND]).ToInt32(); - if (!succ) { - UniError(EINVAL).ThrowErr(env, "Invalid mode"); - return nullptr; - } - - int ret = fchmod(fd, mode); - if (ret == -1) { - UniError(errno).ThrowErr(env); - return nullptr; - } - - return NVal::CreateUndefined(env).val_; -} - -napi_value PropNExporter::FchownSync(napi_env env, napi_callback_info info) -{ - NFuncArg funcArg(env, info); - - if (!funcArg.InitArgs(NARG_CNT::THREE)) { - UniError(EINVAL).ThrowErr(env, "Number of arguments unmatched"); - return nullptr; - } - - bool succ = false; - - int fd; - tie(succ, fd) = NVal(env, funcArg[NARG_POS::FIRST]).ToInt32(); - if (!succ) { - UniError(EINVAL).ThrowErr(env, "Invalid fd"); - return nullptr; - } - - int owner; - tie(succ, owner) = NVal(env, funcArg[NARG_POS::SECOND]).ToInt32(); - if (!succ) { - UniError(EINVAL).ThrowErr(env, "Invalid owner"); - } - - int group; - tie(succ, group) = NVal(env, funcArg[NARG_POS::THIRD]).ToInt32(); - if (!succ) { - UniError(EINVAL).ThrowErr(env, "Invalid group"); - } - - int ret = fchown(fd, owner, group); - if (ret == -1) { - UniError(errno).ThrowErr(env); - return nullptr; - } - - return NVal::CreateUndefined(env).val_; -} - -napi_value PropNExporter::ReadSync(napi_env env, napi_callback_info info) -{ - NFuncArg funcArg(env, info); - - if (!funcArg.InitArgs(NARG_CNT::TWO, NARG_CNT::THREE)) { - UniError(EINVAL).ThrowErr(env, "Number of arguments unmatched"); - return nullptr; - } - - bool succ = false; - - int fd; - tie(succ, fd) = NVal(env, funcArg[NARG_POS::FIRST]).ToInt32(); - if (!succ) { - UniError(EINVAL).ThrowErr(env, "Invalid fd"); - return nullptr; - } - - void *buf = nullptr; - int64_t len; - bool hasPos = false; - int64_t pos; - tie(succ, buf, len, hasPos, pos, ignore) = - CommonFunc::GetReadArg(env, funcArg[NARG_POS::SECOND], funcArg[NARG_POS::THIRD]); - if (!succ) { - return nullptr; - } - - ssize_t actLen; - if (hasPos) { - actLen = pread(fd, buf, len, pos); - } else { - actLen = read(fd, buf, len); - } - if (actLen == -1) { - UniError(errno).ThrowErr(env); - return nullptr; - } - - return NVal::CreateInt64(env, actLen).val_; -} - -struct AsyncIOReadArg { - ssize_t lenRead { 0 }; - int offset { 0 }; - NRef refReadBuf; - - explicit AsyncIOReadArg(NVal jsReadBuf) : refReadBuf(jsReadBuf) {} - ~AsyncIOReadArg() = default; -}; - -napi_value PropNExporter::Read(napi_env env, napi_callback_info info) -{ - NFuncArg funcArg(env, info); - if (!funcArg.InitArgs(NARG_CNT::TWO, NARG_CNT::FOUR)) { - UniError(EINVAL).ThrowErr(env, "Number of arguments unmatched"); - return nullptr; - } - - bool succ = false; - void *buf = nullptr; - int64_t len; - int fd; - bool hasPos = false; - int64_t pos; - int offset; - tie(succ, fd) = NVal(env, funcArg[NARG_POS::FIRST]).ToInt32(); - if (!succ) { - UniError(EINVAL).ThrowErr(env, "Invalid fd"); - return nullptr; - } - - tie(succ, buf, len, hasPos, pos, offset) = - CommonFunc::GetReadArg(env, funcArg[NARG_POS::SECOND], funcArg[NARG_POS::THIRD]); - if (!succ) { - UniError(EINVAL).ThrowErr(env, "Failed GetReadArg"); - return nullptr; - } - - auto arg = make_shared(NVal(env, funcArg[NARG_POS::SECOND])); - auto cbExec = [arg, buf, len, fd, hasPos, pos, offset](napi_env env) -> UniError { - ssize_t actLen; - if (hasPos) { - actLen = pread(fd, buf, len, pos); - } else { - actLen = read(fd, buf, len); - } - if (actLen == -1) { - return UniError(errno); - } else { - arg->lenRead = actLen; - arg->offset = offset; - return UniError(ERRNO_NOERR); - } - }; - - auto cbCompl = [arg](napi_env env, UniError err) -> NVal { - if (err) { - return { env, err.GetNapiErr(env) }; - } - NVal obj = NVal::CreateObject(env); - obj.AddProp({ - NVal::DeclareNapiProperty("bytesRead", NVal::CreateInt64(env, arg->lenRead).val_), - NVal::DeclareNapiProperty("buffer", arg->refReadBuf.Deref(env).val_), - NVal::DeclareNapiProperty("offset", NVal::CreateInt64(env, arg->offset).val_) - }); - return { obj }; - }; - - NVal thisVar(env, funcArg.GetThisVar()); - size_t argc = funcArg.GetArgc(); - bool hasOp = false; - if (argc == NARG_CNT::THREE) { - NVal op = NVal(env, funcArg[NARG_POS::THIRD]); - if (op.HasProp("offset") || op.HasProp("position") || op.HasProp("length")) { - hasOp = true; - } - } - if (argc == NARG_CNT::TWO || (argc == NARG_CNT::THREE && hasOp)) { - return NAsyncWorkPromise(env, thisVar).Schedule("FileIORead", cbExec, cbCompl).val_; - } else { - int cbIdx = ((argc == NARG_CNT::THREE) ? NARG_POS::THIRD : NARG_POS::FOURTH); - NVal cb(env, funcArg[cbIdx]); - return NAsyncWorkCallback(env, thisVar, cb).Schedule("FileIORead", cbExec, cbCompl).val_; - } - - return NVal::CreateUndefined(env).val_; -} - -UniError PropNExporter::WriteExec(shared_ptr arg, void *buf, size_t len, int fd, size_t position) -{ - if (position == (size_t)INVALID_POSITION) { - arg->actLen = write(fd, buf, len); - } else { - arg->actLen = pwrite(fd, buf, len, position); - } - - if (arg->actLen == -1) { - return UniError(errno); - } else { - return UniError(ERRNO_NOERR); - } -} - -napi_value PropNExporter::Write(napi_env env, napi_callback_info info) -{ - NFuncArg funcArg(env, info); - if (!funcArg.InitArgs(NARG_CNT::TWO, NARG_CNT::FOUR)) { - UniError(EINVAL).ThrowErr(env, "Number of arguments unmatched"); - return nullptr; - } - - bool succ = false; - int fd; - tie(succ, fd) = NVal(env, funcArg[NARG_POS::FIRST]).ToInt32(); - if (!succ) { - UniError(EINVAL).ThrowErr(env, "Invalid fd"); - return nullptr; - } - - unique_ptr bufGuard; - void *buf = nullptr; - size_t len; - size_t position; - bool hasPos = false; - tie(succ, bufGuard, buf, len, hasPos, position) = - CommonFunc::GetWriteArg(env, funcArg[NARG_POS::SECOND], funcArg[NARG_POS::THIRD]); - if (!succ) { - UniError(EINVAL).ThrowErr(env, "Failed GetWriteArg"); - return nullptr; - } - - shared_ptr arg; - if (bufGuard) { - arg = make_shared(move(bufGuard)); - } else { - arg = make_shared(NVal(env, funcArg[NARG_POS::SECOND])); - } - auto cbExec = [arg, buf, len, fd, position](napi_env env) -> UniError { - return WriteExec(arg, buf, len, fd, position); - }; - - auto cbCompl = [arg](napi_env env, UniError err) -> NVal { - if (err) { - return { env, err.GetNapiErr(env) }; - } else { - return { NVal::CreateInt64(env, arg->actLen) }; - } - }; - - NVal thisVar(env, funcArg.GetThisVar()); - bool hasOp = false; - size_t argc = funcArg.GetArgc(); - if (argc == NARG_CNT::THREE) { - NVal op = NVal(env, funcArg[NARG_POS::THIRD]); - if (op.HasProp("offset") || op.HasProp("position") || op.HasProp("length") || op.HasProp("encoding")) { - hasOp = true; - } - } - - if (argc == NARG_CNT::TWO || (argc == NARG_CNT::THREE && hasOp)) { - return NAsyncWorkPromise(env, thisVar).Schedule("FileIOWrite", cbExec, cbCompl).val_; - } else { - int cbIdx = ((argc == NARG_CNT::THREE) ? NARG_POS::THIRD : NARG_POS::FOURTH); - NVal cb(env, funcArg[cbIdx]); - return NAsyncWorkCallback(env, thisVar, cb).Schedule("FileIOWrite", cbExec, cbCompl).val_; - } - - return NVal::CreateUndefined(env).val_; -} - -napi_value PropNExporter::UnlinkSync(napi_env env, napi_callback_info info) -{ - NFuncArg funcArg(env, info); - - if (!funcArg.InitArgs(NARG_CNT::ONE)) { - UniError(EINVAL).ThrowErr(env, "Number of arguments unmatched"); - return nullptr; - } - - bool succ = false; - unique_ptr path; - tie(succ, path, ignore) = NVal(env, funcArg[NARG_POS::FIRST]).ToUTF8String(); - if (!succ) { - UniError(EINVAL).ThrowErr(env, "Invalid path"); - return nullptr; - } - - if (unlink(path.get()) == -1) { - UniError(errno).ThrowErr(env); - return nullptr; - } - - return NVal::CreateUndefined(env).val_; -} - -napi_value PropNExporter::WriteSync(napi_env env, napi_callback_info info) -{ - NFuncArg funcArg(env, info); - if (!funcArg.InitArgs(NARG_CNT::TWO, NARG_CNT::THREE)) { - UniError(EINVAL).ThrowErr(env, "Number of arguments unmatched"); - return nullptr; - } - - bool succ = false; - int fd; - tie(succ, fd) = NVal(env, funcArg[NARG_POS::FIRST]).ToInt32(); - if (!succ) { - UniError(EINVAL).ThrowErr(env, "Invalid fd"); - return nullptr; - } - - void *buf = nullptr; - size_t len; - size_t position; - unique_ptr bufGuard; - bool hasPos = false; - tie(succ, bufGuard, buf, len, hasPos, position) = - CommonFunc::GetWriteArg(env, funcArg[NARG_POS::SECOND], funcArg[NARG_POS::THIRD]); - if (!succ) { - return nullptr; - } - - ssize_t writeLen; - if (position == (size_t)INVALID_POSITION) { - writeLen = write(fd, buf, len); - } else { - writeLen = pwrite(fd, buf, len, position); - } - - if (writeLen == -1) { - UniError(errno).ThrowErr(env); - return nullptr; - } - - return NVal::CreateInt64(env, writeLen).val_; -} - -bool PropNExporter::Export() -{ - return exports_.AddProp({ - NVal::DeclareNapiFunction("access", Access), - NVal::DeclareNapiFunction("accessSync", AccessSync), - NVal::DeclareNapiFunction("chmod", Chmod::Async), - NVal::DeclareNapiFunction("chmodSync", Chmod::Sync), - NVal::DeclareNapiFunction("chown", Chown::Async), - NVal::DeclareNapiFunction("chownSync", Chown::Sync), - NVal::DeclareNapiFunction("close", Close::Async), - NVal::DeclareNapiFunction("closeSync", Close::Sync), - NVal::DeclareNapiFunction("copyFile", CopyFile::Async), - NVal::DeclareNapiFunction("copyFileSync", CopyFile::Sync), - NVal::DeclareNapiFunction("createRandomAccessFile", CreateRandomAccessFile::Async), - NVal::DeclareNapiFunction("createRandomAccessFileSync", CreateRandomAccessFile::Sync), - NVal::DeclareNapiFunction("createStream", CreateStream::Async), - NVal::DeclareNapiFunction("createStreamSync", CreateStream::Sync), - NVal::DeclareNapiFunction("createWatcher", Watcher::CreateWatcher), - NVal::DeclareNapiFunction("fchmod", Fchmod::Async), - NVal::DeclareNapiFunction("fchmodSync", Fchmod::Sync), - NVal::DeclareNapiFunction("fchown", Fchown::Async), - NVal::DeclareNapiFunction("fchownSync", Fchown::Sync), - NVal::DeclareNapiFunction("fdatasync", Fdatasync::Async), - NVal::DeclareNapiFunction("fdatasyncSync", Fdatasync::Sync), - NVal::DeclareNapiFunction("fdopenStream", FdopenStream::Async), - NVal::DeclareNapiFunction("fdopenStreamSync", FdopenStream::Sync), - NVal::DeclareNapiFunction("fstat", Fstat::Async), - NVal::DeclareNapiFunction("fstatSync", Fstat::Sync), - NVal::DeclareNapiFunction("fsync", Fsync::Async), - NVal::DeclareNapiFunction("fsyncSync", Fsync::Sync), - NVal::DeclareNapiFunction("ftruncate", Ftruncate::Async), - NVal::DeclareNapiFunction("ftruncateSync", Ftruncate::Sync), - NVal::DeclareNapiFunction("hash", Hash::Async), - NVal::DeclareNapiFunction("lchown", Lchown::Async), - NVal::DeclareNapiFunction("lchownSync", Lchown::Sync), - NVal::DeclareNapiFunction("link", Link::Async), - NVal::DeclareNapiFunction("linkSync", Link::Sync), - NVal::DeclareNapiFunction("lseek", Lseek::Async), - NVal::DeclareNapiFunction("lseekSync", Lseek::Sync), - NVal::DeclareNapiFunction("lstat", Lstat::Async), - NVal::DeclareNapiFunction("lstatSync", Lstat::Sync), - NVal::DeclareNapiFunction("mkdir", Mkdir), - NVal::DeclareNapiFunction("mkdirSync", MkdirSync), - NVal::DeclareNapiFunction("mkdtemp", Mkdtemp::Async), - NVal::DeclareNapiFunction("mkdtempSync", Mkdtemp::Sync), - NVal::DeclareNapiFunction("open", Open::Async), - NVal::DeclareNapiFunction("openSync", Open::Sync), - NVal::DeclareNapiFunction("opendir", OpenDir::Async), - NVal::DeclareNapiFunction("opendirSync", OpenDir::Sync), - NVal::DeclareNapiFunction("readdir", ReadDir::Async), - NVal::DeclareNapiFunction("readdirSync", ReadDir::Sync), - NVal::DeclareNapiFunction("posixFallocate", PosixFallocate::Async), - NVal::DeclareNapiFunction("posixFallocateSync", PosixFallocate::Sync), - NVal::DeclareNapiFunction("read", Read), - NVal::DeclareNapiFunction("readSync", ReadSync), - NVal::DeclareNapiFunction("readText", ReadText::Async), - NVal::DeclareNapiFunction("readTextSync", ReadText::Sync), - NVal::DeclareNapiFunction("rename", Rename::Async), - NVal::DeclareNapiFunction("renameSync", Rename::Sync), - NVal::DeclareNapiFunction("rmdir", Rmdirent::Async), - NVal::DeclareNapiFunction("rmdirSync", Rmdirent::Sync), - NVal::DeclareNapiFunction("stat", Stat::Async), - NVal::DeclareNapiFunction("statSync", Stat::Sync), - NVal::DeclareNapiFunction("symlink", Symlink::Async), - NVal::DeclareNapiFunction("symlinkSync", Symlink::Sync), - NVal::DeclareNapiFunction("truncate", Truncate::Async), - NVal::DeclareNapiFunction("truncateSync", Truncate::Sync), - NVal::DeclareNapiFunction("unlink", Unlink), - NVal::DeclareNapiFunction("unlinkSync", UnlinkSync), - NVal::DeclareNapiFunction("write", Write), - NVal::DeclareNapiFunction("writeSync", WriteSync), - }); -} - -string PropNExporter::GetClassName() -{ - return PropNExporter::className_; -} - -PropNExporter::PropNExporter(napi_env env, napi_value exports) : NExporter(env, exports) {} - -PropNExporter::~PropNExporter() {} -} // namespace ModuleFileIO -} // namespace DistributedFS -} // namespace OHOS diff --git a/interfaces/kits/js/src/mod_fileio/properties/prop_n_exporter.h b/interfaces/kits/js/src/mod_fileio/properties/prop_n_exporter.h deleted file mode 100644 index ad9f99f..0000000 --- a/interfaces/kits/js/src/mod_fileio/properties/prop_n_exporter.h +++ /dev/null @@ -1,66 +0,0 @@ -/* - * Copyright (c) 2021 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#ifndef INTERFACES_KITS_JS_SRC_MOD_FILEIO_PROPERTIES_PROP_N_EXPORTER_H -#define INTERFACES_KITS_JS_SRC_MOD_FILEIO_PROPERTIES_PROP_N_EXPORTER_H - -#include "../../common/napi/n_async/n_ref.h" -#include "../../common/napi/n_exporter.h" -#include "../../common/napi/n_val.h" -#include "../../common/uni_error.h" - -namespace OHOS { -namespace DistributedFS { -namespace ModuleFileIO { -struct AsyncIOWrtieArg { - NRef refWriteArrayBuf_; - std::unique_ptr guardWriteStr_; - ssize_t actLen = 0; - - explicit AsyncIOWrtieArg(NVal refWriteArrayBuf) : refWriteArrayBuf_(refWriteArrayBuf) {} - explicit AsyncIOWrtieArg(std::unique_ptr &&guardWriteStr) : guardWriteStr_(move(guardWriteStr)) {} - ~AsyncIOWrtieArg() = default; -}; - -class PropNExporter final : public NExporter { -public: - inline static const std::string className_ = "__properities__"; - - static napi_value AccessSync(napi_env env, napi_callback_info info); - static napi_value FchmodSync(napi_env env, napi_callback_info info); - static napi_value FchownSync(napi_env env, napi_callback_info info); - static napi_value MkdirSync(napi_env env, napi_callback_info info); - static napi_value ReadSync(napi_env env, napi_callback_info info); - static napi_value RenameSync(napi_env env, napi_callback_info info); - static napi_value RmdirSync(napi_env env, napi_callback_info info); - static napi_value UnlinkSync(napi_env env, napi_callback_info info); - static napi_value FsyncSync(napi_env env, napi_callback_info info); - static napi_value WriteSync(napi_env env, napi_callback_info info); - static napi_value Access(napi_env env, napi_callback_info info); - static napi_value Unlink(napi_env env, napi_callback_info info); - static napi_value Mkdir(napi_env env, napi_callback_info info); - static napi_value Read(napi_env env, napi_callback_info info); - static napi_value Write(napi_env env, napi_callback_info info); - static UniError WriteExec(std::shared_ptr arg, void *buf, size_t len, int fd, size_t position); - bool Export() override; - std::string GetClassName() override; - - PropNExporter(napi_env env, napi_value exports); - ~PropNExporter() override; -}; -} // namespace ModuleFileIO -} // namespace DistributedFS -} // namespace OHOS -#endif \ No newline at end of file diff --git a/interfaces/kits/js/src/mod_fileio/properties/read_dir.cpp b/interfaces/kits/js/src/mod_fileio/properties/read_dir.cpp deleted file mode 100644 index ef9f615..0000000 --- a/interfaces/kits/js/src/mod_fileio/properties/read_dir.cpp +++ /dev/null @@ -1,131 +0,0 @@ -/* - * 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 "read_dir.h" - -#include -#include -#include -#include - -#include "../../common/napi/n_async/n_async_work_callback.h" -#include "../../common/napi/n_async/n_async_work_promise.h" -#include "../../common/napi/n_class.h" -#include "../../common/napi/n_func_arg.h" -#include "../../common/napi/n_val.h" -#include "../../common/uni_error.h" - -namespace OHOS { -namespace DistributedFS { -namespace ModuleFileIO { -using namespace std; - -static tuple> ParseJsPath(napi_env env, napi_value pathFromJs) -{ - auto [succ, path, ignore] = NVal(env, pathFromJs).ToUTF8String(); - return {succ, move(path)}; -} - -static bool VerifyFilePath(char* path) -{ - return strcmp(path, ".") != 0 && strcmp(path, "..") != 0; -} - -napi_value ReadDir::Sync(napi_env env, napi_callback_info info) -{ - NFuncArg funcArg(env, info); - if (!funcArg.InitArgs(NARG_CNT::ONE)) { - return nullptr; - } - auto [succ, path] = ParseJsPath(env, funcArg[NARG_POS::FIRST]); - if (!succ) { - UniError(EINVAL).ThrowErr(env, "Invalid path"); - return nullptr; - } - unique_ptr> dir = { opendir(path.get()), closedir }; - if (!dir) { - UniError(errno).ThrowErr(env); - return nullptr; - } - vector dirFiles; - struct dirent* entry = readdir(dir.get()); - while (entry) { - if (VerifyFilePath(entry->d_name)) { - dirFiles.push_back(entry->d_name); - } - entry = readdir(dir.get()); - } - return NVal::CreateArrayString(env, dirFiles).val_; -} - -struct ReadDirArgs { - vector dirFiles; - explicit ReadDirArgs() - { - dirFiles = vector(); - } - ~ReadDirArgs() = default; -}; - -napi_value ReadDir::Async(napi_env env, napi_callback_info info) -{ - NFuncArg funcArg(env, info); - if (!funcArg.InitArgs(NARG_CNT::ONE, NARG_CNT::TWO)) { - UniError(EINVAL).ThrowErr(env, "Number of arguments unmatched"); - return nullptr; - } - string path; - auto [succ, tmp] = ParseJsPath(env, funcArg[NARG_POS::FIRST]); - if (!succ) { - UniError(EINVAL).ThrowErr(env, "Invalid path"); - return nullptr; - } - path = tmp.get(); - auto arg = make_shared(); - auto cbExec = [arg, path](napi_env env) -> UniError { - unique_ptr> dir = { opendir(path.c_str()), closedir }; - if (!dir) { - return UniError(errno); - } - struct dirent* entry = readdir(dir.get()); - vector dirnames; - while (entry) { - if (VerifyFilePath(entry->d_name)) { - dirnames.push_back(entry->d_name); - } - entry = readdir(dir.get()); - } - arg->dirFiles = dirnames; - return UniError(ERRNO_NOERR); - }; - auto cbCompl = [arg](napi_env env, UniError err) -> NVal { - if (err) { - return { env, err.GetNapiErr(env) }; - } else { - return NVal::CreateArrayString(env, arg->dirFiles); - } - }; - - NVal thisVar(env, funcArg.GetThisVar()); - if (funcArg.GetArgc() == NARG_CNT::ONE) { - return NAsyncWorkPromise(env, thisVar).Schedule(readdirProcedureName, cbExec, cbCompl).val_; - } else { - NVal cb(env, funcArg[NARG_POS::SECOND]); - return NAsyncWorkCallback(env, thisVar, cb).Schedule(readdirProcedureName, cbExec, cbCompl).val_; - } -} -} // namespace ModuleFileIO -} // namespace DistributedFS -} // namespace OHOS \ No newline at end of file diff --git a/interfaces/kits/js/src/mod_fileio/properties/read_dir.h b/interfaces/kits/js/src/mod_fileio/properties/read_dir.h deleted file mode 100644 index e08fdcb..0000000 --- a/interfaces/kits/js/src/mod_fileio/properties/read_dir.h +++ /dev/null @@ -1,33 +0,0 @@ -/* - * 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 INTERFACES_KITS_JS_SRC_MOD_FILEIO_PROPERTIES_READ_DIR_H -#define INTERFACES_KITS_JS_SRC_MOD_FILEIO_PROPERTIES_READ_DIR_H - -#include "../../common/napi/uni_header.h" - -namespace OHOS { -namespace DistributedFS { -namespace ModuleFileIO { -class ReadDir final { -public: - static napi_value Async(napi_env env, napi_callback_info info); - static napi_value Sync(napi_env env, napi_callback_info info); -}; -const std::string readdirProcedureName = "fileIOReadDir"; -} // namespace ModuleFileIO -} // namespace DistributedFS -} // namespace OHOS -#endif \ No newline at end of file diff --git a/interfaces/kits/js/src/mod_fileio/properties/read_text.cpp b/interfaces/kits/js/src/mod_fileio/properties/read_text.cpp deleted file mode 100644 index 6db024c..0000000 --- a/interfaces/kits/js/src/mod_fileio/properties/read_text.cpp +++ /dev/null @@ -1,211 +0,0 @@ -/* - * Copyright (c) 2021 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -#include "read_text.h" - -#include -#include -#include -#include -#include -#include "../../common/file_helper/fd_guard.h" -#include "../../common/napi/n_async/n_async_work_callback.h" -#include "../../common/napi/n_async/n_async_work_promise.h" -#include "../../common/napi/n_func_arg.h" -#include "../common_func.h" - -namespace OHOS { -namespace DistributedFS { -namespace ModuleFileIO { -using namespace std; - -static tuple, bool> GetReadTextArg(napi_env env, napi_value argOption) -{ - NVal op(env, argOption); - ssize_t position = 0; - ssize_t len = 0; - bool succ = false; - bool hasOp = false; - bool hasLen = false; - unique_ptr encoding; - if (op.HasProp("position")) { - tie(succ, position) = op.GetProp("position").ToInt32(); - if (!succ) { - return { false, position, hasLen, len, nullptr, hasOp }; - } - hasOp = true; - } - if (op.HasProp("length")) { - tie(succ, len) = op.GetProp("length").ToInt32(); - if (!succ) { - return { false, position, hasLen, len, nullptr, hasOp }; - } - hasOp = true; - hasLen = true; - } - if (op.HasProp("encoding")) { - tie(succ, encoding, ignore) = op.GetProp("encoding").ToUTF8String(); - if (!succ) { - return { false, position, hasLen, len, nullptr, hasOp }; - } - hasOp = true; - } - return { true, position, hasLen, len, move(encoding), hasOp }; -} - -napi_value ReadText::Sync(napi_env env, napi_callback_info info) -{ - NFuncArg funcArg(env, info); - if (!funcArg.InitArgs(NARG_CNT::ONE, NARG_CNT::THREE)) { - UniError(EINVAL).ThrowErr(env, "Number of arguments unmatched"); - return nullptr; - } - unique_ptr path; - bool succ = false; - FDGuard sfd; - tie(succ, path, ignore) = NVal(env, funcArg[NARG_POS::FIRST]).ToUTF8String(); - if (!succ) { - UniError(EINVAL).ThrowErr(env, "Invalid path"); - return nullptr; - } - ssize_t position = 0; - ssize_t len = 0; - unique_ptr encoding; - bool hasLen = false; - tie(succ, position, hasLen, len, encoding, ignore) = GetReadTextArg(env, funcArg[NARG_POS::SECOND]); - if (!succ) { - UniError(EINVAL).ThrowErr(env, "Invalid option"); - return nullptr; - } - struct stat statbf; - int ret; - sfd.SetFD(open(path.get(), O_RDONLY)); - if ((!sfd) || (fstat(sfd.GetFD(), &statbf) == -1)) { - UniError(errno).ThrowErr(env); - return nullptr; - } - if (position > statbf.st_size) { - UniError(EINVAL).ThrowErr(env, "Invalid position"); - return nullptr; - } - len = !hasLen ? statbf.st_size : len; - len = ((len < statbf.st_size) ? len : statbf.st_size); - std::unique_ptr readbuf = std::make_unique(len + 1); - if (readbuf == nullptr) { - UniError(EINVAL).ThrowErr(env, "file is too large"); - return nullptr; - } - if (memset_s(readbuf.get(), len + 1, 0, len + 1) != EOK) { - UniError(errno).ThrowErr(env, "dfs mem error"); - return nullptr; - } - ret = position > 0 ? pread(sfd.GetFD(), readbuf.get(), len, position) : read(sfd.GetFD(), readbuf.get(), len); - if (ret == -1) { - UniError(EINVAL).ThrowErr(env, "Invalid read file"); - return nullptr; - } - return NVal::CreateUTF8String(env, readbuf.get(), ret).val_; -} - -UniError ReadText::AsyncExec(const std::string &path, std::shared_ptr arg, ssize_t position, - bool hasLen, ssize_t len) -{ - if (arg == nullptr) { - return UniError(ENOMEM); - } - - FDGuard sfd; - struct stat statbf; - arg->len = len; - sfd.SetFD(open(path.c_str(), O_RDONLY)); - if (sfd.GetFD() == -1) { - return UniError(EINVAL); - } - if (fstat(sfd.GetFD(), &statbf) == -1) { - return UniError(EINVAL); - } - if (position > statbf.st_size) { - return UniError(EINVAL); - } - if (!hasLen) { - arg->len = statbf.st_size; - } - arg->len = ((arg->len < statbf.st_size) ? arg->len : statbf.st_size); - arg->buf = std::make_unique(arg->len); - if (arg->buf == nullptr) { - return UniError(ENOMEM); - } - if (position > 0) { - arg->len = pread(sfd.GetFD(), arg->buf.get(), arg->len, position); - } else { - arg->len = read(sfd.GetFD(), arg->buf.get(), arg->len); - } - if (arg->len == -1) { - return UniError(EINVAL); - } - - return UniError(ERRNO_NOERR); -} - -napi_value ReadText::Async(napi_env env, napi_callback_info info) -{ - NFuncArg funcArg(env, info); - if (!funcArg.InitArgs(NARG_CNT::ONE, NARG_CNT::THREE)) { - UniError(EINVAL).ThrowErr(env, "Number of arguments unmatched"); - return nullptr; - } - unique_ptr path; - bool succ = false; - tie(succ, path, ignore) = NVal(env, funcArg[NARG_POS::FIRST]).ToUTF8String(); - if (!succ) { - UniError(EINVAL).ThrowErr(env, "Invalid path"); - return nullptr; - } - ssize_t position; - ssize_t len; - unique_ptr encoding; - bool hasOp = false; - bool hasLen = false; - tie(succ, position, hasLen, len, encoding, hasOp) = GetReadTextArg(env, funcArg[NARG_POS::SECOND]); - if (!succ) { - UniError(EINVAL).ThrowErr(env, "Invalid option"); - return nullptr; - } - auto arg = make_shared(NVal(env, funcArg.GetThisVar())); - if (arg == nullptr) { - return nullptr; - } - auto cbExec = [path = string(path.get()), arg, position, hasLen, len](napi_env env) -> UniError { - return AsyncExec(path, arg, position, hasLen, len); - }; - auto cbComplete = [arg](napi_env env, UniError err) -> NVal { - if (err) { - return { env, err.GetNapiErr(env) }; - } else { - return NVal::CreateUTF8String(env, arg->buf.get(), arg->len); - } - }; - size_t argc = funcArg.GetArgc(); - NVal thisVar(env, funcArg.GetThisVar()); - if (argc == NARG_CNT::ONE || (argc == NARG_CNT::TWO && hasOp)) { - return NAsyncWorkPromise(env, thisVar).Schedule("FileIOReadText", cbExec, cbComplete).val_; - } else { - int cbIdx = !hasOp ? NARG_POS::SECOND : NARG_POS::THIRD; - NVal cb(env, funcArg[cbIdx]); - return NAsyncWorkCallback(env, thisVar, cb).Schedule("FileIOReadText", cbExec, cbComplete).val_; - } -} -} // namespace ModuleFileIO -} // namespace DistributedFS -} // namespace OHOS \ No newline at end of file diff --git a/interfaces/kits/js/src/mod_fileio/properties/read_text.h b/interfaces/kits/js/src/mod_fileio/properties/read_text.h deleted file mode 100644 index 8821437..0000000 --- a/interfaces/kits/js/src/mod_fileio/properties/read_text.h +++ /dev/null @@ -1,44 +0,0 @@ -/* - * Copyright (c) 2021 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#ifndef INTERFACES_KITS_JS_SRC_MOD_FILEIO_PROPERTIES_READ_TEXT_H -#define INTERFACES_KITS_JS_SRC_MOD_FILEIO_PROPERTIES_READ_TEXT_H - -#include "../../common/napi/n_async/n_ref.h" -#include "../../common/napi/n_val.h" -#include "../../common/uni_error.h" - -namespace OHOS { -namespace DistributedFS { -namespace ModuleFileIO { -struct AsyncReadTextArg { - NRef _refReadBuf; - std::unique_ptr buf; - ssize_t len = 0; - explicit AsyncReadTextArg(NVal refReadBuf) : _refReadBuf(refReadBuf) {}; - ~AsyncReadTextArg() = default; -}; - -class ReadText final { -public: -static UniError AsyncExec(const std::string &path, std::shared_ptr arg, ssize_t position, - bool hasLen, ssize_t len); - static napi_value Async(napi_env env, napi_callback_info info); - static napi_value Sync(napi_env env, napi_callback_info info); -}; -} // namespace ModuleFileIO -} // namespace DistributedFS -} // namespace OHOS -#endif \ No newline at end of file diff --git a/interfaces/kits/js/src/mod_fileio/properties/rename.cpp b/interfaces/kits/js/src/mod_fileio/properties/rename.cpp deleted file mode 100644 index 78fb5a2..0000000 --- a/interfaces/kits/js/src/mod_fileio/properties/rename.cpp +++ /dev/null @@ -1,115 +0,0 @@ -/* - * Copyright (c) 2021 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#include "rename.h" - -#include -#include -#include - -#include "../../common/napi/n_async/n_async_work_callback.h" -#include "../../common/napi/n_async/n_async_work_promise.h" -#include "../../common/napi/n_func_arg.h" - -namespace OHOS { -namespace DistributedFS { -namespace ModuleFileIO { -using namespace std; - -napi_value Rename::Sync(napi_env env, napi_callback_info info) -{ - NFuncArg funcArg(env, info); - - if (!funcArg.InitArgs(NARG_CNT::TWO)) { - UniError(EINVAL).ThrowErr(env, "Number of arguments unmatched"); - return nullptr; - } - - bool succ = false; - unique_ptr src; - tie(succ, src, ignore) = NVal(env, funcArg[NARG_POS::FIRST]).ToUTF8String(); - if (!succ) { - UniError(EINVAL).ThrowErr(env, "Invalid src"); - return nullptr; - } - - unique_ptr dest; - tie(succ, dest, ignore) = NVal(env, funcArg[NARG_POS::SECOND]).ToUTF8String(); - if (!succ) { - UniError(EINVAL).ThrowErr(env, "Invalid dest"); - return nullptr; - } - - if (rename(src.get(), dest.get()) == -1) { - UniError(errno).ThrowErr(env); - return nullptr; - } - - return NVal::CreateUndefined(env).val_; -} - -napi_value Rename::Async(napi_env env, napi_callback_info info) -{ - NFuncArg funcArg(env, info); - if (!funcArg.InitArgs(NARG_CNT::TWO, NARG_CNT::THREE)) { - UniError(EINVAL).ThrowErr(env, "Number of arguments unmatched"); - return nullptr; - } - - string path; - bool succ = false; - unique_ptr src; - tie(succ, src, ignore) = NVal(env, funcArg[NARG_POS::FIRST]).ToUTF8String(); - if (!succ) { - UniError(EINVAL).ThrowErr(env, "Invalid src"); - return nullptr; - } - - unique_ptr dest; - tie(succ, dest, ignore) = NVal(env, funcArg[NARG_POS::SECOND]).ToUTF8String(); - if (!succ) { - UniError(EINVAL).ThrowErr(env, "Invalid dest"); - return nullptr; - } - - auto cbExec = [opath = string(src.get()), npath = string(dest.get())](napi_env env) -> UniError { - int ret = rename(opath.c_str(), npath.c_str()); - if (ret == -1) { - return UniError(errno); - } else { - return UniError(ERRNO_NOERR); - } - }; - - auto cbComplCallback = [](napi_env env, UniError err) -> NVal { - if (err) { - return { env, err.GetNapiErr(env) }; - } - return { NVal::CreateUndefined(env) }; - }; - - string procedureName = "FileIORename"; - NVal thisVar(env, funcArg.GetThisVar()); - size_t argc = funcArg.GetArgc(); - if (argc == NARG_CNT::TWO) { - return NAsyncWorkPromise(env, thisVar).Schedule(procedureName, cbExec, cbComplCallback).val_; - } else { - NVal cb(env, funcArg[NARG_POS::THIRD]); - return NAsyncWorkCallback(env, thisVar, cb).Schedule(procedureName, cbExec, cbComplCallback).val_; - } -} -} // namespace ModuleFileIO -} // namespace DistributedFS -} // namespace OHOS \ No newline at end of file diff --git a/interfaces/kits/js/src/mod_fileio/properties/rename.h b/interfaces/kits/js/src/mod_fileio/properties/rename.h deleted file mode 100644 index 0333170..0000000 --- a/interfaces/kits/js/src/mod_fileio/properties/rename.h +++ /dev/null @@ -1,31 +0,0 @@ -/* - * Copyright (c) 2021 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#ifndef INTERFACES_KITS_JS_SRC_MOD_FILEIO_PROPERTIES_RENAME_H -#define INTERFACES_KITS_JS_SRC_MOD_FILEIO_PROPERTIES_RENAME_H - -#include "../../common/napi/n_val.h" -namespace OHOS { -namespace DistributedFS { -namespace ModuleFileIO { -class Rename final { -public: - static napi_value Sync(napi_env env, napi_callback_info info); - static napi_value Async(napi_env env, napi_callback_info info); -}; -} // namespace ModuleFileIO -} // namespace DistributedFS -} // namespace OHOS -#endif \ No newline at end of file diff --git a/interfaces/kits/js/src/mod_fileio/properties/rmdir.cpp b/interfaces/kits/js/src/mod_fileio/properties/rmdir.cpp deleted file mode 100644 index 4a9797c..0000000 --- a/interfaces/kits/js/src/mod_fileio/properties/rmdir.cpp +++ /dev/null @@ -1,97 +0,0 @@ -/* - * Copyright (c) 2021 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#include "rmdir.h" - -#include -#include -#include -#include "../../common/napi/n_async/n_async_work_callback.h" -#include "../../common/napi/n_async/n_async_work_promise.h" -#include "../../common/napi/n_func_arg.h" -namespace OHOS { -namespace DistributedFS { -namespace ModuleFileIO { -using namespace std; - -napi_value Rmdir::Sync(napi_env env, napi_callback_info info) -{ - NFuncArg funcArg(env, info); - - if (!funcArg.InitArgs(NARG_CNT::ONE)) { - UniError(EINVAL).ThrowErr(env, "Number of arguments unmatched"); - return nullptr; - } - - bool succ = false; - unique_ptr path; - tie(succ, path, ignore) = NVal(env, funcArg[NARG_POS::FIRST]).ToUTF8String(); - if (!succ) { - UniError(EINVAL).ThrowErr(env, "Invalid path"); - return nullptr; - } - - if (rmdir(path.get()) == -1) { - UniError(errno).ThrowErr(env); - return nullptr; - } - - return NVal::CreateUndefined(env).val_; -} - -napi_value Rmdir::Async(napi_env env, napi_callback_info info) -{ - NFuncArg funcArg(env, info); - if (!funcArg.InitArgs(NARG_CNT::ONE, NARG_CNT::TWO)) { - UniError(EINVAL).ThrowErr(env, "Number of arguments unmatched"); - return nullptr; - } - - bool succ = false; - unique_ptr path; - tie(succ, path, ignore) = NVal(env, funcArg[NARG_POS::FIRST]).ToUTF8String(); - if (!succ) { - UniError(EINVAL).ThrowErr(env, "Invalid path"); - return nullptr; - } - - auto cbExec = [path = string(path.get())](napi_env env) -> UniError { - int res = rmdir(path.c_str()); - if (res == -1) { - return UniError(errno); - } else { - return UniError(ERRNO_NOERR); - } - }; - auto cbCompl = [](napi_env env, UniError err) -> NVal { - if (err) { - return { env, err.GetNapiErr(env) }; - } else { - return NVal::CreateUndefined(env); - } - }; - string procedureName = "FileIORmdir"; - NVal thisVar(env, funcArg.GetThisVar()); - size_t argc = funcArg.GetArgc(); - if (argc == NARG_CNT::ONE) { - return NAsyncWorkPromise(env, thisVar).Schedule(procedureName, cbExec, cbCompl).val_; - } else { - NVal cb(env, funcArg[NARG_POS::SECOND]); - return NAsyncWorkCallback(env, thisVar, cb).Schedule(procedureName, cbExec, cbCompl).val_; - } -} -} // namespace ModuleFileIO -} // namespace DistributedFS -} // namespace OHOS \ No newline at end of file diff --git a/interfaces/kits/js/src/mod_fileio/properties/rmdir.h b/interfaces/kits/js/src/mod_fileio/properties/rmdir.h deleted file mode 100644 index 6e6e7bf..0000000 --- a/interfaces/kits/js/src/mod_fileio/properties/rmdir.h +++ /dev/null @@ -1,32 +0,0 @@ -/* - * Copyright (c) 2021 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#ifndef INTERFACES_KITS_JS_SRC_MOD_FILEIO_PROPERTIES_RMDIR_H -#define INTERFACES_KITS_JS_SRC_MOD_FILEIO_PROPERTIES_RMDIR_H - -#include "../../common/napi/n_val.h" - -namespace OHOS { -namespace DistributedFS { -namespace ModuleFileIO { -class Rmdir final { -public: - static napi_value Sync(napi_env env, napi_callback_info info); - static napi_value Async(napi_env env, napi_callback_info info); -}; -} // namespace ModuleFileIO -} // namespace DistributedFS -} // namespace OHOS -#endif \ No newline at end of file diff --git a/interfaces/kits/js/src/mod_fileio/properties/rmdirent.cpp b/interfaces/kits/js/src/mod_fileio/properties/rmdirent.cpp deleted file mode 100644 index 66dd48e..0000000 --- a/interfaces/kits/js/src/mod_fileio/properties/rmdirent.cpp +++ /dev/null @@ -1,142 +0,0 @@ -/* - * 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 "rmdirent.h" - -#include -#include -#include -#include -#include -#include - -#include "../../common/napi/n_async/n_async_work_callback.h" -#include "../../common/napi/n_async/n_async_work_promise.h" -#include "../../common/napi/n_func_arg.h" - -namespace OHOS { -namespace DistributedFS { -namespace ModuleFileIO { -using namespace std; - -static tuple> ParseJsPath(napi_env env, napi_value pathFromJs) -{ - auto [succ, path, ignore] = NVal(env, pathFromJs).ToUTF8String(); - return {succ, move(path)}; -} - -static UniError rmdirent(napi_env env, string path) -{ - if (rmdir(path.c_str()) == 0) { - return UniError(ERRNO_NOERR); - } - auto dir = opendir(path.c_str()); - if (!dir) { - return UniError(errno); - } - struct dirent* entry = readdir(dir); - while (entry) { - if (strcmp(entry->d_name, ".") == 0 || strcmp(entry->d_name, "..") == 0) { - entry = readdir(dir); - continue; - } - struct stat fileInformation; - string filePath = path + '/'; - filePath.insert(filePath.length(), entry->d_name); - if (stat(filePath.c_str(), &fileInformation) != 0) { - closedir(dir); - return UniError(errno); - } - if ((fileInformation.st_mode & S_IFMT) == S_IFDIR) { - auto err = rmdirent(env, filePath); - if (err) { - closedir(dir); - return err; - } - } else { - if (unlink(filePath.c_str()) != 0) { - closedir(dir); - return UniError(errno); - } - } - entry = readdir(dir); - } - closedir(dir); - if (rmdir(path.c_str()) != 0) { - return UniError(errno); - } - return UniError(ERRNO_NOERR); -} - -napi_value Rmdirent::Sync(napi_env env, napi_callback_info info) -{ - NFuncArg funcArg(env, info); - - if (!funcArg.InitArgs(NARG_CNT::ONE)) { - UniError(EINVAL).ThrowErr(env, "Number of arguments unmatched"); - return nullptr; - } - - auto [succ, path] = ParseJsPath(env, funcArg[NARG_POS::FIRST]); - if (!succ) { - UniError(EINVAL).ThrowErr(env, "Invalid path"); - return nullptr; - } - - auto err = rmdirent(env, string(path.get())); - if (err) { - err.ThrowErr(env); - return nullptr; - } - return NVal::CreateUndefined(env).val_; -} - -napi_value Rmdirent::Async(napi_env env, napi_callback_info info) -{ - NFuncArg funcArg(env, info); - if (!funcArg.InitArgs(NARG_CNT::ONE, NARG_CNT::TWO)) { - UniError(EINVAL).ThrowErr(env, "Number of arguments unmatched"); - return nullptr; - } - - auto [succ, path] = ParseJsPath(env, funcArg[NARG_POS::FIRST]); - if (!succ) { - UniError(EINVAL).ThrowErr(env, "Invalid path"); - return nullptr; - } - - auto cbExec = [path = string(path.get())](napi_env env) -> UniError { - return rmdirent(env, path); - }; - auto cbCompl = [](napi_env env, UniError err) -> NVal { - if (err) { - return { env, err.GetNapiErr(env) }; - } else { - return NVal::CreateUndefined(env); - } - }; - - NVal thisVar(env, funcArg.GetThisVar()); - size_t argc = funcArg.GetArgc(); - if (argc == NARG_CNT::ONE) { - return NAsyncWorkPromise(env, thisVar).Schedule(rmdirProcedureName, cbExec, cbCompl).val_; - } else { - NVal cb(env, funcArg[NARG_POS::SECOND]); - return NAsyncWorkCallback(env, thisVar, cb).Schedule(rmdirProcedureName, cbExec, cbCompl).val_; - } -} -} // namespace ModuleFileIO -} // namespace DistributedFS -} // namespace OHOS \ No newline at end of file diff --git a/interfaces/kits/js/src/mod_fileio/properties/rmdirent.h b/interfaces/kits/js/src/mod_fileio/properties/rmdirent.h deleted file mode 100644 index b63e528..0000000 --- a/interfaces/kits/js/src/mod_fileio/properties/rmdirent.h +++ /dev/null @@ -1,33 +0,0 @@ -/* - * 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 INTERFACES_KITS_JS_SRC_MOD_FILEIO_PROPERTIES_RMDIRENT_H -#define INTERFACES_KITS_JS_SRC_MOD_FILEIO_PROPERTIES_RMDIRENT_H - -#include "../../common/napi/n_val.h" - -namespace OHOS { -namespace DistributedFS { -namespace ModuleFileIO { -class Rmdirent final { -public: - static napi_value Sync(napi_env env, napi_callback_info info); - static napi_value Async(napi_env env, napi_callback_info info); -}; -const std::string rmdirProcedureName = "FileIORmDirent"; -} // namespace ModuleFileIO -} // namespace DistributedFS -} // namespace OHOS -#endif \ No newline at end of file diff --git a/interfaces/kits/js/src/mod_fileio/properties/stat.cpp b/interfaces/kits/js/src/mod_fileio/properties/stat.cpp deleted file mode 100644 index 029acad..0000000 --- a/interfaces/kits/js/src/mod_fileio/properties/stat.cpp +++ /dev/null @@ -1,127 +0,0 @@ -/* - * Copyright (c) 2021 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -#include "stat.h" - -#include -#include - -#include "../../common/napi/n_async/n_async_work_callback.h" -#include "../../common/napi/n_async/n_async_work_promise.h" -#include "../../common/napi/n_class.h" -#include "../../common/napi/n_func_arg.h" -#include "../../common/napi/n_val.h" -#include "../../common/uni_error.h" - -#include "../class_stat/stat_entity.h" -#include "../class_stat/stat_n_exporter.h" - -namespace OHOS { -namespace DistributedFS { -namespace ModuleFileIO { -using namespace std; - -napi_value Stat::Sync(napi_env env, napi_callback_info info) -{ - NFuncArg funcArg(env, info); - if (!funcArg.InitArgs(NARG_CNT::ONE)) { - UniError(EINVAL).ThrowErr(env, "Number of arguments unmatched"); - return nullptr; - } - - bool succ = false; - unique_ptr pathPtr; - tie(succ, pathPtr, ignore) = NVal(env, funcArg[NARG_POS::FIRST]).ToUTF8String(); - if (!succ) { - UniError(EINVAL).ThrowErr(env, "The first argument requires type string"); - return nullptr; - } - - struct stat buf; - int ret = stat(pathPtr.get(), &buf); - if (ret == -1) { - UniError(errno).ThrowErr(env); - return nullptr; - } - - napi_value objStat = NClass::InstantiateClass(env, StatNExporter::className_, {}); - if (!objStat) { - return nullptr; - } - - auto statEntity = NClass::GetEntityOf(env, objStat); - if (!statEntity) { - return nullptr; - } - - statEntity->stat_ = buf; - return objStat; -} - -struct AsyncStatArg { - struct stat stat_; -}; - -napi_value Stat::Async(napi_env env, napi_callback_info info) -{ - NFuncArg funcArg(env, info); - if (!funcArg.InitArgs(NARG_CNT::ONE, NARG_CNT::TWO)) { - UniError(EINVAL).ThrowErr(env, "Number of arguments unmatched"); - return nullptr; - } - string path; - unique_ptr tmp; - bool succ = false; - tie(succ, tmp, ignore) = NVal(env, funcArg[NARG_POS::FIRST]).ToUTF8String(); - if (!succ) { - UniError(EINVAL).ThrowErr(env, "Invalid path"); - return nullptr; - } - path = tmp.get(); - - auto arg = make_shared(); - auto cbExec = [arg, path](napi_env env) -> UniError { - if (stat(path.c_str(), &arg->stat_)) { - return UniError(errno); - } else { - return UniError(ERRNO_NOERR); - } - }; - auto cbCompl = [arg](napi_env env, UniError err) -> NVal { - if (err) { - return { env, err.GetNapiErr(env) }; - } - napi_value objStat = NClass::InstantiateClass(env, StatNExporter::className_, {}); - if (!objStat) { - return { env, UniError(EIO).GetNapiErr(env) }; - } - auto statEntity = NClass::GetEntityOf(env, objStat); - if (!statEntity) { - return { env, UniError(EIO).GetNapiErr(env) }; - } - statEntity->stat_ = arg->stat_; - return { env, objStat }; - }; - NVal thisVar(env, funcArg.GetThisVar()); - string procedureName = "fileioStatStat"; - if (funcArg.GetArgc() == NARG_CNT::ONE) { - return NAsyncWorkPromise(env, thisVar).Schedule(procedureName, cbExec, cbCompl).val_; - } else { - NVal cb(env, funcArg[NARG_POS::SECOND]); - return NAsyncWorkCallback(env, thisVar, cb).Schedule(procedureName, cbExec, cbCompl).val_; - } -} -} // namespace ModuleFileIO -} // namespace DistributedFS -} // namespace OHOS \ No newline at end of file diff --git a/interfaces/kits/js/src/mod_fileio/properties/stat.h b/interfaces/kits/js/src/mod_fileio/properties/stat.h deleted file mode 100644 index 8b16373..0000000 --- a/interfaces/kits/js/src/mod_fileio/properties/stat.h +++ /dev/null @@ -1,32 +0,0 @@ -/* - * Copyright (c) 2021 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#ifndef INTERFACES_KITS_JS_SRC_MOD_FILEIO_PROPERTIES_STAT_H -#define INTERFACES_KITS_JS_SRC_MOD_FILEIO_PROPERTIES_STAT_H - -#include "../../common/napi/uni_header.h" - -namespace OHOS { -namespace DistributedFS { -namespace ModuleFileIO { -class Stat final { -public: - static napi_value Async(napi_env env, napi_callback_info info); - static napi_value Sync(napi_env env, napi_callback_info info); -}; -} // namespace ModuleFileIO -} // namespace DistributedFS -} // namespace OHOS -#endif \ No newline at end of file diff --git a/interfaces/kits/js/src/mod_fileio/properties/symlink.cpp b/interfaces/kits/js/src/mod_fileio/properties/symlink.cpp deleted file mode 100644 index 20180cb..0000000 --- a/interfaces/kits/js/src/mod_fileio/properties/symlink.cpp +++ /dev/null @@ -1,116 +0,0 @@ -/* - * Copyright (c) 2021 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#include "symlink.h" -#include -#include -#include -#include - -#include "../../common/napi/n_async/n_async_work_callback.h" -#include "../../common/napi/n_async/n_async_work_promise.h" -#include "../../common/napi/n_func_arg.h" -namespace OHOS { -namespace DistributedFS { -namespace ModuleFileIO { -using namespace std; - -static tuple GetSymlinkArg(napi_env env, const NFuncArg &funcArg) -{ - bool succ = false; - unique_ptr src; - tie(succ, src, ignore) = NVal(env, funcArg[NARG_POS::FIRST]).ToUTF8String(); - if (!succ) { - UniError(EINVAL).ThrowErr(env, "Invalid src"); - return { false, "", "" }; - } - - unique_ptr dest; - tie(succ, dest, ignore) = NVal(env, funcArg[NARG_POS::SECOND]).ToUTF8String(); - if (!succ) { - UniError(EINVAL).ThrowErr(env, "Invalid dest"); - return { false, "", "" }; - } - return { true, src.get(), dest.get() }; -} - -napi_value Symlink::Sync(napi_env env, napi_callback_info info) -{ - NFuncArg funcArg(env, info); - if (!funcArg.InitArgs(NARG_CNT::TWO)) { - UniError(EINVAL).ThrowErr(env, "Number of arguments unmatched"); - return nullptr; - } - - bool succ = false; - string oldPath; - string newPath; - tie(succ, oldPath, newPath) = GetSymlinkArg(env, funcArg); - if (!succ) { - return nullptr; - } - - if (symlink(oldPath.c_str(), newPath.c_str()) == -1) { - UniError(errno).ThrowErr(env); - return nullptr; - } - return NVal::CreateUndefined(env).val_; -} - -napi_value Symlink::Async(napi_env env, napi_callback_info info) -{ - NFuncArg funcArg(env, info); - if (!funcArg.InitArgs(NARG_CNT::TWO, NARG_CNT::THREE)) { - UniError(EINVAL).ThrowErr(env, "Number of arguments unmatched"); - return nullptr; - } - - bool succ = false; - string oldPath; - string newPath; - tie(succ, oldPath, newPath) = GetSymlinkArg(env, funcArg); - if (!succ) { - return nullptr; - } - - auto cbExec = [oldPath = move(oldPath), newPath = move(newPath)](napi_env env) -> UniError { - int ret = symlink(oldPath.c_str(), newPath.c_str()); - if (ret == -1) { - return UniError(errno); - } else { - return UniError(ERRNO_NOERR); - } - }; - - auto cbComplCallback = [](napi_env env, UniError err) -> NVal { - if (err) { - return { env, err.GetNapiErr(env) }; - } - return { NVal::CreateUndefined(env) }; - }; - - string procedureName = "FileIOsymLink"; - NVal thisVar(env, funcArg.GetThisVar()); - size_t argc = funcArg.GetArgc(); - if (argc == NARG_CNT::TWO) { - return NAsyncWorkPromise(env, thisVar).Schedule(procedureName, cbExec, cbComplCallback).val_; - } else { - NVal cb(env, funcArg[NARG_POS::THIRD]); - return NAsyncWorkCallback(env, thisVar, cb).Schedule(procedureName, cbExec, cbComplCallback).val_; - } -} -} // namespace ModuleFileIO -} // namespace DistributedFS -} // namespace OHOS \ No newline at end of file diff --git a/interfaces/kits/js/src/mod_fileio/properties/symlink.h b/interfaces/kits/js/src/mod_fileio/properties/symlink.h deleted file mode 100644 index b770a27..0000000 --- a/interfaces/kits/js/src/mod_fileio/properties/symlink.h +++ /dev/null @@ -1,32 +0,0 @@ -/* - * Copyright (c) 2021 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#ifndef INTERFACES_KITS_JS_SRC_MOD_FILEIO_PROPERTIES_SYMLINK_H -#define INTERFACES_KITS_JS_SRC_MOD_FILEIO_PROPERTIES_SYMLINK_H - -#include "../../common/napi/n_val.h" - -namespace OHOS { -namespace DistributedFS { -namespace ModuleFileIO { -class Symlink final { -public: - static napi_value Async(napi_env env, napi_callback_info info); - static napi_value Sync(napi_env env, napi_callback_info info); -}; -} // namespace ModuleFileIO -} // namespace DistributedFS -} // namespace OHOS -#endif \ No newline at end of file diff --git a/interfaces/kits/js/src/mod_fileio/properties/truncate.cpp b/interfaces/kits/js/src/mod_fileio/properties/truncate.cpp deleted file mode 100644 index f07084b..0000000 --- a/interfaces/kits/js/src/mod_fileio/properties/truncate.cpp +++ /dev/null @@ -1,113 +0,0 @@ -/* - * Copyright (c) 2021 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#include "truncate.h" - -#include -#include -#include - -namespace OHOS { -namespace DistributedFS { -namespace ModuleFileIO { -using namespace std; - -napi_value Truncate::Sync(napi_env env, napi_callback_info info) -{ - NFuncArg funcArg(env, info); - - if (!funcArg.InitArgs(NARG_CNT::ONE, NARG_CNT::TWO)) { - UniError(EINVAL).ThrowErr(env, "Number of arguments unmatched"); - return nullptr; - } - - bool succ = false; - unique_ptr path; - tie(succ, path, ignore) = NVal(env, funcArg[NARG_POS::FIRST]).ToUTF8String(); - if (!succ) { - UniError(EINVAL).ThrowErr(env, "Invalid path"); - return nullptr; - } - - int ret = -1; - if (funcArg.GetArgc() == NARG_CNT::ONE) { - ret = truncate(path.get(), 0); - } else { - int len; - tie(succ, len) = NVal(env, funcArg[NARG_POS::SECOND]).ToInt32(); - if (!succ) { - UniError(EINVAL).ThrowErr(env, "Invalid len"); - } - ret = truncate(path.get(), len); - } - - if (ret == -1) { - UniError(errno).ThrowErr(env); - return nullptr; - } - return NVal::CreateUndefined(env).val_; -} - -napi_value Truncate::Async(napi_env env, napi_callback_info info) -{ - NFuncArg funcArg(env, info); - if (!funcArg.InitArgs(NARG_CNT::ONE, NARG_CNT::THREE)) { - UniError(EINVAL).ThrowErr(env, "Number of arguments unmatched"); - return nullptr; - } - bool succ = false; - unique_ptr path; - int len = 0; - tie(succ, path, ignore) = NVal(env, funcArg[NARG_POS::FIRST]).ToUTF8String(); - if (!succ) { - UniError(EINVAL).ThrowErr(env, "Invalid path"); - return nullptr; - } - size_t argc = funcArg.GetArgc(); - if (argc > NARG_CNT::ONE) { - tie(succ, len) = NVal(env, funcArg[NARG_POS::SECOND]).ToInt32(); - if (!succ) { - UniError(EINVAL).ThrowErr(env, "Invalid len"); - return nullptr; - } - } - auto cbExec = [path = string(path.get()), len](napi_env env) -> UniError { - int ret = truncate(path.c_str(), len); - if (ret == -1) { - return UniError(errno); - } else { - return UniError(ERRNO_NOERR); - } - }; - auto cbCompl = [](napi_env env, UniError err) -> NVal { - if (err) { - return { env, err.GetNapiErr(env) }; - } else { - return NVal::CreateUndefined(env); - } - }; - - NVal thisVar(env, funcArg.GetThisVar()); - string procedureName = "fileIOTruncate"; - if (argc == NARG_CNT::ONE || (argc == NARG_CNT::TWO && NVal(env, funcArg[NARG_POS::SECOND]).TypeIs(napi_number))) { - return NAsyncWorkPromise(env, thisVar).Schedule(procedureName, cbExec, cbCompl).val_; - } else { - NVal cb(env, funcArg[NARG_POS::THIRD]); - return NAsyncWorkCallback(env, thisVar, cb).Schedule(procedureName, cbExec, cbCompl).val_; - } -} -} // namespace ModuleFileIO -} // namespace DistributedFS -} // namespace OHOS \ No newline at end of file diff --git a/interfaces/kits/js/src/mod_fileio/properties/truncate.h b/interfaces/kits/js/src/mod_fileio/properties/truncate.h deleted file mode 100644 index b4f32e0..0000000 --- a/interfaces/kits/js/src/mod_fileio/properties/truncate.h +++ /dev/null @@ -1,35 +0,0 @@ -/* - * Copyright (c) 2021 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#ifndef INTERFACES_KITS_JS_SRC_MOD_FILEIO_PROPERTIES_TRUNCATE_H -#define INTERFACES_KITS_JS_SRC_MOD_FILEIO_PROPERTIES_TRUNCATE_H - -#include "../../common/log.h" -#include "../../common/napi/n_async/n_async_work_callback.h" -#include "../../common/napi/n_async/n_async_work_promise.h" -#include "../../common/napi/n_func_arg.h" - -namespace OHOS { -namespace DistributedFS { -namespace ModuleFileIO { -class Truncate final { -public: - static napi_value Sync(napi_env env, napi_callback_info info); - static napi_value Async(napi_env env, napi_callback_info info); -}; -} // namespace ModuleFileIO -} // namespace DistributedFS -} // namespace OHOS -#endif \ No newline at end of file diff --git a/interfaces/kits/js/src/mod_fileio/properties/watcher.cpp b/interfaces/kits/js/src/mod_fileio/properties/watcher.cpp deleted file mode 100644 index 1b3def2..0000000 --- a/interfaces/kits/js/src/mod_fileio/properties/watcher.cpp +++ /dev/null @@ -1,107 +0,0 @@ -/* - * Copyright (c) 2021 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#include "watcher.h" - -#include -#include -#include -#include - -#include "../../common/napi/n_async/n_ref.h" -#include "../../common/napi/n_class.h" -#include "../../common/napi/n_func_arg.h" -#include "../../common/napi/n_val.h" -#include "../../common/uni_error.h" - -#include "../class_watcher/watcher_entity.h" -#include "../class_watcher/watcher_n_exporter.h" -namespace OHOS { -namespace DistributedFS { -namespace ModuleFileIO { -using namespace std; - -void Watcher::RunCommand(uv_fs_event_t *handle, const char *filename, int events, int status) -{ - WatcherInforArg *information = (WatcherInforArg *)handle->data; - uint32_t eventsFirst { events }; - uint32_t eventsSecond { information->events }; - if (eventsFirst & eventsSecond) { - napi_handle_scope scope = nullptr; - napi_open_handle_scope(information->env, &scope); - napi_value callback = nullptr; - napi_get_reference_value(information->env, information->ref, &callback); - vector argv; - argv.push_back(NVal::CreateInt64(information->env, events).val_); - napi_value global = nullptr; - napi_get_global(information->env, &global); - napi_value tmp = nullptr; - napi_call_function(information->env, global, callback, argv.size(), argv.data(), &tmp); - } -} - -napi_value Watcher::CreateWatcher(napi_env env, napi_callback_info info) -{ - NFuncArg funcArg(env, info); - if (!funcArg.InitArgs(NARG_CNT::THREE)) { - UniError(EINVAL).ThrowErr(env, "Number of arguments unmatched"); - return nullptr; - } - - bool succGetPath = false; - unique_ptr filename; - tie(succGetPath, filename, ignore) = NVal(env, funcArg[NARG_POS::FIRST]).ToUTF8String(); - if (!succGetPath) { - UniError(EINVAL).ThrowErr(env, "Invalid filename"); - return nullptr; - } - bool succGetEvent = false; - int event; - tie(succGetEvent, event) = NVal(env, funcArg[NARG_POS::SECOND]).ToInt32(); - if (!succGetEvent) { - UniError(EINVAL).ThrowErr(env, "Invalid event"); - return nullptr; - } - - unique_ptr data = make_unique(); - data->events = event; - data->env = env; - NVal val = NVal(env, funcArg[NARG_POS::THIRD]); - napi_create_reference(val.env_, val.val_, 1, &(data->ref)); - uv_loop_s *loop = nullptr; - napi_get_uv_event_loop(env, &loop); - unique_ptr fsEventReq(new uv_fs_event_t); - uv_fs_event_init(loop, fsEventReq.get()); - fsEventReq->data = data.get(); - uv_fs_event_start(fsEventReq.get(), RunCommand, filename.get(), UV_FS_EVENT_RECURSIVE); - - napi_value objWatcher = NClass::InstantiateClass(env, WatcherNExporter::className_, {}); - if (!objWatcher) { - UniError(EINVAL).ThrowErr(env, "objWatcher create failed"); - return nullptr; - } - auto watcherEntity = NClass::GetEntityOf(env, objWatcher); - if (!watcherEntity) { - UniError(EINVAL).ThrowErr(env, "watcherEntity get failed"); - return nullptr; - } - watcherEntity->fsEventReq_ = std::move(fsEventReq); - watcherEntity->data_ = std::move(data); - - return objWatcher; -} -} // namespace ModuleFileIO -} // namespace DistributedFS -} // namespace OHOS \ No newline at end of file diff --git a/interfaces/kits/js/src/mod_fileio/properties/watcher.h b/interfaces/kits/js/src/mod_fileio/properties/watcher.h deleted file mode 100644 index 45c100c..0000000 --- a/interfaces/kits/js/src/mod_fileio/properties/watcher.h +++ /dev/null @@ -1,35 +0,0 @@ -/* - * Copyright (c) 2021 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#ifndef INTERFACES_KITS_JS_SRC_MOD_FILEIO_PROPERTIES_WATCHER_H -#define INTERFACES_KITS_JS_SRC_MOD_FILEIO_PROPERTIES_WATCHER_H - -#include -#include "../../common/napi/n_val.h" - -namespace OHOS { -namespace DistributedFS { -namespace ModuleFileIO { -class Watcher final { -public: - static napi_value CreateWatcher(napi_env env, napi_callback_info info); - -private: - static void RunCommand(uv_fs_event_t *handle, const char *filename, int events, int status); -}; -} // namespace ModuleFileIO -} // namespace DistributedFS -} // namespace OHOS -#endif \ No newline at end of file diff --git a/interfaces/kits/js/src/mod_securitylabel/security_label.h b/interfaces/kits/js/src/mod_securitylabel/security_label.h deleted file mode 100644 index 6935790..0000000 --- a/interfaces/kits/js/src/mod_securitylabel/security_label.h +++ /dev/null @@ -1,71 +0,0 @@ -/* - * Copyright (c) 2021-2022 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#ifndef FOUNDATION_FILEMANAGEMENT_FILEAPI_INTERFACES_INNERKITS_SECURITY_LABEL_H -#define FOUNDATION_FILEMANAGEMENT_FILEAPI_INTERFACES_INNERKITS_SECURITY_LABEL_H - -#include -#include -#include -#include -#include - -namespace OHOS { -namespace DistributedFS { -namespace ModuleSecurityLabel { -const char XATTR_KEY[] = {"user.security"}; -const std::string DEFAULT_DATA_LEVEL = "s3"; -const std::set DATA_LEVEL = {"s0", "s1", "s2", "s3", "s4"}; -class SecurityLabel { -public: - static bool SetSecurityLabel(const std::string &path, const std::string &dataLevel) - { - if (DATA_LEVEL.count(dataLevel) != 1) { - return false; - } - if (setxattr(path.c_str(), XATTR_KEY, dataLevel.c_str(), dataLevel.size(), 0) < 0) { - return false; - } - return true; - } - - static std::string GetSecurityLabel(const std::string &path) - { - auto xattrValueSize = getxattr(path.c_str(), XATTR_KEY, nullptr, 0); - if (xattrValueSize == -1 || errno == ENOTSUP) { - return ""; - } - if (xattrValueSize <= 0) { - return DEFAULT_DATA_LEVEL; - } - std::unique_ptr xattrValue = std::make_unique((long)xattrValueSize + 1); - if (xattrValue == nullptr) { - return ""; - } - - xattrValueSize = getxattr(path.c_str(), XATTR_KEY, xattrValue.get(), xattrValueSize); - if (xattrValueSize == -1 || errno == ENOTSUP) { - return ""; - } - if (xattrValueSize <= 0) { - return DEFAULT_DATA_LEVEL; - } - return std::string(xattrValue.get()); - } -}; -} // namespace ModuleSecurityLabel -} // namespace FileIO -} // namespace OHOS -#endif \ No newline at end of file diff --git a/interfaces/kits/js/src/mod_securitylabel/securitylabel_n_exporter.cpp b/interfaces/kits/js/src/mod_securitylabel/securitylabel_n_exporter.cpp deleted file mode 100644 index 49abd6f..0000000 --- a/interfaces/kits/js/src/mod_securitylabel/securitylabel_n_exporter.cpp +++ /dev/null @@ -1,187 +0,0 @@ -/* - * Copyright (c) 2021 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#include "securitylabel_n_exporter.h" - -#include - -#include "../common/napi/n_class.h" -#include "../common/napi/n_func_arg.h" -#include "../common/napi/n_val.h" -#include "../common/uni_error.h" -#include "n_async_work_callback.h" -#include "n_async_work_promise.h" -#include "security_label.h" - - -#include - - -namespace OHOS { -namespace DistributedFS { -namespace ModuleSecurityLabel { -using namespace std; - -napi_value SetSecurityLabel(napi_env env, napi_callback_info info) -{ - NFuncArg funcArg(env, info); - if (!funcArg.InitArgs(static_cast(NARG_CNT::TWO), static_cast(NARG_CNT::THREE))) { - UniError(EINVAL).ThrowErr(env, "Number of arguments unmatched"); - return nullptr; - } - - bool succ = false; - std::unique_ptr path; - std::unique_ptr dataLevel; - tie(succ, path, std::ignore) = NVal(env, funcArg[static_cast(NARG_POS::FIRST)]).ToUTF8String(); - if (!succ) { - UniError(EINVAL).ThrowErr(env, "Invalid path"); - return nullptr; - } - tie(succ, dataLevel, std::ignore) = NVal(env, funcArg[static_cast(NARG_POS::SECOND)]).ToUTF8String(); - if (!succ) { - UniError(EINVAL).ThrowErr(env, "Invalid dataLevel"); - return nullptr; - } - std::string pathString(path.get()); - std::string dataLevelString(dataLevel.get()); - if (DATA_LEVEL.find(dataLevelString) == DATA_LEVEL.end()) { - UniError(EINVAL).ThrowErr(env, "Invalid Argument of dataLevelEnum"); - return nullptr; - } - auto cbExec = [pathString, dataLevelString](napi_env env) -> UniError { - bool ret = SecurityLabel::SetSecurityLabel(pathString, dataLevelString); - if (!ret) { - return UniError(-1); - } else { - return UniError(ERRNO_NOERR); - } - }; - auto cbComplete = [](napi_env env, UniError err) -> NVal { - if (err) { - return { env, err.GetNapiErr(env) }; - } else { - return NVal::CreateUndefined(env); - } - }; - std::string procedureName = "SetSecurityLabel"; - NVal thisVar(env, funcArg.GetThisVar()); - if (funcArg.GetArgc() == static_cast(NARG_CNT::TWO)) { - return NAsyncWorkPromise(env, thisVar).Schedule(procedureName, cbExec, cbComplete).val_; - } else { - NVal cb(env, funcArg[static_cast(NARG_POS::THIRD)]); - if (cb.TypeIs(napi_function)) { - return NAsyncWorkCallback(env, thisVar, cb).Schedule(procedureName, cbExec, cbComplete).val_; - } - } - return NVal::CreateUndefined(env).val_; -} - -napi_value SetSecurityLabelSync(napi_env env, napi_callback_info info) -{ - NFuncArg funcArg(env, info); - if (!funcArg.InitArgs(static_cast(NARG_CNT::TWO), static_cast(NARG_CNT::THREE))) { - UniError(EINVAL).ThrowErr(env, "Number of arguments unmatched"); - return nullptr; - } - - bool succ = false; - std::unique_ptr path; - std::unique_ptr dataLevel; - tie(succ, path, std::ignore) = NVal(env, funcArg[static_cast(NARG_POS::FIRST)]).ToUTF8String(); - if (!succ) { - UniError(EINVAL).ThrowErr(env, "Invalid path"); - return nullptr; - } - tie(succ, dataLevel, std::ignore) = NVal(env, funcArg[static_cast(NARG_POS::SECOND)]).ToUTF8String(); - if (!succ) { - UniError(EINVAL).ThrowErr(env, "Invalid dataLevel"); - return nullptr; - } - if (DATA_LEVEL.find(dataLevel.get()) == DATA_LEVEL.end()) { - UniError(EINVAL).ThrowErr(env, "Invalid Argument of dataLevelEnum"); - return nullptr; - } - bool ret = SecurityLabel::SetSecurityLabel(path.get(), dataLevel.get()); - if (!ret) { - return UniError(-1).GetNapiErr(env); - } else { - return NVal::CreateUndefined(env).val_; - } -} - -napi_value GetSecurityLabel(napi_env env, napi_callback_info info) -{ - NFuncArg funcArg(env, info); - if (!funcArg.InitArgs(static_cast(NARG_CNT::ONE), static_cast(NARG_CNT::TWO))) { - UniError(EINVAL).ThrowErr(env, "Number of arguments unmatched"); - return nullptr; - } - - bool succ = false; - std::unique_ptr path; - tie(succ, path, std::ignore) = NVal(env, funcArg[static_cast(NARG_POS::FIRST)]).ToUTF8String(); - if (!succ) { - UniError(EINVAL).ThrowErr(env, "Invalid path"); - return nullptr; - } - auto result = std::make_shared(); - std::string pathString(path.get()); - auto cbExec = [pathString, result](napi_env env) -> UniError { - *result = SecurityLabel::GetSecurityLabel(pathString); - return UniError(ERRNO_NOERR); - }; - auto cbComplete = [result](napi_env env, UniError err) -> NVal { - if (err) { - return { env, err.GetNapiErr(env) }; - } - return { NVal::CreateUTF8String(env, *result) }; - }; - - std::string procedureName = "GetSecurityLabel"; - NVal thisVar(env, funcArg.GetThisVar()); - if (funcArg.GetArgc() == static_cast(NARG_CNT::ONE)) { - return NAsyncWorkPromise(env, thisVar).Schedule(procedureName, cbExec, cbComplete).val_; - } else { - NVal cb(env, funcArg[static_cast(NARG_POS::SECOND)]); - if (cb.TypeIs(napi_function)) { - return NAsyncWorkCallback(env, thisVar, cb).Schedule(procedureName, cbExec, cbComplete).val_; - } - } - return NVal::CreateUndefined(env).val_; -} - -napi_value GetSecurityLabelSync(napi_env env, napi_callback_info info) -{ - NFuncArg funcArg(env, info); - if (!funcArg.InitArgs(static_cast(NARG_CNT::ONE), static_cast(NARG_CNT::TWO))) { - UniError(EINVAL).ThrowErr(env, "Number of arguments unmatched"); - return nullptr; - } - - bool succ = false; - std::unique_ptr path; - tie(succ, path, std::ignore) = NVal(env, funcArg[static_cast(NARG_POS::FIRST)]).ToUTF8String(); - if (!succ) { - UniError(EINVAL).ThrowErr(env, "Invalid path"); - return nullptr; - } - auto result = std::make_shared(); - *result = SecurityLabel::GetSecurityLabel(path.get()); - return NVal::CreateUTF8String(env, *result).val_; -} -} // namespace ModuleSecurityLabel -} // namespace DistributedFS -} // namespace OHOS \ No newline at end of file diff --git a/interfaces/kits/js/src/mod_securitylabel/securitylabel_n_exporter.h b/interfaces/kits/js/src/mod_securitylabel/securitylabel_n_exporter.h deleted file mode 100644 index 0de9959..0000000 --- a/interfaces/kits/js/src/mod_securitylabel/securitylabel_n_exporter.h +++ /dev/null @@ -1,32 +0,0 @@ -/* - * Copyright (c) 2021 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#ifndef SECURITYLABEL_N_EXPORTER_H -#define SECURITYLABEL_N_EXPORTER_H - -#include "../common/napi/n_exporter.h" - - -namespace OHOS { -namespace DistributedFS { -namespace ModuleSecurityLabel { -napi_value SetSecurityLabel(napi_env env, napi_callback_info info); -napi_value SetSecurityLabelSync(napi_env env, napi_callback_info info); -napi_value GetSecurityLabel(napi_env env, napi_callback_info info); -napi_value GetSecurityLabelSync(napi_env env, napi_callback_info info); -} // namespace ModuleSecurityLabel -} // namespace DistributedFS -} // namespace OHOS -#endif // SECURITYLABEL_N_EXPORTER_H \ No newline at end of file diff --git a/interfaces/kits/js/src/mod_securitylabel/securitylabel_napi.cpp b/interfaces/kits/js/src/mod_securitylabel/securitylabel_napi.cpp deleted file mode 100644 index dde3f5e..0000000 --- a/interfaces/kits/js/src/mod_securitylabel/securitylabel_napi.cpp +++ /dev/null @@ -1,43 +0,0 @@ -/* - * Copyright (c) 2021 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#include "napi/native_api.h" -#include "napi/native_node_api.h" - -#include "securitylabel_n_exporter.h" -#include "securitylabel_napi.h" - -namespace OHOS { -namespace DistributedFS { -namespace ModuleSecurityLabel { -/*********************************************** - * Module export and register - ***********************************************/ -napi_value SecurityLabelExport(napi_env env, napi_value exports) -{ - static napi_property_descriptor desc[] = { - DECLARE_NAPI_FUNCTION("setSecurityLabel", SetSecurityLabel), - DECLARE_NAPI_FUNCTION("setSecurityLabelSync", SetSecurityLabelSync), - DECLARE_NAPI_FUNCTION("getSecurityLabel", GetSecurityLabel), - DECLARE_NAPI_FUNCTION("getSecurityLabelSync", GetSecurityLabelSync), - }; - NAPI_CALL(env, napi_define_properties(env, exports, sizeof(desc) / sizeof(desc[0]), desc)); - return exports; -} - -NAPI_MODULE(securitylabel, SecurityLabelExport) -} // namespace ModuleSecurityLabel -} // namespace DistributedFS -} // namespace OHOS \ No newline at end of file diff --git a/interfaces/kits/js/src/mod_securitylabel/securitylabel_napi.h b/interfaces/kits/js/src/mod_securitylabel/securitylabel_napi.h deleted file mode 100644 index 66c52df..0000000 --- a/interfaces/kits/js/src/mod_securitylabel/securitylabel_napi.h +++ /dev/null @@ -1,27 +0,0 @@ -/* - * Copyright (c) 2021 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#ifndef SECURITYLABEL_NAPI_H -#define SECURITYLABEL_NAPI_H - -#include "napi/native_api.h" - -namespace OHOS { -namespace DistributedFS { -namespace ModuleSecurityLabel { -} // namespace ModuleSecurityLabel -} // namespace DistributedFS -} // namespace OHOS -#endif // SECURITYLABEL_NAPI_H \ No newline at end of file diff --git a/interfaces/kits/js/src/mod_statfs/statfs_n_exporter.cpp b/interfaces/kits/js/src/mod_statfs/statfs_n_exporter.cpp deleted file mode 100644 index ea591d6..0000000 --- a/interfaces/kits/js/src/mod_statfs/statfs_n_exporter.cpp +++ /dev/null @@ -1,512 +0,0 @@ -/* - * Copyright (c) 2021 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#include "statfs_n_exporter.h" - -#include -#include - -namespace OHOS { -namespace DistributedFS { -namespace ModuleStatfs { -using namespace FileManagement::LibN; - -napi_value GetFrSizeSync(napi_env env, napi_callback_info info) -{ - NFuncArg funcArg(env, info); - if (!funcArg.InitArgs(NARG_CNT::ONE)) { - NError(EINVAL).ThrowErr(env, "Number of arguments unmatched"); - return nullptr; - } - - bool succ = false; - std::unique_ptr path; - tie(succ, path, std::ignore) = NVal(env, funcArg[NARG_POS::FIRST]).ToUTF8String(); - if (!succ) { - NError(EINVAL).ThrowErr(env, "Invalid path"); - return nullptr; - } - - struct statvfs diskInfo; - int ret = statvfs(path.get(), &diskInfo); - if (ret != 0) { - NError(errno).ThrowErr(env, "Failed get info"); - return nullptr; - } - unsigned long long freeSize = static_cast(diskInfo.f_bsize) * - static_cast(diskInfo.f_bavail); - return NVal::CreateInt64(env, freeSize).val_; -} - -napi_value GetFrSize(napi_env env, napi_callback_info info) -{ - NFuncArg funcArg(env, info); - if (!funcArg.InitArgs(NARG_CNT::ONE, NARG_CNT::TWO)) { - NError(EINVAL).ThrowErr(env, "Number of arguments unmatched"); - return nullptr; - } - - bool succ = false; - std::unique_ptr path; - tie(succ, path, std::ignore) = NVal(env, funcArg[NARG_POS::FIRST]).ToUTF8String(); - if (!succ) { - NError(EINVAL).ThrowErr(env, "Invalid path"); - return nullptr; - } - - auto resultSize = std::make_shared(); - std::string pathString(path.get()); - auto cbExec = [pathString, resultSize]() -> NError { - struct statvfs diskInfo; - int ret = statvfs(pathString.c_str(), &diskInfo); - if (ret != 0) { - return NError(errno); - } - *resultSize = static_cast(diskInfo.f_bsize) * - static_cast(diskInfo.f_bavail); - return NError(ERRNO_NOERR); - }; - auto cbComplete = [resultSize](napi_env env, NError err) -> NVal { - if (err) { - return { env, err.GetNapiErr(env) }; - } - return NVal::CreateInt64(env, *resultSize); - }; - - std::string procedureName = "GetFrSize"; - NVal thisVar(env, funcArg.GetThisVar()); - if (funcArg.GetArgc() == NARG_CNT::ONE) { - return NAsyncWorkPromise(env, thisVar).Schedule(procedureName, cbExec, cbComplete).val_; - } - NVal cb(env, funcArg[NARG_POS::SECOND]); - return NAsyncWorkCallback(env, thisVar, cb).Schedule(procedureName, cbExec, cbComplete).val_; -} - -napi_value GetBSizeSync(napi_env env, napi_callback_info info) -{ - NFuncArg funcArg(env, info); - if (!funcArg.InitArgs(NARG_CNT::ONE)) { - NError(EINVAL).ThrowErr(env, "Number of arguments unmatched"); - return nullptr; - } - - bool succ = false; - std::unique_ptr path; - tie(succ, path, std::ignore) = NVal(env, funcArg[NARG_POS::FIRST]).ToUTF8String(); - if (!succ) { - NError(EINVAL).ThrowErr(env, "Invalid path"); - return nullptr; - } - - struct statvfs diskInfo; - int ret = statvfs(path.get(), &diskInfo); - if (ret != 0) { - NError(errno).ThrowErr(env); - return nullptr; - } - return NVal::CreateInt64(env, diskInfo.f_bsize).val_; -} - -napi_value GetBSize(napi_env env, napi_callback_info info) -{ - NFuncArg funcArg(env, info); - if (!funcArg.InitArgs(NARG_CNT::ONE, NARG_CNT::TWO)) { - NError(EINVAL).ThrowErr(env, "Number of arguments unmatched"); - return nullptr; - } - - bool succ = false; - std::unique_ptr path; - tie(succ, path, std::ignore) = NVal(env, funcArg[NARG_POS::FIRST]).ToUTF8String(); - if (!succ) { - NError(EINVAL).ThrowErr(env, "Invalid path"); - return nullptr; - } - - auto resultSize = std::make_shared(); - std::string pathString(path.get()); - auto cbExec = [pathString, resultSize]() -> NError { - struct statvfs diskInfo; - int ret = statvfs(pathString.c_str(), &diskInfo); - if (ret != 0) { - return NError(errno); - } - *resultSize = diskInfo.f_bsize; - return NError(ERRNO_NOERR); - }; - auto cbComplete = [resultSize](napi_env env, NError err) -> NVal { - if (err) { - return { env, err.GetNapiErr(env) }; - } - return NVal::CreateInt64(env, *resultSize); - }; - - std::string procedureName = "GetBSize"; - NVal thisVar(env, funcArg.GetThisVar()); - if (funcArg.GetArgc() == NARG_CNT::ONE) { - return NAsyncWorkPromise(env, thisVar).Schedule(procedureName, cbExec, cbComplete).val_; - } - NVal cb(env, funcArg[NARG_POS::SECOND]); - return NAsyncWorkCallback(env, thisVar, cb).Schedule(procedureName, cbExec, cbComplete).val_; -} - -napi_value GetBAvailSync(napi_env env, napi_callback_info info) -{ - NFuncArg funcArg(env, info); - if (!funcArg.InitArgs(NARG_CNT::ONE)) { - NError(EINVAL).ThrowErr(env, "Number of arguments unmatched"); - return nullptr; - } - - bool succ = false; - std::unique_ptr path; - tie(succ, path, std::ignore) = NVal(env, funcArg[NARG_POS::FIRST]).ToUTF8String(); - if (!succ) { - NError(EINVAL).ThrowErr(env, "Invalid path"); - return nullptr; - } - - struct statvfs diskInfo; - int ret = statvfs(path.get(), &diskInfo); - if (ret != 0) { - NError(errno).ThrowErr(env); - return nullptr; - } - return NVal::CreateInt64(env, diskInfo.f_bavail).val_; -} - -napi_value GetBAvail(napi_env env, napi_callback_info info) -{ - NFuncArg funcArg(env, info); - if (!funcArg.InitArgs(NARG_CNT::ONE, NARG_CNT::TWO)) { - NError(EINVAL).ThrowErr(env, "Number of arguments unmatched"); - return nullptr; - } - - bool succ = false; - std::unique_ptr path; - tie(succ, path, std::ignore) = NVal(env, funcArg[NARG_POS::FIRST]).ToUTF8String(); - if (!succ) { - NError(EINVAL).ThrowErr(env, "Invalid path"); - return nullptr; - } - - auto resultSize = std::make_shared(); - std::string pathString(path.get()); - auto cbExec = [pathString, resultSize]() -> NError { - struct statvfs diskInfo; - int ret = statvfs(pathString.c_str(), &diskInfo); - if (ret != 0) { - return NError(errno); - } - *resultSize = diskInfo.f_bavail; - return NError(ERRNO_NOERR); - }; - auto cbComplete = [resultSize](napi_env env, NError err) -> NVal { - if (err) { - return { env, err.GetNapiErr(env) }; - } - return NVal::CreateInt64(env, *resultSize); - }; - - std::string procedureName = "GetBAvail"; - NVal thisVar(env, funcArg.GetThisVar()); - if (funcArg.GetArgc() == NARG_CNT::ONE) { - return NAsyncWorkPromise(env, thisVar).Schedule(procedureName, cbExec, cbComplete).val_; - } - NVal cb(env, funcArg[NARG_POS::SECOND]); - return NAsyncWorkCallback(env, thisVar, cb).Schedule(procedureName, cbExec, cbComplete).val_; -} - -napi_value GetBlocksSync(napi_env env, napi_callback_info info) -{ - NFuncArg funcArg(env, info); - if (!funcArg.InitArgs(NARG_CNT::ONE)) { - NError(EINVAL).ThrowErr(env, "Number of arguments unmatched"); - return nullptr; - } - - bool succ = false; - std::unique_ptr path; - tie(succ, path, std::ignore) = NVal(env, funcArg[NARG_POS::FIRST]).ToUTF8String(); - if (!succ) { - NError(EINVAL).ThrowErr(env, "Invalid path"); - return nullptr; - } - - struct statvfs diskInfo; - int ret = statvfs(path.get(), &diskInfo); - if (ret != 0) { - NError(errno).ThrowErr(env); - return nullptr; - } - return NVal::CreateInt64(env, diskInfo.f_blocks).val_; -} - -napi_value GetBlocks(napi_env env, napi_callback_info info) -{ - NFuncArg funcArg(env, info); - if (!funcArg.InitArgs(NARG_CNT::ONE, NARG_CNT::TWO)) { - NError(EINVAL).ThrowErr(env, "Number of arguments unmatched"); - return nullptr; - } - - bool succ = false; - std::unique_ptr path; - tie(succ, path, std::ignore) = NVal(env, funcArg[NARG_POS::FIRST]).ToUTF8String(); - if (!succ) { - NError(EINVAL).ThrowErr(env, "Invalid path"); - return nullptr; - } - - auto resultSize = std::make_shared(); - std::string pathString(path.get()); - auto cbExec = [pathString, resultSize]() -> NError { - struct statvfs diskInfo; - int ret = statvfs(pathString.c_str(), &diskInfo); - if (ret != 0) { - return NError(errno); - } - *resultSize = diskInfo.f_blocks; - return NError(ERRNO_NOERR); - }; - auto cbComplete = [resultSize](napi_env env, NError err) -> NVal { - if (err) { - return { env, err.GetNapiErr(env) }; - } - return NVal::CreateInt64(env, *resultSize); - }; - - std::string procedureName = "GetBlocks"; - NVal thisVar(env, funcArg.GetThisVar()); - if (funcArg.GetArgc() == NARG_CNT::ONE) { - return NAsyncWorkPromise(env, thisVar).Schedule(procedureName, cbExec, cbComplete).val_; - } - NVal cb(env, funcArg[NARG_POS::SECOND]); - return NAsyncWorkCallback(env, thisVar, cb).Schedule(procedureName, cbExec, cbComplete).val_; -} - -napi_value GetBFreeSync(napi_env env, napi_callback_info info) -{ - NFuncArg funcArg(env, info); - if (!funcArg.InitArgs(NARG_CNT::ONE)) { - NError(EINVAL).ThrowErr(env, "Number of arguments unmatched"); - return nullptr; - } - - bool succ = false; - std::unique_ptr path; - tie(succ, path, std::ignore) = NVal(env, funcArg[NARG_POS::FIRST]).ToUTF8String(); - if (!succ) { - NError(EINVAL).ThrowErr(env, "Invalid path"); - return nullptr; - } - - struct statvfs diskInfo; - int ret = statvfs(path.get(), &diskInfo); - if (ret != 0) { - NError(errno).ThrowErr(env); - return nullptr; - } - return NVal::CreateInt64(env, diskInfo.f_bfree).val_; -} - -napi_value GetBFree(napi_env env, napi_callback_info info) -{ - NFuncArg funcArg(env, info); - if (!funcArg.InitArgs(NARG_CNT::ONE, NARG_CNT::TWO)) { - NError(EINVAL).ThrowErr(env, "Number of arguments unmatched"); - return nullptr; - } - - bool succ = false; - std::unique_ptr path; - tie(succ, path, std::ignore) = NVal(env, funcArg[NARG_POS::FIRST]).ToUTF8String(); - if (!succ) { - NError(EINVAL).ThrowErr(env, "Invalid path"); - return nullptr; - } - - auto resultSize = std::make_shared(); - std::string pathString(path.get()); - auto cbExec = [pathString, resultSize]() -> NError { - struct statvfs diskInfo; - int ret = statvfs(pathString.c_str(), &diskInfo); - if (ret != 0) { - return NError(errno); - } - *resultSize = diskInfo.f_bfree; - return NError(ERRNO_NOERR); - }; - auto cbComplete = [resultSize](napi_env env, NError err) -> NVal { - if (err) { - return { env, err.GetNapiErr(env) }; - } - return NVal::CreateInt64(env, *resultSize); - }; - - std::string procedureName = "GetBFree"; - NVal thisVar(env, funcArg.GetThisVar()); - if (funcArg.GetArgc() == NARG_CNT::ONE) { - return NAsyncWorkPromise(env, thisVar).Schedule(procedureName, cbExec, cbComplete).val_; - } - NVal cb(env, funcArg[NARG_POS::SECOND]); - return NAsyncWorkCallback(env, thisVar, cb).Schedule(procedureName, cbExec, cbComplete).val_; -} - -napi_value GetFreeBytesSync(napi_env env, napi_callback_info info) -{ - NFuncArg funcArg(env, info); - if (!funcArg.InitArgs(NARG_CNT::ONE)) { - NError(EINVAL).ThrowErr(env, "Number of arguments unmatched"); - return nullptr; - } - - bool succ = false; - std::unique_ptr path; - tie(succ, path, std::ignore) = NVal(env, funcArg[NARG_POS::FIRST]).ToUTF8String(); - if (!succ) { - NError(EINVAL).ThrowErr(env, "Invalid path"); - return nullptr; - } - - struct statvfs diskInfo; - int ret = statvfs(path.get(), &diskInfo); - if (ret != 0) { - NError(errno).ThrowErr(env); - return nullptr; - } - unsigned long long freeSize = static_cast(diskInfo.f_bsize) * - static_cast(diskInfo.f_bavail); - return NVal::CreateInt64(env, freeSize).val_; -} - -napi_value GetFreeBytes(napi_env env, napi_callback_info info) -{ - NFuncArg funcArg(env, info); - if (!funcArg.InitArgs(NARG_CNT::ONE, NARG_CNT::TWO)) { - NError(EINVAL).ThrowErr(env, "Number of arguments unmatched"); - return nullptr; - } - - bool succ = false; - std::unique_ptr path; - tie(succ, path, std::ignore) = NVal(env, funcArg[NARG_POS::FIRST]).ToUTF8String(); - if (!succ) { - NError(EINVAL).ThrowErr(env, "Invalid path"); - return nullptr; - } - - auto resultSize = std::make_shared(); - std::string pathString(path.get()); - auto cbExec = [pathString, resultSize]() -> NError { - struct statvfs diskInfo; - int ret = statvfs(pathString.c_str(), &diskInfo); - if (ret != 0) { - return NError(errno); - } - *resultSize = static_cast(diskInfo.f_bsize) * - static_cast(diskInfo.f_bavail); - return NError(ERRNO_NOERR); - }; - auto cbComplete = [resultSize](napi_env env, NError err) -> NVal { - if (err) { - return { env, err.GetNapiErr(env) }; - } - return NVal::CreateInt64(env, *resultSize); - }; - - std::string procedureName = "GetFreeBytes"; - NVal thisVar(env, funcArg.GetThisVar()); - if (funcArg.GetArgc() == NARG_CNT::ONE) { - return NAsyncWorkPromise(env, thisVar).Schedule(procedureName, cbExec, cbComplete).val_; - } - NVal cb(env, funcArg[NARG_POS::SECOND]); - return NAsyncWorkCallback(env, thisVar, cb).Schedule(procedureName, cbExec, cbComplete).val_; -} - -napi_value GetTotalBytesSync(napi_env env, napi_callback_info info) -{ - NFuncArg funcArg(env, info); - if (!funcArg.InitArgs(NARG_CNT::ONE)) { - NError(EINVAL).ThrowErr(env, "Number of arguments unmatched"); - return nullptr; - } - - bool succ = false; - std::unique_ptr path; - tie(succ, path, std::ignore) = NVal(env, funcArg[NARG_POS::FIRST]).ToUTF8String(); - if (!succ) { - NError(EINVAL).ThrowErr(env, "Invalid path"); - return nullptr; - } - - struct statvfs diskInfo; - int ret = statvfs(path.get(), &diskInfo); - if (ret != 0) { - NError(errno).ThrowErr(env); - return nullptr; - } - unsigned long long totalSize = static_cast(diskInfo.f_bsize) * - static_cast(diskInfo.f_blocks); - return NVal::CreateInt64(env, totalSize).val_; -} - -napi_value GetTotalBytes(napi_env env, napi_callback_info info) -{ - NFuncArg funcArg(env, info); - if (!funcArg.InitArgs(NARG_CNT::ONE, NARG_CNT::TWO)) { - NError(EINVAL).ThrowErr(env, "Number of arguments unmatched"); - return nullptr; - } - - bool succ = false; - std::unique_ptr path; - tie(succ, path, std::ignore) = NVal(env, funcArg[NARG_POS::FIRST]).ToUTF8String(); - if (!succ) { - NError(EINVAL).ThrowErr(env, "Invalid path"); - return nullptr; - } - - auto resultSize = std::make_shared(); - std::string pathString(path.get()); - auto cbExec = [pathString, resultSize]() -> NError { - struct statvfs diskInfo; - int ret = statvfs(pathString.c_str(), &diskInfo); - if (ret != 0) { - return NError(errno); - } - *resultSize = static_cast(diskInfo.f_bsize) * - static_cast(diskInfo.f_blocks); - return NError(ERRNO_NOERR); - }; - auto cbComplete = [resultSize](napi_env env, NError err) -> NVal { - if (err) { - return { env, err.GetNapiErr(env) }; - } - return { NVal::CreateInt64(env, *resultSize) }; - }; - - std::string procedureName = "GetTotalBytes"; - NVal thisVar(env, funcArg.GetThisVar()); - if (funcArg.GetArgc() == NARG_CNT::ONE) { - return NAsyncWorkPromise(env, thisVar).Schedule(procedureName, cbExec, cbComplete).val_; - } - NVal cb(env, funcArg[NARG_POS::SECOND]); - return NAsyncWorkCallback(env, thisVar, cb).Schedule(procedureName, cbExec, cbComplete).val_; -} -} // namespace ModuleStatfs -} // namespace DistributedFS -} // namespace OHOS diff --git a/interfaces/kits/js/src/mod_statfs/statfs_n_exporter.h b/interfaces/kits/js/src/mod_statfs/statfs_n_exporter.h deleted file mode 100644 index dd25b17..0000000 --- a/interfaces/kits/js/src/mod_statfs/statfs_n_exporter.h +++ /dev/null @@ -1,47 +0,0 @@ -/* - * Copyright (c) 2021 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#ifndef STATFS_N_EXPORTER_H -#define STATFS_N_EXPORTER_H - -#include "filemgmt_libn.h" - -namespace OHOS { -namespace DistributedFS { -namespace ModuleStatfs { -napi_value GetFrSizeSync(napi_env env, napi_callback_info info); -napi_value GetFrSize(napi_env env, napi_callback_info info); - -napi_value GetBSizeSync(napi_env env, napi_callback_info info); -napi_value GetBSize(napi_env env, napi_callback_info info); - -napi_value GetBAvailSync(napi_env env, napi_callback_info info); -napi_value GetBAvail(napi_env env, napi_callback_info info); - -napi_value GetBlocksSync(napi_env env, napi_callback_info info); -napi_value GetBlocks(napi_env env, napi_callback_info info); - -napi_value GetBFreeSync(napi_env env, napi_callback_info info); -napi_value GetBFree(napi_env env, napi_callback_info info); - -napi_value GetFreeBytesSync(napi_env env, napi_callback_info info); -napi_value GetFreeBytes(napi_env env, napi_callback_info info); - -napi_value GetTotalBytesSync(napi_env env, napi_callback_info info); -napi_value GetTotalBytes(napi_env env, napi_callback_info info); -} // namespace ModuleStatfs -} // namespace DistributedFS -} // namespace OHOS -#endif // STATFS_N_EXPORTER_H \ No newline at end of file diff --git a/interfaces/kits/js/src/mod_statfs/statfs_napi.cpp b/interfaces/kits/js/src/mod_statfs/statfs_napi.cpp deleted file mode 100644 index 0ec3891..0000000 --- a/interfaces/kits/js/src/mod_statfs/statfs_napi.cpp +++ /dev/null @@ -1,38 +0,0 @@ -/* - * Copyright (c) 2021 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#include "statfs_n_exporter.h" -#include "statfs_napi.h" - -namespace OHOS { -namespace DistributedFS { -namespace ModuleStatfs { -/*********************************************** - * Module export and register - ***********************************************/ -napi_value StatfsExport(napi_env env, napi_value exports) -{ - static napi_property_descriptor desc[] = { - DECLARE_NAPI_FUNCTION("getFreeBytes", GetFreeBytes), - DECLARE_NAPI_FUNCTION("getTotalBytes", GetTotalBytes), - }; - NAPI_CALL(env, napi_define_properties(env, exports, sizeof(desc) / sizeof(desc[0]), desc)); - return exports; -} - -NAPI_MODULE(statfs, StatfsExport) -} // namespace ModuleStatfs -} // namespace DistributedFS -} // namespace OHOS \ No newline at end of file diff --git a/interfaces/kits/js/src/mod_statfs/statfs_napi.h b/interfaces/kits/js/src/mod_statfs/statfs_napi.h deleted file mode 100644 index 1af18b9..0000000 --- a/interfaces/kits/js/src/mod_statfs/statfs_napi.h +++ /dev/null @@ -1,27 +0,0 @@ -/* - * Copyright (c) 2021 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#ifndef STATFS_NAPI_H -#define STATFS_NAPI_H - -#include "filemgmt_libn.h" - -namespace OHOS { -namespace DistributedFS { -namespace ModuleStatfs { -} // namespace ModuleStatfs -} // namespace DistributedFS -} // namespace OHOS -#endif // STATFS_NAPI_H \ No newline at end of file diff --git a/interfaces/kits/napi/BUILD.gn b/interfaces/kits/napi/BUILD.gn deleted file mode 100644 index fdfe4e2..0000000 --- a/interfaces/kits/napi/BUILD.gn +++ /dev/null @@ -1,138 +0,0 @@ -# Copyright (c) 2021 Huawei Device Co., Ltd. -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -import("//build/ohos.gni") -import( - "//foundation/distributeddatamgr/distributedfile/distributedfile_aafwk.gni") - -common_src = [ - "common/napi/n_class.cpp", - "common/napi/n_func_arg.cpp", - "common/napi/n_val.cpp", - "common/uni_error.cpp", - "common/ability_helper.cpp", - "common/common_func.cpp", -] - -ohos_shared_library("fileshare") { - relative_install_dir = "module" - - include_dirs = [ - "//third_party/node/src", - "//foundation/arkui/napi/interfaces/kits", - "//third_party/bounds_checking_function/include", - ] - - sources = common_src - sources += [ - "file_share_ability/file_share_exporter.cpp", - "file_share_ability/module.cpp", - ] - - deps = [ - "${ability_runtime_path}/frameworks/native/ability/native:abilitykit_native", - "//foundation/arkui/napi:ace_napi", - "//third_party/bounds_checking_function:libsec_static", - ] - - external_deps = [ - "ability_base:want", - "ability_runtime:ability_manager", - "bundle_framework:appexecfwk_base", - "bundle_framework:appexecfwk_core", - "hilog:libhilog", - "ipc:ipc_core", - ] - subsystem_name = "distributeddatamgr" - part_name = "storage_standard" -} - -ohos_shared_library("devicesmgr") { - relative_install_dir = "module" - - include_dirs = [ - "//third_party/node/src", - "//foundation/arkui/napi/interfaces/kits", - "//third_party/bounds_checking_function/include", - "//utils/system/safwk/native/include", - ] - - sources = common_src - sources += [ - "device_storage_manager/device_sm_exporter.cpp", - "device_storage_manager/module.cpp", - ] - - deps = [ - "${ability_runtime_path}/frameworks/native/ability/native:abilitykit_native", - "//foundation/arkui/napi:ace_napi", - "//third_party/bounds_checking_function:libsec_static", - ] - - external_deps = [ - "ability_base:want", - "ability_runtime:ability_manager", - "bundle_framework:appexecfwk_base", - "bundle_framework:appexecfwk_core", - "hilog:libhilog", - "ipc:ipc_core", - "safwk:system_ability_fwk", - "samgr:samgr_proxy", - ] - subsystem_name = "distributeddatamgr" - part_name = "storage_standard" -} - -ohos_shared_library("filepicker") { - relative_install_dir = "module" - - include_dirs = [ - "//third_party/node/src", - "//foundation/arkui/napi/interfaces/kits", - "//third_party/bounds_checking_function/include", - "//utils/system/safwk/native/include", - ] - - sources = common_src - sources += [ - "file_picker_service/file_picker_exporter.cpp", - "file_picker_service/module.cpp", - ] - - deps = [ - "${ability_runtime_path}/frameworks/native/ability/native:abilitykit_native", - "//foundation/arkui/napi:ace_napi", - "//foundation/systemabilitymgr/samgr/interfaces/innerkits/samgr_proxy:samgr_proxy", - "//third_party/bounds_checking_function:libsec_static", - ] - - external_deps = [ - "ability_base:want", - "ability_runtime:ability_manager", - "bundle_framework:appexecfwk_base", - "bundle_framework:appexecfwk_core", - "hilog:libhilog", - "ipc:ipc_core", - "safwk:system_ability_fwk", - ] - subsystem_name = "distributeddatamgr" - part_name = "storage_standard" -} - -group("build_kits_napi") { - deps = [ - ":devicesmgr", - ":filepicker", - ":fileshare", - ] -} diff --git a/interfaces/kits/napi/common/ability_helper.cpp b/interfaces/kits/napi/common/ability_helper.cpp deleted file mode 100644 index c5aae15..0000000 --- a/interfaces/kits/napi/common/ability_helper.cpp +++ /dev/null @@ -1,54 +0,0 @@ -/* - * Copyright (c) 2021 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#include "ability_helper.h" - -#include "log.h" -#include "napi/n_func_arg.h" -#include "napi/uni_header.h" - -namespace OHOS { -namespace DistributedFS { -using namespace std; -using OHOS::AppExecFwk::Ability; -using OHOS::AppExecFwk::AbilityContext; - -Ability* AbilityHelper::GetJsAbility(napi_env env) -{ - napi_value global = nullptr; - napi_value abilityContext = nullptr; - - napi_status status = napi_get_global(env, &global); - if (status != napi_ok || global == nullptr) { - HILOGE("Cannot get global instance for %{public}d", status); - return nullptr; - } - - status = napi_get_named_property(env, global, "ability", &abilityContext); - if (status != napi_ok || abilityContext == nullptr) { - HILOGE("Cannot get ability context for %{public}d", status); - return nullptr; - } - - Ability *ability = nullptr; - status = napi_get_value_external(env, abilityContext, (void **)&ability); - if (status != napi_ok || ability == nullptr) { - HILOGE("Get ability form property failed for %{public}d", status); - } - - return ability; -} -} // namespace DistributedFS -} // namespace OHOS \ No newline at end of file diff --git a/interfaces/kits/napi/common/ability_helper.h b/interfaces/kits/napi/common/ability_helper.h deleted file mode 100644 index 0b93a00..0000000 --- a/interfaces/kits/napi/common/ability_helper.h +++ /dev/null @@ -1,29 +0,0 @@ -/* - * Copyright (c) 2021 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#ifndef INTERFACES_KITS_NAPI_COMMON_ABILITY_HELPER_H -#define INTERFACES_KITS_NAPI_COMMON_ABILITY_HELPER_H - -#include "../common/napi/uni_header.h" -#include "ability.h" - -namespace OHOS { -namespace DistributedFS { -struct AbilityHelper { - static AppExecFwk::Ability *GetJsAbility(napi_env env); -}; -} // namespace DistributedFS -} // namespace OHOS -#endif \ No newline at end of file diff --git a/interfaces/kits/napi/common/common_func.cpp b/interfaces/kits/napi/common/common_func.cpp deleted file mode 100644 index ac022f5..0000000 --- a/interfaces/kits/napi/common/common_func.cpp +++ /dev/null @@ -1,57 +0,0 @@ -/* - * Copyright (c) 2021 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#include "common_func.h" - -#include "napi/n_func_arg.h" - -namespace OHOS { -namespace DistributedFS { -using namespace std; - -tuple CommonFunc::GetCallbackHandles(napi_env env, napi_value object) -{ - bool succ = false; - NVal prop = NVal(env, object); - napi_value successProp, failProp, completeProp; - napi_ref successHandle = nullptr; - napi_ref failHandle = nullptr; - napi_ref completeHandle = nullptr; - string success = "success"; - string fail = "fail"; - string complete = "complete"; - - successProp = prop.GetProp(success).val_; - if (successProp != nullptr) { - napi_create_reference(env, successProp, 1, &successHandle); - succ = true; - } - - failProp = prop.GetProp(fail).val_; - if (succ && failProp != nullptr) { - napi_create_reference(env, failProp, 1, &failHandle); - succ = true; - } - - completeProp = prop.GetProp(complete).val_; - if (succ && completeProp != nullptr) { - napi_create_reference(env, completeProp, 1, &completeHandle); - succ = true; - } - - return { succ, successHandle, failHandle, completeHandle }; -} -} // namespace DistributedFS -} // namespace OHOS diff --git a/interfaces/kits/napi/common/common_func.h b/interfaces/kits/napi/common/common_func.h deleted file mode 100644 index 2a3553e..0000000 --- a/interfaces/kits/napi/common/common_func.h +++ /dev/null @@ -1,34 +0,0 @@ -/* - * Copyright (c) 2021 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#ifndef INTERFACES_KITS_NAPI_COMMON_COMMON_FUNC_H -#define INTERFACES_KITS_NAPI_COMMON_COMMON_FUNC_H - -#include -#include "napi/uni_header.h" - -namespace OHOS { -namespace DistributedFS { -const std::string FUNC_PROP_SUCCESS = "success"; -const std::string FUNC_PROP_FAIL = "fail"; -const std::string FUNC_PROP_COMPLETE = "complete"; - -struct CommonFunc { - static std::tuple GetCallbackHandles(napi_env env, - napi_value object); -}; -} // namespace DistributedFS -} // namespace OHOS -#endif \ No newline at end of file diff --git a/interfaces/kits/napi/common/log.h b/interfaces/kits/napi/common/log.h deleted file mode 100644 index 412b5f6..0000000 --- a/interfaces/kits/napi/common/log.h +++ /dev/null @@ -1,92 +0,0 @@ -/* - * Copyright (c) 2021 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#ifndef INTERFACES_KITS_NAPI_COMMON_LOG_H -#define INTERFACES_KITS_NAPI_COMMON_LOG_H - -#include -#include -#include - -#ifndef FILE_SUBSYSTEM_DEBUG_LOCAL -#include "hilog/log.h" -#endif - -namespace OHOS { -namespace DistributedFS { -#ifndef FILE_SUBSYSTEM_DEBUG_LOCAL -static constexpr int FILEIO_DOMAIN_ID = 0; -static constexpr OHOS::HiviewDFX::HiLogLabel FILEIO_LABEL = { LOG_CORE, FILEIO_DOMAIN_ID, "distributedfilejs" }; - -#ifdef HILOGD -#undef HILOGD -#endif - -#ifdef HILOGF -#undef HILOGF -#endif - -#ifdef HILOGE -#undef HILOGE -#endif - -#ifdef HILOGW -#undef HILOGW -#endif - -#ifdef HILOGI -#undef HILOGI -#endif - -#define HILOGD(fmt, ...) \ - (void)OHOS::HiviewDFX::HiLog::Debug(OHOS::DistributedFS::FILEIO_LABEL, "%{public}s: " fmt, __func__, ##__VA_ARGS__) -#define HILOGI(fmt, ...) \ - (void)OHOS::HiviewDFX::HiLog::Info(OHOS::DistributedFS::FILEIO_LABEL, "%{public}s: " fmt, __func__, ##__VA_ARGS__) -#define HILOGW(fmt, ...) \ - (void)OHOS::HiviewDFX::HiLog::Warn(OHOS::DistributedFS::FILEIO_LABEL, "%{public}s: " fmt, __func__, ##__VA_ARGS__) -#define HILOGE(fmt, ...) \ - (void)OHOS::HiviewDFX::HiLog::Error(OHOS::DistributedFS::FILEIO_LABEL, "%{public}s: " fmt, __func__, ##__VA_ARGS__) -#define HILOGF(fmt, ...) \ - (void)OHOS::HiviewDFX::HiLog::Fatal(OHOS::DistributedFS::FILEIO_LABEL, "%{public}s: " fmt, __func__, ##__VA_ARGS__) - -#else - -#define PCLOG(fmt, ...) \ - do { \ - const std::vector filter = { \ - "{public}", \ - "{private}", \ - }; \ - std::string str____(fmt); \ - for (auto &&pattern : filter) { \ - size_t pos = 0; \ - while (std::string::npos != (pos = str____.find(pattern))) { \ - str____.erase(pos, pattern.length()); \ - } \ - } \ - str____ += "\n"; \ - printf(str____.c_str(), ##__VA_ARGS__); \ - } while (0) \ - -#define HILOGD(fmt, ...) PCLOG("%{public}s: " fmt, __func__, ##__VA_ARGS__) -#define HILOGI(fmt, ...) PCLOG("%{public}s: " fmt, __func__, ##__VA_ARGS__) -#define HILOGW(fmt, ...) PCLOG("%{public}s: " fmt, __func__, ##__VA_ARGS__) -#define HILOGE(fmt, ...) PCLOG("%{public}s: " fmt, __func__, ##__VA_ARGS__) -#define HILOGF(fmt, ...) PCLOG("%{public}s: " fmt, __func__, ##__VA_ARGS__) - -#endif -} // namespace DistributedFS -} // namespace OHOS -#endif \ No newline at end of file diff --git a/interfaces/kits/napi/common/napi/n_class.cpp b/interfaces/kits/napi/common/napi/n_class.cpp deleted file mode 100644 index a9cdff3..0000000 --- a/interfaces/kits/napi/common/napi/n_class.cpp +++ /dev/null @@ -1,100 +0,0 @@ -/* - * Copyright (c) 2021 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#include "n_class.h" - -#include -#include - -#include "../log.h" - -namespace OHOS { -namespace DistributedFS { -using namespace std; -NClass &NClass::GetInstance() -{ - static NClass nClass; - return nClass; -} - -tuple NClass::DefineClass( - napi_env env, - string className, - napi_callback constructor, - vector &&properties) -{ - napi_value classVal = nullptr; - napi_status stat = napi_define_class(env, - className.c_str(), - className.length(), - constructor, - nullptr, - properties.size(), - properties.data(), - &classVal); - if (stat != napi_ok) { - HILOGE("INNER BUG. Cannot define class %{public}s because of %{public}d", className.c_str(), stat); - } - return { stat == napi_ok, classVal }; -} - -bool NClass::SaveClass(napi_env env, string className, napi_value exClass) -{ - NClass &nClass = NClass::GetInstance(); - lock_guard(nClass.exClassMapLock); - - if (nClass.exClassMap.find(className) != nClass.exClassMap.end()) { - return true; - } - - napi_ref constructor; - napi_status res = napi_create_reference(env, exClass, 1, &constructor); - if (res == napi_ok) { - nClass.exClassMap.insert ({ className, constructor }); - HILOGI("Class %{public}s has been saved", className.c_str()); - } else { - HILOGE("INNER BUG. Cannot ref class constructor %{public}s because of %{public}d", className.c_str(), res); - } - return res == napi_ok; -} - -napi_value NClass::InstantiateClass(napi_env env, const string& className, const vector& args) -{ - NClass &nClass = NClass::GetInstance(); - lock_guard(nClass.exClassMapLock); - - auto it = nClass.exClassMap.find(className); - if (it == nClass.exClassMap.end()) { - HILOGE("Class %{public}s hasn't been saved yet", className.c_str()); - return nullptr; - } - - napi_value cons = nullptr; - napi_status status = napi_get_reference_value(env, it->second, &cons); - if (status != napi_ok) { - HILOGE("INNER BUG. Cannot deref class %{public}s because of %{public}d", className.c_str(), status); - return nullptr; - } - - napi_value instance = nullptr; - status = napi_new_instance(env, cons, args.size(), args.data(), &instance); - if (status != napi_ok) { - HILOGE("INNER BUG. Cannot instantiate the class %{public}s because of %{public}d", className.c_str(), status); - return nullptr; - } - return instance; -} -} // namespace DistributedFS -} // namespace OHOS \ No newline at end of file diff --git a/interfaces/kits/napi/common/napi/n_class.h b/interfaces/kits/napi/common/napi/n_class.h deleted file mode 100644 index 55c97d5..0000000 --- a/interfaces/kits/napi/common/napi/n_class.h +++ /dev/null @@ -1,81 +0,0 @@ -/* - * Copyright (c) 2021 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#ifndef INTERFACES_KITS_NAPI_COMMON_NAPI_N_CLASS_H -#define INTERFACES_KITS_NAPI_COMMON_NAPI_N_CLASS_H - -#include "uni_header.h" - -#include -#include -#include - -#include "../log.h" - -namespace OHOS { -namespace DistributedFS { -class NClass final { -public: - NClass(const NClass &) = delete; - NClass &operator = (const NClass &) = delete; - static NClass &GetInstance(); - - static std::tuple DefineClass(napi_env env, - std::string className, - napi_callback constructor, - std::vector &&properties); - static bool SaveClass(napi_env env, std::string className, napi_value exClass); - static napi_value InstantiateClass(napi_env env, const std::string& className, const std::vector& args); - - template static T *GetEntityOf(napi_env env, napi_value objStat) - { - if (!env || !objStat) { - HILOGE("Empty input: env %d, obj %d", env == nullptr, objStat == nullptr); - return nullptr; - } - T *t = nullptr; - napi_status status = napi_unwrap(env, objStat, (void **)&t); - if (status != napi_ok) { - HILOGE("Cannot umwarp for pointer: %d", status); - return nullptr; - } - return t; - } - - template static bool SetEntityFor(napi_env env, napi_value obj, std::unique_ptr entity) - { - napi_status status = napi_wrap( - env, - obj, - entity.get(), - [](napi_env env, void *data, void *hint) { - auto entity = static_cast(data); - delete entity; - }, - nullptr, - nullptr); - entity.release(); - return status == napi_ok; - } - -private: - NClass() = default; - ~NClass() = default; - std::map exClassMap; - std::mutex exClassMapLock; -}; -} // namespace DistributedFS -} // namespace OHOS -#endif \ No newline at end of file diff --git a/interfaces/kits/napi/common/napi/n_exporter.h b/interfaces/kits/napi/common/napi/n_exporter.h deleted file mode 100644 index 5f1b951..0000000 --- a/interfaces/kits/napi/common/napi/n_exporter.h +++ /dev/null @@ -1,40 +0,0 @@ -/* - * Copyright (c) 2021 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#ifndef INTERFACES_KITS_NAPI_COMMON_NAPI_N_EXPORTER_H -#define INTERFACES_KITS_NAPI_COMMON_NAPI_N_EXPORTER_H - -#include "uni_header.h" - -#include - -#include "n_val.h" - -namespace OHOS { -namespace DistributedFS { -class NExporter { -public: - NExporter(napi_env env, napi_value exports) : exports_(env, exports) {}; - virtual ~NExporter() = default; - - virtual bool Export() = 0; - virtual std::string GetClassName() = 0; - -protected: - NVal exports_; -}; -} // namespace DistributedFS -} // namespace OHOS -#endif \ No newline at end of file diff --git a/interfaces/kits/napi/common/napi/n_func_arg.cpp b/interfaces/kits/napi/common/napi/n_func_arg.cpp deleted file mode 100644 index 5200ebd..0000000 --- a/interfaces/kits/napi/common/napi/n_func_arg.cpp +++ /dev/null @@ -1,107 +0,0 @@ -/* - * Copyright (c) 2021 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#include "n_func_arg.h" - -#include "../log.h" - -namespace OHOS { -namespace DistributedFS { -using namespace std; - -NFuncArg::NFuncArg(napi_env env, napi_callback_info info) : env_(env), info_(info) {} - -NFuncArg::~NFuncArg() {} - -void NFuncArg::SetArgc(size_t argc) -{ - argc_ = argc; -} -void NFuncArg::SetThisVar(napi_value thisVar) -{ - thisVar_ = thisVar; -} - -size_t NFuncArg::GetArgc(void) const -{ - return argc_; -} - -napi_value NFuncArg::GetThisVar(void) const -{ - return thisVar_; -} - -napi_value NFuncArg::GetArg(size_t argPos) const -{ - return (argPos < GetArgc()) ? argv_[argPos] : nullptr; -} - -napi_value NFuncArg::operator[](size_t argPos) const -{ - return GetArg(argPos); -} - -bool NFuncArg::InitArgs(std::function argcChecker) -{ - SetArgc(0); - argv_.reset(); - - size_t argc; - napi_value thisVar; - napi_status status = napi_get_cb_info(env_, info_, &argc, nullptr, &thisVar, nullptr); - if (status != napi_ok) { - HILOGE("Cannot get num of func args for %{public}d", status); - return false; - } - if (argc) { - argv_ = make_unique(argc); - status = napi_get_cb_info(env_, info_, &argc, argv_.get(), &thisVar, nullptr); - if (status != napi_ok) { - HILOGE("Cannot get func args for %{public}d", status); - return false; - } - } - SetArgc(argc); - SetThisVar(thisVar); - - return argcChecker(); -} - -bool NFuncArg::InitArgs(size_t argc) -{ - return InitArgs([argc, this]() { - size_t realArgc = GetArgc(); - if (argc != realArgc) { - HILOGE("Num of args recved eq %zu while expecting %{public}zu", realArgc, argc); - return false; - } - return true; - }); -} - -bool NFuncArg::InitArgs(size_t minArgc, size_t maxArgc) -{ - return InitArgs([minArgc, maxArgc, this]() { - size_t realArgc = GetArgc(); - if (minArgc > realArgc || maxArgc < realArgc) { - HILOGE("Num of args recved eq %zu while expecting %{public}zu ~ %{public}zu", realArgc, minArgc, maxArgc); - return false; - } - return true; - }); -} -} // namespace DistributedFS -} // namespace OHOS diff --git a/interfaces/kits/napi/common/napi/n_func_arg.h b/interfaces/kits/napi/common/napi/n_func_arg.h deleted file mode 100644 index e1fba21..0000000 --- a/interfaces/kits/napi/common/napi/n_func_arg.h +++ /dev/null @@ -1,69 +0,0 @@ -/* - * Copyright (c) 2021 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#ifndef INTERFACES_KITS_NAPI_COMMON_NAPI_N_FUNC_ARG_H -#define INTERFACES_KITS_NAPI_COMMON_NAPI_N_FUNC_ARG_H - -#include - -#include "uni_header.h" - -namespace OHOS { -namespace DistributedFS { -enum NARG_CNT { - ZERO = 0, - ONE = 1, - TWO = 2, - THREE = 3, - FOUR = 4, -}; - -enum NARG_POS { - FIRST = 0, - SECOND = 1, - THIRD = 2, - FOURTH = 3, -}; - -class NFuncArg final { -public: - NFuncArg(napi_env env, napi_callback_info info); - virtual ~NFuncArg(); - - bool InitArgs(size_t argc); - bool InitArgs(size_t minArgc, size_t maxArgc); - - size_t GetArgc() const; - napi_value GetThisVar() const; - - napi_value operator[](size_t idx) const; - napi_value GetArg(size_t argPos) const; - -private: - napi_env env_ = nullptr; - napi_callback_info info_ = nullptr; - - size_t argc_ = 0; - std::unique_ptr argv_ = { nullptr }; - napi_value thisVar_ = nullptr; - - bool InitArgs(std::function argcChecker); - - void SetArgc(size_t argc); - void SetThisVar(napi_value thisVar); -}; -} // namespace DistributedFS -} // namespace OHOS -#endif \ No newline at end of file diff --git a/interfaces/kits/napi/common/napi/n_val.cpp b/interfaces/kits/napi/common/napi/n_val.cpp deleted file mode 100644 index 5c28576..0000000 --- a/interfaces/kits/napi/common/napi/n_val.cpp +++ /dev/null @@ -1,280 +0,0 @@ -/* - * Copyright (c) 2021 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#include "n_val.h" - -#include -#include - -#include "../log.h" -#include "../uni_error.h" - -namespace OHOS { -namespace DistributedFS { -using namespace std; - -NVal::NVal(napi_env nEnv, napi_value nVal = nullptr) : env_(nEnv), val_(nVal) {} - -NVal::operator bool() const -{ - return env_ && val_; -} - -bool NVal::TypeIs(napi_valuetype expType) const -{ - if (!*this) { - return false; - } - - napi_valuetype valueType; - napi_typeof(env_, val_, &valueType); - - if (expType != valueType) { - return false; - } - return true; -} - -tuple, size_t> NVal::ToUTF8String() const -{ - size_t strLen = 0; - napi_status status = napi_get_value_string_utf8(env_, val_, nullptr, -1, &strLen); - if (status != napi_ok) { - return { false, nullptr, 0 }; - } - - size_t bufLen = strLen + 1; - unique_ptr str = make_unique(bufLen); - status = napi_get_value_string_utf8(env_, val_, str.get(), bufLen, &strLen); - return make_tuple(status == napi_ok, move(str), strLen); -} - -tuple, size_t> NVal::ToUTF16String() const -{ -#ifdef FILE_SUBSYSTEM_DEBUG_LOCAL - size_t strLen = 0; - napi_status status = napi_get_value_string_utf16(env_, val_, nullptr, -1, &strLen); - if (status != napi_ok) { - return { false, nullptr, 0 }; - } - - auto str = make_unique(++strLen); - status = napi_get_value_string_utf16(env_, val_, str.get(), strLen, nullptr); - if (status != napi_ok) { - return { false, nullptr, 0 }; - } - - strLen = reinterpret_cast(str.get() + strLen) - reinterpret_cast(str.get()); - auto strRet = unique_ptr(reinterpret_cast(str.release())); - return { true, move(strRet), strLen }; -#else - // Note that quickjs doesn't support utf16 - return ToUTF8String(); -#endif -} - -tuple NVal::ToPointer() const -{ - void *res = nullptr; - napi_status status = napi_get_value_external(env_, val_, &res); - return make_tuple(status == napi_ok, res); -} - -tuple NVal::ToBool() const -{ - bool flag = false; - napi_status status = napi_get_value_bool(env_, val_, &flag); - return make_tuple(status == napi_ok, flag); -} - -tuple NVal::ToInt32() const -{ - int32_t res = 0; - napi_status status = napi_get_value_int32(env_, val_, &res); - return make_tuple(status == napi_ok, res); -} - -tuple NVal::ToInt64() const -{ - int64_t res = 0; - napi_status status = napi_get_value_int64(env_, val_, &res); - return make_tuple(status == napi_ok, res); -} - -tuple NVal::ToArraybuffer() const -{ - void *buf = nullptr; - size_t bufLen = 0; - bool status = napi_get_arraybuffer_info(env_, val_, &buf, &bufLen); - return make_tuple(status == napi_ok, buf, bufLen); -} - -tuple NVal::ToTypedArray() const -{ - napi_typedarray_type type; - napi_value inArrayBuffer = nullptr; - size_t byteOffset; - size_t length; - void *data = nullptr; - napi_status status = - napi_get_typedarray_info(env_, val_, &type, &length, (void **)&data, &inArrayBuffer, &byteOffset); - return make_tuple(status == napi_ok, data, length); -} - -bool NVal::HasProp(string propName) const -{ - bool res = false; - - if (!env_ || !val_ || !TypeIs(napi_object)) - return false; - napi_status status = napi_has_named_property(env_, val_, propName.c_str(), &res); - return (status == napi_ok) && res; -} - -NVal NVal::GetProp(string propName) const -{ - if (!HasProp(propName)) { - return { env_, nullptr }; - } - napi_value prop = nullptr; - napi_status status = napi_get_named_property(env_, val_, propName.c_str(), &prop); - if (status != napi_ok) { - return { env_, nullptr }; - } - return NVal(env_, prop); -} - -bool NVal::AddProp(vector &&propVec) const -{ - if (!TypeIs(napi_valuetype::napi_object)) { - HILOGE("INNER BUG. Prop should only be added to objects"); - return false; - } - napi_status status = napi_define_properties(env_, val_, propVec.size(), propVec.data()); - if (status != napi_ok) { - HILOGE("INNER BUG. Cannot define properties because of %{public}d", status); - return false; - } - return true; -} - -bool NVal::AddProp(string propName, napi_value val) const -{ - if (!TypeIs(napi_valuetype::napi_object) || HasProp(propName)) { - HILOGE("INNER BUG. Prop should only be added to objects"); - return false; - } - - napi_status status = napi_set_named_property(env_, val_, propName.c_str(), val); - if (status != napi_ok) { - HILOGE("INNER BUG. Cannot set named property because of %{public}d", status); - return false; - } - return true; -} - -NVal NVal::CreateUndefined(napi_env env) -{ - napi_value res = nullptr; - napi_get_undefined(env, &res); - return { env, res }; -} - -NVal NVal::CreateInt64(napi_env env, int64_t val) -{ - napi_value res = nullptr; - napi_create_int64(env, val, &res); - return { env, res }; -} - -NVal NVal::CreateInt32(napi_env env, int32_t val) -{ - napi_value res = nullptr; - napi_create_int32(env, val, &res); - return { env, res }; -} - -NVal NVal::CreateObject(napi_env env) -{ - napi_value res = nullptr; - napi_create_object(env, &res); - return { env, res }; -} - -NVal NVal::CreateBool(napi_env env, bool val) -{ - napi_value res = nullptr; - napi_get_boolean(env, val, &res); - return { env, res }; -} - -NVal NVal::CreateUTF8String(napi_env env, std::string str) -{ - napi_value res = nullptr; - napi_create_string_utf8(env, str.c_str(), str.length(), &res); - return { env, res }; -} - -NVal NVal::CreateUint8Array(napi_env env, void *buf, size_t bufLen) -{ - napi_value outputBuffer = nullptr; - napi_create_external_arraybuffer( - env, - buf, - bufLen, - [](napi_env env, void *finalize_data, void *finalize_hint) { free(finalize_data); }, - NULL, - &outputBuffer); - napi_value outputArray = nullptr; - napi_create_typedarray(env, napi_uint8_array, bufLen, outputBuffer, 0, &outputArray); - return { env, outputArray }; -} - -napi_property_descriptor NVal::DeclareNapiProperty(const char *name, napi_value val) -{ - return { (name), nullptr, nullptr, nullptr, nullptr, val, napi_default, nullptr }; -} - -napi_property_descriptor NVal::DeclareNapiStaticProperty(const char *name, napi_value val) -{ - return { (name), nullptr, nullptr, nullptr, nullptr, val, napi_static, nullptr }; -} - -napi_property_descriptor NVal::DeclareNapiFunction(const char *name, napi_callback func) -{ - return { (name), nullptr, (func), nullptr, nullptr, nullptr, napi_default, nullptr }; -} - -napi_property_descriptor NVal::DeclareNapiStaticFunction(const char *name, napi_callback func) -{ - return { (name), nullptr, (func), nullptr, nullptr, nullptr, napi_static, nullptr }; -} - -napi_property_descriptor NVal::DeclareNapiGetter(const char *name, napi_callback getter) -{ - return { (name), nullptr, nullptr, (getter), nullptr, nullptr, napi_default, nullptr }; -} - -napi_property_descriptor NVal::DeclareNapiSetter(const char *name, napi_callback setter) -{ - return { (name), nullptr, nullptr, nullptr, (setter), nullptr, napi_default, nullptr }; -} - -napi_property_descriptor NVal::DeclareNapiGetterSetter(const char *name, napi_callback getter, napi_callback setter) -{ - return { (name), nullptr, nullptr, (getter), (setter), nullptr, napi_default, nullptr }; -} -} // namespace DistributedFS -} // namespace OHOS \ No newline at end of file diff --git a/interfaces/kits/napi/common/napi/n_val.h b/interfaces/kits/napi/common/napi/n_val.h deleted file mode 100644 index e23a4c6..0000000 --- a/interfaces/kits/napi/common/napi/n_val.h +++ /dev/null @@ -1,79 +0,0 @@ -/* - * Copyright (c) 2021 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#ifndef INTERFACES_KITS_NAPI_COMMON_NAPI_N_VAL_H -#define INTERFACES_KITS_NAPI_COMMON_NAPI_N_VAL_H - -#include -#include - -#include "uni_header.h" - -namespace OHOS { -namespace DistributedFS { -class NVal final { -public: - NVal() = default; - NVal(napi_env nEnv, napi_value nVal); - NVal(const NVal &) = default; - NVal &operator = (const NVal &) = default; - virtual ~NVal() = default; - - // NOTE! env_ and val_ is LIKELY to be null - napi_env env_ = nullptr; - napi_value val_ = nullptr; - - explicit operator bool() const; - bool TypeIs(napi_valuetype expType) const; - - /* SHOULD ONLY BE USED FOR EXPECTED TYPE */ - std::tuple, size_t> ToUTF8String() const; - std::tuple, size_t> ToUTF16String() const; - std::tuple ToPointer() const; - std::tuple ToBool() const; - std::tuple ToInt32() const; - std::tuple ToInt64() const; - std::tuple ToArraybuffer() const; - std::tuple ToTypedArray() const; - - /* Static helpers to create js objects */ - static NVal CreateUndefined(napi_env env); - static NVal CreateInt64(napi_env env, int64_t val); - static NVal CreateInt32(napi_env env, int32_t val); - static NVal CreateObject(napi_env env); - static NVal CreateBool(napi_env env, bool val); - static NVal CreateUTF8String(napi_env env, std::string str); - static NVal CreateUint8Array(napi_env env, void *buf, size_t bufLen); - - /* SHOULD ONLY BE USED FOR OBJECT */ - bool HasProp(std::string propName) const; - NVal GetProp(std::string propName) const; - bool AddProp(std::vector &&propVec) const; - bool AddProp(std::string propName, napi_value nVal) const; - - /* Static helpers to create prop of js objects */ - static napi_property_descriptor DeclareNapiProperty(const char *name, napi_value val); - static napi_property_descriptor DeclareNapiStaticProperty(const char *name, napi_value val); - static napi_property_descriptor DeclareNapiFunction(const char *name, napi_callback func); - static napi_property_descriptor DeclareNapiStaticFunction(const char *name, napi_callback func); - static napi_property_descriptor DeclareNapiGetter(const char *name, napi_callback getter); - static napi_property_descriptor DeclareNapiSetter(const char *name, napi_callback setter); - static inline napi_property_descriptor DeclareNapiGetterSetter(const char *name, - napi_callback getter, - napi_callback setter); -}; -} // namespace DistributedFS -} // namespace OHOS -#endif \ No newline at end of file diff --git a/interfaces/kits/napi/common/napi/uni_header.h b/interfaces/kits/napi/common/napi/uni_header.h deleted file mode 100644 index b764aae..0000000 --- a/interfaces/kits/napi/common/napi/uni_header.h +++ /dev/null @@ -1,25 +0,0 @@ -/* - * Copyright (c) 2021 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#ifndef INTERFACES_KITS_NAPI_COMMON_NAPI_UNI_HEADER_H -#define INTERFACES_KITS_NAPI_COMMON_NAPI_UNI_HEADER_H - -#ifdef FILE_SUBSYSTEM_DEBUG_LOCAL -#include -#else -#include "napi/native_api.h" -#include "napi/native_node_api.h" -#endif -#endif \ No newline at end of file diff --git a/interfaces/kits/napi/common/uni_error.cpp b/interfaces/kits/napi/common/uni_error.cpp deleted file mode 100644 index 295b286..0000000 --- a/interfaces/kits/napi/common/uni_error.cpp +++ /dev/null @@ -1,118 +0,0 @@ -/* - * Copyright (c) 2021 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#include "uni_error.h" - -#include -#include - -#include "log.h" -#include "napi/n_val.h" - -namespace OHOS { -namespace DistributedFS { -using namespace std; - -UniError::UniError() {} - -UniError::UniError(ELegacy eLegacy) : errno_(eLegacy), codingSystem_(ERR_CODE_SYSTEM_LEGACY) {} - -UniError::UniError(int ePosix) : errno_(ePosix), codingSystem_(ERR_CODE_SYSTEM_POSIX) {} - -UniError::operator bool() const -{ - return errno_ != ERRNO_NOERR; -} - -int UniError::GetErrno(ErrCodeSystem cs) -{ - if (errno_ == ERRNO_NOERR) { - return ERRNO_NOERR; - } - if (cs == codingSystem_) { - return errno_; - } - - if (cs == ERR_CODE_SYSTEM_POSIX) { - // Note that we should support more codes here - return EINVAL; - } - - // Note that this shall be done properly - return ELEGACY_INVAL; -} - -void UniError::SetErrno(ELegacy eLegacy) -{ - errno_ = eLegacy; - codingSystem_ = ERR_CODE_SYSTEM_LEGACY; -} - -void UniError::SetErrno(int ePosix) -{ - errno_ = ePosix; - codingSystem_ = ERR_CODE_SYSTEM_POSIX; -} - -std::string UniError::GetDefaultErrstr() -{ - if (codingSystem_ != ERR_CODE_SYSTEM_POSIX && codingSystem_ != ERR_CODE_SYSTEM_LEGACY) { - return "BUG: Curious coding system"; - } - return strerror(GetErrno(ERR_CODE_SYSTEM_POSIX)); -} - -napi_value UniError::GetNapiErr(napi_env env) -{ - return GetNapiErr(env, GetDefaultErrstr()); -} - -napi_value UniError::GetNapiErr(napi_env env, string errMsg) -{ - napi_value code = NVal::CreateUTF8String(env, to_string(GetErrno(codingSystem_))).val_; - napi_value msg = NVal::CreateUTF8String(env, errMsg).val_; - - napi_value res = nullptr; - napi_status createRes = napi_create_error(env, code, msg, &res); - if (createRes) { - HILOGE("Failed to create an exception, msg = %{public}s", errMsg.c_str()); - } - return res; -} - -void UniError::ThrowErr(napi_env env) -{ - string msg = GetDefaultErrstr(); - napi_value tmp = nullptr; - napi_get_and_clear_last_exception(env, &tmp); - // Note that ace engine cannot throw errors created by napi_create_error so far - napi_status throwStatus = napi_throw_error(env, nullptr, msg.c_str()); - if (throwStatus != napi_ok) { - HILOGE("Failed to throw an exception, %{public}d, code = %{public}s", throwStatus, msg.c_str()); - } -} - -void UniError::ThrowErr(napi_env env, string errMsg) -{ - napi_value tmp = nullptr; - napi_get_and_clear_last_exception(env, &tmp); - // Note that ace engine cannot throw errors created by napi_create_error so far - napi_status throwStatus = napi_throw_error(env, nullptr, errMsg.c_str()); - if (throwStatus != napi_ok) { - HILOGE("Failed to throw an exception, %{public}d, code = %{public}s", throwStatus, errMsg.c_str()); - } -} -} // namespace DistributedFS -} // namespace OHOS \ No newline at end of file diff --git a/interfaces/kits/napi/common/uni_error.h b/interfaces/kits/napi/common/uni_error.h deleted file mode 100644 index 2f20d1c..0000000 --- a/interfaces/kits/napi/common/uni_error.h +++ /dev/null @@ -1,60 +0,0 @@ -/* - * Copyright (c) 2021 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#ifndef INTERFACES_KITS_NAPI_COMMON_UNI_ERROR_H -#define INTERFACES_KITS_NAPI_COMMON_UNI_ERROR_H - -namespace OHOS { -namespace DistributedFS { -enum ELegacy { - ELEGACY_INVAL = 202, - ELEGACY_IO = 300, - ELEGACY_NOENT = 301, -}; - -enum ErrCodeSystem { - ERR_CODE_SYSTEM_LEGACY, - ERR_CODE_SYSTEM_POSIX, -}; - -class UniError { -public: - UniError(); - explicit UniError(ELegacy eLegacy); - explicit UniError(int ePosix); - UniError(const UniError &) = default; - ~UniError() = default; - - UniError &operator = (const UniError &) = default; - - explicit operator bool() const; - - void SetErrno(ELegacy eLegacy); - void SetErrno(int ePosix); - int GetErrno(ErrCodeSystem cs); - - std::string GetDefaultErrstr(); - napi_value GetNapiErr(napi_env env); - napi_value GetNapiErr(napi_env env, std::string errMsg); - void ThrowErr(napi_env env); - void ThrowErr(napi_env env, std::string errMsg); - -private: - int errno_ = ERRNO_NOERR; - ErrCodeSystem codingSystem_ = ERR_CODE_SYSTEM_POSIX; -}; -} // namespace DistributedFS -} // namespace OHOS -#endif \ No newline at end of file diff --git a/interfaces/kits/napi/device_storage_manager/device_sm_exporter.cpp b/interfaces/kits/napi/device_storage_manager/device_sm_exporter.cpp deleted file mode 100644 index 5b38a92..0000000 --- a/interfaces/kits/napi/device_storage_manager/device_sm_exporter.cpp +++ /dev/null @@ -1,1017 +0,0 @@ -/* - * Copyright (c) 2021 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#include "device_sm_exporter.h" - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -#include "../common/ability_helper.h" -#include "../common/common_func.h" -#include "../common/napi/n_class.h" -#include "../common/napi/n_func_arg.h" -#include "../common/napi/n_val.h" -#include "../common/uni_error.h" -#include "device_storage_manager.h" - -using Uri = OHOS::Uri; -using namespace std; -namespace OHOS { -namespace DistributedFS { -namespace ModuleDSMExpoter { -enum COMMON_NUM { - ZERO = 0, - ONE = 1, - TWO = 2, - THREE = 3, -}; -const int ERROR = 300; -const int NULL_ERROR = 202; - -static void ForeachVomInfos(std::vector> &infos, - napi_env &env, - napi_value &getvolumenapi, - int32_t &userId) -{ - int32_t i = 0; - - for (auto vomInfo : infos) { - NVal objv = NVal::CreateObject(env); - objv.AddProp("mId", NVal::CreateUTF8String(env, vomInfo->GetId()).val_); - objv.AddProp("mDiskId", NVal::CreateUTF8String(env, vomInfo->GetDiskId()).val_); - objv.AddProp("mPartGuid", NVal::CreateUTF8String(env, vomInfo->GetPartGuid()).val_); - objv.AddProp("mFsUuid", NVal::CreateUTF8String(env, vomInfo->GetFsUuid()).val_); - objv.AddProp("mType", NVal::CreateInt64(env, vomInfo->GetType()).val_); - objv.AddProp("mMountFlags", NVal::CreateInt64(env, vomInfo->GetMountFlags()).val_); - objv.AddProp("mMountUserId", NVal::CreateInt64(env, vomInfo->GetMountUserId()).val_); - objv.AddProp("mState", NVal::CreateInt64(env, vomInfo->GetState()).val_); - objv.AddProp("mPath", NVal::CreateUTF8String(env, vomInfo->GetPath()).val_); - objv.AddProp("mInternalPath", NVal::CreateUTF8String(env, vomInfo->GetInternalPath()).val_); - objv.AddProp("mFsLabel", NVal::CreateUTF8String(env, vomInfo->GetFsLabel()).val_); - objv.AddProp("IsEmulated", NVal::CreateBool(env, vomInfo->IsEmulated()).val_); - objv.AddProp("IsPrimaryEmulatedForUser", - NVal::CreateBool(env, vomInfo->IsPrimaryEmulatedForUser(userId)).val_); - objv.AddProp("IsRemovable", NVal::CreateBool(env, vomInfo->IsRemovable(userId)).val_); - objv.AddProp("IsPrimary", NVal::CreateBool(env, vomInfo->IsPrimary()).val_); - objv.AddProp("Description", NVal::CreateUTF8String(env, vomInfo->GetDescription()).val_); - objv.AddProp("IsVisibleForUser", NVal::CreateBool(env, vomInfo->IsVisibleForUser(userId)).val_); - - napi_set_property(env, getvolumenapi, NVal::CreateInt32(env, i).val_, objv.val_); - i++; - } -} - -static void ForeachDsmInfos(std::vector> &infos, - napi_env &env, - napi_value &diaknapi) -{ - int32_t i = 0; - - for (auto dsmInfo : infos) { - NVal objt = NVal::CreateObject(env); - objt.AddProp("mId", NVal::CreateUTF8String(env, dsmInfo->GetId()).val_); - objt.AddProp("mSysPath", NVal::CreateUTF8String(env, dsmInfo->GetSysPath()).val_); - objt.AddProp("mSize", NVal::CreateInt64(env, dsmInfo->GetSize()).val_); - objt.AddProp("mLabel", NVal::CreateUTF8String(env, dsmInfo->GetLabel()).val_); - objt.AddProp("mFlags", NVal::CreateInt64(env, dsmInfo->GetFlags()).val_); - objt.AddProp("IsUsb", NVal::CreateBool(env, dsmInfo->IsUsb()).val_); - objt.AddProp("IsSd", NVal::CreateBool(env, dsmInfo->IsSd()).val_); - objt.AddProp("IsAdoptable", NVal::CreateBool(env, dsmInfo->IsAdoptable()).val_); - objt.AddProp("Description", NVal::CreateUTF8String(env, dsmInfo->GetDescription()).val_); - - napi_set_property(env, diaknapi, NVal::CreateInt32(env, i).val_, objt.val_); - i++; - } -} - -void CallBackSuccess(napi_env env, napi_ref successFuncRef, int32_t count, napi_value obj) -{ - napi_value results = nullptr; - napi_value successFunc = nullptr; - napi_value global = nullptr; - napi_get_global(env, &global); - napi_get_reference_value(env, successFuncRef, &successFunc); - if (successFunc == nullptr) { - return; - } - napi_call_function(env, global, successFunc, count, &obj, &results); -} -void CallBackError(napi_env env, napi_ref failFuncRef, string errorProp, int errorCode) -{ - napi_value argvFail[2] = { 0 }; - napi_value results = nullptr; - napi_value failFunc = nullptr; - napi_value global = nullptr; - napi_get_global(env, &global); - argvFail[0] = NVal::CreateUTF8String(env, errorProp).val_; - argvFail[1] = NVal::CreateInt32(env, errorCode).val_; - napi_get_reference_value(env, failFuncRef, &failFunc); - if (failFunc == nullptr) { - return; - } - napi_call_function(env, global, failFunc, COMMON_NUM::TWO, argvFail, &results); -} -void CallComplete(napi_env env, napi_ref completeFuncRef) -{ - napi_value completeFunc = nullptr; - napi_value results = nullptr; - napi_value global = nullptr; - napi_get_global(env, &global); - napi_get_reference_value(env, completeFuncRef, &completeFunc); - if (completeFunc == nullptr) { - return; - } - napi_call_function(env, global, completeFunc, COMMON_NUM::ZERO, nullptr, &results); -} - -std::shared_ptr dsm = DelayedSingleton::GetInstance(); -int32_t userId; -napi_value VolumesToNapi(napi_env env, std::vector> infos) -{ - napi_value getvolumenapi; - napi_create_array(env, &getvolumenapi); - ForeachVomInfos(infos, env, getvolumenapi, userId); - return getvolumenapi; -} - -void PriVolToEmuVol(napi_env env, NVal a, std::shared_ptr &emuVol) -{ - bool succ = false; - - unique_ptr id = nullptr; - tie(succ, id, ignore) = a.GetProp("mId").ToUTF8String(); - string cId = (id == nullptr) ? "" : id.get(); - emuVol->SetId(cId); - - unique_ptr diskId = nullptr; - tie(succ, diskId, ignore) = a.GetProp("mDiskId").ToUTF8String(); - emuVol->SetDiskId((diskId == nullptr) ? "" : diskId.get()); - - int64_t type = 0; - tie(succ, type) = a.GetProp("mType").ToInt64(); - emuVol->SetType(type); - - unique_ptr partGuid = nullptr; - tie(succ, partGuid, ignore) = a.GetProp("mPartGuid").ToUTF8String(); - emuVol->SetPartGuid((partGuid == nullptr) ? "" : partGuid.get()); - - int64_t mountFlags = 0; - tie(succ, mountFlags) = a.GetProp("mMountFlags").ToInt64(); - emuVol->SetMountFlags(mountFlags); - - int64_t mountUserId = 0; - tie(succ, mountUserId) = a.GetProp("mMountUserId").ToInt64(); - emuVol->SetMountUserId(mountUserId); - - unique_ptr path = nullptr; - tie(succ, path, ignore) = a.GetProp("mPath").ToUTF8String(); - emuVol->SetPath((path == nullptr) ? "" : path.get()); - - unique_ptr internalPath = nullptr; - tie(succ, internalPath, ignore) = a.GetProp("mInternalPath").ToUTF8String(); - emuVol->SetInternalPath((internalPath == nullptr) ? "" : internalPath.get()); - - unique_ptr fsType = nullptr; - tie(succ, fsType, ignore) = a.GetProp("mFsType").ToUTF8String(); - emuVol->SetFsUuid((fsType == nullptr) ? "" : fsType.get()); - - unique_ptr fsUuid = nullptr; - tie(succ, fsUuid, ignore) = a.GetProp("mFsUuid").ToUTF8String(); - emuVol->SetFsUuid((fsUuid == nullptr) ? "" : fsUuid.get()); - - unique_ptr fsLabel = nullptr; - tie(succ, fsLabel, ignore) = a.GetProp("mFsLabel").ToUTF8String(); - string tId = (fsLabel == nullptr) ? "" : fsLabel.get(); - emuVol->SetFsLabel(tId); - - int64_t state = 0; - tie(succ, state) = a.GetProp("mState").ToInt64(); - emuVol->SetState(state); -} - -void EmuVolToPriVol(napi_env env, NVal a, std::shared_ptr &priVol) -{ - bool succ = false; - - unique_ptr id = nullptr; - tie(succ, id, ignore) = a.GetProp("mId").ToUTF8String(); - string cId = (id == nullptr) ? "" : id.get(); - priVol->SetId(cId); - - unique_ptr diskId = nullptr; - tie(succ, diskId, ignore) = a.GetProp("mDiskId").ToUTF8String(); - priVol->SetDiskId((diskId == nullptr) ? "" : diskId.get()); - - int64_t type = 0; - tie(succ, type) = a.GetProp("mType").ToInt64(); - priVol->SetType(type); - - unique_ptr partGuid = nullptr; - tie(succ, partGuid, ignore) = a.GetProp("mPartGuid").ToUTF8String(); - priVol->SetPartGuid((partGuid == nullptr) ? "" : partGuid.get()); - - int64_t mountFlags = 0; - tie(succ, mountFlags) = a.GetProp("mMountFlags").ToInt64(); - priVol->SetMountFlags(mountFlags); - - int64_t mountUserId = 0; - tie(succ, mountUserId) = a.GetProp("mMountUserId").ToInt64(); - priVol->SetMountUserId(mountUserId); - - unique_ptr path = nullptr; - tie(succ, path, ignore) = a.GetProp("mPath").ToUTF8String(); - priVol->SetPath((path == nullptr) ? "" : path.get()); - - unique_ptr internalPath = nullptr; - tie(succ, internalPath, ignore) = a.GetProp("mInternalPath").ToUTF8String(); - priVol->SetInternalPath((internalPath == nullptr) ? "" : internalPath.get()); - - unique_ptr fsType = nullptr; - tie(succ, fsType, ignore) = a.GetProp("mFsType").ToUTF8String(); - priVol->SetFsUuid((fsType == nullptr) ? "" : fsType.get()); - - unique_ptr fsUuid = nullptr; - tie(succ, fsUuid, ignore) = a.GetProp("mFsUuid").ToUTF8String(); - priVol->SetFsUuid((fsUuid == nullptr) ? "" : fsUuid.get()); - - unique_ptr fsLabel = nullptr; - tie(succ, fsLabel, ignore) = a.GetProp("mFsLabel").ToUTF8String(); - string tId = (fsLabel == nullptr) ? "" : fsLabel.get(); - priVol->SetFsLabel(tId); - - int64_t state = 0; - tie(succ, state) = a.GetProp("mState").ToInt64(); - priVol->SetState(state); -} - -void VolToDesCription(napi_env env, NVal a, std::shared_ptr &vol) -{ - bool succ = false; - - unique_ptr id = nullptr; - tie(succ, id, ignore) = a.GetProp("mId").ToUTF8String(); - string cId = (id == nullptr) ? "" : id.get(); - vol->SetId(cId); - - unique_ptr diskId = nullptr; - tie(succ, diskId, ignore) = a.GetProp("mDiskId").ToUTF8String(); - vol->SetDiskId((diskId == nullptr) ? "" : diskId.get()); - - int64_t type = 0; - tie(succ, type) = a.GetProp("mType").ToInt64(); - vol->SetType(type); - - unique_ptr partGuid = nullptr; - tie(succ, partGuid, ignore) = a.GetProp("mPartGuid").ToUTF8String(); - vol->SetPartGuid((partGuid == nullptr) ? "" : partGuid.get()); - - int64_t mountFlags = 0; - tie(succ, mountFlags) = a.GetProp("mMountFlags").ToInt64(); - vol->SetMountFlags(mountFlags); - - int64_t mountUserId = 0; - tie(succ, mountUserId) = a.GetProp("mMountUserId").ToInt64(); - vol->SetMountUserId(mountUserId); - - unique_ptr path = nullptr; - tie(succ, path, ignore) = a.GetProp("mPath").ToUTF8String(); - vol->SetPath((path == nullptr) ? "" : path.get()); - - unique_ptr internalPath = nullptr; - tie(succ, internalPath, ignore) = a.GetProp("mInternalPath").ToUTF8String(); - vol->SetInternalPath((internalPath == nullptr) ? "" : internalPath.get()); - - unique_ptr fsType = nullptr; - tie(succ, fsType, ignore) = a.GetProp("mFsType").ToUTF8String(); - vol->SetFsUuid((fsType == nullptr) ? "" : fsType.get()); - - unique_ptr fsUuid = nullptr; - tie(succ, fsUuid, ignore) = a.GetProp("mFsUuid").ToUTF8String(); - vol->SetFsUuid((fsUuid == nullptr) ? "" : fsUuid.get()); - - unique_ptr fsLabel = nullptr; - tie(succ, fsLabel, ignore) = a.GetProp("mFsLabel").ToUTF8String(); - string tId = (fsLabel == nullptr) ? "" : fsLabel.get(); - vol->SetFsLabel(tId); - - int64_t state = 0; - tie(succ, state) = a.GetProp("mState").ToInt64(); - vol->SetState(state); -} - -napi_value DeviceSMExporter::Mount(napi_env env, napi_callback_info info) -{ - NFuncArg funcArg(env, info); - if (!funcArg.InitArgs(NARG_CNT::ONE)) { - UniError(EINVAL).ThrowErr(env, "Number of arguments unmatched"); - return nullptr; - } - bool succ = false; - napi_ref napiSuccFun, napiCompFun, napiFailFun; - tie(succ, napiSuccFun, napiFailFun, napiCompFun) = - CommonFunc::GetCallbackHandles(env, funcArg[NARG_POS::FIRST]); - - unique_ptr deviceId = nullptr; - tie(succ, deviceId, ignore) = NVal(env, funcArg[NARG_POS::FIRST]).GetProp("volId").ToUTF8String(); - - std::string mvId = (deviceId == nullptr) ? "" : deviceId.get(); - if (mvId == "") { - CallBackError(env, napiFailFun, "Mount incoming parameter is null", NULL_ERROR); - CallComplete(env, napiCompFun); - napi_delete_reference(env, napiSuccFun); - napi_delete_reference(env, napiFailFun); - napi_delete_reference(env, napiCompFun); - return nullptr; - } - - bool s = dsm->Mount(mvId); - if (s) { - CallBackSuccess(env, napiSuccFun, COMMON_NUM::ZERO, nullptr); - } else { - CallBackError(env, napiFailFun, "Mount return value error", ERROR); - } - CallComplete(env, napiCompFun); - napi_delete_reference(env, napiSuccFun); - napi_delete_reference(env, napiFailFun); - napi_delete_reference(env, napiCompFun); - return NVal::CreateUndefined(env).val_; -} - -napi_value DeviceSMExporter::UnMount(napi_env env, napi_callback_info info) -{ - NFuncArg funcArg(env, info); - if (!funcArg.InitArgs(NARG_CNT::ONE)) { - UniError(EINVAL).ThrowErr(env, "Number of arguments unmatched"); - return nullptr; - } - bool succ = false; - napi_ref napiSuccFun, napiCompFun, napiFailFun; - tie(succ, napiSuccFun, napiFailFun, napiCompFun) = - CommonFunc::GetCallbackHandles(env, funcArg[NARG_POS::FIRST]); - - unique_ptr deviceId = nullptr; - tie(succ, deviceId, ignore) = NVal(env, funcArg[NARG_POS::FIRST]).GetProp("volId").ToUTF8String(); - - std::string mvId = (deviceId == nullptr) ? "" : deviceId.get(); - if (mvId == "") { - CallBackError(env, napiFailFun, "UnMount incoming parameter is null", NULL_ERROR); - CallComplete(env, napiCompFun); - napi_delete_reference(env, napiSuccFun); - napi_delete_reference(env, napiFailFun); - napi_delete_reference(env, napiCompFun); - return nullptr; - } - - bool s = dsm->UnMount(mvId); - if (s) { - CallBackSuccess(env, napiSuccFun, COMMON_NUM::ZERO, nullptr); - } else { - CallBackError(env, napiFailFun, "UnMount return value error", ERROR); - } - - CallComplete(env, napiCompFun); - napi_delete_reference(env, napiSuccFun); - napi_delete_reference(env, napiFailFun); - napi_delete_reference(env, napiCompFun); - return NVal::CreateUndefined(env).val_; -} - -napi_value DeviceSMExporter::Format(napi_env env, napi_callback_info info) -{ - NFuncArg funcArg(env, info); - if (!funcArg.InitArgs(NARG_CNT::ONE)) { - UniError(EINVAL).ThrowErr(env, "Number of arguments unmatched"); - return nullptr; - } - bool succ = false; - napi_ref napiSuccFun, napiCompFun, napiFailFun; - tie(succ, napiSuccFun, napiFailFun, napiCompFun) = - CommonFunc::GetCallbackHandles(env, funcArg[NARG_POS::FIRST]); - - unique_ptr deviceId = nullptr; - tie(succ, deviceId, ignore) = NVal(env, funcArg[NARG_POS::FIRST]).GetProp("volId").ToUTF8String(); - - std::string mvId = (deviceId == nullptr) ? "" : deviceId.get(); - if (mvId == "") { - CallBackError(env, napiFailFun, "Format incoming parameter is null", NULL_ERROR); - CallComplete(env, napiCompFun); - napi_delete_reference(env, napiSuccFun); - napi_delete_reference(env, napiFailFun); - napi_delete_reference(env, napiCompFun); - return nullptr; - } - - bool s = dsm->Format(mvId); - if (s) { - CallBackSuccess(env, napiSuccFun, COMMON_NUM::ZERO, nullptr); - } else { - CallBackError(env, napiFailFun, "Format fail", ERROR); - } - - CallComplete(env, napiCompFun); - napi_delete_reference(env, napiSuccFun); - napi_delete_reference(env, napiFailFun); - napi_delete_reference(env, napiCompFun); - return NVal::CreateUndefined(env).val_; -} - -napi_value DeviceSMExporter::IsEncrypted(napi_env env, napi_callback_info info) -{ - NFuncArg funcArg(env, info); - if (!funcArg.InitArgs(NARG_CNT::ONE)) { - UniError(EINVAL).ThrowErr(env, "Number of arguments unmatched"); - return nullptr; - } - bool succ = false; - napi_ref napiSuccFun, napiCompFun, napiFailFun; - tie(succ, napiSuccFun, napiFailFun, napiCompFun) = - CommonFunc::GetCallbackHandles(env, funcArg[NARG_POS::FIRST]); - - unique_ptr devfilePath = nullptr; - tie(succ, devfilePath, ignore) = NVal(env, funcArg[NARG_POS::FIRST]).GetProp("filePath").ToUTF8String(); - - std::string mFilePath = (devfilePath == nullptr) ? "" : devfilePath.get(); - if (mFilePath == "") { - CallBackError(env, napiFailFun, "IsEncrypted incoming parameter is null", NULL_ERROR); - CallComplete(env, napiCompFun); - napi_delete_reference(env, napiSuccFun); - napi_delete_reference(env, napiFailFun); - napi_delete_reference(env, napiCompFun); - return nullptr; - } - - bool s = dsm->IsEncrypted(mFilePath); - if (s) { - CallBackSuccess(env, napiSuccFun, COMMON_NUM::ZERO, nullptr); - } else { - CallBackError(env, napiFailFun, "Not A Encrypted Path", ERROR); - } - - CallComplete(env, napiCompFun); - napi_delete_reference(env, napiSuccFun); - napi_delete_reference(env, napiFailFun); - napi_delete_reference(env, napiCompFun); - return NVal::CreateUndefined(env).val_; -} -napi_value DeviceSMExporter::PartitionPublic(napi_env env, napi_callback_info info) -{ - NFuncArg funcArg(env, info); - if (!funcArg.InitArgs(NARG_CNT::ONE)) { - UniError(EINVAL).ThrowErr(env, "Number of arguments unmatched"); - return nullptr; - } - bool succ = false; - napi_ref napiSuccFun, napiCompFun, napiFailFun; - tie(succ, napiSuccFun, napiFailFun, napiCompFun) = - CommonFunc::GetCallbackHandles(env, funcArg[NARG_POS::FIRST]); - - unique_ptr deviceId = nullptr; - tie(succ, deviceId, ignore) = NVal(env, funcArg[NARG_POS::FIRST]).GetProp("diskId").ToUTF8String(); - - std::string dsId = (deviceId == nullptr) ? "" : deviceId.get(); - if (dsId == "") { - CallBackError(env, napiFailFun, "PartitionPublic incoming parameter is null", NULL_ERROR); - CallComplete(env, napiCompFun); - napi_delete_reference(env, napiSuccFun); - napi_delete_reference(env, napiFailFun); - napi_delete_reference(env, napiCompFun); - return nullptr; - } - - bool s = dsm->PartitionPublic(dsId); - if (s) { - CallBackSuccess(env, napiSuccFun, COMMON_NUM::ZERO, nullptr); - } else { - CallBackError(env, napiFailFun, "PartitionPublic fail", ERROR); - } - - CallComplete(env, napiCompFun); - napi_delete_reference(env, napiSuccFun); - napi_delete_reference(env, napiFailFun); - napi_delete_reference(env, napiCompFun); - return NVal::CreateUndefined(env).val_; -} - -napi_value DeviceSMExporter::PartitionPrivate(napi_env env, napi_callback_info info) -{ - NFuncArg funcArg(env, info); - if (!funcArg.InitArgs(NARG_CNT::ONE)) { - UniError(EINVAL).ThrowErr(env, "Number of arguments unmatched"); - return nullptr; - } - bool succ = false; - napi_ref napiSuccFun, napiCompFun, napiFailFun; - tie(succ, napiSuccFun, napiFailFun, napiCompFun) = - CommonFunc::GetCallbackHandles(env, funcArg[NARG_POS::FIRST]); - - unique_ptr deviceId = nullptr; - tie(succ, deviceId, ignore) = NVal(env, funcArg[NARG_POS::FIRST]).GetProp("diskId").ToUTF8String(); - - std::string dsId = (deviceId == nullptr) ? "" : deviceId.get(); - if (dsId == "") { - CallBackError(env, napiFailFun, "PartitionPrivate incoming parameter is null", NULL_ERROR); - CallComplete(env, napiCompFun); - napi_delete_reference(env, napiSuccFun); - napi_delete_reference(env, napiFailFun); - napi_delete_reference(env, napiCompFun); - return nullptr; - } - - bool s = dsm->PartitionPrivate(dsId); - if (s) { - CallBackSuccess(env, napiSuccFun, COMMON_NUM::ZERO, nullptr); - } else { - CallBackError(env, napiFailFun, "PartitionPrivate fail", ERROR); - } - - CallComplete(env, napiCompFun); - napi_delete_reference(env, napiSuccFun); - napi_delete_reference(env, napiFailFun); - napi_delete_reference(env, napiCompFun); - return NVal::CreateUndefined(env).val_; -} - -napi_value DeviceSMExporter::GetVolumes(napi_env env, napi_callback_info info) -{ - NFuncArg funcArg(env, info); - if (!funcArg.InitArgs(NARG_CNT::ONE)) { - UniError(EINVAL).ThrowErr(env, "Number of arguments unmatched"); - return nullptr; - } - bool succ = false; - napi_ref napiSuccFun, napiCompFun, napiFailFun; - tie(succ, napiSuccFun, napiFailFun, napiCompFun) = - CommonFunc::GetCallbackHandles(env, funcArg[NARG_POS::FIRST]); - - std::vector> infos; - bool ret = dsm->GetVolumes(infos); - if (ret) { - napi_value getvolumenapi = VolumesToNapi(env, infos); - - NVal objc = NVal::CreateObject(env); - objc.AddProp("volumeInfos", getvolumenapi); - CallBackSuccess(env, napiSuccFun, COMMON_NUM::ONE, objc.val_); - } else { - CallBackError(env, napiFailFun, "getvolume not exist", ERROR); - } - - CallComplete(env, napiCompFun); - napi_delete_reference(env, napiSuccFun); - napi_delete_reference(env, napiFailFun); - napi_delete_reference(env, napiCompFun); - return NVal::CreateUndefined(env).val_; -} - -napi_value DeviceSMExporter::GetDisks(napi_env env, napi_callback_info info) -{ - NFuncArg funcArg(env, info); - if (!funcArg.InitArgs(NARG_CNT::ONE)) { - UniError(EINVAL).ThrowErr(env, "Number of arguments unmatched"); - return nullptr; - } - bool succ = false; - napi_ref napiSuccFun, napiCompFun, napiFailFun; - tie(succ, napiSuccFun, napiFailFun, napiCompFun) = - CommonFunc::GetCallbackHandles(env, funcArg[NARG_POS::FIRST]); - - std::vector> infos; - bool ret = dsm->GetDisks(infos); - if (ret) { - napi_value diaknapi; - napi_create_array(env, &diaknapi); - ForeachDsmInfos(infos, env, diaknapi); - NVal objn = NVal::CreateObject(env); - objn.AddProp("diskInfos", diaknapi); - CallBackSuccess(env, napiSuccFun, COMMON_NUM::ONE, objn.val_); - } else { - CallBackError(env, napiFailFun, "disk not exist", ERROR); - } - - CallComplete(env, napiCompFun); - napi_delete_reference(env, napiSuccFun); - napi_delete_reference(env, napiFailFun); - napi_delete_reference(env, napiCompFun); - return NVal::CreateUndefined(env).val_; -} - -napi_value DeviceSMExporter::SetPrimaryStorageUuid(napi_env env, napi_callback_info info) -{ - NFuncArg funcArg(env, info); - if (!funcArg.InitArgs(NARG_CNT::ONE)) { - UniError(EINVAL).ThrowErr(env, "Number of arguments unmatched"); - return nullptr; - } - bool succ = false; - napi_ref napiSuccFun, napiCompFun, napiFailFun; - tie(succ, napiSuccFun, napiFailFun, napiCompFun) = - CommonFunc::GetCallbackHandles(env, funcArg[NARG_POS::FIRST]); - - unique_ptr deviceId = nullptr; - tie(succ, deviceId, ignore) = NVal(env, funcArg[NARG_POS::FIRST]).GetProp("volumeUuid").ToUTF8String(); - std::string vuId = (deviceId == nullptr) ? "" : deviceId.get(); - if (vuId == "") { - CallBackError(env, napiFailFun, "SetPrimaryStorageUuid incoming parameter is null", NULL_ERROR); - CallComplete(env, napiCompFun); - napi_delete_reference(env, napiSuccFun); - napi_delete_reference(env, napiFailFun); - napi_delete_reference(env, napiCompFun); - return nullptr; - } - - bool s = dsm->SetPrimaryStorageUuid(vuId); - if (s) { - CallBackSuccess(env, napiSuccFun, COMMON_NUM::ZERO, nullptr); - } else { - CallBackError(env, napiFailFun, "SetPrimaryStorageUuid fail", ERROR); - } - - CallComplete(env, napiCompFun); - napi_delete_reference(env, napiSuccFun); - napi_delete_reference(env, napiFailFun); - napi_delete_reference(env, napiCompFun); - return NVal::CreateUndefined(env).val_; -} - -napi_value DeviceSMExporter::FindVolumeById(napi_env env, napi_callback_info info) -{ - NFuncArg funcArg(env, info); - if (!funcArg.InitArgs(NARG_CNT::ONE)) { - UniError(EINVAL).ThrowErr(env, "Number of arguments unmatched"); - return nullptr; - } - bool succ = false; - napi_ref napiSuccFun, napiCompFun, napiFailFun; - tie(succ, napiSuccFun, napiFailFun, napiCompFun) = - CommonFunc::GetCallbackHandles(env, funcArg[NARG_POS::FIRST]); - - unique_ptr deviceId = nullptr; - tie(succ, deviceId, ignore) = NVal(env, funcArg[NARG_POS::FIRST]).GetProp("volId").ToUTF8String(); - - std::string mvId = (deviceId == nullptr) ? "" : deviceId.get(); - if (mvId == "") { - CallBackError(env, napiFailFun, "FindVolumeById incoming parameter is null", NULL_ERROR); - CallComplete(env, napiCompFun); - napi_delete_reference(env, napiSuccFun); - napi_delete_reference(env, napiFailFun); - napi_delete_reference(env, napiCompFun); - return nullptr; - } - - std::shared_ptr vol; - bool ret = dsm->FindVolumeById(vol, mvId); - if (ret) { - napi_value getvolumenapi; - napi_create_array(env, &getvolumenapi); - std::vector> infos; - dsm->GetVolumes(infos); - ForeachVomInfos(infos, env, getvolumenapi, userId); - NVal objc = NVal::CreateObject(env); - objc.AddProp("volumeInfos", getvolumenapi); - CallBackSuccess(env, napiSuccFun, COMMON_NUM::ONE, objc.val_); - } else { - CallBackError(env, napiFailFun, "FindVolumeById not exist", ERROR); - } - - CallComplete(env, napiCompFun); - napi_delete_reference(env, napiSuccFun); - napi_delete_reference(env, napiFailFun); - napi_delete_reference(env, napiCompFun); - return NVal::CreateUndefined(env).val_; -} - -napi_value DeviceSMExporter::FindVolumeByUuid(napi_env env, napi_callback_info info) -{ - NFuncArg funcArg(env, info); - if (!funcArg.InitArgs(NARG_CNT::ONE)) { - UniError(EINVAL).ThrowErr(env, "Number of arguments unmatched"); - return nullptr; - } - bool succ = false; - napi_ref napiSuccFun, napiCompFun, napiFailFun; - tie(succ, napiSuccFun, napiFailFun, napiCompFun) = - CommonFunc::GetCallbackHandles(env, funcArg[NARG_POS::FIRST]); - - unique_ptr deviceId = nullptr; - tie(succ, deviceId, ignore) = NVal(env, funcArg[NARG_POS::FIRST]).GetProp("volumeUuid").ToUTF8String(); - - std::string mvmId = (deviceId == nullptr) ? "" : deviceId.get(); - if (mvmId == "") { - CallBackError(env, napiFailFun, "FindVolumeByUuid incoming parameter is null", NULL_ERROR); - CallComplete(env, napiCompFun); - napi_delete_reference(env, napiSuccFun); - napi_delete_reference(env, napiFailFun); - napi_delete_reference(env, napiCompFun); - return nullptr; - } - - std::shared_ptr vol; - if (dsm->FindVolumeByUuid(vol, mvmId)) { - napi_value getvolumenapi; - napi_create_array(env, &getvolumenapi); - std::vector> infos; - dsm->GetVolumes(infos); - ForeachVomInfos(infos, env, getvolumenapi, userId); - NVal objc = NVal::CreateObject(env); - objc.AddProp("volumeInfos", getvolumenapi); - CallBackSuccess(env, napiSuccFun, COMMON_NUM::ONE, objc.val_); - } else { - CallBackError(env, napiFailFun, "FindVolumeByUuid not exist", ERROR); - } - - CallComplete(env, napiCompFun); - napi_delete_reference(env, napiSuccFun); - napi_delete_reference(env, napiFailFun); - napi_delete_reference(env, napiCompFun); - return NVal::CreateUndefined(env).val_; -} - -napi_value DeviceSMExporter::FindDiskById(napi_env env, napi_callback_info info) -{ - NFuncArg funcArg(env, info); - if (!funcArg.InitArgs(NARG_CNT::ONE)) { - UniError(EINVAL).ThrowErr(env, "Number of arguments unmatched"); - return nullptr; - } - bool succ = false; - napi_ref napiSuccFun, napiCompFun, napiFailFun; - tie(succ, napiSuccFun, napiFailFun, napiCompFun) = - CommonFunc::GetCallbackHandles(env, funcArg[NARG_POS::FIRST]); - - unique_ptr deviceId = nullptr; - tie(succ, deviceId, ignore) = NVal(env, funcArg[NARG_POS::FIRST]).GetProp("diskId").ToUTF8String(); - - std::string dsId = (deviceId == nullptr) ? "" : deviceId.get(); - if (dsId == "") { - CallBackError(env, napiFailFun, "FindDiskById incoming parameter is null", NULL_ERROR); - CallComplete(env, napiCompFun); - napi_delete_reference(env, napiSuccFun); - napi_delete_reference(env, napiFailFun); - napi_delete_reference(env, napiCompFun); - return nullptr; - } - - std::shared_ptr disk; - if (dsm->FindDiskById(disk, dsId)) { - napi_value diaknapi; - napi_create_array(env, &diaknapi); - std::vector> infos; - dsm->GetDisks(infos); - ForeachDsmInfos(infos, env, diaknapi); - NVal objn = NVal::CreateObject(env); - objn.AddProp("diskInfos", diaknapi); - CallBackSuccess(env, napiSuccFun, COMMON_NUM::ONE, objn.val_); - } else { - CallBackError(env, napiFailFun, "FindDiskById not exist", ERROR); - } - - CallComplete(env, napiCompFun); - napi_delete_reference(env, napiSuccFun); - napi_delete_reference(env, napiFailFun); - napi_delete_reference(env, napiCompFun); - return NVal::CreateUndefined(env).val_; -} - -napi_value DeviceSMExporter::GetPrimaryStorageUuid(napi_env env, napi_callback_info info) -{ - NFuncArg funcArg(env, info); - if (!funcArg.InitArgs(NARG_CNT::ONE)) { - UniError(EINVAL).ThrowErr(env, "Number of arguments unmatched"); - return nullptr; - } - bool succ = false; - napi_ref napiSuccFun, napiCompFun, napiFailFun; - tie(succ, napiSuccFun, napiFailFun, napiCompFun) = - CommonFunc::GetCallbackHandles(env, funcArg[NARG_POS::FIRST]); - - std::string primaryUuid; - bool s = dsm->GetPrimaryStorageUuid(primaryUuid); - if (s) { - NVal obj = NVal::CreateObject(env); - obj.AddProp("primaryUuid", NVal::CreateUTF8String(env, primaryUuid).val_); - CallBackSuccess(env, napiSuccFun, COMMON_NUM::ONE, obj.val_); - } else { - CallBackError(env, napiFailFun, "GetPrimaryStorageUuid return value error", ERROR); - } - - CallComplete(env, napiCompFun); - napi_delete_reference(env, napiSuccFun); - napi_delete_reference(env, napiFailFun); - napi_delete_reference(env, napiCompFun); - return NVal::CreateUndefined(env).val_; -} - -napi_value DeviceSMExporter::FindPrivateForEmulate(napi_env env, napi_callback_info info) -{ - NFuncArg funcArg(env, info); - if (!funcArg.InitArgs(NARG_CNT::ONE)) { - UniError(EINVAL).ThrowErr(env, "Number of arguments unmatched"); - return nullptr; - } - bool succ = false; - napi_ref napiSuccFun, napiCompFun, napiFailFun; - tie(succ, napiSuccFun, napiFailFun, napiCompFun) = - CommonFunc::GetCallbackHandles(env, funcArg[NARG_POS::FIRST]); - - std::shared_ptr emuVol = std::make_shared(); - - NVal a = NVal(env, funcArg[NARG_POS::FIRST]).GetProp("emuVol"); - if (a.TypeIs(napi_object)) { - } else if (a.TypeIs(napi_undefined)) { - } else if (a.TypeIs(napi_null)) { - } - - PriVolToEmuVol(env, a, emuVol); - std::shared_ptr priVol; - bool ret = dsm->FindPrivateForEmulate(priVol, emuVol); - if (ret) { - napi_value getvolumenapi; - napi_create_array(env, &getvolumenapi); - std::vector> infos; - dsm->GetVolumes(infos); - ForeachVomInfos(infos, env, getvolumenapi, userId); - NVal objc = NVal::CreateObject(env); - objc.AddProp("volumeInfos", getvolumenapi); - CallBackSuccess(env, napiSuccFun, COMMON_NUM::ONE, objc.val_); - } else { - CallBackError(env, napiFailFun, "FindPrivateForEmulate not exist", ERROR); - } - - CallComplete(env, napiCompFun); - napi_delete_reference(env, napiSuccFun); - napi_delete_reference(env, napiFailFun); - napi_delete_reference(env, napiCompFun); - return NVal::CreateUndefined(env).val_; -} - -napi_value DeviceSMExporter::FindEmulateForPrivate(napi_env env, napi_callback_info info) -{ - NFuncArg funcArg(env, info); - if (!funcArg.InitArgs(NARG_CNT::ONE)) { - UniError(EINVAL).ThrowErr(env, "Number of arguments unmatched"); - return nullptr; - } - bool succ = false; - napi_ref napiSuccFun, napiCompFun, napiFailFun; - tie(succ, napiSuccFun, napiFailFun, napiCompFun) = - CommonFunc::GetCallbackHandles(env, funcArg[NARG_POS::FIRST]); - - std::shared_ptr priVol = std::make_shared(); - - NVal a = NVal(env, funcArg[NARG_POS::FIRST]).GetProp("priVol"); - if (a.TypeIs(napi_object)) { - } else if (a.TypeIs(napi_undefined)) { - } else if (a.TypeIs(napi_null)) { - } - - EmuVolToPriVol(env, a, priVol); - std::shared_ptr emuVol; - bool ret = dsm->FindEmulateForPrivate(emuVol, priVol); - if (ret) { - napi_value getvolumenapi; - napi_create_array(env, &getvolumenapi); - std::vector> infos; - dsm->GetVolumes(infos); - ForeachVomInfos(infos, env, getvolumenapi, userId); - NVal objc = NVal::CreateObject(env); - objc.AddProp("volumeInfos", getvolumenapi); - CallBackSuccess(env, napiSuccFun, COMMON_NUM::ONE, objc.val_); - } else { - CallBackError(env, napiFailFun, "FindEmulateForPrivate not exist", ERROR); - } - - CallComplete(env, napiCompFun); - napi_delete_reference(env, napiSuccFun); - napi_delete_reference(env, napiFailFun); - napi_delete_reference(env, napiCompFun); - return NVal::CreateUndefined(env).val_; -} - -napi_value DeviceSMExporter::GetBestVolumeDescription(napi_env env, napi_callback_info info) -{ - NFuncArg funcArg(env, info); - if (!funcArg.InitArgs(NARG_CNT::ONE)) { - UniError(EINVAL).ThrowErr(env, "Number of arguments unmatched"); - return nullptr; - } - bool succ = false; - napi_ref napiSuccFun, napiCompFun, napiFailFun; - tie(succ, napiSuccFun, napiFailFun, napiCompFun) = - CommonFunc::GetCallbackHandles(env, funcArg[NARG_POS::FIRST]); - - std::shared_ptr vol = std::make_shared(); - - NVal a = NVal(env, funcArg[NARG_POS::FIRST]).GetProp("vol"); - if (a.TypeIs(napi_object)) { - } else if (a.TypeIs(napi_undefined)) { - } else if (a.TypeIs(napi_null)) { - } - - VolToDesCription(env, a, vol); - - std::string desCription; - bool s = dsm->GetBestVolumeDescription(vol, desCription); - if (s) { - NVal obj = NVal::CreateObject(env); - obj.AddProp("desCription", NVal::CreateUTF8String(env, vol->GetDescription()).val_); - CallBackSuccess(env, napiSuccFun, COMMON_NUM::ONE, obj.val_); - } else { - CallBackError(env, napiFailFun, "GetBestVolumeDescription return value error", ERROR); - } - - CallComplete(env, napiCompFun); - napi_delete_reference(env, napiSuccFun); - napi_delete_reference(env, napiFailFun); - napi_delete_reference(env, napiCompFun); - return NVal::CreateUndefined(env).val_; -} - -napi_value DeviceSMExporter::GetWritableVolumes(napi_env env, napi_callback_info info) -{ - NFuncArg funcArg(env, info); - if (!funcArg.InitArgs(NARG_CNT::ONE)) { - UniError(EINVAL).ThrowErr(env, "Number of arguments unmatched"); - return nullptr; - } - bool succ = false; - napi_ref napiSuccFun, napiCompFun, napiFailFun; - tie(succ, napiSuccFun, napiFailFun, napiCompFun) = - CommonFunc::GetCallbackHandles(env, funcArg[NARG_POS::FIRST]); - - std::vector> infos; - bool ret = dsm->GetWritableVolumes(infos); - if (ret) { - napi_value getvolumenapi; - napi_create_array(env, &getvolumenapi); - ForeachVomInfos(infos, env, getvolumenapi, userId); - NVal objc = NVal::CreateObject(env); - objc.AddProp("volumeInfos", getvolumenapi); - CallBackSuccess(env, napiSuccFun, COMMON_NUM::ONE, objc.val_); - } else { - CallBackError(env, napiFailFun, "GetWritableVolumes not exist", ERROR); - } - - CallComplete(env, napiCompFun); - napi_delete_reference(env, napiSuccFun); - napi_delete_reference(env, napiFailFun); - napi_delete_reference(env, napiCompFun); - return NVal::CreateUndefined(env).val_; -} - -bool DeviceSMExporter::Export() -{ - return exports_.AddProp({ - NVal::DeclareNapiFunction("mount", Mount), - NVal::DeclareNapiFunction("unMount", UnMount), - NVal::DeclareNapiFunction("format", Format), - NVal::DeclareNapiFunction("partitionPublic", PartitionPublic), - NVal::DeclareNapiFunction("partitionPrivate", PartitionPrivate), - NVal::DeclareNapiFunction("getVolumes", GetVolumes), - NVal::DeclareNapiFunction("getDisks", GetDisks), - NVal::DeclareNapiFunction("setPrimaryStorageUuid", SetPrimaryStorageUuid), - NVal::DeclareNapiFunction("findVolumeById", FindVolumeById), - NVal::DeclareNapiFunction("findVolumeByUuid", FindVolumeByUuid), - NVal::DeclareNapiFunction("findDiskById", FindDiskById), - NVal::DeclareNapiFunction("getPrimaryStorageUuid", GetPrimaryStorageUuid), - NVal::DeclareNapiFunction("findPrivateForEmulate", FindPrivateForEmulate), - NVal::DeclareNapiFunction("findEmulateForPrivate", FindEmulateForPrivate), - NVal::DeclareNapiFunction("getWritableVolumes", GetWritableVolumes), - NVal::DeclareNapiFunction("getBestVolumeDescription", GetBestVolumeDescription), - NVal::DeclareNapiFunction("isEncrypted", IsEncrypted), - }); -} - -string DeviceSMExporter::GetClassName() -{ - return DeviceSMExporter::className_; -} - -DeviceSMExporter::DeviceSMExporter(napi_env env, napi_value exports) - : NExporter(env, exports) -{} - -DeviceSMExporter::~DeviceSMExporter() {} -} // namespace ModuleDSMExpoter -} // namespace DistributedFS -} // namespace OHOS diff --git a/interfaces/kits/napi/device_storage_manager/device_sm_exporter.h b/interfaces/kits/napi/device_storage_manager/device_sm_exporter.h deleted file mode 100644 index 457931d..0000000 --- a/interfaces/kits/napi/device_storage_manager/device_sm_exporter.h +++ /dev/null @@ -1,56 +0,0 @@ -/* - * Copyright (c) 2021 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -#ifndef STORAGE_DISKMGR_INTERFACE_KITS_NAPI_DSM_DEVICE_SM_EXPORTER_H -#define STORAGE_DISKMGR_INTERFACE_KITS_NAPI_DSM_DEVICE_SM_EXPORTER_H - -#pragma once - -#include "../common/napi/n_exporter.h" - -namespace OHOS { -namespace DistributedFS { -namespace ModuleDSMExpoter { -class DeviceSMExporter final : public NExporter { -public: - inline static const std::string className_ = "DeviceSMgr"; - static napi_value Mount(napi_env env, napi_callback_info info); - static napi_value UnMount(napi_env env, napi_callback_info info); - static napi_value Format(napi_env env, napi_callback_info info); - static napi_value PartitionPublic(napi_env env, napi_callback_info info); - static napi_value PartitionPrivate(napi_env env, napi_callback_info info); - static napi_value GetVolumes(napi_env env, napi_callback_info info); - static napi_value GetDisks(napi_env env, napi_callback_info info); - static napi_value SetPrimaryStorageUuid(napi_env env, napi_callback_info info); - static napi_value FindVolumeById(napi_env env, napi_callback_info info); - static napi_value FindVolumeByUuid(napi_env env, napi_callback_info info); - static napi_value FindDiskById(napi_env env, napi_callback_info info); - static napi_value GetPrimaryStorageUuid(napi_env env, napi_callback_info info); - static napi_value FindPrivateForEmulate(napi_env env, napi_callback_info info); - static napi_value FindEmulateForPrivate(napi_env env, napi_callback_info info); - static napi_value GetWritableVolumes(napi_env env, napi_callback_info info); - static napi_value GetBestVolumeDescription(napi_env env, napi_callback_info info); - static napi_value IsEncrypted(napi_env env, napi_callback_info info); - bool Export() override; - - std::string GetClassName() override; - - DeviceSMExporter(napi_env env, napi_value exports); - ~DeviceSMExporter() override; -}; -} // namespace ModuleDSMExpoter -} // namespace DistributedFS -} // namespace OHOS - -#endif // STORAGE_DISKMGR_INTERFACE_KITS_NAPI_DSM_DEVICE_SM_EXPORTER_H \ No newline at end of file diff --git a/interfaces/kits/napi/device_storage_manager/module.cpp b/interfaces/kits/napi/device_storage_manager/module.cpp deleted file mode 100644 index 09c5874..0000000 --- a/interfaces/kits/napi/device_storage_manager/module.cpp +++ /dev/null @@ -1,47 +0,0 @@ -/* - * Copyright (c) 2021 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -#include "module.h" - -#include -#include - -#include "../common/log.h" -#include "device_sm_exporter.h" - -using namespace std; - -namespace OHOS { -namespace DistributedFS { -namespace ModuleDSMExpoter { -static napi_value Export(napi_env env, napi_value exports) -{ - std::vector> products; - products.emplace_back(make_unique(env, exports)); - - for (auto && product : products) { - if (!product->Export()) { - HILOGE("INNER BUG. Failed to export class %{public}s for module file", product->GetClassName().c_str()); - return nullptr; - } else { - HILOGE("Class %{public}s for module file has been exported", product->GetClassName().c_str()); - } - } - return exports; -} - -NAPI_MODULE(devicesmgr, Export) -} // namespace ModuleFile -} // namespace DistributedFS -} // namespace OHOS \ No newline at end of file diff --git a/interfaces/kits/napi/device_storage_manager/module.h b/interfaces/kits/napi/device_storage_manager/module.h deleted file mode 100644 index 20bb9f5..0000000 --- a/interfaces/kits/napi/device_storage_manager/module.h +++ /dev/null @@ -1,18 +0,0 @@ -/* - * Copyright (c) 2021 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -#ifndef STORAGE_DISKMGR_INTERFACE_KITS_NAPI_DSM_MODULE_H -#define STORAGE_DISKMGR_INTERFACE_KITS_NAPI_DSM_MODULE_H - -#endif // STORAGE_DISKMGR_INTERFACE_KITS_NAPI_DSM_MODULE_H \ No newline at end of file diff --git a/interfaces/kits/napi/file_picker_service/file_picker_exporter.cpp b/interfaces/kits/napi/file_picker_service/file_picker_exporter.cpp deleted file mode 100644 index 6d5c494..0000000 --- a/interfaces/kits/napi/file_picker_service/file_picker_exporter.cpp +++ /dev/null @@ -1,478 +0,0 @@ -/* - * Copyright (c) 2021 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -#include "file_picker_exporter.h" - -#include -#include -#include -#include - -#include "../common/ability_helper.h" -#include "../common/common_func.h" -#include "../common/napi/n_class.h" -#include "../common/napi/n_func_arg.h" -#include "../common/napi/n_val.h" -#include "../common/uni_error.h" -#include "file_info.h" -#include "root_info.h" -#include "storage_ability.h" -#include "uri.h" - -using Uri = OHOS::Uri; -using namespace std; -namespace OHOS { -namespace DistributedFS { -namespace ModuleFPExpoter { -enum COMMON_NUM { - ZERO = 0, - ONE = 1, - TWO = 2, - THREE = 3, -}; - -enum ERROR_CODE { - SUCCESS_CODE = 200, - OTHER_ARGUMENT_ERROR = 202, - FILE_IO_ERROR = 300, - FILE_PATH_ERROR = 301, - URI_PARAMER_ERROR = 302, -}; - -void CallBackSuccess(napi_env env, napi_ref successFuncRef, int32_t count, napi_value obj) -{ - napi_value results = nullptr; - napi_value successFunc = nullptr; - napi_value global = nullptr; - napi_get_global(env, &global); - napi_get_reference_value(env, successFuncRef, &successFunc); - if (successFunc == nullptr) { - return; - } - napi_call_function(env, global, successFunc, count, &obj, &results); -} - -void CallBackError(napi_env env, napi_ref failFuncRef, string errorProp, int errorCode) -{ - napi_value argvFail[2] = { 0 }; - napi_value results = nullptr; - napi_value failFunc = nullptr; - napi_value global = nullptr; - napi_get_global(env, &global); - argvFail[0] = NVal::CreateUTF8String(env, errorProp).val_; - argvFail[1] = NVal::CreateInt32(env, errorCode).val_; - napi_get_reference_value(env, failFuncRef, &failFunc); - if (failFunc == nullptr) { - return; - } - napi_call_function(env, global, failFunc, COMMON_NUM::TWO, argvFail, &results); -} - -void CallComplete(napi_env env, napi_ref completeFuncRef) -{ - napi_value completeFunc = nullptr; - napi_value results = nullptr; - napi_value global = nullptr; - napi_get_global(env, &global); - napi_get_reference_value(env, completeFuncRef, &completeFunc); - if (completeFunc == nullptr) { - return; - } - napi_call_function(env, global, completeFunc, COMMON_NUM::ZERO, nullptr, &results); -} - -void SaveFileExec(napi_env env, void *data) -{ - auto *asyncInfo = (SaveFileAsyncInfo *)data; - unique_ptr point; - vector result; - Uri uriObj(asyncInfo->dstPath); - asyncInfo->err = point->SaveFiles(uriObj, asyncInfo->srcPath, result); - asyncInfo->saveFileList.assign(result.begin(), result.end()); -} - -void SaveFileComp(napi_env env, napi_status status, void *data) -{ - auto *asyncInfo = (SaveFileAsyncInfo *)data; - if (asyncInfo->err == ERROR_CODE::SUCCESS_CODE) { - napi_value saveListNapi; - napi_create_array(env, &saveListNapi); - int32_t i = 0; - for (auto saveInfo : asyncInfo->saveFileList) { - NVal objt = NVal::CreateObject(env); - objt.AddProp("srcUri", NVal::CreateUTF8String(env, saveInfo.srcUri).val_); - objt.AddProp("dstUri", NVal::CreateUTF8String(env, saveInfo.dstUri).val_); - objt.AddProp("status", NVal::CreateBool(env, saveInfo.status).val_); - - napi_set_property(env, saveListNapi, NVal::CreateInt32(env, i).val_, objt.val_); - i = i + 1; - } - NVal objn = NVal::CreateObject(env); - objn.AddProp("saveFileList", saveListNapi); - CallBackSuccess(env, asyncInfo->callback[COMMON_NUM::ZERO], COMMON_NUM::ONE, objn.val_); - } else { - CallBackError(env, asyncInfo->callback[COMMON_NUM::ONE], "SaveFile fail", asyncInfo->err); - } - CallComplete(env, asyncInfo->callback[COMMON_NUM::TWO]); - napi_delete_reference(env, asyncInfo->callback[COMMON_NUM::ZERO]); - napi_delete_reference(env, asyncInfo->callback[COMMON_NUM::ONE]); - napi_delete_reference(env, asyncInfo->callback[COMMON_NUM::TWO]); - napi_delete_async_work(env, asyncInfo->asyncWork); - delete asyncInfo; -} - -void SearchFileExec(napi_env env, void *data) -{ - auto asyncInfo = (SearchFileAsyncInfo *)data; - unique_ptr point; - vector result; - Uri uriObj(asyncInfo->path); - asyncInfo->err = point->SearchFiles(uriObj, asyncInfo->name, result); - asyncInfo->fileInfoList.assign(result.begin(), result.end()); -} - -void SearchFileComp(napi_env env, napi_status status, void *data) -{ - auto asyncInfo = (SearchFileAsyncInfo *)data; - if (asyncInfo->err == ERROR_CODE::SUCCESS_CODE) { - napi_value fileListNapi; - napi_create_array(env, &fileListNapi); - int32_t i = 0; - for (auto fileInfo : asyncInfo->fileInfoList) { - NVal objt = NVal::CreateObject(env); - objt.AddProp("uri", NVal::CreateUTF8String(env, fileInfo.fileUri).val_); - objt.AddProp("name", NVal::CreateUTF8String(env, fileInfo.fileName).val_); - - objt.AddProp("lastModifiedTime", NVal::CreateInt64(env, fileInfo.lastUseTime).val_); - objt.AddProp("length", NVal::CreateInt32(env, fileInfo.fileSize).val_); - objt.AddProp("num", NVal::CreateInt32(env, fileInfo.dirNum).val_); - string type = (fileInfo.typeDir == 1) ? "dir" : "file"; - objt.AddProp("type", NVal::CreateUTF8String(env, type).val_); - objt.AddProp("suffix", NVal::CreateUTF8String(env, fileInfo.mimeType).val_); - - napi_set_property(env, fileListNapi, NVal::CreateInt32(env, i).val_, objt.val_); - i = i + 1; - } - NVal objn = NVal::CreateObject(env); - objn.AddProp("fileList", fileListNapi); - CallBackSuccess(env, asyncInfo->callback[COMMON_NUM::ZERO], COMMON_NUM::ONE, objn.val_); - } else { - CallBackError(env, asyncInfo->callback[COMMON_NUM::ONE], "SearchFile fail", asyncInfo->err); - } - CallComplete(env, asyncInfo->callback[COMMON_NUM::TWO]); - napi_delete_reference(env, asyncInfo->callback[COMMON_NUM::ZERO]); - napi_delete_reference(env, asyncInfo->callback[COMMON_NUM::ONE]); - napi_delete_reference(env, asyncInfo->callback[COMMON_NUM::TWO]); - napi_delete_async_work(env, asyncInfo->asyncWork); - delete asyncInfo; -} - -void ListExec(napi_env env, void *data) -{ - auto asyncInfo = (ListAsyncInfo *)data; - unique_ptr point; - vector result; - Uri uriObj(asyncInfo->path); - asyncInfo->err = point->QueryFiles(uriObj, result); - asyncInfo->fileInfoList.assign(result.begin(), result.end()); -} - -void ListComp(napi_env env, napi_status status, void *data) -{ - auto asyncInfo = (ListAsyncInfo *)data; - if (asyncInfo->err == ERROR_CODE::SUCCESS_CODE) { - napi_value fileListNapi; - napi_create_array(env, &fileListNapi); - int32_t i = 0; - for (auto fileInfo : asyncInfo->fileInfoList) { - NVal objt = NVal::CreateObject(env); - objt.AddProp("uri", NVal::CreateUTF8String(env, fileInfo.fileUri).val_); - objt.AddProp("name", NVal::CreateUTF8String(env, fileInfo.fileName).val_); - - objt.AddProp("lastModifiedTime", NVal::CreateInt64(env, fileInfo.lastUseTime).val_); - objt.AddProp("length", NVal::CreateInt32(env, fileInfo.fileSize).val_); - objt.AddProp("num", NVal::CreateInt32(env, fileInfo.dirNum).val_); - string type = (fileInfo.typeDir == 1) ? "dir" : "file"; - objt.AddProp("type", NVal::CreateUTF8String(env, type).val_); - objt.AddProp("suffix", NVal::CreateUTF8String(env, fileInfo.mimeType).val_); - - napi_set_property(env, fileListNapi, NVal::CreateInt32(env, i).val_, objt.val_); - i = i + 1; - } - NVal objn = NVal::CreateObject(env); - objn.AddProp("fileList", fileListNapi); - CallBackSuccess(env, asyncInfo->callback[COMMON_NUM::ZERO], COMMON_NUM::ONE, objn.val_); - } else { - CallBackError(env, asyncInfo->callback[COMMON_NUM::ONE], "List fail", asyncInfo->err); - } - CallComplete(env, asyncInfo->callback[COMMON_NUM::TWO]); - napi_delete_reference(env, asyncInfo->callback[COMMON_NUM::ZERO]); - napi_delete_reference(env, asyncInfo->callback[COMMON_NUM::ONE]); - napi_delete_reference(env, asyncInfo->callback[COMMON_NUM::TWO]); - napi_delete_async_work(env, asyncInfo->asyncWork); - delete asyncInfo; -} - -void GetDeviceInfoExec(napi_env env, void *data) -{ - auto asyncInfo = (GetDeviceAsyncInfo *)data; - unique_ptr point; - vector result; - asyncInfo->err = point->QueryDeviceInfo(result); - asyncInfo->deviceInfoList.assign(result.begin(), result.end()); -} - -void GetDeviceInfoComp(napi_env env, napi_status status, void *data) -{ - auto asyncInfo = (GetDeviceAsyncInfo *)data; - if (asyncInfo->err == ERROR_CODE::SUCCESS_CODE) { - napi_value deviceListNapi; - napi_create_array(env, &deviceListNapi); - int32_t i = 0; - for (auto deviceInfo : asyncInfo->deviceInfoList) { - NVal objt = NVal::CreateObject(env); - objt.AddProp("uri", NVal::CreateUTF8String(env, deviceInfo.path).val_); - objt.AddProp("deviceID", NVal::CreateUTF8String(env, deviceInfo.deviceId).val_); - - objt.AddProp("mountID", NVal::CreateInt32(env, deviceInfo.mountFlags).val_); - objt.AddProp("diskID", NVal::CreateUTF8String(env, deviceInfo.diskId).val_); - - napi_set_property(env, deviceListNapi, NVal::CreateInt32(env, i).val_, objt.val_); - i = i + 1; - } - NVal objn = NVal::CreateObject(env); - objn.AddProp("deviceList", deviceListNapi); - CallBackSuccess(env, asyncInfo->callback[COMMON_NUM::ZERO], COMMON_NUM::ONE, objn.val_); - } else { - CallBackError(env, asyncInfo->callback[COMMON_NUM::ONE], "GetDeviceInfo fail", asyncInfo->err); - } - CallComplete(env, asyncInfo->callback[COMMON_NUM::TWO]); - napi_delete_reference(env, asyncInfo->callback[COMMON_NUM::ZERO]); - napi_delete_reference(env, asyncInfo->callback[COMMON_NUM::ONE]); - napi_delete_reference(env, asyncInfo->callback[COMMON_NUM::TWO]); - napi_delete_async_work(env, asyncInfo->asyncWork); - delete asyncInfo; -} - -napi_value FilePickerExporter::Mkdir(napi_env env, napi_callback_info info) -{ - NFuncArg funcArg(env, info); - if (!funcArg.InitArgs(NARG_CNT::ONE)) { - UniError(EINVAL).ThrowErr(env, "Number of arguments unmatched"); - return nullptr; - } - - auto *asyncInfo = new MkdirAsyncInfo; - bool succ = false; - tie(succ, asyncInfo->callback[COMMON_NUM::ZERO], asyncInfo->callback[COMMON_NUM::ONE], - asyncInfo->callback[COMMON_NUM::TWO]) = CommonFunc::GetCallbackHandles(env, funcArg[NARG_POS::FIRST]); - - unique_ptr uri = nullptr; - tie(succ, uri, ignore) = NVal(env, funcArg[NARG_POS::FIRST]).GetProp("uri").ToUTF8String(); - - asyncInfo->path = (uri == nullptr) ? "" : uri.get(); - - if (asyncInfo->path == "") { - CallBackError(env, asyncInfo->callback[COMMON_NUM::ONE], "uri cannot be empty", - ERROR_CODE::URI_PARAMER_ERROR); - delete asyncInfo; - return nullptr; - } - - napi_create_async_work( - env, nullptr, NVal::CreateUTF8String(env, "Mkdir").val_, - [](napi_env env, void *data) { - auto *asyncInfo = (MkdirAsyncInfo *)data; - unique_ptr point; - Uri uriObj(asyncInfo->path); - asyncInfo->err = point->CreateDir(uriObj); - }, - [](napi_env env, napi_status status, void *data) { - auto *asyncInfo = (MkdirAsyncInfo *)data; - if (asyncInfo->err == ERROR_CODE::SUCCESS_CODE) { - CallBackSuccess(env, asyncInfo->callback[COMMON_NUM::ZERO], 0, nullptr); - } else { - CallBackError(env, asyncInfo->callback[COMMON_NUM::ONE], "Mkdir fail", asyncInfo->err); - } - CallComplete(env, asyncInfo->callback[COMMON_NUM::TWO]); - napi_delete_reference(env, asyncInfo->callback[COMMON_NUM::ZERO]); - napi_delete_reference(env, asyncInfo->callback[COMMON_NUM::ONE]); - napi_delete_reference(env, asyncInfo->callback[COMMON_NUM::TWO]); - napi_delete_async_work(env, asyncInfo->asyncWork); - delete asyncInfo; - }, - (void *)asyncInfo, &asyncInfo->asyncWork); - napi_queue_async_work(env, asyncInfo->asyncWork); - - return NVal::CreateUndefined(env).val_; -} - -napi_value FilePickerExporter::SaveFile(napi_env env, napi_callback_info info) -{ - NFuncArg funcArg(env, info); - if (!funcArg.InitArgs(NARG_CNT::ONE)) { - UniError(EINVAL).ThrowErr(env, "Number of arguments unmatched"); - return nullptr; - } - - auto *asyncInfo = new SaveFileAsyncInfo; - - bool succ = false; - tie(succ, asyncInfo->callback[COMMON_NUM::ZERO], asyncInfo->callback[COMMON_NUM::ONE], - asyncInfo->callback[COMMON_NUM::TWO]) = CommonFunc::GetCallbackHandles(env, funcArg[NARG_POS::FIRST]); - - unique_ptr dstUri = nullptr; - tie(succ, dstUri, ignore) = NVal(env, funcArg[NARG_POS::FIRST]).GetProp("dstUri").ToUTF8String(); - - uint32_t srcLen = 0; - vector srcPath; - NVal srcNapi = NVal(env, funcArg[NARG_POS::FIRST]).GetProp("srcUri"); - napi_get_array_length(env, srcNapi.val_, &srcLen); - for (uint32_t i = 0; i < srcLen; ++i) { - napi_value srcElementNapi; - unique_ptr srcElement = nullptr; - napi_get_element(env, srcNapi.val_, i, &srcElementNapi); - tie(succ, srcElement, ignore) = NVal(env, srcElementNapi).ToUTF8String(); - string path = (srcElement == nullptr) ? "" : srcElement.get(); - srcPath.emplace_back(path); - } - - asyncInfo->srcPath.assign(srcPath.begin(), srcPath.end()); - asyncInfo->dstPath = (dstUri == nullptr) ? "" : dstUri.get(); - asyncInfo->srcLen = srcLen; - - if (asyncInfo->dstPath == "" || asyncInfo->srcPath.empty()) { - CallBackError(env, asyncInfo->callback[COMMON_NUM::ONE], "dstUri or srcUri cannot be empty", - ERROR_CODE::URI_PARAMER_ERROR); - delete asyncInfo; - return nullptr; - } - - napi_create_async_work(env, nullptr, NVal::CreateUTF8String(env, "SaveFile").val_, SaveFileExec, - SaveFileComp, (void *)asyncInfo, &asyncInfo->asyncWork); - napi_queue_async_work(env, asyncInfo->asyncWork); - - return NVal::CreateUndefined(env).val_; -} - -napi_value FilePickerExporter::SearchFile(napi_env env, napi_callback_info info) -{ - NFuncArg funcArg(env, info); - if (!funcArg.InitArgs(NARG_CNT::ONE)) { - UniError(EINVAL).ThrowErr(env, "Number of arguments unmatched"); - return nullptr; - } - - auto *asyncInfo = new SearchFileAsyncInfo; - bool succ = false; - tie(succ, asyncInfo->callback[COMMON_NUM::ZERO], asyncInfo->callback[COMMON_NUM::ONE], - asyncInfo->callback[COMMON_NUM::TWO]) = CommonFunc::GetCallbackHandles(env, funcArg[NARG_POS::FIRST]); - - unique_ptr uri = nullptr; - tie(succ, uri, ignore) = NVal(env, funcArg[NARG_POS::FIRST]).GetProp("uri").ToUTF8String(); - - unique_ptr name = nullptr; - tie(succ, name, ignore) = NVal(env, funcArg[NARG_POS::FIRST]).GetProp("name").ToUTF8String(); - - asyncInfo->path = (uri == nullptr) ? "" : uri.get(); - asyncInfo->name = (name == nullptr) ? "" : name.get(); - - if (asyncInfo->path == "") { - CallBackError(env, asyncInfo->callback[COMMON_NUM::ONE], "uri cannot be empty", - ERROR_CODE::URI_PARAMER_ERROR); - delete asyncInfo; - return nullptr; - } - - napi_create_async_work(env, nullptr, NVal::CreateUTF8String(env, "SearchFile").val_, SearchFileExec, - SearchFileComp, (void *)asyncInfo, &asyncInfo->asyncWork); - napi_queue_async_work(env, asyncInfo->asyncWork); - - return NVal::CreateUndefined(env).val_; -} - -napi_value FilePickerExporter::List(napi_env env, napi_callback_info info) -{ - NFuncArg funcArg(env, info); - if (!funcArg.InitArgs(NARG_CNT::ONE)) { - UniError(EINVAL).ThrowErr(env, "Number of arguments unmatched"); - return nullptr; - } - - auto *asyncInfo = new ListAsyncInfo; - - bool succ = false; - tie(succ, asyncInfo->callback[COMMON_NUM::ZERO], asyncInfo->callback[COMMON_NUM::ONE], - asyncInfo->callback[COMMON_NUM::TWO]) = CommonFunc::GetCallbackHandles(env, funcArg[NARG_POS::FIRST]); - - unique_ptr uri = nullptr; - tie(succ, uri, ignore) = NVal(env, funcArg[NARG_POS::FIRST]).GetProp("uri").ToUTF8String(); - - asyncInfo->path = (uri == nullptr) ? "" : uri.get(); - if (asyncInfo->path == "") { - CallBackError(env, asyncInfo->callback[COMMON_NUM::ONE], "uri cannot be empty", - ERROR_CODE::URI_PARAMER_ERROR); - delete asyncInfo; - return nullptr; - } - - napi_create_async_work(env, nullptr, NVal::CreateUTF8String(env, "List").val_, ListExec, ListComp, - (void *)asyncInfo, &asyncInfo->asyncWork); - napi_queue_async_work(env, asyncInfo->asyncWork); - - return NVal::CreateUndefined(env).val_; -} - -napi_value FilePickerExporter::GetDeviceInfo(napi_env env, napi_callback_info info) -{ - NFuncArg funcArg(env, info); - if (!funcArg.InitArgs(NARG_CNT::ONE)) { - UniError(EINVAL).ThrowErr(env, "Number of arguments unmatched"); - return nullptr; - } - - auto *asyncInfo = new GetDeviceAsyncInfo; - - bool succ = false; - tie(succ, asyncInfo->callback[COMMON_NUM::ZERO], asyncInfo->callback[COMMON_NUM::ONE], - asyncInfo->callback[COMMON_NUM::TWO]) = CommonFunc::GetCallbackHandles(env, funcArg[NARG_POS::FIRST]); - - napi_create_async_work(env, nullptr, NVal::CreateUTF8String(env, "GetDeviceInfo").val_, GetDeviceInfoExec, - GetDeviceInfoComp, (void *)asyncInfo, &asyncInfo->asyncWork); - napi_queue_async_work(env, asyncInfo->asyncWork); - - return NVal::CreateUndefined(env).val_; -} - -bool FilePickerExporter::Export() -{ - return exports_.AddProp( - { NVal::DeclareNapiFunction("mkdir", Mkdir), NVal::DeclareNapiFunction("saveFile", SaveFile), - NVal::DeclareNapiFunction("searchFile", SearchFile), NVal::DeclareNapiFunction("list", List), - NVal::DeclareNapiFunction("getDeviceInfo", GetDeviceInfo) }); -} - -string FilePickerExporter::GetClassName() -{ - return FilePickerExporter::className_; -} - -FilePickerExporter::FilePickerExporter(napi_env env, napi_value exports) - : NExporter(env, exports) -{} - -FilePickerExporter::~FilePickerExporter() {} -} // namespace ModuleFPExpoter -} // namespace DistributedFS -} // namespace OHOS \ No newline at end of file diff --git a/interfaces/kits/napi/file_picker_service/file_picker_exporter.h b/interfaces/kits/napi/file_picker_service/file_picker_exporter.h deleted file mode 100644 index 31bd97a..0000000 --- a/interfaces/kits/napi/file_picker_service/file_picker_exporter.h +++ /dev/null @@ -1,96 +0,0 @@ -/* - * Copyright (c) 2021 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -#ifndef STORAGE_DISKMGR_INTERFACE_KITS_NAPI_DSM_FILE_PICKER_EXPORTER_H -#define STORAGE_DISKMGR_INTERFACE_KITS_NAPI_DSM_FILE_PICKER_EXPORTER_H - -#pragma once - -#include "ability.h" - -#include "../common/napi/n_exporter.h" -#include "file_info.h" -#include "root_info.h" -#include "storage_ability.h" - -namespace OHOS { -namespace DistributedFS { -namespace ModuleFPExpoter { -struct MkdirAsyncInfo { - napi_async_work asyncWork = nullptr; - napi_deferred defer = nullptr; - napi_ref callback[3] = { nullptr }; - std::string path = ""; - int err = 0; -}; - -struct SaveFileAsyncInfo { - napi_async_work asyncWork = nullptr; - napi_deferred defer = nullptr; - napi_ref callback[3] = { nullptr }; - std::string dstPath = ""; - size_t srcLen = 0; - int err = 0; - std::vector srcPath; - std::vector saveFileList; -}; - -struct SearchFileAsyncInfo { - napi_async_work asyncWork = nullptr; - napi_deferred defer = nullptr; - napi_ref callback[3] = { nullptr }; - std::string path = ""; - std::string name = ""; - int err = 0; - std::vector fileInfoList; -}; - -struct ListAsyncInfo { - napi_async_work asyncWork = nullptr; - napi_deferred defer = nullptr; - napi_ref callback[3] = { nullptr }; - std::string path = ""; - int err = 0; - std::vector fileInfoList; -}; - -struct GetDeviceAsyncInfo { - napi_async_work asyncWork = nullptr; - napi_deferred defer = nullptr; - napi_ref callback[3] = { nullptr }; - int err = 0; - std::vector deviceInfoList; -}; - -class FilePickerExporter final : public NExporter { -public: - inline static const std::string className_ = "FilePicker"; - static napi_value Mkdir(napi_env env, napi_callback_info info); - static napi_value SaveFile(napi_env env, napi_callback_info info); - static napi_value SearchFile(napi_env env, napi_callback_info info); - static napi_value List(napi_env env, napi_callback_info info); - static napi_value GetDeviceInfo(napi_env env, napi_callback_info info); - - bool Export() override; - - std::string GetClassName() override; - - FilePickerExporter(napi_env env, napi_value exports); - ~FilePickerExporter() override; -}; -} // namespace ModuleFMSExpoter -} // namespace DistributedFS -} // namespace OHOS - -#endif // STORAGE_DISKMGR_INTERFACE_KITS_NAPI_DSM_FILE_PICKER_EXPORTER_H \ No newline at end of file diff --git a/interfaces/kits/napi/file_picker_service/module.cpp b/interfaces/kits/napi/file_picker_service/module.cpp deleted file mode 100644 index 0acd1ca..0000000 --- a/interfaces/kits/napi/file_picker_service/module.cpp +++ /dev/null @@ -1,48 +0,0 @@ -/* - * Copyright (c) 2021 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -#include "module.h" - -#include -#include - -#include "../common/log.h" -#include "file_picker_exporter.h" - -using namespace std; - -namespace OHOS { -namespace DistributedFS { -namespace ModuleFPExpoter { -static napi_value Export(napi_env env, napi_value exports) -{ - std::vector> products; - products.emplace_back(make_unique(env, exports)); - - for (auto &&product : products) { - if (!product->Export()) { - HILOGE("INNER BUG. Failed to export class %{public}s for module filepicker", - product->GetClassName().c_str()); - return nullptr; - } else { - HILOGE("Class %{public}s for module file has been exported", product->GetClassName().c_str()); - } - } - return exports; -} - -NAPI_MODULE(filepicker, Export) -} // namespace ModuleFMSExpoter -} // namespace DistributedFS -} // namespace OHOS \ No newline at end of file diff --git a/interfaces/kits/napi/file_picker_service/module.h b/interfaces/kits/napi/file_picker_service/module.h deleted file mode 100644 index d92e887..0000000 --- a/interfaces/kits/napi/file_picker_service/module.h +++ /dev/null @@ -1,18 +0,0 @@ -/* - * Copyright (c) 2021 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -#ifndef STORAGE_DISKMGR_INTERFACE_KITS_NAPI_FPS_MODULE_H -#define STORAGE_DISKMGR_INTERFACE_KITS_NAPI_FPS_MODULE_H - -#endif // STORAGE_DISKMGR_INTERFACE_KITS_NAPI_FPS_MODULE_H \ No newline at end of file diff --git a/interfaces/kits/napi/file_share_ability/file_share_exporter.cpp b/interfaces/kits/napi/file_share_ability/file_share_exporter.cpp deleted file mode 100644 index 50e846d..0000000 --- a/interfaces/kits/napi/file_share_ability/file_share_exporter.cpp +++ /dev/null @@ -1,278 +0,0 @@ -/* - * Copyright (c) 2021 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#include "file_share_exporter.h" - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -#include "../common/ability_helper.h" -#include "../common/common_func.h" -#include "../common/napi/n_class.h" -#include "../common/napi/n_func_arg.h" -#include "../common/napi/n_val.h" -#include "../common/uni_error.h" -#include "file_share_ability.h" -#include "uri.h" - -using Uri = OHOS::Uri; -using namespace std; -namespace OHOS { -namespace DistributedFS { -namespace ModuleFMSExpoter { -const int OTHER_ARGUMENT_ERROR = 202; -const int URI_PARAMER_ERROR = 302; -const int FILE_IO_ERROR = 300; -const int FILE_PATH_ERROR = 301; -const int SUCCESS = 0; -const int FAILED = -1; -enum COMMON_NUM { - ZERO = 0, - ONE = 1, - TWO = 2, - THREE = 3, -}; - -void CallBackSuccess(napi_env env, napi_ref successFuncRef, int32_t count, napi_value obj) -{ - napi_value results = nullptr; - napi_value successFunc = nullptr; - napi_value global = nullptr; - napi_get_global(env, &global); - napi_get_reference_value(env, successFuncRef, &successFunc); - if (successFunc == nullptr) { - return; - } - napi_call_function(env, global, successFunc, count, &obj, &results); -} - -void CallBackError(napi_env env, napi_ref failFuncRef, string errorProp, int errorCode) -{ - napi_value argvFail[2] = { 0 }; - napi_value results = nullptr; - napi_value failFunc = nullptr; - napi_value global = nullptr; - napi_get_global(env, &global); - argvFail[0] = NVal::CreateUTF8String(env, errorProp).val_; - argvFail[1] = NVal::CreateInt32(env, errorCode).val_; - napi_get_reference_value(env, failFuncRef, &failFunc); - if (failFunc == nullptr) { - return; - } - napi_call_function(env, global, failFunc, COMMON_NUM::TWO, argvFail, &results); -} - -void CallComplete(napi_env env, napi_ref completeFuncRef) -{ - napi_value completeFunc = nullptr; - napi_value results = nullptr; - napi_value global = nullptr; - napi_get_global(env, &global); - napi_get_reference_value(env, completeFuncRef, &completeFunc); - if (completeFunc == nullptr) { - return; - } - napi_call_function(env, global, completeFunc, COMMON_NUM::ZERO, nullptr, &results); -} - -bool CheckUri(AppExecFwk::Ability *ability, napi_env env, string &path) -{ - string pathOrigin = path; - vector uriSplit; - string pattern = "/"; - if (path == "") { - return false; - } - string pathTmp = pathOrigin + pattern; - size_t pos = pathTmp.find(pattern); - while (pos != pathTmp.npos) { - string temp = pathTmp.substr(COMMON_NUM::ZERO, pos); - uriSplit.push_back(temp); - pathTmp = pathTmp.substr(pos + 1, pathTmp.size()); - pos = pathTmp.find(pattern); - } - if (uriSplit[COMMON_NUM::ZERO] != "internal:" || uriSplit[COMMON_NUM::ONE] != "" || - uriSplit.size() <= COMMON_NUM::TWO) { - return false; - } - if (uriSplit[COMMON_NUM::TWO] == "app") { - path = ability->GetDataDir(); - } else if (uriSplit[COMMON_NUM::TWO] == "cache") { - path = ability->GetCacheDir(); - } else { - return false; - } - for (size_t i = COMMON_NUM::THREE; i < uriSplit.size(); ++i) { - path = path + "/" + uriSplit[i]; - } - return true; -} - -int GetRealPath(string &path) -{ - unique_ptr absPath = make_unique(PATH_MAX + 1); - if (realpath(path.c_str(), absPath.get()) == nullptr) { - return errno; - } - path = absPath.get(); - return SUCCESS; -} - -void CallbackUriResult(napi_env env, napi_ref napiFailFun, napi_ref napiSuccFun, string uriRet) -{ - if (uriRet == "") { - CallBackError(env, napiFailFun, "error: fuzzyFileToUri failed", FILE_IO_ERROR); - } else if (uriRet == "ERROR_AUTHORITY") { - CallBackError(env, napiFailFun, "error: authority is not exist", OTHER_ARGUMENT_ERROR); - } else if (uriRet == "ERROR_JSON_CONFIG") { - CallBackError(env, napiFailFun, "error: invalid json config", FILE_IO_ERROR); - } else { - CallBackSuccess(env, napiSuccFun, COMMON_NUM::ONE, NVal::CreateUTF8String(env, uriRet).val_); - } -} - -int CheckArgumentsError(napi_env env, napi_ref napiFailFun, string deviceIdStr, string authorityStr) -{ - if (deviceIdStr == "" || authorityStr == "") { - CallBackError(env, napiFailFun, "error: illegal arguments", OTHER_ARGUMENT_ERROR); - return FAILED; - } - return SUCCESS; -} - -int CheckUriError(napi_env env, napi_ref napiFailFun, AppExecFwk::Ability *ability, int checkPathResult, string path) -{ - if (!checkPathResult) { - CallBackError(env, napiFailFun, "error: illegal uri", URI_PARAMER_ERROR); - return FAILED; - } else if (path.find(ability->GetDataDir()) != 0 && path.find(ability->GetCacheDir()) != 0) { - CallBackError(env, napiFailFun, "error: uri cannot out of this package", URI_PARAMER_ERROR); - return FAILED; - } - return SUCCESS; -} - -int CheckFilePathError(napi_env env, napi_ref napiFailFun, int realPathResult) -{ - if (realPathResult == ENOENT) { - CallBackError(env, napiFailFun, "error: file or directory not exist", FILE_PATH_ERROR); - return FAILED; - } - return SUCCESS; -} - -int CheckIOError(napi_env env, napi_ref napiFailFun, int realPathResult, string path) -{ - struct stat buf; - if (realPathResult != SUCCESS) { - CallBackError(env, napiFailFun, "error: invalid uri", FILE_IO_ERROR); - return FAILED; - } else if (stat(path.c_str(), &buf) != SUCCESS || (buf.st_mode & S_IFMT) != S_IFREG) { - CallBackError(env, napiFailFun, "error: uri cannot be a directory", FILE_IO_ERROR); - return FAILED; - } - return SUCCESS; -} - -napi_value FileShareExporter::FuzzyFileToUri(napi_env env, napi_callback_info info) -{ - NFuncArg funcArg(env, info); - if (!funcArg.InitArgs(NARG_CNT::ONE)) { - UniError(EINVAL).ThrowErr(env, "Number of arguments unmatched"); - return nullptr; - } - bool succ = false; - napi_ref napiSuccFun, napiCompFun, napiFailFun; - tie(succ, napiSuccFun, napiFailFun, napiCompFun) = - CommonFunc::GetCallbackHandles(env, funcArg[NARG_POS::FIRST]); - - unique_ptr uri = nullptr; - tie(succ, uri, ignore) = NVal(env, funcArg[NARG_POS::FIRST]).GetProp("uri").ToUTF8String(); - - unique_ptr deviceId = nullptr; - tie(succ, deviceId, ignore) = NVal(env, funcArg[NARG_POS::FIRST]).GetProp("deviceId").ToUTF8String(); - - unique_ptr authority = nullptr; - tie(succ, authority, ignore) = NVal(env, funcArg[NARG_POS::FIRST]).GetProp("authority").ToUTF8String(); - - unique_ptr displayname = nullptr; - tie(succ, displayname, ignore) = - NVal(env, funcArg[NARG_POS::FIRST]).GetProp("displayName").ToUTF8String(); - string path = (uri == nullptr) ? "" : uri.get(); - string deviceIdStr = (deviceId == nullptr) ? "" : deviceId.get(); - string authorityStr = (authority == nullptr) ? "" : authority.get(); - string displaynameStr = (displayname == nullptr) ? "" : displayname.get(); - - AppExecFwk::Ability *ability = AbilityHelper::GetJsAbility(env); - if (ability == nullptr) { - return nullptr; - } - bool checkPathResult = CheckUri(ability, env, path); - int realPathResult = GetRealPath(path); - if (CheckArgumentsError(env, napiFailFun, deviceIdStr, authorityStr) == FAILED || - CheckUriError(env, napiFailFun, ability, checkPathResult, path) == FAILED || - CheckFilePathError(env, napiFailFun, realPathResult) == FAILED || - CheckIOError(env, napiFailFun, realPathResult, path) == FAILED) { - CallComplete(env, napiCompFun); - napi_delete_reference(env, napiSuccFun); - napi_delete_reference(env, napiFailFun); - napi_delete_reference(env, napiCompFun); - return nullptr; - } - - Uri uriObj(""); - uriObj = FileManager::FileShareAbility::FuzzyFileToUri(ability, deviceIdStr, authorityStr, path, displaynameStr); - - string uriRet = uriObj.ToString(); - CallbackUriResult(env, napiFailFun, napiSuccFun, uriRet); - - CallComplete(env, napiCompFun); - napi_delete_reference(env, napiSuccFun); - napi_delete_reference(env, napiFailFun); - napi_delete_reference(env, napiCompFun); - return NVal::CreateUndefined(env).val_; -} - -bool FileShareExporter::Export() -{ - return exports_.AddProp({ - NVal::DeclareNapiFunction("fuzzyFileToUri", FuzzyFileToUri), - }); -} - -string FileShareExporter::GetClassName() -{ - return FileShareExporter::className_; -} - -FileShareExporter::FileShareExporter(napi_env env, napi_value exports) - : NExporter(env, exports) -{} - -FileShareExporter::~FileShareExporter() {} -} // namespace ModuleFMSExpoter -} // namespace DistributedFS -} // namespace OHOS \ No newline at end of file diff --git a/interfaces/kits/napi/file_share_ability/file_share_exporter.h b/interfaces/kits/napi/file_share_ability/file_share_exporter.h deleted file mode 100644 index 2722981..0000000 --- a/interfaces/kits/napi/file_share_ability/file_share_exporter.h +++ /dev/null @@ -1,41 +0,0 @@ -/* - * Copyright (c) 2021 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -#ifndef STORAGE_DISKMGR_INTERFACE_KITS_NAPI_DSM_FILE_SHARE_EXPORTER_H -#define STORAGE_DISKMGR_INTERFACE_KITS_NAPI_DSM_FILE_SHARE_EXPORTER_H - -#pragma once - -#include "../common/napi/n_exporter.h" - -namespace OHOS { -namespace DistributedFS { -namespace ModuleFMSExpoter { -class FileShareExporter final : public NExporter { -public: - inline static const std::string className_ = "FileShare"; - static napi_value FuzzyFileToUri(napi_env env, napi_callback_info info); - - bool Export() override; - - std::string GetClassName() override; - - FileShareExporter(napi_env env, napi_value exports); - ~FileShareExporter() override; -}; -} // namespace ModuleFMSExpoter -} // namespace DistributedFS -} // namespace OHOS - -#endif // STORAGE_DISKMGR_INTERFACE_KITS_NAPI_DSM_FILE_SHARE_EXPORTER_H \ No newline at end of file diff --git a/interfaces/kits/napi/file_share_ability/module.cpp b/interfaces/kits/napi/file_share_ability/module.cpp deleted file mode 100644 index 25c1336..0000000 --- a/interfaces/kits/napi/file_share_ability/module.cpp +++ /dev/null @@ -1,48 +0,0 @@ -/* - * Copyright (c) 2021 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -#include "module.h" - -#include -#include - -#include "../common/log.h" -#include "file_share_exporter.h" - -using namespace std; - -namespace OHOS { -namespace DistributedFS { -namespace ModuleFMSExpoter { -static napi_value Export(napi_env env, napi_value exports) -{ - std::vector> products; - products.emplace_back(make_unique(env, exports)); - - for (auto &&product : products) { - if (!product->Export()) { - HILOGE("INNER BUG. Failed to export class %{public}s for module file", - product->GetClassName().c_str()); - return nullptr; - } else { - HILOGE("Class %{public}s for module file has been exported", product->GetClassName().c_str()); - } - } - return exports; -} - -NAPI_MODULE(fileshare, Export) -} // namespace ModuleFMSExpoter -} // namespace DistributedFS -} // namespace OHOS \ No newline at end of file diff --git a/interfaces/kits/napi/file_share_ability/module.h b/interfaces/kits/napi/file_share_ability/module.h deleted file mode 100644 index a287cb5..0000000 --- a/interfaces/kits/napi/file_share_ability/module.h +++ /dev/null @@ -1,18 +0,0 @@ -/* - * Copyright (c) 2021 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -#ifndef STORAGE_DISKMGR_INTERFACE_KITS_NAPI_FSA_MODULE_H -#define STORAGE_DISKMGR_INTERFACE_KITS_NAPI_FSA_MODULE_H - -#endif // STORAGE_DISKMGR_INTERFACE_KITS_NAPI_FSA_MODULE_H \ No newline at end of file diff --git a/interfaces/kits/native/storage_service/BUILD.gn b/interfaces/kits/native/storage_service/BUILD.gn deleted file mode 100644 index 7f4a063..0000000 --- a/interfaces/kits/native/storage_service/BUILD.gn +++ /dev/null @@ -1,37 +0,0 @@ -# Copyright (c) 2021 Huawei Device Co., Ltd. -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -import("//build/ohos.gni") - -ohos_shared_library("ss_crypto_api") { - sources = [ "ss_crypto_api.cpp" ] - include_dirs = [ - "include", - "//foundation/systemabilitymgr/samgr/interfaces/innerkits/samgr_proxy/include", - "//third_party/openssl/include/openssl", - "//utils/system/safwk/native/include", - "//third_party/json/include", - "//commonlibrary/c_utils/base/include", - "//third_party/openssl/include", - ] - external_deps = [ - "ability_base:want", - "c_utils:utils", - "hilog:libhilog", - "huks:libhukssdk", - "ipc:ipc_core", - "safwk:system_ability_fwk", - "samgr:samgr_proxy", - ] - subsystem_name = "distributeddatamgr" -} diff --git a/interfaces/kits/native/storage_service/ss_crypto_api.cpp b/interfaces/kits/native/storage_service/ss_crypto_api.cpp deleted file mode 100644 index 8cef6e3..0000000 --- a/interfaces/kits/native/storage_service/ss_crypto_api.cpp +++ /dev/null @@ -1,224 +0,0 @@ -/* - * Copyright (C) 2021 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -#include "ss_crypto_api.h" - -#include -#include - -#include "fbe_crypto.h" -#include "istorage_service.h" -#include "storage_hilog.h" -#include "storage_service_proxy.h" - -namespace OHOS { -const int SCA_ERR_NONE = 0; - -sptr g_cryptoProxy = nullptr; - -bool GetCryptoProxy() -{ - if (g_cryptoProxy != nullptr) { - return true; - } - SSLOG_E("SS_request::Connect start"); - if (g_cryptoProxy == nullptr) { - auto sam = SystemAbilityManagerClient::GetInstance().GetSystemAbilityManager(); - if (sam == nullptr) { - SSLOG_E("SS_request::Connect samgr == nullptr"); - return false; - } - auto object = sam->GetSystemAbility(STORAGE_SERVICE_ID); - if (object == nullptr) { - SSLOG_E("SS_request::Connect object == nullptr"); - return false; - } - g_cryptoProxy = iface_cast(object); - if (g_cryptoProxy == nullptr) { - SSLOG_E("SS_request::Connect service == nullptr"); - return false; - } - } - SSLOG_E("DeviceStorageManager::Connect end"); - return true; -} - -int32_t SsCryptoEnable() -{ - SSLOG_I("CryptoEnable starting....(from gby)"); - if (g_cryptoProxy == nullptr) { - SSLOG_E("The mSsProxy is null..(from gby)"); - return SCA_ERR_NONE; - } - g_cryptoProxy->CryptoEnable(); - SSLOG_I("CryptoEnable end....(from gby)"); - return 0; -} - -int32_t SsCryptoInitialize() -{ - SSLOG_I("CryptoInitialize starting....(from gby)"); - if (g_cryptoProxy == nullptr) { - SSLOG_E("The mSsProxy is null.."); - return SCA_ERR_NONE; - } - g_cryptoProxy->CryptoInitialize(); - SSLOG_I("CryptoInitialize end....(from gby)"); - return 0; -} - -int32_t SsCryptoCreateKey(int32_t userId) -{ - SSLOG_I("CryptoCreateKey starting....(from gby)"); - if (g_cryptoProxy == nullptr) { - SSLOG_E("The mSsProxy is null.."); - return SCA_ERR_NONE; - } - if (userId <= 0) { - SSLOG_E("The input userId is illegal"); - return SCA_ERR_NONE; - } - g_cryptoProxy->CryptoCreateKey(userId); - SSLOG_I("CryptoCreateKey end....(from gby)"); - return 0; -} - -int32_t SsCryptoDeleteKey(int32_t userId) -{ - SSLOG_I("CryptoDeleteKey starting....(from gby)"); - if (g_cryptoProxy == nullptr) { - SSLOG_E("The mSsProxy is null.."); - return SCA_ERR_NONE; - } - if (userId <= 0) { - SSLOG_E("The input userId is illegal"); - return SCA_ERR_NONE; - } - g_cryptoProxy->CryptoDeleteKey(userId); - SSLOG_I("CryptoDeleteKey end....(from gby)"); - return 0; -} - -int32_t SsCryptoAddAuthKey(int32_t userId, const std::string &token, const std::string &secret) -{ - SSLOG_I("CryptoAddAuthKey starting....(from gby)"); - if (g_cryptoProxy == nullptr) { - SSLOG_E("The mSsProxy is null.."); - return SCA_ERR_NONE; - } - if (userId <= 0) { - SSLOG_E("The input userId is illegal"); - return SCA_ERR_NONE; - } - g_cryptoProxy->CryptoAddAuthKey(userId, token, secret); - SSLOG_I("CryptoAddAuthKey end....(from gby)"); - return 0; -} - -int32_t SsCryptoDelAuthKey(int32_t userId, const std::string &token, const std::string &secret) -{ - SSLOG_I("CryptoDelAuthKey starting....(from gby)"); - if (g_cryptoProxy == nullptr) { - SSLOG_E("The mSsProxy is null.."); - return SCA_ERR_NONE; - } - if (userId <= 0) { - SSLOG_E("The input userId is illegal"); - return SCA_ERR_NONE; - } - g_cryptoProxy->CryptoDelAuthKey(userId, token, secret); - SSLOG_I("CryptoDelAuthKey end....(from gby)"); - return 0; -} - -int32_t SsCryptoUnlockKey(int32_t userId, const std::string &token, const std::string &secret) -{ - SSLOG_I("CryptoUnlockKey starting....(from gby)"); - if (g_cryptoProxy == nullptr) { - SSLOG_E("The mSsProxy is null.."); - return SCA_ERR_NONE; - } - if (userId <= 0) { - SSLOG_E("The input userId is illegal"); - return SCA_ERR_NONE; - } - g_cryptoProxy->CryptoUnlockKey(userId, token, secret); - SSLOG_I("CryptoUnlockKey end....(from gby)"); - return 0; -} - -int32_t SsCryptoLockKey(int32_t userId) -{ - SSLOG_I("CryptoLockKey starting....(from gby)"); - if (g_cryptoProxy == nullptr) { - SSLOG_E("The mSsProxy is null.."); - return SCA_ERR_NONE; - } - if (userId <= 0) { - SSLOG_E("The input userId is illegal"); - return SCA_ERR_NONE; - } - g_cryptoProxy->CryptoLockKey(userId); - SSLOG_I("CryptoLockKey end....(from gby)"); - return 0; -} - -int32_t SsCryptoUpdateAuthKey(int32_t userId, const std::string &token, const std::string secret) -{ - SSLOG_I("CryptoUpdateAuthKey starting....(from gby)"); - if (g_cryptoProxy == nullptr) { - SSLOG_E("The mSsProxy is null.."); - return SCA_ERR_NONE; - } - if (userId <= 0) { - SSLOG_E("The input userId is illegal"); - return SCA_ERR_NONE; - } - g_cryptoProxy->CryptoUpdateAuthKey(userId, token, secret); - SSLOG_I("CryptoUpdateAuthKey end....(from gby)"); - return 0; -} - -int32_t SsCryptoInitUserSpace(const std::string &uuid, int32_t userid, int32_t flag) -{ - SSLOG_I("CryptoCreatePaths starting....(from gby)"); - if (g_cryptoProxy == nullptr) { - SSLOG_E("The mSsProxy is null.."); - return SCA_ERR_NONE; - } - if (userid <= 0) { - SSLOG_E("The input userId is illegal"); - return SCA_ERR_NONE; - } - g_cryptoProxy->CryptoInitUserSpace(uuid, userid, flag); - SSLOG_I("CryptoCreatePaths end....(from gby)"); - return 0; -} - -int32_t SsCryptoRemoveUserSpace(const std::string &uuid, int32_t userid, int32_t flag) -{ - SSLOG_I("CryptoRemovePaths starting....(from gby)"); - if (g_cryptoProxy == nullptr) { - SSLOG_E("The mSsProxy is null.."); - return SCA_ERR_NONE; - } - if (userid <= 0) { - SSLOG_E("The input userId is illegal"); - return SCA_ERR_NONE; - } - g_cryptoProxy->CryptoRemoveUserSpace(uuid, userid, flag); - SSLOG_I("CryptoRemovePaths end....(from gby)"); - return 0; -} -} // namespace OHOS \ No newline at end of file diff --git a/interfaces/kits/native/storage_service/ss_crypto_api.h b/interfaces/kits/native/storage_service/ss_crypto_api.h deleted file mode 100644 index 28008d5..0000000 --- a/interfaces/kits/native/storage_service/ss_crypto_api.h +++ /dev/null @@ -1,18 +0,0 @@ -/* - * Copyright (c) 2021 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -#ifndef STORAGE_DISKMGR_INTERFACE_KITS_NATIVE_SS_CRYPTO_API_H -#define STORAGE_DISKMGR_INTERFACE_KITS_NATIVE_SS_CRYPTO_API_H - -#endif // STORAGE_DISKMGR_INTERFACE_KITS_NATIVE_SS_CRYPTO_API_H \ No newline at end of file diff --git a/utils/filemgmt_libhilog/BUILD.gn b/utils/filemgmt_libhilog/BUILD.gn deleted file mode 100644 index c87ddf7..0000000 --- a/utils/filemgmt_libhilog/BUILD.gn +++ /dev/null @@ -1,29 +0,0 @@ -# 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") - -config("log_public_config") { - visibility = [ ":*" ] - - include_dirs = [ "." ] -} - -ohos_shared_library("filemgmt_libhilog") { - public_configs = [ ":log_public_config" ] - public_deps = - [ "//base/hiviewdfx/hilog/interfaces/native/innerkits:libhilog" ] - - subsystem_name = "distributeddatamgr" - part_name = "distributedfilejs" -} diff --git a/utils/filemgmt_libhilog/filemgmt_libhilog.h b/utils/filemgmt_libhilog/filemgmt_libhilog.h deleted file mode 100644 index 0cdf426..0000000 --- a/utils/filemgmt_libhilog/filemgmt_libhilog.h +++ /dev/null @@ -1,52 +0,0 @@ -/* - * 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 FILEMGMT_LIBHILOG_H -#define FILEMGMT_LIBHILOG_H - -#include "hilog/log.h" - -#include - -namespace OHOS { -#ifndef LOG_DOMAIN -#define LOG_DOMAIN 0xD001600 -#endif - -#ifndef LOG_TAG -#define LOG_TAG "FileManagement" -#endif - -static constexpr HiviewDFX::HiLogLabel FILEMGMT_LOG_LABEL = {LOG_CORE, LOG_DOMAIN, LOG_TAG}; - -#if defined __FILE_NAME__ -#define FILEMGMT_FILE_NAME __FILE_NAME__ -#else -#include -#define FILEMGMT_FILE_NAME (strrchr(__FILE__, '/') ? strrchr(__FILE__, '/') + 1 : __FILE__) -#endif - -#define FILEMGMT_PRINT_LOG(Level, fmt, ...) \ - HiviewDFX::HiLog::Level(FILEMGMT_LOG_LABEL, "[%{public}s:%{public}d->%{public}s] " fmt, FILEMGMT_FILE_NAME, \ - __LINE__, __FUNCTION__, ##__VA_ARGS__) - -#define HILOGD(fmt, ...) FILEMGMT_PRINT_LOG(Debug, fmt, ##__VA_ARGS__) -#define HILOGI(fmt, ...) FILEMGMT_PRINT_LOG(Info, fmt, ##__VA_ARGS__) -#define HILOGW(fmt, ...) FILEMGMT_PRINT_LOG(Warn, fmt, ##__VA_ARGS__) -#define HILOGE(fmt, ...) FILEMGMT_PRINT_LOG(Error, fmt, ##__VA_ARGS__) -#define HILOGF(fmt, ...) FILEMGMT_PRINT_LOG(Fatal, fmt, ##__VA_ARGS__) -} // namespace OHOS - -#endif // FILEMGMT_LIBHILOG_H \ No newline at end of file diff --git a/utils/filemgmt_libn/BUILD.gn b/utils/filemgmt_libn/BUILD.gn deleted file mode 100644 index 3fd8f86..0000000 --- a/utils/filemgmt_libn/BUILD.gn +++ /dev/null @@ -1,44 +0,0 @@ -# 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") - -config("libn_public_config") { - visibility = [ ":*" ] - - include_dirs = [ - "include", - "include/n_async", - ] -} - -ohos_shared_library("filemgmt_libn") { - sources = [ - "src/n_async/n_async_work_callback.cpp", - "src/n_async/n_async_work_promise.cpp", - "src/n_async/n_ref.cpp", - "src/n_class.cpp", - "src/n_error.cpp", - "src/n_func_arg.cpp", - "src/n_val.cpp", - ] - - public_configs = [ ":libn_public_config" ] - public_deps = [ - "//foundation/arkui/napi:ace_napi", - "//foundation/distributeddatamgr/distributedfile/utils/filemgmt_libhilog", - ] - - subsystem_name = "distributeddatamgr" - part_name = "distributedfilejs" -} diff --git a/utils/filemgmt_libn/include/filemgmt_libn.h b/utils/filemgmt_libn/include/filemgmt_libn.h deleted file mode 100644 index 01ac939..0000000 --- a/utils/filemgmt_libn/include/filemgmt_libn.h +++ /dev/null @@ -1,26 +0,0 @@ -/* - * 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 FILEMGMT_LIBN_FILEMGMT_LIBN_H -#define FILEMGMT_LIBN_FILEMGMT_LIBN_H - -#include "n_async_work_callback.h" -#include "n_async_work_promise.h" -#include "n_class.h" -#include "n_error.h" -#include "n_exporter.h" -#include "n_func_arg.h" - -#endif // FILEMGMT_LIBN_FILEMGMT_LIBN_H \ No newline at end of file diff --git a/utils/filemgmt_libn/include/n_async/n_async_context.h b/utils/filemgmt_libn/include/n_async/n_async_context.h deleted file mode 100644 index fb09249..0000000 --- a/utils/filemgmt_libn/include/n_async/n_async_context.h +++ /dev/null @@ -1,75 +0,0 @@ -/* - * 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 FILEMGMT_LIBN_N_ASYNC_CONTEXT_H -#define FILEMGMT_LIBN_N_ASYNC_CONTEXT_H - -#include - -#include "n_error.h" -#include "n_ref.h" -#include "n_val.h" - -namespace OHOS { -namespace FileManagement { -namespace LibN { -using NContextCBExec = std::function; -using NContextCBComplete = std::function; - -class NAsyncContext { -public: - NError err_; - NVal res_; - NContextCBExec cbExec_; - NContextCBComplete cbComplete_; - napi_async_work awork_; - NRef thisPtr_; - - NAsyncContext(NVal thisPtr) - : err_(0), res_(NVal()), cbExec_(nullptr), cbComplete_(nullptr), awork_(nullptr), thisPtr_(thisPtr) - { - } - virtual ~NAsyncContext() = default; -}; - -class NAsyncContextPromise : public NAsyncContext { -public: - napi_deferred deferred_ = nullptr; - explicit NAsyncContextPromise(NVal thisPtr) : NAsyncContext(thisPtr) {} - ~NAsyncContextPromise() = default; -}; - -class NAsyncContextCallback : public NAsyncContext { -public: - NRef cb_; - NAsyncContextCallback(NVal thisPtr, NVal cb) : NAsyncContext(thisPtr), cb_(cb) {} - ~NAsyncContextCallback() = default; -}; - -class NAsyncContextLegacy : public NAsyncContext { -public: - NRef cbSucc_; - NRef cbFail_; - NRef cbFinal_; - NAsyncContextLegacy(NVal thisPtr, NVal cbSucc, NVal cbFail, NVal cbFinal) - : NAsyncContext(thisPtr), cbSucc_(cbSucc), cbFail_(cbFail), cbFinal_(cbFinal) - { - } - ~NAsyncContextLegacy() = default; -}; -} // namespace LibN -} // namespace FileManagement -} // namespace OHOS -#endif // FILEMGMT_LIBN_N_ASYNC_CONTEXT_H \ No newline at end of file diff --git a/utils/filemgmt_libn/include/n_async/n_async_work.h b/utils/filemgmt_libn/include/n_async/n_async_work.h deleted file mode 100644 index d3bf6f7..0000000 --- a/utils/filemgmt_libn/include/n_async/n_async_work.h +++ /dev/null @@ -1,36 +0,0 @@ -/* - * 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 FILEMGMT_LIBN_N_ASYNC_WORK_H -#define FILEMGMT_LIBN_N_ASYNC_WORK_H - -#include "n_async_context.h" - -namespace OHOS { -namespace FileManagement { -namespace LibN { -class NAsyncWork { -public: - NAsyncWork(napi_env env) : env_(env) {} - virtual ~NAsyncWork() = default; - virtual NVal Schedule(std::string procedureName, NContextCBExec cbExec, NContextCBComplete cbComplete) = 0; - - napi_env env_ = nullptr; -}; -} // namespace LibN -} // namespace FileManagement -} // namespace OHOS - -#endif // FILEMGMT_LIBN_N_ASYNC_WORK_H \ No newline at end of file diff --git a/utils/filemgmt_libn/include/n_async/n_async_work_callback.h b/utils/filemgmt_libn/include/n_async/n_async_work_callback.h deleted file mode 100644 index 938a2d7..0000000 --- a/utils/filemgmt_libn/include/n_async/n_async_work_callback.h +++ /dev/null @@ -1,38 +0,0 @@ -/* - * 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 FILEMGMT_LIBN_N_ASYNC_WORK_CALLBACK_H -#define FILEMGMT_LIBN_N_ASYNC_WORK_CALLBACK_H - -#include "n_async_work.h" - -namespace OHOS { -namespace FileManagement { -namespace LibN { -class NAsyncWorkCallback : public NAsyncWork { -public: - NAsyncWorkCallback(napi_env env, NVal thisPtr, NVal cb); - ~NAsyncWorkCallback() = default; - - NVal Schedule(std::string procedureName, NContextCBExec cbExec, NContextCBComplete cbComplete) final; - -private: - NAsyncContextCallback *ctx_ = nullptr; -}; -} // namespace LibN -} // namespace FileManagement -} // namespace OHOS - -#endif // FILEMGMT_LIBN_N_ASYNC_WORK_CALLBACK_H \ No newline at end of file diff --git a/utils/filemgmt_libn/include/n_async/n_async_work_promise.h b/utils/filemgmt_libn/include/n_async/n_async_work_promise.h deleted file mode 100644 index 8f67f0c..0000000 --- a/utils/filemgmt_libn/include/n_async/n_async_work_promise.h +++ /dev/null @@ -1,44 +0,0 @@ -/* - * 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 FILEMGMT_LIBN_N_ASYNC_WORK_PROMISE_H -#define FILEMGMT_LIBN_N_ASYNC_WORK_PROMISE_H - -#include - -#include "node_api.h" -#include "js_native_api_types.h" -#include "n_async_context.h" -#include "n_async_work.h" -#include "n_val.h" - -namespace OHOS { -namespace FileManagement { -namespace LibN { -class NAsyncWorkPromise : public NAsyncWork { -public: - NAsyncWorkPromise(napi_env env, NVal thisPtr); - ~NAsyncWorkPromise() = default; - - NVal Schedule(std::string procedureName, NContextCBExec cbExec, NContextCBComplete cbComplete) final; - -private: - NAsyncContextPromise *ctx_; -}; -} // namespace LibN -} // namespace FileManagement -} // namespace OHOS - -#endif // FILEMGMT_LIBN_N_ASYNC_WORK_PROMISE_H \ No newline at end of file diff --git a/utils/filemgmt_libn/include/n_async/n_ref.h b/utils/filemgmt_libn/include/n_async/n_ref.h deleted file mode 100644 index f78e1ac..0000000 --- a/utils/filemgmt_libn/include/n_async/n_ref.h +++ /dev/null @@ -1,43 +0,0 @@ -/* - * 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 FILEMGMT_LIBN_N_REF_H -#define FILEMGMT_LIBN_N_REF_H - -#include "node_api.h" -#include "js_native_api_types.h" -#include "n_val.h" - -namespace OHOS { -namespace FileManagement { -namespace LibN { -class NRef { -public: - NRef(); - NRef(NVal val); - ~NRef(); - - explicit operator bool() const; - NVal Deref(napi_env env); - -private: - napi_env env_ = nullptr; - napi_ref ref_ = nullptr; -}; -} // namespace LibN -} // namespace FileManagement -} // namespace OHOS - -#endif // FILEMGMT_LIBN_N_REF_H \ No newline at end of file diff --git a/utils/filemgmt_libn/include/n_class.h b/utils/filemgmt_libn/include/n_class.h deleted file mode 100644 index c4d8cae..0000000 --- a/utils/filemgmt_libn/include/n_class.h +++ /dev/null @@ -1,83 +0,0 @@ -/* - * 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 FILEMGMT_LIBN_N_CLASS_H -#define FILEMGMT_LIBN_N_CLASS_H - -#include -#include -#include -#include -#include -#include - -#include "n_napi.h" -#include "filemgmt_libhilog.h" - -namespace OHOS { -namespace FileManagement { -namespace LibN { -class NClass final { -public: - NClass(const NClass &) = delete; - NClass &operator=(const NClass &) = delete; - - static std::tuple DefineClass(napi_env env, - std::string className, - napi_callback constructor, - std::vector &&properties); - static bool SaveClass(napi_env env, std::string className, napi_value exClass); - static napi_value InstantiateClass(napi_env env, const std::string& className, const std::vector& args); - - template static T *GetEntityOf(napi_env env, napi_value objStat) - { - if (!env || !objStat) { - HILOGE("Empty input: env %d, obj %d", env == nullptr, objStat == nullptr); - return nullptr; - } - T *t = nullptr; - napi_status status = napi_unwrap(env, objStat, (void **)&t); - if (status != napi_ok) { - HILOGE("Cannot umwarp for pointer: %d", status); - return nullptr; - } - return t; - } - - template static bool SetEntityFor(napi_env env, napi_value obj, std::unique_ptr entity) - { - napi_status status = napi_wrap( - env, obj, entity.get(), - [](napi_env env, void *data, void *hint) { - auto entity = static_cast(data); - delete entity; - }, - nullptr, nullptr); - entity.release(); - return status == napi_ok; - } - -private: - NClass() = default; - ~NClass() = default; - static NClass &GetInstance(); - std::map exClassMap; - std::mutex exClassMapLock; -}; -} // namespace LibN -} // namespace FileManagement -} // namespace OHOS - -#endif // FILEMGMT_LIBN_N_CLASS_H \ No newline at end of file diff --git a/utils/filemgmt_libn/include/n_error.h b/utils/filemgmt_libn/include/n_error.h deleted file mode 100644 index 0241fcc..0000000 --- a/utils/filemgmt_libn/include/n_error.h +++ /dev/null @@ -1,52 +0,0 @@ -/* - * 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 FILEMGMT_LIBN_N_ERROR_H -#define FILEMGMT_LIBN_N_ERROR_H - -#include -#include -#include - -#include "n_napi.h" - -namespace OHOS { -namespace FileManagement { -namespace LibN { -constexpr int ERRNO_NOERR = 0; - -class NError { -public: - NError(); - NError(int ePosix); - NError(std::function()> errGen); - ~NError() = default; - - explicit operator bool() const; - - napi_value GetNapiErr(napi_env env); - - void ThrowErr(napi_env env); - void ThrowErr(napi_env env, std::string errMsg); - -private: - int errno_ = ERRNO_NOERR; - std::string errMsg_; -}; -} // namespace LibN -} // namespace FileManagement -} // namespace OHOS - -#endif // FILEMGMT_LIBN_N_ERROR_H \ No newline at end of file diff --git a/utils/filemgmt_libn/include/n_exporter.h b/utils/filemgmt_libn/include/n_exporter.h deleted file mode 100644 index ec64e7a..0000000 --- a/utils/filemgmt_libn/include/n_exporter.h +++ /dev/null @@ -1,44 +0,0 @@ -/* - * 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 FILEMGMT_LIBN_N_EXPORTER_H -#define FILEMGMT_LIBN_N_EXPORTER_H - -#include "n_napi.h" - -#include -#include - -#include "n_val.h" - -namespace OHOS { -namespace FileManagement { -namespace LibN { -class NExporter { -public: - NExporter(napi_env env, napi_value exports) : exports_(env, exports) {}; - virtual ~NExporter() = default; - - virtual bool Export() = 0; - virtual std::string GetClassName() = 0; - -protected: - NVal exports_; -}; -} // namespace LibN -} // namespace FileManagement -} // namespace OHOS - -#endif // FILEMGMT_LIBN_N_EXPORTER_H \ No newline at end of file diff --git a/utils/filemgmt_libn/include/n_func_arg.h b/utils/filemgmt_libn/include/n_func_arg.h deleted file mode 100644 index 271ad7a..0000000 --- a/utils/filemgmt_libn/include/n_func_arg.h +++ /dev/null @@ -1,75 +0,0 @@ -/* - * 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 FILEMGMT_LIBN_N_FUNC_ARG_H -#define FILEMGMT_LIBN_N_FUNC_ARG_H - -#include -#include -#include - -#include "n_napi.h" -#include "n_val.h" - -namespace OHOS { -namespace FileManagement { -namespace LibN { -enum NARG_CNT { - ZERO = 0, - ONE = 1, - TWO = 2, - THREE = 3, - FOUR = 4, -}; - -enum NARG_POS { - FIRST = 0, - SECOND = 1, - THIRD = 2, - FOURTH = 3, -}; - -class NFuncArg final { -public: - NFuncArg(napi_env env, napi_callback_info info); - virtual ~NFuncArg(); - - bool InitArgs(size_t argc); - bool InitArgs(size_t minArgc, size_t maxArgc); - - size_t GetArgc() const; - napi_value GetThisVar() const; - - napi_value operator[](size_t idx) const; - napi_value GetArg(size_t argPos) const; - -private: - napi_env env_ = nullptr; - napi_callback_info info_ = nullptr; - - size_t argc_ = 0; - std::unique_ptr argv_ = {nullptr}; - napi_value thisVar_ = nullptr; - - bool InitArgs(std::function argcChecker); - - void SetArgc(size_t argc); - void SetThisVar(napi_value thisVar); -}; -} // namespace LibN -} // namespace FileManagement -} // namespace OHOS - -#endif // FILEMGMT_LIBN_N_FUNC_ARG_H \ No newline at end of file diff --git a/utils/filemgmt_libn/include/n_napi.h b/utils/filemgmt_libn/include/n_napi.h deleted file mode 100644 index 61704ef..0000000 --- a/utils/filemgmt_libn/include/n_napi.h +++ /dev/null @@ -1,26 +0,0 @@ -/* - * 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 FILEMGMT_LIBN_N_NAPI_H -#define FILEMGMT_LIBN_N_NAPI_H - -#ifdef FILE_SUBSYSTEM_DEBUG_LOCAL -#include -#else -#include "napi/native_api.h" -#include "napi/native_node_api.h" -#endif - -#endif // FILEMGMT_LIBN_N_NAPI_H \ No newline at end of file diff --git a/utils/filemgmt_libn/include/n_val.h b/utils/filemgmt_libn/include/n_val.h deleted file mode 100644 index 1baf219..0000000 --- a/utils/filemgmt_libn/include/n_val.h +++ /dev/null @@ -1,87 +0,0 @@ -/* - * 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 FILEMGMT_LIBN_N_VAL_H -#define FILEMGMT_LIBN_N_VAL_H - -#include -#include -#include -#include - -#include "n_napi.h" - -namespace OHOS { -namespace FileManagement { -namespace LibN { -class NVal final { -public: - NVal() = default; - NVal(napi_env nEnv, napi_value nVal); - NVal(const NVal &) = default; - NVal &operator=(const NVal &) = default; - virtual ~NVal() = default; - - // NOTE! env_ and val_ is LIKELY to be null - napi_env env_ = nullptr; - napi_value val_ = nullptr; - - explicit operator bool() const; - bool TypeIs(napi_valuetype expType) const; - bool TypeIsError(bool checkErrno = false) const; - - /* SHOULD ONLY BE USED FOR EXPECTED TYPE */ - std::tuple, size_t> ToUTF8String() const; - std::tuple, size_t> ToUTF16String() const; - std::tuple ToPointer() const; - std::tuple ToBool() const; - std::tuple ToInt32() const; - std::tuple ToInt64() const; - std::tuple ToArraybuffer() const; - std::tuple ToTypedArray() const; - std::tuple, uint32_t> ToStringArray(); - std::tuple ToDouble() const; - - /* Static helpers to create js objects */ - static NVal CreateUndefined(napi_env env); - static NVal CreateInt64(napi_env env, int64_t val); - static NVal CreateInt32(napi_env env, int32_t val); - static NVal CreateObject(napi_env env); - static NVal CreateBool(napi_env env, bool val); - static NVal CreateUTF8String(napi_env env, std::string str); - static NVal CreateUTF8String(napi_env env, const char *str, ssize_t len); - static NVal CreateUint8Array(napi_env env, void *buf, size_t bufLen); - static std::tuple CreateArrayBuffer(napi_env env, size_t len); - /* SHOULD ONLY BE USED FOR OBJECT */ - bool HasProp(std::string propName) const; - NVal GetProp(std::string propName) const; - bool AddProp(std::vector &&propVec) const; - bool AddProp(std::string propName, napi_value nVal) const; - - /* Static helpers to create prop of js objects */ - static napi_property_descriptor DeclareNapiProperty(const char *name, napi_value val); - static napi_property_descriptor DeclareNapiStaticProperty(const char *name, napi_value val); - static napi_property_descriptor DeclareNapiFunction(const char *name, napi_callback func); - static napi_property_descriptor DeclareNapiStaticFunction(const char *name, napi_callback func); - static napi_property_descriptor DeclareNapiGetter(const char *name, napi_callback getter); - static napi_property_descriptor DeclareNapiSetter(const char *name, napi_callback setter); - static inline napi_property_descriptor - DeclareNapiGetterSetter(const char *name, napi_callback getter, napi_callback setter); -}; -} // namespace LibN -} // namespace FileManagement -} // namespace OHOS - -#endif // FILEMGMT_LIBN_N_VAL_H \ No newline at end of file diff --git a/utils/filemgmt_libn/src/n_async/n_async_work_callback.cpp b/utils/filemgmt_libn/src/n_async/n_async_work_callback.cpp deleted file mode 100644 index f688e8d..0000000 --- a/utils/filemgmt_libn/src/n_async/n_async_work_callback.cpp +++ /dev/null @@ -1,100 +0,0 @@ -/* - * 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 "n_async_work_callback.h" -#include "filemgmt_libhilog.h" - -namespace OHOS { -namespace FileManagement { -namespace LibN { -using namespace std; - -NAsyncWorkCallback::NAsyncWorkCallback(napi_env env, NVal thisPtr, NVal cb) : NAsyncWork(env) -{ - ctx_ = new NAsyncContextCallback(thisPtr, cb); -} - -static void CallbackExecute(napi_env env, void *data) -{ - auto ctx = static_cast(data); - if (ctx != nullptr && ctx->cbExec_ != nullptr) { - ctx->err_ = ctx->cbExec_(); - } -} - -static void CallbackComplete(napi_env env, napi_status status, void *data) -{ - napi_handle_scope scope = nullptr; - napi_open_handle_scope(env, &scope); - auto ctx = static_cast(data); - if (ctx == nullptr) { - return; - } - if (ctx->cbComplete_ != nullptr) { - ctx->res_ = ctx->cbComplete_(env, ctx->err_); - ctx->cbComplete_ = nullptr; - } - - vector argv; - if (!ctx->res_.TypeIsError(true)) { - argv = {NError(ERRNO_NOERR).GetNapiErr(env), ctx->res_.val_}; - } else { - argv = {ctx->res_.val_}; - } - - napi_value global = nullptr; - napi_value callback = ctx->cb_.Deref(env).val_; - napi_value tmp = nullptr; - napi_get_global(env, &global); - napi_status stat = napi_call_function(env, global, callback, argv.size(), argv.data(), &tmp); - if (stat != napi_ok) { - HILOGE("Failed to call function for %{public}d", stat); - } - napi_close_handle_scope(env, scope); - napi_delete_async_work(env, ctx->awork_); - delete ctx; -} - -NVal NAsyncWorkCallback::Schedule(string procedureName, NContextCBExec cbExec, NContextCBComplete cbComplete) -{ - if (!ctx_->cb_ || !ctx_->cb_.Deref(env_).TypeIs(napi_function)) { - NError(EINVAL).ThrowErr(env_, "The callback shall be a function"); - return NVal(); - } - - ctx_->cbExec_ = move(cbExec); - ctx_->cbComplete_ = move(cbComplete); - - napi_value resource = NVal::CreateUTF8String(env_, procedureName).val_; - - napi_status status = - napi_create_async_work(env_, nullptr, resource, CallbackExecute, CallbackComplete, ctx_, &ctx_->awork_); - if (status != napi_ok) { - HILOGE("INNER BUG. Failed to create async work for %{public}d", status); - return NVal(); - } - - status = napi_queue_async_work(env_, ctx_->awork_); - if (status != napi_ok) { - HILOGE("INNER BUG. Failed to queue async work for %{public}d", status); - return NVal(); - } - - ctx_ = nullptr; // The ownership of ctx_ has been transferred - return NVal::CreateUndefined(env_); -} -} // namespace LibN -} // namespace FileManagement -} // namespace OHOS diff --git a/utils/filemgmt_libn/src/n_async/n_async_work_promise.cpp b/utils/filemgmt_libn/src/n_async/n_async_work_promise.cpp deleted file mode 100644 index 979debf..0000000 --- a/utils/filemgmt_libn/src/n_async/n_async_work_promise.cpp +++ /dev/null @@ -1,102 +0,0 @@ -/* - * 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 "n_async_work_promise.h" - -#include -#include -#include -#include - -#include "filemgmt_libhilog.h" -#include "js_native_api.h" -#include "n_error.h" -#include "node_api.h" - -namespace OHOS { -namespace FileManagement { -namespace LibN { -using namespace std; - -NAsyncWorkPromise::NAsyncWorkPromise(napi_env env, NVal thisPtr) : NAsyncWork(env) -{ - ctx_ = new NAsyncContextPromise(thisPtr); -} - -static void PromiseOnExec(napi_env env, void *data) -{ - auto ctx = static_cast(data); - if (ctx != nullptr && ctx->cbExec_ != nullptr) { - ctx->err_ = ctx->cbExec_(); - } -} - -static void PromiseOnComplete(napi_env env, napi_status status, void *data) -{ - auto ctx = static_cast(data); - if (ctx == nullptr) { - return; - } - if (ctx->cbComplete_ != nullptr) { - ctx->res_ = ctx->cbComplete_(env, ctx->err_); - } - if (!ctx->res_.TypeIsError(true)) { - napi_status status = napi_resolve_deferred(env, ctx->deferred_, ctx->res_.val_); - if (status != napi_ok) { - HILOGE("Internal BUG, cannot resolve promise for %{public}d", status); - } - } else { - napi_status status = napi_reject_deferred(env, ctx->deferred_, ctx->res_.val_); - if (status != napi_ok) { - HILOGE("Internal BUG, cannot reject promise for %{public}d", status); - } - } - ctx->deferred_ = nullptr; - napi_delete_async_work(env, ctx->awork_); - delete ctx; -} - -NVal NAsyncWorkPromise::Schedule(string procedureName, NContextCBExec cbExec, NContextCBComplete cbComplete) -{ - ctx_->cbExec_ = move(cbExec); - ctx_->cbComplete_ = move(cbComplete); - - napi_status status; - napi_value result = nullptr; - status = napi_create_promise(env_, &ctx_->deferred_, &result); - if (status != napi_ok) { - HILOGE("INNER BUG. Cannot create promise for %{public}d", status); - return NVal(); - } - - napi_value resource = NVal::CreateUTF8String(env_, procedureName).val_; - status = napi_create_async_work(env_, nullptr, resource, PromiseOnExec, PromiseOnComplete, ctx_, &ctx_->awork_); - if (status != napi_ok) { - HILOGE("INNER BUG. Failed to create async work for %{public}d", status); - return NVal(); - } - - status = napi_queue_async_work(env_, ctx_->awork_); - if (status != napi_ok) { - HILOGE("INNER BUG. Failed to queue async work for %{public}d", status); - return NVal(); - } - - ctx_ = nullptr; // The ownership of ctx_ has been transferred - return {env_, result}; -} -} // namespace LibN -} // namespace FileManagement -} // namespace OHOS diff --git a/utils/filemgmt_libn/src/n_async/n_ref.cpp b/utils/filemgmt_libn/src/n_async/n_ref.cpp deleted file mode 100644 index 4e63a04..0000000 --- a/utils/filemgmt_libn/src/n_async/n_ref.cpp +++ /dev/null @@ -1,56 +0,0 @@ -/* - * 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 "n_ref.h" -#include "js_native_api.h" - -namespace OHOS { -namespace FileManagement { -namespace LibN { -NRef::NRef() {} - -NRef::NRef(NVal val) -{ - if (val) { - env_ = val.env_; - napi_create_reference(val.env_, val.val_, 1, &ref_); - } -} - -NRef::~NRef() -{ - if (ref_) { - napi_delete_reference(env_, ref_); - } -} - -NRef::operator bool() const -{ - return ref_ != nullptr; -} - -NVal NRef::Deref(napi_env env) -{ - if (!ref_) { - return NVal(); - } - - napi_value val = nullptr; - napi_get_reference_value(env, ref_, &val); - return {env, val}; -} -} // namespace LibN -} // namespace FileManagement -} // namespace OHOS diff --git a/utils/filemgmt_libn/src/n_class.cpp b/utils/filemgmt_libn/src/n_class.cpp deleted file mode 100644 index 45a6f56..0000000 --- a/utils/filemgmt_libn/src/n_class.cpp +++ /dev/null @@ -1,92 +0,0 @@ -/* - * 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 "n_class.h" - -#include "filemgmt_libhilog.h" - -namespace OHOS { -namespace FileManagement { -namespace LibN { -using namespace std; -NClass &NClass::GetInstance() -{ - static thread_local NClass nClass; - return nClass; -} - -tuple NClass::DefineClass(napi_env env, - string className, - napi_callback constructor, - vector &&properties) -{ - napi_value classVal = nullptr; - napi_status stat = napi_define_class(env, className.c_str(), className.length(), constructor, nullptr, - properties.size(), properties.data(), &classVal); - if (stat != napi_ok) { - HILOGE("INNER BUG. Cannot define class %{public}s because of %{public}d", className.c_str(), stat); - } - return {stat == napi_ok, classVal}; -} - -bool NClass::SaveClass(napi_env env, string className, napi_value exClass) -{ - NClass &nClass = NClass::GetInstance(); - lock_guard(nClass.exClassMapLock); - - if (nClass.exClassMap.find(className) != nClass.exClassMap.end()) { - return true; - } - - napi_ref constructor; - napi_status res = napi_create_reference(env, exClass, 1, &constructor); - if (res == napi_ok) { - nClass.exClassMap.insert( {className, constructor}); - HILOGI("Class %{public}s has been saved", className.c_str()); - } else { - HILOGE("INNER BUG. Cannot ref class constructor %{public}s because of %{public}d", className.c_str(), res); - } - return res == napi_ok; -} - -napi_value NClass::InstantiateClass(napi_env env, const string& className, const vector& args) -{ - NClass &nClass = NClass::GetInstance(); - lock_guard(nClass.exClassMapLock); - - auto it = nClass.exClassMap.find(className); - if (it == nClass.exClassMap.end()) { - HILOGE("Class %{public}s hasn't been saved yet", className.c_str()); - return nullptr; - } - - napi_value cons = nullptr; - napi_status status = napi_get_reference_value(env, it->second, &cons); - if (status != napi_ok) { - HILOGE("INNER BUG. Cannot deref class %{public}s because of %{public}d", className.c_str(), status); - return nullptr; - } - - napi_value instance = nullptr; - status = napi_new_instance(env, cons, args.size(), args.data(), &instance); - if (status != napi_ok) { - HILOGE("INNER BUG. Cannot instantiate the class %{public}s because of %{public}d", className.c_str(), status); - return nullptr; - } - return instance; -} -} // namespace LibN -} // namespace FileManagement -} // namespace OHOS \ No newline at end of file diff --git a/utils/filemgmt_libn/src/n_error.cpp b/utils/filemgmt_libn/src/n_error.cpp deleted file mode 100644 index 88fff79..0000000 --- a/utils/filemgmt_libn/src/n_error.cpp +++ /dev/null @@ -1,72 +0,0 @@ -/* - * 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 "n_error.h" - -#include - -#include "n_val.h" -#include "filemgmt_libhilog.h" - -namespace OHOS { -namespace FileManagement { -namespace LibN { -using namespace std; - -NError::NError() {} - -NError::NError(int ePosix) : errno_(ePosix), errMsg_(strerror(errno_)) {} - -NError::NError(std::function()> errGen) -{ - tie(errno_, errMsg_) = errGen(); -} - -NError::operator bool() const -{ - return errno_ != ERRNO_NOERR; -} - -napi_value NError::GetNapiErr(napi_env env) -{ - napi_value code = NVal::CreateUTF8String(env, to_string(errno_)).val_; - napi_value msg = NVal::CreateUTF8String(env, errMsg_).val_; - - napi_value res = nullptr; - napi_status createRes = napi_create_error(env, code, msg, &res); - if (createRes) { - HILOGE("Failed to create an exception, msg = %{public}s", errMsg_.c_str()); - } - return res; -} - -void NError::ThrowErr(napi_env env, string errMsg) -{ - napi_value tmp = nullptr; - napi_get_and_clear_last_exception(env, &tmp); - // Note that ace engine cannot thow errors created by napi_create_error so far - napi_status throwStatus = napi_throw_error(env, nullptr, errMsg.c_str()); - if (throwStatus != napi_ok) { - HILOGE("Failed to throw an exception, %{public}d, code = %{public}s", throwStatus, errMsg.c_str()); - } -} - -void NError::ThrowErr(napi_env env) -{ - ThrowErr(env, errMsg_); -} -} // namespace LibN -} // namespace FileManagement -} // namespace OHOS \ No newline at end of file diff --git a/utils/filemgmt_libn/src/n_func_arg.cpp b/utils/filemgmt_libn/src/n_func_arg.cpp deleted file mode 100644 index 0e4fdfc..0000000 --- a/utils/filemgmt_libn/src/n_func_arg.cpp +++ /dev/null @@ -1,110 +0,0 @@ -/* - * 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 "n_func_arg.h" - -#include "n_error.h" -#include "filemgmt_libhilog.h" - -namespace OHOS { -namespace FileManagement { -namespace LibN { -using namespace std; - -NFuncArg::NFuncArg(napi_env env, napi_callback_info info) : env_(env), info_(info) {} - -NFuncArg::~NFuncArg() {} - -void NFuncArg::SetArgc(size_t argc) -{ - argc_ = argc; -} -void NFuncArg::SetThisVar(napi_value thisVar) -{ - thisVar_ = thisVar; -} - -size_t NFuncArg::GetArgc(void) const -{ - return argc_; -} - -napi_value NFuncArg::GetThisVar(void) const -{ - return thisVar_; -} - -napi_value NFuncArg::GetArg(size_t argPos) const -{ - return (argPos < GetArgc()) ? argv_[argPos] : nullptr; -} - -napi_value NFuncArg::operator[](size_t argPos) const -{ - return GetArg(argPos); -} - -bool NFuncArg::InitArgs(std::function argcChecker) -{ - SetArgc(0); - argv_.reset(); - - size_t argc; - napi_value thisVar; - napi_status status = napi_get_cb_info(env_, info_, &argc, nullptr, &thisVar, nullptr); - if (status != napi_ok) { - HILOGE("Cannot get num of func args for %{public}d", status); - return false; - } - if (argc) { - argv_ = make_unique(argc); - status = napi_get_cb_info(env_, info_, &argc, argv_.get(), &thisVar, nullptr); - if (status != napi_ok) { - HILOGE("Cannot get func args for %{public}d", status); - return false; - } - } - SetArgc(argc); - SetThisVar(thisVar); - - return argcChecker(); -} - -bool NFuncArg::InitArgs(size_t argc) -{ - return InitArgs([argc, this]() { - size_t realArgc = GetArgc(); - if (argc != realArgc) { - HILOGE("Num of args recved eq %zu while expecting %{public}zu", realArgc, argc); - return false; - } - return true; - }); -} - -bool NFuncArg::InitArgs(size_t minArgc, size_t maxArgc) -{ - return InitArgs([minArgc, maxArgc, this]() { - size_t realArgc = GetArgc(); - if (minArgc > realArgc || maxArgc < realArgc) { - HILOGE("Num of args recved eq %zu while expecting %{public}zu ~ %{public}zu", realArgc, minArgc, maxArgc); - return false; - } - return true; - }); -} -} // namespace LibN -} // namespace FileManagement -} // namespace OHOS diff --git a/utils/filemgmt_libn/src/n_val.cpp b/utils/filemgmt_libn/src/n_val.cpp deleted file mode 100644 index 2bb0c38..0000000 --- a/utils/filemgmt_libn/src/n_val.cpp +++ /dev/null @@ -1,325 +0,0 @@ -/* - * 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 "n_val.h" - -#include - -#include "n_error.h" -#include "filemgmt_libhilog.h" - -namespace OHOS { -namespace FileManagement { -namespace LibN { -using namespace std; - -NVal::NVal(napi_env nEnv, napi_value nVal = nullptr) : env_(nEnv), val_(nVal) {} - -NVal::operator bool() const -{ - return env_ && val_; -} - -bool NVal::TypeIs(napi_valuetype expType) const -{ - if (!*this) { - return false; - } - napi_valuetype valueType; - napi_typeof(env_, val_, &valueType); - - if (expType != valueType) { - return false; - } - return true; -} - -bool NVal::TypeIsError(bool checkErrno) const -{ - if (!*this) { - return false; - } - - bool res = false; - napi_is_error(env_, val_, &res); - - return res; -} - -tuple, size_t> NVal::ToUTF8String() const -{ - size_t strLen = 0; - napi_status status = napi_get_value_string_utf8(env_, val_, nullptr, -1, &strLen); - if (status != napi_ok) { - return {false, nullptr, 0}; - } - - size_t bufLen = strLen + 1; - unique_ptr str = make_unique(bufLen); - status = napi_get_value_string_utf8(env_, val_, str.get(), bufLen, &strLen); - return make_tuple(status == napi_ok, move(str), strLen); -} - -tuple, size_t> NVal::ToUTF16String() const -{ -#ifdef FILE_SUBSYSTEM_DEBUG_LOCAL - size_t strLen = 0; - napi_status status = napi_get_value_string_utf16(env_, val_, nullptr, -1, &strLen); - if (status != napi_ok) { - return {false, nullptr, 0}; - } - - auto str = make_unique(++strLen); - status = napi_get_value_string_utf16(env_, val_, str.get(), strLen, nullptr); - if (status != napi_ok) { - return {false, nullptr, 0}; - } - - strLen = reinterpret_cast(str.get() + strLen) - reinterpret_cast(str.get()); - auto strRet = unique_ptr(reinterpret_cast(str.release())); - return {true, move(strRet), strLen}; -#else - // Note that quickjs doesn't support utf16 - return ToUTF8String(); -#endif -} - -tuple NVal::ToPointer() const -{ - void *res = nullptr; - napi_status status = napi_get_value_external(env_, val_, &res); - return make_tuple(status == napi_ok, res); -} - -tuple NVal::ToBool() const -{ - bool flag = false; - napi_status status = napi_get_value_bool(env_, val_, &flag); - return make_tuple(status == napi_ok, flag); -} - -tuple NVal::ToInt32() const -{ - int32_t res = 0; - napi_status status = napi_get_value_int32(env_, val_, &res); - return make_tuple(status == napi_ok, res); -} - -tuple NVal::ToInt64() const -{ - int64_t res = 0; - napi_status status = napi_get_value_int64(env_, val_, &res); - return make_tuple(status == napi_ok, res); -} - -tuple NVal::ToDouble() const -{ - double res = 0; - napi_status status = napi_get_value_double(env_, val_, &res); - return make_tuple(status == napi_ok, res); -} - -tuple, uint32_t> NVal::ToStringArray() -{ - napi_status status; - uint32_t size; - status = napi_get_array_length(env_, val_, &size); - vector stringArray; - napi_value result; - for (uint32_t i = 0; i < size; i++) { - status = napi_get_element(env_, val_, i, &result); - auto [succ, str, ignore] = NVal(env_, result).ToUTF8String(); - stringArray.push_back(string(str.get())); - } - return make_tuple(status == napi_ok, stringArray, size); -} - -tuple NVal::ToArraybuffer() const -{ - void *buf = nullptr; - size_t bufLen = 0; - bool status = napi_get_arraybuffer_info(env_, val_, &buf, &bufLen); - return make_tuple(status == napi_ok, buf, bufLen); -} - -tuple NVal::ToTypedArray() const -{ - napi_typedarray_type type; - napi_value in_array_buffer = nullptr; - size_t byte_offset; - size_t length; - void *data = nullptr; - napi_status status = - napi_get_typedarray_info(env_, val_, &type, &length, (void **)&data, &in_array_buffer, &byte_offset); - return make_tuple(status == napi_ok, data, length); -} - -bool NVal::HasProp(string propName) const -{ - bool res = false; - - if (!env_ || !val_ || !TypeIs(napi_object)) - return false; - napi_status status = napi_has_named_property(env_, val_, propName.c_str(), &res); - return (status == napi_ok) && res; -} - -NVal NVal::GetProp(string propName) const -{ - if (!HasProp(propName)) { - return {env_, nullptr}; - } - napi_value prop = nullptr; - napi_status status = napi_get_named_property(env_, val_, propName.c_str(), &prop); - if (status != napi_ok) { - return {env_, nullptr}; - } - return NVal(env_, prop); -} - -bool NVal::AddProp(vector &&propVec) const -{ - if (!TypeIs(napi_valuetype::napi_object)) { - HILOGE("INNER BUG. Prop should only be added to objects"); - return false; - } - napi_status status = napi_define_properties(env_, val_, propVec.size(), propVec.data()); - if (status != napi_ok) { - HILOGE("INNER BUG. Cannot define properties because of %{public}d", status); - return false; - } - return true; -} - -bool NVal::AddProp(string propName, napi_value val) const -{ - if (!TypeIs(napi_valuetype::napi_object) || HasProp(propName)) { - HILOGE("INNER BUG. Prop should only be added to objects"); - return false; - } - - napi_status status = napi_set_named_property(env_, val_, propName.c_str(), val); - if (status != napi_ok) { - HILOGE("INNER BUG. Cannot set named property because of %{public}d", status); - return false; - } - return true; -} - -NVal NVal::CreateUndefined(napi_env env) -{ - napi_value res = nullptr; - napi_get_undefined(env, &res); - return {env, res}; -} - -NVal NVal::CreateInt64(napi_env env, int64_t val) -{ - napi_value res = nullptr; - napi_create_int64(env, val, &res); - return {env, res}; -} - -NVal NVal::CreateInt32(napi_env env, int32_t val) -{ - napi_value res = nullptr; - napi_create_int32(env, val, &res); - return {env, res}; -} - -NVal NVal::CreateObject(napi_env env) -{ - napi_value res = nullptr; - napi_create_object(env, &res); - return {env, res}; -} - -NVal NVal::CreateBool(napi_env env, bool val) -{ - napi_value res = nullptr; - napi_get_boolean(env, val, &res); - return {env, res}; -} - -NVal NVal::CreateUTF8String(napi_env env, std::string str) -{ - napi_value res = nullptr; - napi_create_string_utf8(env, str.c_str(), str.length(), &res); - return {env, res}; -} - -NVal NVal::CreateUTF8String(napi_env env, const char *str, ssize_t len) -{ - napi_value res = nullptr; - napi_create_string_utf8(env, str, len, &res); - return {env, res}; -} - -NVal NVal::CreateUint8Array(napi_env env, void *buf, size_t bufLen) -{ - napi_value output_buffer = nullptr; - napi_create_external_arraybuffer( - env, buf, bufLen, [](napi_env env, void *finalize_data, void *finalize_hint) { free(finalize_data); }, NULL, - &output_buffer); - napi_value output_array = nullptr; - napi_create_typedarray(env, napi_uint8_array, bufLen, output_buffer, 0, &output_array); - return {env, output_array}; -} - -tuple NVal::CreateArrayBuffer(napi_env env, size_t len) -{ - napi_value val; - void *buf = nullptr; - napi_create_arraybuffer(env, len, &buf, &val); - return {{env, val}, {buf}}; -} - -napi_property_descriptor NVal::DeclareNapiProperty(const char *name, napi_value val) -{ - return {(name), nullptr, nullptr, nullptr, nullptr, val, napi_default, nullptr}; -} - -napi_property_descriptor NVal::DeclareNapiStaticProperty(const char *name, napi_value val) -{ - return {(name), nullptr, nullptr, nullptr, nullptr, val, napi_static, nullptr}; -} - -napi_property_descriptor NVal::DeclareNapiFunction(const char *name, napi_callback func) -{ - return {(name), nullptr, (func), nullptr, nullptr, nullptr, napi_default, nullptr}; -} - -napi_property_descriptor NVal::DeclareNapiStaticFunction(const char *name, napi_callback func) -{ - return {(name), nullptr, (func), nullptr, nullptr, nullptr, napi_static, nullptr}; -} - -napi_property_descriptor NVal::DeclareNapiGetter(const char *name, napi_callback getter) -{ - return {(name), nullptr, nullptr, (getter), nullptr, nullptr, napi_default, nullptr}; -} - -napi_property_descriptor NVal::DeclareNapiSetter(const char *name, napi_callback setter) -{ - return {(name), nullptr, nullptr, nullptr, (setter), nullptr, napi_default, nullptr}; -} - -napi_property_descriptor NVal::DeclareNapiGetterSetter(const char *name, napi_callback getter, napi_callback setter) -{ - return {(name), nullptr, nullptr, (getter), (setter), nullptr, napi_default, nullptr}; -} -} // namespace LibN -} // namespace FileManagement -} // namespace OHOS \ No newline at end of file