merge(main): resolve PR #283 lobby/views.py conflict
This commit is contained in:
7
.claude/settings.json
Normal file
7
.claude/settings.json
Normal file
@@ -0,0 +1,7 @@
|
|||||||
|
{
|
||||||
|
"permissions": {
|
||||||
|
"allow": [
|
||||||
|
"Bash"
|
||||||
|
]
|
||||||
|
}
|
||||||
|
}
|
||||||
119
CLAUDE.md
Normal file
119
CLAUDE.md
Normal file
@@ -0,0 +1,119 @@
|
|||||||
|
# CLAUDE.md
|
||||||
|
|
||||||
|
This file provides guidance to Claude Code (claude.ai/code) when working with code in this repository.
|
||||||
|
|
||||||
|
## Project Overview
|
||||||
|
|
||||||
|
**Weirsøe Party Protocol** is a Danish party game web platform (Jackbox-style) where games display on a primary screen and players participate via mobile. The MVP game is "Fup og Fakta" (a Fibbage-style lie-and-guess game).
|
||||||
|
|
||||||
|
- Backend: Django 6.0.2 + Django Channels (WebSockets) + Redis
|
||||||
|
- Frontend: Angular 19 shell + shared TypeScript API client library
|
||||||
|
- Database: MySQL (SQLite fallback for dev)
|
||||||
|
- Deployment: Proxmox LXC containers (not Docker)
|
||||||
|
|
||||||
|
## Commands
|
||||||
|
|
||||||
|
### Backend (Django)
|
||||||
|
```bash
|
||||||
|
python manage.py runserver # Dev server
|
||||||
|
python manage.py migrate # Apply migrations
|
||||||
|
python manage.py test # Run all backend tests
|
||||||
|
python manage.py test lobby # Run tests for a single app
|
||||||
|
python manage.py shell # Django shell
|
||||||
|
```
|
||||||
|
|
||||||
|
### Frontend — API client (`/frontend`)
|
||||||
|
```bash
|
||||||
|
cd frontend
|
||||||
|
npm install
|
||||||
|
npm test # Vitest unit tests
|
||||||
|
npm run build # TypeScript compile check (--noEmit)
|
||||||
|
```
|
||||||
|
|
||||||
|
### Frontend — Angular shell (`/frontend/angular`)
|
||||||
|
```bash
|
||||||
|
cd frontend/angular
|
||||||
|
npm install
|
||||||
|
npm start # Dev server (ng serve)
|
||||||
|
npm run build # Production build
|
||||||
|
npm run test # Vitest unit tests
|
||||||
|
```
|
||||||
|
|
||||||
|
### i18n validation
|
||||||
|
```bash
|
||||||
|
python scripts/check_i18n_drift.py # Check for key drift between locales
|
||||||
|
```
|
||||||
|
|
||||||
|
## Architecture
|
||||||
|
|
||||||
|
### Backend apps
|
||||||
|
|
||||||
|
| App | Purpose |
|
||||||
|
|-----|---------|
|
||||||
|
| `partyhub/` | Main Django project — settings, root URLs, ASGI/WSGI, i18n bootstrap |
|
||||||
|
| `lobby/` | Session & player management — create/join session, locale-aware error responses |
|
||||||
|
| `fupogfakta/` | Game logic — all domain models, score calculation (server-authoritative) |
|
||||||
|
| `realtime/` | WebSocket event layer (stub) |
|
||||||
|
| `voice/` | Voice/TTS interface (stub, Phase 2) |
|
||||||
|
| `core_admin/` | Health endpoint (`/healthz`), global admin |
|
||||||
|
|
||||||
|
**Key domain models** (all in `fupogfakta/models.py`): `GameSession`, `Player`, `Category`, `Question`, `RoundConfig`, `RoundQuestion`, `LieAnswer`, `Guess`, `ScoreEvent`.
|
||||||
|
|
||||||
|
Score calculation is server-side only. `ScoreEvent` provides an auditable trail of all point changes.
|
||||||
|
|
||||||
|
### Frontend layers
|
||||||
|
|
||||||
|
1. **Shared API client** (`frontend/src/`) — pure TypeScript, framework-agnostic. Defines all API types (`api/types.ts`) and HTTP client abstraction (`api/client.ts`).
|
||||||
|
2. **Angular shell** (`frontend/angular/`) — Angular 19 standalone components (no NgModules), hash-based routing. `host-shell.component` for the presenter screen; `player-shell.component` for mobile players.
|
||||||
|
|
||||||
|
The Angular shell consumes the shared client via `frontend/src/api/angular-client.ts`.
|
||||||
|
|
||||||
|
### Real-time flow
|
||||||
|
|
||||||
|
`LOBBY → LIE → GUESS → REVEAL → FINISHED` — phase transitions broadcast a `PhaseViewModel` to all connected clients via WebSocket. Clients are read-only; only the server is authoritative for state.
|
||||||
|
|
||||||
|
### i18n
|
||||||
|
|
||||||
|
- **Single source of truth**: `shared/i18n/lobby.json` (keys in both `en` and `da`)
|
||||||
|
- Loaded once at startup with LRU cache (`partyhub/i18n_bootstrap.py`)
|
||||||
|
- Key naming: domain-first — `frontend.ui.host.*`, `frontend.ui.player.*`, `backend.errors.*`, `backend.error_codes.*`
|
||||||
|
- Locale resolved from `Accept-Language` header; missing key returns key + logs warning; missing translation falls back to `en`
|
||||||
|
|
||||||
|
## Key Conventions
|
||||||
|
|
||||||
|
### Errors
|
||||||
|
Backend error responses use stable machine-readable codes (`backend.error_codes.*`) with separately localized messages. Never couple error code strings to locale.
|
||||||
|
|
||||||
|
### Game constraints (MVP)
|
||||||
|
- 3–12 players per session
|
||||||
|
- Session codes: 6-char alphanumeric (no 0/O/1/I/L)
|
||||||
|
- Anti-cheat: no duplicate lies, lies cannot match the correct answer, answer order randomized
|
||||||
|
|
||||||
|
### Git workflow
|
||||||
|
- `main`: stable baseline
|
||||||
|
- `feature/<name>`: development branches
|
||||||
|
- `release/vX.Y.Z`: release preparation
|
||||||
|
- Release: merge → create release branch → update `VERSION` + `CHANGELOG.md` → tag → push
|
||||||
|
|
||||||
|
### TypeScript
|
||||||
|
Strict mode required. Target ES2022. API response interfaces in `frontend/src/api/types.ts` must match backend responses exactly.
|
||||||
|
|
||||||
|
### Database
|
||||||
|
Use `ForeignKey` with explicit `on_delete` (`PROTECT`/`CASCADE`/`SET_NULL`). Add `db_index=True` on frequently queried fields. Migrations are auto-generated by Django and versioned in `migrations/`.
|
||||||
|
|
||||||
|
## Environment Variables
|
||||||
|
|
||||||
|
```
|
||||||
|
DJANGO_SECRET_KEY, DJANGO_DEBUG, DJANGO_ALLOWED_HOSTS
|
||||||
|
DB_ENGINE, DB_NAME, DB_USER, DB_PASSWORD, DB_HOST, DB_PORT
|
||||||
|
CHANNEL_REDIS_HOST, CHANNEL_REDIS_PORT
|
||||||
|
USE_SPA_UI (fallback: WPP_SPA_ENABLED)
|
||||||
|
WPP_SPA_ASSET_BASE, WPP_SPA_ASSET_VERSION
|
||||||
|
```
|
||||||
|
|
||||||
|
## Test Files of Note
|
||||||
|
|
||||||
|
- `lobby/tests.py` — comprehensive Django TestCase coverage for session/player/i18n/error flows
|
||||||
|
- `frontend/angular/src/app/api-contract-smoke.spec.ts` — API contract smoke tests
|
||||||
|
- `frontend/angular/src/app/lobby-i18n.spec.ts` — i18n parity checks
|
||||||
|
- `frontend/tests/lobby-loader.parity.test.ts` — shared i18n loader parity
|
||||||
71
PROMPT.md
Normal file
71
PROMPT.md
Normal file
@@ -0,0 +1,71 @@
|
|||||||
|
# Ralph Loop: Implement WebSocket push for Weirsøe Party Protocol
|
||||||
|
|
||||||
|
## Context
|
||||||
|
- Project: /home/agw/projects/weirsoe-party-protocol
|
||||||
|
- Backend: Django 6.0.2 + Django Channels + Redis
|
||||||
|
- The full game REST flow is already implemented in lobby/views.py
|
||||||
|
(create_session, join_session, start_round, show_question, submit_lie,
|
||||||
|
mix_answers, submit_guess, calculate_scores, reveal_scoreboard, finish_game)
|
||||||
|
- realtime/ app exists but is a stub (no consumers.py, no routing)
|
||||||
|
- partyhub/settings.py has channels in INSTALLED_APPS but no CHANNEL_LAYERS or routing
|
||||||
|
- PO hard requirement: WebSocket push is mandatory in MVP (no polling)
|
||||||
|
|
||||||
|
## What to build
|
||||||
|
|
||||||
|
### 1. realtime/consumers.py — GameConsumer
|
||||||
|
- AsyncJsonWebsocketConsumer
|
||||||
|
- Connects to group game_{session_code} on connect (session_code from URL)
|
||||||
|
- Player auth: session_token query param validated against Player model
|
||||||
|
- Host auth: query param role=host, no token required for MVP
|
||||||
|
- On disconnect: clean leave from group
|
||||||
|
- Handles incoming message type "ping" -> replies with {"type": "pong"}
|
||||||
|
- Forwards broadcast group events to WebSocket client
|
||||||
|
|
||||||
|
### 2. partyhub/settings.py — CHANNEL_LAYERS
|
||||||
|
Add CHANNEL_LAYERS using channels_redis.core.RedisChannelLayer.
|
||||||
|
Read CHANNEL_REDIS_HOST (default 127.0.0.1) and CHANNEL_REDIS_PORT (default 6379) from env.
|
||||||
|
|
||||||
|
### 3. partyhub/asgi.py — ASGI routing
|
||||||
|
Wire URLRouter so ws/game/<session_code>/ routes to GameConsumer.
|
||||||
|
Keep existing HTTP routing intact.
|
||||||
|
|
||||||
|
### 4. realtime/routing.py
|
||||||
|
Define websocket_urlpatterns list.
|
||||||
|
|
||||||
|
### 5. realtime/broadcast.py — broadcast helper
|
||||||
|
- async def broadcast_phase_event(session_code, event_type, payload)
|
||||||
|
Sends to group game_{session_code} via channel layer.
|
||||||
|
- def sync_broadcast_phase_event(session_code, event_type, payload)
|
||||||
|
Sync wrapper using async_to_sync for calling from sync REST views.
|
||||||
|
|
||||||
|
### 6. lobby/views.py — hook broadcasts into phase transitions
|
||||||
|
After each phase transition, call sync_broadcast_phase_event:
|
||||||
|
- start_round -> phase.lie_started (question prompt + time limit)
|
||||||
|
- show_question -> phase.question_shown (question text)
|
||||||
|
- mix_answers -> phase.guess_started (shuffled answers + time limit)
|
||||||
|
- calculate_scores -> phase.scores_calculated (per-player score delta)
|
||||||
|
- reveal_scoreboard -> phase.scoreboard (ranked player list)
|
||||||
|
- finish_game -> phase.game_over (final rankings)
|
||||||
|
|
||||||
|
### 7. realtime/tests.py — basic tests
|
||||||
|
- Connect/disconnect test using channels.testing.WebsocketCommunicator
|
||||||
|
- Verify a broadcast reaches a connected client
|
||||||
|
|
||||||
|
## Constraints
|
||||||
|
- Keep auth simple: session_token query param for players, unauthenticated host in MVP
|
||||||
|
- Use async_to_sync wrapper for sync REST views calling async broadcast
|
||||||
|
- Do not break existing REST tests (python manage.py test lobby must still pass)
|
||||||
|
- After each file written, run: python manage.py check
|
||||||
|
- Follow existing code style in lobby/views.py
|
||||||
|
|
||||||
|
## Completion criteria
|
||||||
|
Output the exact text: WEBSOCKET COMPLETE
|
||||||
|
|
||||||
|
...when ALL of the following are true:
|
||||||
|
- realtime/consumers.py exists and handles connect/disconnect/ping
|
||||||
|
- realtime/broadcast.py exists with sync_broadcast_phase_event
|
||||||
|
- partyhub/settings.py has CHANNEL_LAYERS configured
|
||||||
|
- partyhub/asgi.py routes ws/game/<code>/ to GameConsumer
|
||||||
|
- All 6 phase transitions in lobby/views.py call sync_broadcast_phase_event
|
||||||
|
- python manage.py check passes with no errors
|
||||||
|
- python manage.py test lobby passes (existing tests not broken)
|
||||||
25
TODO.md
25
TODO.md
@@ -37,8 +37,8 @@ Byg **Weirsøe Party Protocol**: en dansk party-webapp platform ala Jackbox, hvo
|
|||||||
- [x] `core_admin` (global administration)
|
- [x] `core_admin` (global administration)
|
||||||
- [x] `fupogfakta` (Spil 1)
|
- [x] `fupogfakta` (Spil 1)
|
||||||
- [x] `lobby` (room/session/player join flow)
|
- [x] `lobby` (room/session/player join flow)
|
||||||
- [x] `realtime` (channels events, game state broadcast)
|
- [x] `realtime` (app-skelet oprettet — consumers/routing IKKE implementeret endnu)
|
||||||
- [x] `voice` (fælles voice-acting interface)
|
- [x] `voice` (fælles voice-acting interface — stub)
|
||||||
- [x] Miljøfiler (`.env.test`, `.env.prod` skabeloner)
|
- [x] Miljøfiler (`.env.test`, `.env.prod` skabeloner)
|
||||||
- [x] Konfig for MySQL test/prod
|
- [x] Konfig for MySQL test/prod
|
||||||
|
|
||||||
@@ -53,14 +53,15 @@ Byg **Weirsøe Party Protocol**: en dansk party-webapp platform ala Jackbox, hvo
|
|||||||
- [x] `ScoreEvent` (auditérbar pointslog)
|
- [x] `ScoreEvent` (auditérbar pointslog)
|
||||||
|
|
||||||
### Fase 3 — Spilflow `Fup og Fakta`
|
### Fase 3 — Spilflow `Fup og Fakta`
|
||||||
- [x] Lobby: host opretter session, spillere joiner via kode
|
- [x] Lobby: host opretter session, spillere joiner via kode (REST)
|
||||||
- [x] Runde starter med kategori
|
- [x] Runde starter med kategori (REST)
|
||||||
- [x] Spørgsmål vises -> alle skriver løgn inden X sek
|
- [x] Spørgsmål vises -> alle skriver løgn inden X sek (REST)
|
||||||
- [x] System blander korrekt svar + løgne
|
- [x] System blander korrekt svar + løgne (persisted i JSONField, anti-cheat dedup)
|
||||||
- [x] Guessfase: alle gætter inden Z sek
|
- [x] Guessfase: alle gætter inden Z sek (REST)
|
||||||
- [x] Pointudregning (konfigurerbar pr. runde)
|
- [x] Pointudregning (konfigurerbar pr. runde, ScoreEvent audit trail)
|
||||||
- [x] Scoreboard + næste spørgsmål/runde
|
- [x] Scoreboard + næste spørgsmål/runde (REST)
|
||||||
- [x] Slutresultat
|
- [x] Slutresultat (REST)
|
||||||
|
- [x] **WebSocket push af phase-events til host + spillere** (GameConsumer + broadcast.py, InMemoryChannelLayer i tests)
|
||||||
|
|
||||||
### Fase 4 — Voice-acting (platformkrav)
|
### Fase 4 — Voice-acting (platformkrav)
|
||||||
- [ ] Definér TTS provider-interface
|
- [ ] Definér TTS provider-interface
|
||||||
@@ -103,10 +104,10 @@ Byg **Weirsøe Party Protocol**: en dansk party-webapp platform ala Jackbox, hvo
|
|||||||
- [ ] Migrations + static + health checks
|
- [ ] Migrations + static + health checks
|
||||||
|
|
||||||
### Backlog — Need-to-have / Nice-to-have
|
### Backlog — Need-to-have / Nice-to-have
|
||||||
- [ ] (Need-to-have) Persistér mixed svarrækkefølge pr. round question, så alle spillere ser samme rækkefølge ved reconnect/refresh
|
- [x] (Need-to-have) Persistér mixed svarrækkefølge pr. round question — DONE (JSONField + migration 0003 + test)
|
||||||
- [x] (Need-to-have) Tilføj spiller-auth/session-token for submit_lie (pt. baseret på player_id i payload)
|
- [x] (Need-to-have) Tilføj spiller-auth/session-token for submit_lie (pt. baseret på player_id i payload)
|
||||||
- [ ] (Nice-to-have) Endpoint til status/progress i løgnfasen (antal indsendt ud af total)
|
- [ ] (Nice-to-have) Endpoint til status/progress i løgnfasen (antal indsendt ud af total)
|
||||||
- [ ] (Need-to-have) [Fejltype: CI/lint F401] [Fil/område: core_admin/*, fupogfakta/tests.py+views.py, lobby/admin.py+models.py, realtime/*, voice/*] [Branch/PR: feature/f3-lobby-create-join, feature/fase0-mvp-fup-og-fakta, feature/lobby-mvp (ingen åbne PRs fundet)] Fjern ubrugte scaffold-imports (eller kør ruff check --fix) så quality gate kan blive grøn før merge.
|
- [ ] (Need-to-have) Fjern ubrugte scaffold-imports i core_admin/*, realtime/*, voice/*, fupogfakta/views.py (kør `ruff check --fix`) så CI quality gate er grøn
|
||||||
- [x] (Need-to-have) [Issue #251] Release-often lane: SPA MVP opdelt i 3 merge-klare micro-PR batches (plan + acceptance criteria dokumenteret i `docs/ISSUE-251-RELEASE-OFTEN-SPA-MVP-BATCH-PLAN.md`).
|
- [x] (Need-to-have) [Issue #251] Release-often lane: SPA MVP opdelt i 3 merge-klare micro-PR batches (plan + acceptance criteria dokumenteret i `docs/ISSUE-251-RELEASE-OFTEN-SPA-MVP-BATCH-PLAN.md`).
|
||||||
- [ ] (Need-to-have) Rate limiting på join/submit endpoints
|
- [ ] (Need-to-have) Rate limiting på join/submit endpoints
|
||||||
- [ ] (Need-to-have) Session-kode brute-force beskyttelse
|
- [ ] (Need-to-have) Session-kode brute-force beskyttelse
|
||||||
|
|||||||
27
docs/ISSUE-252-REACT-FALLBACK-TRIGGERS-ARTIFACT.md
Normal file
27
docs/ISSUE-252-REACT-FALLBACK-TRIGGERS-ARTIFACT.md
Normal file
@@ -0,0 +1,27 @@
|
|||||||
|
# ISSUE-252 Artifact — React fallback trigger criteria (delivery-blocking only)
|
||||||
|
|
||||||
|
Issue: **#252**
|
||||||
|
|
||||||
|
## Leveret ændring
|
||||||
|
Dokumentationen i `docs/spa-cutover-flag.md` er opdateret med en dedikeret sektion:
|
||||||
|
- **React fallback trigger-kriterier (kun delivery-blocking)**
|
||||||
|
- klare **tilladelses-kriterier** (alle skal være opfyldt)
|
||||||
|
- tydelige **scope-limits**
|
||||||
|
- eksplicitte **ikke-tilladte** anvendelser
|
||||||
|
|
||||||
|
## Acceptance mapping
|
||||||
|
1. **Clear trigger criteria**
|
||||||
|
- Definerer præcist hvornår fallback er tilladt:
|
||||||
|
- aktiv delivery-blocking fejl i Angular SPA
|
||||||
|
- ingen sikker Angular-fix inden release-vinduet
|
||||||
|
- rollback alene er utilstrækkelig for leveringsbehovet
|
||||||
|
- beslutning + evidens logges eksplicit (inkl. issue/incident-reference)
|
||||||
|
2. **Scope limits**
|
||||||
|
- Begrænset til delivery-blocking host/player-paths.
|
||||||
|
- Ingen feature-bundling eller ikke-kritiske ændringer.
|
||||||
|
- Midlertidig anvendelse kun i aktiv incident/release-vindue.
|
||||||
|
3. **When fallback is allowed**
|
||||||
|
- Kun når alle trigger-kriterier er opfyldt og dokumenteret.
|
||||||
|
|
||||||
|
## Resultat
|
||||||
|
Issue #252 er dokumenteret med operationelle guardrails, så React fallback kun bruges i kontrollerede, leveringsblokerende situationer.
|
||||||
36
docs/ISSUE-278-SMOKE-E2E-GATE-ARTIFACT.md
Normal file
36
docs/ISSUE-278-SMOKE-E2E-GATE-ARTIFACT.md
Normal file
@@ -0,0 +1,36 @@
|
|||||||
|
# Issue #278 Artifact — smoke/e2e gate for da+en locale flow and primary-only audio
|
||||||
|
|
||||||
|
## Scope
|
||||||
|
Acceptance for `[READY][#175][P4]`:
|
||||||
|
1. Verify one MVP host+player smoke run in `en`.
|
||||||
|
2. Verify one MVP host+player smoke run in `da`.
|
||||||
|
3. Verify audio routing remains `primary-device only` so phone/player clients never take playback ownership.
|
||||||
|
|
||||||
|
Dette er en gate-/evidensleverance. Ingen ny produktfunktion ud over test/verifikation.
|
||||||
|
|
||||||
|
## Implemented smoke gate
|
||||||
|
Angular smoke spec: `frontend/angular/src/app/i18n-mvp-flow-smoke.spec.ts`
|
||||||
|
|
||||||
|
The gate now runs two explicit locale scenarios:
|
||||||
|
- `en`: host refresh/start-round copy + player submit-guess copy
|
||||||
|
- `da`: samme flow med dansk copy
|
||||||
|
|
||||||
|
Audio-policy delen af samme smoke-spec verificerer:
|
||||||
|
- host/primary playback path er uændret før player mount
|
||||||
|
- player mount installerer no-audio guard på secondary device
|
||||||
|
- guard fjernes igen ved unmount, så primary path fortsat er eneste aktive output
|
||||||
|
|
||||||
|
## Recommended verification command
|
||||||
|
Køres fra `frontend/angular`:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
npm test -- --run src/app/i18n-mvp-flow-smoke.spec.ts src/app/lobby-i18n.spec.ts src/app/features/player/player-shell.component.spec.ts
|
||||||
|
```
|
||||||
|
|
||||||
|
## Why this is the gate
|
||||||
|
- `i18n-mvp-flow-smoke.spec.ts` giver en lille, samlet smoke/e2e-lignende verifikation af host+player i begge locale-kontekster.
|
||||||
|
- `lobby-i18n.spec.ts` holder shared locale propagation + contract fallback grøn.
|
||||||
|
- `player-shell.component.spec.ts` dækker den dybere regressionflade for audio-guard på secondary device.
|
||||||
|
|
||||||
|
## Conclusion
|
||||||
|
Gate’en verificerer nu eksplicit begge locale-runs (`da` + `en`) og bekræfter primary-only audio routing i MVP-flowet.
|
||||||
272
docs/plans/2026-03-09-fupogfakta-game-engine-design.md
Normal file
272
docs/plans/2026-03-09-fupogfakta-game-engine-design.md
Normal file
@@ -0,0 +1,272 @@
|
|||||||
|
# Design: Fup og Fakta — Game Engine & Platform Architecture
|
||||||
|
|
||||||
|
**Date:** 2026-03-09
|
||||||
|
**Status:** Approved
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Overview
|
||||||
|
|
||||||
|
Build a working Fup og Fakta game (Fibbage-style) on top of a **pluggable game platform**. The platform handles sessions, players, WebSocket push, and Celery-driven timers. Each game is a self-contained **cartridge** that implements a shared driver interface and owns its own models, config, and phase logic.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Platform Architecture
|
||||||
|
|
||||||
|
```
|
||||||
|
partyhub/ Django project — settings, Celery app, ASGI
|
||||||
|
lobby/ Platform layer — sessions, players, GameRun, timer dispatch
|
||||||
|
realtime/ WebSocket consumers (already built)
|
||||||
|
fupogfakta/ Game cartridge #1
|
||||||
|
future_game/ Game cartridge #N (same interface)
|
||||||
|
```
|
||||||
|
|
||||||
|
### Platform provides (`lobby/`)
|
||||||
|
|
||||||
|
#### Models
|
||||||
|
|
||||||
|
**`GameSession`** (exists, minor additions)
|
||||||
|
- `game_type` (CharField) — e.g. `"fupogfakta"`
|
||||||
|
- `host` (FK → User)
|
||||||
|
- `code` (6-char session code)
|
||||||
|
- `status` (LOBBY / ACTIVE / FINISHED)
|
||||||
|
- `config_id` / `config_snapshot` — see Config section
|
||||||
|
|
||||||
|
**`GameRun`** (new — ephemeral, deleted on game exit)
|
||||||
|
- `session` (OneToOne → GameSession)
|
||||||
|
- `current_state` (CharField — game-defined state string)
|
||||||
|
- `phase_deadline` (DateTimeField, nullable)
|
||||||
|
- `is_paused` (BooleanField, default False)
|
||||||
|
- `paused_remaining_seconds` (FloatField, nullable)
|
||||||
|
- `celery_task_id` (CharField, nullable)
|
||||||
|
- `state_data` (JSONField) — game-specific snapshot for current phase
|
||||||
|
|
||||||
|
**`Player`** (exists)
|
||||||
|
- `session`, `nickname`, `score`, `session_token`, `is_connected`
|
||||||
|
|
||||||
|
#### GameDriver interface
|
||||||
|
|
||||||
|
Each cartridge implements:
|
||||||
|
|
||||||
|
```python
|
||||||
|
class GameDriver:
|
||||||
|
game_type: str # e.g. "fupogfakta"
|
||||||
|
|
||||||
|
def on_game_start(session, run, config) -> PhaseResult
|
||||||
|
def on_timer_expired(session, run, config) -> PhaseResult
|
||||||
|
def on_pause(session, run) -> None
|
||||||
|
def on_resume(session, run) -> None
|
||||||
|
def on_exit(session, run) -> None # must clean up all game data
|
||||||
|
def get_ws_payload(state, state_data) -> dict
|
||||||
|
```
|
||||||
|
|
||||||
|
`PhaseResult` = `(next_state: str, duration_seconds: int | None, broadcast_payload: dict)`
|
||||||
|
|
||||||
|
#### Celery task
|
||||||
|
|
||||||
|
```python
|
||||||
|
@app.task
|
||||||
|
def handle_timer_expired(run_id: int, expected_state: str):
|
||||||
|
# If run no longer exists or state has changed → stale task, ignore
|
||||||
|
# Call driver.on_timer_expired(session, run, config)
|
||||||
|
# Apply PhaseResult: update run, broadcast via channel layer, schedule next task
|
||||||
|
```
|
||||||
|
|
||||||
|
`expected_state` prevents stale tasks from firing after pause/resume or manual state changes.
|
||||||
|
|
||||||
|
#### REST endpoints (platform-level)
|
||||||
|
|
||||||
|
- `POST /sessions/{code}/play` — start or resume
|
||||||
|
- `POST /sessions/{code}/pause` — pause current phase timer
|
||||||
|
- `POST /sessions/{code}/exit` — end game, delete GameRun + all game data
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Configuration System
|
||||||
|
|
||||||
|
### Base config model (`partyhub/`)
|
||||||
|
|
||||||
|
```python
|
||||||
|
class BaseGameConfig(models.Model):
|
||||||
|
class Meta:
|
||||||
|
abstract = True
|
||||||
|
|
||||||
|
name = models.CharField(max_length=100) # "Quick game", "Full evening"
|
||||||
|
user = models.ForeignKey(User, null=True, ...) # null = system default
|
||||||
|
is_default = models.BooleanField(default=False)
|
||||||
|
created_at = models.DateTimeField(auto_now_add=True)
|
||||||
|
```
|
||||||
|
|
||||||
|
### Game-specific config (`fupogfakta/`)
|
||||||
|
|
||||||
|
```python
|
||||||
|
class FupOgFaktaConfig(BaseGameConfig):
|
||||||
|
num_rounds = PositiveIntegerField(default=3)
|
||||||
|
questions_per_round = PositiveIntegerField(default=3)
|
||||||
|
min_players = PositiveIntegerField(default=2)
|
||||||
|
max_players = PositiveIntegerField(default=8)
|
||||||
|
lie_seconds = PositiveIntegerField(default=45)
|
||||||
|
guess_seconds = PositiveIntegerField(default=30)
|
||||||
|
reveal_seconds_per_lie = PositiveIntegerField(default=8)
|
||||||
|
scoreboard_recap_seconds = PositiveIntegerField(default=10)
|
||||||
|
# Escalating scoring per round (stored as arrays or separate fields)
|
||||||
|
points_correct = JSONField(default=[1500, 3000, 4500])
|
||||||
|
points_bluff = JSONField(default=[500, 1000, 1500])
|
||||||
|
# Reaction bonus (static, feeds post-game awards only)
|
||||||
|
reaction_bonus = IntegerField(default=5)
|
||||||
|
```
|
||||||
|
|
||||||
|
### Default resolution at session start
|
||||||
|
|
||||||
|
1. User has `is_default=True` row for this game type → use that
|
||||||
|
2. System default (`user=null, is_default=True`) — set in Django admin
|
||||||
|
3. Model field `default=` values (hardcoded)
|
||||||
|
|
||||||
|
User can have **multiple named presets** (one-to-many). When starting a session they choose which to use (or it auto-selects their default). The chosen config's values are **snapshotted into `GameRun.state_data`** at game start — immutable for the life of the session.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Fup og Fakta — Game States
|
||||||
|
|
||||||
|
```
|
||||||
|
LOBBY
|
||||||
|
│ (host presses Play)
|
||||||
|
▼
|
||||||
|
LIE_PHASE timer: lie_seconds
|
||||||
|
│ (all submitted OR timer expires)
|
||||||
|
▼
|
||||||
|
GUESS_PHASE timer: guess_seconds
|
||||||
|
│ (timer expires — no mercy)
|
||||||
|
▼
|
||||||
|
REVEAL_LIE_{n} timer: reveal_seconds_per_lie (one per lie with ≥1 guess)
|
||||||
|
│ → score liar incrementally as each is shown
|
||||||
|
▼
|
||||||
|
REVEAL_TRUTH timer: reveal_seconds_per_lie
|
||||||
|
│ → score correct guessers
|
||||||
|
▼
|
||||||
|
SCOREBOARD_RECAP timer: scoreboard_recap_seconds
|
||||||
|
│
|
||||||
|
├─ more questions in round → back to LIE_PHASE (next question)
|
||||||
|
├─ round done, more rounds → back to LIE_PHASE (next round, next category)
|
||||||
|
└─ all rounds done → POST_GAME_AWARDS
|
||||||
|
timer: configurable
|
||||||
|
→ FINISHED (GameRun deleted, GameSession status = FINISHED)
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Fup og Fakta — Phase Details
|
||||||
|
|
||||||
|
### LIE_PHASE
|
||||||
|
- Question shown to all clients via WebSocket (`phase.lie_started` event)
|
||||||
|
- Players submit lie via `POST /fupogfakta/{code}/lie`
|
||||||
|
- **If lie matches correct answer (case-insensitive):** return `error_code: lie_matches_correct_answer` — player prompted again, does not consume their submission
|
||||||
|
- Anonymous to other players during this phase
|
||||||
|
- `state_data` tracks: question id, round number, how many have submitted (for progress display on host screen)
|
||||||
|
- Timer expires → transition to GUESS_PHASE regardless of how many submitted
|
||||||
|
|
||||||
|
### GUESS_PHASE
|
||||||
|
- Answers mixed (lies + truth, deduped) broadcast to all clients (`phase.guess_started`)
|
||||||
|
- Players guess via `POST /fupogfakta/{code}/guess`
|
||||||
|
- **After selecting:** player can react to other lies with 👍 😂 ❤️ etc. until timer expires. Cannot change guess.
|
||||||
|
- Reactions stored in `LieReaction` model (player, lie, reaction_type)
|
||||||
|
- Timer expires → transition to first REVEAL_LIE (or REVEAL_TRUTH if no lies had guesses)
|
||||||
|
|
||||||
|
### REVEAL_LIE_{n}
|
||||||
|
- One Celery task per lie to reveal (only lies with ≥1 guesser)
|
||||||
|
- Broadcast: which lie, who wrote it, who guessed it (`phase.reveal_lie`)
|
||||||
|
- Score awarded to liar: `points_bluff[round_index] × guesser_count`
|
||||||
|
- Score broadcast immediately (`phase.score_delta`)
|
||||||
|
- Skipped lies (0 guesses): not shown at all
|
||||||
|
|
||||||
|
### REVEAL_TRUTH
|
||||||
|
- Broadcast: correct answer, who guessed correctly (`phase.reveal_truth`)
|
||||||
|
- Score awarded: `points_correct[round_index]` per correct guesser
|
||||||
|
- Also show reaction totals on each lie during this phase
|
||||||
|
|
||||||
|
### SCOREBOARD_RECAP
|
||||||
|
- Full leaderboard broadcast (`phase.scoreboard`)
|
||||||
|
- Auto-advances to next question, next round, or post-game
|
||||||
|
|
||||||
|
### POST_GAME_AWARDS
|
||||||
|
- Computed from `LieReaction` aggregate:
|
||||||
|
- "Most Hilarious Liar" — most 😂 reactions total
|
||||||
|
- "Most Beloved Lie" — most ❤️ reactions on a single lie
|
||||||
|
- etc. (extensible)
|
||||||
|
- Broadcast as `phase.awards`
|
||||||
|
- Then FINISHED → GameRun deleted, all session game data wiped
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Fup og Fakta — Models
|
||||||
|
|
||||||
|
**Existing (keep):** `Category`, `Question`, `RoundQuestion`, `LieAnswer`, `Guess`
|
||||||
|
|
||||||
|
**Remove:** `ScoreEvent` (no audit trail needed — game state is ephemeral)
|
||||||
|
|
||||||
|
**New:**
|
||||||
|
```python
|
||||||
|
class LieReaction(models.Model):
|
||||||
|
lie = ForeignKey(LieAnswer, on_delete=CASCADE)
|
||||||
|
player = ForeignKey(Player, on_delete=CASCADE)
|
||||||
|
reaction = CharField(max_length=20) # "laugh", "heart", "fire", etc.
|
||||||
|
created_at = auto_now_add
|
||||||
|
class Meta:
|
||||||
|
unique_together = [("lie", "player", "reaction")]
|
||||||
|
```
|
||||||
|
|
||||||
|
**Modify `RoundQuestion`:**
|
||||||
|
- Add `reveal_order` (PositiveIntegerField, nullable) — set when GUESS_PHASE ends, determines reveal sequence
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Pause / Resume
|
||||||
|
|
||||||
|
- **Pause:** compute `remaining = phase_deadline - now`, store in `paused_remaining_seconds`, set `is_paused=True`, revoke Celery task by `celery_task_id`
|
||||||
|
- **Resume:** set `phase_deadline = now + paused_remaining_seconds`, schedule new Celery task, clear pause fields
|
||||||
|
- Stale task guard: every Celery task checks `expected_state == run.current_state` before firing
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Host Controls (Session Owner Only)
|
||||||
|
|
||||||
|
| Action | Effect |
|
||||||
|
|--------|--------|
|
||||||
|
| Play | Starts game from LOBBY, or resumes from paused |
|
||||||
|
| Pause | Freezes current phase timer, broadcasts `phase.paused` |
|
||||||
|
| Exit | Ends game immediately, deletes GameRun + all game data |
|
||||||
|
|
||||||
|
Cannot skip. Cannot manually advance phases.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## WebSocket Event Reference
|
||||||
|
|
||||||
|
| Event | Triggered by | Payload |
|
||||||
|
|-------|-------------|---------|
|
||||||
|
| `phase.lie_started` | LIE_PHASE start | question prompt, deadline, round info |
|
||||||
|
| `phase.lie_progress` | Each lie submitted | n_submitted / n_players (no names) |
|
||||||
|
| `phase.guess_started` | GUESS_PHASE start | mixed answers, deadline |
|
||||||
|
| `phase.reveal_lie` | REVEAL_LIE_{n} | lie text, author, guessers, score delta |
|
||||||
|
| `phase.reveal_truth` | REVEAL_TRUTH | correct answer, correct guessers, score delta |
|
||||||
|
| `phase.scoreboard` | SCOREBOARD_RECAP | full leaderboard |
|
||||||
|
| `phase.awards` | POST_GAME_AWARDS | award winners |
|
||||||
|
| `phase.paused` | Pause | remaining_seconds |
|
||||||
|
| `phase.resumed` | Resume | new deadline |
|
||||||
|
| `phase.game_over` | FINISHED | final leaderboard |
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Data Lifecycle
|
||||||
|
|
||||||
|
All game session data (`GameRun`, `RoundQuestion`, `LieAnswer`, `Guess`, `LieReaction`, `Player`) is **deleted when host exits or game reaches FINISHED**. `GameSession` row is kept (with status=FINISHED) for the session code uniqueness constraint. `Category` and `Question` content is permanent.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Not In Scope (This Implementation)
|
||||||
|
|
||||||
|
- TTS / read-aloud (Fase 4, deferred)
|
||||||
|
- Reconnect recovery after server restart (game is gone if server dies)
|
||||||
|
- Spectator/viewer mode (post-MVP)
|
||||||
|
- Rate limiting on endpoints (backlog)
|
||||||
|
- Bulk question import (Fase 5)
|
||||||
2180
docs/plans/2026-03-09-fupogfakta-implementation-plan.md
Normal file
2180
docs/plans/2026-03-09-fupogfakta-implementation-plan.md
Normal file
File diff suppressed because it is too large
Load Diff
@@ -59,6 +59,31 @@ Trin-for-trin:
|
|||||||
|
|
||||||
Target: rollback + sanity-verifikation inden for 10 minutter.
|
Target: rollback + sanity-verifikation inden for 10 minutter.
|
||||||
|
|
||||||
|
## React fallback trigger-kriterier (kun delivery-blocking)
|
||||||
|
Formål: React fallback må kun bruges som kortvarig leverings-sikring, når release ellers er blokeret.
|
||||||
|
|
||||||
|
### Hvornår fallback er tilladt
|
||||||
|
Alle punkter skal være opfyldt:
|
||||||
|
1. **Delivery-blocking fejl i Angular SPA**
|
||||||
|
- Host/player kerneflow kan ikke leveres i release-vinduet (fx login/join/start/round/scoreboard stopper).
|
||||||
|
2. **Ingen hurtig Angular-fix inden for release-vinduet**
|
||||||
|
- Teamet har vurderet at patch + verificering ikke kan nås sikkert i tide.
|
||||||
|
3. **Rollback alene løser ikke leveringsbehovet**
|
||||||
|
- `USE_SPA_UI=false` (legacy) er enten utilstrækkelig for den konkrete leverance eller allerede verificeret som ikke tilstrækkelig.
|
||||||
|
4. **Beslutning er eksplicit logget**
|
||||||
|
- Trigger, impact, UTC-tid, ansvarlig, issue/incident-reference og plan for tilbagevenden til Angular er dokumenteret i release/smoke artifact.
|
||||||
|
|
||||||
|
### Scope-limits for fallback
|
||||||
|
- Fallback omfatter kun **delivery-blocking host/player-paths**.
|
||||||
|
- Ingen nye features, UX-forbedringer eller ikke-kritiske ændringer må bundtes ind i fallback.
|
||||||
|
- Fallback er **midlertidig** og gælder kun for aktiv incident/release-vindue.
|
||||||
|
- Når blocker er fjernet, skal miljøet tilbage på standard cutover-spor (Angular + `USE_SPA_UI` styring).
|
||||||
|
|
||||||
|
### Ikke tilladt
|
||||||
|
- Proaktiv fallback "for en sikkerheds skyld" uden aktiv blocker.
|
||||||
|
- Brug af fallback til at omgå normale kvalitetsgates eller testkrav.
|
||||||
|
- Langvarig drift i fallback-mode uden dokumenteret blocker og opfølgningsplan.
|
||||||
|
|
||||||
## Verifikation
|
## Verifikation
|
||||||
- Flag OFF: `UiScreenTests.test_legacy_templates_are_used_when_spa_flag_is_off`
|
- Flag OFF: `UiScreenTests.test_legacy_templates_are_used_when_spa_flag_is_off`
|
||||||
- Flag ON (host): `UiScreenTests.test_host_screen_can_render_angular_shell_when_feature_flag_enabled`
|
- Flag ON (host): `UiScreenTests.test_host_screen_can_render_angular_shell_when_feature_flag_enabled`
|
||||||
|
|||||||
@@ -262,5 +262,26 @@ describe('HostShellComponent gameplay wiring', () => {
|
|||||||
await component.refreshSession();
|
await component.refreshSession();
|
||||||
|
|
||||||
expect(replaceState).toHaveBeenCalledWith(null, '', '#/host/guess/ABCD12');
|
expect(replaceState).toHaveBeenCalledWith(null, '', '#/host/guess/ABCD12');
|
||||||
|
expect(component.canStartRound).toBe(false);
|
||||||
|
expect(component.canShowQuestion).toBe(false);
|
||||||
|
expect(component.canMixAnswers).toBe(false);
|
||||||
|
expect(component.canCalculateScores).toBe(true);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('uses phase_view_model to keep host action surface phase-specific', async () => {
|
||||||
|
const component = new HostShellComponent();
|
||||||
|
|
||||||
|
expect(component.canStartRound).toBe(true);
|
||||||
|
expect(component.canShowQuestion).toBe(false);
|
||||||
|
|
||||||
|
component.session = sessionDetailPayload('lie') as any;
|
||||||
|
expect(component.canStartRound).toBe(false);
|
||||||
|
expect(component.canShowQuestion).toBe(true);
|
||||||
|
expect(component.canMixAnswers).toBe(true);
|
||||||
|
|
||||||
|
component.session = sessionDetailPayload('reveal') as any;
|
||||||
|
expect(component.canRevealScoreboard).toBe(true);
|
||||||
|
expect(component.canStartNextRound).toBe(false);
|
||||||
|
expect(component.canFinishGame).toBe(false);
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|||||||
@@ -11,6 +11,17 @@ interface SessionDetail {
|
|||||||
session: { code: string; status: string; current_round: number };
|
session: { code: string; status: string; current_round: number };
|
||||||
round_question: { id: number; prompt: string; answers: Array<{ text: string }> } | null;
|
round_question: { id: number; prompt: string; answers: Array<{ text: string }> } | null;
|
||||||
players: Array<{ id: number; nickname: string; score: number }>;
|
players: Array<{ id: number; nickname: string; score: number }>;
|
||||||
|
phase_view_model?: {
|
||||||
|
host?: {
|
||||||
|
can_start_round?: boolean;
|
||||||
|
can_show_question?: boolean;
|
||||||
|
can_mix_answers?: boolean;
|
||||||
|
can_calculate_scores?: boolean;
|
||||||
|
can_reveal_scoreboard?: boolean;
|
||||||
|
can_start_next_round?: boolean;
|
||||||
|
can_finish_game?: boolean;
|
||||||
|
};
|
||||||
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
type LeaderboardEntry = ScoreboardResponse['leaderboard'][number];
|
type LeaderboardEntry = ScoreboardResponse['leaderboard'][number];
|
||||||
@@ -25,18 +36,15 @@ type LeaderboardResponse = FinishGameResponse;
|
|||||||
|
|
||||||
<div class="panel" [attr.data-client-has-no-audio-output]="clientHasNoAudioOutput">
|
<div class="panel" [attr.data-client-has-no-audio-output]="clientHasNoAudioOutput">
|
||||||
<label>{{ copy('common.session_code') }} <input [(ngModel)]="sessionCode" /></label>
|
<label>{{ copy('common.session_code') }} <input [(ngModel)]="sessionCode" /></label>
|
||||||
<label>{{ copy('host.category') }} <input [(ngModel)]="categorySlug" /></label>
|
<label *ngIf="canStartRound">{{ copy('host.category') }} <input [(ngModel)]="categorySlug" /></label>
|
||||||
<button (click)="refreshSession()" [disabled]="loading">{{ copy('common.refresh') }}</button>
|
<button (click)="refreshSession()" [disabled]="loading">{{ copy('common.refresh') }}</button>
|
||||||
<button (click)="startRound()" [disabled]="loading">{{ copy('host.start_round') }}</button>
|
<button *ngIf="canStartRound" (click)="startRound()" [disabled]="loading">{{ copy('host.start_round') }}</button>
|
||||||
<button (click)="showQuestion()" [disabled]="loading || !roundQuestionId">{{ copy('host.show_question') }}</button>
|
<button *ngIf="canShowQuestion" (click)="showQuestion()" [disabled]="loading || !roundQuestionId">{{ copy('host.show_question') }}</button>
|
||||||
<button (click)="mixAnswers()" [disabled]="loading || !roundQuestionId">{{ copy('host.mix_answers') }}</button>
|
<button *ngIf="canMixAnswers" (click)="mixAnswers()" [disabled]="loading || !roundQuestionId">{{ copy('host.mix_answers') }}</button>
|
||||||
<button (click)="calculateScores()" [disabled]="loading || !roundQuestionId">{{ copy('host.calculate_scores') }}</button>
|
<button *ngIf="canCalculateScores" (click)="calculateScores()" [disabled]="loading || !roundQuestionId">{{ copy('host.calculate_scores') }}</button>
|
||||||
<button (click)="loadScoreboard()" [disabled]="loading">{{ copy('host.load_scoreboard') }}</button>
|
<button *ngIf="canRevealScoreboard || scoreboardError" (click)="loadScoreboard()" [disabled]="loading">{{ copy(scoreboardError ? 'host.retry_scoreboard' : 'host.load_scoreboard') }}</button>
|
||||||
<button (click)="startNextRound()" [disabled]="loading">{{ copy('host.start_next_round') }}</button>
|
<button *ngIf="canStartNextRound || nextRoundError" (click)="startNextRound()" [disabled]="loading">{{ copy(nextRoundError ? 'host.retry_next_round' : 'host.start_next_round') }}</button>
|
||||||
<button (click)="finishGame()" [disabled]="loading">{{ copy('host.finish_game') }}</button>
|
<button *ngIf="canFinishGame || finishError" (click)="finishGame()" [disabled]="loading">{{ copy(finishError ? 'host.retry_finish' : 'host.finish_game') }}</button>
|
||||||
<button *ngIf="scoreboardError" (click)="loadScoreboard()" [disabled]="loading">{{ copy('host.retry_scoreboard') }}</button>
|
|
||||||
<button *ngIf="nextRoundError" (click)="startNextRound()" [disabled]="loading">{{ copy('host.retry_next_round') }}</button>
|
|
||||||
<button *ngIf="finishError" (click)="finishGame()" [disabled]="loading">{{ copy('host.retry_finish') }}</button>
|
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<p *ngIf="session" class="hint">{{ copy('host.audio_locale_hint') }}: {{ locale }}</p>
|
<p *ngIf="session" class="hint">{{ copy('host.audio_locale_hint') }}: {{ locale }}</p>
|
||||||
@@ -114,6 +122,34 @@ export class HostShellComponent implements OnInit, OnDestroy {
|
|||||||
this.unsubscribeLocale = null;
|
this.unsubscribeLocale = null;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
get canStartRound(): boolean {
|
||||||
|
return Boolean(this.session?.phase_view_model?.host?.can_start_round ?? !this.session);
|
||||||
|
}
|
||||||
|
|
||||||
|
get canShowQuestion(): boolean {
|
||||||
|
return Boolean(this.session?.phase_view_model?.host?.can_show_question);
|
||||||
|
}
|
||||||
|
|
||||||
|
get canMixAnswers(): boolean {
|
||||||
|
return Boolean(this.session?.phase_view_model?.host?.can_mix_answers);
|
||||||
|
}
|
||||||
|
|
||||||
|
get canCalculateScores(): boolean {
|
||||||
|
return Boolean(this.session?.phase_view_model?.host?.can_calculate_scores);
|
||||||
|
}
|
||||||
|
|
||||||
|
get canRevealScoreboard(): boolean {
|
||||||
|
return Boolean(this.session?.phase_view_model?.host?.can_reveal_scoreboard);
|
||||||
|
}
|
||||||
|
|
||||||
|
get canStartNextRound(): boolean {
|
||||||
|
return Boolean(this.session?.phase_view_model?.host?.can_start_next_round);
|
||||||
|
}
|
||||||
|
|
||||||
|
get canFinishGame(): boolean {
|
||||||
|
return Boolean(this.session?.phase_view_model?.host?.can_finish_game);
|
||||||
|
}
|
||||||
|
|
||||||
copy(key: string): string {
|
copy(key: string): string {
|
||||||
return t(key, this.locale);
|
return t(key, this.locale);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -518,4 +518,28 @@ describe('PlayerShellComponent gameplay wiring', () => {
|
|||||||
expect(component.clientHasNoAudioOutput).toBe(false);
|
expect(component.clientHasNoAudioOutput).toBe(false);
|
||||||
});
|
});
|
||||||
|
|
||||||
|
it('keeps phone client controls phase-specific and low-complexity', () => {
|
||||||
|
const component = new PlayerShellComponent();
|
||||||
|
|
||||||
|
expect(component.showJoinControls).toBe(true);
|
||||||
|
expect(component.showLieControls).toBe(false);
|
||||||
|
expect(component.showGuessControls).toBe(false);
|
||||||
|
expect(component.showFinalLeaderboard).toBe(false);
|
||||||
|
|
||||||
|
component.session = sessionDetailPayload('lie') as any;
|
||||||
|
component.playerId = 9;
|
||||||
|
component.sessionToken = 'tok';
|
||||||
|
expect(component.showJoinControls).toBe(false);
|
||||||
|
expect(component.showLieControls).toBe(true);
|
||||||
|
expect(component.showGuessControls).toBe(false);
|
||||||
|
|
||||||
|
component.session = sessionDetailPayload('guess', { answers: ['A', 'B'] }) as any;
|
||||||
|
expect(component.showLieControls).toBe(false);
|
||||||
|
expect(component.showGuessControls).toBe(true);
|
||||||
|
|
||||||
|
component.session = sessionDetailPayload('finished', { players: [{ id: 1, nickname: 'Luna', score: 8 }] }) as any;
|
||||||
|
expect(component.showGuessControls).toBe(false);
|
||||||
|
expect(component.showFinalLeaderboard).toBe(true);
|
||||||
|
});
|
||||||
|
|
||||||
});
|
});
|
||||||
|
|||||||
@@ -11,6 +11,14 @@ interface SessionDetail {
|
|||||||
session: { code: string; status: string; current_round: number };
|
session: { code: string; status: string; current_round: number };
|
||||||
round_question: { id: number; prompt: string; answers: Array<{ text: string }> } | null;
|
round_question: { id: number; prompt: string; answers: Array<{ text: string }> } | null;
|
||||||
players: Array<{ id: number; nickname: string; score: number }>;
|
players: Array<{ id: number; nickname: string; score: number }>;
|
||||||
|
phase_view_model?: {
|
||||||
|
player?: {
|
||||||
|
can_join?: boolean;
|
||||||
|
can_submit_lie?: boolean;
|
||||||
|
can_submit_guess?: boolean;
|
||||||
|
can_view_final_result?: boolean;
|
||||||
|
};
|
||||||
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
type ConnectionState = 'online' | 'reconnecting' | 'offline';
|
type ConnectionState = 'online' | 'reconnecting' | 'offline';
|
||||||
@@ -49,9 +57,9 @@ function resolveLocalStorage(): Storage | undefined {
|
|||||||
|
|
||||||
<div class="panel" [attr.data-client-has-no-audio-output]="clientHasNoAudioOutput">
|
<div class="panel" [attr.data-client-has-no-audio-output]="clientHasNoAudioOutput">
|
||||||
<label>{{ copy('common.session_code') }} <input [(ngModel)]="sessionCode" /></label>
|
<label>{{ copy('common.session_code') }} <input [(ngModel)]="sessionCode" /></label>
|
||||||
<label>{{ copy('player.nickname') }} <input [(ngModel)]="nickname" /></label>
|
<label *ngIf="showJoinControls">{{ copy('player.nickname') }} <input [(ngModel)]="nickname" /></label>
|
||||||
<button (click)="refreshSession()" [disabled]="loading">{{ copy('common.refresh') }}</button>
|
<button (click)="refreshSession()" [disabled]="loading">{{ copy('common.refresh') }}</button>
|
||||||
<button (click)="joinSession()" [disabled]="loading">{{ copy('player.join') }}</button>
|
<button *ngIf="showJoinControls" (click)="joinSession()" [disabled]="loading">{{ copy('player.join') }}</button>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<p *ngIf="connectionState === 'reconnecting'" class="error">
|
<p *ngIf="connectionState === 'reconnecting'" class="error">
|
||||||
@@ -71,26 +79,30 @@ function resolveLocalStorage(): Storage | undefined {
|
|||||||
<p><strong>{{ copy('common.status') }}:</strong> {{ session.session.status }}</p>
|
<p><strong>{{ copy('common.status') }}:</strong> {{ session.session.status }}</p>
|
||||||
<p *ngIf="session.round_question"><strong>{{ copy('common.prompt') }}:</strong> {{ session.round_question.prompt }}</p>
|
<p *ngIf="session.round_question"><strong>{{ copy('common.prompt') }}:</strong> {{ session.round_question.prompt }}</p>
|
||||||
|
|
||||||
<label>{{ copy('player.lie_label') }} <input [(ngModel)]="lieText" [disabled]="loading || session.session.status !== 'lie'" /></label>
|
<ng-container *ngIf="showLieControls">
|
||||||
<button (click)="submitLie()" [disabled]="loading || session.session.status !== 'lie'">{{ copy('player.submit_lie') }}</button>
|
<label>{{ copy('player.lie_label') }} <input [(ngModel)]="lieText" [disabled]="loading" /></label>
|
||||||
<button *ngIf="submitError?.kind === 'lie'" (click)="submitLie()" [disabled]="loading">{{ copy('player.retry_lie_submit') }}</button>
|
<button (click)="submitLie()" [disabled]="loading">{{ copy('player.submit_lie') }}</button>
|
||||||
|
<button *ngIf="submitError?.kind === 'lie'" (click)="submitLie()" [disabled]="loading">{{ copy('player.retry_lie_submit') }}</button>
|
||||||
|
</ng-container>
|
||||||
|
|
||||||
<div class="answers" *ngIf="session.round_question?.answers?.length">
|
<ng-container *ngIf="showGuessControls">
|
||||||
<button
|
<div class="answers" *ngIf="session.round_question?.answers?.length">
|
||||||
type="button"
|
<button
|
||||||
*ngFor="let answer of session.round_question?.answers"
|
type="button"
|
||||||
(click)="selectedGuess = answer.text"
|
*ngFor="let answer of session.round_question?.answers"
|
||||||
[class.active]="selectedGuess === answer.text"
|
(click)="selectedGuess = answer.text"
|
||||||
[disabled]="loading || session.session.status !== 'guess'"
|
[class.active]="selectedGuess === answer.text"
|
||||||
>
|
[disabled]="loading"
|
||||||
{{ answer.text }}
|
>
|
||||||
</button>
|
{{ answer.text }}
|
||||||
</div>
|
</button>
|
||||||
|
</div>
|
||||||
|
|
||||||
<button (click)="submitGuess()" [disabled]="loading || session.session.status !== 'guess' || !selectedGuess">{{ copy('player.submit_guess') }}</button>
|
<button (click)="submitGuess()" [disabled]="loading || !selectedGuess">{{ copy('player.submit_guess') }}</button>
|
||||||
<button *ngIf="submitError?.kind === 'guess'" (click)="submitGuess()" [disabled]="loading">{{ copy('player.retry_guess_submit') }}</button>
|
<button *ngIf="submitError?.kind === 'guess'" (click)="submitGuess()" [disabled]="loading">{{ copy('player.retry_guess_submit') }}</button>
|
||||||
|
</ng-container>
|
||||||
|
|
||||||
<div *ngIf="session.session.status === 'finished' && finalLeaderboard.length">
|
<div *ngIf="showFinalLeaderboard && finalLeaderboard.length">
|
||||||
<h3>{{ copy('player.final_leaderboard') }}</h3>
|
<h3>{{ copy('player.final_leaderboard') }}</h3>
|
||||||
<ol>
|
<ol>
|
||||||
<li *ngFor="let entry of finalLeaderboard">{{ entry.nickname }}: {{ entry.score }}</li>
|
<li *ngFor="let entry of finalLeaderboard">{{ entry.nickname }}: {{ entry.score }}</li>
|
||||||
@@ -300,6 +312,25 @@ export class PlayerShellComponent implements OnInit, OnDestroy {
|
|||||||
}, 3000);
|
}, 3000);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
get showJoinControls(): boolean {
|
||||||
|
if (!this.session) {
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
return Boolean(this.session?.phase_view_model?.player?.can_join && !this.playerId && !this.sessionToken);
|
||||||
|
}
|
||||||
|
|
||||||
|
get showLieControls(): boolean {
|
||||||
|
return Boolean(this.session?.phase_view_model?.player?.can_submit_lie);
|
||||||
|
}
|
||||||
|
|
||||||
|
get showGuessControls(): boolean {
|
||||||
|
return Boolean(this.session?.phase_view_model?.player?.can_submit_guess);
|
||||||
|
}
|
||||||
|
|
||||||
|
get showFinalLeaderboard(): boolean {
|
||||||
|
return Boolean(this.session?.phase_view_model?.player?.can_view_final_result);
|
||||||
|
}
|
||||||
|
|
||||||
get loadingMessage(): string {
|
get loadingMessage(): string {
|
||||||
switch (this.loadingTransition) {
|
switch (this.loadingTransition) {
|
||||||
case 'join':
|
case 'join':
|
||||||
|
|||||||
@@ -4,42 +4,56 @@ import { HostShellComponent } from './features/host/host-shell.component';
|
|||||||
import { PlayerShellComponent } from './features/player/player-shell.component';
|
import { PlayerShellComponent } from './features/player/player-shell.component';
|
||||||
import { setPreferredLocale } from './lobby-i18n';
|
import { setPreferredLocale } from './lobby-i18n';
|
||||||
|
|
||||||
|
function stubShellGlobals(initialLocale: string) {
|
||||||
|
vi.stubGlobal('window', {
|
||||||
|
location: { hash: '', search: '' },
|
||||||
|
history: { state: null, replaceState: vi.fn() },
|
||||||
|
localStorage: { getItem: vi.fn().mockReturnValue(initialLocale), setItem: vi.fn(), removeItem: vi.fn() },
|
||||||
|
sessionStorage: { getItem: vi.fn().mockReturnValue(null), setItem: vi.fn(), removeItem: vi.fn() },
|
||||||
|
addEventListener: vi.fn(),
|
||||||
|
removeEventListener: vi.fn(),
|
||||||
|
});
|
||||||
|
vi.stubGlobal('navigator', { language: `${initialLocale}-US`, onLine: true });
|
||||||
|
}
|
||||||
|
|
||||||
describe('i18n MVP flow smoke (host/player + audio policy)', () => {
|
describe('i18n MVP flow smoke (host/player + audio policy)', () => {
|
||||||
afterEach(() => {
|
afterEach(() => {
|
||||||
vi.restoreAllMocks();
|
vi.restoreAllMocks();
|
||||||
vi.unstubAllGlobals();
|
vi.unstubAllGlobals();
|
||||||
});
|
});
|
||||||
|
|
||||||
it('resolves host/player copy in en and da from shared catalog', () => {
|
it.each([
|
||||||
vi.stubGlobal('window', {
|
{
|
||||||
location: { hash: '', search: '' },
|
locale: 'en',
|
||||||
history: { state: null, replaceState: vi.fn() },
|
hostRefresh: 'Refresh',
|
||||||
localStorage: { getItem: vi.fn().mockReturnValue('en'), setItem: vi.fn(), removeItem: vi.fn() },
|
hostStartRound: 'Start round',
|
||||||
sessionStorage: { getItem: vi.fn().mockReturnValue(null), setItem: vi.fn(), removeItem: vi.fn() },
|
playerSubmitGuess: 'Submit guess',
|
||||||
addEventListener: vi.fn(),
|
},
|
||||||
removeEventListener: vi.fn(),
|
{
|
||||||
});
|
locale: 'da',
|
||||||
vi.stubGlobal('navigator', { language: 'en-US', onLine: true });
|
hostRefresh: 'Opdatér',
|
||||||
|
hostStartRound: 'Start runde',
|
||||||
|
playerSubmitGuess: 'Send gæt',
|
||||||
|
},
|
||||||
|
])('resolves one host/player locale run for $locale', ({ locale, hostRefresh, hostStartRound, playerSubmitGuess }) => {
|
||||||
|
stubShellGlobals(locale);
|
||||||
|
|
||||||
const host = new HostShellComponent();
|
const host = new HostShellComponent();
|
||||||
const player = new PlayerShellComponent();
|
const player = new PlayerShellComponent();
|
||||||
host.ngOnInit();
|
host.ngOnInit();
|
||||||
player.ngOnInit();
|
player.ngOnInit();
|
||||||
|
setPreferredLocale(locale);
|
||||||
|
|
||||||
expect(host.copy('game.host.start_round')).toBe('Start round');
|
expect(host.copy('common.refresh')).toBe(hostRefresh);
|
||||||
expect(player.copy('game.player.submit_guess')).toBe('Submit guess');
|
expect(host.copy('game.host.start_round')).toBe(hostStartRound);
|
||||||
|
expect(player.copy('game.player.submit_guess')).toBe(playerSubmitGuess);
|
||||||
setPreferredLocale('da');
|
|
||||||
|
|
||||||
expect(host.copy('game.host.start_round')).toBe('Start runde');
|
|
||||||
expect(player.copy('game.player.submit_guess')).toBe('Send gæt');
|
|
||||||
|
|
||||||
player.ngOnDestroy();
|
player.ngOnDestroy();
|
||||||
host.ngOnDestroy();
|
host.ngOnDestroy();
|
||||||
});
|
});
|
||||||
|
|
||||||
it('keeps audio routing policy primary-only (client has no audio output)', async () => {
|
it('keeps audio routing primary-only by guarding player playback without muting the host path', async () => {
|
||||||
const originalPlay = vi.fn().mockRejectedValue(new Error('original play'));
|
const originalPlay = vi.fn().mockRejectedValue(new Error('primary host playback'));
|
||||||
const mediaPrototype = { play: originalPlay };
|
const mediaPrototype = { play: originalPlay };
|
||||||
|
|
||||||
vi.stubGlobal('window', {
|
vi.stubGlobal('window', {
|
||||||
@@ -57,7 +71,7 @@ describe('i18n MVP flow smoke (host/player + audio policy)', () => {
|
|||||||
const host = new HostShellComponent();
|
const host = new HostShellComponent();
|
||||||
host.ngOnInit();
|
host.ngOnInit();
|
||||||
|
|
||||||
await expect(mediaPrototype.play()).rejects.toThrow('original play');
|
await expect(mediaPrototype.play()).rejects.toThrow('primary host playback');
|
||||||
|
|
||||||
const player = new PlayerShellComponent();
|
const player = new PlayerShellComponent();
|
||||||
player.ngOnInit();
|
player.ngOnInit();
|
||||||
@@ -66,7 +80,7 @@ describe('i18n MVP flow smoke (host/player + audio policy)', () => {
|
|||||||
|
|
||||||
player.ngOnDestroy();
|
player.ngOnDestroy();
|
||||||
|
|
||||||
await expect(mediaPrototype.play()).rejects.toThrow('original play');
|
await expect(mediaPrototype.play()).rejects.toThrow('primary host playback');
|
||||||
|
|
||||||
host.ngOnDestroy();
|
host.ngOnDestroy();
|
||||||
});
|
});
|
||||||
|
|||||||
@@ -55,8 +55,12 @@
|
|||||||
<p id="hostCriticalPlayers">Spillere: afventer</p>
|
<p id="hostCriticalPlayers">Spillere: afventer</p>
|
||||||
<p id="hostCriticalRound">Aktiv round question: afventer</p>
|
<p id="hostCriticalRound">Aktiv round question: afventer</p>
|
||||||
</section>
|
</section>
|
||||||
<pre id="out">Klar.</pre>
|
<pre id="out">Ready.</pre>
|
||||||
|
{{ lobby_i18n|json_script:"wppHostI18n" }}
|
||||||
<script>
|
<script>
|
||||||
|
var WPP_HOST_LOCALE="{{ shell_locale|default:'en'|escapejs }}";
|
||||||
|
var WPP_HOST_I18N=JSON.parse(document.getElementById("wppHostI18n").textContent||"{}");
|
||||||
|
function hostCopy(path,fallback){var node=WPP_HOST_I18N;var parts=(path||"").split(".");for(var i=0;i<parts.length;i++){if(!node||typeof node!=="object"){return fallback||path;}node=node[parts[i]];}if(node&&typeof node==="object"){if(node[WPP_HOST_LOCALE]){return node[WPP_HOST_LOCALE];}if(node.en){return node.en;}}return typeof node==="string"?node:(fallback||path);}
|
||||||
var currentSessionStatus="";
|
var currentSessionStatus="";
|
||||||
var autoRefreshEnabled=false;
|
var autoRefreshEnabled=false;
|
||||||
var autoRefreshTimer=null;
|
var autoRefreshTimer=null;
|
||||||
@@ -85,7 +89,7 @@ function code(){return document.getElementById("code").value.trim().toUpperCase(
|
|||||||
function rq(){return document.getElementById("roundQuestionId").value.trim();}
|
function rq(){return document.getElementById("roundQuestionId").value.trim();}
|
||||||
function saveHostContext(){try{localStorage.setItem("wppHostContext",JSON.stringify({code:code(),round_question_id:rq(),session_status:currentSessionStatus||"",auto_refresh:autoRefreshEnabled}));}catch(_e){}}
|
function saveHostContext(){try{localStorage.setItem("wppHostContext",JSON.stringify({code:code(),round_question_id:rq(),session_status:currentSessionStatus||"",auto_refresh:autoRefreshEnabled}));}catch(_e){}}
|
||||||
function restoreHostContext(){try{var raw=localStorage.getItem("wppHostContext");if(!raw){return false;}var ctx=JSON.parse(raw);if(ctx.code){document.getElementById("code").value=(ctx.code||"").toUpperCase();}if(ctx.round_question_id){document.getElementById("roundQuestionId").value=ctx.round_question_id;}if(ctx.session_status){currentSessionStatus=ctx.session_status;}autoRefreshEnabled=!!ctx.auto_refresh;updateAutoRefreshUi();return !!ctx.code;}catch(_e){return false;}}
|
function restoreHostContext(){try{var raw=localStorage.getItem("wppHostContext");if(!raw){return false;}var ctx=JSON.parse(raw);if(ctx.code){document.getElementById("code").value=(ctx.code||"").toUpperCase();}if(ctx.round_question_id){document.getElementById("roundQuestionId").value=ctx.round_question_id;}if(ctx.session_status){currentSessionStatus=ctx.session_status;}autoRefreshEnabled=!!ctx.auto_refresh;updateAutoRefreshUi();return !!ctx.code;}catch(_e){return false;}}
|
||||||
function phaseLabel(status){if(status==="lobby"){return"Lobby";}if(status==="lie"){return"Løgn";}if(status==="guess"){return"Gæt";}if(status==="reveal"){return"Reveal";}if(status==="finished"){return"Afsluttet";}return"Ukendt";}
|
function phaseLabel(status){if(status==="lobby"){return"Lobby";}if(status==="lie"){return"Lie";}if(status==="guess"){return"Guess";}if(status==="reveal"){return"Reveal";}if(status==="finished"){return"Finished";}return"Unknown";}
|
||||||
function hostShellRouteFromPath(){var marker="/lobby/ui/host";var path=(window.location.pathname||"").toLowerCase();var idx=path.indexOf(marker);if(idx===-1){return"";}var remainder=path.slice(idx+marker.length).replace(/^\/+|\/+$/g,"");if(!remainder){return"";}var route=remainder.split("/")[0];return HOST_SHELL_ROUTES[route]?route:"";}
|
function hostShellRouteFromPath(){var marker="/lobby/ui/host";var path=(window.location.pathname||"").toLowerCase();var idx=path.indexOf(marker);if(idx===-1){return"";}var remainder=path.slice(idx+marker.length).replace(/^\/+|\/+$/g,"");if(!remainder){return"";}var route=remainder.split("/")[0];return HOST_SHELL_ROUTES[route]?route:"";}
|
||||||
function expectedHostShellRoute(){return HOST_SHELL_ROUTES[currentSessionStatus]||"";}
|
function expectedHostShellRoute(){return HOST_SHELL_ROUTES[currentSessionStatus]||"";}
|
||||||
function syncHostShellRoute(){var currentRoute=hostShellRouteFromPath();var expectedRoute=expectedHostShellRoute();if(!currentRoute||!expectedRoute){hostShellRouteHint="";return;}if(currentRoute===expectedRoute){hostShellRouteHint="";return;}var nextPath="/lobby/ui/host/"+expectedRoute;window.history.replaceState(null,"",nextPath);hostShellRouteHint="Deep-link route guard: omdirigeret fra /"+currentRoute+" til /"+expectedRoute+" for fase "+phaseLabel(currentSessionStatus)+".";}
|
function syncHostShellRoute(){var currentRoute=hostShellRouteFromPath();var expectedRoute=expectedHostShellRoute();if(!currentRoute||!expectedRoute){hostShellRouteHint="";return;}if(currentRoute===expectedRoute){hostShellRouteHint="";return;}var nextPath="/lobby/ui/host/"+expectedRoute;window.history.replaceState(null,"",nextPath);hostShellRouteHint="Deep-link route guard: omdirigeret fra /"+currentRoute+" til /"+expectedRoute+" for fase "+phaseLabel(currentSessionStatus)+".";}
|
||||||
@@ -93,11 +97,11 @@ function updateAutoRefreshUi(){var btn=document.getElementById("autoRefreshToggl
|
|||||||
function stopAutoRefresh(reason){autoRefreshEnabled=false;if(autoRefreshTimer){clearInterval(autoRefreshTimer);autoRefreshTimer=null;}if(reason){var hint=document.getElementById("autoRefreshHint");if(hint){hint.textContent=reason;}}updateAutoRefreshUi();saveHostContext();}
|
function stopAutoRefresh(reason){autoRefreshEnabled=false;if(autoRefreshTimer){clearInterval(autoRefreshTimer);autoRefreshTimer=null;}if(reason){var hint=document.getElementById("autoRefreshHint");if(hint){hint.textContent=reason;}}updateAutoRefreshUi();saveHostContext();}
|
||||||
function startAutoRefresh(){if(!code()){updateAutoRefreshUi();return;}autoRefreshEnabled=true;if(autoRefreshTimer){clearInterval(autoRefreshTimer);}autoRefreshTimer=setInterval(function(){if(!code()||sessionDetailInFlight){return;}if(currentSessionStatus==="finished"){stopAutoRefresh("Auto-refresh stoppet: spillet er afsluttet.");return;}sessionDetail();},10000);updateAutoRefreshUi();saveHostContext();}
|
function startAutoRefresh(){if(!code()){updateAutoRefreshUi();return;}autoRefreshEnabled=true;if(autoRefreshTimer){clearInterval(autoRefreshTimer);}autoRefreshTimer=setInterval(function(){if(!code()||sessionDetailInFlight){return;}if(currentSessionStatus==="finished"){stopAutoRefresh("Auto-refresh stoppet: spillet er afsluttet.");return;}sessionDetail();},10000);updateAutoRefreshUi();saveHostContext();}
|
||||||
function toggleAutoRefresh(){if(hostActionInFlight||sessionDetailInFlight||!code()){updateAutoRefreshUi();return;}if(autoRefreshEnabled){stopAutoRefresh();return;}startAutoRefresh();}
|
function toggleAutoRefresh(){if(hostActionInFlight||sessionDetailInFlight||!code()){updateAutoRefreshUi();return;}if(autoRefreshEnabled){stopAutoRefresh();return;}startAutoRefresh();}
|
||||||
function formatTimeLabel(dateObj){return dateObj.toLocaleTimeString("da-DK",{hour12:false});}
|
function formatTimeLabel(dateObj){return dateObj.toLocaleTimeString(WPP_HOST_LOCALE,{hour12:false});}
|
||||||
function markSessionRefresh(status){if(status>=200&&status<300){lastRefreshAtLabel=formatTimeLabel(new Date());lastRefreshFailed=false;}else{lastRefreshFailed=true;}updateLastRefreshStatus();}
|
function markSessionRefresh(status){if(status>=200&&status<300){lastRefreshAtLabel=formatTimeLabel(new Date());lastRefreshFailed=false;}else{lastRefreshFailed=true;}updateLastRefreshStatus();}
|
||||||
function updateLastRefreshStatus(){var el=document.getElementById("lastRefreshStatus");if(!el){return;}if(!lastRefreshAtLabel){el.textContent=lastRefreshFailed?"Session-data kan være forældet (ingen succesfuld opdatering endnu).":"Session-data ikke opdateret endnu.";return;}if(lastRefreshFailed){el.textContent="Session-data kan være forældet (seneste succes: "+lastRefreshAtLabel+").";return;}el.textContent="Sidst opdateret: "+lastRefreshAtLabel+".";}
|
function updateLastRefreshStatus(){var el=document.getElementById("lastRefreshStatus");if(!el){return;}if(!lastRefreshAtLabel){el.textContent=lastRefreshFailed?"Session-data kan være forældet (ingen succesfuld opdatering endnu).":"Session-data ikke opdateret endnu.";return;}if(lastRefreshFailed){el.textContent="Session-data kan være forældet (seneste succes: "+lastRefreshAtLabel+").";return;}el.textContent="Sidst opdateret: "+lastRefreshAtLabel+".";}
|
||||||
function normalizeApiError(data){if(!data||typeof data!=="object"){return"";}return (data.error_code||data.error||"").toString();}
|
function normalizeApiError(data){if(!data||typeof data!=="object"){return"";}return (data.error_code||data.error||"").toString();}
|
||||||
function mapUiErrorMessage(errorKey){if(!errorKey){return"";}var key=errorKey.toLowerCase();if(key.indexOf("phase")!==-1){return"Ugyldig fase for handlingen. Opdatér session-status og prøv igen.";}if(key.indexOf("token")!==-1||key.indexOf("auth")!==-1){return"Session-token er ugyldig eller udløbet. Rejoin sessionen og prøv igen.";}if(key.indexOf("round")!==-1||key.indexOf("question")!==-1||key.indexOf("state")!==-1){return"Runde-kontekst matcher ikke længere. Opdatér session-status før næste handling.";}if(key.indexOf("session")!==-1){return"Sessionkoden er ugyldig eller sessionen findes ikke længere.";}return"Handling fejlede. Opdatér session-status og prøv igen.";}
|
function mapUiErrorMessage(errorKey){if(!errorKey){return"";}var key=errorKey.toLowerCase();if(WPP_HOST_I18N&&WPP_HOST_I18N.backend&&WPP_HOST_I18N.backend.errors&&WPP_HOST_I18N.backend.errors[key]){return hostCopy("backend.errors."+key,"Action failed. Refresh state and retry.");}if(key.indexOf("session")!==-1){return hostCopy("backend.errors.session_not_found_or_closed","Session code is invalid, or session no longer exists.");}return hostCopy("backend.errors.generic_action_failed_retry","Action failed. Refresh state and retry.");}
|
||||||
function updateErrorHint(status,data){var el=document.getElementById("hostErrorHint");if(!el){return;}if(status>=200&&status<300){el.textContent="Ingen fejl.";return;}var errKey=normalizeApiError(data);el.textContent="Fejl: "+mapUiErrorMessage(errKey)+" ("+(errKey||("http_"+status))+")";}
|
function updateErrorHint(status,data){var el=document.getElementById("hostErrorHint");if(!el){return;}if(status>=200&&status<300){el.textContent="Ingen fejl.";return;}var errKey=normalizeApiError(data);el.textContent="Fejl: "+mapUiErrorMessage(errKey)+" ("+(errKey||("http_"+status))+")";}
|
||||||
function updateCreateSessionState(){var btn=document.getElementById("createSessionBtn");var hint=document.getElementById("createSessionHint");if(btn){btn.disabled=hostActionInFlight||sessionDetailInFlight;}if(!hint){return;}if(hostActionInFlight){hint.textContent="Opret session er låst mens en host-handling kører.";return;}if(sessionDetailInFlight){hint.textContent="Opret session er låst mens session-opdatering kører.";return;}hint.textContent="Opret session er klar.";}function updateSessionDetailState(){var btn=document.getElementById("sessionDetailBtn");var hint=document.getElementById("sessionDetailHint");var codeInput=document.getElementById("code");if(btn){btn.disabled=sessionDetailInFlight||hostActionInFlight||!code();}if(codeInput){codeInput.readOnly=sessionDetailInFlight||hostActionInFlight;}if(!hint){return;}if(sessionDetailInFlight){hint.textContent="Opdaterer session-status…";return;}if(hostActionInFlight){hint.textContent="Session-opdatering er låst mens en host-handling kører.";return;}if(!code()){hint.textContent="Angiv sessionkode for at opdatere session-status.";updateHostShellErrorBoundary();return;}hint.textContent="Session-opdatering klar.";updateHostShellErrorBoundary();}
|
function updateCreateSessionState(){var btn=document.getElementById("createSessionBtn");var hint=document.getElementById("createSessionHint");if(btn){btn.disabled=hostActionInFlight||sessionDetailInFlight;}if(!hint){return;}if(hostActionInFlight){hint.textContent="Opret session er låst mens en host-handling kører.";return;}if(sessionDetailInFlight){hint.textContent="Opret session er låst mens session-opdatering kører.";return;}hint.textContent="Opret session er klar.";}function updateSessionDetailState(){var btn=document.getElementById("sessionDetailBtn");var hint=document.getElementById("sessionDetailHint");var codeInput=document.getElementById("code");if(btn){btn.disabled=sessionDetailInFlight||hostActionInFlight||!code();}if(codeInput){codeInput.readOnly=sessionDetailInFlight||hostActionInFlight;}if(!hint){return;}if(sessionDetailInFlight){hint.textContent="Opdaterer session-status…";return;}if(hostActionInFlight){hint.textContent="Session-opdatering er låst mens en host-handling kører.";return;}if(!code()){hint.textContent="Angiv sessionkode for at opdatere session-status.";updateHostShellErrorBoundary();return;}hint.textContent="Session-opdatering klar.";updateHostShellErrorBoundary();}
|
||||||
|
|
||||||
|
|||||||
@@ -69,8 +69,12 @@
|
|||||||
<p id="playerCriticalRound">Round question: afventer</p>
|
<p id="playerCriticalRound">Round question: afventer</p>
|
||||||
<p id="playerCriticalJoin">Join-status: afventer</p>
|
<p id="playerCriticalJoin">Join-status: afventer</p>
|
||||||
</section>
|
</section>
|
||||||
<pre id="out">Klar.</pre>
|
<pre id="out">Ready.</pre>
|
||||||
|
{{ lobby_i18n|json_script:"wppPlayerI18n" }}
|
||||||
<script>
|
<script>
|
||||||
|
var WPP_PLAYER_LOCALE="{{ shell_locale|default:'en'|escapejs }}";
|
||||||
|
var WPP_PLAYER_I18N=JSON.parse(document.getElementById("wppPlayerI18n").textContent||"{}");
|
||||||
|
function playerCopy(path,fallback){var node=WPP_PLAYER_I18N;var parts=(path||"").split(".");for(var i=0;i<parts.length;i++){if(!node||typeof node!=="object"){return fallback||path;}node=node[parts[i]];}if(node&&typeof node==="object"){if(node[WPP_PLAYER_LOCALE]){return node[WPP_PLAYER_LOCALE];}if(node.en){return node.en;}}return typeof node==="string"?node:(fallback||path);}
|
||||||
var availableAnswers=[];
|
var availableAnswers=[];
|
||||||
var guessSubmitted=false;
|
var guessSubmitted=false;
|
||||||
var lieSubmitted=false;
|
var lieSubmitted=false;
|
||||||
@@ -105,7 +109,7 @@ function clearPlayerShellFatalError(){playerShellFatalError=false;playerShellRec
|
|||||||
function recoverPlayerShell(mode){if(playerShellRecoverInFlight){return Promise.resolve({error:"recover_in_flight"});}playerShellRecoverInFlight=true;updatePlayerShellErrorBoundary();if(mode==="reload"){window.location.reload();return Promise.resolve({ok:true});}if(!code()){playerShellRecoverInFlight=false;updatePlayerShellErrorBoundary();return Promise.resolve({error:"missing_session_code"});}return sessionDetail().then(function(result){clearPlayerShellFatalError();return result;}).catch(function(err){playerShellRecoverInFlight=false;updatePlayerShellErrorBoundary();throw err;});}
|
function recoverPlayerShell(mode){if(playerShellRecoverInFlight){return Promise.resolve({error:"recover_in_flight"});}playerShellRecoverInFlight=true;updatePlayerShellErrorBoundary();if(mode==="reload"){window.location.reload();return Promise.resolve({ok:true});}if(!code()){playerShellRecoverInFlight=false;updatePlayerShellErrorBoundary();return Promise.resolve({error:"missing_session_code"});}return sessionDetail().then(function(result){clearPlayerShellFatalError();return result;}).catch(function(err){playerShellRecoverInFlight=false;updatePlayerShellErrorBoundary();throw err;});}
|
||||||
function pid(){return document.getElementById("playerId").value.trim();}
|
function pid(){return document.getElementById("playerId").value.trim();}
|
||||||
function rq(){return document.getElementById("roundQuestionId").value.trim();}
|
function rq(){return document.getElementById("roundQuestionId").value.trim();}
|
||||||
function phaseLabel(status){if(status==="lobby"){return"Lobby";}if(status==="lie"){return"Løgn";}if(status==="guess"){return"Gæt";}if(status==="reveal"){return"Reveal";}if(status==="finished"){return"Afsluttet";}return"Ukendt";}
|
function phaseLabel(status){if(status==="lobby"){return"Lobby";}if(status==="lie"){return"Lie";}if(status==="guess"){return"Guess";}if(status==="reveal"){return"Reveal";}if(status==="finished"){return"Finished";}return"Unknown";}
|
||||||
function updatePhaseStatus(){var el=document.getElementById("phaseStatus");if(!el){return;}if(!currentSessionStatus){el.textContent="Fase: ukendt (opdatér session-status).";return;}el.textContent="Fase: "+phaseLabel(currentSessionStatus)+" ("+currentSessionStatus+")";}
|
function updatePhaseStatus(){var el=document.getElementById("phaseStatus");if(!el){return;}if(!currentSessionStatus){el.textContent="Fase: ukendt (opdatér session-status).";return;}el.textContent="Fase: "+phaseLabel(currentSessionStatus)+" ("+currentSessionStatus+")";}
|
||||||
function savePlayerContext(){try{localStorage.setItem(PLAYER_CONTEXT_KEY,JSON.stringify({code:code(),nickname:document.getElementById("nickname").value.trim(),player_id:pid(),session_token:document.getElementById("sessionToken").value.trim(),round_question_id:rq(),auto_refresh:playerAutoRefreshEnabled}));}catch(_e){}}
|
function savePlayerContext(){try{localStorage.setItem(PLAYER_CONTEXT_KEY,JSON.stringify({code:code(),nickname:document.getElementById("nickname").value.trim(),player_id:pid(),session_token:document.getElementById("sessionToken").value.trim(),round_question_id:rq(),auto_refresh:playerAutoRefreshEnabled}));}catch(_e){}}
|
||||||
function loadPlayerContext(){try{var raw=localStorage.getItem(PLAYER_CONTEXT_KEY);if(!raw){return null;}return JSON.parse(raw);}catch(_e){return null;}}
|
function loadPlayerContext(){try{var raw=localStorage.getItem(PLAYER_CONTEXT_KEY);if(!raw){return null;}return JSON.parse(raw);}catch(_e){return null;}}
|
||||||
@@ -118,8 +122,8 @@ function resetRoundContextForManualChange(){document.getElementById("roundQuesti
|
|||||||
function updateContextLockState(){var locked=isPlayerContextLocked()||joinInFlight;var codeField=document.getElementById("code");var nicknameField=document.getElementById("nickname");var playerIdField=document.getElementById("playerId");var tokenField=document.getElementById("sessionToken");if(codeField){codeField.readOnly=locked;}if(nicknameField){nicknameField.readOnly=locked;}if(playerIdField){playerIdField.readOnly=locked;}if(tokenField){tokenField.readOnly=true;}var hint=document.getElementById("contextLockHint");if(!hint){return;}if(joinInFlight){hint.textContent="Låser kontekst…";return;}if(locked){hint.textContent="Spillerkontekst er låst efter join.";return;}hint.textContent="Kontekst er ikke låst endnu.";}
|
function updateContextLockState(){var locked=isPlayerContextLocked()||joinInFlight;var codeField=document.getElementById("code");var nicknameField=document.getElementById("nickname");var playerIdField=document.getElementById("playerId");var tokenField=document.getElementById("sessionToken");if(codeField){codeField.readOnly=locked;}if(nicknameField){nicknameField.readOnly=locked;}if(playerIdField){playerIdField.readOnly=locked;}if(tokenField){tokenField.readOnly=true;}var hint=document.getElementById("contextLockHint");if(!hint){return;}if(joinInFlight){hint.textContent="Låser kontekst…";return;}if(locked){hint.textContent="Spillerkontekst er låst efter join.";return;}hint.textContent="Kontekst er ikke låst endnu.";}
|
||||||
function canAttemptJoin(){return !!(code()&&document.getElementById("nickname").value.trim());}
|
function canAttemptJoin(){return !!(code()&&document.getElementById("nickname").value.trim());}
|
||||||
function normalizeApiError(data){if(!data||typeof data!=="object"){return"";}return (data.error_code||data.error||"").toString();}
|
function normalizeApiError(data){if(!data||typeof data!=="object"){return"";}return (data.error_code||data.error||"").toString();}
|
||||||
function mapUiErrorMessage(errorKey){if(!errorKey){return"";}var key=errorKey.toLowerCase();if(key.indexOf("phase")!==-1){return"Ugyldig fase for handlingen. Opdatér session-status og prøv igen.";}if(key.indexOf("token")!==-1||key.indexOf("auth")!==-1){return"Session-token er ugyldig eller udløbet. Rejoin sessionen og prøv igen.";}if(key.indexOf("round")!==-1||key.indexOf("question")!==-1||key.indexOf("state")!==-1){return"Runde-kontekst matcher ikke længere. Opdatér session-status før næste handling.";}if(key.indexOf("session")!==-1){return"Sessionkoden er ugyldig eller sessionen findes ikke længere.";}return"Handling fejlede. Opdatér session-status og prøv igen.";}
|
function mapUiErrorMessage(errorKey){if(!errorKey){return"";}var key=errorKey.toLowerCase();if(WPP_PLAYER_I18N&&WPP_PLAYER_I18N.backend&&WPP_PLAYER_I18N.backend.errors&&WPP_PLAYER_I18N.backend.errors[key]){return playerCopy("backend.errors."+key,"Action failed. Refresh state and retry.");}if(key.indexOf("session")!==-1){return playerCopy("backend.errors.session_not_found_or_closed","Session code is invalid, or session no longer exists.");}return playerCopy("backend.errors.generic_action_failed_retry","Action failed. Refresh state and retry.");}
|
||||||
function formatTimeLabel(dateObj){return dateObj.toLocaleTimeString("da-DK",{hour12:false});}
|
function formatTimeLabel(dateObj){return dateObj.toLocaleTimeString(WPP_PLAYER_LOCALE,{hour12:false});}
|
||||||
function markPlayerSessionRefresh(status){if(status>=200&&status<300){playerLastRefreshAtLabel=formatTimeLabel(new Date());playerLastRefreshFailed=false;}else{playerLastRefreshFailed=true;}updatePlayerLastRefreshStatus();}
|
function markPlayerSessionRefresh(status){if(status>=200&&status<300){playerLastRefreshAtLabel=formatTimeLabel(new Date());playerLastRefreshFailed=false;}else{playerLastRefreshFailed=true;}updatePlayerLastRefreshStatus();}
|
||||||
function updatePlayerLastRefreshStatus(){var el=document.getElementById("playerLastRefreshStatus");if(!el){return;}if(!playerLastRefreshAtLabel){el.textContent=playerLastRefreshFailed?"Session-data kan være forældet (ingen succesfuld opdatering endnu).":"Session-data ikke opdateret endnu.";return;}if(playerLastRefreshFailed){el.textContent="Session-data kan være forældet (seneste succes: "+playerLastRefreshAtLabel+").";return;}el.textContent="Sidst opdateret: "+playerLastRefreshAtLabel+".";}
|
function updatePlayerLastRefreshStatus(){var el=document.getElementById("playerLastRefreshStatus");if(!el){return;}if(!playerLastRefreshAtLabel){el.textContent=playerLastRefreshFailed?"Session-data kan være forældet (ingen succesfuld opdatering endnu).":"Session-data ikke opdateret endnu.";return;}if(playerLastRefreshFailed){el.textContent="Session-data kan være forældet (seneste succes: "+playerLastRefreshAtLabel+").";return;}el.textContent="Sidst opdateret: "+playerLastRefreshAtLabel+".";}
|
||||||
function updatePlayerAutoRefreshUi(){var btn=document.getElementById("playerAutoRefreshToggleBtn");var hint=document.getElementById("playerAutoRefreshHint");if(btn){btn.textContent="Auto-refresh: "+(playerAutoRefreshEnabled?"ON":"OFF");btn.disabled=sessionDetailInFlight||joinInFlight||!code();}if(!hint){return;}if(sessionDetailInFlight){hint.textContent="Auto-refresh-lås: afvent aktiv session-opdatering.";return;}if(joinInFlight){hint.textContent="Auto-refresh-lås: afvent aktiv join.";return;}if(!code()){hint.textContent="Auto-refresh kræver sessionkode.";return;}if(!playerAutoRefreshEnabled){hint.textContent="Auto-refresh er slået fra.";return;}if(currentSessionStatus==="finished"){hint.textContent="Auto-refresh stoppet: spillet er afsluttet.";return;}hint.textContent="Auto-refresh aktiv (10s) for spillerstatus.";}
|
function updatePlayerAutoRefreshUi(){var btn=document.getElementById("playerAutoRefreshToggleBtn");var hint=document.getElementById("playerAutoRefreshHint");if(btn){btn.textContent="Auto-refresh: "+(playerAutoRefreshEnabled?"ON":"OFF");btn.disabled=sessionDetailInFlight||joinInFlight||!code();}if(!hint){return;}if(sessionDetailInFlight){hint.textContent="Auto-refresh-lås: afvent aktiv session-opdatering.";return;}if(joinInFlight){hint.textContent="Auto-refresh-lås: afvent aktiv join.";return;}if(!code()){hint.textContent="Auto-refresh kræver sessionkode.";return;}if(!playerAutoRefreshEnabled){hint.textContent="Auto-refresh er slået fra.";return;}if(currentSessionStatus==="finished"){hint.textContent="Auto-refresh stoppet: spillet er afsluttet.";return;}hint.textContent="Auto-refresh aktiv (10s) for spillerstatus.";}
|
||||||
|
|||||||
@@ -40,6 +40,7 @@ def host_screen(request, spa_path=None):
|
|||||||
{
|
{
|
||||||
"categories": categories,
|
"categories": categories,
|
||||||
"lobby_i18n": lobby_i18n_catalog(),
|
"lobby_i18n": lobby_i18n_catalog(),
|
||||||
|
"shell_locale": resolve_locale(request),
|
||||||
},
|
},
|
||||||
)
|
)
|
||||||
|
|
||||||
@@ -48,4 +49,8 @@ def player_screen(request):
|
|||||||
if use_spa_ui():
|
if use_spa_ui():
|
||||||
return _render_spa_shell(request, "/player", "player")
|
return _render_spa_shell(request, "/player", "player")
|
||||||
|
|
||||||
return render(request, "lobby/player_screen.html", {"lobby_i18n": lobby_i18n_catalog()})
|
return render(
|
||||||
|
request,
|
||||||
|
"lobby/player_screen.html",
|
||||||
|
{"lobby_i18n": lobby_i18n_catalog(), "shell_locale": resolve_locale(request)},
|
||||||
|
)
|
||||||
|
|||||||
@@ -20,7 +20,9 @@ from fupogfakta.models import (
|
|||||||
ScoreEvent,
|
ScoreEvent,
|
||||||
)
|
)
|
||||||
|
|
||||||
from .i18n import api_error
|
from realtime.broadcast import sync_broadcast_phase_event
|
||||||
|
|
||||||
|
from .i18n import api_error, lobby_i18n_errors
|
||||||
|
|
||||||
SESSION_CODE_ALPHABET = "ABCDEFGHJKLMNPQRSTUVWXYZ23456789"
|
SESSION_CODE_ALPHABET = "ABCDEFGHJKLMNPQRSTUVWXYZ23456789"
|
||||||
SESSION_CODE_LENGTH = 6
|
SESSION_CODE_LENGTH = 6
|
||||||
@@ -321,6 +323,16 @@ def start_round(request: HttpRequest, code: str) -> JsonResponse:
|
|||||||
session.status = GameSession.Status.LIE
|
session.status = GameSession.Status.LIE
|
||||||
session.save(update_fields=["status"])
|
session.save(update_fields=["status"])
|
||||||
|
|
||||||
|
sync_broadcast_phase_event(
|
||||||
|
session.code,
|
||||||
|
"phase.lie_started",
|
||||||
|
{
|
||||||
|
"round_number": session.current_round,
|
||||||
|
"category": {"slug": round_config.category.slug, "name": round_config.category.name},
|
||||||
|
"lie_seconds": round_config.lie_seconds,
|
||||||
|
},
|
||||||
|
)
|
||||||
|
|
||||||
return JsonResponse(
|
return JsonResponse(
|
||||||
{
|
{
|
||||||
"session": {
|
"session": {
|
||||||
@@ -407,6 +419,18 @@ def show_question(request: HttpRequest, code: str) -> JsonResponse:
|
|||||||
|
|
||||||
lie_deadline_at = round_question.shown_at + timedelta(seconds=round_config.lie_seconds)
|
lie_deadline_at = round_question.shown_at + timedelta(seconds=round_config.lie_seconds)
|
||||||
|
|
||||||
|
sync_broadcast_phase_event(
|
||||||
|
session.code,
|
||||||
|
"phase.question_shown",
|
||||||
|
{
|
||||||
|
"round_question_id": round_question.id,
|
||||||
|
"prompt": question.prompt,
|
||||||
|
"shown_at": round_question.shown_at.isoformat(),
|
||||||
|
"lie_deadline_at": lie_deadline_at.isoformat(),
|
||||||
|
"lie_seconds": round_config.lie_seconds,
|
||||||
|
},
|
||||||
|
)
|
||||||
|
|
||||||
return JsonResponse(
|
return JsonResponse(
|
||||||
{
|
{
|
||||||
"round_question": {
|
"round_question": {
|
||||||
@@ -575,6 +599,22 @@ def mix_answers(request: HttpRequest, code: str, round_question_id: int) -> Json
|
|||||||
locked_session.status = GameSession.Status.GUESS
|
locked_session.status = GameSession.Status.GUESS
|
||||||
locked_session.save(update_fields=["status"])
|
locked_session.save(update_fields=["status"])
|
||||||
|
|
||||||
|
try:
|
||||||
|
_guess_config = RoundConfig.objects.get(session=session, number=session.current_round)
|
||||||
|
_guess_seconds = _guess_config.guess_seconds
|
||||||
|
except RoundConfig.DoesNotExist:
|
||||||
|
_guess_seconds = None
|
||||||
|
|
||||||
|
sync_broadcast_phase_event(
|
||||||
|
session.code,
|
||||||
|
"phase.guess_started",
|
||||||
|
{
|
||||||
|
"round_question_id": round_question.id,
|
||||||
|
"answers": [{"text": t} for t in deduped_answers],
|
||||||
|
"guess_seconds": _guess_seconds,
|
||||||
|
},
|
||||||
|
)
|
||||||
|
|
||||||
return JsonResponse(
|
return JsonResponse(
|
||||||
{
|
{
|
||||||
"session": {
|
"session": {
|
||||||
@@ -719,6 +759,12 @@ def reveal_scoreboard(request: HttpRequest, code: str) -> JsonResponse:
|
|||||||
.values("id", "nickname", "score")
|
.values("id", "nickname", "score")
|
||||||
)
|
)
|
||||||
|
|
||||||
|
sync_broadcast_phase_event(
|
||||||
|
session.code,
|
||||||
|
"phase.scoreboard",
|
||||||
|
{"leaderboard": list(leaderboard), "current_round": session.current_round},
|
||||||
|
)
|
||||||
|
|
||||||
return JsonResponse(
|
return JsonResponse(
|
||||||
{
|
{
|
||||||
"session": {
|
"session": {
|
||||||
@@ -792,6 +838,12 @@ def finish_game(request: HttpRequest, code: str) -> JsonResponse:
|
|||||||
|
|
||||||
winner = leaderboard[0] if leaderboard else None
|
winner = leaderboard[0] if leaderboard else None
|
||||||
|
|
||||||
|
sync_broadcast_phase_event(
|
||||||
|
session.code,
|
||||||
|
"phase.game_over",
|
||||||
|
{"winner": winner, "leaderboard": list(leaderboard)},
|
||||||
|
)
|
||||||
|
|
||||||
return JsonResponse(
|
return JsonResponse(
|
||||||
{
|
{
|
||||||
"session": {
|
"session": {
|
||||||
@@ -898,6 +950,21 @@ def calculate_scores(request: HttpRequest, code: str, round_question_id: int) ->
|
|||||||
.values("id", "nickname", "score")
|
.values("id", "nickname", "score")
|
||||||
)
|
)
|
||||||
|
|
||||||
|
score_deltas = [
|
||||||
|
{"player_id": ev.player_id, "delta": ev.delta, "reason": ev.reason}
|
||||||
|
for ev in score_events
|
||||||
|
]
|
||||||
|
|
||||||
|
sync_broadcast_phase_event(
|
||||||
|
session.code,
|
||||||
|
"phase.scores_calculated",
|
||||||
|
{
|
||||||
|
"round_question_id": round_question.id,
|
||||||
|
"score_deltas": score_deltas,
|
||||||
|
"leaderboard": list(leaderboard),
|
||||||
|
},
|
||||||
|
)
|
||||||
|
|
||||||
return JsonResponse(
|
return JsonResponse(
|
||||||
{
|
{
|
||||||
"session": {
|
"session": {
|
||||||
|
|||||||
@@ -1,11 +1,15 @@
|
|||||||
import os
|
import os
|
||||||
from channels.routing import ProtocolTypeRouter
|
|
||||||
|
from channels.routing import ProtocolTypeRouter, URLRouter
|
||||||
from django.core.asgi import get_asgi_application
|
from django.core.asgi import get_asgi_application
|
||||||
|
|
||||||
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'partyhub.settings')
|
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'partyhub.settings')
|
||||||
|
|
||||||
django_asgi_app = get_asgi_application()
|
django_asgi_app = get_asgi_application()
|
||||||
|
|
||||||
|
from realtime.routing import websocket_urlpatterns # noqa: E402 — must come after env setup
|
||||||
|
|
||||||
application = ProtocolTypeRouter({
|
application = ProtocolTypeRouter({
|
||||||
'http': django_asgi_app,
|
'http': django_asgi_app,
|
||||||
|
'websocket': URLRouter(websocket_urlpatterns),
|
||||||
})
|
})
|
||||||
|
|||||||
@@ -116,8 +116,13 @@ WPP_SPA_ASSET_VERSION = env('WPP_SPA_ASSET_VERSION', 'dev')
|
|||||||
|
|
||||||
CHANNEL_REDIS_HOST = env('CHANNEL_REDIS_HOST', '127.0.0.1')
|
CHANNEL_REDIS_HOST = env('CHANNEL_REDIS_HOST', '127.0.0.1')
|
||||||
CHANNEL_REDIS_PORT = int(env('CHANNEL_REDIS_PORT', '6379'))
|
CHANNEL_REDIS_PORT = int(env('CHANNEL_REDIS_PORT', '6379'))
|
||||||
|
|
||||||
|
import sys # noqa: E402
|
||||||
|
_testing = 'test' in sys.argv
|
||||||
CHANNEL_LAYERS = {
|
CHANNEL_LAYERS = {
|
||||||
'default': {
|
'default': {
|
||||||
|
'BACKEND': 'channels.layers.InMemoryChannelLayer',
|
||||||
|
} if _testing else {
|
||||||
'BACKEND': 'channels_redis.core.RedisChannelLayer',
|
'BACKEND': 'channels_redis.core.RedisChannelLayer',
|
||||||
'CONFIG': {'hosts': [(CHANNEL_REDIS_HOST, CHANNEL_REDIS_PORT)]},
|
'CONFIG': {'hosts': [(CHANNEL_REDIS_HOST, CHANNEL_REDIS_PORT)]},
|
||||||
}
|
}
|
||||||
|
|||||||
20
realtime/broadcast.py
Normal file
20
realtime/broadcast.py
Normal file
@@ -0,0 +1,20 @@
|
|||||||
|
from asgiref.sync import async_to_sync
|
||||||
|
from channels.layers import get_channel_layer
|
||||||
|
|
||||||
|
|
||||||
|
async def broadcast_phase_event(session_code: str, event_type: str, payload: dict) -> None:
|
||||||
|
"""Send a phase event to all WebSocket clients connected to a game session."""
|
||||||
|
channel_layer = get_channel_layer()
|
||||||
|
group_name = f"game_{session_code.upper()}"
|
||||||
|
await channel_layer.group_send(
|
||||||
|
group_name,
|
||||||
|
{
|
||||||
|
"type": "phase_event",
|
||||||
|
"payload": {"type": event_type, **payload},
|
||||||
|
},
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def sync_broadcast_phase_event(session_code: str, event_type: str, payload: dict) -> None:
|
||||||
|
"""Sync wrapper for calling broadcast_phase_event from synchronous Django views."""
|
||||||
|
async_to_sync(broadcast_phase_event)(session_code, event_type, payload)
|
||||||
61
realtime/consumers.py
Normal file
61
realtime/consumers.py
Normal file
@@ -0,0 +1,61 @@
|
|||||||
|
import json
|
||||||
|
from urllib.parse import parse_qs
|
||||||
|
|
||||||
|
from channels.generic.websocket import AsyncJsonWebsocketConsumer
|
||||||
|
|
||||||
|
from fupogfakta.models import Player
|
||||||
|
|
||||||
|
|
||||||
|
class GameConsumer(AsyncJsonWebsocketConsumer):
|
||||||
|
"""
|
||||||
|
WebSocket consumer for a game session.
|
||||||
|
|
||||||
|
URL: ws/game/<session_code>/
|
||||||
|
|
||||||
|
Query params:
|
||||||
|
- session_token: player session token (players only)
|
||||||
|
- role=host: skip token check for host in MVP
|
||||||
|
"""
|
||||||
|
|
||||||
|
async def connect(self):
|
||||||
|
self.session_code = self.scope["url_route"]["kwargs"]["session_code"].upper()
|
||||||
|
self.group_name = f"game_{self.session_code}"
|
||||||
|
|
||||||
|
query_string = self.scope.get("query_string", b"").decode()
|
||||||
|
params = parse_qs(query_string)
|
||||||
|
|
||||||
|
role = params.get("role", [None])[0]
|
||||||
|
session_token = params.get("session_token", [None])[0]
|
||||||
|
|
||||||
|
if role != "host":
|
||||||
|
if not session_token:
|
||||||
|
await self.close(code=4001)
|
||||||
|
return
|
||||||
|
|
||||||
|
try:
|
||||||
|
self.player = await Player.objects.aget(
|
||||||
|
session_token=session_token,
|
||||||
|
session__code=self.session_code,
|
||||||
|
)
|
||||||
|
except Player.DoesNotExist:
|
||||||
|
await self.close(code=4003)
|
||||||
|
return
|
||||||
|
else:
|
||||||
|
self.player = None
|
||||||
|
|
||||||
|
await self.channel_layer.group_add(self.group_name, self.channel_name)
|
||||||
|
await self.accept()
|
||||||
|
|
||||||
|
async def disconnect(self, close_code):
|
||||||
|
if hasattr(self, "group_name"):
|
||||||
|
await self.channel_layer.group_discard(self.group_name, self.channel_name)
|
||||||
|
|
||||||
|
async def receive_json(self, content, **kwargs):
|
||||||
|
if content.get("type") == "ping":
|
||||||
|
await self.send_json({"type": "pong"})
|
||||||
|
|
||||||
|
# --- Group message handlers ---
|
||||||
|
|
||||||
|
async def phase_event(self, event):
|
||||||
|
"""Forward any phase_event broadcast to the WebSocket client."""
|
||||||
|
await self.send_json(event["payload"])
|
||||||
7
realtime/routing.py
Normal file
7
realtime/routing.py
Normal file
@@ -0,0 +1,7 @@
|
|||||||
|
from django.urls import re_path
|
||||||
|
|
||||||
|
from . import consumers
|
||||||
|
|
||||||
|
websocket_urlpatterns = [
|
||||||
|
re_path(r"^ws/game/(?P<session_code>[A-Z0-9]{4,8})/$", consumers.GameConsumer.as_asgi()),
|
||||||
|
]
|
||||||
@@ -1,3 +1,72 @@
|
|||||||
|
from channels.testing import WebsocketCommunicator
|
||||||
|
from django.contrib.auth import get_user_model
|
||||||
from django.test import TestCase
|
from django.test import TestCase
|
||||||
|
|
||||||
# Create your tests here.
|
from fupogfakta.models import GameSession, Player
|
||||||
|
from partyhub.asgi import application
|
||||||
|
|
||||||
|
User = get_user_model()
|
||||||
|
|
||||||
|
|
||||||
|
class GameConsumerConnectTest(TestCase):
|
||||||
|
def setUp(self):
|
||||||
|
self.user = User.objects.create_user(username="host", password="pw")
|
||||||
|
self.session = GameSession.objects.create(host=self.user, code="AABBCC")
|
||||||
|
self.player = Player.objects.create(session=self.session, nickname="Tester")
|
||||||
|
|
||||||
|
async def test_player_connect_and_ping(self):
|
||||||
|
token = self.player.session_token
|
||||||
|
communicator = WebsocketCommunicator(
|
||||||
|
application,
|
||||||
|
f"/ws/game/AABBCC/?session_token={token}",
|
||||||
|
)
|
||||||
|
connected, _ = await communicator.connect()
|
||||||
|
self.assertTrue(connected)
|
||||||
|
|
||||||
|
await communicator.send_json_to({"type": "ping"})
|
||||||
|
response = await communicator.receive_json_from()
|
||||||
|
self.assertEqual(response["type"], "pong")
|
||||||
|
|
||||||
|
await communicator.disconnect()
|
||||||
|
|
||||||
|
async def test_connect_without_token_rejected(self):
|
||||||
|
communicator = WebsocketCommunicator(application, "/ws/game/AABBCC/")
|
||||||
|
connected, code = await communicator.connect()
|
||||||
|
self.assertFalse(connected)
|
||||||
|
self.assertEqual(code, 4001)
|
||||||
|
|
||||||
|
async def test_connect_invalid_token_rejected(self):
|
||||||
|
communicator = WebsocketCommunicator(
|
||||||
|
application,
|
||||||
|
"/ws/game/AABBCC/?session_token=invalid-token",
|
||||||
|
)
|
||||||
|
connected, code = await communicator.connect()
|
||||||
|
self.assertFalse(connected)
|
||||||
|
self.assertEqual(code, 4003)
|
||||||
|
|
||||||
|
async def test_host_connect_without_token(self):
|
||||||
|
communicator = WebsocketCommunicator(
|
||||||
|
application,
|
||||||
|
"/ws/game/AABBCC/?role=host",
|
||||||
|
)
|
||||||
|
connected, _ = await communicator.connect()
|
||||||
|
self.assertTrue(connected)
|
||||||
|
await communicator.disconnect()
|
||||||
|
|
||||||
|
async def test_broadcast_reaches_connected_client(self):
|
||||||
|
token = self.player.session_token
|
||||||
|
communicator = WebsocketCommunicator(
|
||||||
|
application,
|
||||||
|
f"/ws/game/AABBCC/?session_token={token}",
|
||||||
|
)
|
||||||
|
connected, _ = await communicator.connect()
|
||||||
|
self.assertTrue(connected)
|
||||||
|
|
||||||
|
from realtime.broadcast import broadcast_phase_event
|
||||||
|
await broadcast_phase_event("AABBCC", "phase.test_event", {"hello": "world"})
|
||||||
|
|
||||||
|
message = await communicator.receive_json_from(timeout=2)
|
||||||
|
self.assertEqual(message["type"], "phase.test_event")
|
||||||
|
self.assertEqual(message["hello"], "world")
|
||||||
|
|
||||||
|
await communicator.disconnect()
|
||||||
|
|||||||
@@ -1,5 +1,6 @@
|
|||||||
Django==6.0.2
|
Django==6.0.2
|
||||||
channels>=4.1,<5
|
channels>=4.1,<5
|
||||||
channels-redis>=4.2,<5
|
channels-redis>=4.2,<5
|
||||||
|
daphne>=4.1,<5
|
||||||
mysqlclient>=2.2,<3
|
mysqlclient>=2.2,<3
|
||||||
python-dotenv>=1.0,<2
|
python-dotenv>=1.0,<2
|
||||||
|
|||||||
Reference in New Issue
Block a user