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
|
use std::time::Duration;
use actix_slog::StructuredLogger;
use actix_web::{get, post, web, App, HttpServer, Responder};
use askama_actix::{Template, TemplateIntoResponse};
use serde::{Deserialize, Serialize};
use slog::Logger;
use xtra::WeakAddress;
use crate::bot::MasterBot;
use crate::youtube_dl::AudioMetadata;
mod api;
mod bot_data;
mod default;
mod front_end_cookie;
mod tmtu;
pub use bot_data::*;
use front_end_cookie::FrontEnd;
pub struct WebServerArgs {
pub domain: String,
pub bind_address: String,
pub bot: WeakAddress<MasterBot>,
}
#[actix_rt::main]
pub async fn start(args: WebServerArgs, logger: Logger) -> std::io::Result<()> {
let bot = args.bot;
let bind_address = args.bind_address;
HttpServer::new(move || {
App::new()
.data(bot.clone())
.wrap(StructuredLogger::new(logger.clone()))
.service(index)
.service(get_bot)
.service(post_front_end)
.service(
web::scope("/api")
.service(api::get_bot_list)
.service(api::get_bot),
)
.service(web::scope("/docs").service(get_api_docs))
.service(actix_files::Files::new("/static", "web_server/static/"))
})
.bind(bind_address)?
.run()
.await?;
Ok(())
}
#[derive(Deserialize)]
#[serde(rename_all = "kebab-case")]
struct FrontEndForm {
front_end: FrontEnd,
}
#[post("/front-end")]
async fn post_front_end(form: web::Form<FrontEndForm>) -> impl Responder {
front_end_cookie::set_front_end(form.into_inner().front_end).await
}
#[derive(Debug, Serialize)]
pub struct BotData {
pub name: String,
pub state: crate::bot::State,
pub volume: f64,
pub position: Option<Duration>,
pub currently_playing: Option<AudioMetadata>,
pub playlist: Vec<AudioMetadata>,
}
#[get("/")]
async fn index(bot: web::Data<WeakAddress<MasterBot>>, front: FrontEnd) -> impl Responder {
match front {
FrontEnd::Default => default::index(bot).await,
FrontEnd::Tmtu => tmtu::index(bot).await,
}
}
#[get("/bot/{name}")]
async fn get_bot(
bot: web::Data<WeakAddress<MasterBot>>,
name: web::Path<String>,
front: FrontEnd,
) -> impl Responder {
match front {
FrontEnd::Default => default::get_bot(bot, name.into_inner()).await,
FrontEnd::Tmtu => tmtu::get_bot(bot, name.into_inner()).await,
}
}
#[derive(Template)]
#[template(path = "docs/api.htm")]
struct ApiDocsTemplate;
#[get("/api")]
async fn get_api_docs() -> impl Responder {
ApiDocsTemplate.into_response()
}
mod filters {
use std::time::Duration;
pub fn fmt_duration(duration: &Option<Duration>) -> Result<String, askama::Error> {
if let Some(duration) = duration {
let secs = duration.as_secs();
let mins = secs / 60;
let submin_secs = secs % 60;
Ok(format!("{:02}:{:02}", mins, submin_secs))
} else {
Ok(String::from("--:--"))
}
}
}
|