Compare commits

...

4 commits

11 changed files with 112 additions and 202 deletions

10
Cargo.lock generated
View file

@ -189,7 +189,7 @@ dependencies = [
[[package]] [[package]]
name = "backbone-lib" name = "backbone-lib"
version = "0.2.11" version = "0.2.12"
dependencies = [ dependencies = [
"bytes", "bytes",
"ewebsock", "ewebsock",
@ -2649,7 +2649,7 @@ dependencies = [
[[package]] [[package]]
name = "protocol" name = "protocol"
version = "0.2.11" version = "0.2.12"
dependencies = [ dependencies = [
"serde", "serde",
] ]
@ -2883,7 +2883,7 @@ checksum = "dc897dd8d9e8bd1ed8cdad82b5966c3e0ecae09fb1907d58efaa013543185d0a"
[[package]] [[package]]
name = "relay-server" name = "relay-server"
version = "0.2.11" version = "0.2.12"
dependencies = [ dependencies = [
"argon2", "argon2",
"axum", "axum",
@ -3893,7 +3893,7 @@ dependencies = [
[[package]] [[package]]
name = "trictrac-store" name = "trictrac-store"
version = "0.2.11" version = "0.2.12"
dependencies = [ dependencies = [
"anyhow", "anyhow",
"base64 0.21.7", "base64 0.21.7",
@ -3906,7 +3906,7 @@ dependencies = [
[[package]] [[package]]
name = "trictrac-web" name = "trictrac-web"
version = "0.2.11" version = "0.2.12"
dependencies = [ dependencies = [
"backbone-lib", "backbone-lib",
"futures", "futures",

116
README.md
View file

@ -2,8 +2,6 @@
This is a game of [Trictrac](https://en.wikipedia.org/wiki/Trictrac) rust implementation. This is a game of [Trictrac](https://en.wikipedia.org/wiki/Trictrac) rust implementation.
The project is still on its early stages.
## Usage ## Usage
Install [devenv](https://devenv.sh/getting-started/), start a devenv shell `devenv shell`, and run the following commands. Install [devenv](https://devenv.sh/getting-started/), start a devenv shell `devenv shell`, and run the following commands.
@ -17,118 +15,18 @@ just run-relay # listens on :8080
just dev just dev
``` ```
Open two browser windows at `http://127.0.0.1:9091`. In one, create a room; in the other, join with the same room name. Open a browser window at `http://127.0.0.1:9091`. You can play against a very basic bot, or invite an other player to connect at the same address.
Playing with the cli against the 'random' bot: `cargo run --bin=client_cli -- --bot random`
## Roadmap
- [x] rules
- [x] command line interface
- [x] basic bot (random play)
- [ ] web client (in progress)
- [ ] network game (in progress)
- [ ] AI bot
## Code structure ## Code structure
- game rules and game state are implemented in the _store/_ folder. - game rules and game state are implemented in the _store/_ folder.
- a server for the network game is implemented in _server/relay-server_, which uses _server/protocol_
- the web client is in _clients/web_, it connects to the server using the _clients/backbone-lib_ library
- the command-line application is implemented in _clients/cli/_; it allows you to play against a bot, or to have two bots play against each other - the command-line application is implemented in _clients/cli/_; it allows you to play against a bot, or to have two bots play against each other
- the bots algorithms and the training of their models are implemented in the _bot/_ and _spiel_bot_ folders. - the bots algorithms and the training of their models are implemented in the _bot/_ and _spiel_bot_ folders. This is a work in progress, they are not performant at all.
### _store_ package ## Inspirations
The game state is defined by the `GameState` struct in _store/src/game.rs_. The `to_string_id()` method allows this state to be encoded compactly in a string (without the played moves history). For a more readable textual representation, the `fmt::Display` trait is implemented. The multiplayer game architecture, implemented in packages _clients/backbone-lib_, _clients/web/game_, _server/protocol_, _server/relay-server_ is a Leptos-optimized adaptation of the macroquad-based [Carbonfreezer/multiplayer](https://github.com/Carbonfreezer/multiplayer) project. It is a multiplayer game system in Rust targeting browser-based board games compiled as WASM. The original project used Macroquad with a polling-based transport layer; this version replaces that with an async session API built for [Leptos](https://leptos.dev/).
### _clients/cli_ package The web client UX/UI is inspired by https://playtiao.com.
`clients/cli/src/game_runner.rs` contains the logic to make two bots play against each other.
### _bot_ package
- `bot/src/strategy/default.rs` contains the code for a basic bot strategy: it determines the list of valid moves (using the `get_possible_moves_sequences` method of `store::MoveRules`) and simply executes the first move in the list.
- `bot/src/strategy/dqnburn.rs` is another bot strategy that uses a reinforcement learning trained model with the DQN algorithm via the burn library (<https://burn.dev/>).
- `bot/scripts/trains.sh` allows you to train agents using different algorithms (DQN, PPO, SAC).
### multiplayer game
Packages "clients/backbone-lib", "clients/web/game", "server/protocol", "server/relay-server" are a Leptos-optimized adaptation of the macroquad-based [Carbonfreezer/multiplayer](https://github.com/Carbonfreezer/multiplayer) project. It is a multiplayer game system in Rust targeting browser-based board games compiled as WASM. The original project used Macroquad with a polling-based transport layer; this version replaces that with an async session API built for [Leptos](https://leptos.dev/).
The system consists of:
- A **relay server** (Axum/Tokio) that routes messages between players and manages rooms, without knowing anything about game rules.
- A **backbone library** that handles WebSocket connection, handshake, and message routing, exposing an async API to the game frontend.
- Game-specific **backend logic** implementing the `BackEndArchitecture` trait, which runs only on the hosting client.
- A **Leptos frontend** that connects to a session and reacts to state updates.
There is no dedicated game server. One of the players acts as the host: their browser runs the game backend locally. The relay server only forwards messages — it never touches game state.
```
┌─────────────────────────────────────────────────────────────┐
│ Host Client │
│ ┌─────────────┐ ┌──────────────────┐ ┌────────────┐ │
│ │ Leptos UI │◄──►│ GameSession │◄──►│ Backend │ │
│ └─────────────┘ └────────┬─────────┘ └────────────┘ │
└───────────────────────────── │ ────────────────────────────┘
│ WebSocket
┌──────▼──────┐
│ Relay Server│
└──────┬──────┘
│ WebSocket
┌───────────────────────────────│────────────────────────────┐
│ ┌─────────────┐ ┌─────────▼────────┐ │
│ │ Leptos UI │◄──►│ GameSession │ (no backend) │
│ └─────────────┘ └──────────────────┘ │
│ Remote Client │
└─────────────────────────────────────────────────────────────┘
```
#### Data flow
- **Actions** (e.g. "place stone at B3") flow from the UI to the host backend via `GameSession::send_action()`.
- **State updates** flow back as `ViewStateUpdate::Full` (full snapshot, on join or reset) or `ViewStateUpdate::Incremental` (delta, for animations).
- **Timers** are managed by the host's background task (wall-clock, no polling required from the game).
#### backbone-lib session API
The key design choice: `backbone-lib` owns a background async task per session. The Leptos app never drives a loop — it just awaits on events.
#### Workspace
**server/protocol**
Shared message-type constants and the `JoinRequest` struct used during the WebSocket handshake.
**server/relay-server**
Listens on port 8080. Loads `GameConfig.json` on startup to know which games exist and their player limits:
```json
[{ "name": "trictrac", "max_players": 10 }]
```
Games can be added at runtime via the `/reload` endpoint. `/enlist` lists active rooms. A watchdog cleans up inactive rooms every 20 minutes.
For production, put it behind a reverse proxy with SSL (the browser requires `wss://` on HTTPS pages). Example Caddy config:
```
your-domain.com {
handle_path /api/* {
reverse_proxy localhost:8080
}
file_server
}
```
**clients/backbone-lib**
Modules:
| Module | Purpose |
| ---------- | ---------------------------------------------------------------------------------------------------------- |
| `session` | `GameSession`, `connect()`, `SessionEvent`, `RoomConfig` |
| `host` | Background async task for the hosting client (drives `BackEndArchitecture`, manages timers) |
| `client` | Background async task for non-hosting clients |
| `protocol` | Wire encoding/decoding helpers (postcard + message-type bytes) |
| `platform` | `spawn_task` / `sleep_ms` abstractions (WASM: `spawn_local` + gloo-timers; native: thread + thread::sleep) |
| `traits` | `BackEndArchitecture`, `BackendCommand`, `ViewStateUpdate`, `SerializationCap` |

View file

@ -2045,6 +2045,7 @@ a:hover { text-decoration: underline; }
text-decoration: none; text-decoration: none;
opacity: 0.8; opacity: 0.8;
transition: opacity 0.15s; transition: opacity 0.15s;
cursor: pointer;
} }
.game-sidebar-link:hover { opacity: 1; text-decoration: underline; text-underline-offset: 2px; } .game-sidebar-link:hover { opacity: 1; text-decoration: underline; text-underline-offset: 2px; }
@ -2078,13 +2079,13 @@ a:hover { text-decoration: underline; }
} }
/* Push the version wrapper to the bottom of the sidebar flex column */ /* Push the version wrapper to the bottom of the sidebar flex column */
.game-sidebar > div:has(.site-nav-version) { .sidebar-footer {
margin-top: auto; margin-top: auto;
padding: 0.75rem 1rem;
border-top: 1px solid rgba(200,164,72,0.12); border-top: 1px solid rgba(200,164,72,0.12);
} }
.site-nav-version { .site-nav-version {
margin: 2em 0 1em;
display: block; display: block;
text-align: center; text-align: center;
font-family: var(--font-ui); font-family: var(--font-ui);

View file

@ -130,14 +130,12 @@
"copy_link": "Copier le lien", "copy_link": "Copier le lien",
"link_copied": "Copié !", "link_copied": "Copié !",
"scan_qr": "ou scannez le QR code", "scan_qr": "ou scannez le QR code",
"join_code_label": "Rejoindre avec un code",
"join_code_placeholder": "Code de la salle",
"share_btn": "Partager", "share_btn": "Partager",
"nickname_modal_title": "Choisissez votre pseudo", "nickname_modal_title": "Choisissez votre pseudo",
"nickname_modal_hint": "Vous jouerez sous le nom de :", "nickname_modal_hint": "Vous jouerez sous le nom de :",
"nickname_modal_play": "Jouer", "nickname_modal_play": "Jouer",
"nickname_modal_or": "ou", "nickname_modal_or": "ou",
"nickname_modal_sign_in": "Se connecter", "nickname_modal_sign_in": "connectez-vous",
"nickname_modal_register": "Créer un compte", "nickname_modal_register": "Créer un compte",
"new_game": "Nouvelle partie", "new_game": "Nouvelle partie",
"language": "Langue" "language": "Langue"

View file

@ -29,7 +29,26 @@ use trictrac_store::CheckerMove;
use std::collections::VecDeque; use std::collections::VecDeque;
const RELAY_URL: &str = "ws://localhost:8080/ws"; /// Newtype wrappers so context lookup can distinguish signals of the same inner type.
#[derive(Clone, Copy)]
pub(crate) struct AnonNickname(pub RwSignal<Option<String>>);
#[derive(Clone, Copy)]
pub(crate) struct AuthEmailVerified(pub RwSignal<bool>);
fn relay_url() -> String {
#[cfg(debug_assertions)]
{
"ws://localhost:8080/ws".to_string()
}
#[cfg(not(debug_assertions))]
{
let location = web_sys::window().and_then(|w| Some(w.location())).unwrap();
let protocol = location.protocol().unwrap_or_default();
let host = location.host().unwrap_or_default();
let ws_protocol = if protocol == "https:" { "wss" } else { "ws" };
format!("{ws_protocol}://{host}/ws")
}
}
const GAME_ID: &str = "trictrac"; const GAME_ID: &str = "trictrac";
const STORAGE_KEY: &str = "trictrac_session"; const STORAGE_KEY: &str = "trictrac_session";
const VERSION: &str = env!("CARGO_PKG_VERSION"); const VERSION: &str = env!("CARGO_PKG_VERSION");
@ -155,14 +174,14 @@ pub fn App() -> impl IntoView {
let auth_username: RwSignal<Option<String>> = RwSignal::new(None); let auth_username: RwSignal<Option<String>> = RwSignal::new(None);
let auth_email_verified: RwSignal<bool> = RwSignal::new(false); let auth_email_verified: RwSignal<bool> = RwSignal::new(false);
provide_context(auth_username); provide_context(auth_username);
provide_context(auth_email_verified); provide_context(AuthEmailVerified(auth_email_verified));
// Set to true once get_me resolves (success or failure) so lobby can // Set to true once get_me resolves (success or failure) so lobby can
// decide immediately whether to show the nickname modal. // decide immediately whether to show the nickname modal.
let auth_loaded: RwSignal<bool> = RwSignal::new(false); let auth_loaded: RwSignal<bool> = RwSignal::new(false);
provide_context(auth_loaded); provide_context(auth_loaded);
// Nickname chosen by an anonymous player; used instead of "Anonymous". // Nickname chosen by an anonymous player; used instead of "Anonymous".
let anon_nickname: RwSignal<Option<String>> = RwSignal::new(None); let anon_nickname: RwSignal<Option<String>> = RwSignal::new(None);
provide_context(anon_nickname); provide_context(AnonNickname(anon_nickname));
spawn_local(async move { spawn_local(async move {
if let Ok(me) = api::get_me().await { if let Ok(me) = api::get_me().await {
auth_username.set(Some(me.username)); auth_username.set(Some(me.username));
@ -205,7 +224,7 @@ pub fn App() -> impl IntoView {
Some(NetCommand::CreateRoom { room }) => { Some(NetCommand::CreateRoom { room }) => {
break Some(( break Some((
RoomConfig { RoomConfig {
relay_url: RELAY_URL.to_string(), relay_url: relay_url(),
game_id: GAME_ID.to_string(), game_id: GAME_ID.to_string(),
room_id: room, room_id: room,
rule_variation: 0, rule_variation: 0,
@ -219,7 +238,7 @@ pub fn App() -> impl IntoView {
Some(NetCommand::JoinRoom { room }) => { Some(NetCommand::JoinRoom { room }) => {
break Some(( break Some((
RoomConfig { RoomConfig {
relay_url: RELAY_URL.to_string(), relay_url: relay_url(),
game_id: GAME_ID.to_string(), game_id: GAME_ID.to_string(),
room_id: room, room_id: room,
rule_variation: 0, rule_variation: 0,
@ -304,7 +323,7 @@ pub fn App() -> impl IntoView {
if !session.is_host { if !session.is_host {
save_session(&StoredSession { save_session(&StoredSession {
relay_url: RELAY_URL.to_string(), relay_url: relay_url(),
game_id: GAME_ID.to_string(), game_id: GAME_ID.to_string(),
room_id: room_id_for_storage.clone(), room_id: room_id_for_storage.clone(),
token: session.reconnect_token, token: session.reconnect_token,
@ -358,7 +377,7 @@ pub fn App() -> impl IntoView {
if is_host { if is_host {
save_session(&StoredSession { save_session(&StoredSession {
relay_url: RELAY_URL.to_string(), relay_url: relay_url(),
game_id: GAME_ID.to_string(), game_id: GAME_ID.to_string(),
room_id: room_id_for_storage.clone(), room_id: room_id_for_storage.clone(),
token: reconnect_token, token: reconnect_token,
@ -544,47 +563,60 @@ fn SiteHamburger() -> impl IntoView {
</div> </div>
// Auth // Auth
{move || match auth_username.get() {
Some(u) => {
let href = format!("/profile/{u}");
view! {
<div class="game-sidebar-section"> <div class="game-sidebar-section">
<svg class="icon" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 640 640"> <svg class="icon" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 640 640">
<path fill="currentColor" d="M240 192C240 147.8 275.8 112 320 112C364.2 112 400 147.8 400 192C400 236.2 364.2 272 320 272C275.8 272 240 236.2 240 192zM448 192C448 121.3 390.7 64 320 64C249.3 64 192 121.3 192 192C192 262.7 249.3 320 320 320C390.7 320 448 262.7 448 192zM144 544C144 473.3 201.3 416 272 416L368 416C438.7 416 496 473.3 496 544L496 552C496 565.3 506.7 576 520 576C533.3 576 544 565.3 544 552L544 544C544 446.8 465.2 368 368 368L272 368C174.8 368 96 446.8 96 544L96 552C96 565.3 106.7 576 120 576C133.3 576 144 565.3 144 552L144 544z"/> <path fill="currentColor" d="M240 192C240 147.8 275.8 112 320 112C364.2 112 400 147.8 400 192C400 236.2 364.2 272 320 272C275.8 272 240 236.2 240 192zM448 192C448 121.3 390.7 64 320 64C249.3 64 192 121.3 192 192C192 262.7 249.3 320 320 320C390.7 320 448 262.7 448 192zM144 544C144 473.3 201.3 416 272 416L368 416C438.7 416 496 473.3 496 544L496 552C496 565.3 506.7 576 520 576C533.3 576 544 565.3 544 552L544 544C544 446.8 465.2 368 368 368L272 368C174.8 368 96 446.8 96 544L96 552C96 565.3 106.7 576 120 576C133.3 576 144 565.3 144 552L144 544z"/>
</svg> </svg>
{move || match auth_username.get() {
Some(u) => {
let href = format!("/profile/{u}");
view! {
<A href=href attr:class="game-sidebar-link" <A href=href attr:class="game-sidebar-link"
on:click=move |_| sidebar_open.set(false)> on:click=move |_| sidebar_open.set(false)>
{u} {u}
</A> </A>
<button class="game-sidebar-btn" on:click=move |_| { </div>
<div class="game-sidebar-section">
<svg class="icon" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 640 640">
<path fill="currentColor" d="M224 160C241.7 160 256 145.7 256 128C256 110.3 241.7 96 224 96L160 96C107 96 64 139 64 192L64 448C64 501 107 544 160 544L224 544C241.7 544 256 529.7 256 512C256 494.3 241.7 480 224 480L160 480C142.3 480 128 465.7 128 448L128 192C128 174.3 142.3 160 160 160L224 160zM566.6 342.6C579.1 330.1 579.1 309.8 566.6 297.3L438.6 169.3C426.1 156.8 405.8 156.8 393.3 169.3C380.8 181.8 380.8 202.1 393.3 214.6L466.7 288L256 288C238.3 288 224 302.3 224 320C224 337.7 238.3 352 256 352L466.7 352L393.3 425.4C380.8 437.9 380.8 458.2 393.3 470.7C405.8 483.2 426.1 483.2 438.6 470.7L566.6 342.7z"/>
</svg>
<a class="game-sidebar-link" on:click=move |_| {
spawn_local(async move { spawn_local(async move {
let _ = api::post_logout().await; let _ = api::post_logout().await;
auth_username.set(None); auth_username.set(None);
}); });
}>{t!(i18n, sign_out)}</button> }>{t!(i18n, sign_out)}</a>
</div>
}.into_any() }.into_any()
}, },
None => view! { None => view! {
<div class="game-sidebar-section">
<svg class="icon" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 640 640">
<path fill="currentColor" d="M416 160L480 160C497.7 160 512 174.3 512 192L512 448C512 465.7 497.7 480 480 480L416 480C398.3 480 384 494.3 384 512C384 529.7 398.3 544 416 544L480 544C533 544 576 501 576 448L576 192C576 139 533 96 480 96L416 96C398.3 96 384 110.3 384 128C384 145.7 398.3 160 416 160zM406.6 342.6C419.1 330.1 419.1 309.8 406.6 297.3L278.6 169.3C266.1 156.8 245.8 156.8 233.3 169.3C220.8 181.8 220.8 202.1 233.3 214.6L306.7 288L96 288C78.3 288 64 302.3 64 320C64 337.7 78.3 352 96 352L306.7 352L233.3 425.4C220.8 437.9 220.8 458.2 233.3 470.7C245.8 483.2 266.1 483.2 278.6 470.7L406.6 342.7z"/>
</svg>
<A href="/account" attr:class="game-sidebar-link" <A href="/account" attr:class="game-sidebar-link"
on:click=move |_| sidebar_open.set(false)> on:click=move |_| sidebar_open.set(false)>
{t!(i18n, sign_in)} {t!(i18n, sign_in)}
</A> </A>
</div>
}.into_any(), }.into_any(),
}} }}
</div>
<div class="sidebar-footer">
// ── Debug section ───────────────────────────────────────────────── // ── Debug section ─────────────────────────────────────────────────
<div class="game-sidebar-section" style="flex-direction:column;gap:0.4rem">
<span class="game-sidebar-label">{t!(i18n, debug_section)}</span>
// "Take snapshot" — only visible while a game is in progress // "Take snapshot" — only visible while a game is in progress
{move || { {move || {
let Screen::Playing(ref state) = screen.get() else { return None; }; let Screen::Playing(ref state) = screen.get() else { return None; };
let vs = state.view_state.clone(); let vs = state.view_state.clone();
let tx = cmd_tx_snapshot.clone(); let tx = cmd_tx_snapshot.clone();
Some(view! { Some(view! {
<button class="game-sidebar-btn" on:click=move |_| {
<div class="game-sidebar-section">
<svg class="icon" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 640 640">
<path fill="currentColor" d="M257.1 96C238.4 96 220.9 105.4 210.5 120.9L184.5 160L128 160C92.7 160 64 188.7 64 224L64 480C64 515.3 92.7 544 128 544L512 544C547.3 544 576 515.3 576 480L576 224C576 188.7 547.3 160 512 160L455.5 160L429.5 120.9C419.1 105.4 401.6 96 382.9 96L257.1 96zM250.4 147.6C251.9 145.4 254.4 144 257.1 144L382.8 144C385.5 144 388 145.3 389.5 147.6L422.7 197.4C427.2 204.1 434.6 208.1 442.7 208.1L512 208.1C520.8 208.1 528 215.3 528 224.1L528 480.1C528 488.9 520.8 496.1 512 496.1L128 496C119.2 496 112 488.8 112 480L112 224C112 215.2 119.2 208 128 208L197.3 208C205.3 208 212.8 204 217.3 197.3L250.5 147.5zM320 448C381.9 448 432 397.9 432 336C432 274.1 381.9 224 320 224C258.1 224 208 274.1 208 336C208 397.9 258.1 448 320 448zM256 336C256 300.7 284.7 272 320 272C355.3 272 384 300.7 384 336C384 371.3 355.3 400 320 400C284.7 400 256 371.3 256 336z"/>
</svg>
<a class="game-sidebar-link" on:click=move |_| {
if let Ok(json) = serde_json::to_string(&vs) { if let Ok(json) = serde_json::to_string(&vs) {
#[cfg(target_arch = "wasm32")] #[cfg(target_arch = "wasm32")]
{ {
@ -610,22 +642,28 @@ fn SiteHamburger() -> impl IntoView {
} else { } else {
t_string!(i18n, take_snapshot).to_owned() t_string!(i18n, take_snapshot).to_owned()
}} }}
</button> </a>
</div>
}) })
}} }}
// "Replay snapshot" — always visible // "Replay snapshot" — always visible
<button class="game-sidebar-btn" on:click=move |_| { <div class="game-sidebar-section">
<svg class="icon" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 640 640">
<path fill="currentColor" d="M534.6 182.6C547.1 170.1 547.1 149.8 534.6 137.3L470.6 73.3C461.4 64.1 447.7 61.4 435.7 66.4C423.7 71.4 416 83.1 416 96L416 128L256 128C150 128 64 214 64 320C64 337.7 78.3 352 96 352C113.7 352 128 337.7 128 320C128 249.3 185.3 192 256 192L416 192L416 224C416 236.9 423.8 248.6 435.8 253.6C447.8 258.6 461.5 255.8 470.7 246.7L534.7 182.7zM105.4 457.4C92.9 469.9 92.9 490.2 105.4 502.7L169.4 566.7C178.6 575.9 192.3 578.6 204.3 573.6C216.3 568.6 224 556.9 224 544L224 512L384 512C490 512 576 426 576 320C576 302.3 561.7 288 544 288C526.3 288 512 302.3 512 320C512 390.7 454.7 448 384 448L224 448L224 416C224 403.1 216.2 391.4 204.2 386.4C192.2 381.4 178.5 384.2 169.3 393.3L105.3 457.3z"/>
</svg>
<a class="game-sidebar-link" on:click=move |_| {
replay_text.set(String::new()); replay_text.set(String::new());
replay_error.set(false); replay_error.set(false);
replay_open.set(true); replay_open.set(true);
sidebar_open.set(false); sidebar_open.set(false);
}>{t!(i18n, replay_snapshot)}</button> }>{t!(i18n, replay_snapshot)}</a>
</div> </div>
<div> <div>
<span class="site-nav-version">"v" {VERSION}</span> <span class="site-nav-version">"v" {VERSION}</span>
</div> </div>
</div> </div>
</div>
// ── Replay snapshot modal ───────────────────────────────────────────── // ── Replay snapshot modal ─────────────────────────────────────────────
<div class="ceremony-overlay" style="z-index:300" <div class="ceremony-overlay" style="z-index:300"

View file

@ -2,6 +2,7 @@ use leptos::prelude::*;
use leptos_router::hooks::use_navigate; use leptos_router::hooks::use_navigate;
use crate::api; use crate::api;
use crate::app::AuthEmailVerified;
use crate::i18n::*; use crate::i18n::*;
#[component] #[component]
@ -9,8 +10,8 @@ pub fn AccountPage() -> impl IntoView {
let i18n = use_i18n(); let i18n = use_i18n();
let auth_username = let auth_username =
use_context::<RwSignal<Option<String>>>().expect("auth_username context not found"); use_context::<RwSignal<Option<String>>>().expect("auth_username context not found");
let auth_email_verified = let auth_email_verified = use_context::<AuthEmailVerified>()
use_context::<RwSignal<bool>>().expect("auth_email_verified context not found"); .expect("auth_email_verified context not found").0;
let navigate = use_navigate(); let navigate = use_navigate();
// Only redirect to profile when the email is actually verified. // Only redirect to profile when the email is actually verified.
@ -107,8 +108,8 @@ fn LoginForm() -> impl IntoView {
let i18n = use_i18n(); let i18n = use_i18n();
let auth_username = let auth_username =
use_context::<RwSignal<Option<String>>>().expect("auth_username context not found"); use_context::<RwSignal<Option<String>>>().expect("auth_username context not found");
let auth_email_verified = let auth_email_verified = use_context::<AuthEmailVerified>()
use_context::<RwSignal<bool>>().expect("auth_email_verified context not found"); .expect("auth_email_verified context not found").0;
let navigate = use_navigate(); let navigate = use_navigate();
let login = RwSignal::new(String::new()); let login = RwSignal::new(String::new());
@ -177,8 +178,8 @@ fn RegisterForm() -> impl IntoView {
let i18n = use_i18n(); let i18n = use_i18n();
let auth_username = let auth_username =
use_context::<RwSignal<Option<String>>>().expect("auth_username context not found"); use_context::<RwSignal<Option<String>>>().expect("auth_username context not found");
let auth_email_verified = let auth_email_verified = use_context::<AuthEmailVerified>()
use_context::<RwSignal<bool>>().expect("auth_email_verified context not found"); .expect("auth_email_verified context not found").0;
let username = RwSignal::new(String::new()); let username = RwSignal::new(String::new());
let email = RwSignal::new(String::new()); let email = RwSignal::new(String::new());

View file

@ -3,7 +3,7 @@ use leptos::prelude::*;
use leptos_router::components::A; use leptos_router::components::A;
use leptos_router::hooks::use_query_map; use leptos_router::hooks::use_query_map;
use crate::app::{NetCommand, Screen}; use crate::app::{AnonNickname, NetCommand, Screen};
use crate::i18n::*; use crate::i18n::*;
// ── Room/nickname generation ────────────────────────────────────────────────── // ── Room/nickname generation ──────────────────────────────────────────────────
@ -103,7 +103,7 @@ pub fn LobbyPage() -> impl IntoView {
let cmd_tx = use_context::<UnboundedSender<NetCommand>>().expect("NetCommand sender"); let cmd_tx = use_context::<UnboundedSender<NetCommand>>().expect("NetCommand sender");
let auth_username = use_context::<RwSignal<Option<String>>>().expect("auth_username context"); let auth_username = use_context::<RwSignal<Option<String>>>().expect("auth_username context");
let auth_loaded = use_context::<RwSignal<bool>>().expect("auth_loaded context"); let auth_loaded = use_context::<RwSignal<bool>>().expect("auth_loaded context");
let anon_nickname = use_context::<RwSignal<Option<String>>>().expect("anon_nickname context"); let anon_nickname = use_context::<AnonNickname>().expect("anon_nickname context").0;
let query = use_query_map(); let query = use_query_map();
let view_state: RwSignal<LobbyView> = RwSignal::new(LobbyView::Idle); let view_state: RwSignal<LobbyView> = RwSignal::new(LobbyView::Idle);
@ -195,12 +195,9 @@ fn IdleCard(
pending_action: RwSignal<Option<PendingLobbyAction>>, pending_action: RwSignal<Option<PendingLobbyAction>>,
) -> impl IntoView { ) -> impl IntoView {
let i18n = use_i18n(); let i18n = use_i18n();
let join_open = RwSignal::new(false);
let join_code = RwSignal::new(String::new());
let cmd_bot = cmd_tx.clone(); let cmd_bot = cmd_tx.clone();
let cmd_create = cmd_tx.clone(); let cmd_create = cmd_tx.clone();
let cmd_join = cmd_tx;
let on_create = move |_: leptos::ev::MouseEvent| { let on_create = move |_: leptos::ev::MouseEvent| {
let code = generate_room_code(); let code = generate_room_code();
@ -232,48 +229,6 @@ fn IdleCard(
{t!(i18n, create_room)} {t!(i18n, create_room)}
</button> </button>
</div> </div>
// Hidden "join by code" fallback
<div style="margin-top:1.25rem;text-align:center">
<button
class="portal-page-btn"
style="font-size:0.75rem;opacity:0.7"
on:click=move |_| join_open.update(|v| *v = !*v)
>
{move || if join_open.get() { "" } else { "" }}
{t!(i18n, join_code_label)}
</button>
{move || {
let cmd = cmd_join.clone();
join_open.get().then(|| view! {
<div style="margin-top:0.75rem;display:flex;gap:0.5rem">
<input
class="login-input"
style="margin:0"
type="text"
placeholder=move || t_string!(i18n, join_code_placeholder)
prop:value=move || join_code.get()
on:input=move |ev| join_code.set(event_target_value(&ev))
/>
<button
class="login-btn login-btn-secondary"
style="margin:0;padding:0 1rem"
disabled=move || join_code.get().is_empty()
on:click=move |_| {
let code = join_code.get();
if auth_username.get_untracked().is_some() {
cmd.unbounded_send(NetCommand::JoinRoom { room: code }).ok();
} else {
pending_action.set(Some(PendingLobbyAction::Join { code }));
}
}
>
{t!(i18n, join_room)}
</button>
</div>
})
}}
</div>
} }
} }
@ -338,8 +293,6 @@ fn NicknameModal(
{t!(i18n, nickname_modal_or)} {t!(i18n, nickname_modal_or)}
" " " "
<A href="/account">{t!(i18n, nickname_modal_sign_in)}</A> <A href="/account">{t!(i18n, nickname_modal_sign_in)}</A>
" · "
<A href="/account">{t!(i18n, nickname_modal_register)}</A>
</p> </p>
</div> </div>
</div> </div>

View file

@ -2,6 +2,7 @@ use leptos::prelude::*;
use leptos_router::hooks::use_query_map; use leptos_router::hooks::use_query_map;
use crate::api; use crate::api;
use crate::app::AuthEmailVerified;
use crate::i18n::*; use crate::i18n::*;
#[derive(Clone, PartialEq)] #[derive(Clone, PartialEq)]
@ -16,8 +17,8 @@ pub fn VerifyEmailPage() -> impl IntoView {
let i18n = use_i18n(); let i18n = use_i18n();
let auth_username = let auth_username =
use_context::<RwSignal<Option<String>>>().expect("auth_username context not found"); use_context::<RwSignal<Option<String>>>().expect("auth_username context not found");
let auth_email_verified = let auth_email_verified = use_context::<AuthEmailVerified>()
use_context::<RwSignal<bool>>().expect("auth_email_verified context not found"); .expect("auth_email_verified context not found").0;
let query = use_query_map(); let query = use_query_map();
let token = query.with(|m| m.get("token").map(|s| s.to_string()).unwrap_or_default()); let token = query.with(|m| m.get("token").map(|s| s.to_string()).unwrap_or_default());

View file

@ -3,10 +3,11 @@
"devenv": { "devenv": {
"locked": { "locked": {
"dir": "src/modules", "dir": "src/modules",
"lastModified": 1776863933, "lastModified": 1779486363,
"narHash": "sha256-6rNmvwTngbmz/j3DGsEYkyakrHHY8N5wgRD9k35HyuM=",
"owner": "cachix", "owner": "cachix",
"repo": "devenv", "repo": "devenv",
"rev": "863b4204725efaeeb73811e376f928232b720646", "rev": "90692720b2ad7a7811204155900bf6bea3a3b420",
"type": "github" "type": "github"
}, },
"original": { "original": {
@ -18,10 +19,11 @@
}, },
"nixpkgs": { "nixpkgs": {
"locked": { "locked": {
"lastModified": 1776734388, "lastModified": 1779102034,
"narHash": "sha256-vZJZjLo513IeI8hjzHFc6TDezUd4uCE2Eq4SNO3DNNg=",
"owner": "NixOS", "owner": "NixOS",
"repo": "nixpkgs", "repo": "nixpkgs",
"rev": "10e7ad5bbcb421fe07e3a4ad53a634b0cd57ffac", "rev": "687f05a9184cad4eaf905c48b63649e3a86f5433",
"type": "github" "type": "github"
}, },
"original": { "original": {
@ -34,6 +36,7 @@
"nixpkgs-cmake3": { "nixpkgs-cmake3": {
"locked": { "locked": {
"lastModified": 1758213207, "lastModified": 1758213207,
"narHash": "sha256-rqoqF0LEi+6ZT59tr+hTQlxVwrzQsET01U4uUdmqRtM=",
"owner": "NixOS", "owner": "NixOS",
"repo": "nixpkgs", "repo": "nixpkgs",
"rev": "f4b140d5b253f5e2a1ff4e5506edbf8267724bde", "rev": "f4b140d5b253f5e2a1ff4e5506edbf8267724bde",

View file

@ -55,6 +55,10 @@ build-relay:
cp target/release/relay-server deploy cp target/release/relay-server deploy
cp -u server/relay-server/GameConfig.json deploy/ cp -u server/relay-server/GameConfig.json deploy/
# generate web stats report from the current nginx logs
stats:
ssh -t raspberry sudo goaccess /var/log/nginx/trictrac_access.log --log-format=COMBINED -o html > var/stats/report.html
# start a trictrac container with nixos-container # start a trictrac container with nixos-container
# `boot.enableContainers = true` must be set on local nixos system # `boot.enableContainers = true` must be set on local nixos system
local: local:

View file

@ -245,6 +245,7 @@ async fn register(
async fn login( async fn login(
mut auth_session: AuthSession<AuthBackend>, mut auth_session: AuthSession<AuthBackend>,
State(state): State<Arc<AppState>>,
Json(body): Json<LoginBody>, Json(body): Json<LoginBody>,
) -> Result<impl IntoResponse, AppError> { ) -> Result<impl IntoResponse, AppError> {
let creds = Credentials { let creds = Credentials {
@ -260,6 +261,18 @@ async fn login(
auth_session.login(&user).await.map_err(|_| AppError::Internal)?; auth_session.login(&user).await.map_err(|_| AppError::Internal)?;
if !user.email_verified {
let _ = db::delete_email_tokens(&state.db, user.id, "verify").await;
let token = generate_token();
let expires_at = now_unix() + VERIFY_TOKEN_EXPIRY;
if db::create_email_token(&state.db, user.id, &token, "verify", expires_at)
.await
.is_ok()
{
state.mailer.send_verification(&user.email, &token).await;
}
}
Ok(Json(MeResponse { Ok(Json(MeResponse {
id: user.id, id: user.id,
username: user.username, username: user.username,