Skip to main content

io_webdav/rfc4791/item/
update.rs

1//! `update-item` coroutine: PUT raw iCalendar bytes against an
2//! existing calendar item.
3//!
4//! Supports the optional `If-Match` precondition so callers can gate
5//! the write on the last-known ETag (RFC 9110 ยง13.1.1).
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//!     rfc4791::item::update::UpdateItem,
18//!     rfc4918::WebdavAuth,
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 ical = b"BEGIN:VCALENDAR\r\n...\r\nEND:VCALENDAR\r\n".to_vec();
29//! let mut coroutine = UpdateItem::new(
30//!     &base_url,
31//!     &auth,
32//!     "io-webdav",
33//!     "/dav/calendars/personal/",
34//!     "event-1",
35//!     ical,
36//!     Some("\"abc123\""),
37//! );
38//! let mut arg = None;
39//!
40//! let updated = loop {
41//!     match coroutine.resume(arg.take()) {
42//!         WebdavCoroutineState::Yielded(WebdavYield::WantsWrite(bytes)) => {
43//!             stream.write_all(&bytes).unwrap();
44//!         }
45//!         WebdavCoroutineState::Yielded(WebdavYield::WantsRead) => {
46//!             let n = stream.read(&mut buf).unwrap();
47//!             arg = Some(&buf[..n]);
48//!         }
49//!         WebdavCoroutineState::Complete(Ok(updated)) => break updated,
50//!         WebdavCoroutineState::Complete(Err(err)) => panic!("{err}"),
51//!     }
52//! };
53//!
54//! println!("updated {} (etag {:?})", updated.id, updated.etag);
55//! ```
56
57use core::mem;
58
59use alloc::{
60    string::{String, ToString},
61    vec::Vec,
62};
63
64use log::trace;
65use url::Url;
66
67use crate::{
68    coroutine::*,
69    rfc4791::item::join_path,
70    rfc4918::{
71        WebdavAuth,
72        put::{Put, PutArgs},
73        read_etag,
74        send::{SendError, SendOk},
75    },
76    webdav_try,
77};
78
79/// Coroutine that updates a calendar item.
80#[derive(Debug)]
81pub struct UpdateItem {
82    id: String,
83    state: State,
84}
85
86impl UpdateItem {
87    /// Builds a new `update-item` coroutine.
88    pub fn new(
89        base_url: &Url,
90        auth: &WebdavAuth,
91        user_agent: &str,
92        calendar_path: &str,
93        id: &str,
94        ical: Vec<u8>,
95        if_match: Option<&str>,
96    ) -> Self {
97        let path = join_path(calendar_path, id);
98        let put = Put::new(PutArgs {
99            base_url,
100            auth,
101            user_agent,
102            path: &path,
103            content_type: "text/calendar; charset=utf-8",
104            body: ical,
105            if_match,
106            if_none_match: None,
107        });
108        Self {
109            id: id.to_string(),
110            state: State::Put(put),
111        }
112    }
113}
114
115impl WebdavCoroutine for UpdateItem {
116    type Yield = WebdavYield;
117    type Return = Result<UpdateItemOk, SendError>;
118
119    fn resume(&mut self, arg: Option<&[u8]>) -> WebdavCoroutineState<Self::Yield, Self::Return> {
120        trace!("sending request");
121        match &mut self.state {
122            State::Put(put) => {
123                let SendOk { response, .. } = webdav_try!(put, arg);
124                let etag = read_etag(&response);
125                let id = mem::take(&mut self.id);
126                WebdavCoroutineState::Complete(Ok(UpdateItemOk { id, etag }))
127            }
128        }
129    }
130}
131
132#[derive(Debug)]
133enum State {
134    Put(Put),
135}
136
137/// Outcome of a successful
138/// [`UpdateItem`] resume.
139#[derive(Clone, Debug)]
140pub struct UpdateItemOk {
141    /// Item identifier (as supplied by the caller).
142    pub id: String,
143    /// Updated entity tag returned by the server, when present.
144    pub etag: Option<String>,
145}