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