use crate::{
dav::{FindCollections, FoundCollection, WebDavError},
names,
requests::{DavRequest, ParseResponseError, PreparedRequest},
};
pub struct FindAddressBooks<'a> {
inner: FindCollections<'a>,
}
impl<'a> FindAddressBooks<'a> {
#[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 }
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct FindAddressBooksResponse {
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);
}
}