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