mirror of
https://github.com/lennart-k/rustical.git
synced 2025-12-14 14:02:29 +00:00
Rename dav crate to caldav to prepare splitting dav functionality into dav crate
This commit is contained in:
53
crates/caldav/src/depth_extractor.rs
Normal file
53
crates/caldav/src/depth_extractor.rs
Normal file
@@ -0,0 +1,53 @@
|
||||
use actix_web::{http::StatusCode, FromRequest, HttpRequest, ResponseError};
|
||||
use derive_more::Display;
|
||||
use futures_util::future::{err, ok, Ready};
|
||||
|
||||
#[derive(Debug, Display)]
|
||||
pub struct InvalidDepthHeader {}
|
||||
|
||||
impl ResponseError for InvalidDepthHeader {
|
||||
fn status_code(&self) -> actix_web::http::StatusCode {
|
||||
StatusCode::BAD_REQUEST
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, PartialEq)]
|
||||
pub enum Depth {
|
||||
Zero,
|
||||
One,
|
||||
Infinity,
|
||||
}
|
||||
|
||||
impl TryFrom<&[u8]> for Depth {
|
||||
type Error = InvalidDepthHeader;
|
||||
|
||||
fn try_from(value: &[u8]) -> Result<Self, Self::Error> {
|
||||
match value {
|
||||
b"0" => Ok(Depth::Zero),
|
||||
b"1" => Ok(Depth::One),
|
||||
b"Infinity" | b"infinity" => Ok(Depth::Infinity),
|
||||
_ => Err(InvalidDepthHeader {}),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl FromRequest for Depth {
|
||||
type Error = InvalidDepthHeader;
|
||||
type Future = Ready<Result<Self, Self::Error>>;
|
||||
|
||||
fn extract(req: &HttpRequest) -> Self::Future {
|
||||
if let Some(depth_header) = req.headers().get("Depth") {
|
||||
match depth_header.as_bytes().try_into() {
|
||||
Ok(depth) => ok(depth),
|
||||
Err(e) => err(e),
|
||||
}
|
||||
} else {
|
||||
// default depth
|
||||
ok(Depth::Zero)
|
||||
}
|
||||
}
|
||||
|
||||
fn from_request(req: &HttpRequest, _payload: &mut actix_web::dev::Payload) -> Self::Future {
|
||||
Self::extract(req)
|
||||
}
|
||||
}
|
||||
42
crates/caldav/src/error.rs
Normal file
42
crates/caldav/src/error.rs
Normal file
@@ -0,0 +1,42 @@
|
||||
use actix_web::{http::StatusCode, HttpResponse};
|
||||
use thiserror::Error;
|
||||
|
||||
use crate::routes::propfind;
|
||||
|
||||
#[derive(Debug, Error)]
|
||||
pub enum Error {
|
||||
#[error("Not found")]
|
||||
NotFound,
|
||||
#[error("Bad request")]
|
||||
BadRequest,
|
||||
#[error("Unauthorized")]
|
||||
Unauthorized,
|
||||
#[error("Internal server error :(")]
|
||||
InternalError,
|
||||
#[error(transparent)]
|
||||
PropfindError(#[from] propfind::Error),
|
||||
#[error("Internal server error")]
|
||||
Other(#[from] anyhow::Error),
|
||||
}
|
||||
|
||||
impl actix_web::error::ResponseError for Error {
|
||||
fn status_code(&self) -> StatusCode {
|
||||
match self {
|
||||
Self::InternalError => StatusCode::INTERNAL_SERVER_ERROR,
|
||||
Self::Other(_) => StatusCode::INTERNAL_SERVER_ERROR,
|
||||
Self::NotFound => StatusCode::NOT_FOUND,
|
||||
Self::BadRequest => StatusCode::BAD_REQUEST,
|
||||
Self::Unauthorized => StatusCode::UNAUTHORIZED,
|
||||
Self::PropfindError(e) => e.status_code(),
|
||||
}
|
||||
}
|
||||
|
||||
fn error_response(&self) -> HttpResponse {
|
||||
match self {
|
||||
Error::Unauthorized => HttpResponse::build(self.status_code())
|
||||
.append_header(("WWW-Authenticate", "Basic"))
|
||||
.body(self.to_string()),
|
||||
_ => HttpResponse::build(self.status_code()).body(self.to_string()),
|
||||
}
|
||||
}
|
||||
}
|
||||
94
crates/caldav/src/lib.rs
Normal file
94
crates/caldav/src/lib.rs
Normal file
@@ -0,0 +1,94 @@
|
||||
use actix_web::http::Method;
|
||||
use actix_web::web::{self, Data};
|
||||
use actix_web::{guard, HttpResponse, Responder};
|
||||
use error::Error;
|
||||
use resources::calendar::CalendarResource;
|
||||
use resources::event::EventResource;
|
||||
use resources::principal::PrincipalCalendarsResource;
|
||||
use resources::root::RootResource;
|
||||
use routes::propfind::route_propfind;
|
||||
use routes::{calendar, event};
|
||||
use rustical_auth::CheckAuthentication;
|
||||
use rustical_store::calendar::CalendarStore;
|
||||
use std::str::FromStr;
|
||||
use std::sync::Arc;
|
||||
use tokio::sync::RwLock;
|
||||
|
||||
pub mod depth_extractor;
|
||||
pub mod error;
|
||||
pub mod namespace;
|
||||
pub mod proptypes;
|
||||
pub mod resource;
|
||||
pub mod resources;
|
||||
pub mod routes;
|
||||
mod xml_snippets;
|
||||
|
||||
pub struct CalDavContext<C: CalendarStore> {
|
||||
pub prefix: String,
|
||||
pub store: Arc<RwLock<C>>,
|
||||
}
|
||||
|
||||
pub fn configure_well_known(cfg: &mut web::ServiceConfig, caldav_root: String) {
|
||||
cfg.service(web::redirect("/caldav", caldav_root).permanent());
|
||||
}
|
||||
|
||||
pub fn configure_dav<A: CheckAuthentication, C: CalendarStore>(
|
||||
cfg: &mut web::ServiceConfig,
|
||||
prefix: String,
|
||||
auth: Arc<A>,
|
||||
store: Arc<RwLock<C>>,
|
||||
) {
|
||||
let propfind_method = || Method::from_str("PROPFIND").unwrap();
|
||||
let report_method = || Method::from_str("REPORT").unwrap();
|
||||
let mkcol_method = || Method::from_str("MKCOL").unwrap();
|
||||
|
||||
cfg.app_data(Data::new(CalDavContext {
|
||||
prefix,
|
||||
store: store.clone(),
|
||||
}))
|
||||
.app_data(Data::from(store.clone()))
|
||||
.app_data(Data::from(auth))
|
||||
.service(
|
||||
web::resource("{path:.*}")
|
||||
// Without the guard this service would handle all requests
|
||||
.guard(guard::Method(Method::OPTIONS))
|
||||
.to(options_handler),
|
||||
)
|
||||
.service(
|
||||
web::resource("").route(web::method(propfind_method()).to(route_propfind::<
|
||||
A,
|
||||
RootResource,
|
||||
C,
|
||||
>)),
|
||||
)
|
||||
.service(web::resource("/{principal}").route(
|
||||
web::method(propfind_method()).to(route_propfind::<A, PrincipalCalendarsResource<C>, C>),
|
||||
))
|
||||
.service(
|
||||
web::resource("/{principal}/{calendar}")
|
||||
.route(web::method(report_method()).to(calendar::route_report_calendar::<A, C>))
|
||||
.route(web::method(propfind_method()).to(route_propfind::<A, CalendarResource<C>, C>))
|
||||
.route(web::method(mkcol_method()).to(calendar::route_mkcol_calendar::<A, C>)),
|
||||
)
|
||||
.service(
|
||||
web::resource("/{principal}/{calendar}/{event}")
|
||||
.route(web::method(propfind_method()).to(route_propfind::<A, EventResource<C>, C>))
|
||||
.route(web::method(Method::DELETE).to(event::delete_event::<A, C>))
|
||||
.route(web::method(Method::GET).to(event::get_event::<A, C>))
|
||||
.route(web::method(Method::PUT).to(event::put_event::<A, C>)),
|
||||
);
|
||||
}
|
||||
|
||||
async fn options_handler() -> impl Responder {
|
||||
HttpResponse::Ok()
|
||||
.insert_header((
|
||||
"Allow",
|
||||
"OPTIONS, GET, HEAD, POST, PUT, REPORT, PROPFIND, PROPPATCH, MKCOL",
|
||||
))
|
||||
.insert_header((
|
||||
"DAV",
|
||||
"1, 2, 3, calendar-access, extended-mkcol",
|
||||
// "1, 2, 3, calendar-access, addressbook, extended-mkcol",
|
||||
))
|
||||
.body("options")
|
||||
}
|
||||
44
crates/caldav/src/namespace.rs
Normal file
44
crates/caldav/src/namespace.rs
Normal file
@@ -0,0 +1,44 @@
|
||||
use quick_xml::events::attributes::Attribute;
|
||||
|
||||
// An enum keeping track of the XML namespaces used for WebDAV and its extensions
|
||||
//
|
||||
// Can also generate appropriate attributes for quick_xml
|
||||
pub enum Namespace {
|
||||
Dav,
|
||||
CalDAV,
|
||||
CardDAV,
|
||||
ICal,
|
||||
CServer,
|
||||
Nextcloud,
|
||||
}
|
||||
|
||||
impl Namespace {
|
||||
pub fn as_str(&self) -> &'static str {
|
||||
match self {
|
||||
Self::Dav => "DAV:",
|
||||
Self::CalDAV => "urn:ietf:params:xml:ns:caldav",
|
||||
Self::CardDAV => "urn:ietf:params:xml:ns:carddav",
|
||||
Self::ICal => "http://apple.com/ns/ical/",
|
||||
Self::CServer => "http://calendarserver.org/ns/",
|
||||
Self::Nextcloud => "http://nextcloud.com/ns",
|
||||
}
|
||||
}
|
||||
|
||||
// Returns an opinionated namespace attribute name
|
||||
pub fn xml_attr(&self) -> &'static str {
|
||||
match self {
|
||||
Self::Dav => "xmlns",
|
||||
Self::CalDAV => "xmlns:C",
|
||||
Self::CardDAV => "xmlns:CARD",
|
||||
Self::ICal => "xmlns:IC",
|
||||
Self::CServer => "xmlns:CS",
|
||||
Self::Nextcloud => "xmlns:NEXTC",
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl From<Namespace> for Attribute<'static> {
|
||||
fn from(value: Namespace) -> Self {
|
||||
(value.xml_attr(), value.as_str()).into()
|
||||
}
|
||||
}
|
||||
39
crates/caldav/src/proptypes.rs
Normal file
39
crates/caldav/src/proptypes.rs
Normal file
@@ -0,0 +1,39 @@
|
||||
use std::io::Write;
|
||||
|
||||
use quick_xml::{events::BytesText, Writer};
|
||||
|
||||
pub fn write_string_prop<'a, W: Write>(
|
||||
writer: &'a mut Writer<W>,
|
||||
propname: &'a str,
|
||||
value: &str,
|
||||
) -> Result<&'a mut Writer<W>, quick_xml::Error> {
|
||||
let el = writer.create_element(propname);
|
||||
if value.is_empty() {
|
||||
el.write_empty()
|
||||
} else {
|
||||
el.write_text_content(BytesText::new(value))
|
||||
}
|
||||
}
|
||||
|
||||
pub fn write_href_prop<'a, W: Write>(
|
||||
writer: &'a mut Writer<W>,
|
||||
propname: &'a str,
|
||||
href: &str,
|
||||
) -> Result<&'a mut Writer<W>, quick_xml::Error> {
|
||||
write_hrefs_prop(writer, propname, vec![href])
|
||||
}
|
||||
|
||||
pub fn write_hrefs_prop<'a, W: Write>(
|
||||
writer: &'a mut Writer<W>,
|
||||
propname: &'a str,
|
||||
hrefs: Vec<&str>,
|
||||
) -> Result<&'a mut Writer<W>, quick_xml::Error> {
|
||||
writer
|
||||
.create_element(propname)
|
||||
.write_inner_content(|writer| {
|
||||
for href in hrefs {
|
||||
write_string_prop(writer, "href", href)?;
|
||||
}
|
||||
Ok(())
|
||||
})
|
||||
}
|
||||
70
crates/caldav/src/resource.rs
Normal file
70
crates/caldav/src/resource.rs
Normal file
@@ -0,0 +1,70 @@
|
||||
use std::io::Write;
|
||||
|
||||
use actix_web::{http::StatusCode, HttpRequest};
|
||||
use anyhow::{anyhow, Result};
|
||||
use async_trait::async_trait;
|
||||
use quick_xml::Writer;
|
||||
use rustical_auth::AuthInfo;
|
||||
|
||||
use crate::xml_snippets::{write_invalid_props_response, write_propstat_response};
|
||||
|
||||
// A resource is identified by a URI and has properties
|
||||
// A resource can also be a collection
|
||||
// A resource cannot be none, only Methods like PROPFIND, GET, REPORT, etc. can be exposed
|
||||
// A resource exists
|
||||
#[async_trait(?Send)]
|
||||
pub trait Resource: Sized {
|
||||
type MemberType: Resource;
|
||||
type UriComponents: Sized; // defines how the resource URI maps to parameters, i.e. /{principal}/{calendar} -> (String, String)
|
||||
|
||||
async fn acquire_from_request(
|
||||
req: HttpRequest,
|
||||
auth_info: AuthInfo,
|
||||
uri_components: Self::UriComponents,
|
||||
prefix: String,
|
||||
) -> Result<Self>;
|
||||
|
||||
fn get_path(&self) -> &str;
|
||||
async fn get_members(&self) -> Result<Vec<Self::MemberType>>;
|
||||
|
||||
fn list_dead_props() -> Vec<&'static str>;
|
||||
fn write_prop<W: Write>(&self, writer: &mut Writer<W>, prop: &str) -> Result<()>;
|
||||
}
|
||||
|
||||
pub trait HandlePropfind {
|
||||
fn propfind(&self, props: Vec<&str>) -> Result<String>;
|
||||
}
|
||||
|
||||
impl<R: Resource> HandlePropfind for R {
|
||||
fn propfind(&self, props: Vec<&str>) -> Result<String> {
|
||||
let mut props = props;
|
||||
if props.contains(&"allprops") {
|
||||
if props.len() != 1 {
|
||||
// allprops MUST be the only queried prop per spec
|
||||
return Err(anyhow!("allprops MUST be the only quereid prop"));
|
||||
}
|
||||
props = R::list_dead_props();
|
||||
}
|
||||
|
||||
let mut invalid_props = Vec::<&str>::new();
|
||||
|
||||
let mut output_buffer = Vec::new();
|
||||
let mut writer = Writer::new_with_indent(&mut output_buffer, b' ', 2);
|
||||
|
||||
write_propstat_response(&mut writer, self.get_path(), StatusCode::OK, |writer| {
|
||||
for prop in props {
|
||||
// TODO: Fix error types
|
||||
match self
|
||||
.write_prop(writer, prop)
|
||||
.map_err(|_e| quick_xml::Error::TextNotFound)
|
||||
{
|
||||
Ok(_) => {}
|
||||
Err(_) => invalid_props.push(prop),
|
||||
};
|
||||
}
|
||||
Ok(())
|
||||
})?;
|
||||
write_invalid_props_response(&mut writer, self.get_path(), invalid_props)?;
|
||||
Ok(std::str::from_utf8(&output_buffer)?.to_string())
|
||||
}
|
||||
}
|
||||
175
crates/caldav/src/resources/calendar.rs
Normal file
175
crates/caldav/src/resources/calendar.rs
Normal file
@@ -0,0 +1,175 @@
|
||||
use std::{io::Write, sync::Arc};
|
||||
|
||||
use actix_web::{web::Data, HttpRequest};
|
||||
use anyhow::{anyhow, Result};
|
||||
use async_trait::async_trait;
|
||||
use quick_xml::{events::BytesText, Writer};
|
||||
use rustical_auth::AuthInfo;
|
||||
use rustical_store::calendar::{Calendar, CalendarStore};
|
||||
use tokio::sync::RwLock;
|
||||
|
||||
use crate::{
|
||||
proptypes::{write_href_prop, write_string_prop},
|
||||
resource::Resource,
|
||||
xml_snippets::write_resourcetype,
|
||||
};
|
||||
|
||||
pub struct CalendarResource<C: CalendarStore> {
|
||||
pub cal_store: Arc<RwLock<C>>,
|
||||
pub calendar: Calendar,
|
||||
pub path: String,
|
||||
pub prefix: String,
|
||||
pub principal: String,
|
||||
}
|
||||
|
||||
#[async_trait(?Send)]
|
||||
impl<C: CalendarStore> Resource for CalendarResource<C> {
|
||||
type MemberType = Self;
|
||||
type UriComponents = (String, String); // principal, calendar_id
|
||||
|
||||
async fn acquire_from_request(
|
||||
req: HttpRequest,
|
||||
_auth_info: AuthInfo,
|
||||
uri_components: Self::UriComponents,
|
||||
prefix: String,
|
||||
) -> Result<Self> {
|
||||
let cal_store = req
|
||||
.app_data::<Data<RwLock<C>>>()
|
||||
.ok_or(anyhow!("no calendar store in app_data!"))?
|
||||
.clone()
|
||||
.into_inner();
|
||||
|
||||
let (principal, cid) = uri_components;
|
||||
let calendar = cal_store.read().await.get_calendar(&cid).await?;
|
||||
Ok(Self {
|
||||
cal_store,
|
||||
calendar,
|
||||
path: req.path().to_string(),
|
||||
prefix,
|
||||
principal,
|
||||
})
|
||||
}
|
||||
|
||||
fn get_path(&self) -> &str {
|
||||
&self.path
|
||||
}
|
||||
|
||||
async fn get_members(&self) -> Result<Vec<Self::MemberType>> {
|
||||
// As of now the calendar resource has no members
|
||||
Ok(vec![])
|
||||
}
|
||||
|
||||
#[inline]
|
||||
fn list_dead_props() -> Vec<&'static str> {
|
||||
vec![
|
||||
"resourcetype",
|
||||
"current-user-principal",
|
||||
"displayname",
|
||||
"supported-calendar-component-set",
|
||||
"supported-calendar-data",
|
||||
"getcontenttype",
|
||||
"calendar-description",
|
||||
"owner",
|
||||
"calendar-color",
|
||||
"current-user-privilege-set",
|
||||
"max-resource-size",
|
||||
]
|
||||
}
|
||||
fn write_prop<W: Write>(&self, writer: &mut Writer<W>, prop: &str) -> Result<()> {
|
||||
match prop {
|
||||
"resourcetype" => write_resourcetype(writer, vec!["C:calendar", "collection"])?,
|
||||
"current-user-principal" | "owner" => {
|
||||
write_href_prop(
|
||||
writer,
|
||||
prop,
|
||||
&format!("{}/{}/", self.prefix, self.principal),
|
||||
)?;
|
||||
}
|
||||
"displayname" => {
|
||||
let el = writer.create_element("displayname");
|
||||
if let Some(name) = self.calendar.clone().name {
|
||||
el.write_text_content(BytesText::new(&name))?;
|
||||
} else {
|
||||
el.write_empty()?;
|
||||
}
|
||||
}
|
||||
"calendar-color" => {
|
||||
let el = writer.create_element("IC:calendar-color");
|
||||
if let Some(color) = self.calendar.clone().color {
|
||||
el.write_text_content(BytesText::new(&color))?;
|
||||
} else {
|
||||
el.write_empty()?;
|
||||
}
|
||||
}
|
||||
"calendar-description" => {
|
||||
let el = writer.create_element("C:calendar-description");
|
||||
if let Some(description) = self.calendar.clone().description {
|
||||
el.write_text_content(BytesText::new(&description))?;
|
||||
} else {
|
||||
el.write_empty()?;
|
||||
}
|
||||
}
|
||||
"supported-calendar-component-set" => {
|
||||
writer
|
||||
.create_element("C:supported-calendar-component-set")
|
||||
.write_inner_content(|writer| {
|
||||
writer
|
||||
.create_element("C:comp")
|
||||
.with_attribute(("name", "VEVENT"))
|
||||
.write_empty()?;
|
||||
Ok(())
|
||||
})?;
|
||||
}
|
||||
"supported-calendar-data" => {
|
||||
writer
|
||||
.create_element("C:supported-calendar-data")
|
||||
.write_inner_content(|writer| {
|
||||
// <cal:calendar-data content-type="text/calendar" version="2.0" />
|
||||
writer
|
||||
.create_element("C:calendar-data")
|
||||
.with_attributes(vec![
|
||||
("content-type", "text/calendar"),
|
||||
("version", "2.0"),
|
||||
])
|
||||
.write_empty()?;
|
||||
Ok(())
|
||||
})?;
|
||||
}
|
||||
"getcontenttype" => {
|
||||
write_string_prop(writer, "getcontenttype", "text/calendar")?;
|
||||
}
|
||||
"max-resource-size" => {
|
||||
write_string_prop(writer, "max-resource-size", "10000000")?;
|
||||
}
|
||||
"current-user-privilege-set" => {
|
||||
writer
|
||||
.create_element("current-user-privilege-set")
|
||||
// These are just hard-coded for now and will possibly change in the future
|
||||
.write_inner_content(|writer| {
|
||||
for privilege in [
|
||||
"read",
|
||||
"read-acl",
|
||||
"write",
|
||||
"write-acl",
|
||||
"write-content",
|
||||
"read-current-user-privilege-set",
|
||||
"bind",
|
||||
"unbind",
|
||||
] {
|
||||
writer
|
||||
.create_element("privilege")
|
||||
.write_inner_content(|writer| {
|
||||
writer.create_element(privilege).write_empty()?;
|
||||
Ok(())
|
||||
})?;
|
||||
}
|
||||
Ok(())
|
||||
})?;
|
||||
}
|
||||
_ => {
|
||||
return Err(anyhow!("invalid prop"));
|
||||
}
|
||||
};
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
76
crates/caldav/src/resources/event.rs
Normal file
76
crates/caldav/src/resources/event.rs
Normal file
@@ -0,0 +1,76 @@
|
||||
use std::sync::Arc;
|
||||
|
||||
use crate::{proptypes::write_string_prop, resource::Resource};
|
||||
use actix_web::{web::Data, HttpRequest};
|
||||
use anyhow::{anyhow, Result};
|
||||
use async_trait::async_trait;
|
||||
use rustical_auth::AuthInfo;
|
||||
use rustical_store::calendar::{CalendarStore, Event};
|
||||
use tokio::sync::RwLock;
|
||||
|
||||
pub struct EventResource<C: CalendarStore> {
|
||||
pub cal_store: Arc<RwLock<C>>,
|
||||
pub path: String,
|
||||
pub event: Event,
|
||||
}
|
||||
|
||||
#[async_trait(?Send)]
|
||||
impl<C: CalendarStore> Resource for EventResource<C> {
|
||||
type UriComponents = (String, String, String); // principal, calendar, event
|
||||
type MemberType = Self;
|
||||
|
||||
fn get_path(&self) -> &str {
|
||||
&self.path
|
||||
}
|
||||
|
||||
async fn get_members(&self) -> Result<Vec<Self::MemberType>> {
|
||||
Ok(vec![])
|
||||
}
|
||||
|
||||
async fn acquire_from_request(
|
||||
req: HttpRequest,
|
||||
_auth_info: AuthInfo,
|
||||
uri_components: Self::UriComponents,
|
||||
_prefix: String,
|
||||
) -> Result<Self> {
|
||||
let (_principal, cid, uid) = uri_components;
|
||||
|
||||
let cal_store = req
|
||||
.app_data::<Data<RwLock<C>>>()
|
||||
.ok_or(anyhow!("no calendar store in app_data!"))?
|
||||
.clone()
|
||||
.into_inner();
|
||||
|
||||
let event = cal_store.read().await.get_event(&cid, &uid).await?;
|
||||
|
||||
Ok(Self {
|
||||
cal_store,
|
||||
event,
|
||||
path: req.path().to_string(),
|
||||
})
|
||||
}
|
||||
|
||||
fn write_prop<W: std::io::Write>(
|
||||
&self,
|
||||
writer: &mut quick_xml::Writer<W>,
|
||||
prop: &str,
|
||||
) -> Result<()> {
|
||||
match prop {
|
||||
"getetag" => {
|
||||
write_string_prop(writer, "getetag", &self.event.get_etag())?;
|
||||
}
|
||||
"calendar-data" => {
|
||||
write_string_prop(writer, "C:calendar-data", self.event.to_ics())?;
|
||||
}
|
||||
"getcontenttype" => {
|
||||
write_string_prop(writer, "getcontenttype", "text/calendar;charset=utf-8")?;
|
||||
}
|
||||
_ => return Err(anyhow!("invalid prop!")),
|
||||
};
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn list_dead_props() -> Vec<&'static str> {
|
||||
vec!["getetag", "calendar-data", "getcontenttype"]
|
||||
}
|
||||
}
|
||||
4
crates/caldav/src/resources/mod.rs
Normal file
4
crates/caldav/src/resources/mod.rs
Normal file
@@ -0,0 +1,4 @@
|
||||
pub mod calendar;
|
||||
pub mod event;
|
||||
pub mod principal;
|
||||
pub mod root;
|
||||
114
crates/caldav/src/resources/principal.rs
Normal file
114
crates/caldav/src/resources/principal.rs
Normal file
@@ -0,0 +1,114 @@
|
||||
use std::sync::Arc;
|
||||
|
||||
use crate::{proptypes::write_href_prop, resource::Resource, xml_snippets::write_resourcetype};
|
||||
use actix_web::{web::Data, HttpRequest};
|
||||
use anyhow::{anyhow, Result};
|
||||
use async_trait::async_trait;
|
||||
use quick_xml::events::BytesText;
|
||||
use rustical_auth::AuthInfo;
|
||||
use rustical_store::calendar::CalendarStore;
|
||||
use tokio::sync::RwLock;
|
||||
|
||||
use super::calendar::CalendarResource;
|
||||
|
||||
pub struct PrincipalCalendarsResource<C: CalendarStore> {
|
||||
prefix: String,
|
||||
principal: String,
|
||||
path: String,
|
||||
cal_store: Arc<RwLock<C>>,
|
||||
}
|
||||
|
||||
#[async_trait(?Send)]
|
||||
impl<C: CalendarStore> Resource for PrincipalCalendarsResource<C> {
|
||||
type UriComponents = ();
|
||||
type MemberType = CalendarResource<C>;
|
||||
|
||||
fn get_path(&self) -> &str {
|
||||
&self.path
|
||||
}
|
||||
|
||||
async fn get_members(&self) -> Result<Vec<Self::MemberType>> {
|
||||
let calendars = self
|
||||
.cal_store
|
||||
.read()
|
||||
.await
|
||||
.get_calendars(&self.principal)
|
||||
.await?;
|
||||
let mut out = Vec::new();
|
||||
for calendar in calendars {
|
||||
let path = format!("{}/{}", &self.path, &calendar.id);
|
||||
out.push(CalendarResource {
|
||||
cal_store: self.cal_store.clone(),
|
||||
calendar,
|
||||
path,
|
||||
prefix: self.prefix.clone(),
|
||||
principal: self.principal.clone(),
|
||||
})
|
||||
}
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
async fn acquire_from_request(
|
||||
req: HttpRequest,
|
||||
auth_info: AuthInfo,
|
||||
_uri_components: Self::UriComponents,
|
||||
prefix: String,
|
||||
) -> Result<Self> {
|
||||
let cal_store = req
|
||||
.app_data::<Data<RwLock<C>>>()
|
||||
.ok_or(anyhow!("no calendar store in app_data!"))?
|
||||
.clone()
|
||||
.into_inner();
|
||||
Ok(Self {
|
||||
cal_store,
|
||||
prefix,
|
||||
principal: auth_info.user_id,
|
||||
path: req.path().to_string(),
|
||||
})
|
||||
}
|
||||
|
||||
fn write_prop<W: std::io::Write>(
|
||||
&self,
|
||||
writer: &mut quick_xml::Writer<W>,
|
||||
prop: &str,
|
||||
) -> Result<()> {
|
||||
match prop {
|
||||
"resourcetype" => write_resourcetype(writer, vec!["principal", "collection"])?,
|
||||
"current-user-principal" | "principal-URL" => {
|
||||
write_href_prop(
|
||||
writer,
|
||||
prop,
|
||||
&format!("{}/{}/", self.prefix, self.principal),
|
||||
)?;
|
||||
}
|
||||
"calendar-home-set" | "calendar-user-address-set" => {
|
||||
writer
|
||||
.create_element(&format!("C:{prop}"))
|
||||
.write_inner_content(|writer| {
|
||||
writer
|
||||
.create_element("href")
|
||||
.write_text_content(BytesText::new(&format!(
|
||||
"{}/{}/",
|
||||
self.prefix, self.principal
|
||||
)))?;
|
||||
Ok(())
|
||||
})?;
|
||||
}
|
||||
"allprops" => {}
|
||||
_ => {
|
||||
return Err(anyhow!("invalid prop"));
|
||||
}
|
||||
};
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn list_dead_props() -> Vec<&'static str> {
|
||||
vec![
|
||||
"resourcetype",
|
||||
"current-user-principal",
|
||||
"principal-URL",
|
||||
"calendar-home-set",
|
||||
"calendar-user-address-set",
|
||||
]
|
||||
}
|
||||
}
|
||||
68
crates/caldav/src/resources/root.rs
Normal file
68
crates/caldav/src/resources/root.rs
Normal file
@@ -0,0 +1,68 @@
|
||||
use crate::{resource::Resource, xml_snippets::write_resourcetype};
|
||||
use actix_web::HttpRequest;
|
||||
use anyhow::{anyhow, Result};
|
||||
use async_trait::async_trait;
|
||||
use quick_xml::events::BytesText;
|
||||
use rustical_auth::AuthInfo;
|
||||
|
||||
pub struct RootResource {
|
||||
prefix: String,
|
||||
principal: String,
|
||||
path: String,
|
||||
}
|
||||
|
||||
#[async_trait(?Send)]
|
||||
impl Resource for RootResource {
|
||||
type UriComponents = ();
|
||||
type MemberType = Self;
|
||||
|
||||
fn get_path(&self) -> &str {
|
||||
&self.path
|
||||
}
|
||||
|
||||
async fn get_members(&self) -> Result<Vec<Self::MemberType>> {
|
||||
Ok(vec![])
|
||||
}
|
||||
|
||||
async fn acquire_from_request(
|
||||
req: HttpRequest,
|
||||
auth_info: AuthInfo,
|
||||
_uri_components: Self::UriComponents,
|
||||
prefix: String,
|
||||
) -> Result<Self> {
|
||||
Ok(Self {
|
||||
prefix,
|
||||
principal: auth_info.user_id,
|
||||
path: req.path().to_string(),
|
||||
})
|
||||
}
|
||||
|
||||
fn write_prop<W: std::io::Write>(
|
||||
&self,
|
||||
writer: &mut quick_xml::Writer<W>,
|
||||
prop: &str,
|
||||
) -> Result<()> {
|
||||
match prop {
|
||||
"resourcetype" => write_resourcetype(writer, vec!["collection"])?,
|
||||
"current-user-principal" => {
|
||||
writer
|
||||
.create_element("current-user-principal")
|
||||
.write_inner_content(|writer| {
|
||||
writer
|
||||
.create_element("href")
|
||||
.write_text_content(BytesText::new(&format!(
|
||||
"{}/{}",
|
||||
self.prefix, self.principal
|
||||
)))?;
|
||||
Ok(())
|
||||
})?;
|
||||
}
|
||||
_ => return Err(anyhow!("invalid prop!")),
|
||||
};
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn list_dead_props() -> Vec<&'static str> {
|
||||
vec!["resourcetype", "current-user-principal"]
|
||||
}
|
||||
}
|
||||
176
crates/caldav/src/routes/calendar.rs
Normal file
176
crates/caldav/src/routes/calendar.rs
Normal file
@@ -0,0 +1,176 @@
|
||||
use crate::namespace::Namespace;
|
||||
use crate::resource::HandlePropfind;
|
||||
use crate::resources::event::EventResource;
|
||||
use crate::xml_snippets::generate_multistatus;
|
||||
use crate::{CalDavContext, Error};
|
||||
use actix_web::http::header::ContentType;
|
||||
use actix_web::web::{Data, Path};
|
||||
use actix_web::{HttpRequest, HttpResponse};
|
||||
use anyhow::Result;
|
||||
use quick_xml::events::BytesText;
|
||||
use roxmltree::{Node, NodeType};
|
||||
use rustical_auth::{AuthInfoExtractor, CheckAuthentication};
|
||||
use rustical_store::calendar::{Calendar, CalendarStore, Event};
|
||||
use std::sync::Arc;
|
||||
use tokio::sync::RwLock;
|
||||
|
||||
async fn _parse_filter(filter_node: &Node<'_, '_>) {
|
||||
for comp_filter_node in filter_node.children() {
|
||||
if comp_filter_node.tag_name().name() != "comp-filter" {
|
||||
dbg!("wtf", comp_filter_node.tag_name().name());
|
||||
continue;
|
||||
}
|
||||
|
||||
for filter in filter_node.children() {
|
||||
match filter.tag_name().name() {
|
||||
// <time-range start=\"20230804T125257Z\" end=\"20231013T125257Z\"/
|
||||
"time-range" => {}
|
||||
_ => {
|
||||
dbg!("unknown filter", filter.tag_name());
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
async fn handle_report_calendar_query<C: CalendarStore>(
|
||||
query_node: Node<'_, '_>,
|
||||
request: HttpRequest,
|
||||
events: Vec<Event>,
|
||||
cal_store: Arc<RwLock<C>>,
|
||||
) -> Result<HttpResponse, Error> {
|
||||
let prop_node = query_node
|
||||
.children()
|
||||
.find(|n| n.node_type() == NodeType::Element && n.tag_name().name() == "prop")
|
||||
.ok_or(Error::BadRequest)?;
|
||||
|
||||
let props: Vec<&str> = prop_node
|
||||
.children()
|
||||
.map(|node| node.tag_name().name())
|
||||
.collect();
|
||||
let output = generate_multistatus(vec![Namespace::Dav, Namespace::CalDAV], |writer| {
|
||||
for event in events {
|
||||
let path = format!("{}/{}", request.path(), event.get_uid());
|
||||
let event_resource = EventResource {
|
||||
cal_store: cal_store.clone(),
|
||||
path: path.clone(),
|
||||
event,
|
||||
};
|
||||
// TODO: proper error handling
|
||||
let propfind_result = event_resource
|
||||
.propfind(props.clone())
|
||||
.map_err(|_e| quick_xml::Error::TextNotFound)?;
|
||||
|
||||
writer.write_event(quick_xml::events::Event::Text(BytesText::from_escaped(
|
||||
propfind_result,
|
||||
)))?;
|
||||
}
|
||||
Ok(())
|
||||
})
|
||||
.map_err(|_e| Error::InternalError)?;
|
||||
|
||||
Ok(HttpResponse::MultiStatus()
|
||||
.content_type(ContentType::xml())
|
||||
.body(output))
|
||||
}
|
||||
|
||||
pub async fn route_report_calendar<A: CheckAuthentication, C: CalendarStore>(
|
||||
context: Data<CalDavContext<C>>,
|
||||
body: String,
|
||||
path: Path<(String, String)>,
|
||||
request: HttpRequest,
|
||||
_auth: AuthInfoExtractor<A>,
|
||||
) -> Result<HttpResponse, Error> {
|
||||
// TODO: Check authorization
|
||||
let (_principal, cid) = path.into_inner();
|
||||
|
||||
let doc = roxmltree::Document::parse(&body).map_err(|_e| Error::BadRequest)?;
|
||||
let query_node = doc.root_element();
|
||||
let events = context.store.read().await.get_events(&cid).await.unwrap();
|
||||
|
||||
dbg!(&body);
|
||||
|
||||
// TODO: implement filtering
|
||||
match query_node.tag_name().name() {
|
||||
"calendar-query" => {}
|
||||
"calendar-multiget" => {}
|
||||
_ => return Err(Error::BadRequest),
|
||||
};
|
||||
handle_report_calendar_query(query_node, request, events, context.store.clone()).await
|
||||
}
|
||||
|
||||
pub async fn handle_mkcol_calendar_set<C: CalendarStore>(
|
||||
store: &RwLock<C>,
|
||||
prop_node: Node<'_, '_>,
|
||||
cid: String,
|
||||
owner: String,
|
||||
) -> Result<()> {
|
||||
let mut cal = Calendar {
|
||||
owner,
|
||||
id: cid.clone(),
|
||||
..Default::default()
|
||||
};
|
||||
for prop in prop_node.children() {
|
||||
match prop.tag_name().name() {
|
||||
"displayname" => {
|
||||
cal.name = prop.text().map(|s| s.to_string());
|
||||
}
|
||||
"timezone" => {
|
||||
cal.timezone = prop.text().map(|s| s.to_string());
|
||||
}
|
||||
"calendar-color" => {
|
||||
cal.color = prop.text().map(|s| s.to_string());
|
||||
}
|
||||
"calendar-description" => {
|
||||
cal.description = prop.text().map(|s| s.to_string());
|
||||
}
|
||||
"calendar-timezone" => {
|
||||
cal.timezone = prop.text().map(|s| s.to_string());
|
||||
}
|
||||
_ => {
|
||||
println!("unsupported mkcol tag: {}", prop.tag_name().name())
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
store.write().await.insert_calendar(cid, cal).await?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub async fn route_mkcol_calendar<A: CheckAuthentication, C: CalendarStore>(
|
||||
path: Path<(String, String)>,
|
||||
body: String,
|
||||
auth: AuthInfoExtractor<A>,
|
||||
context: Data<CalDavContext<C>>,
|
||||
) -> Result<HttpResponse, Error> {
|
||||
let (_principal, cid) = path.into_inner();
|
||||
let doc = roxmltree::Document::parse(&body).map_err(|_e| Error::BadRequest)?;
|
||||
let mkcol_node = doc.root_element();
|
||||
match mkcol_node.tag_name().name() {
|
||||
"mkcol" => {}
|
||||
_ => return Err(Error::BadRequest),
|
||||
}
|
||||
|
||||
// TODO: Why does the spec (rfc5689) allow multiple <set/> elements but only one resource? :/
|
||||
// Well, for now just bother with the first one
|
||||
let set_node = mkcol_node.first_element_child().ok_or(Error::BadRequest)?;
|
||||
match set_node.tag_name().name() {
|
||||
"set" => {}
|
||||
_ => return Err(Error::BadRequest),
|
||||
}
|
||||
|
||||
let prop_node = set_node.first_element_child().ok_or(Error::BadRequest)?;
|
||||
if prop_node.tag_name().name() != "prop" {
|
||||
return Err(Error::BadRequest);
|
||||
}
|
||||
handle_mkcol_calendar_set(
|
||||
&context.store,
|
||||
prop_node,
|
||||
cid.clone(),
|
||||
auth.inner.user_id.clone(),
|
||||
)
|
||||
.await
|
||||
.map_err(|_e| Error::InternalError)?;
|
||||
|
||||
Ok(HttpResponse::Created().body(""))
|
||||
}
|
||||
79
crates/caldav/src/routes/event.rs
Normal file
79
crates/caldav/src/routes/event.rs
Normal file
@@ -0,0 +1,79 @@
|
||||
use crate::CalDavContext;
|
||||
use actix_web::http::StatusCode;
|
||||
use actix_web::web::{Data, Path};
|
||||
use actix_web::{HttpResponse, ResponseError};
|
||||
use rustical_auth::{AuthInfoExtractor, CheckAuthentication};
|
||||
use rustical_store::calendar::CalendarStore;
|
||||
use thiserror::Error;
|
||||
|
||||
#[derive(Debug, Error)]
|
||||
pub enum Error {
|
||||
#[error(transparent)]
|
||||
Other(#[from] anyhow::Error),
|
||||
}
|
||||
|
||||
impl ResponseError for Error {
|
||||
fn status_code(&self) -> actix_web::http::StatusCode {
|
||||
match self {
|
||||
Self::Other(_) => StatusCode::INTERNAL_SERVER_ERROR,
|
||||
}
|
||||
}
|
||||
fn error_response(&self) -> HttpResponse<actix_web::body::BoxBody> {
|
||||
HttpResponse::build(self.status_code()).body(self.to_string())
|
||||
}
|
||||
}
|
||||
|
||||
pub async fn delete_event<A: CheckAuthentication, C: CalendarStore>(
|
||||
context: Data<CalDavContext<C>>,
|
||||
path: Path<(String, String, String)>,
|
||||
auth: AuthInfoExtractor<A>,
|
||||
) -> Result<HttpResponse, Error> {
|
||||
let _user = auth.inner.user_id;
|
||||
// TODO: verify whether user is authorized
|
||||
let (_principal, mut cid, uid) = path.into_inner();
|
||||
if cid.ends_with(".ics") {
|
||||
cid.truncate(cid.len() - 4);
|
||||
}
|
||||
context.store.write().await.delete_event(&cid, &uid).await?;
|
||||
|
||||
Ok(HttpResponse::Ok().body(""))
|
||||
}
|
||||
|
||||
pub async fn get_event<A: CheckAuthentication, C: CalendarStore>(
|
||||
context: Data<CalDavContext<C>>,
|
||||
path: Path<(String, String, String)>,
|
||||
_auth: AuthInfoExtractor<A>,
|
||||
) -> Result<HttpResponse, Error> {
|
||||
// TODO: verify whether user is authorized
|
||||
let (_principal, cid, mut uid) = path.into_inner();
|
||||
if uid.ends_with(".ics") {
|
||||
uid.truncate(uid.len() - 4);
|
||||
}
|
||||
let event = context.store.read().await.get_event(&cid, &uid).await?;
|
||||
|
||||
Ok(HttpResponse::Ok()
|
||||
.insert_header(("ETag", event.get_etag()))
|
||||
.body(event.to_ics().to_string()))
|
||||
}
|
||||
|
||||
pub async fn put_event<A: CheckAuthentication, C: CalendarStore>(
|
||||
context: Data<CalDavContext<C>>,
|
||||
path: Path<(String, String, String)>,
|
||||
body: String,
|
||||
_auth: AuthInfoExtractor<A>,
|
||||
) -> Result<HttpResponse, Error> {
|
||||
// TODO: verify whether user is authorized
|
||||
let (_principal, cid, mut uid) = path.into_inner();
|
||||
// Incredibly bodged method of normalising the uid but works for a prototype
|
||||
if uid.ends_with(".ics") {
|
||||
uid.truncate(uid.len() - 4);
|
||||
}
|
||||
context
|
||||
.store
|
||||
.write()
|
||||
.await
|
||||
.upsert_event(cid, uid, body)
|
||||
.await?;
|
||||
|
||||
Ok(HttpResponse::Ok().body(""))
|
||||
}
|
||||
3
crates/caldav/src/routes/mod.rs
Normal file
3
crates/caldav/src/routes/mod.rs
Normal file
@@ -0,0 +1,3 @@
|
||||
pub mod calendar;
|
||||
pub mod event;
|
||||
pub mod propfind;
|
||||
112
crates/caldav/src/routes/propfind.rs
Normal file
112
crates/caldav/src/routes/propfind.rs
Normal file
@@ -0,0 +1,112 @@
|
||||
use crate::depth_extractor::Depth;
|
||||
use crate::namespace::Namespace;
|
||||
use crate::resource::{HandlePropfind, Resource};
|
||||
use crate::xml_snippets::generate_multistatus;
|
||||
use crate::CalDavContext;
|
||||
use actix_web::http::header::ContentType;
|
||||
use actix_web::http::StatusCode;
|
||||
use actix_web::web::{Data, Path};
|
||||
use actix_web::{HttpRequest, HttpResponse};
|
||||
use anyhow::Result;
|
||||
use quick_xml::events::BytesText;
|
||||
use rustical_auth::{AuthInfoExtractor, CheckAuthentication};
|
||||
use rustical_store::calendar::CalendarStore;
|
||||
use thiserror::Error;
|
||||
|
||||
#[derive(Debug, Error)]
|
||||
pub enum Error {
|
||||
#[error("invalid propfind request: {0}")]
|
||||
InvalidPropfind(&'static str),
|
||||
#[error("input is not valid xml")]
|
||||
ParsingError(#[from] roxmltree::Error),
|
||||
#[error(transparent)]
|
||||
Other(#[from] anyhow::Error),
|
||||
}
|
||||
|
||||
impl actix_web::error::ResponseError for Error {
|
||||
fn status_code(&self) -> actix_web::http::StatusCode {
|
||||
match self {
|
||||
Self::InvalidPropfind(_) => StatusCode::BAD_REQUEST,
|
||||
Self::ParsingError(_) => StatusCode::BAD_REQUEST,
|
||||
Self::Other(_) => StatusCode::INTERNAL_SERVER_ERROR,
|
||||
}
|
||||
}
|
||||
|
||||
fn error_response(&self) -> HttpResponse<actix_web::body::BoxBody> {
|
||||
HttpResponse::build(self.status_code()).body(self.to_string())
|
||||
}
|
||||
}
|
||||
|
||||
fn parse_propfind(body: &str) -> Result<Vec<&str>, Error> {
|
||||
if body.is_empty() {
|
||||
// if body is empty, allprops must be returned (RFC 4918)
|
||||
return Ok(vec!["allprops"]);
|
||||
}
|
||||
let doc = roxmltree::Document::parse(body)?;
|
||||
|
||||
let propfind_node = doc.root_element();
|
||||
if propfind_node.tag_name().name() != "propfind" {
|
||||
return Err(Error::InvalidPropfind("root tag is not <propfind>"));
|
||||
}
|
||||
|
||||
let prop_node = if let Some(el) = propfind_node.first_element_child() {
|
||||
el
|
||||
} else {
|
||||
return Ok(Vec::new());
|
||||
};
|
||||
|
||||
match prop_node.tag_name().name() {
|
||||
"prop" => Ok(prop_node
|
||||
.children()
|
||||
.map(|node| node.tag_name().name())
|
||||
.collect()),
|
||||
_ => Err(Error::InvalidPropfind(
|
||||
"invalid tag in <propfind>, expected <prop>",
|
||||
)),
|
||||
}
|
||||
}
|
||||
|
||||
pub async fn route_propfind<A: CheckAuthentication, R: Resource, C: CalendarStore>(
|
||||
path: Path<R::UriComponents>,
|
||||
body: String,
|
||||
req: HttpRequest,
|
||||
context: Data<CalDavContext<C>>,
|
||||
auth: AuthInfoExtractor<A>,
|
||||
depth: Depth,
|
||||
) -> Result<HttpResponse, Error> {
|
||||
let props = parse_propfind(&body)?;
|
||||
// let req_path = req.path().to_string();
|
||||
let auth_info = auth.inner;
|
||||
|
||||
let resource = R::acquire_from_request(
|
||||
req,
|
||||
auth_info,
|
||||
path.into_inner(),
|
||||
context.prefix.to_string(),
|
||||
)
|
||||
.await?;
|
||||
|
||||
let mut responses = vec![resource.propfind(props.clone())?];
|
||||
|
||||
if depth != Depth::Zero {
|
||||
for member in resource.get_members().await? {
|
||||
responses.push(member.propfind(props.clone())?);
|
||||
}
|
||||
}
|
||||
|
||||
let output = generate_multistatus(
|
||||
vec![Namespace::Dav, Namespace::CalDAV, Namespace::ICal],
|
||||
|writer| {
|
||||
for response in responses {
|
||||
writer.write_event(quick_xml::events::Event::Text(BytesText::from_escaped(
|
||||
response,
|
||||
)))?;
|
||||
}
|
||||
Ok(())
|
||||
},
|
||||
)?;
|
||||
|
||||
Ok(HttpResponse::MultiStatus()
|
||||
.content_type(ContentType::xml())
|
||||
.body(output))
|
||||
}
|
||||
109
crates/caldav/src/xml_snippets.rs
Normal file
109
crates/caldav/src/xml_snippets.rs
Normal file
@@ -0,0 +1,109 @@
|
||||
use std::io::Write;
|
||||
|
||||
use actix_web::http::StatusCode;
|
||||
use anyhow::Result;
|
||||
use quick_xml::{
|
||||
events::{attributes::Attribute, BytesText},
|
||||
Writer,
|
||||
};
|
||||
|
||||
pub fn write_resourcetype<W: Write>(
|
||||
writer: &mut Writer<W>,
|
||||
types: Vec<&str>,
|
||||
) -> Result<(), quick_xml::Error> {
|
||||
writer
|
||||
.create_element("resourcetype")
|
||||
.write_inner_content(|writer| {
|
||||
for resourcetype in types {
|
||||
writer.create_element(resourcetype).write_empty()?;
|
||||
}
|
||||
Ok(())
|
||||
})?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub fn write_invalid_props_response<W: Write>(
|
||||
writer: &mut Writer<W>,
|
||||
href: &str,
|
||||
invalid_props: Vec<&str>,
|
||||
) -> Result<(), quick_xml::Error> {
|
||||
if invalid_props.is_empty() {
|
||||
return Ok(());
|
||||
};
|
||||
|
||||
write_propstat_response(writer, href, StatusCode::NOT_FOUND, |writer| {
|
||||
for prop in invalid_props {
|
||||
writer.create_element(prop).write_empty()?;
|
||||
}
|
||||
Ok(())
|
||||
})?;
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub fn write_propstat_element<F, W: Write>(
|
||||
writer: &mut Writer<W>,
|
||||
status: StatusCode,
|
||||
prop_closure: F,
|
||||
) -> Result<(), quick_xml::Error>
|
||||
where
|
||||
F: FnOnce(&mut Writer<W>) -> Result<(), quick_xml::Error>,
|
||||
{
|
||||
writer
|
||||
.create_element("propstat")
|
||||
.write_inner_content(|writer| {
|
||||
writer
|
||||
.create_element("prop")
|
||||
.write_inner_content(prop_closure)?;
|
||||
|
||||
writer
|
||||
.create_element("status")
|
||||
.write_text_content(BytesText::new(&format!("HTTP/1.1 {}", status)))?;
|
||||
Ok(())
|
||||
})?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
// Writes a propstat response into a multistatus
|
||||
// closure hooks into the <prop> element
|
||||
pub fn write_propstat_response<F, W: Write>(
|
||||
writer: &mut Writer<W>,
|
||||
href: &str,
|
||||
status: StatusCode,
|
||||
prop_closure: F,
|
||||
) -> Result<(), quick_xml::Error>
|
||||
where
|
||||
F: FnOnce(&mut Writer<W>) -> Result<(), quick_xml::Error>,
|
||||
{
|
||||
writer
|
||||
.create_element("response")
|
||||
.write_inner_content(|writer| {
|
||||
writer
|
||||
.create_element("href")
|
||||
.write_text_content(BytesText::new(href))?;
|
||||
|
||||
write_propstat_element(writer, status, prop_closure)?;
|
||||
|
||||
Ok(())
|
||||
})?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub fn generate_multistatus<'a, F, A>(namespaces: A, closure: F) -> Result<String>
|
||||
where
|
||||
F: FnOnce(&mut Writer<&mut Vec<u8>>) -> Result<(), quick_xml::Error>,
|
||||
A: IntoIterator,
|
||||
A::Item: Into<Attribute<'a>>,
|
||||
{
|
||||
let mut output_buffer = Vec::new();
|
||||
let mut writer = Writer::new_with_indent(&mut output_buffer, b' ', 2);
|
||||
writer
|
||||
.create_element("multistatus")
|
||||
.with_attributes(namespaces)
|
||||
.write_inner_content(closure)?;
|
||||
|
||||
Ok(format!(
|
||||
"<?xml version=\"1.0\" encoding=\"utf-8\"?>\n{}",
|
||||
std::str::from_utf8(&output_buffer)?
|
||||
))
|
||||
}
|
||||
Reference in New Issue
Block a user