Add initial carddav support

This commit is contained in:
Lennart
2024-10-27 14:10:01 +01:00
parent 30a795b816
commit 86feb4e189
30 changed files with 2094 additions and 94 deletions

View File

@@ -0,0 +1,111 @@
use super::resource::AddressObjectPathComponents;
use crate::Error;
use actix_web::http::header;
use actix_web::http::header::HeaderValue;
use actix_web::web::{Data, Path};
use actix_web::HttpRequest;
use actix_web::HttpResponse;
use rustical_store::auth::User;
use rustical_store::model::AddressObject;
use rustical_store::AddressbookStore;
use tokio::sync::RwLock;
use tracing::instrument;
use tracing_actix_web::RootSpan;
#[instrument(parent = root_span.id(), skip(store, root_span))]
pub async fn get_object<AS: AddressbookStore + ?Sized>(
path: Path<AddressObjectPathComponents>,
store: Data<RwLock<AS>>,
user: User,
root_span: RootSpan,
) -> Result<HttpResponse, Error> {
let AddressObjectPathComponents {
principal,
cal_id,
object_id,
} = path.into_inner();
if user.id != principal {
return Ok(HttpResponse::Unauthorized().body(""));
}
let addressbook = store
.read()
.await
.get_addressbook(&principal, &cal_id)
.await?;
if user.id != addressbook.principal {
return Ok(HttpResponse::Unauthorized().body(""));
}
let object = store
.read()
.await
.get_object(&principal, &cal_id, &object_id)
.await?;
Ok(HttpResponse::Ok()
.insert_header(("ETag", object.get_etag()))
.insert_header(("Content-Type", "text/calendar"))
.body(object.get_vcf().to_owned()))
}
#[instrument(parent = root_span.id(), skip(store, req, root_span))]
pub async fn put_object<AS: AddressbookStore + ?Sized>(
path: Path<AddressObjectPathComponents>,
store: Data<RwLock<AS>>,
body: String,
user: User,
req: HttpRequest,
root_span: RootSpan,
) -> Result<HttpResponse, Error> {
let AddressObjectPathComponents {
principal,
cal_id: addressbook_id,
object_id,
} = path.into_inner();
if user.id != principal {
return Ok(HttpResponse::Unauthorized().body(""));
}
let addressbook = store
.read()
.await
.get_addressbook(&principal, &addressbook_id)
.await?;
if user.id != addressbook.principal {
return Ok(HttpResponse::Unauthorized().body(""));
}
// TODO: implement If-Match
//
let mut store_write = store.write().await;
if Some(&HeaderValue::from_static("*")) == req.headers().get(header::IF_NONE_MATCH) {
// Only write if not existing
match store_write
.get_object(&principal, &addressbook_id, &object_id)
.await
{
Ok(_) => {
// Conflict
return Ok(HttpResponse::Conflict().body("Resource with this URI already exists"));
}
Err(rustical_store::Error::NotFound) => {
// Path unused, we can proceed
}
Err(err) => {
// Some unknown error :(
return Err(err.into());
}
}
}
let object = AddressObject::from_vcf(object_id, body)?;
store_write
.put_object(principal, addressbook_id, object)
.await?;
Ok(HttpResponse::Created().body(""))
}

View File

@@ -0,0 +1,2 @@
pub mod methods;
pub mod resource;

View File

