caldav: Refactoring

This commit is contained in:
Lennart
2024-05-27 15:41:39 +02:00
parent fe5f3207ae
commit eb70aae9c3
7 changed files with 110 additions and 110 deletions

View File

@@ -0,0 +1,98 @@
use crate::CalDavContext;
use actix_web::http::StatusCode;
use actix_web::web::{Data, Path};
use actix_web::{HttpResponse, ResponseError};
use rustical_auth::{AuthInfoExtractor, CheckAuthentication};
use rustical_store::calendar::CalendarStore;
use thiserror::Error;
#[derive(Debug, Error)]
pub enum Error {
#[error(transparent)]
Other(#[from] anyhow::Error),
}
impl ResponseError for Error {
fn status_code(&self) -> actix_web::http::StatusCode {
match self {
Self::Other(_) => StatusCode::INTERNAL_SERVER_ERROR,
}
}
fn error_response(&self) -> HttpResponse<actix_web::body::BoxBody> {
HttpResponse::build(self.status_code()).body(self.to_string())
}
}
pub async fn delete_event<A: CheckAuthentication, C: CalendarStore + ?Sized>(
context: Data<CalDavContext<C>>,
path: Path<(String, String, String)>,
auth: AuthInfoExtractor<A>,
) -> Result<HttpResponse, Error> {
let _user = auth.inner.user_id;
// TODO: verify whether user is authorized
let (_principal, mut cid, uid) = path.into_inner();
if cid.ends_with(".ics") {
cid.truncate(cid.len() - 4);
}
context.store.write().await.delete_event(&cid, &uid).await?;
Ok(HttpResponse::Ok().body(""))
}
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> {
// TODO: verify whether user is authorized
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(&cid).await?;
if auth.inner.user_id != calendar.owner {
return Ok(HttpResponse::Unauthorized().body(""));
}
if uid.ends_with(".ics") {
uid.truncate(uid.len() - 4);
}
let event = context.store.read().await.get_event(&cid, &uid).await?;
Ok(HttpResponse::Ok()
.insert_header(("ETag", event.get_etag()))
.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>,
) -> 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(&cid).await?;
if auth_info.user_id != calendar.owner {
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);
}
context
.store
.write()
.await
.upsert_event(cid, uid, body)
.await?;
Ok(HttpResponse::Ok().body(""))
}

View File

@@ -1,98 +1,2 @@
use crate::CalDavContext;
use actix_web::http::StatusCode;
use actix_web::web::{Data, Path};
use actix_web::{HttpResponse, ResponseError};
use rustical_auth::{AuthInfoExtractor, CheckAuthentication};
use rustical_store::calendar::CalendarStore;
use thiserror::Error;
#[derive(Debug, Error)]
pub enum Error {
#[error(transparent)]
Other(#[from] anyhow::Error),
}
impl ResponseError for Error {
fn status_code(&self) -> actix_web::http::StatusCode {
match self {
Self::Other(_) => StatusCode::INTERNAL_SERVER_ERROR,
}
}
fn error_response(&self) -> HttpResponse<actix_web::body::BoxBody> {
HttpResponse::build(self.status_code()).body(self.to_string())
}
}
pub async fn delete_event<A: CheckAuthentication, C: CalendarStore + ?Sized>(
context: Data<CalDavContext<C>>,
path: Path<(String, String, String)>,
auth: AuthInfoExtractor<A>,
) -> Result<HttpResponse, Error> {
let _user = auth.inner.user_id;
// TODO: verify whether user is authorized
let (_principal, mut cid, uid) = path.into_inner();
if cid.ends_with(".ics") {
cid.truncate(cid.len() - 4);
}
context.store.write().await.delete_event(&cid, &uid).await?;
Ok(HttpResponse::Ok().body(""))
}
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> {
// TODO: verify whether user is authorized
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(&cid).await?;
if auth.inner.user_id != calendar.owner {
return Ok(HttpResponse::Unauthorized().body(""));
}
if uid.ends_with(".ics") {
uid.truncate(uid.len() - 4);
}
let event = context.store.read().await.get_event(&cid, &uid).await?;
Ok(HttpResponse::Ok()
.insert_header(("ETag", event.get_etag()))
.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>,
) -> 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(&cid).await?;
if auth_info.user_id != calendar.owner {
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);
}
context
.store
.write()
.await
.upsert_event(cid, uid, body)
.await?;
Ok(HttpResponse::Ok().body(""))
}
pub mod methods;
pub mod resource;

View File

@@ -0,0 +1,107 @@
use actix_web::{web::Data, HttpRequest};
use anyhow::{anyhow, Result};
use async_trait::async_trait;
use rustical_auth::AuthInfo;
use rustical_dav::error::Error;
use rustical_dav::resource::{Resource, ResourceService};
use rustical_dav::xml_snippets::TextNode;
use rustical_store::calendar::CalendarStore;
use rustical_store::event::Event;
use serde::Serialize;
use std::sync::Arc;
use strum::{EnumString, IntoStaticStr, VariantNames};
use tokio::sync::RwLock;
pub struct EventResource<C: CalendarStore + ?Sized> {
pub cal_store: Arc<RwLock<C>>,
pub path: String,
pub cid: String,
pub uid: String,
}
#[derive(EnumString, Debug, VariantNames, IntoStaticStr, Clone)]
#[strum(serialize_all = "kebab-case")]
pub enum EventProp {
Getetag,
CalendarData,
Getcontenttype,
}
#[derive(Serialize)]
#[serde(rename_all = "kebab-case")]
pub enum PrincipalPropResponse {
Getetag(TextNode),
CalendarData(TextNode),
Getcontenttype(TextNode),
}
pub struct EventFile {
pub event: Event,
}
impl Resource for EventFile {
type PropType = EventProp;
type PropResponse = PrincipalPropResponse;
fn get_path(&self) -> &str {
"asd"
}
fn get_prop(&self, _prefix: &str, prop: Self::PropType) -> Result<Self::PropResponse> {
match prop {
EventProp::Getetag => Ok(PrincipalPropResponse::Getetag(TextNode(Some(
self.event.get_etag(),
)))),
EventProp::CalendarData => Ok(PrincipalPropResponse::CalendarData(TextNode(Some(
self.event.get_ics().to_owned(),
)))),
EventProp::Getcontenttype => Ok(PrincipalPropResponse::Getcontenttype(TextNode(Some(
"text/calendar;charset=utf-8".to_owned(),
)))),
}
}
}
#[async_trait(?Send)]
impl<C: CalendarStore + ?Sized> ResourceService for EventResource<C> {
type PathComponents = (String, String, String); // principal, calendar, event
type File = EventFile;
type MemberType = EventFile;
async fn get_members(&self, _auth_info: AuthInfo) -> Result<Vec<Self::MemberType>> {
Ok(vec![])
}
async fn new(
req: HttpRequest,
_auth_info: AuthInfo,
path_components: Self::PathComponents,
) -> Result<Self, Error> {
let (_principal, cid, uid) = path_components;
let cal_store = req
.app_data::<Data<RwLock<C>>>()
.ok_or(anyhow!("no calendar store in app_data!"))?
.clone()
.into_inner();
// let event = cal_store.read().await.get_event(&cid, &uid).await?;
Ok(Self {
cal_store,
cid,
uid,
path: req.path().to_string(),
})
}
async fn get_file(&self) -> Result<Self::File> {
let event = self
.cal_store
.read()
.await
.get_event(&self.cid, &self.uid)
.await?;
Ok(EventFile { event })
}
}