diff --git a/interfaces/kits/js/cloudfilesync/BUILD.gn b/interfaces/kits/js/cloudfilesync/BUILD.gn index 55950f66c31de754eacc831fc7c37a087170d075..46372e32e59ecd8d7abf7fda143ccb8ca8aae376 100644 --- a/interfaces/kits/js/cloudfilesync/BUILD.gn +++ b/interfaces/kits/js/cloudfilesync/BUILD.gn @@ -23,8 +23,12 @@ ohos_shared_library("cloudsync") { } sources = [ + "cloud_file_cache_napi.cpp", "cloud_file_download_napi.cpp", + "cloud_file_napi.cpp", "cloud_sync_n_exporter.cpp", + "cloud_sync_napi.cpp", + "file_sync_napi.cpp", "gallery_sync_napi.cpp", ] deps = [ diff --git a/interfaces/kits/js/cloudfilesync/cloud_file_cache_napi.cpp b/interfaces/kits/js/cloudfilesync/cloud_file_cache_napi.cpp new file mode 100644 index 0000000000000000000000000000000000000000..1229654ce15a4815512f58fcbf9ae380f71f26f2 --- /dev/null +++ b/interfaces/kits/js/cloudfilesync/cloud_file_cache_napi.cpp @@ -0,0 +1,84 @@ +/* + * Copyright (c) 2023 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT 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 "cloud_file_cache_napi.h" + +#include + +#include "async_work.h" +#include "cloud_sync_manager.h" +#include "dfs_error.h" +#include "utils_log.h" +#include "uv.h" + +namespace OHOS::FileManagement::CloudSync { +using namespace FileManagement::LibN; +using namespace std; + +napi_value CloudFileCacheNapi::CleanCache(napi_env env, napi_callback_info info) +{ + LOGI("CleanCache start"); + NFuncArg funcArg(env, info); + + if (!funcArg.InitArgs(NARG_CNT::ONE)) { + NError(E_PARAMS).ThrowErr(env); + return nullptr; + } + + auto [succ, uri, ignore] = NVal(env, funcArg[NARG_POS::FIRST]).ToUTF8String(); + if (!succ) { + LOGE("Get uri Error"); + NError(EINVAL).ThrowErr(env); + return nullptr; + } + + auto cbExec = [uri_ = std::string(uri.get())]() -> NError { + std::string accountId = uri_; + CleanOptions cleanOptions; + int32_t ret = CloudSyncManager::GetInstance().Clean(accountId, cleanOptions); + if (ret != E_OK) { + LOGE("Clean error, result: %{public}d", ret); + return NError(Convert2JsErrNum(ret)); + } + LOGI("CleanCache Success"); + return NError(ERRNO_NOERR); + }; + + auto cbComplete = [](napi_env env, NError err) -> NVal { + if (err) { + return {env, err.GetNapiErr(env)}; + } + return NVal::CreateUndefined(env); + }; + + std::string procedureName = "cleanCache"; + auto asyncWork = GetPromiseOrCallBackWork(env, funcArg, static_cast(NARG_CNT::TWO)); + return asyncWork == nullptr ? nullptr : asyncWork->Schedule(procedureName, cbExec, cbComplete).val_; +} + +bool CloudFileCacheNapi::Export() +{ + std::vector props = { + NVal::DeclareNapiFunction("on", CloudFileCacheNapi::On), + NVal::DeclareNapiFunction("off", CloudFileCacheNapi::Off), + NVal::DeclareNapiFunction("start", CloudFileCacheNapi::Start), + NVal::DeclareNapiFunction("stop", CloudFileCacheNapi::Stop), + NVal::DeclareNapiFunction("cleanCache", CloudFileCacheNapi::CleanCache), + }; + + SetClassName("CloudFileCache"); + return ToExport(props); +} +} // namespace OHOS::FileManagement::CloudSync \ No newline at end of file diff --git a/interfaces/kits/js/cloudfilesync/cloud_file_cache_napi.h b/interfaces/kits/js/cloudfilesync/cloud_file_cache_napi.h new file mode 100644 index 0000000000000000000000000000000000000000..a97b38dd0cb62780a0847a9d80811d3674a07cb6 --- /dev/null +++ b/interfaces/kits/js/cloudfilesync/cloud_file_cache_napi.h @@ -0,0 +1,35 @@ +/* + * Copyright (c) 2023 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT 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 OHOS_FILEMGMT_CLOUD_FILE_CACHE_NAPI_H +#define OHOS_FILEMGMT_CLOUD_FILE_CACHE_NAPI_H + +#include "cloud_download_callback.h" +#include "cloud_file_napi.h" +#include "filemgmt_libn.h" + +namespace OHOS::FileManagement::CloudSync { + +class CloudDownloadCallbackImpl; +class CloudFileCacheNapi final : public CloudFileNapi { +public: + CloudFileCacheNapi(napi_env env, napi_value exports) : CloudFileNapi(env, exports) {} + ~CloudFileCacheNapi() = default; + + bool Export() override; + static napi_value CleanCache(napi_env env, napi_callback_info info); +}; +} // namespace OHOS::FileManagement::CloudSync +#endif // OHOS_FILEMGMT_CLOUD_FILE_DOWNLOAD_NAPI_H \ No newline at end of file diff --git a/interfaces/kits/js/cloudfilesync/cloud_file_download_napi.cpp b/interfaces/kits/js/cloudfilesync/cloud_file_download_napi.cpp index 6c7a6bd6f4de945f7cce14fe1400977ac3170401..be31b237bab4376a7ce03d83bc168262a12b41a2 100644 --- a/interfaces/kits/js/cloudfilesync/cloud_file_download_napi.cpp +++ b/interfaces/kits/js/cloudfilesync/cloud_file_download_napi.cpp @@ -26,289 +26,14 @@ namespace OHOS::FileManagement::CloudSync { using namespace FileManagement::LibN; using namespace std; -const int32_t ARGS_ONE = 1; - -CloudFileDownloadNapi::CloudFileDownloadNapi(napi_env env, napi_value exports) : NExporter(env, exports) {} - -CloudFileDownloadNapi::~CloudFileDownloadNapi() {} - -napi_value CloudFileDownloadNapi::Constructor(napi_env env, napi_callback_info info) -{ - LOGI("CloudFileDownloadNapi::Constructor begin"); - NFuncArg funcArg(env, info); - if (!funcArg.InitArgs(NARG_CNT::ZERO)) { - LOGE("Start Number of arguments unmatched"); - NError(E_PARAMS).ThrowErr(env); - return nullptr; - } - - LOGI("CloudFileDownloadNapi::Constructor end"); - return funcArg.GetThisVar(); -} - -napi_value CloudFileDownloadNapi::Start(napi_env env, napi_callback_info info) -{ - LOGI("Start begin"); - NFuncArg funcArg(env, info); - if (!funcArg.InitArgs(NARG_CNT::ONE, NARG_CNT::TWO)) { - LOGE("Start Number of arguments unmatched"); - NError(E_PARAMS).ThrowErr(env); - return nullptr; - } - auto [succUri, uri, ignore] = NVal(env, funcArg[NARG_POS::FIRST]).ToUTF8String(); - if (!succUri) { - LOGE("Start get uri parameter failed!"); - NError(E_PARAMS).ThrowErr(env); - return nullptr; - } - - auto cbExec = [uri = string(uri.get()), env = env]() -> NError { - int32_t ret = CloudSyncManager::GetInstance().StartDownloadFile(uri); - if (ret != E_OK) { - LOGE("Start Download failed! ret = %{public}d", ret); - return NError(Convert2JsErrNum(ret)); - } - LOGI("Start Download Success!"); - return NError(ERRNO_NOERR); - }; - - auto cbCompl = [](napi_env env, NError err) -> NVal { - if (err) { - return {env, err.GetNapiErr(env)}; - } - return NVal::CreateUndefined(env); - }; - - string procedureName = "cloudFileDownload"; - auto asyncWork = GetPromiseOrCallBackWork(env, funcArg, static_cast(NARG_CNT::TWO)); - return asyncWork == nullptr ? nullptr : asyncWork->Schedule(procedureName, cbExec, cbCompl).val_; -} - -CloudDownloadCallbackImpl::CloudDownloadCallbackImpl(napi_env env, napi_value fun) : env_(env) -{ - if (fun != nullptr) { - napi_create_reference(env_, fun, 1, &cbOnRef_); - } -} - -void CloudDownloadCallbackImpl::OnComplete(UvChangeMsg *msg) -{ - auto downloadcCallback = msg->CloudDownloadCallback_.lock(); - if (downloadcCallback == nullptr || downloadcCallback->cbOnRef_ == nullptr) { - LOGE("downloadcCallback->cbOnRef_ is nullptr"); - return; - } - auto env = downloadcCallback->env_; - auto ref = downloadcCallback->cbOnRef_; - napi_handle_scope scope = nullptr; - napi_open_handle_scope(env, &scope); - napi_value jsCallback = nullptr; - napi_status status = napi_get_reference_value(env, ref, &jsCallback); - if (status != napi_ok) { - LOGE("Create reference failed, status: %{public}d", status); - napi_close_handle_scope(env, scope); - return; - } - NVal obj = NVal::CreateObject(env); - obj.AddProp("state", NVal::CreateInt32(env, (int32_t)msg->downloadProgress_.state).val_); - obj.AddProp("processed", NVal::CreateInt64(env, (int64_t)msg->downloadProgress_.downloadedSize).val_); - obj.AddProp("size", NVal::CreateInt64(env, (int64_t)msg->downloadProgress_.totalSize).val_); - obj.AddProp("uri", NVal::CreateUTF8String(env, msg->downloadProgress_.path).val_); - napi_value retVal = nullptr; - napi_value global = nullptr; - napi_get_global(env, &global); - status = napi_call_function(env, global, jsCallback, ARGS_ONE, &(obj.val_), &retVal); - if (status != napi_ok) { - LOGE("napi call function failed, status: %{public}d", status); - } - napi_close_handle_scope(env, scope); -} - -void CloudDownloadCallbackImpl::OnDownloadProcess(DownloadProgressObj &progress) -{ - uv_loop_s *loop = nullptr; - napi_get_uv_event_loop(env_, &loop); - if (loop == nullptr) { - return; - } - - uv_work_t *work = new (nothrow) uv_work_t; - if (work == nullptr) { - LOGE("Failed to create uv work"); - return; - } - - UvChangeMsg *msg = new (std::nothrow) UvChangeMsg(shared_from_this(), progress); - if (msg == nullptr) { - delete work; - return; - } - work->data = reinterpret_cast(msg); - int ret = uv_queue_work( - loop, work, [](uv_work_t *work) {}, - [](uv_work_t *work, int status) { - auto msg = reinterpret_cast(work->data); - OnComplete(msg); - delete msg; - delete work; - }); - if (ret != 0) { - LOGE("Failed to execute libuv work queue, ret: %{public}d", ret); - delete msg; - delete work; - } -} - -void CloudDownloadCallbackImpl::DeleteReference() -{ - if (cbOnRef_ != nullptr) { - napi_delete_reference(env_, cbOnRef_); - cbOnRef_ = nullptr; - } -} - -napi_value CloudFileDownloadNapi::On(napi_env env, napi_callback_info info) -{ - LOGI("On begin"); - NFuncArg funcArg(env, info); - if (!funcArg.InitArgs(NARG_CNT::TWO)) { - LOGE("On Number of arguments unmatched"); - NError(E_PARAMS).ThrowErr(env); - return nullptr; - } - auto [succProgress, progress, ignore] = NVal(env, funcArg[NARG_POS::FIRST]).ToUTF8String(); - if (!(succProgress && std::string(progress.get()) == "progress")) { - LOGE("On get progress failed!"); - NError(E_PARAMS).ThrowErr(env); - return nullptr; - } - - if (!NVal(env, funcArg[NARG_POS::SECOND]).TypeIs(napi_function)) { - LOGE("Argument type mismatch"); - NError(E_PARAMS).ThrowErr(env); - return nullptr; - } - - if (callback_ != nullptr) { - LOGI("callback already exist"); - return NVal::CreateUndefined(env).val_; - } - - callback_ = make_shared(env, NVal(env, funcArg[(int)NARG_POS::SECOND]).val_); - int32_t ret = CloudSyncManager::GetInstance().RegisterDownloadFileCallback(callback_); - if (ret != E_OK) { - LOGE("RegisterDownloadFileCallback error, ret: %{public}d", ret); - NError(Convert2JsErrNum(ret)).ThrowErr(env); - return nullptr; - } - - return NVal::CreateUndefined(env).val_; -} - -napi_value CloudFileDownloadNapi::Off(napi_env env, napi_callback_info info) -{ - LOGI("Off begin"); - NFuncArg funcArg(env, info); - if (!funcArg.InitArgs(NARG_CNT::ONE, NARG_CNT::TWO)) { - LOGE("Off Number of arguments unmatched"); - NError(E_PARAMS).ThrowErr(env); - return nullptr; - } - auto [succProgress, progress, ignore] = NVal(env, funcArg[NARG_POS::FIRST]).ToUTF8String(); - if (!(succProgress && std::string(progress.get()) == "progress")) { - LOGE("Off get progress failed!"); - NError(E_PARAMS).ThrowErr(env); - return nullptr; - } - - if (funcArg.GetArgc() == (uint)NARG_CNT::TWO &&!NVal(env, funcArg[NARG_POS::SECOND]).TypeIs(napi_function)) { - LOGE("Argument type mismatch"); - NError(E_PARAMS).ThrowErr(env); - return nullptr; - } - - int32_t ret = CloudSyncManager::GetInstance().UnregisterDownloadFileCallback(); - if (ret != E_OK) { - LOGE("UnregisterDownloadFileCallback error, ret: %{public}d", ret); - NError(Convert2JsErrNum(ret)).ThrowErr(env); - return nullptr; - } - if (callback_ != nullptr) { - /* napi delete reference */ - callback_->DeleteReference(); - callback_ = nullptr; - } - return NVal::CreateUndefined(env).val_; -} - -napi_value CloudFileDownloadNapi::Stop(napi_env env, napi_callback_info info) -{ - LOGI("Stop begin"); - NFuncArg funcArg(env, info); - if (!funcArg.InitArgs(NARG_CNT::ONE, NARG_CNT::TWO)) { - LOGE("Stop Number of arguments unmatched"); - NError(E_PARAMS).ThrowErr(env); - return nullptr; - } - auto [succUri, uri, ignore] = NVal(env, funcArg[NARG_POS::FIRST]).ToUTF8String(); - if (!succUri) { - LOGE("Stop get uri parameter failed!"); - NError(E_PARAMS).ThrowErr(env); - return nullptr; - } - - auto cbExec = [uri = string(uri.get()), env = env]() -> NError { - int32_t ret = CloudSyncManager::GetInstance().StopDownloadFile(uri); - if (ret != E_OK) { - LOGE("Stop Download failed! ret = %{public}d", ret); - return NError(Convert2JsErrNum(ret)); - } - LOGI("Stop Download Success!"); - return NError(ERRNO_NOERR); - }; - - auto cbCompl = [](napi_env env, NError err) -> NVal { - if (err) { - return {env, err.GetNapiErr(env)}; - } - return NVal::CreateUndefined(env); - }; - - string procedureName = "cloudFileDownload"; - auto asyncWork = GetPromiseOrCallBackWork(env, funcArg, static_cast(NARG_CNT::TWO)); - return asyncWork == nullptr ? nullptr : asyncWork->Schedule(procedureName, cbExec, cbCompl).val_; -} bool CloudFileDownloadNapi::Export() { - LOGI("CloudFileDownloadNapi::Export begin"); - vector props = { - NVal::DeclareNapiFunction("start", CloudFileDownloadNapi::Start), - NVal::DeclareNapiFunction("on", CloudFileDownloadNapi::On), - NVal::DeclareNapiFunction("off", CloudFileDownloadNapi::Off), - NVal::DeclareNapiFunction("stop", CloudFileDownloadNapi::Stop), - }; - - auto [succ, classValue] = - NClass::DefineClass(exports_.env_, className, CloudFileDownloadNapi::Constructor, std::move(props)); - if (!succ) { - LOGE("Failed to define Download class"); - NError(EIO).ThrowErr(exports_.env_); - return false; - } - succ = NClass::SaveClass(exports_.env_, className, classValue); - if (!succ) { - LOGE("Failed to save Download class"); - NError(EIO).ThrowErr(exports_.env_); + SetClassName("Download"); + bool success = CloudFileNapi::Export(); + if (!success) { return false; } - - LOGI("CloudFileDownloadNapi::Export end"); - return exports_.AddProp(className, classValue); -} - -string CloudFileDownloadNapi::GetClassName() -{ - return CloudFileDownloadNapi::className; + return true; } } // namespace OHOS::FileManagement::CloudSync \ No newline at end of file diff --git a/interfaces/kits/js/cloudfilesync/cloud_file_download_napi.h b/interfaces/kits/js/cloudfilesync/cloud_file_download_napi.h index 396310506fa9e3b9ac8d8f54236b6e23ede82555..857eae756f1173bb6fb96c4afec60c9866b69eee 100644 --- a/interfaces/kits/js/cloudfilesync/cloud_file_download_napi.h +++ b/interfaces/kits/js/cloudfilesync/cloud_file_download_napi.h @@ -17,53 +17,18 @@ #define OHOS_FILEMGMT_CLOUD_FILE_DOWNLOAD_NAPI_H #include "cloud_download_callback.h" +#include "cloud_file_napi.h" #include "filemgmt_libn.h" namespace OHOS::FileManagement::CloudSync { class CloudDownloadCallbackImpl; -class CloudFileDownloadNapi final : public LibN::NExporter { +class CloudFileDownloadNapi final : public CloudFileNapi { public: - CloudFileDownloadNapi(napi_env env, napi_value exports); - ~CloudFileDownloadNapi() override; + CloudFileDownloadNapi(napi_env env, napi_value exports) : CloudFileNapi(env, exports) {} + ~CloudFileDownloadNapi() = default; bool Export() override; - std::string GetClassName() override; - static napi_value Constructor(napi_env env, napi_callback_info info); - static napi_value Start(napi_env env, napi_callback_info info); - static napi_value On(napi_env env, napi_callback_info info); - static napi_value Off(napi_env env, napi_callback_info info); - static napi_value Stop(napi_env env, napi_callback_info info); - -private: - static inline std::shared_ptr callback_; - inline static const std::string className = "Download"; -}; - -class CloudDownloadCallbackImpl : public CloudDownloadCallback, - public std::enable_shared_from_this { -public: - CloudDownloadCallbackImpl(napi_env env, napi_value fun); - ~CloudDownloadCallbackImpl() = default; - void OnDownloadProcess(DownloadProgressObj &progress) override; - void DeleteReference(); - - class UvChangeMsg { - public: - UvChangeMsg(std::shared_ptr CloudDownloadCallbackIn, - DownloadProgressObj downloadProgress) - : CloudDownloadCallback_(CloudDownloadCallbackIn), downloadProgress_(downloadProgress) - { - } - ~UvChangeMsg() {} - std::weak_ptr CloudDownloadCallback_; - DownloadProgressObj downloadProgress_; - }; - -private: - static void OnComplete(UvChangeMsg *msg); - napi_env env_; - napi_ref cbOnRef_ = nullptr; }; } // namespace OHOS::FileManagement::CloudSync #endif // OHOS_FILEMGMT_CLOUD_FILE_DOWNLOAD_NAPI_H \ No newline at end of file diff --git a/interfaces/kits/js/cloudfilesync/cloud_file_napi.cpp b/interfaces/kits/js/cloudfilesync/cloud_file_napi.cpp new file mode 100644 index 0000000000000000000000000000000000000000..b1ab4680dca49ee7a38a567634eddecd85d6b33c --- /dev/null +++ b/interfaces/kits/js/cloudfilesync/cloud_file_napi.cpp @@ -0,0 +1,322 @@ +/* + * Copyright (c) 2023 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT 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 "cloud_file_download_napi.h" + +#include + +#include "cloud_sync_manager.h" +#include "cloud_file_napi.h" +#include "dfs_error.h" +#include "utils_log.h" +#include "async_work.h" +#include "uv.h" + +namespace OHOS::FileManagement::CloudSync { +using namespace FileManagement::LibN; +using namespace std; +const int32_t ARGS_ONE = 1; + +CloudFileNapi::CloudFileNapi(napi_env env, napi_value exports) : NExporter(env, exports) {} + +napi_value CloudFileNapi::Constructor(napi_env env, napi_callback_info info) +{ + LOGI("CloudFileNapi::Constructor begin"); + NFuncArg funcArg(env, info); + if (!funcArg.InitArgs(NARG_CNT::ZERO)) { + LOGE("Start Number of arguments unmatched"); + NError(E_PARAMS).ThrowErr(env); + return nullptr; + } + + LOGI("CloudFileNapi::Constructor end"); + return funcArg.GetThisVar(); +} + +napi_value CloudFileNapi::Start(napi_env env, napi_callback_info info) +{ + LOGI("Start begin"); + NFuncArg funcArg(env, info); + if (!funcArg.InitArgs(NARG_CNT::ONE, NARG_CNT::TWO)) { + LOGE("Start Number of arguments unmatched"); + NError(E_PARAMS).ThrowErr(env); + return nullptr; + } + auto [succUri, uri, ignore] = NVal(env, funcArg[NARG_POS::FIRST]).ToUTF8String(); + if (!succUri) { + LOGE("Start get uri parameter failed!"); + NError(E_PARAMS).ThrowErr(env); + return nullptr; + } + + auto cbExec = [uri = string(uri.get()), env = env]() -> NError { + int32_t ret = CloudSyncManager::GetInstance().StartDownloadFile(uri); + if (ret != E_OK) { + LOGE("Start Download failed! ret = %{public}d", ret); + return NError(Convert2JsErrNum(ret)); + } + LOGI("Start Download Success!"); + return NError(ERRNO_NOERR); + }; + + auto cbCompl = [](napi_env env, NError err) -> NVal { + if (err) { + return {env, err.GetNapiErr(env)}; + } + return NVal::CreateUndefined(env); + }; + + string procedureName = "cloudFileDownload"; + auto asyncWork = GetPromiseOrCallBackWork(env, funcArg, static_cast(NARG_CNT::TWO)); + return asyncWork == nullptr ? nullptr : asyncWork->Schedule(procedureName, cbExec, cbCompl).val_; +} + +CloudDownloadCallbackImpl::CloudDownloadCallbackImpl(napi_env env, napi_value fun) : env_(env) +{ + if (fun != nullptr) { + napi_create_reference(env_, fun, 1, &cbOnRef_); + } +} + +void CloudDownloadCallbackImpl::OnComplete(UvChangeMsg *msg) +{ + auto downloadcCallback = msg->CloudDownloadCallback_.lock(); + if (downloadcCallback == nullptr || downloadcCallback->cbOnRef_ == nullptr) { + LOGE("downloadcCallback->cbOnRef_ is nullptr"); + return; + } + auto env = downloadcCallback->env_; + auto ref = downloadcCallback->cbOnRef_; + napi_handle_scope scope = nullptr; + napi_open_handle_scope(env, &scope); + napi_value jsCallback = nullptr; + napi_status status = napi_get_reference_value(env, ref, &jsCallback); + if (status != napi_ok) { + LOGE("Create reference failed, status: %{public}d", status); + napi_close_handle_scope(env, scope); + return; + } + NVal obj = NVal::CreateObject(env); + obj.AddProp("state", NVal::CreateInt32(env, (int32_t)msg->downloadProgress_.state).val_); + obj.AddProp("processed", NVal::CreateInt64(env, (int64_t)msg->downloadProgress_.downloadedSize).val_); + obj.AddProp("size", NVal::CreateInt64(env, (int64_t)msg->downloadProgress_.totalSize).val_); + obj.AddProp("uri", NVal::CreateUTF8String(env, msg->downloadProgress_.path).val_); + napi_value retVal = nullptr; + napi_value global = nullptr; + napi_get_global(env, &global); + status = napi_call_function(env, global, jsCallback, ARGS_ONE, &(obj.val_), &retVal); + if (status != napi_ok) { + LOGE("napi call function failed, status: %{public}d", status); + } + napi_close_handle_scope(env, scope); +} + +void CloudDownloadCallbackImpl::OnDownloadProcess(DownloadProgressObj &progress) +{ + uv_loop_s *loop = nullptr; + napi_get_uv_event_loop(env_, &loop); + if (loop == nullptr) { + return; + } + + uv_work_t *work = new (nothrow) uv_work_t; + if (work == nullptr) { + LOGE("Failed to create uv work"); + return; + } + + UvChangeMsg *msg = new (std::nothrow) UvChangeMsg(shared_from_this(), progress); + if (msg == nullptr) { + delete work; + return; + } + work->data = reinterpret_cast(msg); + int ret = uv_queue_work( + loop, work, [](uv_work_t *work) {}, + [](uv_work_t *work, int status) { + auto msg = reinterpret_cast(work->data); + OnComplete(msg); + delete msg; + delete work; + }); + if (ret != 0) { + LOGE("Failed to execute libuv work queue, ret: %{public}d", ret); + delete msg; + delete work; + } +} + +void CloudDownloadCallbackImpl::DeleteReference() +{ + if (cbOnRef_ != nullptr) { + napi_delete_reference(env_, cbOnRef_); + cbOnRef_ = nullptr; + } +} + +napi_value CloudFileNapi::On(napi_env env, napi_callback_info info) +{ + LOGI("On begin"); + NFuncArg funcArg(env, info); + if (!funcArg.InitArgs(NARG_CNT::TWO)) { + LOGE("On Number of arguments unmatched"); + NError(E_PARAMS).ThrowErr(env); + return nullptr; + } + auto [succProgress, progress, ignore] = NVal(env, funcArg[NARG_POS::FIRST]).ToUTF8String(); + if (!(succProgress && std::string(progress.get()) == "progress")) { + LOGE("On get progress failed!"); + NError(E_PARAMS).ThrowErr(env); + return nullptr; + } + + if (!NVal(env, funcArg[NARG_POS::SECOND]).TypeIs(napi_function)) { + LOGE("Argument type mismatch"); + NError(E_PARAMS).ThrowErr(env); + return nullptr; + } + + if (callback_ != nullptr) { + LOGI("callback already exist"); + return NVal::CreateUndefined(env).val_; + } + + callback_ = make_shared(env, NVal(env, funcArg[(int)NARG_POS::SECOND]).val_); + int32_t ret = CloudSyncManager::GetInstance().RegisterDownloadFileCallback(callback_); + if (ret != E_OK) { + LOGE("RegisterDownloadFileCallback error, ret: %{public}d", ret); + NError(Convert2JsErrNum(ret)).ThrowErr(env); + return nullptr; + } + + return NVal::CreateUndefined(env).val_; +} + +napi_value CloudFileNapi::Off(napi_env env, napi_callback_info info) +{ + LOGI("Off begin"); + NFuncArg funcArg(env, info); + if (!funcArg.InitArgs(NARG_CNT::ONE, NARG_CNT::TWO)) { + LOGE("Off Number of arguments unmatched"); + NError(E_PARAMS).ThrowErr(env); + return nullptr; + } + auto [succProgress, progress, ignore] = NVal(env, funcArg[NARG_POS::FIRST]).ToUTF8String(); + if (!(succProgress && std::string(progress.get()) == "progress")) { + LOGE("Off get progress failed!"); + NError(E_PARAMS).ThrowErr(env); + return nullptr; + } + + if (funcArg.GetArgc() == (uint)NARG_CNT::TWO &&!NVal(env, funcArg[NARG_POS::SECOND]).TypeIs(napi_function)) { + LOGE("Argument type mismatch"); + NError(E_PARAMS).ThrowErr(env); + return nullptr; + } + + int32_t ret = CloudSyncManager::GetInstance().UnregisterDownloadFileCallback(); + if (ret != E_OK) { + LOGE("UnregisterDownloadFileCallback error, ret: %{public}d", ret); + NError(Convert2JsErrNum(ret)).ThrowErr(env); + return nullptr; + } + if (callback_ != nullptr) { + /* napi delete reference */ + callback_->DeleteReference(); + callback_ = nullptr; + } + return NVal::CreateUndefined(env).val_; +} + +napi_value CloudFileNapi::Stop(napi_env env, napi_callback_info info) +{ + LOGI("Stop begin"); + NFuncArg funcArg(env, info); + if (!funcArg.InitArgs(NARG_CNT::ONE, NARG_CNT::TWO)) { + LOGE("Stop Number of arguments unmatched"); + NError(E_PARAMS).ThrowErr(env); + return nullptr; + } + auto [succUri, uri, ignore] = NVal(env, funcArg[NARG_POS::FIRST]).ToUTF8String(); + if (!succUri) { + LOGE("Stop get uri parameter failed!"); + NError(E_PARAMS).ThrowErr(env); + return nullptr; + } + + auto cbExec = [uri = string(uri.get()), env = env]() -> NError { + int32_t ret = CloudSyncManager::GetInstance().StopDownloadFile(uri); + if (ret != E_OK) { + LOGE("Stop Download failed! ret = %{public}d", ret); + return NError(Convert2JsErrNum(ret)); + } + LOGI("Stop Download Success!"); + return NError(ERRNO_NOERR); + }; + + auto cbCompl = [](napi_env env, NError err) -> NVal { + if (err) { + return {env, err.GetNapiErr(env)}; + } + return NVal::CreateUndefined(env); + }; + + string procedureName = "cloudFileDownload"; + auto asyncWork = GetPromiseOrCallBackWork(env, funcArg, static_cast(NARG_CNT::TWO)); + return asyncWork == nullptr ? nullptr : asyncWork->Schedule(procedureName, cbExec, cbCompl).val_; +} + +bool CloudFileNapi::ToExport(std::vector props) +{ + std::string className = GetClassName(); + auto [succ, classValue] = + NClass::DefineClass(exports_.env_, className, Constructor, std::move(props)); + if (!succ) { + NError(E_GETRESULT).ThrowErr(exports_.env_); + LOGE("Failed to define GallerySync class"); + return false; + } + + succ = NClass::SaveClass(exports_.env_, className, classValue); + if (!succ) { + NError(E_GETRESULT).ThrowErr(exports_.env_); + LOGE("Failed to save GallerySync class"); + return false; + } + + return exports_.AddProp(className, classValue); +} + +bool CloudFileNapi::Export() +{ + vector props = { + NVal::DeclareNapiFunction("start", CloudFileNapi::Start), + NVal::DeclareNapiFunction("on", CloudFileNapi::On), + NVal::DeclareNapiFunction("off", CloudFileNapi::Off), + NVal::DeclareNapiFunction("stop", CloudFileNapi::Stop), + }; + return ToExport(props); +} + +void CloudFileNapi::SetClassName(std::string classname) +{ + className = classname; +} + +string CloudFileNapi::GetClassName() +{ + return CloudFileNapi::className; +} +} // namespace OHOS::FileManagement::CloudSync \ No newline at end of file diff --git a/interfaces/kits/js/cloudfilesync/cloud_file_napi.h b/interfaces/kits/js/cloudfilesync/cloud_file_napi.h new file mode 100644 index 0000000000000000000000000000000000000000..a4d1cd5d00e812f34867f0ee4cd9ad638fe08555 --- /dev/null +++ b/interfaces/kits/js/cloudfilesync/cloud_file_napi.h @@ -0,0 +1,71 @@ +/* + * Copyright (c) 2023 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT 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 OHOS_FILEMGMT_CLOUD_FILE_NAPI_H +#define OHOS_FILEMGMT_CLOUD_FILE_NAPI_H + +#include "cloud_download_callback.h" +#include "filemgmt_libn.h" + +namespace OHOS::FileManagement::CloudSync { + +class CloudDownloadCallbackImpl; +class CloudFileNapi : public LibN::NExporter { +public: + CloudFileNapi(napi_env env, napi_value exports); + ~CloudFileNapi() = default; + + bool Export() override; + bool ToExport(std::vector props); + virtual void SetClassName(std::string classname); + std::string GetClassName() override; + static napi_value Constructor(napi_env env, napi_callback_info info); + static napi_value Start(napi_env env, napi_callback_info info); + static napi_value On(napi_env env, napi_callback_info info); + static napi_value Off(napi_env env, napi_callback_info info); + static napi_value Stop(napi_env env, napi_callback_info info); + +private: + static inline std::shared_ptr callback_; + inline static std::string className = "CloudFileNapi"; +}; + +class CloudDownloadCallbackImpl : public CloudDownloadCallback, + public std::enable_shared_from_this { +public: + CloudDownloadCallbackImpl(napi_env env, napi_value fun); + ~CloudDownloadCallbackImpl() = default; + void OnDownloadProcess(DownloadProgressObj &progress) override; + void DeleteReference(); + + class UvChangeMsg { + public: + UvChangeMsg(std::shared_ptr CloudDownloadCallbackIn, + DownloadProgressObj downloadProgress) + : CloudDownloadCallback_(CloudDownloadCallbackIn), downloadProgress_(downloadProgress) + { + } + ~UvChangeMsg() {} + std::weak_ptr CloudDownloadCallback_; + DownloadProgressObj downloadProgress_; + }; + +private: + static void OnComplete(UvChangeMsg *msg); + napi_env env_; + napi_ref cbOnRef_ = nullptr; +}; +} // namespace OHOS::FileManagement::CloudSync +#endif // OHOS_FILEMGMT_CLOUD_FILE_NAPI_H \ No newline at end of file diff --git a/interfaces/kits/js/cloudfilesync/cloud_sync_n_exporter.cpp b/interfaces/kits/js/cloudfilesync/cloud_sync_n_exporter.cpp index 30bfc485beea104ba9137f33b33d78a3e9286e95..52103e0e2de8e1c15ae648ef3e8ce1908d479fa1 100644 --- a/interfaces/kits/js/cloudfilesync/cloud_sync_n_exporter.cpp +++ b/interfaces/kits/js/cloudfilesync/cloud_sync_n_exporter.cpp @@ -14,8 +14,11 @@ */ #include "cloud_sync_n_exporter.h" +#include "cloud_file_cache_napi.h" #include "cloud_file_download_napi.h" -#include "cloud_sync_n_exporter.h" +#include "cloud_file_napi.h" +#include "cloud_sync_napi.h" +#include "file_sync_napi.h" #include "gallery_sync_napi.h" #include "utils_log.h" @@ -52,8 +55,10 @@ napi_value CloudSyncExport(napi_env env, napi_value exports) InitState(env, exports); std::vector> products; + products.emplace_back(std::make_unique(env, exports)); products.emplace_back(std::make_unique(env, exports)); products.emplace_back(std::make_unique(env, exports)); + products.emplace_back(std::make_unique(env, exports)); for (auto &&product : products) { if (!product->Export()) { LOGE("INNER BUG. Failed to export class %{public}s for module cloudSyncDownload ", diff --git a/interfaces/kits/js/cloudfilesync/cloud_sync_napi.cpp b/interfaces/kits/js/cloudfilesync/cloud_sync_napi.cpp new file mode 100644 index 0000000000000000000000000000000000000000..8167e57b2162d93b1c3c83f46a0ec1f2a6d94510 --- /dev/null +++ b/interfaces/kits/js/cloudfilesync/cloud_sync_napi.cpp @@ -0,0 +1,315 @@ +/* + * Copyright (c) 2023 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT 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 "cloud_sync_napi.h" + +#include + +#include "cloud_sync_manager.h" +#include "dfs_error.h" +#include "utils_log.h" +#include "async_work.h" +#include "uv.h" + +namespace OHOS::FileManagement::CloudSync { +using namespace FileManagement::LibN; +using namespace std; + +CloudSyncCallbackImpl::CloudSyncCallbackImpl(napi_env env, napi_value fun) : env_(env) +{ + if (fun != nullptr) { + napi_create_reference(env_, fun, 1, &cbOnRef_); + } +} + +void CloudSyncCallbackImpl::OnComplete(UvChangeMsg *msg) +{ + auto cloudSyncCallback = msg->cloudSyncCallback_.lock(); + if (cloudSyncCallback == nullptr || cloudSyncCallback->cbOnRef_ == nullptr) { + LOGE("cloudSyncCallback->cbOnRef_ is nullptr"); + return; + } + auto env = cloudSyncCallback->env_; + auto ref = cloudSyncCallback->cbOnRef_; + napi_handle_scope scope = nullptr; + napi_open_handle_scope(env, &scope); + napi_value jsCallback = nullptr; + napi_status status = napi_get_reference_value(env, ref, &jsCallback); + if (status != napi_ok) { + LOGE("Create reference failed, status: %{public}d", status); + napi_close_handle_scope(env, scope); + return; + } + NVal obj = NVal::CreateObject(env); + obj.AddProp("state", NVal::CreateInt32(env, (int32_t)msg->state_).val_); + obj.AddProp("error", NVal::CreateInt32(env, (int32_t)msg->error_).val_); + napi_value retVal = nullptr; + napi_value global = nullptr; + napi_get_global(env, &global); + status = napi_call_function(env, global, jsCallback, ARGS_ONE, &(obj.val_), &retVal); + if (status != napi_ok) { + LOGE("napi call function failed, status: %{public}d", status); + } + napi_close_handle_scope(env, scope); +} + +void CloudSyncCallbackImpl::OnSyncStateChanged(CloudSyncState state, ErrorType error) +{ + uv_loop_s *loop = nullptr; + napi_get_uv_event_loop(env_, &loop); + if (loop == nullptr) { + return; + } + + uv_work_t *work = new (nothrow) uv_work_t; + if (work == nullptr) { + LOGE("Failed to create uv work"); + return; + } + + UvChangeMsg *msg = new (std::nothrow) UvChangeMsg(shared_from_this(), state, error); + if (msg == nullptr) { + delete work; + return; + } + + work->data = reinterpret_cast(msg); + int ret = uv_queue_work( + loop, work, [](uv_work_t *work) {}, + [](uv_work_t *work, int status) { + auto msg = reinterpret_cast(work->data); + OnComplete(msg); + delete msg; + delete work; + }); + if (ret != 0) { + LOGE("Failed to execute libuv work queue, ret: %{public}d", ret); + delete msg; + delete work; + } +} + +void CloudSyncCallbackImpl::DeleteReference() +{ + if (cbOnRef_ != nullptr) { + napi_delete_reference(env_, cbOnRef_); + cbOnRef_ = nullptr; + } +} + +void CloudSyncCallbackImpl::OnSyncStateChanged(SyncType type, SyncPromptState state) +{ + return; +} + +napi_value CloudSyncNapi::Constructor(napi_env env, napi_callback_info info) +{ + NFuncArg funcArg(env, info); + if (!funcArg.InitArgs(NARG_CNT::ZERO)) { + NError(E_PARAMS).ThrowErr(env, "Number of arguments unmatched"); + return nullptr; + } + + return funcArg.GetThisVar(); +} + +napi_value CloudSyncNapi::OnCallback(napi_env env, napi_callback_info info) +{ + NFuncArg funcArg(env, info); + if (!funcArg.InitArgs(NARG_CNT::TWO)) { + NError(E_PARAMS).ThrowErr(env, "Number of arguments unmatched"); + LOGE("OnCallback Number of arguments unmatched"); + return nullptr; + } + + auto [succ, type, ignore] = NVal(env, funcArg[(int)NARG_POS::FIRST]).ToUTF8String(); + if (!(succ && (type.get() == std::string("progress")))) { + NError(E_PARAMS).ThrowErr(env); + return nullptr; + } + + if (!NVal(env, funcArg[(int)NARG_POS::SECOND]).TypeIs(napi_function)) { + LOGE("Argument type mismatch"); + NError(E_PARAMS).ThrowErr(env); + return nullptr; + } + + if (callback_ != nullptr) { + LOGI("callback already exist"); + return NVal::CreateUndefined(env).val_; + } + + callback_ = make_shared(env, NVal(env, funcArg[(int)NARG_POS::SECOND]).val_); + int32_t ret = CloudSyncManager::GetInstance().RegisterCallback(callback_); + if (ret != E_OK) { + LOGE("OnCallback Register error, result: %{public}d", ret); + NError(Convert2JsErrNum(ret)).ThrowErr(env); + return nullptr; + } + + return NVal::CreateUndefined(env).val_; +} + +napi_value CloudSyncNapi::OffCallback(napi_env env, napi_callback_info info) +{ + NFuncArg funcArg(env, info); + if (!funcArg.InitArgs(NARG_CNT::ONE, NARG_CNT::TWO)) { + NError(E_PARAMS).ThrowErr(env, "Number of arguments unmatched"); + LOGE("OffCallback Number of arguments unmatched"); + return nullptr; + } + + auto [succ, type, ignore] = NVal(env, funcArg[(int)NARG_POS::FIRST]).ToUTF8String(); + if (!(succ && (type.get() == std::string("progress")))) { + NError(E_PARAMS).ThrowErr(env); + return nullptr; + } + + if (funcArg.GetArgc() == (uint)NARG_CNT::TWO && !NVal(env, funcArg[(int)NARG_POS::SECOND]).TypeIs(napi_function)) { + LOGE("Argument type mismatch"); + NError(E_PARAMS).ThrowErr(env); + return nullptr; + } + + int32_t ret = CloudSyncManager::GetInstance().UnRegisterCallback(); + if (ret != E_OK) { + LOGE("OffCallback UnRegister error, result: %{public}d", ret); + NError(Convert2JsErrNum(ret)).ThrowErr(env); + return nullptr; + } + if (callback_ != nullptr) { + /* napi delete reference */ + callback_->DeleteReference(); + callback_ = nullptr; + } + return NVal::CreateUndefined(env).val_; +} + +napi_value CloudSyncNapi::Start(napi_env env, napi_callback_info info) +{ + NFuncArg funcArg(env, info); + if (!funcArg.InitArgs(NARG_CNT::ZERO, NARG_CNT::ONE)) { + NError(E_PARAMS).ThrowErr(env); + } + + auto cbExec = []() -> NError { + int32_t ret = CloudSyncManager::GetInstance().StartSync(); + if (ret != E_OK) { + LOGE("Start Sync error, result: %{public}d", ret); + return NError(Convert2JsErrNum(ret)); + } + return NError(ERRNO_NOERR); + }; + + auto cbComplete = [](napi_env env, NError err) -> NVal { + if (err) { + return {env, err.GetNapiErr(env)}; + } + return NVal::CreateUndefined(env); + }; + + std::string procedureName = "Start"; + auto asyncWork = GetPromiseOrCallBackWork(env, funcArg, static_cast(NARG_CNT::TWO)); + return asyncWork == nullptr ? nullptr : asyncWork->Schedule(procedureName, cbExec, cbComplete).val_; +} + +napi_value CloudSyncNapi::Stop(napi_env env, napi_callback_info info) +{ + NFuncArg funcArg(env, info); + if (!funcArg.InitArgs(NARG_CNT::ZERO, NARG_CNT::ONE)) { + NError(E_PARAMS).ThrowErr(env); + return nullptr; + } + + auto cbExec = []() -> NError { + int32_t ret = CloudSyncManager::GetInstance().StopSync(); + if (ret != E_OK) { + LOGE("Stop Sync error, result: %{public}d", ret); + return NError(Convert2JsErrNum(ret)); + } + return NError(ERRNO_NOERR); + }; + + auto cbComplete = [](napi_env env, NError err) -> NVal { + if (err) { + return {env, err.GetNapiErr(env)}; + } + return NVal::CreateUndefined(env); + }; + + std::string procedureName = "Stop"; + auto asyncWork = GetPromiseOrCallBackWork(env, funcArg, static_cast(NARG_CNT::TWO)); + return asyncWork == nullptr ? nullptr : asyncWork->Schedule(procedureName, cbExec, cbComplete).val_; +} + +void CloudSyncNapi::SetClassName(std::string classname) +{ + className_ = classname; +} + +std::string CloudSyncNapi::GetClassName() +{ + return className_; +} + +bool CloudSyncNapi::ToExport(std::vector props) +{ + std::string className = GetClassName(); + auto [succ, classValue] = + NClass::DefineClass(exports_.env_, className, Constructor, std::move(props)); + if (!succ) { + NError(E_GETRESULT).ThrowErr(exports_.env_); + LOGE("Failed to define CloudSyncNapi class"); + return false; + } + + succ = NClass::SaveClass(exports_.env_, className, classValue); + if (!succ) { + NError(E_GETRESULT).ThrowErr(exports_.env_); + LOGE("Failed to save CloudSyncNapi class"); + return false; + } + + return exports_.AddProp(className, classValue); +} + +bool CloudSyncNapi::Export() +{ + std::vector props = { + NVal::DeclareNapiFunction("on", OnCallback), + NVal::DeclareNapiFunction("off", OffCallback), + NVal::DeclareNapiFunction("start", Start), + NVal::DeclareNapiFunction("stop", Stop), + }; + std::string className = GetClassName(); + auto [succ, classValue] = + NClass::DefineClass(exports_.env_, className, CloudSyncNapi::Constructor, std::move(props)); + if (!succ) { + NError(E_GETRESULT).ThrowErr(exports_.env_); + LOGE("Failed to define GallerySync class"); + return false; + } + + succ = NClass::SaveClass(exports_.env_, className, classValue); + if (!succ) { + NError(E_GETRESULT).ThrowErr(exports_.env_); + LOGE("Failed to save GallerySync class"); + return false; + } + + return exports_.AddProp(className, classValue); +} + +} // namespace OHOS::FileManagement::CloudSync \ No newline at end of file diff --git a/interfaces/kits/js/cloudfilesync/cloud_sync_napi.h b/interfaces/kits/js/cloudfilesync/cloud_sync_napi.h new file mode 100644 index 0000000000000000000000000000000000000000..6aaddae98ed28dd3e7dc4860dc08f90d20972d65 --- /dev/null +++ b/interfaces/kits/js/cloudfilesync/cloud_sync_napi.h @@ -0,0 +1,73 @@ +/* + * Copyright (c) 2023 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT 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 OHOS_FILEMGMT_CLOUD_SYNC_NAPI_H +#define OHOS_FILEMGMT_CLOUD_SYNC_NAPI_H + +#include "cloud_sync_callback.h" +#include "filemgmt_libn.h" + +namespace OHOS::FileManagement::CloudSync { +const int32_t ARGS_ONE = 1; + +class CloudSyncCallbackImpl; +class CloudSyncNapi : public LibN::NExporter { +public: + void SetClassName(std::string classname); + std::string GetClassName() override; + bool Export() override; + bool ToExport(std::vector props); + static napi_value Constructor(napi_env env, napi_callback_info info); + + static napi_value Start(napi_env env, napi_callback_info info); + static napi_value Stop(napi_env env, napi_callback_info info); + static napi_value OnCallback(napi_env env, napi_callback_info info); + static napi_value OffCallback(napi_env env, napi_callback_info info); + + CloudSyncNapi(napi_env env, napi_value exports) : NExporter(env, exports) {}; + ~CloudSyncNapi() = default; + +private: + static inline std::shared_ptr callback_; + std::string className_; +}; + +class CloudSyncCallbackImpl : public CloudSyncCallback, public std::enable_shared_from_this { +public: + CloudSyncCallbackImpl(napi_env env, napi_value fun); + ~CloudSyncCallbackImpl() = default; + void OnSyncStateChanged(SyncType type, SyncPromptState state) override; + void OnSyncStateChanged(CloudSyncState state, ErrorType error) override; + void DeleteReference(); + + class UvChangeMsg { + public: + UvChangeMsg(std::shared_ptr cloudSyncCallbackIn, CloudSyncState state, ErrorType error) + : cloudSyncCallback_(cloudSyncCallbackIn), state_(state), error_(error) + { + } + ~UvChangeMsg() {} + std::weak_ptr cloudSyncCallback_; + CloudSyncState state_; + ErrorType error_; + }; + +private: + static void OnComplete(UvChangeMsg *msg); + napi_env env_; + napi_ref cbOnRef_ = nullptr; +}; +} // namespace OHOS::FileManagement::CloudSync +#endif // OHOS_FILEMGMT_CLOUD_SYNC_NAPI_H \ No newline at end of file diff --git a/interfaces/kits/js/cloudfilesync/file_sync_napi.cpp b/interfaces/kits/js/cloudfilesync/file_sync_napi.cpp new file mode 100644 index 0000000000000000000000000000000000000000..dbb8620456a7b9b65bfaef7145a142a20554837f --- /dev/null +++ b/interfaces/kits/js/cloudfilesync/file_sync_napi.cpp @@ -0,0 +1,43 @@ +/* + * Copyright (c) 2023 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT 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_sync_napi.h" + +#include +#include + +#include "async_work.h" +#include "cloud_sync_manager.h" +#include "dfs_error.h" +#include "utils_log.h" +#include "uv.h" + +namespace OHOS::FileManagement::CloudSync { +using namespace FileManagement::LibN; +using namespace std; + +bool FileSyncNapi::Export() +{ + std::vector props = { + NVal::DeclareNapiFunction("on", FileSyncNapi::OnCallback), + NVal::DeclareNapiFunction("off", FileSyncNapi::OffCallback), + NVal::DeclareNapiFunction("start", FileSyncNapi::Start), + NVal::DeclareNapiFunction("stop", FileSyncNapi::Stop), + }; + + SetClassName("FileSync"); + return ToExport(props); +} +} // namespace OHOS::FileManagement::CloudSync \ No newline at end of file diff --git a/interfaces/kits/js/cloudfilesync/file_sync_napi.h b/interfaces/kits/js/cloudfilesync/file_sync_napi.h new file mode 100644 index 0000000000000000000000000000000000000000..c860ab13c537bd3db8a4dbfa40bec290962a3749 --- /dev/null +++ b/interfaces/kits/js/cloudfilesync/file_sync_napi.h @@ -0,0 +1,31 @@ +/* + * Copyright (c) 2023 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT 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 OHOS_FILEMGMT_FILE_SYNC_NAPI_H +#define OHOS_FILEMGMT_FILE_SYNC_NAPI_H + +#include "filemgmt_libn.h" +#include "gallery_sync_napi.h" +#include "cloud_sync_napi.h" + +namespace OHOS::FileManagement::CloudSync { +class FileSyncNapi final : public CloudSyncNapi { +public: + bool Export() override; + FileSyncNapi(napi_env env, napi_value exports) : CloudSyncNapi(env, exports) {}; + ~FileSyncNapi() = default; +}; +} // namespace OHOS::FileManagement::CloudSync +#endif // OHOS_FILEMGMT_FILE_SYNC_NAPI_H \ No newline at end of file diff --git a/interfaces/kits/js/cloudfilesync/gallery_sync_napi.cpp b/interfaces/kits/js/cloudfilesync/gallery_sync_napi.cpp index 4a23c6f4ceebd51c6ee821ebdea54912f2d1f88a..17b0456d3e696c0e4237023ef5006e5fe18a01e2 100644 --- a/interfaces/kits/js/cloudfilesync/gallery_sync_napi.cpp +++ b/interfaces/kits/js/cloudfilesync/gallery_sync_napi.cpp @@ -27,263 +27,13 @@ namespace OHOS::FileManagement::CloudSync { using namespace FileManagement::LibN; using namespace std; -CloudSyncCallbackImpl::CloudSyncCallbackImpl(napi_env env, napi_value fun) : env_(env) -{ - if (fun != nullptr) { - napi_create_reference(env_, fun, 1, &cbOnRef_); - } -} - -void CloudSyncCallbackImpl::OnComplete(UvChangeMsg *msg) -{ - auto cloudSyncCallback = msg->cloudSyncCallback_.lock(); - if (cloudSyncCallback == nullptr || cloudSyncCallback->cbOnRef_ == nullptr) { - LOGE("cloudSyncCallback->cbOnRef_ is nullptr"); - return; - } - auto env = cloudSyncCallback->env_; - auto ref = cloudSyncCallback->cbOnRef_; - napi_handle_scope scope = nullptr; - napi_open_handle_scope(env, &scope); - napi_value jsCallback = nullptr; - napi_status status = napi_get_reference_value(env, ref, &jsCallback); - if (status != napi_ok) { - LOGE("Create reference failed, status: %{public}d", status); - napi_close_handle_scope(env, scope); - return; - } - NVal obj = NVal::CreateObject(env); - obj.AddProp("state", NVal::CreateInt32(env, (int32_t)msg->state_).val_); - obj.AddProp("error", NVal::CreateInt32(env, (int32_t)msg->error_).val_); - napi_value retVal = nullptr; - napi_value global = nullptr; - napi_get_global(env, &global); - status = napi_call_function(env, global, jsCallback, ARGS_ONE, &(obj.val_), &retVal); - if (status != napi_ok) { - LOGE("napi call function failed, status: %{public}d", status); - } - napi_close_handle_scope(env, scope); -} - -void CloudSyncCallbackImpl::OnSyncStateChanged(CloudSyncState state, ErrorType error) -{ - uv_loop_s *loop = nullptr; - napi_get_uv_event_loop(env_, &loop); - if (loop == nullptr) { - return; - } - - uv_work_t *work = new (nothrow) uv_work_t; - if (work == nullptr) { - LOGE("Failed to create uv work"); - return; - } - - UvChangeMsg *msg = new (std::nothrow) UvChangeMsg(shared_from_this(), state, error); - if (msg == nullptr) { - delete work; - return; - } - - work->data = reinterpret_cast(msg); - int ret = uv_queue_work( - loop, work, [](uv_work_t *work) {}, - [](uv_work_t *work, int status) { - auto msg = reinterpret_cast(work->data); - OnComplete(msg); - delete msg; - delete work; - }); - if (ret != 0) { - LOGE("Failed to execute libuv work queue, ret: %{public}d", ret); - delete msg; - delete work; - } -} - -void CloudSyncCallbackImpl::DeleteReference() -{ - if (cbOnRef_ != nullptr) { - napi_delete_reference(env_, cbOnRef_); - cbOnRef_ = nullptr; - } -} - -void CloudSyncCallbackImpl::OnSyncStateChanged(SyncType type, SyncPromptState state) -{ - return; -} - -napi_value GallerySyncNapi::Constructor(napi_env env, napi_callback_info info) -{ - NFuncArg funcArg(env, info); - if (!funcArg.InitArgs(NARG_CNT::ZERO)) { - NError(E_PARAMS).ThrowErr(env, "Number of arguments unmatched"); - return nullptr; - } - - return funcArg.GetThisVar(); -} - -napi_value GallerySyncNapi::OnCallback(napi_env env, napi_callback_info info) -{ - NFuncArg funcArg(env, info); - if (!funcArg.InitArgs(NARG_CNT::TWO)) { - NError(E_PARAMS).ThrowErr(env, "Number of arguments unmatched"); - LOGE("OnCallback Number of arguments unmatched"); - return nullptr; - } - - auto [succ, type, ignore] = NVal(env, funcArg[(int)NARG_POS::FIRST]).ToUTF8String(); - if (!(succ && (type.get() == std::string("progress")))) { - NError(E_PARAMS).ThrowErr(env); - return nullptr; - } - - if (!NVal(env, funcArg[(int)NARG_POS::SECOND]).TypeIs(napi_function)) { - LOGE("Argument type mismatch"); - NError(E_PARAMS).ThrowErr(env); - return nullptr; - } - - if (callback_ != nullptr) { - LOGI("callback already exist"); - return NVal::CreateUndefined(env).val_; - } - - callback_ = make_shared(env, NVal(env, funcArg[(int)NARG_POS::SECOND]).val_); - int32_t ret = CloudSyncManager::GetInstance().RegisterCallback(callback_); - if (ret != E_OK) { - LOGE("OnCallback Register error, result: %{public}d", ret); - NError(Convert2JsErrNum(ret)).ThrowErr(env); - return nullptr; - } - - return NVal::CreateUndefined(env).val_; -} - -napi_value GallerySyncNapi::OffCallback(napi_env env, napi_callback_info info) -{ - NFuncArg funcArg(env, info); - if (!funcArg.InitArgs(NARG_CNT::ONE, NARG_CNT::TWO)) { - NError(E_PARAMS).ThrowErr(env, "Number of arguments unmatched"); - LOGE("OffCallback Number of arguments unmatched"); - return nullptr; - } - - auto [succ, type, ignore] = NVal(env, funcArg[(int)NARG_POS::FIRST]).ToUTF8String(); - if (!(succ && (type.get() == std::string("progress")))) { - NError(E_PARAMS).ThrowErr(env); - return nullptr; - } - - if (funcArg.GetArgc() == (uint)NARG_CNT::TWO && !NVal(env, funcArg[(int)NARG_POS::SECOND]).TypeIs(napi_function)) { - LOGE("Argument type mismatch"); - NError(E_PARAMS).ThrowErr(env); - return nullptr; - } - - int32_t ret = CloudSyncManager::GetInstance().UnRegisterCallback(); - if (ret != E_OK) { - LOGE("OffCallback UnRegister error, result: %{public}d", ret); - NError(Convert2JsErrNum(ret)).ThrowErr(env); - return nullptr; - } - if (callback_ != nullptr) { - /* napi delete reference */ - callback_->DeleteReference(); - callback_ = nullptr; - } - return NVal::CreateUndefined(env).val_; -} - -napi_value GallerySyncNapi::Start(napi_env env, napi_callback_info info) -{ - NFuncArg funcArg(env, info); - if (!funcArg.InitArgs(NARG_CNT::ZERO, NARG_CNT::ONE)) { - NError(E_PARAMS).ThrowErr(env); - } - - auto cbExec = []() -> NError { - int32_t ret = CloudSyncManager::GetInstance().StartSync(); - if (ret != E_OK) { - LOGE("Start Sync error, result: %{public}d", ret); - return NError(Convert2JsErrNum(ret)); - } - return NError(ERRNO_NOERR); - }; - - auto cbComplete = [](napi_env env, NError err) -> NVal { - if (err) { - return {env, err.GetNapiErr(env)}; - } - return NVal::CreateUndefined(env); - }; - - std::string PROCEDURE_NAME = "Start"; - auto asyncWork = GetPromiseOrCallBackWork(env, funcArg, static_cast(NARG_CNT::TWO)); - return asyncWork == nullptr ? nullptr : asyncWork->Schedule(PROCEDURE_NAME, cbExec, cbComplete).val_; -} - -napi_value GallerySyncNapi::Stop(napi_env env, napi_callback_info info) -{ - NFuncArg funcArg(env, info); - if (!funcArg.InitArgs(NARG_CNT::ZERO, NARG_CNT::ONE)) { - NError(E_PARAMS).ThrowErr(env); - return nullptr; - } - - auto cbExec = []() -> NError { - int32_t ret = CloudSyncManager::GetInstance().StopSync(); - if (ret != E_OK) { - LOGE("Stop Sync error, result: %{public}d", ret); - return NError(Convert2JsErrNum(ret)); - } - return NError(ERRNO_NOERR); - }; - - auto cbComplete = [](napi_env env, NError err) -> NVal { - if (err) { - return {env, err.GetNapiErr(env)}; - } - return NVal::CreateUndefined(env); - }; - - std::string PROCEDURE_NAME = "Stop"; - auto asyncWork = GetPromiseOrCallBackWork(env, funcArg, static_cast(NARG_CNT::TWO)); - return asyncWork == nullptr ? nullptr : asyncWork->Schedule(PROCEDURE_NAME, cbExec, cbComplete).val_; -} - -std::string GallerySyncNapi::GetClassName() -{ - return GallerySyncNapi::className_; -} - bool GallerySyncNapi::Export() { - std::vector props = { - NVal::DeclareNapiFunction("on", OnCallback), - NVal::DeclareNapiFunction("off", OffCallback), - NVal::DeclareNapiFunction("start", Start), - NVal::DeclareNapiFunction("stop", Stop), - }; - - std::string className = GetClassName(); - auto [succ, classValue] = - NClass::DefineClass(exports_.env_, className, GallerySyncNapi::Constructor, std::move(props)); - if (!succ) { - NError(E_GETRESULT).ThrowErr(exports_.env_); - LOGE("Failed to define GallerySync class"); + SetClassName("GallerySync"); + bool success = CloudSyncNapi::Export(); + if (!success) { return false; } - - succ = NClass::SaveClass(exports_.env_, className, classValue); - if (!succ) { - NError(E_GETRESULT).ThrowErr(exports_.env_); - LOGE("Failed to save GallerySync class"); - return false; - } - - return exports_.AddProp(className, classValue); + return true; } } // namespace OHOS::FileManagement::CloudSync diff --git a/interfaces/kits/js/cloudfilesync/gallery_sync_napi.h b/interfaces/kits/js/cloudfilesync/gallery_sync_napi.h index 76c5e11d04917a22e3c5115a582b11cba2c5a5e6..5ca843c17a27c0160052b4f7e60d7f0ce0cfcbc8 100644 --- a/interfaces/kits/js/cloudfilesync/gallery_sync_napi.h +++ b/interfaces/kits/js/cloudfilesync/gallery_sync_napi.h @@ -16,57 +16,16 @@ #ifndef OHOS_FILEMGMT_GALLERY_SYNC_NAPI_H #define OHOS_FILEMGMT_GALLERY_SYNC_NAPI_H -#include "cloud_sync_callback.h" #include "filemgmt_libn.h" +#include "cloud_sync_napi.h" namespace OHOS::FileManagement::CloudSync { -const int32_t ARGS_ONE = 1; - -class CloudSyncCallbackImpl; -class GallerySyncNapi final : public LibN::NExporter { +class GallerySyncNapi final : public CloudSyncNapi { public: bool Export() override; - std::string GetClassName() override; - - static napi_value Constructor(napi_env env, napi_callback_info info); - - static napi_value Start(napi_env env, napi_callback_info info); - static napi_value Stop(napi_env env, napi_callback_info info); - static napi_value OnCallback(napi_env env, napi_callback_info info); - static napi_value OffCallback(napi_env env, napi_callback_info info); - - GallerySyncNapi(napi_env env, napi_value exports) : NExporter(env, exports) {}; + GallerySyncNapi(napi_env env, napi_value exports) : CloudSyncNapi(env, exports) {} ~GallerySyncNapi() = default; - -private: - static inline std::shared_ptr callback_; - inline static const std::string className_ = "GallerySync"; }; -class CloudSyncCallbackImpl : public CloudSyncCallback, public std::enable_shared_from_this { -public: - CloudSyncCallbackImpl(napi_env env, napi_value fun); - ~CloudSyncCallbackImpl() = default; - void OnSyncStateChanged(SyncType type, SyncPromptState state) override; - void OnSyncStateChanged(CloudSyncState state, ErrorType error) override; - void DeleteReference(); - - class UvChangeMsg { - public: - UvChangeMsg(std::shared_ptr cloudSyncCallbackIn, CloudSyncState state, ErrorType error) - : cloudSyncCallback_(cloudSyncCallbackIn), state_(state), error_(error) - { - } - ~UvChangeMsg() {} - std::weak_ptr cloudSyncCallback_; - CloudSyncState state_; - ErrorType error_; - }; - -private: - static void OnComplete(UvChangeMsg *msg); - napi_env env_; - napi_ref cbOnRef_ = nullptr; -}; } // namespace OHOS::FileManagement::CloudSync #endif // OHOS_FILEMGMT_GALLERY_SYNC_NAPI_H