vstorage 0.8.1

Common API for various icalendar/vcard storages.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
// Copyright 2023-2026 Hugo Osvaldo Barrera
//
// SPDX-License-Identifier: EUPL-1.2

use std::{
    borrow::Cow,
    collections::{HashMap, HashSet},
};

use log::warn;
use vparser::{ContentLine, ParamIter, Parser};

/// A simple component model that only cares about the basic structure.
///
/// Usable only to split components and other simple operations. This
/// is not a full parser and won't validate much beyond `BEGIN` and `END`
/// properly matching. The intent of this parser is not to be validating, but
/// to be very tolerant with inputs, so as to allow operating on somewhat
/// invalid inputs.
///
/// # Known Issues
///
/// Works only with iCalendar, not with vCard.
#[derive(Clone, Debug, PartialEq)]
pub(crate) struct Component<'a> {
    kind: Cow<'a, str>,
    lines: Vec<ContentLine<'a>>,
    subcomponents: Vec<Component<'a>>,
    /// UID of the item (for VEVENT/VTODO/VJOURNAL only).
    uid: Option<Cow<'a, str>>,
    // FIXME: the following fields only exist in mutual exclusion.
    /// TZID property value (for VTIMEZONE components only).
    tzid: Option<Cow<'a, str>>,
    /// TZIDs referenced by this component (for wrapper VCALENDARs only).
    referenced_tzids: HashSet<String>,
}

#[derive(Debug, thiserror::Error, PartialEq)]
pub(crate) enum ComponentError {
    #[error("unknown (or unimplemented) component: {0}")]
    UnknownComponent(String),
    #[error("found data after END of root component")]
    DataAfterEnd,
    #[error("reached end of file while parsing data")]
    UnexpectedEof,
    #[error("unbalanced BEGIN and END lines")]
    WrongEnd,
    #[error("END line had no matching BEGIN line")]
    EndWithoutBegin,
    #[error("found data after last END: line")]
    DataOutsideBeginEnd,
    #[error("VCALENDAR cannot be nested inside other components")]
    InvalidStructure,
}

impl<'a> Component<'a> {
    fn new(kind: Cow<'a, str>) -> Self {
        Component {
            kind,
            lines: Vec::new(),
            subcomponents: Vec::new(),
            uid: None,
            tzid: None,
            referenced_tzids: HashSet::new(),
        }
    }

    /// Parse a VCALENDAR and split into individual items with their timezones.
    ///
    /// For a calendar with multiple `VEVENT`s and `VTIMEZONE`, returns individual
    /// `VEVENT`s wrapped in `VCALENDAR`s with relevant `VTIMEZONE` components copied in.
    pub(crate) fn parse_split(input: &'a str) -> Result<Vec<Component<'a>>, ComponentError> {
        let mut state = ParseState::new(input);

        while let Some(line) = state.parser.next() {
            match line.name().as_ref() {
                "BEGIN" => state.handle_begin(&line)?,
                "END" => {
                    if state.handle_end(&line)? {
                        return Ok(state.finalize());
                    }
                }
                _ => state.handle_property(line)?,
            }
        }

        Err(ComponentError::UnexpectedEof)
    }
}

/// State for the single-pass parser.
struct ParseState<'a> {
    parser: Parser<'a>,
    input_context: Vec<Cow<'a, str>>,
    builder: Option<Builder<'a>>,
    timezones: HashMap<String, Component<'a>>,
    items: HashMap<Cow<'a, str>, Component<'a>>,
    without_uid: Vec<Component<'a>>,
}

impl<'a> ParseState<'a> {
    fn new(input: &'a str) -> Self {
        ParseState {
            parser: Parser::new(input),
            input_context: Vec::new(),
            builder: None,
            timezones: HashMap::new(),
            items: HashMap::new(),
            without_uid: Vec::new(),
        }
    }

