aboutsummaryrefslogtreecommitdiffstats
path: root/src/ui.rs
blob: 914d28932d073f3f24e96bcf8d5516831d74f284 (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
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
use std::net::SocketAddr;
use anyhow::{anyhow, Context};
use askama::Template;
use axum::{
    Form,
    Json,
    Router,
    extract::State,
    extract::{ws::{Message, WebSocket, WebSocketUpgrade}, ConnectInfo},
    http::StatusCode,
    response::IntoResponse,
    routing::{get, post},
};
use serde::Deserialize;

use log::{debug, info, warn, error};
use tower_http::services::ServeDir;

use crate::config;
use crate::SharedState;

pub async fn serve(port: u16, shared_state: SharedState) {
    let app = Router::new()
        .route("/", get(dashboard))
        .route("/settings", get(show_settings))
        .route("/api/settings", post(post_settings))
        .nest_service("/static", ServeDir::new("static"))
        /* For an example for timeouts and tracing, have a look at the git history */
        .with_state(shared_state);

    let listener = tokio::net::TcpListener::bind(("0.0.0.0", port)).await.unwrap();
    axum::serve(listener,
        app.into_make_service_with_connect_info::<SocketAddr>())
        .await.unwrap()
}

#[derive(PartialEq)]
enum ActivePage {
    Dashboard,
    Settings,
    None,
}

impl ActivePage {
    // Used by templates/head.html to include the correct js files in <head>
    fn styles(&self) -> Vec<&'static str> {
        match self {
            ActivePage::Dashboard => vec![],
            ActivePage::Settings => vec!["settings.js", "main.js"],
            ActivePage::None => vec![],
        }
    }
}

#[derive(Template)]
#[template(path = "dashboard.html")]
struct DashboardTemplate<'a> {
    title: &'a str,
    page: ActivePage,
    conf: config::Config,
}

async fn dashboard(State(state): State<SharedState>) -> DashboardTemplate<'static> {
    let conf = {
        let st = state.lock().unwrap();
        st.conf.clone()
    };

    DashboardTemplate {
        title: "Dashboard",
        conf,
        page: ActivePage::Dashboard,
    }
}

#[derive(Template)]
#[template(path = "settings.html")]
struct SettingsTemplate<'a> {
    title: &'a str,
    page: ActivePage,
    conf: config::Config,
}

async fn show_settings(State(state): State<SharedState>) -> SettingsTemplate<'static> {
    SettingsTemplate {
        title: "Settings",
        page: ActivePage::Settings,
        conf: state.lock().unwrap().conf.clone(),
    }
}

#[derive(Template)]
#[template(path = "settings_applied.html")]
struct SettingsAppliedTemplate<'a> {
    title: &'a str,
    page: ActivePage,
    conf: config::Config,
    ok: bool,
    error_message: &'a str,
    error_reason: String,
}

async fn post_settings(
    State(state): State<SharedState>,
    Json(conf): Json<config::Config>) -> (StatusCode, SettingsAppliedTemplate<'static>) {

    match conf.store() {
        Ok(()) => {
            state.lock().unwrap().conf.clone_from(&conf);

            (StatusCode::OK, SettingsAppliedTemplate {
                title: "Settings",
                conf,
                page: ActivePage::None,
                ok: true,
                error_message: "",
                error_reason: "".to_owned(),
            })
        }
        Err(e) => {
            (StatusCode::INTERNAL_SERVER_ERROR, SettingsAppliedTemplate {
                title: "Settings",
                conf,
                page: ActivePage::None,
                ok: false,
                error_message: "Failed to store config",
                error_reason: e.to_string(),
            })
        },
    }
}