Rename dav crate to caldav to prepare splitting dav functionality into dav crate

This commit is contained in:
Lennart
2023-09-14 13:25:58 +02:00
parent 1e65d3d69d
commit 1e6e97abfb
20 changed files with 60 additions and 51 deletions

View File

@@ -0,0 +1,176 @@
use crate::namespace::Namespace;
use crate::resource::HandlePropfind;
use crate::resources::event::EventResource;
use crate::xml_snippets::generate_multistatus;
use crate::{CalDavContext, Error};
use actix_web::http::header::ContentType;
use actix_web::web::{Data, Path};
use actix_web::{HttpRequest, HttpResponse};
use anyhow::Result;
use quick_xml::events::BytesText;
use roxmltree::{Node, NodeType};
use rustical_auth::{AuthInfoExtractor, CheckAuthentication};
use rustical_store::calendar::{Calendar, CalendarStore, Event};
use std::sync::Arc;
use tokio::sync::RwLock;
async fn _parse_filter(filter_node: &Node<'_, '_>) {
for comp_filter_node in filter_node.children() {
if comp_filter_node.tag_name().name() != "comp-filter" {
dbg!("wtf", comp_filter_node.tag_name().name());
continue;
}
for filter in filter_node.children() {
match filter.tag_name().name() {
// <time-range start=\"20230804T125257Z\" end=\"20231013T125257Z\"/
"time-range" => {}
_ => {
dbg!("unknown filter", filter.tag_name());
}
}
}
}
}
async fn handle_report_calendar_query<C: CalendarStore>(
query_node: Node<'_, '_>,
request: HttpRequest,
events: Vec<Event>,
cal_store: Arc<RwLock<C>>,
) -> Result<HttpResponse, Error> {
let prop_node = query_node
.children()
.find(|n| n.node_type() == NodeType::Element && n.tag_name().name() == "prop")
.ok_or(Error::BadRequest)?;
let props: Vec<&str> = prop_node
.children()
.map(|node| node.tag_name().name())
.collect();
let output = generate_multistatus(vec![Namespace::Dav, Namespace::CalDAV], |writer| {
for event in events {
let path = format!("{}/{}", request.path(), event.get_uid());
let event_resource = EventResource {
cal_store: cal_store.clone(),
path: path.clone(),
event,
};
// TODO: proper error handling
let propfind_result = event_resource
.propfind(props.clone())
.map_err(|_e| quick_xml::Error::TextNotFound)?;
writer.write_event(quick_xml::events::Event::Text(BytesText::from_escaped(
propfind_result,
)))?;
}
Ok(())
})
.map_err(|_e| Error::InternalError)?;
Ok(HttpResponse::MultiStatus()
.content_type(ContentType::xml())
.body(output))
}
pub async fn route_report_calendar<A: CheckAuthentication, C: CalendarStore>(
context: Data<CalDavContext<C>>,
body: String,
path: Path<(String, String)>,
request: HttpRequest,
_auth: AuthInfoExtractor<A>,
) -> Result<HttpResponse, Error> {
// TODO: Check authorization
let (_principal, cid) = path.into_inner();
let doc = roxmltree::Document::parse(&body).map_err(|_e| Error::BadRequest)?;
let query_node = doc.root_element();
let events = context.store.read().await.get_events(&cid).await.unwrap();
dbg!(&body);
// TODO: implement filtering
match query_node.tag_name().name() {
"calendar-query" => {}
"calendar-multiget" => {}
_ => return Err(Error::BadRequest),
};
handle_report_calendar_query(query_node, request, events, context.store.clone()).await
}
pub async fn handle_mkcol_calendar_set<C: CalendarStore>(
store: &RwLock<C>,
prop_node: Node<'_, '_>,
cid: String,
owner: String,
) -> Result<()> {
let mut cal = Calendar {
owner,
id: cid.clone(),
..Default::default()
};
for prop in prop_node.children() {
match prop.tag_name().name() {
"displayname" => {
cal.name = prop.text().map(|s| s.to_string());
}
"timezone" => {
cal.timezone = prop.text().map(|s| s.to_string());
}
"calendar-color" => {
cal.color = prop.text().map(|s| s.to_string());
}
"calendar-description" => {
cal.description = prop.text().map(|s| s.to_string());
}
"calendar-timezone" => {
cal.timezone = prop.text().map(|s| s.to_string());
}
_ => {
println!("unsupported mkcol tag: {}", prop.tag_name().name())
}
}
}
store.write().await.insert_calendar(cid, cal).await?;
Ok(())
}
pub async fn route_mkcol_calendar<A: CheckAuthentication, C: CalendarStore>(
path: Path<(String, String)>,
body: String,
auth: AuthInfoExtractor<A>,
context: Data<CalDavContext<C>>,
) -> Result<HttpResponse, Error> {
let (_principal, cid) = path.into_inner();
let doc = roxmltree::Document::parse(&body).map_err(|_e| Error::BadRequest)?;
let mkcol_node = doc.root_element();
match mkcol_node.tag_name().name() {
"mkcol" => {}
_ => return Err(Error::BadRequest),
}
// TODO: Why does the spec (rfc5689) allow multiple <set/> elements but only one resource? :/
// Well, for now just bother with the first one
let set_node = mkcol_node.first_element_child().ok_or(Error::BadRequest)?;
match set_node.tag_name().name() {
"set" => {}
_ => return Err(Error::BadRequest),
}
let prop_node = set_node.first_element_child().ok_or(Error::BadRequest)?;
if prop_node.tag_name().name() != "prop" {
return Err(Error::BadRequest);
}
handle_mkcol_calendar_set(
&context.store,
prop_node,
cid.clone(),
auth.inner.user_id.clone(),
)
.await
.map_err(|_e| Error::InternalError)?;
Ok(HttpResponse::Created().body(""))
}

