I'm creating rust code with react that downloads files, in a test I did the download bar goes completely crazy, it keeps going back and forth
the bytes of the files are correct, I don't understand why this is happening
I have following code
test.lua
local updates = {
{ version = 1, file_name = "100MB.bin" },
{ version = 2, file_name = "1GB.bin" },
{ version = 3, file_name = "10GB.bin" }
}
return updates
use mlua::{Lua, Result as LuaResult};
use reqwest::Client;
use std::path::PathBuf;
use std::env;
use tokio::fs::{self, File};
use tokio::io::AsyncWriteExt;
use tauri::{Window, Emitter};
fn get_executable_directory() -> PathBuf {
env::current_exe()
.expect("Failed to get current executable path")
.parent()
.expect("Failed to get executable directory")
.to_path_buf()
}
fn parse_lua_file(file_path: &str) -> LuaResult<Vec<(u32, String)>> {
let lua = Lua::new();
let lua_code = std::fs::read_to_string(file_path).expect("Failed to read Lua file");
code
let updates: mlua::Table = lua.load(&lua_code).eval()?;
let mut files = Vec::new();
for pair in updates.sequence_values::<mlua::Table>() {
let table = pair?;
let version: u32 = table.get("version")?;
let file_name: String = table.get("file_name")?;
files.push((version, file_name));
}
Ok(files)
}
#[tauri::command]
pub async fn download_files(window: Window) -> Result<(), String> {
// Obtém o diretório do executável
let exe_dir = get_executable_directory();
code
Assistant
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
// Define o caminho para a pasta `patchs`
let patchs_dir = exe_dir.join("patchs");
// Verifica e cria o diretório `patchs` se ele não existir
fs::create_dir_all(&patchs_dir).await.map_err(|e| format!("Failed to create patchs directory: {}", e))?;
// Carrega o arquivo Lua e obtém os arquivos a serem baixados
let lua_file_path = exe_dir.join("test.lua");
let lua_file_path_str = lua_file_path.to_str().ok_or("Invalid file path")?;
let files_to_download = parse_lua_file(lua_file_path_str)
.map_err(|e| format!("Failed to parse Lua file: {}", e))?;
let total_files = files_to_download.len();
let client = Client::new();
for (current_file, (_version, file_name)) in files_to_download.iter().enumerate() {
let url = format!("https://hil-speed.hetzner.com/{}", file_name);
let mut response = client
.get(&url)
.send()
.await
.map_err(|e| format!("Failed to download {}: {}", file_name, e))?;
let total_bytes = response.content_length().unwrap_or(0);
let mut downloaded_bytes = 0;
// Define o caminho completo para o arquivo na pasta `patchs`
let file_path = patchs_dir.join(file_name);
let mut file = File::create(&file_path).await.map_err(|e| format!("Failed to create file {}: {}", file_name, e))?;
// Baixa o arquivo em chunks e grava o progresso
while let Some(chunk) = response.chunk().await.map_err(|e| format!("Failed to read chunk for {}: {}", file_name, e))? {
downloaded_bytes += chunk.len() as u64;
file.write_all(&chunk).await.map_err(|e| format!("Failed to write chunk for {}: {}", file_name, e))?;
// Emite o progresso atualizado
window.emit(
"download-progress",
DownloadProgress {
current_file: current_file + 1,
total_files,
file_name: file_name.clone(),
downloaded_bytes,
total_bytes,
},
).map_err(|e| format!("Failed to send event for {}: {}", file_name, e))?;
}
}
Ok(())
}
React
import { useState, useEffect } from "react";
import { invoke } from "@tauri-apps/api/core";
import { listen } from "@tauri-apps/api/event";
It sounds like the issue with your download progress bar is due to the way progress is being tracked and updated for each individual file. When you download multiple files sequentially, the progress bar resets for each file, causing it to "go back and forth" instead of showing a smooth, continuous progression.
To fix this, you can implement overall (cumulative) progress tracking instead of tracking progress for each file individually. This approach ensures that the progress bar reflects the total progress across all files, providing a smoother and more intuitive user experience.
Here's how you can achieve this:
1. Calculate the Total Bytes for All Files
First, you'll need to calculate the total number of bytes for all the files you intend to download. This requires making a HEAD request to get the Content-Length of each file before starting the download. This way, you can sum up the total bytes and track the cumulative progress.
2. Update the Backend (Rust) Code
Modify your Rust backend to calculate the total bytes and track downloaded bytes cumulatively. Here's how you can adjust your download_files function:
rust
use mlua::{Lua, Result as LuaResult};
use reqwest::Client;
use std::path::PathBuf;
use std::env;
use tokio::fs::{self, File};
use tokio::io::AsyncWriteExt;
use tauri::{Window, Emitter};
use serde::Serialize;
#[derive(Serialize, Clone)]
struct DownloadProgress {
downloaded_bytes: u64,
total_bytes: u64,
progress_percent: f64,
}
fn get_executable_directory() -> PathBuf {
env::current_exe()
.expect("Failed to get current executable path")
.parent()
.expect("Failed to get executable directory")
.to_path_buf()
}
fn parse_lua_file(file_path: &str) -> LuaResult<Vec<(u32, String)>> {
let lua = Lua::new();
let lua_code = std::fs::read_to_string(file_path).expect("Failed to read Lua file");
let updates: mlua::Table = lua.load(&lua_code).eval()?;
let mut files = Vec::new();
for pair in updates.sequence_values::<mlua::Table>() {
let table = pair?;
let version: u32 = table.get("version")?;
let file_name: String = table.get("file_name")?;
files.push((version, file_name));
}
Ok(files)
}
#[tauri::command]
pub async fn download_files(window: Window) -> Result<(), String> {
// Get the executable directory
let exe_dir = get_executable_directory();
// Define the path for the `patchs` folder
let patchs_dir = exe_dir.join("patchs");
// Create the `patchs` directory if it doesn't exist
fs::create_dir_all(&patchs_dir).await.map_err(|e| format!("Failed to create patchs directory: {}", e))?;
// Load the Lua file and get the files to download
let lua_file_path = exe_dir.join("test.lua");
let lua_file_path_str = lua_file_path.to_str().ok_or("Invalid file path")?;
let files_to_download = parse_lua_file(lua_file_path_str)
.map_err(|e| format!("Failed to parse Lua file: {}", e))?;
let client = Client::new();
// Calculate total bytes
let mut total_bytes: u64 = 0;
for (_version, file_name) in &files_to_download {
let head_resp = client.head(&format!("https://hil-speed.hetzner.com/{}", file_name))
.send()
.await
.map_err(|e| format!("Failed to get header for {}: {}", file_name, e))?;
if let Some(len) = head_resp.content_length() {
total_bytes += len;
} else {
return Err(format!("Could not get content length for {}", file_name));
}
}
let mut downloaded_bytes: u64 = 0;
for (_index, (version, file_name)) in files_to_download.iter().enumerate() {
let url = format!("https://hil-speed.hetzner.com/{}", file_name);
let mut response = client
.get(&url)
.send()
.await
.map_err(|e| format!("Failed to download {}: {}", file_name, e))?;
let file_path = patchs_dir.join(file_name);
let mut file = File::create(&file_path).await.map_err(|e| format!("Failed to create file {}: {}", file_name, e))?;
while let Some(chunk) = response.chunk().await.map_err(|e| format!("Failed to read chunk for {}: {}", file_name, e))? {
let chunk_size = chunk.len() as u64;
downloaded_bytes += chunk_size;
file.write_all(&chunk).await.map_err(|e| format!("Failed to write chunk for {}: {}", file_name, e))?;
// Emit the cumulative progress
let progress_percent = if total_bytes > 0 {
(downloaded_bytes as f64 / total_bytes as f64) * 100.0
} else {
0.0
};
window.emit(
"download-progress",
DownloadProgress {
downloaded_bytes,
total_bytes,
progress_percent,
},
).map_err(|e| format!("Failed to send event for {}: {}", file_name, e))?;
}
}
Ok(())
}
Explanation of Changes:
Total Bytes Calculation:
Before downloading, the code makes a HEAD request for each file to get its Content-Length.
Sums up the total bytes of all files to be downloaded.
Cumulative Download Progress:
Maintains a downloaded_bytes counter that increments with each chunk downloaded.
Calculates progress_percent based on the cumulative downloaded_bytes and total_bytes.
Emits a single DownloadProgress event with the cumulative progress.
3. Update the Frontend (React) Code
Adjust your React frontend to handle the cumulative progress:
Removed individual file states (currentFile, totalFiles, fileName) as they are no longer needed for cumulative progress.
Now tracking only downloadedBytes, totalBytes, and progressPercent.
Progress Display:
Updated the progress display to show cumulative bytes and percentage.
Used toFixed(2) to format the percentage to two decimal places for smoother visuals.
4. (Optional) Show Detailed Information
If you still want to display information about the current file being downloaded, you can add additional state management. However, keep in mind that this can cause the progress bar to reset or jump when switching files. For the cleanest user experience, it's recommended to focus on cumulative progress. If needed, you can display the current file information separately without affecting the progress bar.
5. Testing
After implementing these changes:
Run your application and initiate the download process.
Observe the progress bar to ensure it smoothly increases from 0% to 100% without jumping back.
Verify the byte counts to ensure that the cumulative downloaded bytes match the expected total bytes.
6. Additional Enhancements
Error Handling: Ensure that errors in downloading one file don't affect the overall progress tracking.
Pause/Resume Functionality: Implementing pause and resume can be more straightforward with cumulative progress.
Retry Logic: Add retry mechanisms for failed downloads to improve reliability.
Summary
By switching from per-file progress tracking to cumulative progress tracking, you eliminate the issue of the progress bar resetting for each file. This provides a smoother and more accurate representation of the overall download progress, enhancing the user experience.
If you have any further questions or need additional assistance, feel free to ask!