summaryrefslogtreecommitdiff
path: root/src/ui/assets.rs
blob: 0ca95933beff8335448be2fe038f509bfa200b85 (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
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
use ::mime::{FromStrError, Mime};
use axum::{
    http::{StatusCode, header},
    response::{IntoResponse, Response},
};
use rust_embed::EmbeddedFile;

use super::{error::NotFound, mime};
use crate::error::Internal;

#[derive(rust_embed::Embed)]
#[folder = "$OUT_DIR/ui"]
pub struct Assets;

impl Assets {
    pub fn load(path: impl AsRef<str>) -> Result<Asset, Error> {
        let path = path.as_ref();
        let mime = mime::from_path(path)?;

        Self::get(path)
            .map(|file| Asset(mime, file))
            .ok_or(Error::NotFound(path.into()))
    }

    pub fn index() -> Result<Asset, Internal> {
        // "not found" in this case really is an internal error, as it should
        // never happen. `index.html` is a known-valid path with a known-valid
        // file extension.
        Ok(Self::load("index.html")?)
    }
}

pub struct Asset(Mime, EmbeddedFile);

impl IntoResponse for Asset {
    fn into_response(self) -> Response {
        let Self(mime, file) = self;
        (
            StatusCode::OK,
            [(header::CONTENT_TYPE, mime.as_ref())],
            file.data,
        )
            .into_response()
    }
}

#[derive(Debug, thiserror::Error)]
pub enum Error {
    #[error("not found: {0}")]
    NotFound(String),
    #[error(transparent)]
    Mime(#[from] FromStrError),
}

impl IntoResponse for Error {
    fn into_response(self) -> Response {
        match self {
            Self::NotFound(_) => NotFound(self.to_string()).into_response(),
            Self::Mime(_) => Internal::from(self).into_response(),
        }
    }
}