View File

@@ -0,0 +1,79 @@
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>(
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>(
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 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.to_ics().to_string()))
}
pub async fn put_event<A: CheckAuthentication, C: CalendarStore>(
context: Data<CalDavContext<C>>,
path: Path<(String, String, String)>,
body: String,
_auth: AuthInfoExtractor<A>,
) -> Result<HttpResponse, Error> {
// TODO: verify whether user is authorized
let (_principal, cid, mut uid) = path.into_inner();
// 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

@@ -0,0 +1,3 @@
pub mod calendar;
pub mod event;
pub mod propfind;

View File

@@ -0,0 +1,112 @@
use crate::depth_extractor::Depth;
use crate::namespace::Namespace;
use crate::resource::{HandlePropfind, Resource};
use crate::xml_snippets::generate_multistatus;
use crate::CalDavContext;
use actix_web::http::header::ContentType;
use actix_web::http::StatusCode;
use actix_web::web::{Data, Path};
use actix_web::{HttpRequest, HttpResponse};
use anyhow::Result;
use quick_xml::events::BytesText;
use rustical_auth::{AuthInfoExtractor, CheckAuthentication};
use rustical_store::calendar::CalendarStore;
use thiserror::Error;
#[derive(Debug, Error)]
pub enum Error {
#[error("invalid propfind request: {0}")]
InvalidPropfind(&'static str),
#[error("input is not valid xml")]
ParsingError(#[from] roxmltree::Error),
#[error(transparent)]
Other(#[from] anyhow::Error),
}
impl actix_web::error::ResponseError for Error {
fn status_code(&self) -> actix_web::http::StatusCode {
match self {
Self::InvalidPropfind(_) => StatusCode::BAD_REQUEST,
Self::ParsingError(_) => StatusCode::BAD_REQUEST,
Self::Other(_) => StatusCode::INTERNAL_SERVER_ERROR,
}
}
fn error_response(&self) -> HttpResponse<actix_web::body::BoxBody> {
HttpResponse::build(self.status_code()).body(self.to_string())
}
}
fn parse_propfind(body: &str) -> Result<Vec<&str>, Error> {
if body.is_empty() {
// if body is empty, allprops must be returned (RFC 4918)
return Ok(vec!["allprops"]);
}
let doc = roxmltree::Document::parse(body)?;
let propfind_node = doc.root_element();
if propfind_node.tag_name().name() != "propfind" {
return Err(Error::InvalidPropfind("root tag is not <propfind>"));
}
let prop_node = if let Some(el) = propfind_node.first_element_child() {
el
} else {
return Ok(Vec::new());
};
match prop_node.tag_name().name() {
"prop" => Ok(prop_node
.children()
.map(|node| node.tag_name().name())
.collect()),
_ => Err(Error::InvalidPropfind(
"invalid tag in <propfind>, expected <prop>",
)),
}
}
pub async fn route_propfind<A: CheckAuthentication, R: Resource, C: CalendarStore>(
path: Path<R::UriComponents>,
body: String,
req: HttpRequest,
context: Data<CalDavContext<C>>,
auth: AuthInfoExtractor<A>,
depth: Depth,
) -> Result<HttpResponse, Error> {
let props = parse_propfind(&body)?;
// let req_path = req.path().to_string();
let auth_info = auth.inner;
let resource = R::acquire_from_request(
req,
auth_info,
path.into_inner(),
context.prefix.to_string(),
)
.await?;
let mut responses = vec![resource.propfind(props.clone())?];
if depth != Depth::Zero {
for member in resource.get_members().await? {
responses.push(member.propfind(props.clone())?);
}
}
let output = generate_multistatus(
vec![Namespace::Dav, Namespace::CalDAV, Namespace::ICal],
|writer| {
for response in responses {
writer.write_event(quick_xml::events::Event::Text(BytesText::from_escaped(
response,
)))?;
}
Ok(())
},
)?;
Ok(HttpResponse::MultiStatus()
.content_type(ContentType::xml())
.body(output))
}