fix(#147, #325): review round 2 - empty sync-id masters kept, series held when its occurrence fails, declined invites not copied

This commit is contained in:
makiolaj committed 2026-11-14 01:32:21 +01:00
1 parent d5079f0618
commit 0a36a6d287
11 files changed
+88 -53

No files matched your search

@@ -793,31 +793,30 @@ class AndroidCalendarDataSource @Inject constructor(
forEachExportRow(selection, allDayReminderTimeMinutes) { event ->
val calendarId = getLong(EventExportProjection.IDX_CALENDAR_ID)
val calendar = calendars[calendarId]
// Some adapters stamp the calendar's colour onto every row; that is no
// colour of the event's own and would pin it in a copy. A palette key
// means it was chosen.
// An adapter may stamp the calendar colour on every row; a palette key means it was chosen.
val color = getIntOrNull(EventExportProjection.IDX_EVENT_COLOR)?.takeIf {
it != calendar?.color || !getString(EventExportProjection.IDX_EVENT_COLOR_KEY).isNullOrEmpty()
}
val mapped = event(calendar?.displayName).copy(color = color)
val originalId = getLongOrNull(EventExportProjection.IDX_ORIGINAL_ID)
val originalSyncId = getString(EventExportProjection.IDX_ORIGINAL_SYNC_ID)
// An empty ORIGINAL_SYNC_ID still marks an exception, one that can't be linked.
if (originalId == null && originalSyncId == null) {
val originalSyncId = getString(EventExportProjection.IDX_ORIGINAL_SYNC_ID)?.takeIf { it.isNotEmpty() }
val originalInstance = getLongOrNull(EventExportProjection.IDX_ORIGINAL_INSTANCE_TIME)
if (originalId == null && originalSyncId == null && originalInstance == null) {
series += MasterRow(
eventId = getLong(EventExportProjection.IDX_ID),
calendarId = calendarId,
syncId = getString(EventExportProjection.IDX_SYNC_ID)?.takeIf { it.isNotEmpty() },
event = mapped,
declined = getIntOrNull(EventExportProjection.IDX_SELF_ATTENDEE_STATUS) ==
CalendarContract.Attendees.ATTENDEE_STATUS_DECLINED,
)
} else {
// An exception without its occurrence time can't name what it replaces.
val originalInstance = getLongOrNull(EventExportProjection.IDX_ORIGINAL_INSTANCE_TIME)
?: return@forEachExportRow
if (originalInstance == null) return@forEachExportRow
overrides += OverrideRow(
calendarId = calendarId,
originalId = originalId,
originalSyncId = originalSyncId.takeIf { !it.isNullOrEmpty() },
originalSyncId = originalSyncId,
originalInstance = originalInstance.toKotlinInstantFromEpochMillis(),
event = mapped,
)
@@ -252,10 +252,11 @@ class CalendarRepositoryImpl @Inject constructor(
}
override suspend fun exportEvents(calendarIds: Set<Long>) = withContext(io) {
// A file can't carry RDATE: such a series is written as the one-off it reads as.
val rows = dataSource.calendarRows(calendarIds, allDayReminderTimeMinutes())
flattenOverrides(
rows = dataSource.calendarRows(calendarIds, allDayReminderTimeMinutes()),
exdateStamp = ::formatExdateStamp,
keepsRecurrenceDates = false,
rows.copy(series = rows.series.map { it.copy(event = it.event.copy(recurrenceDates = null)) }),
::formatExdateStamp,
)
}
@@ -271,11 +272,9 @@ class CalendarRepositoryImpl @Inject constructor(
)
}
onProgress(0, events.size)
// Checked between events, so cancelling stops the copy; a plain import
// keeps running to the end of its file.
val context = currentCoroutineContext()
return importEvents(targetCalendarId, events) { done ->
context.ensureActive()
if (done < events.size) context.ensureActive()
onProgress(done, events.size)
}
}
@@ -296,6 +295,9 @@ class CalendarRepositoryImpl @Inject constructor(
var skipped = 0
var failed = 0
var notAttempted = 0
// Series whose standalone occurrence didn't land: inserted, they would
// exclude it for good, since a re-run skips it next to its series.
val held = mutableSetOf<String>()
for ((index, event) in events.withIndex()) {
if (index > 0) onProgress(index)
// A known UID means the event is already in this calendar — skip,
@@ -304,6 +306,10 @@ class CalendarRepositoryImpl @Inject constructor(
skipped++
continue
}
if (event.uid != null && event.uid in held) {
failed++
continue
}
try {
dataSource.insertImportedEvent(event, targetCalendarId, allDayMinutes, palette)
imported++
@@ -325,6 +331,7 @@ class CalendarRepositoryImpl @Inject constructor(
// rest of the file — foreign exports do carry rows it rejects
// outright (a malformed RRULE throws straight out of insert).
failed++
event.overrideOf?.let(held::add)
Log.w(TAG, "Skipped an unimportable event", e)
}
}
@@ -185,6 +185,7 @@ internal object EventExportProjection {
CalendarContract.Events.RDATE,
CalendarContract.Events.ACCESS_LEVEL,
CalendarContract.Events.EVENT_COLOR_KEY,
CalendarContract.Events.SELF_ATTENDEE_STATUS,
)
const val IDX_ID = 0
@@ -210,6 +211,7 @@ internal object EventExportProjection {
const val IDX_RDATE = 20
const val IDX_ACCESS_LEVEL = 21
const val IDX_EVENT_COLOR_KEY = 22
const val IDX_SELF_ATTENDEE_STATUS = 23
}
/**
@@ -7,7 +7,7 @@ import kotlin.time.Duration.Companion.days
* The events a calendar copy (#325) inserts into its target, in the shape
* `importEvents` takes: the source's rows flattened as [flattenOverrides] does
* for a backup, minus cancelled series and one-offs, which would arrive live
* (an insert can't be cancelled). Attendees and organizer are never read.
* (an insert can't be cancelled), and declined invitations. Attendees and organizer are never read.
*
* Idempotent per snapshot: `importEvents` skips a UID the target already holds,
* and an [IcsEvent.overrideOf] occurrence whose series it holds, so a re-run
@@ -18,7 +18,7 @@ fun planCalendarCopy(
rows: CalendarRows,
exdateStamp: (occurrenceMillis: Long, isAllDay: Boolean) -> String,
): List<ParsedIcsEvent> {
val live = rows.copy(series = rows.series.filterNot { it.event.status == EventStatus.Cancelled })
val live = rows.copy(series = rows.series.filterNot { it.event.status == EventStatus.Cancelled || it.declined })
return flattenOverrides(live, exdateStamp).map { it.toParsedIcsEvent() }
}
@@ -12,6 +12,8 @@ data class MasterRow(
val calendarId: Long,
val syncId: String?,
val event: IcsEvent,
/** The user declined this invitation. */
val declined: Boolean = false,
)
/**
@@ -52,16 +54,12 @@ data class CalendarRows(
* occurrence missing its series, never a series missing an occurrence.
*
* [exdateStamp] formats an occurrence as an `EXDATE` entry in the provider's
* shape, the same one Calendula's own exclusions use. [keepsRecurrenceDates] is
* false where the output can't carry `RDATE` (an `.ics` file): a series that
* repeats by listed dates alone then reads as the one-off it will be written as,
* and its overrides are left alone rather than excluded from nothing. A
* cancelled series' modified occurrences aren't brought back to life either.
* shape, the same one Calendula's own exclusions use. A cancelled series'
* modified occurrences stay cancelled.
*/
fun flattenOverrides(
rows: CalendarRows,
exdateStamp: (occurrenceMillis: Long, isAllDay: Boolean) -> String,
keepsRecurrenceDates: Boolean = true,
): List<IcsEvent> {
val byId = rows.series.associateBy { it.eventId }
// Sync ids are only unique within an account, so the link is per calendar.
@@ -73,8 +71,7 @@ fun flattenOverrides(
?: override.originalSyncId?.let { bySyncId[override.calendarId to it] }
?: continue
// An exception to a one-off overrides nothing a plain event could carry.
val recurs = if (keepsRecurrenceDates) parent.event.recurs else !parent.event.recurrenceRule.isNullOrBlank()
if (!recurs) continue
if (!parent.event.recurs) continue
val occurrence = override.originalInstance.toEpochMilliseconds()
excluded.getOrPut(parent.eventId) { mutableListOf() } += exdateStamp(occurrence, parent.event.isAllDay)
if (override.isCancelled || parent.event.status == EventStatus.Cancelled) continue
@@ -143,7 +143,7 @@ class CalendarsViewModel @Inject constructor(
uri = uri,
content = IcsWriter().writeCalendar(events, Clock.System.now(), name),
)
events.size
events.count { it.overrideOf == null }
}
BackupResult.Success(count)
} catch (e: CancellationException) {
@@ -6,13 +6,13 @@ import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.padding
import androidx.compose.material3.Button
import androidx.compose.material3.CircularProgressIndicator
import androidx.compose.material3.ExperimentalMaterial3ExpressiveApi
import androidx.compose.material3.LinearWavyProgressIndicator
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.OutlinedButton
import androidx.compose.material3.Text
import androidx.compose.material3.TextButton
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
@@ -63,6 +63,13 @@ fun CopyEventsSheet(
title = stringResource(R.string.calendars_copy_action),
onDismiss = onDismiss,
predictiveBack = true,
actions = {
if (!running) {
TextButton(onClick = onStart, enabled = source != null && target != null) {
Text(stringResource(R.string.calendars_copy_start))
}
}
},
) {
GroupedHint(stringResource(R.string.calendars_copy_hint), style = MaterialTheme.typography.bodySmall)
when (calendars) {
@@ -78,7 +85,7 @@ fun CopyEventsSheet(
}
is CopyCalendars.Ready -> Unit
}
if (sources.isEmpty() && !running) {
if (sources.isEmpty() && run == CopyRunState.Idle) {
GroupedHint(stringResource(R.string.calendars_copy_none))
return@FullScreenPicker
}
@@ -110,15 +117,6 @@ fun CopyEventsSheet(
)
CopyRunState.Idle -> Unit
}
if (!running) {
Button(
onClick = onStart,
enabled = source != null && target != null,
modifier = Modifier.fillMaxWidth(),
) {
Text(stringResource(R.string.calendars_copy_start))
}
}
}
}
@@ -80,7 +80,6 @@ class CopyEventsViewModel @Inject constructor(
job = viewModelScope.launch {
try {
val summary = repository.copyEvents(source, target) { done, total ->
// About every half percent: thousands of inserts needn't mean thousands of frames.
if (done == 0 || done == total || done % (total / 200).coerceAtLeast(1) == 0) {
_run.value = CopyRunState.Running(done, total)
}
@@ -1046,6 +1046,41 @@ class CalendarRepositoryImplTest {
assertThat(summary.skippedDuplicate).isEqualTo(2)
}
@Test
fun `a series waits for a standalone occurrence that didn't land`(
@TempDir tempDir: Path,
) = runTest {
val fake = FakeCalendarDataSource().apply { failingImportSummaries += "moved" }
val repo = testRepository(fake, tempDir, Dispatchers.Unconfined)
val summary = repo.importEvents(
3L,
listOf(parsedEvent("1-s", summary = "moved").copy(overrideOf = "s"), parsedEvent("s"), parsedEvent("t")),
)
assertThat(fake.importedEvents.map { it.first.uid }).containsExactly("t")
assertThat(summary.failed).isEqualTo(2)
}
@Test
fun `a backup writes an RDATE-only series as the one-off a file can hold`(
@TempDir tempDir: Path,
) = runTest {
val start = Instant.parse("2026-01-05T09:00:00Z")
val event = IcsEvent("s", "S", start, Instant.parse("2026-01-05T10:00:00Z"), false, "UTC", recurrenceDates = "20260112T090000Z")
val fake = FakeCalendarDataSource().apply {
calendarRowsResult = CalendarRows(
listOf(MasterRow(1, 1, null, event)),
listOf(OverrideRow(1, 1, null, start, event.copy(recurrenceDates = null))),
)
}
val exported = testRepository(fake, tempDir, Dispatchers.Unconfined).exportEvents(setOf(1L))
assertThat(exported.map { it.uid }).containsExactly("s")
assertThat(exported.single().recurrenceDates).isNull()
}
private fun parsedEvent(uid: String?, summary: String = "E") =
de.jeanlucmakiola.calendula.domain.ics.ParsedIcsEvent(
uid = uid,
@@ -186,18 +186,6 @@ class CalendarRowsTest {
assertThat(IcsParser().parse(text).events.single().overrideOf).isEqualTo("s;1")
}
@Test
fun `a file can't carry RDATE, so an RDATE-only series keeps its overrides out of it`() {
val rows = CalendarRows(
listOf(MasterRow(1, 1, null, event("s").copy(recurrenceDates = "20260112T090000Z"))),
listOf(OverrideRow(1, 1, null, occurrence(1), event("x"))),
)
val flat = flattenOverrides(rows, ::formatExdateStamp, keepsRecurrenceDates = false)
assertThat(flat.map { it.uid }).containsExactly("s")
assertThat(flat.single().exDates).isEmpty()
}
@Test
fun `a cancelled series' moved occurrence isn't brought back`() {
val flat = flatten(
@@ -220,4 +208,11 @@ class CalendarRowsTest {
assertThat(flat.count { it.overrideOf == "s" }).isEqualTo(2)
}
@Test
fun `a copy leaves declined invitations out`() {
val rows = CalendarRows(listOf(series("d").copy(declined = true), series("k", id = 2)), emptyList())
assertThat(planCalendarCopy(rows, ::formatExdateStamp).map { it.uid }).containsExactly("k")
}
}
+6 -3
View File
@@ -507,7 +507,10 @@ times. Its UID is derived from the series UID and the occurrence, so it is the
same in every backup, and it carries the series UID as `X-CALENDULA-OVERRIDE-OF`.
`importEvents` skips such an occurrence wherever its series already is — that
series there has the override itself — so restoring into the calendar a backup
came from adds nothing twice, while a restore into an empty one gets both.
came from adds nothing twice, while a restore into an empty one gets both. If
the standalone occurrence fails to insert, its series is held back too (counted
as not added), since inserted with the occurrence excluded it would make every
re-run skip the occurrence for good.
Exceptions whose series isn't among the rows are left out, a cancelled
series' moved occurrences stay cancelled, and sync ids link only within their
own calendar. A file can't carry `RDATE`, so a backup treats a series that
@@ -518,8 +521,8 @@ and restore exactly as before.
flattened rows straight into `importEvents`, so the UID dedup makes a re-run skip
what landed before. It skips the `.ics` text: the writer pins a timed one-off to
UTC and carries no colour, visibility or `RDATE`; the direct mapping keeps them.
Attendees and organizer are never read, and cancelled events are left out (an
insert can't be cancelled; it would arrive live). A re-run is idempotent per
Attendees and organizer are never read, and cancelled events and declined
invitations are left out (an insert can't be cancelled; it would arrive live). A re-run is idempotent per
snapshot: a series already in the target keeps its overrides, so an occurrence
changed since keeps its earlier copy rather than gaining a second one.