Skip to content
TheChatArchiveThe Chat Archive
gpt-4o-mini-2024-07-18· OpenAIAi2 WildChat-4.8M (AI2)

tenho seguinte código tauri v2 rust use serde::{Deserialize, Serialize}; use…

  1. 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, }

    #[derive(Serialize, Clone)] struct DownloadStatus { status: String, additional_info: Option, }

    async fn get_exe_dir() -> Result<PathBuf, std::io::Error> { tokio::task::spawn_blocking(|| { 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", )) }).await? }

    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 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();
    
    emit_download_status(app_handle, "downloading", Some(entry.file_name.clone())).await?;
    
    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;
        }
    }
    
    // Emitir status de download concluído para o arquivo atual
    emit_download_status(app_handle, "file_completed", Some(entry.file_name.clone())).await?;
    
    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().await.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();
    
    // Emitir status de conexão
    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);
    }
    
    // Emitir status de conexão bem-sucedida
    emit_download_status(&app_handle, "connected", None).await?;
    
    // 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_status(&app_handle, "error", Some(error_message.clone())).await?;
            // Interrompe o processo em caso de erro
            return Err(error_message);
        }
    }
    
    // Emitir status de todos os downloads concluídos
    emit_download_status(&app_handle, "completed", None).await?;
    
    Ok(())
    

    }

    no react eu tenho

    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 DownloadStatus { status: string; // Exemplo: "connecting", "downloading", "completed", "error" additional_info?: string; // Informações adicionais, como o nome do arquivo ou mensagem de erro }

    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 unlistenStatus: (() => void) | null = null; let unlistenInfo: (() => void) | null = null; let unlistenSpeed: (() => void) | null = null;

    (async () => {
      unlistenStatus = await listen<DownloadStatus>("download_status", (event) => {
        const { status, additional_info } = event.payload;
        let newMessage = '';
    
        switch (status) {
          case 'connecting':
            newMessage = 'Conectando ao servidor...';
            break;
          case 'connected':
            newMessage = 'Conexão estabelecida com sucesso. Iniciando download...';
            break;
          case 'downloading':
            newMessage = `Baixando ${additional_info || ''}`;
            break;
          case 'file_completed':
            newMessage = `Download do arquivo concluído: ${additional_info || ''}`;
            break;
          case 'completed':
            newMessage = 'Todos os downloads foram concluídos com sucesso.';
            break;
          case 'error':
            newMessage = `Erro: ${additional_info || 'Ocorreu um erro'}`;
            break;
          default:
            newMessage = 'Status desconhecido';
        }
    
        setMessage(newMessage);
    
        if (status === 'downloading') {
          setIsDownloading(true);
          setFileName(additional_info || '');
        } else if (status === 'completed' || status === 'error') {
          setIsDownloading(false);
        }
      });
    
      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 (unlistenStatus) unlistenStatus();
      if (unlistenInfo) unlistenInfo();
      if (unlistenSpeed) unlistenSpeed();
    };
    

    }, []);

    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}`);
      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)}ps )} <div className="bg-[#1164CA]/[0.95] ml-1 rounded-md h-4" style={{ width: ${progressPercent}% }} /> </> ); };

    export default DownloadManager;

    Em vez de usar nome para mensagens não seria melhor usar id ? também mova o speed para o downloadinfo

  2. Assistant

    Utilizar IDs em vez de nomes de mensagens pode ser uma abordagem mais robusta, pois permite uma maior flexibilidade e manutenção do código. Isso é especialmente útil em aplicações maiores ou quando você deseja modificar mensagens ou adicionar novos estados. Além disso, mover a velocidade do download para o DownloadInfo ajuda a centralizar as informações relacionadas ao download em um único objeto.

    Vou mostrar como você pode adaptar o código Rust e o código React de acordo com essas sugestões.

    Modificações no Código Rust

    Vamos definir IDs para os status e mover a velocidade do download para o DownloadInfo.

    #[derive(Serialize, Clone)]
    struct DownloadInfo {
        current_file: usize,
        total_files: usize,
        file_name: String,
        downloaded_bytes: u64,
        total_bytes: u64,
        speed: f64,  // Adicionando a velocidade ao DownloadInfo
    }
    
    async fn download_file( ...
    ) -> Result<(), String> {
        ...
        
        let speed = 0.0; // Inicializando a velocidade
    
        ...
        
        while let Some(chunk) = response.chunk().await.map_err(|e| e.to_string())? {
            ...
            
            let now = Instant::now();
            if now.duration_since(last_emit_time) >= Duration::from_millis(100) {
                ...
                // Atualizando a estrutura DownloadInfo com a velocidade
                let download_info = DownloadInfo {
                    current_file,
                    total_files,
                    file_name: entry.file_name.clone(),
                    downloaded_bytes,
                    total_bytes,
                    speed,  // Inclusão da velocidade
                };
                app_handle.emit("download_info", download_info).map_err(|e| e.to_string())?;
                last_emit_time = now;
            }
        }
        ...
    }
    
    async fn start_downloads(app_handle: AppHandle) -> Result<(), String> {
        ...
        // Emitir status de conexão bem-sucedida
        emit_download_status(&app_handle, "1", None).await?; // '1' representa "connected"
        ...
    }
    

    Repetir a alteração de status com IDs.

    Modificações no Código React

    Substitua as mensagens por IDs. Agora, vamos modificar o código para escutar pelos novos IDs e lidar com a velocidade do download.

    const DownloadManager = () => {
      const [messageId, setMessageId] = useState("");
      // ...
    
      useEffect(() => {
        let unlistenStatus: (() => void) | null = null;
        let unlistenInfo: (() => void) | null = null;
    
        (async () => {
          unlistenStatus = await listen<DownloadStatus>("download_status", (event) => {
            const { status, additional_info } = event.payload;
    
            let newMessage = '';
            switch (status) {
              case 'connect':
                setMessageId('1'); // Para "connecting"
                break;
              case 'connected':
                setMessageId('2'); // Para "connected"
                break;
              case 'downloading':
                newMessage = `Baixando ${additional_info || ''}`;
                setMessageId('3'); // Para "downloading"
                break;
              case 'file_completed':
                newMessage = `Download do arquivo concluído: ${additional_info || ''}`;
                setMessageId('4'); // Para "file_completed"
                break;
              case 'completed':
                setMessageId('5'); // Para "completed"
                break;
              case 'error':
                newMessage = `Erro: ${additional_info || 'Ocorreu um erro'}`;
                setMessageId('6'); // Para "error"
                break;
              default:
                setMessageId('unknown'); // Mensagem desconhecida
            }
    
            setMessage(newMessage);
          });
    
          unlistenInfo = await listen<DownloadInfo>("download_info", (event) => {
            const { current_file, total_files, file_name, downloaded_bytes, total_bytes, speed } = event.payload;
    
            setCurrentFile(current_file);
            setTotalFiles(total_files);
            setFileName(file_name);
            setDownloadedBytes(downloaded_bytes);
            setTotalBytes(total_bytes);
            setDownloadSpeed(speed); // Atualizar velocidade do download
          });
        })();
    
        return () => {
          if (unlistenStatus) unlistenStatus();
          if (unlistenInfo) unlistenInfo();
        };
      }, []);
    
      return (
        <>
          <div>
            {messageId === '1' && <p>Conectando ao servidor...</p>}
            {messageId === '2' && <p>Conexão estabelecida com sucesso. Iniciando download...</p>}
            {messageId === '3' && <p>{`Baixando ${fileName}`}</p>}
            {messageId === '4' && <p>{`Download do arquivo concluído: ${fileName}`}</p>}
            {messageId === '5' && <p>Todos os downloads foram concluídos com sucesso.</p>}
            {messageId === '6' && <p>{`Erro: ${message}`}</p>}
            {messageId === 'unknown' && <p>Status desconhecido</p>}
          </div>
          {/* Resto do componente */}
        </>
      );
    };
    

    Considerações Finais

    1. IDs de Mensagem: Os IDs ajudam a diferenciar mensagens sem depender de strings longas ou específicas, facilitando o gerenciamento.
    2. Velocidade: Agora a velocidade do download é geral e está associada a cada arquivo baixado.

    Lembre-se de testar todas as funcionalidades após as alterações para garantir que a comunicação entre o frontend e o backend continue funcionando corretamente.

Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.