opendal/services/seafile/
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::sync::Arc;
20
21use http::Response;
22use http::StatusCode;
23use log::debug;
24use mea::rwlock::RwLock;
25
26use super::SEAFILE_SCHEME;
27use super::config::SeafileConfig;
28use super::core::SeafileCore;
29use super::core::SeafileSigner;
30use super::core::parse_dir_detail;
31use super::core::parse_file_detail;
32use super::deleter::SeafileDeleter;
33use super::error::parse_error;
34use super::lister::SeafileLister;
35use super::writer::SeafileWriter;
36use super::writer::SeafileWriters;
37use crate::raw::*;
38use crate::*;
39
40/// [seafile](https://www.seafile.com) services support.
41#[doc = include_str!("docs.md")]
42#[derive(Default)]
43pub struct SeafileBuilder {
44    pub(super) config: SeafileConfig,
45
46    #[deprecated(since = "0.53.0", note = "Use `Operator::update_http_client` instead")]
47    pub(super) http_client: Option<HttpClient>,
48}
49
50impl Debug for SeafileBuilder {
51    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
52        f.debug_struct("SeafileBuilder")
53            .field("config", &self.config)
54            .finish_non_exhaustive()
55    }
56}
57
58impl SeafileBuilder {
59    /// Set root of this backend.
60    ///
61    /// All operations will happen under this root.
62    pub fn root(mut self, root: &str) -> Self {
63        self.config.root = if root.is_empty() {
64            None
65        } else {
66            Some(root.to_string())
67        };
68
69        self
70    }
71
72    /// endpoint of this backend.
73    ///
74    /// It is required. e.g. `http://127.0.0.1:80`
75    pub fn endpoint(mut self, endpoint: &str) -> Self {
76        self.config.endpoint = if endpoint.is_empty() {
77            None
78        } else {
79            Some(endpoint.to_string())
80        };
81
82        self
83    }
84
85    /// username of this backend.
86    ///
87    /// It is required. e.g. `me@example.com`
88    pub fn username(mut self, username: &str) -> Self {
89        self.config.username = if username.is_empty() {
90            None
91        } else {
92            Some(username.to_string())
93        };
94
95        self
96    }
97
98    /// password of this backend.
99    ///
100    /// It is required. e.g. `asecret`
101    pub fn password(mut self, password: &str) -> Self {
102        self.config.password = if password.is_empty() {
103            None
104        } else {
105            Some(password.to_string())
106        };
107
108        self
109    }
110
111    /// Set repo name of this backend.
112    ///
113    /// It is required. e.g. `myrepo`
114    pub fn repo_name(mut self, repo_name: &str) -> Self {
115        self.config.repo_name = repo_name.to_string();
116
117        self
118    }
119
120    /// Specify the http client that used by this service.
121    ///
122    /// # Notes
123    ///
124    /// This API is part of OpenDAL's Raw API. `HttpClient` could be changed
125    /// during minor updates.
126    #[deprecated(since = "0.53.0", note = "Use `Operator::update_http_client` instead")]
127    #[allow(deprecated)]
128    pub fn http_client(mut self, client: HttpClient) -> Self {
129        self.http_client = Some(client);
130        self
131    }
132}
133
134impl Builder for SeafileBuilder {
135    type Config = SeafileConfig;
136
137    /// Builds the backend and returns the result of SeafileBackend.
138    fn build(self) -> Result<impl Access> {
139        debug!("backend build started: {:?}", &self);
140
141        let root = normalize_root(&self.config.root.clone().unwrap_or_default());
142        debug!("backend use root {}", &root);
143
144        // Handle bucket.
145        if self.config.repo_name.is_empty() {
146            return Err(Error::new(ErrorKind::ConfigInvalid, "repo_name is empty")
147                .with_operation("Builder::build")
148                .with_context("service", SEAFILE_SCHEME));
149        }
150
151        debug!("backend use repo_name {}", &self.config.repo_name);
152
153        let endpoint = match &self.config.endpoint {
154            Some(endpoint) => Ok(endpoint.clone()),
155            None => Err(Error::new(ErrorKind::ConfigInvalid, "endpoint is empty")
156                .with_operation("Builder::build")
157                .with_context("service", SEAFILE_SCHEME)),
158        }?;
159
160        let username = match &self.config.username {
161            Some(username) => Ok(username.clone()),
162            None => Err(Error::new(ErrorKind::ConfigInvalid, "username is empty")
163                .with_operation("Builder::build")
164                .with_context("service", SEAFILE_SCHEME)),
165        }?;
166
167        let password = match &self.config.password {
168            Some(password) => Ok(password.clone()),
169            None => Err(Error::new(ErrorKind::ConfigInvalid, "password is empty")
170                .with_operation("Builder::build")
171                .with_context("service", SEAFILE_SCHEME)),
172        }?;
173
174        Ok(SeafileBackend {
175            core: Arc::new(SeafileCore {
176                info: {
177                    let am = AccessorInfo::default();
178                    am.set_scheme(SEAFILE_SCHEME)
179                        .set_root(&root)
180                        .set_native_capability(Capability {
181                            stat: true,
182
183                            read: true,
184
185                            write: true,
186                            write_can_empty: true,
187
188                            delete: true,
189
190                            list: true,
191
192                            shared: true,
193
194                            ..Default::default()
195                        });
196
197                    // allow deprecated api here for compatibility
198                    #[allow(deprecated)]
199                    if let Some(client) = self.http_client {
200                        am.update_http_client(|_| client);
201                    }
202
203                    am.into()
204                },
205                root,
206                endpoint,
207                username,
208                password,
209                repo_name: self.config.repo_name.clone(),
210                signer: Arc::new(RwLock::new(SeafileSigner::default())),
211            }),
212        })
213    }
214}
215
216/// Backend for seafile services.
217#[derive(Debug, Clone)]
218pub struct SeafileBackend {
219    core: Arc<SeafileCore>,
220}
221
222impl Access for SeafileBackend {
223    type Reader = HttpBody;
224    type Writer = SeafileWriters;
225    type Lister = oio::PageLister<SeafileLister>;
226    type Deleter = oio::OneShotDeleter<SeafileDeleter>;
227
228    fn info(&self) -> Arc<AccessorInfo> {
229        self.core.info.clone()
230    }
231
232    async fn stat(&self, path: &str, _args: OpStat) -> Result<RpStat> {
233        if path == "/" {
234            return Ok(RpStat::new(Metadata::new(EntryMode::DIR)));
235        }
236
237        let metadata = if path.ends_with('/') {
238            let dir_detail = self.core.dir_detail(path).await?;
239            parse_dir_detail(dir_detail)
240        } else {
241            let file_detail = self.core.file_detail(path).await?;
242
243            parse_file_detail(file_detail)
244        };
245
246        metadata.map(RpStat::new)
247    }
248
249    async fn read(&self, path: &str, args: OpRead) -> Result<(RpRead, Self::Reader)> {
250        let resp = self.core.download_file(path, args.range()).await?;
251
252        let status = resp.status();
253
254        match status {
255            StatusCode::OK | StatusCode::PARTIAL_CONTENT => {
256                Ok((RpRead::default(), resp.into_body()))
257            }
258            _ => {
259                let (part, mut body) = resp.into_parts();
260                let buf = body.to_buffer().await?;
261                Err(parse_error(Response::from_parts(part, buf)))
262            }
263        }
264    }
265
266    async fn write(&self, path: &str, args: OpWrite) -> Result<(RpWrite, Self::Writer)> {
267        let w = SeafileWriter::new(self.core.clone(), args, path.to_string());
268        let w = oio::OneShotWriter::new(w);
269
270        Ok((RpWrite::default(), w))
271    }
272
273    async fn delete(&self) -> Result<(RpDelete, Self::Deleter)> {
274        Ok((
275            RpDelete::default(),
276            oio::OneShotDeleter::new(SeafileDeleter::new(self.core.clone())),
277        ))
278    }
279
280    async fn list(&self, path: &str, _args: OpList) -> Result<(RpList, Self::Lister)> {
281        let l = SeafileLister::new(self.core.clone(), path);
282        Ok((RpList::default(), oio::PageLister::new(l)))
283    }
284}