summaryrefslogtreecommitdiff
path: root/src/index/routes.rs
blob: 37f6dc985a461b485bbe3a95610961d50c9d488c (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
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
use axum::{
    extract::{Path, State},
    http::{header, StatusCode},
    response::{IntoResponse, Response},
    routing::get,
    Router,
};
use maud::Markup;

use super::{app, templates};
use crate::{
    app::App,
    error::InternalError,
    repo::{channel, login::Login},
};

async fn index(State(app): State<App>, login: Option<Login>) -> Result<Markup, InternalError> {
    match login {
        None => Ok(templates::unauthenticated()),
        Some(login) => index_authenticated(app, login).await,
    }
}

async fn index_authenticated(app: App, login: Login) -> Result<Markup, InternalError> {
    let channels = app.channels().all().await?;

    Ok(templates::authenticated(login, &channels))
}

#[derive(rust_embed::Embed)]
#[folder = "js"]
struct Js;

async fn js(Path(path): Path<String>) -> impl IntoResponse {
    let mime = mime_guess::from_path(&path).first_or_octet_stream();

    match Js::get(&path) {
        Some(file) => (
            StatusCode::OK,
            [(header::CONTENT_TYPE, mime.as_ref())],
            file.data,
        )
            .into_response(),
        None => (StatusCode::NOT_FOUND, "").into_response(),
    }
}

async fn channel(
    State(app): State<App>,
    _: Login,
    Path(channel): Path<channel::Id>,
) -> Result<Markup, ChannelError> {
    let channel = app
        .index()
        .channel(&channel)
        .await
        // impl From would work here, but it'd take more code.
        .map_err(ChannelError)?;
    Ok(templates::channel(&channel))
}

#[derive(Debug)]
struct ChannelError(app::Error);

impl IntoResponse for ChannelError {
    fn into_response(self) -> Response {
        let Self(error) = self;
        match error {
            not_found @ app::Error::ChannelNotFound(_) => {
                (StatusCode::NOT_FOUND, not_found.to_string()).into_response()
            }
            app::Error::DatabaseError(error) => InternalError::from(error).into_response(),
        }
    }
}

pub fn router() -> Router<App> {
    Router::new()
        .route("/", get(index))
        .route("/js/*path", get(js))
        .route("/:channel", get(channel))
}