Migrate from Event type to CalendarObject

This is preparation to support other calendar components like VTODO and
VJOURNAL
This commit is contained in:
Lennart
2024-09-30 19:35:54 +02:00
parent 41d68f9ae0
commit b3a7806139
14 changed files with 229 additions and 161 deletions

View File

@@ -0,0 +1,100 @@
use crate::CalDavContext;
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_auth::{AuthInfoExtractor, CheckAuthentication};
use rustical_store::CalendarStore;
pub async fn get_event<A: CheckAuthentication, C: CalendarStore + ?Sized>(
context: Data<CalDavContext<C>>,
path: Path<(String, String, String)>,
auth: AuthInfoExtractor<A>,
) -> Result<HttpResponse, Error> {
let (principal, cid, mut uid) = path.into_inner();
if auth.inner.user_id != principal {
return Ok(HttpResponse::Unauthorized().body(""));
}
let calendar = context
.store
.read()
.await
.get_calendar(&principal, &cid)
.await?;
if auth.inner.user_id != calendar.principal {
return Ok(HttpResponse::Unauthorized().body(""));
}
if uid.ends_with(".ics") {
uid.truncate(uid.len() - 4);
}
let event = context
.store
.read()
.await
.get_object(&principal, &cid, &uid)
.await?;
Ok(HttpResponse::Ok()
.insert_header(("ETag", event.get_etag()))
.insert_header(("Content-Type", "text/calendar"))
.body(event.get_ics().to_owned()))
}
pub async fn put_event<A: CheckAuthentication, C: CalendarStore + ?Sized>(
context: Data<CalDavContext<C>>,
path: Path<(String, String, String)>,
body: String,
auth: AuthInfoExtractor<A>,
req: HttpRequest,
) -> Result<HttpResponse, Error> {
let (principal, cid, mut uid) = path.into_inner();
let auth_info = auth.inner;
if auth_info.user_id != principal {
return Ok(HttpResponse::Unauthorized().body(""));
}
let calendar = context
.store
.read()
.await
.get_calendar(&principal, &cid)
.await?;
if auth_info.user_id != calendar.principal {
return Ok(HttpResponse::Unauthorized().body(""));
}
// Incredibly bodged method of normalising the uid but works for a prototype
if uid.ends_with(".ics") {
uid.truncate(uid.len() - 4);
}
// TODO: implement If-Match
// Lock the store
let mut store = context.store.write().await;
if Some(&HeaderValue::from_static("*")) == req.headers().get(header::IF_NONE_MATCH) {
// Only write if not existing
match store.get_object(&principal, &cid, &uid).await {
Ok(_) => {
// Conflict
return Ok(HttpResponse::Conflict().body("Resource with this URI already existing"));
}
Err(rustical_store::Error::NotFound) => {
// Path unused, we can proceed
}
Err(err) => {
// Some unknown error :(
return Err(err.into());
}
}
}
store.put_object(principal, cid, uid, body).await?;
Ok(HttpResponse::Created().body(""))
}

View File

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

View File

@@ -0,0 +1,124 @@
use crate::Error;
use actix_web::{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::object::CalendarObject;
use rustical_store::CalendarStore;
use serde::{Deserialize, Serialize};
use std::sync::Arc;
use strum::{EnumString, VariantNames};
use tokio::sync::RwLock;
pub struct CalendarObjectResourceService<C: CalendarStore + ?Sized> {
pub cal_store: Arc<RwLock<C>>,
pub path: String,
pub principal: String,
pub cid: String,
pub uid: String,
}
#[derive(EnumString, Debug, VariantNames, Clone)]
#[strum(serialize_all = "kebab-case")]
pub enum CalendarObjectPropName {
Getetag,
CalendarData,
Getcontenttype,
}
#[derive(Deserialize, Serialize, Debug, Clone)]
#[serde(rename_all = "kebab-case")]
pub enum CalendarObjectProp {
Getetag(String),
#[serde(rename = "C:calendar-data")]
CalendarData(String),
Getcontenttype(String),
#[serde(other)]
Invalid,
}
impl InvalidProperty for CalendarObjectProp {
fn invalid_property(&self) -> bool {
matches!(self, Self::Invalid)
}
}
#[derive(Clone, From, Into)]
pub struct CalendarObjectResource(CalendarObject);
impl Resource for CalendarObjectResource {
type PropName = CalendarObjectPropName;
type Prop = CalendarObjectProp;
type Error = Error;
fn get_prop(&self, _prefix: &str, prop: Self::PropName) -> Result<Self::Prop, Self::Error> {
Ok(match prop {
CalendarObjectPropName::Getetag => CalendarObjectProp::Getetag(self.0.get_etag()),
CalendarObjectPropName::CalendarData => {
CalendarObjectProp::CalendarData(self.0.get_ics().to_owned())
}
CalendarObjectPropName::Getcontenttype => {
CalendarObjectProp::Getcontenttype("text/calendar;charset=utf-8".to_owned())
}
})
}
}
#[async_trait(?Send)]
impl<C: CalendarStore + ?Sized> ResourceService for CalendarObjectResourceService<C> {
type PathComponents = (String, String, String); // principal, calendar, event
type Resource = CalendarObjectResource;
type MemberType = CalendarObjectResource;
type Error = Error;
async fn new(
req: &HttpRequest,
path_components: Self::PathComponents,
) -> Result<Self, Self::Error> {
let (principal, cid, mut uid) = path_components;
if uid.ends_with(".ics") {
uid.truncate(uid.len() - 4);
}
let cal_store = req
.app_data::<Data<RwLock<C>>>()
.expect("no calendar store in app_data!")
.clone()
.into_inner();
Ok(Self {
cal_store,
principal,
cid,
uid,
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
.cal_store
.read()
.await
.get_object(&self.principal, &self.cid, &self.uid)
.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.cal_store
.write()
.await
.delete_object(&self.principal, &self.cid, &self.uid, use_trashbin)
.await?;
Ok(())
}
}