Add basic framework for PROPPATCH implementation

This commit is contained in:
Lennart
2024-06-20 19:40:01 +02:00
parent ae58a11500
commit f78f3e8194
8 changed files with 372 additions and 129 deletions

View File

@@ -3,11 +3,11 @@ use actix_web::{web::Data, HttpRequest};
use anyhow::anyhow; use anyhow::anyhow;
use async_trait::async_trait; use async_trait::async_trait;
use rustical_auth::AuthInfo; use rustical_auth::AuthInfo;
use rustical_dav::resource::{Resource, ResourceService}; use rustical_dav::resource::{InvalidProperty, Resource, ResourceService};
use rustical_dav::xml_snippets::{HrefElement, TextNode}; use rustical_dav::xml_snippets::{HrefElement, TextNode};
use rustical_store::calendar::Calendar; use rustical_store::calendar::Calendar;
use rustical_store::CalendarStore; use rustical_store::CalendarStore;
use serde::Serialize; use serde::{Deserialize, Serialize};
use std::sync::Arc; use std::sync::Arc;
use strum::{EnumString, IntoStaticStr, VariantNames}; use strum::{EnumString, IntoStaticStr, VariantNames};
use tokio::sync::RwLock; use tokio::sync::RwLock;
@@ -19,54 +19,54 @@ pub struct CalendarResource<C: CalendarStore + ?Sized> {
pub calendar_id: String, pub calendar_id: String,
} }
#[derive(Serialize)] #[derive(Debug, Clone, Deserialize, Serialize)]
#[serde(rename_all = "kebab-case")] #[serde(rename_all = "kebab-case")]
pub struct SupportedCalendarComponent { pub struct SupportedCalendarComponent {
#[serde(rename = "@name")] #[serde(rename = "@name")]
pub name: &'static str, pub name: String,
} }
#[derive(Serialize)] #[derive(Debug, Clone, Deserialize, Serialize)]
#[serde(rename_all = "kebab-case")] #[serde(rename_all = "kebab-case")]
pub struct SupportedCalendarComponentSet { pub struct SupportedCalendarComponentSet {
#[serde(rename = "C:comp")] #[serde(rename = "C:comp")]
pub comp: Vec<SupportedCalendarComponent>, pub comp: Vec<SupportedCalendarComponent>,
} }
#[derive(Serialize)] #[derive(Debug, Clone, Deserialize, Serialize)]
#[serde(rename_all = "kebab-case")] #[serde(rename_all = "kebab-case")]
pub struct CalendarData { pub struct CalendarData {
#[serde(rename = "@content-type")] #[serde(rename = "@content-type")]
content_type: &'static str, content_type: String,
#[serde(rename = "@version")] #[serde(rename = "@version")]
version: &'static str, version: String,
} }
impl Default for CalendarData { impl Default for CalendarData {
fn default() -> Self { fn default() -> Self {
Self { Self {
content_type: "text/calendar", content_type: "text/calendar".to_owned(),
version: "2.0", version: "2.0".to_owned(),
} }
} }
} }
#[derive(Serialize, Default)] #[derive(Debug, Clone, Deserialize, Serialize, Default)]
#[serde(rename_all = "kebab-case")] #[serde(rename_all = "kebab-case")]
pub struct SupportedCalendarData { pub struct SupportedCalendarData {
#[serde(rename = "C:calendar-data")] #[serde(rename = "C:calendar-data", alias = "calendar-data")]
calendar_data: CalendarData, calendar_data: CalendarData,
} }
#[derive(Serialize, Default)] #[derive(Debug, Clone, Deserialize, Serialize, Default)]
#[serde(rename_all = "kebab-case")] #[serde(rename_all = "kebab-case")]
pub struct Resourcetype { pub struct Resourcetype {
#[serde(rename = "C:calendar")] #[serde(rename = "C:calendar", alias = "calendar")]
calendar: (), calendar: (),
collection: (), collection: (),
} }
#[derive(Serialize)] #[derive(Debug, Clone, Deserialize, Serialize)]
#[serde(rename_all = "kebab-case")] #[serde(rename_all = "kebab-case")]
pub enum UserPrivilege { pub enum UserPrivilege {
Read, Read,
@@ -79,7 +79,7 @@ pub enum UserPrivilege {
Unbind, Unbind,
} }
#[derive(Serialize)] #[derive(Debug, Clone, Deserialize, Serialize)]
#[serde(rename_all = "kebab-case")] #[serde(rename_all = "kebab-case")]
pub struct UserPrivilegeWrapper { pub struct UserPrivilegeWrapper {
#[serde(rename = "$value")] #[serde(rename = "$value")]
@@ -92,7 +92,7 @@ impl From<UserPrivilege> for UserPrivilegeWrapper {
} }
} }
#[derive(Serialize)] #[derive(Debug, Clone, Deserialize, Serialize)]
#[serde(rename_all = "kebab-case")] #[serde(rename_all = "kebab-case")]
pub struct UserPrivilegeSet { pub struct UserPrivilegeSet {
privilege: Vec<UserPrivilegeWrapper>, privilege: Vec<UserPrivilegeWrapper>,
@@ -117,7 +117,7 @@ impl Default for UserPrivilegeSet {
#[derive(EnumString, Debug, VariantNames, IntoStaticStr, Clone)] #[derive(EnumString, Debug, VariantNames, IntoStaticStr, Clone)]
#[strum(serialize_all = "kebab-case")] #[strum(serialize_all = "kebab-case")]
pub enum CalendarProp { pub enum CalendarPropName {
Resourcetype, Resourcetype,
CurrentUserPrincipal, CurrentUserPrincipal,
Owner, Owner,
@@ -132,9 +132,9 @@ pub enum CalendarProp {
MaxResourceSize, MaxResourceSize,
} }
#[derive(Serialize)] #[derive(Debug, Clone, Deserialize, Serialize)]
#[serde(rename_all = "kebab-case")] #[serde(rename_all = "kebab-case")]
pub enum CalendarPropResponse { pub enum CalendarProp {
Resourcetype(Resourcetype), Resourcetype(Resourcetype),
CurrentUserPrincipal(HrefElement), CurrentUserPrincipal(HrefElement),
Owner(HrefElement), Owner(HrefElement),
@@ -158,8 +158,17 @@ pub enum CalendarPropResponse {
Getcontenttype(TextNode), Getcontenttype(TextNode),
MaxResourceSize(TextNode), MaxResourceSize(TextNode),
CurrentUserPrivilegeSet(UserPrivilegeSet), CurrentUserPrivilegeSet(UserPrivilegeSet),
#[serde(other)]
Invalid,
} }
impl InvalidProperty for CalendarProp {
fn invalid_property(&self) -> bool {
matches!(self, Self::Invalid)
}
}
#[derive(Clone, Debug)]
pub struct CalendarFile { pub struct CalendarFile {
pub calendar: Calendar, pub calendar: Calendar,
pub principal: String, pub principal: String,
@@ -167,60 +176,69 @@ pub struct CalendarFile {
} }
impl Resource for CalendarFile { impl Resource for CalendarFile {
type PropType = CalendarProp; type PropName = CalendarPropName;
type PropResponse = CalendarPropResponse; type Prop = CalendarProp;
type Error = Error; type Error = Error;
fn get_prop( fn get_prop(&self, prefix: &str, prop: Self::PropName) -> Result<Self::Prop, Self::Error> {
&self,
prefix: &str,
prop: Self::PropType,
) -> Result<Self::PropResponse, Self::Error> {
match prop { match prop {
CalendarProp::Resourcetype => { CalendarPropName::Resourcetype => {
Ok(CalendarPropResponse::Resourcetype(Resourcetype::default())) Ok(CalendarProp::Resourcetype(Resourcetype::default()))
} }
CalendarProp::CurrentUserPrincipal => Ok(CalendarPropResponse::CurrentUserPrincipal( CalendarPropName::CurrentUserPrincipal => Ok(CalendarProp::CurrentUserPrincipal(
HrefElement::new(format!("{}/{}/", prefix, self.principal)), HrefElement::new(format!("{}/{}/", prefix, self.principal)),
)), )),
CalendarProp::Owner => Ok(CalendarPropResponse::Owner(HrefElement::new(format!( CalendarPropName::Owner => Ok(CalendarProp::Owner(HrefElement::new(format!(
"{}/{}/", "{}/{}/",
prefix, self.principal prefix, self.principal
)))), )))),
CalendarProp::Displayname => Ok(CalendarPropResponse::Displayname(TextNode( CalendarPropName::Displayname => Ok(CalendarProp::Displayname(TextNode(
self.calendar.name.clone(), self.calendar.name.clone(),
))), ))),
CalendarProp::CalendarColor => Ok(CalendarPropResponse::CalendarColor(TextNode( CalendarPropName::CalendarColor => Ok(CalendarProp::CalendarColor(TextNode(
self.calendar.color.clone(), self.calendar.color.clone(),
))), ))),
CalendarProp::CalendarDescription => Ok(CalendarPropResponse::CalendarDescription( CalendarPropName::CalendarDescription => Ok(CalendarProp::CalendarDescription(
TextNode(self.calendar.description.clone()), TextNode(self.calendar.description.clone()),
)), )),
CalendarProp::CalendarOrder => Ok(CalendarPropResponse::CalendarOrder(TextNode( CalendarPropName::CalendarOrder => Ok(CalendarProp::CalendarOrder(TextNode(
format!("{}", self.calendar.order).into(), format!("{}", self.calendar.order).into(),
))), ))),
CalendarProp::SupportedCalendarComponentSet => { CalendarPropName::SupportedCalendarComponentSet => Ok(
Ok(CalendarPropResponse::SupportedCalendarComponentSet( CalendarProp::SupportedCalendarComponentSet(SupportedCalendarComponentSet {
SupportedCalendarComponentSet { comp: vec![SupportedCalendarComponent {
comp: vec![SupportedCalendarComponent { name: "VEVENT" }], name: "VEVENT".to_owned(),
}, }],
)) }),
} ),
CalendarProp::SupportedCalendarData => Ok(CalendarPropResponse::SupportedCalendarData( CalendarPropName::SupportedCalendarData => Ok(CalendarProp::SupportedCalendarData(
SupportedCalendarData::default(), SupportedCalendarData::default(),
)), )),
CalendarProp::Getcontenttype => Ok(CalendarPropResponse::Getcontenttype(TextNode( CalendarPropName::Getcontenttype => Ok(CalendarProp::Getcontenttype(TextNode(Some(
Some("text/calendar;charset=utf-8".to_owned()), "text/calendar;charset=utf-8".to_owned(),
))), )))),
CalendarProp::MaxResourceSize => Ok(CalendarPropResponse::MaxResourceSize(TextNode( CalendarPropName::MaxResourceSize => Ok(CalendarProp::MaxResourceSize(TextNode(Some(
Some("10000000".to_owned()), "10000000".to_owned(),
))), )))),
CalendarProp::CurrentUserPrivilegeSet => Ok( CalendarPropName::CurrentUserPrivilegeSet => Ok(CalendarProp::CurrentUserPrivilegeSet(
CalendarPropResponse::CurrentUserPrivilegeSet(UserPrivilegeSet::default()), UserPrivilegeSet::default(),
), )),
} }
} }
fn set_prop(&mut self, prop: Self::Prop) -> Result<(), rustical_dav::Error> {
match prop {
CalendarProp::CalendarColor(color) => {
self.calendar.color = color.0;
}
CalendarProp::Displayname(TextNode(name)) => {
self.calendar.name = name;
}
_ => return Err(rustical_dav::Error::PropReadOnly),
}
Ok(())
}
fn get_path(&self) -> &str { fn get_path(&self) -> &str {
&self.path &self.path
} }
@@ -274,4 +292,13 @@ impl<C: CalendarStore + ?Sized> ResourceService for CalendarResource<C> {
cal_store, cal_store,
}) })
} }
async fn save_file(&self, file: Self::File) -> Result<(), Self::Error> {
self.cal_store
.write()
.await
.update_calendar(self.calendar_id.to_owned(), file.calendar)
.await?;
Ok(())
}
} }

View File

@@ -3,11 +3,11 @@ use actix_web::{web::Data, HttpRequest};
use anyhow::anyhow; use anyhow::anyhow;
use async_trait::async_trait; use async_trait::async_trait;
use rustical_auth::AuthInfo; use rustical_auth::AuthInfo;
use rustical_dav::resource::{Resource, ResourceService}; use rustical_dav::resource::{InvalidProperty, Resource, ResourceService};
use rustical_dav::xml_snippets::TextNode; use rustical_dav::xml_snippets::TextNode;
use rustical_store::event::Event; use rustical_store::event::Event;
use rustical_store::CalendarStore; use rustical_store::CalendarStore;
use serde::Serialize; use serde::{Deserialize, Serialize};
use std::sync::Arc; use std::sync::Arc;
use strum::{EnumString, IntoStaticStr, VariantNames}; use strum::{EnumString, IntoStaticStr, VariantNames};
use tokio::sync::RwLock; use tokio::sync::RwLock;
@@ -21,52 +21,59 @@ pub struct EventResource<C: CalendarStore + ?Sized> {
#[derive(EnumString, Debug, VariantNames, IntoStaticStr, Clone)] #[derive(EnumString, Debug, VariantNames, IntoStaticStr, Clone)]
#[strum(serialize_all = "kebab-case")] #[strum(serialize_all = "kebab-case")]
pub enum EventProp { pub enum EventPropName {
Getetag, Getetag,
CalendarData, CalendarData,
Getcontenttype, Getcontenttype,
} }
#[derive(Serialize)] #[derive(Deserialize, Serialize, Debug, Clone, IntoStaticStr)]
#[serde(rename_all = "kebab-case")] #[serde(rename_all = "kebab-case")]
pub enum EventPropResponse { pub enum EventProp {
Getetag(TextNode), Getetag(TextNode),
#[serde(rename = "C:calendar-data")] #[serde(rename = "C:calendar-data")]
CalendarData(TextNode), CalendarData(TextNode),
Getcontenttype(TextNode), Getcontenttype(TextNode),
#[serde(other)]
Invalid,
} }
impl InvalidProperty for EventProp {
fn invalid_property(&self) -> bool {
matches!(self, Self::Invalid)
}
}
#[derive(Clone)]
pub struct EventFile { pub struct EventFile {
pub event: Event, pub event: Event,
pub path: String, pub path: String,
} }
impl Resource for EventFile { impl Resource for EventFile {
type PropType = EventProp; type PropName = EventPropName;
type PropResponse = EventPropResponse; type Prop = EventProp;
type Error = Error; type Error = Error;
fn get_path(&self) -> &str { fn get_path(&self) -> &str {
&self.path &self.path
} }
fn get_prop( fn get_prop(&self, _prefix: &str, prop: Self::PropName) -> Result<Self::Prop, Self::Error> {
&self,
_prefix: &str,
prop: Self::PropType,
) -> Result<Self::PropResponse, Self::Error> {
match prop { match prop {
EventProp::Getetag => Ok(EventPropResponse::Getetag(TextNode(Some( EventPropName::Getetag => Ok(EventProp::Getetag(TextNode(Some(self.event.get_etag())))),
self.event.get_etag(), EventPropName::CalendarData => Ok(EventProp::CalendarData(TextNode(Some(
)))),
EventProp::CalendarData => Ok(EventPropResponse::CalendarData(TextNode(Some(
self.event.get_ics().to_owned(), self.event.get_ics().to_owned(),
)))), )))),
EventProp::Getcontenttype => Ok(EventPropResponse::Getcontenttype(TextNode(Some( EventPropName::Getcontenttype => Ok(EventProp::Getcontenttype(TextNode(Some(
"text/calendar;charset=utf-8".to_owned(), "text/calendar;charset=utf-8".to_owned(),
)))), )))),
} }
} }
fn set_prop(&mut self, _prop: Self::Prop) -> Result<(), rustical_dav::Error> {
Err(rustical_dav::Error::PropReadOnly)
}
} }
#[async_trait(?Send)] #[async_trait(?Send)]
@@ -116,4 +123,8 @@ impl<C: CalendarStore + ?Sized> ResourceService for EventResource<C> {
path: self.path.to_owned(), path: self.path.to_owned(),
}) })
} }
async fn save_file(&self, _file: Self::File) -> Result<(), Self::Error> {
Err(Error::NotImplemented)
}
} }

