webdav_request/client/
mod.rs

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
mod inner;
use std::future::Future;
use std::sync::Arc;

use crate::method::Method;
use crate::reader::LazyResponseReader;
use crate::res::Collection;
use crate::res::MultiStatus;
use crate::{header::HeaderMap, Body};
pub use inner::InnerClient;
use reqwest::header::{HeaderName, HeaderValue, CONTENT_TYPE};
use reqwest::IntoUrl;
use reqwest::Response;
use reqwest::Url;

macro_rules! header_value {
    ($arg:expr) => {
        reqwest::header::HeaderValue::from_bytes($arg.as_bytes()).unwrap()
    };
}
macro_rules! header_name {
    ($arg:expr) => {
        reqwest::header::HeaderName::from_bytes($arg.as_bytes()).unwrap()
    };
}

const ALL_DROP: &str = r#"<?xml version="1.0" encoding="utf-8" ?>
    <D:propfind xmlns:D="DAV:">
        <D:allprop/>
    </D:propfind>
"#;
#[derive(Default, Clone)]
pub struct WebDAVClient {
    inner: Arc<InnerClient>,
}
unsafe impl Send for WebDAVClient {}

unsafe impl Sync for WebDAVClient {}

macro_rules! into_url {
    ($url:expr) => {
        match $url.into_url() {
            Ok(url) => url,
            Err(e) => panic!("{e}")
        }
    };
}

impl WebDAVClient {
    pub fn new(username: &str, password: &str) -> Result<Self, reqwest::Error> {
        Ok(Self {
            inner: Arc::new(InnerClient::new(username, password)?),
        })
    }
    pub fn request(&self, method: Method, url: impl IntoUrl) -> WevDAVRequestBuilder {
        WevDAVRequestBuilder::new(self.inner.clone(), into_url!(url), method)
    }

    #[inline(always)]
    pub fn get(&self, url: impl IntoUrl) -> WevDAVRequestBuilder {
        self.request(Method::GET, url)
    }

    pub fn put(&self, url: impl IntoUrl) -> WevDAVRequestBuilder {
        self.request(Method::PUT, url)
    }

    pub async fn list(&self, url: impl IntoUrl) -> Result<Collection, crate::error::Error> {
        let response = self.all_propfind(url).await?;
        if response.status().is_success() {
            let xml = response.text().await?;
            let multi_status = MultiStatus::parse(&xml)?;
            Ok(Collection::from(multi_status))
        } else {
            Err(crate::error::Error::ResponseError(response.status()))
        }
    }
    #[inline(always)]
    pub async fn all_propfind(
        &self,
        url: impl IntoUrl,
    ) -> Result<Response, crate::error::Error> {
        self.request(Method::PROPFIND, url.into_url()?)
            .header(CONTENT_TYPE, HeaderValue::from_static("application/xml"))
            .header(header_name!("depth"), header_value!("1"))
            .body(ALL_DROP)
            .send().await.map_err(Into::into)
    }
}

pub struct WevDAVRequestBuilder {
    client: Arc<InnerClient>,
    basic_auth: Option<(String, String)>,
    url: Url,
    headers: HeaderMap,
    body: Option<Body>,
    method: Method,
}

impl WevDAVRequestBuilder {
    pub fn new(client: Arc<InnerClient>, url: Url, method: Method) -> Self {
        Self {
            client,
            basic_auth: None,
            headers: HeaderMap::new(),
            url,
            method,
            body: None,
        }
    }
    pub fn basic_auth(self, username: &str, password: &str) -> Self {
        Self {
            basic_auth: Some((username.to_owned(), password.to_owned())),
            ..self
        }
    }
    pub fn body(self, body: impl Into<Body>) -> Self {
        Self {
            body: Some(body.into()),
            ..self
        }
    }
    #[inline(always)]
    pub fn range(self, start: usize, end: usize) -> Self {
        self.header(
            header_name!("range"),
            header_value!(format!("bytes={}-{}", start, end)),
        )
    }
    pub fn header(mut self, key: HeaderName, val: HeaderValue) -> Self {
        self.headers.insert(key, val);
        self
    }
    pub fn headers(mut self, headers: HeaderMap) -> Self {
        self.headers.extend(headers);
        self
    }

    pub fn build(self) -> crate::RequestBuilder {
        let builder = self.client.inner.request(self.method.convert(), self.url);
        let builder = if let Some(body) = self.body {
            builder.body(body)
        } else {
            builder
        };
        if let Some((usr, pass)) = &self.basic_auth {
            builder.basic_auth(usr, Some(pass))
        } else if let Some((usr, psw)) = &self.client.auth {
            builder.basic_auth(usr, Some(psw))
        } else {
            panic!("Missing basic auth!")
        }
        .headers(self.headers)
    }
    pub fn into_lazy_reader(self) -> LazyResponseReader {
        LazyResponseReader::new(self.build())
    }
    pub fn send(self) -> impl Future<Output = Result<Response, reqwest::Error>> {
        self.build().send()
    }
}