Some refactoring

This commit is contained in:
Lennart
2024-06-28 21:55:15 +02:00
parent 6130b1ac6a
commit 04ad124799
11 changed files with 215 additions and 209 deletions

View File

@@ -180,13 +180,11 @@ pub async fn route_report_calendar<A: CheckAuthentication, C: CalendarStore + ?S
let mut responses = Vec::new();
for event in events {
let path = format!("{}/{}", req.path(), event.get_uid());
responses.push(
EventFile {
path: format!("{}/{}", req.path(), event.get_uid()),
event,
}
.propfind(&prefix.0, props.clone())
.await?,
EventFile { event }
.propfind(&prefix.0, path, props.clone())
.await?,
);
}

View File

@@ -1,2 +1,3 @@
pub mod methods;
pub mod prop;
pub mod resource;

View File

@@ -0,0 +1,97 @@
use serde::{Deserialize, Serialize};
#[derive(Debug, Clone, Deserialize, Serialize)]
#[serde(rename_all = "kebab-case")]
pub struct SupportedCalendarComponent {
#[serde(rename = "@name")]
pub name: String,
}
#[derive(Debug, Clone, Deserialize, Serialize)]
#[serde(rename_all = "kebab-case")]
pub struct SupportedCalendarComponentSet {
#[serde(rename = "C:comp")]
pub comp: Vec<SupportedCalendarComponent>,
}
#[derive(Debug, Clone, Deserialize, Serialize)]
#[serde(rename_all = "kebab-case")]
pub struct CalendarData {
#[serde(rename = "@content-type")]
content_type: String,
#[serde(rename = "@version")]
version: String,
}
impl Default for CalendarData {
fn default() -> Self {
Self {
content_type: "text/calendar".to_owned(),
version: "2.0".to_owned(),
}
}
}
#[derive(Debug, Clone, Deserialize, Serialize, Default)]
#[serde(rename_all = "kebab-case")]
pub struct SupportedCalendarData {
#[serde(rename = "C:calendar-data", alias = "calendar-data")]
calendar_data: CalendarData,
}
#[derive(Debug, Clone, Deserialize, Serialize, Default)]
#[serde(rename_all = "kebab-case")]
pub struct Resourcetype {
#[serde(rename = "C:calendar", alias = "calendar")]
calendar: (),
collection: (),
}
#[derive(Debug, Clone, Deserialize, Serialize)]
#[serde(rename_all = "kebab-case")]
pub enum UserPrivilege {
Read,
ReadAcl,
Write,
WriteAcl,
WriteContent,
ReadCurrentUserPrivilegeSet,
Bind,
Unbind,
}
#[derive(Debug, Clone, Deserialize, Serialize)]
#[serde(rename_all = "kebab-case")]
pub struct UserPrivilegeWrapper {
#[serde(rename = "$value")]
privilege: UserPrivilege,
}
impl From<UserPrivilege> for UserPrivilegeWrapper {
fn from(value: UserPrivilege) -> Self {
Self { privilege: value }
}
}
#[derive(Debug, Clone, Deserialize, Serialize)]
#[serde(rename_all = "kebab-case")]
pub struct UserPrivilegeSet {
privilege: Vec<UserPrivilegeWrapper>,
}
impl Default for UserPrivilegeSet {
fn default() -> Self {
Self {
privilege: vec![
UserPrivilege::Read.into(),
UserPrivilege::ReadAcl.into(),
UserPrivilege::Write.into(),
UserPrivilege::WriteAcl.into(),
UserPrivilege::WriteContent.into(),
UserPrivilege::ReadCurrentUserPrivilegeSet.into(),
UserPrivilege::Bind.into(),
UserPrivilege::Unbind.into(),
],
}
}
}

View File