View File

@@ -7,6 +7,7 @@ use principal::PrincipalResource;
use root::RootResource; use root::RootResource;
use rustical_auth::CheckAuthentication; use rustical_auth::CheckAuthentication;
use rustical_dav::propfind::{route_propfind, ServicePrefix}; use rustical_dav::propfind::{route_propfind, ServicePrefix};
use rustical_dav::proppatch::route_proppatch;
use rustical_store::CalendarStore; use rustical_store::CalendarStore;
use std::str::FromStr; use std::str::FromStr;
use std::sync::Arc; use std::sync::Arc;
@@ -35,6 +36,7 @@ pub fn configure_dav<A: CheckAuthentication, C: CalendarStore + ?Sized>(
store: Arc<RwLock<C>>, store: Arc<RwLock<C>>,
) { ) {
let propfind_method = || web::method(Method::from_str("PROPFIND").unwrap()); let propfind_method = || web::method(Method::from_str("PROPFIND").unwrap());
let proppatch_method = || web::method(Method::from_str("PROPPATCH").unwrap());
let report_method = || web::method(Method::from_str("REPORT").unwrap()); let report_method = || web::method(Method::from_str("REPORT").unwrap());
let mkcalendar_method = || web::method(Method::from_str("MKCALENDAR").unwrap()); let mkcalendar_method = || web::method(Method::from_str("MKCALENDAR").unwrap());
@@ -50,15 +52,21 @@ pub fn configure_dav<A: CheckAuthentication, C: CalendarStore + ?Sized>(
.guard(guard::Method(Method::OPTIONS)) .guard(guard::Method(Method::OPTIONS))
.to(options_handler), .to(options_handler),
) )
.service(web::resource("").route(propfind_method().to(route_propfind::<A, RootResource>))) .service(
web::resource("")
.route(propfind_method().to(route_propfind::<A, RootResource>))
.route(proppatch_method().to(route_proppatch::<A, RootResource>)),
)
.service( .service(
web::resource("/{principal}") web::resource("/{principal}")
.route(propfind_method().to(route_propfind::<A, PrincipalResource<C>>)), .route(propfind_method().to(route_propfind::<A, PrincipalResource<C>>))
.route(proppatch_method().to(route_proppatch::<A, PrincipalResource<C>>)),
) )
.service( .service(
web::resource("/{principal}/{calendar}") web::resource("/{principal}/{calendar}")
.route(report_method().to(calendar::methods::report::route_report_calendar::<A, C>)) .route(report_method().to(calendar::methods::report::route_report_calendar::<A, C>))
.route(propfind_method().to(route_propfind::<A, CalendarResource<C>>)) .route(propfind_method().to(route_propfind::<A, CalendarResource<C>>))
.route(proppatch_method().to(route_proppatch::<A, CalendarResource<C>>))
.route( .route(
mkcalendar_method().to(calendar::methods::mkcalendar::route_mkcol_calendar::<A, C>), mkcalendar_method().to(calendar::methods::mkcalendar::route_mkcol_calendar::<A, C>),
) )
@@ -70,6 +78,7 @@ pub fn configure_dav<A: CheckAuthentication, C: CalendarStore + ?Sized>(
.service( .service(
web::resource("/{principal}/{calendar}/{event}") web::resource("/{principal}/{calendar}/{event}")
.route(propfind_method().to(route_propfind::<A, EventResource<C>>)) .route(propfind_method().to(route_propfind::<A, EventResource<C>>))
.route(proppatch_method().to(route_proppatch::<A, EventResource<C>>))
.route(web::method(Method::DELETE).to(event::methods::delete_event::<A, C>)) .route(web::method(Method::DELETE).to(event::methods::delete_event::<A, C>))
.route(web::method(Method::GET).to(event::methods::get_event::<A, C>)) .route(web::method(Method::GET).to(event::methods::get_event::<A, C>))
.route(web::method(Method::PUT).to(event::methods::put_event::<A, C>)), .route(web::method(Method::PUT).to(event::methods::put_event::<A, C>)),

View File

@@ -4,12 +4,12 @@ use actix_web::HttpRequest;
use anyhow::anyhow; use anyhow::anyhow;
use async_trait::async_trait; use async_trait::async_trait;
use rustical_auth::AuthInfo; use rustical_auth::AuthInfo;
use rustical_dav::resource::{Resource, ResourceService}; use rustical_dav::resource::{InvalidProperty, Resource, ResourceService};
use rustical_dav::xml_snippets::HrefElement; use rustical_dav::xml_snippets::HrefElement;
use rustical_store::CalendarStore; use rustical_store::CalendarStore;
use serde::Serialize; use serde::{Deserialize, Serialize};
use std::sync::Arc; use std::sync::Arc;
use strum::{EnumString, IntoStaticStr, VariantNames}; use strum::{AsRefStr, EnumString, VariantNames};
use tokio::sync::RwLock; use tokio::sync::RwLock;
use crate::calendar::resource::CalendarFile; use crate::calendar::resource::CalendarFile;
@@ -20,21 +20,22 @@ pub struct PrincipalResource<C: CalendarStore + ?Sized> {
cal_store: Arc<RwLock<C>>, cal_store: Arc<RwLock<C>>,
} }
#[derive(Clone)]
pub struct PrincipalFile { pub struct PrincipalFile {
principal: String, principal: String,
path: String, path: String,
} }
#[derive(Serialize, Default)] #[derive(Deserialize, Serialize, Default, Debug)]
#[serde(rename_all = "kebab-case")] #[serde(rename_all = "kebab-case")]
pub struct Resourcetype { pub struct Resourcetype {
principal: (), principal: (),
collection: (), collection: (),
} }
#[derive(Serialize)] #[derive(Deserialize, Serialize, Debug)]
#[serde(rename_all = "kebab-case")] #[serde(rename_all = "kebab-case")]
pub enum PrincipalPropResponse { pub enum PrincipalProp {
Resourcetype(Resourcetype), Resourcetype(Resourcetype),
CurrentUserPrincipal(HrefElement), CurrentUserPrincipal(HrefElement),
#[serde(rename = "principal-URL")] #[serde(rename = "principal-URL")]
@@ -43,11 +44,19 @@ pub enum PrincipalPropResponse {
CalendarHomeSet(HrefElement), CalendarHomeSet(HrefElement),
#[serde(rename = "C:calendar-user-address-set")] #[serde(rename = "C:calendar-user-address-set")]
CalendarUserAddressSet(HrefElement), CalendarUserAddressSet(HrefElement),
#[serde(other)]
Invalid,
} }
#[derive(EnumString, Debug, VariantNames, IntoStaticStr, Clone)] impl InvalidProperty for PrincipalProp {
fn invalid_property(&self) -> bool {
matches!(self, Self::Invalid)
}
}
#[derive(EnumString, Debug, VariantNames, AsRefStr, Clone)]
#[strum(serialize_all = "kebab-case")] #[strum(serialize_all = "kebab-case")]
pub enum PrincipalProp { pub enum PrincipalPropName {
Resourcetype, Resourcetype,
CurrentUserPrincipal, CurrentUserPrincipal,
#[strum(serialize = "principal-URL")] #[strum(serialize = "principal-URL")]
@@ -58,36 +67,34 @@ pub enum PrincipalProp {
#[async_trait(?Send)] #[async_trait(?Send)]
impl Resource for PrincipalFile { impl Resource for PrincipalFile {
type PropType = PrincipalProp; type PropName = PrincipalPropName;
type PropResponse = PrincipalPropResponse; type Prop = PrincipalProp;
type Error = Error; type Error = Error;
fn get_prop( fn get_prop(&self, prefix: &str, prop: Self::PropName) -> Result<Self::Prop, Self::Error> {
&self,
prefix: &str,
prop: Self::PropType,
) -> Result<Self::PropResponse, Self::Error> {
match prop { match prop {
PrincipalProp::Resourcetype => { PrincipalPropName::Resourcetype => {
Ok(PrincipalPropResponse::Resourcetype(Resourcetype::default())) Ok(PrincipalProp::Resourcetype(Resourcetype::default()))
} }
PrincipalProp::CurrentUserPrincipal => Ok(PrincipalPropResponse::CurrentUserPrincipal( PrincipalPropName::CurrentUserPrincipal => Ok(PrincipalProp::CurrentUserPrincipal(
HrefElement::new(format!("{}/{}/", prefix, self.principal)), HrefElement::new(format!("{}/{}/", prefix, self.principal)),
)), )),
PrincipalProp::PrincipalUrl => Ok(PrincipalPropResponse::PrincipalUrl( PrincipalPropName::PrincipalUrl => Ok(PrincipalProp::PrincipalUrl(HrefElement::new(
format!("{}/{}/", prefix, self.principal),
))),
PrincipalPropName::CalendarHomeSet => Ok(PrincipalProp::CalendarHomeSet(
HrefElement::new(format!("{}/{}/", prefix, self.principal)), HrefElement::new(format!("{}/{}/", prefix, self.principal)),
)), )),
PrincipalProp::CalendarHomeSet => Ok(PrincipalPropResponse::CalendarHomeSet( PrincipalPropName::CalendarUserAddressSet => Ok(PrincipalProp::CalendarUserAddressSet(
HrefElement::new(format!("{}/{}/", prefix, self.principal)), HrefElement::new(format!("{}/{}/", prefix, self.principal)),
)), )),
PrincipalProp::CalendarUserAddressSet => {
Ok(PrincipalPropResponse::CalendarUserAddressSet(
HrefElement::new(format!("{}/{}/", prefix, self.principal)),
))
}
} }
} }
fn set_prop(&mut self, _prop: Self::Prop) -> Result<(), rustical_dav::Error> {
Err(rustical_dav::Error::PropReadOnly)
}
fn get_path(&self) -> &str { fn get_path(&self) -> &str {
&self.path &self.path
} }
@@ -147,4 +154,8 @@ impl<C: CalendarStore + ?Sized> ResourceService for PrincipalResource<C> {
}) })
.collect()) .collect())
} }
async fn save_file(&self, _file: Self::File) -> Result<(), Self::Error> {
Err(Error::NotImplemented)
}
} }

