ezcal 0.3.4

Ergonomic iCalendar + vCard library for Rust
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
use crate::common::property::{Parameter, Property};
use crate::error::Result;
use crate::vcard::name::{Address, StructuredName};

/// A vCard contact per RFC 6350.
#[derive(Debug, Clone)]
pub struct Contact {
    pub(crate) uid: Option<String>,
    pub(crate) full_name: Option<String>,
    pub(crate) name: Option<StructuredName>,
    pub(crate) emails: Vec<TypedValue>,
    pub(crate) phones: Vec<TypedValue>,
    pub(crate) organization: Option<String>,
    pub(crate) title: Option<String>,
    pub(crate) role: Option<String>,
    pub(crate) note: Option<String>,
    pub(crate) url: Option<String>,
    pub(crate) addresses: Vec<TypedAddress>,
    pub(crate) birthday: Option<String>,
    pub(crate) photo_uri: Option<String>,
    pub(crate) extra_properties: Vec<Property>,
}

/// A value with an optional type parameter (e.g., WORK, HOME).
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct TypedValue {
    pub value: String,
    pub types: Vec<String>,
}

/// An address with optional type parameters.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct TypedAddress {
    pub address: Address,
    pub types: Vec<String>,
    pub label: Option<String>,
}

impl Contact {
    /// Create a new contact builder.
    pub fn new() -> Self {
        Self {
            uid: None,
            full_name: None,
            name: None,
            emails: Vec::new(),
            phones: Vec::new(),
            organization: None,
            title: None,
            role: None,
            note: None,
            url: None,
            addresses: Vec::new(),
            birthday: None,
            photo_uri: None,
            extra_properties: Vec::new(),
        }
    }

    /// Parse all vCards from a string (a .vcf file may contain multiple contacts).
    pub fn parse_all(input: &str) -> Result<Vec<Contact>> {
        crate::vcard::parser::parse_vcards(input)
    }

    /// Parse a single vCard from a string.
    pub fn parse(input: &str) -> Result<Contact> {
        let mut contacts = Self::parse_all(input)?;
        contacts
            .pop()
            .ok_or_else(|| crate::error::Error::Other("no vCard found in input".to_string()))
    }

    pub fn uid(mut self, uid: impl Into<String>) -> Self {
        self.uid = Some(uid.into());
        self
    }

    pub fn full_name(mut self, name: impl Into<String>) -> Self {
        self.full_name = Some(name.into());
        self
    }

    pub fn structured_name(mut self, name: StructuredName) -> Self {
        self.name = Some(name);
        self
    }

    pub fn email(mut self, email: impl Into<String>) -> Self {
        self.emails.push(TypedValue {
            value: email.into(),
            types: Vec::new(),
        });
        self
    }

    pub fn email_typed(mut self, email: impl Into<String>, types: Vec<String>) -> Self {
        self.emails.push(TypedValue {
            value: email.into(),
            types,
        });
        self
    }

    pub fn phone(mut self, phone: impl Into<String>) -> Self {
        self.phones.push(TypedValue {
            value: phone.into(),
            types: Vec::new(),
        });
        self
    }

    pub fn phone_typed(mut self, phone: impl Into<String>, types: Vec<String>) -> Self {
        self.phones.push(TypedValue {
            value: phone.into(),
            types,
        });
        self
    }

    pub fn organization(mut self, org: impl Into<String>) -> Self {
        self.organization = Some(org.into());
        self
    }

    pub fn title(mut self, title: impl Into<String>) -> Self {
        self.title = Some(title.into());
        self
    }

    pub fn role(mut self, role: impl Into<String>) -> Self {
        self.role = Some(role.into());
        self
    }

    pub fn note(mut self, note: impl Into<String>) -> Self {
        self.note = Some(note.into());
        self
    }

    pub fn url(mut self, url: impl Into<String>) -> Self {
        self.url = Some(url.into());
        self
    }

    pub fn address(mut self, address: Address) -> Self {
        self.addresses.push(TypedAddress {
            address,
            types: Vec::new(),
            label: None,
        });
        self
    }

    pub fn address_typed(
        mut self,
        address: Address,
        types: Vec<String>,
        label: Option<String>,
    ) -> Self {
        self.addresses.push(TypedAddress {
            address,
            types,
            label,
        });
        self
    }

    pub fn birthday(mut self, birthday: impl Into<String>) -> Self {
        self.birthday = Some(birthday.into());
        self
    }

