Refactoring around routing and getting the principal uri (less dependence on actix)

This commit is contained in:
Lennart K
2025-06-02 16:17:13 +02:00
parent 0f294cf2e1
commit ef33868151
23 changed files with 169 additions and 216 deletions

View File

@@ -4,12 +4,11 @@ use crate::{
calendar_object::resource::{CalendarObjectPropWrapper, CalendarObjectResource}, calendar_object::resource::{CalendarObjectPropWrapper, CalendarObjectResource},
}; };
use actix_web::{ use actix_web::{
HttpRequest,
dev::{Path, ResourceDef}, dev::{Path, ResourceDef},
http::StatusCode, http::StatusCode,
}; };
use rustical_dav::{ use rustical_dav::{
resource::Resource, resource::{PrincipalUri, Resource},
xml::{MultistatusElement, PropfindType, multistatus::ResponseElement}, xml::{MultistatusElement, PropfindType, multistatus::ResponseElement},
}; };
use rustical_store::{CalendarObject, CalendarStore, auth::User}; use rustical_store::{CalendarObject, CalendarStore, auth::User};
@@ -58,25 +57,25 @@ pub async fn get_objects_calendar_multiget<C: CalendarStore>(
pub async fn handle_calendar_multiget<C: CalendarStore>( pub async fn handle_calendar_multiget<C: CalendarStore>(
cal_multiget: &CalendarMultigetRequest, cal_multiget: &CalendarMultigetRequest,
props: &[&str], props: &[&str],
req: HttpRequest, path: &str,
puri: &impl PrincipalUri,
user: &User, user: &User,
principal: &str, principal: &str,
cal_id: &str, cal_id: &str,
cal_store: &C, cal_store: &C,
) -> Result<MultistatusElement<CalendarObjectPropWrapper, String>, Error> { ) -> Result<MultistatusElement<CalendarObjectPropWrapper, String>, Error> {
let (objects, not_found) = let (objects, not_found) =
get_objects_calendar_multiget(cal_multiget, req.path(), principal, cal_id, cal_store) get_objects_calendar_multiget(cal_multiget, path, principal, cal_id, cal_store).await?;
.await?;
let mut responses = Vec::new(); let mut responses = Vec::new();
for object in objects { for object in objects {
let path = format!("{}/{}.ics", req.path(), object.get_id()); let path = format!("{}/{}.ics", path, object.get_id());
responses.push( responses.push(
CalendarObjectResource { CalendarObjectResource {
object, object,
principal: principal.to_owned(), principal: principal.to_owned(),
} }
.propfind(&path, props, user, req.resource_map())?, .propfind(&path, props, puri, user)?,
); );
} }

View File

@@ -1,6 +1,5 @@
use actix_web::HttpRequest;
use rustical_dav::{ use rustical_dav::{
resource::Resource, resource::{PrincipalUri, Resource},
xml::{MultistatusElement, PropfindType}, xml::{MultistatusElement, PropfindType},
}; };
use rustical_ical::UtcDateTime; use rustical_ical::UtcDateTime;
@@ -217,7 +216,8 @@ pub async fn get_objects_calendar_query<C: CalendarStore>(
pub async fn handle_calendar_query<C: CalendarStore>( pub async fn handle_calendar_query<C: CalendarStore>(
cal_query: &CalendarQueryRequest, cal_query: &CalendarQueryRequest,
props: &[&str], props: &[&str],
req: HttpRequest, path: &str,
puri: &impl PrincipalUri,
user: &User, user: &User,
principal: &str, principal: &str,
cal_id: &str, cal_id: &str,
@@ -227,17 +227,13 @@ pub async fn handle_calendar_query<C: CalendarStore>(
let mut responses = Vec::new(); let mut responses = Vec::new();
for object in objects { for object in objects {
let path = format!( let path = format!("{}/{}.ics", path, object.get_id());
"{}/{}.ics",
req.path().trim_end_matches('/'),
object.get_id()
);
responses.push( responses.push(
CalendarObjectResource { CalendarObjectResource {
object, object,
principal: principal.to_owned(), principal: principal.to_owned(),
} }
.propfind(&path, props, user, req.resource_map())?, .propfind(&path, props, puri, user)?,
); );
} }

View File

@@ -1,4 +1,4 @@
use crate::Error; use crate::{CalDavPrincipalUri, Error};
use actix_web::{ use actix_web::{
HttpRequest, Responder, HttpRequest, Responder,
web::{Data, Path}, web::{Data, Path},
@@ -87,6 +87,7 @@ pub async fn route_report_calendar<C: CalendarStore>(
body: String, body: String,
user: User, user: User,
req: HttpRequest, req: HttpRequest,
puri: Data<CalDavPrincipalUri>,
cal_store: Data<C>, cal_store: Data<C>,
) -> Result<impl Responder, Error> { ) -> Result<impl Responder, Error> {
let (principal, cal_id) = path.into_inner(); let (principal, cal_id) = path.into_inner();
@@ -102,7 +103,8 @@ pub async fn route_report_calendar<C: CalendarStore>(
handle_calendar_query( handle_calendar_query(
cal_query, cal_query,
&props, &props,
req, req.path(),
puri.as_ref(),
&user, &user,
&principal, &principal,
&cal_id, &cal_id,
@@ -114,7 +116,8 @@ pub async fn route_report_calendar<C: CalendarStore>(
handle_calendar_multiget( handle_calendar_multiget(
cal_multiget, cal_multiget,
&props, &props,
req, req.path(),
puri.as_ref(),
&user, &user,
&principal, &principal,
&cal_id, &cal_id,
@@ -126,7 +129,8 @@ pub async fn route_report_calendar<C: CalendarStore>(
handle_sync_collection( handle_sync_collection(
sync_collection, sync_collection,
&props, &props,
req, req.path(),
puri.as_ref(),
&user, &user,
&principal, &principal,
&cal_id, &cal_id,

View File

@@ -3,9 +3,9 @@ use crate::{
Error, Error,
calendar_object::resource::{CalendarObjectPropWrapper, CalendarObjectResource}, calendar_object::resource::{CalendarObjectPropWrapper, CalendarObjectResource},
}; };
use actix_web::{HttpRequest, http::StatusCode}; use actix_web::http::StatusCode;
use rustical_dav::{ use rustical_dav::{
resource::Resource, resource::{PrincipalUri, Resource},
xml::{ xml::{
MultistatusElement, multistatus::ResponseElement, sync_collection::SyncCollectionRequest, MultistatusElement, multistatus::ResponseElement, sync_collection::SyncCollectionRequest,
}, },
@@ -19,7 +19,8 @@ use rustical_store::{
pub async fn handle_sync_collection<C: CalendarStore>( pub async fn handle_sync_collection<C: CalendarStore>(
sync_collection: &SyncCollectionRequest<ReportPropName>, sync_collection: &SyncCollectionRequest<ReportPropName>,
props: &[&str], props: &[&str],
req: HttpRequest, path: &str,
puri: &impl PrincipalUri,
user: &User, user: &User,
principal: &str, principal: &str,
cal_id: &str, cal_id: &str,
@@ -32,22 +33,18 @@ pub async fn handle_sync_collection<C: CalendarStore>(
let mut responses = Vec::new(); let mut responses = Vec::new();
for object in new_objects { for object in new_objects {
let path = format!( let path = format!("{}/{}.ics", path, object.get_id());
"{}/{}.ics",
req.path().trim_end_matches('/'),
object.get_id()
);
responses.push( responses.push(
CalendarObjectResource { CalendarObjectResource {
object, object,
principal: principal.to_owned(), principal: principal.to_owned(),
} }
.propfind(&path, props, user, req.resource_map())?, .propfind(&path, props, puri, user)?,
); );
} }
for object_id in deleted_objects { for object_id in deleted_objects {
let path = format!("{}/{}.ics", req.path().trim_end_matches('/'), object_id); let path = format!("{path}/{object_id}.ics");
responses.push(ResponseElement { responses.push(ResponseElement {
href: path, href: path,
status: Some(StatusCode::NOT_FOUND), status: Some(StatusCode::NOT_FOUND),

View File

@@ -2,10 +2,8 @@ use super::methods::mkcalendar::route_mkcalendar;
use super::methods::post::route_post; use super::methods::post::route_post;
use super::methods::report::route_report_calendar; use super::methods::report::route_report_calendar;
use super::prop::{SupportedCalendarComponentSet, SupportedCalendarData, SupportedReportSet}; use super::prop::{SupportedCalendarComponentSet, SupportedCalendarData, SupportedReportSet};
use crate::Error;
use crate::calendar_object::resource::CalendarObjectResource; use crate::calendar_object::resource::CalendarObjectResource;
use crate::principal::PrincipalResource; use crate::{CalDavPrincipalUri, Error};
use actix_web::dev::ResourceMap;
use actix_web::http::Method; use actix_web::http::Method;
use actix_web::web; use actix_web::web;
use async_trait::async_trait; use async_trait::async_trait;
@@ -15,7 +13,7 @@ use rustical_dav::extensions::{
CommonPropertiesExtension, CommonPropertiesProp, SyncTokenExtension, SyncTokenExtensionProp, CommonPropertiesExtension, CommonPropertiesProp, SyncTokenExtension, SyncTokenExtensionProp,
}; };
use rustical_dav::privileges::UserPrivilegeSet; use rustical_dav::privileges::UserPrivilegeSet;
use rustical_dav::resource::{Resource, ResourceService}; use rustical_dav::resource::{PrincipalUri, Resource, ResourceService};
use rustical_dav::xml::{HrefElement, Resourcetype, ResourcetypeInner}; use rustical_dav::xml::{HrefElement, Resourcetype, ResourcetypeInner};
use rustical_dav_push::{DavPushExtension, DavPushExtensionProp}; use rustical_dav_push::{DavPushExtension, DavPushExtensionProp};
use rustical_ical::CalDateTime; use rustical_ical::CalDateTime;
@@ -100,10 +98,6 @@ impl DavPushExtension for CalendarResource {
} }
} }
impl CommonPropertiesExtension for CalendarResource {
type PrincipalResource = PrincipalResource;
}
impl Resource for CalendarResource { impl Resource for CalendarResource {
type Prop = CalendarPropWrapper; type Prop = CalendarPropWrapper;
type Error = Error; type Error = Error;
@@ -128,7 +122,7 @@ impl Resource for CalendarResource {
fn get_prop( fn get_prop(
&self, &self,
rmap: &ResourceMap, puri: &impl PrincipalUri,
user: &User, user: &User,
prop: &CalendarPropWrapperName, prop: &CalendarPropWrapperName,
) -> Result<Self::Prop, Self::Error> { ) -> Result<Self::Prop, Self::Error> {
@@ -183,7 +177,7 @@ impl Resource for CalendarResource {
CalendarPropWrapper::DavPush(DavPushExtension::get_prop(self, prop)?) CalendarPropWrapper::DavPush(DavPushExtension::get_prop(self, prop)?)
} }
CalendarPropWrapperName::Common(prop) => CalendarPropWrapper::Common( CalendarPropWrapperName::Common(prop) => CalendarPropWrapper::Common(
CommonPropertiesExtension::get_prop(self, rmap, user, prop)?, CommonPropertiesExtension::get_prop(self, puri, user, prop)?,
), ),
}) })
} }
@@ -336,6 +330,7 @@ impl<C: CalendarStore, S: SubscriptionStore> ResourceService for CalendarResourc
type Resource = CalendarResource; type Resource = CalendarResource;
type Error = Error; type Error = Error;
type Principal = User; type Principal = User;
type PrincipalUri = CalDavPrincipalUri;
async fn get_resource( async fn get_resource(
&self, &self,

View File

@@ -1,12 +1,11 @@
use super::methods::{get_event, put_event}; use super::methods::{get_event, put_event};
use crate::{Error, principal::PrincipalResource}; use crate::{CalDavPrincipalUri, Error};
use actix_web::dev::ResourceMap;
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::{ use rustical_dav::{
extensions::{CommonPropertiesExtension, CommonPropertiesProp}, extensions::{CommonPropertiesExtension, CommonPropertiesProp},
privileges::UserPrivilegeSet, privileges::UserPrivilegeSet,
resource::{Resource, ResourceService}, resource::{PrincipalUri, Resource, ResourceService},
xml::Resourcetype, xml::Resourcetype,
}; };
use rustical_store::{CalendarObject, CalendarStore, auth::User}; use rustical_store::{CalendarObject, CalendarStore, auth::User};
@@ -51,10 +50,6 @@ pub struct CalendarObjectResource {
pub principal: String, pub principal: String,
} }
impl CommonPropertiesExtension for CalendarObjectResource {
type PrincipalResource = PrincipalResource;
}
impl Resource for CalendarObjectResource { impl Resource for CalendarObjectResource {
type Prop = CalendarObjectPropWrapper; type Prop = CalendarObjectPropWrapper;
type Error = Error; type Error = Error;
@@ -66,7 +61,7 @@ impl Resource for CalendarObjectResource {
fn get_prop( fn get_prop(
&self, &self,
rmap: &ResourceMap, puri: &impl PrincipalUri,
user: &User, user: &User,
prop: &CalendarObjectPropWrapperName, prop: &CalendarObjectPropWrapperName,
) -> Result<Self::Prop, Self::Error> { ) -> Result<Self::Prop, Self::Error> {
@@ -85,7 +80,7 @@ impl Resource for CalendarObjectResource {
}) })
} }
CalendarObjectPropWrapperName::Common(prop) => CalendarObjectPropWrapper::Common( CalendarObjectPropWrapperName::Common(prop) => CalendarObjectPropWrapper::Common(
CommonPropertiesExtension::get_prop(self, rmap, user, prop)?, CommonPropertiesExtension::get_prop(self, puri, user, prop)?,
), ),
}) })
} }
@@ -119,6 +114,7 @@ impl<C: CalendarStore> ResourceService for CalendarObjectResourceService<C> {
type MemberType = CalendarObjectResource; type MemberType = CalendarObjectResource;
type Error = Error; type Error = Error;
type Principal = User; type Principal = User;
type PrincipalUri = CalDavPrincipalUri;
async fn get_resource( async fn get_resource(
&self, &self,

View File

@@ -1,11 +1,9 @@
use crate::Error;
use crate::calendar::resource::CalendarResource; use crate::calendar::resource::CalendarResource;
use crate::principal::PrincipalResource; use crate::{CalDavPrincipalUri, Error};
use actix_web::dev::ResourceMap;
use async_trait::async_trait; use async_trait::async_trait;
use rustical_dav::extensions::{CommonPropertiesExtension, CommonPropertiesProp}; use rustical_dav::extensions::{CommonPropertiesExtension, CommonPropertiesProp};
use rustical_dav::privileges::UserPrivilegeSet; use rustical_dav::privileges::UserPrivilegeSet;
use rustical_dav::resource::{Resource, ResourceService}; use rustical_dav::resource::{PrincipalUri, Resource, ResourceService};
use rustical_dav::xml::{Resourcetype, ResourcetypeInner}; use rustical_dav::xml::{Resourcetype, ResourcetypeInner};
use rustical_store::CalendarStore; use rustical_store::CalendarStore;
use rustical_store::auth::User; use rustical_store::auth::User;
@@ -24,10 +22,6 @@ pub enum PrincipalPropWrapper {
Common(CommonPropertiesProp), Common(CommonPropertiesProp),
} }
impl CommonPropertiesExtension for CalendarSetResource {
type PrincipalResource = PrincipalResource;
}
impl Resource for CalendarSetResource { impl Resource for CalendarSetResource {
type Prop = PrincipalPropWrapper; type Prop = PrincipalPropWrapper;
type Error = Error; type Error = Error;
@@ -42,13 +36,13 @@ impl Resource for CalendarSetResource {
fn get_prop( fn get_prop(
&self, &self,
rmap: &ResourceMap, puri: &impl PrincipalUri,
user: &User, user: &User,
prop: &PrincipalPropWrapperName, prop: &PrincipalPropWrapperName,
) -> Result<Self::Prop, Self::Error> { ) -> Result<Self::Prop, Self::Error> {
Ok(match prop { Ok(match prop {
PrincipalPropWrapperName::Common(prop) => PrincipalPropWrapper::Common( PrincipalPropWrapperName::Common(prop) => PrincipalPropWrapper::Common(
<Self as CommonPropertiesExtension>::get_prop(self, rmap, user, prop)?, <Self as CommonPropertiesExtension>::get_prop(self, puri, user, prop)?,
), ),
}) })
} }
@@ -83,6 +77,7 @@ impl<C: CalendarStore> ResourceService for CalendarSetResourceService<C> {
type Resource = CalendarSetResource; type Resource = CalendarSetResource;
type Error = Error; type Error = Error;
type Principal = User; type Principal = User;
type PrincipalUri = CalDavPrincipalUri;
async fn get_resource( async fn get_resource(
&self, &self,

View File

@@ -8,8 +8,9 @@ use actix_web::web::{self, Data};
use calendar::resource::CalendarResourceService; use calendar::resource::CalendarResourceService;
use calendar_object::resource::CalendarObjectResourceService; use calendar_object::resource::CalendarObjectResourceService;
use calendar_set::CalendarSetResourceService; use calendar_set::CalendarSetResourceService;
use derive_more::Constructor;
use principal::{PrincipalResource, PrincipalResourceService}; use principal::{PrincipalResource, PrincipalResourceService};
use rustical_dav::resource::{NamedRoute, ResourceService, ResourceServiceRoute}; use rustical_dav::resource::{PrincipalUri, ResourceService, ResourceServiceRoute};
use rustical_dav::resources::RootResourceService; use rustical_dav::resources::RootResourceService;
use rustical_store::auth::{AuthenticationMiddleware, AuthenticationProvider, User}; use rustical_store::auth::{AuthenticationMiddleware, AuthenticationProvider, User};
use rustical_store::{AddressbookStore, CalendarStore, ContactBirthdayStore, SubscriptionStore}; use rustical_store::{AddressbookStore, CalendarStore, ContactBirthdayStore, SubscriptionStore};
@@ -25,6 +26,15 @@ mod subscription;
pub use error::Error; pub use error::Error;
#[derive(Debug, Clone, Constructor)]
pub struct CalDavPrincipalUri(&'static str);
impl PrincipalUri for CalDavPrincipalUri {
fn principal_uri(&self, principal: &str) -> String {
format!("{}/{}", self.0, principal)
}
}
/// Quite a janky implementation but the default METHOD_NOT_ALLOWED response gives us the allowed /// Quite a janky implementation but the default METHOD_NOT_ALLOWED response gives us the allowed
/// methods of a resource /// methods of a resource
fn options_handler() -> ErrorHandlers<BoxBody> { fn options_handler() -> ErrorHandlers<BoxBody> {
@@ -57,6 +67,7 @@ pub fn caldav_service<
C: CalendarStore, C: CalendarStore,
S: SubscriptionStore, S: SubscriptionStore,
>( >(
prefix: &'static str,
auth_provider: Arc<AP>, auth_provider: Arc<AP>,
store: Arc<C>, store: Arc<C>,
addr_store: Arc<AS>, addr_store: Arc<AS>,
@@ -70,7 +81,13 @@ pub fn caldav_service<
.app_data(Data::from(store.clone())) .app_data(Data::from(store.clone()))
.app_data(Data::from(birthday_store.clone())) .app_data(Data::from(birthday_store.clone()))
.app_data(Data::from(subscription_store)) .app_data(Data::from(subscription_store))
.service(RootResourceService::<PrincipalResource, User>::default().actix_resource()) .app_data(Data::new(CalDavPrincipalUri::new(
format!("{prefix}/principal").leak(),
)))
.service(
RootResourceService::<PrincipalResource, User, CalDavPrincipalUri>::default()
.actix_resource(),
)
.service( .service(
web::scope("/principal").service( web::scope("/principal").service(
web::scope("/{principal}") web::scope("/{principal}")
@@ -79,8 +96,7 @@ pub fn caldav_service<
auth_provider, auth_provider,
home_set: &[("calendar", false), ("birthdays", true)], home_set: &[("calendar", false), ("birthdays", true)],
} }
.actix_resource() .actix_resource(),
.name(PrincipalResource::route_name()),
) )
.service( .service(
web::scope("/calendar") web::scope("/calendar")

View File

@@ -1,16 +1,14 @@
use std::sync::Arc;
use crate::Error;
use crate::calendar_set::CalendarSetResource; use crate::calendar_set::CalendarSetResource;
use actix_web::dev::ResourceMap; use crate::{CalDavPrincipalUri, Error};
use async_trait::async_trait; use async_trait::async_trait;
use rustical_dav::extensions::{CommonPropertiesExtension, CommonPropertiesProp}; use rustical_dav::extensions::{CommonPropertiesExtension, CommonPropertiesProp};
use rustical_dav::privileges::UserPrivilegeSet; use rustical_dav::privileges::UserPrivilegeSet;
use rustical_dav::resource::{NamedRoute, Resource, ResourceService}; use rustical_dav::resource::{PrincipalUri, Resource, ResourceService};
use rustical_dav::xml::{HrefElement, Resourcetype, ResourcetypeInner}; use rustical_dav::xml::{HrefElement, Resourcetype, ResourcetypeInner};
use rustical_store::auth::user::PrincipalType; use rustical_store::auth::user::PrincipalType;
use rustical_store::auth::{AuthenticationProvider, User}; use rustical_store::auth::{AuthenticationProvider, User};
use rustical_xml::{EnumUnitVariants, EnumVariants, XmlDeserialize, XmlSerialize}; use rustical_xml::{EnumUnitVariants, EnumVariants, XmlDeserialize, XmlSerialize};
use std::sync::Arc;
#[derive(Clone)] #[derive(Clone)]
pub struct PrincipalResource { pub struct PrincipalResource {
@@ -49,22 +47,6 @@ pub enum PrincipalPropWrapper {
Common(CommonPropertiesProp), Common(CommonPropertiesProp),
} }
impl PrincipalResource {
pub fn get_principal_url(rmap: &ResourceMap, principal: &str) -> String {
Self::get_url(rmap, vec![principal]).unwrap()
}
}
impl NamedRoute for PrincipalResource {
fn route_name() -> &'static str {
"caldav_principal"
}
}
impl CommonPropertiesExtension for PrincipalResource {
type PrincipalResource = Self;
}
impl Resource for PrincipalResource { impl Resource for PrincipalResource {
type Prop = PrincipalPropWrapper; type Prop = PrincipalPropWrapper;
type Error = Error; type Error = Error;
@@ -79,16 +61,16 @@ impl Resource for PrincipalResource {
fn get_prop( fn get_prop(
&self, &self,
rmap: &ResourceMap, puri: &impl PrincipalUri,
user: &User, user: &User,
prop: &PrincipalPropWrapperName, prop: &PrincipalPropWrapperName,
) -> Result<Self::Prop, Self::Error> { ) -> Result<Self::Prop, Self::Error> {
let principal_url = Self::get_url(rmap, vec![&self.principal.id]).unwrap(); let principal_url = puri.principal_uri(&self.principal.id);
let home_set = CalendarHomeSet( let home_set = CalendarHomeSet(
user.memberships() user.memberships()
.into_iter() .into_iter()
.map(|principal| Self::get_url(rmap, vec![principal]).unwrap()) .map(|principal| puri.principal_uri(principal))
.flat_map(|principal_url| { .flat_map(|principal_url| {
self.home_set.iter().map(move |&(home_name, _read_only)| { self.home_set.iter().map(move |&(home_name, _read_only)| {
HrefElement::new(format!("{}/{}", &principal_url, home_name)) HrefElement::new(format!("{}/{}", &principal_url, home_name))
@@ -119,7 +101,7 @@ impl Resource for PrincipalResource {
}) })
} }
PrincipalPropWrapperName::Common(prop) => PrincipalPropWrapper::Common( PrincipalPropWrapperName::Common(prop) => PrincipalPropWrapper::Common(
<Self as CommonPropertiesExtension>::get_prop(self, rmap, user, prop)?, <Self as CommonPropertiesExtension>::get_prop(self, puri, user, prop)?,
), ),
}) })
} }
@@ -147,6 +129,7 @@ impl<AP: AuthenticationProvider> ResourceService for PrincipalResourceService<AP
type Resource = PrincipalResource; type Resource = PrincipalResource;
type Error = Error; type Error = Error;
type Principal = User; type Principal = User;
type PrincipalUri = CalDavPrincipalUri;
async fn get_resource( async fn get_resource(
&self, &self,

View File

@@ -1,11 +1,10 @@
use crate::{Error, principal::PrincipalResource}; use crate::{CardDavPrincipalUri, Error};
use actix_web::dev::ResourceMap;
use async_trait::async_trait; use async_trait::async_trait;
use derive_more::derive::{Constructor, From, Into}; use derive_more::derive::{Constructor, From, Into};
use rustical_dav::{ use rustical_dav::{
extensions::{CommonPropertiesExtension, CommonPropertiesProp}, extensions::{CommonPropertiesExtension, CommonPropertiesProp},
privileges::UserPrivilegeSet, privileges::UserPrivilegeSet,
resource::{Resource, ResourceService}, resource::{PrincipalUri, Resource, ResourceService},
xml::Resourcetype, xml::Resourcetype,
}; };
use rustical_store::{AddressObject, AddressbookStore, auth::User}; use rustical_store::{AddressObject, AddressbookStore, auth::User};
@@ -47,10 +46,6 @@ pub struct AddressObjectResource {
pub principal: String, pub principal: String,
} }
impl CommonPropertiesExtension for AddressObjectResource {
type PrincipalResource = PrincipalResource;
}
impl Resource for AddressObjectResource { impl Resource for AddressObjectResource {
type Prop = AddressObjectPropWrapper; type Prop = AddressObjectPropWrapper;
type Error = Error; type Error = Error;
@@ -62,7 +57,7 @@ impl Resource for AddressObjectResource {
fn get_prop( fn get_prop(
&self, &self,
rmap: &ResourceMap, puri: &impl PrincipalUri,
user: &User, user: &User,
prop: &AddressObjectPropWrapperName, prop: &AddressObjectPropWrapperName,
) -> Result<Self::Prop, Self::Error> { ) -> Result<Self::Prop, Self::Error> {
@@ -81,7 +76,7 @@ impl Resource for AddressObjectResource {
}) })
} }
AddressObjectPropWrapperName::Common(prop) => AddressObjectPropWrapper::Common( AddressObjectPropWrapperName::Common(prop) => AddressObjectPropWrapper::Common(
CommonPropertiesExtension::get_prop(self, rmap, user, prop)?, CommonPropertiesExtension::get_prop(self, puri, user, prop)?,
), ),
}) })
} }
@@ -115,6 +110,7 @@ impl<AS: AddressbookStore> ResourceService for AddressObjectResourceService<AS>
type MemberType = AddressObjectResource; type MemberType = AddressObjectResource;
type Error = Error; type Error = Error;
type Principal = User; type Principal = User;
type PrincipalUri = CardDavPrincipalUri;
async fn get_resource( async fn get_resource(
&self, &self,

View File

@@ -3,12 +3,11 @@ use crate::{
address_object::resource::{AddressObjectPropWrapper, AddressObjectResource}, address_object::resource::{AddressObjectPropWrapper, AddressObjectResource},
}; };
use actix_web::{ use actix_web::{
HttpRequest,
dev::{Path, ResourceDef}, dev::{Path, ResourceDef},
http::StatusCode, http::StatusCode,
}; };
use rustical_dav::{ use rustical_dav::{
resource::Resource, resource::{PrincipalUri, Resource},
xml::{MultistatusElement, PropfindType, multistatus::ResponseElement}, xml::{MultistatusElement, PropfindType, multistatus::ResponseElement},
}; };
use rustical_store::{AddressObject, AddressbookStore, auth::User}; use rustical_store::{AddressObject, AddressbookStore, auth::User};
@@ -60,25 +59,26 @@ pub async fn get_objects_addressbook_multiget<AS: AddressbookStore>(
pub async fn handle_addressbook_multiget<AS: AddressbookStore>( pub async fn handle_addressbook_multiget<AS: AddressbookStore>(
addr_multiget: &AddressbookMultigetRequest, addr_multiget: &AddressbookMultigetRequest,
props: &[&str], props: &[&str],
req: HttpRequest, path: &str,
puri: &impl PrincipalUri,
user: &User, user: &User,
principal: &str, principal: &str,
cal_id: &str, cal_id: &str,
addr_store: &AS, addr_store: &AS,
) -> Result<MultistatusElement<AddressObjectPropWrapper, String>, Error> { ) -> Result<MultistatusElement<AddressObjectPropWrapper, String>, Error> {
let (objects, not_found) = let (objects, not_found) =
get_objects_addressbook_multiget(addr_multiget, req.path(), principal, cal_id, addr_store) get_objects_addressbook_multiget(addr_multiget, path, principal, cal_id, addr_store)
.await?; .await?;
let mut responses = Vec::new(); let mut responses = Vec::new();
for object in objects { for object in objects {
let path = format!("{}/{}.vcf", req.path(), object.get_id()); let path = format!("{}/{}.vcf", path, object.get_id());
responses.push( responses.push(
AddressObjectResource { AddressObjectResource {
object, object,
principal: principal.to_owned(), principal: principal.to_owned(),
} }
.propfind(&path, props, user, req.resource_map())?, .propfind(&path, props, puri, user)?,
); );
} }

View File

@@ -1,4 +1,4 @@
use crate::Error; use crate::{CardDavPrincipalUri, Error};
use actix_web::{ use actix_web::{
HttpRequest, Responder, HttpRequest, Responder,
web::{Data, Path}, web::{Data, Path},
@@ -49,6 +49,7 @@ pub async fn route_report_addressbook<AS: AddressbookStore>(
body: String, body: String,
user: User, user: User,
req: HttpRequest, req: HttpRequest,
puri: Data<CardDavPrincipalUri>,
addr_store: Data<AS>, addr_store: Data<AS>,
) -> Result<impl Responder, Error> { ) -> Result<impl Responder, Error> {
let (principal, addressbook_id) = path.into_inner(); let (principal, addressbook_id) = path.into_inner();
@@ -64,7 +65,8 @@ pub async fn route_report_addressbook<AS: AddressbookStore>(
handle_addressbook_multiget( handle_addressbook_multiget(
addr_multiget, addr_multiget,
&props, &props,
req, req.path(),
puri.as_ref(),
&user, &user,
&principal, &principal,
&addressbook_id, &addressbook_id,
@@ -76,7 +78,8 @@ pub async fn route_report_addressbook<AS: AddressbookStore>(
handle_sync_collection( handle_sync_collection(
sync_collection, sync_collection,
&props, &props,
req, req.path(),
puri.as_ref(),
&user, &user,
&principal, &principal,
&addressbook_id, &addressbook_id,

View File

@@ -2,9 +2,9 @@ use crate::{
Error, Error,
address_object::resource::{AddressObjectPropWrapper, AddressObjectResource}, address_object::resource::{AddressObjectPropWrapper, AddressObjectResource},
}; };
use actix_web::{HttpRequest, http::StatusCode}; use actix_web::http::StatusCode;
use rustical_dav::{ use rustical_dav::{
resource::Resource, resource::{PrincipalUri, Resource},
xml::{ xml::{
MultistatusElement, multistatus::ResponseElement, sync_collection::SyncCollectionRequest, MultistatusElement, multistatus::ResponseElement, sync_collection::SyncCollectionRequest,
}, },
@@ -18,7 +18,8 @@ use rustical_store::{
pub async fn handle_sync_collection<AS: AddressbookStore>( pub async fn handle_sync_collection<AS: AddressbookStore>(
sync_collection: &SyncCollectionRequest, sync_collection: &SyncCollectionRequest,
props: &[&str], props: &[&str],
req: HttpRequest, path: &str,
puri: &impl PrincipalUri,
user: &User, user: &User,
principal: &str, principal: &str,
addressbook_id: &str, addressbook_id: &str,
@@ -31,22 +32,18 @@ pub async fn handle_sync_collection<AS: AddressbookStore>(
let mut responses = Vec::new(); let mut responses = Vec::new();
for object in new_objects { for object in new_objects {
let path = format!( let path = format!("{}/{}.vcf", path.trim_end_matches('/'), object.get_id());
"{}/{}.vcf",
req.path().trim_end_matches('/'),
object.get_id()
);
responses.push( responses.push(
AddressObjectResource { AddressObjectResource {
object, object,
principal: principal.to_owned(), principal: principal.to_owned(),
} }
.propfind(&path, props, user, req.resource_map())?, .propfind(&path, props, puri, user)?,
); );
} }
for object_id in deleted_objects { for object_id in deleted_objects {
let path = format!("{}/{}.vcf", req.path().trim_end_matches('/'), object_id); let path = format!("{}/{}.vcf", path.trim_end_matches('/'), object_id);
responses.push(ResponseElement { responses.push(ResponseElement {
href: path, href: path,
status: Some(StatusCode::NOT_FOUND), status: Some(StatusCode::NOT_FOUND),

View File

@@ -2,10 +2,8 @@ use super::methods::mkcol::route_mkcol;
use super::methods::post::route_post; use super::methods::post::route_post;
use super::methods::report::route_report_addressbook; use super::methods::report::route_report_addressbook;
use super::prop::{SupportedAddressData, SupportedReportSet}; use super::prop::{SupportedAddressData, SupportedReportSet};
use crate::Error;
use crate::address_object::resource::AddressObjectResource; use crate::address_object::resource::AddressObjectResource;
use crate::principal::PrincipalResource; use crate::{CardDavPrincipalUri, Error};
use actix_web::dev::ResourceMap;
use actix_web::http::Method; use actix_web::http::Method;
use actix_web::web; use actix_web::web;
use async_trait::async_trait; use async_trait::async_trait;
@@ -14,7 +12,7 @@ use rustical_dav::extensions::{
CommonPropertiesExtension, CommonPropertiesProp, SyncTokenExtension, SyncTokenExtensionProp, CommonPropertiesExtension, CommonPropertiesProp, SyncTokenExtension, SyncTokenExtensionProp,
}; };
use rustical_dav::privileges::UserPrivilegeSet; use rustical_dav::privileges::UserPrivilegeSet;
use rustical_dav::resource::{Resource, ResourceService}; use rustical_dav::resource::{PrincipalUri, Resource, ResourceService};
use rustical_dav::xml::{Resourcetype, ResourcetypeInner}; use rustical_dav::xml::{Resourcetype, ResourcetypeInner};
use rustical_dav_push::{DavPushExtension, DavPushExtensionProp}; use rustical_dav_push::{DavPushExtension, DavPushExtensionProp};
use rustical_store::auth::User; use rustical_store::auth::User;
@@ -80,10 +78,6 @@ impl DavPushExtension for AddressbookResource {
} }
} }
impl CommonPropertiesExtension for AddressbookResource {
type PrincipalResource = PrincipalResource;
}
impl Resource for AddressbookResource { impl Resource for AddressbookResource {
type Prop = AddressbookPropWrapper; type Prop = AddressbookPropWrapper;
type Error = Error; type Error = Error;
@@ -98,7 +92,7 @@ impl Resource for AddressbookResource {
fn get_prop( fn get_prop(
&self, &self,
rmap: &ResourceMap, puri: &impl PrincipalUri,
user: &User, user: &User,
prop: &AddressbookPropWrapperName, prop: &AddressbookPropWrapperName,
) -> Result<Self::Prop, Self::Error> { ) -> Result<Self::Prop, Self::Error> {
@@ -130,7 +124,7 @@ impl Resource for AddressbookResource {
AddressbookPropWrapper::DavPush(<Self as DavPushExtension>::get_prop(self, prop)?) AddressbookPropWrapper::DavPush(<Self as DavPushExtension>::get_prop(self, prop)?)
} }
AddressbookPropWrapperName::Common(prop) => AddressbookPropWrapper::Common( AddressbookPropWrapperName::Common(prop) => AddressbookPropWrapper::Common(
CommonPropertiesExtension::get_prop(self, rmap, user, prop)?, CommonPropertiesExtension::get_prop(self, puri, user, prop)?,
), ),
}) })
} }
@@ -204,6 +198,7 @@ impl<AS: AddressbookStore, S: SubscriptionStore> ResourceService
type Resource = AddressbookResource; type Resource = AddressbookResource;
type Error = Error; type Error = Error;
type Principal = User; type Principal = User;
type PrincipalUri = CardDavPrincipalUri;
async fn get_resource( async fn get_resource(
&self, &self,

View File

@@ -11,9 +11,10 @@ use actix_web::{
}; };
use address_object::resource::AddressObjectResourceService; use address_object::resource::AddressObjectResourceService;
use addressbook::resource::AddressbookResourceService; use addressbook::resource::AddressbookResourceService;
use derive_more::Constructor;
pub use error::Error; pub use error::Error;
use principal::{PrincipalResource, PrincipalResourceService}; use principal::{PrincipalResource, PrincipalResourceService};
use rustical_dav::resource::{NamedRoute, ResourceService}; use rustical_dav::resource::{PrincipalUri, ResourceService};
use rustical_dav::resources::RootResourceService; use rustical_dav::resources::RootResourceService;
use rustical_store::{ use rustical_store::{
AddressbookStore, SubscriptionStore, AddressbookStore, SubscriptionStore,
@@ -26,6 +27,15 @@ pub mod addressbook;
pub mod error; pub mod error;
pub mod principal; pub mod principal;
#[derive(Debug, Clone, Constructor)]
pub struct CardDavPrincipalUri(&'static str);
impl PrincipalUri for CardDavPrincipalUri {
fn principal_uri(&self, principal: &str) -> String {
format!("{}/{}", self.0, principal)
}
}
/// Quite a janky implementation but the default METHOD_NOT_ALLOWED response gives us the allowed /// Quite a janky implementation but the default METHOD_NOT_ALLOWED response gives us the allowed
/// methods of a resource /// methods of a resource
fn options_handler() -> ErrorHandlers<BoxBody> { fn options_handler() -> ErrorHandlers<BoxBody> {
@@ -53,6 +63,7 @@ fn options_handler() -> ErrorHandlers<BoxBody> {
} }
pub fn carddav_service<AP: AuthenticationProvider, A: AddressbookStore, S: SubscriptionStore>( pub fn carddav_service<AP: AuthenticationProvider, A: AddressbookStore, S: SubscriptionStore>(
prefix: &'static str,
auth_provider: Arc<AP>, auth_provider: Arc<AP>,
store: Arc<A>, store: Arc<A>,
subscription_store: Arc<S>, subscription_store: Arc<S>,
@@ -62,14 +73,19 @@ pub fn carddav_service<AP: AuthenticationProvider, A: AddressbookStore, S: Subsc
.wrap(options_handler()) .wrap(options_handler())
.app_data(Data::from(store.clone())) .app_data(Data::from(store.clone()))
.app_data(Data::from(subscription_store)) .app_data(Data::from(subscription_store))
.service(RootResourceService::<PrincipalResource, User>::default().actix_resource()) .app_data(Data::new(CardDavPrincipalUri::new(
format!("{prefix}/principal").leak(),
)))
.service(
RootResourceService::<PrincipalResource, User, CardDavPrincipalUri>::default()
.actix_resource(),
)
.service( .service(
web::scope("/principal").service( web::scope("/principal").service(
web::scope("/{principal}") web::scope("/{principal}")
.service( .service(
PrincipalResourceService::new(store.clone(), auth_provider) PrincipalResourceService::new(store.clone(), auth_provider)
.actix_resource() .actix_resource(),
.name(PrincipalResource::route_name()),
) )
.service( .service(
web::scope("/{addressbook_id}") web::scope("/{addressbook_id}")

View File

@@ -1,10 +1,9 @@
use crate::Error;
use crate::addressbook::resource::AddressbookResource; use crate::addressbook::resource::AddressbookResource;
use actix_web::dev::ResourceMap; use crate::{CardDavPrincipalUri, Error};
use async_trait::async_trait; use async_trait::async_trait;
use rustical_dav::extensions::{CommonPropertiesExtension, CommonPropertiesProp}; use rustical_dav::extensions::{CommonPropertiesExtension, CommonPropertiesProp};
use rustical_dav::privileges::UserPrivilegeSet; use rustical_dav::privileges::UserPrivilegeSet;
use rustical_dav::resource::{NamedRoute, Resource, ResourceService}; use rustical_dav::resource::{PrincipalUri, Resource, ResourceService};
use rustical_dav::xml::{HrefElement, Resourcetype, ResourcetypeInner}; use rustical_dav::xml::{HrefElement, Resourcetype, ResourcetypeInner};
use rustical_store::AddressbookStore; use rustical_store::AddressbookStore;
use rustical_store::auth::{AuthenticationProvider, User}; use rustical_store::auth::{AuthenticationProvider, User};
@@ -58,22 +57,6 @@ pub enum PrincipalPropWrapper {
Common(CommonPropertiesProp), Common(CommonPropertiesProp),
} }
impl PrincipalResource {
pub fn get_principal_url(rmap: &ResourceMap, principal: &str) -> String {
Self::get_url(rmap, vec![principal]).unwrap()
}
}
impl NamedRoute for PrincipalResource {
fn route_name() -> &'static str {
"carddav_principal"
}
}
impl CommonPropertiesExtension for PrincipalResource {
type PrincipalResource = Self;
}
impl Resource for PrincipalResource { impl Resource for PrincipalResource {
type Prop = PrincipalPropWrapper; type Prop = PrincipalPropWrapper;
type Error = Error; type Error = Error;
@@ -88,16 +71,16 @@ impl Resource for PrincipalResource {
fn get_prop( fn get_prop(
&self, &self,
rmap: &ResourceMap, puri: &impl PrincipalUri,
user: &User, user: &User,
prop: &PrincipalPropWrapperName, prop: &PrincipalPropWrapperName,
) -> Result<Self::Prop, Self::Error> { ) -> Result<Self::Prop, Self::Error> {
let principal_href = HrefElement::new(Self::get_principal_url(rmap, &self.principal.id)); let principal_href = HrefElement::new(puri.principal_uri(&user.id));
let home_set = AddressbookHomeSet( let home_set = AddressbookHomeSet(
user.memberships() user.memberships()
.into_iter() .into_iter()
.map(|principal| Self::get_url(rmap, vec![principal]).unwrap()) .map(|principal| puri.principal_uri(principal))
.map(HrefElement::new) .map(HrefElement::new)
.collect(), .collect(),
); );
@@ -120,7 +103,7 @@ impl Resource for PrincipalResource {
} }
PrincipalPropWrapperName::Common(prop) => PrincipalPropWrapper::Common( PrincipalPropWrapperName::Common(prop) => PrincipalPropWrapper::Common(
CommonPropertiesExtension::get_prop(self, rmap, user, prop)?, CommonPropertiesExtension::get_prop(self, puri, user, prop)?,
), ),
}) })
} }
@@ -145,6 +128,7 @@ impl<A: AddressbookStore, AP: AuthenticationProvider> ResourceService
type Resource = PrincipalResource; type Resource = PrincipalResource;
type Error = Error; type Error = Error;
type Principal = User; type Principal = User;
type PrincipalUri = CardDavPrincipalUri;
async fn get_resource( async fn get_resource(
&self, &self,

View File

@@ -1,10 +1,9 @@
use crate::{ use crate::{
Principal, Principal,
privileges::UserPrivilegeSet, privileges::UserPrivilegeSet,
resource::{NamedRoute, Resource}, resource::{PrincipalUri, Resource},
xml::{HrefElement, Resourcetype}, xml::{HrefElement, Resourcetype},
}; };
use actix_web::dev::ResourceMap;
use rustical_xml::{EnumUnitVariants, EnumVariants, XmlDeserialize, XmlSerialize}; use rustical_xml::{EnumUnitVariants, EnumVariants, XmlDeserialize, XmlSerialize};
#[derive(XmlDeserialize, XmlSerialize, PartialEq, Clone, EnumUnitVariants, EnumVariants)] #[derive(XmlDeserialize, XmlSerialize, PartialEq, Clone, EnumUnitVariants, EnumVariants)]
@@ -28,11 +27,9 @@ pub enum CommonPropertiesProp {
} }
pub trait CommonPropertiesExtension: Resource { pub trait CommonPropertiesExtension: Resource {
type PrincipalResource: NamedRoute;
fn get_prop( fn get_prop(
&self, &self,
rmap: &ResourceMap, principal_uri: &impl PrincipalUri,
principal: &Self::Principal, principal: &Self::Principal,
prop: &CommonPropertiesPropName, prop: &CommonPropertiesPropName,
) -> Result<CommonPropertiesProp, <Self as Resource>::Error> { ) -> Result<CommonPropertiesProp, <Self as Resource>::Error> {
@@ -42,21 +39,16 @@ pub trait CommonPropertiesExtension: Resource {
} }
CommonPropertiesPropName::CurrentUserPrincipal => { CommonPropertiesPropName::CurrentUserPrincipal => {
CommonPropertiesProp::CurrentUserPrincipal( CommonPropertiesProp::CurrentUserPrincipal(
Self::PrincipalResource::get_url(rmap, [&principal.get_id()]) principal_uri.principal_uri(principal.get_id()).into(),
.unwrap()
.into(),
) )
} }
CommonPropertiesPropName::CurrentUserPrivilegeSet => { CommonPropertiesPropName::CurrentUserPrivilegeSet => {
CommonPropertiesProp::CurrentUserPrivilegeSet(self.get_user_privileges(principal)?) CommonPropertiesProp::CurrentUserPrivilegeSet(self.get_user_privileges(principal)?)
} }
CommonPropertiesPropName::Owner => { CommonPropertiesPropName::Owner => CommonPropertiesProp::Owner(
CommonPropertiesProp::Owner(self.get_owner().map(|owner| { self.get_owner()
Self::PrincipalResource::get_url(rmap, [owner]) .map(|owner| principal_uri.principal_uri(owner).into()),
.unwrap() ),
.into()
}))
}
}) })
} }
@@ -68,3 +60,5 @@ pub trait CommonPropertiesExtension: Resource {
Err(crate::Error::PropReadOnly) Err(crate::Error::PropReadOnly)
} }
} }
impl<R: Resource> CommonPropertiesExtension for R {}

View File

@@ -14,7 +14,7 @@ use rustical_xml::XmlDocument;
use tracing::instrument; use tracing::instrument;
use tracing_actix_web::RootSpan; use tracing_actix_web::RootSpan;
#[instrument(parent = root_span.id(), skip(path, req, root_span, resource_service))] #[instrument(parent = root_span.id(), skip(path, req, root_span, resource_service, puri))]
#[allow(clippy::type_complexity)] #[allow(clippy::type_complexity)]
pub(crate) async fn route_propfind<R: ResourceService>( pub(crate) async fn route_propfind<R: ResourceService>(
path: Path<R::PathComponents>, path: Path<R::PathComponents>,
@@ -24,6 +24,7 @@ pub(crate) async fn route_propfind<R: ResourceService>(
depth: Depth, depth: Depth,
root_span: RootSpan, root_span: RootSpan,
resource_service: Data<R>, resource_service: Data<R>,
puri: Data<R::PrincipalUri>,
) -> Result< ) -> Result<
MultistatusElement<<R::Resource as Resource>::Prop, <R::MemberType as Resource>::Prop>, MultistatusElement<<R::Resource as Resource>::Prop, <R::MemberType as Resource>::Prop>,
R::Error, R::Error,
@@ -61,13 +62,13 @@ pub(crate) async fn route_propfind<R: ResourceService>(
member_responses.push(member.propfind( member_responses.push(member.propfind(
&format!("{}/{}", req.path().trim_end_matches('/'), subpath), &format!("{}/{}", req.path().trim_end_matches('/'), subpath),
&props, &props,
puri.as_ref(),
&user, &user,
req.resource_map(),
)?); )?);
} }
} }
let response = resource.propfind(req.path(), &props, &user, req.resource_map())?; let response = resource.propfind(req.path(), &props, puri.as_ref(), &user)?;
Ok(MultistatusElement { Ok(MultistatusElement {
responses: vec![response], responses: vec![response],

View File

@@ -3,7 +3,6 @@ use crate::xml::Resourcetype;
use crate::xml::multistatus::{PropTagWrapper, PropstatElement, PropstatWrapper}; use crate::xml::multistatus::{PropTagWrapper, PropstatElement, PropstatWrapper};
use crate::xml::{TagList, multistatus::ResponseElement}; use crate::xml::{TagList, multistatus::ResponseElement};
use crate::{Error, Principal}; use crate::{Error, Principal};
use actix_web::dev::ResourceMap;
use actix_web::http::header::{EntityTag, IfMatch, IfNoneMatch}; use actix_web::http::header::{EntityTag, IfMatch, IfNoneMatch};
use actix_web::{ResponseError, http::StatusCode}; use actix_web::{ResponseError, http::StatusCode};
use itertools::Itertools; use itertools::Itertools;
@@ -13,8 +12,10 @@ use rustical_xml::{EnumUnitVariants, EnumVariants, XmlDeserialize, XmlSerialize}
use std::str::FromStr; use std::str::FromStr;
mod methods; mod methods;
mod principal_uri;
mod resource_service; mod resource_service;
pub use principal_uri::PrincipalUri;
pub use resource_service::*; pub use resource_service::*;
pub trait ResourceProp: XmlSerialize + XmlDeserialize {} pub trait ResourceProp: XmlSerialize + XmlDeserialize {}
@@ -36,7 +37,7 @@ pub trait Resource: Clone + 'static {
fn get_prop( fn get_prop(
&self, &self,
rmap: &ResourceMap, principal_uri: &impl PrincipalUri,
principal: &Self::Principal, principal: &Self::Principal,
prop: &<Self::Prop as EnumUnitVariants>::UnitVariants, prop: &<Self::Prop as EnumUnitVariants>::UnitVariants,
) -> Result<Self::Prop, Self::Error>; ) -> Result<Self::Prop, Self::Error>;
@@ -101,8 +102,8 @@ pub trait Resource: Clone + 'static {
&self, &self,
path: &str, path: &str,
props: &[&str], props: &[&str],
principal_uri: &impl PrincipalUri,
principal: &Self::Principal, principal: &Self::Principal,
rmap: &ResourceMap,
) -> Result<ResponseElement<Self::Prop>, Self::Error> { ) -> Result<ResponseElement<Self::Prop>, Self::Error> {
let mut props = props.to_vec(); let mut props = props.to_vec();
@@ -154,7 +155,7 @@ pub trait Resource: Clone + 'static {
let prop_responses = valid_props let prop_responses = valid_props
.into_iter() .into_iter()
.map(|prop| self.get_prop(rmap, principal, &prop)) .map(|prop| self.get_prop(principal_uri, principal, &prop))
.collect::<Result<Vec<_>, Self::Error>>()?; .collect::<Result<Vec<_>, Self::Error>>()?;
let mut propstats = vec![PropstatWrapper::Normal(PropstatElement { let mut propstats = vec![PropstatWrapper::Normal(PropstatElement {

View File

@@ -0,0 +1,3 @@
pub trait PrincipalUri: 'static {
fn principal_uri(&self, principal: &str) -> String;
}

View File

@@ -1,17 +1,13 @@
use super::methods::{route_delete, route_propfind, route_proppatch};
use super::{PrincipalUri, Resource};
use crate::Principal;
use actix_web::dev::{AppService, HttpServiceFactory}; use actix_web::dev::{AppService, HttpServiceFactory};
use actix_web::error::UrlGenerationError;
use actix_web::test::TestRequest;
use actix_web::web::Data; use actix_web::web::Data;
use actix_web::{ResponseError, dev::ResourceMap, http::Method, web}; use actix_web::{ResponseError, http::Method, web};
use async_trait::async_trait; use async_trait::async_trait;
use serde::Deserialize; use serde::Deserialize;
use std::str::FromStr; use std::str::FromStr;
use crate::Principal;
use super::Resource;
use super::methods::{route_delete, route_propfind, route_proppatch};
#[async_trait(?Send)] #[async_trait(?Send)]
pub trait ResourceService: Sized + 'static { pub trait ResourceService: Sized + 'static {
type MemberType: Resource<Error = Self::Error, Principal = Self::Principal>; type MemberType: Resource<Error = Self::Error, Principal = Self::Principal>;
@@ -19,6 +15,7 @@ pub trait ResourceService: Sized + 'static {
type Resource: Resource<Error = Self::Error, Principal = Self::Principal>; type Resource: Resource<Error = Self::Error, Principal = Self::Principal>;
type Error: ResponseError + From<crate::Error>; type Error: ResponseError + From<crate::Error>;
type Principal: Principal; type Principal: Principal;
type PrincipalUri: PrincipalUri;
async fn get_members( async fn get_members(
&self, &self,
@@ -31,6 +28,7 @@ pub trait ResourceService: Sized + 'static {
&self, &self,
_path: &Self::PathComponents, _path: &Self::PathComponents,
) -> Result<Self::Resource, Self::Error>; ) -> Result<Self::Resource, Self::Error>;
async fn save_resource( async fn save_resource(
&self, &self,
_path: &Self::PathComponents, _path: &Self::PathComponents,
@@ -38,6 +36,7 @@ pub trait ResourceService: Sized + 'static {
) -> Result<(), Self::Error> { ) -> Result<(), Self::Error> {
Err(crate::Error::Unauthorized.into()) Err(crate::Error::Unauthorized.into())
} }
async fn delete_resource( async fn delete_resource(
&self, &self,
_path: &Self::PathComponents, _path: &Self::PathComponents,
@@ -68,25 +67,6 @@ pub trait ResourceService: Sized + 'static {
} }
} }
pub trait NamedRoute {
fn route_name() -> &'static str;
fn get_url<U, I>(rmap: &ResourceMap, elements: U) -> Result<String, UrlGenerationError>
where
U: IntoIterator<Item = I>,
I: AsRef<str>,
{
Ok(rmap
.url_for(
&TestRequest::default().to_http_request(),
Self::route_name(),
elements,
)?
.path()
.to_owned())
}
}
pub struct ResourceServiceRoute<RS: ResourceService>(pub RS); pub struct ResourceServiceRoute<RS: ResourceService>(pub RS);
impl<RS: ResourceService> HttpServiceFactory for ResourceServiceRoute<RS> { impl<RS: ResourceService> HttpServiceFactory for ResourceServiceRoute<RS> {

View File

@@ -3,9 +3,8 @@ use crate::extensions::{
CommonPropertiesExtension, CommonPropertiesProp, CommonPropertiesPropName, CommonPropertiesExtension, CommonPropertiesProp, CommonPropertiesPropName,
}; };
use crate::privileges::UserPrivilegeSet; use crate::privileges::UserPrivilegeSet;
use crate::resource::{NamedRoute, Resource, ResourceService}; use crate::resource::{PrincipalUri, Resource, ResourceService};
use crate::xml::{Resourcetype, ResourcetypeInner}; use crate::xml::{Resourcetype, ResourcetypeInner};
use actix_web::dev::ResourceMap;
use async_trait::async_trait; use async_trait::async_trait;
use std::marker::PhantomData; use std::marker::PhantomData;
@@ -18,11 +17,7 @@ impl<PR: Resource, P: Principal> Default for RootResource<PR, P> {
} }
} }
impl<PR: Resource + NamedRoute, P: Principal> CommonPropertiesExtension for RootResource<PR, P> { impl<PR: Resource, P: Principal> Resource for RootResource<PR, P> {
type PrincipalResource = PR;
}
impl<PR: Resource + NamedRoute, P: Principal> Resource for RootResource<PR, P> {
type Prop = CommonPropertiesProp; type Prop = CommonPropertiesProp;
type Error = PR::Error; type Error = PR::Error;
type Principal = P; type Principal = P;
@@ -36,11 +31,11 @@ impl<PR: Resource + NamedRoute, P: Principal> Resource for RootResource<PR, P> {
fn get_prop( fn get_prop(
&self, &self,
rmap: &ResourceMap, principal_uri: &impl PrincipalUri,
user: &P, user: &P,
prop: &CommonPropertiesPropName, prop: &CommonPropertiesPropName,
) -> Result<Self::Prop, Self::Error> { ) -> Result<Self::Prop, Self::Error> {
CommonPropertiesExtension::get_prop(self, rmap, user, prop) CommonPropertiesExtension::get_prop(self, principal_uri, user, prop)
} }
fn get_user_privileges(&self, _user: &P) -> Result<UserPrivilegeSet, Self::Error> { fn get_user_privileges(&self, _user: &P) -> Result<UserPrivilegeSet, Self::Error> {
@@ -49,23 +44,28 @@ impl<PR: Resource + NamedRoute, P: Principal> Resource for RootResource<PR, P> {
} }
#[derive(Clone)] #[derive(Clone)]
pub struct RootResourceService<PR: Resource, P: Principal>(PhantomData<PR>, PhantomData<P>); pub struct RootResourceService<PR: Resource, P: Principal, PURI: PrincipalUri>(
PhantomData<PR>,
PhantomData<P>,
PhantomData<PURI>,
);
impl<PR: Resource, P: Principal> Default for RootResourceService<PR, P> { impl<PR: Resource, P: Principal, PURI: PrincipalUri> Default for RootResourceService<PR, P, PURI> {
fn default() -> Self { fn default() -> Self {
Self(PhantomData, PhantomData) Self(PhantomData, PhantomData, PhantomData)
} }
} }
#[async_trait(?Send)] #[async_trait(?Send)]
impl<PR: Resource<Principal = P> + NamedRoute, P: Principal> ResourceService impl<PR: Resource<Principal = P>, P: Principal, PURI: PrincipalUri> ResourceService
for RootResourceService<PR, P> for RootResourceService<PR, P, PURI>
{ {
type PathComponents = (); type PathComponents = ();
type MemberType = PR; type MemberType = PR;
type Resource = RootResource<PR, P>; type Resource = RootResource<PR, P>;
type Error = PR::Error; type Error = PR::Error;
type Principal = P; type Principal = P;
type PrincipalUri = PURI;
async fn get_resource(&self, _: &()) -> Result<Self::Resource, Self::Error> { async fn get_resource(&self, _: &()) -> Result<Self::Resource, Self::Error> {
Ok(RootResource::<PR, P>::default()) Ok(RootResource::<PR, P>::default())

View File

@@ -38,12 +38,14 @@ pub fn make_app<AS: AddressbookStore, CS: CalendarStore, S: SubscriptionStore>(
.wrap(TracingLogger::default()) .wrap(TracingLogger::default())
.wrap(NormalizePath::trim()) .wrap(NormalizePath::trim())
.service(web::scope("/caldav").service(caldav_service( .service(web::scope("/caldav").service(caldav_service(
"/caldav",
auth_provider.clone(), auth_provider.clone(),
cal_store.clone(), cal_store.clone(),
addr_store.clone(), addr_store.clone(),
subscription_store.clone(), subscription_store.clone(),
))) )))
.service(web::scope("/carddav").service(carddav_service( .service(web::scope("/carddav").service(carddav_service(
"/carddav",
auth_provider.clone(), auth_provider.clone(),
addr_store.clone(), addr_store.clone(),
subscription_store, subscription_store,