otimize o código rust use serde::{Deserialize, Serialize}; use std::path::{Path,…
- User
otimize o código rust
use serde::{Deserialize, Serialize}; use std::path::{Path, PathBuf}; use tauri::{AppHandle, Emitter}; use reqwest::Client; use tokio::fs; use tokio::io::AsyncWriteExt; use std::time::{Duration, Instant};
#[derive(Deserialize, Clone)] struct PatchEntry { file_name: String, }
#[derive(Serialize, Clone)] struct DownloadInfo { current_file: usize, total_files: usize, file_name: String, downloaded_bytes: u64, total_bytes: u64, speed: f64, }
#[derive(Serialize, Clone)] struct DownloadStatus { status: String, additional_info: Option, }
fn get_exe_dir() -> PathBuf { std::env::current_exe().unwrap().parent().unwrap().to_path_buf() }
async fn dir_exists(path: &Path) -> Result<bool, std::io::Error> { match fs::metadata(path).await { Ok(metadata) => Ok(metadata.is_dir()), Err(err) if err.kind() == std::io::ErrorKind::NotFound => Ok(false), Err(err) => Err(err), } }
async fn read_patch_file(path: &Path) -> Result<Vec, String> { let content = fs::read_to_string(path).await.map_err(|e| e.to_string())?; let patches: Vec = serde_json::from_str(&content).map_err(|e| e.to_string())?; Ok(patches) }
async fn emit_download_status(app_handle: &AppHandle, status: &str, additional_info: Option,) -> Result<(), String> { app_handle.emit("download_status", DownloadStatus {status: status.to_string(), additional_info }).map_err(|e| e.to_string()) }
async fn download_file( app_handle: &AppHandle, client: &Client, entry: &PatchEntry, download_dir: &Path, current_file: usize, total_files: usize, ) -> Result<(), String> {
let file_path = download_dir.join(&entry.file_name); loop { let url = format!("https://hil-speed.hetzner.com/{}", entry.file_name); let mut response = match client.get(&url).send().await { Ok(resp) => { if resp.status().is_success() { resp } else { return Err(format!( "Failed to download '{}': HTTP {}", entry.file_name, resp.status() )); } } Err(_) => { let mut countdown = 15; while countdown > 0 { emit_download_status(app_handle, "Reconnecting", Some(countdown.to_string())).await?; tokio::time::sleep(Duration::from_secs(1)).await; countdown -= 1; } continue; // Try again } }; let total_bytes = response.content_length().unwrap_or(0); // Remove existing file if any let _ = fs::remove_file(&file_path).await; let mut file = fs::File::create(&file_path).await.map_err(|e| e.to_string())?; let mut downloaded_bytes = 0u64; let start_time = Instant::now(); emit_download_status(app_handle, "Start", None).await?; let mut last_emit_time = Instant::now(); let mut downloading_message_sent = false; let mut download_error = false; loop { match response.chunk().await { Ok(Some(chunk)) => { if let Err(e) = file.write_all(&chunk).await { return Err(format!( "Error writing to file '{}': {}", entry.file_name, e.to_string() )); } downloaded_bytes += chunk.len() as u64; let now = Instant::now(); if now.duration_since(last_emit_time) >= Duration::from_millis(200) { if !downloading_message_sent { emit_download_status(app_handle, "Downloading", None).await?; downloading_message_sent = true; } let speed = if start_time.elapsed().is_zero() { 0.0 } else { downloaded_bytes as f64 / start_time.elapsed().as_secs_f64() }; app_handle.emit("download_info", DownloadInfo { current_file, total_files, file_name: entry.file_name.clone(), downloaded_bytes, total_bytes, speed },).map_err(|e| e.to_string())?; last_emit_time = now; } } Ok(None) => { // End of stream break; } Err(_) => { // Connection error during download download_error = true; break; } } } if download_error { // Close the file drop(file); // Start reconnection let mut countdown = 15; while countdown > 0 { emit_download_status(app_handle, "Reconnecting", Some(countdown.to_string())).await?; tokio::time::sleep(Duration::from_secs(1)).await; countdown -= 1; } emit_download_status(app_handle, "Reconnecting", None).await?; // Attempt to reconnect if check_server_connection(client, "https://hil-speed.hetzner.com/").await.is_err() { continue; } else { continue; } } else { break; } } Ok(()) - Assistant