hoslo commented on code in PR #3771: URL: https://github.com/apache/incubator-opendal/pull/3771#discussion_r1429927777
########## core/src/services/seafile/backend.rs: ########## @@ -0,0 +1,343 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. + +use async_trait::async_trait; +use http::StatusCode; +use log::debug; +use serde::Deserialize; +use std::collections::HashMap; +use std::fmt::Debug; +use std::fmt::Formatter; +use std::sync::Arc; +use tokio::sync::RwLock; + +use super::core::parse_dir_detail; +use super::core::parse_file_detail; +use super::core::SeafileCore; +use super::error::parse_error; +use super::lister::SeafileLister; +use super::writer::SeafileWriter; +use super::writer::SeafileWriters; +use crate::raw::*; +use crate::services::seafile::core::AuthInfo; +use crate::*; + +/// Config for backblaze seafile services support. +#[derive(Default, Deserialize)] +#[serde(default)] +#[non_exhaustive] +pub struct SeafileConfig { + /// root of this backend. + /// + /// All operations will happen under this root. + pub root: Option<String>, + /// server address of this backend. + /// + /// - If server is set, we will take user's input first. + /// - If not, we will try to load it from environment. + pub server: Option<String>, + /// username of this backend. + /// + /// - If username is set, we will take user's input first. + /// - If not, we will try to load it from environment. + pub username: Option<String>, + /// password of this backend. + /// + /// - If password is set, we will take user's input first. + /// - If not, we will try to load it from environment. Review Comment: The description of the environment variable has been removed. ########## core/src/services/seafile/core.rs: ########## @@ -0,0 +1,405 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. + +use bytes::Bytes; +use http::header; +use http::Request; +use http::Response; +use http::StatusCode; +use serde::Deserialize; +use std::sync::Arc; +use tokio::sync::RwLock; + +use std::fmt::Debug; +use std::fmt::Formatter; + +use crate::raw::*; +use crate::*; + +use super::error::parse_error; + +/// Core of [seafile](https://www.seafile.com) services support. +#[derive(Clone)] +pub struct SeafileCore { + /// The root of this core. + pub root: String, + /// The server of this backend. + pub server: String, + /// The username of this backend. + pub username: String, + /// The password id of this backend. + pub password: String, + /// The repo name of this backend. + pub repo_name: String, + + /// auth info of this backend. + pub auth_info: Arc<RwLock<AuthInfo>>, + + pub client: HttpClient, +} + +impl Debug for SeafileCore { + fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result { + f.debug_struct("Backend") + .field("root", &self.root) + .field("server", &self.server) + .field("username", &self.username) + .field("repo_name", &self.repo_name) + .finish_non_exhaustive() + } +} + +impl SeafileCore { + #[inline] + pub async fn send(&self, req: Request<AsyncBody>) -> Result<Response<IncomingAsyncBody>> { + self.client.send(req).await + } + + /// get auth info + pub async fn get_auth_info(&self) -> Result<AuthInfo> { + { + let auth_info = self.auth_info.read().await; + + if !auth_info.token.is_empty() { + return Ok(auth_info.clone()); + } + } + + { + let mut auth_info = self.auth_info.write().await; + let body = format!( + "username={}&password={}", + percent_encode_path(&self.username), + percent_encode_path(&self.password) + ); + let req = Request::post(format!("{}/api2/auth-token/", self.server)) + .header(header::CONTENT_TYPE, "application/x-www-form-urlencoded") + .body(AsyncBody::Bytes(Bytes::from(body))) + .map_err(new_request_build_error)?; + + let resp = self.client.send(req).await?; + let status = resp.status(); + + match status { + StatusCode::OK => { + let resp_body = &resp.into_body().bytes().await?; + let auth_response = serde_json::from_slice::<AuthTokenResponse>(resp_body) + .map_err(new_json_deserialize_error)?; + auth_info.token = auth_response.token; + } + _ => { + return Err(parse_error(resp).await?); + } + } + + let url = format!("{}/api2/repos", self.server); + + let req = Request::get(url) + .header(header::AUTHORIZATION, format!("Token {}", auth_info.token)) + .body(AsyncBody::Empty) + .map_err(new_request_build_error)?; + + let resp = self.client.send(req).await?; + + let status = resp.status(); + + match status { + StatusCode::OK => { + let resp_body = &resp.into_body().bytes().await?; + let list_library_response = + serde_json::from_slice::<Vec<ListLibraryResponse>>(resp_body) + .map_err(new_json_deserialize_error)?; + + for library in list_library_response { + if library.name == self.repo_name { + auth_info.repo_id = library.id; + break; + } + } + + // repo not found + if auth_info.repo_id.is_empty() { + return Err(Error::new( + ErrorKind::NotFound, + &format!("repo {} not found", self.repo_name), + )); + } + } + _ => { + return Err(parse_error(resp).await?); + } + } + Ok(auth_info.clone()) + } + } +} + +impl SeafileCore { + /// get upload url + pub async fn get_upload_url(&self) -> Result<String> { + let auth_info = self.get_auth_info().await?; + + let req = Request::get(format!( + "{}/api2/repos/{}/upload-link/", + self.server, auth_info.repo_id + )); + + let req = req + .header(header::AUTHORIZATION, format!("Token {}", auth_info.token)) + .body(AsyncBody::Empty) + .map_err(new_request_build_error)?; + + let resp = self.send(req).await?; + let status = resp.status(); + + match status { + StatusCode::OK => { + let resp_body = &resp.into_body().bytes().await?; + let upload_url = serde_json::from_slice::<String>(resp_body) + .map_err(new_json_deserialize_error)?; + Ok(upload_url) + } + _ => Err(parse_error(resp).await?), + } + } + + /// get download + pub async fn get_download_url(&self, path: &str) -> Result<String> { + let path = build_abs_path(&self.root, path); + let path = percent_encode_path(&path); + + let auth_info = self.get_auth_info().await?; + + let req = Request::get(format!( + "{}/api2/repos/{}/file/?p={}", + self.server, auth_info.repo_id, path + )); + + let req = req + .header(header::AUTHORIZATION, format!("Token {}", auth_info.token)) Review Comment: fix -- This is an automated message from the Apache Git Service. To respond to the message, please log on to GitHub and use the URL above to go to the specific comment. To unsubscribe, e-mail: [email protected] For queries about this service, please contact Infrastructure at: [email protected]
