diff --git a/frameworks/native/backup_kit_inner/include/service_reverse.h b/frameworks/native/backup_kit_inner/include/service_reverse.h index 3ecb58eaba5dd9964310ca15013e99b5ab85b291..c196689736f4258a804428e66463d419b2727ea3 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 0384c01307b7dc005646472fa9105d499dab1525..53a4964aab2745439c95c63b2b0c4d823a3c0d77 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 8bae936bfc25be782327b18eae7e980033485af5..97de333ab911e4f59baa6eaa29139c5a469b73c6 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 e29c0324bb302f212e2073c1ee82cb30e72bbe6a..08e08533180e3c3367d5d9584a58b2926143084d 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 ba1e761c5fd39867a97fe704e0efbfacb2b9d283..81f6ed9e691f3bd1b1624906ed581abda4933550 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 2d974d1ddb1830a86e7390115ef863da0fa63f6b..187f69ef7dc5926387ecf6b1b3e9d49ba57941a9 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 6328cb70ea63730224ee61a943a8dba13482ed20..100a0dd09d4f7ef62b1b06b943ee4baa4b93fb83 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 8f970cab4fa55ba8f94401d47d6efc36a92f2a52..2fae0a24aa3980a95bbdb7700849d9f10f8720ee 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 ab644a7a91f78013c62e1d8ef68ad741e96d25f3..934cb55932ecd6126b7085ffc6841d1d4097775c 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 ff25e976960a9b1f3e25a1d8d6d38aac8530fa2e..0fbcb4dc26fd04246e0c79551af32dcc6da08726 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 f087a1b03513a7e9b51e8ba0148f2988ac3b5a7a..0108a3437f29762800d384aa2c02880987a1ba1a 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 37be6bfa20128a303e1b4822754624b38e6a503c..ba99705fefbd6f987f5bf405f0f4cc43ad11a6aa 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 52311dde514d0a45fab11942877f2722f8c9cb1c..4ca5a7621f9e4266d5d2df815c80818543d8fe06 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 5d991d6fbd88212b1989695ad6fe100a586f0441..cd06fa1d21beae4a7313b51616f109521339e66f 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 ec0a21c995dcb30c84784606be28b84acda851db..4302e07b8489bd2dd9e0f52468d2357216100306 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 5fb4dfb18fd0464b2bd5d3d442d12f722116611a..16db36cefd384d774767f1f0c00f6146f3a86899 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 7f395fdfd8d96ffbb72196bc2d2527ed273c8ccb..d7430cb197b9ea778bffbbca4c805d1ef086ec80 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 0000000000000000000000000000000000000000..ed07b7f8ff8917886faa4835f222aef3b70d9a43 --- /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 0000000000000000000000000000000000000000..b3856dddbe639cadca56661354eb98dbed82f655 --- /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 d044890ab38ba008483704c8bb351ad2322e8366..e4a1ef547650f74bae42049fabf77f0ec92cb097 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 54511d2f0c149205f7ffe58dc89b32aacf74e914..c8c256879bd5588ecb61977c30f941d5634faf54 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 49dafdff5a3e29d52f277340eeb47fbb3ff73451..5fc20d610966df10727baef4b0d19cb89d5df590 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 28f3d100c8a1a0950a2c35d78b635118a9163716..ae958687bdee7d271ecf1d06049027a080ee81fa 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 1464797e16bf6e41eac1b632ce1af2ee1e80a7c6..d2d5ba4758873d32992445c3a038390630f4f1e9 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 651b6279a67ce8ab49f24155815092be4f7f6045..72fd55d180718a2afc07da53f1a1d104cf07494e 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 3d2cf16ba8a046cad39ca4377ea2c21a571d8e39..5665c5b3920750089039dd1289a7d9fad2126483 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 3e6667d8d2164de1810494a428131faabc668b52..7578aca3653b3d4065b9a1a5517a2c70076251b2 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 79bcb0860a804f0f303b78c56064e1e02306f6c9..d4484365a6e431cbb250803b347ae33a6bdc3c33 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 348ec99a30a172d1f08f816b5ff1a81cf54caede..db61d1369df9f603bb34ee63e919d8b4d3da22b3 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 39a5251735fa091aae44b67af2269334bac5f19a..57e412c92c862ca7f41048a2ec2a0d82b570f0c4 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 efe357b202253a3788f67a905d1f49d1a625108d..2d2dbab3691e26e870e2a75fcc33bd267fb89de2 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 287be85435ceb5e46acee6508d9ee3ee3221e787..ae94248e9f0bbc49318d2c507580f0ea5e9d22a9 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 9754c5f42635b2c5716b9baa31afda1e663c9588..9677dea80b54e46d1473efbb62f6bdfc4ada71ad 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 f9ba51c686795f385c257e6f6ef5ed7aa4f9d09f..d7ce74b5c4169dc138674b1f4572b02206f6ab6e 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 38416eb278302c20eae5cb02dfad8cd429d4e8fb..0b6954c1dbce00a5742732723c49c56fbdca4cdf 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 c35501e1e9eed0f003b425dfd00c2b11be9ee783..364172921d50e5829f04ebea19229e197a27127c 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 d82e580ddb66ece2981e5c3d5fdec45e775bf4ca..e7dd3d0aff01580913c143c88673fde7ce6cec4a 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 8a74af4bd13a2c7e23aa36fc0d242d850fbc3c8b..fc5c50fe80f927ef63a20e7837c4422cbcf6a078 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 1892a24800bea69c6006447fc00445f00b845db2..27d151755e1798302e921b7bf8460c8bd7bf493c 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 309c0bfdb666341f0183ba631442137ecd247901..13d6d8fec6102105b0fa1e009118450240be9c0f 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 1b224076d31f04363b8035c384aa14f4a4214132..ee7e924e040e6393b37e09aa80f5535726eec329 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 cf35e49cb1820ee271211a2393480cf065e83e24..8a3c066a8b4c34d66e4f038642daf42a78cb8653 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 973ff217d9ca90ba4b49fbf79d4a19f960a92a72..2d46ff3eab471707a310fd48531297b39c91d5c5 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 e0e0ad7c231b7a56a57386988ed95e68b6146e4c..5a81d17006117cf73a2a5bf804af3839a6104530 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 0236b9a3673f9555889f26fe9ed5aa83513513ec..d5371dae2b9a0f8821eb41dd5674d82052639d4f 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 7b1bf2f9b96749795245ae35d3dbf962146f7f45..cd066641e8f0115a4f5af966287ad109cc3ef157 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 d5c75557cd2fa4b3e2140081a7e65b87be28b14b..7c2284f6bf33b9c9b602d1cda4e592fc641fb8a1 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 a46f15816e97c41260db7b2c6b6fdfa7cbed83fc..833422e4ebb0d5dee7fa57851714eda00ffa3e34 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 1cfc44a4c725735dd155c55ba8aa8576e089c2fa..c63b4b11f1d46231025bed93e97c97893d6a359c 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 17eca994e256d9460fc29e1c0d8675afe7f83417..41cce333d8a524ee09552d34d4c02dcad095c08d 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 1c842138cf21026ee89923dcbe95b3d82b644c08..b734c8dac5ed4c0c6a3f0449874f84405f335d47 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 22bf8050605d1764497db7490eca15ce5b4b3081..686f146fb1e42d904c925fabc87b70e83dafd4aa 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 9c31f4f9a032349bc304406c895dd75bd8f1fa8f..bc3bebd9b05c95a386f059bf86e18a6ac71fe735 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