Move a series on when its first occurrence is ticked off (#137)

Agendula's own store kept the series open and wrote a completed RECURRENCE-ID
override, which Infomaniak and Apple Reminders show as still open. The series
now advances to its next occurrence and a completed copy is kept; reopening
that occurrence moves it back.
This commit is contained in:
makiolaj committed 2026-11-06 17:52:15 +01:00
1 parent 7bcac70cec
commit 9e5e98ccee
4 files changed
+244 -19

No files matched your search

@@ -28,6 +28,11 @@ private val WINDOW_FORWARD = 730.days
/** Residue lines that describe the old series and must not follow the new one. */
private val SERIES_LINES = listOf("EXDATE", "RDATE", "RRULE", "RECURRENCE-ID", "UID")
private const val OCCURRENCE_MARK = "X-AGENDULA-OCCURRENCE-OF:"
/** How far ahead to look for a series' next occurrence: past any yearly gap, with room to spare. */
private val SERIES_LOOKAHEAD = (366 * 10).days
/** Enough to count every occurrence before a split point without bounding a real series. */
internal const val SPLIT_COUNT_CEILING = 100_000
@@ -479,18 +484,138 @@ class RoomTasksDataSource @Inject constructor(
}
/**
* Ticking one occurrence forks a `RECURRENCE-ID` override carrying the
* completion — the same model [updateInstance] writes. Writing the status onto
* the master instead would close the series: the master is what
* [TaskDao.tasks] filters on, so every occurrence, past and future, would
* leave every list at once.
* Ticking a series' first open occurrence moves the series on to its next
* one and keeps a completed copy, as tasks.org and Apple Reminders do — a
* completed `RECURRENCE-ID` override alone leaves the series showing as open
* in most other clients (#137). Unticking that copy's occurrence moves the
* series back. Any other occurrence forks an override carrying the completion,
* the same model [updateInstance] writes. Writing the status onto the master
* instead would close the series.
*/
override fun setCompletedInstance(taskId: Long, occurrenceStart: Instant, completed: Boolean) =
writeInstance(taskId, occurrenceStart, "complete") { TaskFormWriter.completed(it, completed, clock.now()) }
override fun setCompletedInstance(taskId: Long, occurrenceStart: Instant, completed: Boolean) = tx {
val close = { it: TaskEntity -> TaskFormWriter.completed(it, completed, clock.now()) }
if (!moveSeries(taskId, occurrenceStart, closing = completed, close)) {
writeInstance(taskId, occurrenceStart, "complete", close)
}
}
/** Same override model as [setCompletedInstance]. */
override fun setCancelledInstance(taskId: Long, occurrenceStart: Instant, cancelled: Boolean) =
writeInstance(taskId, occurrenceStart, "cancel") { TaskFormWriter.cancelled(it, cancelled, clock.now()) }
/** Same model as [setCompletedInstance]. */
override fun setCancelledInstance(taskId: Long, occurrenceStart: Instant, cancelled: Boolean) = tx {
val close = { it: TaskEntity -> TaskFormWriter.cancelled(it, cancelled, clock.now()) }
if (!moveSeries(taskId, occurrenceStart, closing = cancelled, close)) {
writeInstance(taskId, occurrenceStart, "cancel", close)
}
}
/**
* Moves the series behind [taskId] past [occurrenceStart] when [closing] its
* first occurrence, or back onto it when reopening the one it last moved past.
* False when neither applies, so the caller writes an override instead.
*/
private fun moveSeries(taskId: Long, occurrenceStart: Instant, closing: Boolean, close: (TaskEntity) -> TaskEntity): Boolean {
val row = tasks.entity(taskId) ?: return false
val master = row.masterId?.let { tasks.entity(it) } ?: row
if (master.recurrenceSpec() == null) return false
val override = if (row.masterId != null) row else tasks.override(master.id, occurrenceStart)
val anchor = override?.recurrenceId ?: occurrenceStart
val closed = master.status == TaskStatus.COMPLETED || master.status == TaskStatus.CANCELLED
if (closed) {
// Only its last occurrence closes a series; reopening that one reopens it.
if (closing || master.recurrenceAnchor?.let { sameSecond(it, anchor) } != true) return false
tasks.update(close(master))
override?.let { tasks.update(close(it)) }
writes.onWritten(setOf(master.listId))
return true
}
return if (closing) advance(master, anchor, override, close) else rewind(master, anchor)
}
private fun advance(master: TaskEntity, anchor: Instant, override: TaskEntity?, close: (TaskEntity) -> TaskEntity): Boolean {
val (first, next) = firstTwo(master) ?: return false
if (!sameSecond(first, anchor)) return false
if (next == null) {
tasks.update(close(master))
override?.let { tasks.update(close(it)) }
writes.onWritten(setOf(master.listId))
return true
}
val now = clock.now()
val (start, due) = override?.let { it.dtstart to it.due } ?: occurrenceTimes(master, anchor)
val copy = close(
(override ?: master).copy(
id = 0,
uid = UUID.randomUUID().toString(),
masterId = null,
recurrenceId = null,
href = null,
etag = null,
rrule = null,
rdate = null,
exdate = null,
dtstart = start,
due = due,
createdAt = now,
sequence = 0,
isDeleted = false,
unknownProperties = (seriesFree(master.unknownProperties) + occurrenceMark(master, anchor)).joinToString("\r\n"),
),
)
val copyId = tasks.insert(copy)
alarms.copyToTask(override?.id ?: master.id, copyId, sameResource = false)
override?.let { tasks.delete(it.id) }
// Keeps the anchor's own sub-second part, which expansion drops.
tasks.update(shifted(master, master.recurrenceAnchor!! + (next - first), spent = 1, now))
writes.onWritten(setOf(master.listId))
return true
}
private fun rewind(master: TaskEntity, anchor: Instant): Boolean {
val anchorNow = master.recurrenceAnchor ?: return false
if (anchor >= anchorNow || sameSecond(anchor, anchorNow)) return false
val back = shifted(master, anchor, spent = -1, clock.now())
val (first, next) = firstTwo(back) ?: return false
if (!sameSecond(first, anchor) || next == null || !sameSecond(next, anchorNow)) return false
tasks.update(back)
val mark = occurrenceMark(master, anchor)
tasks.allIn(master.listId)
.filter { !it.isDeleted && it.unknownProperties?.lines()?.contains(mark) == true }
.forEach { deleteTask(it.id) }
writes.onWritten(setOf(master.listId))
return true
}
/** The series' first occurrence and the one after it (null when it has no other). */
private fun firstTwo(master: TaskEntity): Pair<Instant, Instant?>? {
val spec = master.recurrenceSpec() ?: return null
val from = Instant.fromEpochSeconds(spec.anchor.epochSeconds)
val occurrences = RecurrenceExpander.expand(spec, ExpansionWindow(from = from, until = from + SERIES_LOOKAHEAD, maxOccurrences = 2))
val first = occurrences.firstOrNull() ?: return null
return first to occurrences.getOrNull(1)
}
/** [master] anchored on [at], its `COUNT` reduced by [spent] and the exceptions before [at] dropped. */
private fun shifted(master: TaskEntity, at: Instant, spent: Int, now: Instant): TaskEntity {
val (start, due) = occurrenceTimes(master, at)
val zone = master.timezone ?: zone()
return master.copy(
dtstart = start,
due = due,
rrule = master.rrule?.let { TaskFormWriter.remainingCount(it, spent) },
exdate = if (spent > 0) TaskFormWriter.valuesFrom(master.exdate, at, zone) else master.exdate,
lastModified = now,
isDirty = true,
)
}
private fun seriesFree(unknown: String?): List<String> =
unknown?.lines()?.filterNot { line -> SERIES_LINES.any { line.startsWith(it, ignoreCase = true) } || line.startsWith(OCCURRENCE_MARK) }
?.filter { it.isNotBlank() }.orEmpty()
/** Expansion runs in whole seconds; stored anchors may carry milliseconds. */
private fun sameSecond(a: Instant, b: Instant) = a.epochSeconds == b.epochSeconds
/** Links a completed copy to the occurrence it was split off, so reopening it can move the series back. */
private fun occurrenceMark(master: TaskEntity, anchor: Instant) = "$OCCURRENCE_MARK${master.uid};${anchor.toEpochMilliseconds()}"
/** Applies [write] to the override for [occurrenceStart], forking one if there is none yet. */
private fun writeInstance(