rustical_dav/resource/
mod.rs

1use crate::Principal;
2use crate::privileges::UserPrivilegeSet;
3use crate::xml::multistatus::{PropTagWrapper, PropstatElement, PropstatWrapper};
4use crate::xml::{PropElement, PropfindElement, PropfindType, Resourcetype};
5use crate::xml::{TagList, multistatus::ResponseElement};
6use headers::{ETag, IfMatch, IfNoneMatch};
7use http::StatusCode;
8use itertools::Itertools;
9use quick_xml::name::Namespace;
10pub use resource_service::ResourceService;
11use rustical_xml::{
12    EnumVariants, NamespaceOwned, PropName, XmlDeserialize, XmlDocument, XmlSerialize,
13};
14use std::str::FromStr;
15
16mod axum_methods;
17mod axum_service;
18mod methods;
19mod principal_uri;
20mod resource_service;
21
22pub use axum_methods::{AxumMethods, MethodFunction};
23pub use axum_service::AxumService;
24pub use principal_uri::PrincipalUri;
25
26pub trait ResourceProp: XmlSerialize + XmlDeserialize {}
27impl<T: XmlSerialize + XmlDeserialize> ResourceProp for T {}
28
29pub trait ResourcePropName: FromStr {}
30impl<T: FromStr> ResourcePropName for T {}
31
32pub trait ResourceName {
33    fn get_name(&self) -> String;
34}
35
36pub trait Resource: Clone + Send + 'static {
37    type Prop: ResourceProp + PartialEq + Clone + EnumVariants + PropName + Send;
38    type Error: From<crate::Error>;
39    type Principal: Principal;
40
41    fn is_collection(&self) -> bool;
42
43    fn get_resourcetype(&self) -> Resourcetype;
44
45    fn list_props() -> Vec<(Option<Namespace<'static>>, &'static str)> {
46        Self::Prop::variant_names()
47    }
48
49    fn get_prop(
50        &self,
51        principal_uri: &impl PrincipalUri,
52        principal: &Self::Principal,
53        prop: &<Self::Prop as PropName>::Names,
54    ) -> Result<Self::Prop, Self::Error>;
55
56    fn set_prop(&mut self, _prop: Self::Prop) -> Result<(), crate::Error> {
57        Err(crate::Error::PropReadOnly)
58    }
59
60    fn remove_prop(&mut self, _prop: &<Self::Prop as PropName>::Names) -> Result<(), crate::Error> {
61        Err(crate::Error::PropReadOnly)
62    }
63
64    fn get_displayname(&self) -> Option<&str>;
65    fn set_displayname(&mut self, _name: Option<String>) -> Result<(), crate::Error> {
66        Err(crate::Error::PropReadOnly)
67    }
68
69    fn get_owner(&self) -> Option<&str> {
70        None
71    }
72
73    fn get_etag(&self) -> Option<String> {
74        None
75    }
76
77    fn satisfies_if_match(&self, if_match: &IfMatch) -> bool {
78        if let Some(etag) = self.get_etag() {
79            if let Ok(etag) = ETag::from_str(&etag) {
80                if_match.precondition_passes(&etag)
81            } else {
82                if_match.is_any()
83            }
84        } else {
85            if_match.is_any()
86        }
87    }
88
89    fn satisfies_if_none_match(&self, if_none_match: &IfNoneMatch) -> bool {
90        if let Some(etag) = self.get_etag() {
91            if let Ok(etag) = ETag::from_str(&etag) {
92                if_none_match.precondition_passes(&etag)
93            } else {
94                if_none_match != &IfNoneMatch::any()
95            }
96        } else {
97            if_none_match != &IfNoneMatch::any()
98        }
99    }
100
101    fn get_user_privileges(
102        &self,
103        principal: &Self::Principal,
104    ) -> Result<UserPrivilegeSet, Self::Error>;
105
106    fn parse_propfind(
107        body: &str,
108    ) -> Result<PropfindElement<<Self::Prop as PropName>::Names>, rustical_xml::XmlError> {
109        if !body.is_empty() {
110            PropfindElement::parse_str(body)
111        } else {
112            Ok(PropfindElement {
113                prop: PropfindType::Allprop,
114                include: None,
115            })
116        }
117    }
118
119    fn propfind(
120        &self,
121        path: &str,
122        prop: &PropfindType<<Self::Prop as PropName>::Names>,
123        include: Option<&PropElement<<Self::Prop as PropName>::Names>>,
124        principal_uri: &impl PrincipalUri,
125        principal: &Self::Principal,
126    ) -> Result<ResponseElement<Self::Prop>, Self::Error> {
127        // Collections have a trailing slash
128        let mut path = path.to_string();
129        if self.is_collection() && !path.ends_with('/') {
130            path.push('/');
131        }
132
133        let (mut props, mut invalid_props): (Vec<<Self::Prop as PropName>::Names>, Vec<_>) =
134            match prop {
135                PropfindType::Propname => {
136                    let props = Self::list_props()
137                        .into_iter()
138                        .map(|(ns, tag)| (ns.map(NamespaceOwned::from), tag.to_string()))
139                        .collect_vec();
140
141                    return Ok(ResponseElement {
142                        href: path.to_owned(),
143                        propstat: vec![PropstatWrapper::TagList(PropstatElement {
144                            prop: TagList::from(props),
145                            status: StatusCode::OK,
146                        })],
147                        ..Default::default()
148                    });
149                }
150                PropfindType::Allprop => (
151                    Self::list_props()
152                        .iter()
153                        .map(|(_ns, name)| <Self::Prop as PropName>::Names::from_str(name).unwrap())
154                        .collect(),
155                    vec![],
156                ),
157                PropfindType::Prop(PropElement(valid_tags, invalid_tags)) => (
158                    valid_tags.iter().unique().cloned().collect(),
159                    invalid_tags.to_owned(),
160                ),
161            };
162
163        if let Some(PropElement(valid_tags, invalid_tags)) = include {
164            props.extend(valid_tags.clone());
165            invalid_props.extend(invalid_tags.to_owned());
166        }
167
168        let prop_responses = props
169            .into_iter()
170            .map(|prop| self.get_prop(principal_uri, principal, &prop))
171            .collect::<Result<Vec<_>, Self::Error>>()?;
172
173        let mut propstats = vec![PropstatWrapper::Normal(PropstatElement {
174            status: StatusCode::OK,
175            prop: PropTagWrapper(prop_responses),
176        })];
177        if !invalid_props.is_empty() {
178            propstats.push(PropstatWrapper::TagList(PropstatElement {
179                status: StatusCode::NOT_FOUND,
180                prop: invalid_props.into(),
181            }));
182        }
183        Ok(ResponseElement {
184            href: path.to_owned(),
185            propstat: propstats,
186            ..Default::default()
187        })
188    }
189}