Skip to main content

open_chess_server/http/
games.rs

1//! Game export: PGN by default, JSON with `Accept: application/json`.
2
3use std::collections::HashMap;
4
5use axum::Json;
6use axum::extract::{Path, Query, State};
7use axum::http::{HeaderMap, HeaderValue, header};
8use axum::response::{IntoResponse, Response};
9use chess_core::{Game, PgnGame, PgnPlayer, Side, pgn};
10use chess_proto as p;
11
12use crate::app::{Ctx, Reader};
13use crate::config::Config;
14use crate::error::{ApiError, ApiResult};
15use crate::model::{self, GameRow};
16
17fn flag(q: &HashMap<String, String>, k: &str, default: bool) -> bool {
18    q.get(k).map_or(default, |v| matches!(v.as_str(), "true" | "1" | "yes"))
19}
20
21fn pgn_text(row: &GameRow, game: &Game, cfg: &Config, clocks: bool) -> String {
22    let public_url = cfg.public_url();
23    let player = |s: Side| {
24        let a = row.player(s);
25        let (rating, _, diff) = row.rating(s);
26        PgnPlayer { name: a.username.clone(), rating: Some(rating), rating_diff: diff, title: a.title() }
27    };
28    let first_fullmove = row
29        .initial_fen
30        .as_deref()
31        .and_then(|f| f.split_whitespace().nth(5))
32        .and_then(|n| n.parse().ok())
33        .unwrap_or(1);
34    let event = format!("{} {} game", cfg.site_name, if row.rated { "rated" } else { "casual" });
35    let clocks_ms: Vec<i64> = if clocks && row.has_clock() { row.clock_ms.clone() } else { Vec::new() };
36    pgn(&PgnGame {
37        event: &event,
38        site: format!("{public_url}/{}", row.id),
39        game_id: &row.id,
40        created_at_ms: row.created_ms,
41        white: player(Side::White),
42        black: player(Side::Black),
43        status: row.status,
44        winner: row.winner,
45        clock: row
46            .clock_initial_ms
47            .map(|i| ((i / 1000) as u32, (row.clock_increment_ms.unwrap_or(0) / 1000) as u32)),
48        initial_fen: row.initial_fen.as_deref(),
49        sans: game.sans(),
50        first_to_move: game.first_to_move(),
51        first_fullmove,
52        clocks_ms: &clocks_ms,
53    })
54}
55
56pub(crate) fn json(row: &GameRow, game: &Game, q: &HashMap<String, String>, cfg: &Config) -> p::GameJson {
57    let player = |s: Side| {
58        let a = row.player(s);
59        let (rating, prov, diff) = row.rating(s);
60        p::GamePlayer {
61            user: p::LightUser { id: a.id(), name: a.username.clone(), title: a.title() },
62            rating,
63            rating_diff: diff,
64            provisional: prov.then_some(true),
65            analysis: None,
66        }
67    };
68    p::GameJson {
69        id: row.id.clone(),
70        rated: row.rated,
71        variant: row.variant.clone(),
72        speed: row.speed,
73        perf: row.perf_key().into(),
74        created_at: row.created_ms,
75        last_move_at: row.last_move_ms.or(row.finished_ms).unwrap_or(row.created_ms),
76        status: row.status,
77        source: row.source.clone(),
78        players: p::GamePlayers { white: player(Side::White), black: player(Side::Black) },
79        initial_fen: row.initial_fen.clone(),
80        winner: row.winner,
81        moves: flag(q, "moves", true).then(|| game.sans().join(" ")),
82        pgn: flag(q, "pgnInJson", false).then(|| pgn_text(row, game, cfg, flag(q, "clocks", false))),
83        clock: row.clock_initial_ms.map(|i| {
84            let inc = row.clock_increment_ms.unwrap_or(0) / 1000;
85            p::ExportClock { initial: i / 1000, increment: inc, total_time: i / 1000 + 40 * inc }
86        }),
87        clocks: (flag(q, "clocks", false) && row.has_clock())
88            .then(|| row.clock_ms.iter().map(|ms| ms / 10).collect()),
89    }
90}
91
92pub async fn export(
93    State(ctx): State<Ctx>,
94    _reader: Reader,
95    h: HeaderMap,
96    Path(id): Path<String>,
97    Query(q): Query<HashMap<String, String>>,
98) -> ApiResult<Response> {
99    let c = ctx.db.conn().await?;
100    let row = model::game(&ctx.db, &*c, &id).await?.ok_or_else(|| ApiError::not_found("game"))?;
101    let game =
102        Game::from_moves(row.initial_fen.as_deref(), &row.moves).map_err(|e| anyhow::anyhow!("{e}"))?;
103    let wants_json = h
104        .get(header::ACCEPT)
105        .and_then(|v| v.to_str().ok())
106        .is_some_and(|a| a.contains("application/json") || a.contains("application/x-ndjson"));
107    if wants_json {
108        return Ok(Json(json(&row, &game, &q, &ctx.cfg)).into_response());
109    }
110    let mut r = pgn_text(&row, &game, &ctx.cfg, flag(&q, "clocks", false)).into_response();
111    r.headers_mut().insert(header::CONTENT_TYPE, HeaderValue::from_static("application/x-chess-pgn"));
112    Ok(r)
113}
114
115/// `GET /api/games/user/{username}`: a player's games, newest first, as
116/// NDJSON (Lichess's shape; `max`, default 20, up to 100; `ongoing=false`
117/// leaves out games in progress).
118pub async fn by_user(
119    State(ctx): State<Ctx>,
120    _reader: Reader,
121    Path(username): Path<String>,
122    Query(q): Query<HashMap<String, String>>,
123) -> ApiResult<Response> {
124    let c = ctx.db.conn().await?;
125    let a =
126        model::account_by_name(&ctx.db, &*c, &username).await?.ok_or_else(|| ApiError::not_found("user"))?;
127    let max: i64 = q.get("max").and_then(|m| m.parse().ok()).unwrap_or(20).clamp(1, 100);
128    let ongoing = flag(&q, "ongoing", true);
129    let rows = c
130        .query(
131            &ctx.db.sql(&format!(
132                "{} WHERE (g.white_id = $1 OR g.black_id = $1) AND ($2 OR g.status NOT IN (10, 20))
133                 ORDER BY g.created_at DESC LIMIT $3",
134                model::GAME_SELECT
135            )),
136            &[&a.player_id, &ongoing, &max],
137        )
138        .await?;
139    drop(c);
140    let (tx, rx) = tokio::sync::mpsc::channel::<bytes::Bytes>(rows.len().max(1));
141    for r in &rows {
142        let row = GameRow::from_row(r);
143        let Ok(game) = Game::from_moves(row.initial_fen.as_deref(), &row.moves) else { continue };
144        let _ = tx.try_send(crate::http::line(&json(&row, &game, &q, &ctx.cfg)));
145    }
146    drop(tx);
147    Ok(crate::http::ndjson(rx))
148}