server: the character and name intents, player names and the roster (#23)

This commit is contained in:
2026-11-15 12:01:26 +01:00
parent 5977d45a5a
commit 20dcb87afb
3 changed files with 686 additions and 41 deletions
+26 -1
View File
@@ -5,10 +5,13 @@
## session(id, player_id FK, token_hash UNIQUE, created_at, last_seen) - never expires;
## exactly one GM (partial unique index); max 6 non-GM players, unused keys count.
## Keys are plaintext so the GM can re-show them (Q11); sessions store only SHA-256(token).
## Names (#23, 6.1): `player.setname` fills a NULL name once, `player.rename` overwrites it, and both
## go through `nameTaken` (case-insensitive, "GM" included) and text.validPlayerName. The name is the
## only player field a player writes, and it is also what `roster` publishes to everyone (3.1, Q9).
## This module does no locking: the caller serializes access to the one DbConn (4.3).
import std/[options, strutils, times]
import db_connector/db_sqlite
import crypto
import crypto, text
type
PlayerRole* = enum
@@ -54,6 +57,28 @@ proc playerCount*(db: DbConn): int =
## Non-GM players, named or not (unused keys count toward the 6-player cap).
parseInt(db.getValue(sql"SELECT count(*) FROM player WHERE role = 'player'"))
proc allPlayers*(db: DbConn): seq[Player] =
## Every player row, in id order: the roster (6.1) and the GM's character list walk this.
for row in db.getAllRows(sql"SELECT id, name, role, colour FROM player ORDER BY id"):
result.add rowToPlayer(row)
proc nameTaken*(db: DbConn, name: string, exceptId = 0): bool =
## 6.5 `name-taken`: a player name is unique regardless of case, and the GM's name ("GM") is a
## name like any other - so taking it is refused here, not by a special case.
for row in db.getAllRows(sql"SELECT id, name FROM player WHERE name IS NOT NULL"):
if parseInt(row[0]) == exceptId: continue
if sameName(row[1], name): return true
proc setName*(db: DbConn, playerId: int, name: string): bool =
## `player.setname`: only while the player has no name yet (6.1). false = it already had one.
db.execAffectedRows(sql"UPDATE player SET name = ? WHERE id = ? AND name IS NULL",
name, playerId) > 0
proc renamePlayer*(db: DbConn, playerId: int, name: string): bool =
## `player.rename` (GM only): a named or unnamed player takes the new name.
db.execAffectedRows(sql"UPDATE player SET name = ? WHERE id = ?", name, playerId) > 0
proc keyOf*(db: DbConn, playerId: int): Option[string] =
let s = db.getValue(sql"SELECT secret FROM player_key WHERE player_id = ?", playerId)
if s.len == 0: none(string) else: some(s)