This commit is contained in:
Alex Emmet 2026-02-11 22:44:02 +01:00
commit f0d0447416
4 changed files with 152 additions and 95 deletions

View file

@ -1,3 +1,4 @@
pub mod api; pub mod api;
pub mod server; pub mod server;
pub mod socket; pub mod socket;
pub mod web_path_parser;

View file

@ -1,7 +1,7 @@
use crate::gui::log_panel::log_message; use crate::gui::log_panel::log_message;
use crate::server::api;
use crate::server::socket::handle; use crate::server::socket::handle;
use crate::util::file_util::{load_file_buf, load_file_vec}; use crate::server::{api, web_path_parser};
use crate::util::file_util::load_file_buf;
use crate::{ACTIVE_TASKS, SHUTDOWN}; use crate::{ACTIVE_TASKS, SHUTDOWN};
use base64::Engine; use base64::Engine;
@ -29,7 +29,7 @@ use std::result::Result::Ok;
use std::sync::Arc; use std::sync::Arc;
use std::{future::Future, pin::Pin, time::Duration}; use std::{future::Future, pin::Pin, time::Duration};
use tokio::net::TcpListener; use tokio::net::TcpListener;
use tokio::sync::broadcast; // Import broadcast for the kill switch use tokio::sync::broadcast;
use tokio_rustls::TlsAcceptor; use tokio_rustls::TlsAcceptor;
use tokio_tungstenite::WebSocketStream; use tokio_tungstenite::WebSocketStream;
use tower::Service; use tower::Service;
@ -141,57 +141,27 @@ impl Service<HttpRequest<Incoming>> for HttpService {
Ok(api::handle(&path, &is_acceptable, headers.clone(), body_string).await) Ok(api::handle(&path, &is_acceptable, headers.clone(), body_string).await)
} else { } else {
let mut path_parts: Vec<&str> = path.split("/").collect(); let whole_body = match body.collect().await {
let name = path_parts.remove(path_parts.len() - 1); Ok(collected) => collected,
let name = if name.is_empty() { Err(e) => {
"index.html" log_message(format!("Error collecting body: {}", e));
} else if name.contains(".") && name.contains("?") { return Ok(HttpResponse::builder()
name.split("?").next().unwrap() .status(StatusCode::INTERNAL_SERVER_ERROR)
} else if name.contains(".") { .body(Full::new(Bytes::from(format!(
name "Failed to read body: {}",
} else { e
&format!("{}.html", name) ))))
}; .unwrap());
let code = if let Some(ext) = name.split(".").last() {
match ext {
"html" => "text/html",
"css" => "text/css",
"ico" => "image/x-icon",
"png" => "image/png",
"js" => "application/javascript",
"json" => "application/json",
_ => "application/octet-stream",
} }
} else {
"application/octet-stream"
}; };
let (status, content, body_text): (StatusCode, &str, Vec<u8>) = { let bytes = whole_body.to_bytes();
let content = load_file_vec(&format!("web{}/", path_parts.join("/")), name);
if content.is_empty() { let body_string: Option<String> = match String::from_utf8(bytes.to_vec()) {
let content = load_file_vec("web", "404.html"); Ok(s) => Some(s),
if content.is_empty() { Err(_) => None,
(
StatusCode::NOT_FOUND,
code,
include_str!("../../static/web/404.html")
.as_bytes()
.to_vec(),
)
} else {
(StatusCode::OK, code, content)
}
} else {
(StatusCode::OK, code, content)
}
}; };
let body = Full::new(Bytes::from(body_text.to_vec())); Ok(web_path_parser::handle(&path, headers, body_string).await)
let response = HttpResponse::builder()
.header("Content-Type", content)
.status(status)
.body(body)
.unwrap();
Ok(response)
} }
}; };

View file

