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