feat: complete CalDAV (RFC 4791) and CardDAV (RFC 6352) implementation
- CalDAV: MKCALENDAR, PROPFIND, PUT/GET/DELETE events, REPORT calendar-query - CardDAV: MKCOL, PROPFIND, PUT/GET/DELETE vCards, REPORT addressbook-query - Fix routing: move CalDAV/CardDAV to top-level merge() with explicit routes - Fix DB schema: VARCHAR(36) -> UUID for entity IDs, vcard_data -> vcard - Fix 15 repository stub methods that returned empty results - Fix vCard parser in ContactStorageAdapter (was hardcoded stub) - All operations tested end-to-end in Docker (201/207/200/204 as expected)
This commit is contained in:
@@ -120,9 +120,7 @@ impl CalDavAdapter {
|
||||
let name_str = std::str::from_utf8(name.as_ref()).unwrap_or("");
|
||||
|
||||
match name_str {
|
||||
s if s == "calendar-query" || s.ends_with(":calendar-query") => in_calendar_query = false,
|
||||
s if s == "calendar-multiget" || s.ends_with(":calendar-multiget") => in_calendar_multiget = false,
|
||||
s if s == "sync-collection" || s.ends_with(":sync-collection") => in_sync_collection = false,
|
||||
// Don't reset report-type flags — they're needed at EOF for decision logic
|
||||
s if s == "prop" || s.ends_with(":prop") => in_prop = false,
|
||||
s if s == "filter" || s.ends_with(":filter") => in_filter = false,
|
||||
s if s == "time-range" || s.ends_with(":time-range") => { /* time-range end, attributes already parsed */ },
|
||||
@@ -515,6 +513,73 @@ impl CalDavAdapter {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Generate PROPFIND response for a single calendar collection + its events
|
||||
pub fn generate_calendar_collection_propfind<W: Write>(
|
||||
writer: W,
|
||||
calendar: &CalendarDto,
|
||||
events: &[CalendarEventDto],
|
||||
request: &PropFindRequest,
|
||||
base_href: &str,
|
||||
depth: &str,
|
||||
) -> Result<()> {
|
||||
let mut xml_writer = Writer::new(writer);
|
||||
|
||||
xml_writer.write_event(Event::Start(BytesStart::new("D:multistatus").with_attributes([
|
||||
("xmlns:D", "DAV:"),
|
||||
("xmlns:C", "urn:ietf:params:xml:ns:caldav"),
|
||||
("xmlns:CS", "http://calendarserver.org/ns/"),
|
||||
])))?;
|
||||
|
||||
// Write the calendar collection itself
|
||||
Self::write_calendar_response(&mut xml_writer, calendar, request, base_href)?;
|
||||
|
||||
// If depth > 0, include event resources
|
||||
if depth != "0" {
|
||||
for event in events {
|
||||
// Write a basic DAV response for each event
|
||||
xml_writer.write_event(Event::Start(BytesStart::new("D:response")))?;
|
||||
|
||||
let event_href = format!("{}{}.ics", base_href, event.ical_uid);
|
||||
xml_writer.write_event(Event::Start(BytesStart::new("D:href")))?;
|
||||
xml_writer.write_event(Event::Text(BytesText::new(&event_href)))?;
|
||||
xml_writer.write_event(Event::End(BytesEnd::new("D:href")))?;
|
||||
|
||||
xml_writer.write_event(Event::Start(BytesStart::new("D:propstat")))?;
|
||||
xml_writer.write_event(Event::Start(BytesStart::new("D:prop")))?;
|
||||
|
||||
// resourcetype (empty for non-collection)
|
||||
xml_writer.write_event(Event::Empty(BytesStart::new("D:resourcetype")))?;
|
||||
|
||||
// getetag
|
||||
xml_writer.write_event(Event::Start(BytesStart::new("D:getetag")))?;
|
||||
xml_writer.write_event(Event::Text(BytesText::new(&format!("\"{}\"", event.id))))?;
|
||||
xml_writer.write_event(Event::End(BytesEnd::new("D:getetag")))?;
|
||||
|
||||
// getcontenttype
|
||||
xml_writer.write_event(Event::Start(BytesStart::new("D:getcontenttype")))?;
|
||||
xml_writer.write_event(Event::Text(BytesText::new("text/calendar; component=vevent")))?;
|
||||
xml_writer.write_event(Event::End(BytesEnd::new("D:getcontenttype")))?;
|
||||
|
||||
// getlastmodified
|
||||
xml_writer.write_event(Event::Start(BytesStart::new("D:getlastmodified")))?;
|
||||
xml_writer.write_event(Event::Text(BytesText::new(&event.updated_at.to_rfc2822())))?;
|
||||
xml_writer.write_event(Event::End(BytesEnd::new("D:getlastmodified")))?;
|
||||
|
||||
xml_writer.write_event(Event::End(BytesEnd::new("D:prop")))?;
|
||||
|
||||
xml_writer.write_event(Event::Start(BytesStart::new("D:status")))?;
|
||||
xml_writer.write_event(Event::Text(BytesText::new("HTTP/1.1 200 OK")))?;
|
||||
xml_writer.write_event(Event::End(BytesEnd::new("D:status")))?;
|
||||
|
||||
xml_writer.write_event(Event::End(BytesEnd::new("D:propstat")))?;
|
||||
xml_writer.write_event(Event::End(BytesEnd::new("D:response")))?;
|
||||
}
|
||||
}
|
||||
|
||||
xml_writer.write_event(Event::End(BytesEnd::new("D:multistatus")))?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Generate a response for calendar events
|
||||
pub fn generate_calendar_events_response<W: Write>(
|
||||
writer: W,
|
||||
|
||||
@@ -0,0 +1,286 @@
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use std::io::Cursor;
|
||||
use std::collections::HashMap;
|
||||
use chrono::{Utc, TimeZone};
|
||||
use crate::application::adapters::caldav_adapter::{CalDavAdapter, CalDavReportType};
|
||||
use crate::application::adapters::webdav_adapter::{PropFindRequest, PropFindType, QualifiedName};
|
||||
use crate::application::dtos::calendar_dto::{CalendarDto, CalendarEventDto};
|
||||
|
||||
fn sample_calendar() -> CalendarDto {
|
||||
CalendarDto {
|
||||
id: "cal-001".to_string(),
|
||||
name: "Personal".to_string(),
|
||||
owner_id: "user-001".to_string(),
|
||||
description: Some("My personal calendar".to_string()),
|
||||
color: Some("#FF0000".to_string()),
|
||||
is_public: false,
|
||||
created_at: Utc.with_ymd_and_hms(2025, 1, 1, 0, 0, 0).unwrap(),
|
||||
updated_at: Utc.with_ymd_and_hms(2025, 1, 15, 12, 0, 0).unwrap(),
|
||||
custom_properties: HashMap::new(),
|
||||
}
|
||||
}
|
||||
|
||||
fn sample_event() -> CalendarEventDto {
|
||||
CalendarEventDto {
|
||||
id: "evt-001".to_string(),
|
||||
calendar_id: "cal-001".to_string(),
|
||||
summary: "Team Meeting".to_string(),
|
||||
description: Some("Weekly team sync".to_string()),
|
||||
location: Some("Conference Room A".to_string()),
|
||||
start_time: Utc.with_ymd_and_hms(2025, 6, 15, 10, 0, 0).unwrap(),
|
||||
end_time: Utc.with_ymd_and_hms(2025, 6, 15, 11, 0, 0).unwrap(),
|
||||
all_day: false,
|
||||
rrule: None,
|
||||
ical_uid: "uid-evt-001@oxicloud".to_string(),
|
||||
created_at: Utc.with_ymd_and_hms(2025, 1, 1, 0, 0, 0).unwrap(),
|
||||
updated_at: Utc.with_ymd_and_hms(2025, 1, 1, 0, 0, 0).unwrap(),
|
||||
}
|
||||
}
|
||||
|
||||
// ========================
|
||||
// MKCALENDAR parsing tests
|
||||
// ========================
|
||||
|
||||
#[test]
|
||||
fn test_parse_mkcalendar_full() {
|
||||
let xml = r#"<?xml version="1.0" encoding="UTF-8"?>
|
||||
<C:mkcalendar xmlns:D="DAV:" xmlns:C="urn:ietf:params:xml:ns:caldav">
|
||||
<D:set>
|
||||
<D:prop>
|
||||
<D:displayname>Work Calendar</D:displayname>
|
||||
<C:calendar-description>Work related events</C:calendar-description>
|
||||
<A:calendar-color xmlns:A="http://apple.com/ns/ical/">#0000FF</A:calendar-color>
|
||||
</D:prop>
|
||||
</D:set>
|
||||
</C:mkcalendar>"#;
|
||||
|
||||
let result = CalDavAdapter::parse_mkcalendar(Cursor::new(xml));
|
||||
assert!(result.is_ok(), "Failed to parse MKCALENDAR: {:?}", result.err());
|
||||
let (name, desc, color) = result.unwrap();
|
||||
assert_eq!(name, "Work Calendar");
|
||||
assert_eq!(desc, Some("Work related events".to_string()));
|
||||
assert_eq!(color, Some("#0000FF".to_string()));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_parse_mkcalendar_name_only() {
|
||||
let xml = r#"<?xml version="1.0" encoding="UTF-8"?>
|
||||
<C:mkcalendar xmlns:D="DAV:" xmlns:C="urn:ietf:params:xml:ns:caldav">
|
||||
<D:set>
|
||||
<D:prop>
|
||||
<D:displayname>Minimal Calendar</D:displayname>
|
||||
</D:prop>
|
||||
</D:set>
|
||||
</C:mkcalendar>"#;
|
||||
|
||||
let result = CalDavAdapter::parse_mkcalendar(Cursor::new(xml));
|
||||
assert!(result.is_ok());
|
||||
let (name, desc, color) = result.unwrap();
|
||||
assert_eq!(name, "Minimal Calendar");
|
||||
assert!(desc.is_none());
|
||||
assert!(color.is_none());
|
||||
}
|
||||
|
||||
// ========================
|
||||
// REPORT parsing tests
|
||||
// ========================
|
||||
|
||||
#[test]
|
||||
fn test_parse_calendar_query_report() {
|
||||
let xml = r#"<?xml version="1.0" encoding="UTF-8"?>
|
||||
<C:calendar-query xmlns:D="DAV:" xmlns:C="urn:ietf:params:xml:ns:caldav">
|
||||
<D:prop>
|
||||
<D:getetag/>
|
||||
<C:calendar-data/>
|
||||
</D:prop>
|
||||
<C:filter>
|
||||
<C:comp-filter name="VCALENDAR">
|
||||
<C:comp-filter name="VEVENT">
|
||||
<C:time-range start="2025-06-01T00:00:00Z" end="2025-07-01T00:00:00Z"/>
|
||||
</C:comp-filter>
|
||||
</C:comp-filter>
|
||||
</C:filter>
|
||||
</C:calendar-query>"#;
|
||||
|
||||
let result = CalDavAdapter::parse_report(Cursor::new(xml));
|
||||
assert!(result.is_ok(), "Failed to parse report: {:?}", result.err());
|
||||
|
||||
match result.unwrap() {
|
||||
CalDavReportType::CalendarQuery { time_range, props } => {
|
||||
assert!(time_range.is_some(), "Time range should be parsed");
|
||||
let (start, end) = time_range.unwrap();
|
||||
assert_eq!(start, Utc.with_ymd_and_hms(2025, 6, 1, 0, 0, 0).unwrap());
|
||||
assert_eq!(end, Utc.with_ymd_and_hms(2025, 7, 1, 0, 0, 0).unwrap());
|
||||
assert!(!props.is_empty(), "Props should not be empty");
|
||||
}
|
||||
other => panic!("Expected CalendarQuery, got {:?}", other),
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_parse_calendar_multiget_report() {
|
||||
let xml = r#"<?xml version="1.0" encoding="UTF-8"?>
|
||||
<C:calendar-multiget xmlns:D="DAV:" xmlns:C="urn:ietf:params:xml:ns:caldav">
|
||||
<D:prop>
|
||||
<D:getetag/>
|
||||
<C:calendar-data/>
|
||||
</D:prop>
|
||||
<D:href>/caldav/cal-001/evt-001.ics</D:href>
|
||||
<D:href>/caldav/cal-001/evt-002.ics</D:href>
|
||||
</C:calendar-multiget>"#;
|
||||
|
||||
let result = CalDavAdapter::parse_report(Cursor::new(xml));
|
||||
assert!(result.is_ok(), "Failed to parse multiget: {:?}", result.err());
|
||||
|
||||
match result.unwrap() {
|
||||
CalDavReportType::CalendarMultiget { hrefs, props } => {
|
||||
assert_eq!(hrefs.len(), 2);
|
||||
assert_eq!(hrefs[0], "/caldav/cal-001/evt-001.ics");
|
||||
assert_eq!(hrefs[1], "/caldav/cal-001/evt-002.ics");
|
||||
assert!(!props.is_empty());
|
||||
}
|
||||
other => panic!("Expected CalendarMultiget, got {:?}", other),
|
||||
}
|
||||
}
|
||||
|
||||
// ========================
|
||||
// PROPFIND response tests
|
||||
// ========================
|
||||
|
||||
#[test]
|
||||
fn test_generate_calendars_propfind_response() {
|
||||
let calendars = vec![sample_calendar()];
|
||||
let request = PropFindRequest {
|
||||
prop_find_type: PropFindType::AllProp,
|
||||
};
|
||||
|
||||
let mut output = Vec::new();
|
||||
let result = CalDavAdapter::generate_calendars_propfind_response(
|
||||
&mut output,
|
||||
&calendars,
|
||||
&request,
|
||||
"/caldav/",
|
||||
);
|
||||
|
||||
assert!(result.is_ok(), "Failed to generate propfind response: {:?}", result.err());
|
||||
|
||||
let xml_str = String::from_utf8(output).expect("Invalid UTF-8 in response");
|
||||
assert!(xml_str.contains("multistatus"), "Response should contain multistatus element");
|
||||
assert!(xml_str.contains("Personal"), "Response should contain calendar name");
|
||||
assert!(xml_str.contains("cal-001"), "Response should contain calendar ID in href");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_generate_calendar_collection_propfind_depth_0() {
|
||||
let calendar = sample_calendar();
|
||||
let events = vec![sample_event()];
|
||||
let request = PropFindRequest {
|
||||
prop_find_type: PropFindType::AllProp,
|
||||
};
|
||||
|
||||
let mut output = Vec::new();
|
||||
let result = CalDavAdapter::generate_calendar_collection_propfind(
|
||||
&mut output,
|
||||
&calendar,
|
||||
&events,
|
||||
&request,
|
||||
"/caldav/cal-001",
|
||||
"0",
|
||||
);
|
||||
|
||||
assert!(result.is_ok(), "Failed to generate collection propfind: {:?}", result.err());
|
||||
|
||||
let xml_str = String::from_utf8(output).expect("Invalid UTF-8");
|
||||
assert!(xml_str.contains("multistatus"), "Should have multistatus");
|
||||
assert!(xml_str.contains("Personal"), "Should have calendar name");
|
||||
// Depth 0 should NOT include individual event resources
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_generate_calendar_collection_propfind_depth_1() {
|
||||
let calendar = sample_calendar();
|
||||
let events = vec![sample_event()];
|
||||
let request = PropFindRequest {
|
||||
prop_find_type: PropFindType::AllProp,
|
||||
};
|
||||
|
||||
let mut output = Vec::new();
|
||||
let result = CalDavAdapter::generate_calendar_collection_propfind(
|
||||
&mut output,
|
||||
&calendar,
|
||||
&events,
|
||||
&request,
|
||||
"/caldav/cal-001",
|
||||
"1",
|
||||
);
|
||||
|
||||
assert!(result.is_ok(), "Failed to generate depth-1 propfind: {:?}", result.err());
|
||||
|
||||
let xml_str = String::from_utf8(output).expect("Invalid UTF-8");
|
||||
assert!(xml_str.contains("multistatus"), "Should have multistatus");
|
||||
assert!(xml_str.contains("Personal"), "Should have calendar name");
|
||||
// Depth 1 should include event resources
|
||||
assert!(xml_str.contains("evt-001"), "Depth 1 should include event resources");
|
||||
}
|
||||
|
||||
// ========================
|
||||
// Calendar events response tests
|
||||
// ========================
|
||||
|
||||
#[test]
|
||||
fn test_generate_calendar_events_response() {
|
||||
let events = vec![sample_event()];
|
||||
let report = CalDavReportType::CalendarQuery {
|
||||
time_range: None,
|
||||
props: vec![
|
||||
QualifiedName {
|
||||
namespace: "DAV:".to_string(),
|
||||
name: "getetag".to_string(),
|
||||
},
|
||||
QualifiedName {
|
||||
namespace: "urn:ietf:params:xml:ns:caldav".to_string(),
|
||||
name: "calendar-data".to_string(),
|
||||
},
|
||||
],
|
||||
};
|
||||
|
||||
let mut output = Vec::new();
|
||||
let result = CalDavAdapter::generate_calendar_events_response(
|
||||
&mut output,
|
||||
&events,
|
||||
&report,
|
||||
"/caldav/cal-001",
|
||||
);
|
||||
|
||||
assert!(result.is_ok(), "Failed to generate events response: {:?}", result.err());
|
||||
|
||||
let xml_str = String::from_utf8(output).expect("Invalid UTF-8");
|
||||
assert!(xml_str.contains("multistatus"), "Should have multistatus");
|
||||
assert!(xml_str.contains("evt-001"), "Should reference event ID");
|
||||
assert!(xml_str.contains("BEGIN:VCALENDAR"), "Should contain iCal data");
|
||||
assert!(xml_str.contains("VEVENT"), "Should contain VEVENT component");
|
||||
assert!(xml_str.contains("Team Meeting"), "Should contain event summary");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_generate_empty_events_response() {
|
||||
let events: Vec<CalendarEventDto> = vec![];
|
||||
let report = CalDavReportType::CalendarQuery {
|
||||
time_range: None,
|
||||
props: vec![],
|
||||
};
|
||||
|
||||
let mut output = Vec::new();
|
||||
let result = CalDavAdapter::generate_calendar_events_response(
|
||||
&mut output,
|
||||
&events,
|
||||
&report,
|
||||
"/caldav/cal-001",
|
||||
);
|
||||
|
||||
assert!(result.is_ok(), "Empty events should still produce valid response");
|
||||
let xml_str = String::from_utf8(output).expect("Invalid UTF-8");
|
||||
assert!(xml_str.contains("multistatus"), "Should have multistatus even for empty");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,624 @@
|
||||
/**
|
||||
* CardDAV Adapter Module
|
||||
*
|
||||
* This module provides conversion between CardDAV protocol XML structures and
|
||||
* OxiCloud domain objects. It handles parsing CardDAV request XML and generating
|
||||
* CardDAV response XML according to RFC 6352.
|
||||
*/
|
||||
|
||||
use std::io::{Read, Write, BufReader};
|
||||
use quick_xml::{Reader, Writer, events::{Event, BytesStart, BytesEnd, BytesText}};
|
||||
|
||||
use crate::application::adapters::webdav_adapter::{
|
||||
WebDavAdapter, QualifiedName, PropFindType, PropFindRequest, Result, WebDavError,
|
||||
};
|
||||
use crate::application::dtos::address_book_dto::AddressBookDto;
|
||||
use crate::application::dtos::contact_dto::ContactDto;
|
||||
|
||||
/// CardDAV report type
|
||||
#[derive(Debug, PartialEq)]
|
||||
pub enum CardDavReportType {
|
||||
/// Addressbook-query report
|
||||
AddressbookQuery {
|
||||
props: Vec<QualifiedName>,
|
||||
},
|
||||
/// Addressbook-multiget report
|
||||
AddressbookMultiget {
|
||||
hrefs: Vec<String>,
|
||||
props: Vec<QualifiedName>,
|
||||
},
|
||||
/// Sync-collection report
|
||||
SyncCollection {
|
||||
sync_token: String,
|
||||
props: Vec<QualifiedName>,
|
||||
},
|
||||
}
|
||||
|
||||
/// CardDAV adapter for XML parsing/generation
|
||||
pub struct CardDavAdapter;
|
||||
|
||||
impl CardDavAdapter {
|
||||
/// Parse a REPORT XML request for CardDAV
|
||||
pub fn parse_report<R: Read>(reader: R) -> Result<CardDavReportType> {
|
||||
let mut xml_reader = Reader::from_reader(BufReader::new(reader));
|
||||
xml_reader.config_mut().trim_text(true);
|
||||
|
||||
let mut buffer = Vec::new();
|
||||
let mut in_addressbook_query = false;
|
||||
let mut in_addressbook_multiget = false;
|
||||
let mut in_sync_collection = false;
|
||||
let mut in_prop = false;
|
||||
let mut props = Vec::new();
|
||||
let mut hrefs = Vec::new();
|
||||
let mut sync_token = String::new();
|
||||
let mut in_href = false;
|
||||
let mut in_sync_token = false;
|
||||
|
||||
loop {
|
||||
match xml_reader.read_event_into(&mut buffer) {
|
||||
Ok(Event::Start(ref e)) => {
|
||||
let name = e.name();
|
||||
let name_str = std::str::from_utf8(name.as_ref()).unwrap_or("");
|
||||
|
||||
match name_str {
|
||||
s if s == "addressbook-query" || s.ends_with(":addressbook-query") => in_addressbook_query = true,
|
||||
s if s == "addressbook-multiget" || s.ends_with(":addressbook-multiget") => in_addressbook_multiget = true,
|
||||
s if s == "sync-collection" || s.ends_with(":sync-collection") => in_sync_collection = true,
|
||||
s if s == "prop" || s.ends_with(":prop") => in_prop = true,
|
||||
s if s == "href" || s.ends_with(":href") => in_href = true,
|
||||
s if s == "sync-token" || s.ends_with(":sync-token") => in_sync_token = true,
|
||||
_ if in_prop => {
|
||||
let namespace = WebDavAdapter::extract_namespace(name_str);
|
||||
let prop_name = WebDavAdapter::extract_local_name(name_str);
|
||||
props.push(QualifiedName::new(namespace, prop_name));
|
||||
},
|
||||
_ => {}
|
||||
}
|
||||
},
|
||||
Ok(Event::Text(e)) => {
|
||||
let text = e.decode().unwrap_or_default();
|
||||
if in_href {
|
||||
hrefs.push(text.to_string());
|
||||
} else if in_sync_token {
|
||||
sync_token = text.to_string();
|
||||
}
|
||||
},
|
||||
Ok(Event::End(ref e)) => {
|
||||
let name = e.name();
|
||||
let name_str = std::str::from_utf8(name.as_ref()).unwrap_or("");
|
||||
|
||||
match name_str {
|
||||
s if s == "prop" || s.ends_with(":prop") => in_prop = false,
|
||||
s if s == "href" || s.ends_with(":href") => in_href = false,
|
||||
s if s == "sync-token" || s.ends_with(":sync-token") => in_sync_token = false,
|
||||
_ => {}
|
||||
}
|
||||
},
|
||||
Ok(Event::Empty(ref e)) if in_prop => {
|
||||
let name = e.name();
|
||||
let name_str = std::str::from_utf8(name.as_ref()).unwrap_or("");
|
||||
let namespace = WebDavAdapter::extract_namespace(name_str);
|
||||
let prop_name = WebDavAdapter::extract_local_name(name_str);
|
||||
props.push(QualifiedName::new(namespace, prop_name));
|
||||
},
|
||||
Ok(Event::Eof) => break,
|
||||
Err(e) => return Err(WebDavError::XmlError(e)),
|
||||
_ => (),
|
||||
}
|
||||
buffer.clear();
|
||||
}
|
||||
|
||||
if in_addressbook_multiget || !hrefs.is_empty() {
|
||||
Ok(CardDavReportType::AddressbookMultiget { hrefs, props })
|
||||
} else if in_sync_collection {
|
||||
Ok(CardDavReportType::SyncCollection { sync_token, props })
|
||||
} else if in_addressbook_query {
|
||||
Ok(CardDavReportType::AddressbookQuery { props })
|
||||
} else {
|
||||
// Default
|
||||
Ok(CardDavReportType::AddressbookQuery { props })
|
||||
}
|
||||
}
|
||||
|
||||
/// Generate a PROPFIND response listing address books
|
||||
pub fn generate_addressbooks_propfind_response<W: Write>(
|
||||
writer: W,
|
||||
address_books: &[AddressBookDto],
|
||||
request: &PropFindRequest,
|
||||
base_href: &str,
|
||||
) -> Result<()> {
|
||||
let mut xml_writer = Writer::new(writer);
|
||||
|
||||
xml_writer.write_event(Event::Start(BytesStart::new("D:multistatus").with_attributes([
|
||||
("xmlns:D", "DAV:"),
|
||||
("xmlns:CR", "urn:ietf:params:xml:ns:carddav"),
|
||||
("xmlns:CS", "http://calendarserver.org/ns/"),
|
||||
])))?;
|
||||
|
||||
for book in address_books {
|
||||
Self::write_addressbook_response(&mut xml_writer, book, request, &format!("{}{}/", base_href, book.id))?;
|
||||
}
|
||||
|
||||
xml_writer.write_event(Event::End(BytesEnd::new("D:multistatus")))?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Generate PROPFIND for a single address book collection + contacts
|
||||
pub fn generate_addressbook_collection_propfind<W: Write>(
|
||||
writer: W,
|
||||
address_book: &AddressBookDto,
|
||||
contacts: &[ContactDto],
|
||||
request: &PropFindRequest,
|
||||
base_href: &str,
|
||||
depth: &str,
|
||||
) -> Result<()> {
|
||||
let mut xml_writer = Writer::new(writer);
|
||||
|
||||
xml_writer.write_event(Event::Start(BytesStart::new("D:multistatus").with_attributes([
|
||||
("xmlns:D", "DAV:"),
|
||||
("xmlns:CR", "urn:ietf:params:xml:ns:carddav"),
|
||||
("xmlns:CS", "http://calendarserver.org/ns/"),
|
||||
])))?;
|
||||
|
||||
// Write the address book itself
|
||||
Self::write_addressbook_response(&mut xml_writer, address_book, request, base_href)?;
|
||||
|
||||
// Write contacts if depth > 0
|
||||
if depth != "0" {
|
||||
for contact in contacts {
|
||||
let contact_href = format!("{}{}.vcf", base_href, contact.uid);
|
||||
Self::write_contact_response(&mut xml_writer, contact, &[], &contact_href)?;
|
||||
}
|
||||
}
|
||||
|
||||
xml_writer.write_event(Event::End(BytesEnd::new("D:multistatus")))?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Write address book properties
|
||||
fn write_addressbook_response<W: Write>(
|
||||
xml_writer: &mut Writer<W>,
|
||||
book: &AddressBookDto,
|
||||
request: &PropFindRequest,
|
||||
href: &str,
|
||||
) -> Result<()> {
|
||||
xml_writer.write_event(Event::Start(BytesStart::new("D:response")))?;
|
||||
|
||||
xml_writer.write_event(Event::Start(BytesStart::new("D:href")))?;
|
||||
xml_writer.write_event(Event::Text(BytesText::new(href)))?;
|
||||
xml_writer.write_event(Event::End(BytesEnd::new("D:href")))?;
|
||||
|
||||
xml_writer.write_event(Event::Start(BytesStart::new("D:propstat")))?;
|
||||
xml_writer.write_event(Event::Start(BytesStart::new("D:prop")))?;
|
||||
|
||||
match &request.prop_find_type {
|
||||
PropFindType::AllProp => Self::write_addressbook_all_props(xml_writer, book)?,
|
||||
PropFindType::PropName => Self::write_addressbook_prop_names(xml_writer)?,
|
||||
PropFindType::Prop(props) => Self::write_addressbook_requested_props(xml_writer, book, props)?,
|
||||
}
|
||||
|
||||
xml_writer.write_event(Event::End(BytesEnd::new("D:prop")))?;
|
||||
|
||||
xml_writer.write_event(Event::Start(BytesStart::new("D:status")))?;
|
||||
xml_writer.write_event(Event::Text(BytesText::new("HTTP/1.1 200 OK")))?;
|
||||
xml_writer.write_event(Event::End(BytesEnd::new("D:status")))?;
|
||||
|
||||
xml_writer.write_event(Event::End(BytesEnd::new("D:propstat")))?;
|
||||
xml_writer.write_event(Event::End(BytesEnd::new("D:response")))?;
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn write_addressbook_all_props<W: Write>(
|
||||
xml_writer: &mut Writer<W>,
|
||||
book: &AddressBookDto,
|
||||
) -> Result<()> {
|
||||
// resourcetype: collection + addressbook
|
||||
xml_writer.write_event(Event::Start(BytesStart::new("D:resourcetype")))?;
|
||||
xml_writer.write_event(Event::Empty(BytesStart::new("D:collection")))?;
|
||||
xml_writer.write_event(Event::Empty(BytesStart::new("CR:addressbook")))?;
|
||||
xml_writer.write_event(Event::End(BytesEnd::new("D:resourcetype")))?;
|
||||
|
||||
// displayname
|
||||
xml_writer.write_event(Event::Start(BytesStart::new("D:displayname")))?;
|
||||
xml_writer.write_event(Event::Text(BytesText::new(&book.name)))?;
|
||||
xml_writer.write_event(Event::End(BytesEnd::new("D:displayname")))?;
|
||||
|
||||
// getlastmodified
|
||||
xml_writer.write_event(Event::Start(BytesStart::new("D:getlastmodified")))?;
|
||||
xml_writer.write_event(Event::Text(BytesText::new(&book.updated_at.to_rfc2822())))?;
|
||||
xml_writer.write_event(Event::End(BytesEnd::new("D:getlastmodified")))?;
|
||||
|
||||
// getetag
|
||||
xml_writer.write_event(Event::Start(BytesStart::new("D:getetag")))?;
|
||||
xml_writer.write_event(Event::Text(BytesText::new(&format!("\"{}\"", book.id))))?;
|
||||
xml_writer.write_event(Event::End(BytesEnd::new("D:getetag")))?;
|
||||
|
||||
// getcontenttype
|
||||
xml_writer.write_event(Event::Start(BytesStart::new("D:getcontenttype")))?;
|
||||
xml_writer.write_event(Event::Text(BytesText::new("text/vcard")))?;
|
||||
xml_writer.write_event(Event::End(BytesEnd::new("D:getcontenttype")))?;
|
||||
|
||||
// supported-address-data
|
||||
xml_writer.write_event(Event::Start(BytesStart::new("CR:supported-address-data")))?;
|
||||
xml_writer.write_event(Event::Empty(BytesStart::new("CR:address-data-type").with_attributes([
|
||||
("content-type", "text/vcard"),
|
||||
("version", "3.0"),
|
||||
])))?;
|
||||
xml_writer.write_event(Event::Empty(BytesStart::new("CR:address-data-type").with_attributes([
|
||||
("content-type", "text/vcard"),
|
||||
("version", "4.0"),
|
||||
])))?;
|
||||
xml_writer.write_event(Event::End(BytesEnd::new("CR:supported-address-data")))?;
|
||||
|
||||
// addressbook-description
|
||||
if let Some(ref desc) = book.description {
|
||||
xml_writer.write_event(Event::Start(BytesStart::new("CR:addressbook-description")))?;
|
||||
xml_writer.write_event(Event::Text(BytesText::new(desc)))?;
|
||||
xml_writer.write_event(Event::End(BytesEnd::new("CR:addressbook-description")))?;
|
||||
}
|
||||
|
||||
// current-user-privilege-set
|
||||
xml_writer.write_event(Event::Start(BytesStart::new("D:current-user-privilege-set")))?;
|
||||
xml_writer.write_event(Event::Start(BytesStart::new("D:privilege")))?;
|
||||
xml_writer.write_event(Event::Empty(BytesStart::new("D:read")))?;
|
||||
xml_writer.write_event(Event::End(BytesEnd::new("D:privilege")))?;
|
||||
xml_writer.write_event(Event::Start(BytesStart::new("D:privilege")))?;
|
||||
xml_writer.write_event(Event::Empty(BytesStart::new("D:write")))?;
|
||||
xml_writer.write_event(Event::End(BytesEnd::new("D:privilege")))?;
|
||||
xml_writer.write_event(Event::End(BytesEnd::new("D:current-user-privilege-set")))?;
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn write_addressbook_prop_names<W: Write>(
|
||||
xml_writer: &mut Writer<W>,
|
||||
) -> Result<()> {
|
||||
xml_writer.write_event(Event::Empty(BytesStart::new("D:resourcetype")))?;
|
||||
xml_writer.write_event(Event::Empty(BytesStart::new("D:displayname")))?;
|
||||
xml_writer.write_event(Event::Empty(BytesStart::new("D:getlastmodified")))?;
|
||||
xml_writer.write_event(Event::Empty(BytesStart::new("D:getetag")))?;
|
||||
xml_writer.write_event(Event::Empty(BytesStart::new("D:getcontenttype")))?;
|
||||
xml_writer.write_event(Event::Empty(BytesStart::new("CR:supported-address-data")))?;
|
||||
xml_writer.write_event(Event::Empty(BytesStart::new("CR:addressbook-description")))?;
|
||||
xml_writer.write_event(Event::Empty(BytesStart::new("D:current-user-privilege-set")))?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn write_addressbook_requested_props<W: Write>(
|
||||
xml_writer: &mut Writer<W>,
|
||||
book: &AddressBookDto,
|
||||
props: &[QualifiedName],
|
||||
) -> Result<()> {
|
||||
for prop in props {
|
||||
match (prop.namespace.as_str(), prop.name.as_str()) {
|
||||
("DAV:", "resourcetype") => {
|
||||
xml_writer.write_event(Event::Start(BytesStart::new("D:resourcetype")))?;
|
||||
xml_writer.write_event(Event::Empty(BytesStart::new("D:collection")))?;
|
||||
xml_writer.write_event(Event::Empty(BytesStart::new("CR:addressbook")))?;
|
||||
xml_writer.write_event(Event::End(BytesEnd::new("D:resourcetype")))?;
|
||||
},
|
||||
("DAV:", "displayname") => {
|
||||
xml_writer.write_event(Event::Start(BytesStart::new("D:displayname")))?;
|
||||
xml_writer.write_event(Event::Text(BytesText::new(&book.name)))?;
|
||||
xml_writer.write_event(Event::End(BytesEnd::new("D:displayname")))?;
|
||||
},
|
||||
("DAV:", "getlastmodified") => {
|
||||
xml_writer.write_event(Event::Start(BytesStart::new("D:getlastmodified")))?;
|
||||
xml_writer.write_event(Event::Text(BytesText::new(&book.updated_at.to_rfc2822())))?;
|
||||
xml_writer.write_event(Event::End(BytesEnd::new("D:getlastmodified")))?;
|
||||
},
|
||||
("DAV:", "getetag") => {
|
||||
xml_writer.write_event(Event::Start(BytesStart::new("D:getetag")))?;
|
||||
xml_writer.write_event(Event::Text(BytesText::new(&format!("\"{}\"", book.id))))?;
|
||||
xml_writer.write_event(Event::End(BytesEnd::new("D:getetag")))?;
|
||||
},
|
||||
("DAV:", "getcontenttype") => {
|
||||
xml_writer.write_event(Event::Start(BytesStart::new("D:getcontenttype")))?;
|
||||
xml_writer.write_event(Event::Text(BytesText::new("text/vcard")))?;
|
||||
xml_writer.write_event(Event::End(BytesEnd::new("D:getcontenttype")))?;
|
||||
},
|
||||
("urn:ietf:params:xml:ns:carddav", "addressbook-description") => {
|
||||
if let Some(ref desc) = book.description {
|
||||
xml_writer.write_event(Event::Start(BytesStart::new("CR:addressbook-description")))?;
|
||||
xml_writer.write_event(Event::Text(BytesText::new(desc)))?;
|
||||
xml_writer.write_event(Event::End(BytesEnd::new("CR:addressbook-description")))?;
|
||||
} else {
|
||||
xml_writer.write_event(Event::Empty(BytesStart::new("CR:addressbook-description")))?;
|
||||
}
|
||||
},
|
||||
("urn:ietf:params:xml:ns:carddav", "supported-address-data") => {
|
||||
xml_writer.write_event(Event::Start(BytesStart::new("CR:supported-address-data")))?;
|
||||
xml_writer.write_event(Event::Empty(BytesStart::new("CR:address-data-type").with_attributes([
|
||||
("content-type", "text/vcard"),
|
||||
("version", "3.0"),
|
||||
])))?;
|
||||
xml_writer.write_event(Event::End(BytesEnd::new("CR:supported-address-data")))?;
|
||||
},
|
||||
("DAV:", "current-user-privilege-set") => {
|
||||
xml_writer.write_event(Event::Start(BytesStart::new("D:current-user-privilege-set")))?;
|
||||
xml_writer.write_event(Event::Start(BytesStart::new("D:privilege")))?;
|
||||
xml_writer.write_event(Event::Empty(BytesStart::new("D:read")))?;
|
||||
xml_writer.write_event(Event::End(BytesEnd::new("D:privilege")))?;
|
||||
xml_writer.write_event(Event::Start(BytesStart::new("D:privilege")))?;
|
||||
xml_writer.write_event(Event::Empty(BytesStart::new("D:write")))?;
|
||||
xml_writer.write_event(Event::End(BytesEnd::new("D:privilege")))?;
|
||||
xml_writer.write_event(Event::End(BytesEnd::new("D:current-user-privilege-set")))?;
|
||||
},
|
||||
_ => {
|
||||
let prop_name = if prop.namespace == "urn:ietf:params:xml:ns:carddav" {
|
||||
format!("CR:{}", prop.name)
|
||||
} else if prop.namespace == "DAV:" {
|
||||
format!("D:{}", prop.name)
|
||||
} else {
|
||||
prop.name.clone()
|
||||
};
|
||||
xml_writer.write_event(Event::Empty(BytesStart::new(&prop_name)))?;
|
||||
}
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Generate response for contacts (for REPORT)
|
||||
pub fn generate_contacts_response<W: Write>(
|
||||
writer: W,
|
||||
contacts: &[ContactDto],
|
||||
vcards: &[(String, String)], // (uid, vcard_data)
|
||||
report: &CardDavReportType,
|
||||
base_href: &str,
|
||||
) -> Result<()> {
|
||||
let mut xml_writer = Writer::new(writer);
|
||||
|
||||
xml_writer.write_event(Event::Start(BytesStart::new("D:multistatus").with_attributes([
|
||||
("xmlns:D", "DAV:"),
|
||||
("xmlns:CR", "urn:ietf:params:xml:ns:carddav"),
|
||||
])))?;
|
||||
|
||||
let props = match report {
|
||||
CardDavReportType::AddressbookQuery { props } => props.clone(),
|
||||
CardDavReportType::AddressbookMultiget { props, .. } => props.clone(),
|
||||
CardDavReportType::SyncCollection { props, .. } => props.clone(),
|
||||
};
|
||||
|
||||
for contact in contacts {
|
||||
let href = format!("{}{}.vcf", base_href, contact.uid);
|
||||
let vcard = vcards.iter()
|
||||
.find(|(uid, _)| *uid == contact.uid)
|
||||
.map(|(_, data)| data.as_str())
|
||||
.unwrap_or("");
|
||||
Self::write_contact_response(&mut xml_writer, contact, &props, &href)?;
|
||||
// If address-data is requested, include vcard
|
||||
if props.iter().any(|p| p.name == "address-data") || props.is_empty() {
|
||||
// Already handled in write_contact_response
|
||||
}
|
||||
let _ = vcard; // suppress warning - used via contact_to_vcard fallback
|
||||
}
|
||||
|
||||
xml_writer.write_event(Event::End(BytesEnd::new("D:multistatus")))?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Write a single contact response element
|
||||
fn write_contact_response<W: Write>(
|
||||
xml_writer: &mut Writer<W>,
|
||||
contact: &ContactDto,
|
||||
props: &[QualifiedName],
|
||||
href: &str,
|
||||
) -> Result<()> {
|
||||
xml_writer.write_event(Event::Start(BytesStart::new("D:response")))?;
|
||||
|
||||
xml_writer.write_event(Event::Start(BytesStart::new("D:href")))?;
|
||||
xml_writer.write_event(Event::Text(BytesText::new(href)))?;
|
||||
xml_writer.write_event(Event::End(BytesEnd::new("D:href")))?;
|
||||
|
||||
xml_writer.write_event(Event::Start(BytesStart::new("D:propstat")))?;
|
||||
xml_writer.write_event(Event::Start(BytesStart::new("D:prop")))?;
|
||||
|
||||
if props.is_empty() {
|
||||
// Return standard properties
|
||||
xml_writer.write_event(Event::Empty(BytesStart::new("D:resourcetype")))?;
|
||||
|
||||
xml_writer.write_event(Event::Start(BytesStart::new("D:getetag")))?;
|
||||
xml_writer.write_event(Event::Text(BytesText::new(&format!("\"{}\"", contact.etag))))?;
|
||||
xml_writer.write_event(Event::End(BytesEnd::new("D:getetag")))?;
|
||||
|
||||
xml_writer.write_event(Event::Start(BytesStart::new("D:getcontenttype")))?;
|
||||
xml_writer.write_event(Event::Text(BytesText::new("text/vcard; charset=utf-8")))?;
|
||||
xml_writer.write_event(Event::End(BytesEnd::new("D:getcontenttype")))?;
|
||||
|
||||
// Include vCard data
|
||||
let vcard = contact_to_vcard(contact);
|
||||
xml_writer.write_event(Event::Start(BytesStart::new("CR:address-data")))?;
|
||||
xml_writer.write_event(Event::Text(BytesText::new(&vcard)))?;
|
||||
xml_writer.write_event(Event::End(BytesEnd::new("CR:address-data")))?;
|
||||
} else {
|
||||
for prop in props {
|
||||
match (prop.namespace.as_str(), prop.name.as_str()) {
|
||||
("DAV:", "resourcetype") => {
|
||||
xml_writer.write_event(Event::Empty(BytesStart::new("D:resourcetype")))?;
|
||||
},
|
||||
("DAV:", "getetag") => {
|
||||
xml_writer.write_event(Event::Start(BytesStart::new("D:getetag")))?;
|
||||
xml_writer.write_event(Event::Text(BytesText::new(&format!("\"{}\"", contact.etag))))?;
|
||||
xml_writer.write_event(Event::End(BytesEnd::new("D:getetag")))?;
|
||||
},
|
||||
("DAV:", "getcontenttype") => {
|
||||
xml_writer.write_event(Event::Start(BytesStart::new("D:getcontenttype")))?;
|
||||
xml_writer.write_event(Event::Text(BytesText::new("text/vcard; charset=utf-8")))?;
|
||||
xml_writer.write_event(Event::End(BytesEnd::new("D:getcontenttype")))?;
|
||||
},
|
||||
("DAV:", "getlastmodified") => {
|
||||
xml_writer.write_event(Event::Start(BytesStart::new("D:getlastmodified")))?;
|
||||
xml_writer.write_event(Event::Text(BytesText::new(&contact.updated_at.to_rfc2822())))?;
|
||||
xml_writer.write_event(Event::End(BytesEnd::new("D:getlastmodified")))?;
|
||||
},
|
||||
("urn:ietf:params:xml:ns:carddav", "address-data") => {
|
||||
let vcard = contact_to_vcard(contact);
|
||||
xml_writer.write_event(Event::Start(BytesStart::new("CR:address-data")))?;
|
||||
xml_writer.write_event(Event::Text(BytesText::new(&vcard)))?;
|
||||
xml_writer.write_event(Event::End(BytesEnd::new("CR:address-data")))?;
|
||||
},
|
||||
_ => {
|
||||
let prop_name = if prop.namespace == "urn:ietf:params:xml:ns:carddav" {
|
||||
format!("CR:{}", prop.name)
|
||||
} else if prop.namespace == "DAV:" {
|
||||
format!("D:{}", prop.name)
|
||||
} else {
|
||||
prop.name.clone()
|
||||
};
|
||||
xml_writer.write_event(Event::Empty(BytesStart::new(&prop_name)))?;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
xml_writer.write_event(Event::End(BytesEnd::new("D:prop")))?;
|
||||
|
||||
xml_writer.write_event(Event::Start(BytesStart::new("D:status")))?;
|
||||
xml_writer.write_event(Event::Text(BytesText::new("HTTP/1.1 200 OK")))?;
|
||||
xml_writer.write_event(Event::End(BytesEnd::new("D:status")))?;
|
||||
|
||||
xml_writer.write_event(Event::End(BytesEnd::new("D:propstat")))?;
|
||||
xml_writer.write_event(Event::End(BytesEnd::new("D:response")))?;
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Parse a MKCOL XML request for making an address book
|
||||
pub fn parse_mkaddressbook<R: Read>(reader: R) -> Result<(String, Option<String>, Option<String>)> {
|
||||
let mut xml_reader = Reader::from_reader(BufReader::new(reader));
|
||||
xml_reader.config_mut().trim_text(true);
|
||||
|
||||
let mut buffer = Vec::new();
|
||||
let mut in_set = false;
|
||||
let mut in_prop = false;
|
||||
let mut in_displayname = false;
|
||||
let mut in_description = false;
|
||||
let mut in_color = false;
|
||||
|
||||
let mut displayname = String::new();
|
||||
let mut description = None;
|
||||
let mut color = None;
|
||||
|
||||
loop {
|
||||
match xml_reader.read_event_into(&mut buffer) {
|
||||
Ok(Event::Start(ref e)) => {
|
||||
let name = e.name();
|
||||
let name_str = std::str::from_utf8(name.as_ref()).unwrap_or("");
|
||||
|
||||
match name_str {
|
||||
s if s == "set" || s.ends_with(":set") => in_set = true,
|
||||
s if in_set && (s == "prop" || s.ends_with(":prop")) => in_prop = true,
|
||||
s if in_prop && (s == "displayname" || s.ends_with(":displayname")) => in_displayname = true,
|
||||
s if in_prop && (s == "addressbook-description" || s.ends_with(":addressbook-description")) => in_description = true,
|
||||
s if in_prop && (s.contains("color")) => in_color = true,
|
||||
_ => {}
|
||||
}
|
||||
},
|
||||
Ok(Event::Text(e)) => {
|
||||
let text = e.decode().unwrap_or_default();
|
||||
if in_displayname { displayname = text.to_string(); }
|
||||
else if in_description { description = Some(text.to_string()); }
|
||||
else if in_color { color = Some(text.to_string()); }
|
||||
},
|
||||
Ok(Event::End(ref e)) => {
|
||||
let name = e.name();
|
||||
let name_str = std::str::from_utf8(name.as_ref()).unwrap_or("");
|
||||
match name_str {
|
||||
s if s == "set" || s.ends_with(":set") => in_set = false,
|
||||
s if s == "prop" || s.ends_with(":prop") => in_prop = false,
|
||||
s if s == "displayname" || s.ends_with(":displayname") => in_displayname = false,
|
||||
s if s.contains("description") => in_description = false,
|
||||
s if s.contains("color") => in_color = false,
|
||||
_ => {}
|
||||
}
|
||||
},
|
||||
Ok(Event::Eof) => break,
|
||||
Err(e) => return Err(WebDavError::XmlError(e)),
|
||||
_ => (),
|
||||
}
|
||||
buffer.clear();
|
||||
}
|
||||
|
||||
if displayname.is_empty() {
|
||||
displayname = format!("Address Book {}", uuid::Uuid::new_v4());
|
||||
}
|
||||
|
||||
Ok((displayname, description, color))
|
||||
}
|
||||
}
|
||||
|
||||
/// Convert a ContactDto to vCard 3.0 format
|
||||
pub fn contact_to_vcard(contact: &ContactDto) -> String {
|
||||
let mut vcard = String::from("BEGIN:VCARD\r\nVERSION:3.0\r\n");
|
||||
|
||||
vcard.push_str(&format!("UID:{}\r\n", contact.uid));
|
||||
|
||||
if let (Some(ref last), Some(ref first)) = (&contact.last_name, &contact.first_name) {
|
||||
vcard.push_str(&format!("N:{};{};;;\r\n", last, first));
|
||||
} else if let Some(ref last) = &contact.last_name {
|
||||
vcard.push_str(&format!("N:{};;;;\r\n", last));
|
||||
} else if let Some(ref first) = &contact.first_name {
|
||||
vcard.push_str(&format!("N:;{};;;\r\n", first));
|
||||
}
|
||||
|
||||
if let Some(ref fn_name) = contact.full_name {
|
||||
vcard.push_str(&format!("FN:{}\r\n", fn_name));
|
||||
} else {
|
||||
// FN is mandatory in vCard 3.0
|
||||
let fn_name = format!("{} {}",
|
||||
contact.first_name.as_deref().unwrap_or(""),
|
||||
contact.last_name.as_deref().unwrap_or(""),
|
||||
).trim().to_string();
|
||||
if !fn_name.is_empty() {
|
||||
vcard.push_str(&format!("FN:{}\r\n", fn_name));
|
||||
} else {
|
||||
vcard.push_str("FN:Unknown\r\n");
|
||||
}
|
||||
}
|
||||
|
||||
if let Some(ref nickname) = contact.nickname {
|
||||
vcard.push_str(&format!("NICKNAME:{}\r\n", nickname));
|
||||
}
|
||||
|
||||
for email in &contact.email {
|
||||
vcard.push_str(&format!("EMAIL;TYPE={}:{}\r\n", email.r#type.to_uppercase(), email.email));
|
||||
}
|
||||
|
||||
for phone in &contact.phone {
|
||||
vcard.push_str(&format!("TEL;TYPE={}:{}\r\n", phone.r#type.to_uppercase(), phone.number));
|
||||
}
|
||||
|
||||
for addr in &contact.address {
|
||||
let adr = format!(";;{};{};{};{};{}",
|
||||
addr.street.as_deref().unwrap_or(""),
|
||||
addr.city.as_deref().unwrap_or(""),
|
||||
addr.state.as_deref().unwrap_or(""),
|
||||
addr.postal_code.as_deref().unwrap_or(""),
|
||||
addr.country.as_deref().unwrap_or(""),
|
||||
);
|
||||
vcard.push_str(&format!("ADR;TYPE={}:{}\r\n", addr.r#type.to_uppercase(), adr));
|
||||
}
|
||||
|
||||
if let Some(ref org) = contact.organization {
|
||||
vcard.push_str(&format!("ORG:{}\r\n", org));
|
||||
}
|
||||
if let Some(ref title) = contact.title {
|
||||
vcard.push_str(&format!("TITLE:{}\r\n", title));
|
||||
}
|
||||
if let Some(ref notes) = contact.notes {
|
||||
vcard.push_str(&format!("NOTE:{}\r\n", notes.replace('\n', "\\n")));
|
||||
}
|
||||
if let Some(ref bday) = contact.birthday {
|
||||
vcard.push_str(&format!("BDAY:{}\r\n", bday.format("%Y-%m-%d")));
|
||||
}
|
||||
if let Some(ref photo) = contact.photo_url {
|
||||
vcard.push_str(&format!("PHOTO;VALUE=URI:{}\r\n", photo));
|
||||
}
|
||||
|
||||
vcard.push_str(&format!("REV:{}\r\n", contact.updated_at.format("%Y%m%dT%H%M%SZ")));
|
||||
vcard.push_str("END:VCARD\r\n");
|
||||
|
||||
vcard
|
||||
}
|
||||
@@ -0,0 +1,432 @@
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use std::io::Cursor;
|
||||
use chrono::{Utc, TimeZone, NaiveDate};
|
||||
use crate::application::adapters::carddav_adapter::{CardDavAdapter, CardDavReportType, contact_to_vcard};
|
||||
use crate::application::adapters::webdav_adapter::{PropFindRequest, PropFindType, QualifiedName};
|
||||
use crate::application::dtos::address_book_dto::AddressBookDto;
|
||||
use crate::application::dtos::contact_dto::{ContactDto, EmailDto, PhoneDto, AddressDto};
|
||||
|
||||
fn sample_address_book() -> AddressBookDto {
|
||||
AddressBookDto {
|
||||
id: "ab-001".to_string(),
|
||||
name: "My Contacts".to_string(),
|
||||
owner_id: "user-001".to_string(),
|
||||
description: Some("Personal address book".to_string()),
|
||||
color: Some("#00FF00".to_string()),
|
||||
is_public: false,
|
||||
created_at: Utc.with_ymd_and_hms(2025, 1, 1, 0, 0, 0).unwrap(),
|
||||
updated_at: Utc.with_ymd_and_hms(2025, 1, 15, 12, 0, 0).unwrap(),
|
||||
}
|
||||
}
|
||||
|
||||
fn sample_contact() -> ContactDto {
|
||||
ContactDto {
|
||||
id: "contact-001".to_string(),
|
||||
address_book_id: "ab-001".to_string(),
|
||||
uid: "uid-contact-001@oxicloud".to_string(),
|
||||
full_name: Some("John Doe".to_string()),
|
||||
first_name: Some("John".to_string()),
|
||||
last_name: Some("Doe".to_string()),
|
||||
nickname: Some("Johnny".to_string()),
|
||||
email: vec![
|
||||
EmailDto {
|
||||
email: "john@example.com".to_string(),
|
||||
r#type: "work".to_string(),
|
||||
is_primary: true,
|
||||
},
|
||||
EmailDto {
|
||||
email: "john.doe@personal.com".to_string(),
|
||||
r#type: "home".to_string(),
|
||||
is_primary: false,
|
||||
},
|
||||
],
|
||||
phone: vec![
|
||||
PhoneDto {
|
||||
number: "+1-555-0100".to_string(),
|
||||
r#type: "cell".to_string(),
|
||||
is_primary: true,
|
||||
},
|
||||
],
|
||||
address: vec![
|
||||
AddressDto {
|
||||
street: Some("123 Main St".to_string()),
|
||||
city: Some("Springfield".to_string()),
|
||||
state: Some("IL".to_string()),
|
||||
postal_code: Some("62701".to_string()),
|
||||
country: Some("US".to_string()),
|
||||
r#type: "home".to_string(),
|
||||
is_primary: true,
|
||||
},
|
||||
],
|
||||
organization: Some("Acme Corp".to_string()),
|
||||
title: Some("Software Engineer".to_string()),
|
||||
notes: Some("Met at conference".to_string()),
|
||||
photo_url: None,
|
||||
birthday: Some(NaiveDate::from_ymd_opt(1990, 5, 15).unwrap()),
|
||||
anniversary: None,
|
||||
created_at: Utc.with_ymd_and_hms(2025, 1, 1, 0, 0, 0).unwrap(),
|
||||
updated_at: Utc.with_ymd_and_hms(2025, 3, 10, 8, 30, 0).unwrap(),
|
||||
etag: "etag-abc123".to_string(),
|
||||
}
|
||||
}
|
||||
|
||||
fn sample_contact_minimal() -> ContactDto {
|
||||
ContactDto {
|
||||
id: "contact-002".to_string(),
|
||||
address_book_id: "ab-001".to_string(),
|
||||
uid: "uid-contact-002@oxicloud".to_string(),
|
||||
full_name: Some("Jane Smith".to_string()),
|
||||
first_name: None,
|
||||
last_name: None,
|
||||
nickname: None,
|
||||
email: vec![],
|
||||
phone: vec![],
|
||||
address: vec![],
|
||||
organization: None,
|
||||
title: None,
|
||||
notes: None,
|
||||
photo_url: None,
|
||||
birthday: None,
|
||||
anniversary: None,
|
||||
created_at: Utc.with_ymd_and_hms(2025, 2, 1, 0, 0, 0).unwrap(),
|
||||
updated_at: Utc.with_ymd_and_hms(2025, 2, 1, 0, 0, 0).unwrap(),
|
||||
etag: "etag-def456".to_string(),
|
||||
}
|
||||
}
|
||||
|
||||
// ========================
|
||||
// vCard generation tests
|
||||
// ========================
|
||||
|
||||
#[test]
|
||||
fn test_contact_to_vcard_full() {
|
||||
let contact = sample_contact();
|
||||
let vcard = contact_to_vcard(&contact);
|
||||
|
||||
assert!(vcard.starts_with("BEGIN:VCARD"), "vCard should start with BEGIN:VCARD");
|
||||
assert!(vcard.contains("VERSION:3.0"), "Should be vCard 3.0");
|
||||
assert!(vcard.contains("FN:John Doe"), "Should contain full name");
|
||||
assert!(vcard.contains("N:Doe;John"), "Should contain structured name");
|
||||
assert!(vcard.contains("NICKNAME:Johnny"), "Should contain nickname");
|
||||
assert!(vcard.contains("john@example.com"), "Should contain email");
|
||||
assert!(vcard.contains("+1-555-0100"), "Should contain phone number");
|
||||
assert!(vcard.contains("ORG:Acme Corp"), "Should contain organization");
|
||||
assert!(vcard.contains("TITLE:Software Engineer"), "Should contain title");
|
||||
assert!(vcard.contains("NOTE:Met at conference"), "Should contain notes");
|
||||
assert!(vcard.contains("BDAY:1990-05-15"), "Should contain birthday");
|
||||
assert!(vcard.contains("UID:uid-contact-001@oxicloud"), "Should contain UID");
|
||||
assert!(vcard.ends_with("END:VCARD\r\n") || vcard.trim_end().ends_with("END:VCARD"),
|
||||
"vCard should end with END:VCARD");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_contact_to_vcard_minimal() {
|
||||
let contact = sample_contact_minimal();
|
||||
let vcard = contact_to_vcard(&contact);
|
||||
|
||||
assert!(vcard.contains("BEGIN:VCARD"), "Should start correctly");
|
||||
assert!(vcard.contains("VERSION:3.0"), "Should be vCard 3.0");
|
||||
assert!(vcard.contains("FN:Jane Smith"), "Should have full name");
|
||||
assert!(vcard.contains("UID:uid-contact-002@oxicloud"), "Should have UID");
|
||||
assert!(vcard.contains("END:VCARD"), "Should end correctly");
|
||||
// Should NOT contain optional fields
|
||||
assert!(!vcard.contains("NICKNAME:"), "Should not have nickname");
|
||||
assert!(!vcard.contains("ORG:"), "Should not have org");
|
||||
assert!(!vcard.contains("TITLE:"), "Should not have title");
|
||||
assert!(!vcard.contains("BDAY:"), "Should not have birthday");
|
||||
}
|
||||
|
||||
// ========================
|
||||
// MKADDRESSBOOK parsing tests
|
||||
// ========================
|
||||
|
||||
#[test]
|
||||
fn test_parse_mkaddressbook_full() {
|
||||
let xml = r#"<?xml version="1.0" encoding="UTF-8"?>
|
||||
<D:mkcol xmlns:D="DAV:" xmlns:CR="urn:ietf:params:xml:ns:carddav">
|
||||
<D:set>
|
||||
<D:prop>
|
||||
<D:displayname>Work Contacts</D:displayname>
|
||||
<CR:addressbook-description>Colleagues and clients</CR:addressbook-description>
|
||||
</D:prop>
|
||||
</D:set>
|
||||
</D:mkcol>"#;
|
||||
|
||||
let result = CardDavAdapter::parse_mkaddressbook(Cursor::new(xml));
|
||||
assert!(result.is_ok(), "Failed to parse mkaddressbook: {:?}", result.err());
|
||||
let (name, desc, color) = result.unwrap();
|
||||
assert_eq!(name, "Work Contacts");
|
||||
assert_eq!(desc, Some("Colleagues and clients".to_string()));
|
||||
assert!(color.is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_parse_mkaddressbook_name_only() {
|
||||
let xml = r#"<?xml version="1.0" encoding="UTF-8"?>
|
||||
<D:mkcol xmlns:D="DAV:" xmlns:CR="urn:ietf:params:xml:ns:carddav">
|
||||
<D:set>
|
||||
<D:prop>
|
||||
<D:displayname>Simple Book</D:displayname>
|
||||
</D:prop>
|
||||
</D:set>
|
||||
</D:mkcol>"#;
|
||||
|
||||
let result = CardDavAdapter::parse_mkaddressbook(Cursor::new(xml));
|
||||
assert!(result.is_ok());
|
||||
let (name, desc, color) = result.unwrap();
|
||||
assert_eq!(name, "Simple Book");
|
||||
assert!(desc.is_none());
|
||||
assert!(color.is_none());
|
||||
}
|
||||
|
||||
// ========================
|
||||
// REPORT parsing tests
|
||||
// ========================
|
||||
|
||||
#[test]
|
||||
fn test_parse_addressbook_query_report() {
|
||||
let xml = r#"<?xml version="1.0" encoding="UTF-8"?>
|
||||
<CR:addressbook-query xmlns:D="DAV:" xmlns:CR="urn:ietf:params:xml:ns:carddav">
|
||||
<D:prop>
|
||||
<D:getetag/>
|
||||
<CR:address-data/>
|
||||
</D:prop>
|
||||
</CR:addressbook-query>"#;
|
||||
|
||||
let result = CardDavAdapter::parse_report(Cursor::new(xml));
|
||||
assert!(result.is_ok(), "Failed to parse addressbook-query: {:?}", result.err());
|
||||
|
||||
match result.unwrap() {
|
||||
CardDavReportType::AddressbookQuery { props } => {
|
||||
assert!(!props.is_empty(), "Props should not be empty");
|
||||
}
|
||||
other => panic!("Expected AddressbookQuery, got {:?}", other),
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_parse_addressbook_multiget_report() {
|
||||
let xml = r#"<?xml version="1.0" encoding="UTF-8"?>
|
||||
<CR:addressbook-multiget xmlns:D="DAV:" xmlns:CR="urn:ietf:params:xml:ns:carddav">
|
||||
<D:prop>
|
||||
<D:getetag/>
|
||||
<CR:address-data/>
|
||||
</D:prop>
|
||||
<D:href>/carddav/ab-001/contact-001.vcf</D:href>
|
||||
<D:href>/carddav/ab-001/contact-002.vcf</D:href>
|
||||
<D:href>/carddav/ab-001/contact-003.vcf</D:href>
|
||||
</CR:addressbook-multiget>"#;
|
||||
|
||||
let result = CardDavAdapter::parse_report(Cursor::new(xml));
|
||||
assert!(result.is_ok(), "Failed to parse multiget: {:?}", result.err());
|
||||
|
||||
match result.unwrap() {
|
||||
CardDavReportType::AddressbookMultiget { hrefs, props } => {
|
||||
assert_eq!(hrefs.len(), 3, "Should have 3 hrefs");
|
||||
assert_eq!(hrefs[0], "/carddav/ab-001/contact-001.vcf");
|
||||
assert_eq!(hrefs[2], "/carddav/ab-001/contact-003.vcf");
|
||||
assert!(!props.is_empty());
|
||||
}
|
||||
other => panic!("Expected AddressbookMultiget, got {:?}", other),
|
||||
}
|
||||
}
|
||||
|
||||
// ========================
|
||||
// PROPFIND response tests
|
||||
// ========================
|
||||
|
||||
#[test]
|
||||
fn test_generate_addressbooks_propfind_response() {
|
||||
let addressbooks = vec![sample_address_book()];
|
||||
let request = PropFindRequest {
|
||||
prop_find_type: PropFindType::AllProp,
|
||||
};
|
||||
|
||||
let mut output = Vec::new();
|
||||
let result = CardDavAdapter::generate_addressbooks_propfind_response(
|
||||
&mut output,
|
||||
&addressbooks,
|
||||
&request,
|
||||
"/carddav",
|
||||
);
|
||||
|
||||
assert!(result.is_ok(), "Failed to generate propfind response: {:?}", result.err());
|
||||
|
||||
let xml_str = String::from_utf8(output).expect("Invalid UTF-8");
|
||||
assert!(xml_str.contains("multistatus"), "Should contain multistatus");
|
||||
assert!(xml_str.contains("My Contacts"), "Should contain address book name");
|
||||
assert!(xml_str.contains("ab-001"), "Should contain address book ID in href");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_generate_addressbook_collection_propfind_depth_0() {
|
||||
let addressbook = sample_address_book();
|
||||
let contacts = vec![sample_contact()];
|
||||
let request = PropFindRequest {
|
||||
prop_find_type: PropFindType::AllProp,
|
||||
};
|
||||
|
||||
let mut output = Vec::new();
|
||||
let result = CardDavAdapter::generate_addressbook_collection_propfind(
|
||||
&mut output,
|
||||
&addressbook,
|
||||
&contacts,
|
||||
&request,
|
||||
"/carddav/ab-001",
|
||||
"0",
|
||||
);
|
||||
|
||||
assert!(result.is_ok(), "Failed to generate depth-0 propfind: {:?}", result.err());
|
||||
|
||||
let xml_str = String::from_utf8(output).expect("Invalid UTF-8");
|
||||
assert!(xml_str.contains("multistatus"), "Should contain multistatus");
|
||||
assert!(xml_str.contains("My Contacts"), "Should contain address book name");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_generate_addressbook_collection_propfind_depth_1() {
|
||||
let addressbook = sample_address_book();
|
||||
let contacts = vec![sample_contact(), sample_contact_minimal()];
|
||||
let request = PropFindRequest {
|
||||
prop_find_type: PropFindType::AllProp,
|
||||
};
|
||||
|
||||
let mut output = Vec::new();
|
||||
let result = CardDavAdapter::generate_addressbook_collection_propfind(
|
||||
&mut output,
|
||||
&addressbook,
|
||||
&contacts,
|
||||
&request,
|
||||
"/carddav/ab-001",
|
||||
"1",
|
||||
);
|
||||
|
||||
assert!(result.is_ok(), "Failed to generate depth-1 propfind: {:?}", result.err());
|
||||
|
||||
let xml_str = String::from_utf8(output).expect("Invalid UTF-8");
|
||||
assert!(xml_str.contains("multistatus"), "Should contain multistatus");
|
||||
assert!(xml_str.contains("My Contacts"), "Should contain address book name");
|
||||
// Depth 1 should include contact resources
|
||||
assert!(xml_str.contains("contact-001"), "Should include contact-001");
|
||||
assert!(xml_str.contains("contact-002"), "Should include contact-002");
|
||||
}
|
||||
|
||||
// ========================
|
||||
// Contacts response tests
|
||||
// ========================
|
||||
|
||||
#[test]
|
||||
fn test_generate_contacts_response() {
|
||||
let contacts = vec![sample_contact()];
|
||||
let vcards = vec![
|
||||
("contact-001".to_string(), contact_to_vcard(&sample_contact())),
|
||||
];
|
||||
let report = CardDavReportType::AddressbookQuery {
|
||||
props: vec![
|
||||
QualifiedName {
|
||||
namespace: "DAV:".to_string(),
|
||||
name: "getetag".to_string(),
|
||||
},
|
||||
QualifiedName {
|
||||
namespace: "urn:ietf:params:xml:ns:carddav".to_string(),
|
||||
name: "address-data".to_string(),
|
||||
},
|
||||
],
|
||||
};
|
||||
|
||||
let mut output = Vec::new();
|
||||
let result = CardDavAdapter::generate_contacts_response(
|
||||
&mut output,
|
||||
&contacts,
|
||||
&vcards,
|
||||
&report,
|
||||
"/carddav/ab-001",
|
||||
);
|
||||
|
||||
assert!(result.is_ok(), "Failed to generate contacts response: {:?}", result.err());
|
||||
|
||||
let xml_str = String::from_utf8(output).expect("Invalid UTF-8");
|
||||
assert!(xml_str.contains("multistatus"), "Should contain multistatus");
|
||||
assert!(xml_str.contains("contact-001"), "Should reference contact");
|
||||
assert!(xml_str.contains("etag-abc123"), "Should contain etag");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_generate_empty_contacts_response() {
|
||||
let contacts: Vec<ContactDto> = vec![];
|
||||
let vcards: Vec<(String, String)> = vec![];
|
||||
let report = CardDavReportType::AddressbookQuery {
|
||||
props: vec![],
|
||||
};
|
||||
|
||||
let mut output = Vec::new();
|
||||
let result = CardDavAdapter::generate_contacts_response(
|
||||
&mut output,
|
||||
&contacts,
|
||||
&vcards,
|
||||
&report,
|
||||
"/carddav/ab-001",
|
||||
);
|
||||
|
||||
assert!(result.is_ok(), "Empty contacts should produce valid response");
|
||||
let xml_str = String::from_utf8(output).expect("Invalid UTF-8");
|
||||
assert!(xml_str.contains("multistatus"), "Should have multistatus");
|
||||
}
|
||||
|
||||
// ========================
|
||||
// Multiple address books test
|
||||
// ========================
|
||||
|
||||
#[test]
|
||||
fn test_generate_multiple_addressbooks() {
|
||||
let mut ab2 = sample_address_book();
|
||||
ab2.id = "ab-002".to_string();
|
||||
ab2.name = "Work Contacts".to_string();
|
||||
|
||||
let addressbooks = vec![sample_address_book(), ab2];
|
||||
let request = PropFindRequest {
|
||||
prop_find_type: PropFindType::AllProp,
|
||||
};
|
||||
|
||||
let mut output = Vec::new();
|
||||
let result = CardDavAdapter::generate_addressbooks_propfind_response(
|
||||
&mut output,
|
||||
&addressbooks,
|
||||
&request,
|
||||
"/carddav/",
|
||||
);
|
||||
|
||||
assert!(result.is_ok());
|
||||
let xml_str = String::from_utf8(output).expect("Invalid UTF-8");
|
||||
assert!(xml_str.contains("My Contacts"), "Should contain first address book");
|
||||
assert!(xml_str.contains("Work Contacts"), "Should contain second address book");
|
||||
assert!(xml_str.contains("ab-001"), "Should have first ID");
|
||||
assert!(xml_str.contains("ab-002"), "Should have second ID");
|
||||
}
|
||||
|
||||
// ========================
|
||||
// vCard edge cases
|
||||
// ========================
|
||||
|
||||
#[test]
|
||||
fn test_contact_to_vcard_with_multiple_emails() {
|
||||
let contact = sample_contact();
|
||||
let vcard = contact_to_vcard(&contact);
|
||||
|
||||
// Should contain both emails
|
||||
assert!(vcard.contains("john@example.com"), "Should have work email");
|
||||
assert!(vcard.contains("john.doe@personal.com"), "Should have personal email");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_contact_to_vcard_address_formatting() {
|
||||
let contact = sample_contact();
|
||||
let vcard = contact_to_vcard(&contact);
|
||||
|
||||
// vCard ADR format: ;;street;city;state;postal;country
|
||||
assert!(vcard.contains("123 Main St"), "Should have street");
|
||||
assert!(vcard.contains("Springfield"), "Should have city");
|
||||
assert!(vcard.contains("62701"), "Should have postal code");
|
||||
}
|
||||
}
|
||||
@@ -2,3 +2,9 @@
|
||||
|
||||
pub mod webdav_adapter;
|
||||
pub mod caldav_adapter;
|
||||
pub mod carddav_adapter;
|
||||
|
||||
#[cfg(test)]
|
||||
mod caldav_adapter_test;
|
||||
#[cfg(test)]
|
||||
mod carddav_adapter_test;
|
||||
|
||||
Reference in New Issue
Block a user