From fe59ee6e5914eab5c636ae2d496b50715ae7215e Mon Sep 17 00:00:00 2001 From: Jean-Luc Makiola Date: Tue, 17 Nov 2026 10:59:21 +0100 Subject: [PATCH] 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) + } +}