fix(#481): keep per-calendar settings when calendars can't be read, re-apply mirror reminders

This commit is contained in:
makiolaj committed 2026-11-13 19:46:32 +01:00
1 parent 90b640054a
commit 5ee25c2115
7 files changed
+127 -50

No files matched your search

@@ -14,6 +14,7 @@ import de.jeanlucmakiola.calendula.data.contacts.ContactSpecialDatesDataSource
import de.jeanlucmakiola.calendula.data.contacts.SpecialDatesScheduler
import de.jeanlucmakiola.calendula.data.contacts.SpecialDatesSyncEngine
import de.jeanlucmakiola.calendula.data.fonts.CustomFontStore
import de.jeanlucmakiola.calendula.data.prefs.CalendarPrefKeys
import de.jeanlucmakiola.calendula.data.prefs.SettingsKeys
import de.jeanlucmakiola.calendula.data.reminders.ReminderScanner
import de.jeanlucmakiola.calendula.domain.FontRole
@@ -53,10 +54,13 @@ class SettingsBackupEngine @Inject constructor(
suspend fun export(): String = withContext(io) {
val supported = supportedLanguages()
val snapshot = store.data.first()
// Without the list the per-calendar settings would silently drop out of the file.
val list = if (snapshot.hasCalendarSettings()) calendars.calendars() else emptyList()
val backup = buildSettingsBackup(
snapshot = store.data.first(),
calendars = runCatching { calendars.calendars() }.getOrDefault(emptyList()),
managed = runCatching { calendars.findManagedCalendars() }.getOrDefault(emptyList()),
snapshot = snapshot,
calendars = list,
managed = if (list.any { it.isManaged }) calendars.findManagedCalendars() else emptyList(),
language = LanguageChoice(AppLanguage.currentTag(context, supported)),
launcherName = launcherNames.current(),
)
@@ -80,7 +84,7 @@ class SettingsBackupEngine @Inject constructor(
return@withContext BackupResult.Failure(BackupProblem.NOT_APPLIED, e.message.orEmpty())
}
val lateSkips = withContext(NonCancellable) { afterImport(plan, current) }
BackupResult.Success(plan.summary(plan.calendars.size + lateSkips.matched, lateSkips.skipped))
BackupResult.Success(plan.summary(plan.calendars.orEmpty().size + lateSkips.matched, lateSkips.skipped))
}
private class LateMatches(val matched: Int, val skipped: List<SkippedSetting>)
@@ -99,7 +103,7 @@ class SettingsBackupEngine @Inject constructor(
if (mirroring) {
SpecialDatesScheduler.apply(context, enabled = true)
specialDates.sync()
late = matchSpecialDates(plan)
late = matchSpecialDates(plan, backup = plan.calendars != null)
} else if (wasMirroring) {
SpecialDatesScheduler.apply(context, enabled = false)
specialDates.teardown()
@@ -129,10 +133,11 @@ class SettingsBackupEngine @Inject constructor(
}
/**
* The mirror's calendars exist now, so the entries for them get their ids;
* an all-day reminder goes through the mirror, which rewrites its events.
* The mirror's calendars exist now, so the entries for them get their ids.
* Each mirror's all-day reminders go through the mirror, which rewrites
* its events too; one the file doesn't override inherits again.
*/
private suspend fun matchSpecialDates(plan: SettingsImportPlan): LateMatches {
private suspend fun matchSpecialDates(plan: SettingsImportPlan, backup: Boolean): LateMatches {
val managed = calendars.findManagedCalendars()
val skipped = mutableListOf<SkippedSetting>()
var matched = 0
@@ -142,20 +147,32 @@ class SettingsBackupEngine @Inject constructor(
id?.let { it to entry }
}
if (resolved.isNotEmpty()) {
store.edit { prefs -> resolved.forEach { (id, entry) -> prefs.addCalendarSettings(id, entry) } }
store.edit { prefs ->
resolved.forEach { (id, entry) -> prefs.addCalendarSettings(id, entry.copy(allDayReminders = null)) }
}
}
val mirrorEntries = plan.calendars.values + resolved.map { it.second }
mirrorEntries.forEach { entry ->
val type = entry.calendar.specialDates ?: return@forEach
val minutes = entry.allDayReminders ?: return@forEach
val override = if (minutes.isEmpty()) ReminderOverride.None else ReminderOverride.Minutes(minutes)
specialDates.applyReminders(type, override)
if (backup) {
val entries = (plan.calendars.orEmpty().values + resolved.map { it.second })
.mapNotNull { entry -> entry.calendar.specialDates?.let { it to entry } }
.toMap()
managed.map { it.type }.distinct().forEach { type ->
val minutes = entries[type]?.allDayReminders
val override = when {
minutes == null -> ReminderOverride.Inherit
minutes.isEmpty() -> ReminderOverride.None
else -> ReminderOverride.Minutes(minutes)
}
specialDates.applyReminders(type, override)
}
}
return LateMatches(matched, skipped)
}
/** The highest byte count [import] is worth reading. */
val maxImportBytes: Int get() = SettingsBackupSchema.format.maxChars
private fun environment(current: Preferences): ImportEnvironment = ImportEnvironment(
calendars = runCatching { calendars.calendars() }.getOrDefault(emptyList()),
calendars = runCatching { calendars.calendars() }.getOrNull(),
managed = runCatching { calendars.findManagedCalendars() }.getOrDefault(emptyList()),
contactsPermission = contacts.hasPermission(),
customFonts = FontRole.entries.filter { CustomFontStore.exists(context, it) }.toSet(),
@@ -163,6 +180,13 @@ class SettingsBackupEngine @Inject constructor(
supportedLanguages = supportedLanguages(),
)
private fun Preferences.hasCalendarSettings(): Boolean =
this[CalendarPrefKeys.hiddenCalendarIds].isNotEmpty() ||
this[CalendarPrefKeys.lastUsedCalendarId] != null ||
this[SettingsKeys.perCalendarEventDuration].isNotEmpty() ||
this[SettingsKeys.perCalendarReminderOverride].isNotEmpty() ||
this[SettingsKeys.perCalendarAllDayReminderOverride].isNotEmpty()
private fun supportedLanguages(): List<String> = AppLanguage.supportedTags(context, R.xml.locales_config)
private suspend fun step(name: String, block: suspend () -> Unit) {
@@ -17,7 +17,8 @@ import de.jeanlucmakiola.floret.prefs.set
/** What this device can take of a backup, read before planning. */
data class ImportEnvironment(
val calendars: List<CalendarSource>,
/** Null when the calendar list can't be read: the per-calendar settings are then left alone. */
val calendars: List<CalendarSource>?,
val managed: List<ManagedCalendarRow>,
val contactsPermission: Boolean,
val customFonts: Set<FontRole>,
@@ -27,8 +28,15 @@ data class ImportEnvironment(
/** Something in the file this device could not take, for the import summary. */
sealed interface SkippedSetting {
/** No calendar on this device matches the file's (or more than one does). */
data class Calendar(val displayName: String, val accountName: String) : SkippedSetting
/** No calendar on this device matches the file's, or [ambiguous]ly more than one does. */
data class Calendar(
val displayName: String,
val accountName: String,
val ambiguous: Boolean = false,
) : SkippedSetting
/** The calendars couldn't be read, so the per-calendar settings were left as they are. */
data object CalendarsUnavailable : SkippedSetting
/** A custom font: the font file itself is not part of the backup. */
data class CustomFont(val role: FontRole) : SkippedSetting
@@ -44,7 +52,6 @@ sealed interface SkippedSetting {
}
data class SettingsImportSummary(
val settingsRestored: Int,
val calendarsMatched: Int,
val skipped: List<SkippedSetting>,
)
@@ -52,16 +59,16 @@ data class SettingsImportSummary(
/**
* A validated backup laid onto this device: the stored values to write in one
* edit, the side effects the engine runs after it, and the summary.
* [calendars] null leaves the per-calendar keys untouched.
* [pendingSpecialDates] are mirror calendars that don't exist yet; the engine
* matches them once the mirror's sync has created them.
*/
data class SettingsImportPlan(
val prefs: Map<Pref<*>, Any?>,
val calendars: Map<Long, CalendarSettings>,
val calendars: Map<Long, CalendarSettings>?,
val pendingSpecialDates: List<CalendarSettings>,
val language: LanguageChoice?,
val launcherName: LauncherName?,
val settingsRestored: Int,
val skipped: List<SkippedSetting>,
)
@@ -105,31 +112,36 @@ fun planSettingsImport(
}
}
// The mirror's calendars are torn down when the imported settings leave it off.
val mirroring = prefs[SettingsKeys.specialDatesEnabled] == true
val available = environment.calendars
val calendars = linkedMapOf<Long, CalendarSettings>()
val pending = mutableListOf<CalendarSettings>()
backup.calendars.forEach { entry ->
val type = entry.calendar.specialDates
val id = if (type != null) {
environment.managed.firstOrNull { it.type == type }?.id
} else {
environment.calendars
.filter { !it.isManaged && it.matches(entry.calendar) }
.singleOrNull()?.id
}
when {
id != null -> calendars[id] = entry
type != null -> pending += entry
else -> skipped += entry.calendar.skipped()
if (available == null) {
if (backup.calendars.isNotEmpty()) skipped += SkippedSetting.CalendarsUnavailable
} else {
backup.calendars.forEach { entry ->
val type = entry.calendar.specialDates
if (type != null) {
if (!mirroring) return@forEach
val id = environment.managed.firstOrNull { it.type == type }?.id
if (id != null) calendars[id] = entry else pending += entry
return@forEach
}
val candidates = available.filter { !it.isManaged && it.matches(entry.calendar) }
when (candidates.size) {
1 -> calendars[candidates.single().id] = entry
else -> skipped += entry.calendar.skipped(ambiguous = candidates.size > 1)
}
}
}
return SettingsImportPlan(
prefs = prefs,
calendars = calendars,
calendars = calendars.takeIf { available != null },
pendingSpecialDates = pending,
language = language,
launcherName = backup.launcherName,
settingsRestored = backup.prefs.size,
skipped = skipped,
)
}
@@ -137,7 +149,7 @@ fun planSettingsImport(
/** Writes the plan's stored values, replacing every backed-up setting and all per-calendar ones. */
fun SettingsImportPlan.applyTo(target: MutablePreferences) {
plainSection.apply(target, prefs)
target.writeCalendarSettings(calendars)
calendars?.let(target::writeCalendarSettings)
}
/**
@@ -173,11 +185,11 @@ fun MutablePreferences.addCalendarSettings(id: Long, entry: CalendarSettings) {
}
}
fun CalendarIdentity.skipped(): SkippedSetting = SkippedSetting.Calendar(displayName, accountName)
fun CalendarIdentity.skipped(ambiguous: Boolean = false): SkippedSetting =
SkippedSetting.Calendar(displayName, accountName, ambiguous)
fun SettingsImportPlan.summary(calendarsMatched: Int, more: List<SkippedSetting> = emptyList()) =
SettingsImportSummary(
settingsRestored = settingsRestored,
calendarsMatched = calendarsMatched,
skipped = skipped + more,
)
@@ -186,7 +186,12 @@ private fun ImportSummaryDialog(summary: SettingsImportSummary, onDismiss: () ->
@Composable
private fun SkippedSetting.label(): String = when (this) {
is SkippedSetting.Calendar -> stringResource(R.string.settings_backup_skipped_calendar, displayName, accountName)
is SkippedSetting.Calendar -> stringResource(
if (ambiguous) R.string.settings_backup_skipped_calendar_ambiguous else R.string.settings_backup_skipped_calendar,
displayName,
accountName,
)
SkippedSetting.CalendarsUnavailable -> stringResource(R.string.settings_backup_skipped_calendars_unavailable)
is SkippedSetting.CustomFont -> stringResource(
when (role) {
FontRole.BRAND -> R.string.settings_backup_skipped_font_headings
@@ -11,7 +11,6 @@ import de.jeanlucmakiola.calendula.data.backup.SettingsImportSummary
import de.jeanlucmakiola.floret.android.DocumentTooLargeException
import de.jeanlucmakiola.floret.android.readDocumentBytes
import de.jeanlucmakiola.floret.android.writeDocumentBytes
import de.jeanlucmakiola.floret.backup.BackupFormat
import de.jeanlucmakiola.floret.backup.BackupProblem
import de.jeanlucmakiola.floret.backup.BackupResult
import de.jeanlucmakiola.floret.di.IoDispatcher
@@ -67,7 +66,7 @@ class SettingsBackupViewModel @Inject constructor(
fun import(uri: Uri) = launchWork {
val text = try {
withContext(io) {
context.contentResolver.readDocumentBytes(uri, BackupFormat.DEFAULT_MAX_CHARS).toString(Charsets.UTF_8)
context.contentResolver.readDocumentBytes(uri, engine.maxImportBytes).toString(Charsets.UTF_8)
}
} catch (e: CancellationException) {
throw e
+4 -1
View File
@@ -919,7 +919,7 @@
<string name="settings_backup_export_done">Settings exported.</string>
<string name="settings_backup_export_failed">Couldn\'t export the settings.</string>
<string name="settings_backup_import_confirm_title">Replace your settings?</string>
<string name="settings_backup_import_confirm_message">Every setting is replaced with the one in the file. Your events and calendars stay as they are.</string>
<string name="settings_backup_import_confirm_message">Every setting is replaced with the one in the file. Your events and calendars stay as they are, apart from contact special dates, which follow the imported setting.</string>
<string name="settings_backup_import_confirm_action">Replace</string>
<string name="settings_backup_import_failed_not_backup">That file isn\'t a Calendula settings backup.</string>
<string name="settings_backup_import_failed_newer">That backup is from a newer Calendula. Update the app to import it.</string>
@@ -936,6 +936,9 @@
<string name="settings_backup_imported_skipped">Not imported</string>
<!-- %1$s: calendar name, %2$s: its account -->
<string name="settings_backup_skipped_calendar">%1$s (%2$s): no matching calendar on this phone</string>
<!-- %1$s: calendar name, %2$s: its account -->
<string name="settings_backup_skipped_calendar_ambiguous">%1$s (%2$s): more than one calendar on this phone has that name</string>
<string name="settings_backup_skipped_calendars_unavailable">Calendar settings: Calendula can\'t read your calendars, so they were left as they are</string>
<string name="settings_backup_skipped_font_headings">Custom headings font: choose the font file again</string>
<string name="settings_backup_skipped_font_body">Custom body font: choose the font file again</string>
<string name="settings_backup_skipped_special_dates">Contact special dates: turn them on again to allow access to contacts</string>
@@ -37,7 +37,7 @@ class SettingsBackupTest {
private val birthdays = calendar(3, "Birthdays", account = "Calendula", managed = true)
private fun environment(
calendars: List<CalendarSource> = listOf(work, home, birthdays),
calendars: List<CalendarSource>? = listOf(work, home, birthdays),
managed: List<ManagedCalendarRow> = listOf(ManagedCalendarRow(3, SpecialDateType.Birthday)),
contacts: Boolean = true,
fonts: Set<FontRole> = emptySet(),
@@ -119,7 +119,7 @@ class SettingsBackupTest {
assertThat(target[CalendarPrefKeys.lastUsedCalendarId]).isEqualTo(12L)
assertThat(target[SettingsKeys.perCalendarEventDuration]).containsExactly(11L, 30)
assertThat(target[SettingsKeys.perCalendarReminderOverride]).containsExactly(12L, emptyList<Int>())
assertThat(plan.summary(plan.calendars.size).calendarsMatched).isEqualTo(2)
assertThat(plan.calendars).hasSize(2)
}
@Test
@@ -144,7 +144,33 @@ class SettingsBackupTest {
val plan = import(roundTrip(source), target, environment(calendars = listOf(calendar(5, "Work"), calendar(6, "Work"))))
assertThat(target[CalendarPrefKeys.hiddenCalendarIds]).isEmpty()
assertThat(plan.skipped).hasSize(1)
assertThat(plan.skipped).containsExactly(SkippedSetting.Calendar("Work", "me@example.org", ambiguous = true))
}
@Test
fun `unreadable calendars leave the per-calendar settings alone`() {
val source = mutablePreferencesOf()
source[CalendarPrefKeys.hiddenCalendarIds] = setOf(1L)
val target = mutablePreferencesOf()
target[SettingsKeys.perCalendarEventDuration] = mapOf(4L to 45)
val plan = import(roundTrip(source), target, environment(calendars = null))
assertThat(target[SettingsKeys.perCalendarEventDuration]).containsExactly(4L, 45)
assertThat(plan.skipped).containsExactly(SkippedSetting.CalendarsUnavailable)
}
@Test
fun `mirror calendars are left out when the import turns the mirror off`() {
val source = mutablePreferencesOf()
source[CalendarPrefKeys.hiddenCalendarIds] = setOf(3L)
val target = mutablePreferencesOf()
val plan = import(roundTrip(source), target)
assertThat(target[CalendarPrefKeys.hiddenCalendarIds]).isEmpty()
assertThat(plan.pendingSpecialDates).isEmpty()
assertThat(plan.skipped).isEmpty()
}
@Test
@@ -158,6 +184,7 @@ class SettingsBackupTest {
@Test
fun `a mirror calendar is matched by its date type`() {
val source = mutablePreferencesOf()
source[SettingsKeys.specialDatesEnabled] = true
source[SettingsKeys.perCalendarAllDayReminderOverride] = mapOf(3L to listOf(0, 10080))
val target = mutablePreferencesOf()
@@ -170,6 +197,7 @@ class SettingsBackupTest {
@Test
fun `a mirror calendar that doesn't exist yet waits for the sync`() {
val source = mutablePreferencesOf()
source[SettingsKeys.specialDatesEnabled] = true
source[SettingsKeys.perCalendarAllDayReminderOverride] = mapOf(3L to listOf(0))
val target = mutablePreferencesOf()
+9 -3
View File
@@ -89,11 +89,17 @@ identity instead:
On import an entry matches the one calendar here with the same account name,
account type and display name. No match, or more than one, skips it and the
summary names it. A mirror calendar matches by `special_dates` instead, since
its name is localised; when the mirror has not created it yet, it is matched
after the import's sync, and its all-day reminders are applied through the
mirror so its existing events follow. An id in the prefs whose calendar no
its name is localised, and only when the imported settings keep the mirror on
(otherwise the import tears it down). When the mirror has not created it yet,
it is matched after the import's sync. Every mirror's all-day reminders are
applied through the mirror so its existing events follow; one the file doesn't
override inherits the default again. An id in the prefs whose calendar no
longer exists is left out of the export.
If this device's calendars can't be read, the per-calendar settings here are
left untouched and the summary says so; an export in that state fails rather
than writing a file without them.
## `app`
| Field | Type | Notes |