Game Library: Admin-Panel, Disconnect-UI, IGDB-Cache

- Admin-Panel mit Login (gleiches Passwort wie Soundboard) zum Entfernen
  von Profilen inkl. aller verknuepften Daten
- Disconnect-Buttons im Profil-Detail: Steam/GOG einzeln trennbar
- IGDB persistenter File-Cache (ueberlebt Server-Neustarts)
- SSE-Broadcast-Format korrigiert (buildProfileSummaries shared helper)
- DELETE-Endpoints fuer Profil/Steam/GOG Trennung

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
This commit is contained in:
Daniel 2026-03-08 16:53:01 +01:00
parent d2f2607c06
commit 71b35d573e
4 changed files with 786 additions and 49 deletions

View file

@ -2,8 +2,12 @@
// IGDB (Internet Game Database) API service
// Uses Twitch OAuth for authentication. All requests go through a simple
// throttle so we never exceed the 4 req/s rate-limit.
// Includes a persistent file-based cache so results survive server restarts.
// ──────────────────────────────────────────────────────────────────────────────
import fs from 'node:fs';
import path from 'node:path';
const TWITCH_CLIENT_ID = 'n6u8unhmwvhzsrvw2d2nb2a3qxapsl';
const TWITCH_CLIENT_SECRET = 'h6f6g2r6yyxkfg2xsob0jt8p994s7v';
const TWITCH_AUTH_URL = 'https://id.twitch.tv/oauth2/token';
@ -247,17 +251,84 @@ export async function lookupGame(
return lookupByName(gameName);
}
// ── Batch enrichment ─────────────────────────────────────────────────────────
// ── Persistent file-based cache ──────────────────────────────────────────────
/** In-memory cache keyed by Steam appid. Persists for the server lifetime. */
/** In-memory cache keyed by Steam appid. Loaded from disk on startup. */
const enrichmentCache = new Map<number, IgdbGameInfo>();
/** Cache for name-based lookups (GOG games etc.), keyed by lowercase game name */
const nameCache = new Map<string, IgdbGameInfo>();
let cacheFilePath: string | null = null;
let cacheDirty = false;
let cacheSaveTimer: ReturnType<typeof setTimeout> | null = null;
/**
* Initialize the persistent IGDB cache.
* Call once during plugin init with the data directory path.
*/
export function initIgdbCache(dataDir: string): void {
cacheFilePath = path.join(dataDir, 'igdb-cache.json');
try {
if (fs.existsSync(cacheFilePath)) {
const raw = fs.readFileSync(cacheFilePath, 'utf-8');
const parsed = JSON.parse(raw) as { appid: Record<string, IgdbGameInfo>; name?: Record<string, IgdbGameInfo> };
// Load appid-keyed cache
if (parsed.appid) {
for (const [key, value] of Object.entries(parsed.appid)) {
enrichmentCache.set(Number(key), value);
}
}
// Load name-keyed cache
if (parsed.name) {
for (const [key, value] of Object.entries(parsed.name)) {
nameCache.set(key, value);
}
}
console.log(`[IGDB] Cache loaded: ${enrichmentCache.size} appid entries, ${nameCache.size} name entries`);
}
} catch (err) {
console.error('[IGDB] Failed to load cache:', err);
}
}
/** Save cache to disk (debounced — writes at most every 5 seconds). */
function scheduleCacheSave(): void {
if (!cacheFilePath) return;
cacheDirty = true;
if (cacheSaveTimer) return; // already scheduled
cacheSaveTimer = setTimeout(() => {
cacheSaveTimer = null;
if (!cacheDirty || !cacheFilePath) return;
cacheDirty = false;
try {
const dir = path.dirname(cacheFilePath);
if (!fs.existsSync(dir)) fs.mkdirSync(dir, { recursive: true });
const appidObj: Record<string, IgdbGameInfo> = {};
for (const [k, v] of enrichmentCache) appidObj[String(k)] = v;
const nameObj: Record<string, IgdbGameInfo> = {};
for (const [k, v] of nameCache) nameObj[k] = v;
fs.writeFileSync(cacheFilePath, JSON.stringify({ appid: appidObj, name: nameObj }), 'utf-8');
} catch (err) {
console.error('[IGDB] Failed to save cache:', err);
}
}, 5000);
}
// ── Batch enrichment ─────────────────────────────────────────────────────────
/**
* Enrich a list of Steam games with IGDB metadata.
*
* - Processes in batches of 4 (respecting the 4 req/s rate limit).
* - 300 ms pause between batches.
* - Uses an in-memory cache so repeated calls for the same appid are free.
* - Uses a persistent file-based cache so results survive restarts.
*
* @returns Map keyed by Steam appid IgdbGameInfo (only matched games)
*/
@ -310,9 +381,66 @@ export async function enrichGames(
await Promise.all(promises);
}
// Persist cache to disk
scheduleCacheSave();
console.log(
`[IGDB] Enrichment complete: ${result.size}/${games.length} games matched`,
);
return result;
}
/**
* Enrich a list of games by name (for GOG games that don't have Steam appids).
*
* @returns Map keyed by lowercase game name IgdbGameInfo
*/
export async function enrichGamesByName(
names: string[],
): Promise<Map<string, IgdbGameInfo>> {
const result = new Map<string, IgdbGameInfo>();
const toFetch: string[] = [];
for (const name of names) {
const key = name.toLowerCase();
const cached = nameCache.get(key);
if (cached) {
result.set(key, cached);
} else {
toFetch.push(name);
}
}
if (toFetch.length === 0) {
return result;
}
console.log(`[IGDB] Name lookup: ${result.size} cache hits, ${toFetch.length} to fetch`);
const BATCH_SIZE = 4;
for (let i = 0; i < toFetch.length; i += BATCH_SIZE) {
if (i > 0) {
await new Promise((resolve) => setTimeout(resolve, 300));
}
const batch = toFetch.slice(i, i + BATCH_SIZE);
const promises = batch.map(async (name) => {
try {
const info = await lookupByName(name);
if (info) {
const key = name.toLowerCase();
nameCache.set(key, info);
result.set(key, info);
}
} catch (err) {
console.error(`[IGDB] Error looking up "${name}":`, err);
}
});
await Promise.all(promises);
}
scheduleCacheSave();
return result;
}

