aboutsummaryrefslogtreecommitdiffstats
path: root/src/ui.rs
blob: 6bcb04df8c9dd508b87eb1ddae8046335f6214be (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
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
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))
        .route("/api/set_rc", post(post_rc))
        .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!["dashboard.js", "main.js"],
            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,
    errors: Option<String>,
    params: Vec<crate::dabmux::Param>,
}

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

        let params_result = st.dabmux.get_rc_parameters();

        (st.conf.clone(), params_result)
    };

    let (params, errors) = match params_result {
        Ok(v) => {
            (v, None)
        },
        Err(e) => {
            (Vec::new(), Some(format!("{}", e)))
        },
    };

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

#[derive(Deserialize)]
struct SetRc {
    pub module : String,
    pub param : String,
    pub value : String,
}

async fn post_rc(
    State(state): State<SharedState>,
    Json(set_rc): Json<SetRc>) -> (StatusCode, Json<serde_json::Value>) {

    let set_rc_result = {
        let mut st = state.lock().unwrap();
        st.dabmux.set_rc_parameter(&set_rc.module, &set_rc.param, &set_rc.value)
    };

    match set_rc_result {
        Ok(v) => (StatusCode::OK, Json(v)),
        Err(e) => {
            let e_str = serde_json::Value::String(e.to_string());
            (StatusCode::BAD_REQUEST, Json(e_str))
        },
    }
}

#[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(),
            })
        },
    }
}