Here is how you can modify your Tauri Rust code and React code to add support for resuming downloads from where they left off, both in case of app closure and connection loss. Additionally, the app will display a reconnection message with a countdown when the connection is lost.
Rust Code Updates
1. Modify download_file function to support resuming downloads:
We need to adjust the download_file function to:
- Check if the file already exists and determine how many bytes have been downloaded.
- Use the HTTP
Range header to request the remaining parts of the file.
- Open the existing file in append mode to continue writing where it left off.
Here's the updated download_file function:
use futures_util::stream::StreamExt;
use tokio::fs::OpenOptions;
// ... (rest of your imports)
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);
// Check if the file already exists and get its size
let existing_file_size = if let Ok(metadata) = fs::metadata(&file_path).await {
metadata.len()
} else {
0
};
// Get the total size of the file using a HEAD request
let head_response = client.head(&url).send().await.map_err(|e| e.to_string())?;
if !head_response.status().is_success() {
return Err(format!(
"Failed to get total size for '{}': HTTP {}",
entry.file_name,
head_response.status()
));
}
let total_bytes = head_response.content_length().unwrap_or(0);
// Open the file in append mode
let mut file = if existing_file_size > 0 {
OpenOptions::new()
.append(true)
.open(&file_path)
.await
.map_err(|e| e.to_string())?
} else {
fs::File::create(&file_path).await.map_err(|e| e.to_string())?
};
let mut downloaded_bytes = existing_file_size;
let start_time = Instant::now();
emit_download_status(app_handle, "Start", None).await?;
let mut last_emit_time = Instant::now();
let mut downloading_message_sent = false;
while downloaded_bytes < total_bytes {
// Build GET request with Range header to resume download
let mut request_builder = client.get(&url);
if downloaded_bytes > 0 {
request_builder = request_builder.header("Range", format!("bytes={}-", downloaded_bytes));
}
let response = request_builder.send().await.map_err(|e| e.to_string())?;
if !response.status().is_success()
&& response.status() != reqwest::StatusCode::PARTIAL_CONTENT
{
return Err(format!(
"Falha ao baixar '{}': HTTP {}",
entry.file_name,
response.status()
));
}
let mut response_stream = response.bytes_stream();
while let Some(chunk_result) = response_stream.next().await {
match chunk_result {
Ok(chunk) => {
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) {
if !downloading_message_sent {
emit_download_status(app_handle, "Downloading", None).await?;
downloading_message_sent = true;
}
let speed = if start_time.elapsed().as_secs_f64() == 0.0 {
0.0
} else {
downloaded_bytes as f64 / start_time.elapsed().as_secs_f64()
};
app_handle
.emit(
"download_info",
DownloadInfo {
current_file,
total_files,
file_name: entry.file_name.clone(),
downloaded_bytes,
total_bytes,
speed,
},
)
.map_err(|e| e.to_string())?;
last_emit_time = now;
}
}
Err(e) => {
// Error occurred, start reconnection logic
let error_message = format!("Erro ao baixar '{}': {}", entry.file_name, e);
eprintln!("{}", error_message);
emit_download_status(app_handle, "Error", Some(error_message.clone())).await?;
// Start reconnection countdown
for remaining in (1..=15).rev() {
emit_download_status(app_handle, "Reconnecting", Some(remaining.to_string()))
.await?;
tokio::time::sleep(Duration::from_secs(1)).await;
}
// Continue to retry the download from where it left off
break;
}
}
}
}
Ok(())
}
2. Handle reconnection logic when the connection is lost:
In the code above, when an error occurs during the chunk reading (Err(e)), the code starts a reconnection countdown by emitting a "Reconnecting" status with the remaining seconds. After the countdown, the download resumes from where it left off.
3. Support resuming downloads after app closure:
When the app is closed and reopened, the start_downloads function will:
- Iterate over the list of files in
patch.json.
- Check if each file exists and get its size.
- Resume downloading each file from where it left off.
This is handled by the updated download_file function, which checks for existing file size and uses the HTTP Range header to request the remaining bytes.
React Code Updates
1. Update the DownloadStatusType enum to include Reconnecting:
enum DownloadStatusType {
Connecting = "Connecting",
Connected = "Connected",
Start = "Start",
Downloading = "Downloading",
Reconnecting = "Reconnecting",
Completed = "Completed",
Error = "Error",
}
2. Update the status handling in the event listener:
Modify the useEffect hook to handle the Reconnecting status and display the countdown:
import { useEffect, useState } from "react";
import { listen } from "@tauri-apps/api/event";
import { invoke } from "@tauri-apps/api/tauri"; // Updated import
// ... (rest of your imports and code)
const DownloadManager = () => {
// ... (other state variables)
const [isReconnecting, setIsReconnecting] = useState(false);
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 DownloadStatusType.Connecting:
newMessage = "Conectando ao servidor...";
setIsReconnecting(false);
break;
case DownloadStatusType.Connected:
newMessage = "Conexão estabelecida com sucesso";
setIsReconnecting(false);
break;
case DownloadStatusType.Start:
newMessage = "Iniciando download...";
setIsReconnecting(false);
break;
case DownloadStatusType.Downloading:
newMessage = "Baixando arquivo";
setIsDownloading(true);
setIsReconnecting(false);
break;
case DownloadStatusType.Reconnecting:
newMessage = `Reconectando em ${additional_info} segundos...`;
setIsReconnecting(true);
break;
case DownloadStatusType.Completed:
newMessage = "Atualizações concluídas com sucesso.";
setIsDownloading(false);
setIsReconnecting(false);
break;
case DownloadStatusType.Error:
newMessage = `Erro: ${additional_info}`;
setIsDownloading(false);
setIsReconnecting(false);
break;
default:
newMessage = "Status desconhecido";
setIsReconnecting(false);
}
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);
});
})();
return () => {
if (unlistenStatus) unlistenStatus();
if (unlistenInfo) unlistenInfo();
};
}, [currentFile, totalFiles, downloadedBytes, totalBytes, downloadSpeed]);
// ... (rest of your component code)
};
3. Update the UI rendering to handle reconnection status:
Modify your JSX to display the reconnection message and adjust the progress bar accordingly:
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"
disabled={isDownloading || isReconnecting}
>
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-[12px] font-bold text-opacity-[0.95] text-white flex-grow text-center">
{message}
{isDownloading && totalFiles > 0 && downloadedBytes > 0 && totalBytes > 0 && (
<>
<span className="mx-1">
( <span className="text-blue-400">{currentFile}</span> / {totalFiles} )
</span>
: <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 && totalFiles > 0 && downloadedBytes > 0 && totalBytes > 0 && (
<div className="w-[30%] absolute h-6 flex justify-end items-center right-6 top-2">
<span className="text-[11px] font-bold text-opacity-[0.95] text-yellow-600 text-right">
{formatBytes(downloadSpeed)}ps
</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>
</>
);
4. Disable the "Iniciar Download" button during download or reconnection:
This prevents the user from starting multiple download processes simultaneously.
<button
onClick={startDownload}
className="bg-blue-500 text-white rounded p-2 mb-2"
disabled={isDownloading || isReconnecting}
>
Iniciar Download
</button>
Summary
With these changes:
- The app can resume downloads from where they left off if the app is closed or loses connection.
- If the connection is lost during a download, the app displays a countdown and tries to reconnect after 15 seconds.
- Upon reconnection, the download continues from where it left off.
- When the app is reopened, it checks for partial downloads and resumes them accordingly.
Note: Ensure that you test these changes thoroughly to handle edge cases, such as network instability and file corruption. Additionally, consider implementing checksum verification to ensure file integrity after downloads complete.