move creation of downloaded file in service

This commit is contained in:
grimhilt
2023-06-17 00:37:12 +02:00
parent 0bf5fb76e0
commit b911ad8606
7 changed files with 94 additions and 35 deletions

View File

@@ -9,6 +9,7 @@ pub enum ApiError {
IncorrectRequest(reqwest::Response),
EmptyError(reqwest::Error),
RequestError(reqwest::Error),
Unexpected(String),
}
pub struct ApiBuilder {
@@ -47,6 +48,17 @@ impl ApiBuilder {
self
}
pub fn build_request_remote(&mut self, meth: Method, path: &str) -> &mut ApiBuilder {
dotenv().ok();
let host = env::var("HOST").unwrap();
let mut url = String::from(host);
url.push_str("/");
url.push_str(path);
dbg!(url.clone());
self.request = Some(self.client.request(meth, url));
self
}
fn set_auth(&mut self) -> &mut ApiBuilder {
// todo if not exist
dotenv().ok();

View File

@@ -1,18 +1,29 @@
use crate::services::api::{ApiBuilder, ApiError};
use std::path::PathBuf;
use reqwest::{Method, IntoUrl, Response, Error};
use crate::utils::api::get_local_path_t;
use std::fs::OpenOptions;
use std::io::{self, Write};
pub struct DownloadFiles {
api_builder: ApiBuilder,
path: String,
}
impl DownloadFiles {
pub fn new<U: IntoUrl>(url: U) -> Self {
pub fn new() -> Self {
DownloadFiles {
api_builder: ApiBuilder::new()
.set_request(Method::GET, url),
api_builder: ApiBuilder::new(),
path: String::from(""),
}
}
pub fn set_url_with_remote(&mut self, url: &str) -> &mut DownloadFiles {
self.path = get_local_path_t(url.clone()).strip_prefix("/").unwrap().to_string();
self.api_builder.build_request_remote(Method::GET, url);
self
}
pub async fn send(&mut self) -> Result<Response, Error> {
self.api_builder.send().await
}
@@ -26,4 +37,28 @@ impl DownloadFiles {
Err(ApiError::IncorrectRequest(res))
}
}
pub async fn save(&mut self, local_path: PathBuf) -> Result<(), ApiError> {
let p = local_path.join(PathBuf::from(self.path.clone()));
let res = self.send().await.map_err(ApiError::RequestError)?;
if res.status().is_success() {
let body = res.bytes().await.map_err(ApiError::EmptyError)?;
match DownloadFiles::write_file(p, &body.to_vec()) {
Err(_) => Err(ApiError::Unexpected(String::from(""))),
Ok(_) => Ok(()),
}
} else {
Err(ApiError::IncorrectRequest(res))
}
}
fn write_file(path: PathBuf, content: &Vec<u8>) -> io::Result<()> {
let mut f = OpenOptions::new()
.write(true)
.create(true)
.open(path.clone())?;
f.write_all(&content)?;
Ok(())
}
}

View File

@@ -41,7 +41,8 @@ impl ListFolders {
Err(ApiError::RequestError(err)) => {
eprintln!("fatal: {}", err);
std::process::exit(1);
}
},
_ => todo!(),
}
}
}