move async in services

This commit is contained in:
grimhilt 2023-06-19 18:04:50 +02:00
parent 4cde39dffd
commit f1d552a31c
6 changed files with 147 additions and 147 deletions

View File

@ -5,7 +5,7 @@ use regex::Regex;
use crate::services::api::ApiError; use crate::services::api::ApiError;
use crate::services::req_props::{ReqProps, ObjProps}; use crate::services::req_props::{ReqProps, ObjProps};
use crate::services::download_files::DownloadFiles; use crate::services::download_files::DownloadFiles;
use crate::store::object; use crate::store::object::{self, add_blob, add_tree};
use crate::commands; use crate::commands;
use crate::utils::api::ApiProps; use crate::utils::api::ApiProps;
use crate::global::global::{DIR_PATH, set_dir_path}; use crate::global::global::{DIR_PATH, set_dir_path};
@ -51,31 +51,28 @@ pub fn clone(remote: Values<'_>) {
}; };
// request folder content // request folder content
let mut objs = vec![]; let res = ReqProps::new()
tokio::runtime::Runtime::new().unwrap().block_on(async { .set_request(relative_s.as_str(), &api_props)
let res = ReqProps::new() .gethref()
.set_request(relative_s.as_str(), &api_props) .getlastmodified()
.gethref() .send_req_multiple();
.getlastmodified()
.send_req_multiple() let mut objs = match res {
.await; Ok(o) => o,
objs = match res { Err(ApiError::IncorrectRequest(err)) => {
Ok(o) => o, eprintln!("fatal: {}", err.status());
Err(ApiError::IncorrectRequest(err)) => { std::process::exit(1);
eprintln!("fatal: {}", err.status()); },
std::process::exit(1); Err(ApiError::EmptyError(_)) => {
}, eprintln!("Failed to get body");
Err(ApiError::EmptyError(_)) => { vec![]
eprintln!("Failed to get body");
vec![]
}
Err(ApiError::RequestError(err)) => {
eprintln!("fatal: {}", err);
std::process::exit(1);
},
Err(ApiError::Unexpected(_)) => todo!()
} }
}); Err(ApiError::RequestError(err)) => {
eprintln!("fatal: {}", err);
std::process::exit(1);
},
Err(ApiError::Unexpected(_)) => todo!()
};
// create folder // create folder
if first_iter { if first_iter {
@ -90,14 +87,14 @@ pub fn clone(remote: Values<'_>) {
// create folder // create folder
let p = ref_path.clone().join(Path::new(&relative_s)); let p = ref_path.clone().join(Path::new(&relative_s));
if let Err(err) = DirBuilder::new().recursive(true).create(p.clone()) { if let Err(err) = DirBuilder::new().recursive(true).create(p.clone()) {
eprintln!("error: cannot create directory {}: {}", p.display(), err); eprintln!("err: cannot create directory {}: {}", p.display(), err);
} }
// add tree // add tree
let path_folder = p.strip_prefix(ref_path.clone()).unwrap(); let path_folder = p.strip_prefix(ref_path.clone()).unwrap();
let last_modified = folder.lastmodified.unwrap().timestamp_millis(); let lastmodified = folder.lastmodified.unwrap().timestamp_millis();
if object::add_tree(&path_folder, &last_modified.to_string()).is_err() { if let Err(err) = add_tree(&path_folder, &lastmodified.to_string()) {
eprintln!("error: cannot store object {}", path_folder.display()); eprintln!("err: saving ref of {}: {}", path_folder.display(), err);
} }
} }
@ -119,34 +116,32 @@ pub fn clone(remote: Values<'_>) {
fn download_files(ref_p: PathBuf, files: Vec<ObjProps>, api_props: &ApiProps) { fn download_files(ref_p: PathBuf, files: Vec<ObjProps>, api_props: &ApiProps) {
for obj in files { for obj in files {
tokio::runtime::Runtime::new().unwrap().block_on(async { let relative_s = &obj.clone().relative_s.unwrap();
let relative_s = &obj.clone().relative_s.unwrap(); let res = DownloadFiles::new()
let res = DownloadFiles::new() .set_url(&relative_s, api_props)
.set_url(&relative_s, api_props) .save(ref_p.clone());
.save(ref_p.clone()).await;
match res { match res {
Ok(()) => { Ok(()) => {
let relative_p = Path::new(&relative_s); let relative_p = Path::new(&relative_s);
let last_modified = obj.clone().lastmodified.unwrap().timestamp_millis(); let lastmodified = obj.clone().lastmodified.unwrap().timestamp_millis();
if let Err(_) = object::add_blob(relative_p, &last_modified.to_string()) { if let Err(err) = add_blob(relative_p, &lastmodified.to_string()) {
eprintln!("error saving reference of {}", relative_s.clone()); eprintln!("err: saving ref of {}: {}", relative_s.clone(), err);
}
},
Err(ApiError::Unexpected(_)) => {
eprintln!("error writing {}", relative_s);
},
Err(ApiError::IncorrectRequest(err)) => {
eprintln!("fatal: {}", err.status());
std::process::exit(1);
},
Err(ApiError::EmptyError(_)) => eprintln!("Failed to get body"),
Err(ApiError::RequestError(err)) => {
eprintln!("fatal: {}", err);
std::process::exit(1);
} }
},
Err(ApiError::Unexpected(_)) => {
eprintln!("err: writing {}", relative_s);
},
Err(ApiError::IncorrectRequest(err)) => {
eprintln!("fatal: {}", err.status());
std::process::exit(1);
},
Err(ApiError::EmptyError(_)) => eprintln!("Failed to get body"),
Err(ApiError::RequestError(err)) => {
eprintln!("fatal: {}", err);
std::process::exit(1);
} }
}); }
} }
} }

View File

@ -57,25 +57,22 @@ struct New {
impl PushChange for New { impl PushChange for New {
fn can_push(&self) -> PushState { fn can_push(&self) -> PushState {
// check if exist on server // check if exist on server
let file_infos = tokio::runtime::Runtime::new().unwrap().block_on(async { let res = ReqProps::new()
let res = ReqProps::new() .set_url(&self.obj.path.to_str().unwrap())
.set_url(&self.obj.path.to_str().unwrap()) .getlastmodified()
.getlastmodified() .send_req_single();
.send_req_single()
.await;
match res { let file_infos = match res {
Ok(obj) => Ok(Some(obj)), Ok(obj) => Ok(Some(obj)),
Err(ApiError::IncorrectRequest(err)) => { Err(ApiError::IncorrectRequest(err)) => {
if err.status() == 404 { if err.status() == 404 {
Ok(None) Ok(None)
} else { } else {
Err(()) Err(())
} }
}, },
Err(_) => Err(()), Err(_) => Err(()),
} };
});
if let Ok(infos) = file_infos { if let Ok(infos) = file_infos {
if let Some(info) = infos { if let Some(info) = infos {
@ -92,25 +89,22 @@ impl PushChange for New {
fn push(&self) { fn push(&self) {
let obj = &self.obj; let obj = &self.obj;
tokio::runtime::Runtime::new().unwrap().block_on(async { let res = UploadFile::new()
let res = UploadFile::new() .set_url(obj.path.to_str().unwrap())
.set_url(obj.path.to_str().unwrap()) .set_file(obj.path.clone())
.set_file(obj.path.clone()) .send_with_err();
.send_with_err()
.await;
match res { match res {
Err(ApiError::IncorrectRequest(err)) => { Err(ApiError::IncorrectRequest(err)) => {
eprintln!("fatal: error pushing file {}: {}", obj.name, err.status()); eprintln!("fatal: error pushing file {}: {}", obj.name, err.status());
std::process::exit(1); std::process::exit(1);
}, },
Err(ApiError::RequestError(_)) => { Err(ApiError::RequestError(_)) => {
eprintln!("fatal: request error pushing file {}", obj.name); eprintln!("fatal: request error pushing file {}", obj.name);
std::process::exit(1); std::process::exit(1);
}
_ => (),
} }
}); _ => (),
}
// update tree // update tree
add_blob(&obj.path.clone(), "todo_date"); add_blob(&obj.path.clone(), "todo_date");
@ -128,25 +122,22 @@ struct Deleted {
impl PushChange for Deleted { impl PushChange for Deleted {
fn can_push(&self) -> PushState { fn can_push(&self) -> PushState {
// check if exist on server // check if exist on server
let file_infos = tokio::runtime::Runtime::new().unwrap().block_on(async { let res = ReqProps::new()
let res = ReqProps::new() .set_url(&self.obj.path.to_str().unwrap())
.set_url(&self.obj.path.to_str().unwrap()) .getlastmodified()
.getlastmodified() .send_with_err();
.send_with_err()
.await;
match res { let file_infos = match res {
Ok(obj) => Ok(Some(obj)), Ok(obj) => Ok(Some(obj)),
Err(ApiError::IncorrectRequest(err)) => { Err(ApiError::IncorrectRequest(err)) => {
if err.status() == 404 { if err.status() == 404 {
Ok(None) Ok(None)
} else { } else {
Err(()) Err(())
} }
}, },
Err(_) => Err(()), Err(_) => Err(()),
} };
});
if let Ok(infos) = file_infos { if let Ok(infos) = file_infos {
if let Some(inf) = infos { if let Some(inf) = infos {
@ -164,24 +155,21 @@ impl PushChange for Deleted {
fn push(&self) { fn push(&self) {
let obj = &self.obj; let obj = &self.obj;
tokio::runtime::Runtime::new().unwrap().block_on(async { let res = DeletePath::new()
let res = DeletePath::new() .set_url(obj.path.to_str().unwrap())
.set_url(obj.path.to_str().unwrap()) .send_with_err();
.send_with_err()
.await;
match res { match res {
Err(ApiError::IncorrectRequest(err)) => { Err(ApiError::IncorrectRequest(err)) => {
eprintln!("fatal: error deleting file {}: {}", obj.name, err.status()); eprintln!("fatal: error deleting file {}: {}", obj.name, err.status());
std::process::exit(1); std::process::exit(1);
}, },
Err(ApiError::RequestError(_)) => { Err(ApiError::RequestError(_)) => {
eprintln!("fatal: request error deleting file {}", obj.name); eprintln!("fatal: request error deleting file {}", obj.name);
std::process::exit(1); std::process::exit(1);
}
_ => (),
} }
}); _ => (),
}
// update tree // update tree
rm_blob(&obj.path.clone()); rm_blob(&obj.path.clone());

View File

@ -21,10 +21,15 @@ impl DeletePath {
self.api_builder.send().await self.api_builder.send().await
} }
pub async fn send_with_err(&mut self) -> Result<String, ApiError> { pub fn send_with_err(&mut self) -> Result<String, ApiError> {
let res = self.send().await.map_err(ApiError::RequestError)?; let res = tokio::runtime::Runtime::new().unwrap().block_on(async {
self.send().await
}).map_err(ApiError::RequestError)?;
if res.status().is_success() { if res.status().is_success() {
let body = res.text().await.map_err(ApiError::EmptyError)?; let body = tokio::runtime::Runtime::new().unwrap().block_on(async {
res.text().await
}).map_err(ApiError::EmptyError)?;
Ok(body) Ok(body)
} else { } else {
Err(ApiError::IncorrectRequest(res)) Err(ApiError::IncorrectRequest(res))

View File

@ -38,18 +38,20 @@ impl DownloadFiles {
} }
} }
pub async fn save(&mut self, ref_p: PathBuf) -> Result<(), ApiError> { pub fn save(&mut self, ref_p: PathBuf) -> Result<(), ApiError> {
let p = ref_p.join(PathBuf::from(self.relative_ps.clone())); tokio::runtime::Runtime::new().unwrap().block_on(async {
let res = self.send().await.map_err(ApiError::RequestError)?; let p = ref_p.join(PathBuf::from(self.relative_ps.clone()));
if res.status().is_success() { let res = self.send().await.map_err(ApiError::RequestError)?;
let body = res.bytes().await.map_err(ApiError::EmptyError)?; if res.status().is_success() {
match DownloadFiles::write_file(p, &body.to_vec()) { let body = res.bytes().await.map_err(ApiError::EmptyError)?;
Err(_) => Err(ApiError::Unexpected(String::from(""))), match DownloadFiles::write_file(p, &body.to_vec()) {
Ok(_) => Ok(()), Err(_) => Err(ApiError::Unexpected(String::from(""))),
Ok(_) => Ok(()),
}
} else {
Err(ApiError::IncorrectRequest(res))
} }
} else { })
Err(ApiError::IncorrectRequest(res))
}
} }
fn write_file(path: PathBuf, content: &Vec<u8>) -> io::Result<()> { fn write_file(path: PathBuf, content: &Vec<u8>) -> io::Result<()> {

View File

@ -115,25 +115,30 @@ impl ReqProps {
self.api_builder.send().await self.api_builder.send().await
} }
pub async fn send_with_err(&mut self) -> Result<String, ApiError> { pub fn send_with_err(&mut self) -> Result<String, ApiError> {
let res = self.send().await.map_err(ApiError::RequestError)?; let res = tokio::runtime::Runtime::new().unwrap().block_on(async {
self.send().await
}).map_err(ApiError::RequestError)?;
if res.status().is_success() { if res.status().is_success() {
let body = res.text().await.map_err(ApiError::EmptyError)?; let body = tokio::runtime::Runtime::new().unwrap().block_on(async {
res.text().await
}).map_err(ApiError::EmptyError)?;
Ok(body) Ok(body)
} else { } else {
Err(ApiError::IncorrectRequest(res)) Err(ApiError::IncorrectRequest(res))
} }
} }
pub async fn send_req_multiple(&mut self) -> Result<Vec<ObjProps>, ApiError> { pub fn send_req_multiple(&mut self) -> Result<Vec<ObjProps>, ApiError> {
match self.send_with_err().await { match self.send_with_err() {
Ok(body) => Ok(self.parse(body, true)), Ok(body) => Ok(self.parse(body, true)),
Err(err) => Err(err), Err(err) => Err(err),
} }
} }
pub async fn send_req_single(&mut self) -> Result<ObjProps, ApiError> { pub fn send_req_single(&mut self) -> Result<ObjProps, ApiError> {
match self.send_with_err().await { match self.send_with_err() {
Ok(body) => { Ok(body) => {
let objs = self.parse(body, false); let objs = self.parse(body, false);
let obj = objs[0].clone(); let obj = objs[0].clone();

View File

@ -34,10 +34,15 @@ impl UploadFile {
self.api_builder.send().await self.api_builder.send().await
} }
pub async fn send_with_err(&mut self) -> Result<String, ApiError> { pub fn send_with_err(&mut self) -> Result<String, ApiError> {
let res = self.send().await.map_err(ApiError::RequestError)?; let res = tokio::runtime::Runtime::new().unwrap().block_on(async {
self.send().await
}).map_err(ApiError::RequestError)?;
if res.status().is_success() { if res.status().is_success() {
let body = res.text().await.map_err(ApiError::EmptyError)?; let body = tokio::runtime::Runtime::new().unwrap().block_on(async {
res.text().await
}).map_err(ApiError::EmptyError)?;
Ok(body) Ok(body)
} else { } else {
Err(ApiError::IncorrectRequest(res)) Err(ApiError::IncorrectRequest(res))