diff --git a/interfaces/kits/napi/BUILD.gn b/interfaces/kits/napi/BUILD.gn new file mode 100644 index 0000000000000000000000000000000000000000..9904e359ab9ec57e2c0a9b5e31595c7cd59c11b0 --- /dev/null +++ b/interfaces/kits/napi/BUILD.gn @@ -0,0 +1,137 @@ +# 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/filemanagement/file_api/file_api.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", + "hiviewdfx_hilog_native:libhilog", + "ipc:ipc_core", + ] + subsystem_name = "filemanagement" + 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", + "hiviewdfx_hilog_native:libhilog", + "ipc:ipc_core", + "safwk:system_ability_fwk", + "samgr:samgr_proxy", + ] + subsystem_name = "filemanagement" + 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", + "hiviewdfx_hilog_native:libhilog", + "ipc:ipc_core", + "safwk:system_ability_fwk", + ] + subsystem_name = "filemanagement" + 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 new file mode 100644 index 0000000000000000000000000000000000000000..c5aae1548bf0240a16147f25ad208ca7700a55fa --- /dev/null +++ b/interfaces/kits/napi/common/ability_helper.cpp @@ -0,0 +1,54 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "ability_helper.h" + +#include "log.h" +#include "napi/n_func_arg.h" +#include "napi/uni_header.h" + +namespace OHOS { +namespace DistributedFS { +using namespace std; +using OHOS::AppExecFwk::Ability; +using OHOS::AppExecFwk::AbilityContext; + +Ability* AbilityHelper::GetJsAbility(napi_env env) +{ + napi_value global = nullptr; + napi_value abilityContext = nullptr; + + napi_status status = napi_get_global(env, &global); + if (status != napi_ok || global == nullptr) { + HILOGE("Cannot get global instance for %{public}d", status); + return nullptr; + } + + status = napi_get_named_property(env, global, "ability", &abilityContext); + if (status != napi_ok || abilityContext == nullptr) { + HILOGE("Cannot get ability context for %{public}d", status); + return nullptr; + } + + Ability *ability = nullptr; + status = napi_get_value_external(env, abilityContext, (void **)&ability); + if (status != napi_ok || ability == nullptr) { + HILOGE("Get ability form property failed for %{public}d", status); + } + + return ability; +} +} // namespace DistributedFS +} // namespace OHOS \ No newline at end of file diff --git a/interfaces/kits/napi/common/ability_helper.h b/interfaces/kits/napi/common/ability_helper.h new file mode 100644 index 0000000000000000000000000000000000000000..0b93a005e07217ad4858ccbe471f340550c58ad0 --- /dev/null +++ b/interfaces/kits/napi/common/ability_helper.h @@ -0,0 +1,29 @@ +/* + * 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 new file mode 100644 index 0000000000000000000000000000000000000000..ac022f5722fd7d3e69a6deee01d5611aeb2483ca --- /dev/null +++ b/interfaces/kits/napi/common/common_func.cpp @@ -0,0 +1,57 @@ +/* + * 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 new file mode 100644 index 0000000000000000000000000000000000000000..2a3553e9f262b249c9507203605818c1e90bb967 --- /dev/null +++ b/interfaces/kits/napi/common/common_func.h @@ -0,0 +1,34 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#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 new file mode 100644 index 0000000000000000000000000000000000000000..a5f3bce41f4d0c5e018a75b0c0e60cb81aea2da9 --- /dev/null +++ b/interfaces/kits/napi/common/log.h @@ -0,0 +1,92 @@ +/* + * 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_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, "file_api" }; + +#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 new file mode 100644 index 0000000000000000000000000000000000000000..a9cdff36e71535f9f231aee2ade0ec78aa2885e2 --- /dev/null +++ b/interfaces/kits/napi/common/napi/n_class.cpp @@ -0,0 +1,100 @@ +/* + * 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 new file mode 100644 index 0000000000000000000000000000000000000000..55c97d55db6da4331a74188a25c3614ac53fbae4 --- /dev/null +++ b/interfaces/kits/napi/common/napi/n_class.h @@ -0,0 +1,81 @@ +/* + * 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 new file mode 100644 index 0000000000000000000000000000000000000000..5f1b951636c183ad638ce4fa8fae5e8bd1538b2d --- /dev/null +++ b/interfaces/kits/napi/common/napi/n_exporter.h @@ -0,0 +1,40 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef 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 new file mode 100644 index 0000000000000000000000000000000000000000..5200ebd6047bfb7088cda22c73bf9a0661073f03 --- /dev/null +++ b/interfaces/kits/napi/common/napi/n_func_arg.cpp @@ -0,0 +1,107 @@ +/* + * 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 new file mode 100644 index 0000000000000000000000000000000000000000..e1fba21188692452e3dd8684c2d2fb117cab03b9 --- /dev/null +++ b/interfaces/kits/napi/common/napi/n_func_arg.h @@ -0,0 +1,69 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef 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 new file mode 100644 index 0000000000000000000000000000000000000000..5c28576b02f778f11aebe1ce611282720fdd1d69 --- /dev/null +++ b/interfaces/kits/napi/common/napi/n_val.cpp @@ -0,0 +1,280 @@ +/* + * 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 new file mode 100644 index 0000000000000000000000000000000000000000..e23a4c65e70825544adefc1e773c753b2f07abf2 --- /dev/null +++ b/interfaces/kits/napi/common/napi/n_val.h @@ -0,0 +1,79 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#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 new file mode 100644 index 0000000000000000000000000000000000000000..b764aae19a1bb1348e174f71e1293550e807e57d --- /dev/null +++ b/interfaces/kits/napi/common/napi/uni_header.h @@ -0,0 +1,25 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef 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 new file mode 100644 index 0000000000000000000000000000000000000000..295b2865459191b92afda6ce447bba5da2837c44 --- /dev/null +++ b/interfaces/kits/napi/common/uni_error.cpp @@ -0,0 +1,118 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "uni_error.h" + +#include +#include + +#include "log.h" +#include "napi/n_val.h" + +namespace OHOS { +namespace DistributedFS { +using namespace std; + +UniError::UniError() {} + +UniError::UniError(ELegacy eLegacy) : errno_(eLegacy), codingSystem_(ERR_CODE_SYSTEM_LEGACY) {} + +UniError::UniError(int ePosix) : errno_(ePosix), codingSystem_(ERR_CODE_SYSTEM_POSIX) {} + +UniError::operator bool() const +{ + return errno_ != ERRNO_NOERR; +} + +int UniError::GetErrno(ErrCodeSystem cs) +{ + if (errno_ == ERRNO_NOERR) { + return ERRNO_NOERR; + } + if (cs == codingSystem_) { + return errno_; + } + + if (cs == ERR_CODE_SYSTEM_POSIX) { + // Note that we should support more codes here + return EINVAL; + } + + // Note that this shall be done properly + return ELEGACY_INVAL; +} + +void UniError::SetErrno(ELegacy eLegacy) +{ + errno_ = eLegacy; + codingSystem_ = ERR_CODE_SYSTEM_LEGACY; +} + +void UniError::SetErrno(int ePosix) +{ + errno_ = ePosix; + codingSystem_ = ERR_CODE_SYSTEM_POSIX; +} + +std::string UniError::GetDefaultErrstr() +{ + if (codingSystem_ != ERR_CODE_SYSTEM_POSIX && codingSystem_ != ERR_CODE_SYSTEM_LEGACY) { + return "BUG: Curious coding system"; + } + return strerror(GetErrno(ERR_CODE_SYSTEM_POSIX)); +} + +napi_value UniError::GetNapiErr(napi_env env) +{ + return GetNapiErr(env, GetDefaultErrstr()); +} + +napi_value UniError::GetNapiErr(napi_env env, string errMsg) +{ + napi_value code = NVal::CreateUTF8String(env, to_string(GetErrno(codingSystem_))).val_; + napi_value msg = NVal::CreateUTF8String(env, errMsg).val_; + + napi_value res = nullptr; + napi_status createRes = napi_create_error(env, code, msg, &res); + if (createRes) { + HILOGE("Failed to create an exception, msg = %{public}s", errMsg.c_str()); + } + return res; +} + +void UniError::ThrowErr(napi_env env) +{ + string msg = GetDefaultErrstr(); + napi_value tmp = nullptr; + napi_get_and_clear_last_exception(env, &tmp); + // Note that ace engine cannot 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 new file mode 100644 index 0000000000000000000000000000000000000000..2f20d1cb1d28e37ba39a1f480c6779297eddc1f5 --- /dev/null +++ b/interfaces/kits/napi/common/uni_error.h @@ -0,0 +1,60 @@ +/* + * 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 new file mode 100644 index 0000000000000000000000000000000000000000..5b38a92c63fbbe0acb8b976c05fd33559eeb5895 --- /dev/null +++ b/interfaces/kits/napi/device_storage_manager/device_sm_exporter.cpp @@ -0,0 +1,1017 @@ +/* + * 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 new file mode 100644 index 0000000000000000000000000000000000000000..457931d4fbd8d5918322a4f0f31f07c4da463699 --- /dev/null +++ b/interfaces/kits/napi/device_storage_manager/device_sm_exporter.h @@ -0,0 +1,56 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +#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 new file mode 100644 index 0000000000000000000000000000000000000000..09c58744f579169666137ed83fb33433476e8e99 --- /dev/null +++ b/interfaces/kits/napi/device_storage_manager/module.cpp @@ -0,0 +1,47 @@ +/* + * 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 new file mode 100644 index 0000000000000000000000000000000000000000..20bb9f509f6393c046db41933c01cbf77194e82b --- /dev/null +++ b/interfaces/kits/napi/device_storage_manager/module.h @@ -0,0 +1,18 @@ +/* + * 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 new file mode 100644 index 0000000000000000000000000000000000000000..efe696c06076cfeea4941c5ed5b5a0f2dbd047ad --- /dev/null +++ b/interfaces/kits/napi/file_picker_service/file_picker_exporter.cpp @@ -0,0 +1,478 @@ +/* + * 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 "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 = dynamic_castdata; + 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 = dynamic_castdata; + 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 = dynamic_castdata; + 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 = dynamic_castdata; + 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 = dynamic_castdata; + 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 = dynamic_castdata; + 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 = dynamic_castdata; + 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 = dynamic_castdata; + 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 new file mode 100644 index 0000000000000000000000000000000000000000..31bd97abc36640ad3564d65790fe1e41560e939d --- /dev/null +++ b/interfaces/kits/napi/file_picker_service/file_picker_exporter.h @@ -0,0 +1,96 @@ +/* + * 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 new file mode 100644 index 0000000000000000000000000000000000000000..0acd1ca3a81161892ffcde986a2a56685dcfd802 --- /dev/null +++ b/interfaces/kits/napi/file_picker_service/module.cpp @@ -0,0 +1,48 @@ +/* + * 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 new file mode 100644 index 0000000000000000000000000000000000000000..d92e88741324dca40277e18818dc09f504f18f8f --- /dev/null +++ b/interfaces/kits/napi/file_picker_service/module.h @@ -0,0 +1,18 @@ +/* + * 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 new file mode 100644 index 0000000000000000000000000000000000000000..50e846daa8b2b5363b66d4d1dcc1a6f85a448192 --- /dev/null +++ b/interfaces/kits/napi/file_share_ability/file_share_exporter.cpp @@ -0,0 +1,278 @@ +/* + * 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 new file mode 100644 index 0000000000000000000000000000000000000000..27229812b29ec86bad9ae53fc2d09e183ebaedc6 --- /dev/null +++ b/interfaces/kits/napi/file_share_ability/file_share_exporter.h @@ -0,0 +1,41 @@ +/* + * 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 new file mode 100644 index 0000000000000000000000000000000000000000..25c1336a4437520d85a6b51be6b08351c7cb4f63 --- /dev/null +++ b/interfaces/kits/napi/file_share_ability/module.cpp @@ -0,0 +1,48 @@ +/* + * 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 new file mode 100644 index 0000000000000000000000000000000000000000..a287cb5c955d4302b038dcf69577fca9bd75b742 --- /dev/null +++ b/interfaces/kits/napi/file_share_ability/module.h @@ -0,0 +1,18 @@ +/* + * 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