libdav 0.10.3

CalDAV and CardDAV client implementations.
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
//! List calendar resources, with optional filtering.

use http::Method;

use crate::{
    Depth,
    dav::{ListedResource, WebDavError, extract_listed_resources},
    names,
    requests::{DavRequest, ParseResponseError, PreparedRequest, xml_content_type_header},
    xmlutils::XmlNode,
};

/// Valid component types for calendar resource filtering.
pub const VALID_COMPONENT_TYPES: &[&str] = &["VEVENT", "VTODO", "VJOURNAL", "VFREEBUSY"];

/// Error returned when an invalid component type is specified.
#[derive(thiserror::Error, Debug, Clone, PartialEq, Eq)]
#[error("invalid component type")]
pub struct InvalidComponentType;

/// Error returned when an invalid time range format is specified.
#[derive(thiserror::Error, Debug, Clone, PartialEq, Eq)]
#[error("invalid time range format, expected YYYYMMDDTHHMMSSZ")]
pub struct InvalidTimeRange;

/// Validate that a string is in iCalendar UTC format: `YYYYMMDDTHHMMSSZ`.
fn is_valid_icalendar_utc(s: &str) -> bool {
    if s.len() != 16 {
        return false;
    }
    let bytes = s.as_bytes();
    // YYYYMMDDTHHMMSSZ
    // 0123456789012345
    bytes.iter().take(8).all(u8::is_ascii_digit)
        && bytes.get(8) == Some(&b'T')
        && bytes.iter().skip(9).take(6).all(u8::is_ascii_digit)
        && bytes.get(15) == Some(&b'Z')
}

/// Filter criteria for listing calendar resources.
#[derive(Debug, Clone)]
// TODO: rename to ComponentFilter
pub(super) enum CalendarFilter<'a> {
    /// No filtering.
    All,
    /// Filter by component type with optional time range.
    Component {
        /// Component type to filter for (e.g., "VEVENT", "VTODO").
        component_type: &'a str,
        /// Optional start of time range in iCalendar UTC format (`YYYYMMDDTHHMMSSZ`).
        start: Option<&'a str>,
        /// Optional end of time range in iCalendar UTC format (`YYYYMMDDTHHMMSSZ`).
        end: Option<&'a str>,
    },
}

/// Request to list calendar resources in a collection.
///
/// Unlike [`crate::dav::ListResources`], this request supports filtering by date range and
/// component type.
///
/// Returns metadata only (href, etag, content-type, resource-type), not the actual resource
/// content. For fetching actual resource data, use [`crate::caldav::GetCalendarResources`].
///
/// # Filtering
///
/// By default, no filtering is applied and all calendar resources are returned. Use
/// [`with_component`] or [`with_component_and_time_range`] to filter by component type
/// and/or time range.
///
/// Per RFC 4791, time-range filtering requires specifying a component type.
///
/// [`with_component`]: ListCalendarResources::with_component
/// [`with_component_and_time_range`]: ListCalendarResources::with_component_and_time_range
#[derive(Debug, Clone)]
pub struct ListCalendarResources<'a> {
    collection_href: &'a str,
    filter: CalendarFilter<'a>,
}

impl<'a> ListCalendarResources<'a> {
    /// Create a new request to list calendar resources in the given collection.
    ///
    /// `collection_href` should be a path relative to the server's base URL, typically
    /// ending with a trailing slash.
    ///
    /// By default, no filtering is applied and all calendar resources are returned.
    #[must_use]
    pub fn new(collection_href: &'a str) -> Self {
        Self {
            collection_href,
            filter: CalendarFilter::All,
        }
    }

    /// Filter resources by component type.
    ///
    /// Only resources containing the specified component type will be returned.
    ///
    /// # Errors
    ///
    /// Returns [`InvalidComponentType`] if the component type is not one of:
    /// `VEVENT`, `VTODO`, `VJOURNAL`, or `VFREEBUSY`.
    ///
    /// See [`VALID_COMPONENT_TYPES`] for the list of valid types.
    pub fn with_component(mut self, component_type: &'a str) -> Result<Self, InvalidComponentType> {
        if !VALID_COMPONENT_TYPES.contains(&component_type) {
            return Err(InvalidComponentType);
        }
        self.filter = CalendarFilter::Component {
            component_type,
            start: None,
            end: None,
        };
        Ok(self)
    }

