From b2498d362b86566da72b99e44e51a7917e237c3b Mon Sep 17 00:00:00 2001 From: Jean-Luc Makiola Date: Sat, 14 Nov 2026 03:39:16 +0100 Subject: [PATCH] feat(#516): back up after changes, refreshing the stable copies --- .../jeanlucmakiola/calendula/CalendulaApp.kt | 1 + .../calendula/data/backup/AutoBackup.kt | 143 ++++++++++++++---- .../calendula/data/prefs/SettingsPrefs.kt | 28 +++- .../calendula/domain/backup/BackupPlan.kt | 52 +++++++ .../calendula/ui/calendars/BackupScreen.kt | 7 + .../ui/calendars/CalendarsViewModel.kt | 14 +- .../ui/onboarding/OnboardingViewModel.kt | 1 + app/src/main/res/values/strings.xml | 2 + .../calendula/domain/backup/BackupPlanTest.kt | 38 +++++ docs/ARCHITECTURE.md | 13 ++ 10 files changed, 266 insertions(+), 33 deletions(-) diff --git a/app/src/main/java/de/jeanlucmakiola/calendula/CalendulaApp.kt b/app/src/main/java/de/jeanlucmakiola/calendula/CalendulaApp.kt index 2a5a2b36..8310c571 100644 --- a/app/src/main/java/de/jeanlucmakiola/calendula/CalendulaApp.kt +++ b/app/src/main/java/de/jeanlucmakiola/calendula/CalendulaApp.kt @@ -115,6 +115,7 @@ class CalendulaApp : Application() { enabled = prefs.autoBackupEnabled.first(), intervalMinutes = prefs.autoBackupIntervalMinutes.first(), hasFolder = prefs.autoBackupFolderUri.first() != null, + onChange = prefs.autoBackupOnChange.first(), ) } } diff --git a/app/src/main/java/de/jeanlucmakiola/calendula/data/backup/AutoBackup.kt b/app/src/main/java/de/jeanlucmakiola/calendula/data/backup/AutoBackup.kt index 02977e18..c9d3e150 100644 --- a/app/src/main/java/de/jeanlucmakiola/calendula/data/backup/AutoBackup.kt +++ b/app/src/main/java/de/jeanlucmakiola/calendula/data/backup/AutoBackup.kt @@ -7,10 +7,12 @@ import android.app.PendingIntent import android.content.Context import android.net.Uri import android.os.Build +import android.provider.CalendarContract import android.util.Log import androidx.core.app.NotificationCompat import androidx.core.app.NotificationManagerCompat import androidx.core.net.toUri +import androidx.work.Constraints import androidx.work.CoroutineWorker import androidx.work.ExistingPeriodicWorkPolicy import androidx.work.ExistingWorkPolicy @@ -18,6 +20,7 @@ import androidx.work.OneTimeWorkRequestBuilder import androidx.work.PeriodicWorkRequestBuilder import androidx.work.WorkManager import androidx.work.WorkerParameters +import androidx.work.workDataOf import dagger.hilt.EntryPoint import dagger.hilt.InstallIn import dagger.hilt.android.EntryPointAccessors @@ -26,7 +29,10 @@ import de.jeanlucmakiola.calendula.R import de.jeanlucmakiola.calendula.data.calendar.CalendarRepository import de.jeanlucmakiola.calendula.data.ics.IcsExporter import de.jeanlucmakiola.calendula.data.prefs.SettingsPrefs +import de.jeanlucmakiola.calendula.domain.backup.backupFingerprint import de.jeanlucmakiola.calendula.domain.backup.backupTargets +import de.jeanlucmakiola.calendula.domain.backup.needsRefresh +import de.jeanlucmakiola.calendula.domain.backup.withFingerprint import de.jeanlucmakiola.calendula.domain.backup.planBackupFiles import de.jeanlucmakiola.calendula.domain.backup.latestHeldElsewhere import de.jeanlucmakiola.calendula.domain.backup.latestLedgerKey @@ -43,6 +49,7 @@ import java.time.LocalDateTime import java.util.concurrent.TimeUnit import kotlin.coroutines.cancellation.CancellationException import kotlin.time.Clock +import kotlin.time.Instant /** * Schedules and runs the automatic periodic `.ics` backup (issue #8) of the @@ -54,6 +61,14 @@ object BackupScheduler { private const val WORK_NAME = "auto-backup" private const val WORK_NAME_NOW = "auto-backup-now" + private const val WORK_NAME_CHANGES = "auto-backup-changes" + internal const val KEY_CHANGE_RUN = "change_run" + + /** Quiet time after the last provider change before a change run starts, so a burst makes one run. */ + private const val CHANGE_SETTLE_MINUTES = 2L + + /** Longest a change run waits on a provider that never goes quiet (a long sync). */ + private const val CHANGE_MAX_WAIT_MINUTES = 15L /** * Reconcile the scheduled work with the current settings: enqueue a unique @@ -61,15 +76,17 @@ object BackupScheduler { * it. WorkManager persists the request across reboots on its own. * * The first run is delayed by one interval so it doesn't follow an immediate - * [runNow] with a near-identical copy. + * [runNow] with a near-identical copy. [onChange] also arms the change + * trigger (#516). */ - fun apply(context: Context, enabled: Boolean, intervalMinutes: Long, hasFolder: Boolean) { + fun apply(context: Context, enabled: Boolean, intervalMinutes: Long, hasFolder: Boolean, onChange: Boolean) { val workManager = WorkManager.getInstance(context) if (!enabled || !hasFolder) { workManager.cancelUniqueWork(WORK_NAME) // Also cancel any pending immediate run — otherwise a failing run-now // keeps retrying after the user has turned backup off. workManager.cancelUniqueWork(WORK_NAME_NOW) + workManager.cancelUniqueWork(WORK_NAME_CHANGES) return } // WorkManager's own floor is 15 min; the UI floors the user choice at 30. @@ -82,6 +99,11 @@ object BackupScheduler { ExistingPeriodicWorkPolicy.UPDATE, request, ) + if (onChange) { + watchChanges(context, ExistingWorkPolicy.KEEP) + } else { + workManager.cancelUniqueWork(WORK_NAME_CHANGES) + } } /** @@ -96,6 +118,27 @@ object BackupScheduler { OneTimeWorkRequestBuilder().build(), ) } + + /** + * Arm a one-off run on the next change in the calendar provider (#516). A + * content trigger fires once, so each change run arms the next one, queued + * behind itself ([ExistingWorkPolicy.APPEND_OR_REPLACE]). The provider + * reports every change on its root URI, whoever made it — this app, a sync + * adapter or another app — so that is the URI watched. + */ + internal fun watchChanges(context: Context, policy: ExistingWorkPolicy) { + val constraints = Constraints.Builder() + .addContentUriTrigger(CalendarContract.CONTENT_URI, true) + .setTriggerContentUpdateDelay(CHANGE_SETTLE_MINUTES, TimeUnit.MINUTES) + .setTriggerContentMaxDelay(CHANGE_MAX_WAIT_MINUTES, TimeUnit.MINUTES) + .setRequiresBatteryNotLow(true) + .build() + val request = OneTimeWorkRequestBuilder() + .setConstraints(constraints) + .setInputData(workDataOf(KEY_CHANGE_RUN to true)) + .build() + WorkManager.getInstance(context).enqueueUniqueWork(WORK_NAME_CHANGES, policy, request) + } } /** @@ -122,16 +165,28 @@ class BackupWorker( override suspend fun doWork(): Result { val deps = EntryPointAccessors.fromApplication(applicationContext, Deps::class.java) val prefs = deps.settingsPrefs() + if (!inputData.getBoolean(BackupScheduler.KEY_CHANGE_RUN, false)) return backUp(deps, prefs, changeRun = false) + // A change run neither fails nor retries: the next one is queued behind + // it, and a retry would only wait for another change anyway. + backUp(deps, prefs, changeRun = true) + val stillOn = prefs.autoBackupEnabled.first() && prefs.autoBackupOnChange.first() && + prefs.autoBackupFolderUri.first() != null + if (stillOn) BackupScheduler.watchChanges(applicationContext, ExistingWorkPolicy.APPEND_OR_REPLACE) + return Result.success() + } + + private suspend fun backUp(deps: Deps, prefs: SettingsPrefs, changeRun: Boolean): Result { val now = System.currentTimeMillis() - // The periodic and the immediate run are separate unique works; one at - // a time, or each would overwrite the other's ledger. + // The periodic, the immediate and the change run are separate unique + // works; one at a time, or each would overwrite the other's ledger. val outcome = runLock.withLock { - // Respect the toggle even for already-queued work, so a lingering + // Respect the toggles even for already-queued work, so a lingering // run can't revive itself. if (!prefs.autoBackupEnabled.first()) return Result.success() + if (changeRun && !prefs.autoBackupOnChange.first()) return Result.success() val folder = prefs.autoBackupFolderUri.first() ?: return Result.failure() try { - runBackup(deps, prefs, folder.toUri()) + runBackup(deps, prefs, folder.toUri(), latestOnly = changeRun) } catch (e: CancellationException) { throw e } catch (e: Exception) { @@ -139,7 +194,7 @@ class BackupWorker( RunOutcome.Failed } } - if (outcome == RunOutcome.NothingSelected) return Result.success() + if (outcome == RunOutcome.NothingToDo) return Result.success() val success = outcome == RunOutcome.Written prefs.recordAutoBackupRun(success = success, atMillis = now) if (!success && prefs.autoBackupStatus.first().consecutiveFailures >= FAILURE_NOTIFY_THRESHOLD) { @@ -149,20 +204,25 @@ class BackupWorker( return if (outcome == RunOutcome.Failed) Result.retry() else Result.success() } - private enum class RunOutcome { Written, PartlyFailed, Failed, NothingSelected } + private enum class RunOutcome { Written, PartlyFailed, Failed, NothingToDo } - /** Writes each series and prunes it only once its new file has landed. */ - private suspend fun runBackup(deps: Deps, prefs: SettingsPrefs, folder: Uri): RunOutcome { + /** + * Writes each series and prunes it only once its new file has landed. A + * [latestOnly] run (#516) leaves the dated files and their retention to the + * schedule and rewrites only the stable copies whose calendars changed. + */ + private suspend fun runBackup(deps: Deps, prefs: SettingsPrefs, folder: Uri, latestOnly: Boolean): RunOutcome { val repository = deps.repository() val exporter = deps.exporter() if (!applicationContext.hasPermission(Manifest.permission.READ_CALENDAR)) return RunOutcome.Failed val all = repository.calendars().first() val selection = prefs.autoBackupSelection.first() val targets = backupTargets(all.filter(selection::selects), combined = prefs.autoBackupCombined.first()) - if (targets.isEmpty()) return RunOutcome.NothingSelected + if (targets.isEmpty()) return RunOutcome.NothingToDo prefs.adoptLegacyBackupFile() val listing = exporter.listFolder(folder) val ledger = prefs.autoBackupLedger.first() + val fingerprints = prefs.autoBackupFingerprints.first() // A listing still loading can't tell a gone file from a late one. val existing = if (listing.complete) listing.files.keys else listing.files.keys + ledger.values.flatten() val plans = planBackupFiles( @@ -177,38 +237,51 @@ class BackupWorker( suspend fun record(key: String, files: List) = prefs.updateAutoBackupLedger(folder.toString()) { withLedgerEntry(it, key, files, liveKeys) } var written = 0 + var failed = 0 val landedLatest = mutableSetOf() for (plan in plans) { val target = plan.target - val bytes = try { - IcsWriter() - .writeCalendar(repository.exportEvents(target.calendarIds), stamp, target.calendarName) - .toByteArray(Charsets.UTF_8) + if (latestOnly && plan.latestName == null) continue + val (bytes, fingerprint) = try { + val events = repository.exportEvents(target.calendarIds) + val writer = IcsWriter() + writer.writeCalendar(events, stamp, target.calendarName).toByteArray(Charsets.UTF_8) to + backupFingerprint(writer.writeCalendar(events, FINGERPRINT_STAMP, target.calendarName)) } catch (e: CancellationException) { throw e } catch (e: Exception) { Log.w(TAG, "Reading one series failed", e) + failed++ + continue + } + if (latestOnly && !plan.needsRefresh(fingerprint, fingerprints, existing)) { + landedLatest += target.key continue } // Not cancellable once a file exists: it must reach the ledger, or // nothing would ever prune it. withContext(NonCancellable) { - try { - val name = exporter.writeToFolder(folder, listing, plan.fileName, bytes) - record(target.key, plan.prune + plan.keep + name) - val undeleted = exporter.deleteFromFolder(listing, plan.prune) - record(target.key, plan.prune.filter { it in undeleted } + plan.keep + name) - written++ - } catch (e: Exception) { - Log.w(TAG, "Backup of one series failed", e) + if (!latestOnly) { + try { + val name = exporter.writeToFolder(folder, listing, plan.fileName, bytes) + record(target.key, plan.prune + plan.keep + name) + val undeleted = exporter.deleteFromFolder(listing, plan.prune) + record(target.key, plan.prune.filter { it in undeleted } + plan.keep + name) + written++ + } catch (e: Exception) { + Log.w(TAG, "Backup of one series failed", e) + failed++ + } } - // Best-effort: the stable copy never holds up the dated backup, - // its pruning or the run's status. An old copy goes only once the - // new one has landed, so a series is never left without one. + // Best-effort in a full run: the stable copy never holds up the + // dated backup, its pruning or the run's status. An old copy goes + // only once the new one has landed, so a series is never left + // without one. try { val latest = plan.latestName ?: return@withContext val latestKey = latestLedgerKey(target.key) val landed = exporter.writeToFolder(folder, listing, latest, bytes) + if (latestOnly) written++ // A provider that renamed it leaves a copy to clean up next // run; the intended name stays ours only if it already was. val ownsLatest = landed == latest || latest in ledger[latestKey].orEmpty() @@ -219,11 +292,17 @@ class BackupWorker( withLedgerEntry(it, latestKey, stale + pending + current, liveKeys) } recordLatest(plan.staleLatest) - if (landed == latest) landedLatest += target.key + if (landed == latest) { + landedLatest += target.key + prefs.updateAutoBackupFingerprints(folder.toString()) { + withFingerprint(it, target.key, fingerprint, liveKeys) + } + } val staleLeft = exporter.deleteFromFolder(listing, plan.staleLatest) recordLatest(plan.staleLatest.filter { it in staleLeft }) } catch (e: Exception) { Log.w(TAG, "Stable copy of one series failed", e) + if (latestOnly) failed++ } } } @@ -236,9 +315,10 @@ class BackupWorker( } } } - return when (written) { - plans.size -> RunOutcome.Written - 0 -> RunOutcome.Failed + return when { + failed == 0 && written == 0 -> RunOutcome.NothingToDo + failed == 0 -> RunOutcome.Written + written == 0 -> RunOutcome.Failed else -> RunOutcome.PartlyFailed } } @@ -283,5 +363,8 @@ class BackupWorker( private const val NOTIFICATION_ID = 2 private const val TAG = "BackupWorker" private val runLock = Mutex() + + // Fixed, so the hash follows the events and not the time of the run. + private val FINGERPRINT_STAMP = Instant.fromEpochMilliseconds(0) } } diff --git a/app/src/main/java/de/jeanlucmakiola/calendula/data/prefs/SettingsPrefs.kt b/app/src/main/java/de/jeanlucmakiola/calendula/data/prefs/SettingsPrefs.kt index eaeb8cf5..35ba184e 100644 --- a/app/src/main/java/de/jeanlucmakiola/calendula/data/prefs/SettingsPrefs.kt +++ b/app/src/main/java/de/jeanlucmakiola/calendula/data/prefs/SettingsPrefs.kt @@ -15,6 +15,9 @@ import de.jeanlucmakiola.calendula.domain.backup.normalizeBackupKeep import de.jeanlucmakiola.calendula.domain.backup.BackupLedger import de.jeanlucmakiola.calendula.domain.backup.parseBackupLedger import de.jeanlucmakiola.calendula.domain.backup.persistBackupLedger +import de.jeanlucmakiola.calendula.domain.backup.BackupFingerprints +import de.jeanlucmakiola.calendula.domain.backup.parseBackupFingerprints +import de.jeanlucmakiola.calendula.domain.backup.persistBackupFingerprints import de.jeanlucmakiola.calendula.domain.contacts.SpecialDateType import de.jeanlucmakiola.calendula.ui.agenda.AgendaRange import de.jeanlucmakiola.calendula.ui.agenda.parseAgendaRange @@ -196,6 +199,8 @@ class SettingsPrefs @Inject constructor( val autoBackupCombined: Flow = prefs.snapshot { it.autoBackupCombined } val autoBackupKeep: Flow = prefs.flow(SettingsKeys.autoBackupKeep) val autoBackupLedger: Flow = prefs.flow(SettingsKeys.autoBackupLedger) + val autoBackupOnChange: Flow = prefs.flow(SettingsKeys.autoBackupOnChange) + val autoBackupFingerprints: Flow = prefs.flow(SettingsKeys.autoBackupFingerprints) val specialDatesEnabled: Flow = prefs.flow(SettingsKeys.specialDatesEnabled) val specialDatesTypes: Flow> = prefs.snapshot { it.specialDatesTypes } val specialDatesCalendars: Flow> = prefs.snapshot { it.specialDatesCalendars } @@ -355,7 +360,10 @@ class SettingsPrefs @Inject constructor( it.pinBackupLayout() // The ledger says which files in the old folder are ours; in a new // one a file of the same name may be the user's. - if (it[SettingsKeys.autoBackupFolderUri] != uri) it[SettingsKeys.autoBackupLedger] = emptyMap() + if (it[SettingsKeys.autoBackupFolderUri] != uri) { + it[SettingsKeys.autoBackupLedger] = emptyMap() + it[SettingsKeys.autoBackupFingerprints] = emptyMap() + } it[SettingsKeys.autoBackupFolderUri] = uri } } @@ -369,6 +377,17 @@ class SettingsPrefs @Inject constructor( suspend fun setAutoBackupKeep(keep: Int) = prefs.set(SettingsKeys.autoBackupKeep, keep) + suspend fun setAutoBackupOnChange(enabled: Boolean) = prefs.set(SettingsKeys.autoBackupOnChange, enabled) + + /** Like [updateAutoBackupLedger]: dropped once the folder is no longer [folder]. */ + suspend fun updateAutoBackupFingerprints(folder: String, transform: (BackupFingerprints) -> BackupFingerprints) { + prefs.edit { + if (it[SettingsKeys.autoBackupFolderUri] == folder) { + it[SettingsKeys.autoBackupFingerprints] = transform(it[SettingsKeys.autoBackupFingerprints]) + } + } + } + /** * Atomic, so a run's ledger writes never undo one made meanwhile (pinning * the layout). Dropped when the folder is no longer [folder]: a run still @@ -786,6 +805,13 @@ object SettingsKeys { val autoBackupLedger: Pref = nullableStringPref("auto_backup_files").map(::parseBackupLedger, ::persistBackupLedger) + /** Whether a change to a backed-up calendar also refreshes the stable copies (#516). Opt-in. */ + val autoBackupOnChange: Pref = booleanPref("auto_backup_on_change", false) + + /** Content hash of each series' stable copy, so a change run skips untouched ones (#516). */ + val autoBackupFingerprints: Pref = + nullableStringPref("auto_backup_fingerprints").map(::parseBackupFingerprints, ::persistBackupFingerprints) + /** Master switch for the contact special-dates mirror (issue #15). Opt-in. */ val specialDatesEnabled: Pref = booleanPref("special_dates_enabled", false) diff --git a/app/src/main/java/de/jeanlucmakiola/calendula/domain/backup/BackupPlan.kt b/app/src/main/java/de/jeanlucmakiola/calendula/domain/backup/BackupPlan.kt index cb1085a5..e862872a 100644 --- a/app/src/main/java/de/jeanlucmakiola/calendula/domain/backup/BackupPlan.kt +++ b/app/src/main/java/de/jeanlucmakiola/calendula/domain/backup/BackupPlan.kt @@ -3,6 +3,7 @@ package de.jeanlucmakiola.calendula.domain.backup import de.jeanlucmakiola.calendula.domain.CalendarSource import de.jeanlucmakiola.calendula.domain.isNotSynced import de.jeanlucmakiola.floret.android.safeFileName +import java.security.MessageDigest import java.time.LocalDateTime import java.time.format.DateTimeFormatter @@ -277,3 +278,54 @@ fun parseBackupLedger(stored: String?): BackupLedger = /** Closest offered retention count to [stored], so a stray value still shows a row. */ fun normalizeBackupKeep(stored: Int): Int = BACKUP_KEEP_OPTIONS.minBy { kotlin.math.abs(it - stored) } + +/** + * Content hash of a series' file, per series key (#516), so a run started by a + * change can tell whether the calendars it covers changed at all. + */ +typealias BackupFingerprints = Map + +/** Hash of [text], a series' file written with a fixed stamp so equal events give an equal hash. */ +fun backupFingerprint(text: String): String = + MessageDigest.getInstance("SHA-256").digest(text.toByteArray(Charsets.UTF_8)) + .take(FINGERPRINT_BYTES) + .joinToString("") { "%02x".format(it) } + +/** [previous] with [key] set to [fingerprint]; entries of deleted calendars go, as in [withLedgerEntry]. */ +fun withFingerprint( + previous: BackupFingerprints, + key: String, + fingerprint: String, + liveKeys: Set, +): BackupFingerprints = + previous.filterKeys { it in liveKeys || it == COMBINED_SERIES } + (key to fingerprint) + +private const val FINGERPRINT_BYTES = 16 +private const val FINGERPRINT_SEP = "=" + +fun persistBackupFingerprints(fingerprints: BackupFingerprints): String? = + fingerprints.takeIf { it.isNotEmpty() } + ?.entries?.sortedBy { it.key } + ?.joinToString(LEDGER_ENTRY_SEP) { (key, hash) -> "$key$FINGERPRINT_SEP$hash" } + +fun parseBackupFingerprints(stored: String?): BackupFingerprints = + stored?.split(LEDGER_ENTRY_SEP).orEmpty().mapNotNull { entry -> + val key = entry.substringBefore(FINGERPRINT_SEP, "") + val hash = entry.substringAfter(FINGERPRINT_SEP, "") + if (key.isEmpty() || hash.isEmpty()) null else key to hash + }.toMap() + +/** + * Whether a run started by a change (#516) rewrites this series' stable copy: + * only when its content moved on from what the copy holds, or the copy is + * missing or mid-rename. Never when the name belongs to a file of the user's. + */ +fun BackupFilePlan.needsRefresh( + fingerprint: String, + stored: BackupFingerprints, + existing: Set, +): Boolean { + val latest = latestName ?: return false + return stored[target.key] != fingerprint || latest !in existing || + staleLatest.isNotEmpty() || handOff.isNotEmpty() +} diff --git a/app/src/main/java/de/jeanlucmakiola/calendula/ui/calendars/BackupScreen.kt b/app/src/main/java/de/jeanlucmakiola/calendula/ui/calendars/BackupScreen.kt index 4dd5401a..46d99577 100644 --- a/app/src/main/java/de/jeanlucmakiola/calendula/ui/calendars/BackupScreen.kt +++ b/app/src/main/java/de/jeanlucmakiola/calendula/ui/calendars/BackupScreen.kt @@ -351,6 +351,13 @@ private fun BackupContent( position = Position.Middle, onClick = onEditInterval, ) + GroupedSwitchRow( + title = stringResource(R.string.calendars_auto_backup_on_change), + summary = stringResource(R.string.calendars_auto_backup_on_change_summary), + checked = autoBackup.onChange, + onCheckedChange = viewModel::setAutoBackupOnChange, + position = Position.Middle, + ) val selectedCount = exportable.count(autoBackup.selection::selects) GroupedRow( title = stringResource(R.string.calendars_auto_backup_calendars), diff --git a/app/src/main/java/de/jeanlucmakiola/calendula/ui/calendars/CalendarsViewModel.kt b/app/src/main/java/de/jeanlucmakiola/calendula/ui/calendars/CalendarsViewModel.kt index 5ebad9b6..26720517 100644 --- a/app/src/main/java/de/jeanlucmakiola/calendula/ui/calendars/CalendarsViewModel.kt +++ b/app/src/main/java/de/jeanlucmakiola/calendula/ui/calendars/CalendarsViewModel.kt @@ -88,8 +88,9 @@ class CalendarsViewModel @Inject constructor( settingsPrefs.autoBackupSelection, settingsPrefs.autoBackupCombined, settingsPrefs.autoBackupKeep, - ) { base, selection, combined, keep -> - base.copy(selection = selection, combined = combined, keep = keep) + settingsPrefs.autoBackupOnChange, + ) { base, selection, combined, keep, onChange -> + base.copy(selection = selection, combined = combined, keep = keep, onChange = onChange) } .flowOn(io) .stateWhileSubscribed( @@ -234,6 +235,13 @@ class CalendarsViewModel @Inject constructor( } } + fun setAutoBackupOnChange(enabled: Boolean) { + viewModelScope.launch { + settingsPrefs.setAutoBackupOnChange(enabled) + reschedule() + } + } + fun setAutoBackupKeep(keep: Int) { viewModelScope.launch { if (settingsPrefs.autoBackupKeep.first() == keep) return@launch @@ -268,6 +276,7 @@ class CalendarsViewModel @Inject constructor( enabled = settingsPrefs.autoBackupEnabled.first(), intervalMinutes = settingsPrefs.autoBackupIntervalMinutes.first(), hasFolder = settingsPrefs.autoBackupFolderUri.first() != null, + onChange = settingsPrefs.autoBackupOnChange.first(), ) } @@ -293,6 +302,7 @@ data class AutoBackupUiState( val selection: BackupSelection = BackupSelection(), val combined: Boolean = false, val keep: Int = DEFAULT_BACKUP_KEEP, + val onChange: Boolean = false, ) /** Outcome of a whole-calendar backup, surfaced once to the screen. */ diff --git a/app/src/main/java/de/jeanlucmakiola/calendula/ui/onboarding/OnboardingViewModel.kt b/app/src/main/java/de/jeanlucmakiola/calendula/ui/onboarding/OnboardingViewModel.kt index 3c7c24cd..cee0856c 100644 --- a/app/src/main/java/de/jeanlucmakiola/calendula/ui/onboarding/OnboardingViewModel.kt +++ b/app/src/main/java/de/jeanlucmakiola/calendula/ui/onboarding/OnboardingViewModel.kt @@ -345,6 +345,7 @@ class OnboardingViewModel @Inject constructor( enabled = true, intervalMinutes = prefs.autoBackupIntervalMinutes.first(), hasFolder = true, + onChange = prefs.autoBackupOnChange.first(), ) // Immediate feedback: the first backup lands while onboarding runs. BackupScheduler.runNow(context) diff --git a/app/src/main/res/values/strings.xml b/app/src/main/res/values/strings.xml index 791612c5..8dbd4fe9 100644 --- a/app/src/main/res/values/strings.xml +++ b/app/src/main/res/values/strings.xml @@ -920,6 +920,8 @@ Interval Every %1$s Minimum 30 minutes. + Also back up after changes + Updates the undated copy a few minutes after events change. Dated backups stay on the interval. Calendars %d calendar diff --git a/app/src/test/java/de/jeanlucmakiola/calendula/domain/backup/BackupPlanTest.kt b/app/src/test/java/de/jeanlucmakiola/calendula/domain/backup/BackupPlanTest.kt index ee9be52e..bf878d78 100644 --- a/app/src/test/java/de/jeanlucmakiola/calendula/domain/backup/BackupPlanTest.kt +++ b/app/src/test/java/de/jeanlucmakiola/calendula/domain/backup/BackupPlanTest.kt @@ -284,4 +284,42 @@ class BackupPlanTest { assertThat(ledger.latestHeldElsewhere("1")).containsExactly("Work.ics") assertThat(ledger.latestHeldElsewhere("2")).containsExactly("Job.ics") } + + @Test + fun `fingerprints survive storage and drop deleted calendars`() { + val stored = persistBackupFingerprints(mapOf("1" to "ab", COMBINED_SERIES to "cd")) + assertThat(parseBackupFingerprints(stored)).containsExactly("1", "ab", COMBINED_SERIES, "cd") + assertThat(persistBackupFingerprints(emptyMap())).isNull() + assertThat(parseBackupFingerprints(null)).isEmpty() + val next = withFingerprint(mapOf("1" to "ab", "9" to "ef", COMBINED_SERIES to "cd"), "2", "gh", setOf("1", "2")) + assertThat(next).containsExactly("1", "ab", COMBINED_SERIES, "cd", "2", "gh") + } + + @Test + fun `a fingerprint follows the content`() { + assertThat(backupFingerprint("a")).isEqualTo(backupFingerprint("a")) + assertThat(backupFingerprint("a")).isNotEqualTo(backupFingerprint("b")) + assertThat(backupFingerprint("a")).hasLength(32) + } + + @Test + fun `a change run refreshes only a changed, missing or moving stable copy`() { + val target = backupTargets(listOf(cal(1L, "Work")), combined = false).single() + val ledger = mapOf(latestLedgerKey("1") to listOf("Work.ics")) + val plan = planBackupFiles(listOf(target), ledger, setOf("Work.ics"), at, keep = 3).single() + val stored = mapOf("1" to "h1") + assertThat(plan.needsRefresh("h1", stored, setOf("Work.ics"))).isFalse() + assertThat(plan.needsRefresh("h2", stored, setOf("Work.ics"))).isTrue() + assertThat(plan.needsRefresh("h1", emptyMap(), setOf("Work.ics"))).isTrue() + assertThat(plan.needsRefresh("h1", stored, emptySet())).isTrue() + assertThat(plan.copy(staleLatest = listOf("Job.ics")).needsRefresh("h1", stored, setOf("Work.ics"))).isTrue() + } + + @Test + fun `a change run never writes over a file of the user's`() { + val target = backupTargets(listOf(cal(1L, "Work")), combined = false).single() + val plan = planBackupFiles(listOf(target), emptyMap(), setOf("Work.ics"), at, keep = 3).single() + assertThat(plan.latestName).isNull() + assertThat(plan.needsRefresh("h1", emptyMap(), setOf("Work.ics"))).isFalse() + } } diff --git a/docs/ARCHITECTURE.md b/docs/ARCHITECTURE.md index 9c649bac..b42e9bf0 100644 --- a/docs/ARCHITECTURE.md +++ b/docs/ARCHITECTURE.md @@ -485,6 +485,19 @@ of the backup keeps its last one. The pre-#411 fixed `calendula-backup.ics` is the combined series' stable copy for the install that wrote it, and an install that already had a folder stays on the combined layout. +**Backing up after a change (#516)** is opt-in. `BackupScheduler.watchChanges` +arms a one-off `BackupWorker` with a WorkManager content-URI trigger on the +provider's root URI (the provider notifies every change there, whoever made it: +this app, a sync adapter or another app), a 2-minute settle delay capped at 15 +minutes, and battery-not-low. A trigger fires once, so each change run arms the +next one behind itself (`APPEND_OR_REPLACE`); it shares the run lock with the +scheduled run. A change run only rewrites the stable copies: the dated files +and their retention stay on the interval, so a day of edits can't rotate the +history out. Since the trigger fires for any provider change (reminders, other +calendars, sync bookkeeping), each series' file is hashed with a fixed stamp +(`auto_backup_fingerprints`, reset with the folder) and a change run skips the +series whose hash, stable copy and name are unchanged. + **A backup carries the series' deleted and moved occurrences.** `EXDATE` lives on the master row and is part of `EventExportProjection`; `IcsWriter` marks an all-day series' exclusions `VALUE=DATE`, because RFC 5545 ties `EXDATE`'s value