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};
let patch_file_path = exe_dir.join("patch.json");
let download_dir = exe_dir.join("patchs");
if !dir_exists(&download_dir).await.map_err(|e| e.to_string())? {
fs::create_dir_all(&download_dir).await.map_err(|e| e.to_string())?;
}
let patches = read_patch_file(&patch_file_path).await?;
let client = Client::new();
let total_files = patches.len();
emit_download_status(&app_handle, "Connecting", None).await?;
let server_url = "https://hil-speed.hetzner.com/";
if let Err(err) = check_server_connection(&client, server_url).await {
let error_message = format!("Erro ao conectar ao servidor: {}", err);
eprintln!("{}", error_message);
emit_download_status(&app_handle, "Error", Some(error_message.clone())).await?;
return Err(error_message);
}
emit_download_status(&app_handle, "Connected", None).await?;
for (idx, entry) in patches.iter().enumerate() {
let current_file = idx + 1;
if let Err(err) = download_file(&app_handle, &client, entry, &download_dir, current_file, total_files).await {
let error_message = format!("Erro ao baixar '{}': {}", entry.file_name, err);
eprintln!("{}", error_message);
emit_download_status(&app_handle, "Error", Some(error_message.clone())).await?;
return Err(error_message);
}
}
// Emitir status de conclusão
emit_download_status(&app_handle, "Completed", None).await?;
Ok(())
}
A seguir está uma versão otimizada e melhorada do seu código em Rust. As melhorias incluem refatoração para reduzir a duplicação de código, melhorias na legibilidade e na eficácia da lógica e a adição de anotações que facilitam a compreensão do 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<String>,
}
fn get_exe_dir() -> PathBuf {
std::env::current_exe()
.map(|exe| exe.parent().unwrap().to_path_buf())
.unwrap()
}
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<PatchEntry>, String> {
fs::read_to_string(path)
.await
.map_err(|e| e.to_string())
.and_then(|content| {
serde_json::from_str(&content)
.map_err(|e| e.to_string())
})
}
async fn emit_download_status(app_handle: &AppHandle, status: &str, additional_info: Option<String>) -> 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);
let url = format!("https://hil-speed.hetzner.com/{}", entry.file_name);
loop {
match perform_download(app_handle, client, &url, &file_path, current_file, total_files).await {
Ok(()) => break,
Err(err) => {
emit_download_status(app_handle, "Error", Some(err.clone())).await?;
if let Err(_) = retry_connection(app_handle, client, 15).await {
return Err("Failed to reconnect after several attempts.".to_string());
}
}
}
}
Ok(())
}
async fn perform_download(
app_handle: &AppHandle,
client: &Client,
url: &str,
file_path: &Path,
current_file: usize,
total_files: usize,
) -> Result<(), String> {
let mut response = client.get(url).send().await.map_err(|e| e.to_string())?;
if !response.status().is_success() {
return Err(format!("Failed to download '{}': HTTP {}", url, response.status()));
}
let total_bytes = response.content_length().unwrap_or(0);
// Remove the existing file if necessary
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();
let mut last_emit_time = Instant::now();
emit_download_status(app_handle, "Start", None).await?;
emit_download_status(app_handle, "Downloading", None).await?;
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) {
let speed = downloaded_bytes as f64 / start_time.elapsed().as_secs_f64().max(1.0);
app_handle.emit(
"download_info",
DownloadInfo {
current_file,
total_files,
file_name: String::from(file_path.file_name().unwrap().to_str().unwrap()),
downloaded_bytes,
total_bytes,
speed,
},
).map_err(|e| e.to_string())?;
last_emit_time = now;
}
}
Ok(())
}
async fn retry_connection(app_handle: &AppHandle, client: &Client, max_attempts: usize) -> Result<(), String> {
for attempt in (1..=max_attempts).rev() {
emit_download_status(app_handle, "Reconnecting", Some(attempt.to_string())).await?;
tokio::time::sleep(Duration::from_secs(1)).await;
if check_server_connection(client, "https://hil-speed.hetzner.com/").await.is_ok() {
emit_download_status(app_handle, "Connected", None).await?;
return Ok(());
}
}
Err("Failed to reconnect to the server".to_string())
}
async fn check_server_connection(client: &Client, url: &str) -> Result<(), String> {
let response = client.get(url).send().await.map_err(|e| e.to_string())?;
if response.status().is_success() {
Ok(())
} else {
Err(format!("Failed to connect to server: HTTP {}", response.status()))
}
}
#[tauri::command]
pub async fn start_downloads(app_handle: AppHandle) -> Result<(), String> {
let exe_dir = get_exe_dir();
let patch_file_path = exe_dir.join("patch.json");
let download_dir = exe_dir.join("patchs");
if !dir_exists(&download_dir).await.map_err(|e| e.to_string())? {
fs::create_dir_all(&download_dir).await.map_err(|e| e.to_string())?;
}
let patches = read_patch_file(&patch_file_path).await?;
let client = Client::new();
let total_files = patches.len();
emit_download_status(&app_handle, "Connecting", None).await?;
if check_server_connection(&client, "https://hil-speed.hetzner.com/").await.is_err() {
return Err("Failed to connect to the server.".to_string());
}
emit_download_status(&app_handle, "Connected", None).await?;
for (idx, entry) in patches.iter().enumerate() {
if let Err(err) = download_file(&app_handle, &client, entry, &download_dir, idx + 1, total_files).await {
return Err(format!("Error downloading '{}': {}", entry.file_name, err));
}
}
emit_download_status(&app_handle, "Completed", None).await?;
Ok(())
}
Alterações Principais:
Função perform_download: Consolidou a lógica de download em uma função separada para reduzir a complexidade da função download_file e manter a lógica de erro clara.
Função retry_connection: A lógica de reconexão foi encapsulada em uma função separada, o que a torna reutilizável e melhora a legibilidade.
Uso Aumentado de map_err: Melhoria na propagação de erros para facilitar a detecção de problemas.
Adição de .max(1.0) no cálculo de speed: Para evitar divisão por zero.
Estrutura e Legibilidade: Melhor organização do código e nomes de função mais descritivos para facilitar o entendimento da funcionalidade.
Essas alterações ajudam a tornar o código mais robusto, legível e fácil de manter ao longo do tempo.