io_webdav/rfc6352/addressbook/create.rs
1//! `create-addressbook` coroutine: extended `MKCOL` (RFC 5689)
2//! against the addressbook home-set URL.
3//!
4//! # Example
5//!
6//! ```rust,no_run
7//! use std::{
8//! io::{Read, Write},
9//! net::TcpStream,
10//! };
11//!
12//! use io_webdav::{
13//! coroutine::{WebdavCoroutine, WebdavCoroutineState, WebdavYield},
14//! rfc4918::WebdavAuth,
15//! rfc6352::addressbook::{Addressbook, create::CreateAddressbook},
16//! };
17//! use url::Url;
18//!
19//! // Ready stream needed (TCP-connected, TLS-negociated)
20//! let mut stream = TcpStream::connect("dav.example.org:443").unwrap();
21//! let mut buf = [0u8; 4096];
22//!
23//! let base_url: Url = "https://dav.example.org/".parse().unwrap();
24//! let auth = WebdavAuth::None;
25//! let addressbook = Addressbook {
26//! id: "contacts".into(),
27//! display_name: Some("Contacts".into()),
28//! ..Default::default()
29//! };
30//! let mut coroutine =
31//! CreateAddressbook::new(&base_url, &auth, "io-webdav", "/dav/addressbooks/", &addressbook);
32//! let mut arg = None;
33//!
34//! loop {
35//! match coroutine.resume(arg.take()) {
36//! WebdavCoroutineState::Yielded(WebdavYield::WantsWrite(bytes)) => {
37//! stream.write_all(&bytes).unwrap();
38//! }
39//! WebdavCoroutineState::Yielded(WebdavYield::WantsRead) => {
40//! let n = stream.read(&mut buf).unwrap();
41//! arg = Some(&buf[..n]);
42//! }
43//! WebdavCoroutineState::Complete(Ok(_)) => break,
44//! WebdavCoroutineState::Complete(Err(err)) => panic!("{err}"),
45//! }
46//! }
47//! ```
48
49use log::trace;
50use url::Url;
51
52use crate::{
53 coroutine::*,
54 rfc4918::{WebdavAuth, mkcol::Mkcol, send::SendError},
55 rfc6352::addressbook::{ADDRESSBOOK, Addressbook, join_path, property_set},
56};
57
58/// Coroutine that creates an addressbook collection.
59#[derive(Debug)]
60pub struct CreateAddressbook {
61 state: State,
62}
63
64impl CreateAddressbook {
65 /// Builds a new `create-addressbook` coroutine.
66 pub fn new(
67 base_url: &Url,
68 auth: &WebdavAuth,
69 user_agent: &str,
70 home_set_path: &str,
71 addressbook: &Addressbook,
72 ) -> Self {
73 let path = join_path(home_set_path, &addressbook.id);
74 let set = property_set(addressbook);
75 let mkcol = Mkcol::new(base_url, auth, user_agent, &path, &[ADDRESSBOOK], &set);
76 Self {
77 state: State::Mkcol(mkcol),
78 }
79 }
80}
81
82impl WebdavCoroutine for CreateAddressbook {
83 type Yield = WebdavYield;
84 type Return = Result<(), SendError>;
85
86 fn resume(&mut self, arg: Option<&[u8]>) -> WebdavCoroutineState<Self::Yield, Self::Return> {
87 trace!("sending request");
88 match &mut self.state {
89 State::Mkcol(mkcol) => mkcol.resume(arg),
90 }
91 }
92}
93
94#[derive(Debug)]
95enum State {
96 Mkcol(Mkcol),
97}