[FIX] Web UI
This commit is contained in:
parent
4bb370bca2
commit
059f2e9825
7 changed files with 861 additions and 470 deletions
|
|
@ -1,38 +1,32 @@
|
|||
use crate::server::server::is_local_network;
|
||||
use crate::util::config_util::CONFIG;
|
||||
use axum::routing::{get, post};
|
||||
use axum::{
|
||||
extract::{ConnectInfo, Json, State},
|
||||
http::{HeaderMap, StatusCode},
|
||||
response::{IntoResponse, Response},
|
||||
};
|
||||
use actix_web::{HttpRequest, HttpResponse, Responder, web};
|
||||
use serde_json::{Value, json};
|
||||
use std::net::SocketAddr;
|
||||
use std::sync::Arc;
|
||||
|
||||
pub fn api_router() -> axum::Router<bool> {
|
||||
axum::Router::new()
|
||||
.route("/shutdown", post(shutdown))
|
||||
.route("/reload", post(reload))
|
||||
.route("/users/add", post(users_add))
|
||||
.route("/users/remove", post(users_remove))
|
||||
.route("/users/get", get(users_get))
|
||||
.route("/communities/add", post(communities_add))
|
||||
.route("/communities/get", get(communities_get))
|
||||
.route("/settings/set", post(settings_set))
|
||||
.route("/settings/get", get(settings_get))
|
||||
pub fn api_config(cfg: &mut web::ServiceConfig) {
|
||||
cfg.service(
|
||||
web::scope("/api")
|
||||
.route("/shutdown/", web::post().to(shutdown))
|
||||
.route("/reload/", web::post().to(reload))
|
||||
.route("/users/add/", web::post().to(users_add))
|
||||
.route("/users/remove/", web::post().to(users_remove))
|
||||
.route("/users/get/", web::get().to(users_get))
|
||||
.route("/communities/add/", web::post().to(communities_add))
|
||||
.route("/communities/get/", web::get().to(communities_get))
|
||||
.route("/settings/set/", web::post().to(settings_set))
|
||||
.route("/settings/get/", web::get().to(settings_get)),
|
||||
);
|
||||
}
|
||||
pub async fn settings_set(
|
||||
ConnectInfo(addr): ConnectInfo<SocketAddr>,
|
||||
State(ssl): State<bool>,
|
||||
headers: HeaderMap,
|
||||
) -> Response {
|
||||
if !is_allowed(addr, ssl) {
|
||||
|
||||
async fn settings_set(req: HttpRequest, ssl: web::Data<bool>) -> impl Responder {
|
||||
if !is_allowed_req(&req, *ssl.get_ref()) {
|
||||
return forbidden();
|
||||
}
|
||||
|
||||
let key = headers.get("key").and_then(|v| v.to_str().ok());
|
||||
let value = headers.get("value").and_then(|v| v.to_str().ok());
|
||||
let key = req.headers().get("key").and_then(|v| v.to_str().ok());
|
||||
let value = req.headers().get("value").and_then(|v| v.to_str().ok());
|
||||
|
||||
match (key, value) {
|
||||
(Some(k), Some(v)) => {
|
||||
|
|
@ -48,22 +42,17 @@ pub async fn settings_set(
|
|||
}
|
||||
}
|
||||
|
||||
pub async fn settings_get(
|
||||
ConnectInfo(addr): ConnectInfo<SocketAddr>,
|
||||
State(ssl): State<bool>,
|
||||
) -> Response {
|
||||
if !is_allowed(addr, ssl) {
|
||||
async fn settings_get(req: HttpRequest, ssl: web::Data<bool>) -> impl Responder {
|
||||
if !is_allowed_req(&req, *ssl.get_ref()) {
|
||||
return forbidden();
|
||||
}
|
||||
let config = CONFIG.read().await.config.clone();
|
||||
let serde_config: Value = serde_json::to_value(config.to_string()).unwrap();
|
||||
(StatusCode::OK, Json(serde_config)).into_response()
|
||||
HttpResponse::Ok().json(serde_config)
|
||||
}
|
||||
pub async fn communities_get(
|
||||
ConnectInfo(addr): ConnectInfo<SocketAddr>,
|
||||
State(ssl): State<bool>,
|
||||
) -> Response {
|
||||
if !is_allowed(addr, ssl) {
|
||||
|
||||
async fn communities_get(req: HttpRequest, ssl: web::Data<bool>) -> impl Responder {
|
||||
if !is_allowed_req(&req, *ssl.get_ref()) {
|
||||
return forbidden();
|
||||
}
|
||||
|
||||
|
|
@ -76,14 +65,15 @@ pub async fn communities_get(
|
|||
let s_val: Value = serde_json::to_value(val.to_string()).unwrap();
|
||||
list.push(s_val);
|
||||
}
|
||||
(StatusCode::OK, Json(list)).into_response()
|
||||
HttpResponse::Ok().json(list)
|
||||
}
|
||||
pub async fn communities_add(
|
||||
ConnectInfo(addr): ConnectInfo<SocketAddr>,
|
||||
State(ssl): State<bool>,
|
||||
Json(payload): Json<Value>,
|
||||
) -> Response {
|
||||
if !is_allowed(addr, ssl) {
|
||||
|
||||
async fn communities_add(
|
||||
req: HttpRequest,
|
||||
ssl: web::Data<bool>,
|
||||
payload: web::Json<Value>,
|
||||
) -> impl Responder {
|
||||
if !is_allowed_req(&req, *ssl.get_ref()) {
|
||||
return forbidden();
|
||||
}
|
||||
|
||||
|
|
@ -96,11 +86,9 @@ pub async fn communities_add(
|
|||
|
||||
success()
|
||||
}
|
||||
pub async fn users_get(
|
||||
ConnectInfo(addr): ConnectInfo<SocketAddr>,
|
||||
State(ssl): State<bool>,
|
||||
) -> Response {
|
||||
if !is_allowed(addr, ssl) {
|
||||
|
||||
async fn users_get(req: HttpRequest, ssl: web::Data<bool>) -> impl Responder {
|
||||
if !is_allowed_req(&req, *ssl.get_ref()) {
|
||||
return forbidden();
|
||||
}
|
||||
|
||||
|
|
@ -114,14 +102,15 @@ pub async fn users_get(
|
|||
})
|
||||
.collect();
|
||||
|
||||
(StatusCode::OK, Json(list)).into_response()
|
||||
HttpResponse::Ok().json(list)
|
||||
}
|
||||
pub async fn users_remove(
|
||||
ConnectInfo(addr): ConnectInfo<SocketAddr>,
|
||||
State(ssl): State<bool>,
|
||||
Json(payload): Json<Value>,
|
||||
) -> Response {
|
||||
if !is_allowed(addr, ssl) {
|
||||
|
||||
async fn users_remove(
|
||||
req: HttpRequest,
|
||||
ssl: web::Data<bool>,
|
||||
payload: web::Json<Value>,
|
||||
) -> impl Responder {
|
||||
if !is_allowed_req(&req, *ssl.get_ref()) {
|
||||
return forbidden();
|
||||
}
|
||||
|
||||
|
|
@ -132,12 +121,13 @@ pub async fn users_remove(
|
|||
|
||||
success()
|
||||
}
|
||||
pub async fn users_add(
|
||||
ConnectInfo(addr): ConnectInfo<SocketAddr>,
|
||||
State(ssl): State<bool>,
|
||||
Json(payload): Json<Value>,
|
||||
) -> Response {
|
||||
if !is_allowed(addr, ssl) {
|
||||
|
||||
async fn users_add(
|
||||
req: HttpRequest,
|
||||
ssl: web::Data<bool>,
|
||||
payload: web::Json<Value>,
|
||||
) -> impl Responder {
|
||||
if !is_allowed_req(&req, *ssl.get_ref()) {
|
||||
return forbidden();
|
||||
}
|
||||
|
||||
|
|
@ -149,16 +139,14 @@ pub async fn users_add(
|
|||
if let (Some(user), Some(_)) = crate::users::user_manager::create_user(username).await {
|
||||
let val = user.frontend();
|
||||
let s_val: Value = serde_json::to_value(val.to_string()).unwrap();
|
||||
(StatusCode::OK, Json(s_val)).into_response()
|
||||
HttpResponse::Ok().json(s_val)
|
||||
} else {
|
||||
error()
|
||||
}
|
||||
}
|
||||
pub async fn shutdown(
|
||||
ConnectInfo(addr): ConnectInfo<SocketAddr>,
|
||||
State(ssl): State<bool>,
|
||||
) -> Response {
|
||||
if !is_allowed(addr, ssl) {
|
||||
|
||||
async fn shutdown(req: HttpRequest, ssl: web::Data<bool>) -> impl Responder {
|
||||
if !is_allowed_req(&req, *ssl.get_ref()) {
|
||||
return forbidden();
|
||||
}
|
||||
|
||||
|
|
@ -166,11 +154,8 @@ pub async fn shutdown(
|
|||
success()
|
||||
}
|
||||
|
||||
pub async fn reload(
|
||||
ConnectInfo(addr): ConnectInfo<SocketAddr>,
|
||||
State(ssl): State<bool>,
|
||||
) -> Response {
|
||||
if !is_allowed(addr, ssl) {
|
||||
async fn reload(req: HttpRequest, ssl: web::Data<bool>) -> impl Responder {
|
||||
if !is_allowed_req(&req, *ssl.get_ref()) {
|
||||
return forbidden();
|
||||
}
|
||||
|
||||
|
|
@ -180,18 +165,26 @@ pub async fn reload(
|
|||
success()
|
||||
}
|
||||
|
||||
fn forbidden() -> Response {
|
||||
(StatusCode::FORBIDDEN, "403 Forbidden").into_response()
|
||||
fn forbidden() -> HttpResponse {
|
||||
HttpResponse::Forbidden().body("403 Forbidden")
|
||||
}
|
||||
|
||||
fn success() -> Response {
|
||||
Json(json!({ "type": "success" })).into_response()
|
||||
fn success() -> HttpResponse {
|
||||
HttpResponse::Ok().json(json!({ "type": "success" }))
|
||||
}
|
||||
|
||||
fn error() -> Response {
|
||||
Json(json!({ "type": "error" })).into_response()
|
||||
fn error() -> HttpResponse {
|
||||
HttpResponse::Ok().json(json!({ "type": "error" }))
|
||||
}
|
||||
|
||||
fn is_allowed(addr: SocketAddr, ssl: bool) -> bool {
|
||||
is_local_network(addr.ip()) || ssl
|
||||
}
|
||||
|
||||
fn is_allowed_req(req: &HttpRequest, ssl: bool) -> bool {
|
||||
if let Some(addr) = req.peer_addr() {
|
||||
is_allowed(addr, ssl)
|
||||
} else {
|
||||
false
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,165 +1,98 @@
|
|||
use crate::gui::log_panel::log_message;
|
||||
use crate::server::api::api_router;
|
||||
use crate::server::socket::handle;
|
||||
use crate::server::web_path_parser::codec_for_ext;
|
||||
use crate::util::file_util::{load_file_buf, load_file_vec};
|
||||
use crate::server::api::api_config;
|
||||
use crate::server::socket::WsSession;
|
||||
use crate::server::web_path_parser;
|
||||
use crate::util::file_util::load_file_buf;
|
||||
use crate::{ACTIVE_TASKS, SHUTDOWN};
|
||||
|
||||
use axum::{
|
||||
Router,
|
||||
extract::{
|
||||
ConnectInfo, Path,
|
||||
ws::{WebSocket, WebSocketUpgrade},
|
||||
},
|
||||
http::{HeaderMap, StatusCode},
|
||||
response::{IntoResponse, Response},
|
||||
routing::{any, get},
|
||||
};
|
||||
use axum_server::tls_rustls::RustlsConfig;
|
||||
use futures_util::StreamExt;
|
||||
use actix_web::{App, Error, HttpRequest, HttpServer, Responder, dev::ServerHandle, web};
|
||||
use actix_web_actors::ws;
|
||||
|
||||
use rustls::ServerConfig;
|
||||
use rustls::pki_types::{CertificateDer, PrivateKeyDer};
|
||||
use std::{
|
||||
error::Error,
|
||||
error::Error as StdError,
|
||||
io::{self, BufReader, ErrorKind},
|
||||
net::{IpAddr, SocketAddr},
|
||||
net::IpAddr,
|
||||
sync::Arc,
|
||||
time::Duration,
|
||||
};
|
||||
use tokio::net::TcpListener;
|
||||
use tower::ServiceBuilder;
|
||||
|
||||
fn build_router(ssl: bool) -> Router {
|
||||
Router::new()
|
||||
.route("/ws/{*path}", get(ws_handler))
|
||||
.nest("/api", api_router())
|
||||
.route("/{*path}", any(static_handler))
|
||||
.layer(ServiceBuilder::new())
|
||||
.with_state(ssl)
|
||||
}
|
||||
|
||||
async fn ws_handler(
|
||||
ws: WebSocketUpgrade,
|
||||
Path(path): Path<String>,
|
||||
ConnectInfo(addr): ConnectInfo<SocketAddr>,
|
||||
) -> impl IntoResponse {
|
||||
log_message(format!("WS connection from {}", addr));
|
||||
|
||||
ws.on_upgrade(move |socket| async move {
|
||||
handle_ws(socket, path).await;
|
||||
})
|
||||
}
|
||||
|
||||
async fn handle_ws(socket: WebSocket, path: String) {
|
||||
let (sender, receiver) = socket.split();
|
||||
handle(path, sender, receiver);
|
||||
}
|
||||
|
||||
async fn static_handler(Path(path): Path<String>) -> Response {
|
||||
let mut parts: Vec<&str> = path.split('/').filter(|s| !s.is_empty()).collect();
|
||||
let name = if parts.is_empty() {
|
||||
"index.html"
|
||||
} else {
|
||||
let last_part = parts.last().unwrap();
|
||||
if last_part.contains('.') {
|
||||
parts.pop().unwrap()
|
||||
} else {
|
||||
"index.html"
|
||||
}
|
||||
};
|
||||
|
||||
let path_prefix = parts.join("/");
|
||||
let content_result = load_file_vec(&format!("web/{}/", path_prefix), name);
|
||||
|
||||
match content_result {
|
||||
Ok(content) => {
|
||||
let mime = codec_for_ext(name);
|
||||
let mut headers = HeaderMap::new();
|
||||
headers.insert(axum::http::header::CONTENT_TYPE, mime.parse().unwrap());
|
||||
(StatusCode::OK, headers, content).into_response()
|
||||
}
|
||||
Err(_) => {
|
||||
let content_404 = load_file_vec("web", "404.html").unwrap_or_default();
|
||||
let mut headers = HeaderMap::new();
|
||||
headers.insert(
|
||||
axum::http::header::CONTENT_TYPE,
|
||||
"text/html; charset=utf-8".parse().unwrap(),
|
||||
);
|
||||
(StatusCode::NOT_FOUND, headers, content_404).into_response()
|
||||
}
|
||||
}
|
||||
async fn ws_handler(req: HttpRequest, stream: web::Payload) -> Result<impl Responder, Error> {
|
||||
let path = req.path().to_string();
|
||||
log_message(format!("WS connection from {:?}", req.peer_addr()));
|
||||
let session = WsSession::new(path);
|
||||
ws::start(session, &req, stream)
|
||||
}
|
||||
|
||||
pub async fn start(port: u16) -> bool {
|
||||
match load_tls_config() {
|
||||
Ok(Some(tls)) => run_tls_server(port, tls).await,
|
||||
Ok(_) => run_http_server(port).await,
|
||||
Err(e) => {
|
||||
log_message(format!("TLS config error: {}", e));
|
||||
false
|
||||
}
|
||||
}
|
||||
}
|
||||
let (tx, rx) = std::sync::mpsc::channel();
|
||||
|
||||
async fn run_http_server(port: u16) -> bool {
|
||||
let addr = SocketAddr::from(([0, 0, 0, 0], port));
|
||||
let router = build_router(false);
|
||||
let server_task = tokio::spawn(async move {
|
||||
let server = match load_tls_config() {
|
||||
Ok(Some(tls_config)) => {
|
||||
log_message(format!("HTTPS (HTTP/2) Server running on 0.0.0.0:{}", port));
|
||||
let _config = (*tls_config).clone();
|
||||
HttpServer::new(move || {
|
||||
App::new()
|
||||
.app_data(web::Data::new(true))
|
||||
.configure(api_config)
|
||||
.service(web::resource("/ws/{path:.*}").route(web::get().to(ws_handler)))
|
||||
.default_service(web::to(web_path_parser::handle))
|
||||
})
|
||||
.bind(("0.0.0.0", port))
|
||||
.unwrap()
|
||||
.run()
|
||||
}
|
||||
Ok(None) => {
|
||||
log_message(format!("HTTP Server running on 0.0.0.0:{}", port));
|
||||
HttpServer::new(move || {
|
||||
App::new()
|
||||
.app_data(web::Data::new(false))
|
||||
.configure(api_config)
|
||||
.service(web::resource("/ws/{path:.*}").route(web::get().to(ws_handler)))
|
||||
.default_service(web::to(web_path_parser::handle))
|
||||
})
|
||||
.bind(("0.0.0.0", port))
|
||||
.unwrap()
|
||||
.run()
|
||||
}
|
||||
Err(e) => {
|
||||
log_message(format!("TLS config error: {}", e));
|
||||
return;
|
||||
}
|
||||
};
|
||||
|
||||
log_message(format!("HTTP Server running on {}", addr));
|
||||
|
||||
ACTIVE_TASKS.lock().unwrap().push("WebServer".into());
|
||||
|
||||
tokio::spawn(async move {
|
||||
let listener = TcpListener::bind(addr).await.unwrap();
|
||||
|
||||
axum::serve(
|
||||
listener,
|
||||
router.into_make_service_with_connect_info::<SocketAddr>(),
|
||||
)
|
||||
.with_graceful_shutdown(wait_for_shutdown())
|
||||
.await
|
||||
.unwrap();
|
||||
let server_handle = server.handle();
|
||||
tx.send(server_handle).unwrap();
|
||||
|
||||
ACTIVE_TASKS.lock().unwrap().push("WebServer".into());
|
||||
server.await.unwrap();
|
||||
ACTIVE_TASKS.lock().unwrap().retain(|t| t != "WebServer");
|
||||
log_message("HTTP Server shutdown complete.");
|
||||
log_message("Web Server shutdown complete.");
|
||||
});
|
||||
|
||||
true
|
||||
}
|
||||
|
||||
async fn run_tls_server(port: u16, tls: Arc<ServerConfig>) -> bool {
|
||||
let addr = SocketAddr::from(([0, 0, 0, 0], port));
|
||||
let router = build_router(true);
|
||||
|
||||
let tls_config = RustlsConfig::from_config(tls);
|
||||
|
||||
log_message(format!("HTTPS (HTTP/2) Server running on {}", addr));
|
||||
|
||||
ACTIVE_TASKS.lock().unwrap().push("WebServer".into());
|
||||
let server_handle = rx.recv().unwrap();
|
||||
|
||||
tokio::spawn(async move {
|
||||
axum_server::bind_rustls(addr, tls_config)
|
||||
.serve(router.into_make_service_with_connect_info::<SocketAddr>())
|
||||
.await
|
||||
.unwrap();
|
||||
|
||||
ACTIVE_TASKS.lock().unwrap().retain(|t| t != "WebServer");
|
||||
log_message("HTTPS Server shutdown complete.");
|
||||
wait_for_shutdown(server_handle).await;
|
||||
});
|
||||
|
||||
true
|
||||
server_task.await.is_ok()
|
||||
}
|
||||
|
||||
async fn wait_for_shutdown() {
|
||||
async fn wait_for_shutdown(server_handle: ServerHandle) {
|
||||
loop {
|
||||
if *SHUTDOWN.read().await {
|
||||
log_message("Shutdown signal received.");
|
||||
server_handle.stop(true).await;
|
||||
break;
|
||||
}
|
||||
tokio::time::sleep(Duration::from_millis(100)).await;
|
||||
}
|
||||
}
|
||||
fn load_tls_config() -> Result<Option<Arc<ServerConfig>>, Box<dyn Error>> {
|
||||
|
||||
fn load_tls_config() -> Result<Option<Arc<ServerConfig>>, Box<dyn StdError>> {
|
||||
let cert_file_res = load_file_buf("certs", "cert.pem");
|
||||
let key_file_res = load_file_buf("certs", "cert.key");
|
||||
|
||||
|
|
@ -181,22 +114,21 @@ fn load_tls_config() -> Result<Option<Arc<ServerConfig>>, Box<dyn Error>> {
|
|||
Err(e) => return Err(e.into()), // Other IO error
|
||||
};
|
||||
|
||||
let mut cert_reader = BufReader::new(cert_file_buf);
|
||||
let cert_ders = rustls_pemfile::certs(&mut cert_reader)
|
||||
.collect::<Result<Vec<CertificateDer>, io::Error>>()?;
|
||||
let cert_chain = rustls_pemfile::certs(&mut BufReader::new(cert_file_buf))
|
||||
.collect::<Result<Vec<CertificateDer>, _>>()?;
|
||||
|
||||
// PKCS8
|
||||
let mut key_reader = BufReader::new(key_file_buf);
|
||||
let mut key_ders = rustls_pemfile::pkcs8_private_keys(&mut key_reader)
|
||||
.map(|r| r.map(Into::into)) // Explicit conversion
|
||||
.collect::<Result<Vec<PrivateKeyDer>, io::Error>>()?;
|
||||
.map(|r| r.map(Into::into))
|
||||
.collect::<Result<Vec<PrivateKeyDer>, _>>()?;
|
||||
|
||||
if key_ders.is_empty() {
|
||||
// RSA
|
||||
key_reader = BufReader::new(load_file_buf("certs", "cert.key")?); // Re-read key file
|
||||
key_ders = rustls_pemfile::rsa_private_keys(&mut key_reader)
|
||||
.map(|r| r.map(Into::into))
|
||||
.collect::<Result<Vec<PrivateKeyDer>, io::Error>>()?;
|
||||
.collect::<Result<Vec<PrivateKeyDer>, _>>()?;
|
||||
}
|
||||
|
||||
if key_ders.is_empty() {
|
||||
|
|
@ -204,20 +136,21 @@ fn load_tls_config() -> Result<Option<Arc<ServerConfig>>, Box<dyn Error>> {
|
|||
key_reader = BufReader::new(load_file_buf("certs", "cert.key")?); // Re-read key file
|
||||
key_ders = rustls_pemfile::ec_private_keys(&mut key_reader)
|
||||
.map(|r| r.map(Into::into))
|
||||
.collect::<Result<Vec<PrivateKeyDer>, io::Error>>()?;
|
||||
.collect::<Result<Vec<PrivateKeyDer>, _>>()?;
|
||||
}
|
||||
|
||||
if key_ders.is_empty() {
|
||||
return Err("No private keys found in key file. (Tried PKCS8, RSA, and EC)".into());
|
||||
}
|
||||
|
||||
let config = rustls::ServerConfig::builder()
|
||||
let config = ServerConfig::builder()
|
||||
.with_no_client_auth()
|
||||
.with_single_cert(cert_ders, key_ders.remove(0))
|
||||
.with_single_cert(cert_chain, key_ders.remove(0))
|
||||
.map_err(|e| io::Error::new(ErrorKind::Other, e.to_string()))?;
|
||||
|
||||
Ok(Some(Arc::new(config)))
|
||||
}
|
||||
|
||||
pub fn is_local_network(addr: IpAddr) -> bool {
|
||||
match addr {
|
||||
IpAddr::V4(v4) => {
|
||||
|
|
|
|||
|
|
@ -1,60 +1,97 @@
|
|||
use axum::extract::ws::{Message, WebSocket};
|
||||
use futures::stream::SplitSink;
|
||||
use futures::stream::SplitStream;
|
||||
use crate::{
|
||||
data::communication::{CommunicationType, CommunicationValue},
|
||||
gui::log_panel::log_message,
|
||||
};
|
||||
use actix::{Actor, ActorContext, AsyncContext, StreamHandler};
|
||||
use actix_web_actors::ws;
|
||||
use std::time::{Duration, Instant};
|
||||
|
||||
pub fn handle(
|
||||
_path: String,
|
||||
_writer: SplitSink<WebSocket, Message>,
|
||||
_reader: SplitStream<WebSocket>,
|
||||
) {
|
||||
tokio::spawn(async move {
|
||||
/*
|
||||
if path.starts_with("/ws/users/") {
|
||||
OmikronConnection::client(writer, reader).await;
|
||||
} else if path.starts_with("/ws/community/") {
|
||||
let community_id = path.split("/").nth(3).unwrap();
|
||||
log_message(format!("Community: {}", community_id));
|
||||
if let Some(community) = community_manager::get_community(community_id).await {
|
||||
log_message("Connected");
|
||||
let community_conn: Arc<CommunityConnection> =
|
||||
Arc::from(CommunityConnection::new(writer, reader, community));
|
||||
loop {
|
||||
if *SHUTDOWN.read().await {
|
||||
break;
|
||||
}
|
||||
let msg_result = {
|
||||
let mut session_lock = community_conn.receiver.write().await;
|
||||
session_lock.next().await
|
||||
};
|
||||
const IDLE_TIMEOUT: Duration = Duration::from_secs(30);
|
||||
|
||||
match msg_result {
|
||||
Some(Ok(msg)) => {
|
||||
if msg.is_text() {
|
||||
let text = msg.into_text().unwrap();
|
||||
community_conn
|
||||
.clone()
|
||||
.handle_message(text.to_string())
|
||||
.await;
|
||||
} else if msg.is_close() {
|
||||
log_message(format!("Closing: {}", msg));
|
||||
community_conn.handle_close().await;
|
||||
return;
|
||||
}
|
||||
}
|
||||
Some(Err(e)) => {
|
||||
log_message(format!("Closing ERR: {}", e));
|
||||
community_conn.handle_close().await;
|
||||
return;
|
||||
}
|
||||
None => {
|
||||
log_message("Closed Session me!");
|
||||
community_conn.handle_close().await;
|
||||
return;
|
||||
}
|
||||
}
|
||||
}
|
||||
use actix::Message;
|
||||
|
||||
#[derive(Message)]
|
||||
#[rtype(result = "()")]
|
||||
pub struct WsSendMessage(pub String);
|
||||
|
||||
impl actix::Handler<WsSendMessage> for WsSession {
|
||||
type Result = ();
|
||||
|
||||
fn handle(&mut self, msg: WsSendMessage, ctx: &mut Self::Context) {
|
||||
ctx.text(msg.0);
|
||||
}
|
||||
}
|
||||
|
||||
pub struct WsSession {
|
||||
path: String,
|
||||
last_heartbeat: Instant,
|
||||
}
|
||||
|
||||
impl WsSession {
|
||||
pub fn new(path: String) -> Self {
|
||||
Self {
|
||||
path,
|
||||
last_heartbeat: Instant::now(),
|
||||
}
|
||||
}
|
||||
fn start_heartbeat(&self, ctx: &mut ws::WebsocketContext<Self>) {
|
||||
ctx.run_interval(Duration::from_secs(5), |act, ctx| {
|
||||
if Instant::now().duration_since(act.last_heartbeat) > IDLE_TIMEOUT {
|
||||
ctx.close(None);
|
||||
ctx.stop();
|
||||
return;
|
||||
}
|
||||
|
||||
let ping = CommunicationValue::new(CommunicationType::ping)
|
||||
.to_json()
|
||||
.to_string();
|
||||
|
||||
ctx.text(ping);
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
impl Actor for WsSession {
|
||||
type Context = ws::WebsocketContext<Self>;
|
||||
|
||||
fn started(&mut self, ctx: &mut Self::Context) {
|
||||
self.start_heartbeat(ctx);
|
||||
|
||||
log_message(format!("WebSocket session started for path: {}", self.path));
|
||||
|
||||
if self.path.starts_with("/ws/users/") {
|
||||
log_message(format!("UserConnection handling is not yet implemented.",));
|
||||
} else if self.path.starts_with("/ws/community/") {
|
||||
let community_id = self.path.split('/').nth(3).unwrap_or_default();
|
||||
log_message(format!(
|
||||
"CommunityConnection handling for {} is not yet implemented.",
|
||||
community_id
|
||||
));
|
||||
}
|
||||
}
|
||||
|
||||
fn stopped(&mut self, _ctx: &mut Self::Context) {
|
||||
log_message(format!("WebSocket session stopped for path: {}", self.path));
|
||||
}
|
||||
}
|
||||
|
||||
impl StreamHandler<Result<ws::Message, ws::ProtocolError>> for WsSession {
|
||||
fn handle(&mut self, msg: Result<ws::Message, ws::ProtocolError>, ctx: &mut Self::Context) {
|
||||
match msg {
|
||||
Ok(ws::Message::Ping(msg)) => {
|
||||
self.last_heartbeat = Instant::now();
|
||||
ctx.pong(&msg);
|
||||
}
|
||||
Ok(ws::Message::Pong(_)) => self.last_heartbeat = Instant::now(),
|
||||
Ok(ws::Message::Text(_)) => self.last_heartbeat = Instant::now(),
|
||||
Ok(ws::Message::Close(reason)) => {
|
||||
ctx.close(reason);
|
||||
ctx.stop();
|
||||
}
|
||||
Err(_) => {
|
||||
ctx.stop();
|
||||
}
|
||||
_ => ctx.stop(),
|
||||
}
|
||||
*/
|
||||
});
|
||||
}
|
||||
}
|
||||
|
|
|
|||
116
src/server/web_path_parser.rs
Normal file → Executable file
116
src/server/web_path_parser.rs
Normal file → Executable file
|
|
@ -1,14 +1,10 @@
|
|||
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 actix_web::{HttpRequest, HttpResponse, web};
|
||||
use json::JsonValue;
|
||||
use std::path::{Path, PathBuf};
|
||||
|
||||
use crate::util::file_util::load_file_vec;
|
||||
|
||||
pub fn codec_for_ext(ext: &str) -> &'static str {
|
||||
fn codec_for_ext(ext: &str) -> &'static str {
|
||||
match ext {
|
||||
"html" => "text/html; charset=utf-8",
|
||||
"css" => "text/css",
|
||||
|
|
@ -21,81 +17,77 @@ pub fn codec_for_ext(ext: &str) -> &'static str {
|
|||
}
|
||||
}
|
||||
|
||||
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
|
||||
}
|
||||
pub async fn handle(req: HttpRequest, body: web::Bytes) -> HttpResponse {
|
||||
// Optional JSON parsing
|
||||
let _body_json: Option<JsonValue> = if !body.is_empty() {
|
||||
json::parse(std::str::from_utf8(&body).unwrap_or("")).ok()
|
||||
} else {
|
||||
None
|
||||
};
|
||||
|
||||
let req_path = path.trim_start_matches('/');
|
||||
let req_path = req.path().trim_start_matches('/');
|
||||
|
||||
// 1️⃣ Resolve the filesystem path
|
||||
let mut fs_path = PathBuf::from("web");
|
||||
|
||||
// Boolean P: no path provided → redirect to index.html
|
||||
if req_path.is_empty() {
|
||||
fs_path.push("index.html");
|
||||
} else {
|
||||
fs_path.extend(req_path.split('/'));
|
||||
}
|
||||
|
||||
// Boolean D: path is directory → serve index.html inside
|
||||
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
|
||||
// Boolean E: extension provided
|
||||
let ext_opt = fs_path.extension().and_then(|e| e.to_str());
|
||||
let mut final_name = fs_path
|
||||
.file_name()
|
||||
.and_then(|n| n.to_str())
|
||||
.unwrap_or("index.html");
|
||||
.unwrap_or("")
|
||||
.to_string();
|
||||
|
||||
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
|
||||
}
|
||||
if ext_opt.is_none() {
|
||||
// No extension provided → try HTML
|
||||
if final_name.is_empty() {
|
||||
final_name = "index.html".to_string();
|
||||
} else {
|
||||
include_str!("../../static/web/404.html")
|
||||
.as_bytes()
|
||||
.to_vec()
|
||||
};
|
||||
final_name.push_str(".html");
|
||||
}
|
||||
}
|
||||
|
||||
HttpResponse::builder()
|
||||
.status(StatusCode::NOT_FOUND)
|
||||
.header("content-type", "text/html; charset=utf-8")
|
||||
.body(Full::new(Bytes::from(body)))
|
||||
.unwrap()
|
||||
let content_type = codec_for_ext(
|
||||
fs_path
|
||||
.extension()
|
||||
.and_then(|e| e.to_str())
|
||||
.unwrap_or("html"),
|
||||
);
|
||||
|
||||
let dir = fs_path.parent().unwrap_or(Path::new("web"));
|
||||
|
||||
// 2️⃣ Try to load the resolved file
|
||||
match load_file_vec(dir.to_str().unwrap_or("web"), &final_name) {
|
||||
Ok(content) => HttpResponse::Ok().content_type(content_type).body(content),
|
||||
|
||||
Err(_) => {
|
||||
// For static assets, return plain 404
|
||||
let ext = fs_path.extension().and_then(|e| e.to_str()).unwrap_or("");
|
||||
if matches!(ext, "js" | "css" | "woff2") {
|
||||
return HttpResponse::NotFound()
|
||||
.content_type("text/plain")
|
||||
.body("Not found");
|
||||
}
|
||||
|
||||
// 3️⃣ Try to serve 404.html from web folder
|
||||
let fallback = load_file_vec("web", "404.html")
|
||||
.unwrap_or_else(|_| include_bytes!("../../static/web/404.html").to_vec());
|
||||
|
||||
HttpResponse::NotFound()
|
||||
.content_type("text/html; charset=utf-8")
|
||||
.body(fallback)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
|
|||
Loading…
Reference in a new issue