@@ -0,0 +1,167 @@
use crate::Error;
use actix_web::{dev::ResourceMap, web::Data, HttpRequest};
use async_trait::async_trait;
use derive_more::derive::{From, Into};
use rustical_dav::resource::{InvalidProperty, Resource, ResourceService};
use rustical_store::{model::AddressObject, AddressbookStore};
use serde::{Deserialize, Serialize};
use std::sync::Arc;
use strum::{EnumString, VariantNames};
use tokio::sync::RwLock;
use super::methods::{get_object, put_object};
pub struct AddressObjectResourceService<AS: AddressbookStore + ?Sized> {
pub addr_store: Arc<RwLock<AS>>,
pub path: String,
pub principal: String,
pub cal_id: String,
pub object_id: String,
}
#[derive(EnumString, Debug, VariantNames, Clone)]
#[strum(serialize_all = "kebab-case")]
pub enum AddressObjectPropName {
Getetag,
AddressData,
Getcontenttype,
}
#[derive(Deserialize, Serialize, Debug, Clone)]
#[serde(rename_all = "kebab-case")]
pub enum AddressObjectProp {
// WebDAV (RFC 2518)
Getetag(String),
Getcontenttype(String),
// CalDAV (RFC 4791)
#[serde(rename = "CARD:address-data")]
AddressData(String),
#[serde(other)]
Invalid,
}
impl InvalidProperty for AddressObjectProp {
fn invalid_property(&self) -> bool {
matches!(self, Self::Invalid)
}
}
#[derive(Clone, From, Into)]
pub struct AddressObjectResource(AddressObject);
impl Resource for AddressObjectResource {
type PropName = AddressObjectPropName;
type Prop = AddressObjectProp;
type Error = Error;
fn get_prop(
&self,
_rmap: &ResourceMap,
prop: Self::PropName,
) -> Result<Self::Prop, Self::Error> {
Ok(match prop {
AddressObjectPropName::Getetag => AddressObjectProp::Getetag(self.0.get_etag()),
AddressObjectPropName::AddressData => {
AddressObjectProp::AddressData(self.0.get_vcf().to_owned())
}
AddressObjectPropName::Getcontenttype => {
AddressObjectProp::Getcontenttype("text/calendar;charset=utf-8".to_owned())
}
})
}
#[inline]
fn resource_name() -> &'static str {
"caldav_calendar_object"
}
}
#[derive(Debug, Clone)]
pub struct AddressObjectPathComponents {
pub principal: String,
pub cal_id: String,
pub object_id: String,
}
impl<'de> Deserialize<'de> for AddressObjectPathComponents {
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where
D: serde::Deserializer<'de>,
{
type Inner = (String, String, String);
let (principal, calendar, mut object) = Inner::deserialize(deserializer)?;
if object.ends_with(".ics") {
object.truncate(object.len() - 4);
}
Ok(Self {
principal,
cal_id: calendar,
object_id: object,
})
}
}
#[async_trait(?Send)]
impl<AS: AddressbookStore + ?Sized> ResourceService for AddressObjectResourceService<AS> {
type PathComponents = AddressObjectPathComponents;
type Resource = AddressObjectResource;
type MemberType = AddressObjectResource;
type Error = Error;
async fn new(
req: &HttpRequest,
path_components: Self::PathComponents,
) -> Result<Self, Self::Error> {
let AddressObjectPathComponents {
principal,
cal_id,
object_id,
} = path_components;
let addr_store = req
.app_data::<Data<RwLock<AS>>>()
.expect("no addressbook store in app_data!")
.clone()
.into_inner();
Ok(Self {
addr_store,
principal,
cal_id,
object_id,
path: req.path().to_string(),
})
}
async fn get_resource(&self, principal: String) -> Result<Self::Resource, Self::Error> {
if self.principal != principal {
return Err(Error::Unauthorized);
}
let event = self
.addr_store
.read()
.await
.get_object(&self.principal, &self.cal_id, &self.object_id)
.await?;
Ok(event.into())
}
async fn save_resource(&self, _file: Self::Resource) -> Result<(), Self::Error> {
Err(Error::NotImplemented)
}
async fn delete_resource(&self, use_trashbin: bool) -> Result<(), Self::Error> {
self.addr_store
.write()
.await
.delete_object(&self.principal, &self.cal_id, &self.object_id, use_trashbin)
.await?;
Ok(())
}
#[inline]
fn actix_additional_routes(res: actix_web::Resource) -> actix_web::Resource {
res.get(get_object::<AS>).put(put_object::<AS>)
}
}