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/// Splits an iCalendar file into calendar object resources: one per UID,
100/// overrides with their master, each with the VTIMEZONEs it names. Keeps
101/// VERSION, PRODID and CALSCALE of the file and drops the other calendar
102/// properties, METHOD among them. A component without UID gets
103/// `new_uid(its text)`.
104pub fn split_calendar(text: &str, new_uid: &mut dyn FnMut(&str) -> String) -> Vec<String> {
105 let mut header: Option<Vec<String>> = None;
106 let mut zones: HashMap<String, String> = HashMap::new();
107 // (uid, components, TZIDs they name), in file order.
108 let mut groups: Vec<(String, String, HashSet<String>)> = Vec::new();
109 for cal in top_blocks(text, "VCALENDAR") {
110 let (props, children) = split_level(inner(&cal.lines));
111 header.get_or_insert_with(|| {
112 props
113 .iter()
114 .filter(|l| ["VERSION", "PRODID", "CALSCALE"].contains(&name(l).as_str()))
115 .map(|l| l.to_string())
116 .collect()
117 });
118 for c in children {
119 if c.name == "VTIMEZONE" {
120 if let Some(id) = c.prop("TZID") {
121 zones.entry(id).or_insert_with(|| lines_text(&c.lines));
122 }
123 continue;
124 }
125 let tzids: HashSet<String> = c
126 .lines
127 .iter()
128 .filter_map(|l| param(&unfold(l), "TZID"))
129 .collect();
130 let (uid, text) = match c.prop("UID") {
131 Some(uid) => (uid, lines_text(&c.lines)),
132 None => {
133 let uid = new_uid(&lines_text(&c.lines));
134 let mut text = String::new();
135 push_lines(&mut text, &c.lines[..1]);
136 text.push_str(&format!("UID:{uid}\r\n"));
137 push_lines(&mut text, &c.lines[1..]);
138 (uid, text)
139 }
140 };
141 match groups.iter_mut().find(|g| g.0 == uid) {
142 // A file that holds the same component twice.
143 Some(g) if g.1.contains(&text) => {}
144 Some(g) => {
145 g.1.push_str(&text);
146 g.2.extend(tzids);
147 }
148 None => groups.push((uid, text, tzids)),
149 }
150 }
151 }
152 let mut head = String::from("BEGIN:VCALENDAR\r\n");
153 let header = header.unwrap_or_default();
154 if !header.iter().any(|l| name(l) == "VERSION") {
155 head.push_str("VERSION:2.0\r\n");
156 }
157 if !header.iter().any(|l| name(l) == "PRODID") {
158 head.push_str(PRODID);
159 head.push_str("\r\n");
160 }
161 for l in &header {
162 push_lines(&mut head, &[l.as_str()]);
163 }
164 groups
165 .into_iter()
166 .map(|(_, components, tzids)| {
167 let mut out = head.clone();
168 let mut tzids: Vec<_> = tzids.into_iter().collect();
169 tzids.sort();
170 for id in tzids {
171 if let Some(z) = zones.get(&id) {
172 out.push_str(z);
173 }
174 }
175 out + &components + "END:VCALENDAR\r\n"
176 })
177 .collect()
178}
179
180/// Splits a vCard file into one text per card. A card without UID gets
181/// `new_uid(its text)`, inserted before its END line: vCard 4.0 wants
182/// VERSION right after BEGIN.
183pub fn split_cards(text: &str, new_uid: &mut dyn FnMut(&str) -> String) -> Vec<String> {
184 top_blocks(text, "VCARD")
185 .into_iter()
186 .map(|card| {
187 let text = lines_text(&card.lines);
188 if card.prop("UID").is_some() {
189 return text;
190 }
191 let (body, end) = match card.lines.split_last() {
192 Some((last, body)) if name(last) == "END" => (body, Some(*last)),
193 _ => (&card.lines[..], None),
194 };
195 let mut out = String::new();
196 push_lines(&mut out, body);
197 out.push_str(&format!("UID:{}\r\n", new_uid(&text)));
198 if let Some(end) = end {
199 push_lines(&mut out, &[end]);
200 }
201 out
202 })
203 .collect()
204}
205
206/// A component as its logical lines, BEGIN and END included.
207struct Block<'a> {
208 /// Upper case.
209 name: String,
210 lines: Vec<&'a str>,
211}
212
213impl Block<'_> {
214 /// The value of the first own property called `prop`, not one of a
215 /// nested component, unfolded and unescaped as TEXT.
216 fn prop(&self, prop: &str) -> Option<String> {
217 split_level(inner(&self.lines))
218 .0
219 .into_iter()
220 .find(|l| name(l) == prop)
221 .map(|l| unescape_text(value(&unfold(l))))
222 }
223}
224
225/// `lines` without their BEGIN and END line.
226fn inner<'a, 'b>(lines: &'b [&'a str]) -> &'b [&'a str] {
227 let start = usize::from(lines.first().is_some_and(|l| name(l) == "BEGIN"));
228 let end =
229 lines.len() - usize::from(lines.len() > start && name(lines[lines.len() - 1]) == "END");
230 &lines[start..end]
231}
232
233/// The top-level components called `outer`.
234fn top_blocks<'a>(text: &'a str, outer: &str) -> Vec<Block<'a>> {
235 split_level(&logical_lines(text))
236 .1
237 .into_iter()
238 .filter(|b| b.name == outer)
239 .collect()
240}
241
242/// The properties of this level and its components. A component cut off by
243/// the end of the text is kept, without END.
244fn split_level<'a>(lines: &[&'a str]) -> (Vec<&'a str>, Vec<Block<'a>>) {
245 let mut props = Vec::new();
246 let mut blocks: Vec<Block<'a>> = Vec::new();
247 let mut depth = 0usize;
248 for &line in lines {
249 let n = name(line);
250 if depth == 0 {
251 if n == "BEGIN" {
252 blocks.push(Block {
253 name: value(&unfold(line)).trim().to_ascii_uppercase(),
254 lines: vec![line],
255 });
256 depth = 1;
257 } else if !n.is_empty() {
258 props.push(line);
259 }
260 continue;
261 }
262 blocks.last_mut().expect("depth > 0").lines.push(line);
263 match n.as_str() {
264 "BEGIN" => depth += 1,
265 "END" => depth -= 1,
266 _ => {}
267 }
268 }
269 (props, blocks)
270}
271
272fn push_lines(out: &mut String, lines: &[&str]) {
273 for line in lines {
274 for physical in line.split_inclusive('\n') {
275 out.push_str(physical.trim_end_matches(['\r', '\n']));
276 out.push_str("\r\n");
277 }
278 }
279}
280
281fn lines_text(lines: &[&str]) -> String {
282 let mut out = String::new();
283 push_lines(&mut out, lines);
284 out
285}
286
287fn is_private(c: &Block) -> bool {
288 c.prop("CLASS").is_some_and(|v| {
289 v.eq_ignore_ascii_case("PRIVATE") || v.eq_ignore_ascii_case("CONFIDENTIAL")
290 })
291}
292
293/// Transparent and cancelled events block no time.
294fn blocks_time(e: &Block) -> bool {
295 !(e.prop("TRANSP")
296 .is_some_and(|v| v.eq_ignore_ascii_case("TRANSPARENT"))
297 || e.prop("STATUS")
298 .is_some_and(|v| v.eq_ignore_ascii_case("CANCELLED")))
299}
300
301/// The events of one object as busy time. Events that block no time are
302/// left out; a left-out override becomes an EXDATE of its master, so its
303/// instance stays free. The UID becomes a hash of it, because UIDs often
304/// hold host names or mail addresses.
305fn push_busy(out: &mut String, events: &[&Block]) {
306 let (kept, free): (Vec<&&Block>, Vec<&&Block>) = events.iter().partition(|e| blocks_time(e));
307 let exdates: Vec<String> = free
308 .iter()
309 .filter_map(|e| {
310 let (props, _) = split_level(inner(&e.lines));
311 props
312 .into_iter()
313 .find(|l| name(l) == "RECURRENCE-ID")
314 .map(exdate)
315 })
316 .collect();
317 for e in kept {
318 out.push_str("BEGIN:VEVENT\r\nSUMMARY:Busy\r\n");
319 let (props, _) = split_level(inner(&e.lines));
320 let master = !props.iter().any(|l| name(l) == "RECURRENCE-ID");
321 for line in props {
322 match name(line).as_str() {
323 "UID" => {
324 let uid = unescape_text(value(&unfold(line)));
325 let hash = Sha256::digest(uid.as_bytes());
326 let hex: String = hash[..16].iter().map(|b| format!("{b:02x}")).collect();
327 out.push_str(&format!("UID:{hex}\r\n"));
328 }
329 n if BUSY_PROPS.contains(&n) => push_lines(out, &[line]),
330 _ => {}
331 }
332 }
333 if master {
334 for x in &exdates {
335 out.push_str(x);
336 }
337 }
338 out.push_str("END:VEVENT\r\n");
339 }
340}
341
342/// A RECURRENCE-ID line as the EXDATE of that instance, without RANGE.
343fn exdate(rid: &str) -> String {
344 let line = unfold(rid);
345 let start = value_start(&line);
346 let params: String = param_parts(&line)
347 .into_iter()
348 .filter(|p| !p.trim().to_ascii_uppercase().starts_with("RANGE="))
349 .map(|p| format!(";{p}"))
350 .collect();
351 format!("EXDATE{params}:{}\r\n", &line[start..])
352}
353