forked from yzRobo/CardCast
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.js
More file actions
947 lines (802 loc) · 30.5 KB
/
Copy pathserver.js
File metadata and controls
947 lines (802 loc) · 30.5 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
// server.js - CardCast Main Server (Updated with Coming Soon functionality + MTG Support)
const express = require('express');
const http = require('http');
const socketIo = require('socket.io');
const path = require('path');
const fs = require('fs');
const { exec } = require('child_process');
// Import our modules
const Database = require('./src/database');
const TCGCSVApi = require('./src/tcg-api');
const OverlayServer = require('./src/overlay-server');
const AVAILABLE_GAMES = ['pokemon', 'magic'];
// Initialize Express app
const app = express();
const server = http.createServer(app);
const io = socketIo(server, {
cors: {
origin: "*",
methods: ["GET", "POST"]
}
});
// Load config
const configPath = path.join(__dirname, 'config.json');
let config = {
port: 3888,
theme: 'dark',
autoUpdate: true,
games: {
pokemon: { enabled: true, dataPath: null },
magic: { enabled: true, dataPath: null },
yugioh: { enabled: true, dataPath: null },
lorcana: { enabled: true, dataPath: null },
onepiece: { enabled: true, dataPath: null },
digimon: { enabled: false, dataPath: null },
fab: { enabled: false, dataPath: null },
starwars: { enabled: false, dataPath: null }
},
obs: {
mainOverlayPort: 3888,
prizeOverlayPort: 3889,
decklistPort: 3890
}
};
// Load existing config if it exists
if (fs.existsSync(configPath)) {
try {
config = JSON.parse(fs.readFileSync(configPath, 'utf8'));
} catch (e) {
console.log('Error loading config, using defaults');
}
} else {
fs.writeFileSync(configPath, JSON.stringify(config, null, 2));
}
// Save config function
function saveConfig() {
fs.writeFileSync(configPath, JSON.stringify(config, null, 2));
}
// Initialize components
const db = new Database();
const tcgApi = new TCGCSVApi(db);
const overlayServer = new OverlayServer(io);
// Middleware
app.use(express.json());
app.use(express.static('public'));
// Serve cached images
app.use('/cache', express.static(path.join(__dirname, 'cache')));
// Routes
app.get('/', (req, res) => {
res.sendFile(path.join(__dirname, 'index.html'));
});
// API Routes
app.get('/api/config', (req, res) => {
res.json(config);
});
app.post('/api/config', (req, res) => {
config = { ...config, ...req.body };
saveConfig();
res.json({ success: true, config });
});
// Helper function to get game name
function getGameName(gameId) {
const names = {
pokemon: 'Pokemon',
magic: 'Magic: The Gathering',
yugioh: 'Yu-Gi-Oh!',
lorcana: 'Disney Lorcana',
onepiece: 'One Piece Card Game',
digimon: 'Digimon Card Game',
fab: 'Flesh and Blood',
starwars: 'Star Wars Unlimited'
};
return names[gameId] || gameId;
}
// Get list of games - UPDATED FOR COMING SOON
app.get('/api/games', (req, res) => {
const games = Object.keys(config.games)
.filter(key => config.games[key].enabled)
.map(key => {
// Only Pokemon and Magic are available, all others are coming soon
const isComingSoon = !AVAILABLE_GAMES.includes(key);
if (isComingSoon) {
// For coming soon games, return minimal data
return {
id: key,
name: getGameName(key),
enabled: config.games[key].enabled,
available: false,
comingSoon: true,
hasData: false, // Always false for coming soon games
cardCount: 0,
lastUpdate: null
};
} else {
// For available games, return actual data
const hasData = db.hasGameData(key);
const stats = db.getGameStats().find(g => g.id === key);
return {
id: key,
name: getGameName(key),
enabled: config.games[key].enabled,
available: true,
comingSoon: false,
hasData: hasData,
cardCount: stats?.card_count || 0,
lastUpdate: stats?.last_update || null
};
}
});
res.json(games);
});
// Pokemon set mappings endpoint
app.get('/api/pokemon/set-mappings', (req, res) => {
try {
const mappings = db.getSetMappings('pokemon');
// Convert to a map format for easy lookup
const mappingObject = {};
mappings.forEach(row => {
if (row.set_abbreviation) {
mappingObject[row.set_abbreviation.toUpperCase()] = row.set_name;
}
});
res.json(mappingObject);
} catch (error) {
console.error('Error fetching set mappings:', error);
res.status(500).json({ error: 'Failed to fetch set mappings' });
}
});
// Pokemon sets endpoint
app.get('/api/pokemon/sets', (req, res) => {
try {
const query = `
SELECT DISTINCT
set_name,
set_code,
set_abbreviation,
COUNT(*) as card_count
FROM cards
WHERE game = 'pokemon'
AND set_name IS NOT NULL
GROUP BY set_name, set_code, set_abbreviation
ORDER BY set_name
`;
const sets = db.db.prepare(query).all();
res.json(sets);
} catch (error) {
console.error('Error fetching Pokemon sets:', error);
res.status(500).json({ error: 'Failed to fetch Pokemon sets' });
}
});
// Magic Temp Testing
//---------------------------------------------------------------------------
//---------------------------------------------------------------------------
// Delete game data endpoint - UPDATED FOR COMING SOON
app.delete('/api/games/:game/data', (req, res) => {
const game = req.params.game;
// Only allow delete for set available games
if (!AVAILABLE_GAMES.includes(game)) {
return res.status(400).json({
error: `${getGameName(game)} support is coming soon!`,
comingSoon: true
});
}
console.log(`DELETE request for game: ${game}`);
if (!config.games[game]) {
console.error(`Invalid game requested for deletion: ${game}`);
return res.status(400).json({ error: 'Invalid game' });
}
let dbCleared = false;
let imagesCleared = false;
let errors = [];
try {
// Clear database
console.log(`Attempting to clear database for ${game}...`);
try {
db.clearGameData(game);
dbCleared = true;
console.log(`Database cleared successfully for ${game}`);
} catch (dbError) {
console.error(`Database clear error for ${game}:`, dbError);
errors.push(`Database: ${dbError.message}`);
}
// Clear cached images
const imagesDir = path.join(__dirname, 'cache', 'images', game);
console.log(`Checking for images directory: ${imagesDir}`);
if (fs.existsSync(imagesDir)) {
try {
const files = fs.readdirSync(imagesDir);
console.log(`Found ${files.length} image files to delete`);
let deletedCount = 0;
let failedFiles = [];
files.forEach(file => {
try {
fs.unlinkSync(path.join(imagesDir, file));
deletedCount++;
} catch (fileErr) {
console.error(`Could not delete ${file}:`, fileErr.message);
failedFiles.push(file);
}
});
console.log(`Deleted ${deletedCount}/${files.length} cached images for ${game}`);
if (failedFiles.length > 0) {
errors.push(`Failed to delete ${failedFiles.length} image files`);
}
imagesCleared = deletedCount > 0 || files.length === 0;
} catch (dirErr) {
console.error(`Error reading images directory for ${game}:`, dirErr);
errors.push(`Images directory: ${dirErr.message}`);
}
} else {
console.log(`No images directory found for ${game}`);
imagesCleared = true; // No directory means no images to clear
}
// If at least database was cleared, consider it a success
if (dbCleared) {
const message = errors.length > 0
? `Deleted data for ${game} with some warnings: ${errors.join(', ')}`
: `Successfully deleted all data for ${game}`;
console.log(message);
res.json({
success: true,
message: message,
warnings: errors
});
// Notify connected clients
io.emit('data-deleted', { game });
} else {
throw new Error('Failed to clear database');
}
} catch (error) {
console.error(`Critical error deleting data for ${game}:`, error);
console.error('Stack trace:', error.stack);
res.status(500).json({
error: 'Failed to delete data',
details: error.message,
errors: errors
});
}
});
// Download/Update cards - UPDATED FOR COMING SOON
app.post('/api/download/:game', async (req, res) => {
const game = req.params.game;
const incremental = req.body.incremental || false;
const setCount = req.body.setCount || 'all';
// Only allow download for set available games
if (!AVAILABLE_GAMES.includes(game)) {
return res.status(400).json({
error: `${getGameName(game)} support is coming soon!`,
comingSoon: true
});
}
if (!config.games[game]) {
return res.status(400).json({ error: 'Invalid game' });
}
res.json({
message: incremental ? 'Update started' : 'Download started',
game,
mode: incremental ? 'incremental' : 'full',
setCount
});
// Start download in background
tcgApi.downloadGameData(game, (progress) => {
io.emit('download-progress', {
game,
progress: progress.percent || 0,
message: progress.message || 'Processing...'
});
}, incremental, setCount).then((cardCount) => {
io.emit('download-complete', {
game,
cardCount,
incremental
});
console.log(`${incremental ? 'Updated' : 'Downloaded'} ${cardCount} cards for ${game}`);
}).catch(err => {
console.error(`${incremental ? 'Update' : 'Download'} error for ${game}:`, err);
let userMessage = err.message;
if (err.message.includes('Network error') || err.message.includes('ENOTFOUND')) {
userMessage = `Network error: Cannot connect to ${game} API. Please check your internet connection and try again.`;
} else if (err.message.includes('Timeout error') || err.message.includes('ETIMEDOUT') || err.message.includes('timeout')) {
userMessage = `Timeout error: ${game} API is taking too long to respond. Please try again later or check your network speed.`;
} else if (err.message.includes('Rate limit')) {
userMessage = `Rate limit error: Too many requests to ${game} API. Please wait a few minutes before trying again.`;
} else if (err.message.includes('No cards were fetched')) {
userMessage = `Failed to fetch cards for ${game}. The API might be down or the format may have changed.`;
}
io.emit('download-error', {
game,
error: userMessage,
details: err.message,
canRetry: !err.message.includes('Rate limit')
});
});
});
// Search cards - UPDATED FOR COMING SOON
app.get('/api/search/:game', (req, res) => {
const { game } = req.params;
const { q } = req.query;
// Only allow search for set available games
if (!AVAILABLE_GAMES.includes(game)) {
return res.status(400).json({
error: `${getGameName(game)} support is coming soon!`,
comingSoon: true
});
}
if (!q || q.length < 2) {
return res.json([]);
}
try {
// Use the database's searchCards method which now handles set abbreviations
const results = db.searchCards(game, q);
// Use local_image if available, otherwise fall back to image_url
const processedResults = results.map(card => ({
...card,
display_image: card.image_url || card.local_image
}));
res.json(processedResults);
} catch (error) {
console.error('Search error:', error);
res.json([]);
}
});
// Get card by ID - UPDATED FOR COMING SOON
app.get('/api/card/:game/:id', (req, res) => {
const { game, id } = req.params;
// Only allow for set available games
if (!AVAILABLE_GAMES.includes(game)) {
return res.status(400).json({
error: `${getGameName(game)} support is coming soon!`,
comingSoon: true
});
}
try {
const card = db.getCard(game, id);
if (!card) {
return res.status(404).json({ error: 'Card not found' });
}
// Add display_image field that uses local if available
card.display_image = card.image_url || card.local_image;
res.json(card);
} catch (error) {
console.error('Get card error:', error);
res.status(500).json({ error: 'Failed to get card' });
}
});
// Get game statistics - UPDATED FOR COMING SOON
app.get('/api/stats/:game', (req, res) => {
const { game } = req.params;
// Only allow stats for set available games
if (!AVAILABLE_GAMES.includes(game)) {
return res.status(400).json({
error: `${getGameName(game)} support is coming soon!`,
comingSoon: true
});
}
try {
const stats = db.getGameStats().find(g => g.id === game);
const cacheDir = path.join(__dirname, 'cache', 'images', game);
let imageCount = 0;
let cacheSize = 0;
if (fs.existsSync(cacheDir)) {
const files = fs.readdirSync(cacheDir);
imageCount = files.length;
files.forEach(file => {
const filePath = path.join(cacheDir, file);
const stat = fs.statSync(filePath);
cacheSize += stat.size;
});
}
res.json({
game: game,
cardCount: stats?.card_count || 0,
lastUpdate: stats?.last_update || null,
imageCount: imageCount,
cacheSize: (cacheSize / 1024 / 1024).toFixed(2) + ' MB'
});
} catch (error) {
console.error('Stats error:', error);
res.status(500).json({ error: 'Failed to get stats' });
}
});
// Overlay endpoints
app.get('/pokemon-match', (req, res) => {
res.sendFile(path.join(__dirname, 'overlays', 'pokemon-match.html'));
});
app.get('/pokemon-match-control', (req, res) => {
res.sendFile(path.join(__dirname, 'pokemon-match-control.html'));
});
app.get('/mtg-match-control', (req, res) => {
res.sendFile(path.join(__dirname, 'mtg-match-control.html'));
});
app.get('/mtg-match', (req, res) => {
res.sendFile(path.join(__dirname, 'overlays', 'mtg-match.html'));
});
// Track overlay connections
let overlayClients = new Set();
let mainClients = new Set();
let controlClients = new Set();
let overlayStates = {
'pokemon-match': false,
'prizes': false,
'decklist': false,
'main': false,
'mtg-match': false
};
// Socket.io events
io.on('connection', (socket) => {
console.log('Client connected:', socket.id);
// Send initial state
socket.emit('state', overlayServer.getState());
// Handle overlay registration
socket.on('register-overlay', (type) => {
overlayClients.add(socket.id);
const wasAlreadyConnected = overlayStates[type] === true;
overlayStates[type] = true;
console.log(`Overlay registered: ${type} (${socket.id})`);
// Only notify control panels if this is a new connection
if (!wasAlreadyConnected) {
io.emit('overlay-connected', type);
}
// Notify all main clients that OBS is connected
io.emit('obs-status', { connected: true });
// Send current state to the overlay
const state = overlayServer.getState();
if (type === 'pokemon-match') {
socket.emit('pokemon-match-state', state.pokemonMatch);
// Also send as update for compatibility
socket.emit('pokemon-match-update', {
player1: state.pokemonMatch.player1,
player2: state.pokemonMatch.player2,
stadium: state.pokemonMatch.stadium
});
} else if (type === 'prizes') {
socket.emit('prizes-state', state);
} else if (type === 'decklist') {
socket.emit('decklist-state', state);
} else if (type === 'mtg-match') {
socket.emit('state-update', { mtgMatch: state.mtgMatch });
}
});
// Handle control panel registration
socket.on('register-control', (type) => {
controlClients.add(socket.id);
console.log(`Control panel registered: ${type} (${socket.id})`);
// Send current overlay connection states
Object.keys(overlayStates).forEach(overlayType => {
if (overlayStates[overlayType]) {
socket.emit('overlay-connected', overlayType);
}
});
});
// Handle main client registration
socket.on('register-main', () => {
mainClients.add(socket.id);
// Send current OBS status to this client
socket.emit('obs-status', { connected: overlayClients.size > 0 });
});
// Request state (from overlays)
socket.on('request-state', (type) => {
console.log(`State requested for ${type}`);
const state = overlayServer.getState();
if (type === 'prizes') {
socket.emit('prizes-update', {
player1: state.prizeCards.player1,
player2: state.prizeCards.player2,
game: 'pokemon',
show: true
});
} else if (type === 'decklist') {
socket.emit('decklist-update', {
deck: state.decklist,
show: true
});
} else if (type === 'pokemon-match') {
// Send the pokemonMatch state from the overlay server
socket.emit('pokemon-match-state', state.pokemonMatch);
// Also send as update for compatibility
socket.emit('pokemon-match-update', {
player1: state.pokemonMatch.player1,
player2: state.pokemonMatch.player2,
stadium: state.pokemonMatch.stadium
});
} else if (type === 'mtg-match') {
socket.emit('state-update', { mtgMatch: state.mtgMatch });
}
});
// Handle OBS status check
socket.on('check-obs-status', () => {
socket.emit('obs-status', { connected: overlayClients.size > 0 });
});
// Check overlay status
socket.on('check-overlay-status', (type) => {
if (overlayStates[type]) {
socket.emit('overlay-connected', type);
} else {
socket.emit('overlay-disconnected', type);
}
});
// Search handler - UPDATED FOR COMING SOON
socket.on('search', async (data) => {
const { game, query } = data;
// Only allow search for set available games
if (!AVAILABLE_GAMES.includes(game)) {
socket.emit('search-error', {
error: `${getGameName(game)} support is coming soon!`,
comingSoon: true
});
return;
}
const results = db.searchCards(game, query);
socket.emit('search-results', results);
});
// Display card event
socket.on('display-card', (data) => {
console.log('Display card:', data.card?.name);
overlayServer.updateCard(data.card, data.position);
// Emit to all overlay clients
io.emit('show-card', {
card: data.card,
position: data.position || 'left',
game: data.game
});
});
// Clear display event
socket.on('clear-display', () => {
console.log('Clear display');
overlayServer.clearCard();
io.emit('clear-card', { position: 'both' });
});
// Pokemon Match events
socket.on('pokemon-match-update', (data) => {
console.log('Pokemon match update:', data);
overlayServer.updatePokemonMatch(data); // Store in overlay server
io.emit('pokemon-match-update', data);
});
socket.on('active-pokemon', (data) => {
console.log('Active pokemon update for player', data.player);
overlayServer.updateActivePokemon(data.player, data.pokemon); // Store in overlay server
io.emit('active-pokemon', data);
});
socket.on('bench-update', (data) => {
console.log('Bench update for player', data.player);
overlayServer.updateBench(data.player, data.bench); // Store in overlay server
io.emit('bench-update', data);
});
socket.on('prize-taken', (data) => {
console.log('Prize taken:', data);
overlayServer.takePrize(data.player, data.index);
io.emit('prize-taken', data);
});
socket.on('prizes-reset', () => {
console.log('Prizes reset');
overlayServer.resetPrizes();
io.emit('prizes-reset');
});
socket.on('turn-switch', (data) => {
console.log('Turn switch:', data);
io.emit('turn-switch', data);
});
socket.on('timer-start', (data) => {
console.log('Timer start', data);
io.emit('timer-start', data);
});
socket.on('timer-pause', () => {
console.log('Timer pause');
io.emit('timer-pause');
});
socket.on('timer-reset', (data) => {
console.log('Timer reset', data);
io.emit('timer-reset', data);
});
socket.on('match-reset', () => {
console.log('Match reset');
io.emit('match-reset');
});
socket.on('match-settings', (data) => {
console.log('Match settings:', data);
io.emit('match-settings', data);
});
socket.on('toggle-pokemon-match', (data) => {
console.log('Toggle pokemon match overlay:', data.show);
io.emit('toggle-pokemon-match', data);
});
socket.on('toggle-prizes', (data) => {
console.log('Toggle prizes overlay:', data.show);
io.emit('toggle-prizes', data);
});
// Stadium events
socket.on('stadium-update', (data) => {
console.log('Stadium update:', data.stadium);
overlayServer.updateStadium(data.stadium);
io.emit('stadium-update', data);
});
// Player record events
socket.on('record-update', (data) => {
console.log('Record update for player', data.player, ':', data.record);
overlayServer.updatePlayerRecord(data.player, data.record);
io.emit('record-update', data);
});
// Match score events
socket.on('match-score-update', (data) => {
console.log('Match score update for player', data.player, ':', data.score);
overlayServer.updateMatchScore(data.player, data.score);
io.emit('match-score-update', data);
});
// Turn actions events
socket.on('turn-actions-update', (data) => {
console.log('Turn actions update for player', data.player, ':', data.actions);
overlayServer.updateTurnActions(data.player, data.actions);
io.emit('turn-actions-update', data);
});
socket.on('turn-actions-reset', () => {
console.log('Turn actions reset');
overlayServer.resetTurnActions();
io.emit('turn-actions-reset');
});
// Bench size events
socket.on('bench-size-update', (data) => {
console.log('Bench size update for player', data.player, ':', data.size);
overlayServer.updateBenchSize(data.player, data.size);
io.emit('bench-size-update', data);
});
// Prize card events (alternative handling)
socket.on('update-prizes', (data) => {
console.log('Update prizes:', data);
overlayServer.updatePrizes(data);
io.emit('prizes-update', data);
});
// Decklist events
socket.on('decklist-update', (data) => {
console.log('Update decklist');
overlayServer.updateDecklist(data);
io.emit('decklist-update', data);
});
socket.on('decklist-add-card', (data) => {
console.log('Add card to decklist:', data.card?.name);
overlayServer.addCardToDeck(data.category, data.card);
});
socket.on('decklist-clear', () => {
console.log('Clear decklist');
overlayServer.clearDecklist();
io.emit('decklist-clear');
});
// MTG Match events
socket.on('mtg-life-update', (data) => {
console.log('MTG life update:', data);
overlayServer.updateMTGLife(data.player, data.life);
});
socket.on('mtg-commander-damage-update', (data) => {
console.log('MTG commander damage update:', data);
overlayServer.updateCommanderDamage(data.player, data.commanderName, data.damage);
});
socket.on('mtg-lands-update', (data) => {
console.log('MTG lands update:', data);
overlayServer.updateLands(data.player, data.lands);
});
socket.on('mtg-permanent-add', (data) => {
console.log('MTG add featured permanent:', data);
overlayServer.addFeaturedPermanent(data.player, data.card);
});
socket.on('mtg-permanent-remove', (data) => {
console.log('MTG remove featured permanent:', data);
overlayServer.removeFeaturedPermanent(data.player, data.index);
});
socket.on('mtg-permanents-clear', (data) => {
console.log('MTG clear featured permanents:', data);
overlayServer.clearFeaturedPermanents(data.player);
});
socket.on('mtg-phase-update', (data) => {
console.log('MTG phase update:', data);
overlayServer.updatePhase(data.phase);
});
socket.on('mtg-player-name-update', (data) => {
console.log('MTG player name update:', data);
overlayServer.updateMTGPlayerName(data.player, data.name);
});
socket.on('mtg-player-record-update', (data) => {
console.log('MTG player record update:', data);
overlayServer.updateMTGPlayerRecord(data.player, data.record);
});
socket.on('mtg-games-won-update', (data) => {
console.log('MTG games won update:', data);
overlayServer.updateMTGGamesWon(data.player, data.gamesWon);
});
socket.on('mtg-turn-action', (data) => {
console.log('MTG turn action:', data);
overlayServer.setMTGTurnAction(data.player, data.action, data.value);
});
socket.on('mtg-player-switch', () => {
console.log('MTG player switch');
overlayServer.switchMTGActivePlayer();
});
socket.on('mtg-format-update', (data) => {
console.log('MTG format update:', data);
overlayServer.updateMTGFormat(data.format);
});
socket.on('mtg-match-reset', () => {
console.log('MTG match reset');
overlayServer.resetMTGMatch();
});
// Handle disconnect
socket.on('disconnect', () => {
console.log('Client disconnected:', socket.id);
// Check if it was an overlay client
const wasOverlay = overlayClients.delete(socket.id);
const wasControl = controlClients.delete(socket.id);
mainClients.delete(socket.id);
if (wasOverlay) {
// Check which overlay disconnected
Object.keys(overlayStates).forEach(type => {
// For simplicity, mark all as disconnected when any overlay disconnects
// In production, you'd track which specific overlay each socket represents
overlayStates[type] = false;
});
// Notify control panels
io.emit('overlay-disconnected', 'pokemon-match');
io.emit('overlay-disconnected', 'mtg-match');
// If no more overlays are connected, notify main clients
if (overlayClients.size === 0) {
io.emit('obs-status', { connected: false });
}
}
});
});
// Start server
const PORT = config.port || 3888;
server.listen(PORT, () => {
console.log(`
╔═══════════════════════════════════════╗
║ CardCast v1.0.1 ║
║ TCG Streaming Overlay Tool ║
╚═══════════════════════════════════════╝
Server running on http://localhost:${PORT}
OBS Overlays:
- Main: http://localhost:${PORT}/overlay
- Prizes: http://localhost:${PORT}/prizes
- Decklist: http://localhost:${PORT}/decklist
- Pokemon Match: http://localhost:${PORT}/pokemon-match
- MTG Match: http://localhost:${PORT}/mtg-match
Control Panels:
- Pokemon: http://localhost:${PORT}/pokemon-match-control
- MTG: http://localhost:${PORT}/mtg-match-control
Currently Available:
✓ Pokemon TCG (20,000+ cards)
✓ Magic: The Gathering
Coming Soon:
○ Yu-Gi-Oh!
○ Disney Lorcana
○ One Piece Card Game
○ Digimon Card Game
○ Flesh and Blood
○ Star Wars Unlimited
Cache directory: ${path.join(__dirname, 'cache')}
Database: ${path.join(__dirname, 'data', 'cardcast.db')}
Opening browser...
`);
// Auto-open browser
const url = `http://localhost:${PORT}`;
switch (process.platform) {
case 'win32':
exec(`start ${url}`);
break;
case 'darwin':
exec(`open ${url}`);
break;
case 'linux':
exec(`xdg-open ${url}`);
break;
}
});
// Graceful shutdown
process.on('SIGINT', () => {
console.log('\nShutting down CardCast...');
db.close();
server.close();
process.exit(0);
});
process.on('uncaughtException', (error) => {
console.error('Uncaught Exception:', error);
});
process.on('unhandledRejection', (error) => {
console.error('Unhandled Rejection:', error);
});