opendal/services/pcloud/
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 bytes::Buf;
22use http::Response;
23use http::StatusCode;
24use log::debug;
25
26use super::PCLOUD_SCHEME;
27use super::config::PcloudConfig;
28use super::core::*;
29use super::deleter::PcloudDeleter;
30use super::error::PcloudError;
31use super::error::parse_error;
32use super::lister::PcloudLister;
33use super::writer::PcloudWriter;
34use super::writer::PcloudWriters;
35use crate::raw::*;
36use crate::*;
37
38/// [pCloud](https://www.pcloud.com/) services support.
39#[doc = include_str!("docs.md")]
40#[derive(Default)]
41pub struct PcloudBuilder {
42    pub(super) config: PcloudConfig,
43
44    #[deprecated(since = "0.53.0", note = "Use `Operator::update_http_client` instead")]
45    pub(super) http_client: Option<HttpClient>,
46}
47
48impl Debug for PcloudBuilder {
49    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
50        f.debug_struct("PcloudBuilder")
51            .field("config", &self.config)
52            .finish_non_exhaustive()
53    }
54}
55
56impl PcloudBuilder {
57    /// Set root of this backend.
58    ///
59    /// All operations will happen under this root.
60    pub fn root(mut self, root: &str) -> Self {
61        self.config.root = if root.is_empty() {
62            None
63        } else {
64            Some(root.to_string())
65        };
66
67        self
68    }
69
70    /// Pcloud endpoint.
71    /// <https://api.pcloud.com> for United States and <https://eapi.pcloud.com> for Europe
72    /// ref to [doc.pcloud.com](https://docs.pcloud.com/)
73    ///
74    /// It is required. e.g. `https://api.pcloud.com`
75    pub fn endpoint(mut self, endpoint: &str) -> Self {
76        self.config.endpoint = endpoint.to_string();
77
78        self
79    }
80
81    /// Pcloud username.
82    ///
83    /// It is required. your pCloud login email, e.g. `example@gmail.com`
84    pub fn username(mut self, username: &str) -> Self {
85        self.config.username = if username.is_empty() {
86            None
87        } else {
88            Some(username.to_string())
89        };
90
91        self
92    }
93
94    /// Pcloud password.
95    ///
96    /// It is required. your pCloud login password, e.g. `password`
97    pub fn password(mut self, password: &str) -> Self {
98        self.config.password = if password.is_empty() {
99            None
100        } else {
101            Some(password.to_string())
102        };
103
104        self
105    }
106
107    /// Specify the http client that used by this service.
108    ///
109    /// # Notes
110    ///
111    /// This API is part of OpenDAL's Raw API. `HttpClient` could be changed
112    /// during minor updates.
113    #[deprecated(since = "0.53.0", note = "Use `Operator::update_http_client` instead")]
114    #[allow(deprecated)]
115    pub fn http_client(mut self, client: HttpClient) -> Self {
116        self.http_client = Some(client);
117        self
118    }
119}
120
121impl Builder for PcloudBuilder {
122    type Config = PcloudConfig;
123
124    /// Builds the backend and returns the result of PcloudBackend.
125    fn build(self) -> Result<impl Access> {
126        debug!("backend build started: {:?}", &self);
127
128        let root = normalize_root(&self.config.root.clone().unwrap_or_default());
129        debug!("backend use root {}", &root);
130
131        // Handle endpoint.
132        if self.config.endpoint.is_empty() {
133            return Err(Error::new(ErrorKind::ConfigInvalid, "endpoint is empty")
134                .with_operation("Builder::build")
135                .with_context("service", PCLOUD_SCHEME));
136        }
137
138        debug!("backend use endpoint {}", &self.config.endpoint);
139
140        let username = match &self.config.username {
141            Some(username) => Ok(username.clone()),
142            None => Err(Error::new(ErrorKind::ConfigInvalid, "username is empty")
143                .with_operation("Builder::build")
144                .with_context("service", PCLOUD_SCHEME)),
145        }?;
146
147        let password = match &self.config.password {
148            Some(password) => Ok(password.clone()),
149            None => Err(Error::new(ErrorKind::ConfigInvalid, "password is empty")
150                .with_operation("Builder::build")
151                .with_context("service", PCLOUD_SCHEME)),
152        }?;
153
154        Ok(PcloudBackend {
155            core: Arc::new(PcloudCore {
156                info: {
157                    let am = AccessorInfo::default();
158                    am.set_scheme(PCLOUD_SCHEME)
159                        .set_root(&root)
160                        .set_native_capability(Capability {
161                            stat: true,
162
163                            create_dir: true,
164
165                            read: true,
166
167                            write: true,
168
169                            delete: true,
170                            rename: true,
171                            copy: true,
172
173                            list: true,
174
175                            shared: true,
176
177                            ..Default::default()
178                        });
179
180                    // allow deprecated api here for compatibility
181                    #[allow(deprecated)]
182                    if let Some(client) = self.http_client {
183                        am.update_http_client(|_| client);
184                    }
185
186                    am.into()
187                },
188                root,
189                endpoint: self.config.endpoint.clone(),
190                username,
191                password,
192            }),
193        })
194    }
195}
196
197/// Backend for Pcloud services.
198#[derive(Debug, Clone)]
199pub struct PcloudBackend {
200    core: Arc<PcloudCore>,
201}
202
203impl Access for PcloudBackend {
204    type Reader = HttpBody;
205    type Writer = PcloudWriters;
206    type Lister = oio::PageLister<PcloudLister>;
207    type Deleter = oio::OneShotDeleter<PcloudDeleter>;
208
209    fn info(&self) -> Arc<AccessorInfo> {
210        self.core.info.clone()
211    }
212
213    async fn create_dir(&self, path: &str, _: OpCreateDir) -> Result<RpCreateDir> {
214        self.core.ensure_dir_exists(path).await?;
215        Ok(RpCreateDir::default())
216    }
217
218    async fn stat(&self, path: &str, _args: OpStat) -> Result<RpStat> {
219        let resp = self.core.stat(path).await?;
220
221        let status = resp.status();
222
223        match status {
224            StatusCode::OK => {
225                let bs = resp.into_body();
226                let resp: StatResponse =
227                    serde_json::from_reader(bs.reader()).map_err(new_json_deserialize_error)?;
228                let result = resp.result;
229                if result == 2010 || result == 2055 || result == 2002 {
230                    return Err(Error::new(ErrorKind::NotFound, format!("{resp:?}")));
231                }
232                if result != 0 {
233                    return Err(Error::new(ErrorKind::Unexpected, format!("{resp:?}")));
234                }
235
236                if let Some(md) = resp.metadata {
237                    let md = parse_stat_metadata(md);
238                    return md.map(RpStat::new);
239                }
240
241                Err(Error::new(ErrorKind::Unexpected, format!("{resp:?}")))
242            }
243            _ => Err(parse_error(resp)),
244        }
245    }
246
247    async fn read(&self, path: &str, args: OpRead) -> Result<(RpRead, Self::Reader)> {
248        let link = self.core.get_file_link(path).await?;
249
250        let resp = self.core.download(&link, 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 writer = PcloudWriter::new(self.core.clone(), path.to_string());
268
269        let w = oio::OneShotWriter::new(writer);
270
271        Ok((RpWrite::default(), w))
272    }
273
274    async fn delete(&self) -> Result<(RpDelete, Self::Deleter)> {
275        Ok((
276            RpDelete::default(),
277            oio::OneShotDeleter::new(PcloudDeleter::new(self.core.clone())),
278        ))
279    }
280
281    async fn list(&self, path: &str, _args: OpList) -> Result<(RpList, Self::Lister)> {
282        let l = PcloudLister::new(self.core.clone(), path);
283        Ok((RpList::default(), oio::PageLister::new(l)))
284    }
285
286    async fn copy(&self, from: &str, to: &str, _args: OpCopy) -> Result<RpCopy> {
287        self.core.ensure_dir_exists(to).await?;
288
289        let resp = if from.ends_with('/') {
290            self.core.copy_folder(from, to).await?
291        } else {
292            self.core.copy_file(from, to).await?
293        };
294
295        let status = resp.status();
296
297        match status {
298            StatusCode::OK => {
299                let bs = resp.into_body();
300                let resp: PcloudError =
301                    serde_json::from_reader(bs.reader()).map_err(new_json_deserialize_error)?;
302                let result = resp.result;
303                if result == 2009 || result == 2010 || result == 2055 || result == 2002 {
304                    return Err(Error::new(ErrorKind::NotFound, format!("{resp:?}")));
305                }
306                if result != 0 {
307                    return Err(Error::new(ErrorKind::Unexpected, format!("{resp:?}")));
308                }
309
310                Ok(RpCopy::default())
311            }
312            _ => Err(parse_error(resp)),
313        }
314    }
315
316    async fn rename(&self, from: &str, to: &str, _args: OpRename) -> Result<RpRename> {
317        self.core.ensure_dir_exists(to).await?;
318
319        let resp = if from.ends_with('/') {
320            self.core.rename_folder(from, to).await?
321        } else {
322            self.core.rename_file(from, to).await?
323        };
324
325        let status = resp.status();
326
327        match status {
328            StatusCode::OK => {
329                let bs = resp.into_body();
330                let resp: PcloudError =
331                    serde_json::from_reader(bs.reader()).map_err(new_json_deserialize_error)?;
332                let result = resp.result;
333                if result == 2009 || result == 2010 || result == 2055 || result == 2002 {
334                    return Err(Error::new(ErrorKind::NotFound, format!("{resp:?}")));
335                }
336                if result != 0 {
337                    return Err(Error::new(ErrorKind::Unexpected, format!("{resp:?}")));
338                }
339
340                Ok(RpRename::default())
341            }
342            _ => Err(parse_error(resp)),
343        }
344    }
345}