    fn handle_begin(&mut self, line: &ContentLine<'a>) -> Result<(), ComponentError> {
        let kind = line.value();
        self.input_context.push(kind.clone());

        match kind.as_ref() {
            "VTIMEZONE" => match &mut self.builder {
                Some(_) => return Err(ComponentError::InvalidStructure),
                None => self.builder = Some(Builder::Timezone(Component::new(kind))),
            },
            "VEVENT" | "VTODO" | "VJOURNAL" => {
                if self
                    .builder
                    .replace(Builder::Item(ItemBuilder::new(kind)))
                    .is_some()
                {
                    return Err(ComponentError::InvalidStructure);
                }
            }
            "VCALENDAR" => {
                if self.builder.is_some() {
                    return Err(ComponentError::InvalidStructure);
                }
            }
            _ => match &mut self.builder {
                Some(builder) => builder.push_subcomponent(Component::new(kind)),
                None => return Err(ComponentError::UnknownComponent(kind.to_string())),
            },
        }
        Ok(())
    }

    /// Returns true if root VCALENDAR ended (parsing complete).
    fn handle_end(&mut self, line: &ContentLine<'a>) -> Result<bool, ComponentError> {
        let kind = line.value();

        let expected = self
            .input_context
            .pop()
            .ok_or(ComponentError::EndWithoutBegin)?;
        if kind != expected {
            return Err(ComponentError::WrongEnd);
        }

        match kind.as_ref() {
            "VTIMEZONE" => match self.builder.take() {
                Some(Builder::Timezone(tz)) => match &tz.tzid {
                    Some(tzid) => {
                        self.timezones.insert(normalize_tzid(tzid), tz);
                    }
                    None => {
                        warn!("VTIMEZONE component has no TZID property.");
                    }
                },
                Some(Builder::Item(_)) => return Err(ComponentError::InvalidStructure),
                None => {
                    unreachable!("input_context would be None if this were None");
                }
            },
            "VEVENT" | "VTODO" | "VJOURNAL" => {
                if let Some(Builder::Item(item_builder)) = self.builder.take() {
                    let wrapper = item_builder.into_item();
                    match wrapper.subcomponents.first().and_then(|c| c.uid.as_ref()) {
                        Some(uid) => {
                            self.items.insert(uid.clone(), wrapper);
                        }
                        None => {
                            self.without_uid.push(wrapper);
                        }
                    }
                }
            }
            _ => {
                if let Some(Builder::Item(item_builder)) = &mut self.builder {
                    item_builder.pop_subcomponent();
                }
            }
        }

        if self.input_context.is_empty() {
            if self.parser.next().is_some_and(|l| !l.raw().is_empty()) {
                return Err(ComponentError::DataAfterEnd);
            }
            return Ok(true);
        }
        Ok(false)
    }

    fn handle_property(&mut self, line: ContentLine<'a>) -> Result<(), ComponentError> {
        let name = line.name();

        match &mut self.builder {
            Some(Builder::Timezone(tz)) => {
                if name == "TZID" {
                    tz.tzid = Some(line.value());
                }
                tz.lines.push(line);
            }
            Some(Builder::Item(item_builder)) => {
                item_builder.process_line(line);
            }
            None => {
                if self.input_context.is_empty() {
                    return Err(ComponentError::DataOutsideBeginEnd);
                }
            }
        }
        Ok(())
    }

    fn finalize(self) -> Vec<Component<'a>> {
        let mut result: Vec<Component<'a>> =
            Vec::with_capacity(self.items.len() + self.without_uid.len());

        for mut wrapper in self.items.into_values().chain(self.without_uid) {
            for tzid in &wrapper.referenced_tzids {
                if let Some(tz) = self.timezones.get(tzid) {
                    wrapper.subcomponents.push(tz.clone());
                } else {
                    warn!("Component references non-existent TZID: {tzid}");
                }
            }
            result.push(wrapper);
        }

        result
    }
}

