From 37e70eddb68e2035f58dcf76deef08ffd0529903 Mon Sep 17 00:00:00 2001 From: orfelorfel23 Date: Sat, 21 Nov 2026 15:41:56 +0100 Subject: [PATCH] =?UTF-8?q?feat:=20Bestenliste=20f=C3=BCr=20jedes=20T?= =?UTF-8?q?=C3=BCrchen-Minispiel?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - Zeitmessung startet beim Öffnen des Türchens, endet bei der ersten Server-Antwort mit solved:true (z. B. Codewort abgeschickt) - Pflichtfeld Name am Spielende, Eintrag via POST /api/door/:token/leaderboard - Extra Link /leaderboard zeigt alle Bestenlisten (JSON: /api/leaderboard) - Speicher: data/leaderboard.json, per Compose-Volume persistent Generated by Mistral Vibe. Co-Authored-By: Mistral Vibe --- .gitignore | 4 + data/.gitkeep | 0 deployment-template/docker-compose.yml | 1 + docker-compose.yml | 2 + src/doors/leaderboard.ts | 156 ++++++++++ src/server.ts | 92 ++++++ src/views.ts | 6 +- src/views/leaderboard.ts | 397 +++++++++++++++++++++++++ 8 files changed, 657 insertions(+), 1 deletion(-) create mode 100644 data/.gitkeep create mode 100644 src/doors/leaderboard.ts create mode 100644 src/views/leaderboard.ts diff --git a/.gitignore b/.gitignore index 9ef5615..12411f7 100644 --- a/.gitignore +++ b/.gitignore @@ -7,3 +7,7 @@ qr-codes/ *.log *.tmp temp.txt + +# Bestenlisten-Daten (Spielereinträge) +data/* +!data/.gitkeep diff --git a/data/.gitkeep b/data/.gitkeep new file mode 100644 index 0000000..e69de29 diff --git a/deployment-template/docker-compose.yml b/deployment-template/docker-compose.yml index 2deac02..e587bf2 100644 --- a/deployment-template/docker-compose.yml +++ b/deployment-template/docker-compose.yml @@ -13,6 +13,7 @@ services: DOORS_OVERRIDE_DIR: /app/content-override volumes: - /mnt/Jannik-Cloud-Volume-01/adventskalender:/app/content-override:ro + - /mnt/Jannik-Cloud-Volume-01/adventskalender-leaderboard:/app/data healthcheck: test: ["CMD", "node", "-e", "require('http').get('http://127.0.0.1:3000/health', (r) => process.exit(r.statusCode === 200 ? 0 : 1)).on('error', () => process.exit(1))"] interval: 30s diff --git a/docker-compose.yml b/docker-compose.yml index 6200b2f..e81e75c 100644 --- a/docker-compose.yml +++ b/docker-compose.yml @@ -11,6 +11,8 @@ services: environment: NODE_ENV: production PORT: 3000 + volumes: + - ./data:/app/data healthcheck: test: ["CMD", "node", "-e", "require('http').get('http://127.0.0.1:3000/health', (r) => process.exit(r.statusCode === 200 ? 0 : 1)).on('error', () => process.exit(1))"] interval: 30s diff --git a/src/doors/leaderboard.ts b/src/doors/leaderboard.ts new file mode 100644 index 0000000..b4613ce --- /dev/null +++ b/src/doors/leaderboard.ts @@ -0,0 +1,156 @@ +import fs from 'fs'; +import path from 'path'; + +/** + * Bestenlisten-Speicher für jedes Türchen/Minispiel. + * + * - Start: Öffnen des Türchens (misst der Client, siehe views/leaderboard.ts) + * - Ende: Lösung abgeschickt (erste Server-Antwort mit solved: true) + * - Pro Eintrag wird ein Name gespeichert (Pflichtfeld am Spielende). + * + * Ablage: data/leaderboard.json (per Env LEADERBOARD_FILE überschreibbar). + */ + +export interface LeaderboardEntry { + /** Anzeigename der Spielerin / des Spielers (Pflichtfeld, 1–24 Zeichen) */ + name: string; + /** Gemessene Spielzeit in Millisekunden (Start = Türchen geöffnet) */ + durationMs: number; + /** Zeitpunkt des Eintrags (ISO) */ + dateIso: string; +} + +interface DoorLeaderboard { + entries: LeaderboardEntry[]; +} + +interface LeaderboardData { + doors: Record; +} + +export interface AddEntryResult { + rank: number; + total: number; + top10: LeaderboardEntry[]; +} + +const MIN_DURATION_MS = 500; +const MAX_DURATION_MS = 24 * 60 * 60 * 1000; // 24 h +const MAX_NAME_LENGTH = 24; +const MAX_ENTRIES_PER_DOOR = 200; + +function getStoragePath(): string { + const configured = process.env.LEADERBOARD_FILE?.trim(); + if (configured) { + return path.resolve(configured); + } + return path.resolve(process.cwd(), 'data', 'leaderboard.json'); +} + +function isDoorIdValid(doorId: string): boolean { + return /^\d{2}$/.test(doorId); +} + +function createEmptyData(): LeaderboardData { + return { doors: {} }; +} + +function loadLeaderboard(): LeaderboardData { + const filePath = getStoragePath(); + try { + const raw = fs.readFileSync(filePath, 'utf-8'); + const parsed = JSON.parse(raw) as Partial; + if (!parsed.doors || typeof parsed.doors !== 'object') { + return createEmptyData(); + } + return parsed as LeaderboardData; + } catch { + return createEmptyData(); + } +} + +function saveLeaderboard(data: LeaderboardData): void { + const filePath = getStoragePath(); + fs.mkdirSync(path.dirname(filePath), { recursive: true }); + const tempPath = `${filePath}.tmp`; + fs.writeFileSync(tempPath, JSON.stringify(data, null, 2), 'utf-8'); + fs.renameSync(tempPath, filePath); +} + +function sortedEntries(door: DoorLeaderboard): LeaderboardEntry[] { + return [...door.entries].sort((a, b) => a.durationMs - b.durationMs); +} + +/** Top-Liste eines Türchens (aufsteigend nach Zeit). */ +export function getLeaderboardForDoor(doorId: string): LeaderboardEntry[] { + const data = loadLeaderboard(); + const door = data.doors[doorId]; + if (!door || !Array.isArray(door.entries)) { + return []; + } + return sortedEntries(door); +} + +/** Alle Bestenlisten (nur Türchen mit Einträgen), nach Tür-ID sortiert. */ +export function getAllLeaderboards(): { doorId: string; entries: LeaderboardEntry[] }[] { + const data = loadLeaderboard(); + return Object.keys(data.doors) + .filter((doorId) => isDoorIdValid(doorId)) + .filter((doorId) => (data.doors[doorId]?.entries ?? []).length > 0) + .sort() + .map((doorId) => ({ + doorId, + entries: sortedEntries(data.doors[doorId]), + })); +} + +/** + * Neuen Eintrag speichern und Platzierung zurückgeben. + * Wirft einen Error mit sprechender Meldung, wenn die Eingabe ungültig ist. + */ +export function addLeaderboardEntry( + doorId: string, + rawName: string, + rawDurationMs: number, +): AddEntryResult { + if (!isDoorIdValid(doorId)) { + throw new Error('Ungültige Türchen-ID.'); + } + + const name = rawName.trim().replace(/\s+/g, ' '); + if (name.length < 1 || name.length > MAX_NAME_LENGTH) { + throw new Error(`Bitte einen Namen mit 1–${MAX_NAME_LENGTH} Zeichen eingeben.`); + } + + const durationMs = Math.round(rawDurationMs); + if (!Number.isFinite(durationMs) || durationMs < MIN_DURATION_MS || durationMs > MAX_DURATION_MS) { + throw new Error('Ungültige Spielzeit.'); + } + + const data = loadLeaderboard(); + if (!data.doors[doorId]) { + data.doors[doorId] = { entries: [] }; + } + + const entry: LeaderboardEntry = { + name, + durationMs, + dateIso: new Date().toISOString(), + }; + data.doors[doorId].entries.push(entry); + + if (data.doors[doorId].entries.length > MAX_ENTRIES_PER_DOOR) { + // Bei sehr langen Listen nur die schnellsten behalten, damit die Datei klein bleibt. + data.doors[doorId].entries = sortedEntries(data.doors[doorId]).slice(0, MAX_ENTRIES_PER_DOOR); + } + + saveLeaderboard(data); + + const all = sortedEntries(data.doors[doorId]); + const rank = all.findIndex((item) => item === entry) + 1; + return { + rank, + total: all.length, + top10: all.slice(0, 10), + }; +} diff --git a/src/server.ts b/src/server.ts index e53426a..4068224 100644 --- a/src/server.ts +++ b/src/server.ts @@ -8,8 +8,19 @@ import { verifyBypassToken, } from './doors'; import { executeDoorAction } from './doors/actions'; +import { loadDoorMeta } from './doors'; import { registerAiJailbreakDoor } from './doors/index'; import { renderWichtelWidget } from './doors/wichtel'; +import { + addLeaderboardEntry, + getAllLeaderboards, + getLeaderboardForDoor, +} from './doors/leaderboard'; +import { + renderLeaderboardPage, + renderLeaderboardRuntimeScript, + type LeaderboardPageDoor, +} from './views/leaderboard'; import { IpRateLimiter, sleep } from './security/rateLimiter'; import { renderForbiddenBypassPage, @@ -123,6 +134,87 @@ app.get('/health', (_req: Request, res: Response) => { res.json({ status: 'ok' }); }); +// --------------------------------------------------------------------------- +// Bestenlisten: Aufrufbar über den extra Link /leaderboard +// --------------------------------------------------------------------------- + +app.get('/leaderboard', (_req: Request, res: Response) => { + const doors: LeaderboardPageDoor[] = getAllLeaderboards().map(({ doorId, entries }) => { + const door = loadDoorMeta(doorId, Number.parseInt(doorId, 10)); + return { doorId, day: door.day, title: door.title, entries }; + }); + res.type('html').send(renderLeaderboardPage(doors)); +}); + +app.get('/api/leaderboard', (_req: Request, res: Response) => { + res.json({ doors: getAllLeaderboards() }); +}); + +app.get('/api/door/:token/leaderboard', (req: Request, res: Response) => { + if (!ensureNotBlocked(req, res, true)) { + return; + } + const door = findDoorByToken(extractParam(req.params.token)); + if (!door) { + res.status(404).json({ error: 'Türchen nicht gefunden' }); + return; + } + res.json({ doorId: door.id, top: getLeaderboardForDoor(door.id).slice(0, 10) }); +}); + +app.post('/api/door/:token/leaderboard', async (req: Request, res: Response) => { + if (!ensureNotBlocked(req, res, true)) { + return; + } + + const door = findDoorByToken(extractParam(req.params.token)); + if (!door) { + await handleAuthFailure(req, res, 404, 'Türchen nicht gefunden', renderNotFoundPage, true); + return; + } + + const bypassCandidate = extractBypassCandidate(req); + let isBypassValid = false; + if (bypassCandidate !== undefined) { + isBypassValid = verifyBypassToken(bypassCandidate); + if (!isBypassValid) { + await handleAuthFailure(req, res, 403, 'Ungültiges Vorschau-Passwort', renderForbiddenBypassPage, true); + return; + } + } + + const unlockState = getUnlockState(door.day, isBypassValid); + if (!unlockState.isUnlocked) { + res.status(403).json({ + error: `${door.title} ist noch verschlossen.`, + unlockDateIso: unlockState.unlockDateIso, + }); + return; + } + + const payload = + req.body && typeof req.body === 'object' && !Array.isArray(req.body) + ? (req.body as Record) + : {}; + const name = typeof payload.name === 'string' ? payload.name : ''; + const durationMs = typeof payload.durationMs === 'number' ? payload.durationMs : Number.NaN; + + try { + const result = addLeaderboardEntry(door.id, name, durationMs); + res.json({ + ok: true, + doorId: door.id, + rank: result.rank, + total: result.total, + top10: result.top10, + }); + } catch (error) { + res.status(400).json({ + error: error instanceof Error ? error.message : 'Eintrag konnte nicht gespeichert werden.', + }); + } +}); + app.get('/', (_req: Request, res: Response) => { res.type('html').send(renderHomePage()); }); diff --git a/src/views.ts b/src/views.ts index 5064e81..8bd5a66 100644 --- a/src/views.ts +++ b/src/views.ts @@ -8,6 +8,7 @@ import { renderWinterBackdropSvg, } from './views/assets'; import { renderInteractiveScript } from './views/interactiveScript'; +import { renderLeaderboardRuntimeScript } from './views/leaderboard'; function escapeHtml(value: string): string { return value @@ -1227,5 +1228,8 @@ export function renderUnlockedDoorPage( })(); `; - return renderLayout(door.title, body, script); + // Bestenlisten-Timer + Namensdialog (Start = Öffnen, Ende = solved:true) + const leaderboardScript = renderLeaderboardRuntimeScript(token.trim(), door.id, bypassQuery); + + return renderLayout(door.title, body, script + leaderboardScript); } diff --git a/src/views/leaderboard.ts b/src/views/leaderboard.ts new file mode 100644 index 0000000..3d66a14 --- /dev/null +++ b/src/views/leaderboard.ts @@ -0,0 +1,397 @@ +/** + * Leaderboard-Ansichten. + * + * 1. renderLeaderboardRuntimeScript: muss auf jeder Türchen-Seite geladen werden. + * - Start der Zeitmessung: Öffnen des Türchens (Inhalt wird gemountet), + * gemerkt in localStorage, damit ein Reload die Zeit nicht nullt. + * - Ende: erste Server-Antwort einer Türchen-Aktion mit solved: true + * (z. B. Codewort abgeschickt). Danach erscheint der Namens-Dialog. + * + * 2. renderLeaderboardPage: eigenständige Bestenlisten-Seite unter /leaderboard. + */ + +function escapeHtmlValue(value: string): string { + return value + .replace(/&/g, '&') + .replace(//g, '>') + .replace(/"/g, '"') + .replace(/'/g, '''); +} + +function formatDurationMs(durationMs: number): string { + const totalSeconds = Math.floor(durationMs / 1000); + const hours = Math.floor(totalSeconds / 3600); + const minutes = Math.floor((totalSeconds % 3600) / 60); + const seconds = totalSeconds % 60; + const pad = (n: number) => String(n).padStart(2, '0'); + return hours > 0 + ? `${hours}:${pad(minutes)}:${pad(seconds)}` + : `${minutes}:${pad(seconds)}`; +} + +export interface LeaderboardPageDoor { + doorId: string; + day: number; + title: string; + entries: { name: string; durationMs: number; dateIso: string }[]; +} + +/** + * Laufzeit-Skript für Türchen-Seiten: Timer, fetch-Abo auf solved:true, + * Namensdialog und Eintrag per POST /api/door/:token/leaderboard. + */ +export function renderLeaderboardRuntimeScript(token: string, doorId: string, bypassQuery: string): string { + return ``; +} + +/** + * Eigenständige Bestenlisten-Seite (Link /leaderboard). + */ +export function renderLeaderboardPage(doors: LeaderboardPageDoor[]): string { + const sections = doors.length + ? doors.map((door) => { + const rows = door.entries.slice(0, 10).map((entry, index) => { + const rank = index + 1; + const medal = rank === 1 ? '🥇' : rank === 2 ? '🥈' : rank === 3 ? '🥉' : String(rank); + const dateLabel = escapeHtmlValue( + new Intl.DateTimeFormat('de-DE', { day: '2-digit', month: '2-digit', year: '2-digit' }) + .format(new Date(entry.dateIso)), + ); + return ` + + ${medal} + ${formatDurationMs(entry.durationMs)} + ${escapeHtmlValue(entry.name)} + ${dateLabel} + `; + }).join(''); + + return ` +
+

${door.day} ${escapeHtmlValue(door.title)}

+ + + + + ${rows} +
#ZeitNameDatum
+
`; + }).join('') + : ` +
+

Noch keine Einträge

+

Sobald ein Minispiel gelöst ist, erscheinen hier die besten Zeiten.

+
`; + + return ` + + + + + + Bestenlisten – Adventskalender + + + +
+
+

🏆 Bestenlisten

+

Die schnellsten Runden durch die Türchen – Start ab dem Öffnen bis zur richtigen Lösung.

+
+ ${sections} + +
+ +`; +}