View file

@ -4,7 +4,7 @@ import { sseBroadcast } from '../../core/sse.js';
import fs from 'node:fs';
import path from 'node:path';
import crypto from 'node:crypto';
import { lookupGame, enrichGames, type IgdbGameInfo } from './igdb.js';
import { lookupGame, enrichGames, enrichGamesByName, initIgdbCache, type IgdbGameInfo } from './igdb.js';
import { getGogAuthUrl, exchangeGogCode, refreshGogToken, fetchGogUserInfo, fetchGogGames, type GogGame } from './gog.js';
// ── Types ──
@ -56,6 +56,37 @@ interface GameLibraryData {
const STEAM_API_KEY = process.env.STEAM_API_KEY || '2481D43449821AA4FF66502A9166DF32';
// ── Admin auth helpers (same system as soundboard) ──
function readCookie(req: express.Request, name: string): string | undefined {
const raw = req.headers.cookie || '';
const match = raw.match(new RegExp(`(?:^|;\\s*)${name}=([^;]*)`));
return match ? decodeURIComponent(match[1]) : undefined;
}
function b64url(str: string): string {
return Buffer.from(str).toString('base64url');
}
function verifyAdminToken(adminPwd: string, token: string | undefined): boolean {
if (!token || !adminPwd) return false;
const [body, sig] = token.split('.');
if (!body || !sig) return false;
const expected = crypto.createHmac('sha256', adminPwd).update(body).digest('base64url');
if (expected !== sig) return false;
try {
const payload = JSON.parse(Buffer.from(body, 'base64').toString('utf8')) as { iat: number; exp: number };
return typeof payload.exp === 'number' && Date.now() < payload.exp;
} catch { return false; }
}
function signAdminToken(adminPwd: string): string {
const payload = { iat: Date.now(), exp: Date.now() + 7 * 24 * 3600_000 };
const body = b64url(JSON.stringify(payload));
const sig = crypto.createHmac('sha256', adminPwd).update(body).digest('base64url');
return `${body}.${sig}`;
}
// ── Data Persistence ──
function getDataPath(ctx: PluginContext): string {
@ -87,24 +118,27 @@ function saveData(ctx: PluginContext, data: GameLibraryData): void {
// ── SSE Broadcast ──
function buildProfileSummaries(data: GameLibraryData) {
return Object.values(data.profiles || {}).map(p => {
const steam = p.steamId ? data.users[p.steamId] : null;
const gog = p.gogUserId ? data.gogUsers?.[p.gogUserId] : null;
return {
id: p.id,
displayName: p.displayName,
avatarUrl: p.avatarUrl,
platforms: {
steam: steam ? { steamId: steam.steamId, personaName: steam.personaName, gameCount: steam.games.length } : null,
gog: gog ? { gogUserId: gog.gogUserId, username: gog.username, gameCount: gog.games.length } : null,
},
totalGames: (steam?.games.length || 0) + (gog?.games.length || 0),
lastUpdated: p.lastUpdated,
};
});
}
function broadcastUpdate(data: GameLibraryData): void {
const users = Object.values(data.users).map(u => ({
steamId: u.steamId,
personaName: u.personaName,
avatarUrl: u.avatarUrl,
gameCount: u.games.length,
lastUpdated: u.lastUpdated,
}));
const profiles = Object.values(data.profiles || {}).map(p => ({
id: p.id,
displayName: p.displayName,
avatarUrl: p.avatarUrl,
steamId: p.steamId,
gogUserId: p.gogUserId,
totalGames: (p.steamId && data.users[p.steamId] ? data.users[p.steamId].games.length : 0) +
(p.gogUserId && data.gogUsers?.[p.gogUserId] ? data.gogUsers[p.gogUserId].games.length : 0),
}));
sseBroadcast({ type: 'game_library_update', plugin: 'game-library', users, profiles });
const profiles = buildProfileSummaries(data);
sseBroadcast({ type: 'game_library_update', plugin: 'game-library', profiles });
}
// ── Steam API Helpers ──
@ -151,6 +185,9 @@ const gameLibraryPlugin: Plugin = {
description: 'Steam Spielebibliothek',
async init(ctx) {
// Initialize persistent IGDB cache
initIgdbCache(ctx.dataDir);
const data = loadData(ctx); // ensure file exists
// Migrate: ensure gogUsers and profiles exist
@ -595,22 +632,7 @@ const gameLibraryPlugin: Plugin = {
// ── GET /api/game-library/profiles ──
app.get('/api/game-library/profiles', (_req, res) => {
const data = loadData(ctx);
const profiles = Object.values(data.profiles).map(p => {
const steam = p.steamId ? data.users[p.steamId] : null;
const gog = p.gogUserId ? data.gogUsers[p.gogUserId] : null;
return {
id: p.id,
displayName: p.displayName,
avatarUrl: p.avatarUrl,
platforms: {
steam: steam ? { steamId: steam.steamId, personaName: steam.personaName, gameCount: steam.games.length } : null,
gog: gog ? { gogUserId: gog.gogUserId, username: gog.username, gameCount: gog.games.length } : null,
},
totalGames: (steam?.games.length || 0) + (gog?.games.length || 0),
lastUpdated: p.lastUpdated,
};
});
res.json({ profiles });
res.json({ profiles: buildProfileSummaries(data) });
});
// ── GOG Login (redirect to GOG auth page) ──
@ -774,19 +796,180 @@ const gameLibraryPlugin: Plugin = {
console.log(`[GameLibrary] Benutzer entfernt: ${personaName} (${steamId})`);
res.json({ success: true, message: `${personaName} wurde entfernt.` });
});
// ── DELETE /api/game-library/profile/:profileId/steam ── Unlink Steam
app.delete('/api/game-library/profile/:profileId/steam', (req, res) => {
const data = loadData(ctx);
const profile = data.profiles[req.params.profileId];
if (!profile) { res.status(404).json({ error: 'Profil nicht gefunden.' }); return; }
if (!profile.steamId) { res.status(400).json({ error: 'Kein Steam-Konto verknuepft.' }); return; }
const steamId = profile.steamId;
const name = data.users[steamId]?.personaName || steamId;
delete profile.steamId;
profile.lastUpdated = new Date().toISOString();
// Wenn kein anderes Profil diesen Steam-User nutzt, Daten entfernen
const stillUsed = Object.values(data.profiles).some(p => p.steamId === steamId);
if (!stillUsed) delete data.users[steamId];
// Profil löschen wenn keine Plattform mehr verknüpft
if (!profile.steamId && !profile.gogUserId) {
delete data.profiles[req.params.profileId];
console.log(`[GameLibrary] Profil geloescht (keine Plattformen): ${profile.displayName}`);
}
saveData(ctx, data);
broadcastUpdate(data);
console.log(`[GameLibrary] Steam getrennt: ${name} von ${profile.displayName}`);
res.json({ ok: true });
});
// ── DELETE /api/game-library/profile/:profileId/gog ── Unlink GOG
app.delete('/api/game-library/profile/:profileId/gog', (req, res) => {
const data = loadData(ctx);
const profile = data.profiles[req.params.profileId];
if (!profile) { res.status(404).json({ error: 'Profil nicht gefunden.' }); return; }
if (!profile.gogUserId) { res.status(400).json({ error: 'Kein GOG-Konto verknuepft.' }); return; }
const gogUserId = profile.gogUserId;
const name = data.gogUsers?.[gogUserId]?.username || gogUserId;
delete profile.gogUserId;
profile.lastUpdated = new Date().toISOString();
// Wenn kein anderes Profil diesen GOG-User nutzt, Daten entfernen
const stillUsed = Object.values(data.profiles).some(p => p.gogUserId === gogUserId);
if (!stillUsed && data.gogUsers) delete data.gogUsers[gogUserId];
// Profil löschen wenn keine Plattform mehr verknüpft
if (!profile.steamId && !profile.gogUserId) {
delete data.profiles[req.params.profileId];
console.log(`[GameLibrary] Profil geloescht (keine Plattformen): ${profile.displayName}`);
}
saveData(ctx, data);
broadcastUpdate(data);
console.log(`[GameLibrary] GOG getrennt: ${name} von ${profile.displayName}`);
res.json({ ok: true });
});
// ── DELETE /api/game-library/profile/:profileId ── Ganzes Profil löschen
app.delete('/api/game-library/profile/:profileId', (req, res) => {
const data = loadData(ctx);
const profile = data.profiles[req.params.profileId];
if (!profile) { res.status(404).json({ error: 'Profil nicht gefunden.' }); return; }
const displayName = profile.displayName;
// Zugehörige Daten aufräumen wenn nicht anderweitig genutzt
if (profile.steamId) {
const stillUsed = Object.values(data.profiles).some(p => p.id !== profile.id && p.steamId === profile.steamId);
if (!stillUsed) delete data.users[profile.steamId];
}
if (profile.gogUserId) {
const stillUsed = Object.values(data.profiles).some(p => p.id !== profile.id && p.gogUserId === profile.gogUserId);
if (!stillUsed && data.gogUsers) delete data.gogUsers[profile.gogUserId];
}
delete data.profiles[req.params.profileId];
saveData(ctx, data);
broadcastUpdate(data);
console.log(`[GameLibrary] Profil geloescht: ${displayName}`);
res.json({ ok: true });
});
// ═══════════════════════════════════════════════════════════════════
// Admin endpoints (same auth as soundboard)
// ═══════════════════════════════════════════════════════════════════
const requireAdmin = (req: express.Request, res: express.Response, next: () => void) => {
if (!ctx.adminPwd) { res.status(503).json({ error: 'Admin nicht konfiguriert' }); return; }
if (!verifyAdminToken(ctx.adminPwd, readCookie(req, 'admin'))) {
res.status(401).json({ error: 'Nicht eingeloggt' });
return;
}
next();
};
// ── GET /api/game-library/admin/status ──
app.get('/api/game-library/admin/status', (req, res) => {
if (!ctx.adminPwd) { res.json({ admin: false, configured: false }); return; }
const valid = verifyAdminToken(ctx.adminPwd, readCookie(req, 'admin'));
res.json({ admin: valid, configured: true });
});
// ── POST /api/game-library/admin/login ──
app.post('/api/game-library/admin/login', (req, res) => {
const password = String(req.body?.password || '');
if (!ctx.adminPwd) { res.status(503).json({ error: 'Admin nicht konfiguriert' }); return; }
if (password !== ctx.adminPwd) { res.status(401).json({ error: 'Falsches Passwort' }); return; }
const token = signAdminToken(ctx.adminPwd);
res.setHeader('Set-Cookie', `admin=${token}; HttpOnly; Path=/; Max-Age=${7 * 24 * 3600}; SameSite=Lax`);
res.json({ ok: true });
});
// ── POST /api/game-library/admin/logout ──
app.post('/api/game-library/admin/logout', (_req, res) => {
res.setHeader('Set-Cookie', 'admin=; HttpOnly; Path=/; Max-Age=0; SameSite=Lax');
res.json({ ok: true });
});
// ── GET /api/game-library/admin/profiles ── Alle Profile mit Details
app.get('/api/game-library/admin/profiles', requireAdmin, (_req, res) => {
const data = loadData(ctx);
const profiles = Object.values(data.profiles).map(p => {
const steam = p.steamId ? data.users[p.steamId] : null;
const gog = p.gogUserId ? data.gogUsers?.[p.gogUserId] : null;
return {
id: p.id,
displayName: p.displayName,
avatarUrl: p.avatarUrl,
steamId: p.steamId || null,
steamName: steam?.personaName || null,
steamGames: steam?.games.length || 0,
gogUserId: p.gogUserId || null,
gogName: gog?.username || null,
gogGames: gog?.games.length || 0,
totalGames: (steam?.games.length || 0) + (gog?.games.length || 0),
lastUpdated: p.lastUpdated,
};
});
res.json({ profiles });
});
// ── DELETE /api/game-library/admin/profile/:profileId ── Admin löscht Profil
app.delete('/api/game-library/admin/profile/:profileId', requireAdmin, (req, res) => {
const data = loadData(ctx);
const profileId = String(req.params.profileId);
const profile = data.profiles[profileId];
if (!profile) { res.status(404).json({ error: 'Profil nicht gefunden.' }); return; }
const displayName = profile.displayName;
if (profile.steamId) {
const stillUsed = Object.values(data.profiles).some(p => p.id !== profile.id && p.steamId === profile.steamId);
if (!stillUsed) delete data.users[profile.steamId];
}
if (profile.gogUserId) {
const stillUsed = Object.values(data.profiles).some(p => p.id !== profile.id && p.gogUserId === profile.gogUserId);
if (!stillUsed && data.gogUsers) delete data.gogUsers[profile.gogUserId];
}
delete data.profiles[profileId];
saveData(ctx, data);
broadcastUpdate(data);
console.log(`[GameLibrary] Admin: Profil geloescht: ${displayName}`);
res.json({ ok: true, displayName });
});
},
getSnapshot(ctx) {
const data = loadData(ctx);
return {
'game-library': {
users: Object.values(data.users).map(u => ({
steamId: u.steamId,
personaName: u.personaName,
avatarUrl: u.avatarUrl,
gameCount: u.games.length,
lastUpdated: u.lastUpdated,
})),
profiles: buildProfileSummaries(data),
},
};
},