Skip to main content

io_webdav/rfc6352/card/
enumerate.rs

1//! `enum-cards` coroutine: REPORT `addressbook-query` requesting ETags
2//! only, against an addressbook collection.
3//!
4//! Enumerates the full card spine (id plus ETag) without downloading
5//! any vCard body; bodies are then batch-fetched with
6//! [`MultigetCards`](crate::rfc6352::card::multiget::MultigetCards).
7//!
8//! # Example
9//!
10//! ```rust,no_run
11//! use std::{
12//!     io::{Read, Write},
13//!     net::TcpStream,
14//! };
15//!
16//! use io_webdav::{
17//!     coroutine::{WebdavCoroutine, WebdavCoroutineState, WebdavYield},
18//!     rfc4918::WebdavAuth,
19//!     rfc6352::card::enumerate::EnumCards,
20//! };
21//! use url::Url;
22//!
23//! // Ready stream needed (TCP-connected, TLS-negociated)
24//! let mut stream = TcpStream::connect("dav.example.org:443").unwrap();
25//! let mut buf = [0u8; 4096];
26//!
27//! let base_url: Url = "https://dav.example.org/".parse().unwrap();
28//! let auth = WebdavAuth::None;
29//! let mut coroutine =
30//!     EnumCards::new(&base_url, &auth, "io-webdav", "/dav/addressbooks/contacts/");
31//! let mut arg = None;
32//!
33//! let refs = loop {
34//!     match coroutine.resume(arg.take()) {
35//!         WebdavCoroutineState::Yielded(WebdavYield::WantsWrite(bytes)) => {
36//!             stream.write_all(&bytes).unwrap();
37//!         }
38//!         WebdavCoroutineState::Yielded(WebdavYield::WantsRead) => {
39//!             let n = stream.read(&mut buf).unwrap();
40//!             arg = Some(&buf[..n]);
41//!         }
42//!         WebdavCoroutineState::Complete(Ok(refs)) => break refs,
43//!         WebdavCoroutineState::Complete(Err(err)) => panic!("{err}"),
44//!     }
45//! };
46//!
47//! println!("{} cards", refs.len());
48//! ```
49
50use alloc::{collections::BTreeSet, string::ToString};
51
52use log::trace;
53use url::Url;
54
55use crate::{
56    coroutine::*,
57    rfc4918::{GETETAG, Property, ResponseEntry, WebdavAuth, report::Report, send::SendError},
58    rfc6352::{addressbook::addressbook_query_body, card::CardRef},
59    webdav_try,
60};
61
62const ENUM_PROPS: &[Property] = &[GETETAG];
63
64/// Coroutine that enumerates card references (id plus ETag, no body)
65/// inside an addressbook via REPORT `addressbook-query`.
66#[derive(Debug)]
67pub struct EnumCards {
68    state: State,
69}
70
71impl EnumCards {
72    /// Builds a new `enum-cards` coroutine.
73    pub fn new(
74        base_url: &Url,
75        auth: &WebdavAuth,
76        user_agent: &str,
77        addressbook_path: &str,
78    ) -> Self {
79        let body = addressbook_query_body(ENUM_PROPS);
80        let report = Report::new(base_url, auth, user_agent, addressbook_path, 1, body);
81        Self {
82            state: State::Report(report),
83        }
84    }
85}
86
87impl WebdavCoroutine for EnumCards {
88    type Yield = WebdavYield;
89    type Return = Result<BTreeSet<CardRef>, SendError>;
90
91    fn resume(&mut self, arg: Option<&[u8]>) -> WebdavCoroutineState<Self::Yield, Self::Return> {
92        trace!("sending request");
93        match &mut self.state {
94            State::Report(report) => {
95                let multistatus = webdav_try!(report, arg);
96                let refs = multistatus
97                    .responses
98                    .iter()
99                    .filter_map(from_entry)
100                    .collect();
101                WebdavCoroutineState::Complete(Ok(refs))
102            }
103        }
104    }
105}
106
107fn from_entry(entry: &ResponseEntry) -> Option<CardRef> {
108    // Skip the collection self-entry: an address object resource never
109    // ends in a slash, but some servers (iCloud) echo the addressbook
110    // itself in the query response, which would otherwise enter the
111    // spine as a bogus card named after the collection.
112    if entry.href.ends_with('/') {
113        return None;
114    }
115
116    let uri = entry.id();
117    let id = uri.trim_end_matches(".vcf");
118    if id.is_empty() {
119        return None;
120    }
121
122    Some(CardRef {
123        id: id.to_string(),
124        uri: uri.to_string(),
125        etag: entry
126            .text(GETETAG)
127            .map(|raw| raw.trim_matches('"').to_string()),
128    })
129}
130
131#[derive(Debug)]
132enum State {
133    Report(Report),
134}