diff --git a/app/src/main/java/de/jeanlucmakiola/calendula/data/calendar/CalendarDataSource.kt b/app/src/main/java/de/jeanlucmakiola/calendula/data/calendar/CalendarDataSource.kt index 8cfd3f78..3790ba81 100644 --- a/app/src/main/java/de/jeanlucmakiola/calendula/data/calendar/CalendarDataSource.kt +++ b/app/src/main/java/de/jeanlucmakiola/calendula/data/calendar/CalendarDataSource.kt @@ -1270,7 +1270,7 @@ class AndroidCalendarDataSource @Inject constructor( form: EventForm, allDayReminderTimeMinutes: Int, ): Long { - val row = querySeriesRow(eventId) + val row = querySeriesRow(eventId, beginMillis) // Not a series, so there is no occurrence to single out: the row *is* the // event, and an exception with nothing to be an exception to would leave // an orphan holding the edit (the same test deleteOccurrence makes). @@ -1349,6 +1349,8 @@ class AndroidCalendarDataSource @Inject constructor( // Reminders, guests and colour come along like any new event, and so does // a fresh UID — the detached row is a separate event now, and sharing the // parent's would collide with it in .ics restore dedup. + // Fail before inserting: the EXDATE write below needs a usable length. + row.writeDuration() val detachedId = insertEvent(form.toDetachedOccurrence(), allDayReminderTimeMinutes) // Rows touched, not occurrences excluded — 1 whenever the series row still // exists. It catches the row disappearing under us, not an EXDATE the @@ -1384,7 +1386,7 @@ class AndroidCalendarDataSource @Inject constructor( updated: EventForm, allDayReminderTimeMinutes: Int, ): Long { - val row = querySeriesRow(eventId) + val row = querySeriesRow(eventId, beginMillis) // From the first occurrence on (or with no rule to split) this is // just a series update. if (row.rrule.isNullOrBlank() || beginMillis <= row.dtStartMillis) { @@ -1392,6 +1394,8 @@ class AndroidCalendarDataSource @Inject constructor( return eventId } // Insert the new series first: if it fails, the original is untouched. + // Fail before inserting: truncating the original needs a usable length. + row.writeDuration() val newEventId = insertEvent(updated, allDayReminderTimeMinutes) carrySplitExdate(newEventId, row, beginMillis, original, updated) truncateSeries(eventId, row, beginMillis) @@ -1447,7 +1451,7 @@ class AndroidCalendarDataSource @Inject constructor( } override fun deleteEventFromOccurrence(eventId: Long, beginMillis: Long) { - val row = querySeriesRow(eventId) + val row = querySeriesRow(eventId, beginMillis) // From the first occurrence on = the whole series; also the fallback // when there is no RRULE to truncate. if (row.rrule.isNullOrBlank() || beginMillis <= row.dtStartMillis) { @@ -1476,8 +1480,12 @@ class AndroidCalendarDataSource @Inject constructor( updateEventRow(eventId, values, "truncate series event id=$eventId begin=$beginMillis") } - /** The series anchor: every time-related column of the Events row. */ - private fun querySeriesRow(eventId: Long): SeriesRow = resolver.query( + /** + * The series anchor: every time-related column of the Events row. A recurring + * row with no usable DURATION gets one derived ([seriesDuration]), from the + * expanded occurrence at [occurrenceMillis] when DTEND can't supply it. + */ + private fun querySeriesRow(eventId: Long, occurrenceMillis: Long? = null): SeriesRow = resolver.query( eventUri(eventId), arrayOf( CalendarContract.Events.DTSTART, @@ -1488,11 +1496,12 @@ class AndroidCalendarDataSource @Inject constructor( CalendarContract.Events._SYNC_ID, CalendarContract.Events.EXDATE, CalendarContract.Events.RDATE, + CalendarContract.Events.DTEND, ), null, null, null, )?.use { c -> if (c.moveToFirst()) { - SeriesRow( + val row = SeriesRow( dtStartMillis = c.getLong(0), rrule = c.getString(1), timezone = c.getString(2), @@ -1502,11 +1511,27 @@ class AndroidCalendarDataSource @Inject constructor( exdate = c.getString(6), rdate = c.getString(7), ) + if (!row.recurs || !row.duration.isNullOrBlank()) return@use row + row.copy( + dtEndMillis = if (c.isNull(8)) null else c.getLong(8), + occurrenceSpanMillis = occurrenceMillis?.let { occurrenceSpan(eventId, it) }, + ) } else { null } } ?: throw WriteFailedException("read series row of event id=$eventId") + /** Length of the already-expanded occurrence of [eventId] starting at [beginMillis]. */ + private fun occurrenceSpan(eventId: Long, beginMillis: Long): Long? { + return resolver.query( + instancesUri(beginMillis, beginMillis + 1), + arrayOf(CalendarContract.Instances.BEGIN, CalendarContract.Instances.END), + "${CalendarContract.Instances.EVENT_ID} = ? AND ${CalendarContract.Instances.BEGIN} = ?", + arrayOf(eventId.toString(), beginMillis.toString()), + null, + )?.use { c -> if (c.moveToFirst()) c.getLong(1) - c.getLong(0) else null } + } + private data class SeriesRow( val dtStartMillis: Long, val rrule: String?, @@ -1517,6 +1542,9 @@ class AndroidCalendarDataSource @Inject constructor( val syncId: String? = null, val exdate: String? = null, val rdate: String? = null, + /** Only read for a series with no DURATION, to derive one ([writeDuration]). */ + val dtEndMillis: Long? = null, + val occurrenceSpanMillis: Long? = null, ) { /** * Whether this row expands into more than itself. RDATE counts as much as @@ -1526,14 +1554,23 @@ class AndroidCalendarDataSource @Inject constructor( */ val recurs: Boolean get() = !rrule.isNullOrBlank() || !rdate.isNullOrBlank() + /** + * DURATION for a write that re-expands the series. Refuses rather than + * writing none, which would leave the provider nothing to expand (#502). + */ + fun writeDuration(): String = duration?.takeIf { it.isNotBlank() } + ?: seriesDuration(dtStartMillis, dtEndMillis, occurrenceSpanMillis, allDay != 0) + ?: throw WriteFailedException("series has no usable length") + /** * The time/recurrence set a series write carries together: the provider * re-expands instances only from what the update itself holds. */ fun timeColumns(): ContentValues = ContentValues().apply { put(CalendarContract.Events.DTSTART, dtStartMillis) + putNull(CalendarContract.Events.DTEND) put(CalendarContract.Events.RRULE, rrule) - put(CalendarContract.Events.DURATION, duration) + put(CalendarContract.Events.DURATION, writeDuration()) put(CalendarContract.Events.EVENT_TIMEZONE, timezone) put(CalendarContract.Events.ALL_DAY, allDay) } @@ -1545,7 +1582,7 @@ class AndroidCalendarDataSource @Inject constructor( dtStartMillis = dtStartMillis, rrule = rrule, rdate = rdate, - duration = duration, + duration = writeDuration(), timezone = timezone, allDay = allDay, ) @@ -1732,7 +1769,7 @@ class AndroidCalendarDataSource @Inject constructor( } override fun deleteOccurrence(eventId: Long, beginMillis: Long) { - val row = querySeriesRow(eventId) + val row = querySeriesRow(eventId, beginMillis) // Not a series, so the row *is* the event: an exclusion would put a // recurrence set on a one-off, an exception would leave an orphan. if (!row.recurs) { @@ -1762,7 +1799,7 @@ class AndroidCalendarDataSource @Inject constructor( val values = buildOccurrenceCancelValues( originalInstanceMillis = beginMillis, dtStartMillis = beginMillis, - duration = row.duration, + duration = row.writeDuration(), timezone = row.timezone, allDay = row.allDay, ) diff --git a/app/src/main/java/de/jeanlucmakiola/calendula/data/calendar/EventWriteMapper.kt b/app/src/main/java/de/jeanlucmakiola/calendula/data/calendar/EventWriteMapper.kt index 328b1215..980a38ad 100644 --- a/app/src/main/java/de/jeanlucmakiola/calendula/data/calendar/EventWriteMapper.kt +++ b/app/src/main/java/de/jeanlucmakiola/calendula/data/calendar/EventWriteMapper.kt @@ -369,7 +369,8 @@ internal fun buildMovedMasterValues( /** The recurring copy's DURATION: its own if present, else derived from DTEND. */ private fun MasterEventSnapshot.movedDuration(): String = duration?.takeIf { it.isNotBlank() } - ?: rfc2445Duration((dtEndMillis ?: dtStartMillis) - dtStartMillis, isAllDay) + ?: seriesDuration(dtStartMillis, dtEndMillis ?: dtStartMillis, occurrenceSpanMillis = null, isAllDay = isAllDay) + ?: throw WriteFailedException("move series with no usable length") /** * Raw provider snapshot of one exception row of a recurring series (a modified @@ -454,6 +455,29 @@ internal fun buildOccurrenceExdateValues( existingExdate, listOf(occurrenceMillis), dtStartMillis, rrule, rdate, duration, timezone, allDay, ) +/** + * DURATION for a series row that has none. Rows from other tools can carry a + * DTEND (sometimes 0) instead; rewriting them without a DURATION leaves the + * provider nothing to expand, and every occurrence vanishes (#502). The span of + * an occurrence the provider actually expanded wins over DTEND; null when + * neither gives a length (a DTEND before DTSTART), so the caller fails + * instead of guessing. + */ +internal fun seriesDuration( + dtStartMillis: Long, + dtEndMillis: Long?, + occurrenceSpanMillis: Long?, + isAllDay: Boolean, +): String? { + val span = occurrenceSpanMillis?.takeIf { it >= 0 } + ?: dtEndMillis?.minus(dtStartMillis)?.takeIf { it >= 0 } + ?: return null + if (!isAllDay) return rfc2445Duration(span, isAllDay = false) + // Whole days, rounded: a span read across a DST change or zone offset is a few hours off. + val days = ((span + MILLIS_PER_DAY / 2) / MILLIS_PER_DAY).coerceAtLeast(1) + return rfc2445Duration(days * MILLIS_PER_DAY, isAllDay = true) +} + /** [buildOccurrenceExdateValues] excluding every one of [occurrences] in one write. */ internal fun buildOccurrencesExdateValues( existingExdate: String?, @@ -469,6 +493,7 @@ internal fun buildOccurrencesExdateValues( mergedExdate(exdate, millis, allDay != 0, timezone) }, CalendarContract.Events.DTSTART to dtStartMillis, + CalendarContract.Events.DTEND to null, CalendarContract.Events.RRULE to rrule, CalendarContract.Events.RDATE to rdate, CalendarContract.Events.DURATION to duration, diff --git a/app/src/test/java/de/jeanlucmakiola/calendula/data/calendar/EventWriteMapperTest.kt b/app/src/test/java/de/jeanlucmakiola/calendula/data/calendar/EventWriteMapperTest.kt index 9cd03414..bbfe7355 100644 --- a/app/src/test/java/de/jeanlucmakiola/calendula/data/calendar/EventWriteMapperTest.kt +++ b/app/src/test/java/de/jeanlucmakiola/calendula/data/calendar/EventWriteMapperTest.kt @@ -13,6 +13,7 @@ import kotlinx.datetime.LocalDateTime import kotlinx.datetime.LocalTime import kotlinx.datetime.UtcOffset import org.junit.jupiter.api.Test +import org.junit.jupiter.api.assertThrows import java.time.ZoneId import kotlin.time.Instant @@ -500,6 +501,58 @@ class EventWriteMapperTest { .isEqualTo(CalendarContract.Events.STATUS_CANCELED) } + // --- seriesDuration (#502) --- + + @Test + fun `series duration prefers the expanded occurrence over dtend`() { + // DTEND as the end of the whole series must not stretch every occurrence. + assertThat(seriesDuration(1_000_000L, 9_000_000_000L, 3_600_000L, isAllDay = false)).isEqualTo("P3600S") + } + + @Test + fun `series duration falls back to dtend when it lies after dtstart`() { + assertThat(seriesDuration(1_000_000L, 8_200_000L, null, isAllDay = false)).isEqualTo("P7200S") + } + + @Test + fun `series duration ignores a zero dtend and uses the occurrence span`() { + assertThat(seriesDuration(1_790_852_400_000L, 0L, 7_200_000L, isAllDay = false)).isEqualTo("P7200S") + } + + @Test + fun `series duration gives up rather than guessing`() { + assertThat(seriesDuration(1_000L, 0L, null, isAllDay = false)).isNull() + assertThat(seriesDuration(1_000L, null, null, isAllDay = true)).isNull() + } + + @Test + fun `all-day series duration rounds to whole days`() { + // 47 h: a two-day occurrence read across a DST change. + assertThat(seriesDuration(0L, null, 47L * 3_600_000L, isAllDay = true)).isEqualTo("P2D") + } + + @Test + fun `series duration keeps a zero length the provider already shows`() { + assertThat(seriesDuration(1_000L, 0L, 0L, isAllDay = false)).isEqualTo("P0S") + assertThat(seriesDuration(1_000L, 1_000L, null, isAllDay = true)).isEqualTo("P1D") + } + + @Test + fun `exdate drop clears a stray dtend on the series`() { + val values = buildOccurrenceExdateValues( + existingExdate = null, + occurrenceMillis = 1_784_102_400_000L, + dtStartMillis = 1_783_929_600_000L, + rrule = "FREQ=DAILY;COUNT=5", + rdate = null, + duration = "PT1H", + timezone = "Europe/Berlin", + allDay = 0, + ) + assertThat(values).containsKey(CalendarContract.Events.DTEND) + assertThat(values[CalendarContract.Events.DTEND]).isNull() + } + // --- buildOccurrenceExdateValues ("delete only this event", no _sync_id) --- @Test @@ -1194,6 +1247,14 @@ class EventWriteMapperTest { description = "", ) + @Test + fun `moved series with a zero dtend and no duration is refused, not copied broken`() { + val snapshot = masterSnapshot(dtEndMillis = 0L, rrule = "FREQ=WEEKLY;BYDAY=TH") + assertThrows { + buildMovedMasterValues(snapshot, targetCalendarId = 9L, uid = "u@calendula") + } + } + @Test fun `moved one-off carries target calendar, uid and DTEND but no recurrence`() { val values = buildMovedMasterValues(masterSnapshot(), targetCalendarId = 9L, uid = "u@calendula")