feat: backup device info
This commit is contained in:
1 parent
77c69b3e1b
commit
be933c01f9
5 files changed
+512
-23
No files matched your search
@@ -0,0 +1,70 @@
|
||||
package com.hinnka.mycamera.data
|
||||
|
||||
import com.google.gson.GsonBuilder
|
||||
import com.google.gson.JsonObject
|
||||
import com.google.gson.JsonParser
|
||||
import java.io.File
|
||||
import java.io.OutputStream
|
||||
import java.util.Locale
|
||||
|
||||
internal data class BackupDeviceIdentity(
|
||||
val manufacturer: String,
|
||||
val model: String,
|
||||
val device: String,
|
||||
) {
|
||||
fun matches(other: BackupDeviceIdentity): Boolean {
|
||||
return normalized(manufacturer) == normalized(other.manufacturer) &&
|
||||
normalized(model) == normalized(other.model) &&
|
||||
normalized(device) == normalized(other.device)
|
||||
}
|
||||
|
||||
private fun normalized(value: String): String {
|
||||
return value.trim().lowercase(Locale.ROOT)
|
||||
}
|
||||
}
|
||||
|
||||
internal object BackupDeviceMetadata {
|
||||
const val ENTRY_NAME = "backup_manifest.json"
|
||||
|
||||
private const val SCHEMA_VERSION = 1
|
||||
private val gson = GsonBuilder().setPrettyPrinting().create()
|
||||
|
||||
fun write(identity: BackupDeviceIdentity, output: OutputStream) {
|
||||
val root = JsonObject().apply {
|
||||
addProperty("schema_version", SCHEMA_VERSION)
|
||||
add(
|
||||
"device",
|
||||
JsonObject().apply {
|
||||
addProperty("manufacturer", identity.manufacturer)
|
||||
addProperty("model", identity.model)
|
||||
addProperty("device", identity.device)
|
||||
},
|
||||
)
|
||||
}
|
||||
output.write(gson.toJson(root).toByteArray(Charsets.UTF_8))
|
||||
}
|
||||
|
||||
fun read(restoreDir: File): BackupDeviceIdentity? {
|
||||
val metadataFile = File(restoreDir, ENTRY_NAME)
|
||||
if (!metadataFile.isFile) return null
|
||||
|
||||
return runCatching {
|
||||
val root = metadataFile.reader(Charsets.UTF_8).use(JsonParser::parseReader).asJsonObject
|
||||
if (root.get("schema_version")?.asInt != SCHEMA_VERSION) return@runCatching null
|
||||
val device = root.getAsJsonObject("device") ?: return@runCatching null
|
||||
BackupDeviceIdentity(
|
||||
manufacturer = device.requiredString("manufacturer"),
|
||||
model = device.requiredString("model"),
|
||||
device = device.requiredString("device"),
|
||||
)
|
||||
}.getOrNull()
|
||||
}
|
||||
|
||||
private fun JsonObject.requiredString(name: String): String {
|
||||
return get(name)
|
||||
?.takeIf { it.isJsonPrimitive && it.asJsonPrimitive.isString }
|
||||
?.asString
|
||||
?.takeIf { it.isNotBlank() }
|
||||
?: error("Missing backup device metadata field: $name")
|
||||
}
|
||||
}
|
||||
@@ -2,6 +2,7 @@ package com.hinnka.mycamera.data
|
||||
|
||||
import android.content.Context
|
||||
import android.net.Uri
|
||||
import android.os.Build
|
||||
import com.hinnka.mycamera.utils.PLog
|
||||
import kotlinx.coroutines.Dispatchers
|
||||
import kotlinx.coroutines.withContext
|
||||
@@ -39,6 +40,14 @@ object BackupManager {
|
||||
"custom_logos"
|
||||
)
|
||||
|
||||
// These imported profiles describe a particular camera sensor and must stay with its device.
|
||||
private val DEVICE_SPECIFIC_BACKUP_ENTRIES = setOf(
|
||||
"custom_dcps.json",
|
||||
"custom_raw_noise_profiles.json",
|
||||
"custom_dcps",
|
||||
"custom_raw_noise_profiles",
|
||||
)
|
||||
|
||||
/**
|
||||
* 执行备份
|
||||
* @param context Context
|
||||
@@ -52,6 +61,10 @@ object BackupManager {
|
||||
ZipOutputStream(fileOutput).use { zos ->
|
||||
val filesDir = context.filesDir
|
||||
|
||||
zos.putNextEntry(ZipEntry(BackupDeviceMetadata.ENTRY_NAME))
|
||||
BackupDeviceMetadata.write(currentDeviceIdentity(), zos)
|
||||
zos.closeEntry()
|
||||
|
||||
for (entryName in BACKUP_ENTRIES) {
|
||||
val fileOrDir = File(filesDir, entryName)
|
||||
if (fileOrDir.exists()) {
|
||||
@@ -121,7 +134,7 @@ object BackupManager {
|
||||
if (removedPreferenceCount > 0) {
|
||||
PLog.d(
|
||||
TAG,
|
||||
"Removed $removedPreferenceCount device-bound preferences from backup"
|
||||
"Removed $removedPreferenceCount non-portable preferences from backup"
|
||||
)
|
||||
}
|
||||
} else {
|
||||
@@ -158,11 +171,34 @@ object BackupManager {
|
||||
}
|
||||
|
||||
unzipBackupToDirectory(tempZip, restoreDir)
|
||||
val sanitizedRestorePreferenceCount = BackupPreferenceSanitizer.sanitizeRestoreDirectory(restoreDir)
|
||||
if (sanitizedRestorePreferenceCount > 0) {
|
||||
val backupDeviceIdentity = BackupDeviceMetadata.read(restoreDir)
|
||||
val currentDeviceIdentity = currentDeviceIdentity()
|
||||
val isSameDevice = backupDeviceIdentity?.matches(currentDeviceIdentity) == true
|
||||
if (!isSameDevice) {
|
||||
PLog.i(
|
||||
TAG,
|
||||
"Backup device does not match current device; preserving current " +
|
||||
"hardware-bound preferences. backup=$backupDeviceIdentity, " +
|
||||
"current=$currentDeviceIdentity"
|
||||
)
|
||||
}
|
||||
val preferenceSanitization = BackupPreferenceSanitizer.sanitizeRestoreDirectory(
|
||||
restoreDir = restoreDir,
|
||||
currentFilesDir = context.filesDir,
|
||||
preserveCurrentDeviceSpecificPreferences = !isSameDevice,
|
||||
)
|
||||
if (preferenceSanitization.removedNonPortablePreferenceCount > 0) {
|
||||
PLog.d(
|
||||
TAG,
|
||||
"Removed $sanitizedRestorePreferenceCount device-bound preferences during restore"
|
||||
"Removed ${preferenceSanitization.removedNonPortablePreferenceCount} " +
|
||||
"non-portable preferences during restore"
|
||||
)
|
||||
}
|
||||
if (preferenceSanitization.skippedDeviceSpecificPreferenceCount > 0) {
|
||||
PLog.d(
|
||||
TAG,
|
||||
"Skipped ${preferenceSanitization.skippedDeviceSpecificPreferenceCount} " +
|
||||
"device-specific preferences during cross-device restore"
|
||||
)
|
||||
}
|
||||
val frameAssetMigration = FrameAssetPathMigrator.migrateRestoredData(
|
||||
@@ -190,7 +226,15 @@ object BackupManager {
|
||||
"invalid restored frame templates"
|
||||
)
|
||||
}
|
||||
applyRestoreDirectory(restoreDir, context.filesDir)
|
||||
applyRestoreDirectory(
|
||||
restoreDir = restoreDir,
|
||||
filesDir = context.filesDir,
|
||||
skippedEntries = if (isSameDevice) {
|
||||
emptySet()
|
||||
} else {
|
||||
DEVICE_SPECIFIC_BACKUP_ENTRIES
|
||||
},
|
||||
)
|
||||
|
||||
PLog.d(TAG, "Restore successfully completed from $inputUri")
|
||||
true
|
||||
@@ -243,8 +287,16 @@ object BackupManager {
|
||||
}
|
||||
}
|
||||
|
||||
private fun applyRestoreDirectory(restoreDir: File, filesDir: File) {
|
||||
private fun applyRestoreDirectory(
|
||||
restoreDir: File,
|
||||
filesDir: File,
|
||||
skippedEntries: Set<String>,
|
||||
) {
|
||||
for (entryName in BACKUP_ENTRIES) {
|
||||
if (entryName in skippedEntries) {
|
||||
PLog.d(TAG, "Skipped device-specific backup entry during restore: $entryName")
|
||||
continue
|
||||
}
|
||||
val stagedEntry = File(restoreDir, entryName)
|
||||
if (!stagedEntry.exists()) {
|
||||
continue
|
||||
@@ -282,13 +334,15 @@ object BackupManager {
|
||||
}
|
||||
|
||||
private fun validateBackupZip(inputStream: InputStream) {
|
||||
var allowedEntryCount = 0
|
||||
var supportedDataEntryCount = 0
|
||||
ZipInputStream(inputStream).use { zis ->
|
||||
var zipEntry: ZipEntry? = zis.nextEntry
|
||||
while (zipEntry != null) {
|
||||
val entryName = zipEntry.name
|
||||
if (isAllowedBackupEntry(entryName)) {
|
||||
allowedEntryCount++
|
||||
if (isBackupDataEntry(entryName)) {
|
||||
supportedDataEntryCount++
|
||||
}
|
||||
val bytes = ByteArray(BUFFER_SIZE)
|
||||
while (zis.read(bytes) >= 0) {
|
||||
// Drain the entry so truncated zip files fail before restore.
|
||||
@@ -300,7 +354,7 @@ object BackupManager {
|
||||
zipEntry = zis.nextEntry
|
||||
}
|
||||
}
|
||||
if (allowedEntryCount == 0) {
|
||||
if (supportedDataEntryCount == 0) {
|
||||
throw IllegalStateException("Backup zip does not contain supported entries")
|
||||
}
|
||||
}
|
||||
@@ -310,10 +364,26 @@ object BackupManager {
|
||||
if (normalized.isEmpty() || normalized.contains("../") || normalized == "..") {
|
||||
return false
|
||||
}
|
||||
if (normalized == BackupDeviceMetadata.ENTRY_NAME) {
|
||||
return true
|
||||
}
|
||||
val topLevelName = normalized.substringBefore('/')
|
||||
return BACKUP_ENTRIES.contains(topLevelName)
|
||||
}
|
||||
|
||||
private fun isBackupDataEntry(entryName: String): Boolean {
|
||||
val normalized = entryName.replace('\\', '/').trimStart('/')
|
||||
return BACKUP_ENTRIES.contains(normalized.substringBefore('/'))
|
||||
}
|
||||
|
||||
private fun currentDeviceIdentity(): BackupDeviceIdentity {
|
||||
return BackupDeviceIdentity(
|
||||
manufacturer = Build.MANUFACTURER,
|
||||
model = Build.MODEL,
|
||||
device = Build.DEVICE,
|
||||
)
|
||||
}
|
||||
|
||||
private fun assertInsideDirectory(rootDir: File, target: File, entryName: String) {
|
||||
val rootPath = rootDir.canonicalPath
|
||||
val targetPath = target.canonicalPath
|
||||
|
||||
@@ -1,6 +1,9 @@
|
||||
package com.hinnka.mycamera.data
|
||||
|
||||
import androidx.datastore.preferences.PreferencesProto.PreferenceMap
|
||||
import com.google.gson.Gson
|
||||
import com.google.gson.JsonObject
|
||||
import com.google.gson.JsonParser
|
||||
import java.io.File
|
||||
import java.io.FileInputStream
|
||||
import java.io.FileOutputStream
|
||||
@@ -9,6 +12,12 @@ import java.util.UUID
|
||||
|
||||
internal object BackupPreferenceSanitizer {
|
||||
private const val USER_PREFERENCES_ENTRY = "datastore/user_preferences.preferences_pb"
|
||||
private const val CUSTOM_PRESETS_KEY = "custom_presets_json"
|
||||
|
||||
data class RestoreResult(
|
||||
val removedNonPortablePreferenceCount: Int = 0,
|
||||
val skippedDeviceSpecificPreferenceCount: Int = 0,
|
||||
)
|
||||
|
||||
private val nonPortablePreferenceKeys = setOf(
|
||||
"photo_save_path",
|
||||
@@ -19,6 +28,54 @@ internal object BackupPreferenceSanitizer {
|
||||
"openai_api_key_encrypted_v1",
|
||||
)
|
||||
|
||||
/**
|
||||
* Values that contain identifiers, calibration, or compatibility overrides for the physical
|
||||
* camera/audio hardware. Generic feature choices (for example RAW or video resolution) remain
|
||||
* portable and are deliberately not included here.
|
||||
*/
|
||||
private val deviceSpecificPreferenceKeys = setOf(
|
||||
"raw_dcp_id",
|
||||
"raw_dcp_ids_by_lens",
|
||||
"raw_noise_profile_id",
|
||||
"raw_noise_profile_ids_by_lens",
|
||||
"raw_hncs_profile_id",
|
||||
"raw_color_engine",
|
||||
"raw_black_level_modes",
|
||||
"raw_custom_black_levels",
|
||||
"raw_white_level_modes",
|
||||
"raw_custom_white_levels",
|
||||
"raw_cfa_correction_modes",
|
||||
"photon_core_imaging_tuning",
|
||||
"raw_lens_shading_correction_enabled",
|
||||
"vendor_capture_settings",
|
||||
"custom_vendor_key_settings",
|
||||
"camera_orientation_offsets",
|
||||
"default_focal_length",
|
||||
"custom_focal_lengths",
|
||||
"custom_lens_ids",
|
||||
"lens_id_blacklist",
|
||||
"isz_lens_configs",
|
||||
"preferred_main_camera_id",
|
||||
"preferred_macro_camera_id",
|
||||
"enable_logical_multi_camera_discovery",
|
||||
"logical_camera_binding_whitelist",
|
||||
"hidden_focal_lengths",
|
||||
"video_audio_input_id",
|
||||
"fix_tonemap_preview",
|
||||
"fix_tonemap_capture",
|
||||
"hlg_hardware_compatibility_enabled",
|
||||
"camera_startup_defaults_restored_v1",
|
||||
)
|
||||
|
||||
private val deviceSpecificPresetFields = setOf(
|
||||
"rawDcpId",
|
||||
"rawDcpIdsByLens",
|
||||
"rawHncsProfileId",
|
||||
"rawRenderingEngine",
|
||||
)
|
||||
|
||||
private val gson = Gson()
|
||||
|
||||
fun isUserPreferencesEntry(entryName: String): Boolean {
|
||||
return entryName.replace('\\', '/').trimStart('/') == USER_PREFERENCES_ENTRY
|
||||
}
|
||||
@@ -33,16 +90,163 @@ internal object BackupPreferenceSanitizer {
|
||||
}
|
||||
|
||||
fun sanitizeRestoreDirectory(restoreDir: File): Int {
|
||||
return sanitizeRestoreDirectory(
|
||||
restoreDir = restoreDir,
|
||||
currentFilesDir = null,
|
||||
preserveCurrentDeviceSpecificPreferences = false,
|
||||
).removedNonPortablePreferenceCount
|
||||
}
|
||||
|
||||
fun sanitizeRestoreDirectory(
|
||||
restoreDir: File,
|
||||
currentFilesDir: File?,
|
||||
preserveCurrentDeviceSpecificPreferences: Boolean,
|
||||
): RestoreResult {
|
||||
val preferencesFile = File(restoreDir, USER_PREFERENCES_ENTRY)
|
||||
if (!preferencesFile.isFile) {
|
||||
return 0
|
||||
return RestoreResult()
|
||||
}
|
||||
|
||||
val (preferenceMap, removedCount) = readPreferenceMapWithoutNonPortableKeys(preferencesFile)
|
||||
if (removedCount == 0) {
|
||||
return 0
|
||||
val restoredBuilder = FileInputStream(preferencesFile).use { input ->
|
||||
PreferenceMap.parseFrom(input).toBuilder()
|
||||
}
|
||||
val currentPreferenceMap = currentFilesDir
|
||||
?.let { File(it, USER_PREFERENCES_ENTRY) }
|
||||
?.takeIf(File::isFile)
|
||||
?.let { currentFile ->
|
||||
FileInputStream(currentFile).use(PreferenceMap::parseFrom)
|
||||
}
|
||||
val removedCount = preserveCurrentValues(
|
||||
restoredBuilder = restoredBuilder,
|
||||
currentPreferenceMap = currentPreferenceMap,
|
||||
keys = nonPortablePreferenceKeys,
|
||||
)
|
||||
var skippedDeviceSpecificCount = 0
|
||||
|
||||
if (preserveCurrentDeviceSpecificPreferences) {
|
||||
skippedDeviceSpecificCount += preserveCurrentValues(
|
||||
restoredBuilder = restoredBuilder,
|
||||
currentPreferenceMap = currentPreferenceMap,
|
||||
keys = deviceSpecificPreferenceKeys,
|
||||
)
|
||||
skippedDeviceSpecificCount += preserveCurrentPresetDeviceFields(
|
||||
restoredBuilder = restoredBuilder,
|
||||
currentPreferenceMap = currentPreferenceMap,
|
||||
)
|
||||
}
|
||||
|
||||
if (
|
||||
removedCount == 0 &&
|
||||
currentFilesDir == null &&
|
||||
!preserveCurrentDeviceSpecificPreferences
|
||||
) {
|
||||
return RestoreResult()
|
||||
}
|
||||
|
||||
replacePreferencesFile(preferencesFile, restoredBuilder.build())
|
||||
|
||||
return RestoreResult(
|
||||
removedNonPortablePreferenceCount = removedCount,
|
||||
skippedDeviceSpecificPreferenceCount = skippedDeviceSpecificCount,
|
||||
)
|
||||
}
|
||||
|
||||
private fun preserveCurrentValues(
|
||||
restoredBuilder: PreferenceMap.Builder,
|
||||
currentPreferenceMap: PreferenceMap?,
|
||||
keys: Set<String>,
|
||||
): Int {
|
||||
var skippedCount = 0
|
||||
for (key in keys) {
|
||||
if (restoredBuilder.containsPreferences(key)) {
|
||||
skippedCount++
|
||||
}
|
||||
val currentValue = currentPreferenceMap?.preferencesMap?.get(key)
|
||||
if (currentValue != null) {
|
||||
restoredBuilder.putPreferences(key, currentValue)
|
||||
} else {
|
||||
restoredBuilder.removePreferences(key)
|
||||
}
|
||||
}
|
||||
return skippedCount
|
||||
}
|
||||
|
||||
private fun preserveCurrentPresetDeviceFields(
|
||||
restoredBuilder: PreferenceMap.Builder,
|
||||
currentPreferenceMap: PreferenceMap?,
|
||||
): Int {
|
||||
val restoredValue = restoredBuilder.preferencesMap[CUSTOM_PRESETS_KEY]
|
||||
?.takeIf { it.hasString() }
|
||||
?: return 0
|
||||
val restoredPresets = runCatching {
|
||||
JsonParser.parseString(restoredValue.string).asJsonArray
|
||||
}.getOrNull() ?: return 0
|
||||
val currentPresetsById = currentPreferenceMap
|
||||
?.preferencesMap
|
||||
?.get(CUSTOM_PRESETS_KEY)
|
||||
?.takeIf { it.hasString() }
|
||||
?.let { value ->
|
||||
runCatching { JsonParser.parseString(value.string).asJsonArray }
|
||||
.getOrNull()
|
||||
?.mapNotNull { element ->
|
||||
element.takeIf { it.isJsonObject }
|
||||
?.asJsonObject
|
||||
?.let { preset -> preset.string("id")?.let { it to preset } }
|
||||
}
|
||||
?.toMap()
|
||||
}
|
||||
.orEmpty()
|
||||
|
||||
var skippedCount = 0
|
||||
var changed = false
|
||||
restoredPresets.forEach { element ->
|
||||
if (!element.isJsonObject) return@forEach
|
||||
val restoredPreset = element.asJsonObject
|
||||
val currentPreset = restoredPreset.string("id")?.let(currentPresetsById::get)
|
||||
for (field in deviceSpecificPresetFields) {
|
||||
if (restoredPreset.has(field)) {
|
||||
skippedCount++
|
||||
}
|
||||
val currentField = currentPreset?.get(field)
|
||||
if (currentField != null) {
|
||||
if (restoredPreset.get(field) != currentField) {
|
||||
restoredPreset.add(field, currentField.deepCopy())
|
||||
changed = true
|
||||
}
|
||||
} else if (restoredPreset.remove(field) != null) {
|
||||
changed = true
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (changed) {
|
||||
restoredBuilder.putPreferences(
|
||||
CUSTOM_PRESETS_KEY,
|
||||
restoredValue.toBuilder().setString(gson.toJson(restoredPresets)).build(),
|
||||
)
|
||||
}
|
||||
return skippedCount
|
||||
}
|
||||
|
||||
private fun JsonObject.string(name: String): String? {
|
||||
return get(name)
|
||||
?.takeIf { it.isJsonPrimitive && it.asJsonPrimitive.isString }
|
||||
?.asString
|
||||
?.takeIf(String::isNotBlank)
|
||||
}
|
||||
|
||||
private fun removeKeys(builder: PreferenceMap.Builder, keys: Set<String>): Int {
|
||||
var removedCount = 0
|
||||
for (key in keys) {
|
||||
if (builder.containsPreferences(key)) {
|
||||
builder.removePreferences(key)
|
||||
removedCount++
|
||||
}
|
||||
}
|
||||
return removedCount
|
||||
}
|
||||
|
||||
private fun replacePreferencesFile(preferencesFile: File, preferenceMap: PreferenceMap) {
|
||||
val tempFile = File(
|
||||
preferencesFile.parentFile,
|
||||
"${preferencesFile.name}.${UUID.randomUUID()}.tmp"
|
||||
@@ -63,8 +267,6 @@ internal object BackupPreferenceSanitizer {
|
||||
tempFile.delete()
|
||||
}
|
||||
}
|
||||
|
||||
return removedCount
|
||||
}
|
||||
|
||||
private fun readPreferenceMapWithoutNonPortableKeys(file: File): Pair<PreferenceMap, Int> {
|
||||
@@ -72,13 +274,7 @@ internal object BackupPreferenceSanitizer {
|
||||
PreferenceMap.parseFrom(input).toBuilder()
|
||||
}
|
||||
|
||||
var removedCount = 0
|
||||
for (key in nonPortablePreferenceKeys) {
|
||||
if (builder.containsPreferences(key)) {
|
||||
builder.removePreferences(key)
|
||||
removedCount++
|
||||
}
|
||||
}
|
||||
val removedCount = removeKeys(builder, nonPortablePreferenceKeys)
|
||||
|
||||
return builder.build() to removedCount
|
||||
}
|
||||
|
||||
@@ -0,0 +1,46 @@
|
||||
package com.hinnka.mycamera.data
|
||||
|
||||
import org.junit.Assert.assertEquals
|
||||
import org.junit.Assert.assertFalse
|
||||
import org.junit.Assert.assertNull
|
||||
import org.junit.Assert.assertTrue
|
||||
import org.junit.Rule
|
||||
import org.junit.Test
|
||||
import org.junit.rules.TemporaryFolder
|
||||
import java.io.File
|
||||
import java.io.FileOutputStream
|
||||
|
||||
class BackupDeviceMetadataTest {
|
||||
@get:Rule
|
||||
val temporaryFolder = TemporaryFolder()
|
||||
|
||||
@Test
|
||||
fun metadataRoundTripPreservesDeviceIdentity() {
|
||||
val restoreDir = temporaryFolder.newFolder("restore")
|
||||
val identity = BackupDeviceIdentity(
|
||||
manufacturer = "Google",
|
||||
model = "Pixel 10 Pro",
|
||||
device = "mustang",
|
||||
)
|
||||
FileOutputStream(File(restoreDir, BackupDeviceMetadata.ENTRY_NAME)).use { output ->
|
||||
BackupDeviceMetadata.write(identity, output)
|
||||
}
|
||||
|
||||
assertEquals(identity, BackupDeviceMetadata.read(restoreDir))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun identityMatchRequiresSameManufacturerModelAndDevice() {
|
||||
val identity = BackupDeviceIdentity("Google", "Pixel 10 Pro", "mustang")
|
||||
|
||||
assertTrue(identity.matches(BackupDeviceIdentity(" google ", "PIXEL 10 PRO", "Mustang")))
|
||||
assertFalse(identity.matches(identity.copy(manufacturer = "Samsung")))
|
||||
assertFalse(identity.matches(identity.copy(model = "Pixel 10")))
|
||||
assertFalse(identity.matches(identity.copy(device = "stallion")))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun missingMetadataIsUnknown() {
|
||||
assertNull(BackupDeviceMetadata.read(temporaryFolder.newFolder("legacy-restore")))
|
||||
}
|
||||
}
|
||||
@@ -2,6 +2,7 @@ package com.hinnka.mycamera.data
|
||||
|
||||
import androidx.datastore.preferences.PreferencesProto.PreferenceMap
|
||||
import androidx.datastore.preferences.PreferencesProto.Value
|
||||
import com.google.gson.JsonParser
|
||||
import org.junit.Assert.assertEquals
|
||||
import org.junit.Assert.assertFalse
|
||||
import org.junit.Assert.assertTrue
|
||||
@@ -57,6 +58,108 @@ class BackupPreferenceSanitizerTest {
|
||||
assertTrue(sanitizedMap.containsPreferences("keep_screen_on"))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun crossDeviceRestorePreservesCurrentHardwarePreferences() {
|
||||
val restoreDir = temporaryFolder.newFolder("cross-device-restore")
|
||||
val restoredDatastoreDir = File(restoreDir, "datastore").also { it.mkdirs() }
|
||||
val restoredPreferencesFile = File(
|
||||
restoredDatastoreDir,
|
||||
"user_preferences.preferences_pb",
|
||||
)
|
||||
writePreferenceMap(
|
||||
restoredPreferencesFile,
|
||||
PreferenceMap.newBuilder()
|
||||
.putPreferences("preferred_main_camera_id", stringValue("backup-camera"))
|
||||
.putPreferences("raw_dcp_ids_by_lens", stringValue("backup-dcp-map"))
|
||||
.putPreferences("raw_color_engine", stringValue("HncsLut"))
|
||||
.putPreferences("custom_lens_ids", stringValue("backup-custom-lens"))
|
||||
.putPreferences("photo_save_path", stringValue("BACKUP_PATH"))
|
||||
.putPreferences("keep_screen_on", booleanValue(false))
|
||||
.putPreferences(
|
||||
"custom_presets_json",
|
||||
stringValue(
|
||||
"""[{"id":"shared","name":"Backup preset","rawDcpId":"backup-dcp","rawDcpIdsByLens":{"backup-camera":"backup-dcp"},"rawHncsProfileId":"backup-hncs","rawRenderingEngine":"HncsLut"},{"id":"backup-only","name":"Backup only","rawDcpId":"backup-dcp","rawRenderingEngine":"HncsLut"}]"""
|
||||
),
|
||||
)
|
||||
.build(),
|
||||
)
|
||||
|
||||
val currentFilesDir = temporaryFolder.newFolder("current-files")
|
||||
val currentDatastoreDir = File(currentFilesDir, "datastore").also { it.mkdirs() }
|
||||
writePreferenceMap(
|
||||
File(currentDatastoreDir, "user_preferences.preferences_pb"),
|
||||
PreferenceMap.newBuilder()
|
||||
.putPreferences("preferred_main_camera_id", stringValue("current-camera"))
|
||||
.putPreferences("raw_dcp_ids_by_lens", stringValue("current-dcp-map"))
|
||||
.putPreferences("raw_color_engine", stringValue("AdobeCurve"))
|
||||
.putPreferences("photo_save_path", stringValue("CURRENT_PATH"))
|
||||
.putPreferences(
|
||||
"custom_presets_json",
|
||||
stringValue(
|
||||
"""[{"id":"shared","name":"Current preset","rawDcpId":"current-dcp","rawDcpIdsByLens":{"current-camera":"current-dcp"},"rawHncsProfileId":"current-hncs","rawRenderingEngine":"AdobeCurve"}]"""
|
||||
),
|
||||
)
|
||||
.build(),
|
||||
)
|
||||
|
||||
val result = BackupPreferenceSanitizer.sanitizeRestoreDirectory(
|
||||
restoreDir = restoreDir,
|
||||
currentFilesDir = currentFilesDir,
|
||||
preserveCurrentDeviceSpecificPreferences = true,
|
||||
)
|
||||
|
||||
val sanitizedMap = FileInputStream(restoredPreferencesFile).use(PreferenceMap::parseFrom)
|
||||
assertEquals("current-camera", sanitizedMap.preferencesMap.getValue("preferred_main_camera_id").string)
|
||||
assertEquals("current-dcp-map", sanitizedMap.preferencesMap.getValue("raw_dcp_ids_by_lens").string)
|
||||
assertEquals("AdobeCurve", sanitizedMap.preferencesMap.getValue("raw_color_engine").string)
|
||||
assertEquals("CURRENT_PATH", sanitizedMap.preferencesMap.getValue("photo_save_path").string)
|
||||
assertFalse(sanitizedMap.containsPreferences("custom_lens_ids"))
|
||||
assertFalse(sanitizedMap.preferencesMap.getValue("keep_screen_on").boolean)
|
||||
assertTrue(result.skippedDeviceSpecificPreferenceCount >= 7)
|
||||
|
||||
val presets = JsonParser.parseString(
|
||||
sanitizedMap.preferencesMap.getValue("custom_presets_json").string
|
||||
).asJsonArray
|
||||
val sharedPreset = presets[0].asJsonObject
|
||||
assertEquals("Backup preset", sharedPreset.get("name").asString)
|
||||
assertEquals("current-dcp", sharedPreset.get("rawDcpId").asString)
|
||||
assertEquals(
|
||||
"current-dcp",
|
||||
sharedPreset.getAsJsonObject("rawDcpIdsByLens").get("current-camera").asString,
|
||||
)
|
||||
assertEquals("current-hncs", sharedPreset.get("rawHncsProfileId").asString)
|
||||
assertEquals("AdobeCurve", sharedPreset.get("rawRenderingEngine").asString)
|
||||
val backupOnlyPreset = presets[1].asJsonObject
|
||||
assertFalse(backupOnlyPreset.has("rawDcpId"))
|
||||
assertFalse(backupOnlyPreset.has("rawDcpIdsByLens"))
|
||||
assertFalse(backupOnlyPreset.has("rawHncsProfileId"))
|
||||
assertFalse(backupOnlyPreset.has("rawRenderingEngine"))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun sameDeviceRestoreKeepsBackedUpHardwarePreferences() {
|
||||
val restoreDir = temporaryFolder.newFolder("same-device-restore")
|
||||
val datastoreDir = File(restoreDir, "datastore").also { it.mkdirs() }
|
||||
val preferencesFile = File(datastoreDir, "user_preferences.preferences_pb")
|
||||
writePreferenceMap(
|
||||
preferencesFile,
|
||||
PreferenceMap.newBuilder()
|
||||
.putPreferences("preferred_main_camera_id", stringValue("backup-camera"))
|
||||
.putPreferences("keep_screen_on", booleanValue(true))
|
||||
.build(),
|
||||
)
|
||||
|
||||
BackupPreferenceSanitizer.sanitizeRestoreDirectory(
|
||||
restoreDir = restoreDir,
|
||||
currentFilesDir = temporaryFolder.newFolder("unused-current-files"),
|
||||
preserveCurrentDeviceSpecificPreferences = false,
|
||||
)
|
||||
|
||||
val sanitizedMap = FileInputStream(preferencesFile).use(PreferenceMap::parseFrom)
|
||||
assertEquals("backup-camera", sanitizedMap.preferencesMap.getValue("preferred_main_camera_id").string)
|
||||
assertTrue(sanitizedMap.preferencesMap.getValue("keep_screen_on").boolean)
|
||||
}
|
||||
|
||||
private fun writeUserPreferencesFile(file: File): File {
|
||||
val preferenceMap = PreferenceMap.newBuilder()
|
||||
.putPreferences("photo_save_path", stringValue("EXTERNAL_TREE"))
|
||||
@@ -68,10 +171,14 @@ class BackupPreferenceSanitizerTest {
|
||||
.putPreferences("keep_screen_on", booleanValue(true))
|
||||
.build()
|
||||
|
||||
FileOutputStream(file).use { preferenceMap.writeTo(it) }
|
||||
writePreferenceMap(file, preferenceMap)
|
||||
return file
|
||||
}
|
||||
|
||||
private fun writePreferenceMap(file: File, preferenceMap: PreferenceMap) {
|
||||
FileOutputStream(file).use { preferenceMap.writeTo(it) }
|
||||
}
|
||||
|
||||
private fun stringValue(value: String): Value {
|
||||
return Value.newBuilder().setString(value).build()
|
||||
}
|
||||
|
||||
Reference in new issue
Block a user