mirror of
https://github.com/lennart-k/rustical.git
synced 2025-12-14 07:02:24 +00:00
refactor(caldav)
This commit is contained in:
2
crates/caldav/src/calendar/mod.rs
Normal file
2
crates/caldav/src/calendar/mod.rs
Normal file
@@ -0,0 +1,2 @@
|
||||
pub mod resource;
|
||||
pub mod route;
|
||||
261
crates/caldav/src/calendar/resource.rs
Normal file
261
crates/caldav/src/calendar/resource.rs
Normal file
@@ -0,0 +1,261 @@
|
||||
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::{HrefElement, TextNode};
|
||||
use rustical_store::calendar::{Calendar, CalendarStore};
|
||||
use serde::Serialize;
|
||||
use std::sync::Arc;
|
||||
use strum::{EnumString, IntoStaticStr, VariantNames};
|
||||
use tokio::sync::RwLock;
|
||||
|
||||
pub struct CalendarResource<C: CalendarStore + ?Sized> {
|
||||
pub cal_store: Arc<RwLock<C>>,
|
||||
pub path: String,
|
||||
pub principal: String,
|
||||
pub calendar_id: String,
|
||||
}
|
||||
|
||||
#[derive(Serialize)]
|
||||
#[serde(rename_all = "kebab-case")]
|
||||
pub struct SupportedCalendarComponent {
|
||||
#[serde(rename = "@name")]
|
||||
pub name: &'static str,
|
||||
}
|
||||
|
||||
#[derive(Serialize)]
|
||||
#[serde(rename_all = "kebab-case")]
|
||||
pub struct SupportedCalendarComponentSet {
|
||||
#[serde(rename = "C:comp")]
|
||||
pub comp: Vec<SupportedCalendarComponent>,
|
||||
}
|
||||
|
||||
#[derive(Serialize)]
|
||||
#[serde(rename_all = "kebab-case")]
|
||||
pub struct CalendarData {
|
||||
#[serde(rename = "@content-type")]
|
||||
content_type: &'static str,
|
||||
#[serde(rename = "@version")]
|
||||
version: &'static str,
|
||||
}
|
||||
|
||||
impl Default for CalendarData {
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
content_type: "text/calendar",
|
||||
version: "2.0",
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Serialize, Default)]
|
||||
#[serde(rename_all = "kebab-case")]
|
||||
pub struct SupportedCalendarData {
|
||||
#[serde(rename = "C:calendar-data")]
|
||||
calendar_data: CalendarData,
|
||||
}
|
||||
|
||||
#[derive(Serialize, Default)]
|
||||
#[serde(rename_all = "kebab-case")]
|
||||
pub struct Resourcetype {
|
||||
#[serde(rename = "C:calendar")]
|
||||
calendar: (),
|
||||
collection: (),
|
||||
}
|
||||
|
||||
#[derive(Serialize)]
|
||||
#[serde(rename_all = "kebab-case")]
|
||||
pub enum UserPrivilege {
|
||||
Read,
|
||||
ReadAcl,
|
||||
Write,
|
||||
WriteAcl,
|
||||
WriteContent,
|
||||
ReadCurrentUserPrivilegeSet,
|
||||
Bind,
|
||||
Unbind,
|
||||
}
|
||||
|
||||
#[derive(Serialize)]
|
||||
#[serde(rename_all = "kebab-case")]
|
||||
pub struct UserPrivilegeWrapper {
|
||||
#[serde(rename = "$value")]
|
||||
privilege: UserPrivilege,
|
||||
}
|
||||
|
||||
impl From<UserPrivilege> for UserPrivilegeWrapper {
|
||||
fn from(value: UserPrivilege) -> Self {
|
||||
Self { privilege: value }
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Serialize)]
|
||||
#[serde(rename_all = "kebab-case")]
|
||||
pub struct UserPrivilegeSet {
|
||||
privilege: Vec<UserPrivilegeWrapper>,
|
||||
}
|
||||
|
||||
impl Default for UserPrivilegeSet {
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
privilege: vec![
|
||||
UserPrivilege::Read.into(),
|
||||
UserPrivilege::ReadAcl.into(),
|
||||
UserPrivilege::Write.into(),
|
||||
UserPrivilege::WriteAcl.into(),
|
||||
UserPrivilege::WriteContent.into(),
|
||||
UserPrivilege::ReadCurrentUserPrivilegeSet.into(),
|
||||
UserPrivilege::Bind.into(),
|
||||
UserPrivilege::Unbind.into(),
|
||||
],
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(EnumString, Debug, VariantNames, IntoStaticStr, Clone)]
|
||||
#[strum(serialize_all = "kebab-case")]
|
||||
pub enum CalendarProp {
|
||||
Resourcetype,
|
||||
CurrentUserPrincipal,
|
||||
Owner,
|
||||
Displayname,
|
||||
CalendarColor,
|
||||
CalendarDescription,
|
||||
SupportedCalendarComponentSet,
|
||||
SupportedCalendarData,
|
||||
Getcontenttype,
|
||||
CurrentUserPrivilegeSet,
|
||||
MaxResourceSize,
|
||||
}
|
||||
|
||||
#[derive(Serialize)]
|
||||
#[serde(rename_all = "kebab-case")]
|
||||
pub enum CalendarPropResponse {
|
||||
Resourcetype(Resourcetype),
|
||||
CurrentUserPrincipal(HrefElement),
|
||||
Owner(HrefElement),
|
||||
Displayname(TextNode),
|
||||
#[serde(rename = "IC:calendar-color", alias = "calendar-color")]
|
||||
CalendarColor(TextNode),
|
||||
#[serde(rename = "C:calendar-description", alias = "calendar-description")]
|
||||
CalendarDescription(TextNode),
|
||||
#[serde(
|
||||
rename = "C:supported-calendar-component-set",
|
||||
alias = "supported-calendar-component-set"
|
||||
)]
|
||||
SupportedCalendarComponentSet(SupportedCalendarComponentSet),
|
||||
#[serde(
|
||||
rename = "C:supported-calendar-data",
|
||||
alias = "supported-calendar-data"
|
||||
)]
|
||||
SupportedCalendarData(SupportedCalendarData),
|
||||
Getcontenttype(TextNode),
|
||||
MaxResourceSize(TextNode),
|
||||
CurrentUserPrivilegeSet(UserPrivilegeSet),
|
||||
}
|
||||
|
||||
pub struct CalendarFile {
|
||||
pub calendar: Calendar,
|
||||
pub principal: String,
|
||||
pub path: String,
|
||||
}
|
||||
|
||||
impl Resource for CalendarFile {
|
||||
type PropType = CalendarProp;
|
||||
type PropResponse = CalendarPropResponse;
|
||||
|
||||
fn get_prop(&self, prefix: &str, prop: Self::PropType) -> Result<Self::PropResponse> {
|
||||
match prop {
|
||||
CalendarProp::Resourcetype => {
|
||||
Ok(CalendarPropResponse::Resourcetype(Resourcetype::default()))
|
||||
}
|
||||
CalendarProp::CurrentUserPrincipal => Ok(CalendarPropResponse::CurrentUserPrincipal(
|
||||
HrefElement::new(format!("{}/{}/", prefix, self.principal)),
|
||||
)),
|
||||
CalendarProp::Owner => Ok(CalendarPropResponse::Owner(HrefElement::new(format!(
|
||||
"{}/{}/",
|
||||
prefix, self.principal
|
||||
)))),
|
||||
CalendarProp::Displayname => Ok(CalendarPropResponse::Displayname(TextNode(
|
||||
self.calendar.name.clone(),
|
||||
))),
|
||||
CalendarProp::CalendarColor => Ok(CalendarPropResponse::CalendarColor(TextNode(
|
||||
self.calendar.color.clone(),
|
||||
))),
|
||||
CalendarProp::CalendarDescription => Ok(CalendarPropResponse::CalendarDescription(
|
||||
TextNode(self.calendar.description.clone()),
|
||||
)),
|
||||
CalendarProp::SupportedCalendarComponentSet => {
|
||||
Ok(CalendarPropResponse::SupportedCalendarComponentSet(
|
||||
SupportedCalendarComponentSet {
|
||||
comp: vec![SupportedCalendarComponent { name: "VEVENT" }],
|
||||
},
|
||||
))
|
||||
}
|
||||
CalendarProp::SupportedCalendarData => Ok(CalendarPropResponse::SupportedCalendarData(
|
||||
SupportedCalendarData::default(),
|
||||
)),
|
||||
CalendarProp::Getcontenttype => Ok(CalendarPropResponse::Getcontenttype(TextNode(
|
||||
Some("text/calendar;charset=utf-8".to_owned()),
|
||||
))),
|
||||
CalendarProp::MaxResourceSize => Ok(CalendarPropResponse::MaxResourceSize(TextNode(
|
||||
Some("10000000".to_owned()),
|
||||
))),
|
||||
CalendarProp::CurrentUserPrivilegeSet => Ok(
|
||||
CalendarPropResponse::CurrentUserPrivilegeSet(UserPrivilegeSet::default()),
|
||||
),
|
||||
}
|
||||
}
|
||||
|
||||
fn get_path(&self) -> &str {
|
||||
&self.path
|
||||
}
|
||||
}
|
||||
|
||||
#[async_trait(?Send)]
|
||||
impl<C: CalendarStore + ?Sized> ResourceService for CalendarResource<C> {
|
||||
type MemberType = CalendarFile;
|
||||
type PathComponents = (String, String); // principal, calendar_id
|
||||
type File = CalendarFile;
|
||||
|
||||
async fn get_file(&self) -> Result<Self::File> {
|
||||
let calendar = self
|
||||
.cal_store
|
||||
.read()
|
||||
.await
|
||||
.get_calendar(&self.calendar_id)
|
||||
.await
|
||||
.map_err(|_e| Error::NotFound)?;
|
||||
Ok(CalendarFile {
|
||||
calendar,
|
||||
principal: self.principal.to_owned(),
|
||||
path: self.path.to_owned(),
|
||||
})
|
||||
}
|
||||
|
||||
async fn get_members(&self, _auth_info: AuthInfo) -> Result<Vec<Self::MemberType>> {
|
||||
// As of now the calendar resource has no members since events are shown with REPORT
|
||||
Ok(vec![])
|
||||
}
|
||||
|
||||
async fn new(
|
||||
req: HttpRequest,
|
||||
auth_info: AuthInfo,
|
||||
path_components: Self::PathComponents,
|
||||
) -> Result<Self, rustical_dav::error::Error> {
|
||||
let cal_store = req
|
||||
.app_data::<Data<RwLock<C>>>()
|
||||
.ok_or(anyhow!("no calendar store in app_data!"))?
|
||||
.clone()
|
||||
.into_inner();
|
||||
|
||||
Ok(Self {
|
||||
path: req.path().to_owned(),
|
||||
principal: auth_info.user_id,
|
||||
calendar_id: path_components.1,
|
||||
cal_store,
|
||||
})
|
||||
}
|
||||
}
|
||||
196
crates/caldav/src/calendar/route.rs
Normal file
196
crates/caldav/src/calendar/route.rs
Normal file
@@ -0,0 +1,196 @@
|
||||
use crate::resources::event::EventFile;
|
||||
use crate::CalDavContext;
|
||||
use crate::Error;
|
||||
use actix_web::http::header::ContentType;
|
||||
use actix_web::web::{Data, Path};
|
||||
use actix_web::HttpResponse;
|
||||
use anyhow::Result;
|
||||
use roxmltree::{Node, NodeType};
|
||||
use rustical_auth::{AuthInfoExtractor, CheckAuthentication};
|
||||
use rustical_dav::namespace::Namespace;
|
||||
use rustical_dav::propfind::ServicePrefix;
|
||||
use rustical_dav::resource::HandlePropfind;
|
||||
use rustical_dav::xml_snippets::generate_multistatus;
|
||||
use rustical_store::calendar::{Calendar, CalendarStore};
|
||||
use rustical_store::event::Event;
|
||||
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(
|
||||
query_node: Node<'_, '_>,
|
||||
events: Vec<Event>,
|
||||
prefix: &str,
|
||||
) -> 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 event_files: Vec<_> = events
|
||||
.into_iter()
|
||||
.map(|event| {
|
||||
// TODO: fix
|
||||
// let path = format!("{}/{}", request.path(), event.get_uid());
|
||||
EventFile {
|
||||
event, // cal_store: cal_store.clone(),
|
||||
}
|
||||
})
|
||||
.collect();
|
||||
let mut event_responses = Vec::new();
|
||||
for event_file in event_files {
|
||||
event_responses.push(event_file.propfind(prefix, props.clone()).await?);
|
||||
}
|
||||
// let event_results: Result<Vec<_>, _> = event_files
|
||||
// .iter()
|
||||
// .map(|ev| ev.propfind(props.clone()))
|
||||
// .collect();
|
||||
// let event_responses = event_results?;
|
||||
|
||||
let output = generate_multistatus(vec![Namespace::Dav, Namespace::CalDAV], |writer| {
|
||||
for result in event_responses {
|
||||
writer
|
||||
.write_serializable("response", &result)
|
||||
.map_err(|_e| quick_xml::Error::TextNotFound)?;
|
||||
}
|
||||
Ok(())
|
||||
})?;
|
||||
|
||||
Ok(HttpResponse::MultiStatus()
|
||||
.content_type(ContentType::xml())
|
||||
.body(output))
|
||||
}
|
||||
|
||||
pub async fn route_report_calendar<A: CheckAuthentication, C: CalendarStore + ?Sized>(
|
||||
context: Data<CalDavContext<C>>,
|
||||
body: String,
|
||||
path: Path<(String, String)>,
|
||||
_auth: AuthInfoExtractor<A>,
|
||||
prefix: Data<ServicePrefix>,
|
||||
) -> Result<HttpResponse, Error> {
|
||||
// TODO: Check authorization
|
||||
let (_principal, cid) = path.into_inner();
|
||||
let prefix = &prefix.0;
|
||||
|
||||
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();
|
||||
|
||||
// TODO: implement filtering
|
||||
match query_node.tag_name().name() {
|
||||
"calendar-query" => {}
|
||||
"calendar-multiget" => {}
|
||||
_ => return Err(Error::BadRequest),
|
||||
};
|
||||
handle_report_calendar_query(query_node, events, prefix).await
|
||||
}
|
||||
|
||||
pub async fn handle_mkcol_calendar_set<C: CalendarStore + ?Sized>(
|
||||
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(str::to_string);
|
||||
}
|
||||
"timezone" => {
|
||||
cal.timezone = prop.text().map(str::to_string);
|
||||
}
|
||||
"calendar-color" => {
|
||||
cal.color = prop.text().map(str::to_string);
|
||||
}
|
||||
"calendar-description" => {
|
||||
cal.description = prop.text().map(str::to_string);
|
||||
}
|
||||
"calendar-timezone" => {
|
||||
cal.timezone = prop.text().map(str::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 + ?Sized>(
|
||||
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?;
|
||||
|
||||
Ok(HttpResponse::Created().body(""))
|
||||
}
|
||||
|
||||
pub async fn delete_calendar<A: CheckAuthentication, C: CalendarStore + ?Sized>(
|
||||
context: Data<CalDavContext<C>>,
|
||||
path: Path<(String, String)>,
|
||||
auth: AuthInfoExtractor<A>,
|
||||
) -> Result<HttpResponse, Error> {
|
||||
let _user = auth.inner.user_id;
|
||||
// TODO: verify whether user is authorized
|
||||
let (_principal, cid) = path.into_inner();
|
||||
context.store.write().await.delete_calendar(&cid).await?;
|
||||
|
||||
Ok(HttpResponse::Ok().body(""))
|
||||
}
|
||||
Reference in New Issue
Block a user