View File

@@ -2,9 +2,9 @@ use crate::Error;
use actix_web::HttpRequest; use actix_web::HttpRequest;
use async_trait::async_trait; use async_trait::async_trait;
use rustical_auth::AuthInfo; use rustical_auth::AuthInfo;
use rustical_dav::resource::{Resource, ResourceService}; use rustical_dav::resource::{InvalidProperty, Resource, ResourceService};
use rustical_dav::xml_snippets::HrefElement; use rustical_dav::xml_snippets::HrefElement;
use serde::Serialize; use serde::{Deserialize, Serialize};
use strum::{EnumString, IntoStaticStr, VariantNames}; use strum::{EnumString, IntoStaticStr, VariantNames};
pub struct RootResource { pub struct RootResource {
@@ -14,47 +14,56 @@ pub struct RootResource {
#[derive(EnumString, Debug, VariantNames, IntoStaticStr, Clone)] #[derive(EnumString, Debug, VariantNames, IntoStaticStr, Clone)]
#[strum(serialize_all = "kebab-case")] #[strum(serialize_all = "kebab-case")]
pub enum RootProp { pub enum RootPropName {
Resourcetype, Resourcetype,
CurrentUserPrincipal, CurrentUserPrincipal,
} }
#[derive(Serialize, Default)] #[derive(Deserialize, Serialize, Default, Debug)]
#[serde(rename_all = "kebab-case")] #[serde(rename_all = "kebab-case")]
pub struct Resourcetype { pub struct Resourcetype {
collection: (), collection: (),
} }
#[derive(Serialize)] #[derive(Deserialize, Serialize, Debug)]
#[serde(rename_all = "kebab-case")] #[serde(rename_all = "kebab-case")]
pub enum RootPropResponse { pub enum RootProp {
Resourcetype(Resourcetype), Resourcetype(Resourcetype),
CurrentUserPrincipal(HrefElement), CurrentUserPrincipal(HrefElement),
#[serde(other)]
Invalid,
} }
impl InvalidProperty for RootProp {
fn invalid_property(&self) -> bool {
matches!(self, Self::Invalid)
}
}
#[derive(Clone)]
pub struct RootFile { pub struct RootFile {
pub principal: String, pub principal: String,
pub path: String, pub path: String,
} }
impl Resource for RootFile { impl Resource for RootFile {
type PropType = RootProp; type PropName = RootPropName;
type PropResponse = RootPropResponse; type Prop = RootProp;
type Error = Error; type Error = Error;
fn get_prop( fn get_prop(&self, prefix: &str, prop: Self::PropName) -> Result<Self::Prop, Self::Error> {
&self,
prefix: &str,
prop: Self::PropType,
) -> Result<Self::PropResponse, Self::Error> {
match prop { match prop {
RootProp::Resourcetype => Ok(RootPropResponse::Resourcetype(Resourcetype::default())), RootPropName::Resourcetype => Ok(RootProp::Resourcetype(Resourcetype::default())),
RootProp::CurrentUserPrincipal => Ok(RootPropResponse::CurrentUserPrincipal( RootPropName::CurrentUserPrincipal => Ok(RootProp::CurrentUserPrincipal(
HrefElement::new(format!("{}/{}/", prefix, self.principal)), HrefElement::new(format!("{}/{}/", prefix, self.principal)),
)), )),
} }
} }
fn set_prop(&mut self, _prop: Self::Prop) -> Result<(), rustical_dav::Error> {
Err(rustical_dav::Error::PropReadOnly)
}
fn get_path(&self) -> &str { fn get_path(&self) -> &str {
&self.path &self.path
} }
@@ -91,4 +100,8 @@ impl ResourceService for RootResource {
principal: self.principal.to_owned(), principal: self.principal.to_owned(),
}) })
} }
async fn save_file(&self, _file: Self::File) -> Result<(), Self::Error> {
Err(Error::NotImplemented)
}
} }