    pub fn photo_uri(mut self, uri: impl Into<String>) -> Self {
        self.photo_uri = Some(uri.into());
        self
    }

    /// Add an extra property.
    pub fn property(mut self, prop: Property) -> Self {
        self.extra_properties.push(prop);
        self
    }

    /// Build the contact (finalizes and returns self).
    pub fn build(self) -> Self {
        self
    }

    // --- Accessors ---

    pub fn get_uid(&self) -> Option<&str> {
        self.uid.as_deref()
    }

    pub fn get_full_name(&self) -> Option<&str> {
        self.full_name.as_deref()
    }

    pub fn get_name(&self) -> Option<&StructuredName> {
        self.name.as_ref()
    }

    pub fn get_emails(&self) -> &[TypedValue] {
        &self.emails
    }

    /// Get the first email address, if any.
    pub fn get_email(&self) -> Option<&str> {
        self.emails.first().map(|e| e.value.as_str())
    }

    pub fn get_phones(&self) -> &[TypedValue] {
        &self.phones
    }

    /// Get the first phone number, if any.
    pub fn get_phone(&self) -> Option<&str> {
        self.phones.first().map(|p| p.value.as_str())
    }

    pub fn get_organization(&self) -> Option<&str> {
        self.organization.as_deref()
    }

    pub fn get_title(&self) -> Option<&str> {
        self.title.as_deref()
    }

    pub fn get_role(&self) -> Option<&str> {
        self.role.as_deref()
    }

    pub fn get_note(&self) -> Option<&str> {
        self.note.as_deref()
    }

    pub fn get_url(&self) -> Option<&str> {
        self.url.as_deref()
    }

    pub fn get_addresses(&self) -> &[TypedAddress] {
        &self.addresses
    }

    pub fn get_birthday(&self) -> Option<&str> {
        self.birthday.as_deref()
    }

    pub fn get_photo_uri(&self) -> Option<&str> {
        self.photo_uri.as_deref()
    }

    pub fn get_extra_properties(&self) -> &[Property] {
        &self.extra_properties
    }

    /// Convert to a list of properties for serialization.
    pub(crate) fn to_properties(&self) -> Vec<Property> {
        let mut props = Vec::new();

        // VERSION is always 4.0 for RFC 6350
        props.push(Property::new("VERSION", "4.0"));

        // UID
        let uid = self
            .uid
            .clone()
            .unwrap_or_else(|| format!("urn:uuid:{}", uuid::Uuid::new_v4()));
        props.push(Property::new("UID", uid));

        // FN (required)
        if let Some(ref fn_name) = self.full_name {
            props.push(Property::new("FN", vcard_escape(fn_name)));
        }

        // N (structured name)
        if let Some(ref name) = self.name {
            props.push(Property::new("N", name.to_value()));
        }

        // EMAIL
        for email in &self.emails {
            let mut prop = Property::new("EMAIL", &email.value);
            if !email.types.is_empty() {
                prop = prop.with_param(Parameter::with_values(
                    "TYPE".to_string(),
                    email.types.clone(),
                ));
            }
            props.push(prop);
        }

        // TEL
        for phone in &self.phones {
            let mut prop = Property::new("TEL", &phone.value);
            if !phone.types.is_empty() {
                prop = prop.with_param(Parameter::with_values(
                    "TYPE".to_string(),
                    phone.types.clone(),
                ));
            }
            props.push(prop);
        }

        // ORG
        if let Some(ref org) = self.organization {
            props.push(Property::new("ORG", vcard_escape(org)));
        }

        // TITLE
        if let Some(ref title) = self.title {
            props.push(Property::new("TITLE", vcard_escape(title)));
        }

        // ROLE
        if let Some(ref role) = self.role {
            props.push(Property::new("ROLE", vcard_escape(role)));
        }

        // NOTE
        if let Some(ref note) = self.note {
            props.push(Property::new("NOTE", vcard_escape(note)));
        }

        // URL
        if let Some(ref url) = self.url {
            props.push(Property::new("URL", url));
        }

        // ADR
        for typed_addr in &self.addresses {
            let mut prop = Property::new("ADR", typed_addr.address.to_value());
            if !typed_addr.types.is_empty() {
                prop = prop.with_param(Parameter::with_values(
                    "TYPE".to_string(),
                    typed_addr.types.clone(),
                ));
            }
            if let Some(ref label) = typed_addr.label {
                prop = prop.with_param(Parameter::new("LABEL", label.clone()));
            }
            props.push(prop);
        }

        // BDAY
        if let Some(ref bday) = self.birthday {
            props.push(Property::new("BDAY", bday));
        }

        // PHOTO
        if let Some(ref photo) = self.photo_uri {
            props.push(Property::new("PHOTO", photo));
        }

        props.extend(self.extra_properties.clone());

        props
    }

