opendal/services/koofr/
backend.rs

1// Licensed to the Apache Software Foundation (ASF) under one
2// or more contributor license agreements.  See the NOTICE file
3// distributed with this work for additional information
4// regarding copyright ownership.  The ASF licenses this file
5// to you under the Apache License, Version 2.0 (the
6// "License"); you may not use this file except in compliance
7// with the License.  You may obtain a copy of the License at
8//
9//   http://www.apache.org/licenses/LICENSE-2.0
10//
11// Unless required by applicable law or agreed to in writing,
12// software distributed under the License is distributed on an
13// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
14// KIND, either express or implied.  See the License for the
15// specific language governing permissions and limitations
16// under the License.
17
18use std::fmt::Debug;
19use std::fmt::Formatter;
20use std::sync::Arc;
21
22use bytes::Buf;
23use http::Response;
24use http::StatusCode;
25use log::debug;
26use tokio::sync::Mutex;
27use tokio::sync::OnceCell;
28
29use super::core::File;
30use super::core::KoofrCore;
31use super::core::KoofrSigner;
32use super::delete::KoofrDeleter;
33use super::error::parse_error;
34use super::lister::KoofrLister;
35use super::writer::KoofrWriter;
36use super::writer::KoofrWriters;
37use super::DEFAULT_SCHEME;
38use crate::raw::*;
39use crate::services::KoofrConfig;
40use crate::*;
41impl Configurator for KoofrConfig {
42    type Builder = KoofrBuilder;
43
44    #[allow(deprecated)]
45    fn into_builder(self) -> Self::Builder {
46        KoofrBuilder {
47            config: self,
48            http_client: None,
49        }
50    }
51}
52
53/// [Koofr](https://app.koofr.net/) services support.
54#[doc = include_str!("docs.md")]
55#[derive(Default)]
56pub struct KoofrBuilder {
57    config: KoofrConfig,
58
59    #[deprecated(since = "0.53.0", note = "Use `Operator::update_http_client` instead")]
60    http_client: Option<HttpClient>,
61}
62
63impl Debug for KoofrBuilder {
64    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
65        let mut d = f.debug_struct("KoofrBuilder");
66
67        d.field("config", &self.config);
68        d.finish_non_exhaustive()
69    }
70}
71
72impl KoofrBuilder {
73    /// Set root of this backend.
74    ///
75    /// All operations will happen under this root.
76    pub fn root(mut self, root: &str) -> Self {
77        self.config.root = if root.is_empty() {
78            None
79        } else {
80            Some(root.to_string())
81        };
82
83        self
84    }
85
86    /// endpoint.
87    ///
88    /// It is required. e.g. `https://api.koofr.net/`
89    pub fn endpoint(mut self, endpoint: &str) -> Self {
90        self.config.endpoint = endpoint.to_string();
91
92        self
93    }
94
95    /// email.
96    ///
97    /// It is required. e.g. `test@example.com`
98    pub fn email(mut self, email: &str) -> Self {
99        self.config.email = email.to_string();
100
101        self
102    }
103
104    /// Koofr application password.
105    ///
106    /// Go to <https://app.koofr.net/app/admin/preferences/password>.
107    /// Click "Generate Password" button to generate a new application password.
108    ///
109    /// # Notes
110    ///
111    /// This is not user's Koofr account password.
112    /// Please use the application password instead.
113    /// Please also remind users of this.
114    pub fn password(mut self, password: &str) -> Self {
115        self.config.password = if password.is_empty() {
116            None
117        } else {
118            Some(password.to_string())
119        };
120
121        self
122    }
123
124    /// Specify the http client that used by this service.
125    ///
126    /// # Notes
127    ///
128    /// This API is part of OpenDAL's Raw API. `HttpClient` could be changed
129    /// during minor updates.
130    #[deprecated(since = "0.53.0", note = "Use `Operator::update_http_client` instead")]
131    #[allow(deprecated)]
132    pub fn http_client(mut self, client: HttpClient) -> Self {
133        self.http_client = Some(client);
134        self
135    }
136}
137
138impl Builder for KoofrBuilder {
139    type Config = KoofrConfig;
140
141    /// Builds the backend and returns the result of KoofrBackend.
142    fn build(self) -> Result<impl Access> {
143        debug!("backend build started: {:?}", &self);
144
145        let root = normalize_root(&self.config.root.clone().unwrap_or_default());
146        debug!("backend use root {}", &root);
147
148        if self.config.endpoint.is_empty() {
149            return Err(Error::new(ErrorKind::ConfigInvalid, "endpoint is empty")
150                .with_operation("Builder::build")
151                .with_context("service", Scheme::Koofr));
152        }
153
154        debug!("backend use endpoint {}", &self.config.endpoint);
155
156        if self.config.email.is_empty() {
157            return Err(Error::new(ErrorKind::ConfigInvalid, "email is empty")
158                .with_operation("Builder::build")
159                .with_context("service", Scheme::Koofr));
160        }
161
162        debug!("backend use email {}", &self.config.email);
163
164        let password = match &self.config.password {
165            Some(password) => Ok(password.clone()),
166            None => Err(Error::new(ErrorKind::ConfigInvalid, "password is empty")
167                .with_operation("Builder::build")
168                .with_context("service", Scheme::Koofr)),
169        }?;
170
171        let signer = Arc::new(Mutex::new(KoofrSigner::default()));
172
173        Ok(KoofrBackend {
174            core: Arc::new(KoofrCore {
175                info: {
176                    let am = AccessorInfo::default();
177                    am.set_scheme(DEFAULT_SCHEME)
178                        .set_root(&root)
179                        .set_native_capability(Capability {
180                            stat: true,
181
182                            create_dir: true,
183
184                            read: true,
185
186                            write: true,
187                            write_can_empty: true,
188
189                            delete: true,
190
191                            rename: true,
192
193                            copy: true,
194
195                            list: true,
196
197                            shared: true,
198
199                            ..Default::default()
200                        });
201
202                    // allow deprecated api here for compatibility
203                    #[allow(deprecated)]
204                    if let Some(client) = self.http_client {
205                        am.update_http_client(|_| client);
206                    }
207
208                    am.into()
209                },
210                root,
211                endpoint: self.config.endpoint.clone(),
212                email: self.config.email.clone(),
213                password,
214                mount_id: OnceCell::new(),
215                signer,
216            }),
217        })
218    }
219}
220
221/// Backend for Koofr services.
222#[derive(Debug, Clone)]
223pub struct KoofrBackend {
224    core: Arc<KoofrCore>,
225}
226
227impl Access for KoofrBackend {
228    type Reader = HttpBody;
229    type Writer = KoofrWriters;
230    type Lister = oio::PageLister<KoofrLister>;
231    type Deleter = oio::OneShotDeleter<KoofrDeleter>;
232
233    fn info(&self) -> Arc<AccessorInfo> {
234        self.core.info.clone()
235    }
236
237    async fn create_dir(&self, path: &str, _: OpCreateDir) -> Result<RpCreateDir> {
238        self.core.ensure_dir_exists(path).await?;
239        self.core
240            .create_dir(&build_abs_path(&self.core.root, path))
241            .await?;
242        Ok(RpCreateDir::default())
243    }
244
245    async fn stat(&self, path: &str, _args: OpStat) -> Result<RpStat> {
246        let path = build_rooted_abs_path(&self.core.root, path);
247        let resp = self.core.info(&path).await?;
248
249        let status = resp.status();
250
251        match status {
252            StatusCode::OK => {
253                let bs = resp.into_body();
254
255                let file: File =
256                    serde_json::from_reader(bs.reader()).map_err(new_json_deserialize_error)?;
257
258                let mode = if file.ty == "dir" {
259                    EntryMode::DIR
260                } else {
261                    EntryMode::FILE
262                };
263
264                let mut md = Metadata::new(mode);
265
266                md.set_content_length(file.size)
267                    .set_content_type(&file.content_type)
268                    .set_last_modified(parse_datetime_from_from_timestamp_millis(file.modified)?);
269
270                Ok(RpStat::new(md))
271            }
272            _ => Err(parse_error(resp)),
273        }
274    }
275
276    async fn read(&self, path: &str, args: OpRead) -> Result<(RpRead, Self::Reader)> {
277        let resp = self.core.get(path, args.range()).await?;
278
279        let status = resp.status();
280        match status {
281            StatusCode::OK | StatusCode::PARTIAL_CONTENT => {
282                Ok((RpRead::default(), resp.into_body()))
283            }
284            _ => {
285                let (part, mut body) = resp.into_parts();
286                let buf = body.to_buffer().await?;
287                Err(parse_error(Response::from_parts(part, buf)))
288            }
289        }
290    }
291
292    async fn write(&self, path: &str, _args: OpWrite) -> Result<(RpWrite, Self::Writer)> {
293        let writer = KoofrWriter::new(self.core.clone(), path.to_string());
294
295        let w = oio::OneShotWriter::new(writer);
296
297        Ok((RpWrite::default(), w))
298    }
299
300    async fn delete(&self) -> Result<(RpDelete, Self::Deleter)> {
301        Ok((
302            RpDelete::default(),
303            oio::OneShotDeleter::new(KoofrDeleter::new(self.core.clone())),
304        ))
305    }
306
307    async fn list(&self, path: &str, _args: OpList) -> Result<(RpList, Self::Lister)> {
308        let l = KoofrLister::new(self.core.clone(), path);
309        Ok((RpList::default(), oio::PageLister::new(l)))
310    }
311
312    async fn copy(&self, from: &str, to: &str, _args: OpCopy) -> Result<RpCopy> {
313        self.core.ensure_dir_exists(to).await?;
314
315        if from == to {
316            return Ok(RpCopy::default());
317        }
318
319        let resp = self.core.remove(to).await?;
320
321        let status = resp.status();
322
323        if status != StatusCode::OK && status != StatusCode::NOT_FOUND {
324            return Err(parse_error(resp));
325        }
326
327        let resp = self.core.copy(from, to).await?;
328
329        let status = resp.status();
330
331        match status {
332            StatusCode::OK => Ok(RpCopy::default()),
333            _ => Err(parse_error(resp)),
334        }
335    }
336
337    async fn rename(&self, from: &str, to: &str, _args: OpRename) -> Result<RpRename> {
338        self.core.ensure_dir_exists(to).await?;
339
340        if from == to {
341            return Ok(RpRename::default());
342        }
343
344        let resp = self.core.remove(to).await?;
345
346        let status = resp.status();
347
348        if status != StatusCode::OK && status != StatusCode::NOT_FOUND {
349            return Err(parse_error(resp));
350        }
351
352        let resp = self.core.move_object(from, to).await?;
353
354        let status = resp.status();
355
356        match status {
357            StatusCode::OK => Ok(RpRename::default()),
358            _ => Err(parse_error(resp)),
359        }
360    }
361}