mirror of
https://github.com/lennart-k/rustical.git
synced 2025-12-14 11:42:25 +00:00
Refactoring: Lots of fixes still necessary to get it into a working state
This commit is contained in:
131
crates/dav/src/dav_resource.rs
Normal file
131
crates/dav/src/dav_resource.rs
Normal file
@@ -0,0 +1,131 @@
|
||||
use crate::{error::Error, xml_snippets::TagList};
|
||||
use actix_web::{http::StatusCode, HttpRequest};
|
||||
use anyhow::{anyhow, Result};
|
||||
use async_trait::async_trait;
|
||||
use itertools::Itertools;
|
||||
use rustical_auth::AuthInfo;
|
||||
use serde::Serialize;
|
||||
use std::str::FromStr;
|
||||
use strum::VariantNames;
|
||||
|
||||
#[async_trait(?Send)]
|
||||
pub trait Resource {
|
||||
type PropType: FromStr + VariantNames + Into<&'static str> + Clone;
|
||||
type PropResponse: Serialize;
|
||||
|
||||
fn list_dead_props() -> &'static [&'static str] {
|
||||
Self::PropType::VARIANTS
|
||||
}
|
||||
|
||||
fn get_prop(&self, prop: Self::PropType) -> Result<Self::PropResponse>;
|
||||
|
||||
fn get_path(&self) -> &str;
|
||||
}
|
||||
|
||||
// A resource is identified by a URI and has properties
|
||||
// A resource can also be a collection
|
||||
// A resource cannot be none, only Methods like PROPFIND, GET, REPORT, etc. can be exposed
|
||||
// A resource exists
|
||||
#[async_trait(?Send)]
|
||||
pub trait ResourceService: Sized {
|
||||
type MemberType: Resource;
|
||||
type PathComponents: Sized + Clone; // defines how the resource URI maps to parameters, i.e. /{principal}/{calendar} -> (String, String)
|
||||
type File: Resource;
|
||||
|
||||
async fn new(
|
||||
req: HttpRequest,
|
||||
auth_info: AuthInfo,
|
||||
path_components: Self::PathComponents,
|
||||
prefix: String,
|
||||
) -> Result<Self, Error>;
|
||||
|
||||
async fn get_file(&self) -> Result<Self::File>;
|
||||
|
||||
async fn get_members(
|
||||
&self,
|
||||
auth_info: AuthInfo,
|
||||
path_components: Self::PathComponents,
|
||||
) -> Result<Vec<Self::MemberType>>;
|
||||
}
|
||||
|
||||
#[derive(Serialize)]
|
||||
pub struct PropWrapper<T: Serialize> {
|
||||
#[serde(rename = "$value")]
|
||||
prop: T,
|
||||
}
|
||||
|
||||
#[derive(Serialize)]
|
||||
#[serde(rename_all = "kebab-case")]
|
||||
struct PropstatElement<T: Serialize> {
|
||||
prop: T,
|
||||
status: String,
|
||||
}
|
||||
|
||||
#[derive(Serialize)]
|
||||
#[serde(rename_all = "kebab-case")]
|
||||
pub struct PropstatResponseElement<T1: Serialize, T2: Serialize> {
|
||||
href: String,
|
||||
propstat: Vec<PropstatType<T1, T2>>,
|
||||
}
|
||||
|
||||
#[derive(Serialize)]
|
||||
#[serde(untagged)]
|
||||
enum PropstatType<T1: Serialize, T2: Serialize> {
|
||||
Normal(PropstatElement<T1>),
|
||||
NotFound(PropstatElement<T2>),
|
||||
}
|
||||
|
||||
#[async_trait(?Send)]
|
||||
pub trait HandlePropfind {
|
||||
async fn propfind(&self, props: Vec<&str>) -> Result<impl Serialize>;
|
||||
}
|
||||
|
||||
#[async_trait(?Send)]
|
||||
impl<R: Resource> HandlePropfind for R {
|
||||
async fn propfind(
|
||||
&self,
|
||||
props: Vec<&str>,
|
||||
) -> Result<PropstatResponseElement<PropWrapper<Vec<R::PropResponse>>, TagList>> {
|
||||
let mut props = props.into_iter().unique().collect_vec();
|
||||
if props.contains(&"allprops") {
|
||||
if props.len() != 1 {
|
||||
// allprops MUST be the only queried prop per spec
|
||||
return Err(anyhow!("allprops MUST be the only queried prop"));
|
||||
}
|
||||
props = R::list_dead_props().into();
|
||||
}
|
||||
|
||||
let mut invalid_props = Vec::<&str>::new();
|
||||
let mut prop_responses = Vec::new();
|
||||
for prop in props {
|
||||
if let Ok(valid_prop) = R::PropType::from_str(prop) {
|
||||
match self.get_prop(valid_prop.clone()) {
|
||||
Ok(response) => {
|
||||
prop_responses.push(response);
|
||||
}
|
||||
Err(_) => invalid_props.push(prop),
|
||||
}
|
||||
} else {
|
||||
invalid_props.push(prop);
|
||||
}
|
||||
}
|
||||
|
||||
let mut propstats = Vec::new();
|
||||
propstats.push(PropstatType::Normal(PropstatElement {
|
||||
status: format!("HTTP/1.1 {}", StatusCode::OK),
|
||||
prop: PropWrapper {
|
||||
prop: prop_responses,
|
||||
},
|
||||
}));
|
||||
if !invalid_props.is_empty() {
|
||||
propstats.push(PropstatType::NotFound(PropstatElement {
|
||||
status: format!("HTTP/1.1 {}", StatusCode::NOT_FOUND),
|
||||
prop: TagList(invalid_props.iter().map(|&s| s.to_owned()).collect()),
|
||||
}));
|
||||
}
|
||||
Ok(PropstatResponseElement {
|
||||
href: self.get_path().to_owned(),
|
||||
propstat: propstats,
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -1,5 +1,7 @@
|
||||
pub mod dav_resource;
|
||||
pub mod depth_extractor;
|
||||
pub mod error;
|
||||
pub mod namespace;
|
||||
pub mod propfind;
|
||||
pub mod resource;
|
||||
pub mod xml_snippets;
|
||||
|
||||
137
crates/dav/src/propfind.rs
Normal file
137
crates/dav/src/propfind.rs
Normal file
@@ -0,0 +1,137 @@
|
||||
use crate::dav_resource::HandlePropfind;
|
||||
use crate::dav_resource::ResourceService;
|
||||
use crate::depth_extractor::Depth;
|
||||
use crate::namespace::Namespace;
|
||||
use crate::xml_snippets::generate_multistatus;
|
||||
use actix_web::http::header::ContentType;
|
||||
use actix_web::http::StatusCode;
|
||||
use actix_web::web::{Data, Path};
|
||||
use actix_web::{HttpRequest, HttpResponse};
|
||||
use anyhow::{anyhow, Result};
|
||||
use rustical_auth::{AuthInfoExtractor, CheckAuthentication};
|
||||
use serde::Serialize;
|
||||
use thiserror::Error;
|
||||
|
||||
// This is not the final place for this struct
|
||||
pub struct ServicePrefix(pub String);
|
||||
|
||||
#[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())
|
||||
}
|
||||
}
|
||||
|
||||
pub 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()
|
||||
.filter(|node| node.is_element())
|
||||
.map(|node| node.tag_name().name())
|
||||
.collect()),
|
||||
_ => Err(Error::InvalidPropfind(
|
||||
"invalid tag in <propfind>, expected <prop>",
|
||||
)),
|
||||
}
|
||||
}
|
||||
|
||||
pub async fn handle_propfind<
|
||||
A: CheckAuthentication,
|
||||
R: ResourceService + ?Sized,
|
||||
// C: CalendarStore + ?Sized,
|
||||
>(
|
||||
path: Path<R::PathComponents>,
|
||||
body: String,
|
||||
req: HttpRequest,
|
||||
prefix: Data<ServicePrefix>,
|
||||
auth: AuthInfoExtractor<A>,
|
||||
depth: Depth,
|
||||
) -> Result<HttpResponse, crate::error::Error> {
|
||||
// TODO: fix errors
|
||||
let props = parse_propfind(&body).map_err(|_e| anyhow!("propfind parsing error"))?;
|
||||
let auth_info = auth.inner;
|
||||
let prefix = prefix.0.to_owned();
|
||||
let path_components = path.into_inner();
|
||||
|
||||
let resource_service = R::new(req, auth_info.clone(), path_components.clone(), prefix).await?;
|
||||
|
||||
let resource = resource_service.get_file().await?;
|
||||
let response = resource.propfind(props.clone()).await?;
|
||||
let mut member_responses = Vec::new();
|
||||
|
||||
if depth != Depth::Zero {
|
||||
for member in resource_service
|
||||
.get_members(auth_info, path_components)
|
||||
.await?
|
||||
{
|
||||
member_responses.push(member.propfind(props.clone()).await?);
|
||||
}
|
||||
}
|
||||
|
||||
let output = generate_multistatus(
|
||||
vec![Namespace::Dav, Namespace::CalDAV, Namespace::ICal],
|
||||
|writer| {
|
||||
writer
|
||||
.write_serializable("response", &response)
|
||||
.map_err(|_e| quick_xml::Error::TextNotFound)?;
|
||||
for response in member_responses {
|
||||
writer
|
||||
.write_serializable("response", &response)
|
||||
.map_err(|_e| quick_xml::Error::TextNotFound)?;
|
||||
}
|
||||
Ok(())
|
||||
},
|
||||
)?;
|
||||
|
||||
Ok(HttpResponse::MultiStatus()
|
||||
.content_type(ContentType::xml())
|
||||
.body(output))
|
||||
}
|
||||
|
||||
#[derive(Serialize)]
|
||||
struct MultistatusElement<T1: Serialize, T2: Serialize> {
|
||||
#[serde(rename = "$value")]
|
||||
responses: Vec<T1>,
|
||||
#[serde(rename = "$value")]
|
||||
member_responses: Vec<T2>,
|
||||
#[serde(rename = "@xmlns")]
|
||||
ns_dav: &'static str,
|
||||
#[serde(rename = "@xmlns:C")]
|
||||
ns_caldav: &'static str,
|
||||
#[serde(rename = "@xmlns:IC")]
|
||||
ns_ical: &'static str,
|
||||
}
|
||||
@@ -13,8 +13,8 @@ use strum::VariantNames;
|
||||
// A resource cannot be none, only Methods like PROPFIND, GET, REPORT, etc. can be exposed
|
||||
// A resource exists
|
||||
#[async_trait(?Send)]
|
||||
pub trait Resource: Sized {
|
||||
type MemberType: Resource;
|
||||
pub trait OldResource: Sized {
|
||||
type MemberType: OldResource;
|
||||
type UriComponents: Sized; // defines how the resource URI maps to parameters, i.e. /{principal}/{calendar} -> (String, String)
|
||||
type PropType: FromStr + VariantNames + Into<&'static str> + Clone;
|
||||
type PropResponse: Serialize;
|
||||
@@ -66,7 +66,7 @@ pub trait HandlePropfind {
|
||||
fn propfind(&self, props: Vec<&str>) -> Result<impl Serialize>;
|
||||
}
|
||||
|
||||
impl<R: Resource> HandlePropfind for R {
|
||||
impl<R: OldResource> HandlePropfind for R {
|
||||
fn propfind(&self, props: Vec<&str>) -> Result<impl Serialize> {
|
||||
let mut props = props.into_iter().unique().collect_vec();
|
||||
if props.contains(&"allprops") {
|
||||
|
||||
Reference in New Issue
Block a user