Cotton code
451 lines · 15.3 KB · RustRaw
//! An iCalendar object (RFC 5545), read: the VEVENTs it holds, and the//! instants, durations, rules and exceptions they name.//!//! One reader for every door a calendar comes through — a CalDAV server//! (`cotton_server::caldav`), Google's recurrence lines//! (`cotton_server::google::map`), and a `.ics` file the owner imports as a//! Cotton package ([`crate::import::package_readers`]) — so an event read any//! way lands with the same times, rule and exceptions.use cotton_store::protocol::js::to_iso_string;use crate::transforms::zoned_clock::{instant_from_zoned, zoned_parts, ZonedParts};/// A DATE or DATE-TIME property: its value and the parameters that matter.#[derive(Debug, Clone, Default, PartialEq, Eq)]pub struct IcalTime {    pub value: String,    pub tzid: Option<String>,    pub is_date: bool,}/// One VEVENT, read.#[derive(Debug, Clone, Default, PartialEq, Eq)]pub struct IcalEvent {    pub uid: String,    pub recurrence_id: Option<IcalTime>,    pub status: Option<String>,    pub summary: Option<String>,    pub description: Option<String>,    pub location: Option<String>,    pub start: Option<IcalTime>,    pub end: Option<IcalTime>,    pub duration: Option<String>,    /// `RRULE:…` and `EXDATE…:…` lines, verbatim — the shape Google's    /// `recurrence` array carries.    pub recurrence: Vec<String>,    pub organizer: Option<String>,    /// (address, PARTSTAT)    pub attendees: Vec<(String, Option<String>)>,}/// One content line: name, parameters, value.pub struct Line {    pub name: String,    pub params: Vec<(String, String)>,    pub value: String,}impl Line {    pub fn param(&self, name: &str) -> Option<&str> {        self.params            .iter()            .find(|(key, _)| key.eq_ignore_ascii_case(name))            .map(|(_, value)| value.as_str())    }    pub fn time(&self) -> IcalTime {        IcalTime {            value: self.value.trim().to_string(),            tzid: self                .param("TZID")                .map(|tz| tz.trim_matches('"').to_string()),            is_date: self                .param("VALUE")                .is_some_and(|v| v.eq_ignore_ascii_case("DATE"))                || self.value.trim().len() == 8,        }    }}/// Unfold (RFC 5545 §3.1) and split into content lines.fn lines(text: &str) -> Vec<Line> {    let mut unfolded: Vec<String> = Vec::new();    for raw in text.split('\n') {        let raw = raw.strip_suffix('\r').unwrap_or(raw);        if let Some(rest) = raw.strip_prefix([' ', '\t']) {            if let Some(last) = unfolded.last_mut() {                last.push_str(rest);                continue;            }        }        if !raw.is_empty() {            unfolded.push(raw.to_string());        }    }    unfolded        .iter()        .filter_map(|line| split_line(line))        .collect()}/// `NAME;P=V;Q="a:b":value` — a colon inside a quoted parameter is not the/// separator.pub fn split_line(line: &str) -> Option<Line> {    let mut quoted = false;    let colon = line.char_indices().find_map(|(i, c)| match c {        '"' => {            quoted = !quoted;            None        }        ':' if !quoted => Some(i),        _ => None,    })?;    let (head, value) = (&line[..colon], &line[colon + 1..]);    let mut parts = head.split(';');    let name = parts.next()?.trim().to_ascii_uppercase();    let params = parts        .filter_map(|part| {            let (key, value) = part.split_once('=')?;            Some((key.trim().to_ascii_uppercase(), value.trim().to_string()))        })        .collect();    Some(Line {        name,        params,        value: value.to_string(),    })}/// TEXT values escape `\n`, `\,`, `\;` and `\\`.fn unescape(value: &str) -> String {    let mut out = String::with_capacity(value.len());    let mut chars = value.chars();    while let Some(c) = chars.next() {        if c == '\\' {            match chars.next() {                Some('n' | 'N') => out.push('\n'),                Some(other) => out.push(other),                None => {}            }        } else {            out.push(c);        }    }    out}fn mailto(value: &str) -> String {    let value = value.trim();    value        .strip_prefix("mailto:")        .or_else(|| value.strip_prefix("MAILTO:"))        .unwrap_or(value)        .to_ascii_lowercase()}/// Every VEVENT in one calendar object. VTIMEZONE blocks are skipped: a/// TZID names an IANA zone in practice, and Cotton's zone table reads it.pub fn parse(text: &str) -> Vec<IcalEvent> {    let mut out = Vec::new();    let mut current: Option<IcalEvent> = None;    let mut depth_other = 0_u32;    for line in lines(text) {        match (            line.name.as_str(),            line.value.trim().to_ascii_uppercase().as_str(),        ) {            ("BEGIN", "VEVENT") if current.is_none() => current = Some(IcalEvent::default()),            ("END", "VEVENT") if depth_other == 0 => {                if let Some(event) = current.take() {                    if !event.uid.is_empty() {                        out.push(event);                    }                }            }            ("BEGIN", _) if current.is_some() => depth_other += 1,            ("END", _) if current.is_some() && depth_other > 0 => depth_other -= 1,            _ => {                let Some(event) = current.as_mut() else {                    continue;                };                if depth_other > 0 {                    // Inside a VALARM: its DESCRIPTION is not the event's.                    continue;                }                match line.name.as_str() {                    "UID" => event.uid = line.value.trim().to_string(),                    "RECURRENCE-ID" => event.recurrence_id = Some(line.time()),                    "STATUS" => event.status = Some(line.value.trim().to_ascii_uppercase()),                    "SUMMARY" => event.summary = Some(unescape(&line.value)),                    "DESCRIPTION" => event.description = Some(unescape(&line.value)),                    "LOCATION" => event.location = Some(unescape(&line.value)),                    "DTSTART" => event.start = Some(line.time()),                    "DTEND" => event.end = Some(line.time()),                    "DURATION" => event.duration = Some(line.value.trim().to_string()),                    "RRULE" => event                        .recurrence                        .push(format!("RRULE:{}", line.value.trim())),                    "EXDATE" => {                        let params: String = line                            .params                            .iter()                            .map(|(k, v)| format!(";{k}={v}"))                            .collect();                        event                            .recurrence                            .push(format!("EXDATE{params}:{}", line.value.trim()));                    }                    "ORGANIZER" => event.organizer = Some(mailto(&line.value)),                    "ATTENDEE" => event.attendees.push((                        mailto(&line.value),                        line.param("PARTSTAT").map(str::to_ascii_uppercase),                    )),                    _ => {}                }            }        }    }    out}/// `20261005` → `2026-10-05`.pub fn date_of(value: &str) -> Option<String> {    let v = value.get(..8)?;    v.bytes()        .all(|b| b.is_ascii_digit())        .then(|| format!("{}-{}-{}", &v[..4], &v[4..6], &v[6..8]))}/// A DATE-TIME as an ISO instant: its TZID, `Z`, else the workspace zone/// (a floating time is the reader's wall clock).pub fn instant_of(time: &IcalTime, zone: &str) -> Option<String> {    ical_instant(&time.value, false, time.tzid.as_deref().unwrap_or(zone))}/// `PT1H30M`, `P1D`, `P1W`, `-PT15M` → milliseconds.pub fn duration_ms(value: &str) -> Option<i64> {    let (sign, rest) = match value.strip_prefix('-') {        Some(rest) => (-1, rest),        None => (1, value.strip_prefix('+').unwrap_or(value)),    };    let rest = rest.strip_prefix('P')?;    let mut total = 0_i64;    let mut number = String::new();    let mut in_time = false;    for c in rest.chars() {        match c {            'T' => in_time = true,            '0'..='9' => number.push(c),            unit => {                let n: i64 = number.parse().ok()?;                number.clear();                total += n * match (unit, in_time) {                    ('W', _) => 7 * 86_400_000,                    ('D', _) => 86_400_000,                    ('H', true) => 3_600_000,                    ('M', true) => 60_000,                    ('S', true) => 1000,                    _ => return None,                };            }        }    }    Some(sign * total)}/// The bare rule Cotton stores (`"FREQ=DAILY"`), out of Google's recurrence/// list.pub fn rrule_from_recurrence(recurrence: Option<&[String]>) -> Option<String> {    let line = recurrence?        .iter()        .find(|entry| entry.len() >= 6 && entry[..6].eq_ignore_ascii_case("RRULE:"))?;    let rule = line[6..].trim();    if rule.is_empty() {        None    } else {        Some(rule.to_string())    }}/// The `EXDATE` lines of a Google recurrence → ISO instants.////// Three forms exist and all three arrive in practice:////// ```text///   EXDATE:20260923T090000Z                          — UTC///   EXDATE;TZID=Asia/Kolkata:20260904T120000         — a named zone///   EXDATE;VALUE=DATE:20260904                       — an all-day series/// ```////// One line may carry several comma-separated values. A value with no zone at/// all is read in `zone` — the WORKSPACE's, never the host's, which runs/// `TZ=UTC`: reading a floating value locally would put the cancellation hours/// away from the occurrence it is meant to remove, and the occurrence would/// come back.////// `None` when the recurrence names no EXDATE, so a master with nothing/// cancelled writes NULL rather than `[]` — the same value every row on disk/// already has.pub fn exdates_from_recurrence(recurrence: Option<&[String]>, zone: &str) -> Option<Vec<String>> {    let mut out: Vec<String> = Vec::new();    for line in recurrence.unwrap_or(&[]) {        if line.len() < 6 || !line[..6].eq_ignore_ascii_case("EXDATE") {            continue;        }        let Some(colon) = line.find(':') else {            continue;        };        let params: Vec<&str> = line[..colon].split(';').skip(1).collect();        let tzid = params            .iter()            .find(|param| param.len() >= 5 && param[..5].eq_ignore_ascii_case("TZID="))            .map(|param| param[5..].trim());        let is_date = params            .iter()            .any(|param| param.trim().eq_ignore_ascii_case("VALUE=DATE"));        for raw in line[colon + 1..].split(',') {            if let Some(instant) = ical_instant(raw.trim(), is_date, tzid.unwrap_or(zone)) {                out.push(instant);            }        }    }    if out.is_empty() {        return None;    }    // Sorted so two producers that cancelled the same two occurrences in a    // different order still write the same JSON and the row stops changing.    out.sort();    Some(out)}/// One iCal date/date-time value → an ISO instant, or `None` when it is not/// one.////// A malformed value is DROPPED rather than raised: an EXDATE is a cancellation/// and one unreadable entry from some future Google shape must not make the/// whole series unpullable.pub fn ical_instant(value: &str, is_date: bool, zone: &str) -> Option<String> {    // The TypeScript's    // `^(\d{4})(\d{2})(\d{2})(?:T(\d{2})(\d{2})(\d{2})(Z)?)?$`, read by hand:    // one regex over a fixed-width literal buys nothing a slice cannot say.    let bytes = value.as_bytes();    if bytes.len() != 8 && bytes.len() != 15 && bytes.len() != 16 {        return None;    }    if !bytes[..8].iter().all(u8::is_ascii_digit) {        return None;    }    let timed = bytes.len() > 8;    if timed {        if bytes[8] != b'T' || !bytes[9..15].iter().all(u8::is_ascii_digit) {            return None;        }        if bytes.len() == 16 && bytes[15] != b'Z' {            return None;        }    }    let number = |from: usize, len: usize| value[from..from + len].parse::<i64>().ok();    let parts = ZonedParts {        year: number(0, 4)?,        month: number(4, 2)?,        day: number(6, 2)?,        hour: if timed { number(9, 2)? } else { 0 },        minute: if timed { number(11, 2)? } else { 0 },        second: if timed { number(13, 2)? } else { 0 },    };    let zulu = bytes.len() == 16;    if is_date && !timed {        return to_iso_string(instant_from_zoned(parts, 0, zone).ok()?);    }    if zulu {        return to_iso_string(crate::transforms::zoned_clock::date_utc(            parts.year,            parts.month - 1,            parts.day,            parts.hour,            parts.minute,            parts.second,            0,        ));    }    to_iso_string(instant_from_zoned(parts, 0, zone).ok()?)}/// The title an event with none is stored under.pub const NO_TITLE: &str = "(no title)";pub const DAY_MS: i64 = 24 * 60 * 60 * 1000;pub fn calendar_date(date: &str) -> Option<(i64, i64, i64)> {    let mut parts = date.split('-');    let year: i64 = parts.next()?.parse().ok()?;    let month: i64 = parts.next()?.parse().ok()?;    let day: i64 = parts.next()?.parse().ok()?;    // `Number("")` is 0 and the TypeScript refuses a zero in any position —    // `if (!year || !month || !day)`. A missing component parses as an error    // here, which is the same refusal.    if year == 0 || month == 0 || day == 0 {        return None;    }    Some((year, month, day))}/// `"YYYY-MM-DD"` → the instant a clock in `zone` reads that date's midnight.pub fn day_start_instant(date: &str, zone: &str) -> Option<i64> {    let (year, month, day) = calendar_date(date)?;    instant_from_zoned(        ZonedParts {            year,            month,            day,            hour: 0,            minute: 0,            second: 0,        },        0,        zone,    )    .ok()}/// The instant a clock in `zone` reads 23:59:59.999 on `date`.pub fn day_end_instant(date: &str, zone: &str) -> Option<i64> {    let (year, month, day) = calendar_date(date)?;    instant_from_zoned(        ZonedParts {            year,            month,            day,            hour: 23,            minute: 59,            second: 59,        },        999,        zone,    )    .ok()}/// An instant → the `"YYYY-MM-DD"` its wall clock reads in `zone`.pub fn date_key_in(instant_ms: i64, zone: &str) -> Option<String> {    let parts = zoned_parts(instant_ms, zone).ok()?;    Some(format!(        "{:04}-{:02}-{:02}",        parts.year, parts.month, parts.day    ))}/// An all-day event's stored span: midnight of `first` in `zone`, to/// 23:59:59.999 of its last included day. `end_exclusive` is the morning/// after, as iCalendar and Google both write it; absent, the event is the one/// day.pub fn all_day_span(first: &str, end_exclusive: Option<&str>, zone: &str) -> Option<(String, String)> {    let starts_at = to_iso_string(day_start_instant(first, zone)?)?;    let last_day = match end_exclusive {        Some(end) => date_key_in(day_start_instant(end, zone)? - DAY_MS, zone)?,        None => first.to_string(),    };    Some((starts_at, to_iso_string(day_end_instant(&last_day, zone)?)?))}