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};
let patch_file_path = exe_dir.join("patch.json");
let download_dir = exe_dir.join("patchs");
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())?;
}
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?;
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);
}
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!("Erro ao baixar '{}': {}", entry.file_name, err);
eprintln!("{}", error_message);
emit_download_status(&app_handle, "Error", Some(error_message.clone())).await?;
return Err(error_message);
}
}
// Emitir status de conclusão
emit_download_status(&app_handle, "Completed", None).await?;
Ok(())
}
recebo erro
error[E0590]: break or continue with no label in the condition of a while loop
--> src\download.rs:107:17
|
107 | break;
| ^^^^^ unlabeled break in the condition of a while loop
error[E0061]: this function takes 3 arguments but 4 arguments were supplied
--> src\download.rs:77:21
|
77 | emit_download_status(app_handle, "Reconnecting", None, Some(countdown)).await?;
| ^^^^^^^^^^^^^^^^^^^^ -----------------
| | |
| | unexpected argument of type std::option::Option<{integer}>
| help: remove the extra argument
|
note: function defined here
--> src\download.rs:48:10
|
48 | async fn emit_download_status(app_handle: &AppHandle, status: &str, additional_info: Option,) -> Result<(), String> {
| ^^^^^^^^^^^^^^^^^^^^ ---------------------- ------------ -------------------------------
error[E0061]: this function takes 3 arguments but 4 arguments were supplied
--> src\download.rs:95:9
|
95 | emit_download_status(app_handle, "Start", None, None).await?;
| ^^^^^^^^^^^^^^^^^^^^ ------
| | |
| | unexpected argument of type std::option::Option<_>
| help: remove the extra argument
|
note: function defined here
--> src\download.rs:48:10
|
48 | async fn emit_download_status(app_handle: &AppHandle, status: &str, additional_info: Option,) -> Result<(), String> {
| ^^^^^^^^^^^^^^^^^^^^ ---------------------- ------------ -------------------------------
error[E0308]: match arms have incompatible types
--> src\download.rs:107:17
|
102 | while let Some(chunk) = match response.chunk().await {
| ____________________________-
103 | | Ok(chunk_opt) => chunk_opt,
| | --------- this is found to be of type std::option::Option<bytes::bytes::Bytes>
104 | | Err() => {
105 | | // Erro de conexão durante o download
106 | | download_error = true;
107 | | break;
| | ^^^^^^ expected Option<Bytes>, found ()
108 | | }
109 | | } {
| |_____- match arms have incompatible types
|
= note: expected enum std::option::Option<bytes::bytes::Bytes>
found unit type ()
error[E0277]: the size for values of type [u8] cannot be known at compilation time
--> src\download.rs:102:19
|
102 | while let Some(chunk) = match response.chunk().await {
| ^^^^^^^^^^^ doesn't have a size known at compile-time
|
= help: the trait Sized is not implemented for [u8]
note: required by a bound in std::prelude::v1::Some
--> C:\Users\jonatas.rustup\toolchains\stable-x86_64-pc-windows-msvc\lib/rustlib/src/rust\library\core\src\option.rs:574:17
|
574 | pub enum Option {
| ^ required by this bound in std::prelude::v1::Some
...
582 | Some(#[stable(feature = "rust1", since = "1.0.0")] T),
| ---- required by a bound in this tuple variant
error[E0061]: this function takes 3 arguments but 4 arguments were supplied
--> src\download.rs:118:21
|
118 | emit_download_status(app_handle, "Downloading", None, None).await?;
| ^^^^^^^^^^^^^^^^^^^^ ------
| | |
| | unexpected argument of type std::option::Option<_>
| help: remove the extra argument
|
note: function defined here
--> src\download.rs:48:10
|
48 | async fn emit_download_status(app_handle: &AppHandle, status: &str, additional_info: Option,) -> Result<(), String> {
| ^^^^^^^^^^^^^^^^^^^^ ---------------------- ------------ -------------------------------
error[E0061]: this function takes 3 arguments but 4 arguments were supplied
--> src\download.rs:151:17
|
151 | emit_download_status(app_handle, "Reconnecting", None, Some(countdown)).await?;
| ^^^^^^^^^^^^^^^^^^^^ -----------------
| | |
| | unexpected argument of type std::option::Option<{integer}>
| help: remove the extra argument
|
note: function defined here
--> src\download.rs:48:10
|
48 | async fn emit_download_status(app_handle: &AppHandle, status: &str, additional_info: Option,) -> Result<(), String> {
| ^^^^^^^^^^^^^^^^^^^^ ---------------------- ------------ -------------------------------
error[E0061]: this function takes 2 arguments but 3 arguments were supplied
--> src\download.rs:157:29
|
157 | if let Err(_) = check_server_connection(client, "https://hil-speed.hetzner.com/", app_handle).await {
| ^^^^^^^^^^^^^^^^^^^^^^^ ------------
| | |
| | unexpected argument of type &AppHandle
| help: remove the extra argument
|
note: function defined here
--> src\download.rs:170:10
|
170 | async fn check_server_connection(client: &Client, url: &str) -> Result<(), String> {
| ^^^^^^^^^^^^^^^^^^^^^^^ --------------- ---------
Some errors have detailed explanations: E0061, E0277, E0308, E0590.
For more information about an error, try rustc --explain E0061.
The compiler errors you're encountering are primarily due to mismatches between your function definitions and how you're calling them, as well as some issues with the control flow in your download_file function. Let's address each error one by one and fix your code accordingly.
Error 1: Mismatched Number of Arguments in emit_download_status Calls
Error Message:
code
error[E0061]: this function takes 3 arguments but 4 arguments were supplied
Cause:
Your function emit_download_status is defined to take three arguments:
Solution:
You need to make sure that your function definition matches the number of arguments you're passing. Since you seem to want to pass countdown as additional information, you should:
Convert countdown (an integer) to String and pass it as additional_info.
Error 3: Incompatible Types in match Arms and Control Flow Issues
Error Messages:
code
error[E0308]: `match` arms have incompatible types
error[E0590]: `break` or `continue` with no label in the condition of a `while` loop
Cause:
You're using break inside a match statement that is part of a while let condition, which is invalid because break cannot be used to exit the enclosing while let in this manner.
The match statement's arms return different types (Option<Bytes> vs. ()), causing type incompatibility.
Your code snippet:
rust
while let Some(chunk) = match response.chunk().await {
Ok(chunk_opt) => chunk_opt,
Err(_) => {
download_error = true;
break;
}
} {
// Process chunk
}
Solution:
Refactor your code to avoid using break inside the condition of a while let loop. Instead, use an infinite loop and handle the break statements within the loop body.
Corrected Code:
rust
let mut download_error = false;
loop {
match response.chunk().await {
Ok(Some(chunk)) => {
if let Err(e) = file.write_all(&chunk).await {
return Err(format!(
"Error writing to file '{}': {}",
entry.file_name, 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().is_zero() {
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;
}
}
Ok(None) => {
// End of stream
break;
}
Err(_) => {
download_error = true;
break;
}
}
}
if download_error {
// Close the file
drop(file);
// Initiate reconnection
let mut countdown = 15;
while countdown > 0 {
emit_download_status(app_handle, "Reconnecting", Some(countdown.to_string())).await?;
tokio::time::sleep(Duration::from_secs(1)).await;
countdown -= 1;
}
// Attempt to reconnect
if check_server_connection(client, "https://hil-speed.hetzner.com/").await.is_err() {
continue;
} else {
continue;
}
}
Error 4: Size of [u8] Cannot Be Known at Compilation Time
Error Message:
code
error[E0277]: the size for values of type `[u8]` cannot be known at compilation time
Cause:
This error is likely a side effect of the previous issues. Rust needs to know the size of types at compile time unless you use references or smart pointers.
Solution:
By refactoring the code as shown above, you avoid this error because you're no longer misusing types in the match and while let statements.
Final Revised download_file Function
Combining all corrections, your download_file function should look like this:
rust
Summary of Changes
Adjusted Function Calls to Match Definitions:
Changed emit_download_status calls to pass only three arguments.
Converted countdown to a String when passing it as additional_info.
Removed Extra Argument from check_server_connection Call:
Removed app_handle from the function call.
Refactored Control Flow in download_file:
Replaced while let Some(chunk) = match ... with a loop and proper match handling.
Ensured that all match arms return the same type.
Handled Errors Appropriately:
Used break inside the loop body instead of inside the condition.
Set download_error flag and handled reconnection logic after the loop.
By applying these corrections, your code should compile successfully and work as intended.
I hope this helps you fix the errors and understand the necessary changes. Let me know if you need further assistance!