use std::collections::HashMap;
use std::fmt::Debug;
use std::fmt::Formatter;
use std::sync::Arc;
use bytes::Buf;
use http::StatusCode;
use log::debug;
use serde::Deserialize;
use super::core::*;
use super::error::parse_error;
use super::lister::YandexDiskLister;
use super::writer::YandexDiskWriter;
use super::writer::YandexDiskWriters;
use crate::raw::*;
use crate::services::yandex_disk::reader::YandexDiskReader;
use crate::*;
#[derive(Default, Deserialize)]
#[serde(default)]
#[non_exhaustive]
pub struct YandexDiskConfig {
pub root: Option<String>,
pub access_token: String,
}
impl Debug for YandexDiskConfig {
fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
let mut ds = f.debug_struct("Config");
ds.field("root", &self.root);
ds.finish()
}
}
#[doc = include_str!("docs.md")]
#[derive(Default)]
pub struct YandexDiskBuilder {
config: YandexDiskConfig,
http_client: Option<HttpClient>,
}
impl Debug for YandexDiskBuilder {
fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
let mut d = f.debug_struct("YandexDiskBuilder");
d.field("config", &self.config);
d.finish_non_exhaustive()
}
}
impl YandexDiskBuilder {
pub fn root(&mut self, root: &str) -> &mut Self {
self.config.root = if root.is_empty() {
None
} else {
Some(root.to_string())
};
self
}
pub fn access_token(&mut self, access_token: &str) -> &mut Self {
self.config.access_token = access_token.to_string();
self
}
pub fn http_client(&mut self, client: HttpClient) -> &mut Self {
self.http_client = Some(client);
self
}
}
impl Builder for YandexDiskBuilder {
const SCHEME: Scheme = Scheme::YandexDisk;
type Accessor = YandexDiskBackend;
fn from_map(map: HashMap<String, String>) -> Self {
let config = YandexDiskConfig::deserialize(ConfigDeserializer::new(map))
.expect("config deserialize must succeed");
YandexDiskBuilder {
config,
http_client: None,
}
}
fn build(&mut self) -> Result<Self::Accessor> {
debug!("backend build started: {:?}", &self);
let root = normalize_root(&self.config.root.clone().unwrap_or_default());
debug!("backend use root {}", &root);
if self.config.access_token.is_empty() {
return Err(
Error::new(ErrorKind::ConfigInvalid, "access_token is empty")
.with_operation("Builder::build")
.with_context("service", Scheme::YandexDisk),
);
}
let client = if let Some(client) = self.http_client.take() {
client
} else {
HttpClient::new().map_err(|err| {
err.with_operation("Builder::build")
.with_context("service", Scheme::YandexDisk)
})?
};
Ok(YandexDiskBackend {
core: Arc::new(YandexDiskCore {
root,
access_token: self.config.access_token.clone(),
client,
}),
})
}
}
#[derive(Debug, Clone)]
pub struct YandexDiskBackend {
core: Arc<YandexDiskCore>,
}
impl Access for YandexDiskBackend {
type Reader = YandexDiskReader;
type Writer = YandexDiskWriters;
type Lister = oio::PageLister<YandexDiskLister>;
type BlockingReader = ();
type BlockingWriter = ();
type BlockingLister = ();
fn info(&self) -> AccessorInfo {
let mut am = AccessorInfo::default();
am.set_scheme(Scheme::YandexDisk)
.set_root(&self.core.root)
.set_native_capability(Capability {
stat: true,
create_dir: true,
read: true,
write: true,
write_can_empty: true,
delete: true,
rename: true,
copy: true,
list: true,
list_with_limit: true,
..Default::default()
});
am
}
async fn create_dir(&self, path: &str, _: OpCreateDir) -> Result<RpCreateDir> {
self.core.ensure_dir_exists(path).await?;
Ok(RpCreateDir::default())
}
async fn rename(&self, from: &str, to: &str, _args: OpRename) -> Result<RpRename> {
self.core.ensure_dir_exists(to).await?;
let resp = self.core.move_object(from, to).await?;
let status = resp.status();
match status {
StatusCode::OK | StatusCode::CREATED => Ok(RpRename::default()),
_ => Err(parse_error(resp).await?),
}
}
async fn copy(&self, from: &str, to: &str, _args: OpCopy) -> Result<RpCopy> {
self.core.ensure_dir_exists(to).await?;
let resp = self.core.copy(from, to).await?;
let status = resp.status();
match status {
StatusCode::OK | StatusCode::CREATED => Ok(RpCopy::default()),
_ => Err(parse_error(resp).await?),
}
}
async fn read(&self, path: &str, args: OpRead) -> Result<(RpRead, Self::Reader)> {
Ok((
RpRead::default(),
YandexDiskReader::new(self.core.clone(), path, args),
))
}
async fn stat(&self, path: &str, _args: OpStat) -> Result<RpStat> {
let resp = self.core.metainformation(path, None, None).await?;
let status = resp.status();
match status {
StatusCode::OK => {
let bs = resp.into_body();
let mf: MetainformationResponse =
serde_json::from_reader(bs.reader()).map_err(new_json_deserialize_error)?;
parse_info(mf).map(RpStat::new)
}
_ => Err(parse_error(resp).await?),
}
}
async fn write(&self, path: &str, _args: OpWrite) -> Result<(RpWrite, Self::Writer)> {
let writer = YandexDiskWriter::new(self.core.clone(), path.to_string());
let w = oio::OneShotWriter::new(writer);
Ok((RpWrite::default(), w))
}
async fn delete(&self, path: &str, _: OpDelete) -> Result<RpDelete> {
let resp = self.core.delete(path).await?;
let status = resp.status();
match status {
StatusCode::OK => Ok(RpDelete::default()),
StatusCode::NO_CONTENT => Ok(RpDelete::default()),
StatusCode::ACCEPTED => Ok(RpDelete::default()),
StatusCode::NOT_FOUND => Ok(RpDelete::default()),
_ => Err(parse_error(resp).await?),
}
}
async fn list(&self, path: &str, args: OpList) -> Result<(RpList, Self::Lister)> {
let l = YandexDiskLister::new(self.core.clone(), path, args.limit());
Ok((RpList::default(), oio::PageLister::new(l)))
}
}