From eb160600747dc93870cca901dc79a26b7dca9ac5 Mon Sep 17 00:00:00 2001 From: "1529367376@qq.com" Date: Wed, 13 Dec 2023 18:50:57 +0800 Subject: [PATCH] update Signed-off-by: 1529367376@qq.com --- .../include/adaptor/asset_change_timer.h | 55 +++ .../include/common/bytes_utils.h | 60 +++ .../include/common/object_types_util.h | 30 ++ .../src/adaptor/asset_change_timer.cpp | 140 ++++++ .../innerkitsimpl/src/object_types_util.cpp | 31 ++ .../interfaces/innerkits/object_types.h | 48 +++ .../framework/cloud/cloud_extra_data.cpp | 65 +++ .../include/cloud/cloud_extra_data.h | 51 +++ .../framework/include/snapshot/bind_event.h | 53 +++ .../include/snapshot/machine_status.h | 63 +++ .../framework/include/snapshot/snapshot.h | 53 +++ .../framework/snapshot/bind_event.cpp | 27 ++ .../framework/snapshot/snapshot.cpp | 61 +++ .../service/{rdb => common}/value_proxy.cpp | 106 ++++- .../service/{rdb => common}/value_proxy.h | 22 +- .../service/object/object_asset_loader.cpp | 71 +++ .../service/object/object_asset_loader.h | 42 ++ .../service/object/object_asset_machine.cpp | 340 +++++++++++++++ .../service/object/object_asset_machine.h | 59 +++ .../service/object/object_snapshot.cpp | 111 +++++ .../service/object/object_snapshot.h | 47 ++ .../service/object/object_types_utils.cpp | 25 ++ .../service/object/object_types_utils.h | 28 ++ .../test/object_asset_machine_test.cpp | 172 ++++++++ interface_sdk/api/@ohos.data.commonType.d.ts | 201 +++++++++ kv_store/frameworks/common/js_proxy.h | 62 +++ .../common/include/concurrent_adapter.h | 43 ++ .../common/src/concurrent_adapter.cpp | 40 ++ .../include/cloud_daemon_manager_impl.h | 41 ++ .../include/cloud_daemon_service_proxy.h | 41 ++ .../include/cloud_download_callback_client.h | 34 ++ .../include/cloud_download_callback_stub.h | 39 ++ .../include/cloud_download_uri_manager.h | 41 ++ .../include/cloud_sync_asset_manager_impl.h | 52 +++ .../include/cloud_sync_callback_client.h | 33 ++ .../include/cloud_sync_callback_stub.h | 39 ++ .../include/cloud_sync_manager_impl.h | 79 ++++ .../include/cloud_sync_service_proxy.h | 75 ++++ .../include/download_asset_callback_client.h | 46 ++ .../include/download_asset_callback_stub.h | 39 ++ .../distributed_file_daemon_manager_impl.h | 48 +++ .../include/distributed_file_daemon_proxy.h | 57 +++ .../file_trans_listener_interface_code.h | 29 ++ .../include/file_trans_listener_stub.h | 47 ++ .../include/i_file_trans_listener.h | 40 ++ .../native/cloud_daemon_kit_inner/BUILD.gn | 63 +++ .../cloud_daemon_manager.h | 31 ++ .../cloud_file_daemon_interface_code.h | 26 ++ .../cloud_daemon_kit_inner/i_cloud_daemon.h | 38 ++ .../svc_death_recipient.h | 41 ++ .../native/cloudsync_kit_inner/BUILD.gn | 123 ++++++ .../cloud_download_callback.h | 32 ++ .../cloud_file_sync_service_interface_code.h | 48 +++ .../cloud_sync_asset_manager.h | 77 ++++ .../cloudsync_kit_inner/cloud_sync_callback.h | 65 +++ .../cloudsync_kit_inner/cloud_sync_common.h | 80 ++++ .../cloud_sync_constants.h | 71 +++ .../cloudsync_kit_inner/cloud_sync_manager.h | 109 +++++ .../download_asset_callback.h | 28 ++ .../i_cloud_download_callback.h | 34 ++ .../i_cloud_sync_callback.h | 34 ++ .../i_cloud_sync_service.h | 60 +++ .../i_download_asset_callback.h | 33 ++ .../cloudsync_kit_inner/svc_death_recipient.h | 41 ++ .../interfaces/kits/js/cloudfilesync/BUILD.gn | 56 +++ .../cloudfilesync/cloud_file_cache_napi.cpp | 106 +++++ .../js/cloudfilesync/cloud_file_cache_napi.h | 32 ++ .../cloud_file_download_napi.cpp | 39 ++ .../cloudfilesync/cloud_file_download_napi.h | 30 ++ .../kits/js/cloudfilesync/cloud_file_napi.cpp | 322 ++++++++++++++ .../kits/js/cloudfilesync/cloud_file_napi.h | 71 +++ .../cloudfilesync/cloud_sync_n_exporter.cpp | 139 ++++++ .../js/cloudfilesync/cloud_sync_n_exporter.h | 26 ++ .../kits/js/cloudfilesync/cloud_sync_napi.cpp | 315 ++++++++++++++ .../kits/js/cloudfilesync/cloud_sync_napi.h | 73 ++++ .../kits/js/cloudfilesync/file_sync_napi.cpp | 98 +++++ .../kits/js/cloudfilesync/file_sync_napi.h | 31 ++ .../js/cloudfilesync/gallery_sync_napi.cpp | 39 ++ .../kits/js/cloudfilesync/gallery_sync_napi.h | 30 ++ .../kits/js/cloudsyncmanager/BUILD.gn | 46 ++ .../cloud_sync_manager_n_exporter.cpp | 406 ++++++++++++++++++ .../cloud_sync_manager_n_exporter.h | 29 ++ .../cloud_sync_manager_napi.cpp | 72 ++++ .../cloud_sync_manager_napi.h | 30 ++ mock/src/mock_dfs_service.cpp | 4 + .../frameworks/js/napi/common/BUILD.gn | 47 ++ .../napi/common/src/js_common_type_init.cpp | 75 ++++ .../interfaces/inner_api/common_type/BUILD.gn | 48 +++ .../common_type/include/common_asset_value.h | 45 ++ .../common_type/include/common_errno.h | 38 ++ .../common_type/include/common_type_util.h | 41 ++ .../common_type/include/common_value_object.h | 383 +++++++++++++++++ .../include/common_values_bucket.h | 176 ++++++++ .../common_type/include/visibility.h | 25 ++ .../common_type/src/common_type_util.cpp | 52 +++ .../common_type/src/common_value_object.cpp | 183 ++++++++ .../common_type/src/common_values_bucket.cpp | 162 +++++++ 97 files changed, 7182 insertions(+), 7 deletions(-) create mode 100644 data_object/frameworks/innerkitsimpl/include/adaptor/asset_change_timer.h create mode 100644 data_object/frameworks/innerkitsimpl/include/common/bytes_utils.h create mode 100644 data_object/frameworks/innerkitsimpl/include/common/object_types_util.h create mode 100644 data_object/frameworks/innerkitsimpl/src/adaptor/asset_change_timer.cpp create mode 100644 data_object/frameworks/innerkitsimpl/src/object_types_util.cpp create mode 100644 data_object/interfaces/innerkits/object_types.h create mode 100644 datamgr_service/services/distributeddataservice/framework/cloud/cloud_extra_data.cpp create mode 100644 datamgr_service/services/distributeddataservice/framework/include/cloud/cloud_extra_data.h create mode 100644 datamgr_service/services/distributeddataservice/framework/include/snapshot/bind_event.h create mode 100644 datamgr_service/services/distributeddataservice/framework/include/snapshot/machine_status.h create mode 100644 datamgr_service/services/distributeddataservice/framework/include/snapshot/snapshot.h create mode 100644 datamgr_service/services/distributeddataservice/framework/snapshot/bind_event.cpp create mode 100644 datamgr_service/services/distributeddataservice/framework/snapshot/snapshot.cpp rename datamgr_service/services/distributeddataservice/service/{rdb => common}/value_proxy.cpp (83%) rename datamgr_service/services/distributeddataservice/service/{rdb => common}/value_proxy.h (90%) create mode 100644 datamgr_service/services/distributeddataservice/service/object/object_asset_loader.cpp create mode 100644 datamgr_service/services/distributeddataservice/service/object/object_asset_loader.h create mode 100644 datamgr_service/services/distributeddataservice/service/object/object_asset_machine.cpp create mode 100644 datamgr_service/services/distributeddataservice/service/object/object_asset_machine.h create mode 100644 datamgr_service/services/distributeddataservice/service/object/object_snapshot.cpp create mode 100644 datamgr_service/services/distributeddataservice/service/object/object_snapshot.h create mode 100644 datamgr_service/services/distributeddataservice/service/object/object_types_utils.cpp create mode 100644 datamgr_service/services/distributeddataservice/service/object/object_types_utils.h create mode 100644 datamgr_service/services/distributeddataservice/service/test/object_asset_machine_test.cpp create mode 100644 interface_sdk/api/@ohos.data.commonType.d.ts create mode 100644 kv_store/frameworks/common/js_proxy.h create mode 100644 kv_store/frameworks/libs/distributeddb/common/include/concurrent_adapter.h create mode 100644 kv_store/frameworks/libs/distributeddb/common/src/concurrent_adapter.cpp create mode 100644 mock/innerkits/filemanagement/dfs_service/frameworks/native/cloud_daemon_kit_inner/include/cloud_daemon_manager_impl.h create mode 100644 mock/innerkits/filemanagement/dfs_service/frameworks/native/cloud_daemon_kit_inner/include/cloud_daemon_service_proxy.h create mode 100644 mock/innerkits/filemanagement/dfs_service/frameworks/native/cloudsync_kit_inner/include/cloud_download_callback_client.h create mode 100644 mock/innerkits/filemanagement/dfs_service/frameworks/native/cloudsync_kit_inner/include/cloud_download_callback_stub.h create mode 100644 mock/innerkits/filemanagement/dfs_service/frameworks/native/cloudsync_kit_inner/include/cloud_download_uri_manager.h create mode 100644 mock/innerkits/filemanagement/dfs_service/frameworks/native/cloudsync_kit_inner/include/cloud_sync_asset_manager_impl.h create mode 100644 mock/innerkits/filemanagement/dfs_service/frameworks/native/cloudsync_kit_inner/include/cloud_sync_callback_client.h create mode 100644 mock/innerkits/filemanagement/dfs_service/frameworks/native/cloudsync_kit_inner/include/cloud_sync_callback_stub.h create mode 100644 mock/innerkits/filemanagement/dfs_service/frameworks/native/cloudsync_kit_inner/include/cloud_sync_manager_impl.h create mode 100644 mock/innerkits/filemanagement/dfs_service/frameworks/native/cloudsync_kit_inner/include/cloud_sync_service_proxy.h create mode 100644 mock/innerkits/filemanagement/dfs_service/frameworks/native/cloudsync_kit_inner/include/download_asset_callback_client.h create mode 100644 mock/innerkits/filemanagement/dfs_service/frameworks/native/cloudsync_kit_inner/include/download_asset_callback_stub.h create mode 100644 mock/innerkits/filemanagement/dfs_service/frameworks/native/distributed_file_inner/include/distributed_file_daemon_manager_impl.h create mode 100644 mock/innerkits/filemanagement/dfs_service/frameworks/native/distributed_file_inner/include/distributed_file_daemon_proxy.h create mode 100644 mock/innerkits/filemanagement/dfs_service/frameworks/native/distributed_file_inner/include/file_trans_listener_interface_code.h create mode 100644 mock/innerkits/filemanagement/dfs_service/frameworks/native/distributed_file_inner/include/file_trans_listener_stub.h create mode 100644 mock/innerkits/filemanagement/dfs_service/frameworks/native/distributed_file_inner/include/i_file_trans_listener.h create mode 100644 mock/innerkits/filemanagement/dfs_service/interfaces/inner_api/native/cloud_daemon_kit_inner/BUILD.gn create mode 100644 mock/innerkits/filemanagement/dfs_service/interfaces/inner_api/native/cloud_daemon_kit_inner/cloud_daemon_manager.h create mode 100644 mock/innerkits/filemanagement/dfs_service/interfaces/inner_api/native/cloud_daemon_kit_inner/cloud_file_daemon_interface_code.h create mode 100644 mock/innerkits/filemanagement/dfs_service/interfaces/inner_api/native/cloud_daemon_kit_inner/i_cloud_daemon.h create mode 100644 mock/innerkits/filemanagement/dfs_service/interfaces/inner_api/native/cloud_daemon_kit_inner/svc_death_recipient.h create mode 100644 mock/innerkits/filemanagement/dfs_service/interfaces/inner_api/native/cloudsync_kit_inner/BUILD.gn create mode 100644 mock/innerkits/filemanagement/dfs_service/interfaces/inner_api/native/cloudsync_kit_inner/cloud_download_callback.h create mode 100644 mock/innerkits/filemanagement/dfs_service/interfaces/inner_api/native/cloudsync_kit_inner/cloud_file_sync_service_interface_code.h create mode 100644 mock/innerkits/filemanagement/dfs_service/interfaces/inner_api/native/cloudsync_kit_inner/cloud_sync_asset_manager.h create mode 100644 mock/innerkits/filemanagement/dfs_service/interfaces/inner_api/native/cloudsync_kit_inner/cloud_sync_callback.h create mode 100644 mock/innerkits/filemanagement/dfs_service/interfaces/inner_api/native/cloudsync_kit_inner/cloud_sync_common.h create mode 100644 mock/innerkits/filemanagement/dfs_service/interfaces/inner_api/native/cloudsync_kit_inner/cloud_sync_constants.h create mode 100644 mock/innerkits/filemanagement/dfs_service/interfaces/inner_api/native/cloudsync_kit_inner/cloud_sync_manager.h create mode 100644 mock/innerkits/filemanagement/dfs_service/interfaces/inner_api/native/cloudsync_kit_inner/download_asset_callback.h create mode 100644 mock/innerkits/filemanagement/dfs_service/interfaces/inner_api/native/cloudsync_kit_inner/i_cloud_download_callback.h create mode 100644 mock/innerkits/filemanagement/dfs_service/interfaces/inner_api/native/cloudsync_kit_inner/i_cloud_sync_callback.h create mode 100644 mock/innerkits/filemanagement/dfs_service/interfaces/inner_api/native/cloudsync_kit_inner/i_cloud_sync_service.h create mode 100644 mock/innerkits/filemanagement/dfs_service/interfaces/inner_api/native/cloudsync_kit_inner/i_download_asset_callback.h create mode 100644 mock/innerkits/filemanagement/dfs_service/interfaces/inner_api/native/cloudsync_kit_inner/svc_death_recipient.h create mode 100644 mock/innerkits/filemanagement/dfs_service/interfaces/kits/js/cloudfilesync/BUILD.gn create mode 100644 mock/innerkits/filemanagement/dfs_service/interfaces/kits/js/cloudfilesync/cloud_file_cache_napi.cpp create mode 100644 mock/innerkits/filemanagement/dfs_service/interfaces/kits/js/cloudfilesync/cloud_file_cache_napi.h create mode 100644 mock/innerkits/filemanagement/dfs_service/interfaces/kits/js/cloudfilesync/cloud_file_download_napi.cpp create mode 100644 mock/innerkits/filemanagement/dfs_service/interfaces/kits/js/cloudfilesync/cloud_file_download_napi.h create mode 100644 mock/innerkits/filemanagement/dfs_service/interfaces/kits/js/cloudfilesync/cloud_file_napi.cpp create mode 100644 mock/innerkits/filemanagement/dfs_service/interfaces/kits/js/cloudfilesync/cloud_file_napi.h create mode 100644 mock/innerkits/filemanagement/dfs_service/interfaces/kits/js/cloudfilesync/cloud_sync_n_exporter.cpp create mode 100644 mock/innerkits/filemanagement/dfs_service/interfaces/kits/js/cloudfilesync/cloud_sync_n_exporter.h create mode 100644 mock/innerkits/filemanagement/dfs_service/interfaces/kits/js/cloudfilesync/cloud_sync_napi.cpp create mode 100644 mock/innerkits/filemanagement/dfs_service/interfaces/kits/js/cloudfilesync/cloud_sync_napi.h create mode 100644 mock/innerkits/filemanagement/dfs_service/interfaces/kits/js/cloudfilesync/file_sync_napi.cpp create mode 100644 mock/innerkits/filemanagement/dfs_service/interfaces/kits/js/cloudfilesync/file_sync_napi.h create mode 100644 mock/innerkits/filemanagement/dfs_service/interfaces/kits/js/cloudfilesync/gallery_sync_napi.cpp create mode 100644 mock/innerkits/filemanagement/dfs_service/interfaces/kits/js/cloudfilesync/gallery_sync_napi.h create mode 100644 mock/innerkits/filemanagement/dfs_service/interfaces/kits/js/cloudsyncmanager/BUILD.gn create mode 100644 mock/innerkits/filemanagement/dfs_service/interfaces/kits/js/cloudsyncmanager/cloud_sync_manager_n_exporter.cpp create mode 100644 mock/innerkits/filemanagement/dfs_service/interfaces/kits/js/cloudsyncmanager/cloud_sync_manager_n_exporter.h create mode 100644 mock/innerkits/filemanagement/dfs_service/interfaces/kits/js/cloudsyncmanager/cloud_sync_manager_napi.cpp create mode 100644 mock/innerkits/filemanagement/dfs_service/interfaces/kits/js/cloudsyncmanager/cloud_sync_manager_napi.h create mode 100644 mock/src/mock_dfs_service.cpp create mode 100644 relational_store/frameworks/js/napi/common/BUILD.gn create mode 100644 relational_store/frameworks/js/napi/common/src/js_common_type_init.cpp create mode 100644 relational_store/interfaces/inner_api/common_type/BUILD.gn create mode 100644 relational_store/interfaces/inner_api/common_type/include/common_asset_value.h create mode 100644 relational_store/interfaces/inner_api/common_type/include/common_errno.h create mode 100644 relational_store/interfaces/inner_api/common_type/include/common_type_util.h create mode 100644 relational_store/interfaces/inner_api/common_type/include/common_value_object.h create mode 100644 relational_store/interfaces/inner_api/common_type/include/common_values_bucket.h create mode 100644 relational_store/interfaces/inner_api/common_type/include/visibility.h create mode 100644 relational_store/interfaces/inner_api/common_type/src/common_type_util.cpp create mode 100644 relational_store/interfaces/inner_api/common_type/src/common_value_object.cpp create mode 100644 relational_store/interfaces/inner_api/common_type/src/common_values_bucket.cpp diff --git a/data_object/frameworks/innerkitsimpl/include/adaptor/asset_change_timer.h b/data_object/frameworks/innerkitsimpl/include/adaptor/asset_change_timer.h new file mode 100644 index 00000000..e4ac9374 --- /dev/null +++ b/data_object/frameworks/innerkitsimpl/include/adaptor/asset_change_timer.h @@ -0,0 +1,55 @@ +/* + * Copyright (c) 2022 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +#ifndef ASSET_CHANGE_TIMER_H +#define ASSET_CHANGE_TIMER_H +#include + +#include "executor_pool.h" +#include "flat_object_store.h" +#include "object_types.h" + +namespace OHOS::ObjectStore { +class AssetChangeTimer { +public: + static AssetChangeTimer *GetInstance(FlatObjectStore *flatObjectStore, std::shared_ptr watcher); + void OnAssetChanged(const std::string &sessionId, const std::string &assetKey); + +private: + AssetChangeTimer() = default; + ~AssetChangeTimer() = default; + AssetChangeTimer(const AssetChangeTimer &) = delete; + AssetChangeTimer &operator=(const AssetChangeTimer &) = delete; + AssetChangeTimer(FlatObjectStore *flatObjectStore, std::shared_ptr watcher); + void StartTimer(const std::string &sessionId, const std::string &assetKey); + void StopTimer(const std::string &sessionId, const std::string &assetKey); + std::function ProcessTask(const std::string &sessionId, const std::string &assetKey); + uint32_t HandleAssetChanges(const std::string &sessionId, const std::string &assetKey); + bool GetAssetValue(const std::string &sessionId, const std::string &assetKey, Asset &assetValue); + + std::mutex mutex_; + std::unordered_map assetChangeTasks_; + FlatObjectStore *flatObjectStore_ = nullptr; + std::shared_ptr executor_; + std::shared_ptr watcher_; + + static std::mutex instanceMutex; + static AssetChangeTimer *instance; + static constexpr size_t MAX_THREADS = 3; + static constexpr size_t MIN_THREADS = 0; + static constexpr uint32_t WAIT_INTERVAL = 100; + static constexpr char ASSET_SEPARATOR = '#'; +}; +} // namespace OHOS::ObjectStore +#endif // ASSET_CHANGE_TIMER_H \ No newline at end of file diff --git a/data_object/frameworks/innerkitsimpl/include/common/bytes_utils.h b/data_object/frameworks/innerkitsimpl/include/common/bytes_utils.h new file mode 100644 index 00000000..9e34d725 --- /dev/null +++ b/data_object/frameworks/innerkitsimpl/include/common/bytes_utils.h @@ -0,0 +1,60 @@ +/* + * Copyright (c) 2022 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef BYTES_UTILS_H +#define BYTES_UTILS_H + +#include + +#include "bytes.h" +#include "logger.h" +#include "objectstore_errors.h" + +namespace OHOS::ObjectStore { +class BytesUtils final { +public: + BytesUtils() = delete; + ~BytesUtils() = delete; + + static void PutNum(void *val, uint32_t offset, uint32_t valLen, Bytes &data) + { + uint32_t len = valLen + offset; + if (len > sizeof(data.front()) * data.size()) { + data.resize(len); + } + + for (uint32_t i = 0; i < valLen; i++) { + // 8 bit = 1 byte + data[offset + i] = *(static_cast(val)) >> ((valLen - i - 1) * 8); + } + } + + static uint32_t GetNum(Bytes &data, uint32_t offset, void *val, uint32_t valLen) + { + uint8_t *value = static_cast(val); + uint32_t len = offset + valLen; + uint32_t dataLen = data.size(); + if (dataLen < len) { + LOG_ERROR("GetNum data.size() %{public}d, offset %{public}d, valLen %{public}d", dataLen, offset, valLen); + return ERR_DATA_LEN; + } + for (uint32_t i = 0; i < valLen; i++) { + value[i] = data[len - 1 - i]; + } + return SUCCESS; + } +}; +} // namespace OHOS::ObjectStore +#endif // BYTES_UTILS_H diff --git a/data_object/frameworks/innerkitsimpl/include/common/object_types_util.h b/data_object/frameworks/innerkitsimpl/include/common/object_types_util.h new file mode 100644 index 00000000..7253e51e --- /dev/null +++ b/data_object/frameworks/innerkitsimpl/include/common/object_types_util.h @@ -0,0 +1,30 @@ +/* + * Copyright (c) 2022 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef DISTRIBUTED_OBJECT_TYPES_UTIL_H +#define DISTRIBUTED_OBJECT_TYPES_UTIL_H + +#include "itypes_util.h" +#include "object_types.h" + +namespace OHOS::ITypesUtil { +using AssetBindInfo = OHOS::ObjectStore::AssetBindInfo; + +template<> +API_EXPORT bool Marshalling(const AssetBindInfo &input, MessageParcel &data); +template<> +API_EXPORT bool Unmarshalling(AssetBindInfo &output, MessageParcel &data); +} +#endif // DISTRIBUTED_RDB_RDB_TYPES_UTIL_H diff --git a/data_object/frameworks/innerkitsimpl/src/adaptor/asset_change_timer.cpp b/data_object/frameworks/innerkitsimpl/src/adaptor/asset_change_timer.cpp new file mode 100644 index 00000000..b59145ad --- /dev/null +++ b/data_object/frameworks/innerkitsimpl/src/adaptor/asset_change_timer.cpp @@ -0,0 +1,140 @@ + /* + * Copyright (c) 2022 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +#define LOG_TAG "AssetChangeTimer" + +#include "asset_change_timer.h" +#include "client_adaptor.h" +#include "logger.h" +#include "objectstore_errors.h" + +namespace OHOS::ObjectStore { +std::mutex AssetChangeTimer::instanceMutex; +AssetChangeTimer *AssetChangeTimer::instance = nullptr; + +AssetChangeTimer *AssetChangeTimer::GetInstance( + FlatObjectStore *flatObjectStore, std::shared_ptr watcher) +{ + if (instance == nullptr) { + std::lock_guard lockGuard(instanceMutex); + if (instance == nullptr) { + instance = new (std::nothrow) AssetChangeTimer(flatObjectStore, watcher); + } + } + return instance; +} + +AssetChangeTimer::AssetChangeTimer(FlatObjectStore *flatObjectStore, std::shared_ptr watcher) +{ + flatObjectStore_ = flatObjectStore; + watcher_ = watcher; + executor_ = std::make_shared(MAX_THREADS, MIN_THREADS); +} + +void AssetChangeTimer::OnAssetChanged(const std::string &sessionId, const std::string &assetKey) +{ + StartTimer(sessionId, assetKey); +} + +void AssetChangeTimer::StartTimer(const std::string &sessionId, const std::string &assetKey) +{ + std::string key = sessionId + ASSET_SEPARATOR + assetKey; + std::lock_guard lockGuard(mutex_); + if (assetChangeTasks_.find(key) == assetChangeTasks_.end()) { + assetChangeTasks_[key] = executor_->Schedule( + std::chrono::milliseconds(WAIT_INTERVAL), ProcessTask(sessionId, assetKey)); + } else { + assetChangeTasks_[key] = executor_->Reset(assetChangeTasks_[key], std::chrono::milliseconds(WAIT_INTERVAL)); + } +} + +std::function AssetChangeTimer::ProcessTask(const std::string &sessionId, const std::string &assetKey) +{ + return [=]() { + LOG_DEBUG("Start working on a task, sessionId: %{public}s, assetKey: %{public}s", sessionId.c_str(), + assetKey.c_str()); + StopTimer(sessionId, assetKey); + uint32_t status = HandleAssetChanges(sessionId, assetKey); + if (status == SUCCESS) { + LOG_DEBUG("Asset change task end, start callback, sessionId: %{public}s, assetKey: %{public}s", + sessionId.c_str(), assetKey.c_str()); + watcher_->OnChanged(sessionId, {assetKey}); + } + }; +} + +void AssetChangeTimer::StopTimer(const std::string &sessionId, const std::string &assetKey) +{ + std::string key = sessionId + ASSET_SEPARATOR + assetKey; + std::lock_guard lockGuard(mutex_); + executor_->Remove(assetChangeTasks_[key]); + assetChangeTasks_.erase(key); +} + +uint32_t AssetChangeTimer::HandleAssetChanges(const std::string &sessionId, const std::string &assetKey) +{ + Asset assetValue; + if (!GetAssetValue(sessionId, assetKey, assetValue)) { + LOG_ERROR("GetAssetValue assetValue is not complete, sessionId: %{public}s, assetKey: %{public}s", + sessionId.c_str(), assetKey.c_str()); + return ERR_DB_GET_FAIL; + } + + std::string deviceId; + uint32_t status = flatObjectStore_->GetString(sessionId, DEVICEID_KEY, deviceId); + if (status != SUCCESS) { + LOG_ERROR("get deviceId failed %{public}d", status); + return status; + } + + sptr proxy = ClientAdaptor::GetObjectService(); + if (proxy == nullptr) { + LOG_ERROR("proxy is nullptr."); + return ERR_NULL_PTR; + } + status = proxy->OnAssetChanged(flatObjectStore_->GetBundleName(), sessionId, deviceId, assetValue); + if (status != SUCCESS) { + LOG_ERROR("OnAssetChanged failed status: %{public}d, sessionId: %{public}s, assetKey: %{public}s", + status, sessionId.c_str(), assetKey.c_str()); + } + return status; +} + +bool AssetChangeTimer::GetAssetValue(const std::string &sessionId, const std::string &assetKey, Asset &assetValue) +{ + double doubleStatus; + if (flatObjectStore_->GetDouble(sessionId, assetKey + STATUS_SUFFIX, doubleStatus) == SUCCESS) { + assetValue.status = static_cast(doubleStatus); + } + bool isComplete = true; + isComplete &= (flatObjectStore_->GetString(sessionId, assetKey + NAME_SUFFIX, assetValue.name) == SUCCESS); + isComplete &= (flatObjectStore_->GetString(sessionId, assetKey + URI_SUFFIX, assetValue.uri) == SUCCESS); + isComplete &= (flatObjectStore_->GetString(sessionId, assetKey + PATH_SUFFIX, assetValue.path) == SUCCESS); + isComplete &= + (flatObjectStore_->GetString(sessionId, assetKey + CREATE_TIME_SUFFIX, assetValue.createTime) == SUCCESS); + isComplete &= + (flatObjectStore_->GetString(sessionId, assetKey + MODIFY_TIME_SUFFIX, assetValue.modifyTime) == SUCCESS); + isComplete &= (flatObjectStore_->GetString(sessionId, assetKey + SIZE_SUFFIX, assetValue.size) == SUCCESS); + if (isComplete) { + assetValue.name = assetValue.name.substr(STRING_PREFIX_LEN); + assetValue.uri = assetValue.uri.substr(STRING_PREFIX_LEN); + assetValue.path = assetValue.path.substr(STRING_PREFIX_LEN); + assetValue.createTime = assetValue.createTime.substr(STRING_PREFIX_LEN); + assetValue.modifyTime = assetValue.modifyTime.substr(STRING_PREFIX_LEN); + assetValue.size = assetValue.size.substr(STRING_PREFIX_LEN); + assetValue.hash = assetValue.modifyTime + "_" + assetValue.size; + } + return isComplete; +} +} // namespace OHOS::ObjectStore \ No newline at end of file diff --git a/data_object/frameworks/innerkitsimpl/src/object_types_util.cpp b/data_object/frameworks/innerkitsimpl/src/object_types_util.cpp new file mode 100644 index 00000000..101e2e77 --- /dev/null +++ b/data_object/frameworks/innerkitsimpl/src/object_types_util.cpp @@ -0,0 +1,31 @@ +/* + * Copyright (c) 2022 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "object_types_util.h" + +namespace OHOS::ITypesUtil { +template<> +bool Marshalling(const AssetBindInfo &input, MessageParcel &data) +{ + return ITypesUtil::Marshal(data, input.storeName, input.tableName, input.primaryKey, input.field, + input.assetName); +} +template<> +bool Unmarshalling(AssetBindInfo &output, MessageParcel &data) +{ + return ITypesUtil::Unmarshal(data, output.storeName, output.tableName, output.primaryKey, output.field, + output.assetName); +} +} diff --git a/data_object/interfaces/innerkits/object_types.h b/data_object/interfaces/innerkits/object_types.h new file mode 100644 index 00000000..98e7dcd6 --- /dev/null +++ b/data_object/interfaces/innerkits/object_types.h @@ -0,0 +1,48 @@ +/* + * Copyright (c) 2022 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef OHOS_OBJECT_ASSET_VALUE_H +#define OHOS_OBJECT_ASSET_VALUE_H + +#include +#include "common_values_bucket.h" + +namespace OHOS { +namespace ObjectStore { +struct AssetBindInfo { + std::string storeName; + std::string tableName; + CommonType::ValuesBucket primaryKey; + std::string field; + std::string assetName; +}; + +using Asset = CommonType::AssetValue; +using ValuesBucket = CommonType::ValuesBucket; +using ValueObject = CommonType::ValueObject; +using Assets = std::vector; + +static const std::string STATUS_SUFFIX = ".status"; +static const std::string NAME_SUFFIX = ".name"; +static const std::string URI_SUFFIX = ".uri"; +static const std::string PATH_SUFFIX = ".path"; +static const std::string CREATE_TIME_SUFFIX = ".createTime"; +static const std::string MODIFY_TIME_SUFFIX = ".modifyTime"; +static const std::string SIZE_SUFFIX = ".size"; +static const std::string ASSET_DOT = "."; +static const std::string DEVICEID_KEY = "__deviceId"; +} // namespace ObjectStore +} // namespace OHOS +#endif // OHOS_OBJECT_ASSET_VALUE_H \ No newline at end of file diff --git a/datamgr_service/services/distributeddataservice/framework/cloud/cloud_extra_data.cpp b/datamgr_service/services/distributeddataservice/framework/cloud/cloud_extra_data.cpp new file mode 100644 index 00000000..fdd7f41e --- /dev/null +++ b/datamgr_service/services/distributeddataservice/framework/cloud/cloud_extra_data.cpp @@ -0,0 +1,65 @@ +/* + * 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/cloud_extra_data.h" + +namespace OHOS::DistributedData { +bool ExtensionInfo::Marshal(Serializable::json &node) const +{ + SetValue(node[GET_NAME(accountId)], accountId); + SetValue(node[GET_NAME(bundleName)], bundleName); + SetValue(node[GET_NAME(containerName)], containerName); + SetValue(node[GET_NAME(databaseScopes)], databaseScopes); + SetValue(node[GET_NAME(recordTypes)], recordTypes); + return true; +} + +bool ExtensionInfo::Unmarshal(const Serializable::json &node) +{ + GetValue(node, GET_NAME(accountId), accountId); + GetValue(node, GET_NAME(bundleName), bundleName); + GetValue(node, GET_NAME(containerName), containerName); + GetValue(node, GET_NAME(databaseScopes), databaseScopes); + if (!Unmarshall(databaseScopes, scopes)) { + return false; + } + GetValue(node, GET_NAME(recordTypes), recordTypes); + return Unmarshall(recordTypes, tables); +} + +bool ExtraData::Marshal(Serializable::json &node) const +{ + SetValue(node[GET_NAME(header)], header); + SetValue(node[GET_NAME(data)], data); + return true; +} + +bool ExtraData::Unmarshal(const Serializable::json &node) +{ + GetValue(node, GET_NAME(header), header); + GetValue(node, GET_NAME(data), data); + return info.Unmarshall(data); +} + +bool ExtraData::isPrivate() const +{ + return (std::find(info.scopes.begin(), info.scopes.end(), PRIVATE_TABLE) != info.scopes.end()); +} + +bool ExtraData::isShared() const +{ + return (std::find(info.scopes.begin(), info.scopes.end(), SHARED_TABLE) != info.scopes.end()); +} +} // namespace OHOS::DistributedData \ No newline at end of file diff --git a/datamgr_service/services/distributeddataservice/framework/include/cloud/cloud_extra_data.h b/datamgr_service/services/distributeddataservice/framework/include/cloud/cloud_extra_data.h new file mode 100644 index 00000000..c4d89192 --- /dev/null +++ b/datamgr_service/services/distributeddataservice/framework/include/cloud/cloud_extra_data.h @@ -0,0 +1,51 @@ +/* + * 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 DISTRIBUTEDDATAMGR_DATAMGR_SERVICE5_CLOUD_EXTRA_DATA_H +#define DISTRIBUTEDDATAMGR_DATAMGR_SERVICE5_CLOUD_EXTRA_DATA_H + +#include "metadata/store_meta_data.h" +#include "serializable/serializable.h" + +namespace OHOS::DistributedData { +class API_EXPORT ExtensionInfo final : public Serializable { +public: + std::string accountId; + std::string bundleName; + std::string containerName; + std::string databaseScopes; + std::vector scopes; + std::string recordTypes; + std::vector tables; + bool Marshal(json &node) const override; + bool Unmarshal(const json &node) override; +}; + +class API_EXPORT ExtraData final : public Serializable { +public: + std::string header; + std::string data; + ExtensionInfo info; + + bool Marshal(json &node) const override; + bool Unmarshal(const json &node) override; + bool isPrivate() const; + bool isShared() const; + + static constexpr const char *PRIVATE_TABLE = "private"; + static constexpr const char *SHARED_TABLE = "shared"; +}; +} +#endif // DISTRIBUTEDDATAMGR_DATAMGR_SERVICE5_CLOUD_EXTRA_DATA_H diff --git a/datamgr_service/services/distributeddataservice/framework/include/snapshot/bind_event.h b/datamgr_service/services/distributeddataservice/framework/include/snapshot/bind_event.h new file mode 100644 index 00000000..a87e4130 --- /dev/null +++ b/datamgr_service/services/distributeddataservice/framework/include/snapshot/bind_event.h @@ -0,0 +1,53 @@ +/* + * 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_DISTRIBUTED_DATA_SERVICES_FRAMEWORK_SNAPSHOT_BIND_EVENT_H +#define OHOS_DISTRIBUTED_DATA_SERVICES_FRAMEWORK_SNAPSHOT_BIND_EVENT_H + +#include + +#include "eventcenter/event.h" +#include "snapshot.h" + +namespace OHOS::DistributedData { +class API_EXPORT BindEvent : public Event { +public: + enum : int32_t { + BIND_SNAPSHOT, + COMPENSATE_SYNC, + }; + + struct BindEventInfo { + uint32_t tokenId = 0; + int32_t instanceId = 0; + int32_t user; + std::string bundleName; + std::string storeName; + std::string tableName; + VBucket primaryKey; + std::string filed; + std::string assetName; + }; + + BindEvent(int32_t evtId, BindEventInfo&& bindInfo); + + ~BindEvent() = default; + const BindEventInfo& GetBindInfo() const; + +private: + BindEventInfo bindInfo_; +}; +} // namespace OHOS::DistributedData +#endif // OHOS_DISTRIBUTED_DATA_SERVICES_FRAMEWORK_SNAPSHOT_BIND_EVENT_H diff --git a/datamgr_service/services/distributeddataservice/framework/include/snapshot/machine_status.h b/datamgr_service/services/distributeddataservice/framework/include/snapshot/machine_status.h new file mode 100644 index 00000000..8d4aa0bf --- /dev/null +++ b/datamgr_service/services/distributeddataservice/framework/include/snapshot/machine_status.h @@ -0,0 +1,63 @@ +/* + * 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_DISTRIBUTED_DATA_SERVICES_FRAMEWORK_SNAPSHOT_MACHINE_STATUS_H +#define OHOS_DISTRIBUTED_DATA_SERVICES_FRAMEWORK_SNAPSHOT_MACHINE_STATUS_H + +#include "store/general_value.h" + +namespace OHOS { +namespace DistributedData { + +enum TransferStatus : int32_t { + STATUS_STABLE = 0, + STATUS_TRANSFERRING, + STATUS_DOWNLOADING, + STATUS_UPLOADING, + STATUS_WAIT_TRANSFER, + STATUS_WAIT_UPLOAD, + STATUS_WAIT_DOWNLOAD, + STATUS_BUTT, + STATUS_NO_CHANGE = 0XFFFFFFF, +}; + +enum AssetEvent { + REMOTE_CHANGED = 0, + TRANSFER_FINISHED, + UPLOAD, + UPLOAD_FINISHED, + DOWNLOAD, + DOWNLOAD_FINISHED, + EVENT_BUTT, +}; + +struct AssetBindInfo { + std::string storeName; + std::string tableName; + DistributedData::VBucket primaryKey; + std::string field; + std::string assetName; +}; + +struct StoreInfo { + uint32_t tokenId = 0; + int32_t instanceId = 0; + int32_t user; + std::string bundleName; + std::string storeName; +}; +} // namespace DistributedData +} // namespace OHOS +#endif // OHOS_DISTRIBUTED_DATA_SERVICES_FRAMEWORK_SNAPSHOT_MACHINE_STATUS_H diff --git a/datamgr_service/services/distributeddataservice/framework/include/snapshot/snapshot.h b/datamgr_service/services/distributeddataservice/framework/include/snapshot/snapshot.h new file mode 100644 index 00000000..6cfbbfcf --- /dev/null +++ b/datamgr_service/services/distributeddataservice/framework/include/snapshot/snapshot.h @@ -0,0 +1,53 @@ +/* + * 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_DISTRIBUTED_DATA_SERVICES_FRAMEWORK_SNAPSHOT_SNAPSHOT_H +#define OHOS_DISTRIBUTED_DATA_SERVICES_FRAMEWORK_SNAPSHOT_SNAPSHOT_H +#include "machine_status.h" +#include "store/general_value.h" +#include "visibility.h" +namespace OHOS { +namespace DistributedData { + +class API_EXPORT Snapshot { +public: + virtual ~Snapshot() = default; + + virtual int32_t Transferred(Asset& asset) = 0; + + virtual int32_t Upload(Asset& asset) = 0; + + virtual int32_t Download(Asset& asset) = 0; + + virtual int32_t Uploaded(Asset& asset) = 0; + + virtual int32_t Downloaded(Asset& asset) = 0; + + virtual TransferStatus GetAssetStatus(Asset& asset) = 0; + + virtual int32_t BindAsset(const Asset& asset, const AssetBindInfo& bindInfo, const StoreInfo& storeInfo) = 0; + + virtual int32_t OnDataChanged(Asset& asset, const std::string &deviceId) = 0; + + virtual bool IsBoundAsset(const Asset& asset) = 0; + +}; + +struct BindAssets { + std::shared_ptr>> bindAssets; +}; +} // namespace DistributedData +} // namespace OHOS +#endif // OHOS_DISTRIBUTED_DATA_SERVICES_FRAMEWORK_SNAPSHOT_SNAPSHOT_H diff --git a/datamgr_service/services/distributeddataservice/framework/snapshot/bind_event.cpp b/datamgr_service/services/distributeddataservice/framework/snapshot/bind_event.cpp new file mode 100644 index 00000000..1fe5c649 --- /dev/null +++ b/datamgr_service/services/distributeddataservice/framework/snapshot/bind_event.cpp @@ -0,0 +1,27 @@ +/* + * 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 "snapshot/bind_event.h" + +namespace OHOS::DistributedData { +BindEvent::BindEvent(int32_t evtId, BindEventInfo&& bindInfo) : Event(evtId), bindInfo_(std::move(bindInfo)) +{ +} + +const BindEvent::BindEventInfo& BindEvent::GetBindInfo() const +{ + return bindInfo_; +} +} // namespace OHOS::DistributedData diff --git a/datamgr_service/services/distributeddataservice/framework/snapshot/snapshot.cpp b/datamgr_service/services/distributeddataservice/framework/snapshot/snapshot.cpp new file mode 100644 index 00000000..ef3e82cf --- /dev/null +++ b/datamgr_service/services/distributeddataservice/framework/snapshot/snapshot.cpp @@ -0,0 +1,61 @@ +/* + * 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 "snapshot/snapshot.h" +namespace OHOS::DistributedData { + +int32_t Snapshot::Upload(OHOS::DistributedData::Asset& asset) +{ + return E_OK; +} + +int32_t Snapshot::Download(OHOS::DistributedData::Asset& asset) +{ + return E_OK; +} +int32_t Snapshot::Uploaded(Asset& asset) +{ + return E_OK; +} +int32_t Snapshot::Downloaded(Asset& asset) +{ + return E_OK; +} + +int32_t Snapshot::Transferred(Asset& asset) +{ + return E_OK; +} + +TransferStatus Snapshot::GetAssetStatus(Asset& asset) +{ + return STATUS_BUTT; +} + +int32_t Snapshot::BindAsset(const Asset& asset, const AssetBindInfo& bindInfo, const StoreInfo& storeInfo) +{ + return E_OK; +} + +int32_t Snapshot::OnDataChanged(Asset& asset, const std::string &deviceId) +{ + return E_OK; +} + +bool Snapshot::IsBoundAsset(const Asset& asset) +{ + return false; +} +} // namespace OHOS::DistributedData diff --git a/datamgr_service/services/distributeddataservice/service/rdb/value_proxy.cpp b/datamgr_service/services/distributeddataservice/service/common/value_proxy.cpp similarity index 83% rename from datamgr_service/services/distributeddataservice/service/rdb/value_proxy.cpp rename to datamgr_service/services/distributeddataservice/service/common/value_proxy.cpp index 9ed21cdc..2eb65b42 100644 --- a/datamgr_service/services/distributeddataservice/service/rdb/value_proxy.cpp +++ b/datamgr_service/services/distributeddataservice/service/common/value_proxy.cpp @@ -15,7 +15,7 @@ #define LOG_TAG "ValueProxy" #include "value_proxy.h" -namespace OHOS::DistributedRdb { +namespace OHOS::DistributedData { using namespace OHOS::DistributedData; ValueProxy::Value ValueProxy::Convert(DistributedData::Value &&value) { @@ -31,6 +31,13 @@ ValueProxy::Value ValueProxy::Convert(NativeRdb::ValueObject &&value) return proxy; } +ValueProxy::Value ValueProxy::Convert(CommonType::ValueObject &&value) +{ + Value proxy; + DistributedData::Convert(std::move(value.value), proxy.value_); + return proxy; +} + ValueProxy::Value ValueProxy::Convert(DistributedDB::Type &&value) { Value proxy; @@ -58,6 +65,16 @@ ValueProxy::Values ValueProxy::Convert(std::vector &&val return proxy; } +ValueProxy::Values ValueProxy::Convert(std::vector &&values) +{ + Values proxy; + proxy.value_.reserve(values.size()); + for (auto &value : values) { + proxy.value_.emplace_back(Convert(std::move(value))); + } + return proxy; +} + ValueProxy::Values ValueProxy::Convert(std::vector &&values) { Values proxy; @@ -86,6 +103,15 @@ ValueProxy::Bucket ValueProxy::Convert(NativeRdb::ValuesBucket &&bucket) return proxy; } +ValueProxy::Bucket ValueProxy::Convert(CommonType::ValuesBucket &&bucket) +{ + ValueProxy::Bucket proxy; + for (auto &[key, value] : bucket.values_) { + proxy.value_.insert_or_assign(key, Convert(std::move(value))); + } + return proxy; +} + ValueProxy::Bucket ValueProxy::Convert(DistributedDB::VBucket &&bucket) { ValueProxy::Bucket proxy; @@ -105,6 +131,16 @@ ValueProxy::Buckets ValueProxy::Convert(std::vector &&b return proxy; } +ValueProxy::Buckets ValueProxy::Convert(std::vector &&buckets) +{ + ValueProxy::Buckets proxy; + proxy.value_.reserve(buckets.size()); + for (auto &bucket : buckets) { + proxy.value_.emplace_back(Convert(std::move(bucket))); + } + return proxy; +} + ValueProxy::Buckets ValueProxy::Convert(std::vector &&buckets) { ValueProxy::Buckets proxy; @@ -161,6 +197,21 @@ ValueProxy::Asset::Asset(NativeRdb::AssetValue asset) .path = std::move(asset.path) }; } +ValueProxy::Asset::Asset(CommonType::AssetValue asset) +{ + asset_ = DistributedData::Asset { .version = asset.version, + .status = asset.status, + .expiresTime = asset.expiresTime, + .id = std::move(asset.id), + .name = std::move(asset.name), + .uri = std::move(asset.uri), + .createTime = std::move(asset.createTime), + .modifyTime = std::move(asset.modifyTime), + .size = std::move(asset.size), + .hash = std::move(asset.hash), + .path = std::move(asset.path) }; +} + ValueProxy::Asset::Asset(DistributedDB::Asset asset) { asset_ = DistributedData::Asset { .version = asset.version, @@ -209,6 +260,21 @@ ValueProxy::Asset::operator NativeRdb::AssetValue() .path = std::move(asset_.path) }; } +ValueProxy::Asset::operator CommonType::AssetValue() +{ + return CommonType::AssetValue { .version = asset_.version, + .status = asset_.status, + .expiresTime = asset_.expiresTime, + .id = std::move(asset_.id), + .name = std::move(asset_.name), + .uri = std::move(asset_.uri), + .createTime = std::move(asset_.createTime), + .modifyTime = std::move(asset_.modifyTime), + .size = std::move(asset_.size), + .hash = std::move(asset_.hash), + .path = std::move(asset_.path) }; +} + ValueProxy::Asset::operator DistributedData::Asset() { return std::move(asset_); @@ -305,6 +371,15 @@ ValueProxy::Assets::Assets(NativeRdb::ValueObject::Assets assets) } } +ValueProxy::Assets::Assets(CommonType::ValueObject::Assets assets) +{ + assets_.clear(); + assets_.reserve(assets.size()); + for (auto &asset : assets) { + assets_.emplace_back(std::move(asset)); + } +} + ValueProxy::Assets::Assets(DistributedDB::Assets assets) { assets_.clear(); @@ -342,6 +417,16 @@ ValueProxy::Assets::operator NativeRdb::ValueObject::Assets() return assets; } +ValueProxy::Assets::operator CommonType::ValueObject::Assets() +{ + CommonType::ValueObject::Assets assets; + assets.reserve(assets_.size()); + for (auto &asset : assets_) { + assets.push_back(std::move(asset)); + } + return assets; +} + ValueProxy::Assets::operator DistributedData::Assets() { DistributedData::Assets assets; @@ -378,6 +463,13 @@ ValueProxy::Value::operator NativeRdb::ValueObject() return object; } +ValueProxy::Value::operator CommonType::ValueObject() +{ + CommonType::ValueObject object; + DistributedData::Convert(std::move(value_), object.value); + return object; +} + ValueProxy::Value::operator DistributedData::Value() { DistributedData::Value value; @@ -420,6 +512,16 @@ ValueProxy::Bucket::operator NativeRdb::ValuesBucket() return bucket; } +ValueProxy::Bucket::operator CommonType::ValuesBucket() +{ + CommonType::ValuesBucket bucket; + for (auto &[key, value] : value_) { + bucket.values_.insert_or_assign(key, std::move(value)); + } + value_.clear(); + return bucket; +} + ValueProxy::Buckets &ValueProxy::Buckets::operator=(Buckets &&buckets) noexcept { if (this == &buckets) { @@ -487,4 +589,4 @@ uint32_t ValueProxy::TempAsset::ConvertToDataStatus(const uint32_t &status) } return lowStatus | highStatus; } -} // namespace OHOS::DistributedRdb \ No newline at end of file +} // namespace OHOS::DistributedData \ No newline at end of file diff --git a/datamgr_service/services/distributeddataservice/service/rdb/value_proxy.h b/datamgr_service/services/distributeddataservice/service/common/value_proxy.h similarity index 90% rename from datamgr_service/services/distributeddataservice/service/rdb/value_proxy.h rename to datamgr_service/services/distributeddataservice/service/common/value_proxy.h index d3a21f71..af1d1ce7 100644 --- a/datamgr_service/services/distributeddataservice/service/rdb/value_proxy.h +++ b/datamgr_service/services/distributeddataservice/service/common/value_proxy.h @@ -13,15 +13,17 @@ * limitations under the License. */ -#ifndef OHOS_DISTRIBUTED_DATA_DATAMGR_SERVICE_RDB_VALUE_PROXY_H -#define OHOS_DISTRIBUTED_DATA_DATAMGR_SERVICE_RDB_VALUE_PROXY_H +#ifndef OHOS_DISTRIBUTED_DATA_DATAMGR_SERVICE_COMMON_VALUE_PROXY_H +#define OHOS_DISTRIBUTED_DATA_DATAMGR_SERVICE_COMMON_VALUE_PROXY_H #include "asset_value.h" #include "cloud/cloud_store_types.h" +#include "distributeddb/result_set.h" #include "store/general_value.h" #include "value_object.h" #include "values_bucket.h" -#include "distributeddb/result_set.h" -namespace OHOS::DistributedRdb { +#include "common_values_bucket.h" + +namespace OHOS::DistributedData { class ValueProxy final { public: template @@ -54,10 +56,12 @@ public: *this = proxy; }; Asset(DistributedData::Asset asset); + Asset(CommonType::AssetValue asset); Asset(NativeRdb::AssetValue asset); Asset(DistributedDB::Asset asset); Asset &operator=(const Asset &proxy); Asset &operator=(Asset &&proxy) noexcept; + operator CommonType::AssetValue(); operator NativeRdb::AssetValue(); operator DistributedData::Asset(); operator DistributedDB::Asset(); @@ -90,10 +94,12 @@ public: *this = proxy; }; Assets(DistributedData::Assets assets); + Assets(CommonType::ValueObject::Assets assets); Assets(NativeRdb::ValueObject::Assets assets); Assets(DistributedDB::Assets assets); Assets &operator=(const Assets &proxy); Assets &operator=(Assets &&proxy) noexcept; + operator CommonType::ValueObject::Assets(); operator NativeRdb::ValueObject::Assets(); operator DistributedData::Assets(); operator DistributedDB::Assets(); @@ -113,6 +119,7 @@ public: }; Value &operator=(Value &&value) noexcept; operator NativeRdb::ValueObject(); + operator CommonType::ValueObject(); operator DistributedData::Value(); operator DistributedDB::Type(); @@ -173,6 +180,7 @@ public: return bucket; } operator NativeRdb::ValuesBucket(); + operator CommonType::ValuesBucket(); private: friend ValueProxy; @@ -204,16 +212,20 @@ public: }; static Value Convert(DistributedData::Value &&value); + static Value Convert(CommonType::ValueObject &&value); static Value Convert(NativeRdb::ValueObject &&value); static Value Convert(DistributedDB::Type &&value); static Values Convert(DistributedData::Values &&values); + static Values Convert(std::vector &&values); static Values Convert(std::vector &&values); static Values Convert(std::vector &&values); static Bucket Convert(DistributedData::VBucket &&bucket); static Bucket Convert(NativeRdb::ValuesBucket &&bucket); + static Bucket Convert(CommonType::ValuesBucket &&bucket); static Bucket Convert(DistributedDB::VBucket &&bucket); static Buckets Convert(DistributedData::VBuckets &&buckets); static Buckets Convert(std::vector &&buckets); + static Buckets Convert(std::vector &&buckets); static Buckets Convert(std::vector &&buckets); static Value Convert(DistributedDB::VariantData &&value); @@ -256,4 +268,4 @@ private: } }; } // namespace OHOS::DistributedRdb -#endif // OHOS_DISTRIBUTED_DATA_DATAMGR_SERVICE_RDB_VALUE_PROXY_H +#endif // OHOS_DISTRIBUTED_DATA_DATAMGR_SERVICE_COMMON_VALUE_PROXY_H diff --git a/datamgr_service/services/distributeddataservice/service/object/object_asset_loader.cpp b/datamgr_service/services/distributeddataservice/service/object/object_asset_loader.cpp new file mode 100644 index 00000000..9453f869 --- /dev/null +++ b/datamgr_service/services/distributeddataservice/service/object/object_asset_loader.cpp @@ -0,0 +1,71 @@ +/* + * Copyright (c) 2022 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +#define LOG_TAG "ObjectAssetLoader" + +#include "object_asset_loader.h" +#include "block_data.h" +#include "cloud_sync_asset_manager.h" +#include "log_print.h" +#include "object_manager.h" + +namespace OHOS::DistributedObject { +using namespace OHOS::FileManagement::CloudSync; +ObjectAssetLoader *ObjectAssetLoader::GetInstance() +{ + static ObjectAssetLoader *loader = new ObjectAssetLoader(); + return loader; +} + +bool ObjectAssetLoader::DownLoad(const int32_t userId, const std::string &bundleName, + const std::string &deviceId, const DistributedData::Asset &assetValue) +{ + AssetInfo assetInfo; + assetInfo.uri = assetValue.uri; + assetInfo.assetName = assetValue.name; + ZLOGD("start download file, userId: %{public}d, bundleName: %{public}s, networkId: %{public}s, \ + asset name : %{public}s", userId, bundleName.c_str(), deviceId.c_str(), assetValue.name.c_str());\ + + auto block = std::make_shared>>(WAIT_TIME, std::tuple{ true, OBJECT_SUCCESS }); + auto res = CloudSyncAssetManager::GetInstance().DownloadFile(userId, bundleName, deviceId, assetInfo, + [block](const std::string &uri, int32_t status) { + block->SetValue({ false, status }); + }); + if (res != OBJECT_SUCCESS) { + ZLOGE("DownloadFile fail, bundleName: %{public}s, asset name : %{public}s, result: %{public}d", + bundleName.c_str(), assetValue.name.c_str(), res); + return false; + } + auto [timeout, status] = block->GetValue(); + if (timeout || status != OBJECT_SUCCESS) { + ZLOGE("DownloadFile fail, bundleName: %{public}s, asset name : %{public}s, timeout: %{public}d, \ + status: %{public}d", bundleName.c_str(), assetValue.name.c_str(), timeout, status); + return false; + } + return true; +} + +bool ObjectAssetLoader::DownLoad(const int32_t userId, const std::string& bundleName, const std::string& deviceId, + const DistributedData::Asset& assetValue, std::function callback) +{ + AssetInfo assetInfo; + assetInfo.uri = assetValue.uri; + assetInfo.assetName = assetValue.name; + CloudSyncAssetManager::GetInstance().DownloadFile(userId, bundleName, deviceId, assetInfo, + [callback](const std::string& uri, int32_t status) { + status == 0 ? callback(true) : callback(false); + }); + return true; +} +} // namespace OHOS::DistributedObject \ No newline at end of file diff --git a/datamgr_service/services/distributeddataservice/service/object/object_asset_loader.h b/datamgr_service/services/distributeddataservice/service/object/object_asset_loader.h new file mode 100644 index 00000000..f72138a1 --- /dev/null +++ b/datamgr_service/services/distributeddataservice/service/object/object_asset_loader.h @@ -0,0 +1,42 @@ +/* + * Copyright (c) 2022 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +#ifndef DISTRIBUTEDDATAMGR_OBJECT_ASSET_LOADER_H +#define DISTRIBUTEDDATAMGR_OBJECT_ASSET_LOADER_H + +#include +#include "object_types.h" +#include "store/general_value.h" + +namespace OHOS { +namespace DistributedObject { +class ObjectAssetLoader { +public: + static ObjectAssetLoader *GetInstance(); + bool DownLoad(const int32_t userId, const std::string &bundleName, + const std::string &deviceId, const DistributedData::Asset &assetValue); + + bool DownLoad(const int32_t userId, const std::string& bundleName, const std::string& deviceId, + const DistributedData::Asset& assetValue, std::function callback); +private: + ObjectAssetLoader() = default; + ~ObjectAssetLoader() = default; + ObjectAssetLoader(const ObjectAssetLoader &) = delete; + ObjectAssetLoader &operator=(const ObjectAssetLoader &) = delete; + + static constexpr int WAIT_TIME = 60; +}; +} // namespace DistributedObject +} // namespace OHOS +#endif // DISTRIBUTEDDATAMGR_OBJECT_ASSET_LOADER_H \ No newline at end of file diff --git a/datamgr_service/services/distributeddataservice/service/object/object_asset_machine.cpp b/datamgr_service/services/distributeddataservice/service/object/object_asset_machine.cpp new file mode 100644 index 00000000..5bd0e4ae --- /dev/null +++ b/datamgr_service/services/distributeddataservice/service/object/object_asset_machine.cpp @@ -0,0 +1,340 @@ +/* +* 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. +*/ + +#define LOG_TAG "ObjectAssetMachine" +#include "object_asset_machine.h" + +#include +#include + +#include "cloud/change_event.h" +#include "device_manager_adapter.h" +#include "eventcenter/event_center.h" +#include "log_print.h" +#include "metadata/meta_data_manager.h" +#include "object_asset_loader.h" +#include "snapshot/bind_event.h" +#include "store/auto_cache.h" + +namespace OHOS { +namespace DistributedObject { +using namespace OHOS::DistributedData; +using namespace OHOS::DistributedRdb; +using DmAdapter = OHOS::DistributedData::DeviceManagerAdapter; + +constexpr static const char* SQL_AND = " = ? and "; +constexpr static const int32_t AND_SIZE = 5; +static int32_t DoTransfer(int32_t eventId, ChangedAssetInfo& changedAsset, std::pair& newAsset); + +static int32_t ChangeAssetToNormal(int32_t eventId, Asset& asset, void*); + +static int32_t CompensateSync(int32_t eventId, ChangedAssetInfo& changedAsset, void*); + +static int32_t CompensateTransferring(int32_t eventId, ChangedAssetInfo& changedAsset, void*); + +static int32_t SaveNewAsset(int32_t eventId, ChangedAssetInfo& changedAsset, std::pair& newAsset); + +static int32_t PrintError(int32_t eventId, ChangedAssetInfo& changedAsset, void*); + +static int32_t UpdateStore(ChangedAssetInfo& changedAsset); + +static AutoCache::Store GetStore(ChangedAssetInfo& changedAsset); +static VBuckets GetMigratedData(AutoCache::Store& store, AssetBindInfo& AssetBindInfo, const Asset& newAsset); +static void MergeAssetData(VBucket& record, const Asset& newAsset, const AssetBindInfo& AssetBindInfo); +static void MergeAsset(Asset& oldAsset, const Asset& newAsset); +static std::string BuildSql(const AssetBindInfo& bindInfo, Values& args); + +static const DFAAction AssetDFA[STATUS_BUTT][EVENT_BUTT] = { + { + // STATUS_STABLE + { STATUS_TRANSFERRING, nullptr, (Action)DoTransfer }, // remote_changed + { STATUS_NO_CHANGE, nullptr, (Action)PrintError }, // transfer_finished + { STATUS_UPLOADING, nullptr, nullptr }, // upload + { STATUS_NO_CHANGE, nullptr, (Action)PrintError }, // upload_finished + { STATUS_DOWNLOADING, nullptr, nullptr }, // download + { STATUS_NO_CHANGE, nullptr, (Action)PrintError }, // upload_finished + }, + { + // TRANSFERRING + { STATUS_WAIT_TRANSFER, nullptr, (Action)SaveNewAsset }, // remote_changed + { STATUS_STABLE, nullptr, nullptr }, // transfer_finished + { STATUS_WAIT_UPLOAD, nullptr, (Action)ChangeAssetToNormal }, // upload + { STATUS_NO_CHANGE, nullptr, (Action)PrintError }, // upload_finished + { STATUS_WAIT_DOWNLOAD, nullptr, (Action)ChangeAssetToNormal }, // download + { STATUS_NO_CHANGE, nullptr, (Action)PrintError }, // upload_finished + }, + { + // DOWNLOADING + { STATUS_WAIT_TRANSFER, nullptr, (Action)SaveNewAsset }, // remote_changed + { STATUS_NO_CHANGE, nullptr, (Action)PrintError }, // transfer_finished + { STATUS_NO_CHANGE, nullptr, (Action)PrintError }, // upload + { STATUS_NO_CHANGE, nullptr, (Action)PrintError }, // upload_finished + { STATUS_NO_CHANGE, nullptr, (Action)PrintError }, // download + { STATUS_STABLE, nullptr, nullptr }, // download_finished + }, + { + // STATUS_UPLOADING + { STATUS_WAIT_TRANSFER, nullptr, (Action)SaveNewAsset }, // remote_changed + { STATUS_NO_CHANGE, nullptr, (Action)PrintError }, // transfer_finished + { STATUS_NO_CHANGE, nullptr, (Action)PrintError }, // upload + { STATUS_STABLE, nullptr, nullptr }, // upload_finished + { STATUS_NO_CHANGE, nullptr, (Action)PrintError }, // download + { STATUS_NO_CHANGE, nullptr, (Action)PrintError }, // download_finished + }, + { + // STATUS_WAIT_TRANSFER + { STATUS_NO_CHANGE, nullptr, (Action)SaveNewAsset }, // remote_changed + { STATUS_STABLE, nullptr, (Action)CompensateTransferring }, // transfer_finished + { STATUS_WAIT_UPLOAD, nullptr, (Action)ChangeAssetToNormal }, // upload + { STATUS_STABLE, nullptr, (Action)CompensateTransferring }, // upload_finished + { STATUS_WAIT_DOWNLOAD, nullptr, (Action)ChangeAssetToNormal }, // download + { STATUS_STABLE, nullptr, (Action)CompensateTransferring }, // download_finished + }, + { + // STATUS_WAIT_UPLOAD + { STATUS_WAIT_TRANSFER, nullptr, (Action)SaveNewAsset }, // remote_changed + { STATUS_STABLE, nullptr, (Action)CompensateSync }, // transfer_finished + { STATUS_NO_CHANGE, nullptr, (Action)PrintError }, // upload + { STATUS_NO_CHANGE, nullptr, (Action)PrintError }, // upload_finished + { STATUS_NO_CHANGE, nullptr, (Action)PrintError }, // download + { STATUS_NO_CHANGE, nullptr, (Action)PrintError }, // download_finished + }, + { + // STATUS_WAIT_DOWNLOAD + { STATUS_WAIT_TRANSFER, nullptr, (Action)SaveNewAsset }, // remote_changed + { STATUS_STABLE, nullptr, (Action)CompensateSync }, // transfer_finished + { STATUS_NO_CHANGE, nullptr, (Action)PrintError }, // upload + { STATUS_NO_CHANGE, nullptr, (Action)PrintError }, // upload_finished + { STATUS_NO_CHANGE, nullptr, (Action)PrintError }, // download + { STATUS_NO_CHANGE, nullptr, (Action)PrintError }, // download_finished + } +}; + +int32_t ObjectAssetMachine::DFAPostEvent(AssetEvent eventId, TransferStatus& status, void* param, void* param2) +{ + if (eventId < 0 || eventId >= EVENT_BUTT) { + return GeneralError::E_ERROR; + } + + const DFAAction* action = &AssetDFA[status][eventId]; + if (action->before != nullptr) { + int32_t res = action->before(eventId, param, param2); + if (res != GeneralError::E_OK) { + return GeneralError::E_ERROR; + } + } + if (action->next != STATUS_NO_CHANGE) { + ZLOGI("status before:%{public}d, eventId: %{public}d, status after:%{public}d", status, eventId, action->next); + status = static_cast(action->next); + } + if (action->after != nullptr) { + int32_t res = action->after(eventId, param, param2); + if (res != GeneralError::E_OK) { + return GeneralError::E_ERROR; + } + } + return GeneralError::E_OK; +} + +static int32_t DoTransfer(int32_t eventId, ChangedAssetInfo& changedAsset, std::pair& newAsset) +{ + changedAsset.deviceId = newAsset.first; + changedAsset.asset = newAsset.second; + ObjectAssetLoader::GetInstance()->DownLoad(changedAsset.storeInfo.user, changedAsset.storeInfo.bundleName, + changedAsset.deviceId, changedAsset.asset, [&changedAsset](bool success) { + if (success) { + auto status = UpdateStore(changedAsset); + if (status != E_OK) { + ZLOGE("UpdateStore error, error:%{public}d, assetName:%{public}s, store:%{public}s, " + "table:%{public}s", + status, changedAsset.asset.name.c_str(), + Anonymous::Change(changedAsset.bindInfo.storeName).c_str(), + changedAsset.bindInfo.tableName.c_str()); + } + } + ObjectAssetMachine::DFAPostEvent(TRANSFER_FINISHED, changedAsset.status, (void*)&changedAsset, nullptr); + }); + return E_OK; +} + +static int32_t UpdateStore(ChangedAssetInfo& changedAsset) +{ + auto store = GetStore(changedAsset); + if (store == nullptr) { + ZLOGE("store null, storeId:%{public}s", Anonymous::Change(changedAsset.bindInfo.storeName).c_str()); + return E_ERROR; + } + + VBuckets vBuckets = GetMigratedData(store, changedAsset.bindInfo, changedAsset.asset); + if (vBuckets.empty()) { + return E_OK; + } + return store->MergeMigratedData(changedAsset.bindInfo.tableName, std::move(vBuckets)); +} + +static VBuckets GetMigratedData(AutoCache::Store& store, AssetBindInfo& AssetBindInfo, const Asset& newAsset) +{ + Values args; + VBuckets vBuckets; + auto sql = BuildSql(AssetBindInfo, args); + auto cursor = store->Query(AssetBindInfo.tableName, sql, std::move(args)); + if (cursor == nullptr) { + return vBuckets; + } + int32_t count = cursor->GetCount(); + if (count != 1) { + return vBuckets; + } + vBuckets.reserve(count); + auto err = cursor->MoveToFirst(); + while (err == E_OK && count > 0) { + VBucket entry; + err = cursor->GetRow(entry); + if (err != E_OK) { + return vBuckets; + } + MergeAssetData(entry, newAsset, AssetBindInfo); + vBuckets.emplace_back(std::move(entry)); + err = cursor->MoveToNext(); + count--; + } + return vBuckets; +} + +static std::string BuildSql(const AssetBindInfo& bindInfo, Values& args) +{ + std::string sql; + sql.append("SELECT ").append(bindInfo.field).append(" FROM ").append(bindInfo.tableName).append(" WHERE "); + for (auto const& [key, value] : bindInfo.primaryKey) { + sql.append(key).append(SQL_AND); + args.emplace_back(value); + } + sql = sql.substr(0, sql.size() - AND_SIZE); + return sql; +} + +static void MergeAssetData(VBucket& record, const Asset& newAsset, const AssetBindInfo& assetBindInfo) +{ + for (auto const& [key, primary] : assetBindInfo.primaryKey) { + record[key] = primary; + } + + auto it = record.find(assetBindInfo.field); + if (it == record.end()) { + ZLOGD("Not find field:%{public}s in store", assetBindInfo.field.c_str()); + return; + } + + auto& value = it->second; + if (value.index() == TYPE_INDEX) { + Assets assets{ newAsset }; + value = assets; + return; + } + if (value.index() == TYPE_INDEX) { + auto* asset = Traits::get_if(&value); + if (asset->name != newAsset.name) { + ZLOGD("Asset not same, old uri: %{public}s, new uri: %{public}s", asset->uri.c_str(), newAsset.uri.c_str()); + return; + } + } + + if (value.index() == TYPE_INDEX) { + auto* assets = Traits::get_if(&value); + for (auto& asset : *assets) { + if (asset.name == newAsset.name) { + MergeAsset(asset, newAsset); + return; + } + } + assets->emplace_back(newAsset); + } +} + +static void MergeAsset(Asset& oldAsset, const Asset& newAsset) +{ + oldAsset.name = newAsset.name; + oldAsset.uri = newAsset.uri; + oldAsset.modifyTime = newAsset.modifyTime; + oldAsset.createTime = newAsset.createTime; + oldAsset.size = newAsset.size; + oldAsset.hash = newAsset.hash; + oldAsset.path = newAsset.path; +} + +static AutoCache::Store GetStore(ChangedAssetInfo& changedAsset) +{ + StoreMetaData meta; + meta.storeId = changedAsset.bindInfo.storeName; + meta.bundleName = changedAsset.storeInfo.bundleName; + meta.user = std::to_string(changedAsset.storeInfo.user); + meta.instanceId = changedAsset.storeInfo.instanceId; + meta.deviceId = DmAdapter::GetInstance().GetLocalDevice().uuid; + if (!MetaDataManager::GetInstance().LoadMeta(meta.GetKey(), meta)) { + ZLOGE("meta empty, bundleName:%{public}s, storeId:%{public}s", meta.bundleName.c_str(), + meta.GetStoreAlias().c_str()); + return nullptr; + } + return AutoCache::GetInstance().GetStore(meta, {}); +} + +static int32_t CompensateTransferring(int32_t eventId, ChangedAssetInfo& changedAsset, void*) +{ + std::pair newChangedAsset{ changedAsset.deviceId, changedAsset.asset }; + return ObjectAssetMachine::DFAPostEvent(REMOTE_CHANGED, changedAsset.status, (void*)&changedAsset, + (void*)&newChangedAsset); +} + +static int32_t CompensateSync(int32_t eventId, ChangedAssetInfo& changedAsset, void*) +{ + BindEvent::BindEventInfo bindEventInfo; + bindEventInfo.bundleName = changedAsset.storeInfo.bundleName; + bindEventInfo.user = changedAsset.storeInfo.user; + bindEventInfo.tokenId = changedAsset.storeInfo.tokenId; + bindEventInfo.instanceId = changedAsset.storeInfo.instanceId; + bindEventInfo.storeName = changedAsset.bindInfo.storeName; + bindEventInfo.tableName = changedAsset.bindInfo.tableName; + bindEventInfo.filed = changedAsset.bindInfo.field; + bindEventInfo.primaryKey = changedAsset.bindInfo.primaryKey; + bindEventInfo.assetName = changedAsset.bindInfo.assetName; + auto evt = std::make_unique(BindEvent::COMPENSATE_SYNC, std::move(bindEventInfo)); + EventCenter::GetInstance().PostEvent(std::move(evt)); + return E_OK; +} + +static int32_t SaveNewAsset(int32_t eventId, ChangedAssetInfo& changedAsset, std::pair& newAsset) +{ + changedAsset.deviceId = newAsset.first; + changedAsset.asset = newAsset.second; + return E_OK; +} + +static int32_t ChangeAssetToNormal(int32_t eventId, Asset& asset, void*) +{ + asset.status = Asset::STATUS_NORMAL; + return E_OK; +} + +static int32_t PrintError(int32_t eventId, ChangedAssetInfo& changedAsset, void*) +{ + ZLOGE("An abnormal event has occurred, eventId:%{public}d, status:%{public}d, assetName:%{public}s", eventId, + changedAsset.status, changedAsset.asset.name.c_str()); + return E_OK; +} + +ObjectAssetMachine::ObjectAssetMachine() {} + +} // namespace DistributedObject +} // namespace OHOS diff --git a/datamgr_service/services/distributeddataservice/service/object/object_asset_machine.h b/datamgr_service/services/distributeddataservice/service/object/object_asset_machine.h new file mode 100644 index 00000000..2cf54cf4 --- /dev/null +++ b/datamgr_service/services/distributeddataservice/service/object/object_asset_machine.h @@ -0,0 +1,59 @@ +/* +* 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 DISTRIBUTEDDATAMGR_OBJECT_ASSET_MACHINE_H +#define DISTRIBUTEDDATAMGR_OBJECT_ASSET_MACHINE_H + +#include "snapshot/machine_status.h" + +namespace OHOS { +namespace DistributedObject { +using namespace OHOS::DistributedData; +struct ChangedAssetInfo { + ChangedAssetInfo() = default; + std::string deviceId; + DistributedData::Asset asset; + DistributedData::TransferStatus status = DistributedData::STATUS_STABLE; + AssetBindInfo bindInfo; + StoreInfo storeInfo; + + ChangedAssetInfo(const Asset& bindAsset, const AssetBindInfo& AssetBindInfo, const StoreInfo& store) + { + asset = bindAsset; + bindInfo = AssetBindInfo; + storeInfo = store; + } +}; + +typedef int32_t (*Action)(AssetEvent eventId, void* param, void* param2); + +struct DFAAction { + int32_t next; + Action before; + Action after; +}; + +class ObjectAssetMachine { +public: + ObjectAssetMachine(); + + static int32_t DFAPostEvent(AssetEvent eventId, TransferStatus& status, void* param, void* param2); + +private: +}; +} // namespace DistributedObject +} // namespace OHOS +#endif // DISTRIBUTEDDATAMGR_OBJECT_ASSET_MACHINE_H diff --git a/datamgr_service/services/distributeddataservice/service/object/object_snapshot.cpp b/datamgr_service/services/distributeddataservice/service/object/object_snapshot.cpp new file mode 100644 index 00000000..7c3d06cf --- /dev/null +++ b/datamgr_service/services/distributeddataservice/service/object/object_snapshot.cpp @@ -0,0 +1,111 @@ +/* +* 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. +*/ + +#define LOG_TAG "ObjectSnapshot" +#include "object_snapshot.h" + +#include "eventcenter/event_center.h" +#include "log_print.h" +#include "snapshot/bind_event.h" +#include "store/general_store.h" +namespace OHOS::DistributedObject { + +int32_t ObjectSnapshot::Upload(Asset& asset) +{ + if (!IsBoundAsset(asset)) { + return 0; + } + return assetMachine_->DFAPostEvent(UPLOAD, changedAssets_[asset.uri].status, (void*)&asset, nullptr); +} + +bool ObjectSnapshot::IsBoundAsset(const Asset& asset) +{ + auto it = changedAssets_.find(asset.uri); + if (it != changedAssets_.end()) { + return true; + } + return false; +} + +int32_t ObjectSnapshot::Download(Asset& asset) +{ + if (!IsBoundAsset(asset)) { + return 0; + } + return assetMachine_->DFAPostEvent(DOWNLOAD, changedAssets_[asset.uri].status, (void*)&asset, nullptr); +} + +TransferStatus ObjectSnapshot::GetAssetStatus(Asset& asset) +{ + if (!IsBoundAsset(asset)) { + return STATUS_BUTT; + } + return changedAssets_[asset.uri].status; +} + +int32_t ObjectSnapshot::Uploaded(Asset& asset) +{ + if (!IsBoundAsset(asset)) { + return E_OK; + } + return assetMachine_->DFAPostEvent(UPLOAD_FINISHED, changedAssets_[asset.uri].status, + (void*)&changedAssets_[asset.uri], nullptr); +} + +int32_t ObjectSnapshot::Downloaded(Asset& asset) +{ + if (!IsBoundAsset(asset)) { + return E_OK; + } + return assetMachine_->DFAPostEvent(DOWNLOAD_FINISHED, changedAssets_[asset.uri].status, + (void*)&changedAssets_[asset.uri], nullptr); +} + +int32_t ObjectSnapshot::OnDataChanged(Asset& asset, const std::string& deviceId) +{ + if (!IsBoundAsset(asset)) { + return E_OK; + } + std::pair newAsset{ deviceId, asset }; + return assetMachine_->DFAPostEvent(REMOTE_CHANGED, changedAssets_[asset.uri].status, + (void*)&changedAssets_[asset.uri], (void*)&newAsset); +} + +int32_t ObjectSnapshot::BindAsset(const Asset& asset, const DistributedData::AssetBindInfo& bindInfo, + const StoreInfo& storeInfo) +{ + if (IsBoundAsset(asset)) { + ZLOGD("Asset is bound. asset.uri:%{public}s :", asset.uri.c_str()); + return E_OK; + } + changedAssets_[asset.uri] = ChangedAssetInfo(asset, bindInfo, storeInfo); + return E_OK; +} + +int32_t ObjectSnapshot::Transferred(Asset& asset) +{ + if (!IsBoundAsset(asset)) { + return E_OK; + } + return assetMachine_->DFAPostEvent(TRANSFER_FINISHED, changedAssets_[asset.uri].status, + (void*)&changedAssets_[asset.uri], nullptr); +} +ObjectSnapshot::~ObjectSnapshot() {} + +ObjectSnapshot::ObjectSnapshot() +{ + assetMachine_ = std::make_shared(); +} +} // namespace OHOS::DistributedObject \ No newline at end of file diff --git a/datamgr_service/services/distributeddataservice/service/object/object_snapshot.h b/datamgr_service/services/distributeddataservice/service/object/object_snapshot.h new file mode 100644 index 00000000..be6b0fa3 --- /dev/null +++ b/datamgr_service/services/distributeddataservice/service/object/object_snapshot.h @@ -0,0 +1,47 @@ +/* +* 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 DISTRIBUTEDDATAMGR_OBJECT_SNAPSHOT_H +#define DISTRIBUTEDDATAMGR_OBJECT_SNAPSHOT_H + +#include "object_asset_machine.h" +#include "snapshot/snapshot.h" +#include "store/general_value.h" +namespace OHOS { +namespace DistributedObject { +using namespace DistributedData; +class ObjectSnapshot : public Snapshot { +public: + ObjectSnapshot(); + ~ObjectSnapshot() override; + + int32_t Upload(Asset& asset) override; + int32_t Download(Asset& asset) override; + TransferStatus GetAssetStatus(Asset& asset) override; + int32_t Uploaded(Asset& asset) override; + int32_t Downloaded(Asset& asset) override; + int32_t Transferred(Asset& asset) override; + int32_t OnDataChanged(Asset& asset, const std::string& deviceId) override; + int32_t BindAsset(const Asset& asset, const DistributedData::AssetBindInfo& bindInfo, + const StoreInfo& storeInfo) override; + bool IsBoundAsset(const Asset& asset) override; + +private: + std::map changedAssets_; + std::shared_ptr assetMachine_; +}; +} // namespace DistributedObject +} // namespace OHOS +#endif // DISTRIBUTEDDATAMGR_OBJECT_SNAPSHOT_H diff --git a/datamgr_service/services/distributeddataservice/service/object/object_types_utils.cpp b/datamgr_service/services/distributeddataservice/service/object/object_types_utils.cpp new file mode 100644 index 00000000..21f9e7b2 --- /dev/null +++ b/datamgr_service/services/distributeddataservice/service/object/object_types_utils.cpp @@ -0,0 +1,25 @@ +/* +* 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 "object_types_utils.h" + +namespace OHOS::ITypesUtil { +template<> +bool Unmarshalling(AssetBindInfo &output, MessageParcel &data) +{ + return ITypesUtil::Unmarshal(data, output.storeName, output.tableName, output.primaryKey, output.field, + output.assetName); +} +} \ No newline at end of file diff --git a/datamgr_service/services/distributeddataservice/service/object/object_types_utils.h b/datamgr_service/services/distributeddataservice/service/object/object_types_utils.h new file mode 100644 index 00000000..c09af307 --- /dev/null +++ b/datamgr_service/services/distributeddataservice/service/object/object_types_utils.h @@ -0,0 +1,28 @@ +/* +* 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 DISTRIBUTEDDATAMGR_OBJECT_TYPES_UTILS_H +#define DISTRIBUTEDDATAMGR_OBJECT_TYPES_UTILS_H + +#include "itypes_util.h" +#include "object_types.h" +namespace OHOS::ITypesUtil { + +using AssetBindInfo = OHOS::ObjectStore::AssetBindInfo; + +template<> +bool Unmarshalling(AssetBindInfo &output, MessageParcel &data); + +} +#endif // DISTRIBUTEDDATAMGR_OBJECT_TYPES_UTILS_H diff --git a/datamgr_service/services/distributeddataservice/service/test/object_asset_machine_test.cpp b/datamgr_service/services/distributeddataservice/service/test/object_asset_machine_test.cpp new file mode 100644 index 00000000..8d89b8f3 --- /dev/null +++ b/datamgr_service/services/distributeddataservice/service/test/object_asset_machine_test.cpp @@ -0,0 +1,172 @@ +/* + * 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. + */ + +#define LOG_TAG "ObjectAssetMachineTest" + +#include "object_asset_machine.h" + +#include + +#include "log_print.h" +#include "snapshot/machine_status.h" + +using namespace testing::ext; +using namespace OHOS::DistributedObject; +using namespace OHOS::DistributedData; +class ObjectAssetMachineTest : public testing::Test { +public: + void SetUp(); + void TearDown(); + +protected: + AssetBindInfo AssetBindInfo_; + Asset asset_; + std::string uri_; + std::string bundleName_ = "test_bundleName"; + std::map changedAssets_; + std::string sessionId = "123"; + StoreInfo storeInfo_; +}; + +void ObjectAssetMachineTest::SetUp() +{ + uri_ = "file:://com.huawei.hmos.notepad/data/storage/el2/distributedfiles/dir/asset1.jpg"; + Asset asset{ + .name = "test_name", + .uri = uri_, + .modifyTime = "modifyTime", + .size = "size", + .hash = "modifyTime_size", + }; + asset_ = asset; + + VBucket vBucket{ { "11", 111 } }; + AssetBindInfo AssetBindInfo{ + .storeName = "store_test", + .tableName = "table_test", + .primaryKey = vBucket, + .field = "attachment", + .assetName = "asset1.jpg", + }; + AssetBindInfo_ = AssetBindInfo; + StoreInfo storeInfo{ + .tokenId = 0, + .instanceId = 1, + .user = 100, + .bundleName = "bundleName_test", + .storeName = "store_test", + }; + storeInfo_ = storeInfo; + ChangedAssetInfo changedAssetInfo(asset, AssetBindInfo, storeInfo); + changedAssets_[uri_] = changedAssetInfo; +} + +void ObjectAssetMachineTest::TearDown() {} + +/** +* @tc.name: StatusTransfer +* @tc.desc: . +* @tc.type: FUNC +* @tc.require: +* @tc.author: whj +*/ + +HWTEST_F(ObjectAssetMachineTest, StatusTransfer, TestSize.Level0) +{ + auto machine = std::make_shared(); + Asset asset{ + .name = "test_name", + .uri = uri_, + .modifyTime = "modifyTime1", + .size = "size1", + .hash = "modifyTime1_size1", + }; + std::pair changedAsset{ "device_1", asset }; + machine->DFAPostEvent(REMOTE_CHANGED, changedAssets_[uri_].status, (void*)&changedAssets_[uri_], + (void*)&changedAsset); + ASSERT_EQ(changedAssets_[uri_].status, STATUS_TRANSFERRING); + + changedAsset.first = "device_2"; + changedAsset.second.hash = "modifyTime2_size2"; + machine->DFAPostEvent(REMOTE_CHANGED, changedAssets_[uri_].status, (void*)&changedAssets_[uri_], + (void*)&changedAsset); + ASSERT_EQ(changedAssets_[uri_].status, STATUS_WAIT_TRANSFER); + ASSERT_EQ(changedAssets_[uri_].asset.hash, "modifyTime2_size2"); + ASSERT_EQ(changedAssets_[uri_].deviceId, "device_2"); + + machine->DFAPostEvent(TRANSFER_FINISHED, changedAssets_[uri_].status, (void*)&changedAssets_[uri_], (void*)&asset); + + ASSERT_EQ(changedAssets_[uri_].status, STATUS_TRANSFERRING); + + machine->DFAPostEvent(TRANSFER_FINISHED, changedAssets_[uri_].status, (void*)&changedAssets_[uri_], + (void*)&changedAssets_[uri_].asset); + ASSERT_EQ(changedAssets_[uri_].status, STATUS_STABLE); +} + +/** +* @tc.name: StatusTransfer001 +* @tc.desc: No conflict scenarios. Normal object Migration and cloud synchronization processes. +* @tc.type: FUNC +* @tc.require: +* @tc.author: whj +*/ + +HWTEST_F(ObjectAssetMachineTest, StatusTransfer001, TestSize.Level0) +{ + auto machine = std::make_shared(); + Asset asset{ + .name = "test_name", + .uri = uri_, + .modifyTime = "modifyTime1", + .size = "size1", + .hash = "modifyTime1_size1", + }; + std::pair changedAsset{ "device_1", asset }; + machine->DFAPostEvent(REMOTE_CHANGED, changedAssets_[uri_].status, (void*)&changedAssets_[uri_], + (void*)&changedAsset); + ASSERT_EQ(changedAssets_[uri_].status, STATUS_TRANSFERRING); + ASSERT_EQ(changedAssets_[uri_].asset.hash, asset.hash); + ASSERT_EQ(changedAssets_[uri_].deviceId, "device_1"); + machine->DFAPostEvent(TRANSFER_FINISHED, changedAssets_[uri_].status, (void*)&changedAssets_[uri_], + (void*)&changedAssets_[uri_].asset); + ASSERT_EQ(changedAssets_[uri_].status, STATUS_STABLE); +} + +/** +* @tc.name: StatusTransfer002 +* @tc.desc: No conflict scenarios: normal cloud sync. +* @tc.type: FUNC +* @tc.require: +* @tc.author: whj +*/ + +HWTEST_F(ObjectAssetMachineTest, StatusTransfer002, TestSize.Level0) +{ + auto machine = std::make_shared(); + Asset asset{ + .name = "test_name", + .uri = uri_, + .modifyTime = "modifyTime1", + .size = "size1", + .hash = "modifyTime1_size1", + }; + std::pair changedAsset{ "device_1", asset }; + machine->DFAPostEvent(UPLOAD, changedAssets_[uri_].status, (void*)&changedAssets_[uri_].asset, nullptr); + ASSERT_EQ(changedAssets_[uri_].status, STATUS_UPLOADING); + + machine->DFAPostEvent(UPLOAD_FINISHED, changedAssets_[uri_].status, (void*)&changedAssets_[uri_], + (void*)&changedAssets_[uri_].asset); + ASSERT_EQ(changedAssets_[uri_].status, STATUS_STABLE); +} diff --git a/interface_sdk/api/@ohos.data.commonType.d.ts b/interface_sdk/api/@ohos.data.commonType.d.ts new file mode 100644 index 00000000..e34d24eb --- /dev/null +++ b/interface_sdk/api/@ohos.data.commonType.d.ts @@ -0,0 +1,201 @@ +/* + * 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. + */ + +/** + * @file + * @kit ArkData + */ + +/** + * Indicates the common data types. + * + * @namespace commonType + * @syscap SystemCapability.DistributedDataManager.CommonType + * @crossplatform + * @since 11 + */ +declare namespace commonType { + /** + * Describes the status of asset. + * + * @enum { number } + * @syscap SystemCapability.DistributedDataManager.CommonType + * @crossplatform + * @since 11 + */ + enum AssetStatus { + /** + * Means the status of asset is normal. + * + * @syscap SystemCapability.DistributedDataManager.CommonType + * @crossplatform + * @since 11 + */ + ASSET_NORMAL, + + /** + * Means the asset needs to be inserted. + * + * @syscap SystemCapability.DistributedDataManager.CommonType + * @crossplatform + * @since 11 + */ + ASSET_INSERT, + + /** + * Means the asset needs to be updated. + * + * @syscap SystemCapability.DistributedDataManager.CommonType + * @crossplatform + * @since 11 + */ + ASSET_UPDATE, + + /** + * Means the asset needs to be deleted. + * + * @syscap SystemCapability.DistributedDataManager.CommonType + * @crossplatform + * @since 11 + */ + ASSET_DELETE, + + /** + * Means the status of asset is abnormal. + * + * @syscap SystemCapability.DistributedDataManager.CommonType + * @crossplatform + * @since 11 + */ + ASSET_ABNORMAL, + + /** + * Means the status of asset is downloading. + * + * @syscap SystemCapability.DistributedDataManager.CommonType + * @crossplatform + * @since 11 + */ + ASSET_DOWNLOADING + } + + /** + * Information of the asset. + * + * @interface Asset + * @syscap SystemCapability.DistributedDataManager.CommonType + * @crossplatform + * @since 11 + */ + interface Asset { + /** + * The name of asset. + * @type { string } + * @syscap SystemCapability.DistributedDataManager.CommonType + * @crossplatform + * @since 11 + */ + name: string; + + /** + * The uri of asset. + * + * @type { string } + * @syscap SystemCapability.DistributedDataManager.CommonType + * @crossplatform + * @since 11 + */ + uri: string; + + /** + * The path of asset. + * + * @type { string } + * @syscap SystemCapability.DistributedDataManager.CommonType + * @crossplatform + * @since 11 + */ + path: string; + + /** + * The created time of asset. + * + * @type { string } + * @syscap SystemCapability.DistributedDataManager.CommonType + * @crossplatform + * @since 11 + */ + createTime: string; + + /** + * The modified time of asset. If this field changes, the asset is considered to have changed. + * + * @type { string } + * @syscap SystemCapability.DistributedDataManager.CommonType + * @crossplatform + * @since 11 + */ + modifyTime: string; + + /** + * The size of asset. If this field changes, the asset is considered to have changed. + * + * @type { string } + * @syscap SystemCapability.DistributedDataManager.CommonType + * @crossplatform + * @since 11 + */ + size: string; + + /** + * The status of asset. + * + * @type { ?AssetStatus } + * @syscap SystemCapability.DistributedDataManager.CommonType + * @crossplatform + * @since 11 + */ + status?: AssetStatus; + } + + /** + * Indicates several assets + * + * @syscap SystemCapability.DistributedDataManager.CommonType + * @crossplatform + * @since 11 + */ + type Assets = Array; + + /** + * Indicates possible value types. + * + * @syscap SystemCapability.DistributedDataManager.CommonType + * @crossplatform + * @since 11 + */ + type ValueType = null | number | string | boolean | Uint8Array | Asset | Assets; + + /** + * Values in buckets are stored in key-value pairs. + * + * @syscap SystemCapability.DistributedDataManager.CommonType + * @crossplatform + * @since 11 + */ + type ValuesBucket = { [key: string]: ValueType; }; +} + +export default commonType; diff --git a/kv_store/frameworks/common/js_proxy.h b/kv_store/frameworks/common/js_proxy.h new file mode 100644 index 00000000..19b5dcce --- /dev/null +++ b/kv_store/frameworks/common/js_proxy.h @@ -0,0 +1,62 @@ +/* +* 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_DISTRIBUTED_DATA_FRAMEWORKS_COMMON_JS_PROXY_H +#define OHOS_DISTRIBUTED_DATA_FRAMEWORKS_COMMON_JS_PROXY_H +#include +namespace OHOS::JSProxy { +template +class JSCreator { +public: + // This method will be used to call different subclasses for implementation + virtual std::shared_ptr Create() = 0; + +protected: + // It is not allowed to directly use parent class objects for construction and destruction + JSCreator() = default; + ~JSCreator() = default; +}; + +template +class JSProxy { +public: + void SetInstance(std::shared_ptr instance) + { + instance_ = std::move(instance); + } + + std::shared_ptr GetInstance() const + { + return instance_; + } + +protected: + // It is not allowed to directly use parent class objects for construction and destruction + JSProxy() = default; + ~JSProxy() = default; + +private: + std::shared_ptr instance_; +}; + +template +class JSEntity : public JSCreator, public JSProxy { +protected: + // It is not allowed to directly use parent class objects for construction and destruction + JSEntity() = default; + ~JSEntity() = default; +}; +} // namespace OHOS::JSProxy +#endif // OHOS_DISTRIBUTED_DATA_FRAMEWORKS_COMMON_JS_PROXY_H diff --git a/kv_store/frameworks/libs/distributeddb/common/include/concurrent_adapter.h b/kv_store/frameworks/libs/distributeddb/common/include/concurrent_adapter.h new file mode 100644 index 00000000..a67653ab --- /dev/null +++ b/kv_store/frameworks/libs/distributeddb/common/include/concurrent_adapter.h @@ -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. + */ + +#ifndef CONCURRENT_ADAPTER_H +#define CONCURRENT_ADAPTER_H + +#include "runtime_context.h" +#ifdef USE_FFRT +#include "ffrt.h" +#endif + +namespace DistributedDB { +#ifdef USE_FFRT +#define ADAPTER_AUTO_LOCK(n, m) +#define ADAPTER_WAIT(x) ffrt::wait({x}) +#else +#define ADAPTER_AUTO_LOCK(n, m) std::lock_guard n(m) +#define ADAPTER_WAIT(x) (void)(x) +#endif +using TaskHandle = void *; +using DependenceList = std::initializer_list; +class ConcurrentAdapter { +public: + static int ScheduleTask(const TaskAction &action, DependenceList inDeps = {}, + DependenceList outDeps = {}); + static TaskHandle ScheduleTaskH(const TaskAction &action, DependenceList inDeps = {}, + DependenceList outDeps = {}); +}; +} + +#endif // CONCURRENT_ADAPTER_H diff --git a/kv_store/frameworks/libs/distributeddb/common/src/concurrent_adapter.cpp b/kv_store/frameworks/libs/distributeddb/common/src/concurrent_adapter.cpp new file mode 100644 index 00000000..709d4d3a --- /dev/null +++ b/kv_store/frameworks/libs/distributeddb/common/src/concurrent_adapter.cpp @@ -0,0 +1,40 @@ +/* + * 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 "concurrent_adapter.h" + +namespace DistributedDB { +int ConcurrentAdapter::ScheduleTask(const TaskAction &action, DependenceList inDeps, + DependenceList outDeps) +{ +#ifdef USE_FFRT + ffrt::submit(action, { inDeps.begin(), inDeps.end() }, { outDeps.begin(), outDeps.end() }); + return E_OK; +#else + return RuntimeContext::GetInstance()->ScheduleTask(action); +#endif +} + +TaskHandle ConcurrentAdapter::ScheduleTaskH(const TaskAction &action, DependenceList inDeps, + DependenceList outDeps) +{ +#ifdef USE_FFRT + return ffrt::submit_h(action, { inDeps.begin(), inDeps.end() }, { outDeps.begin(), outDeps.end() }); +#else + (void)action(); + return 0; +#endif +} +} \ No newline at end of file diff --git a/mock/innerkits/filemanagement/dfs_service/frameworks/native/cloud_daemon_kit_inner/include/cloud_daemon_manager_impl.h b/mock/innerkits/filemanagement/dfs_service/frameworks/native/cloud_daemon_kit_inner/include/cloud_daemon_manager_impl.h new file mode 100644 index 00000000..38f8b2f8 --- /dev/null +++ b/mock/innerkits/filemanagement/dfs_service/frameworks/native/cloud_daemon_kit_inner/include/cloud_daemon_manager_impl.h @@ -0,0 +1,41 @@ +/* + * 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_STORAGE_CLOUD_DAEMON_MANAGER_IMPL_H +#define OHOS_STORAGE_CLOUD_DAEMON_MANAGER_IMPL_H + +#include + +#include "cloud_daemon_manager.h" +#include "nocopyable.h" +#include "svc_death_recipient.h" + +namespace OHOS::FileManagement::CloudFile { +class CloudDaemonManagerImpl final : public CloudDaemonManager, public NoCopyable { +public: + static CloudDaemonManagerImpl &GetInstance(); + + int32_t StartFuse(int32_t userId, int32_t devFd, const string &path) override; + +private: + CloudDaemonManagerImpl() = default; + void SetDeathRecipient(const sptr &remoteObject); + + std::atomic_flag isFirstCall_{false}; + sptr deathRecipient_; +}; +} // namespace OHOS::FileManagement::CloudFile + +#endif // OHOS_STORAGE_CLOUD_DAEMON_MANAGER_IMPL_H diff --git a/mock/innerkits/filemanagement/dfs_service/frameworks/native/cloud_daemon_kit_inner/include/cloud_daemon_service_proxy.h b/mock/innerkits/filemanagement/dfs_service/frameworks/native/cloud_daemon_kit_inner/include/cloud_daemon_service_proxy.h new file mode 100644 index 00000000..48de17df --- /dev/null +++ b/mock/innerkits/filemanagement/dfs_service/frameworks/native/cloud_daemon_kit_inner/include/cloud_daemon_service_proxy.h @@ -0,0 +1,41 @@ +/* + * 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_STORAGE_CLOUD_DAEMON_SERVICE_PROXY_H +#define OHOS_STORAGE_CLOUD_DAEMON_SERVICE_PROXY_H + +#include "i_cloud_daemon.h" +#include "iremote_proxy.h" + +namespace OHOS::FileManagement::CloudFile { +using namespace std; +class CloudDaemonServiceProxy : public IRemoteProxy { +public: + explicit CloudDaemonServiceProxy(const sptr &impl) : IRemoteProxy(impl) {} + ~CloudDaemonServiceProxy() override {} + + static sptr GetInstance(); + static void InvaildInstance(); + + int32_t StartFuse(int32_t userId, int32_t devFd, const string &path) override; + +private: + static inline std::mutex proxyMutex_; + static inline sptr serviceProxy_; + static inline BrokerDelegator delegator_; +}; +} // namespace OHOS::FileManagement::CloudFile + +#endif // OHOS_STORAGE_CLOUD_DAEMON_SERVICE_PROXY_H diff --git a/mock/innerkits/filemanagement/dfs_service/frameworks/native/cloudsync_kit_inner/include/cloud_download_callback_client.h b/mock/innerkits/filemanagement/dfs_service/frameworks/native/cloudsync_kit_inner/include/cloud_download_callback_client.h new file mode 100644 index 00000000..4045f595 --- /dev/null +++ b/mock/innerkits/filemanagement/dfs_service/frameworks/native/cloudsync_kit_inner/include/cloud_download_callback_client.h @@ -0,0 +1,34 @@ +/* + * 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_DOWNLOAD_CALLBACK_CLIENT_H +#define OHOS_FILEMGMT_CLOUD_DOWNLOAD_CALLBACK_CLIENT_H + +#include "cloud_download_callback_stub.h" + +namespace OHOS::FileManagement::CloudSync { +class CloudDownloadCallbackClient final : public CloudDownloadCallbackStub { +public: + explicit CloudDownloadCallbackClient(const std::shared_ptr &callback) + : callback_(callback) {} + + void OnDownloadProcess(DownloadProgressObj& progress) override; + +private: + std::shared_ptr callback_; +}; +} // namespace OHOS::FileManagement::CloudSync + +#endif // OHOS_FILEMGMT_CLOUD_DOWNLOAD_CALLBACK_CLIENT_H diff --git a/mock/innerkits/filemanagement/dfs_service/frameworks/native/cloudsync_kit_inner/include/cloud_download_callback_stub.h b/mock/innerkits/filemanagement/dfs_service/frameworks/native/cloudsync_kit_inner/include/cloud_download_callback_stub.h new file mode 100644 index 00000000..721af69a --- /dev/null +++ b/mock/innerkits/filemanagement/dfs_service/frameworks/native/cloudsync_kit_inner/include/cloud_download_callback_stub.h @@ -0,0 +1,39 @@ +/* +* 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_DOWLOAD_CALLBACK_STUB_H +#define OHOS_FILEMGMT_CLOUD_DOWLOAD_CALLBACK_STUB_H + +#include + +#include "i_cloud_download_callback.h" +#include "iremote_stub.h" + +namespace OHOS::FileManagement::CloudSync { +class CloudDownloadCallbackStub : public IRemoteStub { +public: + CloudDownloadCallbackStub(); + virtual ~CloudDownloadCallbackStub() = default; + int32_t OnRemoteRequest(uint32_t code, MessageParcel &data, MessageParcel &reply, MessageOption &option) override; + +private: + using ServiceInterface = int32_t (CloudDownloadCallbackStub::*)(MessageParcel &data, MessageParcel &reply); + std::map opToInterfaceMap_; + + int32_t HandleOnProcess(MessageParcel &data, MessageParcel &reply); +}; +} // namespace OHOS::FileManagement::CloudSync + +#endif // OHOS_FILEMGMT_CLOUD_DOWNLOAD_CALLBACK_STUB_H diff --git a/mock/innerkits/filemanagement/dfs_service/frameworks/native/cloudsync_kit_inner/include/cloud_download_uri_manager.h b/mock/innerkits/filemanagement/dfs_service/frameworks/native/cloudsync_kit_inner/include/cloud_download_uri_manager.h new file mode 100644 index 00000000..41f966bb --- /dev/null +++ b/mock/innerkits/filemanagement/dfs_service/frameworks/native/cloudsync_kit_inner/include/cloud_download_uri_manager.h @@ -0,0 +1,41 @@ +/* + * 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_DOWNLOAD_URI_MANAGER_H +#define OHOS_FILEMGMT_CLOUD_DOWNLOAD_URI_MANAGER_H + +#include "nocopyable.h" + +#include + +namespace OHOS::FileManagement::CloudSync { +class CloudDownloadUriManager : public NoCopyable { +public: + static CloudDownloadUriManager &GetInstance(); + + void SetRegisteredFlag(); + void UnsetRegisteredFlag(); + void AddPathToUri(const std::string& path, const std::string& uri); + std::string GetUri(const std::string& path); + void RemoveUri(const std::string& path); + +private: + CloudDownloadUriManager() = default; + bool registered_{false}; + std::map pathMap_; +}; +} // namespace OHOS::FileManagement::CloudSync + +#endif // OHOS_FILEMGMT_CLOUD_DOWNLOAD_URI_MANAGER_H diff --git a/mock/innerkits/filemanagement/dfs_service/frameworks/native/cloudsync_kit_inner/include/cloud_sync_asset_manager_impl.h b/mock/innerkits/filemanagement/dfs_service/frameworks/native/cloudsync_kit_inner/include/cloud_sync_asset_manager_impl.h new file mode 100644 index 00000000..031a97ea --- /dev/null +++ b/mock/innerkits/filemanagement/dfs_service/frameworks/native/cloudsync_kit_inner/include/cloud_sync_asset_manager_impl.h @@ -0,0 +1,52 @@ +/* + * Copyright (c) 2022 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef OHOS_FILEMGMT_CLOUD_SYNC_ASSET_MANAGER_IMPL_H +#define OHOS_FILEMGMT_CLOUD_SYNC_ASSET_MANAGER_IMPL_H + +#include +#include + +#include "cloud_sync_asset_manager.h" +#include "download_asset_callback_client.h" +#include "nocopyable.h" +#include "svc_death_recipient.h" + +namespace OHOS::FileManagement::CloudSync { +class CloudSyncAssetManagerImpl final : public CloudSyncAssetManager, public NoCopyable { +public: + static CloudSyncAssetManagerImpl &GetInstance(); + + int32_t UploadAsset(const int32_t userId, const std::string &request, std::string &result) override; + int32_t DownloadFile(const int32_t userId, const std::string &bundleName, AssetInfo &assetInfo) override; + int32_t DeleteAsset(const int32_t userId, const std::string &uri) override; + int32_t DownloadFile(const int32_t userId, + const std::string &bundleName, + const std::string &networkId, + AssetInfo &assetInfo, + ResultCallback resultCallback) override; + +private: + CloudSyncAssetManagerImpl() = default; + void SetDeathRecipient(const sptr &remoteObject); + + sptr downloadAssetCallback_; + std::atomic_flag isFirstCall_{false}; + sptr deathRecipient_; + std::mutex callbackInitMutex_; +}; +} // namespace OHOS::FileManagement::CloudSync + +#endif // OHOS_FILEMGMT_CLOUD_SYNC_ASSET_MANAGER_IMPL_H diff --git a/mock/innerkits/filemanagement/dfs_service/frameworks/native/cloudsync_kit_inner/include/cloud_sync_callback_client.h b/mock/innerkits/filemanagement/dfs_service/frameworks/native/cloudsync_kit_inner/include/cloud_sync_callback_client.h new file mode 100644 index 00000000..05a3563a --- /dev/null +++ b/mock/innerkits/filemanagement/dfs_service/frameworks/native/cloudsync_kit_inner/include/cloud_sync_callback_client.h @@ -0,0 +1,33 @@ +/* + * Copyright (c) 2022 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef OHOS_FILEMGMT_CLOUD_SYNC_CALLBACK_CLIENT_H +#define OHOS_FILEMGMT_CLOUD_SYNC_CALLBACK_CLIENT_H + +#include "cloud_sync_callback_stub.h" + +namespace OHOS::FileManagement::CloudSync { +class CloudSyncCallbackClient final : public CloudSyncCallbackStub { +public: + explicit CloudSyncCallbackClient(const std::shared_ptr &callback) : callback_(callback) {} + + void OnSyncStateChanged(CloudSyncState state, ErrorType error) override; + +private: + std::shared_ptr callback_; +}; +} // namespace OHOS::FileManagement::CloudSync + +#endif // OHOS_FILEMGMT_CLOUD_SYNC_CALLBACK_CLIENT_H \ No newline at end of file diff --git a/mock/innerkits/filemanagement/dfs_service/frameworks/native/cloudsync_kit_inner/include/cloud_sync_callback_stub.h b/mock/innerkits/filemanagement/dfs_service/frameworks/native/cloudsync_kit_inner/include/cloud_sync_callback_stub.h new file mode 100644 index 00000000..c518cb35 --- /dev/null +++ b/mock/innerkits/filemanagement/dfs_service/frameworks/native/cloudsync_kit_inner/include/cloud_sync_callback_stub.h @@ -0,0 +1,39 @@ +/* +* Copyright (c) 2022 Huawei Device Co., Ltd. +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +#ifndef OHOS_FILEMGMT_CLOUD_SYNC_CALLBACK_STUB_H +#define OHOS_FILEMGMT_CLOUD_SYNC_CALLBACK_STUB_H + +#include + +#include "i_cloud_sync_callback.h" +#include "iremote_stub.h" + +namespace OHOS::FileManagement::CloudSync { +class CloudSyncCallbackStub : public IRemoteStub { +public: + CloudSyncCallbackStub(); + virtual ~CloudSyncCallbackStub() = default; + int32_t OnRemoteRequest(uint32_t code, MessageParcel &data, MessageParcel &reply, MessageOption &option) override; + +private: + using ServiceInterface = int32_t (CloudSyncCallbackStub::*)(MessageParcel &data, MessageParcel &reply); + std::map opToInterfaceMap_; + + int32_t HandleOnSyncStateChanged(MessageParcel &data, MessageParcel &reply); +}; +} // namespace OHOS::FileManagement::CloudSync + +#endif // OHOS_FILEMGMT_CLOUD_SYNC_CALLBACK_STUB_H \ No newline at end of file diff --git a/mock/innerkits/filemanagement/dfs_service/frameworks/native/cloudsync_kit_inner/include/cloud_sync_manager_impl.h b/mock/innerkits/filemanagement/dfs_service/frameworks/native/cloudsync_kit_inner/include/cloud_sync_manager_impl.h new file mode 100644 index 00000000..3184055e --- /dev/null +++ b/mock/innerkits/filemanagement/dfs_service/frameworks/native/cloudsync_kit_inner/include/cloud_sync_manager_impl.h @@ -0,0 +1,79 @@ +/* + * Copyright (c) 2022 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef OHOS_FILEMGMT_CLOUD_SYNC_MANAGER_IMPL_H +#define OHOS_FILEMGMT_CLOUD_SYNC_MANAGER_IMPL_H + +#include + +#include "nocopyable.h" + +#include "cloud_sync_callback_client.h" +#include "cloud_sync_common.h" +#include "cloud_sync_manager.h" +#include "svc_death_recipient.h" +#include "system_ability_status_change_stub.h" + +namespace OHOS::FileManagement::CloudSync { +class CloudSyncManagerImpl final : public CloudSyncManager, public NoCopyable { +public: + static CloudSyncManagerImpl &GetInstance(); + + int32_t RegisterCallback(const std::shared_ptr callback) override; + int32_t UnRegisterCallback() override; + int32_t StartSync() override; + int32_t StartSync(bool forceFlag, const std::shared_ptr callback) override; + int32_t TriggerSync(const std::string &bundleName, const int32_t &userId) override; + int32_t StopSync() override; + int32_t ChangeAppSwitch(const std::string &accoutId, const std::string &bundleName, bool status) override; + int32_t Clean(const std::string &accountId, const CleanOptions &cleanOptions) override; + int32_t NotifyDataChange(const std::string &accoutId, const std::string &bundleName) override; + int32_t NotifyEventChange(int32_t userId, const std::string &eventId, const std::string &extraData) override; + int32_t EnableCloud(const std::string &accoutId, const SwitchDataObj &switchData) override; + int32_t DisableCloud(const std::string &accoutId) override; + int32_t StartDownloadFile(const std::string &uri) override; + int32_t StartFileCache(const std::string &uri) override; + int32_t StopDownloadFile(const std::string &uri) override; + int32_t RegisterDownloadFileCallback(const std::shared_ptr downloadCallback) override; + int32_t UnregisterDownloadFileCallback() override; + int32_t GetSyncTime(int64_t &syncTime) override; + int32_t CleanCache(const std::string &uri) override; + + class SystemAbilityStatusChange : public SystemAbilityStatusChangeStub { + public: + SystemAbilityStatusChange(std::shared_ptr callback, + std::shared_ptr downloadCallback) + : callback_(callback), downloadCallback_(downloadCallback) {}; + void OnAddSystemAbility(int32_t systemAbilityId, const std::string &deviceId); + void OnRemoveSystemAbility(int32_t systemAbilityId, const std::string &deviceId); + private: + std::shared_ptr callback_; + std::shared_ptr downloadCallback_; + }; +private: + CloudSyncManagerImpl() = default; + void SetDeathRecipient(const sptr &remoteObject); + + std::atomic_flag isFirstCall_{false}; + sptr deathRecipient_; + std::shared_ptr callback_; + std::shared_ptr downloadCallback_; + sptr listener_; + std::mutex subscribeMutex_; + void SubscribeListener(); +}; +} // namespace OHOS::FileManagement::CloudSync + +#endif // OHOS_FILEMGMT_CLOUD_SYNC_MANAGER_IMPL_H diff --git a/mock/innerkits/filemanagement/dfs_service/frameworks/native/cloudsync_kit_inner/include/cloud_sync_service_proxy.h b/mock/innerkits/filemanagement/dfs_service/frameworks/native/cloudsync_kit_inner/include/cloud_sync_service_proxy.h new file mode 100644 index 00000000..5a62f2cd --- /dev/null +++ b/mock/innerkits/filemanagement/dfs_service/frameworks/native/cloudsync_kit_inner/include/cloud_sync_service_proxy.h @@ -0,0 +1,75 @@ +/* + * Copyright (c) 2022 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef OHOS_FILEMGMT_CLOUD_SYNC_SERVICE_PROXY_H +#define OHOS_FILEMGMT_CLOUD_SYNC_SERVICE_PROXY_H + +#include "iremote_proxy.h" +#include "system_ability_load_callback_stub.h" + +#include "i_cloud_sync_service.h" + +namespace OHOS::FileManagement::CloudSync { +class CloudSyncServiceProxy : public IRemoteProxy { +public: + explicit CloudSyncServiceProxy(const sptr &impl) : IRemoteProxy(impl) {} + ~CloudSyncServiceProxy() override {} + + static sptr GetInstance(); + static void InvaildInstance(); + int32_t UnRegisterCallbackInner() override; + int32_t RegisterCallbackInner(const sptr &remoteObject) override; + int32_t StartSyncInner(bool forceFlag) override; + int32_t TriggerSyncInner(const std::string &bundleName, const int32_t &userId) override; + int32_t StopSyncInner() override; + int32_t ChangeAppSwitch(const std::string &accoutId, const std::string &bundleName, bool status) override; + int32_t Clean(const std::string &accountId, const CleanOptions &cleanOptions) override; + int32_t NotifyDataChange(const std::string &accoutId, const std::string &bundleName) override; + int32_t NotifyEventChange(int32_t userId, const std::string &eventId, const std::string &extraData) override; + int32_t EnableCloud(const std::string &accoutId, const SwitchDataObj &switchData) override; + int32_t DisableCloud(const std::string &accoutId) override; + int32_t StartDownloadFile(const std::string &uri) override; + int32_t StartFileCache(const std::string &uri) override; + int32_t StopDownloadFile(const std::string &uri) override; + int32_t RegisterDownloadFileCallback(const sptr &downloadCallback) override; + int32_t UnregisterDownloadFileCallback() override; + int32_t UploadAsset(const int32_t userId, const std::string &request, std::string &result) override; + int32_t DownloadFile(const int32_t userId, const std::string &bundleName, AssetInfoObj &assetInfoObj) override; + int32_t DownloadAsset(const uint64_t taskId, const int32_t userId, + const std::string &bundleName, + const std::string &networkId, + AssetInfoObj &assetInfoObj) override; + int32_t RegisterDownloadAssetCallback(const sptr &remoteObject) override; + int32_t DeleteAsset(const int32_t userId, const std::string &uri) override; + int32_t GetSyncTimeInner(int64_t &syncTime) override; + int32_t CleanCacheInner(const std::string &uri) override; + + class ServiceProxyLoadCallback : public SystemAbilityLoadCallbackStub { + public: + void OnLoadSystemAbilitySuccess(int32_t systemAbilityId, const sptr &remoteObject) override; + void OnLoadSystemAbilityFail(int32_t systemAbilityId) override; + + std::condition_variable proxyConVar_; + std::atomic isLoadSuccess_{false}; + }; + +private: + static inline std::mutex proxyMutex_; + static inline sptr serviceProxy_; + static inline BrokerDelegator delegator_; +}; +} // namespace OHOS::FileManagement::CloudSync + +#endif // OHOS_FILEMGMT_CLOUD_SYNC_SERVICE_PROXY_H diff --git a/mock/innerkits/filemanagement/dfs_service/frameworks/native/cloudsync_kit_inner/include/download_asset_callback_client.h b/mock/innerkits/filemanagement/dfs_service/frameworks/native/cloudsync_kit_inner/include/download_asset_callback_client.h new file mode 100644 index 00000000..6fbd591a --- /dev/null +++ b/mock/innerkits/filemanagement/dfs_service/frameworks/native/cloudsync_kit_inner/include/download_asset_callback_client.h @@ -0,0 +1,46 @@ +/* + * 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_DOWNLOAD_ASSET_CALLBACK_CLIENT_H +#define OHOS_FILEMGMT_DOWNLOAD_ASSET_CALLBACK_CLIENT_H + +#include +#include +#include +#include + +#include "safe_map.h" + +#include "cloud_sync_asset_manager.h" +#include "download_asset_callback_stub.h" + +namespace OHOS::FileManagement::CloudSync { +class DownloadAssetCallbackClient final : public DownloadAssetCallbackStub { +public: + DownloadAssetCallbackClient() = default; + ~DownloadAssetCallbackClient() = default; + void OnFinished(const TaskId taskId, const std::string &uri, const int32_t result) override; + void AddDownloadTaskCallback(const TaskId taskId, CloudSyncAssetManager::ResultCallback callback); + void RemoveDownloadTaskCallback(const TaskId taskId); + CloudSyncAssetManager::ResultCallback GetDownloadTaskCallback(const TaskId taskId); + TaskId GetTaskId(); + +private: + SafeMap callbackListMap_; + std::atomic taskId_{0}; +}; +} // namespace OHOS::FileManagement::CloudSync + +#endif // OHOS_FILEMGMT_DOWNLOAD_ASSET_CALLBACK_CLIENT_H \ No newline at end of file diff --git a/mock/innerkits/filemanagement/dfs_service/frameworks/native/cloudsync_kit_inner/include/download_asset_callback_stub.h b/mock/innerkits/filemanagement/dfs_service/frameworks/native/cloudsync_kit_inner/include/download_asset_callback_stub.h new file mode 100644 index 00000000..3326079a --- /dev/null +++ b/mock/innerkits/filemanagement/dfs_service/frameworks/native/cloudsync_kit_inner/include/download_asset_callback_stub.h @@ -0,0 +1,39 @@ +/* + * 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_DOWNLOAD_ASSET_CALLBACK_STUB_H +#define OHOS_FILEMGMT_DOWNLOAD_ASSET_CALLBACK_STUB_H + +#include + +#include "i_download_asset_callback.h" +#include "iremote_stub.h" + +namespace OHOS::FileManagement::CloudSync { +class DownloadAssetCallbackStub : public IRemoteStub { +public: + DownloadAssetCallbackStub(); + virtual ~DownloadAssetCallbackStub() = default; + int32_t OnRemoteRequest(uint32_t code, MessageParcel &data, MessageParcel &reply, MessageOption &option) override; + +private: + using ServiceInterface = int32_t (DownloadAssetCallbackStub::*)(MessageParcel &data, MessageParcel &reply); + std::map opToInterfaceMap_; + + int32_t HandleOnFinished(MessageParcel &data, MessageParcel &reply); +}; +} // namespace OHOS::FileManagement::CloudSync + +#endif // OHOS_FILEMGMT_DOWNLOAD_ASSET_CALLBACK_STUB_H \ No newline at end of file diff --git a/mock/innerkits/filemanagement/dfs_service/frameworks/native/distributed_file_inner/include/distributed_file_daemon_manager_impl.h b/mock/innerkits/filemanagement/dfs_service/frameworks/native/distributed_file_inner/include/distributed_file_daemon_manager_impl.h new file mode 100644 index 00000000..663f89d5 --- /dev/null +++ b/mock/innerkits/filemanagement/dfs_service/frameworks/native/distributed_file_inner/include/distributed_file_daemon_manager_impl.h @@ -0,0 +1,48 @@ +/* + * 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 DISTRIBUTED_FILE_DAEMON_MANAGER_IMPL_H +#define DISTRIBUTED_FILE_DAEMON_MANAGER_IMPL_H + +#include "ipc/distributed_file_daemon_manager.h" +#include "dm_device_info.h" +#include "nocopyable.h" + +namespace OHOS { +namespace Storage { +namespace DistributedFile { +class DistributedFileDaemonManagerImpl final : public DistributedFileDaemonManager, public NoCopyable { +public: + static DistributedFileDaemonManagerImpl &GetInstance(); + + int32_t OpenP2PConnection(const DistributedHardware::DmDeviceInfo &deviceInfo) override; + int32_t CloseP2PConnection(const DistributedHardware::DmDeviceInfo &deviceInfo) override; + int32_t PrepareSession(const std::string &srcUri, + const std::string &dstUri, + const std::string &srcDeviceId, + const sptr &listener) override; + int32_t RequestSendFile(const std::string &srcUri, + const std::string &dstPath, + const std::string &remoteDeviceId, + const std::string &sessionName); + +private: + DistributedFileDaemonManagerImpl() = default; +}; +} // namespace DistributedFile +} // namespace Storage +} // namespace OHOS + +#endif // DISTRIBUTED_FILE_DAEMON_MANAGER_IMPL_H \ No newline at end of file diff --git a/mock/innerkits/filemanagement/dfs_service/frameworks/native/distributed_file_inner/include/distributed_file_daemon_proxy.h b/mock/innerkits/filemanagement/dfs_service/frameworks/native/distributed_file_inner/include/distributed_file_daemon_proxy.h new file mode 100644 index 00000000..a9c4acd3 --- /dev/null +++ b/mock/innerkits/filemanagement/dfs_service/frameworks/native/distributed_file_inner/include/distributed_file_daemon_proxy.h @@ -0,0 +1,57 @@ +/* + * 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_STORAGE_DISTRIBUTED_FILE_DAEMON_PROXY_H +#define OHOS_STORAGE_DISTRIBUTED_FILE_DAEMON_PROXY_H + +#include + +#include "dm_device_info.h" +#include "ipc/i_daemon.h" +#include "iremote_proxy.h" + + +namespace OHOS { +namespace Storage { +namespace DistributedFile { +class DistributedFileDaemonProxy : public IRemoteProxy { +public: + explicit DistributedFileDaemonProxy(const sptr &impl) : IRemoteProxy(impl) {} + ~DistributedFileDaemonProxy() override {} + + static sptr GetInstance(); + static void InvaildInstance(); + + int32_t OpenP2PConnection(const DistributedHardware::DmDeviceInfo &deviceInfo) override; + int32_t CloseP2PConnection(const DistributedHardware::DmDeviceInfo &deviceInfo) override; + int32_t PrepareSession(const std::string &srcUri, + const std::string &dstUri, + const std::string &srcDeviceId, + const sptr &listener) override; + int32_t RequestSendFile(const std::string &srcUri, + const std::string &dstPath, + const std::string &dstDeviceId, + const std::string &sessionName) override; + +private: + static inline std::mutex proxyMutex_; + static inline sptr daemonProxy_; + static inline BrokerDelegator delegator_; +}; + +} // namespace DistributedFile +} // namespace Storage +} // namespace OHOS +#endif // OHOS_STORAGE_DISTRIBUTED_FILE_DAEMON_PROXY_H \ No newline at end of file diff --git a/mock/innerkits/filemanagement/dfs_service/frameworks/native/distributed_file_inner/include/file_trans_listener_interface_code.h b/mock/innerkits/filemanagement/dfs_service/frameworks/native/distributed_file_inner/include/file_trans_listener_interface_code.h new file mode 100644 index 00000000..29b82bdc --- /dev/null +++ b/mock/innerkits/filemanagement/dfs_service/frameworks/native/distributed_file_inner/include/file_trans_listener_interface_code.h @@ -0,0 +1,29 @@ +/* + * 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_STORAGE_FILE_TRANS_LISTENER_INTERFACE_CODE_H +#define OHOS_STORAGE_FILE_TRANS_LISTENER_INTERFACE_CODE_H +namespace OHOS { +namespace Storage { +namespace DistributedFile { +enum class FileTransListenerInterfaceCode { + FILE_TRANS_LISTENER_ON_PROGRESS = 0, + FILE_TRANS_LISTENER_ON_FAILED, + FILE_TRANS_LISTENER_ON_FINISHED, +}; +} // namespace DistributedFile +} // namespace Storage +} // namespace OHOS + +#endif //OHOS_STORAGE_FILE_TRANS_LISTENER_INTERFACE_CODE_H diff --git a/mock/innerkits/filemanagement/dfs_service/frameworks/native/distributed_file_inner/include/file_trans_listener_stub.h b/mock/innerkits/filemanagement/dfs_service/frameworks/native/distributed_file_inner/include/file_trans_listener_stub.h new file mode 100644 index 00000000..a65d3211 --- /dev/null +++ b/mock/innerkits/filemanagement/dfs_service/frameworks/native/distributed_file_inner/include/file_trans_listener_stub.h @@ -0,0 +1,47 @@ +/* + * 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_STORAGE_FILE_TRANS_LISTENER_STUB_H +#define OHOS_STORAGE_FILE_TRANS_LISTENER_STUB_H + +#include + +#include "i_file_trans_listener.h" +#include "iremote_stub.h" +#include "message_option.h" +#include "message_parcel.h" +#include "refbase.h" + +namespace OHOS { +namespace Storage { +namespace DistributedFile { +class FileTransListenerStub : public IRemoteStub { +public: + FileTransListenerStub(); + virtual ~FileTransListenerStub() = default; + int32_t OnRemoteRequest(uint32_t code, MessageParcel &data, MessageParcel &reply, MessageOption &option) override; + +private: + using FileTransListenerInterface = int32_t (FileTransListenerStub::*)(MessageParcel &data, MessageParcel &reply); + std::map opToInterfaceMap_; + + int32_t HandleOnFileReceive(MessageParcel &data, MessageParcel &reply); + int32_t HandleOnFailed(MessageParcel &data, MessageParcel &reply); + int32_t HandleOnFinished(MessageParcel &data, MessageParcel &reply); +}; +} // namespace DistributedFile +} // namespace Storage +} // namespace OHOS +#endif // OHOS_STORAGE_FILE_TRANS_LISTENER_STUB_H diff --git a/mock/innerkits/filemanagement/dfs_service/frameworks/native/distributed_file_inner/include/i_file_trans_listener.h b/mock/innerkits/filemanagement/dfs_service/frameworks/native/distributed_file_inner/include/i_file_trans_listener.h new file mode 100644 index 00000000..ab27d4f9 --- /dev/null +++ b/mock/innerkits/filemanagement/dfs_service/frameworks/native/distributed_file_inner/include/i_file_trans_listener.h @@ -0,0 +1,40 @@ +/* + * 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_STORAGE_I_FILE_TRANS_LISTENER_H +#define OHOS_STORAGE_I_FILE_TRANS_LISTENER_H +#include + +#include "iremote_broker.h" + +namespace OHOS { +namespace Storage { +namespace DistributedFile { +class IFileTransListener : public IRemoteBroker { +public: + enum { + File_Trans_Listener_SUCCESS = 0, + File_Trans_Listener_DESCRIPTOR_IS_EMPTY, + }; + virtual int32_t OnFileReceive(uint64_t totalBytes, uint64_t processedBytes) = 0; + virtual int32_t OnFailed(const std::string &sessionName) = 0; + virtual int32_t OnFinished(const std::string &sessionName) = 0; + DECLARE_INTERFACE_DESCRIPTOR(u"ohos.storage.distributedfile.translistener") +}; +} // namespace DistributedFile +} // namespace Storage +} // namespace OHOS + +#endif // OHOS_STORAGE_I_FILE_TRANS_LISTENER_H diff --git a/mock/innerkits/filemanagement/dfs_service/interfaces/inner_api/native/cloud_daemon_kit_inner/BUILD.gn b/mock/innerkits/filemanagement/dfs_service/interfaces/inner_api/native/cloud_daemon_kit_inner/BUILD.gn new file mode 100644 index 00000000..4b5c1b72 --- /dev/null +++ b/mock/innerkits/filemanagement/dfs_service/interfaces/inner_api/native/cloud_daemon_kit_inner/BUILD.gn @@ -0,0 +1,63 @@ +# 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. + +import("//build/ohos.gni") +import("//foundation/filemanagement/dfs_service/distributedfile.gni") + +config("public_config") { + include_dirs = [ "." ] +} + +config("private_config") { + include_dirs = [ + "${distributedfile_path}/frameworks/native/cloud_daemon_kit_inner/include", + "${distributedfile_path}/utils/log/include", + ] +} + +ohos_shared_library("cloud_daemon_kit_inner") { + branch_protector_ret = "pac_ret" + sanitize = { + ubsan = true + boundary_sanitize = true + cfi = true + cfi_cross_dso = true + debug = false + } + sources = [ + "${distributedfile_path}/frameworks/native/cloud_daemon_kit_inner/src/cloud_daemon_manager.cpp", + "${distributedfile_path}/frameworks/native/cloud_daemon_kit_inner/src/cloud_daemon_manager_impl.cpp", + "${distributedfile_path}/frameworks/native/cloud_daemon_kit_inner/src/cloud_daemon_service_proxy.cpp", + "${distributedfile_path}/utils/log/src/utils_log.cpp", + ] + + defines = [ + "LOG_DOMAIN=0xD004308", + "LOG_TAG=\"CLOUD_DAEMON_API\"", + ] + + configs = [ ":private_config" ] + public_configs = [ ":public_config" ] + + external_deps = [ + "c_utils:utils", + "hilog:libhilog", + "ipc:ipc_core", + "safwk:system_ability_fwk", + "samgr:samgr_proxy", + ] + + use_exceptions = true + part_name = "dfs_service" + subsystem_name = "filemanagement" +} diff --git a/mock/innerkits/filemanagement/dfs_service/interfaces/inner_api/native/cloud_daemon_kit_inner/cloud_daemon_manager.h b/mock/innerkits/filemanagement/dfs_service/interfaces/inner_api/native/cloud_daemon_kit_inner/cloud_daemon_manager.h new file mode 100644 index 00000000..01b6e378 --- /dev/null +++ b/mock/innerkits/filemanagement/dfs_service/interfaces/inner_api/native/cloud_daemon_kit_inner/cloud_daemon_manager.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_STORAGE_CLOUD_DAEMON_MANAGER_H +#define OHOS_STORAGE_CLOUD_DAEMON_MANAGER_H + +#include + +namespace OHOS::FileManagement::CloudFile { +using namespace std; +class CloudDaemonManager { +public: + static CloudDaemonManager &GetInstance(); + + virtual int32_t StartFuse(int32_t userId, int32_t devFd, const string &path) = 0; +}; +} // namespace OHOS::FileManagement::CloudFile + +#endif // OHOS_STORAGE_CLOUD_DAEMON_MANAGER_H diff --git a/mock/innerkits/filemanagement/dfs_service/interfaces/inner_api/native/cloud_daemon_kit_inner/cloud_file_daemon_interface_code.h b/mock/innerkits/filemanagement/dfs_service/interfaces/inner_api/native/cloud_daemon_kit_inner/cloud_file_daemon_interface_code.h new file mode 100644 index 00000000..894d3d59 --- /dev/null +++ b/mock/innerkits/filemanagement/dfs_service/interfaces/inner_api/native/cloud_daemon_kit_inner/cloud_file_daemon_interface_code.h @@ -0,0 +1,26 @@ +/* + * 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_DAEMON_INTERFACE_CODE_H +#define OHOS_FILEMGMT_CLOUD_FILE_DAEMON_INTERFACE_CODE_H + +/* SAID:5205 */ +namespace OHOS::FileManagement::CloudFile { +enum class CloudFileDaemonInterfaceCode { + CLOUD_DAEMON_CMD_START_FUSE = 0, +}; +} // namespace OHOS::FileManagement::CloudFile + +#endif // OHOS_FILEMGMT_CLOUD_FILE_DAEMON_INTERFACE_CODE_H \ No newline at end of file diff --git a/mock/innerkits/filemanagement/dfs_service/interfaces/inner_api/native/cloud_daemon_kit_inner/i_cloud_daemon.h b/mock/innerkits/filemanagement/dfs_service/interfaces/inner_api/native/cloud_daemon_kit_inner/i_cloud_daemon.h new file mode 100644 index 00000000..28a8c9a6 --- /dev/null +++ b/mock/innerkits/filemanagement/dfs_service/interfaces/inner_api/native/cloud_daemon_kit_inner/i_cloud_daemon.h @@ -0,0 +1,38 @@ +/* + * 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 I_CLOUD_DAEMON_H +#define I_CLOUD_DAEMON_H + +#include "iremote_broker.h" + +namespace OHOS { +namespace FileManagement { +namespace CloudFile { +class ICloudDaemon : public IRemoteBroker { +public: + enum { + CLOUD_DAEMON_SUCCESS = 0, + CLOUD_DAEMON_DESCRIPTOR_IS_EMPTY, + }; + virtual int32_t StartFuse(int32_t userId, int32_t deviceFd, const std::string &path) = 0; + + static inline const std::string SERVICE_NAME { "ohos.filemanagement.distributedfile.clouddaemon" }; + DECLARE_INTERFACE_DESCRIPTOR(u"ohos.filemanagement.distributedfile.clouddaemon") +}; +} // namespace CloudFile +} // namespace FileManagement +} // namespace OHOS +#endif // I_CLOUD_DAEMON_H diff --git a/mock/innerkits/filemanagement/dfs_service/interfaces/inner_api/native/cloud_daemon_kit_inner/svc_death_recipient.h b/mock/innerkits/filemanagement/dfs_service/interfaces/inner_api/native/cloud_daemon_kit_inner/svc_death_recipient.h new file mode 100644 index 00000000..5ecb8af7 --- /dev/null +++ b/mock/innerkits/filemanagement/dfs_service/interfaces/inner_api/native/cloud_daemon_kit_inner/svc_death_recipient.h @@ -0,0 +1,41 @@ +/* + * 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_STORAGE_SVC_DEATH_RECIPIENT_H +#define OHOS_STORAGE_SVC_DEATH_RECIPIENT_H + +#include + +#include "iremote_object.h" + +namespace OHOS::FileManagement::CloudFile { +class SvcDeathRecipient : public IRemoteObject::DeathRecipient { +public: + explicit SvcDeathRecipient(std::function &)> functor) : functor_(functor){}; + void OnRemoteDied(const wptr &object) override + { + if (object == nullptr) { + return; + } + object->RemoveDeathRecipient(this); + functor_(object); + } + +private: + std::function &)> functor_; +}; +} // namespace OHOS::FileManagement::CloudFile + +#endif // OHOS_STORAGE_SVC_DEATH_RECIPIENT_H diff --git a/mock/innerkits/filemanagement/dfs_service/interfaces/inner_api/native/cloudsync_kit_inner/BUILD.gn b/mock/innerkits/filemanagement/dfs_service/interfaces/inner_api/native/cloudsync_kit_inner/BUILD.gn new file mode 100644 index 00000000..52d1c3b1 --- /dev/null +++ b/mock/innerkits/filemanagement/dfs_service/interfaces/inner_api/native/cloudsync_kit_inner/BUILD.gn @@ -0,0 +1,123 @@ +# Copyright (C) 2022 Huawei Device Co., Ltd. +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import("//build/ohos.gni") +import("//foundation/filemanagement/dfs_service/distributedfile.gni") + +config("public_config") { + include_dirs = [ "." ] +} + +config("private_config") { + include_dirs = [ + "${distributedfile_path}/frameworks/native/cloudsync_kit_inner/include", + "${distributedfile_path}/interfaces/inner_api/native/cloudsync_kit_inner", + "${distributedfile_path}/utils/log/include", + "${media_library_path}/frameworks/utils/include", + "${media_library_path}/interfaces/inner_api/media_library_helper/include", + ] +} + +ohos_shared_library("cloudsync_kit_inner") { + branch_protector_ret = "pac_ret" + sanitize = { + ubsan = true + boundary_sanitize = true + cfi = true + cfi_cross_dso = true + debug = false + } + sources = [ + "${distributedfile_path}/frameworks/native/cloudsync_kit_inner/src/cloud_download_callback_client.cpp", + "${distributedfile_path}/frameworks/native/cloudsync_kit_inner/src/cloud_download_callback_stub.cpp", + "${distributedfile_path}/frameworks/native/cloudsync_kit_inner/src/cloud_download_uri_manager.cpp", + "${distributedfile_path}/frameworks/native/cloudsync_kit_inner/src/cloud_sync_callback_client.cpp", + "${distributedfile_path}/frameworks/native/cloudsync_kit_inner/src/cloud_sync_callback_stub.cpp", + "${distributedfile_path}/frameworks/native/cloudsync_kit_inner/src/cloud_sync_common.cpp", + "${distributedfile_path}/frameworks/native/cloudsync_kit_inner/src/cloud_sync_manager.cpp", + "${distributedfile_path}/frameworks/native/cloudsync_kit_inner/src/cloud_sync_manager_impl.cpp", + "${distributedfile_path}/frameworks/native/cloudsync_kit_inner/src/cloud_sync_service_proxy.cpp", + "${distributedfile_path}/utils/log/src/utils_log.cpp", + ] + + defines = [ + "LOG_DOMAIN=0xD004306", + "LOG_TAG=\"CLOUDSYNC_API\"", + ] + + configs = [ ":private_config" ] + public_configs = [ ":public_config" ] + + external_deps = [ + "ability_base:zuri", + "ability_runtime:ability_manager", + "ability_runtime:dataobs_manager", + "c_utils:utils", + "hilog:libhilog", + "ipc:ipc_core", + "safwk:system_ability_fwk", + "samgr:samgr_proxy", + ] + + if (cloudsync_service_media_library) { + external_deps += [ "media_library:media_library" ] + defines += [ "SUPPORT_MEDIA_LIBRARY" ] + } + + use_exceptions = true + part_name = "dfs_service" + subsystem_name = "filemanagement" +} + +ohos_shared_library("cloudsync_asset_kit_inner") { + branch_protector_ret = "pac_ret" + sanitize = { + ubsan = true + boundary_sanitize = true + cfi = true + cfi_cross_dso = true + debug = false + } + sources = [ + "${distributedfile_path}/frameworks/native/cloudsync_kit_inner/src/cloud_download_uri_manager.cpp", + "${distributedfile_path}/frameworks/native/cloudsync_kit_inner/src/cloud_sync_asset_manager.cpp", + "${distributedfile_path}/frameworks/native/cloudsync_kit_inner/src/cloud_sync_asset_manager_impl.cpp", + "${distributedfile_path}/frameworks/native/cloudsync_kit_inner/src/cloud_sync_common.cpp", + "${distributedfile_path}/frameworks/native/cloudsync_kit_inner/src/cloud_sync_service_proxy.cpp", + "${distributedfile_path}/frameworks/native/cloudsync_kit_inner/src/download_asset_callback_client.cpp", + "${distributedfile_path}/frameworks/native/cloudsync_kit_inner/src/download_asset_callback_stub.cpp", + ] + + defines = [ + "LOG_DOMAIN=0xD004309", + "LOG_TAG=\"CLOUD_ASSET_API\"", + ] + + configs = [ ":private_config" ] + public_configs = [ ":public_config" ] + + external_deps = [ + "ability_base:zuri", + "hilog:libhilog", + "ipc:ipc_core", + "safwk:system_ability_fwk", + "samgr:samgr_proxy", + ] + + deps = [ "${utils_path}:libdistributedfileutils" ] + + use_exceptions = true + innerapi_tags = [ "platformsdk" ] + part_name = "dfs_service" + subsystem_name = "filemanagement" +} diff --git a/mock/innerkits/filemanagement/dfs_service/interfaces/inner_api/native/cloudsync_kit_inner/cloud_download_callback.h b/mock/innerkits/filemanagement/dfs_service/interfaces/inner_api/native/cloudsync_kit_inner/cloud_download_callback.h new file mode 100644 index 00000000..9b1dd7f3 --- /dev/null +++ b/mock/innerkits/filemanagement/dfs_service/interfaces/inner_api/native/cloudsync_kit_inner/cloud_download_callback.h @@ -0,0 +1,32 @@ +/* + * 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_DOWNLOAD_CALLBACK_H +#define OHOS_FILEMGMT_CLOUD_DOWNLOAD_CALLBACK_H + +#include + +#include "cloud_sync_common.h" + +namespace OHOS::FileManagement::CloudSync { + +class CloudDownloadCallback { +public: + virtual ~CloudDownloadCallback() = default; + virtual void OnDownloadProcess(DownloadProgressObj& progress) = 0; +}; +} // namespace OHOS::FileManagement::CloudSync + +#endif // OHOS_FILEMGMT_CLOUD_DOWNLOAD_CALLBACK_H diff --git a/mock/innerkits/filemanagement/dfs_service/interfaces/inner_api/native/cloudsync_kit_inner/cloud_file_sync_service_interface_code.h b/mock/innerkits/filemanagement/dfs_service/interfaces/inner_api/native/cloudsync_kit_inner/cloud_file_sync_service_interface_code.h new file mode 100644 index 00000000..a4075be0 --- /dev/null +++ b/mock/innerkits/filemanagement/dfs_service/interfaces/inner_api/native/cloudsync_kit_inner/cloud_file_sync_service_interface_code.h @@ -0,0 +1,48 @@ +/* + * 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_SYNC_SERVICE_INTERFACE_CODE_H +#define OHOS_FILEMGMT_CLOUD_FILE_SYNC_SERVICE_INTERFACE_CODE_H + +/* SAID:5204 */ +namespace OHOS::FileManagement::CloudSync { +enum class CloudFileSyncServiceInterfaceCode { + SERVICE_CMD_UNREGISTER_CALLBACK, + SERVICE_CMD_REGISTER_CALLBACK, + SERVICE_CMD_START_SYNC, + SERVICE_CMD_TRIGGER_SYNC, + SERVICE_CMD_STOP_SYNC, + SERVICE_CMD_CHANGE_APP_SWITCH, + SERVICE_CMD_NOTIFY_DATA_CHANGE, + SERVICE_CMD_NOTIFY_EVENT_CHANGE, + SERVICE_CMD_ENABLE_CLOUD, + SERVICE_CMD_DISABLE_CLOUD, + SERVICE_CMD_CLEAN, + SERVICE_CMD_START_DOWNLOAD_FILE, + SERVICE_CMD_STOP_DOWNLOAD_FILE, + SERVICE_CMD_REGISTER_DOWNLOAD_FILE_CALLBACK, + SERVICE_CMD_UNREGISTER_DOWNLOAD_FILE_CALLBACK, + SERVICE_CMD_UPLOAD_ASSET, + SERVICE_CMD_DOWNLOAD_FILE, + SERVICE_CMD_DELETE_ASSET, + SERVICE_CMD_GET_SYNC_TIME, + SERVICE_CMD_CLEAN_CACHE, + SERVICE_CMD_START_FILE_CACHE, + SERVICE_CMD_DOWNLOAD_ASSET, + SERVICE_CMD_REGISTER_DOWNLOAD_ASSET_CALLBACK +}; +} // namespace OHOS::FileManagement::CloudSync + +#endif // OHOS_FILEMGMT_CLOUD_FILE_SYNC_SERVICE_INTERFACE_CODE_H \ No newline at end of file diff --git a/mock/innerkits/filemanagement/dfs_service/interfaces/inner_api/native/cloudsync_kit_inner/cloud_sync_asset_manager.h b/mock/innerkits/filemanagement/dfs_service/interfaces/inner_api/native/cloudsync_kit_inner/cloud_sync_asset_manager.h new file mode 100644 index 00000000..8211ae6c --- /dev/null +++ b/mock/innerkits/filemanagement/dfs_service/interfaces/inner_api/native/cloudsync_kit_inner/cloud_sync_asset_manager.h @@ -0,0 +1,77 @@ +/* + * Copyright (c) 2022 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef OHOS_FILEMGMT_CLOUD_SYNC_ASSET_MANAGER_H +#define OHOS_FILEMGMT_CLOUD_SYNC_ASSET_MANAGER_H + +#include +#include + +namespace OHOS::FileManagement::CloudSync { +struct AssetInfo { + std::string uri; + std::string recordType; + std::string recordId; + std::string fieldKey; + std::string assetName; +}; + +class CloudSyncAssetManager { +public: + using ResultCallback = std::function; + static CloudSyncAssetManager &GetInstance(); + /** + * @brief 接口触发文件上传 + * + * @param userId 用户Id + * @param request 请求 + * @param result 结果 + * @return int32_t 同步返回执行结果 + */ + virtual int32_t UploadAsset(const int32_t userId, const std::string &request, std::string &result) = 0; + /** + * @brief 接口触发文件下载 + * + * @param userId 用户Id + * @param bundleName 应用包名 + * @param assetInfo 下载文件信息 + * @return int32_t 同步返回执行结果 + */ + virtual int32_t DownloadFile(const int32_t userId, const std::string &bundleName, AssetInfo &assetInfo) = 0; + /** + * @brief 接口触发文件下载 + * + * @param userId 用户Id + * @param bundleName 应用包名 + * @param assetInfo 下载文件信息 + * @return int32_t 同步返回执行结果 + */ + virtual int32_t DownloadFile(const int32_t userId, + const std::string &bundleName, + const std::string &networkId, + AssetInfo &assetInfo, + ResultCallback resultCallback) = 0; + /** + * @brief 接口触发附件删除 + * + * @param userId 用户Id + * @param uri 用户uri + * @return int32_t 同步返回执行结果 + */ + virtual int32_t DeleteAsset(const int32_t userId, const std::string &uri) = 0; +}; +} // namespace OHOS::FileManagement::CloudSync + +#endif // OHOS_FILEMGMT_CLOUD_SYNC_ASSET_MANAGER_H diff --git a/mock/innerkits/filemanagement/dfs_service/interfaces/inner_api/native/cloudsync_kit_inner/cloud_sync_callback.h b/mock/innerkits/filemanagement/dfs_service/interfaces/inner_api/native/cloudsync_kit_inner/cloud_sync_callback.h new file mode 100644 index 00000000..2296e46b --- /dev/null +++ b/mock/innerkits/filemanagement/dfs_service/interfaces/inner_api/native/cloudsync_kit_inner/cloud_sync_callback.h @@ -0,0 +1,65 @@ +/* + * Copyright (c) 2022 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef OHOS_FILEMGMT_CLOUD_SYNC_CALLBACK_H +#define OHOS_FILEMGMT_CLOUD_SYNC_CALLBACK_H + +#include + +#include "cloud_sync_constants.h" + +namespace OHOS::FileManagement::CloudSync { +class CloudSyncCallback { +public: + virtual ~CloudSyncCallback() = default; + /** + * @brief 同步状态变更通知回调 + * + * @param type 0:upload 1:download 2:all + * @param state 同步状态 + * SYNC_STATE_DEFAULT 同步完成 + * SYNC_STATE_SYNCING 同步中 + * SYNC_STATE_FAILED 同步失败 + * SYNC_STATE_PAUSED_NO_NETWORK 未连接网络 + * SYNC_STATE_PAUSED_FOR_WIFI 未连接wifi + * SYNC_STATE_PAUSED_FOR_BATTERY 低电量 + * SYNC_STATE_BATTERY_TOO_LOW 电量过低 + * SYNC_STATE_PAUSED_FOR_SPACE_TOO_LOW 云空间满 + */ + virtual void OnSyncStateChanged(SyncType type, SyncPromptState state) {}; + /** + * @brief 同步状态变更通知回调 + * + * @param state 同步状态类型 + * UPLOADING 正在上传 + * UPLOAD_FAILED 同步上传失败 + * DOWNLOADING 正在下载 + * DOWNLOAD_FAILED 同步下载失败 + * COMPLETED 同步完成 + * STOPPED 同步停止 + * @param error 同步错误类型 + * NO_ERROR 无错误 + * NETWORK_UNAVAILABLE 网络不可用 + * WIFI_UNAVAILABLE wifi不可用 + * BATTERY_LEVEL_LOW 低电量 + * BATTERY_LEVEL_WARNING 电量警告 + * CLOUD_STORAGE_FULL 云空间满 + * LOCAL_STORAGE_FULL 本地空间满 + */ + virtual void OnSyncStateChanged(CloudSyncState state, ErrorType error) {}; +}; +} // namespace OHOS::FileManagement::CloudSync + +#endif // OHOS_FILEMGMT_CLOUD_SYNC_CALLBACK_H \ No newline at end of file diff --git a/mock/innerkits/filemanagement/dfs_service/interfaces/inner_api/native/cloudsync_kit_inner/cloud_sync_common.h b/mock/innerkits/filemanagement/dfs_service/interfaces/inner_api/native/cloudsync_kit_inner/cloud_sync_common.h new file mode 100644 index 00000000..f956215a --- /dev/null +++ b/mock/innerkits/filemanagement/dfs_service/interfaces/inner_api/native/cloudsync_kit_inner/cloud_sync_common.h @@ -0,0 +1,80 @@ +/* + * 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_COMMON_H +#define OHOS_FILEMGMT_CLOUD_SYNC_COMMON_H + +#include + +#include "parcel.h" +#include "cloud_sync_asset_manager.h" + +namespace OHOS::FileManagement::CloudSync { + +struct DownloadProgressObj : public Parcelable { + enum Status : int32_t { + RUNNING = 0, + COMPLETED = 1, + FAILED = 2, + STOPPED = 3, + }; + uint32_t refCount; + std::string path; + int64_t downloadId; + Status state; + int64_t downloadedSize; + int64_t totalSize; + bool ReadFromParcel(Parcel &parcel); + bool Marshalling(Parcel &parcel) const override; + static DownloadProgressObj *Unmarshalling(Parcel &parcel); + std::string to_string(); +}; + +struct SwitchDataObj : public Parcelable { + std::map switchData; + bool ReadFromParcel(Parcel &parcel); + bool Marshalling(Parcel &parcel) const override; + static SwitchDataObj *Unmarshalling(Parcel &parcel); +}; + +struct CleanOptions : public Parcelable { + std::map appActionsData; + bool ReadFromParcel(Parcel &parcel); + bool Marshalling(Parcel &parcel) const override; + static CleanOptions *Unmarshalling(Parcel &parcel); +}; + +struct AssetInfoObj : public Parcelable { + std::string uri; + std::string recordType; + std::string recordId; + std::string fieldKey; + std::string assetName; + bool ReadFromParcel(Parcel &parcel); + bool Marshalling(Parcel &parcel) const override; + static AssetInfoObj *Unmarshalling(Parcel &parcel); + + AssetInfoObj() = default; + AssetInfoObj(const AssetInfo &assetInfo) + : uri(assetInfo.uri), + recordType(assetInfo.recordType), + recordId(assetInfo.recordId), + fieldKey(assetInfo.fieldKey), + assetName(assetInfo.assetName) + { + } +}; +} // namespace OHOS::FileManagement::CloudSync +#endif diff --git a/mock/innerkits/filemanagement/dfs_service/interfaces/inner_api/native/cloudsync_kit_inner/cloud_sync_constants.h b/mock/innerkits/filemanagement/dfs_service/interfaces/inner_api/native/cloudsync_kit_inner/cloud_sync_constants.h new file mode 100644 index 00000000..2c4fc451 --- /dev/null +++ b/mock/innerkits/filemanagement/dfs_service/interfaces/inner_api/native/cloudsync_kit_inner/cloud_sync_constants.h @@ -0,0 +1,71 @@ +/* + * Copyright (c) 2022 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef OHOS_FILEMGMT_CLOUD_SYNC_CONSTANTS_H +#define OHOS_FILEMGMT_CLOUD_SYNC_CONSTANTS_H + +namespace OHOS::FileManagement::CloudSync { +enum class SyncType : int32_t { + UPLOAD = 0, + DOWNLOAD, + ALL, +}; + +enum class SyncPromptState : int32_t { + SYNC_STATE_DEFAULT = 0, + SYNC_STATE_SYNCING, + SYNC_STATE_FAILED, + SYNC_STATE_PAUSED_NO_NETWORK, + SYNC_STATE_PAUSED_FOR_WIFI, + SYNC_STATE_PAUSED_FOR_BATTERY, + SYNC_STATE_BATTERY_TOO_LOW, + SYNC_STATE_PAUSED_FOR_SPACE_TOO_LOW, +}; + +enum CloudSyncState { + UPLOADING = 0, + UPLOAD_FAILED, + DOWNLOADING, + DOWNLOAD_FAILED, + COMPLETED, + STOPPED, +}; + +enum ErrorType { + NO_ERROR = 0, + NETWORK_UNAVAILABLE, + WIFI_UNAVAILABLE, + BATTERY_LEVEL_LOW, + BATTERY_LEVEL_WARNING, + CLOUD_STORAGE_FULL, + LOCAL_STORAGE_FULL, +}; + +enum State { + CLOUD_FILE_DOWNLOAD_RUNNING = 0, + CLOUD_FILE_DOWNLOAD_COMPLETED, + CLOUD_FILE_DOWNLOAD_FAILED, + CLOUD_FILE_DOWNLOAD_STOPPED, +}; + +enum FileSyncState { + FILESYNCSTATE_UPLOADING = 0, + FILESYNCSTATE_DOWNLOADING, + FILESYNCSTATE_COMPLETED, + FILESYNCSTATE_STOPPED, +}; +} // namespace OHOS::FileManagement::CloudSync + +#endif // OHOS_FILEMGMT_CLOUD_SYNC_CONSTANTS_H \ No newline at end of file diff --git a/mock/innerkits/filemanagement/dfs_service/interfaces/inner_api/native/cloudsync_kit_inner/cloud_sync_manager.h b/mock/innerkits/filemanagement/dfs_service/interfaces/inner_api/native/cloudsync_kit_inner/cloud_sync_manager.h new file mode 100644 index 00000000..c43f6535 --- /dev/null +++ b/mock/innerkits/filemanagement/dfs_service/interfaces/inner_api/native/cloudsync_kit_inner/cloud_sync_manager.h @@ -0,0 +1,109 @@ +/* + * Copyright (c) 2022 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef OHOS_FILEMGMT_CLOUD_SYNC_MANAGER_H +#define OHOS_FILEMGMT_CLOUD_SYNC_MANAGER_H + +#include + +#include "cloud_download_callback.h" +#include "cloud_sync_callback.h" +#include "cloud_sync_common.h" + +namespace OHOS::FileManagement::CloudSync { +class CloudSyncManager { +public: + static CloudSyncManager &GetInstance(); + /** + * @brief 注册 + * + * @param callback 注册同步回调 + * @return int32_t 同步返回执行结果 + */ + virtual int32_t RegisterCallback(const std::shared_ptr callback) = 0; + /** + * @brief 注册 + * + * @param callback 卸载同步回调 + * @return int32_t 返回执行结果 + */ + virtual int32_t UnRegisterCallback() = 0; + /** + * @brief 启动同步 + * + * @return int32_t 同步返回执行结果 + */ + virtual int32_t StartSync() = 0; + /** + * @brief 启动同步 + * + * @param forceFlag 是否强制继续同步,当前仅支持低电量下暂停后继续上传 + * @param callback 注册同步回调 + * @return int32_t 同步返回执行结果 + */ + virtual int32_t StartSync(bool forceFlag, const std::shared_ptr callback) = 0; + /** + * @brief 触发同步 + * + * @param bundleName 应用包名 + * @param userId 用户ID + * @return int32_t 同步返回执行结果 + */ + virtual int32_t TriggerSync(const std::string &bundleName, const int32_t &userId) = 0; + /** + * @brief 停止同步 + * + * @return int32_t 同步返回执行结果 + */ + virtual int32_t StopSync() = 0; + /** + * @brief 切换应用云同步开关 + * + * @param accoutId 账号ID + * @param bundleName 应用包名 + * @param status 应用开关状态 + * @return int32_t 同步返回执行结果 + */ + virtual int32_t ChangeAppSwitch(const std::string &accoutId, const std::string &bundleName, bool status) = 0; + /** + * @brief 云数据变化触发同步 + * + * @param accoutId 账号ID + * @param bundleName 应用包名 + * @return int32_t 同步返回执行结果 + */ + virtual int32_t NotifyDataChange(const std::string &accoutId, const std::string &bundleName) = 0; + virtual int32_t NotifyEventChange(int32_t userId, const std::string &eventId, const std::string &extraData) = 0; + virtual int32_t EnableCloud(const std::string &accoutId, const SwitchDataObj &switchData) = 0; + virtual int32_t DisableCloud(const std::string &accoutId) = 0; + /** + * @brief 云账号退出选择保留或清除云数据 + * + * @param accoutId 账号ID + * @param cleanOptions 说明云文件如何处理的方式 + * @return int32_t 同步返回执行结果 + */ + virtual int32_t Clean(const std::string &accountId, const CleanOptions &cleanOptions) = 0; + virtual int32_t StartDownloadFile(const std::string &path) = 0; + virtual int32_t StartFileCache(const std::string &path) = 0; + virtual int32_t StopDownloadFile(const std::string &path) = 0; + virtual int32_t RegisterDownloadFileCallback(const std::shared_ptr downloadCallback) = 0; + virtual int32_t UnregisterDownloadFileCallback() = 0; + virtual int32_t GetSyncTime(int64_t &syncTime) = 0; + virtual int32_t CleanCache(const std::string &uri) = 0; +}; +} // namespace OHOS::FileManagement::CloudSync + +#endif // OHOS_FILEMGMT_CLOUD_SYNC_MANAGER_H diff --git a/mock/innerkits/filemanagement/dfs_service/interfaces/inner_api/native/cloudsync_kit_inner/download_asset_callback.h b/mock/innerkits/filemanagement/dfs_service/interfaces/inner_api/native/cloudsync_kit_inner/download_asset_callback.h new file mode 100644 index 00000000..98330885 --- /dev/null +++ b/mock/innerkits/filemanagement/dfs_service/interfaces/inner_api/native/cloudsync_kit_inner/download_asset_callback.h @@ -0,0 +1,28 @@ +/* + * 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_DOWNLOAD_ASSET_CALLBACK_H +#define OHOS_FILEMGMT_DOWNLOAD_ASSET_CALLBACK_H + +namespace OHOS::FileManagement::CloudSync { +class DownloadAssetCallback { +public: + using TaskId = uint64_t; + virtual ~DownloadAssetCallback() = default; + virtual void OnFinished(const TaskId taskId, const std::string &uri, const int32_t result) = 0; +}; +} // namespace OHOS::FileManagement::CloudSync + +#endif // OHOS_FILEMGMT_DOWNLOAD_ASSET_CALLBACK_H \ No newline at end of file diff --git a/mock/innerkits/filemanagement/dfs_service/interfaces/inner_api/native/cloudsync_kit_inner/i_cloud_download_callback.h b/mock/innerkits/filemanagement/dfs_service/interfaces/inner_api/native/cloudsync_kit_inner/i_cloud_download_callback.h new file mode 100644 index 00000000..c439270f --- /dev/null +++ b/mock/innerkits/filemanagement/dfs_service/interfaces/inner_api/native/cloudsync_kit_inner/i_cloud_download_callback.h @@ -0,0 +1,34 @@ +/* + * 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_I_CLOUD_DOWNLOAD_CALLBACK_H +#define OHOS_FILEMGMT_I_CLOUD_DOWNLOAD_CALLBACK_H + +#include "iremote_broker.h" + +#include "cloud_download_callback.h" + +namespace OHOS::FileManagement::CloudSync { +class ICloudDownloadCallback : public CloudDownloadCallback, public IRemoteBroker { +public: + enum { + SERVICE_CMD_ON_PROCESS = 0, + }; + + DECLARE_INTERFACE_DESCRIPTOR(u"OHOS.Filemanagement.Dfs.ICloudDownloadCallback") +}; +} // namespace OHOS::FileManagement::CloudSync + +#endif // OHOS_FILEMGMT_I_CLOUD_DOWNLOAD_CALLBACK_H \ No newline at end of file diff --git a/mock/innerkits/filemanagement/dfs_service/interfaces/inner_api/native/cloudsync_kit_inner/i_cloud_sync_callback.h b/mock/innerkits/filemanagement/dfs_service/interfaces/inner_api/native/cloudsync_kit_inner/i_cloud_sync_callback.h new file mode 100644 index 00000000..27078e30 --- /dev/null +++ b/mock/innerkits/filemanagement/dfs_service/interfaces/inner_api/native/cloudsync_kit_inner/i_cloud_sync_callback.h @@ -0,0 +1,34 @@ +/* + * Copyright (c) 2022 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef OHOS_FILEMGMT_I_CLOUD_SYNC_CALLBACK_H +#define OHOS_FILEMGMT_I_CLOUD_SYNC_CALLBACK_H + +#include "iremote_broker.h" + +#include "cloud_sync_callback.h" + +namespace OHOS::FileManagement::CloudSync { +class ICloudSyncCallback : public CloudSyncCallback, public IRemoteBroker { +public: + enum { + SERVICE_CMD_ON_SYNC_STATE_CHANGED = 0, + }; + + DECLARE_INTERFACE_DESCRIPTOR(u"OHOS.Filemanagement.Dfs.ICloudSyncCallback") +}; +} // namespace OHOS::FileManagement::CloudSync + +#endif // OHOS_FILEMGMT_I_CLOUD_SYNC_CALLBACK_H \ No newline at end of file diff --git a/mock/innerkits/filemanagement/dfs_service/interfaces/inner_api/native/cloudsync_kit_inner/i_cloud_sync_service.h b/mock/innerkits/filemanagement/dfs_service/interfaces/inner_api/native/cloudsync_kit_inner/i_cloud_sync_service.h new file mode 100644 index 00000000..5bd15d8c --- /dev/null +++ b/mock/innerkits/filemanagement/dfs_service/interfaces/inner_api/native/cloudsync_kit_inner/i_cloud_sync_service.h @@ -0,0 +1,60 @@ +/* + * Copyright (c) 2022 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef OHOS_FILEMGMT_I_CLOUD_SYNC_SERVICE_H +#define OHOS_FILEMGMT_I_CLOUD_SYNC_SERVICE_H + +#include + +#include "iremote_broker.h" + +#include "cloud_sync_common.h" + +namespace OHOS::FileManagement::CloudSync { +class ICloudSyncService : public IRemoteBroker { +public: + DECLARE_INTERFACE_DESCRIPTOR(u"OHOS.Filemanagement.Dfs.ICloudSyncService") + + virtual int32_t UnRegisterCallbackInner() = 0; + virtual int32_t RegisterCallbackInner(const sptr &remoteObject) = 0; + virtual int32_t StartSyncInner(bool forceFlag) = 0; + virtual int32_t TriggerSyncInner(const std::string &bundleName, const int32_t &userId) = 0; + virtual int32_t StopSyncInner() = 0; + virtual int32_t ChangeAppSwitch(const std::string &accoutId, const std::string &bundleName, bool status) = 0; + virtual int32_t Clean(const std::string &accountId, const CleanOptions &cleanOptions) = 0; + virtual int32_t NotifyDataChange(const std::string &accoutId, const std::string &bundleName) = 0; + virtual int32_t NotifyEventChange(int32_t userId, const std::string &eventId, const std::string &extraData) = 0; + virtual int32_t EnableCloud(const std::string &accoutId, const SwitchDataObj &switchData) = 0; + virtual int32_t DisableCloud(const std::string &accoutId) = 0; + virtual int32_t StartDownloadFile(const std::string &path) = 0; + virtual int32_t StartFileCache(const std::string &path) = 0; + virtual int32_t StopDownloadFile(const std::string &path) = 0; + virtual int32_t RegisterDownloadFileCallback(const sptr &downloadCallback) = 0; + virtual int32_t UnregisterDownloadFileCallback() = 0; + virtual int32_t UploadAsset(const int32_t userId, const std::string &request, std::string &result) = 0; + virtual int32_t DownloadFile(const int32_t userId, const std::string &bundleName, AssetInfoObj &assetInfoObj) = 0; + virtual int32_t DownloadAsset(const uint64_t taskId, + const int32_t userId, + const std::string &bundleName, + const std::string &networkId, + AssetInfoObj &assetInfoObj) = 0; + virtual int32_t RegisterDownloadAssetCallback(const sptr &remoteObject) = 0; + virtual int32_t DeleteAsset(const int32_t userId, const std::string &uri) = 0; + virtual int32_t GetSyncTimeInner(int64_t &syncTime) = 0; + virtual int32_t CleanCacheInner(const std::string &uri) = 0; +}; +} // namespace OHOS::FileManagement::CloudSync + +#endif // OHOS_FILEMGMT_I_CLOUD_SYNC_SERVICE_H diff --git a/mock/innerkits/filemanagement/dfs_service/interfaces/inner_api/native/cloudsync_kit_inner/i_download_asset_callback.h b/mock/innerkits/filemanagement/dfs_service/interfaces/inner_api/native/cloudsync_kit_inner/i_download_asset_callback.h new file mode 100644 index 00000000..a61c5f46 --- /dev/null +++ b/mock/innerkits/filemanagement/dfs_service/interfaces/inner_api/native/cloudsync_kit_inner/i_download_asset_callback.h @@ -0,0 +1,33 @@ +/* + * 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_I_DOWNLOAD_ASSET_CALLBACK_H +#define OHOS_FILEMGMT_I_DOWNLOAD_ASSET_CALLBACK_H + +#include "iremote_broker.h" +#include "download_asset_callback.h" + +namespace OHOS::FileManagement::CloudSync { +class IDownloadAssetCallback : public DownloadAssetCallback, public IRemoteBroker { +public: + enum { + SERVICE_CMD_ON_DOWNLOAD_FINSHED = 0, + }; + + DECLARE_INTERFACE_DESCRIPTOR(u"OHOS.Filemanagement.Dfs.IDownloadAssetCallback") +}; +} // namespace OHOS::FileManagement::CloudSync + +#endif // OHOS_FILEMGMT_I_DOWNLOAD_ASSET_CALLBACK_H \ No newline at end of file diff --git a/mock/innerkits/filemanagement/dfs_service/interfaces/inner_api/native/cloudsync_kit_inner/svc_death_recipient.h b/mock/innerkits/filemanagement/dfs_service/interfaces/inner_api/native/cloudsync_kit_inner/svc_death_recipient.h new file mode 100644 index 00000000..d70ce7f5 --- /dev/null +++ b/mock/innerkits/filemanagement/dfs_service/interfaces/inner_api/native/cloudsync_kit_inner/svc_death_recipient.h @@ -0,0 +1,41 @@ +/* + * Copyright (c) 2022 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef OHOS_FILEMGMT_SVC_DEATH_RECIPIENT_H +#define OHOS_FILEMGMT_SVC_DEATH_RECIPIENT_H + +#include + +#include "iremote_object.h" + +namespace OHOS::FileManagement::CloudSync { +class SvcDeathRecipient : public IRemoteObject::DeathRecipient { +public: + explicit SvcDeathRecipient(std::function &)> functor) : functor_(functor){}; + void OnRemoteDied(const wptr &object) override + { + if (object == nullptr) { + return; + } + object->RemoveDeathRecipient(this); + functor_(object); + } + +private: + std::function &)> functor_; +}; +} // namespace OHOS::FileManagement::CloudSync + +#endif // OHOS_FILEMGMT_SVC_DEATH_RECIPIENT_H \ No newline at end of file diff --git a/mock/innerkits/filemanagement/dfs_service/interfaces/kits/js/cloudfilesync/BUILD.gn b/mock/innerkits/filemanagement/dfs_service/interfaces/kits/js/cloudfilesync/BUILD.gn new file mode 100644 index 00000000..81bc984b --- /dev/null +++ b/mock/innerkits/filemanagement/dfs_service/interfaces/kits/js/cloudfilesync/BUILD.gn @@ -0,0 +1,56 @@ +# 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. + +import("//build/ohos.gni") +import("//foundation/filemanagement/dfs_service/distributedfile.gni") + +ohos_shared_library("cloudsync") { + branch_protector_ret = "pac_ret" + sanitize = { + ubsan = true + boundary_sanitize = true + cfi = true + cfi_cross_dso = true + debug = false + } + 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 = [ + "${innerkits_native_path}/cloudsync_kit_inner:cloudsync_kit_inner", + "${utils_path}:libdistributedfileutils", + ] + + external_deps = [ + "file_api:filemgmt_libhilog", + "file_api:filemgmt_libn", + "hilog:libhilog", + "napi:ace_napi", + ] + + defines = [ + "LOG_DOMAIN=0xD004309", + "LOG_TAG=\"CLOUD_FILE_SYNC\"", + ] + + relative_install_dir = "module/file" + + part_name = "dfs_service" + subsystem_name = "filemanagement" +} diff --git a/mock/innerkits/filemanagement/dfs_service/interfaces/kits/js/cloudfilesync/cloud_file_cache_napi.cpp b/mock/innerkits/filemanagement/dfs_service/interfaces/kits/js/cloudfilesync/cloud_file_cache_napi.cpp new file mode 100644 index 00000000..da65c26b --- /dev/null +++ b/mock/innerkits/filemanagement/dfs_service/interfaces/kits/js/cloudfilesync/cloud_file_cache_napi.cpp @@ -0,0 +1,106 @@ +/* + * 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::CleanCloudFileCache(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[(int)NARG_POS::FIRST]).ToUTF8String(); + if (!succ) { + LOGE("Get uri error"); + NError(EINVAL).ThrowErr(env); + return nullptr; + } + + int32_t ret = CloudSyncManager::GetInstance().CleanCache(uri.get()); + if (ret != E_OK) { + NError(Convert2JsErrNum(ret)).ThrowErr(env); + return nullptr; + } + return NVal::CreateUndefined(env).val_; +} + +bool CloudFileCacheNapi::Export() +{ + std::vector props = { + NVal::DeclareNapiFunction("on", CloudFileCacheNapi::On), + NVal::DeclareNapiFunction("off", CloudFileCacheNapi::Off), + NVal::DeclareNapiFunction("start", CloudFileCacheNapi::StartFileCache), + NVal::DeclareNapiFunction("stop", CloudFileCacheNapi::Stop), + NVal::DeclareNapiFunction("cleanCache", CloudFileCacheNapi::CleanCloudFileCache), + }; + + SetClassName("CloudFileCache"); + return ToExport(props); +} + +napi_value CloudFileCacheNapi::StartFileCache(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())]() -> NError { + int32_t ret = CloudSyncManager::GetInstance().StartFileCache(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 = "cloudFileCache"; + auto asyncWork = GetPromiseOrCallBackWork(env, funcArg, static_cast(NARG_CNT::TWO)); + return asyncWork == nullptr ? nullptr : asyncWork->Schedule(procedureName, cbExec, cbCompl).val_; +} +} // namespace OHOS::FileManagement::CloudSync \ No newline at end of file diff --git a/mock/innerkits/filemanagement/dfs_service/interfaces/kits/js/cloudfilesync/cloud_file_cache_napi.h b/mock/innerkits/filemanagement/dfs_service/interfaces/kits/js/cloudfilesync/cloud_file_cache_napi.h new file mode 100644 index 00000000..30c83372 --- /dev/null +++ b/mock/innerkits/filemanagement/dfs_service/interfaces/kits/js/cloudfilesync/cloud_file_cache_napi.h @@ -0,0 +1,32 @@ +/* + * 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_file_napi.h" + +namespace OHOS::FileManagement::CloudSync { +class CloudFileCacheNapi final : public CloudFileNapi { +public: + CloudFileCacheNapi(napi_env env, napi_value exports) : CloudFileNapi(env, exports) {} + ~CloudFileCacheNapi() = default; + + static napi_value StartFileCache(napi_env env, napi_callback_info info); + bool Export() override; + static napi_value CleanCloudFileCache(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/mock/innerkits/filemanagement/dfs_service/interfaces/kits/js/cloudfilesync/cloud_file_download_napi.cpp b/mock/innerkits/filemanagement/dfs_service/interfaces/kits/js/cloudfilesync/cloud_file_download_napi.cpp new file mode 100644 index 00000000..be31b237 --- /dev/null +++ b/mock/innerkits/filemanagement/dfs_service/interfaces/kits/js/cloudfilesync/cloud_file_download_napi.cpp @@ -0,0 +1,39 @@ +/* + * 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 "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; + +bool CloudFileDownloadNapi::Export() +{ + SetClassName("Download"); + bool success = CloudFileNapi::Export(); + if (!success) { + return false; + } + return true; +} +} // namespace OHOS::FileManagement::CloudSync \ No newline at end of file diff --git a/mock/innerkits/filemanagement/dfs_service/interfaces/kits/js/cloudfilesync/cloud_file_download_napi.h b/mock/innerkits/filemanagement/dfs_service/interfaces/kits/js/cloudfilesync/cloud_file_download_napi.h new file mode 100644 index 00000000..ea22a007 --- /dev/null +++ b/mock/innerkits/filemanagement/dfs_service/interfaces/kits/js/cloudfilesync/cloud_file_download_napi.h @@ -0,0 +1,30 @@ +/* + * 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_DOWNLOAD_NAPI_H +#define OHOS_FILEMGMT_CLOUD_FILE_DOWNLOAD_NAPI_H + +#include "cloud_file_napi.h" + +namespace OHOS::FileManagement::CloudSync { +class CloudFileDownloadNapi final : public CloudFileNapi { +public: + CloudFileDownloadNapi(napi_env env, napi_value exports) : CloudFileNapi(env, exports) {} + ~CloudFileDownloadNapi() = default; + + bool Export() override; +}; +} // namespace OHOS::FileManagement::CloudSync +#endif // OHOS_FILEMGMT_CLOUD_FILE_DOWNLOAD_NAPI_H \ No newline at end of file diff --git a/mock/innerkits/filemanagement/dfs_service/interfaces/kits/js/cloudfilesync/cloud_file_napi.cpp b/mock/innerkits/filemanagement/dfs_service/interfaces/kits/js/cloudfilesync/cloud_file_napi.cpp new file mode 100644 index 00000000..a1759f80 --- /dev/null +++ b/mock/innerkits/filemanagement/dfs_service/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 className_; +} +} // namespace OHOS::FileManagement::CloudSync \ No newline at end of file diff --git a/mock/innerkits/filemanagement/dfs_service/interfaces/kits/js/cloudfilesync/cloud_file_napi.h b/mock/innerkits/filemanagement/dfs_service/interfaces/kits/js/cloudfilesync/cloud_file_napi.h new file mode 100644 index 00000000..a0925572 --- /dev/null +++ b/mock/innerkits/filemanagement/dfs_service/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/mock/innerkits/filemanagement/dfs_service/interfaces/kits/js/cloudfilesync/cloud_sync_n_exporter.cpp b/mock/innerkits/filemanagement/dfs_service/interfaces/kits/js/cloudfilesync/cloud_sync_n_exporter.cpp new file mode 100644 index 00000000..ab429817 --- /dev/null +++ b/mock/innerkits/filemanagement/dfs_service/interfaces/kits/js/cloudfilesync/cloud_sync_n_exporter.cpp @@ -0,0 +1,139 @@ +/* + * 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_n_exporter.h" + +#include "cloud_file_cache_napi.h" +#include "cloud_file_download_napi.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" + +namespace OHOS::FileManagement::CloudSync { +using namespace FileManagement::LibN; +using namespace std; + +static void InitState(napi_env env, napi_value exports) +{ + char propertyName[] = "State"; + napi_value obj = nullptr; + napi_create_object(env, &obj); + napi_property_descriptor desc[] = { + DECLARE_NAPI_STATIC_PROPERTY("RUNNING", + NVal::CreateInt32(env, (int32_t)State::CLOUD_FILE_DOWNLOAD_RUNNING).val_), + DECLARE_NAPI_STATIC_PROPERTY("COMPLETED", + NVal::CreateInt32(env, (int32_t)State::CLOUD_FILE_DOWNLOAD_COMPLETED).val_), + DECLARE_NAPI_STATIC_PROPERTY("FAILED", + NVal::CreateInt32(env, (int32_t)State::CLOUD_FILE_DOWNLOAD_FAILED).val_), + DECLARE_NAPI_STATIC_PROPERTY("STOPPED", + NVal::CreateInt32(env, (int32_t)State::CLOUD_FILE_DOWNLOAD_STOPPED).val_), + }; + napi_define_properties(env, obj, sizeof(desc) / sizeof(desc[0]), desc); + napi_set_named_property(env, exports, propertyName, obj); +} + +/*********************************************** + * Module export and register + ***********************************************/ +napi_value CloudSyncExport(napi_env env, napi_value exports) +{ + InitCloudSyncState(env, exports); + InitErrorType(env, exports); + InitState(env, exports); + InitFileSyncState(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 ", + product->GetClassName().c_str()); + return nullptr; + } else { + LOGI("Class %{public}s for module cloudSyncDownload has been exported", product->GetClassName().c_str()); + } + } + return exports; +} + +void InitCloudSyncState(napi_env env, napi_value exports) +{ + char propertyName[] = "SyncState"; + napi_property_descriptor desc[] = { + DECLARE_NAPI_STATIC_PROPERTY("UPLOADING", NVal::CreateInt32(env, UPLOADING).val_), + DECLARE_NAPI_STATIC_PROPERTY("UPLOAD_FAILED", NVal::CreateInt32(env, UPLOAD_FAILED).val_), + DECLARE_NAPI_STATIC_PROPERTY("DOWNLOADING", NVal::CreateInt32(env, DOWNLOADING).val_), + DECLARE_NAPI_STATIC_PROPERTY("DOWNLOAD_FAILED", NVal::CreateInt32(env, DOWNLOAD_FAILED).val_), + DECLARE_NAPI_STATIC_PROPERTY("COMPLETED", NVal::CreateInt32(env, COMPLETED).val_), + DECLARE_NAPI_STATIC_PROPERTY("STOPPED", NVal::CreateInt32(env, STOPPED).val_), + }; + napi_value obj = nullptr; + napi_create_object(env, &obj); + napi_define_properties(env, obj, sizeof(desc) / sizeof(desc[0]), desc); + napi_set_named_property(env, exports, propertyName, obj); +} + +void InitFileSyncState(napi_env env, napi_value exports) +{ + char propertyName[] = "FileSyncState"; + napi_property_descriptor desc[] = { + DECLARE_NAPI_STATIC_PROPERTY("UPLOADING", NVal::CreateInt32(env, FILESYNCSTATE_UPLOADING).val_), + DECLARE_NAPI_STATIC_PROPERTY("DOWNLOADING", NVal::CreateInt32(env, FILESYNCSTATE_DOWNLOADING).val_), + DECLARE_NAPI_STATIC_PROPERTY("COMPLETED", NVal::CreateInt32(env, FILESYNCSTATE_COMPLETED).val_), + DECLARE_NAPI_STATIC_PROPERTY("STOPPED", NVal::CreateInt32(env, FILESYNCSTATE_STOPPED).val_), + }; + napi_value obj = nullptr; + napi_create_object(env, &obj); + napi_define_properties(env, obj, sizeof(desc) / sizeof(desc[0]), desc); + napi_set_named_property(env, exports, propertyName, obj); +} + +void InitErrorType(napi_env env, napi_value exports) +{ + char propertyName[] = "ErrorType"; + napi_property_descriptor desc[] = { + DECLARE_NAPI_STATIC_PROPERTY("NO_ERROR", NVal::CreateInt32(env, NO_ERROR).val_), + DECLARE_NAPI_STATIC_PROPERTY("NETWORK_UNAVAILABLE", NVal::CreateInt32(env, NETWORK_UNAVAILABLE).val_), + DECLARE_NAPI_STATIC_PROPERTY("WIFI_UNAVAILABLE", NVal::CreateInt32(env, WIFI_UNAVAILABLE).val_), + DECLARE_NAPI_STATIC_PROPERTY("BATTERY_LEVEL_LOW", NVal::CreateInt32(env, BATTERY_LEVEL_LOW).val_), + DECLARE_NAPI_STATIC_PROPERTY("BATTERY_LEVEL_WARNING", NVal::CreateInt32(env, BATTERY_LEVEL_WARNING).val_), + DECLARE_NAPI_STATIC_PROPERTY("CLOUD_STORAGE_FULL", NVal::CreateInt32(env, CLOUD_STORAGE_FULL).val_), + DECLARE_NAPI_STATIC_PROPERTY("LOCAL_STORAGE_FULL", NVal::CreateInt32(env, LOCAL_STORAGE_FULL).val_), + }; + napi_value obj = nullptr; + napi_create_object(env, &obj); + napi_define_properties(env, obj, sizeof(desc) / sizeof(desc[0]), desc); + napi_set_named_property(env, exports, propertyName, obj); +} + +static napi_module _module = { + .nm_version = 1, + .nm_flags = 0, + .nm_filename = nullptr, + .nm_register_func = CloudSyncExport, + .nm_modname = "file.cloudSync", + .nm_priv = ((void *)0), + .reserved = {0} +}; + +extern "C" __attribute__((constructor)) void RegisterModule(void) +{ + napi_module_register(&_module); +} +} // namespace OHOS::FileManagement::CloudSync diff --git a/mock/innerkits/filemanagement/dfs_service/interfaces/kits/js/cloudfilesync/cloud_sync_n_exporter.h b/mock/innerkits/filemanagement/dfs_service/interfaces/kits/js/cloudfilesync/cloud_sync_n_exporter.h new file mode 100644 index 00000000..4c00b923 --- /dev/null +++ b/mock/innerkits/filemanagement/dfs_service/interfaces/kits/js/cloudfilesync/cloud_sync_n_exporter.h @@ -0,0 +1,26 @@ +/* + * 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_N_EXPORTER_H +#define OHOS_FILEMGMT_CLOUD_SYNC_N_EXPORTER_H + +#include "filemgmt_libn.h" + +namespace OHOS::FileManagement::CloudSync { +void InitCloudSyncState(napi_env env, napi_value exports); +void InitFileSyncState(napi_env env, napi_value exports); +void InitErrorType(napi_env env, napi_value exports); +} // namespace OHOS::FileManagement::CloudSync +#endif // OHOS_FILEMGMT_CLOUD_SYNC_N_EXPORTER_H \ No newline at end of file diff --git a/mock/innerkits/filemanagement/dfs_service/interfaces/kits/js/cloudfilesync/cloud_sync_napi.cpp b/mock/innerkits/filemanagement/dfs_service/interfaces/kits/js/cloudfilesync/cloud_sync_napi.cpp new file mode 100644 index 00000000..b8d4747f --- /dev/null +++ b/mock/innerkits/filemanagement/dfs_service/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 diff --git a/mock/innerkits/filemanagement/dfs_service/interfaces/kits/js/cloudfilesync/cloud_sync_napi.h b/mock/innerkits/filemanagement/dfs_service/interfaces/kits/js/cloudfilesync/cloud_sync_napi.h new file mode 100644 index 00000000..b7900473 --- /dev/null +++ b/mock/innerkits/filemanagement/dfs_service/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 diff --git a/mock/innerkits/filemanagement/dfs_service/interfaces/kits/js/cloudfilesync/file_sync_napi.cpp b/mock/innerkits/filemanagement/dfs_service/interfaces/kits/js/cloudfilesync/file_sync_napi.cpp new file mode 100644 index 00000000..92951732 --- /dev/null +++ b/mock/innerkits/filemanagement/dfs_service/interfaces/kits/js/cloudfilesync/file_sync_napi.cpp @@ -0,0 +1,98 @@ +/* + * 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; + +struct SyncTimeArg { + int64_t time = 0; +}; + +napi_value FileSyncNapi::GetLastSyncTime(napi_env env, napi_callback_info info) +{ + LOGI("GetLastSyncTime Start"); + NFuncArg funcArg(env, info); + if (!funcArg.InitArgs(NARG_CNT::ZERO, NARG_CNT::ONE)) { + NError(E_PARAMS).ThrowErr(env); + return nullptr; + } + + auto arg = make_shared(); + if (arg == nullptr) { + HILOGE("Failed to request heap memory."); + NError(ENOMEM).ThrowErr(env); + return nullptr; + } + + auto cbExec = [arg]() -> NError { + int32_t ret = CloudSyncManager::GetInstance().GetSyncTime(arg->time); + if (ret != E_OK) { + LOGE("GetLastSyncTime error, result: %{public}d", ret); + return NError(Convert2JsErrNum(ret)); + } + return NError(ERRNO_NOERR); + }; + + auto cbComplete = [cbArg = arg](napi_env env, NError err) -> NVal { + if (err) { + return {env, err.GetNapiErr(env)}; + } + return NVal::CreateInt64(env, cbArg->time); + }; + + const std::string procedureName = "getLastSyncTime"; + NVal thisVar(env, funcArg.GetThisVar()); + if (funcArg.GetArgc() == NARG_CNT::ONE) { + if (!NVal(env, funcArg[NARG_POS::FIRST]).TypeIs(napi_number)) { + NVal cb(env, funcArg[NARG_POS::FIRST]); + return NAsyncWorkCallback(env, thisVar, cb).Schedule(procedureName, cbExec, cbComplete).val_; + } + LOGE("Get napi_number Error"); + NError(EINVAL).ThrowErr(env); + return nullptr; + } + return NAsyncWorkPromise(env, thisVar).Schedule(procedureName, cbExec, cbComplete).val_; +} + +struct SyncStateArg { + vector stateList {}; +}; + +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), + NVal::DeclareNapiFunction("getLastSyncTime", FileSyncNapi::GetLastSyncTime), + }; + + SetClassName("FileSync"); + return ToExport(props); +} +} // namespace OHOS::FileManagement::CloudSync \ No newline at end of file diff --git a/mock/innerkits/filemanagement/dfs_service/interfaces/kits/js/cloudfilesync/file_sync_napi.h b/mock/innerkits/filemanagement/dfs_service/interfaces/kits/js/cloudfilesync/file_sync_napi.h new file mode 100644 index 00000000..525d2f9b --- /dev/null +++ b/mock/innerkits/filemanagement/dfs_service/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 "gallery_sync_napi.h" +#include "cloud_sync_napi.h" + +namespace OHOS::FileManagement::CloudSync { +class FileSyncNapi final : public CloudSyncNapi { +public: + bool Export() override; + static napi_value GetLastSyncTime(napi_env env, napi_callback_info info); + FileSyncNapi(napi_env env, napi_value exports) : CloudSyncNapi(env, exports) {}; + ~FileSyncNapi() = default; +}; +} // namespace OHOS::FileManagement::CloudSync +#endif // OHOS_FILEMGMT_FILE_SYNC_NAPI_H diff --git a/mock/innerkits/filemanagement/dfs_service/interfaces/kits/js/cloudfilesync/gallery_sync_napi.cpp b/mock/innerkits/filemanagement/dfs_service/interfaces/kits/js/cloudfilesync/gallery_sync_napi.cpp new file mode 100644 index 00000000..17b0456d --- /dev/null +++ b/mock/innerkits/filemanagement/dfs_service/interfaces/kits/js/cloudfilesync/gallery_sync_napi.cpp @@ -0,0 +1,39 @@ +/* + * 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 "gallery_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; + +bool GallerySyncNapi::Export() +{ + SetClassName("GallerySync"); + bool success = CloudSyncNapi::Export(); + if (!success) { + return false; + } + return true; +} +} // namespace OHOS::FileManagement::CloudSync diff --git a/mock/innerkits/filemanagement/dfs_service/interfaces/kits/js/cloudfilesync/gallery_sync_napi.h b/mock/innerkits/filemanagement/dfs_service/interfaces/kits/js/cloudfilesync/gallery_sync_napi.h new file mode 100644 index 00000000..0ce0dc84 --- /dev/null +++ b/mock/innerkits/filemanagement/dfs_service/interfaces/kits/js/cloudfilesync/gallery_sync_napi.h @@ -0,0 +1,30 @@ +/* + * 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_GALLERY_SYNC_NAPI_H +#define OHOS_FILEMGMT_GALLERY_SYNC_NAPI_H + +#include "cloud_sync_napi.h" + +namespace OHOS::FileManagement::CloudSync { +class GallerySyncNapi final : public CloudSyncNapi { +public: + bool Export() override; + GallerySyncNapi(napi_env env, napi_value exports) : CloudSyncNapi(env, exports) {} + ~GallerySyncNapi() = default; +}; + +} // namespace OHOS::FileManagement::CloudSync +#endif // OHOS_FILEMGMT_GALLERY_SYNC_NAPI_H diff --git a/mock/innerkits/filemanagement/dfs_service/interfaces/kits/js/cloudsyncmanager/BUILD.gn b/mock/innerkits/filemanagement/dfs_service/interfaces/kits/js/cloudsyncmanager/BUILD.gn new file mode 100644 index 00000000..436a33a0 --- /dev/null +++ b/mock/innerkits/filemanagement/dfs_service/interfaces/kits/js/cloudsyncmanager/BUILD.gn @@ -0,0 +1,46 @@ +# 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. + +import("//build/ohos.gni") +import("//foundation/filemanagement/dfs_service/distributedfile.gni") + +ohos_shared_library("cloudsyncmanager") { + branch_protector_ret = "pac_ret" + sanitize = { + ubsan = true + boundary_sanitize = true + cfi = true + cfi_cross_dso = true + debug = false + } + sources = [ + "cloud_sync_manager_n_exporter.cpp", + "cloud_sync_manager_napi.cpp", + ] + deps = [ + "${innerkits_native_path}/cloudsync_kit_inner:cloudsync_kit_inner", + "${utils_path}:libdistributedfileutils", + ] + + external_deps = [ + "file_api:filemgmt_libhilog", + "file_api:filemgmt_libn", + "hilog:libhilog", + "napi:ace_napi", + ] + + relative_install_dir = "module/file" + + part_name = "dfs_service" + subsystem_name = "filemanagement" +} diff --git a/mock/innerkits/filemanagement/dfs_service/interfaces/kits/js/cloudsyncmanager/cloud_sync_manager_n_exporter.cpp b/mock/innerkits/filemanagement/dfs_service/interfaces/kits/js/cloudsyncmanager/cloud_sync_manager_n_exporter.cpp new file mode 100644 index 00000000..3f411c8f --- /dev/null +++ b/mock/innerkits/filemanagement/dfs_service/interfaces/kits/js/cloudsyncmanager/cloud_sync_manager_n_exporter.cpp @@ -0,0 +1,406 @@ +/* + * 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_manager_n_exporter.h" + +#include + +#include + +#include "cloud_sync_common.h" +#include "cloud_sync_manager.h" +#include "dfs_error.h" +#include "utils_log.h" +#include "async_work.h" + +namespace OHOS::FileManagement::CloudSync { +using namespace FileManagement::LibN; +using namespace std; + +napi_value ChangeAppCloudSwitch(napi_env env, napi_callback_info info) +{ + NFuncArg funcArg(env, info); + if (!funcArg.InitArgs(static_cast(NARG_CNT::THREE), static_cast(NARG_CNT::FOUR))) { + NError(E_PARAMS).ThrowErr(env, "Number of arguments unmatched"); + return nullptr; + } + + bool succ = false; + std::unique_ptr accoutId; + std::unique_ptr bundleName; + bool status; + + tie(succ, accoutId, std::ignore) = NVal(env, funcArg[(int)NARG_POS::FIRST]).ToUTF8String(); + if (!succ) { + NError(E_PARAMS).ThrowErr(env); + return nullptr; + } + + tie(succ, bundleName, std::ignore) = NVal(env, funcArg[(int)NARG_POS::SECOND]).ToUTF8String(); + if (!succ) { + NError(E_PARAMS).ThrowErr(env); + return nullptr; + } + + tie(succ, status) = NVal(env, funcArg[(int)NARG_POS::THIRD]).ToBool(); + if (!succ) { + NError(E_PARAMS).ThrowErr(env); + return nullptr; + } + + string accoutIdStr(accoutId.get()); + string bundleNameStr(bundleName.get()); + + auto cbExec = [accoutIdStr, bundleNameStr, status]() -> NError { + int32_t result = CloudSyncManager::GetInstance().ChangeAppSwitch(accoutIdStr, bundleNameStr, status); + if (result == E_PERMISSION_DENIED || result == E_PERMISSION_SYSTEM) { + return result == E_PERMISSION_DENIED? NError(Convert2JsErrNum(E_PERMISSION_DENIED)) : + NError(Convert2JsErrNum(E_PERMISSION_SYSTEM)); + } + 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 = "ChangeAppCloudSwitch"; + NVal thisVar(env, funcArg.GetThisVar()); + auto asyncWork = GetPromiseOrCallBackWork(env, funcArg, static_cast(NARG_CNT::FOUR)); + return asyncWork == nullptr ? nullptr : asyncWork->Schedule(procedureName, cbExec, cbComplete).val_; +} + +napi_value NotifyDataChangeInner(napi_env env, NFuncArg &funcArg) +{ + LOGI("NotifyDataChangeInner entrance"); + bool succ = false; + std::unique_ptr accoutId; + std::unique_ptr bundleName; + + tie(succ, accoutId, std::ignore) = NVal(env, funcArg[(int)NARG_POS::FIRST]).ToUTF8String(); + if (!succ) { + NError(E_PARAMS).ThrowErr(env); + return nullptr; + } + + tie(succ, bundleName, std::ignore) = NVal(env, funcArg[(int)NARG_POS::SECOND]).ToUTF8String(); + if (!succ) { + NError(E_PARAMS).ThrowErr(env); + return nullptr; + } + + string accoutIdStr(accoutId.get()); + string bundleNameStr(bundleName.get()); + + auto cbExec = [accoutIdStr, bundleNameStr]() -> NError { + int32_t result = CloudSyncManager::GetInstance().NotifyDataChange(accoutIdStr, bundleNameStr); + if (result == E_PERMISSION_DENIED || result == E_PERMISSION_SYSTEM) { + return result == E_PERMISSION_DENIED? NError(Convert2JsErrNum(E_PERMISSION_DENIED)) : + NError(Convert2JsErrNum(E_PERMISSION_SYSTEM)); + } + 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 = "NotifyDataChange"; + auto asyncWork = GetPromiseOrCallBackWork(env, funcArg, static_cast(NARG_CNT::THREE)); + return asyncWork == nullptr ? nullptr : asyncWork->Schedule(procedureName, cbExec, cbComplete).val_; +} + +static bool IsNotifyEventChange(napi_env env, NFuncArg &funcArg) +{ + auto options = NVal(env, funcArg[NARG_POS::SECOND]); + if (options.TypeIs(napi_object)) { + return true; + } + return false; +} + +napi_value NotifyEventChange(napi_env env, NFuncArg &funcArg) +{ + LOGI("NotifyEventChange entrance"); + bool succ = false; + int32_t userId; + tie(succ, userId) = NVal(env, funcArg[(int)NARG_POS::FIRST]).ToInt32(); + if (!succ) { + NError(E_PARAMS).ThrowErr(env); + return nullptr; + } + + auto argv = NVal(env, funcArg[NARG_POS::SECOND]); + if (!argv.HasProp("eventId") || !argv.HasProp("extraData")) { + NError(E_PARAMS).ThrowErr(env); + return nullptr; + } + + std::unique_ptr eventId; + std::unique_ptr extraData; + + tie(succ, eventId, std::ignore) = argv.GetProp("eventId").ToUTF8String(); + if (!succ) { + NError(E_PARAMS).ThrowErr(env); + return nullptr; + } + tie(succ, extraData, std::ignore) = argv.GetProp("extraData").ToUTF8String(); + if (!succ) { + NError(E_PARAMS).ThrowErr(env); + return nullptr; + } + + string eventIdStr(eventId.get()); + string extraDataStr(extraData.get()); + + auto cbExec = [userId, eventIdStr, extraDataStr]() -> NError { + int32_t result = CloudSyncManager::GetInstance().NotifyEventChange(userId, eventIdStr, extraDataStr); + if (result == E_PERMISSION_DENIED || result == E_PERMISSION_SYSTEM) { + return result == E_PERMISSION_DENIED? NError(Convert2JsErrNum(E_PERMISSION_DENIED)) : + NError(Convert2JsErrNum(E_PERMISSION_SYSTEM)); + } + 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 = "NotifyEventChange"; + auto asyncWork = GetPromiseOrCallBackWork(env, funcArg, static_cast(NARG_CNT::THREE)); + return asyncWork == nullptr ? nullptr : asyncWork->Schedule(procedureName, cbExec, cbComplete).val_; +} + +napi_value NotifyDataChange(napi_env env, napi_callback_info info) +{ + LOGI("NotifyDataChange entrance"); + NFuncArg funcArg(env, info); + if (!funcArg.InitArgs(static_cast(NARG_CNT::TWO), static_cast(NARG_CNT::THREE))) { + NError(E_PARAMS).ThrowErr(env, "Number of arguments unmatched"); + return nullptr; + } + + if (IsNotifyEventChange(env, funcArg)) { + return NotifyEventChange(env, funcArg); + } + return NotifyDataChangeInner(env, funcArg); +} + +napi_value DisableCloud(napi_env env, napi_callback_info info) +{ + LOGI("DisableCloud"); + NFuncArg funcArg(env, info); + if (!funcArg.InitArgs(static_cast(NARG_CNT::ONE), static_cast(NARG_CNT::TWO))) { + NError(E_PARAMS).ThrowErr(env, "Number of arguments unmatched"); + return nullptr; + } + + bool succ = false; + std::unique_ptr accoutId; + + tie(succ, accoutId, std::ignore) = NVal(env, funcArg[(int)NARG_POS::FIRST]).ToUTF8String(); + if (!succ) { + NError(E_PARAMS).ThrowErr(env); + return nullptr; + } + + string accoutIdStr(accoutId.get()); + + auto cbExec = [accoutIdStr]() -> NError { + int32_t result = CloudSyncManager::GetInstance().DisableCloud(accoutIdStr); + if (result == E_PERMISSION_DENIED || result == E_PERMISSION_SYSTEM) { + return result == E_PERMISSION_DENIED? NError(Convert2JsErrNum(E_PERMISSION_DENIED)) : + NError(Convert2JsErrNum(E_PERMISSION_SYSTEM)); + } + 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 = "DisableCloud"; + auto asyncWork = GetPromiseOrCallBackWork(env, funcArg, static_cast(NARG_CNT::TWO)); + return asyncWork == nullptr ? nullptr : asyncWork->Schedule(procedureName, cbExec, cbComplete).val_; +} + + +bool ParseSwitches(napi_env env, napi_value object, SwitchDataObj &data) +{ + napi_valuetype valueType = napi_undefined; + napi_typeof(env, object, &valueType); + if (valueType != napi_object) { + LOGE("ParseSwitches failed, not napi object"); + return false; + } + napi_value bundleNameArr = nullptr; + napi_get_property_names(env, object, &bundleNameArr); + uint32_t bundleNameNum = 0; + napi_get_array_length(env, bundleNameArr, &bundleNameNum); + for (uint32_t i = 0; i < bundleNameNum; ++i) { + napi_value item = nullptr; + napi_get_element(env, bundleNameArr, i, &item); + std::unique_ptr bundleId; + bool succ = false; + tie(succ, bundleId, std::ignore) = NVal(env, item).ToUTF8String(); + if (!succ) { + LOGE("fail to get string"); + return false; + } + + napi_value val = nullptr; + napi_get_named_property(env, object, bundleId.get(), &val); + bool switchVal = false; + tie(succ, switchVal) = NVal(env, val).ToBool(); + if (!succ) { + LOGE("fail to get switchVal"); + return false; + } + data.switchData.emplace(bundleId.get(), switchVal); + } + return true; +} + +napi_value EnableCloud(napi_env env, napi_callback_info info) +{ + LOGI("EnableCloud"); + NFuncArg funcArg(env, info); + if (!funcArg.InitArgs(static_cast(NARG_CNT::TWO), static_cast(NARG_CNT::THREE))) { + NError(E_PARAMS).ThrowErr(env, "Number of arguments unmatched"); + return nullptr; + } + + bool succ = false; + std::unique_ptr accoutId; + + tie(succ, accoutId, std::ignore) = NVal(env, funcArg[(int)NARG_POS::FIRST]).ToUTF8String(); + if (!succ) { + NError(E_PARAMS).ThrowErr(env); + return nullptr; + } + SwitchDataObj switchData; + if (!ParseSwitches(env, funcArg[(int)NARG_POS::SECOND], switchData)) { + NError(E_PARAMS).ThrowErr(env); + return nullptr; + } + + string accoutIdStr(accoutId.get()); + + auto cbExec = [accoutIdStr, switchData]() -> NError { + int32_t result = CloudSyncManager::GetInstance().EnableCloud(accoutIdStr, switchData); + if (result == E_PERMISSION_DENIED || result == E_PERMISSION_SYSTEM) { + return result == E_PERMISSION_DENIED? NError(Convert2JsErrNum(E_PERMISSION_DENIED)) : + NError(Convert2JsErrNum(E_PERMISSION_SYSTEM)); + } + 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 = "EnableCloud"; + auto asyncWork = GetPromiseOrCallBackWork(env, funcArg, static_cast(NARG_CNT::THREE)); + return asyncWork == nullptr ? nullptr : asyncWork->Schedule(procedureName, cbExec, cbComplete).val_; +} + +bool ParseAppActions(napi_env env, napi_value object, CleanOptions &cleanOptions) +{ + napi_valuetype valueType = napi_undefined; + napi_typeof(env, object, &valueType); + if (valueType != napi_object) { + LOGE("ParseAppActions failed, not napi object"); + return false; + } + napi_value bundleNameArr = nullptr; + napi_get_property_names(env, object, &bundleNameArr); + uint32_t bundleNameNum = 0; + napi_get_array_length(env, bundleNameArr, &bundleNameNum); + for (uint32_t i = 0; i < bundleNameNum; ++i) { + napi_value item = nullptr; + napi_get_element(env, bundleNameArr, i, &item); + std::unique_ptr bundleNameStr = nullptr; + bool resGetKey = false; + tie(resGetKey, bundleNameStr, ignore) = NVal(env, item).ToUTF8String(); + if (!resGetKey) { + LOGE("Fail to get string"); + return false; + } + napi_value actionObj = nullptr; + napi_get_named_property(env, object, bundleNameStr.get(), &actionObj); + int appActionsVal = 0; + bool resGetValue = false; + tie(resGetValue, appActionsVal) = NVal(env, actionObj).ToInt32(); + if (!resGetValue) { + LOGE("Fail to get appActionsVal"); + return false; + } + cleanOptions.appActionsData.emplace(string(bundleNameStr.get()).c_str(), appActionsVal); + } + return true; +} +napi_value Clean(napi_env env, napi_callback_info info) +{ + LOGI("Clean"); + NFuncArg funcArg(env, info); + if (!funcArg.InitArgs(static_cast(NARG_CNT::TWO), static_cast(NARG_CNT::THREE))) { + NError(E_PARAMS).ThrowErr(env, "Number of arguments unmatched"); + return nullptr; + } + std::unique_ptr accoutId = nullptr; + bool succ = false; + tie(succ, accoutId, ignore) = NVal(env, funcArg[(int)NARG_POS::FIRST]).ToUTF8String(); + if (!succ) { + NError(E_PARAMS).ThrowErr(env); + return nullptr; + } + CleanOptions cleanOptions {}; + if (!ParseAppActions(env, funcArg[(int)NARG_POS::SECOND], cleanOptions)) { + NError(E_PARAMS).ThrowErr(env); + return nullptr; + } + + std::string accoutIdStr(accoutId.get()); + auto cbExec = [accoutIdStr, cleanOptions]() -> NError { + int32_t result = CloudSyncManager::GetInstance().Clean(accoutIdStr, cleanOptions); + if (result == E_PERMISSION_DENIED || result == E_PERMISSION_SYSTEM) { + return result == E_PERMISSION_DENIED? NError(Convert2JsErrNum(E_PERMISSION_DENIED)) : + NError(Convert2JsErrNum(E_PERMISSION_SYSTEM)); + } + 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 = "Clean"; + auto asyncWork = GetPromiseOrCallBackWork(env, funcArg, static_cast(NARG_CNT::THREE)); + return asyncWork == nullptr ? nullptr : asyncWork->Schedule(procedureName, cbExec, cbComplete).val_; +} + +} // namespace OHOS::FileManagement::CloudSync diff --git a/mock/innerkits/filemanagement/dfs_service/interfaces/kits/js/cloudsyncmanager/cloud_sync_manager_n_exporter.h b/mock/innerkits/filemanagement/dfs_service/interfaces/kits/js/cloudsyncmanager/cloud_sync_manager_n_exporter.h new file mode 100644 index 00000000..3e60af8c --- /dev/null +++ b/mock/innerkits/filemanagement/dfs_service/interfaces/kits/js/cloudsyncmanager/cloud_sync_manager_n_exporter.h @@ -0,0 +1,29 @@ +/* + * 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_MANAGER_N_EXPORTER_H +#define OHOS_FILEMGMT_CLOUD_SYNC_MANAGER_N_EXPORTER_H + +#include "filemgmt_libn.h" + +namespace OHOS::FileManagement::CloudSync { +napi_value ChangeAppCloudSwitch(napi_env env, napi_callback_info info); +napi_value Clean(napi_env env, napi_callback_info info); +napi_value NotifyDataChange(napi_env env, napi_callback_info info); +napi_value NotifyEventChange(napi_env env, napi_callback_info info); +napi_value EnableCloud(napi_env env, napi_callback_info info); +napi_value DisableCloud(napi_env env, napi_callback_info info); +} // namespace OHOS::FileManagement::CloudSync +#endif // OHOS_FILEMGMT_CLOUD_SYNC_MANAGER_NAPI_H diff --git a/mock/innerkits/filemanagement/dfs_service/interfaces/kits/js/cloudsyncmanager/cloud_sync_manager_napi.cpp b/mock/innerkits/filemanagement/dfs_service/interfaces/kits/js/cloudsyncmanager/cloud_sync_manager_napi.cpp new file mode 100644 index 00000000..c0b33253 --- /dev/null +++ b/mock/innerkits/filemanagement/dfs_service/interfaces/kits/js/cloudsyncmanager/cloud_sync_manager_napi.cpp @@ -0,0 +1,72 @@ +/* + * 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_manager_napi.h" +#include "cloud_sync_manager_n_exporter.h" + +namespace OHOS::FileManagement::CloudSync { +using namespace FileManagement::LibN; +/*********************************************** + * Module export and register + ***********************************************/ + +static napi_value Init(napi_env env, napi_value exports) +{ + CloudSyncManagerExport(env, exports); + InitENumACtions(env, exports); + + return exports; +} + +void CloudSyncManagerExport(napi_env env, napi_value exports) +{ + static napi_property_descriptor desc[] = { + DECLARE_NAPI_FUNCTION("changeAppCloudSwitch", ChangeAppCloudSwitch), + DECLARE_NAPI_FUNCTION("clean", Clean), + DECLARE_NAPI_FUNCTION("notifyDataChange", NotifyDataChange), + DECLARE_NAPI_FUNCTION("enableCloud", EnableCloud), + DECLARE_NAPI_FUNCTION("disableCloud", DisableCloud), + }; + napi_define_properties(env, exports, sizeof(desc) / sizeof(desc[0]), desc); +} + +void InitENumACtions(napi_env env, napi_value exports) +{ + char propertyName[] = "Action"; + napi_value actionObj = nullptr; + napi_create_object(env, &actionObj); + napi_property_descriptor desc[] = { + DECLARE_NAPI_STATIC_PROPERTY("RETAIN_DATA", NVal::CreateInt32(env, (int32_t)Action::RETAIN_DATA).val_), + DECLARE_NAPI_STATIC_PROPERTY("CLEAR_DATA", NVal::CreateInt32(env, (int32_t)Action::CLEAR_DATA).val_), + }; + napi_define_properties(env, actionObj, sizeof(desc) / sizeof(desc[0]), desc); + napi_set_named_property(env, exports, propertyName, actionObj); +} + +static napi_module _module = { + .nm_version = 1, + .nm_flags = 0, + .nm_filename = nullptr, + .nm_register_func = Init, + .nm_modname = "file.cloudSyncManager", + .nm_priv = ((void *)0), + .reserved = {0} +}; + +extern "C" __attribute__((constructor)) void RegisterModule(void) +{ + napi_module_register(&_module); +} +} // namespace OHOS::FileManagement::CloudSync diff --git a/mock/innerkits/filemanagement/dfs_service/interfaces/kits/js/cloudsyncmanager/cloud_sync_manager_napi.h b/mock/innerkits/filemanagement/dfs_service/interfaces/kits/js/cloudsyncmanager/cloud_sync_manager_napi.h new file mode 100644 index 00000000..8484d12d --- /dev/null +++ b/mock/innerkits/filemanagement/dfs_service/interfaces/kits/js/cloudsyncmanager/cloud_sync_manager_napi.h @@ -0,0 +1,30 @@ +/* + * 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_MANAGER_NAPI_H +#define OHOS_FILEMGMT_CLOUD_SYNC_MANAGER_NAPI_H + +#include "filemgmt_libn.h" + +enum Action { + RETAIN_DATA = 0, + CLEAR_DATA +}; + +namespace OHOS::FileManagement::CloudSync { +void CloudSyncManagerExport(napi_env env, napi_value exports); +void InitENumACtions(napi_env env, napi_value exports); +} // namespace OHOS::FileManagement::CloudSync +#endif // OHOS_FILEMGMT_CLOUD_SYNC_MANAGER_NAPI_H \ No newline at end of file diff --git a/mock/src/mock_dfs_service.cpp b/mock/src/mock_dfs_service.cpp new file mode 100644 index 00000000..9b9c765d --- /dev/null +++ b/mock/src/mock_dfs_service.cpp @@ -0,0 +1,4 @@ +// +// Created by 86131 on 2023/12/13. +// + diff --git a/relational_store/frameworks/js/napi/common/BUILD.gn b/relational_store/frameworks/js/napi/common/BUILD.gn new file mode 100644 index 00000000..5ec56adf --- /dev/null +++ b/relational_store/frameworks/js/napi/common/BUILD.gn @@ -0,0 +1,47 @@ +# Copyright (c) 2022 Huawei Device Co., Ltd. +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import("//build/ohos.gni") +import("//foundation/distributeddatamgr/relational_store/relational_store.gni") +group("build_module") { + deps = [ ":commontype_napi" ] +} + +config("objectstore_config") { + ldflags = [ "-Wl,--exclude-libs=ALL" ] + + cflags = [ "-DHILOG_ENABLE" ] + + include_dirs = [ "${relational_store_innerapi_path}/common_type/include" ] +} + +config("objectstore_public_config") { + visibility = [ ":*" ] + + include_dirs = [ "." ] +} + +ohos_shared_library("commontype_napi") { + part_name = "relational_store" + sources = [ "${relational_store_base_path}/frameworks/js/napi/common/src/js_common_type_init.cpp" ] + + configs = [ ":objectstore_config" ] + + external_deps = [ + "hilog:libhilog", + "napi:ace_napi", + ] + + relative_install_dir = "module/data" + subsystem_name = "distributeddatamgr" +} diff --git a/relational_store/frameworks/js/napi/common/src/js_common_type_init.cpp b/relational_store/frameworks/js/napi/common/src/js_common_type_init.cpp new file mode 100644 index 00000000..cd024caa --- /dev/null +++ b/relational_store/frameworks/js/napi/common/src/js_common_type_init.cpp @@ -0,0 +1,75 @@ +/* + * Copyright (c) 2022 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "napi/native_api.h" +#include "napi/native_node_api.h" +#include "common_asset_value.h" + +namespace OHOS::CommonType { +static napi_status SetNamedProperty(napi_env env, napi_value &obj, const std::string &name, + int32_t value) +{ + napi_value property = nullptr; + napi_status status = napi_create_int32(env, value, &property); + if (status != napi_ok) { + return status; + } + status = napi_set_named_property(env, obj, name.c_str(), property); + return status; +} + +static napi_value ExportAssetStatus(napi_env env) +{ + napi_value assetStatus = nullptr; + napi_create_object(env, &assetStatus); + SetNamedProperty(env, assetStatus, "ASSET_NORMAL", AssetValue::STATUS_NORMAL); + SetNamedProperty(env, assetStatus, "ASSET_INSERT", AssetValue::STATUS_INSERT); + SetNamedProperty(env, assetStatus, "ASSET_UPDATE", AssetValue::STATUS_UPDATE); + SetNamedProperty(env, assetStatus, "ASSET_DELETE", AssetValue::STATUS_DELETE); + SetNamedProperty(env, assetStatus, "ASSET_ABNORMAL", AssetValue::STATUS_ABNORMAL); + SetNamedProperty(env, assetStatus, "ASSET_DOWNLOADING", AssetValue::STATUS_DOWNLOADING); + napi_object_freeze(env, assetStatus); + return assetStatus; +} +} + +static napi_value CommonTypeExport(napi_env env, napi_value exports) +{ + napi_status status; + static napi_property_descriptor desc[] = { + DECLARE_NAPI_PROPERTY("AssetStatus", OHOS::CommonType::ExportAssetStatus(env)), + }; + + status = napi_define_properties(env, exports, sizeof(desc) / sizeof(desc[0]), desc); + if (status != napi_ok) { + return nullptr; + } + return exports; +} + +static napi_module storageModule = { + .nm_version = 1, + .nm_flags = 0, + .nm_filename = nullptr, + .nm_register_func = CommonTypeExport, + .nm_modname = "data.commonType", + .nm_priv = ((void *)0), + .reserved = { 0 }, +}; + +static __attribute__((constructor)) void RegisterModule() +{ + napi_module_register(&storageModule); +} \ No newline at end of file diff --git a/relational_store/interfaces/inner_api/common_type/BUILD.gn b/relational_store/interfaces/inner_api/common_type/BUILD.gn new file mode 100644 index 00000000..1297d1e6 --- /dev/null +++ b/relational_store/interfaces/inner_api/common_type/BUILD.gn @@ -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. +import("//build/ohos.gni") +import("//foundation/distributeddatamgr/relational_store/relational_store.gni") + +config("common_type_config") { + visibility = [ "*:*" ] + + include_dirs = [ + "include", + "${kvstore_path}/common", + ] +} + +ohos_shared_library("common_type") { + part_name = "relational_store" + + ldflags = [ "-Wl,--exclude-libs,ALL" ] + cflags_cc = [ "-fvisibility=hidden" ] + + public_configs = [ ":common_type_config" ] + + sources = [ + "src/common_type_util.cpp", + "src/common_value_object.cpp", + "src/common_values_bucket.cpp", + ] + + external_deps = [ + "c_utils:utils", + "hilog:libhilog", + "hitrace:hitrace_meter", + "ipc:ipc_single", + ] + + innerapi_tags = [ "platformsdk" ] + subsystem_name = "distributeddatamgr" +} diff --git a/relational_store/interfaces/inner_api/common_type/include/common_asset_value.h b/relational_store/interfaces/inner_api/common_type/include/common_asset_value.h new file mode 100644 index 00000000..6008690b --- /dev/null +++ b/relational_store/interfaces/inner_api/common_type/include/common_asset_value.h @@ -0,0 +1,45 @@ +/* + * 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_COMMONTYPE_ASSET_VALUE_H +#define OHOS_COMMONTYPE_ASSET_VALUE_H +#include +namespace OHOS::CommonType { +struct AssetValue { + enum Status : int32_t { + STATUS_UNKNOWN, + STATUS_NORMAL, + STATUS_INSERT, + STATUS_UPDATE, + STATUS_DELETE, + STATUS_ABNORMAL, + STATUS_DOWNLOADING, + STATUS_BUTT + }; + static constexpr uint64_t NO_EXPIRES_TIME = 0; + uint32_t version = 0; + mutable uint32_t status = STATUS_UNKNOWN; + uint64_t expiresTime = NO_EXPIRES_TIME; + std::string id; + std::string name; + std::string uri; + std::string createTime; + std::string modifyTime; + std::string size; + std::string hash; + std::string path; +}; +} +#endif // OHOS_COMMONTYPE_H diff --git a/relational_store/interfaces/inner_api/common_type/include/common_errno.h b/relational_store/interfaces/inner_api/common_type/include/common_errno.h new file mode 100644 index 00000000..8c8007d4 --- /dev/null +++ b/relational_store/interfaces/inner_api/common_type/include/common_errno.h @@ -0,0 +1,38 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef OHOS_COMMONTYPE_ERRNO_H +#define OHOS_COMMONTYPE_ERRNO_H + +namespace OHOS { +namespace CommonType { + +/** +* @brief The error code in the correct case. +*/ +constexpr int E_OK = 0; + +/** +* @brief The base code of the exception error code. +*/ +constexpr int E_BASE = 14800000; + +/** +* @brief The error code for the object type is invalid. +*/ +constexpr int E_INVALID_OBJECT_TYPE = (E_BASE + 20); +} // namespace CommonType +} // namespace OHOS +#endif diff --git a/relational_store/interfaces/inner_api/common_type/include/common_type_util.h b/relational_store/interfaces/inner_api/common_type/include/common_type_util.h new file mode 100644 index 00000000..4396b3b8 --- /dev/null +++ b/relational_store/interfaces/inner_api/common_type/include/common_type_util.h @@ -0,0 +1,41 @@ +/* + * Copyright (c) 2022 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef OHOS_COMMONTYPE_TYPES_UTIL_H +#define OHOS_COMMONTYPE_TYPES_UTIL_H + +#include "itypes_util.h" +#include "visibility.h" +#include "common_value_object.h" +#include "common_values_bucket.h" + +namespace OHOS::ITypesUtil { +using ValueObject = CommonType::ValueObject; +using ValuesBucket = CommonType::ValuesBucket; +using Asset = CommonType::AssetValue; +template<> +API_EXPORT bool Marshalling(const ValueObject &input, MessageParcel &data); +template<> +API_EXPORT bool Unmarshalling(ValueObject &output, MessageParcel &data); +template<> +API_EXPORT bool Marshalling(const ValuesBucket &input, MessageParcel &data); +template<> +API_EXPORT bool Unmarshalling(ValuesBucket &output, MessageParcel &data); +template<> +API_EXPORT bool Marshalling(const Asset &input, MessageParcel &data); +template<> +API_EXPORT bool Unmarshalling(Asset &output, MessageParcel &data); +} +#endif // OHOS_COMMONTYPE_TYPES_UTIL_H diff --git a/relational_store/interfaces/inner_api/common_type/include/common_value_object.h b/relational_store/interfaces/inner_api/common_type/include/common_value_object.h new file mode 100644 index 00000000..095debca --- /dev/null +++ b/relational_store/interfaces/inner_api/common_type/include/common_value_object.h @@ -0,0 +1,383 @@ +/* + * 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 OHOS_COMMONTYPE_VALUE_OBJECT_H +#define OHOS_COMMONTYPE_VALUE_OBJECT_H + +#include +#include +#include + +#include "common_asset_value.h" +#include "visibility.h" +namespace OHOS { +namespace CommonType { +/** + * The ValueObject class of CommonType. + */ +class API_EXPORT ValueObject { +public: + /** + * @brief Use Type replace std::variant. + */ + using Nil = std::monostate; + using Blob = std::vector; + using Asset = AssetValue; + using Assets = std::vector; + using Type = std::variant; + template + struct index_of : std::integral_constant {}; + + template + inline static constexpr size_t index_of_v = index_of::value; + + template + struct index_of + : std::integral_constant ? 0 : index_of_v + 1> {}; + + template + struct variant_size_of { + static constexpr size_t value = sizeof...(Types); + }; + + template + struct variant_index_of { + static constexpr size_t value = index_of_v; + }; + + template + static variant_size_of variant_size_test(const std::variant &); + + template + static variant_index_of variant_index_test(const T &, const std::variant &); + + template + inline constexpr static int32_t TYPE_INDEX = + decltype(variant_index_test(std::declval(), std::declval()))::value; + + inline constexpr static int32_t TYPE_MAX = decltype(variant_size_test(std::declval()))::value; + + /** + * @brief Indicates the ValueObject {@link ValueObject} type. + * */ + enum TypeId : int32_t { + /** Indicates the ValueObject type is NULL.*/ + TYPE_NULL = TYPE_INDEX, + /** Indicates the ValueObject type is int.*/ + TYPE_INT = TYPE_INDEX, + /** Indicates the ValueObject type is double.*/ + TYPE_DOUBLE = TYPE_INDEX, + /** Indicates the ValueObject type is string.*/ + TYPE_STRING = TYPE_INDEX, + /** Indicates the ValueObject type is bool.*/ + TYPE_BOOL = TYPE_INDEX, + /** Indicates the ValueObject type is blob.*/ + TYPE_BLOB = TYPE_INDEX, + /** Indicates the ValueObject type is asset.*/ + TYPE_ASSET = TYPE_INDEX, + /** Indicates the ValueObject type is assets.*/ + TYPE_ASSETS = TYPE_INDEX, + /** the BUTT.*/ + TYPE_BUTT = TYPE_MAX + }; + Type value; + + /** + * @brief convert a std::variant input to another std::variant output with different (..._Types) + */ + template + static inline std::enable_if_t<(TYPE_INDEX) < TYPE_MAX, const char *> DeclType() + { + return DECLARE_TYPES[TYPE_INDEX]; + } + /** + * @brief Constructor. + */ + API_EXPORT ValueObject(); + + /** + * @brief Destructor. + */ + API_EXPORT ~ValueObject(); + + /** + * @brief Constructor. + * + * A parameterized constructor used to create a ValueObject instance. + */ + API_EXPORT ValueObject(Type val) noexcept; + + /** + * @brief Move constructor. + */ + API_EXPORT ValueObject(ValueObject &&val) noexcept; + + /** + * @brief Copy constructor. + */ + API_EXPORT ValueObject(const ValueObject &val); + + /** + * @brief Constructor. + * + * This constructor is used to convert the int input parameter to a value of type ValueObject. + * + * @param val Indicates an int input parameter. + */ + API_EXPORT ValueObject(int32_t val); + + /** + * @brief Constructor. + * + * This constructor is used to convert the int64_t input parameter to a value of type ValueObject. + * + * @param val Indicates an int64_t input parameter. + */ + API_EXPORT ValueObject(int64_t val); + + /** + * @brief Constructor. + * + * This constructor is used to convert the double input parameter to a value of type ValueObject. + * + * @param val Indicates an double input parameter. + */ + API_EXPORT ValueObject(double val); + + /** + * @brief Constructor. + * + * This constructor is used to convert the bool input parameter to a value of type ValueObject. + * + * @param val Indicates an bool input parameter. + */ + API_EXPORT ValueObject(bool val); + + /** + * @brief Constructor. + * + * This constructor is used to convert the string input parameter to a value of type ValueObject. + * + * @param val Indicates an string input parameter. + */ + API_EXPORT ValueObject(std::string val); + + /** + * @brief Constructor. + * + * This constructor is used to convert the const char * input parameter to a value of type ValueObject. + * + * @param val Indicates an const char * input parameter. + */ + API_EXPORT ValueObject(const char *val); + + /** + * @brief Constructor. + * + * This constructor is used to convert the vector input parameter to a value of type ValueObject. + * + * @param val Indicates an vector input parameter. + */ + API_EXPORT ValueObject(const std::vector &blob); + + /** + * @brief Constructor. + * + * This constructor is used to convert the Asset input parameter to a value of type ValueObject. + * + * @param val Indicates an Asset input parameter. + */ + API_EXPORT ValueObject(Asset val); + + /** + * @brief Constructor. + * + * This constructor is used to convert the Assets input parameter to a value of type ValueObject. + * + * @param val Indicates an Assets input parameter. + */ + API_EXPORT ValueObject(Assets val); + + /** + * @brief Move assignment operator overloaded function. + */ + API_EXPORT ValueObject &operator=(ValueObject &&valueObject) noexcept; + + /** + * @brief Copy assignment operator overloaded function. + */ + API_EXPORT ValueObject &operator=(const ValueObject &valueObject); + + /** + * @brief Obtains the type in this {@code ValueObject} object. + */ + API_EXPORT TypeId GetType() const; + + /** + * @brief Obtains the int value in this {@code ValueObject} object. + */ + API_EXPORT int GetInt(int &val) const; + + /** + * @brief Obtains the long value in this {@code ValueObject} object. + */ + API_EXPORT int GetLong(int64_t &val) const; + + /** + * @brief Obtains the double value in this {@code ValueObject} object. + */ + API_EXPORT int GetDouble(double &val) const; + + /** + * @brief Obtains the bool value in this {@code ValueObject} object. + */ + API_EXPORT int GetBool(bool &val) const; + + /** + * @brief Obtains the string value in this {@code ValueObject} object. + */ + API_EXPORT int GetString(std::string &val) const; + + /** + * @brief Obtains the vector value in this {@code ValueObject} object. + */ + API_EXPORT int GetBlob(std::vector &val) const; + + /** + * @brief Obtains the vector value in this {@code ValueObject} object. + */ + API_EXPORT int GetAsset(Asset &val) const; + + /** + * @brief Obtains the vector value in this {@code ValueObject} object. + */ + API_EXPORT int GetAssets(Assets &val) const; + + /** + * @brief Type conversion function. + * + * @return Returns the int type ValueObject. + */ + operator int() const + { + return static_cast(std::get(value)); + } + + /** + * @brief Type conversion function. + * + * @return Returns the int64_t type ValueObject. + */ + operator int64_t() const + { + return std::get(value); + } + + /** + * @brief Type conversion function. + * + * @return Returns the double type ValueObject. + */ + operator double() const + { + return std::get(value); + } + + /** + * @brief Type conversion function. + * + * @return Returns the bool type ValueObject. + */ + operator bool() const + { + return std::get(value); + } + + /** + * @brief Type conversion function. + * + * @return Returns the string type ValueObject. + */ + operator std::string() const + { + return std::get(value); + } + + /** + * @brief Type conversion function. + * + * @return Returns the vector type ValueObject. + */ + operator Blob() const + { + return std::get(value); + } + + /** + * @brief Type conversion function. + * + * @return Returns the vector type ValueObject. + */ + operator Asset() const + { + return std::get(value); + } + + /** + * @brief Type conversion function. + * + * @return Returns the vector type ValueObject. + */ + operator Assets() const + { + return std::get(value); + } + + /** + * @brief Type conversion function. + * + * @return Returns the Type type ValueObject. + */ + operator Type() const + { + return value; + } + +private: + template + int Get(T &output) const; + static constexpr const char *DECLARE_TYPES[TypeId::TYPE_BUTT] = { + /** Indicates the ValueObject type is NULL.*/ + "", + /** Indicates the ValueObject type is int.*/ + "INT", + /** Indicates the ValueObject type is double.*/ + "REAL", + /** Indicates the ValueObject type is string.*/ + "TEXT", + /** Indicates the ValueObject type is bool.*/ + "INT", + /** Indicates the ValueObject type is blob.*/ + "BLOB", + /** Indicates the ValueObject type is asset.*/ + "ASSET", + /** Indicates the ValueObject type is assets.*/ + "ASSETS" + }; +}; +using ValueObjectType = ValueObject::TypeId; +} // namespace CommonType +} // namespace OHOS +#endif diff --git a/relational_store/interfaces/inner_api/common_type/include/common_values_bucket.h b/relational_store/interfaces/inner_api/common_type/include/common_values_bucket.h new file mode 100644 index 00000000..c93aa189 --- /dev/null +++ b/relational_store/interfaces/inner_api/common_type/include/common_values_bucket.h @@ -0,0 +1,176 @@ +/* + * 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 OHOS_COMMONTYPE_VALUE_BUCKET_H +#define OHOS_COMMONTYPE_VALUE_BUCKET_H + +#include +#include + +#include "common_value_object.h" +namespace OHOS { +class Parcel; +namespace CommonType { +/** + * The ValuesBucket class of CommonType. + */ +class API_EXPORT ValuesBucket { +public: + /** + * @brief Constructor. + */ + API_EXPORT ValuesBucket(); + + /** + * @brief Constructor. + * + * A parameterized constructor used to create a ValuesBucket instance. + */ + API_EXPORT ValuesBucket(std::map values); + API_EXPORT ValuesBucket(const ValuesBucket &values); + API_EXPORT ValuesBucket &operator =(const ValuesBucket &values); + API_EXPORT ValuesBucket(ValuesBucket &&values) noexcept; + API_EXPORT ValuesBucket &operator =(ValuesBucket &&values) noexcept; + + /** + * @brief Destructor. + */ + API_EXPORT ~ValuesBucket(); + + /** + * @brief Put the string value to this {@code ValuesBucket} object for the given column name. + * + * @param columnName Indicates the name of the column. + * @param value Indicates the string value. + */ + API_EXPORT void PutString(const std::string &columnName, const std::string &value); + + /** + * @brief Put the int value to this {@code ValuesBucket} object for the given column name. + * + * @param columnName Indicates the name of the column. + * @param value Indicates the int value. + */ + API_EXPORT void PutInt(const std::string &columnName, int value); + + /** + * @brief Put the long value to this {@code ValuesBucket} object for the given column name. + * + * @param columnName Indicates the name of the column. + * @param value Indicates the long value. + */ + API_EXPORT void PutLong(const std::string &columnName, int64_t value); + + /** + * @brief Put the double value to this {@code ValuesBucket} object for the given column name. + * + * @param columnName Indicates the name of the column. + * @param value Indicates the double value. + */ + API_EXPORT void PutDouble(const std::string &columnName, double value); + + /** + * @brief Put the bool value to this {@code ValuesBucket} object for the given column name. + * + * @param columnName Indicates the name of the column. + * @param value Indicates the bool value. + */ + API_EXPORT void PutBool(const std::string &columnName, bool value); + + /** + * @brief Put the vector value to this {@code ValuesBucket} object for the given column name. + * + * @param columnName Indicates the name of the column. + * @param value Indicates the vector value. + */ + API_EXPORT void PutBlob(const std::string &columnName, const std::vector &value); + + /** + * @brief Put NULL to this {@code ValuesBucket} object for the given column name. + * + * @param columnName Indicates the name of the column. + */ + API_EXPORT void PutNull(const std::string &columnName); + + /** + * @brief Put the integer double bool string bytes asset asset and so on + * to this {@code ValuesBucket} object for the given column name. + * + * @param columnName Indicates the name of the column. + */ + API_EXPORT void Put(const std::string &columnName, const ValueObject &value); + + /** + * @brief Delete the ValueObject object for the given column name. + * + * @param columnName Indicates the name of the column. + */ + API_EXPORT void Delete(const std::string &columnName); + + /** + * @brief Clear the ValuesBucket object's valuesmap. + */ + API_EXPORT void Clear(); + + /** + * @brief Obtains the ValuesBucket object's valuesmap size. + */ + API_EXPORT int Size() const; + + /** + * @brief Checks whether the ValuesBucket object's valuesmap is empty. + */ + API_EXPORT bool IsEmpty() const; + + /** + * @brief Checks whether the ValuesBucket object's valuesmap contain the specified columnName. + * + * @param columnName Indicates the name of the column. + */ + API_EXPORT bool HasColumn(const std::string &columnName) const; + + /** + * @brief Obtains the specified value for the given column name. + * + * @param columnName Indicates the name of the column. + */ + API_EXPORT bool GetObject(const std::string &columnName, ValueObject &value) const; + + /** + * @brief Obtains the ValuesBucket object's valuesmap. + */ + API_EXPORT std::map GetAll() const; + + /** + * @brief Obtains the ValuesBucket object's valuesmap. + */ + API_EXPORT void GetAll(std::map &output) const; + + /** + * @brief set a ValuesBucket object to parcel. + */ + API_EXPORT bool Marshalling(Parcel &parcel) const; + + /** + * @brief Obtains a ValuesBucket object from parcel. + */ + API_EXPORT static ValuesBucket Unmarshalling(Parcel &parcel); + + std::map values_; +}; + +} // namespace CommonType +} // namespace OHOS +#endif diff --git a/relational_store/interfaces/inner_api/common_type/include/visibility.h b/relational_store/interfaces/inner_api/common_type/include/visibility.h new file mode 100644 index 00000000..1cc13490 --- /dev/null +++ b/relational_store/interfaces/inner_api/common_type/include/visibility.h @@ -0,0 +1,25 @@ +/* + * 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 COMMON_TYPE_VISIBILITY_H +#define COMMON_TYPE_VISIBILITY_H +#ifndef API_EXPORT +#if defined(__GNUC__) || defined(__clang__) +#define API_EXPORT __attribute__((visibility ("default"))) +#else +#define API_EXPORT +#endif +#endif +#endif // COMMON_TYPE_VISIBILITY_H diff --git a/relational_store/interfaces/inner_api/common_type/src/common_type_util.cpp b/relational_store/interfaces/inner_api/common_type/src/common_type_util.cpp new file mode 100644 index 00000000..aa2efd9b --- /dev/null +++ b/relational_store/interfaces/inner_api/common_type/src/common_type_util.cpp @@ -0,0 +1,52 @@ +/* + * Copyright (c) 2022 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "common_type_util.h" +namespace OHOS::ITypesUtil { +template<> +bool Marshalling(const ValueObject &input, MessageParcel &data) +{ + return Marshal(data, input.value); +} +template<> +bool Unmarshalling(ValueObject &output, MessageParcel &data) +{ + return Unmarshal(data, output.value); +} + +template<> +bool Marshalling(const ValuesBucket &input, MessageParcel &data) +{ + return Marshal(data, input.values_); +} +template<> +bool Unmarshalling(ValuesBucket &output, MessageParcel &data) +{ + return Unmarshal(data, output.values_); +} + +template<> +bool Marshalling(const Asset &input, MessageParcel &data) +{ + return Marshal(data, input.name, input.uri, input.path, input.createTime, + input.modifyTime, input.size, input.status, input.hash); +} +template<> +bool Unmarshalling(Asset &output, MessageParcel &data) +{ + return Unmarshal(data, output.name, output.uri, output.path, output.createTime, + output.modifyTime, output.size, output.status, output.hash); +} +} diff --git a/relational_store/interfaces/inner_api/common_type/src/common_value_object.cpp b/relational_store/interfaces/inner_api/common_type/src/common_value_object.cpp new file mode 100644 index 00000000..0efba7bb --- /dev/null +++ b/relational_store/interfaces/inner_api/common_type/src/common_value_object.cpp @@ -0,0 +1,183 @@ +/* + * 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_value_object.h" +#include "common_errno.h" + +namespace OHOS { +namespace CommonType { +ValueObject::ValueObject() +{ +} + +ValueObject::ValueObject(Type val) noexcept : value(std::move(val)) +{ +} + +ValueObject::ValueObject(ValueObject &&val) noexcept +{ + if (this == &val) { + return; + } + value = std::move(val.value); +} + +ValueObject::ValueObject(const ValueObject &val) +{ + if (this == &val) { + return; + } + value = val.value; +} + +ValueObject::~ValueObject() +{ +} + +ValueObject::ValueObject(int val) : value(static_cast(val)) +{ +} + +ValueObject::ValueObject(int64_t val) : value(val) +{ +} + +ValueObject::ValueObject(double val) : value(val) +{ +} + +ValueObject::ValueObject(bool val) : value(val) +{ +} + +ValueObject::ValueObject(std::string val) : value(std::move(val)) +{ +} + +ValueObject::ValueObject(const char *val) : ValueObject(std::string(val)) +{ +} + +ValueObject::ValueObject(const std::vector &val) : value(val) +{ +} + +ValueObject::ValueObject(ValueObject::Asset val) : value(std::move(val)) +{ +} + +ValueObject::ValueObject(ValueObject::Assets val) : value(std::move(val)) +{ +} + +ValueObject &ValueObject::operator=(ValueObject &&val) noexcept +{ + if (this == &val) { + return *this; + } + value = std::move(val.value); + return *this; +} + +ValueObject &ValueObject::operator=(const ValueObject &val) +{ + if (this == &val) { + return *this; + } + value = val.value; + return *this; +} + +ValueObjectType ValueObject::GetType() const +{ + return ValueObjectType(value.index()); +} + +int ValueObject::GetInt(int &val) const +{ + int64_t value = 0; + auto ret = Get(value); + val = value; + return ret; +} + +int ValueObject::GetLong(int64_t &val) const +{ + return Get(val); +} + +int ValueObject::GetDouble(double &val) const +{ + return Get(val); +} + +int ValueObject::GetBool(bool &val) const +{ + return Get(val); +} + +int ValueObject::GetString(std::string &val) const +{ + if (Get(val) == 0) { + return E_OK; + } + + double ftmp; + if (Get(ftmp) == 0) { + val = std::to_string(ftmp); + return E_OK; + } + + int64_t itmp; + if (Get(itmp) == 0) { + val = std::to_string(itmp); + return E_OK; + } + + bool btmp; + if (Get(btmp) == 0) { + val = std::to_string(btmp); + return E_OK; + } + return E_INVALID_OBJECT_TYPE; +} + +int ValueObject::GetBlob(std::vector &val) const +{ + return Get(val); +} + +int ValueObject::GetAsset(Asset &val) const +{ + return Get(val); +} + +int ValueObject::GetAssets(Assets &val) const +{ + return Get(val); +} + +template +int ValueObject::Get(T &output) const +{ + const T *v = std::get_if(&value); + if (v == nullptr) { + return E_INVALID_OBJECT_TYPE; + } + output = static_cast(*v); + return E_OK; +} +} // namespace CommonType +} // namespace OHOS diff --git a/relational_store/interfaces/inner_api/common_type/src/common_values_bucket.cpp b/relational_store/interfaces/inner_api/common_type/src/common_values_bucket.cpp new file mode 100644 index 00000000..59efabfb --- /dev/null +++ b/relational_store/interfaces/inner_api/common_type/src/common_values_bucket.cpp @@ -0,0 +1,162 @@ +/* + * 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_values_bucket.h" +#include "itypes_util.h" + +namespace OHOS { +namespace CommonType { +ValuesBucket::ValuesBucket() +{ +} + +ValuesBucket::ValuesBucket(std::map values) : values_(std::move(values)) +{ +} + +ValuesBucket::ValuesBucket(const ValuesBucket &values) : values_(values.values_) +{ +} + +ValuesBucket &ValuesBucket::operator=(const ValuesBucket &values) +{ + values_ = values.values_; + return *this; +} + +ValuesBucket::ValuesBucket(ValuesBucket &&values) noexcept : values_(std::move(values.values_)) +{ +} + +ValuesBucket &ValuesBucket::operator=(ValuesBucket &&values) noexcept +{ + values_ = std::move(values.values_); + return *this; +} + +ValuesBucket::~ValuesBucket() +{ +} + +void ValuesBucket::PutString(const std::string &columnName, const std::string &value) +{ + values_.insert(std::make_pair(columnName, ValueObject(value))); +} + +void ValuesBucket::PutInt(const std::string &columnName, int value) +{ + values_.insert(std::make_pair(columnName, ValueObject(value))); +} + +void ValuesBucket::PutLong(const std::string &columnName, int64_t value) +{ + values_.insert(std::make_pair(columnName, ValueObject(value))); +} + +void ValuesBucket::PutDouble(const std::string &columnName, double value) +{ + values_.insert(std::make_pair(columnName, ValueObject(value))); +} + +void ValuesBucket::PutBool(const std::string &columnName, bool value) +{ + values_.insert(std::make_pair(columnName, ValueObject(value))); +} + +void ValuesBucket::PutBlob(const std::string &columnName, const std::vector &value) +{ + values_.insert(std::make_pair(columnName, ValueObject(value))); +} + +void ValuesBucket::PutNull(const std::string &columnName) +{ + values_.insert(std::make_pair(columnName, ValueObject())); +} + +void ValuesBucket::Put(const std::string &columnName, const ValueObject &value) +{ + values_.insert_or_assign(columnName, value); +} + +void ValuesBucket::Delete(const std::string &columnName) +{ + values_.erase(columnName); +} + +void ValuesBucket::Clear() +{ + values_.clear(); +} + +int ValuesBucket::Size() const +{ + return values_.size(); +} + +bool ValuesBucket::IsEmpty() const +{ + return values_.empty(); +} + +bool ValuesBucket::HasColumn(const std::string &columnName) const +{ + auto iter = values_.find(columnName); + if (iter == values_.end()) { + return false; + } + return true; +} + +bool ValuesBucket::GetObject(const std::string &columnName, ValueObject &value) const +{ + auto iter = values_.find(columnName); + if (iter == values_.end()) { + return false; + } + value = iter->second; + return true; +} + +std::map ValuesBucket::GetAll() const +{ + return values_; +} + +void ValuesBucket::GetAll(std::map &output) const +{ + output = values_; +} + +bool ValuesBucket::Marshalling(Parcel &parcel) const +{ + MessageParcel *data = static_cast(&parcel); + if (data == nullptr) { + return false; + } + return ITypesUtil::Marshal(*data, values_); +} + +ValuesBucket ValuesBucket::Unmarshalling(Parcel &parcel) +{ + MessageParcel *data = static_cast(&parcel); + if (data == nullptr) { + return {}; + } + ValuesBucket bucket; + ITypesUtil::Unmarshal(*data, bucket.values_); + return bucket; +} +} // namespace CommonType +} // namespace OHOS -- Gitee