    /// Build a contact from parsed properties.
    pub(crate) fn from_properties(props: Vec<Property>) -> Result<Self> {
        let mut contact = Contact::new();
        let mut extra = Vec::new();

        for prop in props {
            match prop.name.as_str() {
                "VERSION" => {} // We handle this internally
                "UID" => contact.uid = Some(prop.value.clone()),
                "FN" => contact.full_name = Some(vcard_unescape(&prop.value)),
                "N" => contact.name = Some(StructuredName::parse(&prop.value)),
                "EMAIL" => {
                    let types = extract_types(&prop);
                    contact.emails.push(TypedValue {
                        value: prop.value.clone(),
                        types,
                    });
                }
                "TEL" => {
                    let types = extract_types(&prop);
                    contact.phones.push(TypedValue {
                        value: prop.value.clone(),
                        types,
                    });
                }
                "ORG" => contact.organization = Some(vcard_unescape(&prop.value)),
                "TITLE" => contact.title = Some(vcard_unescape(&prop.value)),
                "ROLE" => contact.role = Some(vcard_unescape(&prop.value)),
                "NOTE" => contact.note = Some(vcard_unescape(&prop.value)),
                "URL" => contact.url = Some(prop.value.clone()),
                "ADR" => {
                    let types = extract_types(&prop);
                    let label = prop.param_value("LABEL").map(|s| s.to_string());
                    contact.addresses.push(TypedAddress {
                        address: Address::parse(&prop.value),
                        types,
                        label,
                    });
                }
                "BDAY" => contact.birthday = Some(prop.value.clone()),
                "PHOTO" => contact.photo_uri = Some(prop.value.clone()),
                _ => extra.push(prop),
            }
        }

        contact.extra_properties = extra;
        Ok(contact)
    }
}

impl Default for Contact {
    fn default() -> Self {
        Self::new()
    }
}

impl std::fmt::Display for Contact {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "{}", crate::vcard::writer::write_contact(self))
    }
}

fn extract_types(prop: &Property) -> Vec<String> {
    prop.param("TYPE")
        .map(|p| p.values.clone())
        .unwrap_or_default()
}

fn vcard_escape(s: &str) -> String {
    s.replace('\\', "\\\\")
        .replace(',', "\\,")
        .replace('\n', "\\n")
}

fn vcard_unescape(s: &str) -> String {
    let mut result = String::with_capacity(s.len());
    let mut chars = s.chars().peekable();
    while let Some(ch) = chars.next() {
        if ch == '\\' {
            match chars.peek() {
                Some('n') | Some('N') => {
                    result.push('\n');
                    chars.next();
                }
                Some('\\') => {
                    result.push('\\');
                    chars.next();
                }
                Some(',') => {
                    result.push(',');
                    chars.next();
                }
                Some(';') => {
                    result.push(';');
                    chars.next();
                }
                _ => result.push('\\'),
            }
        } else {
            result.push(ch);
        }
    }
    result
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn contact_builder() {
        let contact = Contact::new()
            .full_name("Jane Doe")
            .email("jane@example.com")
            .phone("+1-555-0123")
            .organization("Acme Corp")
            .build();

        assert_eq!(contact.get_full_name(), Some("Jane Doe"));
        assert_eq!(contact.get_email(), Some("jane@example.com"));
        assert_eq!(contact.get_phone(), Some("+1-555-0123"));
        assert_eq!(contact.get_organization(), Some("Acme Corp"));
    }

    #[test]
    fn contact_typed_email() {
        let contact = Contact::new()
            .full_name("Test")
            .email_typed("work@example.com", vec!["WORK".to_string()])
            .email_typed("home@example.com", vec!["HOME".to_string()])
            .build();

        assert_eq!(contact.get_emails().len(), 2);
        assert_eq!(contact.get_emails()[0].types, vec!["WORK"]);
    }

    #[test]
    fn vcard_escape_roundtrip() {
        let original = "Hello, World\\test\nnewline";
        let escaped = vcard_escape(original);
        let unescaped = vcard_unescape(&escaped);
        assert_eq!(unescaped, original);
    }
}