From e7699011f9d54b58117613eb7e9ec8e26ab532e8 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E5=BC=A0=E6=99=9F=E9=92=B0?= Date: Tue, 7 Jan 2025 21:56:52 +0800 Subject: [PATCH] =?UTF-8?q?=E5=A4=87=E4=BB=BD=E6=81=A2=E5=A4=8D=E6=96=B0?= =?UTF-8?q?=E5=A2=9E=E6=95=B0=E6=8D=AE=E9=87=8F=E5=A4=A7=E5=B0=8F=E8=8E=B7?= =?UTF-8?q?=E5=8F=96=E6=8E=A5=E5=8F=A3?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: 张晟钰 --- .../include/service_reverse.h | 2 + .../include/service_reverse_stub.h | 2 + .../src/b_incremental_backup_session.cpp | 16 ++ .../backup_kit_inner/src/b_session_backup.cpp | 16 ++ .../src/service_incremental_reverse.cpp | 9 + .../backup_kit_inner/src/service_proxy.cpp | 26 ++ .../backup_kit_inner/src/service_reverse.cpp | 9 + .../src/service_reverse_stub.cpp | 19 ++ .../impl/b_incremental_backup_session.h | 9 + .../backup_kit_inner/impl/b_session_backup.h | 11 + .../native/backup_kit_inner/impl/i_service.h | 1 + .../impl/i_service_ipc_interface_code.h | 1 + .../backup_kit_inner/impl/i_service_reverse.h | 2 + .../i_service_reverse_ipc_interface_code.h | 2 + .../backup_kit_inner/impl/service_proxy.h | 2 +- interfaces/kits/js/BUILD.gn | 1 + interfaces/kits/js/backup/general_callbacks.h | 4 +- .../kits/js/backup/parse_inc_info_from_js.cpp | 120 +++++++++ .../kits/js/backup/parse_inc_info_from_js.h | 32 +++ .../kits/js/backup/prop_n_operation.cpp | 63 +---- .../js/backup/session_backup_n_exporter.cpp | 74 +++++- .../js/backup/session_backup_n_exporter.h | 1 + .../session_incremental_backup_n_exporter.cpp | 121 +++++---- .../session_incremental_backup_n_exporter.h | 1 + .../include/module_external/bms_adapter.h | 5 + .../backup_sa/include/module_ipc/service.h | 39 +++ .../module_ipc/service_reverse_proxy.h | 2 + .../include/module_ipc/service_stub.h | 1 + .../src/module_external/bms_adapter.cpp | 36 +++ .../service_incremental_reverse_proxy.cpp | 18 ++ .../src/module_ipc/service_reverse_proxy.cpp | 18 ++ .../backup_sa/src/module_ipc/service_stub.cpp | 16 ++ .../backup_sa/src/module_ipc/sub_service.cpp | 236 ++++++++++++++++++ .../backup_kit_inner/service_proxy_mock.cpp | 5 + .../mock/module_external/bms_adapter_mock.cpp | 7 + .../include/bms_adapter_mock.h | 4 + .../module_external/src/bms_adapter_mock.cpp | 8 + .../include/service_reverse_proxy_mock.h | 6 + .../module_ipc/include/service_stub_mock.h | 2 + tests/mock/module_ipc/service_mock.cpp | 30 +++ .../module_ipc/service_reverse_proxy_mock.cpp | 4 + tests/mock/module_ipc/service_stub_mock.cpp | 7 + .../mock/module_ipc/src/service_stub_mock.cpp | 5 + .../mock/utils_mock/include/b_jsonutil_mock.h | 2 + .../backup_impl/include/i_service_mock.h | 5 + .../include/service_reverse_mock.h | 2 + .../backup_impl/service_reverse_stub_test.cpp | 5 + .../module_ipc/service_incremental_test.cpp | 5 + .../module_ipc/service_stub_test.cpp | 1 + .../backup_sa/session/service_proxy_mock.cpp | 5 + .../backup_sa/session/service_proxy_mock.h | 1 + utils/include/b_jsonutil/b_jsonutil.h | 21 ++ utils/src/b_jsonutil/b_jsonutil.cpp | 43 ++++ 53 files changed, 964 insertions(+), 119 deletions(-) create mode 100644 interfaces/kits/js/backup/parse_inc_info_from_js.cpp create mode 100644 interfaces/kits/js/backup/parse_inc_info_from_js.h diff --git a/frameworks/native/backup_kit_inner/include/service_reverse.h b/frameworks/native/backup_kit_inner/include/service_reverse.h index 3ecb58eab..c19668973 100644 --- a/frameworks/native/backup_kit_inner/include/service_reverse.h +++ b/frameworks/native/backup_kit_inner/include/service_reverse.h @@ -31,6 +31,7 @@ public: void BackupOnBundleFinished(int32_t errCode, std::string bundleName) override; void BackupOnAllBundlesFinished(int32_t errCode) override; void BackupOnProcessInfo(std::string bundleName, std::string processInfo) override; + void BackupOnScanningInfo(std::string scannedInfo) override; void RestoreOnBundleStarted(int32_t errCode, std::string bundleName) override; void RestoreOnBundleFinished(int32_t errCode, std::string bundleName) override; @@ -47,6 +48,7 @@ public: void IncrementalBackupOnBundleFinished(int32_t errCode, std::string bundleName) override; void IncrementalBackupOnAllBundlesFinished(int32_t errCode) override; void IncrementalBackupOnProcessInfo(std::string bundleName, std::string processInfo) override; + void IncrementalBackupOnScanningInfo(std::string scannedInfo) override; void IncrementalRestoreOnBundleStarted(int32_t errCode, std::string bundleName) override; void IncrementalRestoreOnBundleFinished(int32_t errCode, std::string bundleName) override; diff --git a/frameworks/native/backup_kit_inner/include/service_reverse_stub.h b/frameworks/native/backup_kit_inner/include/service_reverse_stub.h index 0384c0130..53a4964aa 100644 --- a/frameworks/native/backup_kit_inner/include/service_reverse_stub.h +++ b/frameworks/native/backup_kit_inner/include/service_reverse_stub.h @@ -40,6 +40,7 @@ private: int32_t CmdBackupOnBundleFinished(MessageParcel &data, MessageParcel &reply); int32_t CmdBackupOnAllBundlesFinished(MessageParcel &data, MessageParcel &reply); int32_t CmdBackupOnProcessInfo(MessageParcel &data, MessageParcel &reply); + int32_t CmdBackupOnScanningInfo(MessageParcel &data, MessageParcel &reply); int32_t CmdRestoreOnBundleStarted(MessageParcel &data, MessageParcel &reply); int32_t CmdRestoreOnBundleFinished(MessageParcel &data, MessageParcel &reply); @@ -54,6 +55,7 @@ private: int32_t CmdIncrementalBackupOnBundleFinished(MessageParcel &data, MessageParcel &reply); int32_t CmdIncrementalBackupOnAllBundlesFinished(MessageParcel &data, MessageParcel &reply); int32_t CmdIncrementalBackupOnProcessInfo(MessageParcel &data, MessageParcel &reply); + int32_t CmdIncrementalBackupOnScanningInfo(MessageParcel &data, MessageParcel &reply); int32_t CmdIncrementalRestoreOnBundleStarted(MessageParcel &data, MessageParcel &reply); int32_t CmdIncrementalRestoreOnBundleFinished(MessageParcel &data, MessageParcel &reply); diff --git a/frameworks/native/backup_kit_inner/src/b_incremental_backup_session.cpp b/frameworks/native/backup_kit_inner/src/b_incremental_backup_session.cpp index 8bae936bf..97de333ab 100644 --- a/frameworks/native/backup_kit_inner/src/b_incremental_backup_session.cpp +++ b/frameworks/native/backup_kit_inner/src/b_incremental_backup_session.cpp @@ -135,6 +135,22 @@ UniqueFd BIncrementalBackupSession::GetLocalCapabilities() return fd; } +ErrCode BIncrementalBackupSession::GetBackupDataSize(bool isPreciseScan, vector bundleNameList) +{ + HILOGI("GetBackupDataSize Begin"); + auto proxy = ServiceProxy::GetInstance(); + if (proxy == nullptr) { + HILOGE("Failed to get backup service"); + return BError(BError::Codes::SDK_BROKEN_IPC, "Failed to get backup service").GetCode(); + } + ErrCode err = proxy->GetBackupDataSize(isPreciseScan, bundleNameList); + if (err != ERR_OK) { + return BError(BError::Codes::SDK_BROKEN_IPC, "Failed to GetBackupDataSize").GetCode(); + } + HILOGI("GetBackupDataSize end"); + return ERR_OK; +} + ErrCode BIncrementalBackupSession::AppendBundles(vector bundlesToBackup) { auto proxy = ServiceProxy::GetInstance(); diff --git a/frameworks/native/backup_kit_inner/src/b_session_backup.cpp b/frameworks/native/backup_kit_inner/src/b_session_backup.cpp index e29c0324b..08e085331 100644 --- a/frameworks/native/backup_kit_inner/src/b_session_backup.cpp +++ b/frameworks/native/backup_kit_inner/src/b_session_backup.cpp @@ -145,6 +145,22 @@ UniqueFd BSessionBackup::GetLocalCapabilities() return fd; } +ErrCode BSessionBackup::GetBackupDataSize(bool isPreciseScan, vector bundleNameList) +{ + HILOGI("GetBackupDataSize Begin"); + auto proxy = ServiceProxy::GetInstance(); + if (proxy == nullptr) { + HILOGE("Failed to get backup service"); + return BError(BError::Codes::SDK_BROKEN_IPC, "Failed to get backup service").GetCode(); + } + ErrCode err = proxy->GetBackupDataSize(isPreciseScan, bundleNameList); + if (err != ERR_OK) { + return BError(BError::Codes::SDK_BROKEN_IPC, "Failed to GetBackupDataSize").GetCode(); + } + HILOGI("GetBackupDataSize end"); + return ERR_OK; +} + ErrCode BSessionBackup::AppendBundles(vector bundlesToBackup) { auto proxy = ServiceProxy::GetInstance(); diff --git a/frameworks/native/backup_kit_inner/src/service_incremental_reverse.cpp b/frameworks/native/backup_kit_inner/src/service_incremental_reverse.cpp index ba1e761c5..81f6ed9e6 100644 --- a/frameworks/native/backup_kit_inner/src/service_incremental_reverse.cpp +++ b/frameworks/native/backup_kit_inner/src/service_incremental_reverse.cpp @@ -81,6 +81,15 @@ void ServiceReverse::IncrementalBackupOnProcessInfo(std::string bundleName, std: callbacksIncrementalBackup_.onProcess(bundleName, processInfo); } +void ServiceReverse::IncrementalBackupOnScanningInfo(std::string scannedInfo) +{ + if (scenario_ != Scenario::BACKUP || !callbacksIncrementalBackup_.onBackupSizeReport) { + HILOGE("Error scenario or callback is nullptr, scenario = %{public}d", scenario_); + return; + } + callbacksIncrementalBackup_.onBackupSizeReport(scannedInfo); +} + void ServiceReverse::IncrementalRestoreOnBundleStarted(int32_t errCode, string bundleName) { if (scenario_ != Scenario::RESTORE || !callbacksIncrementalRestore_.onBundleStarted) { diff --git a/frameworks/native/backup_kit_inner/src/service_proxy.cpp b/frameworks/native/backup_kit_inner/src/service_proxy.cpp index 2d974d1dd..187f69ef7 100644 --- a/frameworks/native/backup_kit_inner/src/service_proxy.cpp +++ b/frameworks/native/backup_kit_inner/src/service_proxy.cpp @@ -810,4 +810,30 @@ UniqueFd ServiceProxy::GetLocalCapabilitiesForBundleInfos() HILOGI("ServiceProxy, end GetLocalCapabilitiesForBundleInfos"); return fd; } + +ErrCode ServiceProxy::GetBackupDataSize(bool isPreciseScan, vector bundleNameList) +{ + HILOGI("ServiceProxy GetBackupDataSize Begin."); + BExcepUltils::BAssert(Remote(), BError::Codes::SDK_INVAL_ARG, "Remote is nullptr"); + MessageParcel data; + if (!data.WriteInterfaceToken(GetDescriptor())) { + return BError(BError::Codes::SDK_INVAL_ARG, "Failed to write descriptor").GetCode(); + } + if (!data.WriteBool(isPreciseScan)) { + return BError(BError::Codes::SDK_INVAL_ARG, "Failed to write isPreciseScan").GetCode(); + } + if (!WriteParcelableVector(bundleNameList, data)) { + return BError(BError::Codes::SDK_INVAL_ARG, "Failed to write bundleNameList").GetCode(); + } + MessageParcel reply; + MessageOption option; + option.SetWaitTime(BConstants::IPC_MAX_WAIT_TIME); + int32_t ret = Remote()->SendRequest( + static_cast(IServiceInterfaceCode::SERVICE_CMD_GET_BACKUP_DATA_SIZE), data, reply, option); + if (ret != NO_ERROR) { + string str = "Failed to send out the request because of " + to_string(ret); + return BError(BError::Codes::SDK_INVAL_ARG, str.data()).GetCode(); + } + return BError(BError::Codes::OK, "success"); +} } // namespace OHOS::FileManagement::Backup diff --git a/frameworks/native/backup_kit_inner/src/service_reverse.cpp b/frameworks/native/backup_kit_inner/src/service_reverse.cpp index 6328cb70e..100a0dd09 100644 --- a/frameworks/native/backup_kit_inner/src/service_reverse.cpp +++ b/frameworks/native/backup_kit_inner/src/service_reverse.cpp @@ -79,6 +79,15 @@ void ServiceReverse::BackupOnProcessInfo(std::string bundleName, std::string pro callbacksBackup_.onProcess(bundleName, processInfo); } +void ServiceReverse::BackupOnScanningInfo(std::string scannedInfo) +{ + if (scenario_ != Scenario::BACKUP || !callbacksBackup_.onBackupSizeReport) { + HILOGE("Error scenario or callback is nullptr"); + return; + } + callbacksBackup_.onBackupSizeReport(scannedInfo); +} + void ServiceReverse::RestoreOnBundleStarted(int32_t errCode, string bundleName) { if (scenario_ != Scenario::RESTORE || !callbacksRestore_.onBundleStarted) { diff --git a/frameworks/native/backup_kit_inner/src/service_reverse_stub.cpp b/frameworks/native/backup_kit_inner/src/service_reverse_stub.cpp index 8f970cab4..2fae0a24a 100644 --- a/frameworks/native/backup_kit_inner/src/service_reverse_stub.cpp +++ b/frameworks/native/backup_kit_inner/src/service_reverse_stub.cpp @@ -45,6 +45,9 @@ int32_t ServiceReverseStub::OnRemoteRequest(uint32_t code, } void ServiceReverseStub::ServiceReverseStubSupplement() { + opToInterfaceMap_[static_cast( + IServiceReverseInterfaceCode::SERVICER_INCREMENTAL_BACKUP_ON_SCANNED_INFO)] = + &ServiceReverseStub::CmdIncrementalBackupOnScanningInfo; opToInterfaceMap_[static_cast(IServiceReverseInterfaceCode::SERVICER_INCREMENTAL_RESTORE_ON_FILE_READY)] = &ServiceReverseStub::CmdIncrementalRestoreOnFileReady; opToInterfaceMap_[static_cast( @@ -78,6 +81,8 @@ ServiceReverseStub::ServiceReverseStub() &ServiceReverseStub::CmdBackupOnAllBundlesFinished; opToInterfaceMap_[static_cast(IServiceReverseInterfaceCode::SERVICER_BACKUP_ON_PROCESS_INFO)] = &ServiceReverseStub::CmdBackupOnProcessInfo; + opToInterfaceMap_[static_cast(IServiceReverseInterfaceCode::SERVICER_BACKUP_ON_SCANNED_INFO)] = + &ServiceReverseStub::CmdBackupOnScanningInfo; opToInterfaceMap_[static_cast(IServiceReverseInterfaceCode::SERVICER_RESTORE_ON_FILE_READY)] = &ServiceReverseStub::CmdRestoreOnFileReady; @@ -164,6 +169,13 @@ int32_t ServiceReverseStub::CmdBackupOnProcessInfo(MessageParcel &data, MessageP return BError(BError::Codes::OK); } +int32_t ServiceReverseStub::CmdBackupOnScanningInfo(MessageParcel &data, MessageParcel &reply) +{ + std::string scannedInfo = data.ReadString(); + BackupOnScanningInfo(scannedInfo); + return BError(BError::Codes::OK); +} + int32_t ServiceReverseStub::CmdRestoreOnBundleStarted(MessageParcel &data, MessageParcel &reply) { int32_t errCode = data.ReadInt32(); @@ -282,6 +294,13 @@ int32_t ServiceReverseStub::CmdIncrementalBackupOnProcessInfo(MessageParcel &dat return BError(BError::Codes::OK); } +int32_t ServiceReverseStub::CmdIncrementalBackupOnScanningInfo(MessageParcel &data, MessageParcel &reply) +{ + std::string scannedInfo = data.ReadString(); + IncrementalBackupOnScanningInfo(scannedInfo); + return BError(BError::Codes::OK); +} + int32_t ServiceReverseStub::CmdIncrementalRestoreOnBundleStarted(MessageParcel &data, MessageParcel &reply) { int32_t errCode = data.ReadInt32(); diff --git a/interfaces/inner_api/native/backup_kit_inner/impl/b_incremental_backup_session.h b/interfaces/inner_api/native/backup_kit_inner/impl/b_incremental_backup_session.h index ab644a7a9..934cb5593 100644 --- a/interfaces/inner_api/native/backup_kit_inner/impl/b_incremental_backup_session.h +++ b/interfaces/inner_api/native/backup_kit_inner/impl/b_incremental_backup_session.h @@ -38,6 +38,7 @@ public: std::function onResultReport; // 某个应用备份流程中自定义错误信息的上报的回调函数 std::function onBackupServiceDied; // 当备份服务意外死亡时执行的回调函数 std::function onProcess; // 上报备份恢复过程中的进度和异常 + std::function onBackupSizeReport; // 返回已获取待备份数据量的信息 }; public: @@ -67,6 +68,14 @@ public: */ UniqueFd GetLocalCapabilities(); + /** + * @brief 获取需要备份的应用数据量大小 + * @param isPreciseScan 是否获取精确大小 + * @param bundleNameList 需要获取数据量大小的包名列表,包含时间戳信息 + * @return ErrCode 规范错误码 + */ + ErrCode GetBackupDataSize(bool isPreciseScan, std::vector bundleNameList); + /** * @brief 用于追加应用,现阶段仅支持在Start之前调用 * diff --git a/interfaces/inner_api/native/backup_kit_inner/impl/b_session_backup.h b/interfaces/inner_api/native/backup_kit_inner/impl/b_session_backup.h index ff25e9769..0fbcb4dc2 100644 --- a/interfaces/inner_api/native/backup_kit_inner/impl/b_session_backup.h +++ b/interfaces/inner_api/native/backup_kit_inner/impl/b_session_backup.h @@ -21,6 +21,8 @@ #include #include "b_file_info.h" +#include "b_incremental_data.h" +#include "errors.h" #include "errors.h" #include "svc_death_recipient.h" #include "unique_fd.h" @@ -36,6 +38,7 @@ public: std::function onResultReport; // 某个应用备份流程中自定义错误信息的上报的回调函数 std::function onBackupServiceDied; // 当备份服务意外死亡时执行的回调函数 std::function onProcess; // 上报备份恢复过程中的进度和异常 + std::function onBackupSizeReport; // 返回已获取待备份数据量的信息 }; public: @@ -64,6 +67,14 @@ public: */ UniqueFd GetLocalCapabilities(); + /** + * @brief 获取需要备份的应用数据量大小 + * @param isPreciseScan 是否获取精确大小 + * @param bundleNameList 需要获取数据量大小的包名列表,包含时间戳信息 + * @return ErrCode 规范错误码 + */ + ErrCode GetBackupDataSize(bool isPreciseScan, std::vector bundleNameList); + /** * @brief 用于追加应用,现阶段仅支持在Start之前调用 * diff --git a/interfaces/inner_api/native/backup_kit_inner/impl/i_service.h b/interfaces/inner_api/native/backup_kit_inner/impl/i_service.h index f087a1b03..0108a3437 100644 --- a/interfaces/inner_api/native/backup_kit_inner/impl/i_service.h +++ b/interfaces/inner_api/native/backup_kit_inner/impl/i_service.h @@ -95,6 +95,7 @@ public: virtual ErrCode StartFwkTimer(bool &isFwkStart) = 0; virtual ErrCode StopExtTimer(bool &isExtStop) = 0; virtual ErrCode RefreshDataSize(int64_t totalSize) = 0; + virtual ErrCode GetBackupDataSize(bool isPreciseScan, std::vector bundleNameList) = 0; DECLARE_INTERFACE_DESCRIPTOR(u"OHOS.Filemanagement.Backup.IService") }; diff --git a/interfaces/inner_api/native/backup_kit_inner/impl/i_service_ipc_interface_code.h b/interfaces/inner_api/native/backup_kit_inner/impl/i_service_ipc_interface_code.h index 37be6bfa2..ba99705fe 100644 --- a/interfaces/inner_api/native/backup_kit_inner/impl/i_service_ipc_interface_code.h +++ b/interfaces/inner_api/native/backup_kit_inner/impl/i_service_ipc_interface_code.h @@ -57,6 +57,7 @@ enum class IServiceInterfaceCode { SERVICE_CMD_CANCEL_BUNDLE, SERVICE_CMD_STOP_EXT_TIMER, SERVICE_CMD_REFRESH_DATA_SIZE, + SERVICE_CMD_GET_BACKUP_DATA_SIZE, }; } // namespace OHOS::FileManagement::Backup diff --git a/interfaces/inner_api/native/backup_kit_inner/impl/i_service_reverse.h b/interfaces/inner_api/native/backup_kit_inner/impl/i_service_reverse.h index 52311dde5..4ca5a7621 100644 --- a/interfaces/inner_api/native/backup_kit_inner/impl/i_service_reverse.h +++ b/interfaces/inner_api/native/backup_kit_inner/impl/i_service_reverse.h @@ -39,6 +39,7 @@ public: virtual void BackupOnBundleFinished(int32_t errCode, std::string bundleName) = 0; virtual void BackupOnAllBundlesFinished(int32_t errCode) = 0; virtual void BackupOnProcessInfo(std::string bundleName, std::string processInfo) = 0; + virtual void BackupOnScanningInfo(std::string scannedInfo) = 0; virtual void RestoreOnBundleStarted(int32_t errCode, std::string bundleName) = 0; virtual void RestoreOnFileReady(std::string bundleName, std::string fileName, int fd, int32_t errCode) = 0; @@ -55,6 +56,7 @@ public: virtual void IncrementalBackupOnBundleFinished(int32_t errCode, std::string bundleName) = 0; virtual void IncrementalBackupOnAllBundlesFinished(int32_t errCode) = 0; virtual void IncrementalBackupOnProcessInfo(std::string bundleName, std::string processInfo) = 0; + virtual void IncrementalBackupOnScanningInfo(std::string scannedInfo) = 0; virtual void IncrementalRestoreOnBundleStarted(int32_t errCode, std::string bundleName) = 0; virtual void IncrementalRestoreOnFileReady(std::string bundleName, diff --git a/interfaces/inner_api/native/backup_kit_inner/impl/i_service_reverse_ipc_interface_code.h b/interfaces/inner_api/native/backup_kit_inner/impl/i_service_reverse_ipc_interface_code.h index 5d991d6fb..cd06fa1d2 100644 --- a/interfaces/inner_api/native/backup_kit_inner/impl/i_service_reverse_ipc_interface_code.h +++ b/interfaces/inner_api/native/backup_kit_inner/impl/i_service_reverse_ipc_interface_code.h @@ -25,6 +25,7 @@ enum class IServiceReverseInterfaceCode { SERVICER_BACKUP_ON_TASK_FINISHED, SERVICER_BACKUP_ON_RESULT_REPORT, SERVICER_BACKUP_ON_PROCESS_INFO, + SERVICER_BACKUP_ON_SCANNED_INFO, SERVICER_RESTORE_ON_SUB_TASK_STARTED, SERVICER_RESTORE_ON_SUB_TASK_FINISHED, SERVICER_RESTORE_ON_TASK_FINISHED, @@ -37,6 +38,7 @@ enum class IServiceReverseInterfaceCode { SERVICER_INCREMENTAL_BACKUP_ON_TASK_FINISHED, SERVICER_INCREMENTAL_BACKUP_ON_RESULT_REPORT, SERVICER_INCREMENTAL_BACKUP_ON_PROCESS_INFO, + SERVICER_INCREMENTAL_BACKUP_ON_SCANNED_INFO, SERVICER_INCREMENTAL_RESTORE_ON_SUB_TASK_STARTED, SERVICER_INCREMENTAL_RESTORE_ON_SUB_TASK_FINISHED, SERVICER_INCREMENTAL_RESTORE_ON_TASK_FINISHED, diff --git a/interfaces/inner_api/native/backup_kit_inner/impl/service_proxy.h b/interfaces/inner_api/native/backup_kit_inner/impl/service_proxy.h index ec0a21c99..4302e07b8 100644 --- a/interfaces/inner_api/native/backup_kit_inner/impl/service_proxy.h +++ b/interfaces/inner_api/native/backup_kit_inner/impl/service_proxy.h @@ -78,7 +78,7 @@ public: ErrCode StartFwkTimer(bool &isFwkStart) override; ErrCode StopExtTimer(bool &isExtStop) override; ErrCode RefreshDataSize(int64_t totalSize) override; - + ErrCode GetBackupDataSize(bool isPreciseScan, std::vector bundleNameList) override; public: explicit ServiceProxy(const sptr &impl) : IRemoteProxy(impl) {} ~ServiceProxy() override {} diff --git a/interfaces/kits/js/BUILD.gn b/interfaces/kits/js/BUILD.gn index 5fb4dfb18..16db36cef 100644 --- a/interfaces/kits/js/BUILD.gn +++ b/interfaces/kits/js/BUILD.gn @@ -149,6 +149,7 @@ ohos_shared_library("backup") { sources = [ "${path_backup_js}/backup/general_callbacks.cpp", "${path_backup_js}/backup/module.cpp", + "${path_backup_js}/backup/parse_inc_info_from_js.cpp", "${path_backup_js}/backup/prop_n_exporter.cpp", "${path_backup_js}/backup/prop_n_operation.cpp", "${path_backup_js}/backup/session_backup_n_exporter.cpp", diff --git a/interfaces/kits/js/backup/general_callbacks.h b/interfaces/kits/js/backup/general_callbacks.h index 7f395fdfd..d7430cb19 100644 --- a/interfaces/kits/js/backup/general_callbacks.h +++ b/interfaces/kits/js/backup/general_callbacks.h @@ -53,7 +53,8 @@ public: onAllBundlesEnd(env, thisPtr, jsCallbacks.GetProp("onAllBundlesEnd")), onBackupServiceDied(env, thisPtr, jsCallbacks.GetProp("onBackupServiceDied")), onResultReport(env, thisPtr, jsCallbacks.GetProp("onResultReport")), - onProcess(env, thisPtr, jsCallbacks.GetProp("onProcess")) {}; + onProcess(env, thisPtr, jsCallbacks.GetProp("onProcess")), + onBackupSizeReport(env, thisPtr, jsCallbacks.GetProp("onBackupSizeReport")) {}; public: void RemoveCallbackRef(); public: @@ -64,6 +65,7 @@ public: BackupRestoreCallback onBackupServiceDied; BackupRestoreCallback onResultReport; BackupRestoreCallback onProcess; + BackupRestoreCallback onBackupSizeReport; }; } // namespace OHOS::FileManagement::Backup #endif // INTERFACES_KITS_JS_SRC_MOD_BACKUP_PROPERTIES_GENERAL_CALLBACKS_H \ No newline at end of file diff --git a/interfaces/kits/js/backup/parse_inc_info_from_js.cpp b/interfaces/kits/js/backup/parse_inc_info_from_js.cpp new file mode 100644 index 000000000..ed07b7f8f --- /dev/null +++ b/interfaces/kits/js/backup/parse_inc_info_from_js.cpp @@ -0,0 +1,120 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +#include + +#include "b_error/b_error.h" +#include "b_resources/b_constants.h" +#include "filemgmt_libn.h" + +#include "incremental_backup_data.h" +#include "parse_inc_info_from_js.h" + +namespace OHOS::FileManagement::Backup { +using namespace std; +using namespace LibN; +bool Parse::CheckDataList(const LibN::NVal &data) +{ + LibN::NVal name = data.GetProp(BConstants::BUNDLE_NAME); + if (name.val_ == nullptr) { + HILOGE("name.val is nullptr"); + return false; + } + auto [succ, str, ignore] = name.ToUTF8String(); + if (!succ) { + HILOGE("convert name failed"); + return false; + } + + LibN::NVal time = data.GetProp(BConstants::LAST_INCREMENTAL_TIME); + if (time.val_ == nullptr) { + HILOGE("time.val is nullptr"); + return false; + } + tie(succ, ignore) = time.ToInt64(); + if (!succ) { + HILOGE("convert time failed"); + return false; + } + return true; +} + +std::tuple> Parse::ParseDataList(napi_env env, const napi_value& value) +{ + uint32_t size = 0; + napi_status status = napi_get_array_length(env, value, &size); + if (status != napi_ok) { + HILOGE("Get array length failed!"); + return {false, {}}; + } + if (size == 0) { + HILOGI("array length is zero!"); + return {true, {}}; + } + + napi_value result; + std::vector backupData; + for (uint32_t i = 0; i < size; i++) { + status = napi_get_element(env, value, i, &result); + if (status != napi_ok) { + HILOGE("Get element failed! index is :%{public}u", i); + return {false, {}}; + } else { + NVal element(env, result); + if (!CheckDataList(element)) { + HILOGE("bundles are invalid!"); + return {false, {}}; + } + IncrementalBackupData data(element); + backupData.emplace_back(data.bundleName, + data.lastIncrementalTime, + data.manifestFd, + data.parameters, + data.priority); + } + } + return {true, backupData}; +} + +bool Parse::VerifyAndParseParams(napi_env env, LibN::NFuncArg &funcArg, + bool &isPreciseScan, std::vector &bundleNames) +{ + if (!funcArg.InitArgs(NARG_CNT::TWO)) { + HILOGE("Number of arguments unmatched."); + NError(BError(BError::Codes::SDK_INVAL_ARG, "Number of arguments unmatched.").GetCode()).ThrowErr(env); + return false; + } + + NVal jsBundleBool(env, funcArg[NARG_POS::FIRST]); + bool succ; + tie(succ, isPreciseScan) = jsBundleBool.ToBool(); + if (!succ) { + HILOGE("First argument is not bool."); + NError(BError(BError::Codes::SDK_INVAL_ARG, "Failed to get isPreciseScan.").GetCode()).ThrowErr(env); + return false; + } + tie(succ, bundleNames) = ParseDataList(env, funcArg[NARG_POS::SECOND]); + if (!succ) { + HILOGE("bundles array invalid."); + NError(BError(BError::Codes::SDK_INVAL_ARG, "bundles array invalid.").GetCode()).ThrowErr(env); + return false; + } + if (bundleNames.empty()) { + HILOGI("BundleName list is empty."); + NError(BError(BError::Codes::SDK_INVAL_ARG, "BundleName list is empty.").GetCode()).ThrowErr(env); + return false; + } + return true; +} +} // namespace OHOS::FileManagement::Backup \ No newline at end of file diff --git a/interfaces/kits/js/backup/parse_inc_info_from_js.h b/interfaces/kits/js/backup/parse_inc_info_from_js.h new file mode 100644 index 000000000..b3856dddb --- /dev/null +++ b/interfaces/kits/js/backup/parse_inc_info_from_js.h @@ -0,0 +1,32 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +#ifndef INTERFACES_KITS_JS_SRC_MOD_BACKUP_PARSE_INCREMENT_INFO_FROM_JS_H +#define INTERFACES_KITS_JS_SRC_MOD_BACKUP_PARSE_INCREMENT_INFO_FROM_JS_H + +#include +#include + +#include "b_incremental_data.h" + +namespace OHOS::FileManagement::Backup { +class Parse { +public: + static bool CheckDataList(const LibN::NVal &data); + static std::tuple> ParseDataList(napi_env env, const napi_value& value); + static bool VerifyAndParseParams(napi_env env, LibN::NFuncArg &funcArg, + bool &isPreciseScan, std::vector &bundleNames); +}; +} // namespace OHOS::FileManagement::Backup +#endif //INTERFACES_KITS_JS_SRC_MOD_BACKUP_PARSE_INCREMENT_INFO_FROM_JS_H \ No newline at end of file diff --git a/interfaces/kits/js/backup/prop_n_operation.cpp b/interfaces/kits/js/backup/prop_n_operation.cpp index d044890ab..e4a1ef547 100644 --- a/interfaces/kits/js/backup/prop_n_operation.cpp +++ b/interfaces/kits/js/backup/prop_n_operation.cpp @@ -21,6 +21,7 @@ #include "filemgmt_libhilog.h" #include "filemgmt_libn.h" #include "incremental_backup_data.h" +#include "parse_inc_info_from_js.h" #include "service_proxy.h" #include "access_token.h" #include "accesstoken_kit.h" @@ -69,70 +70,10 @@ static napi_value AsyncCallback(napi_env env, const NFuncArg& funcArg) } } -static bool CheckDataList(const LibN::NVal &data) -{ - LibN::NVal name = data.GetProp(BConstants::BUNDLE_NAME); - if (name.val_ == nullptr) { - return false; - } - auto [succ, str, ignore] = name.ToUTF8String(); - if (!succ) { - return false; - } - - LibN::NVal time = data.GetProp(BConstants::LAST_INCREMENTAL_TIME); - if (time.val_ == nullptr) { - return false; - } - tie(succ, ignore) = time.ToInt64(); - if (!succ) { - return false; - } - return true; -} - -static std::tuple> ParseDataList(napi_env env, const napi_value& value) -{ - uint32_t size = 0; - napi_status status = napi_get_array_length(env, value, &size); - if (status != napi_ok) { - HILOGE("Get array length failed!"); - return {false, {}}; - } - if (size == 0) { - HILOGI("array length is zero!"); - return {true, {}}; - } - - napi_value result; - std::vector backupData; - for (uint32_t i = 0; i < size; i++) { - status = napi_get_element(env, value, i, &result); - if (status != napi_ok) { - HILOGE("Get element failed! index is :%{public}u", i); - return {false, {}}; - } else { - NVal element(env, result); - if (!CheckDataList(element)) { - HILOGE("bundles are invalid!"); - return {false, {}}; - } - IncrementalBackupData data(element); - backupData.emplace_back(data.bundleName, - data.lastIncrementalTime, - data.manifestFd, - data.parameters, - data.priority); - } - } - return {true, backupData}; -} - static napi_value AsyncDataList(napi_env env, const NFuncArg& funcArg) { HILOGD("called LocalCapabilities::AsyncDataList begin"); - - auto [succ, bundles] = ParseDataList(env, funcArg[NARG_POS::FIRST]); + auto [succ, bundles] = Parse::ParseDataList(env, funcArg[NARG_POS::FIRST]); if (!succ) { HILOGE("bundles array invalid."); NError(BError(BError::Codes::SDK_INVAL_ARG, "bundles array invalid.").GetCode()).ThrowErr(env); diff --git a/interfaces/kits/js/backup/session_backup_n_exporter.cpp b/interfaces/kits/js/backup/session_backup_n_exporter.cpp index 54511d2f0..c8c256879 100644 --- a/interfaces/kits/js/backup/session_backup_n_exporter.cpp +++ b/interfaces/kits/js/backup/session_backup_n_exporter.cpp @@ -26,6 +26,7 @@ #include "directory_ex.h" #include "filemgmt_libhilog.h" #include "general_callbacks.h" +#include "parse_inc_info_from_js.h" #include "service_proxy.h" namespace OHOS::FileManagement::Backup { @@ -313,6 +314,30 @@ static bool SetSessionBackupEntity(napi_env env, NFuncArg &funcArg, std::unique_ return true; } +static void OnBackupSizeReport(weak_ptr pCallbacks, const std::string scannedResult) +{ + HILOGI("Callback OnBackupSizeReport..."); + auto callbacks = pCallbacks.lock(); + if (!callbacks) { + HILOGE("callback function OnScanning has already been released"); + return; + } + if (!bool(callbacks->onBackupSizeReport)) { + HILOGE("callback function OnScanning is undefined"); + return; + } + auto cbCompl = [scannedInfo {scannedResult}](napi_env env, vector &argv) -> bool { + napi_value napi_scanned = nullptr; + if (napi_create_string_utf8(env, scannedInfo.c_str(), scannedInfo.size(), &napi_scanned) != napi_ok) { + HILOGE("create napi string failed"); + return false; + } + argv.push_back(napi_scanned); + return true; + }; + callbacks->onBackupSizeReport.CallJsMethod(cbCompl); +} + napi_value SessionBackupNExporter::Constructor(napi_env env, napi_callback_info cbinfo) { HILOGD("called SessionBackup::Constructor begin"); @@ -348,7 +373,8 @@ napi_value SessionBackupNExporter::Constructor(napi_env env, napi_callback_info .onAllBundlesFinished = bind(onAllBundlesEnd, backupEntity->callbacks, placeholders::_1), .onResultReport = bind(OnResultReport, backupEntity->callbacks, placeholders::_1, placeholders::_2), .onBackupServiceDied = bind(OnBackupServiceDied, backupEntity->callbacks), - .onProcess = bind(OnProcess, backupEntity->callbacks, placeholders::_1, placeholders::_2)}, errMsg, errCode); + .onProcess = bind(OnProcess, backupEntity->callbacks, placeholders::_1, placeholders::_2), + .onBackupSizeReport = bind(OnBackupSizeReport, backupEntity->callbacks, placeholders::_1)}, errMsg, errCode); if (!backupEntity->session) { std::tuple errInfo = std::make_tuple(errCode, BError::GetBackupMsgByErrno(errCode) + ", " + errMsg); @@ -407,6 +433,51 @@ napi_value SessionBackupNExporter::GetLocalCapabilities(napi_env env, napi_callb return NAsyncWorkPromise(env, thisVar).Schedule(className, cbExec, cbCompl).val_; } +napi_value SessionBackupNExporter::GetBackupDataSize(napi_env env, napi_callback_info cbinfo) +{ + HILOGI("called GetBackupDataSize Begin"); + if (!SAUtils::CheckBackupPermission()) { + HILOGE("Has no permission!"); + NError(E_PERMISSION).ThrowErr(env); + return nullptr; + } + if (!SAUtils::IsSystemApp()) { + HILOGE("System app check failed!"); + NError(E_PERMISSION_SYS).ThrowErr(env); + return nullptr; + } + NFuncArg funcArg(env, cbinfo); + std::vector bundleNames; + bool isPreciseScan; + if (!Parse::VerifyAndParseParams(env, funcArg, isPreciseScan, bundleNames)) { + HILOGE("VerifyAndParseParams failed"); + return nullptr; + } + auto backupEntity = NClass::GetEntityOf(env, funcArg.GetThisVar()); + if (!(backupEntity && backupEntity->session)) { + HILOGE("Failed to get backupSession entity."); + NError(BError(BError::Codes::SDK_INVAL_ARG, "Failed to get backupSession entity.").GetCode()).ThrowErr(env); + return nullptr; + } + auto cbExec = [session {backupEntity->session.get()}, isPreciseScan {isPreciseScan}, + bundleNames {move(bundleNames)}]() -> NError { + if (!session) { + return NError(BError(BError::Codes::SDK_INVAL_ARG, "backup session is nullptr").GetCode()); + } + auto ret = session->GetBackupDataSize(isPreciseScan, bundleNames); + if (ret != ERR_OK) { + return NError(BError(BError::Codes::SDK_INVAL_ARG, "Failed to GetBackupDataSize").GetCode()); + } + HILOGI("GetBackupDataSize end"); + return NError(ERRNO_NOERR); + }; + auto cbCompl = [](napi_env env, NError err) -> NVal { + return err ? NVal {env, err.GetNapiErr(env)} : NVal::CreateUndefined(env); + }; + NVal thisVar(env, funcArg.GetThisVar()); + return NAsyncWorkPromise(env, thisVar).Schedule(className, cbExec, cbCompl).val_; +} + static bool VerifyParamSuccess(NFuncArg &funcArg, std::vector &bundleNames, std::vector &bundleInfos, napi_env env) { @@ -587,6 +658,7 @@ bool SessionBackupNExporter::Export() HILOGD("called SessionBackupNExporter::Export begin"); vector props = { NVal::DeclareNapiFunction("getLocalCapabilities", GetLocalCapabilities), + NVal::DeclareNapiFunction("getBackupDataSize", GetBackupDataSize), NVal::DeclareNapiFunction("appendBundles", AppendBundles), NVal::DeclareNapiFunction("release", Release), NVal::DeclareNapiFunction("cancel", Cancel), diff --git a/interfaces/kits/js/backup/session_backup_n_exporter.h b/interfaces/kits/js/backup/session_backup_n_exporter.h index 49dafdff5..5fc20d610 100644 --- a/interfaces/kits/js/backup/session_backup_n_exporter.h +++ b/interfaces/kits/js/backup/session_backup_n_exporter.h @@ -27,6 +27,7 @@ public: static napi_value Constructor(napi_env env, napi_callback_info cbinfo); static napi_value GetLocalCapabilities(napi_env env, napi_callback_info cbinfo); + static napi_value GetBackupDataSize(napi_env env, napi_callback_info cbinfo); static napi_value AppendBundles(napi_env env, napi_callback_info cbinfo); static napi_value Release(napi_env env, napi_callback_info cbinfo); static napi_value Cancel(napi_env env, napi_callback_info cbinfo); diff --git a/interfaces/kits/js/backup/session_incremental_backup_n_exporter.cpp b/interfaces/kits/js/backup/session_incremental_backup_n_exporter.cpp index 28f3d100c..ae958687b 100644 --- a/interfaces/kits/js/backup/session_incremental_backup_n_exporter.cpp +++ b/interfaces/kits/js/backup/session_incremental_backup_n_exporter.cpp @@ -28,6 +28,7 @@ #include "filemgmt_libhilog.h" #include "general_callbacks.h" #include "incremental_backup_data.h" +#include "parse_inc_info_from_js.h" #include "service_proxy.h" namespace OHOS::FileManagement::Backup { @@ -317,6 +318,30 @@ static bool SetIncrementalBackupEntity(napi_env env, NFuncArg &funcArg, std::uni return true; } +static void OnBackupSizeReport(weak_ptr pCallbacks, const std::string scannedResult) +{ + HILOGI("Callback OnBackupSizeReport..."); + auto callbacks = pCallbacks.lock(); + if (!callbacks) { + HILOGE("callback function OnScanning has already been released"); + return; + } + if (!bool(callbacks->onBackupSizeReport)) { + HILOGE("callback function OnScanning is undefined"); + return; + } + auto cbCompl = [scannedInfo {scannedResult}](napi_env env, vector &argv) -> bool { + napi_value napi_scanned = nullptr; + if (napi_create_string_utf8(env, scannedInfo.c_str(), scannedInfo.size(), &napi_scanned) != napi_ok) { + HILOGE("create napi string failed"); + return false; + } + argv.push_back(napi_scanned); + return true; + }; + callbacks->onBackupSizeReport.CallJsMethod(cbCompl); +} + napi_value SessionIncrementalBackupNExporter::Constructor(napi_env env, napi_callback_info cbinfo) { HILOGD("called SessionIncrementalBackup::Constructor begin"); @@ -330,13 +355,11 @@ napi_value SessionIncrementalBackupNExporter::Constructor(napi_env env, napi_cal } NFuncArg funcArg(env, cbinfo); if (!funcArg.InitArgs(NARG_CNT::ONE)) { - HILOGE("Number of arguments unmatched"); NError(BError(BError::Codes::SDK_INVAL_ARG, "Number of arguments unmatched.").GetCode()).ThrowErr(env); return nullptr; } NVal callbacks(env, funcArg[NARG_POS::FIRST]); if (!callbacks.TypeIs(napi_object)) { - HILOGE("First argument is not an object."); NError(BError(BError::Codes::SDK_INVAL_ARG, "First argument is not an object.").GetCode()).ThrowErr(env); return nullptr; } @@ -353,7 +376,8 @@ napi_value SessionIncrementalBackupNExporter::Constructor(napi_env env, napi_cal .onAllBundlesFinished = bind(onAllBundlesEnd, backupEntity->callbacks, placeholders::_1), .onResultReport = bind(OnResultReport, backupEntity->callbacks, placeholders::_1, placeholders::_2), .onBackupServiceDied = bind(OnBackupServiceDied, backupEntity->callbacks), - .onProcess = bind(OnProcess, backupEntity->callbacks, placeholders::_1, placeholders::_2)}, errMsg, errCode); + .onProcess = bind(OnProcess, backupEntity->callbacks, placeholders::_1, placeholders::_2), + .onBackupSizeReport = bind(OnBackupSizeReport, backupEntity->callbacks, placeholders::_1)}, errMsg, errCode); if (!backupEntity->session) { std::tuple errInfo = std::make_tuple(errCode, BError::GetBackupMsgByErrno(errCode) + ", " + errMsg); @@ -412,63 +436,49 @@ napi_value SessionIncrementalBackupNExporter::GetLocalCapabilities(napi_env env, return NAsyncWorkPromise(env, thisVar).Schedule(className, cbExec, cbCompl).val_; } -static bool CheckDataList(const LibN::NVal &data) +napi_value SessionIncrementalBackupNExporter::GetBackupDataSize(napi_env env, napi_callback_info cbinfo) { - LibN::NVal name = data.GetProp(BConstants::BUNDLE_NAME); - if (name.val_ == nullptr) { - return false; - } - auto [succ, str, ignore] = name.ToUTF8String(); - if (!succ) { - return false; - } - - LibN::NVal time = data.GetProp(BConstants::LAST_INCREMENTAL_TIME); - if (time.val_ == nullptr) { - return false; + HILOGI("called GetBackupDataSize Begin"); + if (!SAUtils::CheckBackupPermission()) { + HILOGE("Has no permission!"); + NError(E_PERMISSION).ThrowErr(env); + return nullptr; } - tie(succ, ignore) = time.ToInt64(); - if (!succ) { - return false; + if (!SAUtils::IsSystemApp()) { + HILOGE("System app check failed!"); + NError(E_PERMISSION_SYS).ThrowErr(env); + return nullptr; } - return true; -} - -static std::tuple> ParseDataList(napi_env env, const napi_value& value) -{ - uint32_t size = 0; - napi_status status = napi_get_array_length(env, value, &size); - if (status != napi_ok) { - HILOGE("Get array length failed!"); - return {false, {}}; + NFuncArg funcArg(env, cbinfo); + std::vector bundleNames; + bool isPreciseScan; + if (!Parse::VerifyAndParseParams(env, funcArg, isPreciseScan, bundleNames)) { + HILOGE("VerifyAndParseParams failed"); + return nullptr; } - if (size == 0) { - HILOGI("array length is zero!"); - return {true, {}}; + auto backupEntity = NClass::GetEntityOf(env, funcArg.GetThisVar()); + if (!(backupEntity && backupEntity->session)) { + HILOGE("Failed to get backupSession entity."); + NError(BError(BError::Codes::SDK_INVAL_ARG, "Failed to get backupSession entity.").GetCode()).ThrowErr(env); + return nullptr; } - - napi_value result; - std::vector backupData; - for (uint32_t i = 0; i < size; i++) { - status = napi_get_element(env, value, i, &result); - if (status != napi_ok) { - HILOGE("Get element failed! index is :%{public}u", i); - return {false, {}}; - } else { - NVal element(env, result); - if (!CheckDataList(element)) { - HILOGE("bundles are invalid!"); - return {false, {}}; - } - IncrementalBackupData data(element); - backupData.emplace_back(data.bundleName, - data.lastIncrementalTime, - data.manifestFd, - data.parameters, - data.priority); + auto cbExec = [session {backupEntity->session.get()}, isPreciseScan {isPreciseScan}, + bundleNames {move(bundleNames)}]() -> NError { + if (!session) { + return NError(BError(BError::Codes::SDK_INVAL_ARG, "backup session is nullptr").GetCode()); } - } - return {true, backupData}; + auto ret = session->GetBackupDataSize(isPreciseScan, bundleNames); + if (ret != ERR_OK) { + return NError(BError(BError::Codes::SDK_INVAL_ARG, "Failed to GetBackupDataSize").GetCode()); + } + HILOGI("GetBackupDataSize end"); + return NError(ERRNO_NOERR); + }; + auto cbCompl = [](napi_env env, NError err) -> NVal { + return err ? NVal {env, err.GetNapiErr(env)} : NVal::CreateUndefined(env); + }; + NVal thisVar(env, funcArg.GetThisVar()); + return NAsyncWorkPromise(env, thisVar).Schedule(className, cbExec, cbCompl).val_; } static bool VerifyParamSuccess(NFuncArg &funcArg, std::vector &backupBundles, @@ -479,7 +489,7 @@ static bool VerifyParamSuccess(NFuncArg &funcArg, std::vector NError(BError(BError::Codes::SDK_INVAL_ARG, "Number of arguments unmatched.").GetCode()).ThrowErr(env); return false; } - auto [succ, bundles] = ParseDataList(env, funcArg[NARG_POS::FIRST]); + auto [succ, bundles] = Parse::ParseDataList(env, funcArg[NARG_POS::FIRST]); if (!succ) { HILOGE("bundles array invalid."); NError(BError(BError::Codes::SDK_INVAL_ARG, "bundles array invalid.").GetCode()).ThrowErr(env); @@ -647,6 +657,7 @@ bool SessionIncrementalBackupNExporter::Export() HILOGD("called SessionIncrementalBackupNExporter::Export begin"); vector props = { NVal::DeclareNapiFunction("getLocalCapabilities", GetLocalCapabilities), + NVal::DeclareNapiFunction("getBackupDataSize", GetBackupDataSize), NVal::DeclareNapiFunction("appendBundles", AppendBundles), NVal::DeclareNapiFunction("release", Release), NVal::DeclareNapiFunction("cancel", Cancel), diff --git a/interfaces/kits/js/backup/session_incremental_backup_n_exporter.h b/interfaces/kits/js/backup/session_incremental_backup_n_exporter.h index 1464797e1..d2d5ba475 100644 --- a/interfaces/kits/js/backup/session_incremental_backup_n_exporter.h +++ b/interfaces/kits/js/backup/session_incremental_backup_n_exporter.h @@ -27,6 +27,7 @@ public: static napi_value Constructor(napi_env env, napi_callback_info cbinfo); static napi_value GetLocalCapabilities(napi_env env, napi_callback_info cbinfo); + static napi_value GetBackupDataSize(napi_env env, napi_callback_info cbinfo); static napi_value AppendBundles(napi_env env, napi_callback_info cbinfo); static napi_value Release(napi_env env, napi_callback_info cbinfo); static napi_value Cancel(napi_env env, napi_callback_info cbinfo); diff --git a/services/backup_sa/include/module_external/bms_adapter.h b/services/backup_sa/include/module_external/bms_adapter.h index 651b6279a..72fd55d18 100644 --- a/services/backup_sa/include/module_external/bms_adapter.h +++ b/services/backup_sa/include/module_external/bms_adapter.h @@ -75,6 +75,11 @@ public: static std::vector GetBundleInfosForIndex( const vector &bundleNames, int32_t userId); + + static int64_t GetBundleDataSize(const std::string &bundleName, int32_t userId); + + static void CreatBackupEnv(const std::vector &bundleNameList, int32_t userId); + private: static bool GetCurBundleExtenionInfo(AppExecFwk::BundleInfo &installedBundle, const std::string &bundleName, std::vector &extensionInfos, sptr bms, diff --git a/services/backup_sa/include/module_ipc/service.h b/services/backup_sa/include/module_ipc/service.h index 3d2cf16ba..5665c5b39 100644 --- a/services/backup_sa/include/module_ipc/service.h +++ b/services/backup_sa/include/module_ipc/service.h @@ -104,6 +104,8 @@ public: const ErrCode errCode, const BackupRestoreScenario sennario); void StartGetFdTask(std::string bundleName, wptr ptr); + ErrCode GetBackupDataSize(bool isPreciseScan, vector bundleNameList) override; + // 以下都是非IPC接口 public: void OnStart() override; @@ -314,6 +316,9 @@ public: explicit Service(int32_t saID, bool runOnCreate = false) : SystemAbility(saID, runOnCreate) { threadPool_.Start(BConstants::EXTENSION_THREAD_POOL_COUNT); + sendScannendResultThreadPool_.Start(BConstants::SA_THREAD_POOL_COUNT); + getDataSizeThreadPool_.Start(BConstants::SA_THREAD_POOL_COUNT); + callbackScannedInfoThreadPool_.Start(BConstants::SA_THREAD_POOL_COUNT); session_ = sptr(new SvcSessionManager(wptr(this))); disposal_ = make_shared(); clearRecorder_ = make_shared(); @@ -322,6 +327,9 @@ public: ~Service() override { threadPool_.Stop(); + sendScannendResultThreadPool_.Stop(); + getDataSizeThreadPool_.Stop(); + callbackScannedInfoThreadPool_.Stop(); }; private: @@ -604,6 +612,26 @@ private: void StartCurBundleBackupOrRestore(const std::string &bundleName); void CallOnBundleEndByScenario(const std::string &bundleName, BackupRestoreScenario scenario, ErrCode errCode); + + void GetDataSizeStepByStep(bool isPreciseScan, vector bundleNameList, string &scanning); + + void GetPresumablySize(vector bundleNameList, string &scanning); + + void GetPrecisesSize(vector bundleNameList, string &scanning); + + void WriteToList(BJsonUtil::BundleDataSize bundleDataSize); + + void DeleteFromList(size_t scannedSize); + + void WriteScannedInfoToList(const string &bundleName, int64_t dataSize, int64_t incDataSize); + + void SendScannedInfo(const string &scannendInfos, sptr session); + + void CyclicSendScannedInfo(bool isPreciseScan, vector bundleNameList); + + bool GetScanningInfo(wptr obj, size_t scannedSize, string &scanning); + + void SetScanningInfo(string &scanning, string name); private: static sptr instance_; static std::mutex instanceLock_; @@ -625,10 +653,21 @@ private: OHOS::ThreadPool threadPool_; std::mutex extensionMutexLock_; std::mutex failedBundlesLock_; + + std::mutex scannedListLock_; + std::mutex getDataSizeLock_; + OHOS::ThreadPool callbackScannedInfoThreadPool_; + OHOS::ThreadPool getDataSizeThreadPool_; + OHOS::ThreadPool sendScannendResultThreadPool_; + std::condition_variable getDataSizeCon_; + std::atomic isScannedEnd_ {false}; + std::atomic onScanning_ {false}; public: std::map> backupExtMutexMap_; std::map failedBundles_; std::atomic successBundlesNum_ {0}; + std::vector bundleDataSizeList_; + std::string scannedInfo_; }; } // namespace OHOS::FileManagement::Backup diff --git a/services/backup_sa/include/module_ipc/service_reverse_proxy.h b/services/backup_sa/include/module_ipc/service_reverse_proxy.h index 3e6667d8d..7578aca36 100644 --- a/services/backup_sa/include/module_ipc/service_reverse_proxy.h +++ b/services/backup_sa/include/module_ipc/service_reverse_proxy.h @@ -28,6 +28,7 @@ public: void BackupOnBundleFinished(int32_t errCode, std::string bundleName) override; void BackupOnAllBundlesFinished(int32_t errCode) override; void BackupOnProcessInfo(std::string bundleName, std::string processInfo) override; + void BackupOnScanningInfo(std::string scannedInfo) override; void RestoreOnBundleStarted(int32_t errCode, std::string bundleName) override; void RestoreOnFileReady(std::string bundleName, std::string fileName, int fd, int32_t errCode) override; @@ -44,6 +45,7 @@ public: void IncrementalBackupOnBundleFinished(int32_t errCode, std::string bundleName) override; void IncrementalBackupOnAllBundlesFinished(int32_t errCode) override; void IncrementalBackupOnProcessInfo(std::string bundleName, std::string processInfo) override; + void IncrementalBackupOnScanningInfo(std::string scannedInfo) override; void IncrementalRestoreOnBundleStarted(int32_t errCode, std::string bundleName) override; void IncrementalRestoreOnFileReady(std::string bundleName, std::string fileName, int fd, int manifestFd, diff --git a/services/backup_sa/include/module_ipc/service_stub.h b/services/backup_sa/include/module_ipc/service_stub.h index 79bcb0860..d4484365a 100644 --- a/services/backup_sa/include/module_ipc/service_stub.h +++ b/services/backup_sa/include/module_ipc/service_stub.h @@ -72,6 +72,7 @@ private: int32_t CmdStartFwkTimer(MessageParcel &data, MessageParcel &reply); int32_t CmdStopExtTimer(MessageParcel &data, MessageParcel &reply); int32_t CmdRefreshDataSize(MessageParcel &data, MessageParcel &reply); + int32_t CmdGetBackupDataSize(MessageParcel &data, MessageParcel &reply); void ServiceStubSupplement(); void ServiceStubSuppAppendBundles(); diff --git a/services/backup_sa/src/module_external/bms_adapter.cpp b/services/backup_sa/src/module_external/bms_adapter.cpp index 348ec99a3..db61d1369 100644 --- a/services/backup_sa/src/module_external/bms_adapter.cpp +++ b/services/backup_sa/src/module_external/bms_adapter.cpp @@ -645,4 +645,40 @@ std::vector BundleMgrAdapter::GetBundleInfosForInde HILOGI("End, bundleInfos size:%{public}zu", bundleInfos.size()); return bundleInfos; } + +int64_t BundleMgrAdapter::GetBundleDataSize(const std::string &bundleName, int32_t userId) +{ + return GetBundleStats(bundleName, userId); +} + +void BundleMgrAdapter::CreatBackupEnv(const std::vector &bundleNameList, int32_t userId) +{ + HILOGI("CreatBackupEnv start"); + auto bms = GetBundleManager(); + for (auto const &bundleNameTime : bundleNameList) { + auto bundleName = bundleNameTime.bundleName; + if (SAUtils::IsSABundleName(bundleName)) { + HILOGI("SA don't need creat env"); + continue; + } + AppExecFwk::BundleInfo installedBundle; + std::vector extensionInfos; + bool getBundleSuccess = GetCurBundleExtenionInfo(installedBundle, bundleName, extensionInfos, bms, userId); + if (!getBundleSuccess) { + HILOGE("Failed to get bundle info from bms, bundleName:%{public}s", bundleName.c_str()); + continue; + } + struct BJsonEntityCaps::BundleBackupConfigPara backupPara; + if (!GetBackupExtConfig(extensionInfos, backupPara)) { + HILOGE("No backup extension ability found, bundleName:%{public}s", bundleName.c_str()); + continue; + } + if (!CreateIPCInteractionFiles(userId, bundleName, bundleNameTime.lastIncrementalTime, backupPara.includes, + backupPara.excludes)) { + HILOGE("Create bundleInteraction dir failed, bundleName:%{public}s", bundleName.c_str()); + continue; + } + } + HILOGI("CreatBackupEnv end"); +} } // namespace OHOS::FileManagement::Backup diff --git a/services/backup_sa/src/module_ipc/service_incremental_reverse_proxy.cpp b/services/backup_sa/src/module_ipc/service_incremental_reverse_proxy.cpp index 39a525173..57e412c92 100644 --- a/services/backup_sa/src/module_ipc/service_incremental_reverse_proxy.cpp +++ b/services/backup_sa/src/module_ipc/service_incremental_reverse_proxy.cpp @@ -139,6 +139,24 @@ void ServiceReverseProxy::IncrementalBackupOnProcessInfo(std::string bundleName, } } +void ServiceReverseProxy::IncrementalBackupOnScanningInfo(std::string scannedInfo) +{ + BExcepUltils::BAssert(Remote(), BError::Codes::SDK_INVAL_ARG, "Remote is nullptr"); + MessageParcel data; + if (!data.WriteInterfaceToken(GetDescriptor()) || !data.WriteString(scannedInfo)) { + throw BError(BError::Codes::SA_BROKEN_IPC); + } + + MessageParcel reply; + MessageOption option; + if (int err = Remote()->SendRequest( + static_cast(IServiceReverseInterfaceCode::SERVICER_INCREMENTAL_BACKUP_ON_SCANNED_INFO), data, + reply, option); + err != ERR_OK) { + throw BError(BError::Codes::SA_BROKEN_IPC, to_string(err)); + } +} + void ServiceReverseProxy::IncrementalRestoreOnBundleStarted(int32_t errCode, string bundleName) { BExcepUltils::BAssert(Remote(), BError::Codes::SDK_INVAL_ARG, "Remote is nullptr"); diff --git a/services/backup_sa/src/module_ipc/service_reverse_proxy.cpp b/services/backup_sa/src/module_ipc/service_reverse_proxy.cpp index efe357b20..2d2dbab36 100644 --- a/services/backup_sa/src/module_ipc/service_reverse_proxy.cpp +++ b/services/backup_sa/src/module_ipc/service_reverse_proxy.cpp @@ -129,6 +129,24 @@ void ServiceReverseProxy::BackupOnProcessInfo(std::string bundleName, std::strin } } +void ServiceReverseProxy::BackupOnScanningInfo(std::string scannedInfo) +{ + BExcepUltils::BAssert(Remote(), BError::Codes::SDK_INVAL_ARG, "Remote is nullptr"); + MessageParcel data; + if (!data.WriteInterfaceToken(GetDescriptor()) || !data.WriteString(scannedInfo)) { + throw BError(BError::Codes::SA_BROKEN_IPC); + } + + MessageParcel reply; + MessageOption option; + if (int err = Remote()->SendRequest( + static_cast(IServiceReverseInterfaceCode::SERVICER_BACKUP_ON_SCANNED_INFO), data, + reply, option); + err != ERR_OK) { + throw BError(BError::Codes::SA_BROKEN_IPC, to_string(err)); + } +} + void ServiceReverseProxy::RestoreOnBundleStarted(int32_t errCode, string bundleName) { BExcepUltils::BAssert(Remote(), BError::Codes::SDK_INVAL_ARG, "Remote is nullptr"); diff --git a/services/backup_sa/src/module_ipc/service_stub.cpp b/services/backup_sa/src/module_ipc/service_stub.cpp index 287be8543..ae94248e9 100644 --- a/services/backup_sa/src/module_ipc/service_stub.cpp +++ b/services/backup_sa/src/module_ipc/service_stub.cpp @@ -36,6 +36,8 @@ const int INVALID_FD = -1; void ServiceStub::ServiceStubSupplement() { + opToInterfaceMap_[static_cast(IServiceInterfaceCode::SERVICE_CMD_GET_BACKUP_DATA_SIZE)] = + &ServiceStub::CmdGetBackupDataSize; opToInterfaceMap_[static_cast(IServiceInterfaceCode::SERVICE_CMD_UPDATE_TIMER)] = &ServiceStub::CmdUpdateTimer; opToInterfaceMap_[static_cast(IServiceInterfaceCode::SERVICE_CMD_UPDATE_SENDRATE)] = @@ -839,4 +841,18 @@ int32_t ServiceStub::CmdGetLocalCapabilitiesForBdInfos(MessageParcel &data, Mess } return BError(BError::Codes::OK); } + +int32_t ServiceStub::CmdGetBackupDataSize(MessageParcel &data, MessageParcel &reply) +{ + HILOGI("ServiceStub CmdGetBackupDataSize Begin."); + bool isPreciseScan = true; + isPreciseScan = data.ReadBool(); + vector bundleNameList; + if (!ReadParcelableVector(bundleNameList, data)) { + return BError(BError::Codes::SA_INVAL_ARG, "Failed to receive bundleNames"); + } + auto ret = GetBackupDataSize(isPreciseScan, bundleNameList); + HILOGI("ServiceStub GetBackupDataSize End ret = %{public}d", ret); + return ret; +} } // namespace OHOS::FileManagement::Backup diff --git a/services/backup_sa/src/module_ipc/sub_service.cpp b/services/backup_sa/src/module_ipc/sub_service.cpp index 9754c5f42..9677dea80 100644 --- a/services/backup_sa/src/module_ipc/sub_service.cpp +++ b/services/backup_sa/src/module_ipc/sub_service.cpp @@ -66,6 +66,11 @@ namespace OHOS::FileManagement::Backup { using namespace std; +namespace { +const int32_t WAIT_SCANNING_INFO_SEND_TIME = 5; +const int ERR_SIZE = -1; +} // namespace + vector Service::MakeDetailList(const vector &bundleNames) { vector bundleDetails {}; @@ -797,4 +802,235 @@ void Service::CallOnBundleEndByScenario(const std::string &bundleName, BackupRes session_->GetServiceReverseProxy()->IncrementalBackupOnBundleFinished(errCode, bundleName); } } + +ErrCode Service::GetBackupDataSize(bool isPreciseScan, vector bundleNameList) +{ + try { + HILOGI("start GetBackupDataSize"); + if (session_ == nullptr || onScanning_.load()) { + HILOGE("GetBackupDataSize error 1.session is nullptr 2.onScanning_ = %{public}d", onScanning_.load()); + return BError(BError::Codes::SA_INVAL_ARG); + } + session_->IncreaseSessionCnt(__PRETTY_FUNCTION__); + onScanning_.store(true); + ErrCode ret = VerifyCaller(); + if (ret != ERR_OK) { + session_->DecreaseSessionCnt(__PRETTY_FUNCTION__); + return BError(BError::Codes::SA_INVAL_ARG, "verify caller failed"); + } + BundleMgrAdapter::CreatBackupEnv(bundleNameList, GetUserIdDefault()); + CyclicSendScannedInfo(isPreciseScan, bundleNameList); + return BError(BError::Codes::OK); + } catch (...) { + session_->DecreaseSessionCnt(__PRETTY_FUNCTION__); + return BError(BError::Codes::SA_INVAL_ARG); + } +} + +void Service::CyclicSendScannedInfo(bool isPreciseScan, vector bundleNameList) +{ + auto task = [isPreciseScan {isPreciseScan}, bundleNameList {move(bundleNameList)}, + obj {wptr(this)}, session {session_}]() { + auto ptr = obj.promote(); + if (ptr == nullptr) { + HILOGE("ptr is nullptr"); + session->DecreaseSessionCnt(__PRETTY_FUNCTION__); + return; + } + size_t listSize = bundleNameList.size(); + HILOGI("need scanf num = %{public}zu", listSize); + string scanning; + size_t allScannedSize = 0; + ptr->GetDataSizeStepByStep(isPreciseScan, bundleNameList, scanning); + while (!ptr->isScannedEnd_.load()) { + std::unique_lock lock(ptr->getDataSizeLock_); + ptr->getDataSizeCon_.wait_for(lock, std::chrono::seconds(WAIT_SCANNING_INFO_SEND_TIME), + [ptr] { return ptr->isScannedEnd_.load(); }); + auto scannedSize = ptr->bundleDataSizeList_.size(); + allScannedSize += scannedSize; + HILOGI("ScannedSize = %{public}zu, allScannedSize = %{public}zu", scannedSize, allScannedSize); + if (!ptr->GetScanningInfo(obj, scannedSize, scanning)) { + ptr->SendScannedInfo("", session); + continue; + } + ptr->DeleteFromList(scannedSize); + ptr->SendScannedInfo(ptr->scannedInfo_, session); + } + ptr->isScannedEnd_.store(false); + session->DecreaseSessionCnt(__PRETTY_FUNCTION__); + }; + + callbackScannedInfoThreadPool_.AddTask([task, session {session_}]() { + try { + task(); + } catch (...) { + session->DecreaseSessionCnt(__PRETTY_FUNCTION__); + HILOGE("Failed to add task to thread pool"); + } + }); +} + +void Service::GetDataSizeStepByStep(bool isPreciseScan, vector bundleNameList, string &scanning) +{ + auto task = [isPreciseScan {isPreciseScan}, bundleNameList {move(bundleNameList)}, + &scanning, obj {wptr(this)}]() { + auto ptr = obj.promote(); + if (ptr == nullptr) { + HILOGE("ptr is nullptr"); + return; + } + if (!isPreciseScan) { + HILOGI("start GetPresumablySize"); + ptr->GetPresumablySize(bundleNameList, scanning); + } else { + HILOGI("start GetPrecisesSize"); + ptr->GetPrecisesSize(bundleNameList, scanning); + } + std::lock_guard lock(ptr->getDataSizeLock_); + ptr->isScannedEnd_.store(true); + ptr->getDataSizeCon_.notify_all(); + ptr->onScanning_.store(false); + }; + + getDataSizeThreadPool_.AddTask([task]() { + try { + task(); + } catch (...) { + HILOGE("Failed to add task to thread pool"); + } + }); +} + +void Service::GetPresumablySize(vector bundleNameList, string &scanning) +{ + int32_t userId = GetUserIdDefault(); + for (const auto &bundleData : bundleNameList) { + string name = bundleData.bundleName; + SetScanningInfo(scanning, name); + if (SAUtils::IsSABundleName(name)) { + WriteScannedInfoToList(name, 0, ERR_SIZE); + continue; + } + int64_t dataSize = BundleMgrAdapter::GetBundleDataSize(name, userId); + if (dataSize == 0) { + WriteScannedInfoToList(name, ERR_SIZE, ERR_SIZE); + continue; + } + WriteScannedInfoToList(name, dataSize, ERR_SIZE); + } + SetScanningInfo(scanning, ""); + HILOGI("GetPresumablySize end"); +} + +void Service::GetPrecisesSize(vector bundleNameList, string &scanning) +{ + for (const auto &bundleData : bundleNameList) { + vector bundleNames; + vector lastBackTimes; + string name = bundleData.bundleName; + SetScanningInfo(scanning, name); + BJsonUtil::BundleDetailInfo bundleDetail = BJsonUtil::ParseBundleNameIndexStr(name); + if (bundleDetail.bundleIndex > 0) { + std::string bundleNameIndex = "+clone-" + std::to_string(bundleDetail.bundleIndex) + "+" + + bundleDetail.bundleName; + bundleNames.push_back(bundleNameIndex); + } else { + bundleNames.push_back(name); + } + int64_t lastTime = bundleData.lastIncrementalTime; + lastBackTimes.push_back(lastTime); + vector pkgFileSizes {}; + vector incPkgFileSizes {}; + int32_t err = StorageMgrAdapter::GetBundleStatsForIncrease(GetUserIdDefault(), bundleNames, lastBackTimes, + pkgFileSizes, incPkgFileSizes); + if (err != 0) { + HILOGE("filed to get datasize from storage, err =%{public}d, bundlename = %{public}s, index = %{public}d", + err, name.c_str(), bundleDetail.bundleIndex); + WriteScannedInfoToList(name, ERR_SIZE, ERR_SIZE); + continue; + } + if (lastTime == 0 && pkgFileSizes.size() > 0) { + WriteScannedInfoToList(name, pkgFileSizes[0], ERR_SIZE); + } else if (pkgFileSizes.size() > 0 && incPkgFileSizes.size() > 0) { + WriteScannedInfoToList(name, pkgFileSizes[0], incPkgFileSizes[0]); + } else { + HILOGE ("pkgFileSizes or incPkgFileSizes error, %{public}zu, %{public}zu", + pkgFileSizes.size(), incPkgFileSizes.size()); + } + } + SetScanningInfo(scanning, ""); + HILOGI("GetPrecisesSize end"); +} + +void Service::WriteToList(BJsonUtil::BundleDataSize bundleDataSize) +{ + std::lock_guard lock(scannedListLock_); + bundleDataSizeList_.push_back(bundleDataSize); +} + +void Service::DeleteFromList(size_t scannedSize) +{ + std::lock_guard lock(scannedListLock_); + bundleDataSizeList_.erase(bundleDataSizeList_.begin(), bundleDataSizeList_.begin() + scannedSize); +} + +bool Service::GetScanningInfo(wptr obj, size_t scannedSize, string &scanning) +{ + auto ptr = obj.promote(); + if (ptr == nullptr) { + HILOGE("ptr is nullptr"); + return false; + } + std::lock_guard lock(scannedListLock_); + if (!BJsonUtil::WriteToStr(ptr->bundleDataSizeList_, scannedSize, scanning, ptr->scannedInfo_)) { + return false; + } + return true; +} + +void Service::SetScanningInfo(string &scanning, string name) +{ + std::lock_guard lock(scannedListLock_); + scanning = name; +} + +void Service::WriteScannedInfoToList(const string &bundleName, int64_t dataSize, int64_t incDataSize) +{ + BJsonUtil::BundleDataSize bundleDataSize; + bundleDataSize.bundleName = bundleName; + bundleDataSize.dataSize = dataSize; + bundleDataSize.incDataSize = incDataSize; + HILOGI("name = %{public}s, size = %{public}" PRId64 ", incSize = %{public}" PRId64 "", + bundleName.c_str(), dataSize, incDataSize); + WriteToList(bundleDataSize); +} + +void Service::SendScannedInfo(const string&scannendInfos, sptr session) +{ + if (scannendInfos.empty()) { + HILOGE("write json failed , info is null"); + } + if (session == nullptr) { + HILOGE("session is nullptr"); + return; + } + HILOGI("start send scanned info"); + auto task = [session {session}, scannendInfos {scannendInfos}]() { + if (session->GetScenario() == IServiceReverse::Scenario::BACKUP && session->GetIsIncrementalBackup()) { + HILOGI("this is incremental backup sending info"); + session->GetServiceReverseProxy()->IncrementalBackupOnScanningInfo(scannendInfos); + return; + } + HILOGI("this is full backup sending info"); + session->GetServiceReverseProxy()->BackupOnScanningInfo(scannendInfos); + }; + + sendScannendResultThreadPool_.AddTask([task]() { + try { + task(); + } catch (...) { + HILOGE("Failed to add task to thread pool"); + } + }); +} } \ No newline at end of file diff --git a/tests/mock/backup_kit_inner/service_proxy_mock.cpp b/tests/mock/backup_kit_inner/service_proxy_mock.cpp index f9ba51c68..d7ce74b5c 100644 --- a/tests/mock/backup_kit_inner/service_proxy_mock.cpp +++ b/tests/mock/backup_kit_inner/service_proxy_mock.cpp @@ -282,4 +282,9 @@ UniqueFd ServiceProxy::GetLocalCapabilitiesForBundleInfos() { return UniqueFd(-1); } + +ErrCode ServiceProxy::GetBackupDataSize(bool isPreciseScan, vector bundleNameList) +{ + return BError(BError::Codes::OK); +} } // namespace OHOS::FileManagement::Backup \ No newline at end of file diff --git a/tests/mock/module_external/bms_adapter_mock.cpp b/tests/mock/module_external/bms_adapter_mock.cpp index 38416eb27..0b6954c1d 100644 --- a/tests/mock/module_external/bms_adapter_mock.cpp +++ b/tests/mock/module_external/bms_adapter_mock.cpp @@ -110,4 +110,11 @@ std::vector BundleMgrAdapter::GetBundleInfosForInde "com.example.app2backup"}); return bundleInfos; } + +int64_t BundleMgrAdapter::GetBundleDataSize(const std::string &bundleName, int32_t userId) +{ + return 0; +} + +void BundleMgrAdapter::CreatBackupEnv(const std::vector &bundleNameList, int32_t userId) {} } // namespace OHOS::FileManagement::Backup diff --git a/tests/mock/module_external/include/bms_adapter_mock.h b/tests/mock/module_external/include/bms_adapter_mock.h index c35501e1e..364172921 100644 --- a/tests/mock/module_external/include/bms_adapter_mock.h +++ b/tests/mock/module_external/include/bms_adapter_mock.h @@ -38,6 +38,8 @@ public: virtual std::vector GetFullBundleInfos(int32_t) = 0; virtual std::vector GetBundleInfosForLocalCapabilities(int32_t) = 0; virtual std::vector GetBundleInfosForIndex(const vector&, int32_t) = 0; + virtual int64_t GetBundleDataSize(const std::string&, int32_t) = 0; + virtual void CreatBackupEnv(const std::vector&, int32_t) = 0; public: BBundleMgrAdapter() = default; virtual ~BBundleMgrAdapter() = default; @@ -63,6 +65,8 @@ public: MOCK_METHOD((std::vector), GetFullBundleInfos, (int32_t)); MOCK_METHOD((std::vector), GetBundleInfosForLocalCapabilities, (int32_t)); MOCK_METHOD((std::vector), GetBundleInfosForIndex, (const vector&, int32_t)); + MOCK_METHOD(int64_t, GetBundleDataSize, (const std::string&, int32_t)); + MOCK_METHOD(void, CreatBackupEnv, (const std::vector&, int32_t)); }; } // namespace OHOS::FileManagement::Backup #endif // OHOS_FILEMGMT_BACKUP_BMS_ADAPTER_MOCK_H diff --git a/tests/mock/module_external/src/bms_adapter_mock.cpp b/tests/mock/module_external/src/bms_adapter_mock.cpp index d82e580dd..e7dd3d0af 100644 --- a/tests/mock/module_external/src/bms_adapter_mock.cpp +++ b/tests/mock/module_external/src/bms_adapter_mock.cpp @@ -81,4 +81,12 @@ std::vector BundleMgrAdapter::GetBundleInfosForInde { return BBundleMgrAdapter::bms->GetBundleInfosForIndex(bundleNames, userId); } + +int64_t BundleMgrAdapter::GetBundleDataSize(const std::string &bundleName, int32_t userId) +{ + return BBundleMgrAdapter::bms->GetBundleDataSize(bundleName, userId); +} + +void BundleMgrAdapter::CreatBackupEnv(const std::vector &bundleNameList, int32_t userId) {} + } // namespace OHOS::FileManagement::Backup \ No newline at end of file diff --git a/tests/mock/module_ipc/include/service_reverse_proxy_mock.h b/tests/mock/module_ipc/include/service_reverse_proxy_mock.h index 8a74af4bd..fc5c50fe8 100644 --- a/tests/mock/module_ipc/include/service_reverse_proxy_mock.h +++ b/tests/mock/module_ipc/include/service_reverse_proxy_mock.h @@ -31,24 +31,30 @@ public: MOCK_METHOD(void, BackupOnBundleFinished, (int32_t, std::string)); MOCK_METHOD(void, BackupOnAllBundlesFinished, (int32_t)); MOCK_METHOD(void, BackupOnProcessInfo, (std::string, std::string)); + MOCK_METHOD(void, BackupOnScanningInfo, (std::string)); + MOCK_METHOD(void, RestoreOnBundleStarted, (int32_t, std::string)); MOCK_METHOD(void, RestoreOnBundleFinished, (int32_t, std::string)); MOCK_METHOD(void, RestoreOnAllBundlesFinished, (int32_t)); MOCK_METHOD(void, RestoreOnFileReady, (std::string, std::string, int, int32_t)); MOCK_METHOD(void, RestoreOnResultReport, (std::string, std::string, ErrCode)); MOCK_METHOD(void, RestoreOnProcessInfo, (std::string, std::string)); + MOCK_METHOD(void, IncrementalBackupOnFileReady, (std::string, std::string, int, int, int32_t)); MOCK_METHOD(void, IncrementalBackupOnBundleStarted, (int32_t, std::string)); MOCK_METHOD(void, IncrementalBackupOnResultReport, (std::string, std::string)); MOCK_METHOD(void, IncrementalBackupOnBundleFinished, (int32_t, std::string)); MOCK_METHOD(void, IncrementalBackupOnAllBundlesFinished, (int32_t)); MOCK_METHOD(void, IncrementalBackupOnProcessInfo, (std::string, std::string)); + MOCK_METHOD(void, IncrementalBackupOnScanningInfo, (std::string)); + MOCK_METHOD(void, IncrementalRestoreOnBundleStarted, (int32_t, std::string)); MOCK_METHOD(void, IncrementalRestoreOnBundleFinished, (int32_t, std::string)); MOCK_METHOD(void, IncrementalRestoreOnAllBundlesFinished, (int32_t)); MOCK_METHOD(void, IncrementalRestoreOnFileReady, (std::string, std::string, int, int, int32_t)); MOCK_METHOD(void, IncrementalRestoreOnResultReport, (std::string, std::string, ErrCode));; MOCK_METHOD(void, IncrementalRestoreOnProcessInfo, (std::string, std::string)); + public: ServiceReverseProxyMock() : IRemoteProxy(nullptr) {} virtual ~ServiceReverseProxyMock() = default; diff --git a/tests/mock/module_ipc/include/service_stub_mock.h b/tests/mock/module_ipc/include/service_stub_mock.h index 1892a2480..27d151755 100644 --- a/tests/mock/module_ipc/include/service_stub_mock.h +++ b/tests/mock/module_ipc/include/service_stub_mock.h @@ -54,6 +54,7 @@ public: virtual int32_t CmdUpdateSendRate(MessageParcel&, MessageParcel&) = 0; virtual int32_t CmdStopExtTimer(MessageParcel&, MessageParcel&) = 0; virtual int32_t CmdRefreshDataSize(MessageParcel&, MessageParcel&) = 0; + virtual int32_t CmdGetBackupDataSize(MessageParcel&, MessageParcel&) = 0; virtual void ServiceStubSupplement() = 0; virtual void ServiceStubSuppAppendBundles() = 0; @@ -98,6 +99,7 @@ public: MOCK_METHOD(int32_t, CmdUpdateSendRate, (MessageParcel&, MessageParcel&)); MOCK_METHOD(int32_t, CmdStopExtTimer, (MessageParcel&, MessageParcel&)); MOCK_METHOD(int32_t, CmdRefreshDataSize, (MessageParcel&, MessageParcel&)); + MOCK_METHOD(int32_t, CmdGetBackupDataSize, (MessageParcel&, MessageParcel&)); MOCK_METHOD(void, ServiceStubSupplement, ()); MOCK_METHOD(void, ServiceStubSuppAppendBundles, ()); }; diff --git a/tests/mock/module_ipc/service_mock.cpp b/tests/mock/module_ipc/service_mock.cpp index 309c0bfdb..13d6d8fec 100644 --- a/tests/mock/module_ipc/service_mock.cpp +++ b/tests/mock/module_ipc/service_mock.cpp @@ -365,4 +365,34 @@ void SetUserIdAndRestoreType(RestoreTypeEnum restoreType, int32_t userId) {} void Service::CallOnBundleEndByScenario(const std::string &bundleName, BackupRestoreScenario scenario, ErrCode errCode) {} + +void Service::SetUserIdAndRestoreType(RestoreTypeEnum restoreType, int32_t userId) {} + +ErrCode Service::GetBackupDataSize(bool isPreciseScan, vector bundleNameList) +{ + return BError(BError::Codes::OK); +} + +void Service::GetDataSizeStepByStep(bool isPreciseScan, vector bundleNameList, string &scanning) {} + +void Service::GetPresumablySize(vector bundleNameList, string &scanning) {} + +void Service::GetPrecisesSize(vector bundleNameList, string &scanning) {} + +void Service::WriteToList(BJsonUtil::BundleDataSize bundleDataSize) {} + +void Service::DeleteFromList(size_t scannedSize) {} + +void Service::WriteScannedInfoToList(const string &bundleName, int64_t dataSize, int64_t incDataSize) {} + +void Service::SendScannedInfo(const string&scannendInfos, sptr session) {} + +void Service::CyclicSendScannedInfo(bool isPreciseScan, vector bundleNameList) {} + +bool Service::GetScanningInfo(wptr obj, size_t scannedSize, string &scanning) +{ + return true; +} + +void Service::SetScanningInfo(string &scanning, string name) {} } // namespace OHOS::FileManagement::Backup diff --git a/tests/mock/module_ipc/service_reverse_proxy_mock.cpp b/tests/mock/module_ipc/service_reverse_proxy_mock.cpp index 1b224076d..ee7e924e0 100644 --- a/tests/mock/module_ipc/service_reverse_proxy_mock.cpp +++ b/tests/mock/module_ipc/service_reverse_proxy_mock.cpp @@ -32,6 +32,8 @@ void ServiceReverseProxy::BackupOnAllBundlesFinished(int32_t errCode) {} void ServiceReverseProxy::BackupOnProcessInfo(std::string bundleName, std::string processInfo) {} +void ServiceReverseProxy::BackupOnScanningInfo(std::string scannedInfo) {} + void ServiceReverseProxy::RestoreOnBundleStarted(int32_t errCode, string bundleName) {} void ServiceReverseProxy::RestoreOnBundleFinished(int32_t errCode, string bundleName) {} @@ -57,6 +59,8 @@ void ServiceReverseProxy::IncrementalBackupOnAllBundlesFinished(int32_t errCode) void ServiceReverseProxy::IncrementalBackupOnProcessInfo(std::string bundleName, std::string processInfo) {} +void ServiceReverseProxy::IncrementalBackupOnScanningInfo(std::string scannedInfo) {} + void ServiceReverseProxy::IncrementalRestoreOnBundleStarted(int32_t errCode, string bundleName) {} void ServiceReverseProxy::IncrementalRestoreOnBundleFinished(int32_t errCode, string bundleName) {} diff --git a/tests/mock/module_ipc/service_stub_mock.cpp b/tests/mock/module_ipc/service_stub_mock.cpp index cf35e49cb..8a3c066a8 100644 --- a/tests/mock/module_ipc/service_stub_mock.cpp +++ b/tests/mock/module_ipc/service_stub_mock.cpp @@ -96,6 +96,8 @@ void ServiceStub::ServiceStubSupplement() opToInterfaceMap_[static_cast( IServiceInterfaceCode::SERVICE_CMD_GET_LOCAL_CAPABILITIES_FOR_BUNDLE_INFOS)] = &ServiceStub::CmdGetLocalCapabilitiesForBdInfos; + opToInterfaceMap_[static_cast(IServiceInterfaceCode::SERVICE_CMD_GET_BACKUP_DATA_SIZE)] = + &ServiceStub::CmdGetBackupDataSize; } int32_t ServiceStub::OnRemoteRequest(uint32_t code, MessageParcel &data, MessageParcel &reply, MessageOption &option) @@ -386,4 +388,9 @@ int32_t ServiceStub::CmdGetLocalCapabilitiesForBdInfos(MessageParcel &data, Mess { return BError(BError::Codes::OK); } + +int32_t ServiceStub::CmdGetBackupDataSize(MessageParcel &data, MessageParcel &reply) +{ + return BError(BError::Codes::OK); +} } // namespace OHOS::FileManagement::Backup diff --git a/tests/mock/module_ipc/src/service_stub_mock.cpp b/tests/mock/module_ipc/src/service_stub_mock.cpp index 973ff217d..2d46ff3ea 100644 --- a/tests/mock/module_ipc/src/service_stub_mock.cpp +++ b/tests/mock/module_ipc/src/service_stub_mock.cpp @@ -176,4 +176,9 @@ int32_t ServiceStub::CmdGetLocalCapabilitiesForBdInfos(MessageParcel &data, Mess { return BServiceStub::stub->CmdGetLocalCapabilitiesForBdInfos(data, reply); } + +int32_t ServiceStub::CmdGetBackupDataSize(MessageParcel &data, MessageParcel &reply) +{ + return BServiceStub::stub->CmdGetBackupDataSize(data, reply); +} } // namespace OHOS::FileManagement::Backup diff --git a/tests/mock/utils_mock/include/b_jsonutil_mock.h b/tests/mock/utils_mock/include/b_jsonutil_mock.h index e0e0ad7c2..5a81d1700 100644 --- a/tests/mock/utils_mock/include/b_jsonutil_mock.h +++ b/tests/mock/utils_mock/include/b_jsonutil_mock.h @@ -39,6 +39,7 @@ public: virtual bool BuildBundleInfoJson(int32_t, std::string&) = 0; virtual bool HasUnicastInfo(std::string&) = 0; virtual std::string BuildInitSessionErrInfo(int32_t, std::string, std::string) = 0; + virtual bool WriteToStr(std::vector&, size_t, std::string, std::string&) = 0; public: BBJsonUtil() = default; virtual ~BBJsonUtil() = default; @@ -64,6 +65,7 @@ public: MOCK_METHOD(bool, BuildBundleInfoJson, (int32_t, std::string&)); MOCK_METHOD(bool, HasUnicastInfo, (std::string&)); MOCK_METHOD(std::string, BuildInitSessionErrInfo, (int32_t, std::string, std::string)); + MOCK_METHOD(bool, WriteToStr, (std::vector&, size_t, std::string, std::string&)); }; } // namespace OHOS::FileManagement::Backup #endif // OHOS_FILEMGMT_BACKUP_B_JSONUTIL_MOCK_MOCK_H diff --git a/tests/unittests/backup_api/backup_impl/include/i_service_mock.h b/tests/unittests/backup_api/backup_impl/include/i_service_mock.h index 0236b9a36..d5371dae2 100644 --- a/tests/unittests/backup_api/backup_impl/include/i_service_mock.h +++ b/tests/unittests/backup_api/backup_impl/include/i_service_mock.h @@ -262,6 +262,11 @@ public: { return BError(BError::Codes::OK); } + + ErrCode GetBackupDataSize(bool isPreciseScan, std::vector bundleNameList) + { + return BError(BError::Codes::OK); + } }; } // namespace OHOS::FileManagement::Backup #endif // MOCK_I_SERVICE_MOCK_H \ No newline at end of file diff --git a/tests/unittests/backup_api/backup_impl/include/service_reverse_mock.h b/tests/unittests/backup_api/backup_impl/include/service_reverse_mock.h index 7b1bf2f9b..cd066641e 100644 --- a/tests/unittests/backup_api/backup_impl/include/service_reverse_mock.h +++ b/tests/unittests/backup_api/backup_impl/include/service_reverse_mock.h @@ -42,6 +42,7 @@ public: void BackupOnBundleFinished(int32_t errCode, std::string bundleName) override {} void BackupOnAllBundlesFinished(int32_t errCode) override {} void BackupOnProcessInfo(std::string bundleName, std::string processInfo) override {} + void BackupOnScanningInfo(std::string scannedInfo) override {} void RestoreOnBundleStarted(int32_t errCode, std::string bundleName) override {} void RestoreOnBundleFinished(int32_t errCode, std::string bundleName) override {} @@ -57,6 +58,7 @@ public: void IncrementalBackupOnBundleFinished(int32_t errCode, std::string bundleName) override {} void IncrementalBackupOnAllBundlesFinished(int32_t errCode) override {} void IncrementalBackupOnProcessInfo(std::string bundleName, std::string processInfo) override {} + void IncrementalBackupOnScanningInfo(std::string scannedInfo) override {} void IncrementalRestoreOnBundleStarted(int32_t errCode, std::string bundleName) override {} void IncrementalRestoreOnBundleFinished(int32_t errCode, std::string bundleName) override {} diff --git a/tests/unittests/backup_api/backup_impl/service_reverse_stub_test.cpp b/tests/unittests/backup_api/backup_impl/service_reverse_stub_test.cpp index d5c75557c..7c2284f6b 100644 --- a/tests/unittests/backup_api/backup_impl/service_reverse_stub_test.cpp +++ b/tests/unittests/backup_api/backup_impl/service_reverse_stub_test.cpp @@ -46,12 +46,15 @@ public: MOCK_METHOD2(BackupOnBundleFinished, void(int32_t errCode, string bundleName)); MOCK_METHOD1(BackupOnAllBundlesFinished, void(int32_t errCode)); MOCK_METHOD2(BackupOnProcessInfo, void(std::string bundleName, std::string processInfo)); + MOCK_METHOD1(BackupOnScanningInfo, void(std::string scannedInfo)); + MOCK_METHOD2(RestoreOnBundleStarted, void(int32_t errCode, std::string bundleName)); MOCK_METHOD2(RestoreOnBundleFinished, void(int32_t errCode, string bundleName)); MOCK_METHOD1(RestoreOnAllBundlesFinished, void(int32_t errCode)); MOCK_METHOD4(RestoreOnFileReady, void(string bundleName, string fileName, int fd, int32_t errCode)); MOCK_METHOD3(RestoreOnResultReport, void(string result, string bundleName, ErrCode errCode)); MOCK_METHOD2(RestoreOnProcessInfo, void(std::string bundleName, std::string processInfo)); + MOCK_METHOD5(IncrementalBackupOnFileReady, void(string bundleName, string fileName, int fd, int manifestFd, int32_t errCode)); MOCK_METHOD2(IncrementalBackupOnBundleStarted, void(int32_t errCode, string bundleName)); @@ -59,6 +62,8 @@ public: MOCK_METHOD2(IncrementalBackupOnBundleFinished, void(int32_t errCode, string bundleName)); MOCK_METHOD1(IncrementalBackupOnAllBundlesFinished, void(int32_t errCode)); MOCK_METHOD2(IncrementalBackupOnProcessInfo, void(std::string bundleName, std::string processInfo)); + MOCK_METHOD1(IncrementalBackupOnScanningInfo, void(std::string scannedInfo)); + MOCK_METHOD2(IncrementalRestoreOnBundleStarted, void(int32_t errCode, std::string bundleName)); MOCK_METHOD2(IncrementalRestoreOnBundleFinished, void(int32_t errCode, string bundleName)); MOCK_METHOD1(IncrementalRestoreOnAllBundlesFinished, void(int32_t errCode)); diff --git a/tests/unittests/backup_sa/module_ipc/service_incremental_test.cpp b/tests/unittests/backup_sa/module_ipc/service_incremental_test.cpp index a46f15816..833422e4e 100644 --- a/tests/unittests/backup_sa/module_ipc/service_incremental_test.cpp +++ b/tests/unittests/backup_sa/module_ipc/service_incremental_test.cpp @@ -316,6 +316,11 @@ UniqueFd Service::GetLocalCapabilitiesForBundleInfos() { return UniqueFd(-1); } + +ErrCode Service::GetBackupDataSize(bool isPreciseScan, vector bundleNameList) +{ + return BError(BError::Codes::OK); +} } // namespace OHOS::FileManagement::Backup namespace OHOS::FileManagement::Backup { diff --git a/tests/unittests/backup_sa/module_ipc/service_stub_test.cpp b/tests/unittests/backup_sa/module_ipc/service_stub_test.cpp index 1cfc44a4c..c63b4b11f 100644 --- a/tests/unittests/backup_sa/module_ipc/service_stub_test.cpp +++ b/tests/unittests/backup_sa/module_ipc/service_stub_test.cpp @@ -91,6 +91,7 @@ public: MOCK_METHOD1(RefreshDataSize, ErrCode(int64_t totalsize)); MOCK_METHOD3(UpdateSendRate, ErrCode(std::string &bundleName, int32_t sendRate, bool &result)); MOCK_METHOD2(ReportAppProcessInfo, ErrCode(const std::string processInfo, BackupRestoreScenario sennario)); + MOCK_METHOD2(GetBackupDataSize, ErrCode(bool isPreciseScan, vector bundleNameList)); }; class ServiceStubTest : public testing::Test { diff --git a/tests/unittests/backup_sa/session/service_proxy_mock.cpp b/tests/unittests/backup_sa/session/service_proxy_mock.cpp index 17eca994e..41cce333d 100644 --- a/tests/unittests/backup_sa/session/service_proxy_mock.cpp +++ b/tests/unittests/backup_sa/session/service_proxy_mock.cpp @@ -233,4 +233,9 @@ UniqueFd ServiceProxy::GetLocalCapabilitiesForBundleInfos() { return UniqueFd(-1); } + +ErrCode ServiceProxy::GetBackupDataSize(bool isPreciseScan, vector bundleNameList) +{ + return BError(BError::Codes::OK); +} } // namespace OHOS::FileManagement::Backup \ No newline at end of file diff --git a/tests/unittests/backup_sa/session/service_proxy_mock.h b/tests/unittests/backup_sa/session/service_proxy_mock.h index 1c842138c..b734c8dac 100644 --- a/tests/unittests/backup_sa/session/service_proxy_mock.h +++ b/tests/unittests/backup_sa/session/service_proxy_mock.h @@ -67,6 +67,7 @@ public: MOCK_METHOD0(GetAppLocalListAndDoIncrementalBackup, ErrCode()); MOCK_METHOD1(StopExtTimer, ErrCode(bool &isExtStop)); MOCK_METHOD1(RefreshDataSize, ErrCode(int64_t totalsize)); + MOCK_METHOD2(GetBackupDataSize, ErrCode(bool isPreciseScan, std::vector bundleNameList)); }; } // End of namespace OHOS::FileManagement::Backup #endif // TEST_UNITTEST_SERVICE_PROXY_MOCK_H diff --git a/utils/include/b_jsonutil/b_jsonutil.h b/utils/include/b_jsonutil/b_jsonutil.h index 22bf80506..686f146fb 100644 --- a/utils/include/b_jsonutil/b_jsonutil.h +++ b/utils/include/b_jsonutil/b_jsonutil.h @@ -30,6 +30,12 @@ public: int32_t userId; }BundleDetailInfo; + typedef struct BundleDataSize { + std::string bundleName; + int64_t dataSize = -1; + int64_t incDataSize = -1; + }BundleDataSize; + /** * @brief 带有拼接字符的bundleName按照拼接字符进行分割 * @@ -179,6 +185,21 @@ public: * @return 拼接结果 */ static std::string BuildInitSessionErrInfo(int32_t userId, std::string callerName, std::string activeTime); + + /** + * @brief 将已经扫描的结果转换成json串 + * + * @param bundleDataList 存储扫描结果的结构体列表 + * @param listSize 当前需要返回的数量 + * @param scanning 当前正在扫描的包名 + * @param jsonStr 需要返回的结果 + * + * @return 是否成功 + */ + static bool WriteToStr(std::vector &bundleDataList, + size_t listSize, + std::string scanning, + std::string &jsonStr); }; } // namespace OHOS::FileManagement::Backup diff --git a/utils/src/b_jsonutil/b_jsonutil.cpp b/utils/src/b_jsonutil/b_jsonutil.cpp index 9c31f4f9a..bc3bebd9b 100644 --- a/utils/src/b_jsonutil/b_jsonutil.cpp +++ b/utils/src/b_jsonutil/b_jsonutil.cpp @@ -496,4 +496,47 @@ std::string BJsonUtil::BuildInitSessionErrInfo(int32_t userId, std::string calle cJSON_free(jsonStr); return errMsg; } + +bool BJsonUtil::WriteToStr(std::vector &bundleDataList, + size_t listSize, + std::string scanning, + std::string &jsonStr) +{ + cJSON *root = cJSON_CreateObject(); + if (root == nullptr) { + HILOGE("CreateObject failed"); + return false; + } + cJSON *scannedArray = cJSON_CreateArray(); + if (scannedArray == nullptr) { + HILOGE("CreateArray failed"); + cJSON_Delete(root); + return false; + } + cJSON_AddItemToObject(root, "scaned", scannedArray); + for (size_t i = 0; i < listSize; i++) { + cJSON *item = cJSON_CreateObject(); + if (item == nullptr) { + HILOGE("cJSON_CreateObject failed"); + continue; + } + cJSON_AddStringToObject(item, "bundleName", bundleDataList[i].bundleName.c_str()); + cJSON_AddNumberToObject(item, "dataSize", bundleDataList[i].dataSize); + cJSON_AddNumberToObject(item, "incDataSize", bundleDataList[i].incDataSize); + cJSON_AddItemToArray(scannedArray, item); + } + cJSON_AddStringToObject(root, "scanning", scanning.c_str()); + HILOGI("end to add item"); + char *jsonString = cJSON_Print(root); + if (jsonString == nullptr) { + HILOGE("cJSON_Print failed"); + cJSON_Delete(root); + return false; + } + jsonStr = string(jsonString); + cJSON_Delete(root); + free(jsonString); + HILOGI("write json str ok, scanned size is %{public}zu", listSize); + return true; +} } \ No newline at end of file -- Gitee