minicaldav 0.1.3

Minimal caldav client
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
// minicaldav: Small and easy CalDAV client.
// Copyright (C) 2022 Florian Loers
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program.  If not, see <http://www.gnu.org/licenses/>.

//! CalDAV client implementation using ureq.

use std::time::{SystemTime, UNIX_EPOCH};
use ureq::Agent;
use url::Url;

/// Send a PROPFIND to the given url using the given HTTP Basic authorization and search the result XML for a value.
/// # Arguments
/// - client: ureq Agent
/// - username: used for HTTP Basic auth
/// - password: used for HTTP Basic auth
/// - url: The caldav endpoint url
/// - body: The CalDAV request body to send via PROPFIND
/// - prop_path: The path in the response XML the get the XML text value from.
/// - depth: Value for the Depth field
pub fn propfind_get(
    client: Agent,
    username: &str,
    password: &str,
    url: &Url,
    body: &str,
    prop_path: &[&str],
    depth: &str,
) -> Result<(String, xmltree::Element), Error> {
    let auth = format!(
        "Basic {}",
        base64::encode(format!("{}:{}", username, password))
    );
    let reader = client
        .request("PROPFIND", url.as_str())
        .set("Authorization", &auth)
        .set("CONTENT_TYPE", "application/xml")
        .set("Depth", depth)
        .send_bytes(body.as_bytes())?
        .into_reader();
    let root = xmltree::Element::parse(reader)?;
    let mut element = &root;
    let mut searched = 0;
    for prop in prop_path {
        for e in &element.children {
            if let Some(child) = e.as_element() {
                if child.name == *prop {
                    searched += 1;
                    element = child;
                    break;
                }
            }
        }
    }

    if searched != prop_path.len() {
        Err(Error {
            kind: ErrorKind::Parsing,
            message: format!("Could not find data {:?} in PROPFIND response.", prop_path),
        })
    } else {
        Ok((
            element
                .get_text()
                .map(|s| s.to_string())
                .unwrap_or_else(|| "".to_string()),
            root,
        ))
    }
}

pub static USER_PRINCIPAL_REQUEST: &str = r#"
    <d:propfind xmlns:d="DAV:">
       <d:prop>
           <d:current-user-principal />
       </d:prop>
    </d:propfind>
"#;

/// Get the CalDAV principal URL for the given credentials from the caldav server.
pub fn get_principal_url(
    client: Agent,
    username: &str,
    password: &str,
    url: &Url,
) -> Result<Url, Error> {
    let principal_url = propfind_get(
        client,
        username,
        password,
        url,
        USER_PRINCIPAL_REQUEST,
        &[
            "response",
            "propstat",
            "prop",
            "current-user-principal",
            "href",
        ],
        "0",
    )?
    .0;
    Ok(url.join(&principal_url)?)
}

pub static HOMESET_REQUEST: &str = r#"
    <d:propfind xmlns:d="DAV:" xmlns:c="urn:ietf:params:xml:ns:caldav" >
      <d:self/>
      <d:prop>
        <c:calendar-home-set />
      </d:prop>
    </d:propfind>
"#;

/// Get the homeset url for the given credentials from the caldav server.
pub fn get_home_set_url(
    client: Agent,
    username: &str,
    password: &str,
    url: &Url,
) -> Result<Url, Error> {
    let principal_url = get_principal_url(client.clone(), username, password, url)?;
    let homeset_url = propfind_get(
        client,
        username,
        password,
        &principal_url,
        HOMESET_REQUEST,
        &["response", "propstat", "prop", "calendar-home-set", "href"],
        "0",
    )?
    .0;
    Ok(url.join(&homeset_url)?)
}

pub static CALENDARS_REQUEST: &str = r#"
    <d:propfind xmlns:d="DAV:" xmlns:c="urn:ietf:params:xml:ns:caldav" >
       <d:prop>
         <d:displayname />
         <d:resourcetype />
         <c:supported-calendar-component-set />
       </d:prop>
    </d:propfind>
"#;

/// Get calendars for the given credentials.
pub fn get_calendars(
    client: Agent,
    username: &str,
    password: &str,
    base_url: &Url,
) -> Result<Vec<CalendarRef>, Error> {
    let homeset_url = get_home_set_url(client.clone(), username, password, base_url)?;
    let mut calendars = Vec::new();
    let root = propfind_get(
        client,
        username,
        password,
        &homeset_url,
        CALENDARS_REQUEST,
        &[],
        "1",
    )?
    .1;
    for response in &root.children {
        if let Some(response) = response.as_element() {
            let name = response
                .get_child("propstat")
                .and_then(|e| e.get_child("prop"))
                .and_then(|e| e.get_child("displayname"))
                .and_then(|e| e.get_text());
            let is_calendar = response
                .get_child("propstat")
                .and_then(|e| e.get_child("prop"))
                .and_then(|e| e.get_child("resourcetype"))
                .map(|e| e.get_child("calendar").is_some())
                .unwrap_or(false);
            let supports_vevents = response
                .get_child("propstat")
                .and_then(|e| e.get_child("prop"))
                .and_then(|e| e.get_child("supported-calendar-component-set"))
                .map(|e| {
                    for c in &e.children {
                        if let Some(child) = c.as_element() {
                            if child.name == "comp" {
                                if let Some(name) = child.attributes.get("name") {
                                    if name == "VEVENT" {
                                        return true;
                                    }
                                }
                            }
                        }
                    }
                    false
                })
                .unwrap_or(false);
            let href = response.get_child("href").and_then(|e| e.get_text());

            if href.is_none() || name.is_none() || !is_calendar || !supports_vevents {
                continue;
            }
            calendars.push(CalendarRef {
                url: base_url.join(&href.unwrap()).unwrap(),
                name: name.unwrap().to_string(),
            })
        }
    }
    Ok(calendars)
}

