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)`, and so does a component type that reuses the UID of
126/// another type: one object holds one type only.
127pub fn split_calendar(text: &str, new_uid: &mut dyn FnMut(&str) -> String) -> Vec<String> {
128 let mut header: Option<Vec<String>> = None;
129 let mut zones: HashMap<String, String> = HashMap::new();
130 // (uid, components, TZIDs they name), in file order.
131 let mut groups: Vec<(String, String, HashSet<String>)> = Vec::new();
132 // By the UID in the file and the component type.
133 let mut by_uid: HashMap<(String, String), usize> = HashMap::new();
134 let mut file_uids: HashSet<String> = HashSet::new();
135 // A file that holds the same component twice keeps one copy.
136 let mut seen: HashSet<String> = HashSet::new();
137 for cal in top_blocks(text, "VCALENDAR") {
138 let (props, children) = split_level(inner(&cal.lines));
139 header.get_or_insert_with(|| {
140 props
141 .iter()
142 .filter(|l| ["VERSION", "PRODID", "CALSCALE"].contains(&name(l).as_str()))
143 .map(|l| l.to_string())
144 .collect()
145 });
146 for c in children {
147 if c.name == "VTIMEZONE" {
148 if let Some(id) = c.prop("TZID") {
149 zones.entry(id).or_insert_with(|| lines_text(&c.lines));
150 }
151 continue;
152 }
153 let tzids: HashSet<String> = c
154 .lines
155 .iter()
156 .filter_map(|l| param(&unfold(l), "TZID"))
157 .collect();
158 let file_uid = c.prop("UID").filter(|u| !u.trim().is_empty());
159 let group = file_uid
160 .as_ref()
161 .and_then(|u| by_uid.get(&(u.clone(), c.name.clone())).copied());
162 let uid = match (&file_uid, group) {
163 (_, Some(i)) => groups[i].0.clone(),
164 (Some(u), None) if !file_uids.contains(u) => u.clone(),
165 _ => new_uid(&lines_text(&c.lines)),
166 };
167 let text = match file_uid.as_ref() == Some(&uid) {
168 true => lines_text(&c.lines),
169 false => {
170 let rest = without_own(&c.lines, "UID");
171 let mut text = String::new();
172 push_lines(&mut text, &rest[..1]);
173 text.push_str(&format!("UID:{uid}\r\n"));
174 push_lines(&mut text, &rest[1..]);
175 text
176 }
177 };
178 if !seen.insert(text.clone()) {
179 continue;
180 }
181 match group {
182 Some(i) => {
183 groups[i].1.push_str(&text);
184 groups[i].2.extend(tzids);
185 }
186 None => {
187 let key = file_uid.unwrap_or_else(|| uid.clone());
188 file_uids.insert(key.clone());
189 by_uid.insert((key, c.name.clone()), groups.len());
190 groups.push((uid, text, tzids));
191 }
192 }
193 }
194 }
195 let mut head = String::from("BEGIN:VCALENDAR\r\n");
196 let header = header.unwrap_or_default();
197 if !header.iter().any(|l| name(l) == "VERSION") {
198 head.push_str("VERSION:2.0\r\n");
199 }
200 if !header.iter().any(|l| name(l) == "PRODID") {
201 head.push_str(PRODID);
202 head.push_str("\r\n");
203 }
204 for l in &header {
205 push_lines(&mut head, &[l.as_str()]);
206 }
207 groups
208 .into_iter()
209 .map(|(_, components, tzids)| {
210 let mut out = head.clone();
211 let mut tzids: Vec<_> = tzids.into_iter().collect();
212 tzids.sort();
213 for id in tzids {
214 if let Some(z) = zones.get(&id) {
215 out.push_str(z);
216 }
217 }
218 out + &components + "END:VCALENDAR\r\n"
219 })
220 .collect()
221}
222
223/// Splits a vCard file into one text per card. A card without UID gets
224/// `new_uid(its text)`, inserted before its END line: vCard 4.0 wants
225/// VERSION right after BEGIN.
226pub fn split_cards(text: &str, new_uid: &mut dyn FnMut(&str) -> String) -> Vec<String> {
227 top_blocks(text, "VCARD")
228 .into_iter()
229 .map(|card| {
230 let text = lines_text(&card.lines);
231 if card.prop("UID").is_some_and(|u| !u.trim().is_empty()) {
232 return text;
233 }
234 let lines = without_own(&card.lines, "UID");
235 let (body, end) = match lines.split_last() {
236 Some((last, body)) if name(last) == "END" => (body, Some(*last)),
237 _ => (&lines[..], None),
238 };
239 let mut out = String::new();
240 push_lines(&mut out, body);
241 out.push_str(&format!("UID:{}\r\n", new_uid(&text)));
242 if let Some(end) = end {
243 push_lines(&mut out, &[end]);
244 }
245 out
246 })
247 .collect()
248}
249
250/// A component as its logical lines, BEGIN and END included.
251struct Block<'a> {
252 /// Upper case.
253 name: String,
254 lines: Vec<&'a str>,
255}
256
257impl Block<'_> {
258 /// The value of the first own property called `prop`, not one of a
259 /// nested component, unfolded and unescaped as TEXT.
260 fn prop(&self, prop: &str) -> Option<String> {
261 split_level(inner(&self.lines))
262 .0
263 .into_iter()
264 .find(|l| name(l) == prop)
265 .map(|l| unescape_text(value(&unfold(l))))
266 }
267}
268
269/// A component's lines without its own `prop` lines. Nested components keep
270/// theirs.
271fn without_own<'a>(lines: &[&'a str], prop: &str) -> Vec<&'a str> {
272 let mut depth = 0usize;
273 let mut out = Vec::with_capacity(lines.len());
274 for &line in lines {
275 let n = name(line);
276 match n.as_str() {
277 "BEGIN" => depth += 1,
278 "END" => depth = depth.saturating_sub(1),
279 _ if depth == 1 && n == prop => continue,
280 _ => {}
281 }
282 out.push(line);
283 }
284 out
285}
286
287/// `lines` without their BEGIN and END line.
288fn inner<'a, 'b>(lines: &'b [&'a str]) -> &'b [&'a str] {
289 let start = usize::from(lines.first().is_some_and(|l| name(l) == "BEGIN"));
290 let end =
291 lines.len() - usize::from(lines.len() > start && name(lines[lines.len() - 1]) == "END");
292 &lines[start..end]
293}
294
295/// The top-level components called `outer`.
296fn top_blocks<'a>(text: &'a str, outer: &str) -> Vec<Block<'a>> {
297 split_level(&logical_lines(text))
298 .1
299 .into_iter()
300 .filter(|b| b.name == outer)
301 .collect()
302}
303
304/// The properties of this level and its components. A component cut off by
305/// the end of the text is kept, without END.
306fn split_level<'a>(lines: &[&'a str]) -> (Vec<&'a str>, Vec<Block<'a>>) {
307 let mut props = Vec::new();
308 let mut blocks: Vec<Block<'a>> = Vec::new();
309 let mut depth = 0usize;
310 for &line in lines {
311 let n = name(line);
312 if depth == 0 {
313 if n == "BEGIN" {
314 blocks.push(Block {
315 name: value(&unfold(line)).trim().to_ascii_uppercase(),
316 lines: vec![line],
317 });
318 depth = 1;
319 } else if !n.is_empty() {
320 props.push(line);
321 }
322 continue;
323 }
324 blocks.last_mut().expect("depth > 0").lines.push(line);
325 match n.as_str() {
326 "BEGIN" => depth += 1,
327 "END" => depth -= 1,
328 _ => {}
329 }
330 }
331 (props, blocks)
332}
333
334fn push_lines(out: &mut String, lines: &[&str]) {
335 for line in lines {
336 for physical in line.split_inclusive('\n') {
337 out.push_str(physical.trim_end_matches(['\r', '\n']));
338 out.push_str("\r\n");
339 }
340 }
341}
342
343fn lines_text(lines: &[&str]) -> String {
344 let mut out = String::new();
345 push_lines(&mut out, lines);
346 out
347}
348
349fn is_private(c: &Block) -> bool {
350 c.prop("CLASS").is_some_and(|v| {
351 v.eq_ignore_ascii_case("PRIVATE") || v.eq_ignore_ascii_case("CONFIDENTIAL")
352 })
353}
354
355/// Transparent and cancelled events block no time.
356fn blocks_time(e: &Block) -> bool {
357 !(e.prop("TRANSP")
358 .is_some_and(|v| v.eq_ignore_ascii_case("TRANSPARENT"))
359 || e.prop("STATUS")
360 .is_some_and(|v| v.eq_ignore_ascii_case("CANCELLED")))
361}
362
363/// The events of one object as busy time. Events that block no time are
364/// left out; a left-out override becomes an EXDATE of its master, so its
365/// instance stays free. The UID becomes a hash of it, because UIDs often
366/// hold host names or mail addresses.
367fn push_busy(out: &mut String, events: &[&Block]) {
368 let (kept, free): (Vec<&&Block>, Vec<&&Block>) = events.iter().partition(|e| blocks_time(e));
369 let exdates: Vec<String> = free
370 .iter()
371 .filter_map(|e| {
372 let (props, _) = split_level(inner(&e.lines));
373 props
374 .into_iter()
375 .find(|l| name(l) == "RECURRENCE-ID")
376 .map(exdate)
377 })
378 .collect();
379 for e in kept {
380 out.push_str("BEGIN:VEVENT\r\nSUMMARY:Busy\r\n");
381 let (props, _) = split_level(inner(&e.lines));
382 let master = !props.iter().any(|l| name(l) == "RECURRENCE-ID");
383 for line in props {
384 match name(line).as_str() {
385 "UID" => {
386 let uid = unescape_text(value(&unfold(line)));
387 let hash = Sha256::digest(uid.as_bytes());
388 let hex: String = hash[..16].iter().map(|b| format!("{b:02x}")).collect();
389 out.push_str(&format!("UID:{hex}\r\n"));
390 }
391 n if BUSY_PROPS.contains(&n) => push_lines(out, &[line]),
392 _ => {}
393 }
394 }
395 if master {
396 for x in &exdates {
397 out.push_str(x);
398 }
399 }
400 out.push_str("END:VEVENT\r\n");
401 }
402}
403
404/// A RECURRENCE-ID line as the EXDATE of that instance, without RANGE.
405fn exdate(rid: &str) -> String {
406 let line = unfold(rid);
407 let start = value_start(&line);
408 let params: String = param_parts(&line)
409 .into_iter()
410 .filter(|p| !p.trim().to_ascii_uppercase().starts_with("RANGE="))
411 .map(|p| format!(";{p}"))
412 .collect();
413 format!("EXDATE{params}:{}\r\n", &line[start..])
414}
415