io_webdav/rfc6352/card/list.rs
1//! `list-cards` coroutine: REPORT `addressbook-query` against an
2//! addressbook collection.
3//!
4//! Stays byte-oriented: the vCard payload is returned as raw bytes
5//! and parsed by io-addressbook.
6//!
7//! # Example
8//!
9//! ```rust,no_run
10//! use std::{
11//! io::{Read, Write},
12//! net::TcpStream,
13//! };
14//!
15//! use io_webdav::{
16//! coroutine::{WebdavCoroutine, WebdavCoroutineState, WebdavYield},
17//! rfc4918::WebdavAuth,
18//! rfc6352::card::list::ListCards,
19//! };
20//! use url::Url;
21//!
22//! // Ready stream needed (TCP-connected, TLS-negociated)
23//! let mut stream = TcpStream::connect("dav.example.org:443").unwrap();
24//! let mut buf = [0u8; 4096];
25//!
26//! let base_url: Url = "https://dav.example.org/".parse().unwrap();
27//! let auth = WebdavAuth::None;
28//! let mut coroutine =
29//! ListCards::new(&base_url, &auth, "io-webdav", "/dav/addressbooks/contacts/");
30//! let mut arg = None;
31//!
32//! let cards = loop {
33//! match coroutine.resume(arg.take()) {
34//! WebdavCoroutineState::Yielded(WebdavYield::WantsWrite(bytes)) => {
35//! stream.write_all(&bytes).unwrap();
36//! }
37//! WebdavCoroutineState::Yielded(WebdavYield::WantsRead) => {
38//! let n = stream.read(&mut buf).unwrap();
39//! arg = Some(&buf[..n]);
40//! }
41//! WebdavCoroutineState::Complete(Ok(cards)) => break cards,
42//! WebdavCoroutineState::Complete(Err(err)) => panic!("{err}"),
43//! }
44//! };
45//!
46//! println!("{} cards", cards.len());
47//! ```
48
49use alloc::collections::BTreeSet;
50
51use log::trace;
52use url::Url;
53
54use crate::{
55 coroutine::*,
56 rfc4918::{WebdavAuth, report::Report, send::SendError},
57 rfc6352::{
58 addressbook::addressbook_query_body,
59 card::{CARD_PROPS, CardEntry, card_from_entry},
60 },
61 webdav_try,
62};
63
64/// Coroutine that lists cards inside an addressbook via REPORT
65/// `addressbook-query`.
66#[derive(Debug)]
67pub struct ListCards {
68 state: State,
69}
70
71impl ListCards {
72 /// Builds a new `list-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(CARD_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 ListCards {
88 type Yield = WebdavYield;
89 type Return = Result<BTreeSet<CardEntry>, 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 cards = multistatus
97 .responses
98 .iter()
99 .filter_map(card_from_entry)
100 .collect();
101 WebdavCoroutineState::Complete(Ok(cards))
102 }
103 }
104 }
105}
106
107#[derive(Debug)]
108enum State {
109 Report(Report),
110}