pub struct CalendarRef {
    pub url: Url,
    pub name: String,
}

impl std::fmt::Debug for CalendarRef {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("CalendarRef")
            .field("url", &self.url.to_string())
            .field("name", &self.name)
            .finish()
    }
}

#[derive(Clone)]
pub struct EventRef {
    pub etag: Option<String>,
    pub url: Url,
    pub data: String,
}

impl std::fmt::Debug for EventRef {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("EventRef")
            .field("etag", &self.etag)
            .field("url", &self.url.to_string())
            .field("data", &self.data)
            .finish()
    }
}

pub static CALENDAR_EVENTS_REQUEST: &str = r#"
    <c:calendar-query xmlns:d="DAV:" xmlns:c="urn:ietf:params:xml:ns:caldav">
        <d:prop>
            <d:getetag />
            <c:calendar-data />
        </d:prop>
        <c:filter>
            <c:comp-filter name="VCALENDAR">
                <c:comp-filter name="VEVENT" />
            </c:comp-filter>
        </c:filter>
    </c:calendar-query>
"#;

/// Get ICAL formatted events from the CalDAV server.
pub fn get_events(
    client: Agent,
    username: &str,
    password: &str,
    base_url: &Url,
    calendar_ref: &CalendarRef,
) -> Result<Vec<EventRef>, Error> {
    let auth = format!(
        "Basic {}",
        base64::encode(format!("{}:{}", username, password))
    );

    let reader = client
        .request("REPORT", calendar_ref.url.as_str())
        .set("Authorization", &auth)
        .set("CONTENT_TYPE", "application/xml")
        .send_bytes(CALENDAR_EVENTS_REQUEST.as_bytes())?
        .into_reader();

    let root = xmltree::Element::parse(reader)?;
    let mut events = Vec::new();
    for c in &root.children {
        if let Some(child) = c.as_element() {
            let href = child.get_child("href").and_then(|e| e.get_text());
            let etag = child
                .get_child("propstat")
                .and_then(|e| e.get_child("prop"))
                .and_then(|e| e.get_child("getetag"))
                .and_then(|e| e.get_text())
                .map(|e| e.to_string());
            let data = child
                .get_child("propstat")
                .and_then(|e| e.get_child("prop"))
                .and_then(|e| e.get_child("calendar-data"))
                .and_then(|e| e.get_text());
            if href.is_none() || etag.is_none() || data.is_none() {
                continue;
            }
            if let Ok(url) = base_url.join(&href.unwrap()) {
                events.push(EventRef {
                    url,
                    data: data.unwrap().to_string(),
                    etag,
                })
            }
        }
    }

    Ok(events)
}

/// Save the given event on the CalDAV server.
/// If no event for the events url exist it will create a new event.
/// Otherwise this is an update operation.
pub fn save_event(
    client: Agent,
    username: &str,
    password: &str,
    event_ref: EventRef,
) -> Result<EventRef, Error> {
    let auth = format!(
        "Basic {}",
        base64::encode(format!("{}:{}", username, password))
    );

    let response = client
        .put(event_ref.url.as_str())
        .set("Content-Type", "text/calendar")
        .set("Content-Length", &event_ref.data.len().to_string())
        .set("Authorization", &auth)
        .send(event_ref.data.as_bytes())?;

    if let Some(etag) = response.header("ETag") {
        Ok(EventRef {
            etag: Some(etag.into()),
            ..event_ref
        })
    } else {
        Ok(EventRef {
            etag: Some(
                SystemTime::now()
                    .duration_since(UNIX_EPOCH)
                    .map(|t| t.as_millis().to_string())
                    .unwrap_or_else(|_| "0".to_string()),
            ),
            ..event_ref
        })
    }
}

/// Delete the given event from the CalDAV server.
pub fn remove_event(
    client: Agent,
    username: &str,
    password: &str,
    event_ref: EventRef,
) -> Result<(), Error> {
    let auth = format!(
        "Basic {}",
        base64::encode(format!("{}:{}", username, password))
    );

    let _response = client
        .delete(event_ref.url.as_str())
        .set("Authorization", &auth)
        .call()?;

    Ok(())
}

/// Errors that may occur during CalDAV operations.
#[derive(Debug)]
pub struct Error {
    pub kind: ErrorKind,
    pub message: String,
}

#[derive(Debug)]
pub enum ErrorKind {
    Http,
    Parsing,
}

impl From<ureq::Error> for Error {
    fn from(e: ureq::Error) -> Self {
        Self {
            kind: ErrorKind::Http,
            message: format!("{:?}", e),
        }
    }
}

impl From<xmltree::ParseError> for Error {
    fn from(e: xmltree::ParseError) -> Self {
        Self {
            kind: ErrorKind::Parsing,
            message: e.to_string(),
        }
    }
}

impl From<url::ParseError> for Error {
    fn from(e: url::ParseError) -> Self {
        Self {
            kind: ErrorKind::Parsing,
            message: e.to_string(),
        }
    }
}