diff --git a/Cargo.lock b/Cargo.lock index 55837b8..6db513a 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -207,11 +207,23 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "1aa79e62e7697b8e29b513a68abacf485adcd1fe8284a4316c5ae868e6633327" dependencies = [ "iana-time-zone", + "js-sys", "num-traits", "serde", + "wasm-bindgen", "windows-link", ] +[[package]] +name = "chrono-tz" +version = "0.10.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a6139a8597ed92cf816dfb33f5dd6cf0bb93a6adc938f11039f371bc5bcd26c3" +dependencies = [ + "chrono", + "phf", +] + [[package]] name = "clru" version = "0.6.3" @@ -2033,6 +2045,24 @@ version = "2.3.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "9b4f627cb1b25917193a259e49bdad08f671f8d9708acfd5fe0a8c1455d87220" +[[package]] +name = "phf" +version = "0.12.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "913273894cec178f401a31ec4b656318d95473527be05c0752cc41cdc32be8b7" +dependencies = [ + "phf_shared", +] + +[[package]] +name = "phf_shared" +version = "0.12.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "06005508882fb681fd97892ecff4b7fd0fee13ef1aa569f8695dae7ab9099981" +dependencies = [ + "siphasher", +] + [[package]] name = "pin-project-lite" version = "0.2.17" @@ -2112,6 +2142,15 @@ dependencies = [ "parking_lot", ] +[[package]] +name = "quick-xml" +version = "0.42.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "41b1177fdf999d2321d3fb46ff47159d9c1fb9ad66a4879f8c50a0b504615e9b" +dependencies = [ + "memchr", +] + [[package]] name = "quote" version = "1.0.47" @@ -2279,6 +2318,19 @@ dependencies = [ "windows-sys 0.52.0", ] +[[package]] +name = "rrule" +version = "0.14.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "720acfb4980b9d8a6a430f6d7a11933e701ebbeba5eee39cc9d8c5f932aaff74" +dependencies = [ + "chrono", + "chrono-tz", + "log", + "regex", + "thiserror", +] + [[package]] name = "rusqlite" version = "0.37.0" @@ -2553,6 +2605,12 @@ version = "2.7.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "bbbb5d9659141646ae647b42fe094daf6c6192d1620870b449d9557f748b2daa" +[[package]] +name = "siphasher" +version = "1.0.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "33f4fe9184a62d842c9ef383018f3306d8ba224fd9d836f56d7288308847c256" + [[package]] name = "sketches-ddsketch" version = "0.3.1" @@ -2645,6 +2703,27 @@ dependencies = [ "wiremock", ] +[[package]] +name = "synapse-caldav" +version = "0.1.0" +dependencies = [ + "chrono", + "chrono-tz", + "quick-xml", + "reqwest", + "rrule", + "rusqlite", + "rustls", + "serde", + "serde_json", + "synapse-core", + "tempfile", + "thiserror", + "tokio", + "uuid", + "webpki-roots", +] + [[package]] name = "synapse-core" version = "0.1.0" diff --git a/crates/synapse-caldav/Cargo.toml b/crates/synapse-caldav/Cargo.toml new file mode 100644 index 0000000..5180a8c --- /dev/null +++ b/crates/synapse-caldav/Cargo.toml @@ -0,0 +1,25 @@ +[package] +name = "synapse-caldav" +version = "0.1.0" +edition.workspace = true +license.workspace = true +description = "CalDAV events and VTODO tasks, two-way with Synapse blocks and journals" + +[dependencies] +synapse-core.workspace = true +chrono.workspace = true +serde.workspace = true +serde_json.workspace = true +thiserror.workspace = true +uuid.workspace = true +rusqlite.workspace = true +quick-xml = "0.42.0" +rrule = "0.14.0" +chrono-tz = "0.10.4" +reqwest = { version = "0.13.5", default-features = false, features = ["rustls-no-provider"] } +rustls = { version = "0.23.46", default-features = false, features = ["ring", "std", "tls12"] } +webpki-roots = "1.0.10" + +[dev-dependencies] +tempfile = "3.27.0" +tokio = { version = "1.54.0", features = ["rt-multi-thread", "macros", "net", "io-util", "sync", "time"] } diff --git a/crates/synapse-caldav/src/calendar.rs b/crates/synapse-caldav/src/calendar.rs new file mode 100644 index 0000000..25bf685 --- /dev/null +++ b/crates/synapse-caldav/src/calendar.rs @@ -0,0 +1,585 @@ +//! Typed views over iCalendar components: date-times, events, tasks and RRULE expansion. + +use crate::ical::{Component, Prop, escape}; +use crate::{Error, Result, ical}; +use chrono::{DateTime, Duration, NaiveDate, NaiveDateTime, NaiveTime, TimeZone, Utc}; +use chrono_tz::Tz; + +/// An iCalendar DATE / DATE-TIME value with its zone semantics preserved. +#[derive(Debug, Clone, PartialEq)] +pub enum DtValue { + Date(NaiveDate), + /// No zone: wall-clock time in the viewer's zone. + Floating(NaiveDateTime), + Utc(DateTime), + Zoned(Tz, NaiveDateTime), +} + +impl DtValue { + pub fn parse(p: &Prop) -> Option { + let v = p.value.trim(); + if p.param("VALUE") == Some("DATE") || (v.len() == 8 && !v.contains('T')) { + return NaiveDate::parse_from_str(v, "%Y%m%d") + .ok() + .map(DtValue::Date); + } + if let Some(z) = v.strip_suffix('Z') { + let n = NaiveDateTime::parse_from_str(z, "%Y%m%dT%H%M%S").ok()?; + return Some(DtValue::Utc(Utc.from_utc_datetime(&n))); + } + let n = NaiveDateTime::parse_from_str(v, "%Y%m%dT%H%M%S").ok()?; + match p.param("TZID").and_then(|t| t.parse::().ok()) { + Some(tz) => Some(DtValue::Zoned(tz, n)), + None => Some(DtValue::Floating(n)), + } + } + + pub fn to_prop(&self, name: &str) -> Prop { + match self { + DtValue::Date(d) => { + Prop::new(name, d.format("%Y%m%d").to_string()).with_param("VALUE", "DATE") + } + DtValue::Floating(n) => Prop::new(name, n.format("%Y%m%dT%H%M%S").to_string()), + DtValue::Utc(u) => Prop::new(name, u.format("%Y%m%dT%H%M%SZ").to_string()), + DtValue::Zoned(tz, n) => { + Prop::new(name, n.format("%Y%m%dT%H%M%S").to_string()).with_param("TZID", tz.name()) + } + } + } + + pub fn is_date(&self) -> bool { + matches!(self, DtValue::Date(_)) + } + + /// Wall-clock time in the viewer's zone `view` (all-day values become midnight). + pub fn local(&self, view: Tz) -> NaiveDateTime { + match self { + DtValue::Date(d) => d.and_time(NaiveTime::MIN), + DtValue::Floating(n) => *n, + DtValue::Utc(u) => u.with_timezone(&view).naive_local(), + DtValue::Zoned(tz, n) => match tz.from_local_datetime(n).earliest() { + Some(t) => t.with_timezone(&view).naive_local(), + None => *n, // non-existent local time (DST gap) + }, + } + } + + pub fn local_date(&self, view: Tz) -> NaiveDate { + match self { + DtValue::Date(d) => *d, + _ => self.local(view).date(), + } + } +} + +fn parse_duration(s: &str) -> Option { + let s = s.trim(); + let (neg, s) = match s.strip_prefix('-') { + Some(r) => (true, r), + None => (false, s.strip_prefix('+').unwrap_or(s)), + }; + let s = s.strip_prefix('P')?; + let (mut secs, mut num) = (0i64, String::new()); + let mut in_time = false; + for c in s.chars() { + match c { + 'T' => in_time = true, + '0'..='9' => num.push(c), + _ => { + let n: i64 = num.parse().ok()?; + num.clear(); + secs += n * match (c, in_time) { + ('W', _) => 604_800, + ('D', _) => 86_400, + ('H', true) => 3600, + ('M', true) => 60, + ('S', true) => 1, + _ => return None, + }; + } + } + } + Some(Duration::seconds(if neg { -secs } else { secs })) +} + +fn add(dt: &DtValue, d: Duration) -> DtValue { + match dt { + DtValue::Date(x) => DtValue::Date(*x + d), + DtValue::Floating(x) => DtValue::Floating(*x + d), + DtValue::Utc(x) => DtValue::Utc(*x + d), + DtValue::Zoned(tz, x) => DtValue::Zoned(*tz, *x + d), + } +} + +#[derive(Debug, Clone, PartialEq)] +pub struct Event { + pub uid: String, + pub summary: String, + pub description: Option, + pub location: Option, + pub start: DtValue, + pub end: Option, + pub status: Option, + pub recurrence_id: Option, + pub has_rrule: bool, +} + +impl Event { + pub fn from_component(c: &Component) -> Option { + let start = DtValue::parse(c.prop("DTSTART")?)?; + let end = match c.prop("DTEND").and_then(DtValue::parse) { + Some(e) => Some(e), + None => c + .prop("DURATION") + .and_then(|p| parse_duration(&p.value)) + .map(|d| add(&start, d)), + }; + Some(Event { + uid: c.text("UID")?, + summary: c.text("SUMMARY").unwrap_or_default(), + description: c.text("DESCRIPTION"), + location: c.text("LOCATION"), + start, + end, + status: c.text("STATUS"), + recurrence_id: c.prop("RECURRENCE-ID").and_then(DtValue::parse), + has_rrule: c.prop("RRULE").is_some(), + }) + } + + /// Length used for occurrences: DTEND-DTSTART, one day for dates, zero for instants. + pub fn duration(&self, view: Tz) -> Duration { + match &self.end { + Some(e) => e.local(view) - self.start.local(view), + None if self.start.is_date() => Duration::days(1), + None => Duration::zero(), + } + } +} + +/// One concrete instance of an event inside a requested window. +#[derive(Debug, Clone, PartialEq)] +pub struct Occurrence { + pub uid: String, + pub calendar: String, + pub href: String, + pub summary: String, + pub description: Option, + pub location: Option, + /// Wall-clock in the viewer's zone. + pub start: NaiveDateTime, + pub end: NaiveDateTime, + pub all_day: bool, + pub recurring: bool, +} + +/// Parses the VCALENDAR in `ics` and returns its top-level component list's inner components. +pub fn parse_calendar(ics: &str) -> Result { + ical::parse(ics)? + .into_iter() + .find(|c| c.name == "VCALENDAR") + .ok_or_else(|| Error::Ical("no VCALENDAR".into())) +} + +fn rrule_text(c: &Component, start: &DtValue) -> Option { + let rule = c.prop("RRULE")?; + // The recurrence engine wants DTSTART in text form; dates and floating times are treated + // as UTC wall-clock (windows are padded and re-filtered in the viewer's zone afterwards). + let dtstart = match start { + DtValue::Date(d) => format!("DTSTART:{}T000000Z", d.format("%Y%m%d")), + DtValue::Floating(n) => format!("DTSTART:{}Z", n.format("%Y%m%dT%H%M%S")), + DtValue::Utc(u) => format!("DTSTART:{}", u.format("%Y%m%dT%H%M%SZ")), + DtValue::Zoned(tz, n) => { + format!("DTSTART;TZID={}:{}", tz.name(), n.format("%Y%m%dT%H%M%S")) + } + }; + // For all-day events UNTIL is a DATE; the engine needs a date-time. + let rule_text: Vec = rule + .value + .split(';') + .map(|kv| match kv.strip_prefix("UNTIL=") { + Some(u) if start.is_date() && u.len() == 8 => format!("UNTIL={u}T235959Z"), + _ => kv.to_string(), + }) + .collect(); + let mut s = format!("{dtstart}\nRRULE:{}", rule_text.join(";")); + for ex in c.props_named("EXDATE") { + for v in ex.value.split(',') { + let dt = DtValue::parse(&Prop { + value: v.to_string(), + ..ex.clone() + })?; + let line = match dt { + DtValue::Date(d) => format!("EXDATE:{}T000000Z", d.format("%Y%m%d")), + DtValue::Floating(n) => format!("EXDATE:{}Z", n.format("%Y%m%dT%H%M%S")), + DtValue::Utc(u) => format!("EXDATE:{}", u.format("%Y%m%dT%H%M%SZ")), + DtValue::Zoned(tz, n) => { + format!("EXDATE;TZID={}:{}", tz.name(), n.format("%Y%m%dT%H%M%S")) + } + }; + s.push('\n'); + s.push_str(&line); + } + } + Some(s) +} + +/// Start values of a (possibly recurring) component that fall in `[from, to)` (viewer-zone +/// wall-clock). Non-recurring components yield their own start. +pub fn expand_starts( + c: &Component, + start: &DtValue, + view: Tz, + from: NaiveDateTime, + to: NaiveDateTime, +) -> Vec { + let Some(text) = rrule_text(c, start) else { + return vec![start.clone()]; + }; + let Ok(set) = text.parse::() else { + return vec![start.clone()]; + }; + let pad = Duration::days(2); + let utc = |n: NaiveDateTime| rrule::Tz::UTC.from_utc_datetime(&n); + let res = set.after(utc(from - pad)).before(utc(to + pad)).all(2000); + res.dates + .into_iter() + .map(|d| { + // Rebuild a DtValue of the same flavour as the master start. + match start { + DtValue::Date(_) => DtValue::Date(d.date_naive()), + DtValue::Floating(_) => DtValue::Floating(d.naive_utc()), + DtValue::Utc(_) => DtValue::Utc(d.with_timezone(&Utc)), + DtValue::Zoned(tz, _) => DtValue::Zoned(*tz, d.with_timezone(tz).naive_local()), + } + }) + .filter(|v| { + let s = v.local(view); + s < to && s >= from - Duration::days(366) + }) + .collect() +} + +/// Occurrences of all VEVENTs in one calendar object overlapping `[from, to)`. +pub fn event_occurrences( + cal: &Component, + calendar: &str, + href: &str, + view: Tz, + from: NaiveDateTime, + to: NaiveDateTime, +) -> Vec { + let comps: Vec<&Component> = cal.children_named("VEVENT").collect(); + let events: Vec<(&Component, Event)> = comps + .iter() + .filter_map(|c| Event::from_component(c).map(|e| (*c, e))) + .collect(); + // Overrides replace the generated instance with the same RECURRENCE-ID. + let overridden: Vec<(&str, NaiveDateTime)> = events + .iter() + .filter_map(|(_, e)| { + e.recurrence_id + .as_ref() + .map(|r| (e.uid.as_str(), r.local(view))) + }) + .collect(); + let mut out = Vec::new(); + for (c, e) in &events { + if e.status.as_deref() == Some("CANCELLED") { + continue; + } + let dur = e.duration(view); + let all_day = e.start.is_date(); + let starts = if e.recurrence_id.is_some() { + vec![e.start.clone()] + } else { + expand_starts(c, &e.start, view, from, to) + }; + for s in starts { + let sl = s.local(view); + if e.recurrence_id.is_none() && overridden.contains(&(e.uid.as_str(), sl)) { + continue; + } + let el = sl + dur; + // Overlap test; zero-length events count when their start is inside. + let overlaps = if dur.is_zero() { + sl >= from && sl < to + } else { + sl < to && el > from + }; + if overlaps { + out.push(Occurrence { + uid: e.uid.clone(), + calendar: calendar.to_string(), + href: href.to_string(), + summary: e.summary.clone(), + description: e.description.clone(), + location: e.location.clone(), + start: sl, + end: el, + all_day, + recurring: e.has_rrule || e.recurrence_id.is_some(), + }); + } + } + } + out.sort_by_key(|o| (o.start, o.summary.clone())); + out +} + +// ------------------------------------------------------------------------------- tasks + +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum TodoStatus { + NeedsAction, + InProcess, + Completed, + Cancelled, +} + +impl TodoStatus { + pub fn as_str(self) -> &'static str { + match self { + TodoStatus::NeedsAction => "NEEDS-ACTION", + TodoStatus::InProcess => "IN-PROCESS", + TodoStatus::Completed => "COMPLETED", + TodoStatus::Cancelled => "CANCELLED", + } + } + + pub fn parse(s: &str) -> TodoStatus { + match s.to_ascii_uppercase().as_str() { + "IN-PROCESS" => TodoStatus::InProcess, + "COMPLETED" => TodoStatus::Completed, + "CANCELLED" => TodoStatus::Cancelled, + _ => TodoStatus::NeedsAction, + } + } +} + +/// The task fields Synapse understands; everything else stays in the raw component. +#[derive(Debug, Clone, PartialEq)] +pub struct Todo { + pub uid: String, + pub summary: String, + pub description: Option, + pub status: TodoStatus, + pub percent: Option, + /// iCalendar PRIORITY: 0 = none, 1 = highest … 9 = lowest. + pub priority: u8, + pub start: Option, + pub due: Option, + pub completed: Option>, + pub last_modified: Option>, + pub has_rrule: bool, +} + +fn utc_prop(c: &Component, name: &str) -> Option> { + match DtValue::parse(c.prop(name)?)? { + DtValue::Utc(u) => Some(u), + DtValue::Floating(n) | DtValue::Zoned(_, n) => Some(Utc.from_utc_datetime(&n)), + DtValue::Date(d) => Some(Utc.from_utc_datetime(&d.and_time(NaiveTime::MIN))), + } +} + +impl Todo { + pub fn from_component(c: &Component) -> Option { + Some(Todo { + uid: c.text("UID")?, + summary: c.text("SUMMARY").unwrap_or_default(), + description: c.text("DESCRIPTION").filter(|s| !s.trim().is_empty()), + status: c + .text("STATUS") + .map(|s| TodoStatus::parse(&s)) + .unwrap_or(TodoStatus::NeedsAction), + percent: c + .text("PERCENT-COMPLETE") + .and_then(|s| s.trim().parse().ok()), + priority: c + .text("PRIORITY") + .and_then(|s| s.trim().parse().ok()) + .unwrap_or(0), + start: c.prop("DTSTART").and_then(DtValue::parse), + due: c.prop("DUE").and_then(DtValue::parse), + completed: utc_prop(c, "COMPLETED"), + last_modified: utc_prop(c, "LAST-MODIFIED").or_else(|| utc_prop(c, "DTSTAMP")), + has_rrule: c.prop("RRULE").is_some(), + }) + } + + /// Writes this task's fields onto `c`, keeping unknown properties, and stamps + /// LAST-MODIFIED/DTSTAMP with `now`. + pub fn apply_to(&self, c: &mut Component, now: DateTime) { + c.set(Prop::new("UID", &self.uid)); + c.set(Prop::new("SUMMARY", escape(&self.summary))); + match &self.description { + Some(d) => c.set(Prop::new("DESCRIPTION", escape(d))), + None => c.remove("DESCRIPTION"), + } + c.set(Prop::new("STATUS", self.status.as_str())); + match (self.status, self.percent) { + (TodoStatus::Completed, _) => c.set(Prop::new("PERCENT-COMPLETE", "100")), + (_, Some(p)) if p < 100 => c.set(Prop::new("PERCENT-COMPLETE", p.to_string())), + _ => c.remove("PERCENT-COMPLETE"), + } + if self.priority == 0 { + c.remove("PRIORITY"); + } else { + c.set(Prop::new("PRIORITY", self.priority.to_string())); + } + match &self.start { + Some(s) => c.set(s.to_prop("DTSTART")), + None => c.remove("DTSTART"), + } + match &self.due { + Some(d) => c.set(d.to_prop("DUE")), + None => c.remove("DUE"), + } + match self.completed { + Some(t) if self.status == TodoStatus::Completed => { + c.set(DtValue::Utc(t).to_prop("COMPLETED")) + } + _ => c.remove("COMPLETED"), + } + let stamp = DtValue::Utc(now); + c.set(stamp.to_prop("LAST-MODIFIED")); + c.set(stamp.to_prop("DTSTAMP")); + } + + /// A fresh VCALENDAR wrapping one VTODO. + pub fn to_calendar(&self, now: DateTime) -> Component { + let mut cal = Component::new("VCALENDAR"); + cal.props.push(Prop::new("VERSION", "2.0")); + cal.props + .push(Prop::new("PRODID", "-//Synapse//CalDAV//EN")); + let mut t = Component::new("VTODO"); + self.apply_to(&mut t, now); + cal.children.push(t); + cal + } +} + +/// First VTODO of a calendar object that is not a recurrence override. +pub fn master_todo(cal: &Component) -> Option<&Component> { + cal.children_named("VTODO") + .find(|c| c.prop("RECURRENCE-ID").is_none()) + .or_else(|| cal.children_named("VTODO").next()) +} + +pub fn master_todo_mut(cal: &mut Component) -> Option<&mut Component> { + let idx = cal + .children + .iter() + .position(|c| c.name == "VTODO" && c.prop("RECURRENCE-ID").is_none()) + .or_else(|| cal.children.iter().position(|c| c.name == "VTODO"))?; + Some(&mut cal.children[idx]) +} + +/// Due/start instances of a recurring task inside `[from, to)`. +pub fn todo_occurrences( + c: &Component, + view: Tz, + from: NaiveDateTime, + to: NaiveDateTime, +) -> Vec { + let Some(anchor) = c + .prop("DTSTART") + .or_else(|| c.prop("DUE")) + .and_then(DtValue::parse) + else { + return Vec::new(); + }; + expand_starts(c, &anchor, view, from, to) +} + +pub fn calendar_kinds(cal: &Component) -> (bool, bool) { + ( + cal.children.iter().any(|c| c.name == "VEVENT"), + cal.children.iter().any(|c| c.name == "VTODO"), + ) +} + +#[cfg(test)] +mod tests { + use super::*; + + fn d(y: i32, m: u32, day: u32) -> NaiveDate { + NaiveDate::from_ymd_opt(y, m, day).unwrap() + } + + #[test] + fn weekly_zoned_with_exdate_and_override() { + let ics = "BEGIN:VCALENDAR\r\nBEGIN:VEVENT\r\nUID:s1\r\nSUMMARY:Standup\r\nDTSTART;TZID=Europe/Madrid:20261007T100000\r\nDTEND;TZID=Europe/Madrid:20261007T103000\r\nRRULE:FREQ=WEEKLY;BYDAY=WE\r\nEXDATE;TZID=Europe/Madrid:20261014T100000\r\nEND:VEVENT\r\nBEGIN:VEVENT\r\nUID:s1\r\nSUMMARY:Standup (moved)\r\nRECURRENCE-ID;TZID=Europe/Madrid:20261028T100000\r\nDTSTART;TZID=Europe/Madrid:20261028T150000\r\nDTEND;TZID=Europe/Madrid:20261028T153000\r\nEND:VEVENT\r\nEND:VCALENDAR\r\n"; + let cal = parse_calendar(ics).unwrap(); + let tz = chrono_tz::Europe::Madrid; + let win = |a: NaiveDate, b: NaiveDate| { + event_occurrences( + &cal, + "c", + "h", + tz, + a.and_time(NaiveTime::MIN), + b.and_time(NaiveTime::MIN), + ) + }; + assert_eq!(win(d(2026, 10, 14), d(2026, 10, 15)).len(), 0, "exdate"); + let o = win(d(2026, 10, 21), d(2026, 10, 22)); + assert_eq!(o.len(), 1); + assert_eq!( + o[0].start.time(), + NaiveTime::from_hms_opt(10, 0, 0).unwrap() + ); + assert!(o[0].recurring); + // Override moved the 28th to 15:00 and replaced the generated instance. + let o = win(d(2026, 10, 28), d(2026, 10, 29)); + assert_eq!(o.len(), 1); + assert_eq!(o[0].summary, "Standup (moved)"); + // Same wall-clock across the DST change (Oct 25 2026): Nov 4 is still 10:00. + let o = win(d(2026, 11, 4), d(2026, 11, 5)); + assert_eq!( + o[0].start.time(), + NaiveTime::from_hms_opt(10, 0, 0).unwrap() + ); + } + + #[test] + fn utc_event_shown_in_viewer_zone_and_all_day_daily_count() { + let ics = "BEGIN:VCALENDAR\r\nBEGIN:VEVENT\r\nUID:u\r\nSUMMARY:Call\r\nDTSTART:20261021T230000Z\r\nDURATION:PT1H\r\nEND:VEVENT\r\nBEGIN:VEVENT\r\nUID:a\r\nSUMMARY:Holiday\r\nDTSTART;VALUE=DATE:20261021\r\nRRULE:FREQ=DAILY;COUNT=3;UNTIL=20261110\r\nEND:VEVENT\r\nEND:VCALENDAR\r\n"; + let cal = parse_calendar(ics).unwrap(); + let tz = chrono_tz::Europe::Madrid; + let day = |n: NaiveDate| { + event_occurrences( + &cal, + "c", + "h", + tz, + n.and_time(NaiveTime::MIN), + (n + Duration::days(1)).and_time(NaiveTime::MIN), + ) + }; + // 23:00Z is 01:00 on the 22nd in Madrid (CEST, UTC+2). + assert!(day(d(2026, 10, 21)).iter().all(|o| o.summary != "Call")); + let o = day(d(2026, 10, 22)); + assert!( + o.iter() + .any(|o| o.summary == "Call" && o.end - o.start == Duration::hours(1)) + ); + assert!(o.iter().any(|o| o.summary == "Holiday" && o.all_day)); + assert!(day(d(2026, 10, 24)).is_empty()); + } + + #[test] + fn todo_roundtrip_preserves_unknown() { + let ics = "BEGIN:VCALENDAR\r\nBEGIN:VTODO\r\nUID:t\r\nSUMMARY:Pay\r\nX-APPLE-SORT-ORDER:5\r\nPRIORITY:1\r\nDUE;VALUE=DATE:20261025\r\nEND:VTODO\r\nEND:VCALENDAR\r\n"; + let mut cal = parse_calendar(ics).unwrap(); + let mut t = Todo::from_component(master_todo(&cal).unwrap()).unwrap(); + assert_eq!(t.priority, 1); + t.status = TodoStatus::Completed; + t.completed = Some(Utc.with_ymd_and_hms(2026, 10, 21, 8, 0, 0).unwrap()); + t.apply_to(master_todo_mut(&mut cal).unwrap(), Utc::now()); + let out = ical::serialize(&cal); + assert!(out.contains("X-APPLE-SORT-ORDER:5")); + assert!(out.contains("STATUS:COMPLETED") && out.contains("PERCENT-COMPLETE:100")); + assert!(out.contains("COMPLETED:20261021T080000Z")); + } +} diff --git a/crates/synapse-caldav/src/dav.rs b/crates/synapse-caldav/src/dav.rs new file mode 100644 index 0000000..e9b10ca --- /dev/null +++ b/crates/synapse-caldav/src/dav.rs @@ -0,0 +1,410 @@ +//! Async CalDAV client (RFC 4791 / RFC 6578). Credentials are supplied by the caller and held +//! only in memory. + +use crate::xml::{Multistatus, esc, parse_multistatus}; +use crate::{Error, Result}; +use reqwest::header::{ + CONTENT_TYPE, ETAG, HeaderMap, HeaderValue, IF_MATCH, IF_NONE_MATCH, LOCATION, +}; +use reqwest::{Method, StatusCode, Url}; +use std::sync::Arc; + +#[derive(Clone)] +pub struct Credentials { + pub username: String, + /// Account password or (preferably) an app password. + pub password: String, +} + +impl std::fmt::Debug for Credentials { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.debug_struct("Credentials") + .field("username", &self.username) + .finish_non_exhaustive() + } +} + +#[derive(Debug, Clone, PartialEq)] +pub struct CalendarInfo { + /// Server-relative path, as returned by the server (identity of the collection). + pub href: String, + pub name: String, + pub supports_events: bool, + pub supports_tasks: bool, + pub ctag: Option, + pub sync_token: Option, +} + +#[derive(Debug, Clone, PartialEq)] +pub struct RemoteObject { + pub href: String, + pub etag: String, + pub ics: String, +} + +#[derive(Debug, Default)] +pub struct SyncChanges { + /// (href, etag) of created/modified members. + pub changed: Vec<(String, String)>, + pub deleted: Vec, + pub new_token: Option, +} + +pub struct DavClient { + http: reqwest::Client, + base: Url, + creds: Credentials, +} + +const NS: &str = r#"xmlns:d="DAV:" xmlns:c="urn:ietf:params:xml:ns:caldav" xmlns:cs="http://calendarserver.org/ns/""#; + +fn tls_client() -> Result { + let mut roots = rustls::RootCertStore::empty(); + roots.extend(webpki_roots::TLS_SERVER_ROOTS.iter().cloned()); + let cfg = rustls::ClientConfig::builder_with_provider(Arc::new( + rustls::crypto::ring::default_provider(), + )) + .with_safe_default_protocol_versions() + .map_err(|e| Error::Tls(e.to_string()))? + .with_root_certificates(roots) + .with_no_client_auth(); + Ok(reqwest::Client::builder() + .use_preconfigured_tls(cfg) + .redirect(reqwest::redirect::Policy::none()) + .user_agent("synapse-caldav") + .build()?) +} + +fn strip_quotes_etag(h: &HeaderMap) -> Option { + h.get(ETAG) + .and_then(|v| v.to_str().ok()) + .map(str::to_string) +} + +impl DavClient { + /// `base` is the server root (`https://cloud.example.com`) or any DAV URL below it. + pub fn new(base: &str, creds: Credentials) -> Result { + Ok(DavClient { + http: tls_client()?, + base: Url::parse(base).map_err(|e| Error::Discovery(format!("bad url: {e}")))?, + creds, + }) + } + + fn url(&self, href: &str) -> Result { + self.base + .join(href) + .map_err(|e| Error::Other(format!("bad href {href}: {e}"))) + } + + /// Sends a request, following redirects manually so the method and body are preserved + /// (credentials only ever go to the original host). + async fn send( + &self, + method: &str, + url: Url, + headers: &[(&'static str, String)], + body: Option, + ) -> Result<(StatusCode, HeaderMap, String)> { + let m = Method::from_bytes(method.as_bytes()).map_err(|e| Error::Other(e.to_string()))?; + let mut url = url; + for _ in 0..6 { + let mut rb = self.http.request(m.clone(), url.clone()); + if url.host_str() == self.base.host_str() + && url.port_or_known_default() == self.base.port_or_known_default() + { + rb = rb.basic_auth(&self.creds.username, Some(&self.creds.password)); + } + for (k, v) in headers { + rb = rb.header( + *k, + HeaderValue::from_str(v).map_err(|e| Error::Other(e.to_string()))?, + ); + } + if let Some(b) = &body { + rb = rb.body(b.clone()); + } + let resp = rb.send().await?; + let status = resp.status(); + if status.is_redirection() + && let Some(loc) = resp.headers().get(LOCATION).and_then(|v| v.to_str().ok()) + { + url = url.join(loc).map_err(|e| Error::Other(e.to_string()))?; + continue; + } + let h = resp.headers().clone(); + let text = resp.text().await?; + return Ok((status, h, text)); + } + Err(Error::Other("too many redirects".into())) + } + + async fn xml( + &self, + method: &str, + href: &str, + depth: Option<&str>, + body: String, + ) -> Result<(StatusCode, Multistatus)> { + let mut hs = vec![( + CONTENT_TYPE.as_str(), + "application/xml; charset=utf-8".to_string(), + )]; + if let Some(d) = depth { + hs.push(("depth", d.to_string())); + } + let url = self.url(href)?; + let (st, _, text) = self.send(method, url, &hs, Some(body)).await?; + if st.as_u16() == 207 { + Ok((st, parse_multistatus(&text)?)) + } else { + Ok((st, Multistatus::default())) + } + } + + fn check(st: StatusCode, what: &str) -> Result<()> { + if st.as_u16() == 207 || st.is_success() { + Ok(()) + } else { + Err(Error::Status { + status: st.as_u16(), + what: what.to_string(), + }) + } + } + + // ------------------------------------------------------------------ discovery + + /// Resolves the calendar-home-set path: `.well-known/caldav`, current-user-principal, + /// calendar-home-set. + pub async fn discover(&self) -> Result { + let principal_body = format!( + r#""# + ); + let mut candidates = vec!["/.well-known/caldav".to_string()]; + let base_path = self.base.path().to_string(); + if base_path != "/" && !base_path.is_empty() { + candidates.push(base_path); + } + candidates.push("/".to_string()); + let mut principal = None; + let mut last = String::from("no candidate answered"); + for c in &candidates { + let (st, ms) = self + .xml("PROPFIND", c, Some("0"), principal_body.clone()) + .await?; + if st.as_u16() != 207 { + last = format!("{c}: HTTP {st}"); + continue; + } + if let Some(h) = ms + .responses + .iter() + .find_map(|r| r.text(&["current-user-principal", "href"])) + { + principal = Some(h.to_string()); + break; + } + last = format!("{c}: no current-user-principal"); + } + let principal = principal.ok_or(Error::Discovery(last))?; + let home_body = format!( + r#""# + ); + let (st, ms) = self + .xml("PROPFIND", &principal, Some("0"), home_body) + .await?; + Self::check(st, "calendar-home-set")?; + ms.responses + .iter() + .find_map(|r| r.text(&["calendar-home-set", "href"])) + .map(str::to_string) + .ok_or_else(|| Error::Discovery("no calendar-home-set".into())) + } + + /// Calendar collections below `home` that hold events and/or tasks. + pub async fn list_calendars(&self, home: &str) -> Result> { + let body = format!( + r#""# + ); + let (st, ms) = self.xml("PROPFIND", home, Some("1"), body).await?; + Self::check(st, "list calendars")?; + let mut out = Vec::new(); + for r in ms.responses { + if !r.has(&["resourcetype", "calendar"]) { + continue; + } + let (ev, td) = ( + r.has(&["supported-calendar-component-set", "comp:VEVENT"]), + r.has(&["supported-calendar-component-set", "comp:VTODO"]), + ); + // Servers omitting the set support everything. + let none = !r.has(&["supported-calendar-component-set"]); + let name = r + .text(&["displayname"]) + .map(str::to_string) + .unwrap_or_else(|| { + r.href + .trim_end_matches('/') + .rsplit('/') + .next() + .unwrap_or("") + .to_string() + }); + out.push(CalendarInfo { + name, + supports_events: ev || none, + supports_tasks: td || none, + ctag: r.text(&["getctag"]).map(str::to_string), + sync_token: r.text(&["sync-token"]).map(str::to_string), + href: r.href, + }); + } + Ok(out) + } + + // ----------------------------------------------------------------------- sync + + /// RFC 6578 incremental sync. Returns `Ok(None)` when the server does not support it or + /// rejected the token; callers then fall back to [`DavClient::list_etags`]. + pub async fn sync_collection( + &self, + cal: &str, + token: Option<&str>, + ) -> Result> { + let body = format!( + r#"{}1"#, + esc(token.unwrap_or("")) + ); + let (st, ms) = self.xml("REPORT", cal, None, body).await?; + if matches!(st.as_u16(), 403 | 405 | 409 | 410 | 412 | 415 | 501) { + return Ok(None); + } + Self::check(st, "sync-collection")?; + let Some(new_token) = ms.sync_token else { + return Ok(None); + }; + let mut ch = SyncChanges { + new_token: Some(new_token), + ..Default::default() + }; + for r in ms.responses { + if r.is_removed() { + ch.deleted.push(r.href); + } else if let Some(e) = r.text(&["getetag"]) { + ch.changed.push((r.href.clone(), e.to_string())); + } + } + Ok(Some(ch)) + } + + /// All members of a collection with their etags (fallback when no sync-collection). + pub async fn list_etags(&self, cal: &str) -> Result> { + let body = format!( + r#""# + ); + let (st, ms) = self.xml("PROPFIND", cal, Some("1"), body).await?; + Self::check(st, "list etags")?; + let me = cal.trim_end_matches('/'); + Ok(ms + .responses + .into_iter() + .filter(|r| r.href.trim_end_matches('/') != me) + .filter_map(|r| { + r.text(&["getetag"]) + .map(|e| (r.href.clone(), e.to_string())) + }) + .collect()) + } + + /// Current ctag of a collection. + pub async fn ctag(&self, cal: &str) -> Result> { + let body = format!( + r#""# + ); + let (st, ms) = self.xml("PROPFIND", cal, Some("0"), body).await?; + Self::check(st, "ctag")?; + Ok(ms + .responses + .iter() + .find_map(|r| r.text(&["getctag"]).map(str::to_string))) + } + + pub async fn multiget(&self, cal: &str, hrefs: &[String]) -> Result> { + let mut out = Vec::new(); + for chunk in hrefs.chunks(50) { + let items: String = chunk + .iter() + .map(|h| format!("{}", esc(h))) + .collect(); + let body = format!( + r#"{items}"# + ); + let (st, ms) = self.xml("REPORT", cal, Some("1"), body).await?; + Self::check(st, "calendar-multiget")?; + for r in ms.responses { + if let (Some(e), Some(d)) = (r.text(&["getetag"]), r.text(&["calendar-data"])) { + out.push(RemoteObject { + href: r.href.clone(), + etag: e.to_string(), + ics: d.to_string(), + }); + } + } + } + Ok(out) + } + + // ------------------------------------------------------------------ resources + + pub async fn get(&self, href: &str) -> Result { + let (st, h, text) = self.send("GET", self.url(href)?, &[], None).await?; + Self::check(st, &format!("GET {href}"))?; + Ok(RemoteObject { + href: href.to_string(), + etag: strip_quotes_etag(&h).unwrap_or_default(), + ics: text, + }) + } + + /// Creates (`if_match = None`, only if absent) or replaces (`Some(etag)`) an object. + /// Returns the new etag. A 412 becomes [`Error::PreconditionFailed`]. + pub async fn put(&self, href: &str, ics: &str, if_match: Option<&str>) -> Result { + let hs = vec![ + ( + CONTENT_TYPE.as_str(), + "text/calendar; charset=utf-8".to_string(), + ), + match if_match { + Some(e) => (IF_MATCH.as_str(), e.to_string()), + None => (IF_NONE_MATCH.as_str(), "*".to_string()), + }, + ]; + let (st, h, _) = self + .send("PUT", self.url(href)?, &hs, Some(ics.to_string())) + .await?; + if st == StatusCode::PRECONDITION_FAILED { + return Err(Error::PreconditionFailed(href.to_string())); + } + Self::check(st, &format!("PUT {href}"))?; + match strip_quotes_etag(&h) { + Some(e) => Ok(e), + // Some servers rewrite the object on PUT and omit the etag. + None => Ok(self.get(href).await?.etag), + } + } + + pub async fn delete(&self, href: &str, if_match: Option<&str>) -> Result<()> { + let hs: Vec<(&'static str, String)> = if_match + .map(|e| vec![(IF_MATCH.as_str(), e.to_string())]) + .unwrap_or_default(); + let (st, _, _) = self.send("DELETE", self.url(href)?, &hs, None).await?; + if st == StatusCode::PRECONDITION_FAILED { + return Err(Error::PreconditionFailed(href.to_string())); + } + if st == StatusCode::NOT_FOUND { + return Ok(()); + } + Self::check(st, &format!("DELETE {href}")) + } +} diff --git a/crates/synapse-caldav/src/error.rs b/crates/synapse-caldav/src/error.rs new file mode 100644 index 0000000..ae7d4f4 --- /dev/null +++ b/crates/synapse-caldav/src/error.rs @@ -0,0 +1,27 @@ +use thiserror::Error; + +#[derive(Debug, Error)] +pub enum Error { + #[error("core: {0}")] + Core(#[from] synapse_core::Error), + #[error("sqlite: {0}")] + Sqlite(#[from] rusqlite::Error), + #[error("http: {0}")] + Http(#[from] reqwest::Error), + #[error("server answered {status} for {what}")] + Status { status: u16, what: String }, + #[error("etag mismatch for {0}")] + PreconditionFailed(String), + #[error("xml: {0}")] + Xml(String), + #[error("icalendar: {0}")] + Ical(String), + #[error("discovery failed: {0}")] + Discovery(String), + #[error("tls: {0}")] + Tls(String), + #[error("{0}")] + Other(String), +} + +pub type Result = std::result::Result; diff --git a/crates/synapse-caldav/src/ical.rs b/crates/synapse-caldav/src/ical.rs new file mode 100644 index 0000000..f79399f --- /dev/null +++ b/crates/synapse-caldav/src/ical.rs @@ -0,0 +1,288 @@ +//! Minimal RFC 5545 content-line parser/serialiser. +//! +//! Components keep every property (including unknown `X-` ones) in order, so a VTODO fetched +//! from a server can be edited and written back without losing data we do not understand. + +use crate::{Error, Result}; + +#[derive(Debug, Clone, PartialEq, Default)] +pub struct Prop { + pub name: String, + pub params: Vec<(String, String)>, + /// Raw (still escaped) value. + pub value: String, +} + +impl Prop { + pub fn new(name: &str, value: impl Into) -> Self { + Prop { + name: name.to_ascii_uppercase(), + params: Vec::new(), + value: value.into(), + } + } + + pub fn with_param(mut self, k: &str, v: &str) -> Self { + self.params.push((k.to_ascii_uppercase(), v.to_string())); + self + } + + pub fn param(&self, k: &str) -> Option<&str> { + self.params + .iter() + .find(|(n, _)| n.eq_ignore_ascii_case(k)) + .map(|(_, v)| v.as_str()) + } + + /// Value with TEXT escapes resolved. + pub fn text(&self) -> String { + unescape(&self.value) + } +} + +#[derive(Debug, Clone, PartialEq, Default)] +pub struct Component { + pub name: String, + pub props: Vec, + pub children: Vec, +} + +impl Component { + pub fn new(name: &str) -> Self { + Component { + name: name.to_ascii_uppercase(), + ..Default::default() + } + } + + pub fn prop(&self, name: &str) -> Option<&Prop> { + self.props + .iter() + .find(|p| p.name.eq_ignore_ascii_case(name)) + } + + pub fn props_named<'a>(&'a self, name: &'a str) -> impl Iterator { + self.props + .iter() + .filter(move |p| p.name.eq_ignore_ascii_case(name)) + } + + pub fn text(&self, name: &str) -> Option { + self.prop(name).map(Prop::text) + } + + /// Replaces the first property of that name (or appends it) and drops duplicates. + pub fn set(&mut self, prop: Prop) { + let name = prop.name.clone(); + let mut placed = false; + let mut out = Vec::with_capacity(self.props.len() + 1); + for p in self.props.drain(..) { + if p.name == name { + if !placed { + out.push(prop.clone()); + placed = true; + } + } else { + out.push(p); + } + } + if !placed { + out.push(prop); + } + self.props = out; + } + + pub fn remove(&mut self, name: &str) { + self.props.retain(|p| !p.name.eq_ignore_ascii_case(name)); + } + + pub fn children_named<'a>(&'a self, name: &'a str) -> impl Iterator { + self.children + .iter() + .filter(move |c| c.name.eq_ignore_ascii_case(name)) + } +} + +pub fn escape(s: &str) -> String { + let mut o = String::with_capacity(s.len()); + for c in s.chars() { + match c { + '\\' => o.push_str("\\\\"), + ';' => o.push_str("\\;"), + ',' => o.push_str("\\,"), + '\n' => o.push_str("\\n"), + '\r' => {} + c => o.push(c), + } + } + o +} + +pub fn unescape(s: &str) -> String { + let mut o = String::with_capacity(s.len()); + let mut it = s.chars(); + while let Some(c) = it.next() { + if c == '\\' { + match it.next() { + Some('n') | Some('N') => o.push('\n'), + Some(x) => o.push(x), + None => o.push('\\'), + } + } else { + o.push(c); + } + } + o +} + +fn unfold(input: &str) -> Vec { + let mut lines: Vec = Vec::new(); + for raw in input.split('\n') { + let line = raw.strip_suffix('\r').unwrap_or(raw); + if let Some(rest) = line.strip_prefix([' ', '\t']) + && let Some(last) = lines.last_mut() + { + last.push_str(rest); + continue; + } + if !line.is_empty() { + lines.push(line.to_string()); + } + } + lines +} + +fn parse_line(line: &str) -> Result { + // name *(;param=value) : value ; colons inside quoted params are not separators. + let mut in_quotes = false; + let mut colon = None; + for (i, c) in line.char_indices() { + match c { + '"' => in_quotes = !in_quotes, + ':' if !in_quotes => { + colon = Some(i); + break; + } + _ => {} + } + } + let colon = colon.ok_or_else(|| Error::Ical(format!("bad content line: {line}")))?; + let (head, value) = (&line[..colon], &line[colon + 1..]); + let mut parts: Vec<&str> = Vec::new(); + let (mut start, mut q) = (0, false); + for (i, c) in head.char_indices() { + match c { + '"' => q = !q, + ';' if !q => { + parts.push(&head[start..i]); + start = i + 1; + } + _ => {} + } + } + parts.push(&head[start..]); + let mut prop = Prop::new(parts[0], value); + for p in &parts[1..] { + if let Some((k, v)) = p.split_once('=') { + prop.params + .push((k.to_ascii_uppercase(), v.trim_matches('"').to_string())); + } + } + Ok(prop) +} + +/// Parses a calendar object; returns the top-level components (normally one `VCALENDAR`). +pub fn parse(input: &str) -> Result> { + let mut stack: Vec = Vec::new(); + let mut done = Vec::new(); + for line in unfold(input) { + let prop = parse_line(&line)?; + match prop.name.as_str() { + "BEGIN" => stack.push(Component::new(&prop.value)), + "END" => { + let c = stack + .pop() + .ok_or_else(|| Error::Ical("END without BEGIN".into()))?; + match stack.last_mut() { + Some(parent) => parent.children.push(c), + None => done.push(c), + } + } + _ => match stack.last_mut() { + Some(c) => c.props.push(prop), + None => return Err(Error::Ical("property outside component".into())), + }, + } + } + if !stack.is_empty() { + return Err(Error::Ical("unterminated component".into())); + } + Ok(done) +} + +fn fold(line: &str, out: &mut String) { + // Fold at 75 octets without splitting a UTF-8 character. + let mut count = 0; + for c in line.chars() { + let n = c.len_utf8(); + if count + n > 75 { + out.push_str("\r\n "); + count = 1; + } + out.push(c); + count += n; + } + out.push_str("\r\n"); +} + +fn write_component(c: &Component, out: &mut String) { + fold(&format!("BEGIN:{}", c.name), out); + for p in &c.props { + let mut l = p.name.clone(); + for (k, v) in &p.params { + l.push(';'); + l.push_str(k); + l.push('='); + if v.contains([';', ':', ',']) { + l.push('"'); + l.push_str(v); + l.push('"'); + } else { + l.push_str(v); + } + } + l.push(':'); + l.push_str(&p.value); + fold(&l, out); + } + for ch in &c.children { + write_component(ch, out); + } + fold(&format!("END:{}", c.name), out); +} + +pub fn serialize(c: &Component) -> String { + let mut s = String::new(); + write_component(c, &mut s); + s +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn roundtrip_with_folding_and_params() { + let src = "BEGIN:VCALENDAR\r\nVERSION:2.0\r\nBEGIN:VEVENT\r\nUID:a\r\nSUMMARY:Long \r\n title\\, with comma\r\nDTSTART;TZID=\"Europe/Madrid\":20261021T100000\r\nX-FOO;P=\"a:b\":bar\r\nEND:VEVENT\r\nEND:VCALENDAR\r\n"; + let cal = parse(src).unwrap(); + let ev = &cal[0].children[0]; + assert_eq!(ev.text("SUMMARY").unwrap(), "Long title, with comma"); + assert_eq!( + ev.prop("DTSTART").unwrap().param("TZID"), + Some("Europe/Madrid") + ); + assert_eq!(ev.prop("X-FOO").unwrap().param("P"), Some("a:b")); + let again = parse(&serialize(&cal[0])).unwrap(); + assert_eq!(cal, again); + } +} diff --git a/crates/synapse-caldav/src/lib.rs b/crates/synapse-caldav/src/lib.rs new file mode 100644 index 0000000..b00e8e0 --- /dev/null +++ b/crates/synapse-caldav/src/lib.rs @@ -0,0 +1,14 @@ +//! CalDAV events and VTODO tasks, two-way with Synapse. See `docs/caldav.md`. + +pub mod calendar; +pub mod dav; +mod error; +pub mod ical; +pub mod mapping; +pub mod store; +pub mod sync; +pub mod xml; + +pub use dav::{CalendarInfo, Credentials, DavClient}; +pub use error::{Error, Result}; +pub use sync::{Config, SyncReport, events_for_day, materialize_day, refresh_calendars, sync}; diff --git a/crates/synapse-caldav/src/mapping.rs b/crates/synapse-caldav/src/mapping.rs new file mode 100644 index 0000000..6ee1709 --- /dev/null +++ b/crates/synapse-caldav/src/mapping.rs @@ -0,0 +1,263 @@ +//! Logseq task syntax <-> VTODO fields. +//! +//! ```text +//! TODO [#A] Pay rent +//! SCHEDULED: <2026-10-21 Wed> +//! DEADLINE: <2026-10-25 Sun 14:00> +//! free-form notes (become DESCRIPTION) +//! ``` + +use crate::calendar::{DtValue, Todo, TodoStatus}; +use chrono::{DateTime, NaiveDate, NaiveDateTime, NaiveTime, Utc}; +use chrono_tz::Tz; + +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum Marker { + Todo, + Later, + Doing, + Now, + Done, + Canceled, +} + +impl Marker { + pub const ALL: [(&'static str, Marker); 7] = [ + ("TODO", Marker::Todo), + ("LATER", Marker::Later), + ("DOING", Marker::Doing), + ("NOW", Marker::Now), + ("DONE", Marker::Done), + ("CANCELED", Marker::Canceled), + ("CANCELLED", Marker::Canceled), + ]; + + pub fn as_str(self) -> &'static str { + match self { + Marker::Todo => "TODO", + Marker::Later => "LATER", + Marker::Doing => "DOING", + Marker::Now => "NOW", + Marker::Done => "DONE", + Marker::Canceled => "CANCELED", + } + } + + pub fn status(self) -> TodoStatus { + match self { + Marker::Todo | Marker::Later => TodoStatus::NeedsAction, + Marker::Doing | Marker::Now => TodoStatus::InProcess, + Marker::Done => TodoStatus::Completed, + Marker::Canceled => TodoStatus::Cancelled, + } + } + + /// Marker for a remote status, keeping `prev` when it is an equivalent spelling. + pub fn for_status(s: TodoStatus, prev: Option) -> Marker { + match prev { + Some(p) if p.status() == s => p, + _ => match s { + TodoStatus::NeedsAction => Marker::Todo, + TodoStatus::InProcess => Marker::Doing, + TodoStatus::Completed => Marker::Done, + TodoStatus::Cancelled => Marker::Canceled, + }, + } + } +} + +/// Parsed form of a task block's content. +#[derive(Debug, Clone, PartialEq)] +pub struct TaskText { + pub marker: Marker, + pub priority: Option, + pub title: String, + pub scheduled: Option, + pub deadline: Option, + pub notes: String, +} + +fn split_marker(content: &str) -> Option<(Marker, &str)> { + let first = content.lines().next()?; + Marker::ALL.iter().find_map(|(word, m)| { + let rest = first.strip_prefix(word)?; + (rest.is_empty() || rest.starts_with(' ')).then_some((*m, rest)) + }) +} + +/// Detects the marker at the start of `content` (first line). +pub fn marker_of(content: &str) -> Option { + split_marker(content).map(|(m, _)| m) +} + +fn parse_ldate(s: &str) -> Option { + // `<2026-10-21 Wed>` or `<2026-10-21 Wed 14:00>`; repeaters (`+1w`) are ignored. + let inner = s.trim().strip_prefix('<')?.split('>').next()?; + let mut parts = inner.split_whitespace(); + let date = NaiveDate::parse_from_str(parts.next()?, "%Y-%m-%d").ok()?; + let time = parts.find_map(|p| NaiveTime::parse_from_str(p, "%H:%M").ok()); + Some(match time { + Some(t) => DtValue::Floating(NaiveDateTime::new(date, t)), + None => DtValue::Date(date), + }) +} + +fn fmt_ldate(v: &DtValue, view: Tz) -> String { + let n = v.local(view); + let day = n.format("%Y-%m-%d %a"); + if v.is_date() { + format!("<{day}>") + } else { + format!("<{day} {}>", n.format("%H:%M")) + } +} + +pub fn parse_task(content: &str) -> Option { + let (marker, rest) = split_marker(content)?; + let mut lines = content.lines(); + lines.next(); + let mut title = rest.trim().to_string(); + let mut priority = None; + if let Some(rest) = title.strip_prefix("[#") + && let Some((p, tail)) = rest.split_once(']') + && p.len() == 1 + { + priority = p.chars().next().map(|c| c.to_ascii_uppercase()); + title = tail.trim().to_string(); + } + let (mut scheduled, mut deadline) = (None, None); + let mut notes = Vec::new(); + for l in lines { + let t = l.trim(); + if let Some(r) = t.strip_prefix("SCHEDULED:") { + scheduled = parse_ldate(r); + } else if let Some(r) = t.strip_prefix("DEADLINE:") { + deadline = parse_ldate(r); + } else { + notes.push(l); + } + } + Some(TaskText { + marker, + priority, + title, + scheduled, + deadline, + notes: notes.join("\n").trim().to_string(), + }) +} + +pub fn render_task(t: &TaskText, view: Tz) -> String { + let mut out = t.marker.as_str().to_string(); + if let Some(p) = t.priority { + out.push_str(&format!(" [#{p}]")); + } + if !t.title.is_empty() { + out.push(' '); + out.push_str(&t.title); + } + if let Some(s) = &t.scheduled { + out.push_str(&format!("\nSCHEDULED: {}", fmt_ldate(s, view))); + } + if let Some(d) = &t.deadline { + out.push_str(&format!("\nDEADLINE: {}", fmt_ldate(d, view))); + } + if !t.notes.is_empty() { + out.push('\n'); + out.push_str(&t.notes); + } + out +} + +pub fn priority_to_ical(p: Option) -> u8 { + match p { + Some('A') => 1, + Some('B') => 5, + Some('C') => 9, + _ => 0, + } +} + +pub fn priority_from_ical(p: u8) -> Option { + match p { + 1..=4 => Some('A'), + 5 => Some('B'), + 6..=9 => Some('C'), + _ => None, + } +} + +/// Re-zones a floating local time so that the remote keeps an unambiguous instant. +fn to_remote(v: DtValue, view: Tz) -> DtValue { + match v { + DtValue::Floating(n) => DtValue::Zoned(view, n), + o => o, + } +} + +/// Task fields from block content. `existing` supplies the fields Synapse does not model +/// (percent, COMPLETED timestamp) and the previous values for unchanged dates. +pub fn todo_from_text( + t: &TaskText, + uid: &str, + existing: Option<&Todo>, + view: Tz, + now: DateTime, +) -> Todo { + let status = t.marker.status(); + // Keep the original zoned value when the local rendering did not change. + let keep = |new: &Option, old: Option<&DtValue>| match (new, old) { + (Some(n), Some(o)) if n.local(view) == o.local(view) && n.is_date() == o.is_date() => { + Some(o.clone()) + } + (Some(n), _) => Some(to_remote(n.clone(), view)), + (None, _) => None, + }; + Todo { + uid: uid.to_string(), + summary: t.title.clone(), + description: (!t.notes.is_empty()).then(|| t.notes.clone()), + status, + percent: existing.and_then(|e| e.percent), + priority: priority_to_ical(t.priority), + start: keep(&t.scheduled, existing.and_then(|e| e.start.as_ref())), + due: keep(&t.deadline, existing.and_then(|e| e.due.as_ref())), + completed: match status { + TodoStatus::Completed => Some(existing.and_then(|e| e.completed).unwrap_or(now)), + _ => None, + }, + last_modified: Some(now), + has_rrule: existing.is_some_and(|e| e.has_rrule), + } +} + +pub fn text_from_todo(t: &Todo, prev: Option) -> TaskText { + TaskText { + marker: Marker::for_status(t.status, prev), + priority: priority_from_ical(t.priority), + title: t.summary.clone(), + scheduled: t.start.clone(), + deadline: t.due.clone(), + notes: t.description.clone().unwrap_or_default(), + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn parse_and_render() { + let c = "TODO [#A] Pay rent\nSCHEDULED: <2026-10-21 Wed>\nDEADLINE: <2026-10-25 Sun 14:00>\nsome note"; + let t = parse_task(c).unwrap(); + assert_eq!(t.marker, Marker::Todo); + assert_eq!(t.priority, Some('A')); + assert_eq!(t.title, "Pay rent"); + assert_eq!(t.notes, "some note"); + assert!(t.scheduled.as_ref().unwrap().is_date()); + assert_eq!(render_task(&t, chrono_tz::UTC), c); + assert!(parse_task("TODOS x").is_none()); + assert_eq!(parse_task("DONE").unwrap().title, ""); + assert_eq!(priority_from_ical(priority_to_ical(Some('B'))), Some('B')); + } +} diff --git a/crates/synapse-caldav/src/store.rs b/crates/synapse-caldav/src/store.rs new file mode 100644 index 0000000..3e79426 --- /dev/null +++ b/crates/synapse-caldav/src/store.rs @@ -0,0 +1,204 @@ +//! `caldav_*` tables living in the graph database (sync tokens, etags, uid <-> block ids). + +use crate::Result; +use rusqlite::{Connection, OptionalExtension, params}; + +const SCHEMA: &str = r#" +CREATE TABLE IF NOT EXISTS caldav_meta (key TEXT PRIMARY KEY, value TEXT NOT NULL); +CREATE TABLE IF NOT EXISTS caldav_calendar ( + href TEXT PRIMARY KEY, + name TEXT NOT NULL, + events INTEGER NOT NULL, + tasks INTEGER NOT NULL, + ctag TEXT, + sync_token TEXT +); +-- One row per remote calendar object. `ics` is the last server version (needed to edit a task +-- without losing unknown properties and to answer events_for_day offline). +CREATE TABLE IF NOT EXISTS caldav_object ( + href TEXT PRIMARY KEY, + calendar TEXT NOT NULL, + uid TEXT NOT NULL, + kind TEXT NOT NULL, + etag TEXT NOT NULL, + ics TEXT NOT NULL, + block_id TEXT, + synced_content TEXT +); +CREATE INDEX IF NOT EXISTS caldav_object_cal ON caldav_object(calendar, kind); +CREATE INDEX IF NOT EXISTS caldav_object_uid ON caldav_object(uid); +CREATE INDEX IF NOT EXISTS caldav_object_block ON caldav_object(block_id); +-- Event occurrences materialised as journal blocks. +CREATE TABLE IF NOT EXISTS caldav_event_block ( + uid TEXT NOT NULL, + day TEXT NOT NULL, + block_id TEXT NOT NULL, + content TEXT NOT NULL, + PRIMARY KEY (uid, day, block_id) +); +"#; + +pub fn ensure_schema(conn: &Connection) -> Result<()> { + conn.execute_batch(SCHEMA)?; + Ok(()) +} + +#[derive(Debug, Clone)] +pub struct CalendarRow { + pub href: String, + pub name: String, + pub events: bool, + pub tasks: bool, + pub ctag: Option, + pub sync_token: Option, +} + +#[derive(Debug, Clone)] +pub struct ObjectRow { + pub href: String, + pub calendar: String, + pub uid: String, + pub kind: String, + pub etag: String, + pub ics: String, + pub block_id: Option, + pub synced_content: Option, +} + +const OBJ_COLS: &str = "href, calendar, uid, kind, etag, ics, block_id, synced_content"; + +fn obj_row(r: &rusqlite::Row<'_>) -> rusqlite::Result { + Ok(ObjectRow { + href: r.get(0)?, + calendar: r.get(1)?, + uid: r.get(2)?, + kind: r.get(3)?, + etag: r.get(4)?, + ics: r.get(5)?, + block_id: r.get(6)?, + synced_content: r.get(7)?, + }) +} + +pub fn meta_get(c: &Connection, key: &str) -> Result> { + Ok( + c.query_row("SELECT value FROM caldav_meta WHERE key=?1", [key], |r| { + r.get(0) + }) + .optional()?, + ) +} + +pub fn meta_set(c: &Connection, key: &str, value: &str) -> Result<()> { + c.execute( + "INSERT INTO caldav_meta(key, value) VALUES(?1, ?2) ON CONFLICT(key) DO UPDATE SET value=?2", + [key, value], + )?; + Ok(()) +} + +pub fn calendars(c: &Connection) -> Result> { + let mut st = c.prepare("SELECT href, name, events, tasks, ctag, sync_token FROM caldav_calendar ORDER BY name, href")?; + let rows = st + .query_map([], |r| { + Ok(CalendarRow { + href: r.get(0)?, + name: r.get(1)?, + events: r.get::<_, i64>(2)? != 0, + tasks: r.get::<_, i64>(3)? != 0, + ctag: r.get(4)?, + sync_token: r.get(5)?, + }) + })? + .collect::>()?; + Ok(rows) +} + +pub fn calendar(c: &Connection, href: &str) -> Result> { + Ok(calendars(c)?.into_iter().find(|r| r.href == href)) +} + +/// Inserts or updates a calendar's descriptive fields, keeping its sync state. +pub fn upsert_calendar( + c: &Connection, + name: &str, + href: &str, + events: bool, + tasks: bool, +) -> Result<()> { + c.execute( + "INSERT INTO caldav_calendar(href, name, events, tasks) VALUES(?1, ?2, ?3, ?4) + ON CONFLICT(href) DO UPDATE SET name=?2, events=?3, tasks=?4", + params![href, name, events, tasks], + )?; + Ok(()) +} + +pub fn set_calendar_state( + c: &Connection, + href: &str, + ctag: Option<&str>, + token: Option<&str>, +) -> Result<()> { + c.execute( + "UPDATE caldav_calendar SET ctag=COALESCE(?2, ctag), sync_token=COALESCE(?3, sync_token) WHERE href=?1", + params![href, ctag, token], + )?; + Ok(()) +} + +pub fn clear_calendar_token(c: &Connection, href: &str) -> Result<()> { + c.execute( + "UPDATE caldav_calendar SET sync_token=NULL, ctag=NULL WHERE href=?1", + [href], + )?; + Ok(()) +} + +pub fn object(c: &Connection, href: &str) -> Result> { + Ok(c.query_row( + &format!("SELECT {OBJ_COLS} FROM caldav_object WHERE href=?1"), + [href], + obj_row, + ) + .optional()?) +} + +pub fn object_by_block(c: &Connection, block: &str) -> Result> { + Ok(c.query_row( + &format!("SELECT {OBJ_COLS} FROM caldav_object WHERE block_id=?1"), + [block], + obj_row, + ) + .optional()?) +} + +pub fn objects( + c: &Connection, + calendar: Option<&str>, + kind: Option<&str>, +) -> Result> { + let mut st = c.prepare(&format!( + "SELECT {OBJ_COLS} FROM caldav_object WHERE (?1 IS NULL OR calendar=?1) AND (?2 IS NULL OR kind=?2) ORDER BY href" + ))?; + let rows = st + .query_map(params![calendar, kind], obj_row)? + .collect::>()?; + Ok(rows) +} + +pub fn put_object(c: &Connection, o: &ObjectRow) -> Result<()> { + c.execute( + &format!( + "INSERT INTO caldav_object({OBJ_COLS}) VALUES(?1,?2,?3,?4,?5,?6,?7,?8) + ON CONFLICT(href) DO UPDATE SET calendar=?2, uid=?3, kind=?4, etag=?5, ics=?6, block_id=?7, synced_content=?8" + ), + params![o.href, o.calendar, o.uid, o.kind, o.etag, o.ics, o.block_id, o.synced_content], + )?; + Ok(()) +} + +pub fn delete_object(c: &Connection, href: &str) -> Result<()> { + c.execute("DELETE FROM caldav_object WHERE href=?1", [href])?; + Ok(()) +} diff --git a/crates/synapse-caldav/src/sync.rs b/crates/synapse-caldav/src/sync.rs new file mode 100644 index 0000000..8264fdc --- /dev/null +++ b/crates/synapse-caldav/src/sync.rs @@ -0,0 +1,638 @@ +//! Two-way synchronisation between a CalDAV account and a Synapse graph. +//! +//! The futures hold `&Graph` (which is `Send` but not `Sync`) across awaits, so they are not +//! `Send`: drive them with `block_on` on a current-thread runtime / dedicated thread. + +use crate::calendar::{ + self, Event, Todo, event_occurrences, master_todo, master_todo_mut, parse_calendar, +}; +use crate::dav::{CalendarInfo, DavClient, RemoteObject}; +use crate::mapping::{self, Marker, TaskText}; +use crate::store::{self, ObjectRow}; +use crate::{Error, Result, ical}; +use chrono::{DateTime, Duration, NaiveDate, NaiveTime, TimeZone, Utc}; +use chrono_tz::Tz; +use serde_json::Value; +use synapse_core::{Block, BlockId, Graph, Placement, Properties}; +use uuid::Uuid; + +pub const PROP_UID: &str = "caldav-uid"; +pub const PROP_CALENDAR: &str = "caldav-calendar"; +pub const PROP_EVENT: &str = "caldav-event"; + +#[derive(Debug, Clone)] +pub struct Config { + /// Zone used to show UTC/zoned times and to interpret floating ones. + pub tz: Tz, + /// Href of the task list that receives new tasks written in journals + /// (default: the first calendar that supports VTODO). + pub default_task_calendar: Option, +} + +impl Config { + pub fn new(tz: Tz) -> Self { + Config { + tz, + default_task_calendar: None, + } + } +} + +#[derive(Debug, Default, Clone, PartialEq, Eq)] +pub struct SyncReport { + pub calendars: usize, + pub events_changed: usize, + pub tasks_pulled: usize, + pub removed_remote: usize, + pub tasks_created_remote: usize, + pub tasks_updated_remote: usize, + pub tasks_deleted_remote: usize, + pub conflicts: usize, +} + +fn now_utc(graph: &Graph) -> DateTime { + Utc.timestamp_millis_opt(graph.now_ms()) + .single() + .unwrap_or_else(Utc::now) +} + +/// Discovers the account's calendars and records them locally (sync state is preserved). +pub async fn refresh_calendars(graph: &Graph, client: &DavClient) -> Result> { + store::ensure_schema(graph.conn())?; + let home = match store::meta_get(graph.conn(), "home")? { + Some(h) => h, + None => { + let h = client.discover().await?; + store::meta_set(graph.conn(), "home", &h)?; + h + } + }; + let cals = client.list_calendars(&home).await?; + for c in &cals { + if c.supports_events || c.supports_tasks { + store::upsert_calendar( + graph.conn(), + &c.name, + &c.href, + c.supports_events, + c.supports_tasks, + )?; + } + } + Ok(cals) +} + +/// Full two-way sync: pull every calendar, then push local task changes. +pub async fn sync(graph: &Graph, client: &DavClient, cfg: &Config) -> Result { + store::ensure_schema(graph.conn())?; + if store::meta_get(graph.conn(), "enabled_at")?.is_none() { + store::meta_set(graph.conn(), "enabled_at", &graph.now_ms().to_string())?; + } + refresh_calendars(graph, client).await?; + let mut rep = SyncReport::default(); + let cals = store::calendars(graph.conn())?; + rep.calendars = cals.len(); + for cal in &cals { + pull_calendar(graph, client, cfg, cal, &mut rep).await?; + } + push_tasks(graph, client, cfg, &mut rep).await?; + Ok(rep) +} + +// ------------------------------------------------------------------------------- pull + +async fn pull_calendar( + graph: &Graph, + client: &DavClient, + cfg: &Config, + cal: &store::CalendarRow, + rep: &mut SyncReport, +) -> Result<()> { + let known: std::collections::HashMap = + store::objects(graph.conn(), Some(&cal.href), None)? + .into_iter() + .map(|o| (o.href, o.etag)) + .collect(); + type Pulled = ( + Vec<(String, String)>, + Vec, + Option, + Option, + ); + let (changed, deleted, new_token, new_ctag): Pulled; + let incremental = match client + .sync_collection(&cal.href, cal.sync_token.as_deref()) + .await? + { + Some(ch) => Some(ch), + None if cal.sync_token.is_some() => { + // Token rejected: restart with a full sync-collection. + store::clear_calendar_token(graph.conn(), &cal.href)?; + client.sync_collection(&cal.href, None).await? + } + None => None, + }; + if let Some(ch) = incremental { + changed = ch.changed; + deleted = ch.deleted; + new_token = ch.new_token; + new_ctag = None; + } else { + // ctag/etag fallback. + let ctag = client.ctag(&cal.href).await?; + if ctag.is_some() && ctag == cal.ctag { + return Ok(()); + } + let all = client.list_etags(&cal.href).await?; + let present: std::collections::HashSet<&String> = all.iter().map(|(h, _)| h).collect(); + deleted = known + .keys() + .filter(|h| !present.contains(h)) + .cloned() + .collect(); + changed = all.to_vec(); + new_token = None; + new_ctag = ctag; + } + for h in &deleted { + remove_remote(graph, h, rep)?; + } + let want: Vec = changed + .iter() + .filter(|(h, e)| known.get(h) != Some(e)) + .map(|(h, _)| h.clone()) + .collect(); + if !want.is_empty() { + for obj in client.multiget(&cal.href, &want).await? { + apply_remote(graph, cfg, &cal.href, &cal.name, &obj, rep)?; + } + } + store::set_calendar_state( + graph.conn(), + &cal.href, + new_ctag.as_deref(), + new_token.as_deref(), + )?; + Ok(()) +} + +fn merge_props(block: &Block, uid: &str, cal: &str) -> Properties { + let mut p = block.properties.clone(); + p.insert(PROP_UID.into(), Value::String(uid.into())); + p.insert(PROP_CALENDAR.into(), Value::String(cal.into())); + p +} + +fn conflict_note(graph: &Graph, block: &Block, label: &str, content: &str) -> Result<()> { + let note = format!("CalDAV conflict: {label} version (older, kept as note)\n{content}"); + graph.insert_block(block.page_id, Placement::LastChildOf(Some(block.id)), ¬e)?; + Ok(()) +} + +fn remove_remote(graph: &Graph, href: &str, rep: &mut SyncReport) -> Result<()> { + let Some(row) = store::object(graph.conn(), href)? else { + return Ok(()); + }; + rep.removed_remote += 1; + if let Some(bid) = row + .block_id + .as_deref() + .and_then(|s| Uuid::parse_str(s).ok()) + && let Some(block) = graph.get_block(bid)? + { + if Some(&block.content) == row.synced_content.as_ref() { + graph.delete_block(bid)?; + } else { + // Local edits win over a remote delete: detach and let the push re-create it. + let mut p = block.properties.clone(); + p.remove(PROP_UID); + p.remove(PROP_CALENDAR); + graph.set_block_properties(bid, p)?; + } + } + store::delete_object(graph.conn(), href) +} + +fn apply_remote( + graph: &Graph, + cfg: &Config, + cal_href: &str, + cal_name: &str, + obj: &RemoteObject, + rep: &mut SyncReport, +) -> Result<()> { + let cal = parse_calendar(&obj.ics)?; + let is_task = cal.children_named("VTODO").next().is_some(); + let is_event = cal.children_named("VEVENT").next().is_some(); + let comp = if is_task { + master_todo(&cal) + } else { + cal.children_named("VEVENT").next() + }; + let Some(comp) = comp else { return Ok(()) }; + let Some(uid) = comp.text("UID") else { + return Ok(()); + }; + let existing = store::object(graph.conn(), &obj.href)?; + + if !is_task { + if is_event { + rep.events_changed += 1; + } + store::put_object( + graph.conn(), + &ObjectRow { + href: obj.href.clone(), + calendar: cal_href.to_string(), + uid, + kind: if is_event { "VEVENT" } else { "OTHER" }.into(), + etag: obj.etag.clone(), + ics: obj.ics.clone(), + block_id: None, + synced_content: None, + }, + )?; + return Ok(()); + } + + let Some(todo) = Todo::from_component(comp) else { + return Ok(()); + }; + rep.tasks_pulled += 1; + let block = existing + .as_ref() + .and_then(|r| r.block_id.as_deref()) + .and_then(|s| Uuid::parse_str(s).ok()) + .map(|id| graph.get_block(id)) + .transpose()? + .flatten(); + let mut row = ObjectRow { + href: obj.href.clone(), + calendar: cal_href.to_string(), + uid: uid.clone(), + kind: "VTODO".into(), + etag: obj.etag.clone(), + ics: obj.ics.clone(), + block_id: existing.as_ref().and_then(|r| r.block_id.clone()), + synced_content: existing.as_ref().and_then(|r| r.synced_content.clone()), + }; + match block { + None if existing.as_ref().is_some_and(|r| r.block_id.is_some()) => { + // Deleted locally: keep the old etag so the push phase can delete remotely. + return Ok(()); + } + None => { + let page = graph.ensure_page(cal_name, None)?; + let content = mapping::render_task(&mapping::text_from_todo(&todo, None), cfg.tz); + let b = graph.insert_block(page.id, Placement::LastChildOf(None), &content)?; + graph.set_block_properties(b.id, merge_props(&b, &uid, cal_href))?; + row.block_id = Some(b.id.to_string()); + row.synced_content = Some(content); + } + Some(b) => { + let prev = mapping::marker_of(&b.content); + let content = mapping::render_task(&mapping::text_from_todo(&todo, prev), cfg.tz); + let local_changed = Some(&b.content) != row.synced_content.as_ref(); + if !local_changed || b.content == content { + if b.content != content { + graph.update_block(b.id, &content)?; + } + row.synced_content = Some(content); + } else { + rep.conflicts += 1; + let remote_ms = todo + .last_modified + .map(|t| t.timestamp_millis()) + .unwrap_or(0); + if remote_ms >= b.updated_at { + conflict_note(graph, &b, "local", &b.content)?; + graph.update_block(b.id, &content)?; + row.synced_content = Some(content); + } else { + // Local is newer: keep it (the push phase uploads it) and note the remote. + conflict_note(graph, &b, "remote", &content)?; + } + } + } + } + store::put_object(graph.conn(), &row) +} + +// ------------------------------------------------------------------------------- push + +fn default_task_calendar(graph: &Graph, cfg: &Config) -> Result> { + let cals = store::calendars(graph.conn())?; + Ok(match &cfg.default_task_calendar { + Some(h) => cals.into_iter().find(|c| &c.href == h), + None => cals.into_iter().find(|c| c.tasks), + }) +} + +async fn push_tasks( + graph: &Graph, + client: &DavClient, + cfg: &Config, + rep: &mut SyncReport, +) -> Result<()> { + // Tracked tasks: edits and deletions. + for row in store::objects(graph.conn(), None, Some("VTODO"))? { + if row.block_id.is_none() { + continue; + } + push_tracked(graph, client, cfg, row, rep).await?; + } + // New tasks typed into journals. + let Some(cal) = default_task_calendar(graph, cfg)? else { + return Ok(()); + }; + let since: i64 = store::meta_get(graph.conn(), "enabled_at")? + .and_then(|s| s.parse().ok()) + .unwrap_or(0); + let mut st = graph.conn().prepare( + "SELECT b.id FROM blocks b JOIN pages p ON p.id=b.page_id + WHERE p.journal_date IS NOT NULL AND b.updated_at >= ?1 + AND b.properties NOT LIKE '%caldav-uid%' ORDER BY b.created_at", + )?; + let ids: Vec = st + .query_map([since], |r| r.get(0))? + .collect::>()?; + drop(st); + for id in ids { + let Some(b) = Uuid::parse_str(&id) + .ok() + .map(|i| graph.get_block(i)) + .transpose()? + .flatten() + else { + continue; + }; + let Some(task) = mapping::parse_task(&b.content) else { + continue; + }; + if matches!(task.marker, Marker::Done | Marker::Canceled) { + continue; + } + let uid = Uuid::now_v7().to_string(); + let todo = mapping::todo_from_text(&task, &uid, None, cfg.tz, now_utc(graph)); + let ics = ical::serialize(&todo.to_calendar(now_utc(graph))); + let href = format!("{}/{}.ics", cal.href.trim_end_matches('/'), uid); + let etag = client.put(&href, &ics, None).await?; + graph.set_block_properties(b.id, merge_props(&b, &uid, &cal.href))?; + store::put_object( + graph.conn(), + &ObjectRow { + href, + calendar: cal.href.clone(), + uid, + kind: "VTODO".into(), + etag, + ics, + block_id: Some(b.id.to_string()), + synced_content: Some(b.content.clone()), + }, + )?; + rep.tasks_created_remote += 1; + } + Ok(()) +} + +async fn push_tracked( + graph: &Graph, + client: &DavClient, + cfg: &Config, + row: ObjectRow, + rep: &mut SyncReport, +) -> Result<()> { + let mut row = row; + for attempt in 0..2 { + let block = row + .block_id + .as_deref() + .and_then(|s| Uuid::parse_str(s).ok()) + .map(|id| graph.get_block(id)) + .transpose()? + .flatten(); + let Some(block) = block else { + // Deleted locally. + match client.delete(&row.href, Some(&row.etag)).await { + Ok(()) => { + store::delete_object(graph.conn(), &row.href)?; + rep.tasks_deleted_remote += 1; + } + Err(Error::PreconditionFailed(_)) => { + // Changed remotely meanwhile: the remote edit wins, bring it back. + let obj = client.get(&row.href).await?; + store::delete_object(graph.conn(), &row.href)?; + let name = store::calendar(graph.conn(), &row.calendar)? + .map(|c| c.name) + .unwrap_or_default(); + apply_remote(graph, cfg, &row.calendar, &name, &obj, rep)?; + } + Err(e) => return Err(e), + } + return Ok(()); + }; + if Some(&block.content) == row.synced_content.as_ref() { + return Ok(()); + } + let Some(task) = mapping::parse_task(&block.content) else { + return Ok(()); // no longer a task; leave the remote alone + }; + let mut cal = parse_calendar(&row.ics)?; + let existing = master_todo(&cal).and_then(Todo::from_component); + let now = now_utc(graph); + let todo = mapping::todo_from_text(&task, &row.uid, existing.as_ref(), cfg.tz, now); + let Some(comp) = master_todo_mut(&mut cal) else { + return Ok(()); + }; + todo.apply_to(comp, now); + let ics = ical::serialize(&cal); + match client.put(&row.href, &ics, Some(&row.etag)).await { + Ok(etag) => { + row.etag = etag; + row.ics = ics; + row.synced_content = Some(block.content.clone()); + store::put_object(graph.conn(), &row)?; + rep.tasks_updated_remote += 1; + return Ok(()); + } + Err(Error::PreconditionFailed(_)) if attempt == 0 => { + // Both sides changed: resolve by last-modified, then retry once. + let obj = client.get(&row.href).await?; + let name = store::calendar(graph.conn(), &row.calendar)? + .map(|c| c.name) + .unwrap_or_default(); + apply_remote(graph, cfg, &row.calendar, &name, &obj, rep)?; + row = store::object(graph.conn(), &row.href)? + .ok_or_else(|| Error::Other("object vanished".into()))?; + } + Err(e) => return Err(e), + } + } + Ok(()) +} + +// ------------------------------------------------------------------------------ events + +/// Events (with recurrences expanded) overlapping `day`, from the local cache. +pub fn events_for_day(graph: &Graph, day: NaiveDate, tz: Tz) -> Result> { + events_between(graph, day, day + Duration::days(1), tz) +} + +/// Events overlapping `[from, to)` (dates), from the local cache. +pub fn events_between( + graph: &Graph, + from: NaiveDate, + to: NaiveDate, + tz: Tz, +) -> Result> { + store::ensure_schema(graph.conn())?; + let names: std::collections::HashMap = store::calendars(graph.conn())? + .into_iter() + .map(|c| (c.href, c.name)) + .collect(); + let (f, t) = (from.and_time(NaiveTime::MIN), to.and_time(NaiveTime::MIN)); + let mut out = Vec::new(); + for o in store::objects(graph.conn(), None, Some("VEVENT"))? { + let Ok(cal) = parse_calendar(&o.ics) else { + continue; + }; + let name = names.get(&o.calendar).cloned().unwrap_or_default(); + out.extend(event_occurrences(&cal, &name, &o.href, tz, f, t)); + } + out.sort_by_key(|o| (o.start, o.summary.clone())); + Ok(out) +} + +fn clean(s: &str) -> String { + s.replace("[[", "[ [") + .replace("]]", "] ]") + .replace('\n', " ") +} + +fn occurrence_text(o: &calendar::Occurrence) -> String { + let when = if o.all_day { + "All day".to_string() + } else { + format!("{}-{}", o.start.format("%H:%M"), o.end.format("%H:%M")) + }; + let title = clean(&o.summary); + // A page per recurring meeting collects its notes across occurrences. + let title = if o.recurring && !title.is_empty() { + format!("[[{title}]]") + } else { + title + }; + format!("{when} {title}") +} + +/// Writes the day's events into its journal as blocks (idempotent; updates changed events and +/// removes blocks of events that vanished). Returns the block ids, in time order. +pub fn materialize_day(graph: &Graph, day: NaiveDate, tz: Tz) -> Result> { + let occs = events_for_day(graph, day, tz)?; + let journal = graph.journal(day)?; + let day_s = day.to_string(); + let mut ids = Vec::new(); + let mut keep = Vec::new(); + for o in &occs { + let text = occurrence_text(o); + let key = format!("{}@{}", o.uid, o.start.format("%Y%m%dT%H%M%S")); + let existing: Option<(String, String)> = graph + .conn() + .query_row( + "SELECT block_id, content FROM caldav_event_block WHERE uid=?1 AND day=?2", + [&key, &day_s], + |r| Ok((r.get(0)?, r.get(1)?)), + ) + .ok(); + let block = match existing { + Some((bid, old)) => match Uuid::parse_str(&bid) + .ok() + .map(|i| graph.get_block(i)) + .transpose()? + .flatten() + { + Some(b) => { + // Do not overwrite text the user edited by hand. + if b.content == old && old != text { + graph.update_block(b.id, &text)?; + } + b + } + None => new_event_block(graph, &journal, &text, &o.uid)?, + }, + None => new_event_block(graph, &journal, &text, &o.uid)?, + }; + graph.conn().execute( + "DELETE FROM caldav_event_block WHERE uid=?1 AND day=?2", + [&key, &day_s], + )?; + graph.conn().execute( + "INSERT INTO caldav_event_block(uid, day, block_id, content) VALUES(?1,?2,?3,?4)", + [&key, &day_s, &block.id.to_string(), &text], + )?; + keep.push(key); + ids.push(block.id); + } + // Events no longer on that day. + let mut st = graph + .conn() + .prepare("SELECT uid, block_id, content FROM caldav_event_block WHERE day=?1")?; + let rows: Vec<(String, String, String)> = st + .query_map([&day_s], |r| Ok((r.get(0)?, r.get(1)?, r.get(2)?)))? + .collect::>()?; + drop(st); + for (key, bid, content) in rows { + if keep.contains(&key) { + continue; + } + if let Some(b) = Uuid::parse_str(&bid) + .ok() + .map(|i| graph.get_block(i)) + .transpose()? + .flatten() + && b.content == content + { + graph.delete_block(b.id)?; + } + graph.conn().execute( + "DELETE FROM caldav_event_block WHERE uid=?1 AND day=?2", + [&key, &day_s], + )?; + } + Ok(ids) +} + +fn new_event_block( + graph: &Graph, + journal: &synapse_core::Page, + text: &str, + uid: &str, +) -> Result { + let b = graph.insert_block(journal.id, Placement::LastChildOf(None), text)?; + let mut p = b.properties.clone(); + p.insert(PROP_EVENT.into(), Value::String(uid.into())); + Ok(graph.set_block_properties(b.id, p)?) +} + +/// Helper for UIs: the event model behind a cached object. +pub fn event_of(ics: &str) -> Option { + let cal = parse_calendar(ics).ok()?; + cal.children_named("VEVENT").find_map(Event::from_component) +} + +/// Marks a task block done/undone locally (the next sync pushes it). +pub fn set_task_done(graph: &Graph, id: BlockId, done: bool) -> Result<()> { + let b = graph + .get_block(id)? + .ok_or_else(|| Error::Other("block not found".into()))?; + let Some(t) = mapping::parse_task(&b.content) else { + return Err(Error::Other("not a task block".into())); + }; + let new = TaskText { + marker: if done { Marker::Done } else { Marker::Todo }, + ..t + }; + graph.update_block(id, &mapping::render_task(&new, chrono_tz::UTC))?; + Ok(()) +} diff --git a/crates/synapse-caldav/src/xml.rs b/crates/synapse-caldav/src/xml.rs new file mode 100644 index 0000000..c570f54 --- /dev/null +++ b/crates/synapse-caldav/src/xml.rs @@ -0,0 +1,223 @@ +//! WebDAV multistatus parsing (namespace prefixes are ignored; local names only). + +use crate::{Error, Result}; +use quick_xml::Reader; +use quick_xml::events::Event; + +#[derive(Debug, Default, Clone)] +pub struct Response { + pub href: String, + /// Response-level status (used by `sync-collection` for removed members). + pub status: Option, + /// Elements found under `prop` in successful propstats: (path below `prop`, text). + /// Every element yields an entry, so presence can be tested with `has`. + pub items: Vec<(Vec, String)>, +} + +impl Response { + pub fn text(&self, path: &[&str]) -> Option<&str> { + self.items + .iter() + .find(|(p, t)| p.iter().map(String::as_str).eq(path.iter().copied()) && !t.is_empty()) + .map(|(_, t)| t.as_str()) + } + + pub fn has(&self, path: &[&str]) -> bool { + self.items + .iter() + .any(|(p, _)| p.iter().map(String::as_str).eq(path.iter().copied())) + } + + pub fn is_removed(&self) -> bool { + self.status.as_deref().is_some_and(|s| s.contains(" 404")) + } +} + +#[derive(Debug, Default)] +pub struct Multistatus { + pub responses: Vec, + pub sync_token: Option, +} + +fn local(s: &str) -> String { + s.rsplit(':').next().unwrap_or("").to_string() +} + +fn xerr(e: impl std::fmt::Display) -> Error { + Error::Xml(e.to_string()) +} + +#[derive(Default)] +struct Parser { + out: Multistatus, + stack: Vec, + resp: Option, + ps_items: Vec<(Vec, String)>, + ps_status: String, + text: String, +} + +impl Parser { + fn in_prop(&self) -> Option { + self.stack.iter().position(|s| s == "prop") + } + + fn start(&mut self, name: String) { + self.text.clear(); + match name.as_str() { + "response" => self.resp = Some(Response::default()), + "propstat" => { + self.ps_items.clear(); + self.ps_status.clear(); + } + _ => {} + } + self.stack.push(name); + if let Some(pos) = self.in_prop() + && self.stack.len() > pos + 1 + && self.resp.is_some() + { + self.ps_items + .push((self.stack[pos + 1..].to_vec(), String::new())); + } + } + + fn end(&mut self) { + let Some(name) = self.stack.last().cloned() else { + return; + }; + let t = std::mem::take(&mut self.text); + let t = t.trim(); + let in_propstat = self.stack.iter().any(|s| s == "propstat"); + match name.as_str() { + "href" if self.in_prop().is_none() && self.stack.len() == 3 => { + if let Some(r) = self.resp.as_mut() { + r.href = t.to_string(); + } + } + "status" if in_propstat => self.ps_status = t.to_string(), + "status" => { + if let Some(r) = self.resp.as_mut() { + r.status = Some(t.to_string()); + } + } + "sync-token" if self.in_prop().is_none() && self.stack.len() == 2 => { + self.out.sync_token = Some(t.to_string()); + } + "propstat" => { + if let Some(r) = self.resp.as_mut() + && self.ps_status.contains(" 2") + { + r.items.append(&mut self.ps_items); + } + self.ps_items.clear(); + } + "response" => { + if let Some(r) = self.resp.take() { + self.out.responses.push(r); + } + } + _ => {} + } + if let Some(pos) = self.in_prop() + && self.stack.len() > pos + 1 + && !t.is_empty() + { + let path = self.stack[pos + 1..].to_vec(); + if let Some(it) = self + .ps_items + .iter_mut() + .rev() + .find(|(p, v)| *p == path && v.is_empty()) + { + it.1 = t.to_string(); + } + } + self.stack.pop(); + } +} + +fn element_name(e: &quick_xml::events::BytesStart<'_>) -> String { + let mut name = local(e.name().as_ref()); + // `` is distinguished by its attribute. + if name == "comp" { + for a in e.attributes().flatten() { + if a.key.as_ref() == "name" { + name = format!("comp:{}", a.value); + } + } + } + name +} + +pub fn parse_multistatus(xml: &str) -> Result { + let mut rd = Reader::from_str(xml); + let mut p = Parser::default(); + loop { + match rd.read_event().map_err(xerr)? { + Event::Start(e) => p.start(element_name(&e)), + Event::Empty(e) => { + p.start(element_name(&e)); + p.end(); + } + Event::Text(t) => p + .text + .push_str(&Ok::<_, std::convert::Infallible>(t.xml10_content()).map_err(xerr)?), + Event::CData(c) => p.text.push_str(c.as_ref()), + Event::GeneralRef(r) => match r.resolve_char_ref() { + Ok(Some(c)) => p.text.push(c), + _ => match &*r { + "amp" => p.text.push('&'), + "lt" => p.text.push('<'), + "gt" => p.text.push('>'), + "quot" => p.text.push('"'), + "apos" => p.text.push('\''), + _ => {} + }, + }, + Event::End(_) => p.end(), + Event::Eof => break, + _ => {} + } + } + Ok(p.out) +} + +/// Escapes text for inclusion in an XML request body. +pub fn esc(s: &str) -> String { + s.replace('&', "&") + .replace('<', "<") + .replace('>', ">") +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn multistatus_basic() { + let x = r#" + +/cal/a.ics"e1" +BEGIN:VCALENDAR +SUMMARY:A & B +END:VCALENDARHTTP/1.1 200 OK +HTTP/1.1 404 Not Found +/cal/gone.icsHTTP/1.1 404 Not Found +tok-7 +"#; + let m = parse_multistatus(x).unwrap(); + assert_eq!(m.sync_token.as_deref(), Some("tok-7")); + assert_eq!(m.responses.len(), 2); + assert_eq!(m.responses[0].href, "/cal/a.ics"); + assert_eq!(m.responses[0].text(&["getetag"]), Some("\"e1\"")); + assert!( + m.responses[0] + .text(&["calendar-data"]) + .unwrap() + .contains("A & B") + ); + assert!(!m.responses[0].has(&["getctag"]), "404 propstat ignored"); + assert!(m.responses[1].is_removed()); + } +} diff --git a/crates/synapse-caldav/tests/mock.rs b/crates/synapse-caldav/tests/mock.rs new file mode 100644 index 0000000..bac9119 --- /dev/null +++ b/crates/synapse-caldav/tests/mock.rs @@ -0,0 +1,398 @@ +//! A tiny in-process CalDAV server (just enough of RFC 4791/6578 for the client). +#![allow(dead_code)] + +use std::collections::BTreeMap; +use std::sync::{Arc, Mutex}; +use tokio::io::{AsyncReadExt, AsyncWriteExt}; +use tokio::net::TcpListener; + +pub const HOME: &str = "/dav/calendars/user/"; +pub const PERSONAL: &str = "/dav/calendars/user/personal/"; +pub const TASKS: &str = "/dav/calendars/user/tasks/"; + +#[derive(Default)] +pub struct State { + pub objects: BTreeMap, // path -> (etag, body) + pub rev: u64, + log: Vec<(u64, String, bool)>, // rev, path, deleted + pub support_sync: bool, + pub requests: Vec, + pub puts: Vec<(String, Option)>, // path, if-match +} + +#[derive(Clone)] +pub struct Mock { + pub state: Arc>, + pub base: String, +} + +impl Mock { + pub async fn start() -> Mock { + let l = TcpListener::bind("127.0.0.1:0").await.unwrap(); + let base = format!("http://{}", l.local_addr().unwrap()); + let state = Arc::new(Mutex::new(State { + support_sync: true, + ..Default::default() + })); + let st = state.clone(); + tokio::spawn(async move { + loop { + let Ok((mut sock, _)) = l.accept().await else { + break; + }; + let st = st.clone(); + tokio::spawn(async move { + if let Some(req) = read_request(&mut sock).await { + let resp = handle(&st, req); + let _ = sock.write_all(resp.as_bytes()).await; + let _ = sock.shutdown().await; + } + }); + } + }); + Mock { state, base } + } + + /// Server-side write (as another client would do). Returns the new etag. + pub fn set(&self, path: &str, body: &str) -> String { + let mut s = self.state.lock().unwrap(); + put(&mut s, path, body) + } + + pub fn remove(&self, path: &str) { + let mut s = self.state.lock().unwrap(); + s.objects.remove(path); + s.rev += 1; + let r = s.rev; + s.log.push((r, path.to_string(), true)); + } + + pub fn body(&self, path: &str) -> Option { + self.state + .lock() + .unwrap() + .objects + .get(path) + .map(|o| o.1.clone()) + } + + pub fn paths(&self, dir: &str) -> Vec { + self.state + .lock() + .unwrap() + .objects + .keys() + .filter(|p| p.starts_with(dir)) + .cloned() + .collect() + } + + pub fn disable_sync_collection(&self) { + self.state.lock().unwrap().support_sync = false; + } + + pub fn count_requests(&self, needle: &str) -> usize { + self.state + .lock() + .unwrap() + .requests + .iter() + .filter(|r| r.contains(needle)) + .count() + } +} + +fn put(s: &mut State, path: &str, body: &str) -> String { + s.rev += 1; + let etag = format!("\"e{}\"", s.rev); + s.objects + .insert(path.to_string(), (etag.clone(), body.to_string())); + let r = s.rev; + s.log.push((r, path.to_string(), false)); + etag +} + +struct Req { + method: String, + path: String, + headers: BTreeMap, + body: String, +} + +async fn read_request(sock: &mut tokio::net::TcpStream) -> Option { + let mut buf = Vec::new(); + let mut tmp = [0u8; 4096]; + let head_end = loop { + let n = sock.read(&mut tmp).await.ok()?; + if n == 0 { + return None; + } + buf.extend_from_slice(&tmp[..n]); + if let Some(i) = buf.windows(4).position(|w| w == b"\r\n\r\n") { + break i + 4; + } + }; + let head = String::from_utf8_lossy(&buf[..head_end]).to_string(); + let mut lines = head.lines(); + let first = lines.next()?; + let mut parts = first.split_whitespace(); + let (method, path) = (parts.next()?.to_string(), parts.next()?.to_string()); + let headers: BTreeMap = lines + .filter_map(|l| { + l.split_once(':') + .map(|(k, v)| (k.trim().to_lowercase(), v.trim().to_string())) + }) + .collect(); + let len: usize = headers + .get("content-length") + .and_then(|v| v.parse().ok()) + .unwrap_or(0); + while buf.len() < head_end + len { + let n = sock.read(&mut tmp).await.ok()?; + if n == 0 { + break; + } + buf.extend_from_slice(&tmp[..n]); + } + let body = String::from_utf8_lossy(&buf[head_end..]).to_string(); + Some(Req { + method, + path, + headers, + body, + }) +} + +fn http(status: &str, headers: &[(&str, String)], body: &str) -> String { + let mut s = format!( + "HTTP/1.1 {status}\r\nContent-Length: {}\r\nConnection: close\r\n", + body.len() + ); + for (k, v) in headers { + s.push_str(&format!("{k}: {v}\r\n")); + } + s.push_str("\r\n"); + s.push_str(body); + s +} + +fn xml_escape(s: &str) -> String { + s.replace('&', "&") + .replace('<', "<") + .replace('>', ">") +} + +fn multistatus(inner: &str) -> String { + let body = format!( + r#"{inner}"# + ); + http( + "207 Multi-Status", + &[("Content-Type", "application/xml".into())], + &body, + ) +} + +fn prop_response(href: &str, props: &str) -> String { + format!( + "{href}{props}HTTP/1.1 200 OK" + ) +} + +fn ctag(s: &State, dir: &str) -> String { + // Per-collection ctag: highest revision touching the collection. + let r = s + .log + .iter() + .filter(|(_, p, _)| p.starts_with(dir)) + .map(|(r, _, _)| *r) + .max() + .unwrap_or(0); + format!("ctag-{r}") +} + +fn calendar_props(s: &State, dir: &str, name: &str, comps: &[&str]) -> String { + let comps: String = comps + .iter() + .map(|c| format!(r#""#)) + .collect(); + format!( + "{name}{comps}{}", + ctag(s, dir) + ) +} + +fn hrefs_in(body: &str) -> Vec { + let mut out = Vec::new(); + let mut rest = body; + while let Some(i) = rest.find("") { + let after = &rest[i + 8..]; + let Some(j) = after.find("") else { + break; + }; + out.push(after[..j].replace("&", "&")); + rest = &after[j..]; + } + out +} + +fn handle(st: &Arc>, req: Req) -> String { + let mut s = st.lock().unwrap(); + s.requests.push(format!("{} {}", req.method, req.path)); + if !req + .headers + .get("authorization") + .is_some_and(|a| a.starts_with("Basic ")) + { + return http( + "401 Unauthorized", + &[("WWW-Authenticate", "Basic realm=\"mock\"".into())], + "", + ); + } + let (m, p, b) = (req.method.as_str(), req.path.as_str(), req.body.as_str()); + match (m, p) { + ("PROPFIND", "/.well-known/caldav") => { + http("301 Moved Permanently", &[("Location", "/dav/".into())], "") + } + ("PROPFIND", "/dav/") => multistatus(&prop_response( + "/dav/", + "/dav/principals/user/", + )), + ("PROPFIND", "/dav/principals/user/") => multistatus(&prop_response( + p, + &format!("{HOME}"), + )), + ("PROPFIND", HOME) => { + let mut inner = prop_response(HOME, ""); + inner += &prop_response( + PERSONAL, + &calendar_props(&s, PERSONAL, "Personal", &["VEVENT", "VTODO"]), + ); + inner += &prop_response(TASKS, &calendar_props(&s, TASKS, "Tasks", &["VTODO"])); + multistatus(&inner) + } + ("PROPFIND", cal) if cal == PERSONAL || cal == TASKS => { + if b.contains("getctag") { + multistatus(&prop_response( + cal, + &format!("{}", ctag(&s, cal)), + )) + } else { + let mut inner = + prop_response(cal, ""); + for (path, (etag, _)) in s.objects.iter().filter(|(k, _)| k.starts_with(cal)) { + inner += &prop_response( + path, + &format!("{}", xml_escape(etag)), + ); + } + multistatus(&inner) + } + } + ("REPORT", cal) if b.contains("sync-collection") => { + if !s.support_sync { + return http("501 Not Implemented", &[], ""); + } + let since: u64 = b + .split("") + .nth(1) + .and_then(|t| t.split("").next()) + .and_then(|t| t.strip_prefix("tok-")) + .and_then(|t| t.parse().ok()) + .unwrap_or(0); + let mut latest: BTreeMap<&String, bool> = BTreeMap::new(); + for (r, path, deleted) in &s.log { + if *r > since && path.starts_with(cal) { + latest.insert(path, *deleted); + } + } + let mut inner = String::new(); + for (path, deleted) in latest { + if deleted { + inner += &format!( + "{path}HTTP/1.1 404 Not Found" + ); + } else if let Some((etag, _)) = s.objects.get(path) { + inner += &prop_response( + path, + &format!("{}", xml_escape(etag)), + ); + } + } + inner += &format!("tok-{}", s.rev); + multistatus(&inner) + } + ("REPORT", _) if b.contains("calendar-multiget") => { + let mut inner = String::new(); + for h in hrefs_in(b) { + if let Some((etag, body)) = s.objects.get(&h) { + inner += &prop_response( + &h, + &format!( + "{}{}", + xml_escape(etag), + xml_escape(body) + ), + ); + } + } + multistatus(&inner) + } + ("GET", path) => match s.objects.get(path) { + Some((etag, body)) => http( + "200 OK", + &[ + ("ETag", etag.clone()), + ("Content-Type", "text/calendar".into()), + ], + body, + ), + None => http("404 Not Found", &[], ""), + }, + ("PUT", path) => { + let if_match = req.headers.get("if-match").cloned(); + s.puts.push((path.to_string(), if_match.clone())); + let current = s.objects.get(path).map(|o| o.0.clone()); + let ok = match ( + &if_match, + req.headers.get("if-none-match").map(String::as_str), + ¤t, + ) { + (Some(m), _, Some(c)) => m == c, + (Some(_), _, None) => false, + (None, Some("*"), Some(_)) => false, + _ => true, + }; + if !ok { + return http("412 Precondition Failed", &[], ""); + } + let etag = put(&mut s, path, b); + http( + if current.is_some() { + "204 No Content" + } else { + "201 Created" + }, + &[("ETag", etag)], + "", + ) + } + ("DELETE", path) => { + if let (Some(m), Some((c, _))) = (req.headers.get("if-match"), s.objects.get(path)) + && m != c + { + return http("412 Precondition Failed", &[], ""); + } + if s.objects.remove(path).is_some() { + s.rev += 1; + let r = s.rev; + s.log.push((r, path.to_string(), true)); + http("204 No Content", &[], "") + } else { + http("404 Not Found", &[], "") + } + } + _ => http("404 Not Found", &[], ""), + } +} diff --git a/crates/synapse-caldav/tests/sync.rs b/crates/synapse-caldav/tests/sync.rs new file mode 100644 index 0000000..d6f0590 --- /dev/null +++ b/crates/synapse-caldav/tests/sync.rs @@ -0,0 +1,367 @@ +mod mock; + +use chrono::NaiveDate; +use chrono_tz::Europe::Madrid; +use mock::{HOME, Mock, PERSONAL, TASKS}; +use synapse_caldav::{ + Config, Credentials, DavClient, events_for_day, materialize_day, refresh_calendars, sync, +}; +use synapse_core::{Graph, Placement}; + +fn day(y: i32, m: u32, d: u32) -> NaiveDate { + NaiveDate::from_ymd_opt(y, m, d).unwrap() +} + +fn ms(y: i32, m: u32, d: u32, h: u32) -> i64 { + day(y, m, d) + .and_hms_opt(h, 0, 0) + .unwrap() + .and_utc() + .timestamp_millis() +} + +fn client(m: &Mock) -> DavClient { + DavClient::new( + &m.base, + Credentials { + username: "u".into(), + password: "app-pw".into(), + }, + ) + .unwrap() +} + +fn graph() -> (tempfile::TempDir, Graph) { + let dir = tempfile::tempdir().unwrap(); + let g = Graph::open(dir.path()).unwrap(); + g.set_now(Some(ms(2026, 10, 21, 9))); + (dir, g) +} + +fn vtodo(uid: &str, body: &str) -> String { + format!( + "BEGIN:VCALENDAR\r\nVERSION:2.0\r\nPRODID:-//Other//EN\r\nBEGIN:VTODO\r\nUID:{uid}\r\n{body}END:VTODO\r\nEND:VCALENDAR\r\n" + ) +} + +fn page_blocks(g: &Graph, title: &str) -> Vec<(usize, synapse_core::Block)> { + let p = g.page_by_title(title).unwrap().unwrap(); + g.page_tree(p.id).unwrap() +} + +const STANDUP: &str = "BEGIN:VCALENDAR\r\nVERSION:2.0\r\nBEGIN:VEVENT\r\nUID:standup\r\nSUMMARY:Standup\r\nDTSTART;TZID=Europe/Madrid:20261007T100000\r\nDTEND;TZID=Europe/Madrid:20261007T103000\r\nRRULE:FREQ=WEEKLY;BYDAY=WE\r\nEND:VEVENT\r\nBEGIN:VEVENT\r\nUID:dentist\r\nSUMMARY:Dentist\r\nDTSTART;TZID=Europe/Madrid:20261021T170000\r\nDURATION:PT45M\r\nEND:VEVENT\r\nEND:VCALENDAR\r\n"; + +#[tokio::test] +async fn discovery_and_calendar_listing() { + let m = Mock::start().await; + let (_d, g) = graph(); + let c = client(&m); + let cals = refresh_calendars(&g, &c).await.unwrap(); + assert_eq!(cals.len(), 2); + let tasks = cals.iter().find(|c| c.href == TASKS).unwrap(); + assert!(tasks.supports_tasks && !tasks.supports_events); + let personal = cals.iter().find(|c| c.href == PERSONAL).unwrap(); + assert!(personal.supports_events && personal.supports_tasks); + assert!(m.count_requests("PROPFIND /.well-known/caldav") >= 1); + assert_eq!(c.discover().await.unwrap(), HOME); +} + +#[tokio::test] +async fn events_recurrence_and_journal_materialisation() { + let m = Mock::start().await; + m.set(&format!("{PERSONAL}standup.ics"), STANDUP); + let (_d, g) = graph(); + let cfg = Config::new(Madrid); + let rep = sync(&g, &client(&m), &cfg).await.unwrap(); + assert_eq!(rep.events_changed, 1); + + // 2026-10-21 is a Wednesday: the weekly standup and the dentist. + let evs = events_for_day(&g, day(2026, 10, 21), Madrid).unwrap(); + let names: Vec<_> = evs.iter().map(|e| e.summary.as_str()).collect(); + assert_eq!(names, ["Standup", "Dentist"]); + assert!(evs[0].recurring && !evs[1].recurring); + assert_eq!(evs[1].end - evs[1].start, chrono::Duration::minutes(45)); + assert!( + events_for_day(&g, day(2026, 10, 22), Madrid) + .unwrap() + .is_empty() + ); + assert_eq!( + events_for_day(&g, day(2026, 10, 28), Madrid).unwrap().len(), + 1 + ); + + let ids = materialize_day(&g, day(2026, 10, 21), Madrid).unwrap(); + assert_eq!(ids.len(), 2); + let j = g.journal(day(2026, 10, 21)).unwrap(); + let tree = g.page_tree(j.id).unwrap(); + assert_eq!(tree[0].1.content, "10:00-10:30 [[Standup]]"); + assert_eq!(tree[1].1.content, "17:00-17:45 Dentist"); + // The recurring meeting got its own page (via the [[link]]), the one-off did not. + assert!(g.page_by_title("Standup").unwrap().is_some()); + assert!(g.page_by_title("Dentist").unwrap().is_none()); + // Idempotent. + assert_eq!(materialize_day(&g, day(2026, 10, 21), Madrid).unwrap(), ids); + assert_eq!(g.page_tree(j.id).unwrap().len(), 2); + + // Dentist cancelled remotely: the next sync + materialise removes its block only. + m.remove(&format!("{PERSONAL}standup.ics")); + m.set( + &format!("{PERSONAL}standup.ics"), + &STANDUP.replace("UID:dentist", "UID:dentist\r\nSTATUS:CANCELLED"), + ); + sync(&g, &client(&m), &cfg).await.unwrap(); + materialize_day(&g, day(2026, 10, 21), Madrid).unwrap(); + let tree = g.page_tree(j.id).unwrap(); + assert_eq!(tree.len(), 1); + assert_eq!(tree[0].1.content, "10:00-10:30 [[Standup]]"); +} + +#[tokio::test] +async fn task_round_trip_both_directions() { + let m = Mock::start().await; + let path = format!("{TASKS}milk.ics"); + m.set(&path, &vtodo("milk", "SUMMARY:Buy milk\r\nPRIORITY:1\r\nDUE;VALUE=DATE:20261025\r\nX-KEEP:me\r\nLAST-MODIFIED:20261020T080000Z\r\n")); + let (_d, g) = graph(); + let cfg = Config::new(Madrid); + let c = client(&m); + + // Remote -> local. + let rep = sync(&g, &c, &cfg).await.unwrap(); + assert_eq!(rep.tasks_pulled, 1); + let blocks = page_blocks(&g, "Tasks"); + assert_eq!(blocks.len(), 1); + let b = &blocks[0].1; + assert_eq!(b.content, "TODO [#A] Buy milk\nDEADLINE: <2026-10-25 Sun>"); + assert_eq!(b.properties["caldav-uid"], "milk"); + assert_eq!(b.properties["caldav-calendar"], TASKS); + + // Local completion -> remote. + g.set_now(Some(ms(2026, 10, 21, 10))); + g.update_block(b.id, "DONE [#A] Buy milk\nDEADLINE: <2026-10-25 Sun>") + .unwrap(); + let rep = sync(&g, &c, &cfg).await.unwrap(); + assert_eq!(rep.tasks_updated_remote, 1); + let remote = m.body(&path).unwrap(); + assert!( + remote.contains("STATUS:COMPLETED") && remote.contains("PERCENT-COMPLETE:100"), + "{remote}" + ); + assert!(remote.contains("COMPLETED:20261021T100000Z"), "{remote}"); + assert!( + remote.contains("X-KEEP:me"), + "unknown properties survive: {remote}" + ); + // The PUT was conditional on the etag we had. + assert!( + m.state + .lock() + .unwrap() + .puts + .iter() + .any(|(p, im)| p == &path && im.is_some()) + ); + // No echo: another sync changes nothing. + let rep = sync(&g, &c, &cfg).await.unwrap(); + assert_eq!((rep.tasks_updated_remote, rep.conflicts), (0, 0)); + + // Remote reopens it as in-process -> local DOING. + let reopened = remote + .replace("STATUS:COMPLETED", "STATUS:IN-PROCESS") + .replace("PERCENT-COMPLETE:100", "PERCENT-COMPLETE:30") + .replace("COMPLETED:20261021T100000Z\r\n", ""); + m.set(&path, &reopened); + sync(&g, &c, &cfg).await.unwrap(); + let b = g.get_block(b.id).unwrap().unwrap(); + assert_eq!(b.content, "DOING [#A] Buy milk\nDEADLINE: <2026-10-25 Sun>"); +} + +#[tokio::test] +async fn new_journal_task_goes_to_default_list_and_completes_remotely() { + let m = Mock::start().await; + m.set(&format!("{PERSONAL}standup.ics"), STANDUP); // gives the account an events-only-ish calendar + let (_d, g) = graph(); + let mut cfg = Config::new(Madrid); + cfg.default_task_calendar = Some(TASKS.into()); + let c = client(&m); + sync(&g, &c, &cfg).await.unwrap(); // establishes "enabled_at" + + let j = g.today_journal().unwrap(); + let plain = g + .insert_block(j.id, Placement::LastChildOf(None), "just a note") + .unwrap(); + let t = g + .insert_block( + j.id, + Placement::LastChildOf(None), + "LATER [#B] Call the bank\nSCHEDULED: <2026-10-22 Thu 09:30>", + ) + .unwrap(); + let rep = sync(&g, &c, &cfg).await.unwrap(); + assert_eq!(rep.tasks_created_remote, 1); + let paths = m.paths(TASKS); + assert_eq!(paths.len(), 1); + let body = m.body(&paths[0]).unwrap(); + assert!( + body.contains("SUMMARY:Call the bank") && body.contains("PRIORITY:5"), + "{body}" + ); + assert!( + body.contains("DTSTART;TZID=Europe/Madrid:20261022T093000"), + "{body}" + ); + assert!( + g.get_block(plain.id) + .unwrap() + .unwrap() + .properties + .is_empty() + ); + let t = g.get_block(t.id).unwrap().unwrap(); + assert!(t.properties.contains_key("caldav-uid")); + assert_eq!( + t.content, "LATER [#B] Call the bank\nSCHEDULED: <2026-10-22 Thu 09:30>", + "content untouched" + ); + + // Completed in another app -> DONE here; LATER spelling kept only for open states. + m.set( + &paths[0], + &body.replace("STATUS:NEEDS-ACTION", "STATUS:COMPLETED"), + ); + sync(&g, &c, &cfg).await.unwrap(); + let t = g.get_block(t.id).unwrap().unwrap(); + assert!( + t.content.starts_with("DONE [#B] Call the bank"), + "{}", + t.content + ); +} + +#[tokio::test] +async fn conflict_last_modified_wins_and_loser_kept_as_child() { + let m = Mock::start().await; + let path = format!("{TASKS}t.ics"); + m.set( + &path, + &vtodo( + "t", + "SUMMARY:Plan trip\r\nLAST-MODIFIED:20261021T080000Z\r\n", + ), + ); + let (_d, g) = graph(); + let cfg = Config::new(Madrid); + let c = client(&m); + sync(&g, &c, &cfg).await.unwrap(); + let b = page_blocks(&g, "Tasks")[0].1.clone(); + + // Case 1: remote edited later (11:00) than the local edit (10:00): remote wins. + g.set_now(Some(ms(2026, 10, 21, 10))); + g.update_block(b.id, "TODO Plan trip to Rome").unwrap(); + m.set( + &path, + &vtodo( + "t", + "SUMMARY:Plan trip to Paris\r\nLAST-MODIFIED:20261021T110000Z\r\n", + ), + ); + g.set_now(Some(ms(2026, 10, 21, 12))); + let rep = sync(&g, &c, &cfg).await.unwrap(); + assert_eq!(rep.conflicts, 1); + let tree = page_blocks(&g, "Tasks"); + assert_eq!(tree[0].1.content, "TODO Plan trip to Paris"); + assert_eq!(tree[1].0, 1); + assert!(tree[1].1.content.contains("local") && tree[1].1.content.contains("Plan trip to Rome")); + + // Case 2: local edited later (14:00) than the remote (13:00): local wins and is pushed. + m.set( + &path, + &vtodo( + "t", + "SUMMARY:Plan trip to Oslo\r\nLAST-MODIFIED:20261021T130000Z\r\n", + ), + ); + g.set_now(Some(ms(2026, 10, 21, 14))); + g.update_block(b.id, "TODO Plan trip to Lima").unwrap(); + g.set_now(Some(ms(2026, 10, 21, 15))); + let rep = sync(&g, &c, &cfg).await.unwrap(); + assert_eq!(rep.conflicts, 1); + assert_eq!( + g.get_block(b.id).unwrap().unwrap().content, + "TODO Plan trip to Lima" + ); + assert!(m.body(&path).unwrap().contains("SUMMARY:Plan trip to Lima")); + let tree = page_blocks(&g, "Tasks"); + assert!( + tree.iter() + .any(|(d, x)| *d == 1 && x.content.contains("remote") && x.content.contains("Oslo")) + ); +} + +#[tokio::test] +async fn stale_etag_on_push_refetches_and_retries() { + let m = Mock::start().await; + let path = format!("{TASKS}r.ics"); + m.set( + &path, + &vtodo("r", "SUMMARY:Race\r\nLAST-MODIFIED:20261021T080000Z\r\n"), + ); + let (_d, g) = graph(); + let cfg = Config::new(Madrid); + let c = client(&m); + sync(&g, &c, &cfg).await.unwrap(); + let b = page_blocks(&g, "Tasks")[0].1.clone(); + g.set_now(Some(ms(2026, 10, 21, 10))); + g.update_block(b.id, "TODO Race local").unwrap(); + // Our cached etag is out of date although the pull sees no change since its token. + g.conn() + .execute("UPDATE caldav_object SET etag='\"stale\"'", []) + .unwrap(); + let rep = sync(&g, &c, &cfg).await.unwrap(); + assert_eq!(rep.conflicts, 1); + assert_eq!(rep.tasks_updated_remote, 1); + assert!(m.body(&path).unwrap().contains("SUMMARY:Race local")); + let puts = m.state.lock().unwrap().puts.clone(); + assert_eq!( + puts.len(), + 2, + "first PUT rejected with 412, second accepted: {puts:?}" + ); +} + +#[tokio::test] +async fn deletions_both_ways_and_ctag_fallback() { + let m = Mock::start().await; + m.disable_sync_collection(); + m.set(&format!("{TASKS}a.ics"), &vtodo("a", "SUMMARY:Alpha\r\n")); + m.set(&format!("{TASKS}b.ics"), &vtodo("b", "SUMMARY:Beta\r\n")); + let (_d, g) = graph(); + let cfg = Config::new(Madrid); + let c = client(&m); + sync(&g, &c, &cfg).await.unwrap(); + assert_eq!(page_blocks(&g, "Tasks").len(), 2); + assert_eq!( + m.count_requests("REPORT"), + 3, + "two refused sync-collections + one multiget" + ); + + // Unchanged ctag: the second sync lists nothing. + let before = m.count_requests("depth"); + sync(&g, &c, &cfg).await.unwrap(); + assert_eq!(m.count_requests("depth"), before); + + // Remote delete of Alpha -> block gone; local delete of Beta -> remote gone. + m.remove(&format!("{TASKS}a.ics")); + let beta = page_blocks(&g, "Tasks") + .into_iter() + .find(|(_, b)| b.content.contains("Beta")) + .unwrap() + .1; + g.delete_block(beta.id).unwrap(); + let rep = sync(&g, &c, &cfg).await.unwrap(); + assert_eq!(rep.removed_remote, 1); + assert_eq!(rep.tasks_deleted_remote, 1); + assert!(page_blocks(&g, "Tasks").is_empty()); + assert!(m.paths(TASKS).is_empty()); +} diff --git a/docs/caldav.md b/docs/caldav.md new file mode 100644 index 0000000..d569cb6 --- /dev/null +++ b/docs/caldav.md @@ -0,0 +1,65 @@ +# CalDAV (`synapse-caldav`) + +Two-way sync of CalDAV calendars (VEVENT) and task lists (VTODO) with a Synapse graph. + +## Usage +```rust +let client = DavClient::new("https://cloud.example.com", Credentials { username, password })?; +let cfg = Config::new(chrono_tz::Europe::Madrid); // viewer zone; optional default task list +let report = synapse_caldav::sync(&graph, &client, &cfg).await?; // pull, then push +let events = events_for_day(&graph, date, cfg.tz)?; // from the local cache +materialize_day(&graph, date, cfg.tz)?; // optional: events as journal blocks +``` +Credentials (use an app password on Nextcloud) are passed by the caller and never stored. +The futures hold `&Graph` across awaits and are therefore not `Send`: run them with `block_on` +on a dedicated thread. + +## Protocol +Discovery: `/.well-known/caldav` → `current-user-principal` → `calendar-home-set`. Changes come +from `sync-collection` (RFC 6578); servers without it (or rejecting the token) fall back to +ctag + etag listing. Changed objects are fetched with `calendar-multiget`; writes are `PUT` +with `If-Match` (or `If-None-Match: *` for creation) and `DELETE` with `If-Match`. TLS is +rustls with the bundled webpki roots (self-signed servers are not supported yet). + +## Mapping +| Logseq block | VTODO | +|---|---| +| `TODO`/`LATER` | `STATUS:NEEDS-ACTION` | +| `DOING`/`NOW` | `IN-PROCESS` | +| `DONE` | `COMPLETED` + `PERCENT-COMPLETE:100` + `COMPLETED` | +| `CANCELED` | `CANCELLED` | +| `[#A]`/`[#B]`/`[#C]` | `PRIORITY` 1/5/9 (read back: 1–4 A, 5 B, 6–9 C) | +| `SCHEDULED: <2026-10-21 Wed [14:00]>` | `DTSTART` (date, or zoned time in `Config::tz`) | +| `DEADLINE: <…>` | `DUE` | +| other lines | `DESCRIPTION` | + +Block properties: `caldav-uid::`, `caldav-calendar::` (list href). Unknown VTODO properties are +preserved on write-back (the last server copy is cached and edited in place). Remote tasks with +no block yet are created on a page named after the task list. + +New tasks: a block in a **journal** that starts with a marker (not `DONE`/`CANCELED`), has no +`caldav-uid`, and was edited after the first sync is created in the default task list +(`Config::default_task_calendar`, else the first list supporting VTODO). Older journals are +never scanned, so imported history is not uploaded. + +## Events +Events live only in the cache (`caldav_object.ics`). `events_for_day` / `events_between` expand +`RRULE`/`EXDATE`/`RECURRENCE-ID` overrides, convert zones (`TZID`, UTC, floating, all-day) to the +viewer zone and skip `CANCELLED`. `materialize_day` writes `10:00-10:30 [[Standup]]` blocks in +that day's journal (property `caldav-event`); recurring meetings link to a page named after +the summary. It is idempotent, refreshes unedited blocks and removes blocks of vanished events. +Event blocks are not pushed back. + +## Conflicts +If a task changed on both sides since the last sync, the newer one wins (remote +`LAST-MODIFIED`/`DTSTAMP` vs block `updated_at`); the loser is kept as a child block +(`CalDAV conflict: … version (older, kept as note)`). A 412 on push triggers a re-fetch, the same +resolution and one retry. Delete vs edit: the edit wins (the block is detached and re-pushed). + +## Tables (graph DB) +`caldav_meta`, `caldav_calendar` (ctag, sync token), `caldav_object` (href, uid, etag, last +server ICS, block id, last synced content), `caldav_event_block`. + +## Not done yet +Pushing event edits, RRULE-aware completion of recurring tasks (the whole VTODO is completed), +custom CA certificates, multiple accounts, VALARM, attendees.