    /// Filter resources by component type and time range.
    ///
    /// Only resources containing the specified component type that overlap with the
    /// given time range will be returned.
    ///
    /// Both `start` and `end` are optional. Dates should be in iCalendar UTC format:
    /// `YYYYMMDDTHHMMSSZ` (e.g., `20240101T000000Z`).
    ///
    /// - If only `start` is provided, returns resources that end after the start date.
    /// - If only `end` is provided, returns resources that start before the end date.
    /// - If both are provided, returns resources that overlap with the time range.
    ///
    /// # Errors
    ///
    /// Returns [`InvalidComponentType`] if the component type is not valid.
    /// Returns [`InvalidTimeRange`] if the format of `start` or `end` is invalid.
    pub fn with_component_and_time_range(
        mut self,
        component_type: &'a str,
        start: Option<&'a str>,
        end: Option<&'a str>,
    ) -> Result<Self, ComponentFilterError> {
        if !VALID_COMPONENT_TYPES.contains(&component_type) {
            return Err(ComponentFilterError::InvalidComponentType);
        }
        if start.is_some_and(|s| !is_valid_icalendar_utc(s)) {
            return Err(ComponentFilterError::InvalidTimeRange);
        }
        if end.is_some_and(|e| !is_valid_icalendar_utc(e)) {
            return Err(ComponentFilterError::InvalidTimeRange);
        }
        self.filter = CalendarFilter::Component {
            component_type,
            start,
            end,
        };
        Ok(self)
    }
}

/// Error returned when setting component type with time range fails.
#[derive(thiserror::Error, Debug, Clone, PartialEq, Eq)]
pub enum ComponentFilterError {
    /// Component type is invalid.
    #[error("invalid component type")]
    InvalidComponentType,
    /// Input date has invalid format.
    #[error("invalid time range format, expected YYYYMMDDTHHMMSSZ")]
    InvalidTimeRange,
}

impl From<InvalidComponentType> for ComponentFilterError {
    fn from(_: InvalidComponentType) -> Self {
        Self::InvalidComponentType
    }
}

impl From<InvalidTimeRange> for ComponentFilterError {
    fn from(_: InvalidTimeRange) -> Self {
        Self::InvalidTimeRange
    }
}

/// Response from a [`ListCalendarResources`] request.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ListCalendarResourcesResponse {
    /// Resources in the collection matching the query.
    pub resources: Vec<ListedResource>,
}

