libdav 0.10.3

CalDAV and CardDAV client implementations.
Documentation
//! Find address books under an address book home set.

use crate::{
    dav::{FindCollections, FoundCollection, WebDavError},
    names,
    requests::{DavRequest, ParseResponseError, PreparedRequest},
};

/// Request to find address books under an address book home set.
///
/// Sends a PROPFIND request with depth 1 to discover address books and their properties.
///
/// # Example
///
/// ```
/// # use libdav::carddav::FindAddressBooks;
/// # use libdav::CardDavClient;
/// # use tower_service::Service;
/// # use http::Uri;
/// # async fn example<C>(carddav: &CardDavClient<C>) -> Result<(), Box<dyn std::error::Error>>
/// # where
/// #     C: Service<http::Request<String>, Response = http::Response<hyper::body::Incoming>> + Send + Sync,
/// #     C::Error: std::error::Error + Send + Sync,
/// # {
/// let addressbook_home_set = Uri::from_static("/addressbooks/user/");
/// let response = carddav.request(
///     FindAddressBooks::new(&addressbook_home_set)
/// ).await?;
///
/// for addressbook in response.addressbooks {
///     println!("Found address book: {}", addressbook.href);
///     println!("  Supports sync: {}", addressbook.supports_sync);
/// }
/// # Ok(())
/// # }
/// ```
pub struct FindAddressBooks<'a> {
    inner: FindCollections<'a>,
}

impl<'a> FindAddressBooks<'a> {
    /// Create a new request to find address books.
    ///
    /// `addressbook_home_set` is the URI of the address book home set.
    #[must_use]
    pub fn new(addressbook_home_set: &'a hyper::Uri) -> Self {
        let inner =
            FindCollections::new(addressbook_home_set).with_collection_type(&names::ADDRESSBOOK);
        Self { inner }
    }
}

/// Response from a [`FindAddressBooks`] request.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct FindAddressBooksResponse {
    /// Address books found.
    pub addressbooks: Vec<FoundCollection>,
}

impl DavRequest for FindAddressBooks<'_> {
    type Response = FindAddressBooksResponse;
    type ParseError = ParseResponseError;
    type Error<E> = WebDavError<E>;

    fn prepare_request(&self) -> Result<PreparedRequest, http::Error> {
        self.inner.prepare_request()
    }

    fn parse_response(
        &self,
        parts: &http::response::Parts,
        body: &[u8],
    ) -> Result<Self::Response, ParseResponseError> {
        let response = self.inner.parse_response(parts, body)?;
        Ok(FindAddressBooksResponse {
            addressbooks: response.collections,
        })
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use http::StatusCode;

    #[test]
    fn test_prepare_request() {
        let home_set = hyper::Uri::from_static("/addressbooks/user/");
        let req = FindAddressBooks::new(&home_set);
        let prepared = req.prepare_request().unwrap();

        assert_eq!(prepared.path, "/addressbooks/user/");
        assert_eq!(
            prepared.headers,
            vec![
                ("Depth".to_string(), "1".to_string()),
                (
                    "Content-Type".to_string(),
                    "application/xml; charset=utf-8".to_string()
                )
            ]
        );
    }

    #[test]
    fn test_parse_response() {
        let home_set = hyper::Uri::from_static("/addressbooks/user/");
        let req = FindAddressBooks::new(&home_set);
        let response_xml = r#"<?xml version="1.0"?>
            <multistatus xmlns="DAV:" xmlns:CARD="urn:ietf:params:xml:ns:carddav">
                <response>
                    <href>/addressbooks/user/contacts/</href>
                    <propstat>
                        <prop>
                            <resourcetype>
                                <collection/>
                                <CARD:addressbook/>
                            </resourcetype>
                            <getetag>"xyz789"</getetag>
                        </prop>
                        <status>HTTP/1.1 200 OK</status>
                    </propstat>
                </response>
            </multistatus>"#;

        let response = http::Response::builder()
            .status(StatusCode::MULTI_STATUS)
            .body(())
            .unwrap();
        let (parts, ()) = response.into_parts();
        let result = req.parse_response(&parts, response_xml.as_bytes()).unwrap();

        assert_eq!(result.addressbooks.len(), 1);
        assert_eq!(result.addressbooks[0].href, "/addressbooks/user/contacts/");
        assert_eq!(result.addressbooks[0].etag, Some("\"xyz789\"".to_string()));
        assert!(!result.addressbooks[0].supports_sync);
    }
}