//! Busy time of calendar objects: for free-busy-query (RFC 4791, 7.10) and //! for free-busy requests to a scheduling outbox (RFC 6638, 5). use calcard::icalendar::{ ICalendar, ICalendarComponentType, ICalendarEntry, ICalendarFreeBusyType, ICalendarMethod, ICalendarParameterName, ICalendarParameterValue, ICalendarPeriod, ICalendarProperty, ICalendarStatus, ICalendarTransparency, ICalendarValue, }; use chrono::{DateTime, Utc}; use xmltree::XMLNode; use crate::expand::{expand, prop_stamp, stamp}; use crate::filter::TimeRange; use crate::itip::{Is, own_partstat}; use crate::xml::{CALDAV, Name, document, el, hrefs, with_children, with_text}; use crate::zone::{Zone, Zones, add}; /// In the order a client ranks them. #[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)] pub enum Busy { Busy, Tentative, Unavailable, } impl Busy { fn fbtype(self) -> &'static str { match self { Busy::Busy => "BUSY", Busy::Tentative => "BUSY-TENTATIVE", Busy::Unavailable => "BUSY-UNAVAILABLE", } } } #[derive(Debug, Clone, PartialEq, Eq)] pub struct Period { pub kind: Busy, pub start: DateTime, pub end: DateTime, } /// The busy periods of one calendar object, clipped to `range`. Transparent /// and cancelled events are free; VFREEBUSY components count as stored. /// /// With `me`, the calendar user's own answer counts too: an instance it /// declined is free, one it has not answered or accepted tentatively is /// tentative. pub fn busy(cal: &ICalendar, range: &TimeRange, floating: &Zone, me: Option) -> Vec { let zones = Zones::new(cal, floating.clone()); let mut out = Vec::new(); let mut push = |kind, start: DateTime, end: DateTime| { let (start, end) = (start.max(range.start), end.min(range.end)); if start < end { out.push(Period { kind, start, end }); } }; for x in expand(cal, range.clone(), floating.clone()).instances { let c = &cal.components[x.component]; if c.component_type != ICalendarComponentType::VEvent || c.transparency() == Some(&ICalendarTransparency::Transparent) { continue; } let kind = match c.status() { Some(ICalendarStatus::Cancelled) => continue, Some(ICalendarStatus::Tentative) => Busy::Tentative, _ => Busy::Busy, }; let kind = match me.and_then(|me| own_partstat(c, me)).as_deref() { Some("DECLINED") => continue, Some("NEEDS-ACTION" | "TENTATIVE") => Busy::Tentative, _ => kind, }; push(kind, x.start, x.end); } for c in cal .components .iter() .filter(|c| c.component_type == ICalendarComponentType::VFreebusy) { for e in c.properties(&ICalendarProperty::Freebusy) { let kind = match e.parameter(&ICalendarParameterName::Fbtype) { Some(ICalendarParameterValue::Fbtype(ICalendarFreeBusyType::Free)) => continue, Some(ICalendarParameterValue::Fbtype(ICalendarFreeBusyType::BusyTentative)) => { Busy::Tentative } Some(ICalendarParameterValue::Fbtype(ICalendarFreeBusyType::BusyUnavailable)) => { Busy::Unavailable } _ => Busy::Busy, }; for (s, e) in periods(&zones, e) { push(kind, s, e); } } } out } /// Sorts the periods and joins those of one kind that overlap or touch. pub fn merge(mut periods: Vec) -> Vec { periods.sort_by_key(|p| (p.kind, p.start)); let mut out: Vec = Vec::with_capacity(periods.len()); for p in periods { match out.last_mut() { Some(last) if last.kind == p.kind && p.start <= last.end => { last.end = last.end.max(p.end); } _ => out.push(p), } } out } /// The VCALENDAR a free-busy-query answers with. pub fn vfreebusy(periods: &[Period], range: &TimeRange, now: DateTime) -> String { render(periods, range, now, "", "") } /// `method` goes into the VCALENDAR and `props` into the VFREEBUSY, both as /// ready content lines. fn render( periods: &[Period], range: &TimeRange, now: DateTime, method: &str, props: &str, ) -> String { let t = |d: DateTime| d.format("%Y%m%dT%H%M%SZ").to_string(); let mut out = format!( "BEGIN:VCALENDAR\r\nVERSION:2.0\r\nPRODID:-//dovenest//pimdav//EN\r\n{method}\ BEGIN:VFREEBUSY\r\n{props}DTSTAMP:{}\r\nDTSTART:{}\r\nDTEND:{}\r\n", t(now), t(range.start), t(range.end) ); for p in periods { out.push_str(&format!( "FREEBUSY;FBTYPE={}:{}/{}\r\n", p.kind.fbtype(), t(p.start), t(p.end) )); } out.push_str("END:VFREEBUSY\r\nEND:VCALENDAR\r\n"); out } /// The PERIOD values of a FREEBUSY property. pub(crate) fn periods(zones: &Zones, e: &ICalendarEntry) -> Vec<(DateTime, DateTime)> { e.values .iter() .filter_map(|v| period(zones, e.tz_id(), v)) .collect() } pub(crate) fn period( zones: &Zones, tzid: Option<&str>, v: &ICalendarValue, ) -> Option<(DateTime, DateTime)> { match v { ICalendarValue::Period(ICalendarPeriod::Range { start, end }) => Some(( stamp(zones, start, tzid)?.utc(), stamp(zones, end, tzid)?.utc(), )), ICalendarValue::Period(ICalendarPeriod::Duration { start, duration }) => { let s = stamp(zones, start, tzid)?.utc(); Some((s, add(s, duration.to_time_delta()?))) } _ => None, } } /// A free-busy request POSTed to a scheduling outbox (RFC 6638, 5). #[derive(Debug, Clone, PartialEq)] pub struct Request { pub range: TimeRange, pub organizer: String, /// Without duplicates. pub attendees: Vec, pub uid: Option, } /// Parses an outbox POST body. `Err` names the failed precondition. pub fn request(body: &[u8]) -> Result { let invalid = || Name::new(CALDAV, "valid-scheduling-message"); let cal = std::str::from_utf8(body) .ok() .and_then(|s| ICalendar::parse(s).ok()) .ok_or_else(|| Name::new(CALDAV, "valid-calendar-data"))?; let method = cal .components .first() .and_then(|root| root.property(&ICalendarProperty::Method)?.values.first()); if !matches!( method, Some(ICalendarValue::Method(ICalendarMethod::Request)) ) { return Err(invalid()); } let mut found = cal .components .iter() .filter(|c| c.component_type == ICalendarComponentType::VFreebusy); let (Some(c), None) = (found.next(), found.next()) else { return Err(invalid()); }; let zones = Zones::new(&cal, Zone::Utc); let at = |p: &ICalendarProperty| Some(prop_stamp(&zones, c, p)?.utc()); let text = |e: &ICalendarEntry| Some(e.values.first()?.as_text()?.trim().to_string()); let (Some(start), Some(end)) = ( at(&ICalendarProperty::Dtstart), at(&ICalendarProperty::Dtend), ) else { return Err(invalid()); }; let Some(organizer) = c.property(&ICalendarProperty::Organizer).and_then(text) else { return Err(invalid()); }; let mut attendees: Vec = Vec::new(); for a in c.properties(&ICalendarProperty::Attendee).filter_map(text) { if !attendees.iter().any(|x| x.eq_ignore_ascii_case(&a)) { attendees.push(a); } } if start >= end || attendees.is_empty() { return Err(invalid()); } Ok(Request { range: start..end, organizer, attendees, uid: c.uid().map(str::to_string), }) } /// The VFREEBUSY REPLY of `attendee` to `req`. pub fn reply(periods: &[Period], req: &Request, attendee: &str, now: DateTime) -> String { // The values come from the request: no line breaks may get through. let clean = |s: &str| s.chars().filter(|c| !c.is_control()).collect::(); let fold = |line: String| crate::text::fold(&line, "\r\n"); let mut props = fold(format!("ORGANIZER:{}", clean(&req.organizer))) + &fold(format!("ATTENDEE:{}", clean(attendee))); if let Some(uid) = &req.uid { let uid = crate::text::escape_text(&clean(uid)); props.push_str(&fold(format!("UID:{uid}"))); } render(periods, &req.range, now, "METHOD:REPLY\r\n", &props) } /// The body answering an outbox POST: per recipient its address, the /// REQUEST-STATUS and the reply, if there is one. pub fn schedule_response(answers: &[(String, &str, Option)]) -> String { document(&with_children( el(CALDAV, "schedule-response"), answers.iter().map(|(to, status, data)| { let mut e = with_children( el(CALDAV, "response"), [ with_children(el(CALDAV, "recipient"), hrefs([to.as_str()])), with_text(el(CALDAV, "request-status"), *status), ], ); if let Some(d) = data { e.children.push(XMLNode::Element(with_text( el(CALDAV, "calendar-data"), d.as_str(), ))); } e }), )) }