/// Normalize a TZID value for case-insensitive comparison.
///
/// Strips surrounding quotes if present and converts to lowercase.
fn normalize_tzid(value: &str) -> String {
    // FIXME: this ends up rewriting MOST names, since they're typically mixed case.
    let stripped = if value.starts_with('"') && value.ends_with('"') && value.len() >= 2 {
        &value[1..value.len() - 1]
    } else {
        value
    };
    stripped.to_lowercase()
}

/// Builder for the current line we're parsing.
enum Builder<'a> {
    Timezone(Component<'a>),
    Item(ItemBuilder<'a>),
}

impl<'a> Builder<'a> {
    fn push_subcomponent(&mut self, subcomponent: Component<'a>) {
        match self {
            Builder::Timezone(tz) => tz.subcomponents.push(subcomponent),
            Builder::Item(ib) => ib.push_subcomponent(subcomponent),
        }
    }
}

/// Builder for an item (VEVENT/VTODO/VJOURNAL) with its wrapper VCALENDAR.
struct ItemBuilder<'a> {
    /// Wrapper VCALENDAR. Holds `referenced_tzids` and `uid`.
    wrapper: Component<'a>,
    /// Stack of nested components: [VEVENT, VALARM, ...].
    component_stack: Vec<Component<'a>>,
}

impl<'a> ItemBuilder<'a> {
    fn new(kind: Cow<'a, str>) -> Self {
        let wrapper = Component::new(Cow::Borrowed("VCALENDAR"));
        let item = Component::new(kind);
        ItemBuilder {
            wrapper,
            component_stack: vec![item],
        }
    }

    fn push_subcomponent(&mut self, component: Component<'a>) {
        self.current().subcomponents.push(component);
    }

    fn pop_subcomponent(&mut self) {
        if let Some(child) = self.component_stack.pop() {
            self.current().subcomponents.push(child);
        }
    }

    fn process_line(&mut self, line: ContentLine<'a>) {
        let name = line.name();

        // Store the UID for the primary component for easy access later.
        if name == "UID"
            && self.component_stack.len() == 1
            && let Some(item) = self.component_stack.first_mut()
        {
            item.uid = Some(line.value());
        }

        if name == "TZID" {
            self.current().tzid = Some(line.value());
        }

        for param in ParamIter::new(&line.params()) {
            if param.name() == "TZID" {
                self.wrapper
                    .referenced_tzids
                    .insert(normalize_tzid(param.value()));
            }
        }

        self.current().lines.push(line);
    }

    fn current(&mut self) -> &mut Component<'a> {
        self.component_stack
            .last_mut()
            .expect("component_stack non-empty")
    }

    fn into_item(self) -> Component<'a> {
        let mut wrapper = self.wrapper;
        for component in self.component_stack {
            wrapper.subcomponents.push(component);
        }
        wrapper
    }
}

impl std::fmt::Display for Component<'_> {
    /// Write a fully encoded representation of this item.
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "BEGIN:{}\r\n", self.kind)?;
        for line in &self.lines {
            write!(f, "{}\r\n", line.raw())?;
        }
        for component in &self.subcomponents {
            write!(f, "{component}")?;
        }
        write!(f, "END:{}\r\n", self.kind)
    }
}

#[cfg(test)]
mod test {
    use std::collections::HashSet;

    use crate::simple_component::ComponentError;

