-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.js
More file actions
3080 lines (2747 loc) · 162 KB
/
Copy pathserver.js
File metadata and controls
3080 lines (2747 loc) · 162 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// ============================================================
// Gameparty - Express + SQLite Backend
// ============================================================
const express = require('express');
const compression = require('compression');
const Database = require('better-sqlite3');
const cors = require('cors');
const path = require('path');
const fs = require('fs');
const crypto = require('crypto');
const { version } = require('./package.json');
// ---- Logger (define early, before DB) ----
const logBuffer = [];
const LOG_MAX = 500;
const LOG_LEVEL = (process.env.LOG_LEVEL || 'INFO').toUpperCase(); // OFF | INFO | DEBUG
function log(level, message) {
const entry = { ts: new Date().toLocaleString('sv-SE', { timeZone: process.env.TZ || 'Europe/Berlin' }), level, message };
logBuffer.push(entry);
if (logBuffer.length > LOG_MAX) logBuffer.shift();
if (LOG_LEVEL === 'OFF') return;
if (level === 'DEBUG' && LOG_LEVEL !== 'DEBUG') return;
console[level === 'ERROR' ? 'error' : 'log'](`[${entry.ts}] [${level}] ${message}`);
}
const logger = {
info: (msg) => log('INFO', msg),
error: (msg) => log('ERROR', msg),
debug: (msg) => log('DEBUG', msg),
};
const app = express();
const PORT = process.env.PORT || 3000;
// Global shop cooldowns (in-memory, reset on server restart)
const shopGlobalCooldownTs = {}; // { itemId: timestamp }
const shopLocalCooldownTs = {}; // { player: { itemId: timestamp } }
app.use(cors());
app.use(compression());
app.use(express.json());
// index.html mit versionierten Asset-URLs ausliefern (Cache-Busting)
app.get('/', (req, res) => {
let html = fs.readFileSync(path.join(__dirname, 'index.html'), 'utf8');
html = html
.replace('css/style.css"', `css/style.css?v=${version}"`)
.replace('js/i18n.js"', `js/i18n.js?v=${version}"`)
.replace('js/data.js"', `js/data.js?v=${version}"`)
.replace('js/app.js"', `js/app.js?v=${version}"`);
res.setHeader('Cache-Control', 'no-store');
res.send(html);
});
app.use(express.static(path.join(__dirname), {
setHeaders(res, filePath) {
if (/\.(js|css|svg|png|jpg|jpeg|webp|ico|woff2?)$/.test(filePath)) {
res.setHeader('Cache-Control', 'public, max-age=31536000, immutable');
}
}
}));
// ---- RAWG: Static file serving for downloaded covers + screenshots ----
const gamefilesDir = process.env.GAMEFILES_PATH || path.join(__dirname, 'gamefiles');
const coversDir = path.join(gamefilesDir, 'covers');
const screenshotsDir = path.join(gamefilesDir, 'screenshots');
fs.mkdirSync(coversDir, { recursive: true });
fs.mkdirSync(screenshotsDir, { recursive: true });
app.use('/gamefiles', express.static(gamefilesDir));
// ---- Server-Sent Events ----
const sseClients = new Set();
function broadcast() {
sseClients.forEach(res => res.write('event: update\ndata: {}\n\n'));
}
// Broadcast nach jedem erfolgreichen POST/PUT/DELETE
app.use((req, res, next) => {
if (req.method === 'GET') return next();
const originalJson = res.json.bind(res);
res.json = (data) => {
originalJson(data);
if (data && !data.error) broadcast();
};
next();
});
// Kein Cache für alle API-Routen
app.use('/api', (req, res, next) => {
res.setHeader('Cache-Control', 'no-store');
next();
});
// ---- Auth middleware ----
const SESSION_TTL_MS = 30 * 24 * 60 * 60 * 1000;
function requireAuth(req, res, next) {
const header = req.headers['authorization'] || '';
const token = header.startsWith('Bearer ') ? header.slice(7) : null;
if (!token) return res.status(401).json({ error: 'Nicht angemeldet' });
const s = db.prepare('SELECT player, role, created_at FROM auth_sessions WHERE token = ?').get(token);
if (!s) return res.status(401).json({ error: 'Sitzung abgelaufen' });
if (Date.now() - s.created_at > SESSION_TTL_MS) {
db.prepare('DELETE FROM auth_sessions WHERE token = ?').run(token);
return res.status(401).json({ error: 'Sitzung abgelaufen' });
}
req.authPlayer = s.player;
req.authRole = s.role;
next();
}
const PUBLIC_ROUTES = [
{ method: 'POST', path: '/login' },
{ method: 'POST', path: '/logout' },
{ method: 'GET', path: '/users' },
{ method: 'GET', path: '/events' },
{ method: 'GET', path: '/logs' },
{ method: 'GET', path: '/time' },
{ method: 'GET', path: '/init' },
{ method: 'GET', path: '/settings' },
];
app.use('/api', (req, res, next) => {
if (PUBLIC_ROUTES.some(p => p.method === req.method && req.path === p.path)) return next();
requireAuth(req, res, next);
});
// GET /api/time — server timestamp for client clock sync
app.get('/api/time', (req, res) => res.json({ now: Date.now() }));
// GET /api/logs
app.get('/api/logs', (req, res) => {
const level = req.query.level || 'ALL';
const limit = Math.min(parseInt(req.query.limit || '200'), 500);
let entries = logBuffer;
if (level !== 'ALL') entries = entries.filter(e => e.level === level);
res.json(entries.slice(-limit).reverse()); // newest first
});
app.get('/api/events', (req, res) => {
const qToken = req.query.token;
if (qToken) {
const s = db.prepare('SELECT player FROM auth_sessions WHERE token = ?').get(qToken);
if (!s) { res.status(401).end(); return; }
}
res.setHeader('Content-Type', 'text/event-stream');
res.setHeader('Cache-Control', 'no-cache');
res.setHeader('Connection', 'keep-alive');
res.flushHeaders();
sseClients.add(res);
logger.debug('SSE client connected');
// Heartbeat alle 25s damit die Verbindung nicht vom Browser gekappt wird
const heartbeat = setInterval(() => res.write(':\n\n'), 25000);
req.on('close', () => { sseClients.delete(res); clearInterval(heartbeat); logger.debug('SSE client disconnected'); });
});
// ---- Database Setup ----
const db = new Database(process.env.DB_PATH || path.join(__dirname, 'gameparty.db'));
db.pragma('journal_mode = WAL');
db.pragma('foreign_keys = ON');
logger.info('Database initialized');
// Migration: rename stars table BEFORE CREATE TABLE runs (must happen first)
{
const hasStarsTable = db.prepare("SELECT name FROM sqlite_master WHERE type='table' AND name='stars'").get();
const hasControllerpoints = db.prepare("SELECT name FROM sqlite_master WHERE type='table' AND name='controllerpoints'").get();
if (hasStarsTable && !hasControllerpoints) {
// Simple rename — controllerpoints doesn't exist yet
db.prepare('ALTER TABLE stars RENAME TO controllerpoints').run();
} else if (hasStarsTable && hasControllerpoints) {
// Both tables exist: copy data from old stars table, then drop it
db.prepare('INSERT OR REPLACE INTO controllerpoints (player, amount) SELECT player, amount FROM stars').run();
db.prepare('DROP TABLE stars').run();
}
}
db.exec(`
CREATE TABLE IF NOT EXISTS users (name TEXT PRIMARY KEY, pin TEXT, role TEXT DEFAULT 'player');
CREATE TABLE IF NOT EXISTS games (id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT UNIQUE, maxPlayers INT, genre TEXT, lanRating INT DEFAULT 0, previewUrl TEXT, ready INT DEFAULT 0, status TEXT DEFAULT 'approved', suggestedBy TEXT, sessionCoins INT DEFAULT 0, shop_links TEXT DEFAULT '[]');
CREATE TABLE IF NOT EXISTS game_players (game_id INT, player TEXT, PRIMARY KEY(game_id, player));
CREATE TABLE IF NOT EXISTS coins (player TEXT PRIMARY KEY, amount INT DEFAULT 0);
CREATE TABLE IF NOT EXISTS history (id INTEGER PRIMARY KEY AUTOINCREMENT, player TEXT, amount INT, reason TEXT, timestamp INT);
CREATE TABLE IF NOT EXISTS sessions (id INTEGER PRIMARY KEY AUTOINCREMENT, game TEXT, players TEXT, coinsPerPlayer INT, timestamp INT);
CREATE TABLE IF NOT EXISTS tokens (id INTEGER PRIMARY KEY AUTOINCREMENT, player TEXT, type TEXT, timestamp INT);
CREATE TABLE IF NOT EXISTS genres_played (player TEXT, genre TEXT, PRIMARY KEY(player, genre));
CREATE TABLE IF NOT EXISTS proposals (id TEXT PRIMARY KEY, game TEXT, isNewGame INT, leader TEXT, status TEXT, scheduledTime TEXT, scheduledDay TEXT, message TEXT, createdAt INT, approvedAt INT, startedAt INT, completedAt INT, pendingCoins INT, coinsApproved INT);
CREATE TABLE IF NOT EXISTS proposal_players (proposal_id TEXT, player TEXT, PRIMARY KEY(proposal_id, player));
CREATE TABLE IF NOT EXISTS attendees (player TEXT PRIMARY KEY);
CREATE TABLE IF NOT EXISTS settings (key TEXT PRIMARY KEY, value TEXT);
CREATE TABLE IF NOT EXISTS controllerpoints (player TEXT PRIMARY KEY, amount INT DEFAULT 0);
CREATE TABLE IF NOT EXISTS challenges (
id TEXT PRIMARY KEY,
challenger TEXT,
opponent TEXT,
game TEXT,
stakeCoins INT DEFAULT 0,
stakeControllerpoints INT DEFAULT 0,
status TEXT DEFAULT 'pending',
winner TEXT,
createdAt INT,
resolvedAt INT
);
CREATE TABLE IF NOT EXISTS team_challenges (
id TEXT PRIMARY KEY,
game TEXT,
stakeCoinsPerPerson INT DEFAULT 0,
stakeControllerpointsPerPerson INT DEFAULT 0,
teamA TEXT,
teamB TEXT,
status TEXT DEFAULT 'pending',
winnerTeam TEXT,
createdBy TEXT,
createdAt INT,
resolvedAt INT
);
CREATE TABLE IF NOT EXISTS ffa_challenges (
id TEXT PRIMARY KEY,
game TEXT,
stakeCoinsPerPerson INT DEFAULT 0,
stakeControllerpointsPerPerson INT DEFAULT 0,
players TEXT,
status TEXT DEFAULT 'pending',
placements TEXT DEFAULT NULL,
payoutConfig TEXT DEFAULT NULL,
createdBy TEXT,
createdAt INT,
resolvedAt INT,
acceptances TEXT DEFAULT '[]'
);
CREATE TABLE IF NOT EXISTS player_events (
id INTEGER PRIMARY KEY AUTOINCREMENT,
target TEXT,
type TEXT,
from_player TEXT,
message TEXT,
createdAt INT
);
CREATE TABLE IF NOT EXISTS live_sessions (
id TEXT PRIMARY KEY,
game TEXT NOT NULL,
leader TEXT NOT NULL,
startedAt INT,
endedAt INT,
status TEXT DEFAULT 'lobby',
pending_coins INT DEFAULT 0
);
CREATE TABLE IF NOT EXISTS live_session_players (
session_id TEXT,
player TEXT,
joinedAt INT,
PRIMARY KEY (session_id, player)
);
`);
// Migration: stakeStars columns in challenge tables
const challengeCols = db.prepare("PRAGMA table_info(challenges)").all().map(c => c.name);
if (challengeCols.includes('stakeStars')) {
db.prepare('ALTER TABLE challenges RENAME COLUMN stakeStars TO stakeControllerpoints').run();
db.prepare('ALTER TABLE team_challenges RENAME COLUMN stakeStars TO stakeControllerpoints').run();
db.prepare('ALTER TABLE team_challenges RENAME COLUMN stakeStarsPerPerson TO stakeControllerpointsPerPerson').run();
db.prepare('ALTER TABLE ffa_challenges RENAME COLUMN stakeStars TO stakeControllerpoints').run();
db.prepare('ALTER TABLE ffa_challenges RENAME COLUMN stakeStarsPerPerson TO stakeControllerpointsPerPerson').run();
}
// ---- Migration: deadline Feld in player_events ----
try { db.prepare('ALTER TABLE player_events ADD COLUMN deadline INTEGER').run(); } catch {}
// ---- Migration: status Feld in player_events (fuer Penalty-Queue) ----
try { db.prepare("ALTER TABLE player_events ADD COLUMN status TEXT DEFAULT 'active'").run(); } catch {}
// Bestehende Eintraege auf active setzen (falls noch nicht gesetzt)
try { db.prepare("UPDATE player_events SET status = 'active' WHERE status IS NULL").run(); } catch {}
// ---- Migration: ip Feld in users (fuer LAN-IP-Verwaltung) ----
try { db.prepare("ALTER TABLE users ADD COLUMN ip TEXT DEFAULT ''").run(); } catch {}
// Migration: Gaming account fields
['steam', 'ubisoft', 'battlenet', 'epic', 'ea', 'riot', 'discord', 'teamspeak'].forEach(col => {
try { db.prepare(`ALTER TABLE users ADD COLUMN ${col} TEXT DEFAULT ''`).run(); } catch {}
});
// ---- Migration: lang Feld in users (Sprache: 'en' oder 'de') ----
try { db.prepare("ALTER TABLE users ADD COLUMN lang TEXT DEFAULT 'en'").run(); } catch {}
// ---- Migration: medium Feld in live_sessions (fuer LAN/Steam/etc) ----
try { db.prepare("ALTER TABLE live_sessions ADD COLUMN medium TEXT DEFAULT 'lan'").run(); } catch {}
// ---- Migration: medium_account Feld in live_sessions ----
try { db.prepare("ALTER TABLE live_sessions ADD COLUMN medium_account TEXT").run(); } catch {}
// ---- Migration: medium Feld in sessions (fuer LAN/Steam/etc) ----
try { db.prepare("ALTER TABLE sessions ADD COLUMN medium TEXT DEFAULT 'lan'").run(); } catch {}
// ---- Migration: medium Feld in proposals (fuer LAN/Steam/etc) ----
try { db.prepare("ALTER TABLE proposals ADD COLUMN medium TEXT DEFAULT 'lan'").run(); } catch {}
// ---- Migration: medium_account Feld in proposals ----
try { db.prepare("ALTER TABLE proposals ADD COLUMN medium_account TEXT").run(); } catch {}
// ---- Migration: Rename steamRating to previewUrl ----
try {
db.exec('ALTER TABLE games RENAME COLUMN steamRating TO previewUrl');
console.log('Migration: steamRating → previewUrl');
} catch (e) { /* bereits migriert oder Spalte existiert nicht */ }
// ---- Migration: shop_links Feld in games ----
try { db.prepare("ALTER TABLE games ADD COLUMN shop_links TEXT DEFAULT '[]'").run(); } catch {}
// ---- Migration: RAWG fields in games ----
try { db.prepare("ALTER TABLE games ADD COLUMN cover_url TEXT DEFAULT ''").run(); } catch {}
try { db.prepare("ALTER TABLE games ADD COLUMN description TEXT DEFAULT ''").run(); } catch {}
try { db.prepare("ALTER TABLE games ADD COLUMN rating INT DEFAULT 0").run(); } catch {}
try { db.prepare("ALTER TABLE games ADD COLUMN rawg_id INT DEFAULT 0").run(); } catch {}
try { db.prepare("ALTER TABLE games ADD COLUMN platforms TEXT DEFAULT ''").run(); } catch {}
try { db.prepare("ALTER TABLE games ADD COLUMN released TEXT DEFAULT ''").run(); } catch {}
try { db.prepare("ALTER TABLE games ADD COLUMN requirements TEXT DEFAULT ''").run(); } catch {}
try { db.prepare("ALTER TABLE games ADD COLUMN screenshots TEXT DEFAULT '[]'").run(); } catch {}
// ---- Migration: pending_coins Feld in live_sessions ----
try { db.prepare("ALTER TABLE live_sessions ADD COLUMN pending_coins INT DEFAULT 0").run(); } catch {}
// ---- Migration: acceptances Feld in team_challenges ----
try { db.prepare("ALTER TABLE team_challenges ADD COLUMN acceptances TEXT DEFAULT '[]'").run(); } catch {}
// ---- Migration: payoutMode/payoutConfig fuer challenges & team_challenges ----
try { db.prepare("ALTER TABLE challenges ADD COLUMN payoutMode TEXT DEFAULT 'winner_takes_all'").run(); } catch {}
try { db.prepare("ALTER TABLE challenges ADD COLUMN payoutConfig TEXT DEFAULT NULL").run(); } catch {}
try { db.prepare("ALTER TABLE team_challenges ADD COLUMN payoutMode TEXT DEFAULT 'winner_takes_all'").run(); } catch {}
try { db.prepare("ALTER TABLE team_challenges ADD COLUMN payoutConfig TEXT DEFAULT NULL").run(); } catch {}
// ---- Migration: challenge_id und challenge_type in live_sessions ----
try { db.prepare("ALTER TABLE live_sessions ADD COLUMN challenge_id TEXT").run(); } catch {}
try { db.prepare("ALTER TABLE live_sessions ADD COLUMN challenge_type TEXT").run(); } catch {}
// ---- Migration: player slots for live_sessions ----
try { db.prepare("ALTER TABLE live_sessions ADD COLUMN max_slots INT DEFAULT 0").run(); } catch {}
try { db.prepare("ALTER TABLE proposals ADD COLUMN max_slots INT DEFAULT 0").run(); } catch {}
try { db.prepare("ALTER TABLE live_session_players ADD COLUMN slot_number INT").run(); } catch {}
// ---- Tabelle: duel_votes ----
db.exec(`CREATE TABLE IF NOT EXISTS duel_votes (
session_id TEXT,
player TEXT,
voted_for TEXT,
created_at INT,
PRIMARY KEY (session_id, player)
)`);
// Indexes für häufige WHERE-Spalten
try { db.prepare("CREATE INDEX IF NOT EXISTS idx_player_events_target ON player_events(target)").run(); } catch {}
try { db.prepare("CREATE INDEX IF NOT EXISTS idx_live_sessions_status ON live_sessions(status)").run(); } catch {}
try { db.prepare("CREATE INDEX IF NOT EXISTS idx_challenges_status ON challenges(status)").run(); } catch {}
try { db.prepare("CREATE INDEX IF NOT EXISTS idx_team_challenges_status ON team_challenges(status)").run(); } catch {}
try { db.prepare("CREATE INDEX IF NOT EXISTS idx_ffa_challenges_status ON ffa_challenges(status)").run(); } catch {}
try { db.prepare("CREATE INDEX IF NOT EXISTS idx_history_player ON history(player)").run(); } catch {}
try { db.prepare("ALTER TABLE history ADD COLUMN cp_amount INT DEFAULT 0").run(); } catch {}
try { db.prepare("ALTER TABLE live_sessions ADD COLUMN duration_min INT DEFAULT 0").run(); } catch {}
try { db.prepare("ALTER TABLE live_sessions ADD COLUMN coin_rate REAL DEFAULT 0").run(); } catch {}
try { db.prepare("ALTER TABLE sessions ADD COLUMN duration_min INT DEFAULT 0").run(); } catch {}
try { db.prepare("ALTER TABLE proposal_players ADD COLUMN slot_number INT").run(); } catch {}
// ---- Migration: payoutAmounts / collected fuer challenges, team_challenges, ffa_challenges ----
try { db.prepare("ALTER TABLE challenges ADD COLUMN payoutAmounts TEXT DEFAULT NULL").run(); } catch {}
try { db.prepare("ALTER TABLE challenges ADD COLUMN payoutStarAmounts TEXT DEFAULT NULL").run(); } catch {}
try { db.prepare("ALTER TABLE challenges ADD COLUMN collected TEXT DEFAULT '[]'").run(); } catch {}
try { db.prepare("ALTER TABLE team_challenges ADD COLUMN payoutAmounts TEXT DEFAULT NULL").run(); } catch {}
try { db.prepare("ALTER TABLE team_challenges ADD COLUMN payoutStarAmounts TEXT DEFAULT NULL").run(); } catch {}
try { db.prepare("ALTER TABLE team_challenges ADD COLUMN collected TEXT DEFAULT '[]'").run(); } catch {}
try { db.prepare("ALTER TABLE ffa_challenges ADD COLUMN payoutAmounts TEXT DEFAULT NULL").run(); } catch {}
try { db.prepare("ALTER TABLE ffa_challenges ADD COLUMN payoutStarAmounts TEXT DEFAULT NULL").run(); } catch {}
try { db.prepare("ALTER TABLE ffa_challenges ADD COLUMN collected TEXT DEFAULT '[]'").run(); } catch {}
// ---- Migration: sessionPayoutAmounts / sessionCollected fuer live_sessions collect-flow ----
try { db.prepare("ALTER TABLE live_sessions ADD COLUMN sessionPayoutAmounts TEXT DEFAULT NULL").run(); } catch {}
try { db.prepare("ALTER TABLE live_sessions ADD COLUMN sessionCollected TEXT DEFAULT '[]'").run(); } catch {}
// ---- Migration: session_id column in player_events for indexed session_payout lookup ----
try { db.prepare("ALTER TABLE player_events ADD COLUMN session_id TEXT DEFAULT NULL").run(); } catch {}
try { db.prepare("CREATE INDEX IF NOT EXISTS idx_player_events_session_id ON player_events(target, type, session_id)").run(); } catch {}
// ---- auth_sessions: server-side session tokens ----
db.exec(`CREATE TABLE IF NOT EXISTS auth_sessions (
token TEXT PRIMARY KEY,
player TEXT NOT NULL,
role TEXT NOT NULL,
created_at INTEGER NOT NULL
)`);
try { db.prepare('CREATE INDEX IF NOT EXISTS idx_auth_sessions_player ON auth_sessions(player)').run(); } catch {}
// Prune expired sessions on startup (30 days TTL)
db.prepare('DELETE FROM auth_sessions WHERE created_at < ?').run(Date.now() - 30 * 24 * 60 * 60 * 1000);
// ---- Cleanup: verwaiste Attendees (Spieler geloescht, aber noch in attendees) ----
try {
const result = db.prepare('DELETE FROM attendees WHERE player NOT IN (SELECT name FROM users)').run();
if (result.changes > 0) {
console.log(`Startup-Cleanup: ${result.changes} verwaiste Attendee-Eintraege entfernt`);
}
} catch (e) { /* Tabelle existiert noch nicht beim ersten Start */ }
// ---- Seed Data (from data.js CONFIG + FALLBACK_GAMES) ----
function seedIfEmpty() {
const userCount = db.prepare('SELECT COUNT(*) as c FROM users').get().c;
if (userCount === 0) {
console.log('Seeding initial users...');
const insertUser = db.prepare('INSERT OR IGNORE INTO users (name, pin, role) VALUES (?, ?, ?)');
const insertAttendee = db.prepare('INSERT OR IGNORE INTO attendees (player) VALUES (?)');
const insertCoin = db.prepare('INSERT OR IGNORE INTO coins (player, amount) VALUES (?, 0)');
const insertControllerpoint = db.prepare('INSERT OR IGNORE INTO controllerpoints (player, amount) VALUES (?, 0)');
const adminName = process.env.SEED_ADMIN_NAME;
const adminPin = process.env.SEED_ADMIN_PIN;
const users = (adminName && adminPin)
? [{ name: adminName, pin: adminPin, role: 'admin' }]
: [
{ name: 'Daniel', pin: '1234', role: 'admin' },
{ name: 'Martin', pin: '1111', role: 'player' },
{ name: 'Kevin', pin: '2222', role: 'player' },
{ name: 'Peter', pin: '3333', role: 'player' },
{ name: 'Julian', pin: '4444', role: 'player' },
{ name: 'Lars', pin: '5555', role: 'player' },
{ name: 'Wolf', pin: '6666', role: 'player' }
];
const seedMany = db.transaction(() => {
for (const u of users) {
insertUser.run(u.name, u.pin, u.role);
insertAttendee.run(u.name);
insertCoin.run(u.name);
insertControllerpoint.run(u.name);
}
});
seedMany();
}
}
seedIfEmpty();
// ---- Migration: Ensure existing users have controllerpoints ----
function migrateControllerpoints() {
const players = db.prepare('SELECT name FROM users').all();
const insertControllerpoint = db.prepare('INSERT OR IGNORE INTO controllerpoints (player, amount) VALUES (?, 0)');
const transaction = db.transaction(() => {
for (const u of players) insertControllerpoint.run(u.name);
});
transaction();
}
migrateControllerpoints();
// ---- Helper: Get shop price from settings (with fallback) ----
function getShopPrice(itemId, defaultPrice) {
const row = db.prepare('SELECT value FROM settings WHERE key = ?').get(`shop_price_${itemId}`);
return row ? (parseInt(row.value) || defaultPrice) : defaultPrice;
}
// ---- Helper: Check if shop item is enabled ----
function isShopItemEnabled(itemId) {
const row = db.prepare('SELECT value FROM settings WHERE key = ?').get(`shop_enabled_${itemId}`);
return row ? row.value === '1' : true; // default enabled
}
// ---- Helper: Get shop cooldown config (type + ms) from settings ----
function getShopCooldownConfig(itemId) {
const typeRow = db.prepare('SELECT value FROM settings WHERE key = ?').get(`shop_cooldown_type_${itemId}`);
const msRow = db.prepare('SELECT value FROM settings WHERE key = ?').get(`shop_cooldown_ms_${itemId}`);
return {
type: typeRow?.value || 'none',
ms: parseInt(msRow?.value || '0') || 0
};
}
// ---- Helper: Check remaining cooldown (returns ms remaining, 0 if none) ----
function checkShopCooldown(itemId, player) {
const { type, ms } = getShopCooldownConfig(itemId);
if (!ms || type === 'none') return 0;
const now = Date.now();
if (type === 'global') {
return Math.max(0, ms - (now - (shopGlobalCooldownTs[itemId] || 0)));
} else {
return Math.max(0, ms - (now - ((shopLocalCooldownTs[player] || {})[itemId] || 0)));
}
}
// ---- Helper: Set cooldown after shop action ----
function setShopCooldown(itemId, player) {
const { type, ms } = getShopCooldownConfig(itemId);
if (!ms || type === 'none') return;
const now = Date.now();
if (type === 'global') {
shopGlobalCooldownTs[itemId] = now;
} else {
if (!shopLocalCooldownTs[player]) shopLocalCooldownTs[player] = {};
shopLocalCooldownTs[player][itemId] = now;
}
}
// ---- Helper: Get game with players ----
function getGameWithPlayers(game) {
const players = db.prepare('SELECT player FROM game_players WHERE game_id = ?').all(game.id);
const playersObj = {};
players.forEach(p => { playersObj[p.player] = true; });
return {
id: game.id,
name: game.name,
maxPlayers: game.maxPlayers,
genre: game.genre || '',
lanRating: game.lanRating,
ready: !!game.ready,
status: game.status,
suggestedBy: game.suggestedBy,
shopLinks: JSON.parse(game.shop_links || '[]'),
cover_url: game.cover_url || '',
description: game.description || '',
rating: game.rating || 0,
rawg_id: game.rawg_id || 0,
platforms: game.platforms || '',
released: game.released || '',
requirements: game.requirements || '',
screenshots: game.screenshots || '[]',
players: playersObj
};
}
function getAllGamesWithPlayers() {
const games = db.prepare('SELECT * FROM games').all();
return games.map(getGameWithPlayers);
}
// ---- API Routes ----
// GET /api/init - Load everything for initial state
app.get('/api/init', (req, res) => {
const users = db.prepare('SELECT name, role, ip, lang, steam, ubisoft, battlenet, epic, ea, riot, discord, teamspeak FROM users').all();
const games = getAllGamesWithPlayers();
const coins = {};
db.prepare('SELECT player, amount FROM coins').all().forEach(r => { coins[r.player] = r.amount; });
const controllerpoints = {};
db.prepare('SELECT player, amount FROM controllerpoints').all().forEach(r => { controllerpoints[r.player] = r.amount; });
const attendees = db.prepare('SELECT player FROM attendees WHERE player IN (SELECT name FROM users)').all().map(r => r.player);
const settings = {};
db.prepare('SELECT key, value FROM settings').all().forEach(r => { settings[r.key] = r.value; });
const players = users.map(u => u.name);
res.json({ users, games, coins, controllerpoints, attendees, settings, players, version, shopCooldowns: shopGlobalCooldownTs });
});
// POST /api/login
app.post('/api/login', (req, res) => {
const { name, pin } = req.body;
const user = db.prepare('SELECT * FROM users WHERE name = ?').get(name);
if (!user || user.pin !== pin) {
return res.status(401).json({ error: 'Falsche PIN' });
}
const cutoff = Date.now() - SESSION_TTL_MS;
db.prepare('DELETE FROM auth_sessions WHERE player = ? AND created_at < ?').run(name, cutoff);
const token = crypto.randomBytes(32).toString('hex');
db.prepare('INSERT INTO auth_sessions (token, player, role, created_at) VALUES (?, ?, ?, ?)').run(token, name, user.role, Date.now());
logger.info('User login: ' + name);
res.json({ success: true, role: user.role, token });
});
// POST /api/logout
app.post('/api/logout', (req, res) => {
const header = req.headers['authorization'] || '';
const token = header.startsWith('Bearer ') ? header.slice(7) : null;
if (token) db.prepare('DELETE FROM auth_sessions WHERE token = ?').run(token);
res.json({ success: true });
});
// GET /api/games
app.get('/api/games', (req, res) => {
res.json(getAllGamesWithPlayers());
});
// POST /api/games/suggest
app.post('/api/games/suggest', (req, res) => {
const { name, genre, maxPlayers, suggestedBy, shopLinks, coverUrl, description, rating, rawgId, platforms, released, requirements, screenshots } = req.body;
if (!name) return res.status(400).json({ error: 'Name required' });
const existing = db.prepare('SELECT id FROM games WHERE LOWER(name) = LOWER(?)').get(name);
if (existing) return res.status(409).json({ error: 'Spiel existiert bereits' });
const result = db.prepare('INSERT INTO games (name, maxPlayers, genre, status, suggestedBy, shop_links, cover_url, description, rating, rawg_id, platforms, released, requirements, screenshots) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)').run(name, maxPlayers || 4, genre || '', 'suggested', suggestedBy || null, JSON.stringify(shopLinks || []), coverUrl || '', description || '', rating || 0, rawgId || 0, platforms || '', released || '', requirements || '', JSON.stringify(screenshots || []));
if (suggestedBy) {
db.prepare('INSERT OR IGNORE INTO game_players (game_id, player) VALUES (?, ?)').run(result.lastInsertRowid, suggestedBy);
}
logger.info('Game suggested: ' + name);
res.json({ success: true, id: result.lastInsertRowid });
});
// PUT /api/games/:name/approve
app.put('/api/games/:name/approve', (req, res) => {
const game = db.prepare('SELECT id, name, suggestedBy FROM games WHERE name = ?').get(req.params.name);
if (!game) return res.status(404).json({ error: 'Spiel nicht gefunden' });
db.prepare('UPDATE games SET status = ? WHERE id = ?').run('approved', game.id);
// Notify interested players
const interested = db.prepare('SELECT player FROM game_players WHERE game_id = ?').all(game.id).map(r => r.player);
const toNotify = new Set(interested);
if (game.suggestedBy) toNotify.add(game.suggestedBy);
const payload = JSON.stringify({ game: game.name });
const now = Date.now();
toNotify.forEach(player => {
db.prepare('INSERT INTO player_events (target, type, from_player, message, createdAt, status) VALUES (?, ?, ?, ?, ?, ?)')
.run(player, 'game_approved', '', payload, now, 'active');
});
logger.info('Game approved: ' + req.params.name);
broadcast({ type: 'update' });
res.json({ success: true });
});
// DELETE /api/games/shop-links — clear all shop links
app.delete('/api/games/shop-links', (req, res) => {
db.prepare("UPDATE games SET shop_links = '[]'").run();
logger.info('All shop links cleared');
broadcast({ type: 'update' });
res.json({ ok: true });
});
// DELETE /api/games/:name
app.delete('/api/games/:name', (req, res) => {
const game = db.prepare('SELECT id, name, suggestedBy, status, cover_url, screenshots FROM games WHERE name = ?').get(req.params.name);
if (!game) return res.status(404).json({ error: 'Spiel nicht gefunden' });
// Collect players to notify BEFORE deletion
const toNotify = new Set();
if (game.status === 'suggested') {
const interested = db.prepare('SELECT player FROM game_players WHERE game_id = ?').all(game.id).map(r => r.player);
interested.forEach(p => toNotify.add(p));
if (game.suggestedBy) toNotify.add(game.suggestedBy);
}
// Delete local image files
const toDelete = [];
if (game.cover_url && game.cover_url.startsWith('/gamefiles/')) toDelete.push(game.cover_url);
try { JSON.parse(game.screenshots || '[]').forEach(u => { if (u && u.startsWith('/gamefiles/')) toDelete.push(u); }); } catch {}
toDelete.forEach(relUrl => {
try { fs.unlinkSync(path.join(gamefilesDir, relUrl.replace('/gamefiles/', ''))); } catch {}
});
db.transaction(() => {
db.prepare('DELETE FROM game_players WHERE game_id = ?').run(game.id);
db.prepare('DELETE FROM games WHERE id = ?').run(game.id);
})();
// Send rejection notifications
if (toNotify.size > 0) {
const payload = JSON.stringify({ game: game.name });
const now = Date.now();
toNotify.forEach(player => {
db.prepare('INSERT INTO player_events (target, type, from_player, message, createdAt, status) VALUES (?, ?, ?, ?, ?, ?)')
.run(player, 'game_rejected', '', payload, now, 'active');
});
}
logger.info('Game deleted: ' + req.params.name);
broadcast({ type: 'update' });
res.json({ success: true });
});
// PUT /api/games/:name
app.put('/api/games/:name', (req, res) => {
const game = db.prepare('SELECT id FROM games WHERE name = ?').get(req.params.name);
if (!game) return res.status(404).json({ error: 'Spiel nicht gefunden' });
const { newName, genre, maxPlayers, shopLinks, rawgId, coverUrl, description, rating, platforms, released, requirements } = req.body;
const updates = [];
const params = [];
if (newName !== undefined) { updates.push('name = ?'); params.push(newName); }
if (genre !== undefined) { updates.push('genre = ?'); params.push(genre); }
if (maxPlayers !== undefined) { updates.push('maxPlayers = ?'); params.push(maxPlayers); }
if (shopLinks !== undefined) { updates.push('shop_links = ?'); params.push(JSON.stringify(shopLinks)); }
if (rawgId !== undefined) { updates.push('rawg_id = ?'); params.push(rawgId); }
if (coverUrl !== undefined) { updates.push('cover_url = ?'); params.push(coverUrl); }
if (description !== undefined) { updates.push('description = ?'); params.push(description); }
if (rating !== undefined) { updates.push('rating = ?'); params.push(rating); }
if (platforms !== undefined) { updates.push('platforms = ?'); params.push(platforms); }
if (released !== undefined) { updates.push('released = ?'); params.push(released); }
if (requirements !== undefined) { updates.push('requirements = ?'); params.push(requirements); }
if (updates.length > 0) {
params.push(game.id);
db.prepare(`UPDATE games SET ${updates.join(', ')} WHERE id = ?`).run(...params);
}
res.json({ success: true });
});
// POST /api/games/:name/interest
app.post('/api/games/:name/interest', (req, res) => {
const { player } = req.body;
const game = db.prepare('SELECT id FROM games WHERE name = ?').get(req.params.name);
if (!game) return res.status(404).json({ error: 'Spiel nicht gefunden' });
const existing = db.prepare('SELECT 1 FROM game_players WHERE game_id = ? AND player = ?').get(game.id, player);
if (existing) {
db.prepare('DELETE FROM game_players WHERE game_id = ? AND player = ?').run(game.id, player);
res.json({ interested: false });
} else {
db.prepare('INSERT INTO game_players (game_id, player) VALUES (?, ?)').run(game.id, player);
res.json({ interested: true });
}
});
// POST /api/games/fetch-csv-url — fetch a public CSV (or Google Sheets) URL server-side, return parsed games
app.post('/api/games/fetch-csv-url', async (req, res) => {
let { url } = req.body;
if (!url) return res.status(400).json({ error: 'url required' });
// Google Sheets: convert edit/view URL to CSV export URL
const sheetsMatch = url.match(/docs\.google\.com\/spreadsheets\/d\/([a-zA-Z0-9_-]+)/);
if (sheetsMatch) url = `https://docs.google.com/spreadsheets/d/${sheetsMatch[1]}/export?format=csv`;
try {
const response = await fetch(url, { headers: { 'User-Agent': 'Gameparty/1.0' } });
if (!response.ok) return res.status(400).json({ error: `Fetch failed: HTTP ${response.status}` });
const text = await response.text();
const games = parseGameCSVServer(text);
res.json({ games });
} catch (e) {
res.status(400).json({ error: 'URL konnte nicht geladen werden: ' + e.message });
}
});
function parseGameCSVServer(text) {
const lines = text.trim().split(/\r?\n/);
if (lines.length < 2) return [];
const headers = lines[0].split(',').map(h => h.trim().replace(/^"|"$/g, '').toLowerCase());
return lines.slice(1).map(line => {
const values = [];
let inQuote = false, cur = '';
for (let i = 0; i < line.length; i++) {
const ch = line[i];
if (ch === '"' && !inQuote) { inQuote = true; }
else if (ch === '"' && inQuote && line[i + 1] === '"') { cur += '"'; i++; }
else if (ch === '"' && inQuote) { inQuote = false; }
else if (ch === ',' && !inQuote) { values.push(cur); cur = ''; }
else { cur += ch; }
}
values.push(cur);
const row = Object.fromEntries(headers.map((h, i) => [h, (values[i] || '').trim()]));
const shopLinks = [];
let n = 1;
while (row[`shoplink_label_${n}`] !== undefined || row[`shoplink_url_${n}`] !== undefined) {
const platform = (row[`shoplink_label_${n}`] || '').trim();
const url = (row[`shoplink_url_${n}`] || '').trim();
if (platform || url) shopLinks.push({ platform, url });
delete row[`shoplink_label_${n}`]; delete row[`shoplink_url_${n}`];
n++;
}
if (shopLinks.length === 0 && row.shoplinks) {
try { const p = JSON.parse(row.shoplinks); if (Array.isArray(p)) shopLinks.push(...p); } catch {}
delete row.shoplinks;
}
row.shopLinks = shopLinks;
// Normalize lowercased headers back to camelCase
if ('maxplayers' in row) { row.maxPlayers = row.maxplayers; delete row.maxplayers; }
return row;
}).filter(r => r.name && r.name.trim());
}
// POST /api/games/import
app.post('/api/games/import', (req, res) => {
const { games } = req.body;
if (!Array.isArray(games) || games.length === 0)
return res.status(400).json({ error: 'games array required' });
let imported = 0, updated = 0;
const upsertStmt = db.prepare(
`INSERT INTO games (name, maxPlayers, genre, status, shop_links) VALUES (?, ?, ?, ?, ?)
ON CONFLICT(name) DO UPDATE SET
maxPlayers = excluded.maxPlayers,
genre = excluded.genre,
shop_links = excluded.shop_links`
);
const tx = db.transaction(() => {
for (const g of games) {
if (!g.name?.trim()) continue;
const shopLinks = Array.isArray(g.shopLinks) ? JSON.stringify(g.shopLinks) : '[]';
const existing = db.prepare('SELECT id FROM games WHERE name = ?').get(g.name.trim());
upsertStmt.run(
g.name.trim(),
parseInt(g.maxPlayers) || 4,
g.genre?.trim() || '',
'approved',
shopLinks
);
existing ? updated++ : imported++;
}
});
tx();
logger.info('Games imported: ' + imported + ' new, ' + updated + ' updated');
broadcast();
res.json({ imported, updated });
});
// GET /api/genres
const BASE_GENRES = ['2D Plattformer', '3D Plattformer', 'Action', 'Adventure', 'Battle Royale', 'Beat em Up', 'Crafting', 'Egoshooter', 'Horror', 'Indie', 'Openworld', 'Racing', 'Rollenspiel', 'Simulation', 'Sport', 'Strategie', 'Survival', 'Taktik', 'Topdown'];
app.get('/api/genres', (req, res) => {
const games = db.prepare("SELECT genre FROM games WHERE genre IS NOT NULL AND genre != ''").all();
const genres = new Set(BASE_GENRES);
games.forEach(g => {
g.genre.split(',').forEach(genre => {
const trimmed = genre.trim();
if (trimmed) genres.add(trimmed);
});
});
res.json([...genres].sort());
});
// GET /api/coins
app.get('/api/coins', (req, res) => {
const coins = {};
db.prepare('SELECT player, amount FROM coins').all().forEach(r => { coins[r.player] = r.amount; });
res.json(coins);
});
// POST /api/coins/add
app.post('/api/coins/add', (req, res) => {
if (req.authRole !== 'admin') return res.status(403).json({ error: 'Admin required' });
const { player, amount, reason } = req.body;
if (player === 'alle') {
const allPlayers = db.prepare('SELECT name FROM users').all();
const ts = Date.now();
const tx = db.transaction(() => {
allPlayers.forEach(u => {
db.prepare('INSERT INTO coins (player, amount) VALUES (?, MAX(0, ?)) ON CONFLICT(player) DO UPDATE SET amount = MAX(0, amount + ?)').run(u.name, amount, amount);
db.prepare('INSERT INTO history (player, amount, reason, timestamp) VALUES (?, ?, ?, ?)').run(u.name, amount, reason || '', ts);
});
});
tx();
broadcast({ type: 'update' });
return res.json({ affectedPlayers: allPlayers.length });
}
db.prepare('INSERT INTO coins (player, amount) VALUES (?, MAX(0, ?)) ON CONFLICT(player) DO UPDATE SET amount = MAX(0, amount + ?)').run(player, amount, amount);
db.prepare('INSERT INTO history (player, amount, reason, timestamp) VALUES (?, ?, ?, ?)').run(player, amount, reason || '', Date.now());
const row = db.prepare('SELECT amount FROM coins WHERE player = ?').get(player);
res.json({ newBalance: row ? row.amount : 0 });
});
// POST /api/coins/spend
app.post('/api/coins/spend', (req, res) => {
const { player, amount, reason } = req.body;
const row = db.prepare('SELECT amount FROM coins WHERE player = ?').get(player);
if (!row || row.amount < amount) return res.status(400).json({ error: 'Nicht genug Coins' });
db.prepare('UPDATE coins SET amount = amount - ? WHERE player = ?').run(amount, player);
db.prepare('INSERT INTO history (player, amount, reason, timestamp) VALUES (?, ?, ?, ?)').run(player, -amount, reason || '', Date.now());
res.json({ newBalance: row.amount - amount });
});
// POST /api/shop/rob-coins
app.post('/api/shop/rob-coins', (req, res) => {
const { thief, target } = req.body;
const expectedCost = getShopPrice('rob_coins', 10);
if (!thief || !target) return res.status(400).json({ error: 'thief und target erforderlich' });
if (!isShopItemEnabled('rob_coins')) return res.status(403).json({ error: 'Item deaktiviert' });
const remainingCd = checkShopCooldown('rob_coins', thief);
if (remainingCd > 0) return res.status(429).json({ error: 'cooldown', remainingMs: remainingCd });
const thiefRow = db.prepare('SELECT amount FROM coins WHERE player = ?').get(thief);
if (!thiefRow || thiefRow.amount < expectedCost) return res.status(400).json({ error: 'Nicht genug Coins' });
const stolen = Math.floor(Math.random() * 21); // 0 bis 20
const tx = db.transaction(() => {
// Kosten vom Täter abziehen
db.prepare('UPDATE coins SET amount = amount - ? WHERE player = ?').run(expectedCost, thief);
db.prepare('INSERT INTO history (player, amount, reason, timestamp) VALUES (?, ?, ?, ?)').run(thief, -expectedCost, `Shop: Taschendieb Münzen (Ziel: ${target})`, Date.now());
if (stolen > 0) {
// Gestohlene Coins vom Opfer abziehen (mindestens 0)
const targetRow = db.prepare('SELECT amount FROM coins WHERE player = ?').get(target);
const actualStolen = targetRow ? Math.min(stolen, targetRow.amount) : 0;
if (actualStolen > 0) {
db.prepare('UPDATE coins SET amount = amount - ? WHERE player = ?').run(actualStolen, target);
db.prepare('INSERT INTO history (player, amount, reason, timestamp) VALUES (?, ?, ?, ?)').run(target, -actualStolen, `Taschendieb: ${thief} hat ${actualStolen} Coins gestohlen`, Date.now());
db.prepare('INSERT INTO coins (player, amount) VALUES (?, ?) ON CONFLICT(player) DO UPDATE SET amount = amount + ?').run(thief, actualStolen, actualStolen);
db.prepare('INSERT INTO history (player, amount, reason, timestamp) VALUES (?, ?, ?, ?)').run(thief, actualStolen, `Beute: ${actualStolen} Coins von ${target} gestohlen`, Date.now());
return actualStolen;
}
}
return 0;
});
const actualStolen = tx();
setShopCooldown('rob_coins', thief);
broadcast({ type: 'update' });
res.json({ stolen: actualStolen });
});
// GET /api/shop/cooldowns
app.get('/api/shop/cooldowns', (req, res) => {
const player = req.query.player || '';
const now = Date.now();
const result = {};
// Global cooldowns
for (const [itemId, ts] of Object.entries(shopGlobalCooldownTs)) {
const { ms } = getShopCooldownConfig(itemId);
const remaining = Math.max(0, ms - (now - ts));
if (remaining > 0) result[itemId] = { ts, ms, remaining };
}
// Local cooldowns for this player
if (player && shopLocalCooldownTs[player]) {
for (const [itemId, ts] of Object.entries(shopLocalCooldownTs[player])) {
const { ms } = getShopCooldownConfig(itemId);
const remaining = Math.max(0, ms - (now - ts));
if (remaining > 0) result[itemId] = { ts, ms, remaining };
}
}
res.json(result);
});
// POST /api/shop/rob-controller
app.post('/api/shop/rob-controller', (req, res) => {
const { thief, target } = req.body;
const expectedCost = getShopPrice('rob_controller', 50);
if (!thief || !target) return res.status(400).json({ error: 'thief und target erforderlich' });
if (!isShopItemEnabled('rob_controller')) return res.status(403).json({ error: 'Item deaktiviert' });
const remainingMs = checkShopCooldown('rob_controller', thief);
if (remainingMs > 0) return res.status(429).json({ error: 'cooldown', remainingMs });
const thiefRow = db.prepare('SELECT amount FROM coins WHERE player = ?').get(thief);
if (!thiefRow || thiefRow.amount < expectedCost) return res.status(400).json({ error: 'Nicht genug Coins' });
const targetControllerpoints = db.prepare('SELECT amount FROM controllerpoints WHERE player = ?').get(target);
const success = Math.random() < 0.5 && targetControllerpoints && targetControllerpoints.amount > 0;
const tx = db.transaction(() => {
// Kosten vom Täter abziehen
db.prepare('UPDATE coins SET amount = amount - ? WHERE player = ?').run(expectedCost, thief);
if (success) {
db.prepare('INSERT INTO history (player, amount, cp_amount, reason, timestamp) VALUES (?, ?, ?, ?, ?)').run(thief, -expectedCost, 1, `Shop: Taschendieb Controller (Ziel: ${target})`, Date.now());
// 1 Controller-Punkt vom Opfer stehlen
db.prepare('UPDATE controllerpoints SET amount = amount - 1 WHERE player = ?').run(target);
db.prepare('INSERT INTO controllerpoints (player, amount) VALUES (?, 1) ON CONFLICT(player) DO UPDATE SET amount = amount + 1').run(thief);
db.prepare('INSERT INTO history (player, amount, cp_amount, reason, timestamp) VALUES (?, ?, ?, ?, ?)').run(target, 0, -1, `Controller-Punkt gestohlen von ${thief}`, Date.now());
} else {
db.prepare('INSERT INTO history (player, amount, cp_amount, reason, timestamp) VALUES (?, ?, ?, ?, ?)').run(thief, -expectedCost, 0, `Shop: Taschendieb Controller (Ziel: ${target}) – Fehlschlag`, Date.now());
}
});
tx();
setShopCooldown('rob_controller', thief);
broadcast({ type: 'update' });
res.json({ success });
});
// GET /api/controllerpoints
app.get('/api/controllerpoints', (req, res) => {
const controllerpoints = {};
db.prepare('SELECT player, amount FROM controllerpoints').all().forEach(r => { controllerpoints[r.player] = r.amount; });
res.json(controllerpoints);
});
// POST /api/shop/buy-controllerpoint — Spieler kauft 1 Controller-Punkt für Coins (kein Admin nötig)
app.post('/api/shop/buy-controllerpoint', (req, res) => {
const { player } = req.body;
const expectedCost = getShopPrice('buy_controllerpoint', 20);
if (!player) return res.status(400).json({ error: 'player erforderlich' });
if (!isShopItemEnabled('buy_controllerpoint')) return res.status(403).json({ error: 'Item deaktiviert' });
const cdRemaining = checkShopCooldown('buy_controllerpoint', player);
if (cdRemaining > 0) return res.status(429).json({ error: 'cooldown', remainingMs: cdRemaining });
const coinRow = db.prepare('SELECT amount FROM coins WHERE player = ?').get(player);
if (!coinRow || coinRow.amount < expectedCost) return res.status(400).json({ error: 'Nicht genug Coins' });
const tx = db.transaction(() => {
db.prepare('UPDATE coins SET amount = amount - ? WHERE player = ?').run(expectedCost, player);
db.prepare('INSERT INTO history (player, amount, cp_amount, reason, timestamp) VALUES (?, ?, ?, ?, ?)').run(player, -expectedCost, 1, 'Shop: Controller-Punkt kaufen', Date.now());
db.prepare('INSERT INTO controllerpoints (player, amount) VALUES (?, 1) ON CONFLICT(player) DO UPDATE SET amount = amount + 1').run(player);
});
tx();
setShopCooldown('buy_controllerpoint', player);
const row = db.prepare('SELECT amount FROM controllerpoints WHERE player = ?').get(player);
res.json({ newControllerpoints: row ? row.amount : 1 });
});
// POST /api/controllerpoints/add
app.post('/api/controllerpoints/add', (req, res) => {
const { player, amount } = req.body;
if (!player || !amount) return res.status(400).json({ error: 'player und amount erforderlich' });
if (req.authRole !== 'admin') return res.status(403).json({ error: 'Nur Admins können Controller-Punkte vergeben' });
if (player === 'alle') {
const allPlayers = db.prepare('SELECT name FROM users').all();
const tx = db.transaction(() => {
allPlayers.forEach(u => {
db.prepare('INSERT INTO controllerpoints (player, amount) VALUES (?, ?) ON CONFLICT(player) DO UPDATE SET amount = amount + ?').run(u.name, amount, amount);
});
});
tx();
broadcast({ type: 'update' });
return res.json({ affectedPlayers: allPlayers.length });
}
db.prepare('INSERT INTO controllerpoints (player, amount) VALUES (?, ?) ON CONFLICT(player) DO UPDATE SET amount = amount + ?').run(player, amount, amount);
const row = db.prepare('SELECT amount FROM controllerpoints WHERE player = ?').get(player);
broadcast({ type: 'update' });
res.json({ newControllerpoints: row ? row.amount : 0 });
});
// GET /api/history/:player
app.get('/api/history/:player', (req, res) => {
const history = db.prepare('SELECT * FROM history WHERE player = ? ORDER BY timestamp DESC LIMIT 100').all(req.params.player);
res.json(history);
});
// GET /api/sessions