View File

@@ -2,6 +2,7 @@ pub mod depth_extractor;
pub mod error; pub mod error;
pub mod namespace; pub mod namespace;
pub mod propfind; pub mod propfind;
pub mod proppatch;
pub mod resource; pub mod resource;
pub mod xml; pub mod xml;
pub mod xml_snippets; pub mod xml_snippets;

165
crates/dav/src/proppatch.rs Normal file
View File

@@ -0,0 +1,165 @@
use crate::namespace::Namespace;
use crate::propfind::MultistatusElement;
use crate::resource::InvalidProperty;
use crate::resource::Resource;
use crate::resource::ResourceService;
use crate::resource::{PropstatElement, PropstatResponseElement, PropstatType};
use crate::xml::tag_list::TagList;
use crate::xml::tag_name::TagName;
use crate::Error;
use actix_web::http::header::ContentType;
use actix_web::http::StatusCode;
use actix_web::{web::Path, HttpRequest, HttpResponse};
use rustical_auth::{AuthInfoExtractor, CheckAuthentication};
use serde::{Deserialize, Serialize};
// https://docs.rs/quick-xml/latest/quick_xml/de/index.html#normal-enum-variant
#[derive(Deserialize, Serialize, Clone, Debug)]
#[serde(rename_all = "kebab-case")]
struct PropertyElement<T> {
#[serde(rename = "$value")]
prop: T,
}
#[derive(Deserialize, Clone, Debug)]
#[serde(rename_all = "kebab-case")]
struct SetPropertyElement<T> {
prop: PropertyElement<T>,
}
#[derive(Deserialize, Clone, Debug)]
#[serde(rename_all = "kebab-case")]
struct RemovePropertyElement {
#[serde(rename = "$value")]
prop: TagName,
}
#[derive(Deserialize, Clone, Debug)]
#[serde(rename_all = "kebab-case")]
struct PropertyupdateElement<T> {
#[serde(default = "Vec::new")]
set: Vec<SetPropertyElement<T>>,
#[serde(default = "Vec::new")]
remove: Vec<RemovePropertyElement>,
}
pub async fn route_proppatch<A: CheckAuthentication, R: ResourceService + ?Sized>(
path: Path<R::PathComponents>,
body: String,
req: HttpRequest,
auth: AuthInfoExtractor<A>,
) -> Result<HttpResponse, R::Error> {
let auth_info = auth.inner;
let path_components = path.into_inner();
let href = req.path().to_owned();
let resource_service = R::new(req, auth_info.clone(), path_components.clone()).await?;
// TODO: Implement remove!
let PropertyupdateElement::<<R::File as Resource>::Prop> {
set: set_els,
remove: remove_els,
} = quick_xml::de::from_str(&body).map_err(Error::XmlDecodeError)?;
// Extract all property names without verification
// Weird workaround because quick_xml doesn't allow untagged enums
let propnames: Vec<String> = quick_xml::de::from_str::<PropertyupdateElement<TagName>>(&body)
.map_err(Error::XmlDecodeError)?
.set
.into_iter()
.map(|set_el| set_el.prop.prop.into())
.collect();
// Invalid properties
let props_not_found: Vec<String> = propnames
.iter()
.zip(&set_els)
.filter_map(
|(
name,
SetPropertyElement {
prop: PropertyElement { prop },
},
)| {
if prop.invalid_property() {
Some(name.to_string())
} else {
None
}
},
)
.collect();
// Filter out invalid props
let set_props: Vec<<R::File as Resource>::Prop> = set_els
.into_iter()
.filter_map(
|SetPropertyElement {
prop: PropertyElement { prop },
}| {
if prop.invalid_property() {
None
} else {
Some(prop)
}
},
)
.collect();
let mut resource = resource_service.get_file().await?;
let mut props_ok = Vec::new();
let mut props_conflict = Vec::new();
for (prop, propname) in set_props.into_iter().zip(propnames) {
match resource.set_prop(prop) {
Ok(()) => {
props_ok.push(propname);
}
Err(Error::PropReadOnly) => {
props_conflict.push(propname);
}
Err(err) => {
return Err(err.into());
}
};
}
if props_not_found.is_empty() && props_conflict.is_empty() {
// Only save if no errors occured
resource_service.save_file(resource).await?;
}
let mut output = "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n".to_owned();
let mut ser = quick_xml::se::Serializer::new(&mut output);
ser.indent(' ', 4);
MultistatusElement {
responses: vec![PropstatResponseElement {
href,
propstat: vec![
PropstatType::Normal(PropstatElement {
prop: TagList::from(props_ok),
status: format!("HTTP/1.1 {}", StatusCode::OK),
}),
PropstatType::NotFound(PropstatElement {
prop: TagList::from(props_not_found),
status: format!("HTTP/1.1 {}", StatusCode::NOT_FOUND),
}),
PropstatType::Conflict(PropstatElement {
prop: TagList::from(props_conflict),
status: format!("HTTP/1.1 {}", StatusCode::CONFLICT),
}),
],
}],
// Dummy just for typing
member_responses: Vec::<String>::new(),
ns_dav: Namespace::Dav.as_str(),
ns_caldav: Namespace::CalDAV.as_str(),
ns_ical: Namespace::ICal.as_str(),
}
.serialize(ser)
.unwrap();
Ok(HttpResponse::MultiStatus()
.content_type(ContentType::xml())
.body(output))
}

