Vote + Results done
This commit is contained in:
235
src/main.rs
Normal file
235
src/main.rs
Normal file
@@ -0,0 +1,235 @@
|
||||
extern crate core;
|
||||
|
||||
use bytes::Bytes;
|
||||
use bytes::Buf;
|
||||
use chrono::{DateTime, Utc};
|
||||
use dotenvy::dotenv;
|
||||
use futures;
|
||||
use http_body_util::{BodyExt, Full};
|
||||
use hyper::body::Incoming;
|
||||
use hyper::server::conn::http1;
|
||||
use hyper::service::service_fn;
|
||||
use hyper::{Error, Method, Request, Response, StatusCode};
|
||||
use hyper_util::rt::{TokioIo, TokioTimer};
|
||||
use serde::{Deserialize, Serialize};
|
||||
use serde_json::{from_reader, Value};
|
||||
use sqlx::sqlite::SqlitePool;
|
||||
use std::collections::HashMap;
|
||||
use std::env;
|
||||
use std::env::vars;
|
||||
use std::fs::File;
|
||||
use std::io::Read;
|
||||
use std::net::SocketAddr;
|
||||
use std::str::FromStr;
|
||||
use std::sync::{Arc, Mutex};
|
||||
use std::time::SystemTime;
|
||||
use tokio::net::TcpListener;
|
||||
|
||||
#[derive(Serialize, Deserialize)]
|
||||
struct Player {
|
||||
id: i64,
|
||||
name: String,
|
||||
}
|
||||
|
||||
#[derive(Serialize, Deserialize, Debug)]
|
||||
struct Vote {
|
||||
vote_plus_id: i64,
|
||||
vote_plus_nickname: String,
|
||||
vote_plus_reason: String,
|
||||
vote_moins_id: i64,
|
||||
vote_moins_nickname: String,
|
||||
vote_moins_reason: String,
|
||||
}
|
||||
async fn service(req: Request<Incoming>, db: Arc<Mutex<SqlitePool>>) -> Result<Response<Full<Bytes>>, Error> {
|
||||
match req.method() {
|
||||
&Method::GET => { get(req,db).await }
|
||||
&Method::POST => {
|
||||
post(req, db).await
|
||||
}
|
||||
_ => { Ok(Response::new(Full::new(Bytes::from("This method is unimplemented")))) }
|
||||
}
|
||||
}
|
||||
|
||||
async fn get(req: Request<Incoming>, db: Arc<Mutex<SqlitePool>>) -> Result<Response<Full<Bytes>>, Error> {
|
||||
let path = req.uri().path();
|
||||
if path.starts_with("/static/") {
|
||||
get_file(path).await
|
||||
} else if path.starts_with("/data/") {
|
||||
get_data(path, &req, db).await
|
||||
} else {
|
||||
get_page(path).await
|
||||
}
|
||||
}
|
||||
|
||||
async fn get_page(path: &str) -> Result<Response<Full<Bytes>>, Error> {
|
||||
let uri_map_path = find_in_vars("ROUTES_FILE");
|
||||
let file = File::open(uri_map_path).expect("Could not find routes");
|
||||
let map: Value = from_reader(file).expect("Could not read data");
|
||||
match &map[path] {
|
||||
Value::String(s) => get_file(s.as_str()).await,
|
||||
_ => not_found().await
|
||||
}
|
||||
}
|
||||
|
||||
async fn get_file(path: &str) -> Result<Response<Full<Bytes>>, Error> {
|
||||
let current_dir = env::current_dir().unwrap().clone();
|
||||
let mut path = path;
|
||||
if path.starts_with(r"/") {
|
||||
path = path.strip_prefix(r"/").unwrap();
|
||||
}
|
||||
let file_path = current_dir.join(path);
|
||||
|
||||
match File::open(&file_path) {
|
||||
Ok(mut file) => {
|
||||
let mut buf = Vec::new();
|
||||
file.read_to_end(&mut buf).unwrap();
|
||||
let header = match file_path.extension().unwrap().to_str().unwrap() {
|
||||
"js" => "text/javascript",
|
||||
"html" => "text/html",
|
||||
"css" => "text/css",
|
||||
_ => ""
|
||||
};
|
||||
Ok(Response::builder().header("content-type", header).body(Full::new(Bytes::from(buf))).unwrap())
|
||||
}
|
||||
Err(_) => not_found().await
|
||||
}
|
||||
}
|
||||
|
||||
async fn get_data(path: &str, req: &Request<Incoming>, db: Arc<Mutex<SqlitePool>>) -> Result<Response<Full<Bytes>>, Error> {
|
||||
let pool = db.clone().lock().unwrap().clone();
|
||||
match path {
|
||||
"/data/players" => {
|
||||
let items = sqlx::query!(r#"SELECT id, name FROM players"#).fetch_all(&pool).await.unwrap();
|
||||
let players: Vec<Player> = items.iter().map(|x| Player { id: x.id, name: x.name.clone() }).collect();
|
||||
Ok(Response::new(Full::new(Bytes::from(serde_json::to_string(&players).unwrap()))))
|
||||
}
|
||||
"/data/votes" => {
|
||||
let votes = get_votes(req, db).await;
|
||||
Ok(Response::new(Full::new(Bytes::from(serde_json::to_string(&votes).unwrap()))))
|
||||
}
|
||||
"/data/results" => {
|
||||
let votes = get_votes(req, db).await;
|
||||
let ids: Vec<[i64; 2]> = votes.iter().map(|x| [x.vote_plus_id, x.vote_moins_id]).collect();
|
||||
let mut results: Vec<HashMap<i64, i64>> = Vec::new();
|
||||
for i in 0..=1 {
|
||||
let mut counts = HashMap::new();
|
||||
ids.iter().for_each(|x| {
|
||||
if counts.get(&x[i]).is_none() {
|
||||
counts.insert(x[i], 0);
|
||||
}
|
||||
*counts.get_mut(&x[i]).unwrap() += 1;
|
||||
});
|
||||
results.push(counts);
|
||||
}
|
||||
|
||||
let mut sorted: Vec<Vec<(i64, i64)>> = results.into_iter().map(|hashmap| hashmap.into_iter().collect::<Vec<(i64, i64)>>()).collect();
|
||||
|
||||
sorted.iter_mut().for_each(|x| x.sort_by(|a, b| b.1.cmp(&a.1)));
|
||||
|
||||
Ok(Response::new(Full::new(Bytes::from(serde_json::to_string(&sorted).unwrap()))))
|
||||
}
|
||||
_ => not_found().await
|
||||
}
|
||||
}
|
||||
|
||||
async fn get_votes(req: &Request<Incoming>, db: Arc<Mutex<SqlitePool>>) -> Vec<Vote> {
|
||||
let pool = db.clone().lock().unwrap().clone();
|
||||
let headers = req.headers();
|
||||
let date = match headers.get("Date-to-fetch") {
|
||||
Some(date) => {
|
||||
let date = date.to_str().unwrap();
|
||||
let parsed_date = date.parse::<i64>();
|
||||
if parsed_date.is_err() {
|
||||
None
|
||||
} else {
|
||||
DateTime::from_timestamp_millis(parsed_date.unwrap())
|
||||
}
|
||||
}
|
||||
None => Some(DateTime::from(SystemTime::now()))
|
||||
};
|
||||
if date.is_none() {
|
||||
return Vec::new();
|
||||
}
|
||||
let items = futures::executor::block_on(async move {
|
||||
let formatted_date = format!("{}", date.unwrap().format("%d/%m/%Y"));
|
||||
sqlx::query!(r#"SELECT * FROM votes WHERE timestamp = ?1 ORDER BY id"#, formatted_date).fetch_all(&pool).await.unwrap()
|
||||
});
|
||||
items.iter().map(|x| Vote {
|
||||
vote_plus_id: x.plus_id,
|
||||
vote_plus_nickname: x.plus_nickname.clone(),
|
||||
vote_plus_reason: x.plus_reason.clone(),
|
||||
vote_moins_id: x.moins_id,
|
||||
vote_moins_nickname: x.moins_nickname.clone(),
|
||||
vote_moins_reason: x.moins_reason.clone(),
|
||||
}).collect()
|
||||
}
|
||||
|
||||
async fn post(req: Request<Incoming>, db: Arc<Mutex<SqlitePool>>) -> Result<Response<Full<Bytes>>, Error> {
|
||||
let path = req.uri().path();
|
||||
if path != "/post" {
|
||||
return Ok(Response::builder().status(StatusCode::BAD_REQUEST).body(Full::new(Bytes::from("Bad Request"))).unwrap());
|
||||
}
|
||||
let body = req.into_body().collect().await.unwrap();
|
||||
let data: Result<Vote, serde_json::Error> = serde_json::from_reader(body.aggregate().reader());
|
||||
if data.is_err() {
|
||||
return Ok(Response::builder().status(StatusCode::BAD_REQUEST).body(Full::new(Bytes::from("Bad Request"))).unwrap())
|
||||
}
|
||||
let vote = data.unwrap();
|
||||
let timestamp: DateTime<Utc> = DateTime::from(SystemTime::now());
|
||||
let formatted = timestamp.format("%d/%m/%Y").to_string();
|
||||
let pool = db.clone().lock().unwrap().clone();
|
||||
let mut conn = pool.acquire().await.unwrap();
|
||||
let result = sqlx::query!(r#"INSERT INTO votes ( plus_id, plus_nickname, plus_reason, moins_id, moins_nickname, moins_reason, timestamp )
|
||||
VALUES ( ?1, ?2, ?3, ?4, ?5, ?6, ?7 )"#,
|
||||
vote.vote_plus_id,
|
||||
vote.vote_plus_nickname,
|
||||
vote.vote_plus_reason,
|
||||
vote.vote_moins_id,
|
||||
vote.vote_moins_nickname,
|
||||
vote.vote_moins_reason,
|
||||
formatted).execute(&mut *conn).await;
|
||||
if result.is_err() {
|
||||
return Ok(Response::builder().status(StatusCode::INTERNAL_SERVER_ERROR).body(Full::new(Bytes::from("Internet Error"))).unwrap())
|
||||
}
|
||||
Ok(Response::builder().body(Full::new(Bytes::from("OK"))).unwrap())
|
||||
}
|
||||
|
||||
async fn not_found() -> Result<Response<Full<Bytes>>, Error> {
|
||||
let current_dir = env::current_dir().unwrap().clone();
|
||||
let file_path = current_dir.join("static/html/404.html");
|
||||
let mut file = File::open(file_path).unwrap();
|
||||
let mut buf = Vec::new();
|
||||
file.read_to_end(&mut buf).unwrap();
|
||||
Ok(Response::builder().status(StatusCode::NOT_FOUND).body(Full::new(Bytes::from(buf))).unwrap())
|
||||
}
|
||||
|
||||
fn find_in_vars(pattern: &str) -> String {
|
||||
let mut vars = vars();
|
||||
let result = vars.find(|x| x.0.contains(pattern)).expect(&format!("Could not find '{}' in environment variables", pattern));
|
||||
result.1
|
||||
}
|
||||
|
||||
#[tokio::main]
|
||||
async fn main() {
|
||||
let _ = dotenv();
|
||||
let db_adrr = find_in_vars("DATABASE_ADRR");
|
||||
let db_pool = Arc::new(Mutex::new(SqlitePool::connect(&db_adrr).await.unwrap()));
|
||||
let bind_adrr: SocketAddr = SocketAddr::from_str(find_in_vars("BIND_ADRR").as_str()).expect("Could not parse bind address");
|
||||
let listener = TcpListener::bind(bind_adrr).await.expect("Could not bind to address.");
|
||||
loop {
|
||||
let (tcp, _) = listener.accept().await.expect("Could not accept stream");
|
||||
let io = TokioIo::new(tcp);
|
||||
let db = db_pool.clone();
|
||||
let service = service_fn(move |req| {
|
||||
service(req, db.clone())
|
||||
});
|
||||
tokio::task::spawn(async move {
|
||||
if let Err(err) = http1::Builder::new()
|
||||
.timer(TokioTimer::new())
|
||||
.serve_connection(io, service).await
|
||||
{
|
||||
println!("Failed to serve connection: {:?}", err);
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user