Tenho seguinte código tauri v2 rust use serde::{Deserialize, Serialize}; use…
- User
Tenho seguinte código tauri v2 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()) }
fn is_recoverable_error(_error: &str) -> bool { // Aqui você pode adicionar lógica para determinar se o erro é recuperável // Por simplicidade, vamos considerar todos os erros como recuperáveis true }
async fn attempt_download_file( app_handle: &AppHandle, client: &Client, entry: &PatchEntry, url: &str, file_path: &Path, current_file: usize, total_files: usize, ) -> Result<(), String> { // Verificar se o arquivo já existe e obter o tamanho existente let existing_size = if file_path.exists() { fs::metadata(&file_path) .await .map_err(|e| e.to_string())? .len() } else { 0 };
// Fazer uma requisição HEAD para obter o tamanho total do arquivo let head_response = client.head(url).send().await.map_err(|e| e.to_string())?; if !head_response.status().is_success() { return Err(format!( "Falha ao realizar HEAD para '{}': HTTP {}", entry.file_name, head_response.status() )); } let total_size = head_response .headers() .get("content-length") .and_then(|v| v.to_str().ok()) .and_then(|s| s.parse::<u64>().ok()) .unwrap_or(0); // Se o arquivo já estiver completamente baixado, pular o download if existing_size >= total_size && total_size > 0 { // Emitir informações de download para atualizar a UI app_handle.emit("download_info", DownloadInfo { current_file, total_files, file_name: entry.file_name.clone(), downloaded_bytes: existing_size, total_bytes: total_size, speed: 0.0, }).map_err(|e| e.to_string())?; return Ok(()); } // Configurar a requisição GET com o cabeçalho Range para retomar o download let mut request = client.get(url); if existing_size > 0 { request = request.header("Range", format!("bytes={}-", existing_size)); } let mut response = request.send().await.map_err(|e| e.to_string())?; if !response.status().is_success() && response.status() != reqwest::StatusCode::PARTIAL_CONTENT { return Err(format!( "Falha ao baixar '{}': HTTP {}", entry.file_name, response.status() )); } // Abrir o arquivo no modo apropriado (append ou create) use tokio::fs::OpenOptions; let mut file = if existing_size > 0 { OpenOptions::new() .append(true) .open(&file_path) .await .map_err(|e| e.to_string())? } else { fs::File::create(&file_path).await.map_err(|e| e.to_string())? }; let mut downloaded_bytes = existing_size; let start_time = Instant::now(); // Emitir status "Start" emit_download_status(app_handle, "Start", None).await?; let mut last_emit_time = Instant::now(); let mut downloading_message_sent = false; let total_size = if total_size == 0 { existing_size } else { total_size }; while let Some(chunk) = response.chunk().await.map_err(|e| e.to_string())? { file.write_all(&chunk).await.map_err(|e| 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 elapsed_secs = start_time.elapsed().as_secs_f64(); let speed = if elapsed_secs > 0.0 { (downloaded_bytes - existing_size) as f64 / elapsed_secs } else { 0.0 }; app_handle.emit("download_info", DownloadInfo { current_file, total_files, file_name: entry.file_name.clone(), downloaded_bytes, total_bytes: total_size, speed, }).map_err(|e| e.to_string())?; last_emit_time = now; } } // Garantir que todos os dados foram gravados file.flush().await.map_err(|e| e.to_string())?; Ok(()) - Assistant