BlueGit

ict rusty-teams

Files

rusty-teams / crates / chatsvc / src / ical / write.rs

write.rs

write.rs 8.4 KiB Download Raw
1use chrono::{DateTime, Utc};
2
3use crate::calendar::Repeat;
4use crate::google_calendar::rrule_for_repeat;
5
6#[derive(Debug, Clone)]
7pub struct CalDavEventDraft {
8 pub uid: String,
9 pub summary: String,
10 pub start: DateTime<Utc>,
11 pub end: DateTime<Utc>,
12 pub all_day: bool,
13 pub description: Option<String>,
14 pub location: Option<String>,
15 pub join_url: Option<String>,
16 pub attendees: Vec<String>,
17 pub repeat: Repeat,
18 pub sequence: u32,
19}
20
21/// Build a VCALENDAR 2.0 document containing one VEVENT (no METHOD).
22pub fn build_vevent(draft: &CalDavEventDraft, stamp: DateTime<Utc>) -> String {
23 let mut lines = vec![
24 "BEGIN:VCALENDAR".to_owned(),
25 "VERSION:2.0".to_owned(),
26 "PRODID:-//rusty-teams//CalDAV//EN".to_owned(),
27 "CALSCALE:GREGORIAN".to_owned(),
28 "BEGIN:VEVENT".to_owned(),
29 format!("UID:{}", draft.uid),
30 format!("DTSTAMP:{}", format_utc(stamp)),
31 format!("SEQUENCE:{}", draft.sequence),
32 format!("SUMMARY:{}", escape(&draft.summary)),
33 ];
34 if draft.all_day {
35 lines.push(format!(
36 "DTSTART;VALUE=DATE:{}",
37 draft.start.format("%Y%m%d")
38 ));
39 lines.push(format!("DTEND;VALUE=DATE:{}", draft.end.format("%Y%m%d")));
40 } else {
41 lines.push(format!("DTSTART:{}", format_utc(draft.start)));
42 lines.push(format!("DTEND:{}", format_utc(draft.end)));
43 }
44 let mut description = draft.description.clone().unwrap_or_default();
45 if let Some(join) = &draft.join_url {
46 if !description.is_empty() {
47 description.push_str("\n\n");
48 }
49 description.push_str(join);
50 lines.push(format!("URL:{join}"));
51 }
52 if !description.is_empty() {
53 lines.push(format!("DESCRIPTION:{}", escape(&description)));
54 }
55 if let Some(location) = &draft.location {
56 lines.push(format!("LOCATION:{}", escape(location)));
57 }
58 if let Some(rrule) = rrule_for_repeat(draft.repeat, draft.start.naive_utc()) {
59 let rule = rrule.trim_start_matches("RRULE:");
60 lines.push(format!("RRULE:{rule}"));
61 }
62 for attendee in &draft.attendees {
63 lines.push(format!("ATTENDEE:mailto:{attendee}"));
64 }
65 lines.push("END:VEVENT".to_owned());
66 lines.push("END:VCALENDAR".to_owned());
67 lines.join("\r\n") + "\r\n"
68}
69
70/// Add EXDATE for one occurrence on the series master and bump SEQUENCE.
71/// Leaves overrides and other VEVENT blocks untouched.
72pub fn exclude_occurrence_from_ics(ics: &str, occurrence: DateTime<Utc>) -> Result<String, String> {
73 let mut out = Vec::new();
74 let mut in_event = false;
75 let mut is_master = false;
76 let mut event_lines: Vec<String> = Vec::new();
77 let mut patched = false;
78
79 for raw in ics.lines() {
80 let line = raw.trim_end_matches('\r').to_owned();
81 let upper = line.to_ascii_uppercase();
82 if upper == "BEGIN:VEVENT" {
83 in_event = true;
84 is_master = false;
85 event_lines = vec![line];
86 continue;
87 }
88 if !in_event {
89 out.push(line);
90 continue;
91 }
92 if upper == "END:VEVENT" {
93 event_lines.push(line);
94 if is_master {
95 out.extend(patch_master_exdate(event_lines, occurrence)?);
96 patched = true;
97 } else {
98 out.extend(event_lines);
99 }
100 in_event = false;
101 event_lines = Vec::new();
102 continue;
103 }
104 if upper.starts_with("RRULE") || upper.starts_with("RDATE") {
105 is_master = true;
106 }
107 event_lines.push(line);
108 }
109 if !patched {
110 return Err("CalDAV series master with RRULE/RDATE not found".into());
111 }
112 Ok(out.join("\r\n") + "\r\n")
113}
114
115fn patch_master_exdate(
116 mut lines: Vec<String>,
117 occurrence: DateTime<Utc>,
118) -> Result<Vec<String>, String> {
119 let all_day = lines.iter().any(|line| {
120 let upper = line.to_ascii_uppercase();
121 upper.starts_with("DTSTART") && upper.contains("VALUE=DATE") && !upper.contains("DATE-TIME")
122 });
123 let (exdate, value) = if all_day {
124 let value = occurrence.format("%Y%m%d").to_string();
125 (format!("EXDATE;VALUE=DATE:{value}"), value)
126 } else {
127 let value = format_utc(occurrence);
128 (format!("EXDATE:{value}"), value)
129 };
130 let mut sequence_bumped = false;
131 let mut excluded = false;
132 for line in &mut lines {
133 let upper = line.to_ascii_uppercase();
134 if upper.starts_with("SEQUENCE:") {
135 let current = line.split_once(':').map(|(_, v)| v).unwrap_or("0");
136 let next = current.trim().parse::<u32>().unwrap_or(0).saturating_add(1);
137 *line = format!("SEQUENCE:{next}");
138 sequence_bumped = true;
139 }
140 if upper.starts_with("EXDATE")
141 && line
142 .split_once(':')
143 .is_some_and(|(_, values)| values.split(',').any(|item| item == value))
144 {
145 excluded = true;
146 }
147 }
148 if !sequence_bumped {
149 let at = lines
150 .iter()
151 .position(|l| l.to_ascii_uppercase().starts_with("UID:"))
152 .map_or(1, |idx| idx + 1);
153 lines.insert(at, "SEQUENCE:1".to_owned());
154 }
155 if !excluded {
156 let Some(idx) = lines.iter().position(|l| {
157 let upper = l.to_ascii_uppercase();
158 upper.starts_with("RRULE") || upper.starts_with("RDATE")
159 }) else {
160 return Err("CalDAV series master missing RRULE/RDATE".into());
161 };
162 lines.insert(idx + 1, exdate);
163 }
164 Ok(lines)
165}
166
167fn format_utc(dt: DateTime<Utc>) -> String {
168 dt.format("%Y%m%dT%H%M%SZ").to_string()
169}
170
171fn escape(value: &str) -> String {
172 value
173 .replace('\\', "\\\\")
174 .replace('\n', "\\n")
175 .replace(',', "\\,")
176 .replace(';', "\\;")
177}
178
179#[cfg(test)]
180mod tests {
181 use super::*;
182 use chrono::TimeZone;
183
184 #[test]
185 fn builds_without_method() {
186 let ics = build_vevent(
187 &CalDavEventDraft {
188 uid: "u1".into(),
189 summary: "Meet".into(),
190 start: Utc.with_ymd_and_hms(2026, 1, 1, 10, 0, 0).unwrap(),
191 end: Utc.with_ymd_and_hms(2026, 1, 1, 11, 0, 0).unwrap(),
192 all_day: false,
193 description: None,
194 location: None,
195 join_url: Some("https://teams.microsoft.com/l/meetup-join/x".into()),
196 attendees: vec!["a@b.c".into()],
197 repeat: Repeat::Never,
198 sequence: 0,
199 },
200 Utc.with_ymd_and_hms(2026, 1, 1, 9, 0, 0).unwrap(),
201 );
202 assert!(ics.contains("BEGIN:VCALENDAR"));
203 assert!(!ics.contains("METHOD:"));
204 assert!(ics.contains("URL:https://teams.microsoft.com/l/meetup-join/x"));
205 assert!(ics.contains("ATTENDEE:mailto:a@b.c"));
206 }
207
208 #[test]
209 fn exclude_occurrence_keeps_a_zoned_exdate_and_adds_its_own_line() {
210 let ics = "BEGIN:VCALENDAR\r\nBEGIN:VEVENT\r\nUID:series\r\nDTSTART;TZID=Europe/Berlin:20260105T100000\r\nRRULE:FREQ=WEEKLY\r\nEXDATE;TZID=Europe/Berlin:20260105T100000\r\nEND:VEVENT\r\nEND:VCALENDAR\r\n";
211 let patched =
212 exclude_occurrence_from_ics(ics, Utc.with_ymd_and_hms(2026, 1, 12, 9, 0, 0).unwrap())
213 .unwrap();
214 assert!(patched.contains("EXDATE;TZID=Europe/Berlin:20260105T100000\r\n"));
215 assert!(patched.contains("EXDATE:20260112T090000Z\r\n"));
216 }
217
218 #[test]
219 fn exclude_occurrence_of_an_all_day_series_uses_a_date() {
220 let ics = "BEGIN:VCALENDAR\r\nBEGIN:VEVENT\r\nUID:series\r\nDTSTART;VALUE=DATE:20260105\r\nRRULE:FREQ=WEEKLY\r\nEND:VEVENT\r\nEND:VCALENDAR\r\n";
221 let patched =
222 exclude_occurrence_from_ics(ics, Utc.with_ymd_and_hms(2026, 1, 12, 0, 0, 0).unwrap())
223 .unwrap();
224 assert!(patched.contains("EXDATE;VALUE=DATE:20260112\r\n"));
225 }
226
227 #[test]
228 fn exclude_occurrence_adds_exdate_and_keeps_rrule() {
229 let ics = "BEGIN:VCALENDAR\r\nBEGIN:VEVENT\r\nUID:series\r\nSEQUENCE:2\r\nDTSTART:20260105T090000Z\r\nDTEND:20260105T100000Z\r\nRRULE:FREQ=WEEKLY\r\nSUMMARY:Standup\r\nEND:VEVENT\r\nEND:VCALENDAR\r\n";
230 let patched =
231 exclude_occurrence_from_ics(ics, Utc.with_ymd_and_hms(2026, 1, 12, 9, 0, 0).unwrap())
232 .unwrap();
233 assert!(patched.contains("RRULE:FREQ=WEEKLY"));
234 assert!(patched.contains("EXDATE:20260112T090000Z"));
235 assert!(patched.contains("SEQUENCE:3"));
236 }
237}