Modern Apps git

← Modern-Apps.git

findfamily: restore manual backup/restore overflow button (#879)

Commit
21a428f663691c9bd0af7d642de321fd282b921d
Author
Vayun Mathur <[email protected]>
When
2026-10-31 17:34 UTC (1 month ago)
Parents
194eded
Symptom: since v2.6.11 the app offers no manual backup or restore UI, so users who distrusted or could not use OS-triggered systemwide backups had no way to move their family data to a new device (GitHub #879).

Root cause: commit df2edbb04 ('remove un-needed backup buttons') deleted the backup wiring from the map overlay (and sibling apps). Only the UI call sites were cut: the underlying machinery - ZipBackupFormat/BackupHelper in :library, BackupButtons in :library:ui, SqlCipherDbCodec in :library:room, AppBackupAgent, and FindFamilyViewModel.backupPassphrase - all survived untouched.

Fix: new ui/BackupMenuButton.kt renders the singular overflow action in the transparent TopAppBarOverlay (the bar draws no container, so transparency is unchanged) and opens a small dropdown with labelled 'Back up' and 'Restore' items instead of the two bare icon buttons the old menu held. Export uses SAF ACTION_CREATE_DOCUMENT and import uses ACTION_OPEN_DOCUMENT through the shared ZipBackupFormat, with success/failure feedback via AppMessages (no Toast) and an app relaunch after import so the restored files are actually picked up (#548). Wiring threads the existing ViewModel passphrase through MainPageContent into MapOverlayBar as an optional slot, so store-listing previews (which pass null) render unchanged. New domain/FamilyBackup.kt pins the format contract (passwords-db.db plus datastore_default.preferences_pb entries) in one place.

Compatibility: the zip entry names are byte-identical to every backup written since 9db56fb09, so old files restore. Legacy database-only backups (from before the DataStore entry) still restore; the missing store entry is skipped. Schema drift is covered by the existing Room 1..14 migrations on first open. One deliberate addition versus the removed UI: the manual backup now also includes datastore_default (device identity plus E2EE keys), matching what AppBackupAgent already backs up for the OS path - without it a cross-device restore would silently regenerate the identity and orphan every share. Security posture is unchanged from the old UI: the zip holds the decrypted database and is not password-protected, so the file itself must be treated as sensitive.

User-visible effect: the map overlay again shows one overflow button (when nothing is selected); tapping it offers Back up (writes a .zip anywhere the user picks) and Restore (reads one back, then restarts into the restored data).

Verification: :findfamily:compileDevKotlin and :findfamily:testDevUnitTest pass, including 6 new FamilyBackupTest cases (real zip round trip plus legacy db-only recognition); :findfamily:lintDev passes; detekt reports zero findings in the touched files (./check still fails on 12 pre-existing errors in untouched files such as Networking.kt and LocationTrackingInbound.kt). On-device SAF picker flow and an end-to-end restore still need manual testing.

Diff

findfamily/src/main/java/com/vayunmathur/findfamily/domain/FamilyBackup.kt
diff --git a/findfamily/src/main/java/com/vayunmathur/findfamily/domain/FamilyBackup.kt b/findfamily/src/main/java/com/vayunmathur/findfamily/domain/FamilyBackup.ktnew file mode 100644index 0000000000..8034be1343--- /dev/null+++ b/findfamily/src/main/java/com/vayunmathur/findfamily/domain/FamilyBackup.kt@@ -0,0 +1,64 @@+package com.vayunmathur.findfamily.domain++/**+ * Manual backup contract for Find Family.+ *+ * The on-disk format is owned by `:library` ([com.vayunmathur.library.util.BackupHelper]):+ * a zip containing one `<dbName>.db` entry per database plus one `<store>.preferences_pb`+ * entry per DataStore. Those entry names have been stable since the format was+ * introduced ("general: add backup / restore functionality", 9db56fb09), so the+ * literals below double as the compatibility pin: backups written by any older+ * app version restore with the current code, because the reader derives the+ * same names from [dbName]/[datastoreName].+ *+ * The manual backup covers the same payload as the OS-triggered one+ * ([com.vayunmathur.findfamily.util.AppBackupAgent]): the encrypted Room+ * database plus the default DataStore, which holds the stable device identity+ * and the E2EE key material. Pre-removal manual backups contained only the+ * database entry; such legacy files still restore — the missing DataStore+ * entry is simply skipped by the reader.+ */+object FamilyBackup {+    /** Room database name, shared with [com.vayunmathur.findfamily.data.FindFamilyRepository]. */+    const val DB_NAME = "passwords-db"++    /** DataStore holding the device identity and E2EE keys. */+    const val DATASTORE_NAME = "datastore_default"++    /** Zip entry for the (decrypted) database export. */+    fun dbEntryName(dbName: String = DB_NAME): String = "$dbName.db"++    /** Zip entry for a DataStore export. */+    fun datastoreEntryName(storeName: String = DATASTORE_NAME): String = "$storeName.preferences_pb"++    /** Database configs for the backup format: name to SQLCipher passphrase. */+    fun dbConfigs(passphrase: String): List<Pair<String, String>> = listOf(DB_NAME to passphrase)++    /** DataStore names included in the backup. */+    fun datastoreNames(): List<String> = listOf(DATASTORE_NAME)++    /** What a backup zip contains, derived from its entry file names. */+    data class BackupContents(+        val databasePresent: Boolean,+        val datastorePresent: Boolean,+    ) {+        /** A file is restorable if it carries the database; the DataStore is optional. */+        val isRestorable: Boolean get() = databasePresent++        /** Database-only files written before the DataStore was included. */+        val isLegacy: Boolean get() = databasePresent && !datastorePresent+    }++    /**+     * Classifies a backup zip by its entry file names (e.g. `passwords-db.db`,+     * `datastore_default.preferences_pb`). Unknown extra entries are ignored:+     * other apps' files fail [isRestorable] instead of throwing.+     */+    fun describeEntries(entryNames: Collection<String>): BackupContents {+        val names = entryNames.map { it.substringAfterLast('/') }.toSet()+        return BackupContents(+            databasePresent = dbEntryName() in names,+            datastorePresent = datastoreEntryName() in names,+        )+    }+}
findfamily/src/main/java/com/vayunmathur/findfamily/ui/BackupMenuButton.kt
diff --git a/findfamily/src/main/java/com/vayunmathur/findfamily/ui/BackupMenuButton.kt b/findfamily/src/main/java/com/vayunmathur/findfamily/ui/BackupMenuButton.ktnew file mode 100644index 0000000000..3fdfdf9dd1--- /dev/null+++ b/findfamily/src/main/java/com/vayunmathur/findfamily/ui/BackupMenuButton.kt@@ -0,0 +1,162 @@+package com.vayunmathur.findfamily.ui++import androidx.activity.compose.rememberLauncherForActivityResult+import androidx.activity.result.contract.ActivityResultContracts+import androidx.compose.runtime.Composable+import androidx.compose.runtime.remember+import androidx.compose.runtime.rememberCoroutineScope+import androidx.compose.ui.platform.LocalContext+import androidx.compose.ui.res.stringResource+import com.vayunmathur.findfamily.R+import com.vayunmathur.findfamily.domain.FamilyBackup+import com.vayunmathur.library.log.Log+import com.vayunmathur.library.room.SqlCipherDbCodec+import com.vayunmathur.library.ui.DropdownMenu+import com.vayunmathur.library.ui.DropdownMenuItem+import com.vayunmathur.library.ui.IconBackup+import com.vayunmathur.library.ui.IconMoreVert+import com.vayunmathur.library.ui.IconRestore+import com.vayunmathur.library.ui.Text+import com.vayunmathur.library.ui.R as UiR+import com.vayunmathur.library.util.AppMessages+import com.vayunmathur.library.util.BackupFormat+import com.vayunmathur.library.util.ZipBackupFormat+import kotlinx.coroutines.Dispatchers+import kotlinx.coroutines.delay+import kotlinx.coroutines.launch+import kotlinx.coroutines.withContext++/**+ * The map overlay's singular backup entry point: an overflow icon that opens a+ * small menu with "Back up" and "Restore".+ *+ * This restores the manual backup UI removed in df2edbb04 ("remove un-needed+ * backup buttons"), adapted to the current transparent bar: previously the same+ * overflow button held two bare backup/restore icon buttons; now it holds two+ * labelled menu items instead. The bar itself stays container-free+ * ([TopAppBarOverlay] draws no background) — this composable only renders the+ * icon and its dropdown.+ *+ * Export writes a user-chosen file via SAF (`ACTION_CREATE_DOCUMENT`) and+ * import reads one via `ACTION_OPEN_DOCUMENT`, using the same [ZipBackupFormat]+ * every other app uses, so files stay interchangeable with older Find Family+ * backups (see [FamilyBackup] for the format contract). The zip is not+ * password-protected — exactly as before — because the database is decrypted+ * into the zip by [SqlCipherDbCodec]; treat the file as sensitive.+ *+ * @param dbPassphrase SQLCipher passphrase for the database export, read off+ *   the composables (see `FindFamilyViewModel.backupPassphrase`).+ * @param menuExpanded whether the backup/restore menu is open; hoisted so the+ *   overlay action wrapping this icon owns the toggle.+ */+@Composable+fun BackupMenuButton(+    dbPassphrase: String,+    menuExpanded: Boolean,+    onMenuExpandedChange: (Boolean) -> Unit,+) {+    val context = LocalContext.current+    val scope = rememberCoroutineScope()+    val format = remember(dbPassphrase) {+        ZipBackupFormat(+            dbConfigs = FamilyBackup.dbConfigs(dbPassphrase),+            datastoreNames = FamilyBackup.datastoreNames(),+            dbCodec = SqlCipherDbCodec,+        )+    }++    val exportLauncher = rememberLauncherForActivityResult(+        ActivityResultContracts.CreateDocument(format.mimeType)+    ) { uri ->+        uri?.let { scope.launch(Dispatchers.IO) { runBackupExport(context, format, it) } }+    }+    val importLauncher = rememberLauncherForActivityResult(+        ActivityResultContracts.OpenDocument()+    ) { uri ->+        uri?.let { scope.launch(Dispatchers.IO) { runBackupImport(context, format, it) } }+    }++    IconMoreVert()+    DropdownMenu(menuExpanded, { onMenuExpandedChange(false) }) {+        DropdownMenuItem(+            text = { Text(stringResource(R.string.backup_menu_backup)) },+            leadingIcon = { IconBackup() },+            onClick = {+                onMenuExpandedChange(false)+                exportLauncher.launch(format.defaultFileName)+            },+        )+        DropdownMenuItem(+            text = { Text(stringResource(R.string.backup_menu_restore)) },+            leadingIcon = { IconRestore() },+            onClick = {+                onMenuExpandedChange(false)+                importLauncher.launch(arrayOf(format.mimeType))+            },+        )+    }+}++/** Long enough for the import message to be read before the process goes away. */+private const val RESTART_DELAY_MS = 1500L++private fun relaunch(context: android.content.Context) {+    context.packageManager.getLaunchIntentForPackage(context.packageName)?.let { intent ->+        intent.addFlags(+            android.content.Intent.FLAG_ACTIVITY_NEW_TASK or+                android.content.Intent.FLAG_ACTIVITY_CLEAR_TASK+        )+        context.startActivity(intent)+    }+    Runtime.getRuntime().exit(0)+}++// Broad catch is deliberate: export/import cross arbitrary content providers and+// the zip codec, and every failure mode is logged and messaged below.+@Suppress("TooGenericExceptionCaught")+private suspend fun runBackupExport(+    context: android.content.Context,+    format: BackupFormat,+    uri: android.net.Uri,+) {+    try {+        context.contentResolver.openOutputStream(uri)?.use { os ->+            format.export(context, null, os)+        }+        withContext(Dispatchers.Main) {+            AppMessages.show(context.getString(UiR.string.backup_export_success))+        }+    } catch (e: Exception) {+        Log.error("BackupMenuButton", "Export FAILED", e)+        withContext(Dispatchers.Main) {+            AppMessages.show(context.getString(UiR.string.backup_export_failed_format, e.message))+        }+    }+}++@Suppress("TooGenericExceptionCaught")+private suspend fun runBackupImport(+    context: android.content.Context,+    format: BackupFormat,+    uri: android.net.Uri,+) {+    try {+        context.contentResolver.openInputStream(uri)?.use { inputStream ->+            format.import(context, null, inputStream)+        }+        withContext(Dispatchers.Main) {+            AppMessages.show(context.getString(UiR.string.backup_import_success))+        }+        // DataStore and Room assume exclusive ownership of their files and keep the contents+        // cached, so a live process neither picks up the files the import just replaced nor stops+        // writing the pre-restore state back over them - which silently undid the restore before+        // the user got round to restarting (#548). Give the message a moment, then relaunch.+        delay(RESTART_DELAY_MS)+        withContext(Dispatchers.Main) { relaunch(context) }+    } catch (e: Exception) {+        Log.error("BackupMenuButton", "Import FAILED", e)+        withContext(Dispatchers.Main) {+            AppMessages.show(context.getString(UiR.string.backup_import_failed_format, e.message))+        }+    }+}
findfamily/src/main/java/com/vayunmathur/findfamily/ui/MainPage.kt
diff --git a/findfamily/src/main/java/com/vayunmathur/findfamily/ui/MainPage.kt b/findfamily/src/main/java/com/vayunmathur/findfamily/ui/MainPage.ktindex 0744eb8a9f..9cc6b900d2 100644--- a/findfamily/src/main/java/com/vayunmathur/findfamily/ui/MainPage.kt+++ b/findfamily/src/main/java/com/vayunmathur/findfamily/ui/MainPage.kt@@ -290,6 +290,7 @@ fun MainPage(         familyActions = familyActions,         personActions = personActions,         actions = mainActions,+        backupPassphrase = ffViewModel.backupPassphrase,         historyScrubber = {             if (historyMode) {                 // Scoped to the person: a deep link can swap the selection while history
findfamily/src/main/java/com/vayunmathur/findfamily/ui/MainPageContent.kt
diff --git a/findfamily/src/main/java/com/vayunmathur/findfamily/ui/MainPageContent.kt b/findfamily/src/main/java/com/vayunmathur/findfamily/ui/MainPageContent.ktindex 55d484c5a2..551abb7226 100644--- a/findfamily/src/main/java/com/vayunmathur/findfamily/ui/MainPageContent.kt+++ b/findfamily/src/main/java/com/vayunmathur/findfamily/ui/MainPageContent.kt@@ -43,6 +43,7 @@ fun MainPageContent(     actions: MainPageActions,     map: @Composable () -> Unit,     historyScrubber: @Composable BoxScope.() -> Unit = {},+    backupPassphrase: String? = null, ) {     val scaffoldState = rememberBottomSheetScaffoldState() @@ -173,7 +174,7 @@ fun MainPageContent(             // light, whatever the app's theme.             Box(Modifier.align(Alignment.TopCenter).fillMaxWidth()) {                 MaterialTheme(colorScheme = lightScheme) {-                    MapOverlayBar(state, actions)+                    MapOverlayBar(state, actions, backupPassphrase)                 }             } 
findfamily/src/main/java/com/vayunmathur/findfamily/ui/MainPageOverlays.kt
diff --git a/findfamily/src/main/java/com/vayunmathur/findfamily/ui/MainPageOverlays.kt b/findfamily/src/main/java/com/vayunmathur/findfamily/ui/MainPageOverlays.ktindex f8ac97ff27..06e75a4ffd 100644--- a/findfamily/src/main/java/com/vayunmathur/findfamily/ui/MainPageOverlays.kt+++ b/findfamily/src/main/java/com/vayunmathur/findfamily/ui/MainPageOverlays.kt@@ -10,6 +10,8 @@ import com.vayunmathur.library.ui.Spacing import com.vayunmathur.library.ui.TopAppBarOverlay import androidx.compose.runtime.Composable import androidx.compose.runtime.getValue+import androidx.compose.runtime.mutableStateOf+import androidx.compose.runtime.remember import androidx.compose.runtime.setValue import androidx.compose.ui.Modifier import androidx.compose.ui.res.stringResource@@ -26,9 +28,12 @@ import com.vayunmathur.library.ui.IconVerify internal fun MapOverlayBar(     state: MainPageUiState,     actions: MainPageActions,+    backupPassphrase: String? = null, ) {+    var backupMenuExpanded by remember { mutableStateOf(false) }      val gpsWarningDescription = stringResource(R.string.gps_fallback_warning_content_description)+    val menuDescription = stringResource(R.string.map_menu_content_description)     val findNearbyDescription = stringResource(R.string.find_nearby_content_description)     val verifyDescription = stringResource(R.string.verify_security_code_content_description)     val deletePersonDescription = stringResource(R.string.delete_person_content_description)@@ -53,7 +58,19 @@ internal fun MapOverlayBar(                         contentDescription = gpsWarningDescription,                         onClick = { actions.onGpsWarningClick() }                     )-                } else null+                } else null,+                // Singular backup entry point: one overflow button whose menu holds+                // "Back up" and "Restore" (GitHub #879). Null in previews, where no+                // passphrase exists and the button stays hidden.+                backupPassphrase?.let { passphrase ->+                    OverlayAction(+                        icon = {+                            BackupMenuButton(passphrase, backupMenuExpanded, { backupMenuExpanded = it })+                        },+                        contentDescription = menuDescription,+                        onClick = { backupMenuExpanded = !backupMenuExpanded }+                    )+                }             )         } else if (selectedUserId != null && !state.historyMode) {             if (state.isSelfSelected) emptyList() else listOfNotNull(
findfamily/src/main/res/values/strings.xml
diff --git a/findfamily/src/main/res/values/strings.xml b/findfamily/src/main/res/values/strings.xmlindex 6cc875e24f..15cbb3a2b2 100644--- a/findfamily/src/main/res/values/strings.xml+++ b/findfamily/src/main/res/values/strings.xml@@ -287,6 +287,10 @@     <string name="gps_fallback_warning_content_description">Network location unavailable</string>     <!-- MainPage: Content description for the overflow button on the map that opens the backup and restore actions. Noun phrase -->     <string name="map_menu_content_description">More options</string>+    <!-- BackupMenuButton: Menu item that exports the database and settings to a user-chosen file. Verb phrase -->+    <string name="backup_menu_backup">Back up</string>+    <!-- BackupMenuButton: Menu item that restores a previously exported backup file. Verb phrase -->+    <string name="backup_menu_restore">Restore</string>     <!-- MainPage: Content description for the map overlay button that starts Find Nearby (UWB) for the selected person. Verb phrase -->     <string name="find_nearby_content_description">Find nearby</string>     <!-- MainPage: Content description for the map overlay button that shows the end-to-end encryption security code for the selected person. Verb phrase -->
findfamily/src/test/java/com/vayunmathur/findfamily/domain/FamilyBackupTest.kt
diff --git a/findfamily/src/test/java/com/vayunmathur/findfamily/domain/FamilyBackupTest.kt b/findfamily/src/test/java/com/vayunmathur/findfamily/domain/FamilyBackupTest.ktnew file mode 100644index 0000000000..3ec7d92e92--- /dev/null+++ b/findfamily/src/test/java/com/vayunmathur/findfamily/domain/FamilyBackupTest.kt@@ -0,0 +1,115 @@+package com.vayunmathur.findfamily.domain++import com.vayunmathur.library.util.BackupHelper+import java.io.ByteArrayInputStream+import java.io.ByteArrayOutputStream+import java.io.File+import java.nio.file.Files+import kotlin.test.Test+import kotlin.test.assertContentEquals+import kotlin.test.assertEquals+import kotlin.test.assertFalse+import kotlin.test.assertTrue++/**+ * Pure-JVM tests for the manual backup contract ([FamilyBackup]).+ *+ * The zip layer under test is the real [BackupHelper] used on device — only+ * the database codec is stood in for with raw bytes, because SQLCipher needs a+ * device. Every case builds its zip with the historic entry names, so a rename+ * that would orphan older backup files fails here first.+ */+class FamilyBackupTest {++    private val dbBytes = "fake-sqlite-payload-v14".toByteArray()+    private val datastoreBytes = "fake-datastore-identity".toByteArray()++    /** Zips [files] (sitting in [baseDir]) and returns the unzipped name→bytes map. */+    private fun roundTrip(files: List<File>, baseDir: File): Map<String, ByteArray> {+        val zipped = ByteArrayOutputStream().also { BackupHelper.zipFiles(files, baseDir, it) }.toByteArray()+        val outDir = Files.createTempDirectory("ff-restore").toFile()+        try {+            BackupHelper.unzipFiles(ByteArrayInputStream(zipped), outDir)+            return outDir.walkTopDown().filter { it.isFile }.associate { it.name to it.readBytes() }+        } finally {+            outDir.deleteRecursively()+        }+    }++    private fun stageDir(block: (File) -> List<File>): Pair<List<File>, File> {+        val dir = Files.createTempDirectory("ff-backup").toFile()+        return try {+            block(dir) to dir+        } catch (e: Exception) {+            dir.deleteRecursively()+            throw e+        }+    }++    // --- config builders ---++    @Test+    fun dbConfigsCarryHistoricDbName() {+        assertEquals(listOf("passwords-db" to "pw"), FamilyBackup.dbConfigs("pw"))+    }++    @Test+    fun datastoreNamesCarryDefaultStore() {+        assertEquals(listOf("datastore_default"), FamilyBackup.datastoreNames())+    }++    // --- serialize / deserialize round trip ---++    @Test+    fun fullBackupRoundTripsThroughRealZipLayer() {+        val (files, dir) = stageDir { d ->+            listOf(+                File(d, FamilyBackup.dbEntryName()).apply { writeBytes(dbBytes) },+                File(d, FamilyBackup.datastoreEntryName()).apply { writeBytes(datastoreBytes) },+            )+        }+        try {+            val restored = roundTrip(files, dir)+            assertContentEquals(dbBytes, restored[FamilyBackup.dbEntryName()])+            assertContentEquals(datastoreBytes, restored[FamilyBackup.datastoreEntryName()])+            val contents = FamilyBackup.describeEntries(restored.keys)+            assertTrue(contents.isRestorable)+            assertFalse(contents.isLegacy)+        } finally {+            dir.deleteRecursively()+        }+    }++    // --- legacy-format restore ---++    @Test+    fun legacyDatabaseOnlyBackupIsRecognizedAndRestorable() {+        // What backups looked like before the DataStore entry was added: the+        // reader must still accept them (the missing store is skipped on import).+        val (files, dir) = stageDir { d ->+            listOf(File(d, FamilyBackup.dbEntryName()).apply { writeBytes(dbBytes) })+        }+        try {+            val restored = roundTrip(files, dir)+            assertContentEquals(dbBytes, restored[FamilyBackup.dbEntryName()])+            val contents = FamilyBackup.describeEntries(restored.keys)+            assertTrue(contents.isRestorable)+            assertTrue(contents.isLegacy)+        } finally {+            dir.deleteRecursively()+        }+    }++    @Test+    fun foreignFileIsNotRestorable() {+        val contents = FamilyBackup.describeEntries(listOf("notes-backup.zip", "photo.jpg"))+        assertFalse(contents.isRestorable)+        assertFalse(contents.isLegacy)+    }++    @Test+    fun emptyBackupIsNotRestorable() {+        val contents = FamilyBackup.describeEntries(emptyList())+        assertFalse(contents.isRestorable)+    }+}