diff --git a/src-tauri/src/utils.rs b/src-tauri/src/utils.rs index f3426ca..c20404c 100644 --- a/src-tauri/src/utils.rs +++ b/src-tauri/src/utils.rs @@ -2,12 +2,14 @@ use futures_util::StreamExt; use reqwest; use sevenz_rust::Password; use std::path::Path; +use std::time::{Duration, Instant}; use std::{fs::File, io::Write}; use tauri::{AppHandle, Manager}; use crate::app_profile::ProgressPayload; const LETTERS: &str = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"; +const EMIT_BUFFER_RATE: f64 = 1.0 / 15.0; pub fn clear_folder(path: &Path) -> Result<(), String> { std::fs::remove_dir_all(path).ok(); @@ -27,13 +29,8 @@ pub async fn download( url: &str, output_path: &Path, ) -> Result<(), String> { - // Create the downloading client - let client = reqwest::Client::new(); - // Send the initial request - let download = client - .get(url) - .send() + let download = reqwest::get(url) .await .map_err(|e| format!("Failed to initialize download from `{}`.\n{:?}", &url, e))?; let total_size = download.content_length().unwrap(); @@ -49,6 +46,8 @@ pub async fn download( let mut current_downloaded: u64 = 0; let mut stream = download.bytes_stream(); + let mut emit_timer = Instant::now(); + // Download into the file while let Some(item) = stream.next().await { let chunk = item.map_err(|e| format!("Error while downloading file.\n{:?}", e))?; @@ -57,21 +56,25 @@ pub async fn download( // Cap the downloaded at the total size current_downloaded += chunk.len() as u64; - if current_downloaded > total_size { current_downloaded = total_size; } // Emit the download progress if let Some(app) = app { - let _ = app.emit_all( - "progress_info", - ProgressPayload { - state: "downloading".to_string(), - current: current_downloaded, - total: total_size, - }, - ); + // Emitting too often could cause crashes, so buffer it to the buffer rate + if emit_timer.elapsed() >= Duration::from_secs_f64(EMIT_BUFFER_RATE) { + let _ = app.emit_all( + "progress_info", + ProgressPayload { + state: "downloading".to_string(), + current: current_downloaded, + total: total_size, + }, + ); + + emit_timer = Instant::now(); + } } }