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
177                            create_dir: true,
178
179                            read: true,
180
181                            write: true,
182
183                            delete: true,
184                            rename: true,
185                            copy: true,
186
187                            list: true,
188
189                            shared: true,
190
191                            ..Default::default()
192                        });
193
194                    // allow deprecated api here for compatibility
195                    #[allow(deprecated)]
196                    if let Some(client) = self.http_client {
197                        am.update_http_client(|_| client);
198                    }
199
200                    am.into()
201                },
202                root,
203                endpoint: self.config.endpoint.clone(),
204                username,
205                password,
206            }),
207        })
208    }
209}
210
211/// Backend for Pcloud services.
212#[derive(Debug, Clone)]
213pub struct PcloudBackend {
214    core: Arc<PcloudCore>,
215}
216
217impl Access for PcloudBackend {
218    type Reader = HttpBody;
219    type Writer = PcloudWriters;
220    type Lister = oio::PageLister<PcloudLister>;
221    type Deleter = oio::OneShotDeleter<PcloudDeleter>;
222
223    fn info(&self) -> Arc<AccessorInfo> {
224        self.core.info.clone()
225    }
226
227    async fn create_dir(&self, path: &str, _: OpCreateDir) -> Result<RpCreateDir> {
228        self.core.ensure_dir_exists(path).await?;
229        Ok(RpCreateDir::default())
230    }
231
232    async fn stat(&self, path: &str, _args: OpStat) -> Result<RpStat> {
233        let resp = self.core.stat(path).await?;
234
235        let status = resp.status();
236
237        match status {
238            StatusCode::OK => {
239                let bs = resp.into_body();
240                let resp: StatResponse =
241                    serde_json::from_reader(bs.reader()).map_err(new_json_deserialize_error)?;
242                let result = resp.result;
243                if result == 2010 || result == 2055 || result == 2002 {
244                    return Err(Error::new(ErrorKind::NotFound, format!("{resp:?}")));
245                }
246                if result != 0 {
247                    return Err(Error::new(ErrorKind::Unexpected, format!("{resp:?}")));
248                }
249
250                if let Some(md) = resp.metadata {
251                    let md = parse_stat_metadata(md);
252                    return md.map(RpStat::new);
253                }
254
255                Err(Error::new(ErrorKind::Unexpected, format!("{resp:?}")))
256            }
257            _ => Err(parse_error(resp)),
258        }
259    }
260
261    async fn read(&self, path: &str, args: OpRead) -> Result<(RpRead, Self::Reader)> {
262        let link = self.core.get_file_link(path).await?;
263
264        let resp = self.core.download(&link, args.range()).await?;
265
266        let status = resp.status();
267
268        match status {
269            StatusCode::OK | StatusCode::PARTIAL_CONTENT => {
270                Ok((RpRead::default(), resp.into_body()))
271            }
272            _ => {
273                let (part, mut body) = resp.into_parts();
274                let buf = body.to_buffer().await?;
275                Err(parse_error(Response::from_parts(part, buf)))
276            }
277        }
278    }
279
280    async fn write(&self, path: &str, _args: OpWrite) -> Result<(RpWrite, Self::Writer)> {
281        let writer = PcloudWriter::new(self.core.clone(), path.to_string());
282
283        let w = oio::OneShotWriter::new(writer);
284
285        Ok((RpWrite::default(), w))
286    }
287
288    async fn delete(&self) -> Result<(RpDelete, Self::Deleter)> {
289        Ok((
290            RpDelete::default(),
291            oio::OneShotDeleter::new(PcloudDeleter::new(self.core.clone())),
292        ))
293    }
294
295    async fn list(&self, path: &str, _args: OpList) -> Result<(RpList, Self::Lister)> {
296        let l = PcloudLister::new(self.core.clone(), path);
297        Ok((RpList::default(), oio::PageLister::new(l)))
298    }
299
300    async fn copy(&self, from: &str, to: &str, _args: OpCopy) -> Result<RpCopy> {
301        self.core.ensure_dir_exists(to).await?;
302
303        let resp = if from.ends_with('/') {
304            self.core.copy_folder(from, to).await?
305        } else {
306            self.core.copy_file(from, to).await?
307        };
308
309        let status = resp.status();
310
311        match status {
312            StatusCode::OK => {
313                let bs = resp.into_body();
314                let resp: PcloudError =
315                    serde_json::from_reader(bs.reader()).map_err(new_json_deserialize_error)?;
316                let result = resp.result;
317                if result == 2009 || result == 2010 || result == 2055 || result == 2002 {
318                    return Err(Error::new(ErrorKind::NotFound, format!("{resp:?}")));
319                }
320                if result != 0 {
321                    return Err(Error::new(ErrorKind::Unexpected, format!("{resp:?}")));
322                }
323
324                Ok(RpCopy::default())
325            }
326            _ => Err(parse_error(resp)),
327        }
328    }
329
330    async fn rename(&self, from: &str, to: &str, _args: OpRename) -> Result<RpRename> {
331        self.core.ensure_dir_exists(to).await?;
332
333        let resp = if from.ends_with('/') {
334            self.core.rename_folder(from, to).await?
335        } else {
336            self.core.rename_file(from, to).await?
337        };
338
339        let status = resp.status();
340
341        match status {
342            StatusCode::OK => {
343                let bs = resp.into_body();
344                let resp: PcloudError =
345                    serde_json::from_reader(bs.reader()).map_err(new_json_deserialize_error)?;
346                let result = resp.result;
347                if result == 2009 || result == 2010 || result == 2055 || result == 2002 {
348                    return Err(Error::new(ErrorKind::NotFound, format!("{resp:?}")));
349                }
350                if result != 0 {
351                    return Err(Error::new(ErrorKind::Unexpected, format!("{resp:?}")));
352                }
353
354                Ok(RpRename::default())
355            }
356            _ => Err(parse_error(resp)),
357        }
358    }
359}