calendar: import RDATE/EXDATE and resolve occurrences in the event zone (#554)
- Commit
240ccf84c2aab3b23160adf6643d1831c9a5bd08- Author
- vayun-mathur <[email protected]>
- When
- 2026-08-19 00:26 UTC (3 months ago)
- Parents
5b69714
Diff
calendar/src/main/java/com/vayunmathur/calendar/data/Event.kt
diff --git a/calendar/src/main/java/com/vayunmathur/calendar/data/Event.kt b/calendar/src/main/java/com/vayunmathur/calendar/data/Event.ktindex 93ff32b4ee..815d1d6cc6 100644--- a/calendar/src/main/java/com/vayunmathur/calendar/data/Event.kt+++ b/calendar/src/main/java/com/vayunmathur/calendar/data/Event.kt@@ -13,6 +13,7 @@ import kotlinx.datetime.toInstant import kotlinx.datetime.toLocalDateTime import com.vayunmathur.calendar.util.RRule import com.vayunmathur.calendar.util.parseIcalBasicDate+import com.vayunmathur.calendar.util.parseIcalOccurrenceDate import com.vayunmathur.calendar.util.toIcalBasic import com.vayunmathur.calendar.util.toIcalUtcDateTime import kotlinx.serialization.Serializable@@ -166,14 +167,17 @@ data class Event( end = start + durationMillis } - // Parse EXDATE field - comma-separated RFC 5545 dates (YYYYMMDD or YYYYMMDDTHHMMSSZ)- val exdate = exdateStr?.split(",")?.mapNotNull { parseIcalBasicDate(it.trim()) }- ?: emptyList()+ // EXDATE/RDATE are comma-separated RFC 5545 dates, either YYYYMMDD or a+ // datetime. A datetime is resolved in the event's own zone, because a+ // late-evening occurrence written as UTC lands on the next UTC day and+ // taking the date off the raw string would move it.+ val exdate = exdateStr?.split(",")?.mapNotNull {+ parseIcalOccurrenceDate(it.trim(), tz)+ } ?: emptyList() - // RDATE is the same shape, and may carry a leading "TZID=...:" or- // "VALUE=DATE:" parameter when another client wrote it.+ // Another client may prefix the value with "TZID=...:" or "VALUE=DATE:". val rdate = rdateStr?.split(",")?.mapNotNull {- parseIcalBasicDate(it.trim().substringAfterLast(':'))+ parseIcalOccurrenceDate(it.trim().substringAfterLast(':'), tz) } ?: emptyList() if (deleted) continue
calendar/src/main/java/com/vayunmathur/calendar/ui/IcsImport.kt
diff --git a/calendar/src/main/java/com/vayunmathur/calendar/ui/IcsImport.kt b/calendar/src/main/java/com/vayunmathur/calendar/ui/IcsImport.ktindex 9f6524cbf5..bf5f1ed789 100644--- a/calendar/src/main/java/com/vayunmathur/calendar/ui/IcsImport.kt+++ b/calendar/src/main/java/com/vayunmathur/calendar/ui/IcsImport.kt@@ -14,15 +14,18 @@ import androidx.compose.ui.Modifier import androidx.compose.ui.graphics.Color import androidx.compose.ui.unit.dp import androidx.glance.LocalContext+import com.vayunmathur.calendar.R import com.vayunmathur.calendar.data.Event import com.vayunmathur.calendar.util.AllDayFormat import com.vayunmathur.calendar.util.BasicIsoInstantFormat import com.vayunmathur.calendar.util.RRule+import kotlinx.datetime.LocalDate import kotlinx.datetime.LocalDateTime import kotlinx.datetime.TimeZone import kotlinx.datetime.atStartOfDayIn import kotlinx.datetime.format.char import kotlinx.datetime.toInstant+import kotlinx.datetime.toLocalDateTime import java.io.BufferedInputStream import java.io.InputStream import kotlin.time.Duration@@ -46,6 +49,15 @@ fun EventCard(event: Event) { Text(dateRangeString(context, event.startDateTimeDisplay.date, event.endDateTimeDisplay.date, event.startDateTimeDisplay.time, event.endDateTimeDisplay.time, event.allDay)) // RRULE text event.rrule?.let { Text(it.describe(context)) }+ if (event.rdate.isNotEmpty()) {+ Text(+ context.resources.getQuantityString(+ R.plurals.repeat_dates_summary,+ event.rdate.size + 1,+ event.rdate.size + 1,+ )+ )+ } if (event.description.isNotBlank()) { Text(event.description)@@ -79,6 +91,11 @@ fun parseICSFile(iS: InputStream): List<Event> { } var current = mutableMapOf<String, String>()+ // RDATE and EXDATE legitimately appear on several lines in one VEVENT, so unlike every other+ // property they have to accumulate instead of overwriting. The params half is kept per line+ // because each line carries its own TZID.+ var rdateProps = mutableListOf<Pair<String, String>>()+ var exdateProps = mutableListOf<Pair<String, String>>() var inEvent = false for (raw in lines) {@@ -86,6 +103,8 @@ fun parseICSFile(iS: InputStream): List<Event> { if (line.equals("BEGIN:VEVENT", ignoreCase = true)) { inEvent = true current = mutableMapOf()+ rdateProps = mutableListOf()+ exdateProps = mutableListOf() continue } if (line.equals("END:VEVENT", ignoreCase = true)) {@@ -123,14 +142,25 @@ fun parseICSFile(iS: InputStream): List<Event> { endMillis = startMillis + 1.days.inWholeMilliseconds } + val zone = TimeZone.of(timezone)+ val startDate = startMillis?.let {+ Instant.fromEpochMilliseconds(it).toLocalDateTime(zone).date+ }+ // DTSTART is an occurrence in its own right, so the model keeps RDATE as the extra+ // days only; a file that lists the start date again would otherwise double it up.+ val rdate = parseIcsDates(rdateProps, zone).filter { it != startDate }+ val exdate = parseIcsDates(exdateProps, zone)+ val evt = Event(id, -1, title, description, location, null, startMillis ?: 0L, endMillis ?: (startMillis ?: 0L), timezone,- startAllDay, rrule)+ startAllDay, rrule, exdate = exdate, rdate = rdate) events.add(evt) } catch (e: Exception) { Log.e("IcsImport", "Error parsing VEVENT", e) } inEvent = false current = mutableMapOf()+ rdateProps = mutableListOf()+ exdateProps = mutableListOf() continue } @@ -156,6 +186,8 @@ fun parseICSFile(iS: InputStream): List<Event> { current["DTEND"] = value current["DTEND_PROP"] = left }+ "RDATE" -> rdateProps.add(left to value)+ "EXDATE" -> exdateProps.add(left to value) else -> current[propName] = value } }@@ -163,8 +195,27 @@ fun parseICSFile(iS: InputStream): List<Event> { return events } +/**+ * The days a set of RDATE or EXDATE lines names, in [zone]. Each line's value is itself a+ * comma-separated list, and a value is either a bare day or a datetime that has to be resolved to+ * one.+ */+private fun parseIcsDates(props: List<Pair<String, String>>, zone: TimeZone): List<LocalDate> =+ props.flatMap { (left, values) -> values.split(",").map { left to it.trim() } }+ .mapNotNull { (left, value) ->+ if (value.length == 8 && value.all { it.isDigit() }) {+ runCatching { AllDayFormat.parse(value) }.getOrNull()+ } else {+ // Reuse the DTSTART/DTEND parser so TZID, 'Z' and floating values behave the same.+ parseICSTime(left, value).first?.let {+ Instant.fromEpochMilliseconds(it).toLocalDateTime(zone).date+ }+ }+ }+ .distinct()+ .sorted()+ // Parse ICS time value with optional params-left (like DTSTART;TZID=America/Los_Angeles)-// Returns Triple(startMillisOrNull, isAllDay, timezoneOrNull) private fun parseICSTime(propLeft: String?, value: String?): Triple<Long?, Boolean, String?> { if (value == null) return Triple(null, false, null)
calendar/src/main/java/com/vayunmathur/calendar/util/DateFormats.kt
diff --git a/calendar/src/main/java/com/vayunmathur/calendar/util/DateFormats.kt b/calendar/src/main/java/com/vayunmathur/calendar/util/DateFormats.ktindex 8ad412d042..9c9a285f07 100644--- a/calendar/src/main/java/com/vayunmathur/calendar/util/DateFormats.kt+++ b/calendar/src/main/java/com/vayunmathur/calendar/util/DateFormats.kt@@ -56,3 +56,14 @@ fun parseIcalUntil(value: String, timeZone: TimeZone): LocalDate? = runCatching AllDayFormat.parse(value) } }.getOrNull()++/**+ * The calendar day one EXDATE/RDATE value falls on, resolved in [timeZone].+ *+ * A date-only value already is that day. A datetime is an instant, so it has to be converted before+ * the day is taken: 22:00 in New York is written as the following day in UTC, and reading the day+ * straight off the string would move the occurrence. Falls back to the leading date for a datetime+ * that carries no offset, which is all a floating value can mean without its TZID.+ */+fun parseIcalOccurrenceDate(value: String, timeZone: TimeZone): LocalDate? =+ parseIcalUntil(value, timeZone) ?: parseIcalBasicDate(value)
calendar/src/test/java/com/vayunmathur/calendar/ui/IcsImportTest.kt
diff --git a/calendar/src/test/java/com/vayunmathur/calendar/ui/IcsImportTest.kt b/calendar/src/test/java/com/vayunmathur/calendar/ui/IcsImportTest.ktnew file mode 100644index 0000000000..1855f087d1--- /dev/null+++ b/calendar/src/test/java/com/vayunmathur/calendar/ui/IcsImportTest.kt@@ -0,0 +1,107 @@+package com.vayunmathur.calendar.ui++import kotlinx.datetime.LocalDate+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertTrue++class IcsImportTest {++ /**+ * Properties are passed as separate lines rather than one indented block: a line starting with a+ * space is an RFC 5545 continuation, so an indented heredoc would fold the whole event into one+ * line.+ */+ private fun parse(vararg properties: String) = parseICSFile(+ (+ listOf("BEGIN:VCALENDAR", "VERSION:2.0", "BEGIN:VEVENT", "UID:test-1", "SUMMARY:Test") ++ properties ++ listOf("END:VEVENT", "END:VCALENDAR")+ ).joinToString("\r\n").byteInputStream()+ )++ @Test+ fun repeatDatesOnOneLineAreImported() {+ val events = parse(+ "DTSTART;VALUE=DATE:20250704",+ "DTEND;VALUE=DATE:20250705",+ "RDATE;VALUE=DATE:20250708,20250712",+ )+ assertEquals(1, events.size)+ assertEquals(listOf(LocalDate(2025, 7, 8), LocalDate(2025, 7, 12)), events[0].rdate)+ }++ @Test+ fun repeatDatesSpreadOverSeveralLinesAllSurvive() {+ // The property map is last-wins, so before RDATE accumulated these lines overwrote each+ // other and every date but the last was silently dropped.+ val events = parse(+ "DTSTART;VALUE=DATE:20250704",+ "DTEND;VALUE=DATE:20250705",+ "RDATE;VALUE=DATE:20250708",+ "RDATE;VALUE=DATE:20250712",+ "RDATE;VALUE=DATE:20250715",+ )+ assertEquals(+ listOf(LocalDate(2025, 7, 8), LocalDate(2025, 7, 12), LocalDate(2025, 7, 15)),+ events[0].rdate,+ )+ }++ @Test+ fun excludedDatesAreImported() {+ val events = parse(+ "DTSTART;VALUE=DATE:20250704",+ "DTEND;VALUE=DATE:20250705",+ "RRULE:FREQ=DAILY;INTERVAL=1",+ "EXDATE;VALUE=DATE:20250706",+ "EXDATE;VALUE=DATE:20250707",+ )+ assertEquals(listOf(LocalDate(2025, 7, 6), LocalDate(2025, 7, 7)), events[0].exdate)+ }++ @Test+ fun theStartDateIsNotRepeatedAsAnExtraDate() {+ // DTSTART is already an occurrence; keeping it in rdate too would double it up.+ val events = parse(+ "DTSTART;VALUE=DATE:20250704",+ "DTEND;VALUE=DATE:20250705",+ "RDATE;VALUE=DATE:20250704,20250708",+ )+ assertEquals(listOf(LocalDate(2025, 7, 8)), events[0].rdate)+ }++ @Test+ fun aLateEveningRepeatKeepsItsLocalDay() {+ // 22:00 New York is 02:00 the next day in UTC. Taking the day off the raw value would push+ // every occurrence forward by one.+ val events = parse(+ "DTSTART;TZID=America/New_York:20250704T220000",+ "DTEND;TZID=America/New_York:20250704T230000",+ "RDATE;TZID=America/New_York:20250708T220000",+ )+ assertEquals("America/New_York", events[0].timezone)+ assertEquals(listOf(LocalDate(2025, 7, 8)), events[0].rdate)+ }++ @Test+ fun aUtcRepeatIsResolvedInTheEventZone() {+ val events = parse(+ "DTSTART;TZID=America/New_York:20250704T220000",+ "DTEND;TZID=America/New_York:20250704T230000",+ "RDATE:20250709T020000Z",+ )+ assertEquals(listOf(LocalDate(2025, 7, 8)), events[0].rdate)+ }++ @Test+ fun anEventWithNoRepeatHasNoDates() {+ val events = parse(+ "DTSTART;VALUE=DATE:20250704",+ "DTEND;VALUE=DATE:20250705",+ )+ assertTrue(events[0].rdate.isEmpty())+ assertTrue(events[0].exdate.isEmpty())+ assertTrue(!events[0].isRecurring)+ }+}
calendar/src/test/java/com/vayunmathur/calendar/util/DateFormatsTest.kt
diff --git a/calendar/src/test/java/com/vayunmathur/calendar/util/DateFormatsTest.kt b/calendar/src/test/java/com/vayunmathur/calendar/util/DateFormatsTest.ktindex dec4c7cdc5..497fd1f6a9 100644--- a/calendar/src/test/java/com/vayunmathur/calendar/util/DateFormatsTest.kt+++ b/calendar/src/test/java/com/vayunmathur/calendar/util/DateFormatsTest.kt@@ -32,30 +32,52 @@ class DateFormatsTest { @Test fun writtenOccurrencesParseBackToTheirLocalDate() { // The provider round-trip the RDATE column relies on: what toIcalUtcDateTime writes has to- // come back out of parseIcalBasicDate as the same calendar day it was written for.- val date = LocalDate(2025, 7, 4)- val written = date.toIcalUtcDateTime(LocalTime(9, 0), TimeZone.of("America/New_York"))- assertEquals(date, parseIcalBasicDate(written))- assertEquals(date, parseIcalBasicDate(date.toIcalBasic()))+ // come back out as the same calendar day it was written for, including when the UTC value+ // lands on the following day.+ val zone = TimeZone.of("America/New_York")+ for (time in listOf(LocalTime(9, 0), LocalTime(22, 0), LocalTime(23, 59))) {+ val date = LocalDate(2025, 7, 4)+ val written = date.toIcalUtcDateTime(time, zone)+ assertEquals(date, parseIcalOccurrenceDate(written, zone), "round trip at $time")+ }+ val allDay = LocalDate(2025, 7, 4)+ assertEquals(allDay, parseIcalOccurrenceDate(allDay.toIcalBasic(), TimeZone.UTC))+ }++ @Test+ fun readingAUtcOccurrenceInTheWrongZoneWouldMoveIt() {+ // Guards the reason parseIcalOccurrenceDate takes a zone at all: the same value is July 4 in+ // New York and July 5 in UTC.+ val written = LocalDate(2025, 7, 4).toIcalUtcDateTime(LocalTime(22, 0), TimeZone.of("America/New_York"))+ assertEquals(LocalDate(2025, 7, 4), parseIcalOccurrenceDate(written, TimeZone.of("America/New_York")))+ assertEquals(LocalDate(2025, 7, 5), parseIcalOccurrenceDate(written, TimeZone.UTC))+ }++ @Test+ fun aFloatingDateTimeFallsBackToItsLeadingDate() {+ // No 'Z' and no offset, so there is nothing to resolve against.+ assertEquals(LocalDate(2025, 7, 4), parseIcalOccurrenceDate("20250704T090000", TimeZone.UTC)) } @Test fun occurrencesWrittenByOtherClientsStillParse() { // Google Calendar and friends prefix RDATE values with parameters; Event.getAllEvents strips // everything up to the last colon before handing the value over.+ val zone = TimeZone.of("America/New_York") assertEquals( LocalDate(2025, 7, 4),- parseIcalBasicDate("TZID=America/New_York:20250704T090000".substringAfterLast(':')),+ parseIcalOccurrenceDate("TZID=America/New_York:20250704T090000".substringAfterLast(':'), zone), ) assertEquals( LocalDate(2025, 7, 4),- parseIcalBasicDate("VALUE=DATE:20250704".substringAfterLast(':')),+ parseIcalOccurrenceDate("VALUE=DATE:20250704".substringAfterLast(':'), zone), ) } @Test fun garbageIsNotADate() {+ assertNull(parseIcalOccurrenceDate("", TimeZone.UTC))+ assertNull(parseIcalOccurrenceDate("not-a-date", TimeZone.UTC)) assertNull(parseIcalBasicDate(""))- assertNull(parseIcalBasicDate("not-a-date")) } }