@ -0,0 +1,101 @@
use std::path::{Path, PathBuf};
use axum::http::HeaderValue;
use http_body_util::Full;
use hyper::body::Bytes;
use hyper::{HeaderMap, Response as HttpResponse, StatusCode};
use json::JsonValue;
use crate::util::file_util::load_file_vec;
fn codec_for_ext(ext: &str) -> &'static str {
match ext {
"html" => "text/html; charset=utf-8",
"css" => "text/css",
"js" => "application/javascript",
"json" => "application/json",
"png" => "image/png",
"ico" => "image/x-icon",
"woff2" => "font/woff2",
_ => "application/octet-stream",
}
}
pub async fn handle(
path: &str,
_headers: HeaderMap<HeaderValue>,
body_string: Option<String>,
) -> HttpResponse<Full<Bytes>> {
let path_parts: Vec<&str> = path.split("/").filter(|s| !s.is_empty()).collect();
let _body: Option<JsonValue> = if body_string.is_some() {
if let Ok(body_json) = json::parse(&body_string.unwrap()) {
Some(body_json)
} else {
None
}
} else {
None
};
let req_path = path.trim_start_matches('/');
let mut fs_path = PathBuf::from("web");
if req_path.is_empty() {
fs_path.push("index.html");
} else {
fs_path.extend(req_path.split('/'));
}
if fs_path.is_dir() {
fs_path.push("index.html");
}
let ext = fs_path.extension().and_then(|e| e.to_str()).unwrap_or("");
let codec = codec_for_ext(ext);
let dir = fs_path.parent().unwrap_or(Path::new("web"));
let name = fs_path
.file_name()
.and_then(|n| n.to_str())
.unwrap_or("index.html");
let content = load_file_vec(dir.to_str().unwrap_or("web"), name);
if let Ok(content) = content {
HttpResponse::builder()
.status(StatusCode::OK)
.header("content-type", codec)
.body(Full::new(Bytes::from(content)))
.unwrap()
} else {
if matches!(ext, "js" | "css" | "woff2") {
return HttpResponse::builder()
.status(StatusCode::NOT_FOUND)
.header("content-type", "text/plain")
.body(Full::new(Bytes::from("Not found")))
.unwrap();
}
let fallback = load_file_vec("web", "404.html");
let body = if let Ok(fallback) = fallback {
if fallback.is_empty() {
include_str!("../../static/web/404.html")
.as_bytes()
.to_vec()
} else {
fallback
}
} else {
include_str!("../../static/web/404.html")
.as_bytes()
.to_vec()
};
HttpResponse::builder()
.status(StatusCode::NOT_FOUND)
.header("content-type", "text/html; charset=utf-8")
.body(Full::new(Bytes::from(body)))
.unwrap()
}
}

75
src/util/file_util.rs Normal file → Executable file
View file

