Massive refactoring how DAV resources and routes work

This commit is contained in:
Lennart
2024-10-03 23:02:13 +02:00
parent 9c8c05eaca
commit a47d056df0
15 changed files with 218 additions and 162 deletions

1
Cargo.lock generated
View File

@@ -1965,6 +1965,7 @@ dependencies = [
"strum", "strum",
"thiserror", "thiserror",
"tokio", "tokio",
"url",
] ]
[[package]] [[package]]

View File

@@ -24,3 +24,4 @@ async-trait = "0.1"
thiserror = "1.0" thiserror = "1.0"
strum = { version = "0.26", features = ["strum_macros", "derive"] } strum = { version = "0.26", features = ["strum_macros", "derive"] }
derive_more = { version = "1.0", features = ["from", "into"] } derive_more = { version = "1.0", features = ["from", "into"] }
url = "2.5.2"

View File

@@ -8,7 +8,7 @@ use actix_web::{
}; };
use rustical_dav::{ use rustical_dav::{
methods::propfind::{PropElement, PropfindType}, methods::propfind::{PropElement, PropfindType},
resource::HandlePropfind, resource::Resource,
xml::{multistatus::PropstatWrapper, MultistatusElement}, xml::{multistatus::PropstatWrapper, MultistatusElement},
}; };
use rustical_store::{model::object::CalendarObject, CalendarStore}; use rustical_store::{model::object::CalendarObject, CalendarStore};
@@ -88,7 +88,7 @@ pub async fn handle_calendar_multiget<C: CalendarStore + ?Sized>(
let path = format!("{}/{}", req.path(), object.get_uid()); let path = format!("{}/{}", req.path(), object.get_uid());
responses.push( responses.push(
CalendarObjectResource::from(object) CalendarObjectResource::from(object)
.propfind(prefix, &path, props.clone()) .propfind(&path, props.clone(), req.resource_map())
.await?, .await?,
); );
} }

View File

