use std::fmt::Debug;
use std::str::FromStr;
use std::sync::Arc;
use http::Response;
use http::StatusCode;
use log::debug;
use super::WEBDAV_SCHEME;
use super::config::WebdavConfig;
use super::core::*;
use super::deleter::WebdavDeleter;
use super::error::parse_error;
use super::lister::WebdavLister;
use super::writer::WebdavWriter;
use opendal_core::raw::oio;
use opendal_core::raw::*;
use opendal_core::*;
#[doc = include_str!("docs.md")]
#[derive(Default)]
pub struct WebdavBuilder {
pub(super) config: WebdavConfig,
}
impl Debug for WebdavBuilder {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("WebdavBuilder")
.field("config", &self.config)
.finish_non_exhaustive()
}
}
impl WebdavBuilder {
pub fn endpoint(mut self, endpoint: &str) -> Self {
self.config.endpoint = if endpoint.is_empty() {
None
} else {
Some(endpoint.to_string())
};
self
}
pub fn username(mut self, username: &str) -> Self {
if !username.is_empty() {
self.config.username = Some(username.to_owned());
}
self
}
pub fn password(mut self, password: &str) -> Self {
if !password.is_empty() {
self.config.password = Some(password.to_owned());
}
self
}
pub fn token(mut self, token: &str) -> Self {
if !token.is_empty() {
self.config.token = Some(token.to_string());
}
self
}
pub fn root(mut self, root: &str) -> Self {
self.config.root = if root.is_empty() {
None
} else {
Some(root.to_string())
};
self
}
pub fn disable_create_dir(mut self, disable: bool) -> Self {
self.config.disable_create_dir = disable;
self
}
pub fn enable_user_metadata(mut self, enable: bool) -> Self {
self.config.enable_user_metadata = enable;
self
}
pub fn user_metadata_prefix(mut self, prefix: &str) -> Self {
if !prefix.is_empty() {
self.config.user_metadata_prefix = Some(prefix.to_string());
}
self
}
pub fn user_metadata_uri(mut self, uri: &str) -> Self {
if !uri.is_empty() {
self.config.user_metadata_uri = Some(uri.to_string());
}
self
}
}
impl Builder for WebdavBuilder {
type Config = WebdavConfig;
fn build(self) -> Result<impl Access> {
debug!("backend build started: {:?}", &self);
let endpoint = match &self.config.endpoint {
Some(v) => v,
None => {
return Err(Error::new(ErrorKind::ConfigInvalid, "endpoint is empty")
.with_context("service", WEBDAV_SCHEME));
}
};
let server_path = http::Uri::from_str(endpoint)
.map_err(|err| {
Error::new(ErrorKind::ConfigInvalid, "endpoint is invalid")
.with_context("service", WEBDAV_SCHEME)
.set_source(err)
})?
.path()
.trim_end_matches('/')
.to_string();
let root = normalize_root(&self.config.root.clone().unwrap_or_default());
debug!("backend use root {root}");
let mut authorization = None;
if let Some(username) = &self.config.username {
authorization = Some(format_authorization_by_basic(
username,
self.config.password.as_deref().unwrap_or_default(),
)?);
}
if let Some(token) = &self.config.token {
authorization = Some(format_authorization_by_bearer(token)?)
}
let core = Arc::new(WebdavCore {
info: {
let am = AccessorInfo::default();
am.set_scheme(WEBDAV_SCHEME)
.set_root(&root)
.set_native_capability(Capability {
stat: true,
read: true,
write: true,
write_can_empty: true,
write_with_user_metadata: self.config.enable_user_metadata,
create_dir: true,
delete: true,
copy: !self.config.disable_copy,
rename: true,
list: true,
shared: true,
..Default::default()
});
am.into()
},
endpoint: endpoint.to_string(),
server_path,
authorization,
root,
user_metadata_prefix: self
.config
.user_metadata_prefix
.unwrap_or_else(|| DEFAULT_USER_METADATA_PREFIX.to_string()),
user_metadata_uri: self
.config
.user_metadata_uri
.unwrap_or_else(|| DEFAULT_USER_METADATA_URI.to_string()),
disable_create_dir: self.config.disable_create_dir,
});
Ok(WebdavBackend { core })
}
}
#[derive(Clone, Debug)]
pub struct WebdavBackend {
core: Arc<WebdavCore>,
}
impl Access for WebdavBackend {
type Reader = HttpBody;
type Writer = oio::OneShotWriter<WebdavWriter>;
type Lister = oio::PageLister<WebdavLister>;
type Deleter = oio::OneShotDeleter<WebdavDeleter>;
fn info(&self) -> Arc<AccessorInfo> {
self.core.info.clone()
}
async fn create_dir(&self, path: &str, _: OpCreateDir) -> Result<RpCreateDir> {
self.core.webdav_mkcol(path).await?;
Ok(RpCreateDir::default())
}
async fn stat(&self, path: &str, _: OpStat) -> Result<RpStat> {
let metadata = self.core.webdav_stat(path).await?;
Ok(RpStat::new(metadata))
}
async fn read(&self, path: &str, args: OpRead) -> Result<(RpRead, Self::Reader)> {
let resp = self.core.webdav_get(path, args.range(), &args).await?;
let status = resp.status();
match status {
StatusCode::OK | StatusCode::PARTIAL_CONTENT => {
Ok((RpRead::default(), resp.into_body()))
}
_ => {
let (part, mut body) = resp.into_parts();
let buf = body.to_buffer().await?;
Err(parse_error(Response::from_parts(part, buf)))
}
}
}
async fn write(&self, path: &str, args: OpWrite) -> Result<(RpWrite, Self::Writer)> {
if !self.core.disable_create_dir {
self.core.webdav_mkcol(get_parent(path)).await?;
}
Ok((
RpWrite::default(),
oio::OneShotWriter::new(WebdavWriter::new(self.core.clone(), args, path.to_string())),
))
}
async fn delete(&self) -> Result<(RpDelete, Self::Deleter)> {
Ok((
RpDelete::default(),
oio::OneShotDeleter::new(WebdavDeleter::new(self.core.clone())),
))
}
async fn list(&self, path: &str, args: OpList) -> Result<(RpList, Self::Lister)> {
Ok((
RpList::default(),
oio::PageLister::new(WebdavLister::new(self.core.clone(), path, args)),
))
}
async fn copy(&self, from: &str, to: &str, _args: OpCopy) -> Result<RpCopy> {
let resp = self.core.webdav_copy(from, to).await?;
let status = resp.status();
match status {
StatusCode::CREATED | StatusCode::NO_CONTENT => Ok(RpCopy::default()),
_ => Err(parse_error(resp)),
}
}
async fn rename(&self, from: &str, to: &str, _args: OpRename) -> Result<RpRename> {
let resp = self.core.webdav_move(from, to).await?;
let status = resp.status();
match status {
StatusCode::CREATED | StatusCode::NO_CONTENT | StatusCode::OK => {
Ok(RpRename::default())
}
_ => Err(parse_error(resp)),
}
}
}