bundle.rs
⎇
Raw
1//! Whole collections as one file, and one file split into objects: public
2//! feeds, export and import.
3//!
4//! Works on the text, not on parsed data, so a kept line reaches the output
5//! unchanged. Only line endings are rewritten, to CRLF.
6
7use std::collections::{HashMap, HashSet};
8
9use sha2::{Digest, Sha256};
10
11use crate::text::{
12 escape_text, logical_lines, name, param, param_parts, unescape_text, unfold, value, value_start,
13};
14
15const PRODID: &str = "PRODID:-//dovenest//pimdav//EN";
16
17/// The properties a busy-only event keeps.
18const BUSY_PROPS: [&str; 13] = [
19 "UID",
20 "DTSTAMP",
21 "DTSTART",
22 "DTEND",
23 "DURATION",
24 "RRULE",
25 "RDATE",
26 "EXDATE",
27 "EXRULE",
28 "RECURRENCE-ID",
29 "SEQUENCE",
30 "TRANSP",
31 "STATUS",
32];
33
34/// How much of a calendar a file shows.
35#[derive(Debug, Clone, Copy, PartialEq, Eq)]
36pub enum Detail {
37 /// Everything, for the owner or a borrower.
38 All,
39 /// Everything, except that an object with a private or confidential
40 /// component shows as busy time only, as Google and Nextcloud do.
41 Public,
42 /// Busy time only.
43 Busy,
44}
45
46/// One VCALENDAR with the components of every object in `objects`, each
47/// VTIMEZONE once per TZID. Subscribers are asked to poll hourly.
48pub fn calendar(objects: &[&str], name: Option<&str>, detail: Detail) -> String {
49 let mut zones = String::new();
50 let mut body = String::new();
51 let mut seen = HashSet::new();
52 for object in objects {
53 for cal in top_blocks(object, "VCALENDAR") {
54 let children = split_level(inner(&cal.lines)).1;
55 for z in children.iter().filter(|c| c.name == "VTIMEZONE") {
56 if z.prop("TZID").is_some_and(|id| seen.insert(id)) {
57 push_lines(&mut zones, &z.lines);
58 }
59 }
60 let busy = match detail {
61 Detail::All => false,
62 Detail::Busy => true,
63 Detail::Public => children.iter().any(is_private),
64 };
65 if busy {
66 let events: Vec<&Block> = children.iter().filter(|c| c.name == "VEVENT").collect();
67 push_busy(&mut body, &events);
68 } else {
69 for c in children.iter().filter(|c| c.name != "VTIMEZONE") {
70 push_lines(&mut body, &c.lines);
71 }
72 }
73 }
74 }
75 // RFC 7986's REFRESH-INTERVAL, and Outlook's own name for it.
76 let mut out = format!(
77 "BEGIN:VCALENDAR\r\nVERSION:2.0\r\n{PRODID}\r\n\
78 REFRESH-INTERVAL;VALUE=DURATION:PT1H\r\nX-PUBLISHED-TTL:PT1H\r\n"
79 );
80 // RFC 7986's NAME, and the X-WR-CALNAME most clients read instead.
81 if let Some(name) = name {
82 let name = escape_text(name);
83 out.push_str(&format!("NAME:{name}\r\nX-WR-CALNAME:{name}\r\n"));
84 }
85 out + &zones + &body + "END:VCALENDAR\r\n"
86}
87
88/// Every vCard of `objects`, one after the other.
89pub fn cards(objects: &[&str]) -> String {
90 let mut out = String::new();
91 for object in objects {
92 for card in top_blocks(object, "VCARD") {
93 push_lines(&mut out, &card.lines);
94 }
95 }
96 out
97}
98
99/// The display name and color a calendar file names for itself: RFC 7986's
100/// NAME and COLOR, or the X-WR-CALNAME and X-APPLE-CALENDAR-COLOR most
101/// exports carry instead. The color is as written; the caller checks it.
102pub fn calendar_meta(text: &str) -> (Option<String>, Option<String>) {
103 let Some(cal) = top_blocks(text, "VCALENDAR").into_iter().next() else {
104 return (None, None);
105 };
106 let first = |props: &[&str]| {
107 props
108 .iter()
109 .find_map(|p| cal.prop(p))
110 .map(|v| v.trim().to_string())
111 .filter(|v| !v.is_empty())
112 };
113 (
114 first(&["NAME", "X-WR-CALNAME"]),
115 first(&["COLOR", "X-APPLE-CALENDAR-COLOR"]),
116 )
117}
118
119/// Splits an iCalendar file into calendar object resources: one per UID,
120/// overrides with their master, each with the VTIMEZONEs it names. Keeps
121/// VERSION, PRODID and CALSCALE of the file and drops the other calendar
122/// properties, METHOD among them. A component without UID gets
123/// `new_uid(its text)`.
124pub fn split_calendar(text: &str, new_uid: &mut dyn FnMut(&str) -> String) -> Vec<String> {
125 let mut header: Option<Vec<String>> = None;
126 let mut zones: HashMap<String, String> = HashMap::new();
127 // (uid, components, TZIDs they name), in file order.
128 let mut groups: Vec<(String, String, HashSet<String>)> = Vec::new();
129 for cal in top_blocks(text, "VCALENDAR") {
130 let (props, children) = split_level(inner(&cal.lines));
131 header.get_or_insert_with(|| {
132 props
133 .iter()
134 .filter(|l| ["VERSION", "PRODID", "CALSCALE"].contains(&name(l).as_str()))
135 .map(|l| l.to_string())
136 .collect()
137 });
138 for c in children {
139 if c.name == "VTIMEZONE" {
140 if let Some(id) = c.prop("TZID") {
141 zones.entry(id).or_insert_with(|| lines_text(&c.lines));
142 }
143 continue;
144 }
145 let tzids: HashSet<String> = c
146 .lines
147 .iter()
148 .filter_map(|l| param(&unfold(l), "TZID"))
149 .collect();
150 let (uid, text) = match c.prop("UID") {
151 Some(uid) => (uid, lines_text(&c.lines)),
152 None => {
153 let uid = new_uid(&lines_text(&c.lines));
154 let mut text = String::new();
155 push_lines(&mut text, &c.lines[..1]);
156 text.push_str(&format!("UID:{uid}\r\n"));
157 push_lines(&mut text, &c.lines[1..]);
158 (uid, text)
159 }
160 };
161 match groups.iter_mut().find(|g| g.0 == uid) {
162 // A file that holds the same component twice.
163 Some(g) if g.1.contains(&text) => {}
164 Some(g) => {
165 g.1.push_str(&text);
166 g.2.extend(tzids);
167 }
168 None => groups.push((uid, text, tzids)),
169 }
170 }
171 }
172 let mut head = String::from("BEGIN:VCALENDAR\r\n");
173 let header = header.unwrap_or_default();
174 if !header.iter().any(|l| name(l) == "VERSION") {
175 head.push_str("VERSION:2.0\r\n");
176 }
177 if !header.iter().any(|l| name(l) == "PRODID") {
178 head.push_str(PRODID);
179 head.push_str("\r\n");
180 }
181 for l in &header {
182 push_lines(&mut head, &[l.as_str()]);
183 }
184 groups
185 .into_iter()
186 .map(|(_, components, tzids)| {
187 let mut out = head.clone();
188 let mut tzids: Vec<_> = tzids.into_iter().collect();
189 tzids.sort();
190 for id in tzids {
191 if let Some(z) = zones.get(&id) {
192 out.push_str(z);
193 }
194 }
195 out + &components + "END:VCALENDAR\r\n"
196 })
197 .collect()
198}
199
200/// Splits a vCard file into one text per card. A card without UID gets
201/// `new_uid(its text)`, inserted before its END line: vCard 4.0 wants
202/// VERSION right after BEGIN.
203pub fn split_cards(text: &str, new_uid: &mut dyn FnMut(&str) -> String) -> Vec<String> {
204 top_blocks(text, "VCARD")
205 .into_iter()
206 .map(|card| {
207 let text = lines_text(&card.lines);
208 if card.prop("UID").is_some() {
209 return text;
210 }
211 let (body, end) = match card.lines.split_last() {
212 Some((last, body)) if name(last) == "END" => (body, Some(*last)),
213 _ => (&card.lines[..], None),
214 };
215 let mut out = String::new();
216 push_lines(&mut out, body);
217 out.push_str(&format!("UID:{}\r\n", new_uid(&text)));
218 if let Some(end) = end {
219 push_lines(&mut out, &[end]);
220 }
221 out
222 })
223 .collect()
224}
225
226/// A component as its logical lines, BEGIN and END included.
227struct Block<'a> {
228 /// Upper case.
229 name: String,
230 lines: Vec<&'a str>,
231}
232
233impl Block<'_> {
234 /// The value of the first own property called `prop`, not one of a
235 /// nested component, unfolded and unescaped as TEXT.
236 fn prop(&self, prop: &str) -> Option<String> {
237 split_level(inner(&self.lines))
238 .0
239 .into_iter()
240 .find(|l| name(l) == prop)
241 .map(|l| unescape_text(value(&unfold(l))))
242 }
243}
244
245/// `lines` without their BEGIN and END line.
246fn inner<'a, 'b>(lines: &'b [&'a str]) -> &'b [&'a str] {
247 let start = usize::from(lines.first().is_some_and(|l| name(l) == "BEGIN"));
248 let end =
249 lines.len() - usize::from(lines.len() > start && name(lines[lines.len() - 1]) == "END");
250 &lines[start..end]
251}
252
253/// The top-level components called `outer`.
254fn top_blocks<'a>(text: &'a str, outer: &str) -> Vec<Block<'a>> {
255 split_level(&logical_lines(text))
256 .1
257 .into_iter()
258 .filter(|b| b.name == outer)
259 .collect()
260}
261
262/// The properties of this level and its components. A component cut off by
263/// the end of the text is kept, without END.
264fn split_level<'a>(lines: &[&'a str]) -> (Vec<&'a str>, Vec<Block<'a>>) {
265 let mut props = Vec::new();
266 let mut blocks: Vec<Block<'a>> = Vec::new();
267 let mut depth = 0usize;
268 for &line in lines {
269 let n = name(line);
270 if depth == 0 {
271 if n == "BEGIN" {
272 blocks.push(Block {
273 name: value(&unfold(line)).trim().to_ascii_uppercase(),
274 lines: vec![line],
275 });
276 depth = 1;
277 } else if !n.is_empty() {
278 props.push(line);
279 }
280 continue;
281 }
282 blocks.last_mut().expect("depth > 0").lines.push(line);
283 match n.as_str() {
284 "BEGIN" => depth += 1,
285 "END" => depth -= 1,
286 _ => {}
287 }
288 }
289 (props, blocks)
290}
291
292fn push_lines(out: &mut String, lines: &[&str]) {
293 for line in lines {
294 for physical in line.split_inclusive('\n') {
295 out.push_str(physical.trim_end_matches(['\r', '\n']));
296 out.push_str("\r\n");
297 }
298 }
299}
300
301fn lines_text(lines: &[&str]) -> String {
302 let mut out = String::new();
303 push_lines(&mut out, lines);
304 out
305}
306
307fn is_private(c: &Block) -> bool {
308 c.prop("CLASS").is_some_and(|v| {
309 v.eq_ignore_ascii_case("PRIVATE") || v.eq_ignore_ascii_case("CONFIDENTIAL")
310 })
311}
312
313/// Transparent and cancelled events block no time.
314fn blocks_time(e: &Block) -> bool {
315 !(e.prop("TRANSP")
316 .is_some_and(|v| v.eq_ignore_ascii_case("TRANSPARENT"))
317 || e.prop("STATUS")
318 .is_some_and(|v| v.eq_ignore_ascii_case("CANCELLED")))
319}
320
321/// The events of one object as busy time. Events that block no time are
322/// left out; a left-out override becomes an EXDATE of its master, so its
323/// instance stays free. The UID becomes a hash of it, because UIDs often
324/// hold host names or mail addresses.
325fn push_busy(out: &mut String, events: &[&Block]) {
326 let (kept, free): (Vec<&&Block>, Vec<&&Block>) = events.iter().partition(|e| blocks_time(e));
327 let exdates: Vec<String> = free
328 .iter()
329 .filter_map(|e| {
330 let (props, _) = split_level(inner(&e.lines));
331 props
332 .into_iter()
333 .find(|l| name(l) == "RECURRENCE-ID")
334 .map(exdate)
335 })
336 .collect();
337 for e in kept {
338 out.push_str("BEGIN:VEVENT\r\nSUMMARY:Busy\r\n");
339 let (props, _) = split_level(inner(&e.lines));
340 let master = !props.iter().any(|l| name(l) == "RECURRENCE-ID");
341 for line in props {
342 match name(line).as_str() {
343 "UID" => {
344 let uid = unescape_text(value(&unfold(line)));
345 let hash = Sha256::digest(uid.as_bytes());
346 let hex: String = hash[..16].iter().map(|b| format!("{b:02x}")).collect();
347 out.push_str(&format!("UID:{hex}\r\n"));
348 }
349 n if BUSY_PROPS.contains(&n) => push_lines(out, &[line]),
350 _ => {}
351 }
352 }
353 if master {
354 for x in &exdates {
355 out.push_str(x);
356 }
357 }
358 out.push_str("END:VEVENT\r\n");
359 }
360}
361
362/// A RECURRENCE-ID line as the EXDATE of that instance, without RANGE.
363fn exdate(rid: &str) -> String {
364 let line = unfold(rid);
365 let start = value_start(&line);
366 let params: String = param_parts(&line)
367 .into_iter()
368 .filter(|p| !p.trim().to_ascii_uppercase().starts_with("RANGE="))
369 .map(|p| format!(";{p}"))
370 .collect();
371 format!("EXDATE{params}:{}\r\n", &line[start..])
372}
373