opendal/services/webdav/
backend.rs1use std::fmt::Debug;
19use std::str::FromStr;
20use std::sync::Arc;
21
22use http::Response;
23use http::StatusCode;
24use log::debug;
25
26use super::WEBDAV_SCHEME;
27use super::config::WebdavConfig;
28use super::core::*;
29use super::deleter::WebdavDeleter;
30use super::error::parse_error;
31use super::lister::WebdavLister;
32use super::writer::WebdavWriter;
33use crate::raw::*;
34use crate::*;
35
36#[doc = include_str!("docs.md")]
38#[derive(Default)]
39pub struct WebdavBuilder {
40 pub(super) config: WebdavConfig,
41
42 #[deprecated(since = "0.53.0", note = "Use `Operator::update_http_client` instead")]
43 pub(super) http_client: Option<HttpClient>,
44}
45
46impl Debug for WebdavBuilder {
47 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
48 f.debug_struct("WebdavBuilder")
49 .field("config", &self.config)
50 .finish_non_exhaustive()
51 }
52}
53
54impl WebdavBuilder {
55 pub fn endpoint(mut self, endpoint: &str) -> Self {
59 self.config.endpoint = if endpoint.is_empty() {
60 None
61 } else {
62 Some(endpoint.to_string())
63 };
64
65 self
66 }
67
68 pub fn username(mut self, username: &str) -> Self {
72 if !username.is_empty() {
73 self.config.username = Some(username.to_owned());
74 }
75 self
76 }
77
78 pub fn password(mut self, password: &str) -> Self {
82 if !password.is_empty() {
83 self.config.password = Some(password.to_owned());
84 }
85 self
86 }
87
88 pub fn token(mut self, token: &str) -> Self {
92 if !token.is_empty() {
93 self.config.token = Some(token.to_string());
94 }
95 self
96 }
97
98 pub fn root(mut self, root: &str) -> Self {
100 self.config.root = if root.is_empty() {
101 None
102 } else {
103 Some(root.to_string())
104 };
105
106 self
107 }
108
109 #[deprecated(since = "0.53.0", note = "Use `Operator::update_http_client` instead")]
116 #[allow(deprecated)]
117 pub fn http_client(mut self, client: HttpClient) -> Self {
118 self.http_client = Some(client);
119 self
120 }
121}
122
123impl Builder for WebdavBuilder {
124 type Config = WebdavConfig;
125
126 fn build(self) -> Result<impl Access> {
127 debug!("backend build started: {:?}", &self);
128
129 let endpoint = match &self.config.endpoint {
130 Some(v) => v,
131 None => {
132 return Err(Error::new(ErrorKind::ConfigInvalid, "endpoint is empty")
133 .with_context("service", WEBDAV_SCHEME));
134 }
135 };
136 let server_path = http::Uri::from_str(endpoint)
138 .map_err(|err| {
139 Error::new(ErrorKind::ConfigInvalid, "endpoint is invalid")
140 .with_context("service", WEBDAV_SCHEME)
141 .set_source(err)
142 })?
143 .path()
144 .trim_end_matches('/')
145 .to_string();
146
147 let root = normalize_root(&self.config.root.clone().unwrap_or_default());
148 debug!("backend use root {root}");
149
150 let mut authorization = None;
151 if let Some(username) = &self.config.username {
152 authorization = Some(format_authorization_by_basic(
153 username,
154 self.config.password.as_deref().unwrap_or_default(),
155 )?);
156 }
157 if let Some(token) = &self.config.token {
158 authorization = Some(format_authorization_by_bearer(token)?)
159 }
160
161 let core = Arc::new(WebdavCore {
162 info: {
163 let am = AccessorInfo::default();
164 am.set_scheme(WEBDAV_SCHEME)
165 .set_root(&root)
166 .set_native_capability(Capability {
167 stat: true,
168
169 read: true,
170
171 write: true,
172 write_can_empty: true,
173
174 create_dir: true,
175 delete: true,
176
177 copy: !self.config.disable_copy,
178
179 rename: true,
180
181 list: true,
182
183 shared: true,
186
187 ..Default::default()
188 });
189
190 #[allow(deprecated)]
192 if let Some(client) = self.http_client {
193 am.update_http_client(|_| client);
194 }
195
196 am.into()
197 },
198 endpoint: endpoint.to_string(),
199 server_path,
200 authorization,
201 root,
202 });
203 Ok(WebdavBackend { core })
204 }
205}
206
207#[derive(Clone, Debug)]
209pub struct WebdavBackend {
210 core: Arc<WebdavCore>,
211}
212
213impl Access for WebdavBackend {
214 type Reader = HttpBody;
215 type Writer = oio::OneShotWriter<WebdavWriter>;
216 type Lister = oio::PageLister<WebdavLister>;
217 type Deleter = oio::OneShotDeleter<WebdavDeleter>;
218
219 fn info(&self) -> Arc<AccessorInfo> {
220 self.core.info.clone()
221 }
222
223 async fn create_dir(&self, path: &str, _: OpCreateDir) -> Result<RpCreateDir> {
224 self.core.webdav_mkcol(path).await?;
225 Ok(RpCreateDir::default())
226 }
227
228 async fn stat(&self, path: &str, _: OpStat) -> Result<RpStat> {
229 let metadata = self.core.webdav_stat(path).await?;
230 Ok(RpStat::new(metadata))
231 }
232
233 async fn read(&self, path: &str, args: OpRead) -> Result<(RpRead, Self::Reader)> {
234 let resp = self.core.webdav_get(path, args.range(), &args).await?;
235
236 let status = resp.status();
237
238 match status {
239 StatusCode::OK | StatusCode::PARTIAL_CONTENT => {
240 Ok((RpRead::default(), resp.into_body()))
241 }
242 _ => {
243 let (part, mut body) = resp.into_parts();
244 let buf = body.to_buffer().await?;
245 Err(parse_error(Response::from_parts(part, buf)))
246 }
247 }
248 }
249
250 async fn write(&self, path: &str, args: OpWrite) -> Result<(RpWrite, Self::Writer)> {
251 self.core.webdav_mkcol(get_parent(path)).await?;
253
254 Ok((
255 RpWrite::default(),
256 oio::OneShotWriter::new(WebdavWriter::new(self.core.clone(), args, path.to_string())),
257 ))
258 }
259
260 async fn delete(&self) -> Result<(RpDelete, Self::Deleter)> {
261 Ok((
262 RpDelete::default(),
263 oio::OneShotDeleter::new(WebdavDeleter::new(self.core.clone())),
264 ))
265 }
266
267 async fn list(&self, path: &str, args: OpList) -> Result<(RpList, Self::Lister)> {
268 Ok((
269 RpList::default(),
270 oio::PageLister::new(WebdavLister::new(self.core.clone(), path, args)),
271 ))
272 }
273
274 async fn copy(&self, from: &str, to: &str, _args: OpCopy) -> Result<RpCopy> {
275 let resp = self.core.webdav_copy(from, to).await?;
276
277 let status = resp.status();
278
279 match status {
280 StatusCode::CREATED | StatusCode::NO_CONTENT => Ok(RpCopy::default()),
281 _ => Err(parse_error(resp)),
282 }
283 }
284
285 async fn rename(&self, from: &str, to: &str, _args: OpRename) -> Result<RpRename> {
286 let resp = self.core.webdav_move(from, to).await?;
287
288 let status = resp.status();
289 match status {
290 StatusCode::CREATED | StatusCode::NO_CONTENT | StatusCode::OK => {
291 Ok(RpRename::default())
292 }
293 _ => Err(parse_error(resp)),
294 }
295 }
296}