opendal/services/aliyun_drive/
backend.rs1use std::fmt::Debug;
19use std::fmt::Formatter;
20use std::sync::Arc;
21
22use bytes::Buf;
23use chrono::Utc;
24use http::Response;
25use http::StatusCode;
26use log::debug;
27use tokio::sync::Mutex;
28
29use super::core::*;
30use super::delete::AliyunDriveDeleter;
31use super::error::parse_error;
32use super::lister::AliyunDriveLister;
33use super::lister::AliyunDriveParent;
34use super::writer::AliyunDriveWriter;
35use crate::raw::*;
36use crate::services::AliyunDriveConfig;
37use crate::*;
38
39impl Configurator for AliyunDriveConfig {
40 type Builder = AliyunDriveBuilder;
41
42 #[allow(deprecated)]
43 fn into_builder(self) -> Self::Builder {
44 AliyunDriveBuilder {
45 config: self,
46 http_client: None,
47 }
48 }
49}
50
51#[doc = include_str!("docs.md")]
52#[derive(Default)]
53pub struct AliyunDriveBuilder {
54 config: AliyunDriveConfig,
55
56 #[deprecated(since = "0.53.0", note = "Use `Operator::update_http_client` instead")]
57 http_client: Option<HttpClient>,
58}
59
60impl Debug for AliyunDriveBuilder {
61 fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
62 let mut d = f.debug_struct("AliyunDriveBuilder");
63
64 d.field("config", &self.config);
65 d.finish_non_exhaustive()
66 }
67}
68
69impl AliyunDriveBuilder {
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 access_token(mut self, access_token: &str) -> Self {
85 self.config.access_token = Some(access_token.to_string());
86
87 self
88 }
89
90 pub fn client_id(mut self, client_id: &str) -> Self {
92 self.config.client_id = Some(client_id.to_string());
93
94 self
95 }
96
97 pub fn client_secret(mut self, client_secret: &str) -> Self {
99 self.config.client_secret = Some(client_secret.to_string());
100
101 self
102 }
103
104 pub fn refresh_token(mut self, refresh_token: &str) -> Self {
106 self.config.refresh_token = Some(refresh_token.to_string());
107
108 self
109 }
110
111 pub fn drive_type(mut self, drive_type: &str) -> Self {
113 self.config.drive_type = drive_type.to_string();
114
115 self
116 }
117
118 #[deprecated(since = "0.53.0", note = "Use `Operator::update_http_client` instead")]
125 #[allow(deprecated)]
126 pub fn http_client(mut self, client: HttpClient) -> Self {
127 self.http_client = Some(client);
128 self
129 }
130}
131
132impl Builder for AliyunDriveBuilder {
133 const SCHEME: Scheme = Scheme::AliyunDrive;
134 type Config = AliyunDriveConfig;
135
136 fn build(self) -> Result<impl Access> {
137 debug!("backend build started: {:?}", &self);
138
139 let root = normalize_root(&self.config.root.clone().unwrap_or_default());
140 debug!("backend use root {}", &root);
141
142 let sign = match self.config.access_token.clone() {
143 Some(access_token) if !access_token.is_empty() => {
144 AliyunDriveSign::Access(access_token)
145 }
146 _ => match (
147 self.config.client_id.clone(),
148 self.config.client_secret.clone(),
149 self.config.refresh_token.clone(),
150 ) {
151 (Some(client_id), Some(client_secret), Some(refresh_token)) if
152 !client_id.is_empty() && !client_secret.is_empty() && !refresh_token.is_empty() => {
153 AliyunDriveSign::Refresh(client_id, client_secret, refresh_token, None, 0)
154 }
155 _ => return Err(Error::new(
156 ErrorKind::ConfigInvalid,
157 "access_token and a set of client_id, client_secret, and refresh_token are both missing.")
158 .with_operation("Builder::build")
159 .with_context("service", Scheme::AliyunDrive)),
160 },
161 };
162
163 let drive_type = match self.config.drive_type.as_str() {
164 "" | "default" => DriveType::Default,
165 "resource" => DriveType::Resource,
166 "backup" => DriveType::Backup,
167 _ => {
168 return Err(Error::new(
169 ErrorKind::ConfigInvalid,
170 "drive_type is invalid.",
171 ))
172 }
173 };
174 debug!("backend use drive_type {drive_type:?}");
175
176 Ok(AliyunDriveBackend {
177 core: Arc::new(AliyunDriveCore {
178 info: {
179 let am = AccessorInfo::default();
180 am.set_scheme(Scheme::AliyunDrive)
181 .set_root(&root)
182 .set_native_capability(Capability {
183 stat: true,
184 create_dir: true,
185 read: true,
186 write: true,
187 write_can_multi: true,
188 write_multi_min_size: Some(100 * 1024),
190 write_multi_max_size: if cfg!(target_pointer_width = "64") {
192 Some(5 * 1024 * 1024 * 1024)
193 } else {
194 Some(usize::MAX)
195 },
196 delete: true,
197 copy: true,
198 rename: true,
199 list: true,
200 list_with_limit: true,
201 shared: true,
202 ..Default::default()
203 });
204
205 #[allow(deprecated)]
207 if let Some(client) = self.http_client {
208 am.update_http_client(|_| client);
209 }
210
211 am.into()
212 },
213 endpoint: "https://openapi.alipan.com".to_string(),
214 root,
215 drive_type,
216 signer: Arc::new(Mutex::new(AliyunDriveSigner {
217 drive_id: None,
218 sign,
219 })),
220 dir_lock: Arc::new(Mutex::new(())),
221 }),
222 })
223 }
224}
225
226#[derive(Clone, Debug)]
227pub struct AliyunDriveBackend {
228 core: Arc<AliyunDriveCore>,
229}
230
231impl Access for AliyunDriveBackend {
232 type Reader = HttpBody;
233 type Writer = AliyunDriveWriter;
234 type Lister = oio::PageLister<AliyunDriveLister>;
235 type Deleter = oio::OneShotDeleter<AliyunDriveDeleter>;
236
237 fn info(&self) -> Arc<AccessorInfo> {
238 self.core.info.clone()
239 }
240
241 async fn create_dir(&self, path: &str, _args: OpCreateDir) -> Result<RpCreateDir> {
242 self.core.ensure_dir_exists(path).await?;
243
244 Ok(RpCreateDir::default())
245 }
246
247 async fn rename(&self, from: &str, to: &str, _args: OpRename) -> Result<RpRename> {
248 if from == to {
249 return Ok(RpRename::default());
250 }
251 let res = self.core.get_by_path(from).await?;
252 let file: AliyunDriveFile =
253 serde_json::from_reader(res.reader()).map_err(new_json_serialize_error)?;
254 match self.core.get_by_path(to).await {
256 Err(err) if err.kind() == ErrorKind::NotFound => {}
257 Err(err) => return Err(err),
258 Ok(res) => {
259 let file: AliyunDriveFile =
260 serde_json::from_reader(res.reader()).map_err(new_json_serialize_error)?;
261 self.core.delete_path(&file.file_id).await?;
262 }
263 };
264
265 let parent_file_id = self.core.ensure_dir_exists(get_parent(to)).await?;
266 self.core.move_path(&file.file_id, &parent_file_id).await?;
267
268 let from_name = get_basename(from);
269 let to_name = get_basename(to);
270
271 if from_name != to_name {
272 self.core.update_path(&file.file_id, to_name).await?;
273 }
274
275 Ok(RpRename::default())
276 }
277
278 async fn copy(&self, from: &str, to: &str, _args: OpCopy) -> Result<RpCopy> {
279 if from == to {
280 return Ok(RpCopy::default());
281 }
282 let res = self.core.get_by_path(from).await?;
283 let file: AliyunDriveFile =
284 serde_json::from_reader(res.reader()).map_err(new_json_serialize_error)?;
285 match self.core.get_by_path(to).await {
287 Err(err) if err.kind() == ErrorKind::NotFound => {}
288 Err(err) => return Err(err),
289 Ok(res) => {
290 let file: AliyunDriveFile =
291 serde_json::from_reader(res.reader()).map_err(new_json_serialize_error)?;
292 self.core.delete_path(&file.file_id).await?;
293 }
294 };
295 let parent_path = get_parent(to);
298 let parent_file_id = self.core.ensure_dir_exists(parent_path).await?;
299
300 let auto_rename = file.parent_file_id == parent_file_id;
304 let res = self
305 .core
306 .copy_path(&file.file_id, &parent_file_id, auto_rename)
307 .await?;
308 let file: CopyResponse =
309 serde_json::from_reader(res.reader()).map_err(new_json_serialize_error)?;
310 let file_id = file.file_id;
311
312 let from_name = get_basename(from);
313 let to_name = get_basename(to);
314
315 if from_name != to_name {
316 self.core.update_path(&file_id, to_name).await?;
317 }
318
319 Ok(RpCopy::default())
320 }
321
322 async fn stat(&self, path: &str, _args: OpStat) -> Result<RpStat> {
323 let res = self.core.get_by_path(path).await?;
324 let file: AliyunDriveFile =
325 serde_json::from_reader(res.reader()).map_err(new_json_serialize_error)?;
326
327 if file.path_type == "folder" {
328 let meta = Metadata::new(EntryMode::DIR).with_last_modified(
329 file.updated_at
330 .parse::<chrono::DateTime<Utc>>()
331 .map_err(|e| {
332 Error::new(ErrorKind::Unexpected, "parse last modified time").set_source(e)
333 })?,
334 );
335
336 return Ok(RpStat::new(meta));
337 }
338
339 let mut meta = Metadata::new(EntryMode::FILE).with_last_modified(
340 file.updated_at
341 .parse::<chrono::DateTime<Utc>>()
342 .map_err(|e| {
343 Error::new(ErrorKind::Unexpected, "parse last modified time").set_source(e)
344 })?,
345 );
346 if let Some(v) = file.size {
347 meta = meta.with_content_length(v);
348 }
349 if let Some(v) = file.content_type {
350 meta = meta.with_content_type(v);
351 }
352
353 Ok(RpStat::new(meta))
354 }
355
356 async fn read(&self, path: &str, args: OpRead) -> Result<(RpRead, Self::Reader)> {
357 let res = self.core.get_by_path(path).await?;
358 let file: AliyunDriveFile =
359 serde_json::from_reader(res.reader()).map_err(new_json_serialize_error)?;
360 let resp = self.core.download(&file.file_id, args.range()).await?;
361
362 let status = resp.status();
363 match status {
364 StatusCode::OK | StatusCode::PARTIAL_CONTENT => {
365 Ok((RpRead::default(), resp.into_body()))
366 }
367 _ => {
368 let (part, mut body) = resp.into_parts();
369 let buf = body.to_buffer().await?;
370 Err(parse_error(Response::from_parts(part, buf)))
371 }
372 }
373 }
374
375 async fn delete(&self) -> Result<(RpDelete, Self::Deleter)> {
376 Ok((
377 RpDelete::default(),
378 oio::OneShotDeleter::new(AliyunDriveDeleter::new(self.core.clone())),
379 ))
380 }
381
382 async fn list(&self, path: &str, args: OpList) -> Result<(RpList, Self::Lister)> {
383 let parent = match self.core.get_by_path(path).await {
384 Err(err) if err.kind() == ErrorKind::NotFound => None,
385 Err(err) => return Err(err),
386 Ok(res) => {
387 let file: AliyunDriveFile =
388 serde_json::from_reader(res.reader()).map_err(new_json_serialize_error)?;
389 Some(AliyunDriveParent {
390 file_id: file.file_id,
391 path: path.to_string(),
392 updated_at: file.updated_at,
393 })
394 }
395 };
396
397 let l = AliyunDriveLister::new(self.core.clone(), parent, args.limit());
398
399 Ok((RpList::default(), oio::PageLister::new(l)))
400 }
401
402 async fn write(&self, path: &str, args: OpWrite) -> Result<(RpWrite, Self::Writer)> {
403 let parent_path = get_parent(path);
404 let parent_file_id = self.core.ensure_dir_exists(parent_path).await?;
405
406 match self.core.get_by_path(path).await {
408 Err(err) if err.kind() == ErrorKind::NotFound => {}
409 Err(err) => return Err(err),
410 Ok(res) => {
411 let file: AliyunDriveFile =
412 serde_json::from_reader(res.reader()).map_err(new_json_serialize_error)?;
413 self.core.delete_path(&file.file_id).await?;
414 }
415 };
416
417 let writer =
418 AliyunDriveWriter::new(self.core.clone(), &parent_file_id, get_basename(path), args);
419
420 Ok((RpWrite::default(), writer))
421 }
422}