From fe59ee6e5914eab5c636ae2d496b50715ae7215e Mon Sep 17 00:00:00 2001 From: Jean-Luc Makiola Date: Tue, 17 Nov 2026 10:59:21 +0100 Subject: [PATCH 1/4] Add automatic backup (#77) --- CHANGELOG.md | 6 + .../de/jeanlucmakiola/agendula/AgendulaApp.kt | 3 + .../jeanlucmakiola/agendula/MainActivity.kt | 7 + .../agendula/data/backup/AutoBackupPolicy.kt | 49 ++++ .../agendula/data/backup/AutoBackupPrefs.kt | 103 ++++++++ .../data/backup/AutoBackupScheduler.kt | 77 ++++++ .../agendula/data/backup/AutoBackupWorker.kt | 69 ++++++ .../agendula/data/backup/BackupNotifier.kt | 99 ++++++++ .../agendula/data/export/ExportWriter.kt | 65 ++++- .../agendula/ui/export/ExportScreen.kt | 2 +- .../agendula/ui/navigation/AgendulaNavHost.kt | 2 + .../agendula/ui/navigation/Destinations.kt | 1 + .../agendula/ui/navigation/NavRequest.kt | 3 + .../ui/settings/AutoBackupViewModel.kt | 77 ++++++ .../agendula/ui/settings/BackupScreen.kt | 232 +++++++++++++++++- app/src/main/res/values/strings.xml | 38 ++- .../data/backup/AutoBackupPolicyTest.kt | 60 +++++ 17 files changed, 878 insertions(+), 15 deletions(-) create mode 100644 app/src/main/java/de/jeanlucmakiola/agendula/data/backup/AutoBackupPolicy.kt create mode 100644 app/src/main/java/de/jeanlucmakiola/agendula/data/backup/AutoBackupPrefs.kt create mode 100644 app/src/main/java/de/jeanlucmakiola/agendula/data/backup/AutoBackupScheduler.kt create mode 100644 app/src/main/java/de/jeanlucmakiola/agendula/data/backup/AutoBackupWorker.kt create mode 100644 app/src/main/java/de/jeanlucmakiola/agendula/data/backup/BackupNotifier.kt create mode 100644 app/src/main/java/de/jeanlucmakiola/agendula/ui/settings/AutoBackupViewModel.kt create mode 100644 app/src/test/java/de/jeanlucmakiola/agendula/data/backup/AutoBackupPolicyTest.kt diff --git a/CHANGELOG.md b/CHANGELOG.md index 67c3d4b..07bc8db 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -7,6 +7,12 @@ All notable changes to this project are documented here. The format follows ## [Unreleased] +### Added +- Automatic backup. Settings → Backup & restore can save all your lists as a + dated zip into a folder you pick, every few hours, days or weeks, and keeps + only the latest few (7 by default). Restore one with Import tasks. A + notification says so if backups keep failing (#77). + ## [1.3.2] - 2026-11-13 ### Added diff --git a/app/src/main/java/de/jeanlucmakiola/agendula/AgendulaApp.kt b/app/src/main/java/de/jeanlucmakiola/agendula/AgendulaApp.kt index 8c9d05f..94fe777 100644 --- a/app/src/main/java/de/jeanlucmakiola/agendula/AgendulaApp.kt +++ b/app/src/main/java/de/jeanlucmakiola/agendula/AgendulaApp.kt @@ -9,6 +9,7 @@ import dagger.hilt.InstallIn import dagger.hilt.android.EntryPointAccessors import dagger.hilt.android.HiltAndroidApp import dagger.hilt.components.SingletonComponent +import de.jeanlucmakiola.agendula.data.backup.AutoBackupScheduler import de.jeanlucmakiola.agendula.data.di.ApplicationScope import de.jeanlucmakiola.agendula.data.di.ChannelRefresher import de.jeanlucmakiola.agendula.data.reminders.ReminderMaintenanceWorker @@ -89,6 +90,7 @@ class AgendulaApp : Application(), Configuration.Provider { runCatching { entryPoint.reminderRefresher().start() } runCatching { entryPoint.providerSnapshotSource().start() } runCatching { ReminderMaintenanceWorker.schedule(this@AgendulaApp) } + runCatching { entryPoint.autoBackupScheduler().start() } } } @@ -125,5 +127,6 @@ class AgendulaApp : Application(), Configuration.Provider { fun taskWidgetUpdater(): TaskWidgetUpdater fun reminderRefresher(): ReminderRefresher fun providerSnapshotSource(): ProviderSnapshotSource + fun autoBackupScheduler(): AutoBackupScheduler } } diff --git a/app/src/main/java/de/jeanlucmakiola/agendula/MainActivity.kt b/app/src/main/java/de/jeanlucmakiola/agendula/MainActivity.kt index 0a0abd0..23572be 100644 --- a/app/src/main/java/de/jeanlucmakiola/agendula/MainActivity.kt +++ b/app/src/main/java/de/jeanlucmakiola/agendula/MainActivity.kt @@ -155,6 +155,7 @@ class MainActivity : ComponentActivity() { const val EXTRA_TASK_ID = "de.jeanlucmakiola.agendula.extra.TASK_ID" const val EXTRA_OCCURRENCE_START = "de.jeanlucmakiola.agendula.extra.OCCURRENCE_START" private const val EXTRA_OPEN_ACCOUNTS = "de.jeanlucmakiola.agendula.extra.OPEN_ACCOUNTS" + private const val ACTION_OPEN_BACKUP = "de.jeanlucmakiola.agendula.action.OPEN_BACKUP" /** The account a sign-in notification is about, on the intent it opens. */ const val EXTRA_SIGN_IN_ACCOUNT_ID = "de.jeanlucmakiola.agendula.extra.SIGN_IN_ACCOUNT_ID" @@ -195,6 +196,11 @@ class MainActivity : ComponentActivity() { .putExtra(EXTRA_OPEN_ACCOUNTS, true) .addFlags(Intent.FLAG_ACTIVITY_NEW_TASK) + /** Opens Settings → Backup & restore, where a failing automatic backup is fixed. */ + fun backupIntent(context: Context): Intent = + Intent(ACTION_OPEN_BACKUP, null, context, MainActivity::class.java) + .addFlags(Intent.FLAG_ACTIVITY_NEW_TASK) + /** * The launcher shortcut's, Quick Settings tile's and a widget's "New * task". [listId] preset the list when it names exactly one, [dueToday] @@ -245,6 +251,7 @@ class MainActivity : ComponentActivity() { returnHome = true, ) ACTION_TODAY -> return NavRequest.OpenSmart(SmartList.TODAY) + ACTION_OPEN_BACKUP -> return NavRequest.OpenBackup ACTION_OPEN_SMART -> intent.getStringExtra(EXTRA_SMART_LIST) ?.let { name -> SmartList.entries.firstOrNull { it.name == name } } ?.let { return NavRequest.OpenSmart(it) } diff --git a/app/src/main/java/de/jeanlucmakiola/agendula/data/backup/AutoBackupPolicy.kt b/app/src/main/java/de/jeanlucmakiola/agendula/data/backup/AutoBackupPolicy.kt new file mode 100644 index 0000000..92067e5 --- /dev/null +++ b/app/src/main/java/de/jeanlucmakiola/agendula/data/backup/AutoBackupPolicy.kt @@ -0,0 +1,49 @@ +package de.jeanlucmakiola.agendula.data.backup + +import java.time.LocalDateTime +import java.time.format.DateTimeFormatter +import java.util.Locale + +/** + * The rules of the automatic backup that need no Android: how a backup file is + * named, which ones rotation removes, and the bounds of the user's choices. + * + * Rotation only ever touches files whose name matches [fileName]'s pattern, so + * anything else the user keeps in the same folder is safe. + */ +object AutoBackupPolicy { + + const val DEFAULT_INTERVAL_MINUTES = 1_440 + const val MIN_INTERVAL_MINUTES = 60 + const val MAX_INTERVAL_MINUTES = 999 * 10_080 + + /** Every 6 and 12 hours, daily, weekly. */ + val INTERVAL_PRESETS = listOf(360, 720, 1_440, 10_080) + + const val DEFAULT_KEEP = 7 + const val MAX_KEEP = 999 + val KEEP_PRESETS = listOf(3, 7, 14, 30) + + private const val PREFIX = "agendula-backup-" + private const val EXTENSION = ".zip" + private val STAMP = DateTimeFormatter.ofPattern("uuuu-MM-dd-HHmmss", Locale.ROOT) + private val NAME = Regex("""agendula-backup-(\d{4}-\d{2}-\d{2}-\d{6})\.zip""") + + /** `agendula-backup-2026-11-17-143005.zip`: sortable, and readable in a file manager. */ + fun fileName(at: LocalDateTime): String = PREFIX + STAMP.format(at) + EXTENSION + + /** When the backup named [name] was taken, or null when it is not one of ours. */ + fun timestampOf(name: String): LocalDateTime? = + NAME.matchEntire(name)?.let { runCatching { LocalDateTime.parse(it.groupValues[1], STAMP) }.getOrNull() } + + /** The backups in [names] beyond the newest [keep], oldest last. */ + fun staleBackups(names: Collection, keep: Int): List = + names.mapNotNull { name -> timestampOf(name)?.let { name to it } } + .sortedByDescending { it.second } + .drop(clampKeep(keep)) + .map { it.first } + + fun clampInterval(minutes: Int): Int = minutes.coerceIn(MIN_INTERVAL_MINUTES, MAX_INTERVAL_MINUTES) + + fun clampKeep(count: Int): Int = count.coerceIn(1, MAX_KEEP) +} diff --git a/app/src/main/java/de/jeanlucmakiola/agendula/data/backup/AutoBackupPrefs.kt b/app/src/main/java/de/jeanlucmakiola/agendula/data/backup/AutoBackupPrefs.kt new file mode 100644 index 0000000..74a06fd --- /dev/null +++ b/app/src/main/java/de/jeanlucmakiola/agendula/data/backup/AutoBackupPrefs.kt @@ -0,0 +1,103 @@ +package de.jeanlucmakiola.agendula.data.backup + +import androidx.datastore.core.DataStore +import androidx.datastore.preferences.core.Preferences +import androidx.datastore.preferences.core.booleanPreferencesKey +import androidx.datastore.preferences.core.edit +import androidx.datastore.preferences.core.intPreferencesKey +import androidx.datastore.preferences.core.longPreferencesKey +import androidx.datastore.preferences.core.stringPreferencesKey +import de.jeanlucmakiola.agendula.data.export.ExportFailure +import kotlinx.coroutines.flow.Flow +import kotlinx.coroutines.flow.distinctUntilChanged +import kotlinx.coroutines.flow.map +import javax.inject.Inject +import javax.inject.Singleton + +/** What the automatic backup does: [folderUri] is a persisted SAF tree grant. */ +data class AutoBackupConfig( + val enabled: Boolean = false, + val folderUri: String? = null, + val intervalMinutes: Int = AutoBackupPolicy.DEFAULT_INTERVAL_MINUTES, + val keepCount: Int = AutoBackupPolicy.DEFAULT_KEEP, +) { + /** Whether there is anything to schedule. */ + val active: Boolean get() = enabled && folderUri != null +} + +/** How the last automatic backup went; [lastRunMillis] 0 = never ran. */ +data class AutoBackupStatus( + val lastRunMillis: Long = 0L, + val lastSuccess: Boolean = false, + val consecutiveFailures: Int = 0, + val failure: ExportFailure? = null, +) + +/** The automatic backup's settings and last outcome, in the app's DataStore. */ +@Singleton +class AutoBackupPrefs @Inject constructor( + private val dataStore: DataStore, +) { + val config: Flow = dataStore.data.map { p -> + AutoBackupConfig( + enabled = p[ENABLED] ?: false, + folderUri = p[FOLDER], + intervalMinutes = p[INTERVAL]?.let(AutoBackupPolicy::clampInterval) + ?: AutoBackupPolicy.DEFAULT_INTERVAL_MINUTES, + keepCount = p[KEEP]?.let(AutoBackupPolicy::clampKeep) ?: AutoBackupPolicy.DEFAULT_KEEP, + ) + }.distinctUntilChanged() + + val status: Flow = dataStore.data.map { p -> + AutoBackupStatus( + lastRunMillis = p[LAST_RUN] ?: 0L, + lastSuccess = p[LAST_SUCCESS] ?: false, + consecutiveFailures = p[FAILURES] ?: 0, + failure = p[FAILURE_REASON]?.let { runCatching { ExportFailure.valueOf(it) }.getOrNull() }, + ) + }.distinctUntilChanged() + + suspend fun setEnabled(enabled: Boolean) = dataStore.edit { it[ENABLED] = enabled } + + /** Points the backup at [uri] and turns it on; the caller has taken the grant. */ + suspend fun setFolder(uri: String) = dataStore.edit { + it[FOLDER] = uri + it[ENABLED] = true + } + + suspend fun setIntervalMinutes(minutes: Int) = + dataStore.edit { it[INTERVAL] = AutoBackupPolicy.clampInterval(minutes) } + + suspend fun setKeepCount(count: Int) = dataStore.edit { it[KEEP] = AutoBackupPolicy.clampKeep(count) } + + suspend fun recordSuccess(atMillis: Long) = dataStore.edit { + it[LAST_RUN] = atMillis + it[LAST_SUCCESS] = true + it[FAILURES] = 0 + it.remove(FAILURE_REASON) + } + + /** Returns how many runs in a row have now failed. */ + suspend fun recordFailure(atMillis: Long, reason: ExportFailure): Int { + var failures = 0 + dataStore.edit { + failures = (it[FAILURES] ?: 0) + 1 + it[LAST_RUN] = atMillis + it[LAST_SUCCESS] = false + it[FAILURES] = failures + it[FAILURE_REASON] = reason.name + } + return failures + } + + private companion object { + val ENABLED = booleanPreferencesKey("auto_backup_enabled") + val FOLDER = stringPreferencesKey("auto_backup_folder") + val INTERVAL = intPreferencesKey("auto_backup_interval_minutes") + val KEEP = intPreferencesKey("auto_backup_keep") + val LAST_RUN = longPreferencesKey("auto_backup_last_run") + val LAST_SUCCESS = booleanPreferencesKey("auto_backup_last_success") + val FAILURES = intPreferencesKey("auto_backup_failures") + val FAILURE_REASON = stringPreferencesKey("auto_backup_failure_reason") + } +} diff --git a/app/src/main/java/de/jeanlucmakiola/agendula/data/backup/AutoBackupScheduler.kt b/app/src/main/java/de/jeanlucmakiola/agendula/data/backup/AutoBackupScheduler.kt new file mode 100644 index 0000000..122f73b --- /dev/null +++ b/app/src/main/java/de/jeanlucmakiola/agendula/data/backup/AutoBackupScheduler.kt @@ -0,0 +1,77 @@ +package de.jeanlucmakiola.agendula.data.backup + +import android.content.Context +import androidx.work.ExistingPeriodicWorkPolicy +import androidx.work.ExistingWorkPolicy +import androidx.work.OneTimeWorkRequestBuilder +import androidx.work.PeriodicWorkRequestBuilder +import androidx.work.WorkInfo +import androidx.work.WorkManager +import dagger.hilt.android.qualifiers.ApplicationContext +import de.jeanlucmakiola.agendula.data.di.ApplicationScope +import kotlinx.coroutines.CoroutineScope +import kotlinx.coroutines.flow.Flow +import kotlinx.coroutines.flow.distinctUntilChanged +import kotlinx.coroutines.flow.map +import kotlinx.coroutines.launch +import java.util.concurrent.TimeUnit +import javax.inject.Inject +import javax.inject.Singleton + +/** + * Keeps WorkManager in step with [AutoBackupPrefs]: a unique periodic request + * while the backup is on and has a folder, nothing otherwise. Reactive, so every + * settings change (and every launch) reconciles without the caller having to. + */ +@Singleton +class AutoBackupScheduler @Inject constructor( + @ApplicationContext private val context: Context, + private val prefs: AutoBackupPrefs, + @ApplicationScope private val scope: CoroutineScope, +) { + + /** Call once, from `Application.onCreate`. */ + fun start() { + scope.launch { + prefs.config + .map { if (it.active) it.intervalMinutes else null } + .distinctUntilChanged() + .collect { interval -> runCatching { apply(interval) } } + } + } + + /** One backup now, e.g. right after a folder is picked. Rapid taps coalesce. */ + fun runNow() { + WorkManager.getInstance(context).enqueueUniqueWork( + WORK_NAME_NOW, + ExistingWorkPolicy.KEEP, + OneTimeWorkRequestBuilder().build(), + ) + } + + /** Whether a [runNow] backup is queued or running. */ + val runningNow: Flow = + WorkManager.getInstance(context).getWorkInfosForUniqueWorkFlow(WORK_NAME_NOW) + .map { infos -> infos.any { !it.state.isFinished && it.state != WorkInfo.State.BLOCKED } } + .distinctUntilChanged() + + /** [intervalMinutes] null cancels. The first periodic run waits one interval. */ + private fun apply(intervalMinutes: Int?) { + val workManager = WorkManager.getInstance(context) + if (intervalMinutes == null) { + workManager.cancelUniqueWork(WORK_NAME) + workManager.cancelUniqueWork(WORK_NAME_NOW) + return + } + val minutes = intervalMinutes.toLong() + val request = PeriodicWorkRequestBuilder(minutes, TimeUnit.MINUTES) + .setInitialDelay(minutes, TimeUnit.MINUTES) + .build() + workManager.enqueueUniquePeriodicWork(WORK_NAME, ExistingPeriodicWorkPolicy.UPDATE, request) + } + + private companion object { + const val WORK_NAME = "auto-backup" + const val WORK_NAME_NOW = "auto-backup-now" + } +} diff --git a/app/src/main/java/de/jeanlucmakiola/agendula/data/backup/AutoBackupWorker.kt b/app/src/main/java/de/jeanlucmakiola/agendula/data/backup/AutoBackupWorker.kt new file mode 100644 index 0000000..99eb540 --- /dev/null +++ b/app/src/main/java/de/jeanlucmakiola/agendula/data/backup/AutoBackupWorker.kt @@ -0,0 +1,69 @@ +package de.jeanlucmakiola.agendula.data.backup + +import android.content.Context +import android.util.Log +import androidx.core.net.toUri +import androidx.hilt.work.HiltWorker +import androidx.work.CoroutineWorker +import androidx.work.WorkerParameters +import dagger.assisted.Assisted +import dagger.assisted.AssistedInject +import de.jeanlucmakiola.agendula.data.export.ExportFailedException +import de.jeanlucmakiola.agendula.data.export.ExportFailure +import de.jeanlucmakiola.agendula.data.export.ExportWriter +import de.jeanlucmakiola.agendula.data.export.TaskExporter +import de.jeanlucmakiola.agendula.data.tasks.StartupGate +import kotlinx.coroutines.flow.first +import java.time.LocalDateTime +import kotlin.coroutines.cancellation.CancellationException + +/** + * One automatic backup: every list of the current store, as the export's zip, + * into a new dated file in the chosen folder, then rotation down to the kept + * count. A failure is recorded for the settings status line and, once it + * repeats, raised as a notification; a periodic request still runs next time. + */ +@HiltWorker +class AutoBackupWorker @AssistedInject constructor( + @Assisted context: Context, + @Assisted params: WorkerParameters, + private val prefs: AutoBackupPrefs, + private val startupGate: StartupGate, + private val exporter: TaskExporter, + private val writer: ExportWriter, + private val notifier: BackupNotifier, +) : CoroutineWorker(context, params) { + + override suspend fun doWork(): Result { + val config = prefs.config.first() + // Turned off since this was queued: nothing to do, and nothing to retry. + val folder = config.folderUri?.takeIf { config.enabled } ?: return Result.success() + val now = System.currentTimeMillis() + return try { + startupGate.awaitReady() + val documents = exporter.export() + // No lists means nothing worth keeping; writing an empty backup would + // rotate the real ones out of the folder. + if (documents.isNotEmpty()) { + val tree = folder.toUri() + writer.writeZipToTree(tree, AutoBackupPolicy.fileName(LocalDateTime.now()), documents) + writer.deleteFromTree(tree) { names -> AutoBackupPolicy.staleBackups(names, config.keepCount) } + } + prefs.recordSuccess(now) + notifier.cancelFailure() + Result.success() + } catch (cancelled: CancellationException) { + throw cancelled + } catch (error: Exception) { + Log.w(TAG, "Automatic backup failed", error) + val reason = (error as? ExportFailedException)?.failure ?: ExportFailure.WRITE_FAILED + if (prefs.recordFailure(now, reason) >= FAILURE_NOTIFY_THRESHOLD) notifier.postFailure() + Result.failure() + } + } + + private companion object { + const val TAG = "AutoBackupWorker" + const val FAILURE_NOTIFY_THRESHOLD = 2 + } +} diff --git a/app/src/main/java/de/jeanlucmakiola/agendula/data/backup/BackupNotifier.kt b/app/src/main/java/de/jeanlucmakiola/agendula/data/backup/BackupNotifier.kt new file mode 100644 index 0000000..eb61bf2 --- /dev/null +++ b/app/src/main/java/de/jeanlucmakiola/agendula/data/backup/BackupNotifier.kt @@ -0,0 +1,99 @@ +package de.jeanlucmakiola.agendula.data.backup + +import android.Manifest +import android.annotation.SuppressLint +import android.app.NotificationChannel +import android.app.NotificationManager +import android.app.PendingIntent +import android.content.Context +import android.content.pm.PackageManager +import android.os.Build +import androidx.core.app.NotificationCompat +import androidx.core.app.NotificationManagerCompat +import androidx.core.content.ContextCompat +import dagger.Binds +import dagger.Module +import dagger.hilt.InstallIn +import dagger.hilt.android.qualifiers.ApplicationContext +import dagger.hilt.components.SingletonComponent +import dagger.multibindings.IntoSet +import de.jeanlucmakiola.agendula.MainActivity +import de.jeanlucmakiola.agendula.R +import de.jeanlucmakiola.agendula.data.di.ChannelRefresher +import javax.inject.Inject +import javax.inject.Singleton + +/** + * Says so when automatic backups keep failing — a revoked folder grant or an + * unmounted SD card would otherwise go unnoticed until the backup is needed. + * Its own low-importance channel, so it can be silenced on its own. + */ +@Singleton +class BackupNotifier @Inject constructor( + @ApplicationContext private val context: Context, +) : ChannelRefresher { + + private fun canPost(): Boolean { + val granted = Build.VERSION.SDK_INT < Build.VERSION_CODES.TIRAMISU || + ContextCompat.checkSelfPermission(context, Manifest.permission.POST_NOTIFICATIONS) == + PackageManager.PERMISSION_GRANTED + return granted && NotificationManagerCompat.from(context).areNotificationsEnabled() + } + + // canPost() checks POST_NOTIFICATIONS before we ever call notify(). + @SuppressLint("MissingPermission") + fun postFailure() { + if (!canPost()) return + ensureChannel() + val notification = NotificationCompat.Builder(context, CHANNEL_ID) + .setSmallIcon(R.drawable.ic_notification) + .setContentTitle(context.getString(R.string.backup_failed_title)) + .setContentText(context.getString(R.string.backup_failed_text)) + .setCategory(NotificationCompat.CATEGORY_ERROR) + .setPriority(NotificationCompat.PRIORITY_LOW) + .setAutoCancel(true) + .setContentIntent( + PendingIntent.getActivity( + context, + NOTIFICATION_ID, + MainActivity.backupIntent(context), + PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_IMMUTABLE, + ), + ) + .build() + runCatching { NotificationManagerCompat.from(context).notify(NOTIFICATION_ID, notification) } + } + + fun cancelFailure() { + NotificationManagerCompat.from(context).cancel(NOTIFICATION_ID) + } + + private fun ensureChannel() { + context.getSystemService(NotificationManager::class.java).createNotificationChannel( + NotificationChannel( + CHANNEL_ID, + context.getString(R.string.backup_channel_name), + NotificationManager.IMPORTANCE_LOW, + ).apply { description = context.getString(R.string.backup_channel_description) }, + ) + } + + /** Re-create the channel, if it exists, in the current language. */ + override fun refreshChannel() { + val manager = context.getSystemService(NotificationManager::class.java) + if (manager.getNotificationChannel(CHANNEL_ID) != null) ensureChannel() + } + + private companion object { + const val CHANNEL_ID = "auto_backup" + const val NOTIFICATION_ID = 5 + } +} + +@Module +@InstallIn(SingletonComponent::class) +abstract class BackupModule { + @Binds + @IntoSet + abstract fun bindBackupChannel(impl: BackupNotifier): ChannelRefresher +} diff --git a/app/src/main/java/de/jeanlucmakiola/agendula/data/export/ExportWriter.kt b/app/src/main/java/de/jeanlucmakiola/agendula/data/export/ExportWriter.kt index 849dd0e..52de154 100644 --- a/app/src/main/java/de/jeanlucmakiola/agendula/data/export/ExportWriter.kt +++ b/app/src/main/java/de/jeanlucmakiola/agendula/data/export/ExportWriter.kt @@ -72,9 +72,7 @@ class ExportWriter @Inject constructor( suspend fun writeToTree(treeUri: Uri, documents: List): ExportResult = withContext(io) { runCatching { - val tree = DocumentFile.fromTreeUri(context, treeUri) - ?: throw ExportFailedException(ExportFailure.FOLDER_UNAVAILABLE) - if (!tree.canWrite()) throw ExportFailedException(ExportFailure.FOLDER_NOT_WRITABLE) + val tree = openWritableTree(treeUri) val existing = tree.listFiles().associateBy { it.name } documents.forEach { document -> @@ -94,21 +92,63 @@ class ExportWriter @Inject constructor( * themselves — one attachment rather than one per list. */ suspend fun writeZip(target: Uri, documents: List): ExportResult = + withContext(io) { + runCatching { zipInto(target, documents) }.getOrElse { throw asExportFailure(it) } + ExportResult(documents.size, documents.map { it.fileName }) + } + + /** + * Writes every document into a new zip named [fileName] inside [treeUri]. + * A zip that could not be written completely is removed again, so a failed + * run never leaves a truncated file that looks like a backup. + */ + suspend fun writeZipToTree(treeUri: Uri, fileName: String, documents: List): ExportResult = withContext(io) { runCatching { - context.contentResolver.openOutputStream(target, "wt")?.use { raw -> - ZipOutputStream(raw.buffered()).use { zip -> - documents.forEach { document -> - zip.putNextEntry(ZipEntry(document.fileName)) - zip.write(document.content) - zip.closeEntry() - } - } - } ?: throw ExportFailedException(ExportFailure.WRITE_FAILED) + val tree = openWritableTree(treeUri) + val file = tree.createFile(MIME_ZIP, fileName) + ?: throw ExportFailedException(ExportFailure.CANNOT_CREATE_FILE) + try { + zipInto(file.uri, documents) + } catch (error: Exception) { + runCatching { file.delete() } + throw error + } }.getOrElse { throw asExportFailure(it) } ExportResult(documents.size, documents.map { it.fileName }) } + /** + * Deletes the files of [treeUri] that [select] picks from the folder's file + * names. Best effort: a file that will not go is left and the rest still are. + */ + suspend fun deleteFromTree(treeUri: Uri, select: (List) -> Collection): Int = + withContext(io) { + val files = runCatching { DocumentFile.fromTreeUri(context, treeUri)?.listFiles() } + .getOrNull().orEmpty() + val doomed = select(files.mapNotNull { it.name }).toSet() + files.count { it.name in doomed && runCatching { it.delete() }.getOrDefault(false) } + } + + private fun openWritableTree(treeUri: Uri): DocumentFile { + val tree = DocumentFile.fromTreeUri(context, treeUri) + ?: throw ExportFailedException(ExportFailure.FOLDER_UNAVAILABLE) + if (!tree.canWrite()) throw ExportFailedException(ExportFailure.FOLDER_NOT_WRITABLE) + return tree + } + + private fun zipInto(target: Uri, documents: List) { + context.contentResolver.openOutputStream(target, "wt")?.use { raw -> + ZipOutputStream(raw.buffered()).use { zip -> + documents.forEach { document -> + zip.putNextEntry(ZipEntry(document.fileName)) + zip.write(document.content) + zip.closeEntry() + } + } + } ?: throw ExportFailedException(ExportFailure.WRITE_FAILED) + } + private fun write(target: Uri, bytes: ByteArray) { runCatching { // "wt" truncates. Without it a shorter export leaves the tail of the @@ -129,5 +169,6 @@ class ExportWriter @Inject constructor( private companion object { const val MIME_ICALENDAR = "text/calendar" + const val MIME_ZIP = "application/zip" } } diff --git a/app/src/main/java/de/jeanlucmakiola/agendula/ui/export/ExportScreen.kt b/app/src/main/java/de/jeanlucmakiola/agendula/ui/export/ExportScreen.kt index e1557ed..fb797ef 100644 --- a/app/src/main/java/de/jeanlucmakiola/agendula/ui/export/ExportScreen.kt +++ b/app/src/main/java/de/jeanlucmakiola/agendula/ui/export/ExportScreen.kt @@ -339,7 +339,7 @@ private fun openIntent(destination: ExportDestination): Intent? = runCatching { private fun Context.canHandle(intent: Intent): Boolean = packageManager.queryIntentActivities(intent, 0).isNotEmpty() -private fun failureMessage(reason: ExportFailure): Int = when (reason) { +internal fun failureMessage(reason: ExportFailure): Int = when (reason) { ExportFailure.FOLDER_UNAVAILABLE -> R.string.export_failed_folder ExportFailure.FOLDER_NOT_WRITABLE -> R.string.export_failed_read_only ExportFailure.CANNOT_CREATE_FILE -> R.string.export_failed_create diff --git a/app/src/main/java/de/jeanlucmakiola/agendula/ui/navigation/AgendulaNavHost.kt b/app/src/main/java/de/jeanlucmakiola/agendula/ui/navigation/AgendulaNavHost.kt index e3d942d..c25ce03 100644 --- a/app/src/main/java/de/jeanlucmakiola/agendula/ui/navigation/AgendulaNavHost.kt +++ b/app/src/main/java/de/jeanlucmakiola/agendula/ui/navigation/AgendulaNavHost.kt @@ -76,6 +76,8 @@ fun AgendulaNavHost( nav.navigate(Dest.TaskDetail.build(navRequest.taskId, navRequest.occurrenceStart)) NavRequest.OpenAccounts -> nav.navigate(Dest.Settings.build(Dest.Settings.SECTION_ACCOUNTS)) { launchSingleTop = true } + NavRequest.OpenBackup -> + nav.navigate(Dest.Settings.build(Dest.Settings.SECTION_BACKUP)) { launchSingleTop = true } is NavRequest.OpenAccount -> nav.navigate(Dest.Settings.buildAccount(navRequest.accountId)) { launchSingleTop = true } is NavRequest.NewTask -> diff --git a/app/src/main/java/de/jeanlucmakiola/agendula/ui/navigation/Destinations.kt b/app/src/main/java/de/jeanlucmakiola/agendula/ui/navigation/Destinations.kt index a67668e..e558322 100644 --- a/app/src/main/java/de/jeanlucmakiola/agendula/ui/navigation/Destinations.kt +++ b/app/src/main/java/de/jeanlucmakiola/agendula/ui/navigation/Destinations.kt @@ -40,6 +40,7 @@ object Dest { const val ARG_ACCOUNT = "account" const val route = "settings?$ARG_SECTION={$ARG_SECTION}&$ARG_ACCOUNT={$ARG_ACCOUNT}" const val SECTION_ACCOUNTS = "Accounts" + const val SECTION_BACKUP = "Backup" val arguments = listOf( navArgument(ARG_SECTION) { type = NavType.StringType; nullable = true; defaultValue = null }, diff --git a/app/src/main/java/de/jeanlucmakiola/agendula/ui/navigation/NavRequest.kt b/app/src/main/java/de/jeanlucmakiola/agendula/ui/navigation/NavRequest.kt index f61ea27..4f993e4 100644 --- a/app/src/main/java/de/jeanlucmakiola/agendula/ui/navigation/NavRequest.kt +++ b/app/src/main/java/de/jeanlucmakiola/agendula/ui/navigation/NavRequest.kt @@ -22,6 +22,9 @@ sealed interface NavRequest { /** Settings → Accounts, where a sync report's detail lives. */ data object OpenAccounts : NavRequest + /** Settings → Backup & restore, from a failed automatic backup. */ + data object OpenBackup : NavRequest + /** One account's detail — where "sign in again" lives. */ data class OpenAccount(val accountId: Long) : NavRequest diff --git a/app/src/main/java/de/jeanlucmakiola/agendula/ui/settings/AutoBackupViewModel.kt b/app/src/main/java/de/jeanlucmakiola/agendula/ui/settings/AutoBackupViewModel.kt new file mode 100644 index 0000000..6394b4d --- /dev/null +++ b/app/src/main/java/de/jeanlucmakiola/agendula/ui/settings/AutoBackupViewModel.kt @@ -0,0 +1,77 @@ +package de.jeanlucmakiola.agendula.ui.settings + +import android.content.Context +import android.content.Intent +import android.net.Uri +import androidx.core.net.toUri +import androidx.lifecycle.ViewModel +import androidx.lifecycle.viewModelScope +import dagger.hilt.android.lifecycle.HiltViewModel +import dagger.hilt.android.qualifiers.ApplicationContext +import de.jeanlucmakiola.agendula.data.backup.AutoBackupConfig +import de.jeanlucmakiola.agendula.data.backup.AutoBackupPrefs +import de.jeanlucmakiola.agendula.data.backup.AutoBackupScheduler +import de.jeanlucmakiola.agendula.data.backup.AutoBackupStatus +import kotlinx.coroutines.flow.SharingStarted +import kotlinx.coroutines.flow.StateFlow +import kotlinx.coroutines.flow.combine +import kotlinx.coroutines.flow.first +import kotlinx.coroutines.flow.stateIn +import kotlinx.coroutines.launch +import javax.inject.Inject + +data class AutoBackupUiState( + val config: AutoBackupConfig = AutoBackupConfig(), + val status: AutoBackupStatus = AutoBackupStatus(), + val running: Boolean = false, +) + +/** The automatic-backup block of Backup & restore. Scheduling follows the prefs on its own. */ +@HiltViewModel +class AutoBackupViewModel @Inject constructor( + @ApplicationContext private val context: Context, + private val prefs: AutoBackupPrefs, + private val scheduler: AutoBackupScheduler, +) : ViewModel() { + + val state: StateFlow = + combine(prefs.config, prefs.status, scheduler.runningNow) { config, status, running -> + AutoBackupUiState(config, status, running) + }.stateIn(viewModelScope, SharingStarted.WhileSubscribed(5_000), AutoBackupUiState()) + + /** Turning it on without a folder is the screen's to handle: it asks for one first. */ + fun setEnabled(enabled: Boolean) { + viewModelScope.launch { + prefs.setEnabled(enabled) + if (enabled && prefs.config.first().active) scheduler.runNow() + } + } + + /** + * Keeps a persisted grant on [tree] so background runs can write to it, lets + * go of the previous folder's, turns the backup on and takes one right away. + */ + fun chooseFolder(tree: Uri) { + viewModelScope.launch { + val flags = Intent.FLAG_GRANT_READ_URI_PERMISSION or Intent.FLAG_GRANT_WRITE_URI_PERMISSION + val resolver = context.contentResolver + if (runCatching { resolver.takePersistableUriPermission(tree, flags) }.isFailure) return@launch + val previous = prefs.config.first().folderUri?.toUri() + prefs.setFolder(tree.toString()) + if (previous != null && previous != tree) { + runCatching { resolver.releasePersistableUriPermission(previous, flags) } + } + scheduler.runNow() + } + } + + fun setIntervalMinutes(minutes: Int) { + viewModelScope.launch { prefs.setIntervalMinutes(minutes) } + } + + fun setKeepCount(count: Int) { + viewModelScope.launch { prefs.setKeepCount(count) } + } + + fun backUpNow() = scheduler.runNow() +} diff --git a/app/src/main/java/de/jeanlucmakiola/agendula/ui/settings/BackupScreen.kt b/app/src/main/java/de/jeanlucmakiola/agendula/ui/settings/BackupScreen.kt index 0cd7175..3b50ecc 100644 --- a/app/src/main/java/de/jeanlucmakiola/agendula/ui/settings/BackupScreen.kt +++ b/app/src/main/java/de/jeanlucmakiola/agendula/ui/settings/BackupScreen.kt @@ -1,20 +1,64 @@ package de.jeanlucmakiola.agendula.ui.settings +import androidx.activity.compose.rememberLauncherForActivityResult +import androidx.activity.result.contract.ActivityResultContracts +import androidx.compose.foundation.layout.Spacer +import androidx.compose.foundation.layout.height +import androidx.compose.foundation.layout.size +import androidx.compose.material3.CircularProgressIndicator +import androidx.compose.material3.MaterialTheme import androidx.compose.runtime.Composable +import androidx.compose.runtime.getValue +import androidx.compose.runtime.mutableStateOf +import androidx.compose.runtime.remember +import androidx.compose.runtime.saveable.rememberSaveable +import androidx.compose.runtime.setValue +import androidx.compose.ui.Modifier +import androidx.compose.ui.platform.LocalContext +import androidx.compose.ui.res.pluralStringResource import androidx.compose.ui.res.stringResource +import androidx.compose.ui.unit.dp +import androidx.core.net.toUri +import androidx.documentfile.provider.DocumentFile +import androidx.hilt.lifecycle.viewmodel.compose.hiltViewModel +import androidx.lifecycle.compose.collectAsStateWithLifecycle import de.jeanlucmakiola.agendula.R +import de.jeanlucmakiola.agendula.data.backup.AutoBackupPolicy +import de.jeanlucmakiola.agendula.data.export.ExportFailure +import de.jeanlucmakiola.agendula.ui.common.reminderUnitLabel +import de.jeanlucmakiola.agendula.ui.export.failureMessage import de.jeanlucmakiola.floret.components.CollapsingScaffold +import de.jeanlucmakiola.floret.components.CustomAmountEditor +import de.jeanlucmakiola.floret.components.CustomExpandRow +import de.jeanlucmakiola.floret.components.FullScreenPicker +import de.jeanlucmakiola.floret.components.GroupedHint import de.jeanlucmakiola.floret.components.GroupedRow +import de.jeanlucmakiola.floret.components.GroupedSectionHeader +import de.jeanlucmakiola.floret.components.GroupedSwitchRow +import de.jeanlucmakiola.floret.components.OptionRows import de.jeanlucmakiola.floret.components.Position +import de.jeanlucmakiola.floret.locale.relativeTimeAgo +import de.jeanlucmakiola.floret.reminders.ReminderUnit +import de.jeanlucmakiola.floret.reminders.decomposeReminderMinutes -/** Backup & restore: the way into export and import, as its own entry (after Calendula). */ +/** Backup & restore: export, import and the automatic backup (after Calendula). */ @Composable internal fun BackupScreen( onOpenExport: () -> Unit, onOpenImport: () -> Unit, onBack: () -> Unit, visible: Boolean, + viewModel: AutoBackupViewModel = hiltViewModel(), ) { + val state by viewModel.state.collectAsStateWithLifecycle() + val config = state.config + var picker by rememberSaveable { mutableStateOf(null) } + + val pickFolder = rememberLauncherForActivityResult( + contract = ActivityResultContracts.OpenDocumentTree(), + ) { uri -> uri?.let(viewModel::chooseFolder) } + val launchFolderPicker = { runCatching { pickFolder.launch(config.folderUri?.toUri()) } } + CollapsingScaffold( title = stringResource(R.string.settings_section_backup), onBack = onBack, @@ -33,5 +77,191 @@ internal fun BackupScreen( position = Position.Bottom, onClick = onOpenImport, ) + + Spacer(Modifier.height(16.dp)) + GroupedSectionHeader(stringResource(R.string.backup_auto_header)) + GroupedSwitchRow( + title = stringResource(R.string.backup_auto), + summary = stringResource(R.string.backup_auto_hint), + checked = config.active, + onCheckedChange = { on -> + // On without a folder has nowhere to write: ask for one, and the + // pick turns it on. + if (on && config.folderUri == null) launchFolderPicker() else viewModel.setEnabled(on) + }, + position = if (config.active) Position.Top else Position.Alone, + ) + if (config.active) { + GroupedRow( + title = stringResource(R.string.backup_auto_folder), + summary = rememberFolderName(config.folderUri) + ?: stringResource(R.string.backup_auto_folder_unset), + position = Position.Middle, + onClick = { launchFolderPicker() }, + ) + GroupedRow( + title = stringResource(R.string.backup_auto_interval), + summary = backupIntervalLabel(config.intervalMinutes), + position = Position.Middle, + onClick = { picker = BackupPicker.Interval }, + ) + GroupedRow( + title = stringResource(R.string.backup_auto_keep), + summary = backupKeepLabel(config.keepCount), + position = Position.Middle, + onClick = { picker = BackupPicker.Keep }, + ) + GroupedRow( + title = stringResource(R.string.backup_auto_now), + position = Position.Bottom, + dimmed = state.running, + trailing = if (state.running) ({ CircularProgressIndicator(Modifier.size(20.dp)) }) else null, + onClick = viewModel::backUpNow.takeUnless { state.running }, + ) + GroupedHint(backupStatusText(state), style = MaterialTheme.typography.bodySmall) + } + Spacer(Modifier.height(24.dp)) + } + + when (picker) { + BackupPicker.Interval -> AmountPicker( + title = stringResource(R.string.backup_auto_interval), + hint = stringResource(R.string.backup_auto_interval_hint), + presets = AutoBackupPolicy.INTERVAL_PRESETS, + selected = config.intervalMinutes, + label = { backupIntervalLabel(it) }, + units = INTERVAL_UNITS, + onSelect = viewModel::setIntervalMinutes, + onDismiss = { picker = null }, + ) + BackupPicker.Keep -> AmountPicker( + title = stringResource(R.string.backup_auto_keep), + hint = stringResource(R.string.backup_auto_keep_hint), + presets = AutoBackupPolicy.KEEP_PRESETS, + selected = config.keepCount, + label = { backupKeepLabel(it) }, + units = emptyList(), + onSelect = viewModel::setKeepCount, + onDismiss = { picker = null }, + ) + null -> Unit } } + +private enum class BackupPicker { Interval, Keep } + +private val INTERVAL_UNITS = listOf(ReminderUnit.Hours, ReminderUnit.Days, ReminderUnit.Weeks) + +/** + * Presets plus a custom amount, full-screen. [units] scale the custom amount + * (to minutes, for the interval); empty means a plain count. + */ +@Composable +private fun AmountPicker( + title: String, + hint: String, + presets: List, + selected: Int, + label: @Composable (Int) -> String, + units: List, + onSelect: (Int) -> Unit, + onDismiss: () -> Unit, +) { + val customSelected = selected !in presets + val seed = remember(selected) { + if (units.isEmpty()) { + selected.takeIf { customSelected } to null + } else { + val amount = decomposeReminderMinutes(selected.takeIf { customSelected }) + amount.amount to amount.unit.takeIf { it in units } + } + } + var expanded by rememberSaveable { mutableStateOf(false) } + var amountText by rememberSaveable { mutableStateOf(seed.first?.toString().orEmpty()) } + var unitIndex by rememberSaveable { mutableStateOf(seed.second?.let(units::indexOf) ?: 0) } + val value = amountText.toIntOrNull()?.takeIf { it in 1..999 } + ?.let { amount -> amount * (units.getOrNull(unitIndex)?.minutesFactor ?: 1) } + + FullScreenPicker(title = title, onDismiss = onDismiss) { + GroupedHint(hint) + Spacer(Modifier.height(8.dp)) + OptionRows( + options = presets, + selected = selected, + label = label, + onSelect = { + onSelect(it) + onDismiss() + }, + ) + CustomExpandRow( + title = if (customSelected) { + stringResource(R.string.reminder_custom_with_value, label(selected)) + } else { + stringResource(R.string.reminder_custom) + }, + position = Position.Bottom, + expanded = expanded, + onExpandedChange = { expanded = it }, + checked = customSelected, + ) { + CustomAmountEditor( + amountText = amountText, + onAmountChange = { amountText = it }, + preview = value?.let { label(it) } ?: stringResource(R.string.reminder_custom_amount), + setLabel = stringResource(R.string.reminder_custom_set), + confirmEnabled = value != null, + onConfirm = { + value?.let { + onSelect(it) + onDismiss() + } + }, + placeholder = "1", + unitLabels = units.map { stringResource(reminderUnitLabel(it)) }, + selectedUnit = unitIndex, + onUnitChange = { unitIndex = it }, + ) + } + } +} + +/** "Every 6 hours" / "Every day" / "Every 2 weeks": the interval in its largest whole unit. */ +@Composable +private fun backupIntervalLabel(minutes: Int): String = when { + minutes % MINUTES_PER_WEEK == 0 -> + pluralStringResource(R.plurals.backup_every_weeks, minutes / MINUTES_PER_WEEK, minutes / MINUTES_PER_WEEK) + minutes % MINUTES_PER_DAY == 0 -> + pluralStringResource(R.plurals.backup_every_days, minutes / MINUTES_PER_DAY, minutes / MINUTES_PER_DAY) + else -> pluralStringResource(R.plurals.backup_every_hours, minutes / 60, minutes / 60) +} + +@Composable +private fun backupKeepLabel(count: Int): String = pluralStringResource(R.plurals.backup_keep_count, count, count) + +@Composable +private fun backupStatusText(state: AutoBackupUiState): String { + val status = state.status + return when { + state.running -> stringResource(R.string.backup_auto_status_running) + status.lastRunMillis == 0L -> stringResource(R.string.backup_auto_status_never) + status.lastSuccess -> stringResource(R.string.backup_auto_status_ok, relativeTimeAgo(status.lastRunMillis)) + else -> stringResource( + R.string.backup_auto_status_failed, + relativeTimeAgo(status.lastRunMillis), + stringResource(failureMessage(status.failure ?: ExportFailure.WRITE_FAILED)), + ) + } +} + +/** The folder's display name, resolved from its tree Uri. */ +@Composable +private fun rememberFolderName(uri: String?): String? { + val context = LocalContext.current + return remember(uri) { + uri?.let { runCatching { DocumentFile.fromTreeUri(context, it.toUri())?.name }.getOrNull() } + } +} + +private const val MINUTES_PER_DAY = 1_440 +private const val MINUTES_PER_WEEK = 10_080 diff --git a/app/src/main/res/values/strings.xml b/app/src/main/res/values/strings.xml index 5211b6b..41a4ac6 100644 --- a/app/src/main/res/values/strings.xml +++ b/app/src/main/res/values/strings.xml @@ -506,7 +506,7 @@ Storage Where your tasks are kept Backup & restore - Export and import + Export, import and automatic backup Task store Each store keeps its own tasks. Switching does not move them across — copy them over first, or export them from Backup & restore. On this device @@ -564,6 +564,42 @@ A file could not be created in the chosen folder Access to the chosen location was lost + + Automatic backup + Back up automatically + Saves all your lists as a dated zip in a folder you pick. Restore one with Import tasks. + Folder + Choose a folder + Frequency + Android may run a backup a little later than this to save battery. + + Every hour + Every %1$d hours + + + Every day + Every %1$d days + + + Every week + Every %1$d weeks + + Backups to keep + Once a new backup is saved, older ones in the folder are deleted. Other files there are left alone. + + Only the latest + The latest %1$d + + Back up now + Backing up… + No backup yet + Last backup %1$s + Backup failed %1$s. %2$s + Automatic backup + When automatic backups keep failing + Automatic backup failed + Your tasks are not being backed up. Tap to check the backup folder. + Import tasks Bring in tasks from an iCalendar file diff --git a/app/src/test/java/de/jeanlucmakiola/agendula/data/backup/AutoBackupPolicyTest.kt b/app/src/test/java/de/jeanlucmakiola/agendula/data/backup/AutoBackupPolicyTest.kt new file mode 100644 index 0000000..679b610 --- /dev/null +++ b/app/src/test/java/de/jeanlucmakiola/agendula/data/backup/AutoBackupPolicyTest.kt @@ -0,0 +1,60 @@ +package de.jeanlucmakiola.agendula.data.backup + +import com.google.common.truth.Truth.assertThat +import org.junit.jupiter.api.Test +import java.time.LocalDateTime + +class AutoBackupPolicyTest { + + private fun name(day: Int, hour: Int = 3) = AutoBackupPolicy.fileName(LocalDateTime.of(2026, 11, day, hour, 0, 5)) + + @Test + fun `names a backup by its local time`() { + assertThat(AutoBackupPolicy.fileName(LocalDateTime.of(2026, 1, 2, 9, 4, 7))) + .isEqualTo("agendula-backup-2026-01-02-090407.zip") + } + + @Test + fun `reads the time back out of its own names only`() { + assertThat(AutoBackupPolicy.timestampOf(name(17))).isEqualTo(LocalDateTime.of(2026, 11, 17, 3, 0, 5)) + assertThat(AutoBackupPolicy.timestampOf("agendula-tasks.zip")).isNull() + assertThat(AutoBackupPolicy.timestampOf("agendula-backup-2026-11-17-030005 (1).zip")).isNull() + assertThat(AutoBackupPolicy.timestampOf("agendula-backup-2026-13-40-030005.zip")).isNull() + } + + @Test + fun `rotation drops everything beyond the newest kept`() { + val names = listOf(name(3), name(1), name(5), name(4), name(2)) + assertThat(AutoBackupPolicy.staleBackups(names, keep = 3)).containsExactly(name(2), name(1)).inOrder() + } + + @Test + fun `rotation orders by time within a day`() { + val names = listOf(name(1, hour = 23), name(1, hour = 9), name(1, hour = 10)) + assertThat(AutoBackupPolicy.staleBackups(names, keep = 1)).containsExactly(name(1, hour = 10), name(1, hour = 9)) + } + + @Test + fun `rotation leaves files that are not backups alone`() { + val names = listOf("notes.txt", "agendula-tasks.zip", name(1), name(2)) + assertThat(AutoBackupPolicy.staleBackups(names, keep = 1)).containsExactly(name(1)) + } + + @Test + fun `rotation keeps at least the newest backup`() { + assertThat(AutoBackupPolicy.staleBackups(listOf(name(1), name(2)), keep = 0)).containsExactly(name(1)) + } + + @Test + fun `nothing is stale while under the limit`() { + assertThat(AutoBackupPolicy.staleBackups(listOf(name(1), name(2)), keep = 7)).isEmpty() + } + + @Test + fun `clamps the user's choices`() { + assertThat(AutoBackupPolicy.clampInterval(15)).isEqualTo(AutoBackupPolicy.MIN_INTERVAL_MINUTES) + assertThat(AutoBackupPolicy.clampInterval(1_440)).isEqualTo(1_440) + assertThat(AutoBackupPolicy.clampKeep(0)).isEqualTo(1) + assertThat(AutoBackupPolicy.clampKeep(5_000)).isEqualTo(AutoBackupPolicy.MAX_KEEP) + } +} From 457ebadd7bf4f1ae1f1305dd98e214faa78a0e3a Mon Sep 17 00:00:00 2001 From: Jean-Luc Makiola Date: Tue, 17 Nov 2026 11:09:25 +0100 Subject: [PATCH 2/4] Harden automatic backup after review (#77) UTC file names, partial-then-rename writes, one run at a time, no-lists and read failures reported as such, folder name read off the main thread, shared notification permission check. --- .../agendula/data/sync/SyncNoticeNotifier.kt | 9 +- .../agendula/data/backup/AutoBackupPolicy.kt | 30 +++++-- .../agendula/data/backup/AutoBackupPrefs.kt | 33 ++++--- .../data/backup/AutoBackupScheduler.kt | 2 + .../agendula/data/backup/AutoBackupWorker.kt | 49 +++++++--- .../agendula/data/backup/BackupNotifier.kt | 16 +--- .../agendula/data/export/ExportWriter.kt | 89 ++++++++++++++----- .../data/reminders/NotificationPermission.kt | 16 ++++ .../agendula/data/reminders/TaskNotifier.kt | 9 +- .../agendula/ui/export/ExportScreen.kt | 2 +- .../ui/settings/AutoBackupViewModel.kt | 29 +++++- .../agendula/ui/settings/BackupScreen.kt | 83 ++++++++++------- app/src/main/res/values/strings.xml | 5 +- .../data/backup/AutoBackupPolicyTest.kt | 28 ++++-- 14 files changed, 274 insertions(+), 126 deletions(-) create mode 100644 app/src/main/java/de/jeanlucmakiola/agendula/data/reminders/NotificationPermission.kt diff --git a/app/src/full/java/de/jeanlucmakiola/agendula/data/sync/SyncNoticeNotifier.kt b/app/src/full/java/de/jeanlucmakiola/agendula/data/sync/SyncNoticeNotifier.kt index 64130e9..30eb17f 100644 --- a/app/src/full/java/de/jeanlucmakiola/agendula/data/sync/SyncNoticeNotifier.kt +++ b/app/src/full/java/de/jeanlucmakiola/agendula/data/sync/SyncNoticeNotifier.kt @@ -1,20 +1,18 @@ package de.jeanlucmakiola.agendula.data.sync -import android.Manifest import android.annotation.SuppressLint import android.app.NotificationChannel import android.app.NotificationManager import android.app.PendingIntent import android.content.Context import android.content.Intent -import android.content.pm.PackageManager import android.os.Build import androidx.core.app.NotificationCompat import androidx.core.app.NotificationManagerCompat -import androidx.core.content.ContextCompat import dagger.hilt.android.qualifiers.ApplicationContext import de.jeanlucmakiola.agendula.MainActivity import de.jeanlucmakiola.agendula.data.di.ChannelRefresher +import de.jeanlucmakiola.agendula.data.reminders.canPostNotifications import de.jeanlucmakiola.agendula.R import javax.inject.Inject import javax.inject.Singleton @@ -37,10 +35,7 @@ class SyncNoticeNotifier @Inject constructor( ) : ChannelRefresher { fun canPost(): Boolean { - val granted = Build.VERSION.SDK_INT < Build.VERSION_CODES.TIRAMISU || - ContextCompat.checkSelfPermission(context, Manifest.permission.POST_NOTIFICATIONS) == - PackageManager.PERMISSION_GRANTED - return granted && NotificationManagerCompat.from(context).areNotificationsEnabled() + return context.canPostNotifications() } // canPost() checks POST_NOTIFICATIONS before we ever call notify(). diff --git a/app/src/main/java/de/jeanlucmakiola/agendula/data/backup/AutoBackupPolicy.kt b/app/src/main/java/de/jeanlucmakiola/agendula/data/backup/AutoBackupPolicy.kt index 92067e5..f92bbc2 100644 --- a/app/src/main/java/de/jeanlucmakiola/agendula/data/backup/AutoBackupPolicy.kt +++ b/app/src/main/java/de/jeanlucmakiola/agendula/data/backup/AutoBackupPolicy.kt @@ -1,6 +1,8 @@ package de.jeanlucmakiola.agendula.data.backup +import java.time.Instant import java.time.LocalDateTime +import java.time.ZoneOffset import java.time.format.DateTimeFormatter import java.util.Locale @@ -8,7 +10,9 @@ import java.util.Locale * The rules of the automatic backup that need no Android: how a backup file is * named, which ones rotation removes, and the bounds of the user's choices. * - * Rotation only ever touches files whose name matches [fileName]'s pattern, so + * Names carry UTC, so a time-zone change or the DST fall-back can never make a + * new backup sort before an older one and get rotated out. Rotation only ever + * touches files matching [fileName]'s pattern (or their [partialName]), so * anything else the user keeps in the same folder is safe. */ object AutoBackupPolicy { @@ -26,23 +30,33 @@ object AutoBackupPolicy { private const val PREFIX = "agendula-backup-" private const val EXTENSION = ".zip" - private val STAMP = DateTimeFormatter.ofPattern("uuuu-MM-dd-HHmmss", Locale.ROOT) - private val NAME = Regex("""agendula-backup-(\d{4}-\d{2}-\d{2}-\d{6})\.zip""") + private const val PARTIAL_SUFFIX = ".partial" + private val STAMP = DateTimeFormatter.ofPattern("uuuu-MM-dd-HHmmss'Z'", Locale.ROOT) + private val NAME = Regex("""agendula-backup-(\d{4}-\d{2}-\d{2}-\d{6}Z)\.zip""") - /** `agendula-backup-2026-11-17-143005.zip`: sortable, and readable in a file manager. */ - fun fileName(at: LocalDateTime): String = PREFIX + STAMP.format(at) + EXTENSION + /** `agendula-backup-2026-11-17-143005Z.zip`: sortable, and readable in a file manager. */ + fun fileName(at: Instant): String = PREFIX + STAMP.format(at.atOffset(ZoneOffset.UTC)) + EXTENSION + + /** The name a backup is written under until it is complete. */ + fun partialName(fileName: String): String = fileName + PARTIAL_SUFFIX /** When the backup named [name] was taken, or null when it is not one of ours. */ - fun timestampOf(name: String): LocalDateTime? = - NAME.matchEntire(name)?.let { runCatching { LocalDateTime.parse(it.groupValues[1], STAMP) }.getOrNull() } + fun timestampOf(name: String): Instant? = + NAME.matchEntire(name)?.let { match -> + runCatching { LocalDateTime.parse(match.groupValues[1], STAMP).toInstant(ZoneOffset.UTC) }.getOrNull() + } - /** The backups in [names] beyond the newest [keep], oldest last. */ + /** The backups in [names] beyond the newest [keep], newest first. */ fun staleBackups(names: Collection, keep: Int): List = names.mapNotNull { name -> timestampOf(name)?.let { name to it } } .sortedByDescending { it.second } .drop(clampKeep(keep)) .map { it.first } + /** Backups a run never finished, e.g. because the process was killed mid-write. */ + fun abandonedPartials(names: Collection): List = + names.filter { it.endsWith(PARTIAL_SUFFIX) && timestampOf(it.removeSuffix(PARTIAL_SUFFIX)) != null } + fun clampInterval(minutes: Int): Int = minutes.coerceIn(MIN_INTERVAL_MINUTES, MAX_INTERVAL_MINUTES) fun clampKeep(count: Int): Int = count.coerceIn(1, MAX_KEEP) diff --git a/app/src/main/java/de/jeanlucmakiola/agendula/data/backup/AutoBackupPrefs.kt b/app/src/main/java/de/jeanlucmakiola/agendula/data/backup/AutoBackupPrefs.kt index 74a06fd..bf75352 100644 --- a/app/src/main/java/de/jeanlucmakiola/agendula/data/backup/AutoBackupPrefs.kt +++ b/app/src/main/java/de/jeanlucmakiola/agendula/data/backup/AutoBackupPrefs.kt @@ -25,12 +25,26 @@ data class AutoBackupConfig( val active: Boolean get() = enabled && folderUri != null } -/** How the last automatic backup went; [lastRunMillis] 0 = never ran. */ +/** Why an automatic backup failed: the export's write failures, plus the two before any write. */ +enum class BackupFailure { + FOLDER_UNAVAILABLE, + FOLDER_NOT_WRITABLE, + CANNOT_CREATE_FILE, + LOST_ACCESS, + WRITE_FAILED, + READ_FAILED, + NO_LISTS, + ; + + companion object { + fun of(failure: ExportFailure): BackupFailure = valueOf(failure.name) + } +} + +/** How the last automatic backup went; [lastRunMillis] 0 = never ran, [failure] null = it worked. */ data class AutoBackupStatus( val lastRunMillis: Long = 0L, - val lastSuccess: Boolean = false, - val consecutiveFailures: Int = 0, - val failure: ExportFailure? = null, + val failure: BackupFailure? = null, ) /** The automatic backup's settings and last outcome, in the app's DataStore. */ @@ -51,9 +65,9 @@ class AutoBackupPrefs @Inject constructor( val status: Flow = dataStore.data.map { p -> AutoBackupStatus( lastRunMillis = p[LAST_RUN] ?: 0L, - lastSuccess = p[LAST_SUCCESS] ?: false, - consecutiveFailures = p[FAILURES] ?: 0, - failure = p[FAILURE_REASON]?.let { runCatching { ExportFailure.valueOf(it) }.getOrNull() }, + failure = p[FAILURE_REASON]?.let { + runCatching { BackupFailure.valueOf(it) }.getOrDefault(BackupFailure.WRITE_FAILED) + }, ) }.distinctUntilChanged() @@ -72,18 +86,16 @@ class AutoBackupPrefs @Inject constructor( suspend fun recordSuccess(atMillis: Long) = dataStore.edit { it[LAST_RUN] = atMillis - it[LAST_SUCCESS] = true it[FAILURES] = 0 it.remove(FAILURE_REASON) } /** Returns how many runs in a row have now failed. */ - suspend fun recordFailure(atMillis: Long, reason: ExportFailure): Int { + suspend fun recordFailure(atMillis: Long, reason: BackupFailure): Int { var failures = 0 dataStore.edit { failures = (it[FAILURES] ?: 0) + 1 it[LAST_RUN] = atMillis - it[LAST_SUCCESS] = false it[FAILURES] = failures it[FAILURE_REASON] = reason.name } @@ -96,7 +108,6 @@ class AutoBackupPrefs @Inject constructor( val INTERVAL = intPreferencesKey("auto_backup_interval_minutes") val KEEP = intPreferencesKey("auto_backup_keep") val LAST_RUN = longPreferencesKey("auto_backup_last_run") - val LAST_SUCCESS = booleanPreferencesKey("auto_backup_last_success") val FAILURES = intPreferencesKey("auto_backup_failures") val FAILURE_REASON = stringPreferencesKey("auto_backup_failure_reason") } diff --git a/app/src/main/java/de/jeanlucmakiola/agendula/data/backup/AutoBackupScheduler.kt b/app/src/main/java/de/jeanlucmakiola/agendula/data/backup/AutoBackupScheduler.kt index 122f73b..86b7540 100644 --- a/app/src/main/java/de/jeanlucmakiola/agendula/data/backup/AutoBackupScheduler.kt +++ b/app/src/main/java/de/jeanlucmakiola/agendula/data/backup/AutoBackupScheduler.kt @@ -27,6 +27,7 @@ import javax.inject.Singleton class AutoBackupScheduler @Inject constructor( @ApplicationContext private val context: Context, private val prefs: AutoBackupPrefs, + private val notifier: BackupNotifier, @ApplicationScope private val scope: CoroutineScope, ) { @@ -61,6 +62,7 @@ class AutoBackupScheduler @Inject constructor( if (intervalMinutes == null) { workManager.cancelUniqueWork(WORK_NAME) workManager.cancelUniqueWork(WORK_NAME_NOW) + notifier.cancelFailure() return } val minutes = intervalMinutes.toLong() diff --git a/app/src/main/java/de/jeanlucmakiola/agendula/data/backup/AutoBackupWorker.kt b/app/src/main/java/de/jeanlucmakiola/agendula/data/backup/AutoBackupWorker.kt index 99eb540..1bf42ab 100644 --- a/app/src/main/java/de/jeanlucmakiola/agendula/data/backup/AutoBackupWorker.kt +++ b/app/src/main/java/de/jeanlucmakiola/agendula/data/backup/AutoBackupWorker.kt @@ -13,8 +13,11 @@ import de.jeanlucmakiola.agendula.data.export.ExportFailure import de.jeanlucmakiola.agendula.data.export.ExportWriter import de.jeanlucmakiola.agendula.data.export.TaskExporter import de.jeanlucmakiola.agendula.data.tasks.StartupGate +import de.jeanlucmakiola.agendula.domain.export.ExportDocument import kotlinx.coroutines.flow.first -import java.time.LocalDateTime +import kotlinx.coroutines.sync.Mutex +import kotlinx.coroutines.sync.withLock +import java.time.Instant import kotlin.coroutines.cancellation.CancellationException /** @@ -34,20 +37,23 @@ class AutoBackupWorker @AssistedInject constructor( private val notifier: BackupNotifier, ) : CoroutineWorker(context, params) { - override suspend fun doWork(): Result { + // The periodic run and "Back up now" are separate work chains; one at a time, + // or one run's rotation could delete what the other is still writing. + override suspend fun doWork(): Result = runLock.withLock { backUp() } + + private suspend fun backUp(): Result { val config = prefs.config.first() // Turned off since this was queued: nothing to do, and nothing to retry. val folder = config.folderUri?.takeIf { config.enabled } ?: return Result.success() val now = System.currentTimeMillis() return try { startupGate.awaitReady() - val documents = exporter.export() - // No lists means nothing worth keeping; writing an empty backup would - // rotate the real ones out of the folder. - if (documents.isNotEmpty()) { - val tree = folder.toUri() - writer.writeZipToTree(tree, AutoBackupPolicy.fileName(LocalDateTime.now()), documents) - writer.deleteFromTree(tree) { names -> AutoBackupPolicy.staleBackups(names, config.keepCount) } + val documents = readLists() + val tree = folder.toUri() + val fileName = AutoBackupPolicy.fileName(Instant.ofEpochMilli(now)) + writer.writeZipToTree(tree, fileName, AutoBackupPolicy.partialName(fileName), documents) + writer.deleteFromTree(tree) { names -> + AutoBackupPolicy.staleBackups(names, config.keepCount) + AutoBackupPolicy.abandonedPartials(names) } prefs.recordSuccess(now) notifier.cancelFailure() @@ -56,14 +62,37 @@ class AutoBackupWorker @AssistedInject constructor( throw cancelled } catch (error: Exception) { Log.w(TAG, "Automatic backup failed", error) - val reason = (error as? ExportFailedException)?.failure ?: ExportFailure.WRITE_FAILED + val reason = when (error) { + is BackupFailedException -> error.failure + is ExportFailedException -> BackupFailure.of(error.failure) + else -> BackupFailure.of(ExportFailure.WRITE_FAILED) + } if (prefs.recordFailure(now, reason) >= FAILURE_NOTIFY_THRESHOLD) notifier.postFailure() Result.failure() } } + /** + * No lists is a failure, not an empty backup: it is what an unreachable task + * app looks like, and an empty zip would rotate the real backups out. + */ + private suspend fun readLists(): List { + val documents = try { + exporter.export() + } catch (cancelled: CancellationException) { + throw cancelled + } catch (error: Exception) { + throw BackupFailedException(BackupFailure.READ_FAILED, error) + } + return documents.ifEmpty { throw BackupFailedException(BackupFailure.NO_LISTS) } + } + + private class BackupFailedException(val failure: BackupFailure, cause: Throwable? = null) : + Exception(failure.name, cause) + private companion object { const val TAG = "AutoBackupWorker" const val FAILURE_NOTIFY_THRESHOLD = 2 + val runLock = Mutex() } } diff --git a/app/src/main/java/de/jeanlucmakiola/agendula/data/backup/BackupNotifier.kt b/app/src/main/java/de/jeanlucmakiola/agendula/data/backup/BackupNotifier.kt index eb61bf2..d1d4b12 100644 --- a/app/src/main/java/de/jeanlucmakiola/agendula/data/backup/BackupNotifier.kt +++ b/app/src/main/java/de/jeanlucmakiola/agendula/data/backup/BackupNotifier.kt @@ -1,16 +1,12 @@ package de.jeanlucmakiola.agendula.data.backup -import android.Manifest import android.annotation.SuppressLint import android.app.NotificationChannel import android.app.NotificationManager import android.app.PendingIntent import android.content.Context -import android.content.pm.PackageManager -import android.os.Build import androidx.core.app.NotificationCompat import androidx.core.app.NotificationManagerCompat -import androidx.core.content.ContextCompat import dagger.Binds import dagger.Module import dagger.hilt.InstallIn @@ -20,6 +16,7 @@ import dagger.multibindings.IntoSet import de.jeanlucmakiola.agendula.MainActivity import de.jeanlucmakiola.agendula.R import de.jeanlucmakiola.agendula.data.di.ChannelRefresher +import de.jeanlucmakiola.agendula.data.reminders.canPostNotifications import javax.inject.Inject import javax.inject.Singleton @@ -33,17 +30,10 @@ class BackupNotifier @Inject constructor( @ApplicationContext private val context: Context, ) : ChannelRefresher { - private fun canPost(): Boolean { - val granted = Build.VERSION.SDK_INT < Build.VERSION_CODES.TIRAMISU || - ContextCompat.checkSelfPermission(context, Manifest.permission.POST_NOTIFICATIONS) == - PackageManager.PERMISSION_GRANTED - return granted && NotificationManagerCompat.from(context).areNotificationsEnabled() - } - - // canPost() checks POST_NOTIFICATIONS before we ever call notify(). + // canPostNotifications() checks POST_NOTIFICATIONS before we ever call notify(). @SuppressLint("MissingPermission") fun postFailure() { - if (!canPost()) return + if (!context.canPostNotifications()) return ensureChannel() val notification = NotificationCompat.Builder(context, CHANNEL_ID) .setSmallIcon(R.drawable.ic_notification) diff --git a/app/src/main/java/de/jeanlucmakiola/agendula/data/export/ExportWriter.kt b/app/src/main/java/de/jeanlucmakiola/agendula/data/export/ExportWriter.kt index 52de154..b3abfed 100644 --- a/app/src/main/java/de/jeanlucmakiola/agendula/data/export/ExportWriter.kt +++ b/app/src/main/java/de/jeanlucmakiola/agendula/data/export/ExportWriter.kt @@ -2,6 +2,7 @@ package de.jeanlucmakiola.agendula.data.export import android.content.Context import android.net.Uri +import android.provider.DocumentsContract import androidx.documentfile.provider.DocumentFile import dagger.hilt.android.qualifiers.ApplicationContext import de.jeanlucmakiola.agendula.data.di.IoDispatcher @@ -99,37 +100,80 @@ class ExportWriter @Inject constructor( /** * Writes every document into a new zip named [fileName] inside [treeUri]. - * A zip that could not be written completely is removed again, so a failed - * run never leaves a truncated file that looks like a backup. + * + * The zip is written under [partialName] and renamed once complete, so a run + * that fails — or a process killed mid-write — never leaves a truncated file + * under a finished name. A provider that cannot rename gets the zip written + * under [fileName] directly. An existing [fileName] is left as it is. */ - suspend fun writeZipToTree(treeUri: Uri, fileName: String, documents: List): ExportResult = - withContext(io) { - runCatching { - val tree = openWritableTree(treeUri) - val file = tree.createFile(MIME_ZIP, fileName) - ?: throw ExportFailedException(ExportFailure.CANNOT_CREATE_FILE) - try { - zipInto(file.uri, documents) - } catch (error: Exception) { - runCatching { file.delete() } - throw error + suspend fun writeZipToTree( + treeUri: Uri, + fileName: String, + partialName: String, + documents: List, + ): ExportResult = withContext(io) { + runCatching { + val tree = openWritableTree(treeUri) + if (fileName !in childDocuments(treeUri)) { + val partial = createAndZip(tree, MIME_PARTIAL, partialName, documents) + if (!runCatching { partial.renameTo(fileName) }.getOrDefault(false)) { + runCatching { partial.delete() } + createAndZip(tree, MIME_ZIP, fileName, documents) } - }.getOrElse { throw asExportFailure(it) } - ExportResult(documents.size, documents.map { it.fileName }) - } + } + }.getOrElse { throw asExportFailure(it) } + ExportResult(documents.size, documents.map { it.fileName }) + } /** * Deletes the files of [treeUri] that [select] picks from the folder's file * names. Best effort: a file that will not go is left and the rest still are. */ - suspend fun deleteFromTree(treeUri: Uri, select: (List) -> Collection): Int = + suspend fun deleteFromTree(treeUri: Uri, select: (Set) -> Collection): Int = withContext(io) { - val files = runCatching { DocumentFile.fromTreeUri(context, treeUri)?.listFiles() } - .getOrNull().orEmpty() - val doomed = select(files.mapNotNull { it.name }).toSet() - files.count { it.name in doomed && runCatching { it.delete() }.getOrDefault(false) } + val children = runCatching { childDocuments(treeUri) }.getOrDefault(emptyMap()) + select(children.keys).count { name -> + val uri = children[name] ?: return@count false + runCatching { DocumentsContract.deleteDocument(context.contentResolver, uri) }.getOrDefault(false) + } } + private fun createAndZip( + tree: DocumentFile, + mime: String, + name: String, + documents: List, + ): DocumentFile { + val file = tree.createFile(mime, name) ?: throw ExportFailedException(ExportFailure.CANNOT_CREATE_FILE) + try { + zipInto(file.uri, documents) + } catch (error: Exception) { + runCatching { file.delete() } + throw error + } + return file + } + + /** The folder's files by name, in one provider query rather than one per file. */ + private fun childDocuments(treeUri: Uri): Map { + val children = DocumentsContract.buildChildDocumentsUriUsingTree( + treeUri, + DocumentsContract.getTreeDocumentId(treeUri), + ) + val projection = arrayOf( + DocumentsContract.Document.COLUMN_DOCUMENT_ID, + DocumentsContract.Document.COLUMN_DISPLAY_NAME, + ) + return context.contentResolver.query(children, projection, null, null, null)?.use { cursor -> + buildMap { + while (cursor.moveToNext()) { + val name = cursor.getString(1) ?: continue + put(name, DocumentsContract.buildDocumentUriUsingTree(treeUri, cursor.getString(0))) + } + } + }.orEmpty() + } + private fun openWritableTree(treeUri: Uri): DocumentFile { val tree = DocumentFile.fromTreeUri(context, treeUri) ?: throw ExportFailedException(ExportFailure.FOLDER_UNAVAILABLE) @@ -170,5 +214,8 @@ class ExportWriter @Inject constructor( private companion object { const val MIME_ICALENDAR = "text/calendar" const val MIME_ZIP = "application/zip" + + // Not a zip MIME type, so the provider keeps the suffix rather than adding ".zip". + const val MIME_PARTIAL = "application/octet-stream" } } diff --git a/app/src/main/java/de/jeanlucmakiola/agendula/data/reminders/NotificationPermission.kt b/app/src/main/java/de/jeanlucmakiola/agendula/data/reminders/NotificationPermission.kt new file mode 100644 index 0000000..f0722a3 --- /dev/null +++ b/app/src/main/java/de/jeanlucmakiola/agendula/data/reminders/NotificationPermission.kt @@ -0,0 +1,16 @@ +package de.jeanlucmakiola.agendula.data.reminders + +import android.Manifest +import android.content.Context +import android.content.pm.PackageManager +import android.os.Build +import androidx.core.app.NotificationManagerCompat +import androidx.core.content.ContextCompat + +/** Whether a notification posted now would show: the runtime permission (13+) and the app-wide switch. */ +fun Context.canPostNotifications(): Boolean { + val granted = Build.VERSION.SDK_INT < Build.VERSION_CODES.TIRAMISU || + ContextCompat.checkSelfPermission(this, Manifest.permission.POST_NOTIFICATIONS) == + PackageManager.PERMISSION_GRANTED + return granted && NotificationManagerCompat.from(this).areNotificationsEnabled() +} diff --git a/app/src/main/java/de/jeanlucmakiola/agendula/data/reminders/TaskNotifier.kt b/app/src/main/java/de/jeanlucmakiola/agendula/data/reminders/TaskNotifier.kt index 081b2f9..2065694 100644 --- a/app/src/main/java/de/jeanlucmakiola/agendula/data/reminders/TaskNotifier.kt +++ b/app/src/main/java/de/jeanlucmakiola/agendula/data/reminders/TaskNotifier.kt @@ -1,6 +1,5 @@ package de.jeanlucmakiola.agendula.data.reminders -import android.Manifest import android.annotation.SuppressLint import android.app.NotificationChannel import android.app.NotificationChannelGroup @@ -8,14 +7,11 @@ import android.app.NotificationManager import android.app.PendingIntent import android.content.Context import android.content.Intent -import android.content.pm.PackageManager -import android.os.Build import android.os.Bundle import android.text.format.DateFormat import android.util.TypedValue import androidx.core.app.NotificationCompat import androidx.core.app.NotificationManagerCompat -import androidx.core.content.ContextCompat import androidx.core.content.edit import de.jeanlucmakiola.agendula.MainActivity import de.jeanlucmakiola.agendula.R @@ -62,10 +58,7 @@ class TaskNotifier @Inject constructor( private val channelPrefs get() = context.getSharedPreferences(CHANNEL_PREFS, Context.MODE_PRIVATE) fun canPost(): Boolean { - val granted = Build.VERSION.SDK_INT < Build.VERSION_CODES.TIRAMISU || - ContextCompat.checkSelfPermission(context, Manifest.permission.POST_NOTIFICATIONS) == - PackageManager.PERMISSION_GRANTED - return granted && NotificationManagerCompat.from(context).areNotificationsEnabled() + return context.canPostNotifications() } // canPost() checks POST_NOTIFICATIONS before we ever call notify(). diff --git a/app/src/main/java/de/jeanlucmakiola/agendula/ui/export/ExportScreen.kt b/app/src/main/java/de/jeanlucmakiola/agendula/ui/export/ExportScreen.kt index fb797ef..e1557ed 100644 --- a/app/src/main/java/de/jeanlucmakiola/agendula/ui/export/ExportScreen.kt +++ b/app/src/main/java/de/jeanlucmakiola/agendula/ui/export/ExportScreen.kt @@ -339,7 +339,7 @@ private fun openIntent(destination: ExportDestination): Intent? = runCatching { private fun Context.canHandle(intent: Intent): Boolean = packageManager.queryIntentActivities(intent, 0).isNotEmpty() -internal fun failureMessage(reason: ExportFailure): Int = when (reason) { +private fun failureMessage(reason: ExportFailure): Int = when (reason) { ExportFailure.FOLDER_UNAVAILABLE -> R.string.export_failed_folder ExportFailure.FOLDER_NOT_WRITABLE -> R.string.export_failed_read_only ExportFailure.CANNOT_CREATE_FILE -> R.string.export_failed_create diff --git a/app/src/main/java/de/jeanlucmakiola/agendula/ui/settings/AutoBackupViewModel.kt b/app/src/main/java/de/jeanlucmakiola/agendula/ui/settings/AutoBackupViewModel.kt index 6394b4d..99c65bd 100644 --- a/app/src/main/java/de/jeanlucmakiola/agendula/ui/settings/AutoBackupViewModel.kt +++ b/app/src/main/java/de/jeanlucmakiola/agendula/ui/settings/AutoBackupViewModel.kt @@ -4,6 +4,7 @@ import android.content.Context import android.content.Intent import android.net.Uri import androidx.core.net.toUri +import androidx.documentfile.provider.DocumentFile import androidx.lifecycle.ViewModel import androidx.lifecycle.viewModelScope import dagger.hilt.android.lifecycle.HiltViewModel @@ -12,18 +13,28 @@ import de.jeanlucmakiola.agendula.data.backup.AutoBackupConfig import de.jeanlucmakiola.agendula.data.backup.AutoBackupPrefs import de.jeanlucmakiola.agendula.data.backup.AutoBackupScheduler import de.jeanlucmakiola.agendula.data.backup.AutoBackupStatus +import de.jeanlucmakiola.agendula.data.di.IoDispatcher +import kotlinx.coroutines.CoroutineDispatcher +import kotlinx.coroutines.flow.MutableStateFlow import kotlinx.coroutines.flow.SharingStarted import kotlinx.coroutines.flow.StateFlow import kotlinx.coroutines.flow.combine +import kotlinx.coroutines.flow.distinctUntilChanged import kotlinx.coroutines.flow.first +import kotlinx.coroutines.flow.map import kotlinx.coroutines.flow.stateIn import kotlinx.coroutines.launch +import kotlinx.coroutines.withContext import javax.inject.Inject data class AutoBackupUiState( val config: AutoBackupConfig = AutoBackupConfig(), val status: AutoBackupStatus = AutoBackupStatus(), val running: Boolean = false, + /** The backup folder's display name; null while unknown or unreadable. */ + val folderName: String? = null, + /** The last folder picked could not be kept for background writes. */ + val folderRejected: Boolean = false, ) /** The automatic-backup block of Backup & restore. Scheduling follows the prefs on its own. */ @@ -32,11 +43,21 @@ class AutoBackupViewModel @Inject constructor( @ApplicationContext private val context: Context, private val prefs: AutoBackupPrefs, private val scheduler: AutoBackupScheduler, + @IoDispatcher private val io: CoroutineDispatcher, ) : ViewModel() { + private val folderRejected = MutableStateFlow(false) + + // A provider query, so off the main thread: the folder may be on an SD card + // or a cloud provider that is slow to answer. + private val folderName = prefs.config.map { it.folderUri }.distinctUntilChanged().map { uri -> + uri?.let { withContext(io) { runCatching { DocumentFile.fromTreeUri(context, it.toUri())?.name }.getOrNull() } } + } + val state: StateFlow = - combine(prefs.config, prefs.status, scheduler.runningNow) { config, status, running -> - AutoBackupUiState(config, status, running) + combine(prefs.config, prefs.status, scheduler.runningNow, folderName, folderRejected) { + config, status, running, name, rejected -> + AutoBackupUiState(config, status, running, name, rejected) }.stateIn(viewModelScope, SharingStarted.WhileSubscribed(5_000), AutoBackupUiState()) /** Turning it on without a folder is the screen's to handle: it asks for one first. */ @@ -55,7 +76,9 @@ class AutoBackupViewModel @Inject constructor( viewModelScope.launch { val flags = Intent.FLAG_GRANT_READ_URI_PERMISSION or Intent.FLAG_GRANT_WRITE_URI_PERMISSION val resolver = context.contentResolver - if (runCatching { resolver.takePersistableUriPermission(tree, flags) }.isFailure) return@launch + val granted = runCatching { resolver.takePersistableUriPermission(tree, flags) }.isSuccess + folderRejected.value = !granted + if (!granted) return@launch val previous = prefs.config.first().folderUri?.toUri() prefs.setFolder(tree.toString()) if (previous != null && previous != tree) { diff --git a/app/src/main/java/de/jeanlucmakiola/agendula/ui/settings/BackupScreen.kt b/app/src/main/java/de/jeanlucmakiola/agendula/ui/settings/BackupScreen.kt index 3b50ecc..f5ec319 100644 --- a/app/src/main/java/de/jeanlucmakiola/agendula/ui/settings/BackupScreen.kt +++ b/app/src/main/java/de/jeanlucmakiola/agendula/ui/settings/BackupScreen.kt @@ -10,23 +10,22 @@ import androidx.compose.material3.MaterialTheme import androidx.compose.runtime.Composable import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableStateOf +import androidx.compose.runtime.produceState import androidx.compose.runtime.remember import androidx.compose.runtime.saveable.rememberSaveable import androidx.compose.runtime.setValue import androidx.compose.ui.Modifier -import androidx.compose.ui.platform.LocalContext import androidx.compose.ui.res.pluralStringResource import androidx.compose.ui.res.stringResource import androidx.compose.ui.unit.dp import androidx.core.net.toUri -import androidx.documentfile.provider.DocumentFile import androidx.hilt.lifecycle.viewmodel.compose.hiltViewModel import androidx.lifecycle.compose.collectAsStateWithLifecycle +import kotlinx.coroutines.delay import de.jeanlucmakiola.agendula.R import de.jeanlucmakiola.agendula.data.backup.AutoBackupPolicy -import de.jeanlucmakiola.agendula.data.export.ExportFailure +import de.jeanlucmakiola.agendula.data.backup.BackupFailure import de.jeanlucmakiola.agendula.ui.common.reminderUnitLabel -import de.jeanlucmakiola.agendula.ui.export.failureMessage import de.jeanlucmakiola.floret.components.CollapsingScaffold import de.jeanlucmakiola.floret.components.CustomAmountEditor import de.jeanlucmakiola.floret.components.CustomExpandRow @@ -35,8 +34,8 @@ import de.jeanlucmakiola.floret.components.GroupedHint import de.jeanlucmakiola.floret.components.GroupedRow import de.jeanlucmakiola.floret.components.GroupedSectionHeader import de.jeanlucmakiola.floret.components.GroupedSwitchRow -import de.jeanlucmakiola.floret.components.OptionRows import de.jeanlucmakiola.floret.components.Position +import de.jeanlucmakiola.floret.components.positionOf import de.jeanlucmakiola.floret.locale.relativeTimeAgo import de.jeanlucmakiola.floret.reminders.ReminderUnit import de.jeanlucmakiola.floret.reminders.decomposeReminderMinutes @@ -91,11 +90,13 @@ internal fun BackupScreen( }, position = if (config.active) Position.Top else Position.Alone, ) + if (state.folderRejected) { + GroupedHint(stringResource(R.string.backup_auto_folder_rejected), style = MaterialTheme.typography.bodySmall) + } if (config.active) { GroupedRow( title = stringResource(R.string.backup_auto_folder), - summary = rememberFolderName(config.folderUri) - ?: stringResource(R.string.backup_auto_folder_unset), + summary = state.folderName ?: stringResource(R.string.backup_auto_folder_unset), position = Position.Middle, onClick = { launchFolderPicker() }, ) @@ -185,15 +186,17 @@ private fun AmountPicker( FullScreenPicker(title = title, onDismiss = onDismiss) { GroupedHint(hint) Spacer(Modifier.height(8.dp)) - OptionRows( - options = presets, - selected = selected, - label = label, - onSelect = { - onSelect(it) - onDismiss() - }, - ) + presets.forEachIndexed { index, preset -> + GroupedRow( + title = label(preset), + position = positionOf(index, presets.size + 1), + checked = preset == selected, + onClick = { + onSelect(preset) + onDismiss() + }, + ) + } CustomExpandRow( title = if (customSelected) { stringResource(R.string.reminder_custom_with_value, label(selected)) @@ -228,12 +231,15 @@ private fun AmountPicker( /** "Every 6 hours" / "Every day" / "Every 2 weeks": the interval in its largest whole unit. */ @Composable -private fun backupIntervalLabel(minutes: Int): String = when { - minutes % MINUTES_PER_WEEK == 0 -> - pluralStringResource(R.plurals.backup_every_weeks, minutes / MINUTES_PER_WEEK, minutes / MINUTES_PER_WEEK) - minutes % MINUTES_PER_DAY == 0 -> - pluralStringResource(R.plurals.backup_every_days, minutes / MINUTES_PER_DAY, minutes / MINUTES_PER_DAY) - else -> pluralStringResource(R.plurals.backup_every_hours, minutes / 60, minutes / 60) +private fun backupIntervalLabel(minutes: Int): String { + val (amount, unit) = decomposeReminderMinutes(minutes) + val count = amount ?: 1 + return when (unit) { + ReminderUnit.Weeks -> pluralStringResource(R.plurals.backup_every_weeks, count, count) + ReminderUnit.Days -> pluralStringResource(R.plurals.backup_every_days, count, count) + ReminderUnit.Hours -> pluralStringResource(R.plurals.backup_every_hours, count, count) + ReminderUnit.Minutes -> pluralStringResource(R.plurals.backup_every_hours, count / 60, count / 60) + } } @Composable @@ -242,26 +248,35 @@ private fun backupKeepLabel(count: Int): String = pluralStringResource(R.plurals @Composable private fun backupStatusText(state: AutoBackupUiState): String { val status = state.status + // "5 minutes ago" has to move on while the screen stays open. + val now by produceState(System.currentTimeMillis()) { + while (true) { + delay(STATUS_TICK_MILLIS) + value = System.currentTimeMillis() + } + } + val failure = status.failure return when { state.running -> stringResource(R.string.backup_auto_status_running) status.lastRunMillis == 0L -> stringResource(R.string.backup_auto_status_never) - status.lastSuccess -> stringResource(R.string.backup_auto_status_ok, relativeTimeAgo(status.lastRunMillis)) + failure == null -> stringResource(R.string.backup_auto_status_ok, relativeTimeAgo(status.lastRunMillis, now)) else -> stringResource( R.string.backup_auto_status_failed, - relativeTimeAgo(status.lastRunMillis), - stringResource(failureMessage(status.failure ?: ExportFailure.WRITE_FAILED)), + relativeTimeAgo(status.lastRunMillis, now), + stringResource(backupFailureMessage(failure)), ) } } -/** The folder's display name, resolved from its tree Uri. */ -@Composable -private fun rememberFolderName(uri: String?): String? { - val context = LocalContext.current - return remember(uri) { - uri?.let { runCatching { DocumentFile.fromTreeUri(context, it.toUri())?.name }.getOrNull() } - } +private fun backupFailureMessage(failure: BackupFailure): Int = when (failure) { + BackupFailure.FOLDER_UNAVAILABLE -> R.string.export_failed_folder + BackupFailure.FOLDER_NOT_WRITABLE -> R.string.export_failed_read_only + BackupFailure.CANNOT_CREATE_FILE -> R.string.export_failed_create + BackupFailure.LOST_ACCESS -> R.string.export_failed_access + BackupFailure.WRITE_FAILED -> R.string.export_failed + BackupFailure.READ_FAILED -> R.string.backup_failed_read + BackupFailure.NO_LISTS -> R.string.backup_failed_no_lists } -private const val MINUTES_PER_DAY = 1_440 -private const val MINUTES_PER_WEEK = 10_080 +private const val STATUS_TICK_MILLIS = 60_000L + diff --git a/app/src/main/res/values/strings.xml b/app/src/main/res/values/strings.xml index 41a4ac6..cb57497 100644 --- a/app/src/main/res/values/strings.xml +++ b/app/src/main/res/values/strings.xml @@ -570,6 +570,7 @@ Saves all your lists as a dated zip in a folder you pick. Restore one with Import tasks. Folder Choose a folder + That folder can\'t be kept for backups in the background. Pick another one. Frequency Android may run a backup a little later than this to save battery. @@ -595,10 +596,12 @@ No backup yet Last backup %1$s Backup failed %1$s. %2$s + Your tasks could not be read + There were no lists to back up Automatic backup When automatic backups keep failing Automatic backup failed - Your tasks are not being backed up. Tap to check the backup folder. + Your tasks are not being backed up. Tap to see why. Import tasks diff --git a/app/src/test/java/de/jeanlucmakiola/agendula/data/backup/AutoBackupPolicyTest.kt b/app/src/test/java/de/jeanlucmakiola/agendula/data/backup/AutoBackupPolicyTest.kt index 679b610..09d0f95 100644 --- a/app/src/test/java/de/jeanlucmakiola/agendula/data/backup/AutoBackupPolicyTest.kt +++ b/app/src/test/java/de/jeanlucmakiola/agendula/data/backup/AutoBackupPolicyTest.kt @@ -2,24 +2,28 @@ package de.jeanlucmakiola.agendula.data.backup import com.google.common.truth.Truth.assertThat import org.junit.jupiter.api.Test -import java.time.LocalDateTime +import java.time.Instant class AutoBackupPolicyTest { - private fun name(day: Int, hour: Int = 3) = AutoBackupPolicy.fileName(LocalDateTime.of(2026, 11, day, hour, 0, 5)) + private fun at(day: Int, hour: Int = 3): Instant = + Instant.parse("2026-11-%02dT%02d:00:05Z".format(day, hour)) + + private fun name(day: Int, hour: Int = 3) = AutoBackupPolicy.fileName(at(day, hour)) @Test - fun `names a backup by its local time`() { - assertThat(AutoBackupPolicy.fileName(LocalDateTime.of(2026, 1, 2, 9, 4, 7))) - .isEqualTo("agendula-backup-2026-01-02-090407.zip") + fun `names a backup by its UTC time`() { + assertThat(AutoBackupPolicy.fileName(Instant.parse("2026-01-02T09:04:07Z"))) + .isEqualTo("agendula-backup-2026-01-02-090407Z.zip") } @Test fun `reads the time back out of its own names only`() { - assertThat(AutoBackupPolicy.timestampOf(name(17))).isEqualTo(LocalDateTime.of(2026, 11, 17, 3, 0, 5)) + assertThat(AutoBackupPolicy.timestampOf(name(17))).isEqualTo(at(17)) assertThat(AutoBackupPolicy.timestampOf("agendula-tasks.zip")).isNull() - assertThat(AutoBackupPolicy.timestampOf("agendula-backup-2026-11-17-030005 (1).zip")).isNull() - assertThat(AutoBackupPolicy.timestampOf("agendula-backup-2026-13-40-030005.zip")).isNull() + assertThat(AutoBackupPolicy.timestampOf("agendula-backup-2026-11-17-030005Z (1).zip")).isNull() + assertThat(AutoBackupPolicy.timestampOf("agendula-backup-2026-13-40-030005Z.zip")).isNull() + assertThat(AutoBackupPolicy.timestampOf(AutoBackupPolicy.partialName(name(17)))).isNull() } @Test @@ -36,7 +40,7 @@ class AutoBackupPolicyTest { @Test fun `rotation leaves files that are not backups alone`() { - val names = listOf("notes.txt", "agendula-tasks.zip", name(1), name(2)) + val names = listOf("notes.txt", "agendula-tasks.zip", AutoBackupPolicy.partialName(name(3)), name(1), name(2)) assertThat(AutoBackupPolicy.staleBackups(names, keep = 1)).containsExactly(name(1)) } @@ -50,6 +54,12 @@ class AutoBackupPolicyTest { assertThat(AutoBackupPolicy.staleBackups(listOf(name(1), name(2)), keep = 7)).isEmpty() } + @Test + fun `finds partial backups a killed run left behind`() { + val partial = AutoBackupPolicy.partialName(name(1)) + assertThat(AutoBackupPolicy.abandonedPartials(listOf(partial, name(1), "notes.partial"))).containsExactly(partial) + } + @Test fun `clamps the user's choices`() { assertThat(AutoBackupPolicy.clampInterval(15)).isEqualTo(AutoBackupPolicy.MIN_INTERVAL_MINUTES) From 47a79413b12f0644837beb5526085588bc8453b8 Mon Sep 17 00:00:00 2001 From: Jean-Luc Makiola Date: Tue, 17 Nov 2026 11:17:19 +0100 Subject: [PATCH 3/4] Address second review of automatic backup (#77) Retry transient failures, keep future-dated files out of rotation, forget folders without a grant after a restore, let the scheduler own the first backup, show the last good backup after failures. --- .../agendula/data/backup/AutoBackupPolicy.kt | 10 ++- .../agendula/data/backup/AutoBackupPrefs.kt | 62 ++++++++++++---- .../data/backup/AutoBackupScheduler.kt | 52 ++++++++++++-- .../agendula/data/backup/AutoBackupWorker.kt | 20 +++--- .../agendula/data/export/ExportWriter.kt | 71 ++++++++++++------- .../agendula/ui/export/ExportScreen.kt | 2 +- .../ui/settings/AutoBackupViewModel.kt | 21 +++--- .../agendula/ui/settings/BackupScreen.kt | 30 ++++---- app/src/main/res/values/strings.xml | 1 + .../data/backup/AutoBackupPolicyTest.kt | 20 ++++-- 10 files changed, 203 insertions(+), 86 deletions(-) diff --git a/app/src/main/java/de/jeanlucmakiola/agendula/data/backup/AutoBackupPolicy.kt b/app/src/main/java/de/jeanlucmakiola/agendula/data/backup/AutoBackupPolicy.kt index f92bbc2..82221a9 100644 --- a/app/src/main/java/de/jeanlucmakiola/agendula/data/backup/AutoBackupPolicy.kt +++ b/app/src/main/java/de/jeanlucmakiola/agendula/data/backup/AutoBackupPolicy.kt @@ -46,9 +46,13 @@ object AutoBackupPolicy { runCatching { LocalDateTime.parse(match.groupValues[1], STAMP).toInstant(ZoneOffset.UTC) }.getOrNull() } - /** The backups in [names] beyond the newest [keep], newest first. */ - fun staleBackups(names: Collection, keep: Int): List = - names.mapNotNull { name -> timestampOf(name)?.let { name to it } } + /** + * The backups in [names] beyond the newest [keep], newest first. A name dated + * after [now] (a skewed clock, another device) is left out of the ranking + * altogether: counted, it would outrank and rotate away the backup just written. + */ + fun staleBackups(names: Collection, keep: Int, now: Instant): List = + names.mapNotNull { name -> timestampOf(name)?.takeIf { !it.isAfter(now) }?.let { name to it } } .sortedByDescending { it.second } .drop(clampKeep(keep)) .map { it.first } diff --git a/app/src/main/java/de/jeanlucmakiola/agendula/data/backup/AutoBackupPrefs.kt b/app/src/main/java/de/jeanlucmakiola/agendula/data/backup/AutoBackupPrefs.kt index bf75352..745f349 100644 --- a/app/src/main/java/de/jeanlucmakiola/agendula/data/backup/AutoBackupPrefs.kt +++ b/app/src/main/java/de/jeanlucmakiola/agendula/data/backup/AutoBackupPrefs.kt @@ -25,26 +25,39 @@ data class AutoBackupConfig( val active: Boolean get() = enabled && folderUri != null } -/** Why an automatic backup failed: the export's write failures, plus the two before any write. */ -enum class BackupFailure { - FOLDER_UNAVAILABLE, - FOLDER_NOT_WRITABLE, - CANNOT_CREATE_FILE, - LOST_ACCESS, - WRITE_FAILED, - READ_FAILED, - NO_LISTS, +/** + * Why an automatic backup failed: the export's write failures ([export]), plus + * the two that happen before anything is written. [transient] ones are retried. + */ +enum class BackupFailure(val export: ExportFailure?, val transient: Boolean) { + FOLDER_UNAVAILABLE(ExportFailure.FOLDER_UNAVAILABLE, transient = true), + FOLDER_NOT_WRITABLE(ExportFailure.FOLDER_NOT_WRITABLE, transient = false), + CANNOT_CREATE_FILE(ExportFailure.CANNOT_CREATE_FILE, transient = true), + LOST_ACCESS(ExportFailure.LOST_ACCESS, transient = false), + WRITE_FAILED(ExportFailure.WRITE_FAILED, transient = true), + READ_FAILED(null, transient = true), + NO_LISTS(null, transient = false), ; companion object { - fun of(failure: ExportFailure): BackupFailure = valueOf(failure.name) + fun of(failure: ExportFailure): BackupFailure = when (failure) { + ExportFailure.FOLDER_UNAVAILABLE -> FOLDER_UNAVAILABLE + ExportFailure.FOLDER_NOT_WRITABLE -> FOLDER_NOT_WRITABLE + ExportFailure.CANNOT_CREATE_FILE -> CANNOT_CREATE_FILE + ExportFailure.LOST_ACCESS -> LOST_ACCESS + ExportFailure.WRITE_FAILED -> WRITE_FAILED + } } } -/** How the last automatic backup went; [lastRunMillis] 0 = never ran, [failure] null = it worked. */ +/** + * How the automatic backup has gone: [lastRunMillis] 0 = never ran, [failure] + * null = the last run worked, [lastSuccessMillis] 0 = none has yet. + */ data class AutoBackupStatus( val lastRunMillis: Long = 0L, val failure: BackupFailure? = null, + val lastSuccessMillis: Long = 0L, ) /** The automatic backup's settings and last outcome, in the app's DataStore. */ @@ -65,18 +78,32 @@ class AutoBackupPrefs @Inject constructor( val status: Flow = dataStore.data.map { p -> AutoBackupStatus( lastRunMillis = p[LAST_RUN] ?: 0L, + lastSuccessMillis = p[LAST_SUCCESS_AT] ?: 0L, failure = p[FAILURE_REASON]?.let { runCatching { BackupFailure.valueOf(it) }.getOrDefault(BackupFailure.WRITE_FAILED) }, ) }.distinctUntilChanged() - suspend fun setEnabled(enabled: Boolean) = dataStore.edit { it[ENABLED] = enabled } + /** A fresh start, on or off, also restarts the count towards the failure notification. */ + suspend fun setEnabled(enabled: Boolean) = dataStore.edit { + it[ENABLED] = enabled + it.remove(FAILURES) + } /** Points the backup at [uri] and turns it on; the caller has taken the grant. */ suspend fun setFolder(uri: String) = dataStore.edit { it[FOLDER] = uri it[ENABLED] = true + it.remove(FAILURES) + } + + /** Forgets a folder this install holds no grant for, e.g. settings restored onto a new device. */ + suspend fun forgetFolder(uri: String) = dataStore.edit { + if (it[FOLDER] != uri) return@edit + it.remove(FOLDER) + it[ENABLED] = false + listOf(LAST_RUN, LAST_SUCCESS_AT, FAILURES, FAILURE_REASON).forEach { key -> it.remove(key) } } suspend fun setIntervalMinutes(minutes: Int) = @@ -86,15 +113,19 @@ class AutoBackupPrefs @Inject constructor( suspend fun recordSuccess(atMillis: Long) = dataStore.edit { it[LAST_RUN] = atMillis + it[LAST_SUCCESS_AT] = atMillis it[FAILURES] = 0 it.remove(FAILURE_REASON) } - /** Returns how many runs in a row have now failed. */ - suspend fun recordFailure(atMillis: Long, reason: BackupFailure): Int { + /** + * Records a failed attempt. Only [final] attempts — no retry left — count + * towards the failure notification; returns how many runs in a row have failed. + */ + suspend fun recordFailure(atMillis: Long, reason: BackupFailure, final: Boolean): Int { var failures = 0 dataStore.edit { - failures = (it[FAILURES] ?: 0) + 1 + failures = (it[FAILURES] ?: 0) + if (final) 1 else 0 it[LAST_RUN] = atMillis it[FAILURES] = failures it[FAILURE_REASON] = reason.name @@ -108,6 +139,7 @@ class AutoBackupPrefs @Inject constructor( val INTERVAL = intPreferencesKey("auto_backup_interval_minutes") val KEEP = intPreferencesKey("auto_backup_keep") val LAST_RUN = longPreferencesKey("auto_backup_last_run") + val LAST_SUCCESS_AT = longPreferencesKey("auto_backup_last_success_at") val FAILURES = intPreferencesKey("auto_backup_failures") val FAILURE_REASON = stringPreferencesKey("auto_backup_failure_reason") } diff --git a/app/src/main/java/de/jeanlucmakiola/agendula/data/backup/AutoBackupScheduler.kt b/app/src/main/java/de/jeanlucmakiola/agendula/data/backup/AutoBackupScheduler.kt index 86b7540..739d1ad 100644 --- a/app/src/main/java/de/jeanlucmakiola/agendula/data/backup/AutoBackupScheduler.kt +++ b/app/src/main/java/de/jeanlucmakiola/agendula/data/backup/AutoBackupScheduler.kt @@ -1,6 +1,7 @@ package de.jeanlucmakiola.agendula.data.backup import android.content.Context +import androidx.work.BackoffPolicy import androidx.work.ExistingPeriodicWorkPolicy import androidx.work.ExistingWorkPolicy import androidx.work.OneTimeWorkRequestBuilder @@ -12,6 +13,7 @@ import de.jeanlucmakiola.agendula.data.di.ApplicationScope import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.flow.Flow import kotlinx.coroutines.flow.distinctUntilChanged +import kotlinx.coroutines.flow.first import kotlinx.coroutines.flow.map import kotlinx.coroutines.launch import java.util.concurrent.TimeUnit @@ -22,6 +24,9 @@ import javax.inject.Singleton * Keeps WorkManager in step with [AutoBackupPrefs]: a unique periodic request * while the backup is on and has a folder, nothing otherwise. Reactive, so every * settings change (and every launch) reconciles without the caller having to. + * Turning the backup on, or pointing it at a new folder, also takes one backup + * at once — here rather than at the call site, so it is ordered after any + * cancellation an earlier "off" caused. */ @Singleton class AutoBackupScheduler @Inject constructor( @@ -31,31 +36,62 @@ class AutoBackupScheduler @Inject constructor( @ApplicationScope private val scope: CoroutineScope, ) { + private data class Plan(val folderUri: String, val intervalMinutes: Int) + /** Call once, from `Application.onCreate`. */ fun start() { scope.launch { + runCatching { forgetUngrantedFolder() } + var previous: Plan? = null + var first = true prefs.config - .map { if (it.active) it.intervalMinutes else null } + .map { config -> config.folderUri?.takeIf { config.active }?.let { Plan(it, config.intervalMinutes) } } .distinctUntilChanged() - .collect { interval -> runCatching { apply(interval) } } + .collect { plan -> + runCatching { + apply(plan?.intervalMinutes) + if (!first && plan != null && plan.folderUri != previous?.folderUri) runNow() + } + previous = plan + first = false + } } } - /** One backup now, e.g. right after a folder is picked. Rapid taps coalesce. */ + /** One backup now. A newer request replaces a queued or running one, so it runs on the current settings. */ fun runNow() { WorkManager.getInstance(context).enqueueUniqueWork( WORK_NAME_NOW, - ExistingWorkPolicy.KEEP, - OneTimeWorkRequestBuilder().build(), + ExistingWorkPolicy.REPLACE, + OneTimeWorkRequestBuilder() + .setBackoffCriteria(BackoffPolicy.EXPONENTIAL, BACKOFF_MINUTES, TimeUnit.MINUTES) + .build(), ) } - /** Whether a [runNow] backup is queued or running. */ + /** Whether a [runNow] backup is about to run or running; waiting out a retry does not count. */ val runningNow: Flow = WorkManager.getInstance(context).getWorkInfosForUniqueWorkFlow(WORK_NAME_NOW) - .map { infos -> infos.any { !it.state.isFinished && it.state != WorkInfo.State.BLOCKED } } + .map { infos -> + infos.any { + it.state == WorkInfo.State.RUNNING || + (it.state == WorkInfo.State.ENQUEUED && it.runAttemptCount == 0) + } + } .distinctUntilChanged() + /** + * Settings restored onto another device (Android's own backup) bring the + * folder along but not the grant to write to it; every run would fail. + */ + private suspend fun forgetUngrantedFolder() { + val folder = prefs.config.first().folderUri ?: return + val granted = context.contentResolver.persistedUriPermissions.any { + it.uri.toString() == folder && it.isWritePermission + } + if (!granted) prefs.forgetFolder(folder) + } + /** [intervalMinutes] null cancels. The first periodic run waits one interval. */ private fun apply(intervalMinutes: Int?) { val workManager = WorkManager.getInstance(context) @@ -68,6 +104,7 @@ class AutoBackupScheduler @Inject constructor( val minutes = intervalMinutes.toLong() val request = PeriodicWorkRequestBuilder(minutes, TimeUnit.MINUTES) .setInitialDelay(minutes, TimeUnit.MINUTES) + .setBackoffCriteria(BackoffPolicy.EXPONENTIAL, BACKOFF_MINUTES, TimeUnit.MINUTES) .build() workManager.enqueueUniquePeriodicWork(WORK_NAME, ExistingPeriodicWorkPolicy.UPDATE, request) } @@ -75,5 +112,6 @@ class AutoBackupScheduler @Inject constructor( private companion object { const val WORK_NAME = "auto-backup" const val WORK_NAME_NOW = "auto-backup-now" + const val BACKOFF_MINUTES = 10L } } diff --git a/app/src/main/java/de/jeanlucmakiola/agendula/data/backup/AutoBackupWorker.kt b/app/src/main/java/de/jeanlucmakiola/agendula/data/backup/AutoBackupWorker.kt index 1bf42ab..0081693 100644 --- a/app/src/main/java/de/jeanlucmakiola/agendula/data/backup/AutoBackupWorker.kt +++ b/app/src/main/java/de/jeanlucmakiola/agendula/data/backup/AutoBackupWorker.kt @@ -23,8 +23,10 @@ import kotlin.coroutines.cancellation.CancellationException /** * One automatic backup: every list of the current store, as the export's zip, * into a new dated file in the chosen folder, then rotation down to the kept - * count. A failure is recorded for the settings status line and, once it - * repeats, raised as a notification; a periodic request still runs next time. + * count. A transient failure is retried a few times with backoff; every + * failure is recorded for the settings status line, and a run that has given + * up twice in a row raises a notification. A periodic request runs again next + * interval either way. */ @HiltWorker class AutoBackupWorker @AssistedInject constructor( @@ -50,10 +52,10 @@ class AutoBackupWorker @AssistedInject constructor( startupGate.awaitReady() val documents = readLists() val tree = folder.toUri() - val fileName = AutoBackupPolicy.fileName(Instant.ofEpochMilli(now)) - writer.writeZipToTree(tree, fileName, AutoBackupPolicy.partialName(fileName), documents) - writer.deleteFromTree(tree) { names -> - AutoBackupPolicy.staleBackups(names, config.keepCount) + AutoBackupPolicy.abandonedPartials(names) + val stamp = Instant.ofEpochMilli(now) + val fileName = AutoBackupPolicy.fileName(stamp) + writer.writeZipToTree(tree, fileName, AutoBackupPolicy.partialName(fileName), documents) { names -> + AutoBackupPolicy.staleBackups(names, config.keepCount, stamp) + AutoBackupPolicy.abandonedPartials(names) } prefs.recordSuccess(now) notifier.cancelFailure() @@ -67,8 +69,9 @@ class AutoBackupWorker @AssistedInject constructor( is ExportFailedException -> BackupFailure.of(error.failure) else -> BackupFailure.of(ExportFailure.WRITE_FAILED) } - if (prefs.recordFailure(now, reason) >= FAILURE_NOTIFY_THRESHOLD) notifier.postFailure() - Result.failure() + val retry = reason.transient && runAttemptCount < MAX_RETRIES + if (prefs.recordFailure(now, reason, final = !retry) >= FAILURE_NOTIFY_THRESHOLD) notifier.postFailure() + if (retry) Result.retry() else Result.failure() } } @@ -93,6 +96,7 @@ class AutoBackupWorker @AssistedInject constructor( private companion object { const val TAG = "AutoBackupWorker" const val FAILURE_NOTIFY_THRESHOLD = 2 + const val MAX_RETRIES = 3 val runLock = Mutex() } } diff --git a/app/src/main/java/de/jeanlucmakiola/agendula/data/export/ExportWriter.kt b/app/src/main/java/de/jeanlucmakiola/agendula/data/export/ExportWriter.kt index b3abfed..ec71c71 100644 --- a/app/src/main/java/de/jeanlucmakiola/agendula/data/export/ExportWriter.kt +++ b/app/src/main/java/de/jeanlucmakiola/agendula/data/export/ExportWriter.kt @@ -99,44 +99,61 @@ class ExportWriter @Inject constructor( } /** - * Writes every document into a new zip named [fileName] inside [treeUri]. + * Writes every document into a new zip named [fileName] inside [treeUri], + * then deletes the files [prune] picks from the folder's names (best effort: + * a file that will not go is left, and the write still counts). * - * The zip is written under [partialName] and renamed once complete, so a run - * that fails — or a process killed mid-write — never leaves a truncated file - * under a finished name. A provider that cannot rename gets the zip written - * under [fileName] directly. An existing [fileName] is left as it is. + * Where the provider can rename, the zip is written under [partialName] and + * renamed once complete, so a run that fails — or a process killed mid-write + * — never leaves a truncated file under a finished name. Elsewhere it is + * written under [fileName] directly. An existing [fileName] is left as it is. */ suspend fun writeZipToTree( treeUri: Uri, fileName: String, partialName: String, documents: List, + prune: (Set) -> Collection = { emptyList() }, ): ExportResult = withContext(io) { - runCatching { + val children = runCatching { val tree = openWritableTree(treeUri) - if (fileName !in childDocuments(treeUri)) { - val partial = createAndZip(tree, MIME_PARTIAL, partialName, documents) - if (!runCatching { partial.renameTo(fileName) }.getOrDefault(false)) { - runCatching { partial.delete() } - createAndZip(tree, MIME_ZIP, fileName, documents) - } - } + val children = childDocuments(treeUri) + if (fileName !in children) writeViaPartial(tree, fileName, partialName, documents) + children - partialName }.getOrElse { throw asExportFailure(it) } + prune(children.keys + fileName).forEach { name -> + val uri = children[name] ?: return@forEach + runCatching { DocumentsContract.deleteDocument(context.contentResolver, uri) } + } ExportResult(documents.size, documents.map { it.fileName }) } - /** - * Deletes the files of [treeUri] that [select] picks from the folder's file - * names. Best effort: a file that will not go is left and the rest still are. - */ - suspend fun deleteFromTree(treeUri: Uri, select: (Set) -> Collection): Int = - withContext(io) { - val children = runCatching { childDocuments(treeUri) }.getOrDefault(emptyMap()) - select(children.keys).count { name -> - val uri = children[name] ?: return@count false - runCatching { DocumentsContract.deleteDocument(context.contentResolver, uri) }.getOrDefault(false) - } + private fun writeViaPartial( + tree: DocumentFile, + fileName: String, + partialName: String, + documents: List, + ) { + val partial = tree.createFile(MIME_PARTIAL, partialName) + if (partial == null || !partial.supportsRename()) { + partial?.let { runCatching { it.delete() } } + createAndZip(tree, MIME_ZIP, fileName, documents) + return } + zipOrDelete(partial, documents) + if (!runCatching { partial.renameTo(fileName) }.getOrDefault(false)) { + runCatching { partial.delete() } + createAndZip(tree, MIME_ZIP, fileName, documents) + } + } + + private fun DocumentFile.supportsRename(): Boolean = runCatching { + context.contentResolver.query(uri, arrayOf(DocumentsContract.Document.COLUMN_FLAGS), null, null, null) + ?.use { cursor -> + cursor.moveToFirst() && + cursor.getInt(0) and DocumentsContract.Document.FLAG_SUPPORTS_RENAME != 0 + } ?: false + }.getOrDefault(false) private fun createAndZip( tree: DocumentFile, @@ -145,13 +162,17 @@ class ExportWriter @Inject constructor( documents: List, ): DocumentFile { val file = tree.createFile(mime, name) ?: throw ExportFailedException(ExportFailure.CANNOT_CREATE_FILE) + zipOrDelete(file, documents) + return file + } + + private fun zipOrDelete(file: DocumentFile, documents: List) { try { zipInto(file.uri, documents) } catch (error: Exception) { runCatching { file.delete() } throw error } - return file } /** The folder's files by name, in one provider query rather than one per file. */ diff --git a/app/src/main/java/de/jeanlucmakiola/agendula/ui/export/ExportScreen.kt b/app/src/main/java/de/jeanlucmakiola/agendula/ui/export/ExportScreen.kt index e1557ed..fb797ef 100644 --- a/app/src/main/java/de/jeanlucmakiola/agendula/ui/export/ExportScreen.kt +++ b/app/src/main/java/de/jeanlucmakiola/agendula/ui/export/ExportScreen.kt @@ -339,7 +339,7 @@ private fun openIntent(destination: ExportDestination): Intent? = runCatching { private fun Context.canHandle(intent: Intent): Boolean = packageManager.queryIntentActivities(intent, 0).isNotEmpty() -private fun failureMessage(reason: ExportFailure): Int = when (reason) { +internal fun failureMessage(reason: ExportFailure): Int = when (reason) { ExportFailure.FOLDER_UNAVAILABLE -> R.string.export_failed_folder ExportFailure.FOLDER_NOT_WRITABLE -> R.string.export_failed_read_only ExportFailure.CANNOT_CREATE_FILE -> R.string.export_failed_create diff --git a/app/src/main/java/de/jeanlucmakiola/agendula/ui/settings/AutoBackupViewModel.kt b/app/src/main/java/de/jeanlucmakiola/agendula/ui/settings/AutoBackupViewModel.kt index 99c65bd..c5c2450 100644 --- a/app/src/main/java/de/jeanlucmakiola/agendula/ui/settings/AutoBackupViewModel.kt +++ b/app/src/main/java/de/jeanlucmakiola/agendula/ui/settings/AutoBackupViewModel.kt @@ -22,6 +22,7 @@ import kotlinx.coroutines.flow.combine import kotlinx.coroutines.flow.distinctUntilChanged import kotlinx.coroutines.flow.first import kotlinx.coroutines.flow.map +import kotlinx.coroutines.flow.onStart import kotlinx.coroutines.flow.stateIn import kotlinx.coroutines.launch import kotlinx.coroutines.withContext @@ -49,10 +50,11 @@ class AutoBackupViewModel @Inject constructor( private val folderRejected = MutableStateFlow(false) // A provider query, so off the main thread: the folder may be on an SD card - // or a cloud provider that is slow to answer. + // or a cloud provider that is slow to answer. Starts unknown so the rest of + // the screen does not wait for it. private val folderName = prefs.config.map { it.folderUri }.distinctUntilChanged().map { uri -> uri?.let { withContext(io) { runCatching { DocumentFile.fromTreeUri(context, it.toUri())?.name }.getOrNull() } } - } + }.onStart { emit(null) } val state: StateFlow = combine(prefs.config, prefs.status, scheduler.runningNow, folderName, folderRejected) { @@ -60,17 +62,19 @@ class AutoBackupViewModel @Inject constructor( AutoBackupUiState(config, status, running, name, rejected) }.stateIn(viewModelScope, SharingStarted.WhileSubscribed(5_000), AutoBackupUiState()) - /** Turning it on without a folder is the screen's to handle: it asks for one first. */ + /** + * Turning it on without a folder is the screen's to handle: it asks for one + * first. The scheduler takes the first backup once it is on. + */ fun setEnabled(enabled: Boolean) { - viewModelScope.launch { - prefs.setEnabled(enabled) - if (enabled && prefs.config.first().active) scheduler.runNow() - } + if (!enabled) folderRejected.value = false + viewModelScope.launch { prefs.setEnabled(enabled) } } /** * Keeps a persisted grant on [tree] so background runs can write to it, lets - * go of the previous folder's, turns the backup on and takes one right away. + * go of the previous folder's and turns the backup on; the scheduler takes a + * backup into the new folder right away. */ fun chooseFolder(tree: Uri) { viewModelScope.launch { @@ -84,7 +88,6 @@ class AutoBackupViewModel @Inject constructor( if (previous != null && previous != tree) { runCatching { resolver.releasePersistableUriPermission(previous, flags) } } - scheduler.runNow() } } diff --git a/app/src/main/java/de/jeanlucmakiola/agendula/ui/settings/BackupScreen.kt b/app/src/main/java/de/jeanlucmakiola/agendula/ui/settings/BackupScreen.kt index f5ec319..9e938a4 100644 --- a/app/src/main/java/de/jeanlucmakiola/agendula/ui/settings/BackupScreen.kt +++ b/app/src/main/java/de/jeanlucmakiola/agendula/ui/settings/BackupScreen.kt @@ -26,6 +26,7 @@ import de.jeanlucmakiola.agendula.R import de.jeanlucmakiola.agendula.data.backup.AutoBackupPolicy import de.jeanlucmakiola.agendula.data.backup.BackupFailure import de.jeanlucmakiola.agendula.ui.common.reminderUnitLabel +import de.jeanlucmakiola.agendula.ui.export.failureMessage import de.jeanlucmakiola.floret.components.CollapsingScaffold import de.jeanlucmakiola.floret.components.CustomAmountEditor import de.jeanlucmakiola.floret.components.CustomExpandRow @@ -90,9 +91,6 @@ internal fun BackupScreen( }, position = if (config.active) Position.Top else Position.Alone, ) - if (state.folderRejected) { - GroupedHint(stringResource(R.string.backup_auto_folder_rejected), style = MaterialTheme.typography.bodySmall) - } if (config.active) { GroupedRow( title = stringResource(R.string.backup_auto_folder), @@ -121,6 +119,9 @@ internal fun BackupScreen( ) GroupedHint(backupStatusText(state), style = MaterialTheme.typography.bodySmall) } + if (state.folderRejected) { + GroupedHint(stringResource(R.string.backup_auto_folder_rejected), style = MaterialTheme.typography.bodySmall) + } Spacer(Modifier.height(24.dp)) } @@ -260,23 +261,26 @@ private fun backupStatusText(state: AutoBackupUiState): String { state.running -> stringResource(R.string.backup_auto_status_running) status.lastRunMillis == 0L -> stringResource(R.string.backup_auto_status_never) failure == null -> stringResource(R.string.backup_auto_status_ok, relativeTimeAgo(status.lastRunMillis, now)) - else -> stringResource( + status.lastSuccessMillis == 0L -> stringResource( R.string.backup_auto_status_failed, relativeTimeAgo(status.lastRunMillis, now), stringResource(backupFailureMessage(failure)), ) + // After a run of failures, when the last good one was is what matters. + else -> stringResource( + R.string.backup_auto_status_failed_last_ok, + relativeTimeAgo(status.lastRunMillis, now), + stringResource(backupFailureMessage(failure)), + relativeTimeAgo(status.lastSuccessMillis, now), + ) } } -private fun backupFailureMessage(failure: BackupFailure): Int = when (failure) { - BackupFailure.FOLDER_UNAVAILABLE -> R.string.export_failed_folder - BackupFailure.FOLDER_NOT_WRITABLE -> R.string.export_failed_read_only - BackupFailure.CANNOT_CREATE_FILE -> R.string.export_failed_create - BackupFailure.LOST_ACCESS -> R.string.export_failed_access - BackupFailure.WRITE_FAILED -> R.string.export_failed - BackupFailure.READ_FAILED -> R.string.backup_failed_read - BackupFailure.NO_LISTS -> R.string.backup_failed_no_lists -} +private fun backupFailureMessage(failure: BackupFailure): Int = failure.export?.let(::failureMessage) + ?: when (failure) { + BackupFailure.NO_LISTS -> R.string.backup_failed_no_lists + else -> R.string.backup_failed_read + } private const val STATUS_TICK_MILLIS = 60_000L diff --git a/app/src/main/res/values/strings.xml b/app/src/main/res/values/strings.xml index cb57497..c15ada9 100644 --- a/app/src/main/res/values/strings.xml +++ b/app/src/main/res/values/strings.xml @@ -596,6 +596,7 @@ No backup yet Last backup %1$s Backup failed %1$s. %2$s + Backup failed %1$s. %2$s. Last good backup %3$s Your tasks could not be read There were no lists to back up Automatic backup diff --git a/app/src/test/java/de/jeanlucmakiola/agendula/data/backup/AutoBackupPolicyTest.kt b/app/src/test/java/de/jeanlucmakiola/agendula/data/backup/AutoBackupPolicyTest.kt index 09d0f95..a071d37 100644 --- a/app/src/test/java/de/jeanlucmakiola/agendula/data/backup/AutoBackupPolicyTest.kt +++ b/app/src/test/java/de/jeanlucmakiola/agendula/data/backup/AutoBackupPolicyTest.kt @@ -11,6 +11,10 @@ class AutoBackupPolicyTest { private fun name(day: Int, hour: Int = 3) = AutoBackupPolicy.fileName(at(day, hour)) + private companion object { + val NOW: Instant = Instant.parse("2026-11-30T00:00:00Z") + } + @Test fun `names a backup by its UTC time`() { assertThat(AutoBackupPolicy.fileName(Instant.parse("2026-01-02T09:04:07Z"))) @@ -29,29 +33,35 @@ class AutoBackupPolicyTest { @Test fun `rotation drops everything beyond the newest kept`() { val names = listOf(name(3), name(1), name(5), name(4), name(2)) - assertThat(AutoBackupPolicy.staleBackups(names, keep = 3)).containsExactly(name(2), name(1)).inOrder() + assertThat(AutoBackupPolicy.staleBackups(names, keep = 3, now = NOW)).containsExactly(name(2), name(1)).inOrder() } @Test fun `rotation orders by time within a day`() { val names = listOf(name(1, hour = 23), name(1, hour = 9), name(1, hour = 10)) - assertThat(AutoBackupPolicy.staleBackups(names, keep = 1)).containsExactly(name(1, hour = 10), name(1, hour = 9)) + assertThat(AutoBackupPolicy.staleBackups(names, keep = 1, now = NOW)).containsExactly(name(1, hour = 10), name(1, hour = 9)) } @Test fun `rotation leaves files that are not backups alone`() { val names = listOf("notes.txt", "agendula-tasks.zip", AutoBackupPolicy.partialName(name(3)), name(1), name(2)) - assertThat(AutoBackupPolicy.staleBackups(names, keep = 1)).containsExactly(name(1)) + assertThat(AutoBackupPolicy.staleBackups(names, keep = 1, now = NOW)).containsExactly(name(1)) } @Test fun `rotation keeps at least the newest backup`() { - assertThat(AutoBackupPolicy.staleBackups(listOf(name(1), name(2)), keep = 0)).containsExactly(name(1)) + assertThat(AutoBackupPolicy.staleBackups(listOf(name(1), name(2)), keep = 0, now = NOW)).containsExactly(name(1)) } @Test fun `nothing is stale while under the limit`() { - assertThat(AutoBackupPolicy.staleBackups(listOf(name(1), name(2)), keep = 7)).isEmpty() + assertThat(AutoBackupPolicy.staleBackups(listOf(name(1), name(2)), keep = 7, now = NOW)).isEmpty() + } + + @Test + fun `a backup dated in the future never outranks the one just written`() { + val names = listOf("agendula-backup-2027-06-01-000000Z.zip", name(5), name(4)) + assertThat(AutoBackupPolicy.staleBackups(names, keep = 1, now = NOW)).containsExactly(name(4)) } @Test From 7642c49ef68711dcefb70a645a01316bf7d7dd0f Mon Sep 17 00:00:00 2001 From: Jean-Luc Makiola Date: Tue, 17 Nov 2026 11:26:12 +0100 Subject: [PATCH 4/4] Address third review of automatic backup (#77) Rotation never removes the backup just written, unreachable folders are retried, the running state covers scheduled runs, and a folder switch mid-run no longer records a failure. --- .../de/jeanlucmakiola/agendula/AgendulaApp.kt | 2 +- .../agendula/data/backup/AutoBackupPolicy.kt | 16 +++++++----- .../agendula/data/backup/AutoBackupPrefs.kt | 8 +----- .../data/backup/AutoBackupScheduler.kt | 26 +++++++++++-------- .../agendula/data/backup/AutoBackupWorker.kt | 14 +++++----- .../agendula/data/export/ExportWriter.kt | 2 ++ .../ui/settings/AutoBackupViewModel.kt | 6 ++--- .../agendula/ui/settings/BackupScreen.kt | 8 +++--- .../data/backup/AutoBackupPolicyTest.kt | 23 +++++++++------- 9 files changed, 54 insertions(+), 51 deletions(-) diff --git a/app/src/main/java/de/jeanlucmakiola/agendula/AgendulaApp.kt b/app/src/main/java/de/jeanlucmakiola/agendula/AgendulaApp.kt index 94fe777..4d686f1 100644 --- a/app/src/main/java/de/jeanlucmakiola/agendula/AgendulaApp.kt +++ b/app/src/main/java/de/jeanlucmakiola/agendula/AgendulaApp.kt @@ -75,6 +75,7 @@ class AgendulaApp : Application(), Configuration.Provider { if (started.get()) runCatching { entryPoint.taskNotifier().refreshChannel() } } startupGate.start() + entryPoint.autoBackupScheduler().start() refreshNotificationChannels() ProcessLifecycleOwner.get().lifecycle.addObserver(entryPoint.databaseCheckpoint()) scope.launch { @@ -90,7 +91,6 @@ class AgendulaApp : Application(), Configuration.Provider { runCatching { entryPoint.reminderRefresher().start() } runCatching { entryPoint.providerSnapshotSource().start() } runCatching { ReminderMaintenanceWorker.schedule(this@AgendulaApp) } - runCatching { entryPoint.autoBackupScheduler().start() } } } diff --git a/app/src/main/java/de/jeanlucmakiola/agendula/data/backup/AutoBackupPolicy.kt b/app/src/main/java/de/jeanlucmakiola/agendula/data/backup/AutoBackupPolicy.kt index 82221a9..bb2e116 100644 --- a/app/src/main/java/de/jeanlucmakiola/agendula/data/backup/AutoBackupPolicy.kt +++ b/app/src/main/java/de/jeanlucmakiola/agendula/data/backup/AutoBackupPolicy.kt @@ -47,21 +47,23 @@ object AutoBackupPolicy { } /** - * The backups in [names] beyond the newest [keep], newest first. A name dated - * after [now] (a skewed clock, another device) is left out of the ranking - * altogether: counted, it would outrank and rotate away the backup just written. + * The backups in [names] beyond the newest [keep], newest first. [current], + * the backup just written, always ranks first, so one dated ahead by a + * skewed clock can never rotate it away. */ - fun staleBackups(names: Collection, keep: Int, now: Instant): List = - names.mapNotNull { name -> timestampOf(name)?.takeIf { !it.isAfter(now) }?.let { name to it } } + fun staleBackups(names: Collection, keep: Int, current: String): List = + names.filter { it != current } + .mapNotNull { name -> timestampOf(name)?.let { name to it } } .sortedByDescending { it.second } - .drop(clampKeep(keep)) .map { it.first } + .drop(clampKeep(keep) - 1) /** Backups a run never finished, e.g. because the process was killed mid-write. */ fun abandonedPartials(names: Collection): List = names.filter { it.endsWith(PARTIAL_SUFFIX) && timestampOf(it.removeSuffix(PARTIAL_SUFFIX)) != null } - fun clampInterval(minutes: Int): Int = minutes.coerceIn(MIN_INTERVAL_MINUTES, MAX_INTERVAL_MINUTES) + /** Whole hours, within bounds. */ + fun clampInterval(minutes: Int): Int = (minutes / 60 * 60).coerceIn(MIN_INTERVAL_MINUTES, MAX_INTERVAL_MINUTES) fun clampKeep(count: Int): Int = count.coerceIn(1, MAX_KEEP) } diff --git a/app/src/main/java/de/jeanlucmakiola/agendula/data/backup/AutoBackupPrefs.kt b/app/src/main/java/de/jeanlucmakiola/agendula/data/backup/AutoBackupPrefs.kt index 745f349..de399b4 100644 --- a/app/src/main/java/de/jeanlucmakiola/agendula/data/backup/AutoBackupPrefs.kt +++ b/app/src/main/java/de/jeanlucmakiola/agendula/data/backup/AutoBackupPrefs.kt @@ -40,13 +40,7 @@ enum class BackupFailure(val export: ExportFailure?, val transient: Boolean) { ; companion object { - fun of(failure: ExportFailure): BackupFailure = when (failure) { - ExportFailure.FOLDER_UNAVAILABLE -> FOLDER_UNAVAILABLE - ExportFailure.FOLDER_NOT_WRITABLE -> FOLDER_NOT_WRITABLE - ExportFailure.CANNOT_CREATE_FILE -> CANNOT_CREATE_FILE - ExportFailure.LOST_ACCESS -> LOST_ACCESS - ExportFailure.WRITE_FAILED -> WRITE_FAILED - } + fun of(failure: ExportFailure): BackupFailure = entries.firstOrNull { it.export == failure } ?: WRITE_FAILED } } diff --git a/app/src/main/java/de/jeanlucmakiola/agendula/data/backup/AutoBackupScheduler.kt b/app/src/main/java/de/jeanlucmakiola/agendula/data/backup/AutoBackupScheduler.kt index 739d1ad..77c4700 100644 --- a/app/src/main/java/de/jeanlucmakiola/agendula/data/backup/AutoBackupScheduler.kt +++ b/app/src/main/java/de/jeanlucmakiola/agendula/data/backup/AutoBackupScheduler.kt @@ -12,6 +12,7 @@ import dagger.hilt.android.qualifiers.ApplicationContext import de.jeanlucmakiola.agendula.data.di.ApplicationScope import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.flow.Flow +import kotlinx.coroutines.flow.combine import kotlinx.coroutines.flow.distinctUntilChanged import kotlinx.coroutines.flow.first import kotlinx.coroutines.flow.map @@ -38,7 +39,7 @@ class AutoBackupScheduler @Inject constructor( private data class Plan(val folderUri: String, val intervalMinutes: Int) - /** Call once, from `Application.onCreate`. */ + /** Call once, first thing in `Application.onCreate`, so no settings change predates the collector. */ fun start() { scope.launch { runCatching { forgetUngrantedFolder() } @@ -69,16 +70,19 @@ class AutoBackupScheduler @Inject constructor( ) } - /** Whether a [runNow] backup is about to run or running; waiting out a retry does not count. */ - val runningNow: Flow = - WorkManager.getInstance(context).getWorkInfosForUniqueWorkFlow(WORK_NAME_NOW) - .map { infos -> - infos.any { - it.state == WorkInfo.State.RUNNING || - (it.state == WorkInfo.State.ENQUEUED && it.runAttemptCount == 0) - } - } - .distinctUntilChanged() + /** + * Whether a backup is running, or a [runNow] one is about to; a periodic one + * waiting for its time, or any run waiting out a retry, does not count. + */ + val running: Flow = WorkManager.getInstance(context).let { workManager -> + combine( + workManager.getWorkInfosForUniqueWorkFlow(WORK_NAME_NOW), + workManager.getWorkInfosForUniqueWorkFlow(WORK_NAME), + ) { now, periodic -> + now.any { it.state == WorkInfo.State.RUNNING || (it.state == WorkInfo.State.ENQUEUED && it.runAttemptCount == 0) } || + periodic.any { it.state == WorkInfo.State.RUNNING } + }.distinctUntilChanged() + } /** * Settings restored onto another device (Android's own backup) bring the diff --git a/app/src/main/java/de/jeanlucmakiola/agendula/data/backup/AutoBackupWorker.kt b/app/src/main/java/de/jeanlucmakiola/agendula/data/backup/AutoBackupWorker.kt index 0081693..231c1d2 100644 --- a/app/src/main/java/de/jeanlucmakiola/agendula/data/backup/AutoBackupWorker.kt +++ b/app/src/main/java/de/jeanlucmakiola/agendula/data/backup/AutoBackupWorker.kt @@ -9,7 +9,6 @@ import androidx.work.WorkerParameters import dagger.assisted.Assisted import dagger.assisted.AssistedInject import de.jeanlucmakiola.agendula.data.export.ExportFailedException -import de.jeanlucmakiola.agendula.data.export.ExportFailure import de.jeanlucmakiola.agendula.data.export.ExportWriter import de.jeanlucmakiola.agendula.data.export.TaskExporter import de.jeanlucmakiola.agendula.data.tasks.StartupGate @@ -39,13 +38,11 @@ class AutoBackupWorker @AssistedInject constructor( private val notifier: BackupNotifier, ) : CoroutineWorker(context, params) { - // The periodic run and "Back up now" are separate work chains; one at a time, - // or one run's rotation could delete what the other is still writing. + // One at a time across the periodic and "now" chains. override suspend fun doWork(): Result = runLock.withLock { backUp() } private suspend fun backUp(): Result { val config = prefs.config.first() - // Turned off since this was queued: nothing to do, and nothing to retry. val folder = config.folderUri?.takeIf { config.enabled } ?: return Result.success() val now = System.currentTimeMillis() return try { @@ -55,7 +52,7 @@ class AutoBackupWorker @AssistedInject constructor( val stamp = Instant.ofEpochMilli(now) val fileName = AutoBackupPolicy.fileName(stamp) writer.writeZipToTree(tree, fileName, AutoBackupPolicy.partialName(fileName), documents) { names -> - AutoBackupPolicy.staleBackups(names, config.keepCount, stamp) + AutoBackupPolicy.abandonedPartials(names) + AutoBackupPolicy.staleBackups(names, config.keepCount, fileName) + AutoBackupPolicy.abandonedPartials(names) } prefs.recordSuccess(now) notifier.cancelFailure() @@ -64,13 +61,16 @@ class AutoBackupWorker @AssistedInject constructor( throw cancelled } catch (error: Exception) { Log.w(TAG, "Automatic backup failed", error) + // The user moved the backup elsewhere mid-run; the old folder's failure is not theirs. + if (prefs.config.first().folderUri != folder) return Result.success() val reason = when (error) { is BackupFailedException -> error.failure is ExportFailedException -> BackupFailure.of(error.failure) - else -> BackupFailure.of(ExportFailure.WRITE_FAILED) + else -> BackupFailure.WRITE_FAILED } val retry = reason.transient && runAttemptCount < MAX_RETRIES - if (prefs.recordFailure(now, reason, final = !retry) >= FAILURE_NOTIFY_THRESHOLD) notifier.postFailure() + val failures = prefs.recordFailure(now, reason, final = !retry) + if (!retry && failures >= FAILURE_NOTIFY_THRESHOLD) notifier.postFailure() if (retry) Result.retry() else Result.failure() } } diff --git a/app/src/main/java/de/jeanlucmakiola/agendula/data/export/ExportWriter.kt b/app/src/main/java/de/jeanlucmakiola/agendula/data/export/ExportWriter.kt index ec71c71..515430b 100644 --- a/app/src/main/java/de/jeanlucmakiola/agendula/data/export/ExportWriter.kt +++ b/app/src/main/java/de/jeanlucmakiola/agendula/data/export/ExportWriter.kt @@ -198,6 +198,8 @@ class ExportWriter @Inject constructor( private fun openWritableTree(treeUri: Uri): DocumentFile { val tree = DocumentFile.fromTreeUri(context, treeUri) ?: throw ExportFailedException(ExportFailure.FOLDER_UNAVAILABLE) + // An unmounted volume or a dead provider answers neither query. + if (!tree.exists()) throw ExportFailedException(ExportFailure.FOLDER_UNAVAILABLE) if (!tree.canWrite()) throw ExportFailedException(ExportFailure.FOLDER_NOT_WRITABLE) return tree } diff --git a/app/src/main/java/de/jeanlucmakiola/agendula/ui/settings/AutoBackupViewModel.kt b/app/src/main/java/de/jeanlucmakiola/agendula/ui/settings/AutoBackupViewModel.kt index c5c2450..255b709 100644 --- a/app/src/main/java/de/jeanlucmakiola/agendula/ui/settings/AutoBackupViewModel.kt +++ b/app/src/main/java/de/jeanlucmakiola/agendula/ui/settings/AutoBackupViewModel.kt @@ -49,15 +49,13 @@ class AutoBackupViewModel @Inject constructor( private val folderRejected = MutableStateFlow(false) - // A provider query, so off the main thread: the folder may be on an SD card - // or a cloud provider that is slow to answer. Starts unknown so the rest of - // the screen does not wait for it. + // A provider query: off the main thread, and not holding up the rest of the state. private val folderName = prefs.config.map { it.folderUri }.distinctUntilChanged().map { uri -> uri?.let { withContext(io) { runCatching { DocumentFile.fromTreeUri(context, it.toUri())?.name }.getOrNull() } } }.onStart { emit(null) } val state: StateFlow = - combine(prefs.config, prefs.status, scheduler.runningNow, folderName, folderRejected) { + combine(prefs.config, prefs.status, scheduler.running, folderName, folderRejected) { config, status, running, name, rejected -> AutoBackupUiState(config, status, running, name, rejected) }.stateIn(viewModelScope, SharingStarted.WhileSubscribed(5_000), AutoBackupUiState()) diff --git a/app/src/main/java/de/jeanlucmakiola/agendula/ui/settings/BackupScreen.kt b/app/src/main/java/de/jeanlucmakiola/agendula/ui/settings/BackupScreen.kt index 9e938a4..08cfdd3 100644 --- a/app/src/main/java/de/jeanlucmakiola/agendula/ui/settings/BackupScreen.kt +++ b/app/src/main/java/de/jeanlucmakiola/agendula/ui/settings/BackupScreen.kt @@ -85,8 +85,7 @@ internal fun BackupScreen( summary = stringResource(R.string.backup_auto_hint), checked = config.active, onCheckedChange = { on -> - // On without a folder has nowhere to write: ask for one, and the - // pick turns it on. + // No folder yet: the pick turns it on. if (on && config.folderUri == null) launchFolderPicker() else viewModel.setEnabled(on) }, position = if (config.active) Position.Top else Position.Alone, @@ -249,13 +248,14 @@ private fun backupKeepLabel(count: Int): String = pluralStringResource(R.plurals @Composable private fun backupStatusText(state: AutoBackupUiState): String { val status = state.status - // "5 minutes ago" has to move on while the screen stays open. - val now by produceState(System.currentTimeMillis()) { + // Ticks so "5 minutes ago" moves on; never behind a run that just finished. + val tick by produceState(System.currentTimeMillis()) { while (true) { delay(STATUS_TICK_MILLIS) value = System.currentTimeMillis() } } + val now = maxOf(tick, status.lastRunMillis, status.lastSuccessMillis) val failure = status.failure return when { state.running -> stringResource(R.string.backup_auto_status_running) diff --git a/app/src/test/java/de/jeanlucmakiola/agendula/data/backup/AutoBackupPolicyTest.kt b/app/src/test/java/de/jeanlucmakiola/agendula/data/backup/AutoBackupPolicyTest.kt index a071d37..b3bca3e 100644 --- a/app/src/test/java/de/jeanlucmakiola/agendula/data/backup/AutoBackupPolicyTest.kt +++ b/app/src/test/java/de/jeanlucmakiola/agendula/data/backup/AutoBackupPolicyTest.kt @@ -11,9 +11,8 @@ class AutoBackupPolicyTest { private fun name(day: Int, hour: Int = 3) = AutoBackupPolicy.fileName(at(day, hour)) - private companion object { - val NOW: Instant = Instant.parse("2026-11-30T00:00:00Z") - } + private fun stale(names: List, keep: Int, current: String = names.max()) = + AutoBackupPolicy.staleBackups(names, keep, current) @Test fun `names a backup by its UTC time`() { @@ -33,35 +32,38 @@ class AutoBackupPolicyTest { @Test fun `rotation drops everything beyond the newest kept`() { val names = listOf(name(3), name(1), name(5), name(4), name(2)) - assertThat(AutoBackupPolicy.staleBackups(names, keep = 3, now = NOW)).containsExactly(name(2), name(1)).inOrder() + assertThat(stale(names, keep = 3)).containsExactly(name(2), name(1)).inOrder() } @Test fun `rotation orders by time within a day`() { val names = listOf(name(1, hour = 23), name(1, hour = 9), name(1, hour = 10)) - assertThat(AutoBackupPolicy.staleBackups(names, keep = 1, now = NOW)).containsExactly(name(1, hour = 10), name(1, hour = 9)) + assertThat(stale(names, keep = 1)).containsExactly(name(1, hour = 10), name(1, hour = 9)) } @Test fun `rotation leaves files that are not backups alone`() { val names = listOf("notes.txt", "agendula-tasks.zip", AutoBackupPolicy.partialName(name(3)), name(1), name(2)) - assertThat(AutoBackupPolicy.staleBackups(names, keep = 1, now = NOW)).containsExactly(name(1)) + assertThat(stale(names, keep = 1, current = name(2))).containsExactly(name(1)) } @Test fun `rotation keeps at least the newest backup`() { - assertThat(AutoBackupPolicy.staleBackups(listOf(name(1), name(2)), keep = 0, now = NOW)).containsExactly(name(1)) + assertThat(stale(listOf(name(1), name(2)), keep = 0)).containsExactly(name(1)) } @Test fun `nothing is stale while under the limit`() { - assertThat(AutoBackupPolicy.staleBackups(listOf(name(1), name(2)), keep = 7, now = NOW)).isEmpty() + assertThat(stale(listOf(name(1), name(2)), keep = 7)).isEmpty() } @Test fun `a backup dated in the future never outranks the one just written`() { - val names = listOf("agendula-backup-2027-06-01-000000Z.zip", name(5), name(4)) - assertThat(AutoBackupPolicy.staleBackups(names, keep = 1, now = NOW)).containsExactly(name(4)) + val future = "agendula-backup-2027-06-01-000000Z.zip" + assertThat(stale(listOf(future, name(5), name(4)), keep = 1, current = name(5))) + .containsExactly(future, name(4)) + assertThat(stale(listOf(future, name(5), name(4)), keep = 2, current = name(5))) + .containsExactly(name(4)) } @Test @@ -74,6 +76,7 @@ class AutoBackupPolicyTest { fun `clamps the user's choices`() { assertThat(AutoBackupPolicy.clampInterval(15)).isEqualTo(AutoBackupPolicy.MIN_INTERVAL_MINUTES) assertThat(AutoBackupPolicy.clampInterval(1_440)).isEqualTo(1_440) + assertThat(AutoBackupPolicy.clampInterval(90)).isEqualTo(60) assertThat(AutoBackupPolicy.clampKeep(0)).isEqualTo(1) assertThat(AutoBackupPolicy.clampKeep(5_000)).isEqualTo(AutoBackupPolicy.MAX_KEEP) }