    #[test]
    fn test_parse_and_split_collection() {
        use super::Component;

        let calendar = vec![
            "BEGIN:VCALENDAR",
            "BEGIN:VTIMEZONE",
            "TZID:Europe/Rome",
            "X-LIC-LOCATION:Europe/Rome",
            "BEGIN:DAYLIGHT",
            "TZOFFSETFROM:+0100",
            "TZOFFSETTO:+0200",
            "TZNAME:CEST",
            "DTSTART:19700329T020000",
            "RRULE:FREQ=YEARLY;BYDAY=-1SU;BYMONTH=3",
            "END:DAYLIGHT",
            "BEGIN:STANDARD",
            "TZOFFSETFROM:+0200",
            "TZOFFSETTO:+0100",
            "TZNAME:CET",
            "DTSTART:19701025T030000",
            "RRULE:FREQ=YEARLY;BYDAY=-1SU;BYMONTH=10",
            "END:STANDARD",
            "END:VTIMEZONE",
            "BEGIN:VEVENT",
            "DTSTART:19970714T170000Z",
            "DTEND:19970715T035959Z",
            "SUMMARY:Bastille Day Party",
            "X-SOMETHING:r",
            "UID:11bb6bed-c29b-4999-a627-12dee35f8395",
            "END:VEVENT",
            "BEGIN:VEVENT",
            "DTSTART:19970714T170000Z",
            "DTEND:19970715T035959Z",
            "SUMMARY:Bastille Day Party (copy)",
            "X-SOMETHING:s",
            "UID:b8d52b8b-dd6b-4ef9-9249-0ad7c28f9e5a",
            "END:VEVENT",
            "END:VCALENDAR",
        ]
        .join("\r\n");

        let serialised_split = Component::parse_split(&calendar)
            .unwrap()
            .iter()
            .map(Component::to_string)
            .collect::<Vec<_>>();

        let expected_first = [
            "BEGIN:VCALENDAR",
            "BEGIN:VEVENT",
            "DTSTART:19970714T170000Z",
            "DTEND:19970715T035959Z",
            "SUMMARY:Bastille Day Party (copy)",
            "X-SOMETHING:s",
            "UID:b8d52b8b-dd6b-4ef9-9249-0ad7c28f9e5a",
            "END:VEVENT",
            "END:VCALENDAR",
            "",
        ]
        .join("\r\n");
        let expected_second = [
            "BEGIN:VCALENDAR",
            "BEGIN:VEVENT",
            "DTSTART:19970714T170000Z",
            "DTEND:19970715T035959Z",
            "SUMMARY:Bastille Day Party",
            "X-SOMETHING:r",
            "UID:11bb6bed-c29b-4999-a627-12dee35f8395",
            "END:VEVENT",
            "END:VCALENDAR",
            "",
        ]
        .join("\r\n");

        // Comparing like this since the order is not deterministic.
        assert!(serialised_split.iter().any(|c| **c == expected_first));
        assert!(serialised_split.iter().any(|c| **c == expected_second));
    }

    #[test]
    fn test_missing_end() {
        use super::Component;

        let calendar = [
            "BEGIN:VCALENDAR",
            "BEGIN:VTIMEZONE",
            "TZID:Europe/Rome",
            "END:VTIMEZONE",
            "BEGIN:VEVENT",
            "SUMMARY:This event is probably invalid due to missing fields",
            "UID:11bb6bed-c29b-4999-a627-12dee35f8395",
            "END:VEVENT",
        ]
        .join("\r\n");

        assert_eq!(
            Component::parse_split(&calendar),
            Err(ComponentError::UnexpectedEof)
        );
    }

    #[test]
    fn test_unknown_kind() {
        use super::Component;

        let calendar = [
            "BEGIN:VCALENDAR",
            "BEGIN:VTIMEZONE",
            "TZID:Europe/Rome",
            "END:VTIMEZONE",
            "BEGIN:VEVENT",
            "SUMMARY:This event is probably invalid due to missing fields",
            "UID:11bb6bed-c29b-4999-a627-12dee35f8395",
            "END:VEVENT",
            "BEGIN:VAUTOMOBILE",
            "END:VAUTOMOBILE",
            "END:VCALENDAR",
        ]
        .join("\r\n");

        assert_eq!(
            Component::parse_split(&calendar),
            Err(ComponentError::UnknownComponent("VAUTOMOBILE".to_string()))
        );
    }

