feat: enhance backup and restore with zip validation and progress UI

This commit is contained in:
zhoubinjia committed 2026-05-18 10:27:09 +08:00
1 parent 0d3ed9bc5c
commit cc4207d15a
5 files changed
+233 -58

No files matched your search

@@ -8,6 +8,9 @@ import kotlinx.coroutines.withContext
import java.io.File
import java.io.FileInputStream
import java.io.FileOutputStream
import java.io.InputStream
import java.io.OutputStream
import java.util.UUID
import java.util.zip.ZipEntry
import java.util.zip.ZipInputStream
import java.util.zip.ZipOutputStream
@@ -18,6 +21,7 @@ import java.util.zip.ZipOutputStream
*/
object BackupManager {
private const val TAG = "BackupManager"
private const val BUFFER_SIZE = 64 * 1024
// 需备份的目录/文件相对路径列表 (相对于 context.filesDir)
private val BACKUP_ENTRIES = listOf(
@@ -38,27 +42,49 @@ object BackupManager {
* @return 备份是否成功
*/
suspend fun performBackup(context: Context, outputUri: Uri): Boolean = withContext(Dispatchers.IO) {
val tempZip = File(context.cacheDir, "backup-${UUID.randomUUID()}.zip")
try {
val outputStream = context.contentResolver.openOutputStream(outputUri)
?: throw IllegalStateException("Cannot open output stream for URI: $outputUri")
FileOutputStream(tempZip).use { fileOutput ->
ZipOutputStream(fileOutput).use { zos ->
val filesDir = context.filesDir
ZipOutputStream(outputStream).use { zos ->
val filesDir = context.filesDir
for (entryName in BACKUP_ENTRIES) {
val fileOrDir = File(filesDir, entryName)
if (fileOrDir.exists()) {
zipFile(fileOrDir, fileOrDir.name, zos)
} else {
PLog.d(TAG, "Skip missing backup entry: $entryName")
for (entryName in BACKUP_ENTRIES) {
val fileOrDir = File(filesDir, entryName)
if (fileOrDir.exists()) {
zipFile(fileOrDir, fileOrDir.name, zos)
} else {
PLog.d(TAG, "Skip missing backup entry: $entryName")
}
}
zos.finish()
zos.flush()
fileOutput.fd.sync()
}
}
PLog.d(TAG, "Backup successfully completed to $outputUri")
validateBackupZip(tempZip)
val outputStream = context.contentResolver.openOutputStream(outputUri, "wt")
?: throw IllegalStateException("Cannot open output stream for URI: $outputUri")
outputStream.use { output ->
FileInputStream(tempZip).use { input ->
copyStream(input, output)
}
}
context.contentResolver.openInputStream(outputUri)?.use { input ->
validateBackupZip(input)
} ?: throw IllegalStateException("Cannot read written backup from URI: $outputUri")
PLog.d(TAG, "Backup successfully completed to $outputUri, size=${tempZip.length()}")
true
} catch (e: Exception) {
PLog.e(TAG, "Backup failed", e)
false
} finally {
if (tempZip.exists() && !tempZip.delete()) {
PLog.w(TAG, "Failed to delete temp backup zip: $tempZip")
}
}
}
@@ -86,11 +112,7 @@ object BackupManager {
FileInputStream(fileToZip).use { fis ->
val zipEntry = ZipEntry(fileName)
zos.putNextEntry(zipEntry)
val bytes = ByteArray(1024)
var length: Int
while (fis.read(bytes).also { length = it } >= 0) {
zos.write(bytes, 0, length)
}
copyStream(fis, zos)
zos.closeEntry()
}
}
@@ -102,53 +124,162 @@ object BackupManager {
* @return 恢复是否成功
*/
suspend fun performRestore(context: Context, inputUri: Uri): Boolean = withContext(Dispatchers.IO) {
val tempZip = File(context.cacheDir, "restore-${UUID.randomUUID()}.zip")
val restoreDir = File(context.cacheDir, "restore-${UUID.randomUUID()}")
try {
val inputStream = context.contentResolver.openInputStream(inputUri)
?: throw IllegalStateException("Cannot open input stream for URI: $inputUri")
inputStream.use { input ->
FileOutputStream(tempZip).use { output ->
copyStream(input, output)
output.fd.sync()
}
}
val filesDir = context.filesDir
validateBackupZip(tempZip)
ZipInputStream(inputStream).use { zis ->
if (!restoreDir.mkdirs()) {
throw IllegalStateException("Cannot create restore staging dir: $restoreDir")
}
unzipBackupToDirectory(tempZip, restoreDir)
applyRestoreDirectory(restoreDir, context.filesDir)
PLog.d(TAG, "Restore successfully completed from $inputUri")
true
} catch (e: Exception) {
PLog.e(TAG, "Restore failed", e)
false
} finally {
if (tempZip.exists() && !tempZip.delete()) {
PLog.w(TAG, "Failed to delete temp restore zip: $tempZip")
}
if (restoreDir.exists() && !restoreDir.deleteRecursively()) {
PLog.w(TAG, "Failed to delete temp restore dir: $restoreDir")
}
}
}
private fun unzipBackupToDirectory(zipFile: File, targetDir: File) {
FileInputStream(zipFile).use { fileInput ->
ZipInputStream(fileInput).use { zis ->
var zipEntry: ZipEntry? = zis.nextEntry
while (zipEntry != null) {
val newFile = File(filesDir, zipEntry.name)
// 防止 Zip Slip 漏洞
if (!newFile.canonicalPath.startsWith(filesDir.canonicalPath + File.separator)) {
PLog.w(TAG, "Skip entry outside of target dir: ${zipEntry.name}")
val entryName = zipEntry.name
if (!isAllowedBackupEntry(entryName)) {
PLog.w(TAG, "Skip unknown backup entry: $entryName")
zis.closeEntry()
zipEntry = zis.nextEntry
continue
}
val newFile = File(targetDir, entryName)
assertInsideDirectory(targetDir, newFile, entryName)
if (zipEntry.isDirectory) {
if (!newFile.isDirectory && !newFile.mkdirs()) {
PLog.w(TAG, "Failed to create directory: $newFile")
throw IllegalStateException("Failed to create directory: $newFile")
}
} else {
// 确保父目录存在
val parent = newFile.parentFile
if (parent != null && !parent.isDirectory && !parent.mkdirs()) {
PLog.w(TAG, "Failed to create parent directory for: $newFile")
throw IllegalStateException("Failed to create parent directory for: $newFile")
}
// 写入文件
FileOutputStream(newFile).use { fos ->
val bytes = ByteArray(1024)
var length: Int
while (zis.read(bytes).also { length = it } >= 0) {
fos.write(bytes, 0, length)
}
copyStream(zis, fos)
}
}
zis.closeEntry()
zipEntry = zis.nextEntry
}
}
PLog.d(TAG, "Restore successfully completed from $inputUri")
true
} catch (e: Exception) {
PLog.e(TAG, "Restore failed", e)
false
}
}
private fun applyRestoreDirectory(restoreDir: File, filesDir: File) {
for (entryName in BACKUP_ENTRIES) {
val stagedEntry = File(restoreDir, entryName)
if (!stagedEntry.exists()) {
continue
}
val targetEntry = File(filesDir, entryName)
copyFileTree(stagedEntry, targetEntry, filesDir)
}
}
private fun copyFileTree(source: File, target: File, rootDir: File) {
assertInsideDirectory(rootDir, target, target.name)
if (source.isDirectory) {
if (!target.isDirectory && !target.mkdirs()) {
throw IllegalStateException("Failed to create target directory: $target")
}
source.listFiles()?.forEach { child ->
copyFileTree(child, File(target, child.name), rootDir)
}
} else {
val parent = target.parentFile
if (parent != null && !parent.isDirectory && !parent.mkdirs()) {
throw IllegalStateException("Failed to create parent directory for: $target")
}
source.copyTo(target, overwrite = true)
}
}
private fun validateBackupZip(zipFile: File) {
if (!zipFile.isFile || zipFile.length() <= 0L) {
throw IllegalStateException("Backup zip is empty: $zipFile")
}
FileInputStream(zipFile).use { input ->
validateBackupZip(input)
}
}
private fun validateBackupZip(inputStream: InputStream) {
var allowedEntryCount = 0
ZipInputStream(inputStream).use { zis ->
var zipEntry: ZipEntry? = zis.nextEntry
while (zipEntry != null) {
val entryName = zipEntry.name
if (isAllowedBackupEntry(entryName)) {
allowedEntryCount++
val bytes = ByteArray(BUFFER_SIZE)
while (zis.read(bytes) >= 0) {
// Drain the entry so truncated zip files fail before restore.
}
} else {
PLog.w(TAG, "Found unknown backup entry during validation: $entryName")
}
zis.closeEntry()
zipEntry = zis.nextEntry
}
}
if (allowedEntryCount == 0) {
throw IllegalStateException("Backup zip does not contain supported entries")
}
}
private fun isAllowedBackupEntry(entryName: String): Boolean {
val normalized = entryName.replace('\\', '/').trimStart('/')
if (normalized.isEmpty() || normalized.contains("../") || normalized == "..") {
return false
}
val topLevelName = normalized.substringBefore('/')
return BACKUP_ENTRIES.contains(topLevelName)
}
private fun assertInsideDirectory(rootDir: File, target: File, entryName: String) {
val rootPath = rootDir.canonicalPath
val targetPath = target.canonicalPath
if (targetPath != rootPath && !targetPath.startsWith(rootPath + File.separator)) {
throw IllegalStateException("Entry escapes target directory: $entryName")
}
}
private fun copyStream(input: InputStream, output: OutputStream) {
val buffer = ByteArray(BUFFER_SIZE)
var length: Int
while (input.read(buffer).also { length = it } >= 0) {
output.write(buffer, 0, length)
}
}
}
@@ -52,6 +52,7 @@ import androidx.compose.material.icons.filled.FilterNone
import androidx.compose.material3.AlertDialog
import androidx.compose.material3.Card
import androidx.compose.material3.CardDefaults
import androidx.compose.material3.CircularProgressIndicator
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.HorizontalDivider
import androidx.compose.material3.Icon
@@ -124,6 +125,10 @@ enum class SettingsTab {
GENERAL, IMAGING, RAW, PHANTOM, ABOUT
}
private enum class BackupOperation {
BACKUP, RESTORE
}
private const val TELEGRAM_GROUP_URL = "https://t.me/photoncameraapp"
private const val QQ_GROUP_URL = "https://qun.qq.com/universal-share/share?ac=1&authKey=SFezWP1Ub5Egb5yMc7dbc1W4BVKGzzs1Ld9RD%2BKYn%2FlXiuqD4XZCGse48v%2FNcvrq&busi_data=eyJncm91cENvZGUiOiI1Njk2MDU0NTIiLCJ0b2tlbiI6IjNTM0Z4MkN1NUpDQVU1OXJDZ0xFVlJOb0xHZHFCQ0xWc1pKQWpSVzNVT0FwaHFRcEFYR0lFTU9mNUxuNFl5TDEiLCJ1aW4iOiI0MTk3NzQ2OTYifQ%3D%3D&data=WwMa6V5hKvkhzfvOaOKz8MKqNOvSSjTxTRj6Dn-1bHP68fZuRJ66cyD5xOhydrUkF8yIA70R_yXqlFRwJGoaCQ&svctype=4&tempid=h5_group_info"
@@ -237,6 +242,7 @@ fun SettingsScreen(
var rawWhitePointCorrectionUi by remember { mutableStateOf(rawWhitePointCorrection) }
var aiFocusScoreThresholdUi by remember(aiFocusScoreThreshold) { mutableStateOf(aiFocusScoreThreshold) }
var showAspectRatioDialog by remember { mutableStateOf(false) }
var backupOperation by remember { mutableStateOf<BackupOperation?>(null) }
LaunchedEffect(rawNlmNoiseFactor, rawExposureCompensation, rawBlackPointCorrection, rawWhitePointCorrection) {
if (!isRawSliderAdjusting) {
@@ -264,11 +270,16 @@ fun SettingsScreen(
) { uri ->
uri?.let {
coroutineScope.launch {
val success = com.hinnka.mycamera.data.BackupManager.performBackup(context, it)
if (success) {
android.widget.Toast.makeText(context, R.string.backup_success, android.widget.Toast.LENGTH_SHORT).show()
} else {
android.widget.Toast.makeText(context, R.string.backup_failed, android.widget.Toast.LENGTH_SHORT).show()
backupOperation = BackupOperation.BACKUP
try {
val success = com.hinnka.mycamera.data.BackupManager.performBackup(context, it)
if (success) {
android.widget.Toast.makeText(context, R.string.backup_success, android.widget.Toast.LENGTH_SHORT).show()
} else {
android.widget.Toast.makeText(context, R.string.backup_failed, android.widget.Toast.LENGTH_SHORT).show()
}
} finally {
backupOperation = null
}
}
}
@@ -279,11 +290,16 @@ fun SettingsScreen(
) { uri ->
uri?.let {
coroutineScope.launch {
val success = com.hinnka.mycamera.data.BackupManager.performRestore(context, it)
if (success) {
android.widget.Toast.makeText(context, R.string.restore_success, android.widget.Toast.LENGTH_LONG).show()
} else {
android.widget.Toast.makeText(context, R.string.restore_failed, android.widget.Toast.LENGTH_SHORT).show()
backupOperation = BackupOperation.RESTORE
try {
val success = com.hinnka.mycamera.data.BackupManager.performRestore(context, it)
if (success) {
android.widget.Toast.makeText(context, R.string.restore_success, android.widget.Toast.LENGTH_LONG).show()
} else {
android.widget.Toast.makeText(context, R.string.restore_failed, android.widget.Toast.LENGTH_SHORT).show()
}
} finally {
backupOperation = null
}
}
}
@@ -662,7 +678,13 @@ fun SettingsScreen(
NavigationSettingItem(
title = stringResource(R.string.settings_backup_settings),
description = stringResource(R.string.settings_backup_settings_description),
description = if (backupOperation == BackupOperation.BACKUP) {
stringResource(R.string.backup_in_progress)
} else {
stringResource(R.string.settings_backup_settings_description)
},
enabled = backupOperation == null,
showProgress = backupOperation == BackupOperation.BACKUP,
onClick = { backupLauncher.launch("photon_camera_backup_${System.currentTimeMillis()}.zip") }
)
@@ -673,7 +695,13 @@ fun SettingsScreen(
NavigationSettingItem(
title = stringResource(R.string.settings_restore_settings),
description = stringResource(R.string.settings_restore_settings_description),
description = if (backupOperation == BackupOperation.RESTORE) {
stringResource(R.string.restore_in_progress)
} else {
stringResource(R.string.settings_restore_settings_description)
},
enabled = backupOperation == null,
showProgress = backupOperation == BackupOperation.RESTORE,
onClick = { restoreLauncher.launch(arrayOf("application/zip", "application/x-zip-compressed", "application/octet-stream")) }
)
}
@@ -2489,12 +2517,14 @@ fun NavigationSettingItem(
title: String,
description: String,
onClick: () -> Unit,
enabled: Boolean = true,
showProgress: Boolean = false,
modifier: Modifier = Modifier
) {
Row(
modifier = modifier
.fillMaxWidth()
.clickable(onClick = onClick)
.clickable(enabled = enabled, onClick = onClick)
.padding(vertical = 8.dp),
horizontalArrangement = Arrangement.SpaceBetween,
verticalAlignment = Alignment.CenterVertically
@@ -2502,7 +2532,7 @@ fun NavigationSettingItem(
Column(modifier = Modifier.weight(1f)) {
Text(
text = title,
color = Color.White,
color = Color.White.copy(alpha = if (enabled || showProgress) 1f else 0.5f),
fontSize = 16.sp,
fontWeight = FontWeight.Normal
)
@@ -2517,11 +2547,19 @@ fun NavigationSettingItem(
Spacer(modifier = Modifier.width(16.dp))
Icon(
imageVector = Icons.Default.ChevronRight,
contentDescription = null,
tint = Color.White.copy(alpha = 0.6f)
)
if (showProgress) {
CircularProgressIndicator(
modifier = Modifier.size(22.dp),
color = Color.White.copy(alpha = 0.8f),
strokeWidth = 2.dp
)
} else {
Icon(
imageVector = Icons.Default.ChevronRight,
contentDescription = null,
tint = Color.White.copy(alpha = if (enabled) 0.6f else 0.3f)
)
}
}
}
@@ -443,8 +443,10 @@
<string name="settings_restore_settings_description">从之前的备份 ZIP 文件中恢复。应用可能需要重启才能生效。</string>
<string name="backup_success">备份成功</string>
<string name="backup_failed">备份失败</string>
<string name="backup_in_progress">正在备份设置和自定义内容...</string>
<string name="restore_success">恢复成功,请重新启动应用。</string>
<string name="restore_failed">恢复失败</string>
<string name="restore_in_progress">正在恢复设置和自定义内容...</string>
<string name="filter_management_title">滤镜管理</string>
<string name="apply_lut_title">应用 LUT</string>
<string name="apply_lut_processing">正在应用 LUT...</string>
@@ -337,8 +337,10 @@
<string name="settings_restore_settings_description">從先前的備份 ZIP 檔案中還原。應用可能需要重新啟動才能生效。</string>
<string name="backup_success">備份成功</string>
<string name="backup_failed">備份失敗</string>
<string name="backup_in_progress">正在備份設定和自訂內容...</string>
<string name="restore_success">還原成功,請重新啟動應用。</string>
<string name="restore_failed">還原失敗</string>
<string name="restore_in_progress">正在還原設定和自訂內容...</string>
<string name="filter_management_title">濾鏡管理</string>
<string name="frame_management_title">邊框管理</string>
<string name="category_all">所有</string>
+2
View File
@@ -448,8 +448,10 @@
<string name="settings_restore_settings_description">Restore from a previous backup ZIP file. App may require a restart to apply.</string>
<string name="backup_success">Backup completed successfully</string>
<string name="backup_failed">Backup failed</string>
<string name="backup_in_progress">Backing up settings and custom content...</string>
<string name="restore_success">Restore completed successfully. Please restart the app.</string>
<string name="restore_failed">Restore failed</string>
<string name="restore_in_progress">Restoring settings and custom content...</string>
<string name="filter_management_title">LUT Management</string>
<string name="apply_lut_title">Apply LUT</string>
<string name="apply_lut_processing">Applying LUT...</string>