use std::net::IpAddr;
use bytes::Bytes;
use http_body_util::Full;
use hyper::body::Incoming;
use hyper::{Method, Request, Response, StatusCode};
use crate::server::dufs::{full_to_box_body, handle_dufs_request, ServerResponseBody};
use crate::server::handlers::{
empty_response, handle_cancel, handle_download, handle_info, handle_prepare_download,
handle_prepare_upload, handle_register, handle_upload, handle_web_portal, ServerState,
};
#[derive(Clone, Debug)]
pub struct ClientConnectionInfo {
pub remote_ip: IpAddr,
pub cert_fingerprint: Option<String>,
}
fn to_box_body(res: Response<Full<Bytes>>) -> Response<ServerResponseBody> {
res.map(full_to_box_body)
}
pub async fn route_request(
req: Request<Incoming>,
client: ClientConnectionInfo,
state: &ServerState,
) -> Result<Response<ServerResponseBody>, hyper::Error> {
let method = req.method();
let path = req.uri().path();
if let Some(dufs_cfg) = state.dufs_manager.get_config().await {
let is_dufs_explicit = path == "/dufs" || path.starts_with("/dufs/");
let is_localsend_api = path.starts_with("/api/localsend/");
let is_download_endpoint = path == "/download" || path == "/api/localsend/v2/download";
if is_dufs_explicit || (!is_localsend_api && !is_download_endpoint) {
let mut cfg = dufs_cfg;
if is_dufs_explicit {
cfg.path_prefix = "/dufs".to_string();
} else {
cfg.path_prefix = String::new();
}
return handle_dufs_request(req, client.remote_ip, &cfg).await;
}
}
let response = match (method, path) {
(&Method::GET, "/") | (&Method::GET, "/index.html") => {
to_box_body(handle_web_portal(&req, state).await)
}
(&Method::GET, "/api/localsend/v2/info") | (&Method::GET, "/api/localsend/v1/info") => {
to_box_body(handle_info(client.remote_ip, state).await)
}
(&Method::POST, "/api/localsend/v2/register") => {
to_box_body(handle_register(req, client.remote_ip, client.cert_fingerprint, state).await)
}
(&Method::POST, "/api/localsend/v2/prepare-upload") => {
to_box_body(handle_prepare_upload(req, client.remote_ip, client.cert_fingerprint, state).await)
}
(&Method::POST, "/api/localsend/v2/upload") => {
to_box_body(handle_upload(req, client.remote_ip, state).await)
}
(&Method::POST, "/api/localsend/v2/prepare-download") => {
to_box_body(handle_prepare_download(req, client.remote_ip, state).await)
}
(&Method::GET, "/api/localsend/v2/download") | (&Method::GET, "/download") => {
to_box_body(handle_download(req, client.remote_ip, state).await)
}
(&Method::POST, "/api/localsend/v2/cancel") => {
to_box_body(handle_cancel(req, client.remote_ip, state).await)
}
_ => to_box_body(empty_response(StatusCode::NOT_FOUND)),
};
Ok(response)
}