Tenho o seguinte código tauri v2 rust use serde::{Deserialize, Serialize}; use…
- User
Tenho o 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(Debug, Deserialize, Clone)] struct PatchEntry { file_name: String, }
#[derive(Debug, Serialize, Clone)] struct DownloadMessage { message: String, }
#[derive(Debug, Serialize, Clone)] struct DownloadInfo { current_file: usize, total_files: usize, file_name: String, downloaded_bytes: u64, total_bytes: u64, }
fn get_exe_dir() -> Result<PathBuf, std::io::Error> { std::env::current_exe()?.parent() .map(|p| p.to_path_buf()) .ok_or_else(|| std::io::Error::new( std::io::ErrorKind::Other, "Não foi possível determinar o diretório do executável", )) }
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) }
fn emit_download_message(app_handle: &AppHandle, message: &str) -> Result<(), String> { app_handle.emit("download_message", DownloadMessage { message: message.to_string() }) .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 url = format!("https://hil-speed.hetzner.com/{}", entry.file_name); let file_path = download_dir.join(&entry.file_name);
let mut response = client.get(&url).send().await.map_err(|e| e.to_string())?; if !response.status().is_success() { return Err(format!("Falha ao baixar '{}': HTTP {}", entry.file_name, response.status())); } let total_bytes = response.content_length().unwrap_or(0); 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(); // Converter o erro para String usando map_err emit_download_message(app_handle, "Baixando").map_err(|e| e.to_string())?; let mut last_emit_time = Instant::now(); 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(100) { let elapsed = start_time.elapsed().as_secs_f64(); let speed = if elapsed > 0.0 { downloaded_bytes as f64 / elapsed } else { 0.0 }; app_handle.emit("download_info", DownloadInfo { current_file, total_files, file_name: entry.file_name.clone(), downloaded_bytes, total_bytes, }).map_err(|e| e.to_string())?; app_handle.emit("download_speed", speed).map_err(|e| e.to_string())?; last_emit_time = now; } } emit_download_message(app_handle, "Download concluído").map_err(|e| e.to_string())?; Ok(())}
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!("Falha ao conectar ao servidor: HTTP {}", response.status())) } }
#[tauri::command] pub async fn start_downloads(app_handle: AppHandle) -> Result<(), String> { // Obter o diretório do executável let exe_dir = get_exe_dir().map_err(|e| e.to_string())?;
// Definir caminhos let patch_file_path = exe_dir.join("patch.json"); let download_dir = exe_dir.join("patchs"); // Verificar se o diretório de download existe, criar se não existir 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())?; } // Ler os patches do arquivo JSON let patches = read_patch_file(&patch_file_path).await?; let client = Client::new(); let total_files = patches.len(); emit_download_message(&app_handle, "Conectando ao servidor...").map_err(|e| e.to_string())?; 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_message(&app_handle, &error_message).map_err(|e| e.to_string())?; return Err(error_message); } emit_download_message(&app_handle, "Conexão estabelecida com sucesso. Iniciando download...") .map_err(|e| e.to_string())?; // Executar downloads sequencialmente, um arquivo por vez 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_message(&app_handle, &error_message).map_err(|e| e.to_string())?; // Interrompe o processo em caso de erro return Err(error_message); } } emit_download_message(&app_handle, "Todos os downloads foram concluídos com sucesso.") .map_err(|e| e.to_string())?; Ok(())}
E o código front end em react
import { useEffect, useState } from "react"; import { listen } from "@tauri-apps/api/event"; import { invoke } from "@tauri-apps/api/core";
function formatBytes(bytes: number) { if (bytes === 0) return '0 B'; const k = 1024; const units = ['B', 'KB', 'MB', 'GB', 'TB', 'PB']; const i = Math.floor(Math.log(bytes) / Math.log(k)); const value = bytes / Math.pow(k, i); return
${value.toFixed(2)} ${units[i]}; }interface DownloadMessage { message: string; }
interface DownloadInfo { current_file: number; total_files: number; file_name: string; downloaded_bytes: number; total_bytes: number; }
const DownloadManager = () => { const [message, setMessage] = useState(""); const [currentFile, setCurrentFile] = useState(0); const [totalFiles, setTotalFiles] = useState(0); const [fileName, setFileName] = useState(""); const [downloadedBytes, setDownloadedBytes] = useState(0); const [totalBytes, setTotalBytes] = useState(0); const [isDownloading, setIsDownloading] = useState(false); const [downloadSpeed, setDownloadSpeed] = useState(0);
useEffect(() => { const unlistenUpdate = listen("download_message", (event) => { const { message } = event.payload; setMessage(message); });
const unlistenInfo = listen<DownloadInfo>("download_info", (event) => { const { current_file, total_files, file_name, downloaded_bytes, total_bytes, } = event.payload; setCurrentFile(current_file); setTotalFiles(total_files); setFileName(file_name); setDownloadedBytes(downloaded_bytes); setTotalBytes(total_bytes); }); const unlistenSpeed = listen<number>("download_speed", (event) => { const speedInBytes = event.payload; setDownloadSpeed(speedInBytes); }); return () => { unlistenUpdate.then((fn) => fn()); unlistenInfo.then((fn) => fn()); unlistenSpeed.then((fn) => fn()); };}, [isDownloading]);
const startDownload = async () => { if (isDownloading) return; setIsDownloading(true);
try { await invoke("start_downloads"); } catch (error) { setMessage(`Erro ao iniciar o download: ${error}`); } finally { setIsDownloading(false); }};
const progressPercent = totalBytes > 0 ? (downloadedBytes / totalBytes) * 100 : 0;
return ( <> Iniciar Download {message} {isDownloading && totalFiles > 0 && ( ( {currentFile} / {totalFiles} ) )} {isDownloading && fileName && ( <> : {fileName} ( {formatBytes(downloadedBytes)} / {formatBytes(totalBytes)} ) </> )} {isDownloading && ( {formatBytes(downloadSpeed)} /s )} <div className="bg-[#1164CA]/[0.95] ml-1 rounded-md h-4" style={{ width:
${progressPercent}%}} /> </> ); };export default DownloadManager;
As mensagens estão bugando, por exemplo
Quando vou baixar novamente depois de baixar já um vez a mensagem, está exibindo mensagem baixando e depois baixando (curentfile / totalfile): file (bytesdownload/totalbytes) Conectando com o servidor acontece a mesma coisa
como posso corrigir isso ?
- Assistant
O problema que você está enfrentando é causado pela forma como os ouvintes de eventos (listeners) estão sendo registrados no seu componente React. No seu código atual, você está adicionando
[isDownloading]como uma dependência no array de dependências douseEffect. Isso faz com que, toda vez queisDownloadingmudar, ouseEffectseja executado novamente e novos ouvintes sejam registrados. No entanto, os ouvintes anteriores não estão sendo removidos corretamente, o que leva a múltiplos ouvintes sendo registrados para o mesmo evento. Isso resulta em mensagens duplicadas ou sobrepostas, como você observou.Para resolver esse problema, você precisa garantir que os ouvintes sejam registrados apenas uma vez, quando o componente for montado, e removidos quando o componente for desmontado. Para isso, você deve remover
[isDownloading]do array de dependências douseEffect, de modo que ele seja executado apenas uma vez.Aqui está como você pode ajustar seu código:
import { useEffect, useState } from "react"; import { listen } from "@tauri-apps/api/event"; import { invoke } from "@tauri-apps/api/core"; function formatBytes(bytes: number) { if (bytes === 0) return '0 B'; const k = 1024; const units = ['B', 'KB', 'MB', 'GB', 'TB', 'PB']; const i = Math.floor(Math.log(bytes) / Math.log(k)); const value = bytes / Math.pow(k, i); return `${value.toFixed(2)} ${units[i]}`; } interface DownloadMessage { message: string; } interface DownloadInfo { current_file: number; total_files: number; file_name: string; downloaded_bytes: number; total_bytes: number; } const DownloadManager = () => { const [message, setMessage] = useState(""); const [currentFile, setCurrentFile] = useState(0); const [totalFiles, setTotalFiles] = useState(0); const [fileName, setFileName] = useState(""); const [downloadedBytes, setDownloadedBytes] = useState(0); const [totalBytes, setTotalBytes] = useState(0); const [isDownloading, setIsDownloading] = useState(false); const [downloadSpeed, setDownloadSpeed] = useState(0); useEffect(() => { let unlistenUpdate: (() => void) | null = null; let unlistenInfo: (() => void) | null = null; let unlistenSpeed: (() => void) | null = null; (async () => { unlistenUpdate = await listen<DownloadMessage>("download_message", (event) => { const { message } = event.payload; setMessage(message); }); unlistenInfo = await listen<DownloadInfo>("download_info", (event) => { const { current_file, total_files, file_name, downloaded_bytes, total_bytes, } = event.payload; setCurrentFile(current_file); setTotalFiles(total_files); setFileName(file_name); setDownloadedBytes(downloaded_bytes); setTotalBytes(total_bytes); }); unlistenSpeed = await listen<number>("download_speed", (event) => { const speedInBytes = event.payload; setDownloadSpeed(speedInBytes); }); })(); return () => { if (unlistenUpdate) unlistenUpdate(); if (unlistenInfo) unlistenInfo(); if (unlistenSpeed) unlistenSpeed(); }; }, []); // Remova 'isDownloading' daqui const startDownload = async () => { if (isDownloading) return; setIsDownloading(true); // Resetar o estado ao iniciar um novo download setMessage(""); setCurrentFile(0); setTotalFiles(0); setFileName(""); setDownloadedBytes(0); setTotalBytes(0); setDownloadSpeed(0); try { await invoke("start_downloads"); } catch (error) { setMessage(`Erro ao iniciar o download: ${error}`); } finally { setIsDownloading(false); } }; const progressPercent = totalBytes > 0 ? (downloadedBytes / totalBytes) * 100 : 0; return ( <> <div className="absolute bottom-20 rounded-lg w-[71%] h-[8%] flex flex-col justify-between items-center"> <button onClick={startDownload} className="bg-blue-500 text-white rounded p-2 mb-2"> Iniciar Download </button> </div> <div className="absolute bottom-3 rounded-lg w-[71%] h-[8%] flex flex-col justify-between items-center"> <div className="w-full flex items-center"> <p className="text-[14px] font-bold text-opacity-[0.95] text-white flex-grow text-center"> {message} {isDownloading && totalFiles > 0 && ( <span className="mx-1">( {currentFile} / {totalFiles} )</span> )} {isDownloading && fileName && ( <> : <span className="text-orange-500">{fileName}</span> <span className="mx-1">( <span className="text-green-600">{formatBytes(downloadedBytes)}</span> / {formatBytes(totalBytes)} )</span> </> )} </p> </div> {isDownloading && ( <div className="w-[30%] absolute h-6 flex justify-end items-center right-6 top-2"> <span className="text-[10px] font-bold text-opacity-[0.95] text-yellow-600 text-right"> {formatBytes(downloadSpeed)} /s </span> </div> )} <div className="w-[95%] bg-[#0E1622]/[0.95] text-green-600 rounded-md h-6 flex items-center shadow-inner shadow-gray-800"> <div className="bg-[#1164CA]/[0.95] ml-1 rounded-md h-4" style={{ width: `${progressPercent}%` }} /> </div> </div> </> ); }; export default DownloadManager;Explicação das mudanças:
-
Remover
isDownloadingdo array de dependências douseEffect: Isso garante que ouseEffectseja executado apenas uma vez, quando o componente for montado, e não toda vez queisDownloadingmudar. Dessa forma, os ouvintes de eventos são registrados apenas uma vez. -
Usar
asyncdentro douseEffect: Como a funçãolistenretorna uma Promise que resolve em uma função de cancelamento (unlisten), precisamos usarawaitpara obter essa função corretamente. -
Modificar a função de limpeza (
returndouseEffect): Verificamos seunlistenUpdate,unlistenInfoeunlistenSpeednão são nulos antes de chamá-los, garantindo que os ouvintes sejam corretamente removidos quando o componente for desmontado. -
Resetar o estado ao iniciar um novo download: Dentro de
startDownload, antes de iniciar o download, resetamos os estados relevantes para garantir que a interface reflita um novo download e não mantenha informações do download anterior.
Com essas mudanças, você evitará que múltiplos ouvintes sejam registrados para os mesmos eventos, o que causava as mensagens duplicadas ou sobrepostas. Além disso, ao resetar o estado ao iniciar um novo download, você garante que a interface comece limpa para cada novo download.
Nota adicional:
Se você precisar que os estados sejam resetados também quando o download for concluído ou falhar, certifique-se de ajustar os estados dentro do bloco
finallyda funçãostartDownloadou dentro dos tratamentos de sucesso/erro adequados. -