summaryrefslogtreecommitdiff
path: root/src/public/mod.rs
blob: cf8156de3a3dae0ec0ece78a74fefd00a26b6c40 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
use axum::{
    body::Body,
    http::{Request, StatusCode},
    response::{IntoResponse, Response},
    routing::get,
    Router,
};
use tower::ServiceExt;
use tower_http::services::ServeFile;

use crate::types::http::ResponseCode;

pub mod admin;
pub mod console;
pub mod file;
pub mod pages;

pub fn router() -> Router {
    Router::new()
        .nest("/", pages::router())
        .route("/js/*path", get(file::js))
        .route("/css/*path", get(file::css))
        .route("/fonts/*path", get(file::fonts))
        .route("/image/*path", get(file::image))
        .route("/image/avatar", get(file::avatar))
        .route("/image/banner", get(file::banner))
}

pub async fn serve(path: &str) -> Response {
    if !path.chars().any(|c| c == '.') {
        return ResponseCode::BadRequest.text("Invalid file path");
    }

    let path = format!("public{path}");
    let file = ServeFile::new(path);

    let Ok(res) = file.oneshot(Request::new(Body::empty())).await else {
        tracing::error!("Error while fetching file");
        return ResponseCode::InternalServerError.text("Error while fetching file");
    };

    if res.status() != StatusCode::OK {
        return ResponseCode::NotFound.text("File not found");
    }

    res.into_response()
}