Your Rust code can be optimized and improved for clarity, error handling, and readability. Below are some suggestions to enhance the code:
rust Copy code
use anyhow::{Context, Result};
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().unwrap().parent().unwrap().to_path_buf()
}
async fn dir_exists(path: &Path) -> Result<bool> {
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.into()),
}
}
async fn read_patch_file(path: &Path) -> Result<Vec<PatchEntry>> {
let content = fs::read_to_string(path).await?;
let patches: Vec<PatchEntry> = serde_json::from_str(&content)?;
Ok(patches)
}
async fn emit_download_status(app_handle: &AppHandle, status: &str, additional_info: Option<String>) -> Result<()> {
app_handle.emit("download_status", DownloadStatus {
status: status.to_string(),
additional_info,
}).map_err(|e| e.into())
}
async fn emit_download_info(app_handle: &AppHandle, info: DownloadInfo) -> Result<()> {
app_handle.emit("download_info", info).map_err(|e| e.into())
}
async fn download_file(
app_handle: &AppHandle,
client: &Client,
entry: &PatchEntry,
download_dir: &Path,
current_file: usize,
total_files: usize,
) -> Result<()> {
let file_path = download_dir.join(&entry.file_name);
let url = format!("https://hil-speed.hetzner.com/{}", entry.file_name);
loop {
let response = client.get(&url).send().await.context(format!("Failed to download '{}'", entry.file_name))?;
if !response.status().is_success() {
return Err(anyhow::anyhow!("Failed to download '{}': HTTP {}", entry.file_name, response.status()));
}
let total_bytes = response.content_length().unwrap_or(0);
let _ = fs::remove_file(&file_path).await; // Ignore error when file doesn't exist
let mut file = fs::File::create(&file_path).await.context(format!("Error creating file '{}'", entry.file_name))?;
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();
loop {
match response.chunk().await {
Ok(Some(chunk)) => {
file.write_all(&chunk).await.context(format!("Error writing to file '{}'", entry.file_name))?;
downloaded_bytes += chunk.len() as u64;
let now = Instant::now();
if now.duration_since(last_emit_time) >= Duration::from_millis(200) {
let speed = if start_time.elapsed().is_zero() {
0.0
} else {
downloaded_bytes as f64 / start_time.elapsed().as_secs_f64()
};
emit_download_info(app_handle, DownloadInfo {
current_file,
total_files,
file_name: entry.file_name.clone(),
downloaded_bytes,
total_bytes,
speed,
}).await?;
last_emit_time = now;
}
}
Ok(None) => break, // End of stream
Err(e) => {
// Handle connection error
emit_download_status(app_handle, "Error", Some(format!("Connection error while downloading '{}': {}", entry.file_name, e))).await?;
return Err(anyhow::anyhow!("Connection error: {}", e));
}
}
}
break; // Successfully downloaded
}
Ok(())
}
async fn check_server_connection(client: &Client, url: &str) -> Result<()> {
let response = client.get(url).send().await?;
if response.status().is_success() {
Ok(())
} else {
Err(anyhow::anyhow!("Failed to connect to server: HTTP {}", response.status()))
}
}
#[tauri::command]
pub async fn start_downloads(app_handle: AppHandle) -> Result<()> {
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? {
fs::create_dir_all(&download_dir).await?;
}
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?;
check_server_connection(&client, "https://hil-speed.hetzner.com/").await.context("Connection failed")?;
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!("Error downloading '{}': {}", entry.file_name, err);
eprintln!("{}", error_message);
emit_download_status(&app_handle, "Error", Some(error_message.clone())).await?;
return Err(err);
}
}
emit_download_status(&app_handle, "Completed", None).await?;
Ok(())
}
This refactoring improves maintainability and can make it easier to extend or debug the application in the future.