-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathhandlers.rs
188 lines (173 loc) · 5.05 KB
/
handlers.rs
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
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
use crate::AppState;
use actix::Addr;
use actix_files::NamedFile;
use actix_web::{
cookie, get, http, post, web, HttpMessage, HttpRequest, HttpResponse, Responder, Result,
};
use rand::{distributions::Bernoulli, rngs::ThreadRng};
use rand_distr::Distribution;
use std::path::PathBuf;
use uuid::Uuid;
pub struct ApplicationState {
pub rng: ThreadRng,
pub addr: Addr<AppState>,
probabilities: Vec<Bernoulli>,
}
impl ApplicationState {
pub fn new(rng: ThreadRng, addr: Addr<AppState>, probabilities: Vec<f64>) -> Self {
ApplicationState {
rng,
addr,
probabilities: probabilities
.iter()
.map(|p| Bernoulli::new(*p).unwrap())
.collect::<Vec<Bernoulli>>(),
}
}
pub fn get_bernoulli(&self, i: usize) -> Bernoulli {
*self
.probabilities
.get(i)
.unwrap_or(&Bernoulli::new(0.0).unwrap())
}
}
/// Set a cookie for 2 hours involving a uuid and the chosen name.
/// Will overwrite any existing cookie.
/// No redirecting
#[get("/cookie/{id}")]
pub async fn set_cookie(path: web::Path<String>) -> HttpResponse {
let cookie = (cookie::Cookie::build("id", Uuid::new_v4().to_string() + "_" + path.as_str()))
.max_age(time::Duration::hours(2))
.path("/")
.same_site(cookie::SameSite::Strict)
.finish();
let rep = HttpResponse::build(http::StatusCode::OK)
.cookie(cookie)
.content_type("plain/text")
.body("Set Cookie");
rep
}
/// Redirects to the game page.
#[get("/redirect")]
pub async fn redirect() -> HttpResponse {
HttpResponse::build(http::StatusCode::FOUND)
.header(http::header::LOCATION, "/game/".to_string())
.finish()
}
/// Handling for game page
pub async fn game_html() -> Result<NamedFile> {
Ok(NamedFile::open("../game/index.html")?)
}
/// Handling for static game path files
#[get("/game/pkg/{filename}.{ext}")]
pub async fn game_files(path: web::Path<(String, String)>) -> Result<NamedFile> {
let (filename, ext) = path.into_inner();
Ok(NamedFile::open(
("../game/pkg/".to_string() + &filename + "." + &ext)
.parse::<PathBuf>()
.unwrap(),
)?)
}
/// Handling for game styling
#[get("/game/style/styles.css")]
pub async fn game_style() -> Result<NamedFile> {
Ok(NamedFile::open(
"../game/style/styles.css"
.to_string()
.parse::<PathBuf>()
.unwrap(),
)?)
}
/// Handling for game styling
#[get("/game/audio/{file}.mp3")]
pub async fn game_audio(path: web::Path<String>) -> Result<NamedFile> {
let filename = path.into_inner();
Ok(NamedFile::open(
("../game/audio/".to_string() + &filename + ".mp3")
.parse::<PathBuf>()
.unwrap(),
)?)
}
#[get("/")]
pub async fn index() -> Result<NamedFile> {
Ok(NamedFile::open("../login/index.html")?)
}
/// Handling for game styling
#[get("/pkg/{filename}.{ext}")]
pub async fn index_files(path: web::Path<(String, String)>) -> Result<NamedFile> {
let (filename, ext) = path.into_inner();
Ok(NamedFile::open(
("../login/pkg/".to_string() + &filename + "." + &ext)
.parse::<PathBuf>()
.unwrap(),
)?)
}
/// Handling for game styling
#[get("/style/styles.css")]
pub async fn index_style() -> Result<NamedFile> {
Ok(NamedFile::open(
"../login/style/styles.css"
.to_string()
.parse::<PathBuf>()
.unwrap(),
)?)
}
/// Flip a coin using the thread rng handle. Send the result to application
#[get("/flip/{coin}")]
pub async fn flip(req: HttpRequest) -> impl Responder {
use crate::app::CoinFlipped;
let coin = req
.match_info()
.get("coin")
.map(|s| s.parse::<usize>().ok())
.flatten()
.unwrap_or(0); // if invalid, number defaults to first coin
let app_data = req.app_data::<web::Data<ApplicationState>>().unwrap();
let mut rng = app_data.rng.clone();
let addr = &app_data.addr;
let result: bool = app_data.get_bernoulli(coin).sample(&mut rng);
if let Some(user_id) = req.cookie("id") {
addr.do_send(CoinFlipped {
user_id: user_id.value().to_string(),
arm: coin,
result,
});
HttpResponse::build(http::StatusCode::OK)
.content_type("plain/text")
.body(format!("{}", result))
} else {
return HttpResponse::build(http::StatusCode::UNAUTHORIZED).finish();
}
}
/// Getting information for user to update their view
#[get("/count")]
pub async fn count(req: HttpRequest) -> impl Responder {
use crate::app::GetCount;
let id = req.cookie("id").unwrap().value().to_string();
let app_data = req.app_data::<web::Data<ApplicationState>>().unwrap();
let addr = &app_data.addr;
let count = addr
.send(GetCount { id: id.clone() })
.await
.expect("Failed to get count");
HttpResponse::build(http::StatusCode::OK)
.content_type("plain/text")
.body(format!("{}\n{}", count, id))
}
/// Send a message to the application to flush state into dump.json
#[post("/flush")]
pub async fn flush(req: HttpRequest) -> impl Responder {
use crate::app::Flush;
let app_data = req.app_data::<web::Data<ApplicationState>>().unwrap();
let addr = &app_data.addr;
addr.do_send(Flush {});
HttpResponse::Ok()
.content_type("plain/text")
.body("Sent Application message to flush")
}
/// instead of 404 page, redirects to root
pub async fn not_found() -> HttpResponse {
HttpResponse::build(http::StatusCode::FOUND)
.header(http::header::LOCATION, "/".to_string())
.finish()
}