impl DavRequest for ListCalendarResources<'_> {
    type Response = ListCalendarResourcesResponse;
    type ParseError = ParseResponseError;
    type Error<E> = WebDavError<E>;

    fn prepare_request(&self) -> Result<PreparedRequest, http::Error> {
        let component_filter = match &self.filter {
            CalendarFilter::All => {
                vec![]
            }
            CalendarFilter::Component {
                component_type,
                start,
                end,
            } => {
                let time_range_attrs: Vec<(&str, &str)> = match (start, end) {
                    (Some(s), Some(e)) => vec![("start", *s), ("end", *e)],
                    (Some(s), None) => vec![("start", *s)],
                    (None, Some(e)) => vec![("end", *e)],
                    (None, None) => vec![],
                };

                let comp_filter_children = if time_range_attrs.is_empty() {
                    vec![]
                } else {
                    vec![XmlNode::new(&names::TIME_RANGE).with_attributes(time_range_attrs)]
                };

                let comp_filter = XmlNode::new(&names::COMP_FILTER)
                    .with_attributes(vec![("name", component_type)])
                    .with_children(comp_filter_children);

                vec![
                    XmlNode::new(&names::COMP_FILTER)
                        .with_attributes(vec![("name", "VCALENDAR")])
                        .with_children(vec![comp_filter]),
                ]
            }
        };

        let filter = XmlNode::new(&names::FILTER).with_children(component_filter);

        let mut prop = XmlNode::new(&names::PROP);
        prop.children = vec![
            XmlNode::new(&names::RESOURCETYPE),
            XmlNode::new(&names::GETCONTENTTYPE),
            XmlNode::new(&names::GETETAG),
        ];

        let mut calendar_query = XmlNode::new(&names::CALENDAR_QUERY);
        calendar_query.children = vec![prop, filter];

        let body = calendar_query.render_node();

        Ok(PreparedRequest {
            method: Method::from_bytes(b"REPORT")?,
            path: self.collection_href.to_string(),
            body,
            headers: vec![
                ("Depth".to_string(), Depth::One.to_string()),
                xml_content_type_header(),
            ],
        })
    }

    fn parse_response(
        &self,
        parts: &http::response::Parts,
        body: &[u8],
    ) -> Result<Self::Response, ParseResponseError> {
        if !parts.status.is_success() {
            return Err(ParseResponseError::BadStatusCode(parts.status));
        }

        let resources = extract_listed_resources(body, self.collection_href)?;
        Ok(ListCalendarResourcesResponse { resources })
    }
}

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

    #[test]
    fn test_prepare_request_no_filter() {
        let req = ListCalendarResources::new("/calendars/personal/");
        let prepared = req.prepare_request().unwrap();

        assert_eq!(prepared.method, Method::from_bytes(b"REPORT").unwrap());
        assert_eq!(prepared.path, "/calendars/personal/");
        assert_eq!(
            prepared.body,
            concat!(
                r#"<C:calendar-query xmlns:D="DAV:" xmlns:C="urn:ietf:params:xml:ns:caldav">"#,
                r#"<D:prop><D:resourcetype/><D:getcontenttype/><D:getetag/></D:prop>"#,
                r#"<C:filter/>"#,
                r#"</C:calendar-query>"#,
            )
        );
        assert_eq!(
            prepared.headers,
            vec![
                ("Depth".to_string(), "1".to_string()),
                (
                    "Content-Type".to_string(),
                    "application/xml; charset=utf-8".to_string()
                )
            ]
        );
    }

    #[test]
    fn test_prepare_request_with_component() {
        let req = ListCalendarResources::new("/calendars/personal/")
            .with_component("VEVENT")
            .unwrap();
        let prepared = req.prepare_request().unwrap();

        assert_eq!(
            prepared.body,
            concat!(
                r#"<C:calendar-query xmlns:D="DAV:" xmlns:C="urn:ietf:params:xml:ns:caldav">"#,
                r#"<D:prop><D:resourcetype/><D:getcontenttype/><D:getetag/></D:prop>"#,
                r#"<C:filter><C:comp-filter name="VCALENDAR">"#,
                r#"<C:comp-filter name="VEVENT"/>"#,
                r#"</C:comp-filter></C:filter>"#,
                r#"</C:calendar-query>"#,
            )
        );
    }

    #[test]
    fn test_prepare_request_with_component_and_start_only() {
        let req = ListCalendarResources::new("/calendars/personal/")
            .with_component_and_time_range("VEVENT", Some("20240101T000000Z"), None)
            .unwrap();
        let prepared = req.prepare_request().unwrap();

        assert_eq!(
            prepared.body,
            concat!(
                r#"<C:calendar-query xmlns:D="DAV:" xmlns:C="urn:ietf:params:xml:ns:caldav">"#,
                r#"<D:prop><D:resourcetype/><D:getcontenttype/><D:getetag/></D:prop>"#,
                r#"<C:filter><C:comp-filter name="VCALENDAR">"#,
                r#"<C:comp-filter name="VEVENT"><C:time-range start="20240101T000000Z"/></C:comp-filter>"#,
                r#"</C:comp-filter></C:filter>"#,
                r#"</C:calendar-query>"#,
            )
        );
    }

    #[test]
    fn test_prepare_request_with_component_and_end_only() {
        let req = ListCalendarResources::new("/calendars/personal/")
            .with_component_and_time_range("VTODO", None, Some("20240201T000000Z"))
            .unwrap();
        let prepared = req.prepare_request().unwrap();

        assert_eq!(
            prepared.body,
            concat!(
                r#"<C:calendar-query xmlns:D="DAV:" xmlns:C="urn:ietf:params:xml:ns:caldav">"#,
                r#"<D:prop><D:resourcetype/><D:getcontenttype/><D:getetag/></D:prop>"#,
                r#"<C:filter><C:comp-filter name="VCALENDAR">"#,
                r#"<C:comp-filter name="VTODO"><C:time-range end="20240201T000000Z"/></C:comp-filter>"#,
                r#"</C:comp-filter></C:filter>"#,
                r#"</C:calendar-query>"#,
            )
        );
    }

    #[test]
    fn test_prepare_request_with_component_and_full_time_range() {
        let req = ListCalendarResources::new("/calendars/personal/")
            .with_component_and_time_range(
                "VJOURNAL",
                Some("20240101T000000Z"),
                Some("20240201T000000Z"),
            )
            .unwrap();
        let prepared = req.prepare_request().unwrap();

        assert_eq!(
            prepared.body,
            concat!(
                r#"<C:calendar-query xmlns:D="DAV:" xmlns:C="urn:ietf:params:xml:ns:caldav">"#,
                r#"<D:prop><D:resourcetype/><D:getcontenttype/><D:getetag/></D:prop>"#,
                r#"<C:filter><C:comp-filter name="VCALENDAR">"#,
                r#"<C:comp-filter name="VJOURNAL"><C:time-range start="20240101T000000Z" end="20240201T000000Z"/></C:comp-filter>"#,
                r#"</C:comp-filter></C:filter>"#,
                r#"</C:calendar-query>"#,
            )
        );
    }

    #[test]
    fn test_with_component_invalid() {
        let result = ListCalendarResources::new("/calendars/personal/").with_component("INVALID");

        assert_eq!(result.unwrap_err(), InvalidComponentType);
    }

    #[test]
    fn test_with_component_and_time_range_invalid_component() {
        let result = ListCalendarResources::new("/calendars/personal/")
            .with_component_and_time_range("INVALID", Some("20240101T000000Z"), None);

        assert_eq!(
            result.unwrap_err(),
            ComponentFilterError::InvalidComponentType
        );
    }

    #[test]
    fn test_with_component_and_time_range_invalid_start() {
        let result = ListCalendarResources::new("/calendars/personal/")
            .with_component_and_time_range("VEVENT", Some("invalid"), None);

        assert_eq!(result.unwrap_err(), ComponentFilterError::InvalidTimeRange);
    }

    #[test]
    fn test_with_component_and_time_range_invalid_end() {
        let result = ListCalendarResources::new("/calendars/personal/")
            .with_component_and_time_range("VEVENT", None, Some("2024-01-01"));

        assert_eq!(result.unwrap_err(), ComponentFilterError::InvalidTimeRange);
    }

    #[test]
    fn test_with_component_and_time_range_missing_z_suffix() {
        let result = ListCalendarResources::new("/calendars/personal/")
            .with_component_and_time_range("VEVENT", Some("20240101T000000"), None);

        assert_eq!(result.unwrap_err(), ComponentFilterError::InvalidTimeRange);
    }

    #[test]
    fn test_parse_response_success() {
        let req = ListCalendarResources::new("/calendars/personal/");
        let body = br#"<?xml version="1.0" encoding="utf-8"?>
<multistatus xmlns="DAV:">
  <response>
    <href>/calendars/personal/</href>
    <propstat>
      <prop>
        <resourcetype><collection/></resourcetype>
      </prop>
      <status>HTTP/1.1 200 OK</status>
    </propstat>
  </response>
  <response>
    <href>/calendars/personal/event1.ics</href>
    <propstat>
      <prop>
        <getetag>"abc123"</getetag>
        <getcontenttype>text/calendar</getcontenttype>
        <resourcetype/>
      </prop>
      <status>HTTP/1.1 200 OK</status>
    </propstat>
  </response>
  <response>
    <href>/calendars/personal/event2.ics</href>
    <propstat>
      <prop>
        <getetag>"def456"</getetag>
        <getcontenttype>text/calendar</getcontenttype>
        <resourcetype/>
      </prop>
      <status>HTTP/1.1 200 OK</status>
    </propstat>
  </response>
</multistatus>"#;

        let response = http::Response::builder()
            .status(StatusCode::MULTI_STATUS)
            .body(())
            .unwrap();
        let (parts, ()) = response.into_parts();
        let result = req.parse_response(&parts, body).unwrap();

        assert_eq!(result.resources.len(), 2);
        assert_eq!(result.resources[0].href, "/calendars/personal/event1.ics");
        assert_eq!(result.resources[0].etag, Some("\"abc123\"".to_string()));
        assert_eq!(
            result.resources[0].content_type,
            Some("text/calendar".to_string())
        );
        assert_eq!(result.resources[1].href, "/calendars/personal/event2.ics");
        assert_eq!(result.resources[1].etag, Some("\"def456\"".to_string()));
    }

    #[test]
    fn test_parse_response_empty() {
        let req = ListCalendarResources::new("/calendars/personal/");
        let body = br#"<?xml version="1.0" encoding="utf-8"?>
<multistatus xmlns="DAV:">
  <response>
    <href>/calendars/personal/</href>
    <propstat>
      <prop>
        <resourcetype><collection/></resourcetype>
      </prop>
      <status>HTTP/1.1 200 OK</status>
    </propstat>
  </response>
</multistatus>"#;

        let response = http::Response::builder()
            .status(StatusCode::MULTI_STATUS)
            .body(())
            .unwrap();
        let (parts, ()) = response.into_parts();
        let result = req.parse_response(&parts, body).unwrap();

        assert!(result.resources.is_empty());
    }

    #[test]
    fn test_parse_response_bad_status() {
        let req = ListCalendarResources::new("/calendars/personal/");
        let response = http::Response::builder()
            .status(StatusCode::FORBIDDEN)
            .body(())
            .unwrap();
        let (parts, ()) = response.into_parts();
        let result = req.parse_response(&parts, b"");

        assert!(matches!(
            result,
            Err(ParseResponseError::BadStatusCode(StatusCode::FORBIDDEN))
        ));
    }
}