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 crate::raw::*;
38use crate::services::KoofrConfig;
39use crate::*;
40
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    const SCHEME: Scheme = Scheme::Koofr;
140    type Config = KoofrConfig;
141
142    /// Builds the backend and returns the result of KoofrBackend.
143    fn build(self) -> Result<impl Access> {
144        debug!("backend build started: {:?}", &self);
145
146        let root = normalize_root(&self.config.root.clone().unwrap_or_default());
147        debug!("backend use root {}", &root);
148
149        if self.config.endpoint.is_empty() {
150            return Err(Error::new(ErrorKind::ConfigInvalid, "endpoint is empty")
151                .with_operation("Builder::build")
152                .with_context("service", Scheme::Koofr));
153        }
154
155        debug!("backend use endpoint {}", &self.config.endpoint);
156
157        if self.config.email.is_empty() {
158            return Err(Error::new(ErrorKind::ConfigInvalid, "email is empty")
159                .with_operation("Builder::build")
160                .with_context("service", Scheme::Koofr));
161        }
162
163        debug!("backend use email {}", &self.config.email);
164
165        let password = match &self.config.password {
166            Some(password) => Ok(password.clone()),
167            None => Err(Error::new(ErrorKind::ConfigInvalid, "password is empty")
168                .with_operation("Builder::build")
169                .with_context("service", Scheme::Koofr)),
170        }?;
171
172        let signer = Arc::new(Mutex::new(KoofrSigner::default()));
173
174        Ok(KoofrBackend {
175            core: Arc::new(KoofrCore {
176                info: {
177                    let am = AccessorInfo::default();
178                    am.set_scheme(Scheme::Koofr)
179                        .set_root(&root)
180                        .set_native_capability(Capability {
181                            stat: true,
182                            stat_has_content_length: true,
183                            stat_has_content_type: true,
184                            stat_has_last_modified: true,
185
186                            create_dir: true,
187
188                            read: true,
189
190                            write: true,
191                            write_can_empty: true,
192
193                            delete: true,
194
195                            rename: true,
196
197                            copy: true,
198
199                            list: true,
200                            list_has_content_length: true,
201                            list_has_content_type: true,
202                            list_has_last_modified: true,
203
204                            shared: true,
205
206                            ..Default::default()
207                        });
208
209                    // allow deprecated api here for compatibility
210                    #[allow(deprecated)]
211                    if let Some(client) = self.http_client {
212                        am.update_http_client(|_| client);
213                    }
214
215                    am.into()
216                },
217                root,
218                endpoint: self.config.endpoint.clone(),
219                email: self.config.email.clone(),
220                password,
221                mount_id: OnceCell::new(),
222                signer,
223            }),
224        })
225    }
226}
227
228/// Backend for Koofr services.
229#[derive(Debug, Clone)]
230pub struct KoofrBackend {
231    core: Arc<KoofrCore>,
232}
233
234impl Access for KoofrBackend {
235    type Reader = HttpBody;
236    type Writer = KoofrWriters;
237    type Lister = oio::PageLister<KoofrLister>;
238    type Deleter = oio::OneShotDeleter<KoofrDeleter>;
239    type BlockingReader = ();
240    type BlockingWriter = ();
241    type BlockingLister = ();
242    type BlockingDeleter = ();
243
244    fn info(&self) -> Arc<AccessorInfo> {
245        self.core.info.clone()
246    }
247
248    async fn create_dir(&self, path: &str, _: OpCreateDir) -> Result<RpCreateDir> {
249        self.core.ensure_dir_exists(path).await?;
250        self.core
251            .create_dir(&build_abs_path(&self.core.root, path))
252            .await?;
253        Ok(RpCreateDir::default())
254    }
255
256    async fn stat(&self, path: &str, _args: OpStat) -> Result<RpStat> {
257        let path = build_rooted_abs_path(&self.core.root, path);
258        let resp = self.core.info(&path).await?;
259
260        let status = resp.status();
261
262        match status {
263            StatusCode::OK => {
264                let bs = resp.into_body();
265
266                let file: File =
267                    serde_json::from_reader(bs.reader()).map_err(new_json_deserialize_error)?;
268
269                let mode = if file.ty == "dir" {
270                    EntryMode::DIR
271                } else {
272                    EntryMode::FILE
273                };
274
275                let mut md = Metadata::new(mode);
276
277                md.set_content_length(file.size)
278                    .set_content_type(&file.content_type)
279                    .set_last_modified(parse_datetime_from_from_timestamp_millis(file.modified)?);
280
281                Ok(RpStat::new(md))
282            }
283            _ => Err(parse_error(resp)),
284        }
285    }
286
287    async fn read(&self, path: &str, args: OpRead) -> Result<(RpRead, Self::Reader)> {
288        let resp = self.core.get(path, args.range()).await?;
289
290        let status = resp.status();
291        match status {
292            StatusCode::OK | StatusCode::PARTIAL_CONTENT => {
293                Ok((RpRead::default(), resp.into_body()))
294            }
295            _ => {
296                let (part, mut body) = resp.into_parts();
297                let buf = body.to_buffer().await?;
298                Err(parse_error(Response::from_parts(part, buf)))
299            }
300        }
301    }
302
303    async fn write(&self, path: &str, _args: OpWrite) -> Result<(RpWrite, Self::Writer)> {
304        let writer = KoofrWriter::new(self.core.clone(), path.to_string());
305
306        let w = oio::OneShotWriter::new(writer);
307
308        Ok((RpWrite::default(), w))
309    }
310
311    async fn delete(&self) -> Result<(RpDelete, Self::Deleter)> {
312        Ok((
313            RpDelete::default(),
314            oio::OneShotDeleter::new(KoofrDeleter::new(self.core.clone())),
315        ))
316    }
317
318    async fn list(&self, path: &str, _args: OpList) -> Result<(RpList, Self::Lister)> {
319        let l = KoofrLister::new(self.core.clone(), path);
320        Ok((RpList::default(), oio::PageLister::new(l)))
321    }
322
323    async fn copy(&self, from: &str, to: &str, _args: OpCopy) -> Result<RpCopy> {
324        self.core.ensure_dir_exists(to).await?;
325
326        if from == to {
327            return Ok(RpCopy::default());
328        }
329
330        let resp = self.core.remove(to).await?;
331
332        let status = resp.status();
333
334        if status != StatusCode::OK && status != StatusCode::NOT_FOUND {
335            return Err(parse_error(resp));
336        }
337
338        let resp = self.core.copy(from, to).await?;
339
340        let status = resp.status();
341
342        match status {
343            StatusCode::OK => Ok(RpCopy::default()),
344            _ => Err(parse_error(resp)),
345        }
346    }
347
348    async fn rename(&self, from: &str, to: &str, _args: OpRename) -> Result<RpRename> {
349        self.core.ensure_dir_exists(to).await?;
350
351        if from == to {
352            return Ok(RpRename::default());
353        }
354
355        let resp = self.core.remove(to).await?;
356
357        let status = resp.status();
358
359        if status != StatusCode::OK && status != StatusCode::NOT_FOUND {
360            return Err(parse_error(resp));
361        }
362
363        let resp = self.core.move_object(from, to).await?;
364
365        let status = resp.status();
366
367        match status {
368            StatusCode::OK => Ok(RpRename::default()),
369            _ => Err(parse_error(resp)),
370        }
371    }
372}