planetwars.dev/planetwars-server/src/routes/matches.rs

69 lines
2 KiB
Rust
Raw Normal View History

2022-07-04 20:33:35 +00:00
use axum::{extract::Path, Json};
2022-01-01 15:32:55 +00:00
use hyper::StatusCode;
2022-01-01 10:26:49 +00:00
use serde::{Deserialize, Serialize};
2022-07-05 18:34:20 +00:00
use std::path::PathBuf;
2022-01-01 10:26:49 +00:00
2022-01-01 15:32:55 +00:00
use crate::{
2022-07-04 20:33:35 +00:00
db::matches::{self, MatchState},
DatabaseConnection, MATCHES_DIR,
2022-01-01 15:32:55 +00:00
};
2022-01-02 15:14:03 +00:00
#[derive(Serialize, Deserialize)]
pub struct ApiMatch {
id: i32,
timestamp: chrono::NaiveDateTime,
2022-02-16 17:40:32 +00:00
state: MatchState,
2022-01-02 15:14:03 +00:00
players: Vec<ApiMatchPlayer>,
}
#[derive(Serialize, Deserialize)]
pub struct ApiMatchPlayer {
2022-07-06 20:41:27 +00:00
bot_version_id: Option<i32>,
bot_id: Option<i32>,
bot_name: Option<String>,
2022-01-02 15:14:03 +00:00
}
pub async fn list_matches(conn: DatabaseConnection) -> Result<Json<Vec<ApiMatch>>, StatusCode> {
matches::list_matches(&conn)
.map_err(|_| StatusCode::BAD_REQUEST)
.map(|matches| Json(matches.into_iter().map(match_data_to_api).collect()))
}
pub fn match_data_to_api(data: matches::FullMatchData) -> ApiMatch {
2022-01-02 15:14:03 +00:00
ApiMatch {
id: data.base.id,
timestamp: data.base.created_at,
2022-02-16 17:40:32 +00:00
state: data.base.state,
2022-01-02 15:14:03 +00:00
players: data
.match_players
.iter()
.map(|_p| ApiMatchPlayer {
2022-07-06 20:41:27 +00:00
bot_version_id: _p.bot_version.as_ref().map(|cb| cb.id),
bot_id: _p.bot.as_ref().map(|b| b.id),
bot_name: _p.bot.as_ref().map(|b| b.name.clone()),
})
2022-01-02 15:14:03 +00:00
.collect(),
}
}
pub async fn get_match_data(
Path(match_id): Path<i32>,
conn: DatabaseConnection,
) -> Result<Json<ApiMatch>, StatusCode> {
let match_data = matches::find_match(match_id, &conn)
.map_err(|_| StatusCode::NOT_FOUND)
2022-03-13 14:20:03 +00:00
.map(match_data_to_api)?;
Ok(Json(match_data))
}
2022-01-02 16:56:52 +00:00
pub async fn get_match_log(
Path(match_id): Path<i32>,
conn: DatabaseConnection,
) -> Result<Vec<u8>, StatusCode> {
2022-03-12 08:04:12 +00:00
let match_base =
matches::find_match_base(match_id, &conn).map_err(|_| StatusCode::NOT_FOUND)?;
2022-01-02 16:56:52 +00:00
let log_path = PathBuf::from(MATCHES_DIR).join(&match_base.log_path);
let log_contents = std::fs::read(log_path).map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?;
Ok(log_contents)
}