[Clean]
This commit is contained in:
parent
c17e1de478
commit
f0d0447416
4 changed files with 152 additions and 95 deletions
|
|
@ -1,3 +1,4 @@
|
|||
pub mod api;
|
||||
pub mod server;
|
||||
pub mod socket;
|
||||
pub mod web_path_parser;
|
||||
|
|
|
|||
|
|
@ -1,7 +1,7 @@
|
|||
use crate::gui::log_panel::log_message;
|
||||
use crate::server::api;
|
||||
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 base64::Engine;
|
||||
|
|
@ -29,7 +29,7 @@ use std::result::Result::Ok;
|
|||
use std::sync::Arc;
|
||||
use std::{future::Future, pin::Pin, time::Duration};
|
||||
use tokio::net::TcpListener;
|
||||
use tokio::sync::broadcast; // Import broadcast for the kill switch
|
||||
use tokio::sync::broadcast;
|
||||
use tokio_rustls::TlsAcceptor;
|
||||
use tokio_tungstenite::WebSocketStream;
|
||||
use tower::Service;
|
||||
|
|
@ -141,57 +141,27 @@ impl Service<HttpRequest<Incoming>> for HttpService {
|
|||
|
||||
Ok(api::handle(&path, &is_acceptable, headers.clone(), body_string).await)
|
||||
} else {
|
||||
let mut path_parts: Vec<&str> = path.split("/").collect();
|
||||
let name = path_parts.remove(path_parts.len() - 1);
|
||||
let name = if name.is_empty() {
|
||||
"index.html"
|
||||
} else if name.contains(".") && name.contains("?") {
|
||||
name.split("?").next().unwrap()
|
||||
} else if name.contains(".") {
|
||||
name
|
||||
} else {
|
||||
&format!("{}.html", name)
|
||||
};
|
||||
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",
|
||||
let whole_body = match body.collect().await {
|
||||
Ok(collected) => collected,
|
||||
Err(e) => {
|
||||
log_message(format!("Error collecting body: {}", e));
|
||||
return Ok(HttpResponse::builder()
|
||||
.status(StatusCode::INTERNAL_SERVER_ERROR)
|
||||
.body(Full::new(Bytes::from(format!(
|
||||
"Failed to read body: {}",
|
||||
e
|
||||
))))
|
||||
.unwrap());
|
||||
}
|
||||
} else {
|
||||
"application/octet-stream"
|
||||
};
|
||||
let (status, content, body_text): (StatusCode, &str, Vec<u8>) = {
|
||||
let content = load_file_vec(&format!("web{}/", path_parts.join("/")), name);
|
||||
if content.is_empty() {
|
||||
let content = load_file_vec("web", "404.html");
|
||||
if content.is_empty() {
|
||||
(
|
||||
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 bytes = whole_body.to_bytes();
|
||||
|
||||
let body_string: Option<String> = match String::from_utf8(bytes.to_vec()) {
|
||||
Ok(s) => Some(s),
|
||||
Err(_) => None,
|
||||
};
|
||||
|
||||
let body = Full::new(Bytes::from(body_text.to_vec()));
|
||||
let response = HttpResponse::builder()
|
||||
.header("Content-Type", content)
|
||||
.status(status)
|
||||
.body(body)
|
||||
.unwrap();
|
||||
Ok(response)
|
||||
Ok(web_path_parser::handle(&path, headers, body_string).await)
|
||||
}
|
||||
};
|
||||
|
||||
|
|
|
|||
101
src/server/web_path_parser.rs
Normal file
101
src/server/web_path_parser.rs
Normal 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
75
src/util/file_util.rs
Normal file → Executable file
|
|
@ -1,8 +1,9 @@
|
|||
use std::ffi::OsStr;
|
||||
use std::fs::{self, File};
|
||||
use std::io::{self, BufReader, Read, Write};
|
||||
use std::io::{self, BufReader, Read};
|
||||
use std::path::{Path, PathBuf};
|
||||
use sysinfo::System;
|
||||
use tokio::io::AsyncWriteExt;
|
||||
use uuid::Uuid;
|
||||
use walkdir::WalkDir;
|
||||
use zip::ZipArchive;
|
||||
|
|
@ -33,7 +34,7 @@ fn delete_dir_recursive(directory: &Path) -> bool {
|
|||
log_message(format!(
|
||||
"[IMPORTANT] Couldn't delete directory {}: {}",
|
||||
directory.display(),
|
||||
e
|
||||
e,
|
||||
));
|
||||
return false;
|
||||
}
|
||||
|
|
@ -124,31 +125,13 @@ pub fn load_file(path: &str, name: &str) -> String {
|
|||
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 file_path = dir.join(name);
|
||||
|
||||
if !dir.exists() {
|
||||
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
|
||||
std::fs::read(file_path)
|
||||
}
|
||||
|
||||
pub fn save_file(path: &str, name: &str, value: &str) {
|
||||
let dir = Path::new(&get_directory()).join(path);
|
||||
let file_path = dir.join(name);
|
||||
|
|
@ -190,6 +173,7 @@ pub fn get_directory() -> String {
|
|||
.to_string()
|
||||
}
|
||||
|
||||
// Helper to download the zip file content to a file on disk
|
||||
#[allow(dead_code)]
|
||||
pub fn used_space() -> u64 {
|
||||
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?;
|
||||
|
||||
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 file = File::create(zip_path)?;
|
||||
file.write_all(&bytes)?;
|
||||
file.flush()?;
|
||||
let mut zip_file = tokio::fs::File::create(zip_path).await?;
|
||||
let body = response.bytes().await?;
|
||||
zip_file.write_all(&body).await?;
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
|
@ -346,30 +328,33 @@ fn extract_zip_contents_to_folder(
|
|||
Ok(())
|
||||
}
|
||||
|
||||
#[allow(dead_code)]
|
||||
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 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);
|
||||
|
||||
log_message(format!("Downloading {}...", url));
|
||||
|
||||
if let Err(e) = download_zip(url, &zip_path).await {
|
||||
log_message(format!("Download failed: {}", e));
|
||||
log_message(format!("Error downloading file: {}", e));
|
||||
return;
|
||||
}
|
||||
|
||||
log_message("Download complete. Extracting...");
|
||||
|
||||
if let Err(e) = extract_zip_contents_to_folder(&zip_path, &target_dir) {
|
||||
log_message(format!("Extraction failed: {}", e));
|
||||
let _ = fs::remove_file(&zip_path);
|
||||
return;
|
||||
let zip_path_clone = zip_path.clone();
|
||||
let target_dir_clone = target_dir.clone();
|
||||
let extract_result = extract_zip_contents_to_folder(&zip_path_clone, &target_dir_clone);
|
||||
if let Err(e) = extract_result {
|
||||
log_message(format!("Panic during ZIP extraction: {}", e));
|
||||
}
|
||||
|
||||
let _ = fs::remove_file(&zip_path);
|
||||
|
||||
log_message(format!(
|
||||
"Successfully extracted to {}",
|
||||
target_dir.display()
|
||||
));
|
||||
if let Err(e) = tokio::fs::remove_file(&zip_path).await {
|
||||
log_message(format!(
|
||||
"Error cleaning up ZIP file {}: {}",
|
||||
zip_path.display(),
|
||||
e
|
||||
));
|
||||
} else {
|
||||
log_message("Downloaded ZIP file");
|
||||
}
|
||||
}
|
||||
|
|
|
|||
Loading…
Reference in a new issue