    #[test]
    fn test_multiline_uid() {
        use super::Component;

        let calendar = [
            "BEGIN:VCALENDAR",
            "BEGIN:VTIMEZONE",
            "TZID:Europe/Rome",
            "END:VTIMEZONE",
            "BEGIN:VEVENT",
            "SUMMARY:This event is probably invalid due to missing fields",
            "UID:horrible-",
            " example",
            "END:VEVENT",
            "END:VCALENDAR",
        ]
        .join("\r\n");

        let calendar = Component::parse_split(&calendar).unwrap().pop().unwrap();

        assert_eq!(
            calendar.subcomponents[0].uid.as_ref().unwrap(),
            "horrible-example"
        );
    }

    #[test]
    fn test_splitting_and_including_tzid() {
        use super::Component;

        // Dummy data with minimal fields to match splitting logic.
        let calendar = [
            "BEGIN:VCALENDAR",
            "BEGIN:VTIMEZONE",
            "TZID:Europe/Rome",
            "END:VTIMEZONE",
            "BEGIN:VTIMEZONE",
            "TZID:America/New_York",
            "END:VTIMEZONE",
            "BEGIN:VTIMEZONE",
            "TZID:Pacific/Honolulu", // Unused.
            "END:VTIMEZONE",
            "BEGIN:VEVENT",
            "DTSTART;TZID=Europe/Rome:19970714T170000", // Unquoted TZID.
            "UID:event-unquoted",
            "END:VEVENT",
            "BEGIN:VEVENT",
            "DTSTART;TZID=\"America/New_York\":19970714T170000", // Quoted TZID.
            "UID:event-quoted",
            "END:VEVENT",
            "BEGIN:VEVENT",
            "DTSTART;TZID=Europe/Rome:19970714T090000",
            "DTEND;TZID=\"America/New_York\":19970714T170000", // References both.
            "UID:event-both",
            "END:VEVENT",
            "END:VCALENDAR",
        ]
        .join("\r\n");

        let components = Component::parse_split(&calendar).unwrap();

        // event-unquoted should only have Europe/Rome.
        let tzids_unquoted: Vec<_> = components
            .iter()
            .find(|c| {
                c.subcomponents
                    .iter()
                    .any(|s| s.uid.as_deref() == Some("event-unquoted"))
            })
            .unwrap()
            .subcomponents
            .iter()
            .filter_map(|c| c.tzid.as_deref())
            .collect();
        assert_eq!(tzids_unquoted, vec!["Europe/Rome"]);

        // event-quoted should only have America/New_York.
        let tzids_quoted: Vec<_> = components
            .iter()
            .find(|c| {
                c.subcomponents
                    .iter()
                    .any(|s| s.uid.as_deref() == Some("event-quoted"))
            })
            .unwrap()
            .subcomponents
            .iter()
            .filter_map(|c| c.tzid.as_deref())
            .collect();
        assert_eq!(tzids_quoted, vec!["America/New_York"]);

        // event-both should have both Europe/Rome and America/New_York.
        let tzids_both: HashSet<_> = components
            .iter()
            .find(|c| {
                c.subcomponents
                    .iter()
                    .any(|s| s.uid.as_deref() == Some("event-both"))
            })
            .unwrap()
            .subcomponents
            .iter()
            .filter_map(|c| c.tzid.as_deref())
            .collect();
        assert!(tzids_both.contains("Europe/Rome"));
        assert!(tzids_both.contains("America/New_York"));
        assert_eq!(tzids_both.len(), 2);

        // Verify unused timezone never appears in any output.
        for component in &components {
            assert!(!component.to_string().contains("Pacific/Honolulu"));
        }
    }

    #[test]
    fn test_data_after_end() {
        use super::Component;

        let calendar = [
            "BEGIN:VCALENDAR",
            "BEGIN:VEVENT",
            "UID:test-event",
            "END:VEVENT",
            "END:VCALENDAR",
            "BEGIN:VCALENDAR", // Extra content after proper end.
            "BEGIN:VEVENT",
            "UID:orphan-event",
            "END:VEVENT",
            "END:VCALENDAR",
        ]
        .join("\r\n");

        assert_eq!(
            Component::parse_split(&calendar),
            Err(ComponentError::DataAfterEnd)
        );
    }
}