@ -1,8 +1,9 @@
use std::ffi::OsStr; use std::ffi::OsStr;
use std::fs::{self, File}; use std::fs::{self, File};
use std::io::{self, BufReader, Read, Write}; use std::io::{self, BufReader, Read};
use std::path::{Path, PathBuf}; use std::path::{Path, PathBuf};
use sysinfo::System; use sysinfo::System;
use tokio::io::AsyncWriteExt;
use uuid::Uuid; use uuid::Uuid;
use walkdir::WalkDir; use walkdir::WalkDir;
use zip::ZipArchive; use zip::ZipArchive;
@ -33,7 +34,7 @@ fn delete_dir_recursive(directory: &Path) -> bool {
log_message(format!( log_message(format!(
"[IMPORTANT] Couldn't delete directory {}: {}", "[IMPORTANT] Couldn't delete directory {}: {}",
directory.display(), directory.display(),
e e,
)); ));
return false; return false;
} }
@ -124,31 +125,13 @@ pub fn load_file(path: &str, name: &str) -> String {
content content
} }
pub fn load_file_vec(path: &str, name: &str) -> Vec<u8> { pub fn load_file_vec(path: &str, name: &str) -> Result<Vec<u8>, std::io::Error> {
let dir = Path::new(&get_directory()).join(path); let dir = Path::new(&get_directory()).join(path);
let file_path = dir.join(name); let file_path = dir.join(name);
if !dir.exists() { std::fs::read(file_path)
if let Err(e) = fs::create_dir_all(&dir) {
log_message(format!("[IMPORTANT] Couldn't create directories: {}", e));
return Vec::new();
}
return Vec::new();
}
if !file_path.exists() {
if let Err(e) = File::create(&file_path) {
log_message(format!("[IMPORTANT] Couldn't create file: {}", e));
}
return Vec::new();
}
let mut content = Vec::new();
if let Ok(mut f) = File::open(&file_path) {
let _ = f.read_to_end(&mut content);
}
content
} }
pub fn save_file(path: &str, name: &str, value: &str) { pub fn save_file(path: &str, name: &str, value: &str) {
let dir = Path::new(&get_directory()).join(path); let dir = Path::new(&get_directory()).join(path);
let file_path = dir.join(name); let file_path = dir.join(name);
@ -190,6 +173,7 @@ pub fn get_directory() -> String {
.to_string() .to_string()
} }
// Helper to download the zip file content to a file on disk
#[allow(dead_code)] #[allow(dead_code)]
pub fn used_space() -> u64 { pub fn used_space() -> u64 {
get_directory_size(&PathBuf::from(get_directory())) get_directory_size(&PathBuf::from(get_directory()))
@ -257,14 +241,12 @@ pub async fn download_zip(url: &str, zip_path: &Path) -> Result<(), Box<dyn std:
let response = client.get(url).send().await?; let response = client.get(url).send().await?;
if !response.status().is_success() { if !response.status().is_success() {
return Err(format!("Download failed: {}", response.status()).into()); return Err(format!("Failed to download file: Status {}", response.status()).into());
} }
let bytes = response.bytes().await?; let mut zip_file = tokio::fs::File::create(zip_path).await?;
let body = response.bytes().await?;
let mut file = File::create(zip_path)?; zip_file.write_all(&body).await?;
file.write_all(&bytes)?;
file.flush()?;
Ok(()) Ok(())
} }
@ -346,30 +328,33 @@ fn extract_zip_contents_to_folder(
Ok(()) Ok(())
} }
#[allow(dead_code)]
pub async fn download_and_extract_zip(url: &str, as_name: &str) { pub async fn download_and_extract_zip(url: &str, as_name: &str) {
log_message("Downloading ZIP file...");
let base_dir = PathBuf::from(get_directory()); let base_dir = PathBuf::from(get_directory());
let zip_path = base_dir.join(format!("{}.zip", Uuid::new_v4())); let zip_filename = format!("{}.zip", Uuid::new_v4());
let zip_path = base_dir.join(&zip_filename);
let target_dir = base_dir.join(as_name); let target_dir = base_dir.join(as_name);
log_message(format!("Downloading {}...", url));
if let Err(e) = download_zip(url, &zip_path).await { if let Err(e) = download_zip(url, &zip_path).await {
log_message(format!("Download failed: {}", e)); log_message(format!("Error downloading file: {}", e));
return; return;
} }
log_message("Download complete. Extracting..."); let zip_path_clone = zip_path.clone();
let target_dir_clone = target_dir.clone();
if let Err(e) = extract_zip_contents_to_folder(&zip_path, &target_dir) { let extract_result = extract_zip_contents_to_folder(&zip_path_clone, &target_dir_clone);
log_message(format!("Extraction failed: {}", e)); if let Err(e) = extract_result {
let _ = fs::remove_file(&zip_path); log_message(format!("Panic during ZIP extraction: {}", e));
return;
} }
let _ = fs::remove_file(&zip_path); if let Err(e) = tokio::fs::remove_file(&zip_path).await {
log_message(format!(
log_message(format!( "Error cleaning up ZIP file {}: {}",
"Successfully extracted to {}", zip_path.display(),
target_dir.display() e
)); ));
} else {
log_message("Downloaded ZIP file");
}
} }