@@ -1,7 +1,7 @@
use actix_web::HttpRequest; use actix_web::HttpRequest;
use rustical_dav::{ use rustical_dav::{
methods::propfind::{PropElement, PropfindType}, methods::propfind::{PropElement, PropfindType},
resource::HandlePropfind, resource::Resource,
xml::{multistatus::PropstatWrapper, MultistatusElement}, xml::{multistatus::PropstatWrapper, MultistatusElement},
}; };
use rustical_store::{model::object::CalendarObject, CalendarStore}; use rustical_store::{model::object::CalendarObject, CalendarStore};
@@ -176,7 +176,6 @@ pub async fn get_objects_calendar_query<C: CalendarStore + ?Sized>(
pub async fn handle_calendar_query<C: CalendarStore + ?Sized>( pub async fn handle_calendar_query<C: CalendarStore + ?Sized>(
cal_query: CalendarQueryRequest, cal_query: CalendarQueryRequest,
req: HttpRequest, req: HttpRequest,
prefix: &str,
principal: &str, principal: &str,
cid: &str, cid: &str,
cal_store: &RwLock<C>, cal_store: &RwLock<C>,
@@ -197,10 +196,14 @@ pub async fn handle_calendar_query<C: CalendarStore + ?Sized>(
let mut responses = Vec::new(); let mut responses = Vec::new();
for object in objects { for object in objects {
let path = format!("{}/{}", req.path(), object.get_uid()); let path = CalendarObjectResource::get_url(
req.resource_map(),
vec![principal, cid, object.get_uid()],
)
.unwrap();
responses.push( responses.push(
CalendarObjectResource::from(object) CalendarObjectResource::from(object)
.propfind(prefix, &path, props.clone()) .propfind(&path, props.clone(), req.resource_map())
.await?, .await?,
); );
} }

View File

@@ -51,22 +51,14 @@ pub async fn route_report_calendar<C: CalendarStore + ?Sized>(
Ok(match request.clone() { Ok(match request.clone() {
ReportRequest::CalendarQuery(cal_query) => { ReportRequest::CalendarQuery(cal_query) => {
handle_calendar_query(cal_query, req, &prefix, &principal, &cid, &cal_store).await? handle_calendar_query(cal_query, req, &principal, &cid, &cal_store).await?
} }
ReportRequest::CalendarMultiget(cal_multiget) => { ReportRequest::CalendarMultiget(cal_multiget) => {
handle_calendar_multiget(cal_multiget, req, &prefix, &principal, &cid, &cal_store) handle_calendar_multiget(cal_multiget, req, &prefix, &principal, &cid, &cal_store)
.await? .await?
} }
ReportRequest::SyncCollection(sync_collection) => { ReportRequest::SyncCollection(sync_collection) => {
handle_sync_collection( handle_sync_collection(sync_collection, req, &principal, &cid, &cal_store).await?
sync_collection,
req,
&prefix.0,
&principal,
&cid,
&cal_store,
)
.await?
} }
}) })
} }

View File

@@ -1,7 +1,7 @@
use actix_web::{http::StatusCode, HttpRequest}; use actix_web::{http::StatusCode, HttpRequest};
use rustical_dav::{ use rustical_dav::{
methods::propfind::{PropElement, PropfindType}, methods::propfind::{PropElement, PropfindType},
resource::HandlePropfind, resource::Resource,
xml::{ xml::{
multistatus::{PropstatWrapper, ResponseElement}, multistatus::{PropstatWrapper, ResponseElement},
MultistatusElement, MultistatusElement,
@@ -45,7 +45,6 @@ pub struct SyncCollectionRequest {
pub async fn handle_sync_collection<C: CalendarStore + ?Sized>( pub async fn handle_sync_collection<C: CalendarStore + ?Sized>(
sync_collection: SyncCollectionRequest, sync_collection: SyncCollectionRequest,
req: HttpRequest, req: HttpRequest,
prefix: &str,
principal: &str, principal: &str,
cid: &str, cid: &str,
cal_store: &RwLock<C>, cal_store: &RwLock<C>,
@@ -71,16 +70,22 @@ pub async fn handle_sync_collection<C: CalendarStore + ?Sized>(
let mut responses = Vec::new(); let mut responses = Vec::new();
for object in new_objects { for object in new_objects {
let path = format!("{}/{}", req.path(), object.get_uid()); let path = CalendarObjectResource::get_url(
req.resource_map(),
vec![principal, cid, &object.get_uid()],
)
.unwrap();
responses.push( responses.push(
CalendarObjectResource::from(object) CalendarObjectResource::from(object)
.propfind(prefix, &path, props.clone()) .propfind(&path, props.clone(), req.resource_map())
.await?, .await?,
); );
} }
for object_uid in deleted_objects { for object_uid in deleted_objects {
let path = format!("{}/{}", req.path(), object_uid); let path =
CalendarObjectResource::get_url(req.resource_map(), vec![principal, cid, &object_uid])
.unwrap();
responses.push(ResponseElement { responses.push(ResponseElement {
href: path, href: path,
status: Some(format!("HTTP/1.1 {}", StatusCode::NOT_FOUND)), status: Some(format!("HTTP/1.1 {}", StatusCode::NOT_FOUND)),

View File

@@ -1,5 +1,11 @@
use super::prop::{
Resourcetype, SupportedCalendarComponent, SupportedCalendarComponentSet, SupportedCalendarData,
SupportedReportSet, UserPrivilegeSet,
};
use crate::calendar_object::resource::CalendarObjectResource; use crate::calendar_object::resource::CalendarObjectResource;
use crate::principal::PrincipalResource;
use crate::Error; use crate::Error;
use actix_web::dev::ResourceMap;
use actix_web::{web::Data, HttpRequest}; use actix_web::{web::Data, HttpRequest};
use async_trait::async_trait; use async_trait::async_trait;
use derive_more::derive::{From, Into}; use derive_more::derive::{From, Into};
@@ -12,11 +18,6 @@ use std::sync::Arc;
use strum::{EnumString, VariantNames}; use strum::{EnumString, VariantNames};
use tokio::sync::RwLock; use tokio::sync::RwLock;
use super::prop::{
Resourcetype, SupportedCalendarComponent, SupportedCalendarComponentSet, SupportedCalendarData,
SupportedReportSet, UserPrivilegeSet,
};
pub struct CalendarResourceService<C: CalendarStore + ?Sized> { pub struct CalendarResourceService<C: CalendarStore + ?Sized> {
pub cal_store: Arc<RwLock<C>>, pub cal_store: Arc<RwLock<C>>,
pub path: String, pub path: String,
@@ -94,16 +95,21 @@ impl Resource for CalendarResource {
type Prop = CalendarProp; type Prop = CalendarProp;
type Error = Error; type Error = Error;
fn get_prop(&self, prefix: &str, prop: Self::PropName) -> Result<Self::Prop, Self::Error> { fn get_prop(
&self,
rmap: &ResourceMap,
prop: Self::PropName,
) -> Result<Self::Prop, Self::Error> {
Ok(match prop { Ok(match prop {
CalendarPropName::Resourcetype => CalendarProp::Resourcetype(Resourcetype::default()), CalendarPropName::Resourcetype => CalendarProp::Resourcetype(Resourcetype::default()),
CalendarPropName::CurrentUserPrincipal => CalendarProp::CurrentUserPrincipal( CalendarPropName::CurrentUserPrincipal => {
HrefElement::new(format!("{}/user/{}/", prefix, self.0.principal)), CalendarProp::CurrentUserPrincipal(HrefElement::new(
), PrincipalResource::get_url(rmap, vec![&self.0.principal]).unwrap(),
CalendarPropName::Owner => CalendarProp::Owner(HrefElement::new(format!( ))
"{}/user/{}/", }
prefix, self.0.principal CalendarPropName::Owner => CalendarProp::Owner(HrefElement::new(
))), PrincipalResource::get_url(rmap, vec![&self.0.principal]).unwrap(),
)),
CalendarPropName::Displayname => CalendarProp::Displayname(self.0.displayname.clone()), CalendarPropName::Displayname => CalendarProp::Displayname(self.0.displayname.clone()),
CalendarPropName::CalendarColor => CalendarProp::CalendarColor(self.0.color.clone()), CalendarPropName::CalendarColor => CalendarProp::CalendarColor(self.0.color.clone()),
CalendarPropName::CalendarDescription => { CalendarPropName::CalendarDescription => {
@@ -219,6 +225,11 @@ impl Resource for CalendarResource {
CalendarPropName::Getctag => Err(rustical_dav::Error::PropReadOnly), CalendarPropName::Getctag => Err(rustical_dav::Error::PropReadOnly),
} }
} }
#[inline]
fn resource_name() -> &'static str {
"caldav_calendar"
}
} }
#[async_trait(?Send)] #[async_trait(?Send)]
@@ -242,8 +253,10 @@ impl<C: CalendarStore + ?Sized> ResourceService for CalendarResourceService<C> {
Ok(calendar.into()) Ok(calendar.into())
} }
async fn get_members(&self) -> Result<Vec<(String, Self::MemberType)>, Self::Error> { async fn get_members(
// As of now the calendar resource has no members since events are shown with REPORT &self,
rmap: &ResourceMap,
) -> Result<Vec<(String, Self::MemberType)>, Self::Error> {
Ok(self Ok(self
.cal_store .cal_store
.read() .read()
@@ -251,7 +264,16 @@ impl<C: CalendarStore + ?Sized> ResourceService for CalendarResourceService<C> {
.get_objects(&self.principal, &self.calendar_id) .get_objects(&self.principal, &self.calendar_id)
.await? .await?
.into_iter() .into_iter()
.map(|event| (format!("{}/{}", self.path, &event.get_uid()), event.into())) .map(|object| {
(
CalendarObjectResource::get_url(
rmap,
vec![&self.principal, &self.calendar_id, object.get_uid()],
)
.unwrap(),
object.into(),
)
})
.collect()) .collect())
} }

View File

@@ -1,5 +1,5 @@
use crate::Error; use crate::Error;
use actix_web::{web::Data, HttpRequest}; use actix_web::{dev::ResourceMap, web::Data, HttpRequest};
use async_trait::async_trait; use async_trait::async_trait;
use derive_more::derive::{From, Into}; use derive_more::derive::{From, Into};
use rustical_dav::resource::{InvalidProperty, Resource, ResourceService}; use rustical_dav::resource::{InvalidProperty, Resource, ResourceService};
@@ -51,7 +51,11 @@ impl Resource for CalendarObjectResource {
type Prop = CalendarObjectProp; type Prop = CalendarObjectProp;
type Error = Error; type Error = Error;
fn get_prop(&self, _prefix: &str, prop: Self::PropName) -> Result<Self::Prop, Self::Error> { fn get_prop(
&self,
_rmap: &ResourceMap,
prop: Self::PropName,
) -> Result<Self::Prop, Self::Error> {
Ok(match prop { Ok(match prop {
CalendarObjectPropName::Getetag => CalendarObjectProp::Getetag(self.0.get_etag()), CalendarObjectPropName::Getetag => CalendarObjectProp::Getetag(self.0.get_etag()),
CalendarObjectPropName::CalendarData => { CalendarObjectPropName::CalendarData => {
@@ -62,6 +66,11 @@ impl Resource for CalendarObjectResource {
} }
}) })
} }
#[inline]
fn resource_name() -> &'static str {
"caldav_calendar_object"
}
} }
#[async_trait(?Send)] #[async_trait(?Send)]

View File

@@ -5,9 +5,8 @@ use calendar::resource::CalendarResourceService;
use calendar_object::resource::CalendarObjectResourceService; use calendar_object::resource::CalendarObjectResourceService;
use principal::PrincipalResourceService; use principal::PrincipalResourceService;
use root::RootResourceService; use root::RootResourceService;
use rustical_dav::methods::{ use rustical_dav::methods::{propfind::ServicePrefix, route_delete};
propfind::ServicePrefix, route_delete, route_propfind, route_proppatch, use rustical_dav::resource::ResourceService;
};
use rustical_store::auth::{AuthenticationMiddleware, AuthenticationProvider}; use rustical_store::auth::{AuthenticationMiddleware, AuthenticationProvider};
use rustical_store::CalendarStore; use rustical_store::CalendarStore;
use std::str::FromStr; use std::str::FromStr;
@@ -36,8 +35,6 @@ pub fn configure_dav<AP: AuthenticationProvider, C: CalendarStore + ?Sized>(
auth_provider: Arc<AP>, auth_provider: Arc<AP>,
store: Arc<RwLock<C>>, store: Arc<RwLock<C>>,
) { ) {
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());
@@ -55,40 +52,18 @@ pub fn configure_dav<AP: AuthenticationProvider, C: CalendarStore + ?Sized>(
.guard(guard::Method(Method::OPTIONS)) .guard(guard::Method(Method::OPTIONS))
.to(options_handler), .to(options_handler),
) )
.service( .service(RootResourceService::actix_resource())
web::resource("")
.route(propfind_method().to(route_propfind::<RootResourceService>))
.route(proppatch_method().to(route_proppatch::<RootResourceService>)),
)
.service( .service(
web::scope("/user").service( web::scope("/user").service(
web::scope("/{principal}") web::scope("/{principal}")
.service( .service(PrincipalResourceService::<C>::actix_resource())
web::resource("")
.route(
propfind_method()
.to(route_propfind::<PrincipalResourceService<C>>),
)
.route(
proppatch_method()
.to(route_proppatch::<PrincipalResourceService<C>>),
),
)
.service( .service(
web::scope("/{calendar}") web::scope("/{calendar}")
.service( .service(
web::resource("") CalendarResourceService::<C>::actix_resource()
.route(report_method().to( .route(report_method().to(
calendar::methods::report::route_report_calendar::<C>, calendar::methods::report::route_report_calendar::<C>,
)) ))
.route(
propfind_method()
.to(route_propfind::<CalendarResourceService<C>>),
)
.route(
proppatch_method()
.to(route_proppatch::<CalendarResourceService<C>>),
)
.route( .route(
web::method(Method::DELETE) web::method(Method::DELETE)
.to(route_delete::<CalendarResourceService<C>>), .to(route_delete::<CalendarResourceService<C>>),
@@ -98,28 +73,20 @@ pub fn configure_dav<AP: AuthenticationProvider, C: CalendarStore + ?Sized>(
)), )),
) )
.service( .service(
web::resource("/{event}") web::scope("/{object}").service(
.route( CalendarObjectResourceService::<C>::actix_resource()
propfind_method().to(route_propfind::< .route(web::method(Method::DELETE).to(route_delete::<
CalendarObjectResourceService<C>, CalendarObjectResourceService<C>,
>), >))
) .route(
.route(proppatch_method().to(route_proppatch::< web::method(Method::GET)
CalendarObjectResourceService<C>, .to(calendar_object::methods::get_event::<C>),
>)) )
.route( .route(
web::method(Method::DELETE).to(route_delete::< web::method(Method::PUT)
CalendarObjectResourceService<C>, .to(calendar_object::methods::put_event::<C>),
>), ),
) ),
.route(
web::method(Method::GET)
.to(calendar_object::methods::get_event::<C>),
)
.route(
web::method(Method::PUT)
.to(calendar_object::methods::put_event::<C>),
),
), ),
), ),
), ),

View File

@@ -1,4 +1,5 @@
use crate::Error; use crate::Error;
use actix_web::dev::ResourceMap;
use actix_web::web::Data; use actix_web::web::Data;
use actix_web::HttpRequest; use actix_web::HttpRequest;
use async_trait::async_trait; use async_trait::async_trait;
@@ -14,7 +15,6 @@ use crate::calendar::resource::CalendarResource;
pub struct PrincipalResourceService<C: CalendarStore + ?Sized> { pub struct PrincipalResourceService<C: CalendarStore + ?Sized> {
principal: String, principal: String,
path: String,
cal_store: Arc<RwLock<C>>, cal_store: Arc<RwLock<C>>,
} }
@@ -67,8 +67,13 @@ impl Resource for PrincipalResource {
type Prop = PrincipalProp; type Prop = PrincipalProp;
type Error = Error; type Error = Error;
fn get_prop(&self, prefix: &str, prop: Self::PropName) -> Result<Self::Prop, Self::Error> { fn get_prop(
let principal_href = HrefElement::new(format!("{}/user/{}/", prefix, self.principal)); &self,
rmap: &ResourceMap,
prop: Self::PropName,
) -> Result<Self::Prop, Self::Error> {
let principal_href = HrefElement::new(Self::get_url(rmap, vec![&self.principal]).unwrap());
Ok(match prop { Ok(match prop {
PrincipalPropName::Resourcetype => PrincipalProp::Resourcetype(Resourcetype::default()), PrincipalPropName::Resourcetype => PrincipalProp::Resourcetype(Resourcetype::default()),
PrincipalPropName::CurrentUserPrincipal => { PrincipalPropName::CurrentUserPrincipal => {
@@ -81,6 +86,11 @@ impl Resource for PrincipalResource {
} }
}) })
} }
#[inline]
fn resource_name() -> &'static str {
"caldav_principal"
}
} }
#[async_trait(?Send)] #[async_trait(?Send)]
@@ -102,7 +112,6 @@ impl<C: CalendarStore + ?Sized> ResourceService for PrincipalResourceService<C>
Ok(Self { Ok(Self {
cal_store, cal_store,
path: req.path().to_owned(),
principal, principal,
}) })
} }
@@ -116,7 +125,10 @@ impl<C: CalendarStore + ?Sized> ResourceService for PrincipalResourceService<C>
}) })
} }
async fn get_members(&self) -> Result<Vec<(String, Self::MemberType)>, Self::Error> { async fn get_members(
&self,
rmap: &ResourceMap,
) -> Result<Vec<(String, Self::MemberType)>, Self::Error> {
let calendars = self let calendars = self
.cal_store .cal_store
.read() .read()
@@ -125,7 +137,12 @@ impl<C: CalendarStore + ?Sized> ResourceService for PrincipalResourceService<C>
.await?; .await?;
Ok(calendars Ok(calendars
.into_iter() .into_iter()
.map(|cal| (format!("{}/{}", &self.path, &cal.id), cal.into())) .map(|cal| {
(
CalendarResource::get_url(rmap, vec![&self.principal, &cal.id]).unwrap(),
cal.into(),
)
})
.collect()) .collect())
} }

View File

@@ -1,4 +1,6 @@
use crate::principal::PrincipalResource;
use crate::Error; use crate::Error;
use actix_web::dev::ResourceMap;
use actix_web::HttpRequest; use actix_web::HttpRequest;
use async_trait::async_trait; use async_trait::async_trait;
use rustical_dav::resource::{InvalidProperty, Resource, ResourceService}; use rustical_dav::resource::{InvalidProperty, Resource, ResourceService};
@@ -47,14 +49,23 @@ impl Resource for RootResource {
type Prop = RootProp; type Prop = RootProp;
type Error = Error; type Error = Error;
fn get_prop(&self, prefix: &str, prop: Self::PropName) -> Result<Self::Prop, Self::Error> { fn get_prop(
&self,
rmap: &ResourceMap,
prop: Self::PropName,
) -> Result<Self::Prop, Self::Error> {
Ok(match prop { Ok(match prop {
RootPropName::Resourcetype => RootProp::Resourcetype(Resourcetype::default()), RootPropName::Resourcetype => RootProp::Resourcetype(Resourcetype::default()),
RootPropName::CurrentUserPrincipal => RootProp::CurrentUserPrincipal(HrefElement::new( RootPropName::CurrentUserPrincipal => RootProp::CurrentUserPrincipal(HrefElement::new(
format!("{}/user/{}/", prefix, self.principal), PrincipalResource::get_url(rmap, vec![&self.principal]).unwrap(),
)), )),
}) })
} }
#[inline]
fn resource_name() -> &'static str {
"caldav_root"
}
} }
#[async_trait(?Send)] #[async_trait(?Send)]

View File

@@ -1,12 +1,11 @@
use crate::depth_extractor::Depth; use crate::depth_extractor::Depth;
use crate::resource::HandlePropfind;
use crate::resource::Resource; use crate::resource::Resource;
use crate::resource::ResourceService; use crate::resource::ResourceService;
use crate::xml::multistatus::PropstatWrapper; use crate::xml::multistatus::PropstatWrapper;
use crate::xml::MultistatusElement; use crate::xml::MultistatusElement;
use crate::xml::TagList; use crate::xml::TagList;
use crate::Error; use crate::Error;
use actix_web::web::{Data, Path}; use actix_web::web::Path;
use actix_web::HttpRequest; use actix_web::HttpRequest;
use derive_more::derive::Deref; use derive_more::derive::Deref;
use log::debug; use log::debug;
@@ -43,7 +42,6 @@ pub async fn route_propfind<R: ResourceService>(
path_components: Path<R::PathComponents>, path_components: Path<R::PathComponents>,
body: String, body: String,
req: HttpRequest, req: HttpRequest,
prefix: Data<ServicePrefix>,
user: User, user: User,
depth: Depth, depth: Depth,
) -> Result< ) -> Result<
@@ -54,7 +52,6 @@ pub async fn route_propfind<R: ResourceService>(
R::Error, R::Error,
> { > {
debug!("{body}"); debug!("{body}");
let prefix = prefix.into_inner();
let resource_service = R::new(&req, path_components.into_inner()).await?; let resource_service = R::new(&req, path_components.into_inner()).await?;
@@ -81,13 +78,19 @@ pub async fn route_propfind<R: ResourceService>(
let mut member_responses = Vec::new(); let mut member_responses = Vec::new();
if depth != Depth::Zero { if depth != Depth::Zero {
for (path, member) in resource_service.get_members().await? { for (path, member) in resource_service.get_members(req.resource_map()).await? {
member_responses.push(member.propfind(&prefix, &path, props.clone()).await?); member_responses.push(
member
.propfind(&path, props.clone(), req.resource_map())
.await?,
);
} }
} }
let resource = resource_service.get_resource(user.id).await?; let resource = resource_service.get_resource(user.id).await?;
let response = resource.propfind(&prefix, req.path(), props).await?; let response = resource
.propfind(req.path(), props, req.resource_map())
.await?;
Ok(MultistatusElement { Ok(MultistatusElement {
responses: vec![response], responses: vec![response],

View File

@@ -1,6 +1,12 @@
use crate::methods::{route_propfind, route_proppatch};
use crate::xml::multistatus::{PropTagWrapper, PropstatElement, PropstatWrapper}; use crate::xml::multistatus::{PropTagWrapper, PropstatElement, PropstatWrapper};
use crate::xml::{multistatus::ResponseElement, TagList}; use crate::xml::{multistatus::ResponseElement, TagList};
use crate::Error; use crate::Error;
use actix_web::dev::ResourceMap;
use actix_web::error::UrlGenerationError;
use actix_web::http::Method;
use actix_web::test::TestRequest;
use actix_web::web;
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 core::fmt;
@@ -18,7 +24,8 @@ pub trait Resource: Clone {
Self::PropName::VARIANTS Self::PropName::VARIANTS
} }
fn get_prop(&self, prefix: &str, prop: Self::PropName) -> Result<Self::Prop, Self::Error>; fn get_prop(&self, rmap: &ResourceMap, prop: Self::PropName)
-> Result<Self::Prop, Self::Error>;
fn set_prop(&mut self, _prop: Self::Prop) -> Result<(), crate::Error> { fn set_prop(&mut self, _prop: Self::Prop) -> Result<(), crate::Error> {
Err(crate::Error::PropReadOnly) Err(crate::Error::PropReadOnly)
@@ -27,61 +34,31 @@ pub trait Resource: Clone {
fn remove_prop(&mut self, _prop: Self::PropName) -> Result<(), crate::Error> { fn remove_prop(&mut self, _prop: Self::PropName) -> Result<(), crate::Error> {
Err(crate::Error::PropReadOnly) Err(crate::Error::PropReadOnly)
} }
}
pub trait InvalidProperty { fn resource_name() -> &'static str;
fn invalid_property(&self) -> bool;
}
// A resource is identified by a URI and has properties fn get_url<U, I>(rmap: &ResourceMap, elements: U) -> Result<String, UrlGenerationError>
// A resource can also be a collection where
// A resource cannot be none, only Methods like PROPFIND, GET, REPORT, etc. can be exposed U: IntoIterator<Item = I>,
// A resource exists I: AsRef<str>,
#[async_trait(?Send)] {
pub trait ResourceService: Sized { Ok(rmap
type MemberType: Resource<Error = Self::Error>; .url_for(
type PathComponents: Sized + Clone; // defines how the resource URI maps to parameters, i.e. /{principal}/{calendar} -> (String, String) &TestRequest::default().to_http_request(),
type Resource: Resource<Error = Self::Error>; Self::resource_name(),
type Error: ResponseError + From<crate::Error> + From<anyhow::Error>; elements,
)?
async fn new( .path()
req: &HttpRequest, .to_owned())
path_components: Self::PathComponents,
) -> Result<Self, Self::Error>;
async fn get_members(&self) -> Result<Vec<(String, Self::MemberType)>, Self::Error> {
Ok(vec![])
} }
async fn get_resource(&self, principal: String) -> Result<Self::Resource, Self::Error>; #[allow(async_fn_in_trait)]
async fn save_resource(&self, file: Self::Resource) -> Result<(), Self::Error>;
async fn delete_resource(&self, _use_trashbin: bool) -> Result<(), Self::Error> {
Err(crate::Error::Unauthorized.into())
}
}
#[async_trait(?Send)]
pub trait HandlePropfind {
type Error: ResponseError + From<crate::Error> + From<anyhow::Error>;
async fn propfind( async fn propfind(
&self, &self,
prefix: &str,
path: &str,
props: Vec<&str>,
) -> Result<impl Serialize, Self::Error>;
}
#[async_trait(?Send)]
impl<R: Resource> HandlePropfind for R {
type Error = R::Error;
async fn propfind(
&self,
prefix: &str,
path: &str, path: &str,
mut props: Vec<&str>, mut props: Vec<&str>,
) -> Result<ResponseElement<PropstatWrapper<R::Prop>>, R::Error> { rmap: &ResourceMap,
) -> Result<ResponseElement<PropstatWrapper<Self::Prop>>, Self::Error> {
if props.contains(&"propname") { if props.contains(&"propname") {
if props.len() != 1 { if props.len() != 1 {
// propname MUST be the only queried prop per spec // propname MUST be the only queried prop per spec
@@ -89,7 +66,7 @@ impl<R: Resource> HandlePropfind for R {
Error::BadRequest("propname MUST be the only queried prop".to_owned()).into(), Error::BadRequest("propname MUST be the only queried prop".to_owned()).into(),
); );
} }
let props: Vec<String> = R::list_props() let props: Vec<String> = Self::list_props()
.iter() .iter()
.map(|&prop| prop.to_string()) .map(|&prop| prop.to_string())
.collect(); .collect();
@@ -109,26 +86,26 @@ impl<R: Resource> HandlePropfind for R {
Error::BadRequest("allprop MUST be the only queried prop".to_owned()).into(), Error::BadRequest("allprop MUST be the only queried prop".to_owned()).into(),
); );
} }
props = R::list_props().into(); props = Self::list_props().into();
} }
let (valid_props, invalid_props): (Vec<Option<R::PropName>>, Vec<Option<&str>>) = props let (valid_props, invalid_props): (Vec<Option<Self::PropName>>, Vec<Option<&str>>) = props
.into_iter() .into_iter()
.map(|prop| { .map(|prop| {
if let Ok(valid_prop) = R::PropName::from_str(prop) { if let Ok(valid_prop) = Self::PropName::from_str(prop) {
(Some(valid_prop), None) (Some(valid_prop), None)
} else { } else {
(None, Some(prop)) (None, Some(prop))
} }
}) })
.unzip(); .unzip();
let valid_props: Vec<R::PropName> = valid_props.into_iter().flatten().collect(); let valid_props: Vec<Self::PropName> = valid_props.into_iter().flatten().collect();
let invalid_props: Vec<&str> = invalid_props.into_iter().flatten().collect(); let invalid_props: Vec<&str> = invalid_props.into_iter().flatten().collect();
let prop_responses = valid_props let prop_responses = valid_props
.into_iter() .into_iter()
.map(|prop| self.get_prop(prefix, prop)) .map(|prop| self.get_prop(rmap, prop))
.collect::<Result<Vec<R::Prop>, R::Error>>()?; .collect::<Result<Vec<Self::Prop>, Self::Error>>()?;
let mut propstats = vec![PropstatWrapper::Normal(PropstatElement { let mut propstats = vec![PropstatWrapper::Normal(PropstatElement {
status: format!("HTTP/1.1 {}", StatusCode::OK), status: format!("HTTP/1.1 {}", StatusCode::OK),
@@ -153,3 +130,51 @@ impl<R: Resource> HandlePropfind for R {
}) })
} }
} }
pub trait InvalidProperty {
fn invalid_property(&self) -> bool;
}
// 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 ResourceService: Sized + 'static {
type MemberType: Resource<Error = Self::Error>;
type PathComponents: for<'de> Deserialize<'de> + Sized + Clone + 'static; // defines how the resource URI maps to parameters, i.e. /{principal}/{calendar} -> (String, String)
type Resource: Resource<Error = Self::Error>;
type Error: ResponseError + From<crate::Error> + From<anyhow::Error>;
async fn new(
req: &HttpRequest,
path_components: Self::PathComponents,
) -> Result<Self, Self::Error>;
async fn get_members(
&self,
_rmap: &ResourceMap,
) -> Result<Vec<(String, Self::MemberType)>, Self::Error> {
Ok(vec![])
}
async fn get_resource(&self, principal: String) -> Result<Self::Resource, Self::Error>;
async fn save_resource(&self, file: Self::Resource) -> Result<(), Self::Error>;
async fn delete_resource(&self, _use_trashbin: bool) -> Result<(), Self::Error> {
Err(crate::Error::Unauthorized.into())
}
fn resource_name() -> &'static str {
Self::Resource::resource_name()
}
fn actix_resource() -> actix_web::Resource {
let propfind_method = || web::method(Method::from_str("PROPFIND").unwrap());
let proppatch_method = || web::method(Method::from_str("PROPPATCH").unwrap());
web::resource("")
.name(Self::resource_name())
.route(propfind_method().to(route_propfind::<Self>))
.route(proppatch_method().to(route_proppatch::<Self>))
}
}

View File

@@ -1,7 +1,6 @@
use super::AuthenticationProvider; use super::AuthenticationProvider;
use actix_web::{ use actix_web::{
dev::{forward_ready, Service, ServiceRequest, ServiceResponse, Transform}, dev::{forward_ready, Service, ServiceRequest, ServiceResponse, Transform},
error::ErrorUnauthorized,
http::header::Header, http::header::Header,
HttpMessage, HttpMessage,
}; };

View File

@@ -42,7 +42,8 @@ pub fn make_app<CS: CalendarStore + ?Sized>(
// }), // }),
) )
.service( .service(
web::scope("/frontend").configure(|cfg| configure_frontend(cfg, cal_store.clone())), web::scope("/frontend")
.configure(|cfg| configure_frontend(cfg, auth_provider.clone(), cal_store.clone())),
) )
.service(web::redirect("/", "/frontend").permanent()) .service(web::redirect("/", "/frontend").permanent())
} }