Skip to content

Commit

Permalink
async
Browse files Browse the repository at this point in the history
  • Loading branch information
wznmickey committed Apr 22, 2024
1 parent a853871 commit 5b8b07f
Show file tree
Hide file tree
Showing 2 changed files with 72 additions and 35 deletions.
52 changes: 36 additions & 16 deletions src/account.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,11 +2,12 @@ use crate::config::*;
use crate::course::*;
use crate::download::*;
use dialoguer::{theme::ColorfulTheme, Confirm};
use indicatif::ProgressBar;
use futures::future::join_all;
use indicatif::{ProgressBar, ProgressState, ProgressStyle};
use std::fmt::Write;
use std::fs;
use std::fs::*;
use std::rc::Rc;

use std::time::{SystemTime, UNIX_EPOCH};
pub struct Account {
config: Config,
Expand Down Expand Up @@ -90,7 +91,10 @@ impl Account {
}
}
pub fn download_files(&self) -> () {

let rt = tokio::runtime::Runtime::new().unwrap();
let msg = rt.block_on(self.download_files_help());
}
pub async fn download_files_help(&self) -> () {
for file in &self.need_download_files {
println!("{:?}", file.my_full_path);
}
Expand All @@ -101,21 +105,29 @@ impl Account {
.unwrap()
{
println!("Download files...");
let pb = ProgressBar::new(self.need_download_files.len() as u64);
let pb = ProgressBar::new(self.download_size);
pb.set_style(ProgressStyle::with_template("{spinner:.green} [{elapsed_precise}] [{wide_bar:.cyan/blue}] {bytes}/{total_bytes} ({eta})")
.unwrap()
.with_key("eta", |state: &ProgressState, w: &mut dyn Write| write!(w, "{:.1}s", state.eta().as_secs_f64()).unwrap())
.progress_chars("#>-"));
for file in &self.need_download_files {
println!("start downloading : {:?}", file.my_full_path);
// println!("start downloading : {:?}", file.my_full_path);
self.remote_data
.download_file(&file.my_full_path, file.url.as_str());
println!("finished: {:?}", file.my_full_path);
pb.inc(1);
.download_file(&file.my_full_path, file.url.as_str())
.await;
// println!("finished: {:?}", file.my_full_path);
pb.inc(file.size);
}
pb.finish_with_message("done");
} else {
println!("Do not download");
}
}
pub fn update_files(&self) -> () {

let rt = tokio::runtime::Runtime::new().unwrap();
let msg = rt.block_on(self.update_files_help());
}
pub async fn update_files_help(&self) -> () {
for file in &self.need_update_files {
println!("{:?}", file.my_full_path);
}
Expand All @@ -126,9 +138,13 @@ impl Account {
.unwrap()
{
println!("Update files...");
let pb = ProgressBar::new(self.need_update_files.len() as u64);
for file in &self.need_update_files {
println!("start updating : {:?}", file.my_full_path);
let pb = ProgressBar::new(self.update_size);
pb.set_style(ProgressStyle::with_template("{spinner:.green} [{elapsed_precise}] [{wide_bar:.cyan/blue}] {bytes}/{total_bytes} ({eta})")
.unwrap()
.with_key("eta", |state: &ProgressState, w: &mut dyn Write| write!(w, "{:.1}s", state.eta().as_secs_f64()).unwrap())
.progress_chars("#>-"));
let result = join_all(self.need_update_files.iter().map(|file| async {
// println!("start updating : {:?}", file.my_full_path);
let x = SystemTime::now()
.duration_since(UNIX_EPOCH)
.unwrap()
Expand All @@ -140,10 +156,14 @@ impl Account {
.push(x + "_" + file.my_full_path.file_name().unwrap().to_str().unwrap());
fs::copy(&file.my_full_path, my_full_path_old);
self.remote_data
.download_file(&file.my_full_path, file.url.as_str());
println!("finished: {:?}", file.my_full_path);
pb.inc(1);
}
.download_file(&file.my_full_path, file.url.as_str())
.await;
// println!("finished: {:?}", file.my_full_path);
pb.inc(file.size);
}));
// for file in &self.need_update_files {

// }
pb.finish_with_message("done");
} else {
println!("Do not update");
Expand Down
55 changes: 36 additions & 19 deletions src/download.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ use crate::course::*;
use reqwest::blocking;
use reqwest::blocking::Response;
use reqwest::header;
use reqwest::*;
use reqwest::{self};
use serde_json::Value;
// use std::fs;
Expand All @@ -12,6 +13,7 @@ use std::rc::Rc;
pub struct RemoteData {
client: reqwest::blocking::Client,
url: String,
async_client: reqwest::Client,
}

impl RemoteData {
Expand All @@ -20,10 +22,14 @@ impl RemoteData {
header.insert("Authorization", header::HeaderValue::from_str(key).unwrap());
Self {
client: blocking::ClientBuilder::new()
.default_headers(header)
.default_headers(header.clone())
.build()
.unwrap(),
url: url.to_string(),
async_client: reqwest::ClientBuilder::new()
.default_headers(header)
.build()
.unwrap(),
}
}
fn get_remote_resource(&self, url: &str) -> Vec<Response> {
Expand Down Expand Up @@ -149,24 +155,35 @@ impl RemoteData {
ans
}

pub fn download_file(&self, path: &Path, url: &str) -> () {
let file = std::fs::File::create(path);
let _ = match || -> Result<(), Box<dyn std::error::Error>> {
match file {
Ok(mut file) => {
let temp = self.client.get(url).send()?;
file.write(&temp.bytes()?)?;
}
Err(e) => {
println!("{e}");
}
}
Ok(())
}() {
Ok(_) => {}
Err(e) => {
println!("{e}");
pub async fn download_file(&self, path: &Path, url: &str) -> () {
let temp = self.async_client.get(url).send().await;
match temp {
Ok(temp) => {
let temp = &temp.bytes().await;
match temp {
Ok(temp) => {
let temp_file = std::fs::File::create(path);
let mut file: std::fs::File;
match temp_file {
Err(e) => {
println!("{e}");
return;
}
Ok(temp) => file = temp,
};
match file.write(temp) {
Ok(_) => {}
Err(e) => {
println!("{e}");
}
};
}
Err(e) => {
println!("{e}")
}
};
}
};
Err(e) => println!("{e}"),
}
}
}

0 comments on commit 5b8b07f

Please sign in to comment.