View File

@@ -2,29 +2,32 @@ use crate::xml::tag_list::TagList;
use crate::Error; use crate::Error;
use actix_web::{http::StatusCode, HttpRequest, ResponseError}; use actix_web::{http::StatusCode, HttpRequest, ResponseError};
use async_trait::async_trait; use async_trait::async_trait;
use core::fmt;
use itertools::Itertools; use itertools::Itertools;
use rustical_auth::AuthInfo; use rustical_auth::AuthInfo;
use serde::Serialize; use serde::{Deserialize, Serialize};
use std::str::FromStr; use std::str::FromStr;
use strum::VariantNames; use strum::VariantNames;
#[async_trait(?Send)] #[async_trait(?Send)]
pub trait Resource { pub trait Resource: Clone {
type PropType: FromStr + VariantNames + Clone; type PropName: FromStr + VariantNames + Clone;
type PropResponse: Serialize; type Prop: Serialize + for<'de> Deserialize<'de> + fmt::Debug + InvalidProperty;
type Error: ResponseError + From<crate::Error> + From<anyhow::Error>; type Error: ResponseError + From<crate::Error> + From<anyhow::Error>;
fn list_dead_props() -> &'static [&'static str] { fn list_dead_props() -> &'static [&'static str] {
Self::PropType::VARIANTS Self::PropName::VARIANTS
} }
fn get_prop( fn get_prop(&self, prefix: &str, prop: Self::PropName) -> Result<Self::Prop, Self::Error>;
&self,
prefix: &str,
prop: Self::PropType,
) -> Result<Self::PropResponse, Self::Error>;
fn get_path(&self) -> &str; fn get_path(&self) -> &str;
fn set_prop(&mut self, prop: Self::Prop) -> Result<(), crate::Error>;
}
pub trait InvalidProperty {
fn invalid_property(&self) -> bool;
} }
// A resource is identified by a URI and has properties // A resource is identified by a URI and has properties
@@ -47,6 +50,8 @@ pub trait ResourceService: Sized {
async fn get_file(&self) -> Result<Self::File, Self::Error>; async fn get_file(&self) -> Result<Self::File, Self::Error>;
async fn get_members(&self, auth_info: AuthInfo) -> Result<Vec<Self::MemberType>, Self::Error>; async fn get_members(&self, auth_info: AuthInfo) -> Result<Vec<Self::MemberType>, Self::Error>;
async fn save_file(&self, file: Self::File) -> Result<(), Self::Error>;
} }
#[derive(Serialize)] #[derive(Serialize)]
@@ -57,23 +62,24 @@ pub struct PropWrapper<T: Serialize> {
#[derive(Serialize)] #[derive(Serialize)]
#[serde(rename_all = "kebab-case")] #[serde(rename_all = "kebab-case")]
struct PropstatElement<T: Serialize> { pub struct PropstatElement<T: Serialize> {
prop: T, pub prop: T,
status: String, pub status: String,
} }
#[derive(Serialize)] #[derive(Serialize)]
#[serde(rename_all = "kebab-case")] #[serde(rename_all = "kebab-case")]
pub struct PropstatResponseElement<T1: Serialize, T2: Serialize> { pub struct PropstatResponseElement<T1: Serialize, T2: Serialize> {
href: String, pub href: String,
propstat: Vec<PropstatType<T1, T2>>, pub propstat: Vec<PropstatType<T1, T2>>,
} }
#[derive(Serialize)] #[derive(Serialize)]
#[serde(untagged)] #[serde(untagged)]
enum PropstatType<T1: Serialize, T2: Serialize> { pub enum PropstatType<T1: Serialize, T2: Serialize> {
Normal(PropstatElement<T1>), Normal(PropstatElement<T1>),
NotFound(PropstatElement<T2>), NotFound(PropstatElement<T2>),
Conflict(PropstatElement<T2>),
} }
#[async_trait(?Send)] #[async_trait(?Send)]
@@ -92,7 +98,7 @@ impl<R: Resource> HandlePropfind for R {
&self, &self,
prefix: &str, prefix: &str,
props: Vec<&str>, props: Vec<&str>,
) -> Result<PropstatResponseElement<PropWrapper<Vec<R::PropResponse>>, TagList>, R::Error> { ) -> Result<PropstatResponseElement<PropWrapper<Vec<R::Prop>>, TagList>, R::Error> {
let mut props = props; let mut props = props;
if props.contains(&"propname") { if props.contains(&"propname") {
if props.len() != 1 { if props.len() != 1 {
@@ -117,7 +123,7 @@ impl<R: Resource> HandlePropfind for R {
let mut invalid_props = Vec::new(); let mut invalid_props = Vec::new();
let mut prop_responses = Vec::new(); let mut prop_responses = Vec::new();
for prop in props { for prop in props {
if let Ok(valid_prop) = R::PropType::from_str(prop) { if let Ok(valid_prop) = R::PropName::from_str(prop) {
let response = self.get_prop(prefix, valid_prop.clone())?; let response = self.get_prop(prefix, valid_prop.clone())?;
prop_responses.push(response); prop_responses.push(response);
} else { } else {