@@ -13,6 +13,11 @@ use std::sync::Arc;
use strum::{EnumString, VariantNames};
use tokio::sync::RwLock;
use super::prop::{
Resourcetype, SupportedCalendarComponent, SupportedCalendarComponentSet, SupportedCalendarData,
UserPrivilegeSet,
};
pub struct CalendarResource<C: CalendarStore + ?Sized> {
pub cal_store: Arc<RwLock<C>>,
pub path: String,
@@ -20,102 +25,6 @@ pub struct CalendarResource<C: CalendarStore + ?Sized> {
pub calendar_id: String,
}
#[derive(Debug, Clone, Deserialize, Serialize)]
#[serde(rename_all = "kebab-case")]
pub struct SupportedCalendarComponent {
#[serde(rename = "@name")]
pub name: String,
}
#[derive(Debug, Clone, Deserialize, Serialize)]
#[serde(rename_all = "kebab-case")]
pub struct SupportedCalendarComponentSet {
#[serde(rename = "C:comp")]
pub comp: Vec<SupportedCalendarComponent>,
}
#[derive(Debug, Clone, Deserialize, Serialize)]
#[serde(rename_all = "kebab-case")]
pub struct CalendarData {
#[serde(rename = "@content-type")]
content_type: String,
#[serde(rename = "@version")]
version: String,
}
impl Default for CalendarData {
fn default() -> Self {
Self {
content_type: "text/calendar".to_owned(),
version: "2.0".to_owned(),
}
}
}
#[derive(Debug, Clone, Deserialize, Serialize, Default)]
#[serde(rename_all = "kebab-case")]
pub struct SupportedCalendarData {
#[serde(rename = "C:calendar-data", alias = "calendar-data")]
calendar_data: CalendarData,
}
#[derive(Debug, Clone, Deserialize, Serialize, Default)]
#[serde(rename_all = "kebab-case")]
pub struct Resourcetype {
#[serde(rename = "C:calendar", alias = "calendar")]
calendar: (),
collection: (),
}
#[derive(Debug, Clone, Deserialize, Serialize)]
#[serde(rename_all = "kebab-case")]
pub enum UserPrivilege {
Read,
ReadAcl,
Write,
WriteAcl,
WriteContent,
ReadCurrentUserPrivilegeSet,
Bind,
Unbind,
}
#[derive(Debug, Clone, Deserialize, Serialize)]
#[serde(rename_all = "kebab-case")]
pub struct UserPrivilegeWrapper {
#[serde(rename = "$value")]
privilege: UserPrivilege,
}
impl From<UserPrivilege> for UserPrivilegeWrapper {
fn from(value: UserPrivilege) -> Self {
Self { privilege: value }
}
}
#[derive(Debug, Clone, Deserialize, Serialize)]
#[serde(rename_all = "kebab-case")]
pub struct UserPrivilegeSet {
privilege: Vec<UserPrivilegeWrapper>,
}
impl Default for UserPrivilegeSet {
fn default() -> Self {
Self {
privilege: vec![
UserPrivilege::Read.into(),
UserPrivilege::ReadAcl.into(),
UserPrivilege::Write.into(),
UserPrivilege::WriteAcl.into(),
UserPrivilege::WriteContent.into(),
UserPrivilege::ReadCurrentUserPrivilegeSet.into(),
UserPrivilege::Bind.into(),
UserPrivilege::Unbind.into(),
],
}
}
}
#[derive(EnumString, Debug, VariantNames, Clone)]
#[strum(serialize_all = "kebab-case")]
pub enum CalendarPropName {
@@ -176,7 +85,6 @@ impl InvalidProperty for CalendarProp {
pub struct CalendarFile {
pub calendar: Calendar,
pub principal: String,
pub path: String,
}
impl Resource for CalendarFile {
@@ -190,7 +98,7 @@ impl Resource for CalendarFile {
Ok(CalendarProp::Resourcetype(Resourcetype::default()))
}
CalendarPropName::CurrentUserPrincipal => Ok(CalendarProp::CurrentUserPrincipal(
HrefElement::new(format!("{}/{}/", prefix, self.principal)),
HrefElement::new(format!("{}/user/{}/", prefix, self.principal)),
)),
CalendarPropName::Owner => Ok(CalendarProp::Owner(HrefElement::new(format!(
"{}/{}/",
@@ -306,10 +214,6 @@ impl Resource for CalendarFile {
CalendarPropName::CurrentUserPrivilegeSet => Err(rustical_dav::Error::PropReadOnly),
}
}
fn get_path(&self) -> &str {
&self.path
}
}
#[async_trait(?Send)]
@@ -330,14 +234,13 @@ impl<C: CalendarStore + ?Sized> ResourceService for CalendarResource<C> {
Ok(CalendarFile {
calendar,
principal: self.principal.to_owned(),
path: self.path.to_owned(),
})
}
async fn get_members(
&self,
_auth_info: AuthInfo,
) -> Result<Vec<Self::MemberType>, Self::Error> {
) -> Result<Vec<(String, Self::MemberType)>, Self::Error> {
// As of now the calendar resource has no members since events are shown with REPORT
Ok(self
.cal_store
@@ -346,16 +249,18 @@ impl<C: CalendarStore + ?Sized> ResourceService for CalendarResource<C> {
.get_events(&self.principal, &self.calendar_id)
.await?
.into_iter()
.map(|event| EventFile {
path: format!("{}/{}", self.path, &event.get_uid()),
event,
.map(|event| {
(
format!("{}/{}", self.path, &event.get_uid()),
EventFile { event },
)
})
.collect())
}
async fn new(
req: HttpRequest,
auth_info: AuthInfo,
req: &HttpRequest,
auth_info: &AuthInfo,
path_components: Self::PathComponents,
) -> Result<Self, Self::Error> {
let cal_store = req
@@ -366,7 +271,7 @@ impl<C: CalendarStore + ?Sized> ResourceService for CalendarResource<C> {
Ok(Self {
path: req.path().to_owned(),
principal: auth_info.user_id,
principal: auth_info.user_id.to_owned(),
calendar_id: path_components.1,
cal_store,
})

View File

@@ -47,7 +47,6 @@ impl InvalidProperty for EventProp {
#[derive(Clone)]
pub struct EventFile {
pub event: Event,
pub path: String,
}
impl Resource for EventFile {
@@ -55,10 +54,6 @@ impl Resource for EventFile {
type Prop = EventProp;
type Error = Error;
fn get_path(&self) -> &str {
&self.path
}
fn get_prop(&self, _prefix: &str, prop: Self::PropName) -> Result<Self::Prop, Self::Error> {
match prop {
EventPropName::Getetag => Ok(EventProp::Getetag(self.event.get_etag())),
@@ -79,16 +74,9 @@ impl<C: CalendarStore + ?Sized> ResourceService for EventResource<C> {
type MemberType = EventFile;
type Error = Error;
async fn get_members(
&self,
_auth_info: AuthInfo,
) -> Result<Vec<Self::MemberType>, Self::Error> {
Ok(vec![])
}
async fn new(
req: HttpRequest,
_auth_info: AuthInfo,
req: &HttpRequest,
_auth_info: &AuthInfo,
path_components: Self::PathComponents,
) -> Result<Self, Self::Error> {
let (principal, cid, uid) = path_components;
@@ -115,10 +103,7 @@ impl<C: CalendarStore + ?Sized> ResourceService for EventResource<C> {
.await
.get_event(&self.principal, &self.cid, &self.uid)
.await?;
Ok(EventFile {
event,
path: self.path.to_owned(),
})
Ok(EventFile { event })
}
async fn save_file(&self, _file: Self::File) -> Result<(), Self::Error> {

View File

@@ -58,30 +58,57 @@ pub fn configure_dav<A: CheckAuthentication, C: CalendarStore + ?Sized>(
.route(proppatch_method().to(route_proppatch::<A, RootResource>)),
)
.service(
web::resource("/{principal}")
.route(propfind_method().to(route_propfind::<A, PrincipalResource<C>>))
.route(proppatch_method().to(route_proppatch::<A, PrincipalResource<C>>)),
)
.service(
web::resource("/{principal}/{calendar}")
.route(report_method().to(calendar::methods::report::route_report_calendar::<A, C>))
.route(propfind_method().to(route_propfind::<A, CalendarResource<C>>))
.route(proppatch_method().to(route_proppatch::<A, CalendarResource<C>>))
.route(
mkcalendar_method().to(calendar::methods::mkcalendar::route_mkcol_calendar::<A, C>),
)
.route(
web::method(Method::DELETE)
.to(calendar::methods::delete::route_delete_calendar::<A, C>),
),
)
.service(
web::resource("/{principal}/{calendar}/{event}")
.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::GET).to(event::methods::get_event::<A, C>))
.route(web::method(Method::PUT).to(event::methods::put_event::<A, C>)),
web::scope("/user").service(
web::scope("/{principal}")
.service(
web::resource("")
.route(propfind_method().to(route_propfind::<A, PrincipalResource<C>>))
.route(proppatch_method().to(route_proppatch::<A, PrincipalResource<C>>)),
)
.service(
web::scope("/{calendar}")
.service(
web::resource("")
.route(
report_method().to(
calendar::methods::report::route_report_calendar::<A, C>,
),
)
.route(
propfind_method().to(route_propfind::<A, CalendarResource<C>>),
)
.route(
proppatch_method()
.to(route_proppatch::<A, CalendarResource<C>>),
)
.route(mkcalendar_method().to(
calendar::methods::mkcalendar::route_mkcol_calendar::<A, C>,
))
.route(
web::method(Method::DELETE).to(
calendar::methods::delete::route_delete_calendar::<A, C>,
),
),
)
.service(
web::resource("/{event}")
.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::GET).to(event::methods::get_event::<A, C>),
)
.route(
web::method(Method::PUT).to(event::methods::put_event::<A, C>),
),
),
),
),
);
}

View File

@@ -23,7 +23,6 @@ pub struct PrincipalResource<C: CalendarStore + ?Sized> {
#[derive(Clone)]
pub struct PrincipalFile {
principal: String,
path: String,
}
#[derive(Deserialize, Serialize, Default, Debug)]
@@ -80,20 +79,16 @@ impl Resource for PrincipalFile {
HrefElement::new(format!("{}/{}/", prefix, self.principal)),
)),
PrincipalPropName::PrincipalUrl => Ok(PrincipalProp::PrincipalUrl(HrefElement::new(
format!("{}/{}/", prefix, self.principal),
format!("{}/user/{}/", prefix, self.principal),
))),
PrincipalPropName::CalendarHomeSet => Ok(PrincipalProp::CalendarHomeSet(
HrefElement::new(format!("{}/{}/", prefix, self.principal)),
HrefElement::new(format!("{}/user/{}/", prefix, self.principal)),
)),
PrincipalPropName::CalendarUserAddressSet => Ok(PrincipalProp::CalendarUserAddressSet(
HrefElement::new(format!("{}/{}/", prefix, self.principal)),
HrefElement::new(format!("{}/user/{}/", prefix, self.principal)),
)),
}
}
fn get_path(&self) -> &str {
&self.path
}
}
#[async_trait(?Send)]
@@ -104,8 +99,8 @@ impl<C: CalendarStore + ?Sized> ResourceService for PrincipalResource<C> {
type Error = Error;
async fn new(
req: HttpRequest,
auth_info: AuthInfo,
req: &HttpRequest,
auth_info: &AuthInfo,
(principal,): Self::PathComponents,
) -> Result<Self, Self::Error> {
if auth_info.user_id != principal {
@@ -127,14 +122,13 @@ impl<C: CalendarStore + ?Sized> ResourceService for PrincipalResource<C> {
async fn get_file(&self) -> Result<Self::File, Self::Error> {
Ok(PrincipalFile {
principal: self.principal.to_owned(),
path: self.path.to_owned(),
})
}
async fn get_members(
&self,
_auth_info: AuthInfo,
) -> Result<Vec<Self::MemberType>, Self::Error> {
) -> Result<Vec<(String, Self::MemberType)>, Self::Error> {
let calendars = self
.cal_store
.read()
@@ -143,10 +137,14 @@ impl<C: CalendarStore + ?Sized> ResourceService for PrincipalResource<C> {
.await?;
Ok(calendars
.into_iter()
.map(|cal| CalendarFile {
path: format!("{}/{}", &self.path, &cal.id),
calendar: cal,
principal: self.principal.to_owned(),
.map(|cal| {
(
format!("{}/{}", &self.path, &cal.id),
CalendarFile {
calendar: cal,
principal: self.principal.to_owned(),
},
)
})
.collect())
}

View File

@@ -9,13 +9,13 @@ use strum::{EnumString, VariantNames};
pub struct RootResource {
principal: String,
path: String,
}
#[derive(EnumString, Debug, VariantNames, Clone)]
#[strum(serialize_all = "kebab-case")]
pub enum RootPropName {
Resourcetype,
// Defined by RFC 5397
CurrentUserPrincipal,
}
@@ -43,7 +43,6 @@ impl InvalidProperty for RootProp {
#[derive(Clone)]
pub struct RootFile {
pub principal: String,
pub path: String,
}
impl Resource for RootFile {
@@ -55,14 +54,10 @@ impl Resource for RootFile {
match prop {
RootPropName::Resourcetype => Ok(RootProp::Resourcetype(Resourcetype::default())),
RootPropName::CurrentUserPrincipal => Ok(RootProp::CurrentUserPrincipal(
HrefElement::new(format!("{}/{}/", prefix, self.principal)),
HrefElement::new(format!("{}/user/{}/", prefix, self.principal)),
)),
}
}
fn get_path(&self) -> &str {
&self.path
}
}
#[async_trait(?Send)]
@@ -72,27 +67,18 @@ impl ResourceService for RootResource {
type File = RootFile;
type Error = Error;
async fn get_members(
&self,
_auth_info: AuthInfo,
) -> Result<Vec<Self::MemberType>, Self::Error> {
Ok(vec![])
}
async fn new(
req: HttpRequest,
auth_info: AuthInfo,
_req: &HttpRequest,
auth_info: &AuthInfo,
_path_components: Self::PathComponents,
) -> Result<Self, Self::Error> {
Ok(Self {
principal: auth_info.user_id,
path: req.path().to_string(),
principal: auth_info.user_id.to_owned(),
})
}
async fn get_file(&self) -> Result<Self::File, Self::Error> {
Ok(RootFile {
path: self.path.to_owned(),
principal: self.principal.to_owned(),
})
}

View File

@@ -38,7 +38,7 @@ struct PropfindElement {
}
pub async fn route_propfind<A: CheckAuthentication, R: ResourceService + ?Sized>(
path: Path<R::PathComponents>,
path_components: Path<R::PathComponents>,
body: String,
req: HttpRequest,
prefix: Data<ServicePrefix>,
@@ -48,9 +48,10 @@ pub async fn route_propfind<A: CheckAuthentication, R: ResourceService + ?Sized>
debug!("{body}");
let auth_info = auth.inner;
let prefix = prefix.0.to_owned();
let path_components = path.into_inner();
let path_components = path_components.into_inner();
let path = req.path().to_owned();
let resource_service = R::new(req, auth_info.clone(), path_components.clone()).await?;
let resource_service = R::new(&req, &auth_info, path_components.clone()).await?;
// A request body is optional. If empty we MUST return all props
let propfind: PropfindElement = if !body.is_empty() {
@@ -75,13 +76,13 @@ pub async fn route_propfind<A: CheckAuthentication, R: ResourceService + ?Sized>
let mut member_responses = Vec::new();
if depth != Depth::Zero {
for member in resource_service.get_members(auth_info).await? {
member_responses.push(member.propfind(&prefix, props.clone()).await?);
for (path, member) in resource_service.get_members(auth_info).await? {
member_responses.push(member.propfind(&prefix, path, props.clone()).await?);
}
}
let resource = resource_service.get_file().await?;
let response = resource.propfind(&prefix, props).await?;
let response = resource.propfind(&prefix, path, props).await?;
Ok(MultistatusElement {
responses: vec![response],

View File

@@ -59,7 +59,7 @@ pub async fn route_proppatch<A: CheckAuthentication, R: ResourceService + ?Sized
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?;
let resource_service = R::new(&req, &auth_info, path_components.clone()).await?;
debug!("{body}");

View File

@@ -21,8 +21,6 @@ pub trait Resource: Clone {
fn get_prop(&self, prefix: &str, prop: Self::PropName) -> Result<Self::Prop, Self::Error>;
fn get_path(&self) -> &str;
fn set_prop(&mut self, _prop: Self::Prop) -> Result<(), crate::Error> {
Err(crate::Error::PropReadOnly)
}
@@ -48,14 +46,19 @@ pub trait ResourceService: Sized {
type Error: ResponseError + From<crate::Error> + From<anyhow::Error>;
async fn new(
req: HttpRequest,
auth_info: AuthInfo,
req: &HttpRequest,
auth_info: &AuthInfo,
path_components: Self::PathComponents,
) -> Result<Self, 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<(String, Self::MemberType)>, Self::Error> {
Ok(vec![])
}
async fn save_file(&self, file: Self::File) -> Result<(), Self::Error>;
}
@@ -99,8 +102,12 @@ pub enum PropstatType<T1: Serialize, T2: Serialize> {
pub trait HandlePropfind {
type Error: ResponseError + From<crate::Error> + From<anyhow::Error>;
async fn propfind(&self, prefix: &str, props: Vec<&str>)
-> Result<impl Serialize, Self::Error>;
async fn propfind(
&self,
prefix: &str,
path: String,
props: Vec<&str>,
) -> Result<impl Serialize, Self::Error>;
}
#[async_trait(?Send)]
@@ -110,6 +117,7 @@ impl<R: Resource> HandlePropfind for R {
async fn propfind(
&self,
prefix: &str,
path: String,
props: Vec<&str>,
) -> Result<PropstatResponseElement<PropWrapper<Vec<R::Prop>>, TagList>, R::Error> {
let mut props = props;
@@ -125,7 +133,7 @@ impl<R: Resource> HandlePropfind for R {
.map(|&prop| prop.to_string())
.collect();
return Ok(PropstatResponseElement {
href: self.get_path().to_owned(),
href: path,
propstat: vec![PropstatType::Normal(PropstatElement {
prop: PropWrapper::TagList(TagList::from(props)),
status: format!("HTTP/1.1 {}", StatusCode::OK),
@@ -177,7 +185,7 @@ impl<R: Resource> HandlePropfind for R {
}));
}
Ok(PropstatResponseElement {
href: self.get_path().to_owned(),
href: path,
propstat: propstats,
})
}