(feat:background) Fix Rust-based file download & Create the 'bg' directory on app setup

This commit is contained in:
KingRainbow44
2023-11-29 23:48:29 -05:00
parent 41c074e462
commit ee4b5ad0d9
4 changed files with 1219 additions and 25 deletions

1200
src-tauri/Cargo.lock generated

File diff suppressed because it is too large Load Diff

View File

@@ -13,10 +13,12 @@ edition = "2021"
tauri-build = { version = "1.5", features = [] }
[dependencies]
tauri = { version = "1.5", features = ["shell-open"] }
tauri = { version = "1.5", features = [ "api-all"] }
serde = { version = "1.0", features = ["derive"] }
serde_json = "1.0"
reqwest = "0.11.22"
[features]
# this feature is used for production builds or when `devPath` points to the filesystem
# DO NOT REMOVE!!

View File

@@ -1,4 +1,3 @@
use core::error::Error;
use std::fs::File;
use std::io::Write;
use std::path::Path;
@@ -9,17 +8,20 @@ use std::path::Path;
/// url: The URL to download from.
/// to_file: The file to save to.
#[tauri::command]
pub async fn download_file(url: String, to_file: String) -> Result<String, Box<dyn Error>> {
let mut response = reqwest::get(&url).await?;
pub async fn download_file(url: String, to_file: String) -> Result<String, String> {
let mut response = reqwest::get(&url).await
.expect("Failed to send request");
let mut dest = {
let fname = Path::new(&to_file);
match File::create(&fname) {
Ok(f) => f,
Err(e) => return Err(Box::new(e)),
Err(_) => return Err("Failed to create file".to_string()),
}
};
while let Some(chunk) = response.chunk().await? {
dest.write_all(&chunk).await?;
while let Some(chunk) = response.chunk().await
.expect("Unable to read chunk") {
dest.write_all(&chunk)
.expect("Failed to write chunk to file")
}
Ok("Downloaded".to_string())
}

View File

@@ -1,15 +1,29 @@
// Prevents additional console window on Windows in release, DO NOT REMOVE!!
#![cfg_attr(not(debug_assertions), windows_subsystem = "windows")]
// Learn more about Tauri commands at https://tauri.app/v1/guides/features/command
#[tauri::command]
fn greet(name: &str) -> String {
format!("Hello, {}! You've been greeted from Rust!", name)
}
use std::fs::create_dir;
mod http;
fn main() {
tauri::Builder::default()
.invoke_handler(tauri::generate_handler![greet])
.invoke_handler(tauri::generate_handler![
http::download_file
])
.setup(|app| {
// Create base directories.
let app_data_dir = app.path_resolver()
.app_data_dir()
.expect("Failed to get app data directory");
let background_directory = app_data_dir.join("bg");
if !background_directory.exists() {
create_dir(background_directory.as_path())
.expect("Failed to create app data directory");
}
Ok(())
})
.run(tauri::generate_context!())
.expect("error while running tauri application");
}