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