-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathServer.js
More file actions
1442 lines (1198 loc) · 43.7 KB
/
Copy pathServer.js
File metadata and controls
1442 lines (1198 loc) · 43.7 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
const express = require('express');
const session = require('express-session');
const path = require('path');
const fs = require('fs').promises;
const fetch = require('node-fetch');
const app = express();
const PORT = 3000;
// Configure session middleware
app.use(session({
secret: 'pokemon-secret-key-2025', // Change this in production
resave: false,
saveUninitialized: false,
cookie: {
secure: false, // Set to true if using HTTPS
maxAge: 24 * 60 * 60 * 1000 // 24 hours
}
}));
// Middleware to parse form data with increased limits
app.use(express.urlencoded({ extended: true, limit: '10mb' }));
app.use(express.json({ limit: '10mb' }));
// Serve static files from Client folder
app.use(express.static('Client'));
// Data folder path
const DATA_FOLDER = path.join(__dirname, 'Data');
const USERS_FILE = path.join(DATA_FOLDER, 'users.json');
const PROJECT_INFO_FILE = path.join(DATA_FOLDER, 'project-info.json');
const ARENA_FILE = path.join(DATA_FOLDER, 'arena.json');
// YouTube API configuration
const YOUTUBE_API_KEY = process.env.YOUTUBE_API_KEY;
const YOUTUBE_API_BASE_URL = 'https://www.googleapis.com/youtube/v3';
// Initialize data folder and files if they don't exist
async function initializeDataFolder() {
try {
await fs.mkdir(DATA_FOLDER, { recursive: true });
try {
await fs.access(USERS_FILE);
} catch {
// Create users.json if it doesn't exist
await fs.writeFile(USERS_FILE, JSON.stringify([], null, 2));
console.log('Created users.json file');
}
try {
await fs.access(PROJECT_INFO_FILE);
} catch {
// Create project-info.json if it doesn't exist
const defaultProjectInfo = {
projectName: "Pokemon Explorer",
description: "A comprehensive Pokemon discovery platform",
version: "1.0.0",
submittedBy: []
};
await fs.writeFile(PROJECT_INFO_FILE, JSON.stringify(defaultProjectInfo, null, 2));
console.log('Created project-info.json file');
}
// Enhanced arena file initialization
try {
const arenaData = await getArenaData();
// Ensure arena file exists with proper structure
await fs.writeFile(ARENA_FILE, JSON.stringify(arenaData, null, 2));
console.log('✅ Arena file initialized/validated');
console.log(`📊 Loaded arena with ${Object.keys(arenaData.players).length} players and ${arenaData.battles.length} battles`);
} catch (arenaError) {
console.error('❌ Error initializing arena file:', arenaError);
// Create fresh arena file
const defaultArenaData = createDefaultArenaData();
await fs.writeFile(ARENA_FILE, JSON.stringify(defaultArenaData, null, 2));
console.log('Created fresh arena.json file');
}
} catch (error) {
console.error('Error initializing data folder:', error);
}
}
// Helper function to read users from file
async function getUsers() {
try {
const data = await fs.readFile(USERS_FILE, 'utf8');
return JSON.parse(data);
} catch (error) {
console.error('Error reading users:', error);
return [];
}
}
// Helper function to save users to file
async function saveUsers(users) {
try {
await fs.writeFile(USERS_FILE, JSON.stringify(users, null, 2));
} catch (error) {
console.error('Error saving users:', error);
throw error;
}
}
// Helper functions for arena management
async function getArenaData() {
try {
const data = await fs.readFile(ARENA_FILE, 'utf8');
// Check if data is empty or corrupted
if (!data || data.trim().length === 0) {
console.log('⚠️ Arena file is empty, creating default data');
return createDefaultArenaData();
}
try {
const parsedData = JSON.parse(data);
// Validate structure and ensure all required properties exist
if (!parsedData || typeof parsedData !== 'object') {
console.log('⚠️ Arena data is not an object, recreating');
return createDefaultArenaData();
}
// Ensure all required properties exist
const validData = {
players: parsedData.players || {},
battles: parsedData.battles || [],
onlinePlayers: parsedData.onlinePlayers || []
};
// If the structure was invalid, save the corrected version
if (!parsedData.players || !parsedData.battles || !parsedData.onlinePlayers) {
console.log('🔧 Fixed arena data structure');
await fs.writeFile(ARENA_FILE, JSON.stringify(validData, null, 2));
}
return validData;
} catch (parseError) {
console.error('❌ JSON parse error:', parseError.message);
console.log('🔧 Creating backup of corrupted file and recreating');
// Create backup of corrupted file
const corruptedBackup = ARENA_FILE + '.corrupted.' + Date.now();
try {
await fs.writeFile(corruptedBackup, data);
console.log(`💾 Saved corrupted file as: ${corruptedBackup}`);
} catch (backupError) {
console.error('Failed to create corrupted backup:', backupError);
}
return createDefaultArenaData();
}
} catch (error) {
if (error.code === 'ENOENT') {
console.log('📁 Arena file does not exist, creating new one');
return createDefaultArenaData();
}
console.error('❌ Error reading arena file:', error.message);
return createDefaultArenaData();
}
}
function createDefaultArenaData() {
return {
players: {},
battles: [],
onlinePlayers: []
};
}
async function saveArenaData(arenaData) {
try {
// Validate data before saving
if (!arenaData || typeof arenaData !== 'object') {
throw new Error('Invalid arena data: not an object');
}
// Ensure required properties exist and are the correct type
const validData = {
players: arenaData.players && typeof arenaData.players === 'object' ? arenaData.players : {},
battles: Array.isArray(arenaData.battles) ? arenaData.battles : [],
onlinePlayers: Array.isArray(arenaData.onlinePlayers) ? arenaData.onlinePlayers : []
};
// Create backup ONLY if arena file already exists and has content
let shouldCreateBackup = false;
try {
const existingData = await fs.readFile(ARENA_FILE, 'utf8');
if (existingData && existingData.trim().length > 0) {
shouldCreateBackup = true;
}
} catch (error) {
// File doesn't exist, no need for backup
shouldCreateBackup = false;
}
if (shouldCreateBackup) {
try {
const backupFile = ARENA_FILE + '.backup';
const currentData = await fs.readFile(ARENA_FILE, 'utf8');
await fs.writeFile(backupFile, currentData);
} catch (backupError) {
console.log('⚠️ Could not create backup (file may not exist yet)');
}
}
// Save with pretty formatting to avoid corruption
const jsonString = JSON.stringify(validData, null, 2);
await fs.writeFile(ARENA_FILE, jsonString);
} catch (error) {
console.error('❌ Error saving arena data:', error);
// Try to restore from backup ONLY if backup exists and has valid content
try {
const backupFile = ARENA_FILE + '.backup';
const backupData = await fs.readFile(backupFile, 'utf8');
if (backupData && backupData.trim().length > 0) {
// Validate backup before restoring
const parsedBackup = JSON.parse(backupData);
if (parsedBackup && typeof parsedBackup === 'object') {
await fs.writeFile(ARENA_FILE, backupData);
console.log('🔄 Restored arena data from backup');
return; // Exit successfully
}
}
} catch (restoreError) {
console.log('⚠️ Could not restore from backup or backup is invalid');
}
// If restore failed or no valid backup, create fresh file but preserve any valid existing data
console.log('🔧 Creating fresh arena file');
try {
const existingData = await fs.readFile(ARENA_FILE, 'utf8');
const parsed = JSON.parse(existingData);
if (parsed && parsed.players && Object.keys(parsed.players).length > 0) {
console.log('💾 Preserving existing player data');
const preservedData = {
players: parsed.players || {},
battles: parsed.battles || [],
onlinePlayers: []
};
await fs.writeFile(ARENA_FILE, JSON.stringify(preservedData, null, 2));
} else {
throw new Error('No valid existing data to preserve');
}
} catch (preserveError) {
console.log('🆕 Creating completely fresh arena file');
const defaultData = createDefaultArenaData();
await fs.writeFile(ARENA_FILE, JSON.stringify(defaultData, null, 2));
}
throw error;
}
}
async function updatePlayerStats(playerId, result) {
try {
const arenaData = await getArenaData();
// Initialize player stats if they don't exist
if (!arenaData.players[playerId]) {
arenaData.players[playerId] = {
wins: 0,
losses: 0,
draws: 0
};
}
// Store old stats for comparison
const oldStats = { ...arenaData.players[playerId] };
// Update stats based on result
switch(result) {
case 'win':
arenaData.players[playerId].wins++;
break;
case 'loss':
arenaData.players[playerId].losses++;
break;
case 'draw':
arenaData.players[playerId].draws++;
break;
default:
throw new Error(`Invalid result: ${result}`);
}
const newStats = arenaData.players[playerId];
await saveArenaData(arenaData);
} catch (error) {
console.error(`❌ Error updating player stats for ${playerId}:`, error);
throw error;
}
}
// Enhanced addOnlinePlayer function
async function addOnlinePlayer(user) {
try {
const arenaData = await getArenaData();
// Ensure player stats exist
if (!arenaData.players[user.id]) {
arenaData.players[user.id] = {
wins: 0,
losses: 0,
draws: 0
};
console.log(`🆕 New player registered in arena: ${user.name}`);
await saveArenaData(arenaData);
}
const playerStats = arenaData.players[user.id];
const onlinePlayer = {
id: user.id,
name: user.name,
email: user.email,
lastSeen: new Date().toISOString(),
wins: playerStats.wins,
losses: playerStats.losses,
draws: playerStats.draws
};
// Check if player is already online to avoid spam
const wasAlreadyOnline = arenaData.onlinePlayers.some(p => p.id === user.id);
// Remove if already exists and add fresh entry
arenaData.onlinePlayers = arenaData.onlinePlayers.filter(p => p.id !== user.id);
arenaData.onlinePlayers.push(onlinePlayer);
await saveArenaData(arenaData);
} catch (error) {
// Silently fail
}
}
async function removeOnlinePlayer(userId) {
const arenaData = await getArenaData();
arenaData.onlinePlayers = arenaData.onlinePlayers.filter(p => p.id !== userId);
await saveArenaData(arenaData);
}
async function cleanupOfflinePlayers() {
try {
const arenaData = await getArenaData();
const fiveMinutesAgo = new Date(Date.now() - 5 * 60 * 1000);
const beforeCount = arenaData.onlinePlayers.length;
const removedPlayers = [];
arenaData.onlinePlayers = arenaData.onlinePlayers.filter(player => {
const isOnline = new Date(player.lastSeen) > fiveMinutesAgo;
if (!isOnline) {
removedPlayers.push(player.name);
}
return isOnline;
});
const afterCount = arenaData.onlinePlayers.length;
if (beforeCount !== afterCount) {
await saveArenaData(arenaData);
}
} catch (error) {
console.error('❌ Error during cleanup:', error);
}
}
app.post('/logout', async (req, res) => {
const userId = req.session.user ? req.session.user.id : null;
const email = req.session.user ? req.session.user.email : null;
if (userId) {
try {
await removeOnlinePlayer(userId);
} catch (error) {
// Silently handle errors
}
}
req.session.destroy((err) => {
if (err) {
console.error('❌ Logout error:', err);
return res.status(500).json({ error: 'Could not log out' });
}
res.json({ message: 'Logged out successfully', redirect: '/' });
});
});
// Enhanced function to synchronize arena stats with individual battle histories
async function synchronizeArenaStats() {
try {
const users = await getUsers();
const arenaData = await getArenaData();
// Reset all player stats
const newPlayerStats = {};
// Initialize all users with zero stats
users.forEach(user => {
newPlayerStats[user.id] = {
wins: 0,
losses: 0,
draws: 0
};
});
// Count battles from individual player files
for (const user of users) {
try {
const battleHistory = await getPlayerBattleHistory(user.email);
battleHistory.forEach(battle => {
// Only count player vs player battles (not bot battles)
if (battle.battleType === 'vs-player' && battle.player2Id !== 'bot') {
const userWon = (battle.player1Id === user.id && battle.result === 'player1_wins') ||
(battle.player2Id === user.id && battle.result === 'player2_wins');
const userLost = (battle.player1Id === user.id && battle.result === 'player2_wins') ||
(battle.player2Id === user.id && battle.result === 'player1_wins');
if (userWon) {
newPlayerStats[user.id].wins++;
} else if (userLost) {
newPlayerStats[user.id].losses++;
} else if (battle.result === 'draw') {
newPlayerStats[user.id].draws++;
}
}
});
const stats = newPlayerStats[user.id];
} catch (error) {
console.error(`❌ Error processing battles for ${user.name}:`, error);
}
}
// Update arena data with synchronized stats
arenaData.players = newPlayerStats;
// Update online players with new stats
arenaData.onlinePlayers.forEach(onlinePlayer => {
const playerStats = newPlayerStats[onlinePlayer.id] || { wins: 0, losses: 0, draws: 0 };
onlinePlayer.wins = playerStats.wins;
onlinePlayer.losses = playerStats.losses;
onlinePlayer.draws = playerStats.draws;
});
await saveArenaData(arenaData);
return newPlayerStats;
} catch (error) {
console.error('❌ Error synchronizing arena stats:', error);
throw error;
}
}
async function saveBattleResult(battleData) {
try {
const {
player1Id,
player2Id,
player1Pokemon,
player2Pokemon,
player1Score,
player2Score,
result,
battleType = 'vs-player'
} = battleData;
// Only save battle history and stats for player vs player battles
if (battleType === 'vs-player' && player2Id !== 'bot') {
const battleRecord = {
id: Date.now().toString(),
player1Id,
player2Id,
player1Pokemon,
player2Pokemon,
player1Score,
player2Score,
result,
battleType,
timestamp: new Date().toISOString()
};
// Save to individual player files first
await saveBattleToPlayerFiles(battleRecord);
// Then update arena data
const arenaData = await getArenaData();
arenaData.battles.push(battleRecord);
// Update player stats in arena data
if (result === 'player1_wins') {
await updatePlayerStats(player1Id, 'win');
await updatePlayerStats(player2Id, 'loss');
} else if (result === 'player2_wins') {
await updatePlayerStats(player1Id, 'loss');
await updatePlayerStats(player2Id, 'win');
} else if (result === 'draw') {
await updatePlayerStats(player1Id, 'draw');
await updatePlayerStats(player2Id, 'draw');
}
// Refresh online players stats
await refreshOnlinePlayersStats();
}
} catch (error) {
console.error('❌ Error saving battle result:', error);
throw error;
}
}
// Helper function to save battle to individual player files
async function saveBattleToPlayerFiles(battleRecord) {
try {
const users = await getUsers();
const player1 = users.find(u => u.id === battleRecord.player1Id);
const player2 = users.find(u => u.id === battleRecord.player2Id);
if (player1) {
await saveBattleToPlayerFile(player1.email, battleRecord);
}
if (player2) {
await saveBattleToPlayerFile(player2.email, battleRecord);
}
} catch (error) {
console.error('Error saving battle to player files:', error);
}
}
// Helper function to save battle to individual player's history file
async function saveBattleToPlayerFile(email, battleRecord) {
try {
const safeFolderName = email.replace(/[@.]/g, '_');
const userFolder = path.join(DATA_FOLDER, safeFolderName);
const battleHistoryFile = path.join(userFolder, 'battle-history.json');
// Ensure user folder exists
await fs.mkdir(userFolder, { recursive: true });
// Read existing battle history
let battleHistory = [];
try {
const data = await fs.readFile(battleHistoryFile, 'utf8');
battleHistory = JSON.parse(data);
} catch {
// File doesn't exist, start with empty array
}
// Add new battle
battleHistory.push(battleRecord);
// Save updated battle history
await fs.writeFile(battleHistoryFile, JSON.stringify(battleHistory, null, 2));
} catch (error) {
console.error(`Error saving battle to ${email}'s history:`, error);
}
}
// Helper function to get player's battle history
async function getPlayerBattleHistory(email) {
try {
const safeFolderName = email.replace(/[@.]/g, '_');
const battleHistoryFile = path.join(DATA_FOLDER, safeFolderName, 'battle-history.json');
const data = await fs.readFile(battleHistoryFile, 'utf8');
return JSON.parse(data);
} catch {
return []; // Return empty array if file doesn't exist
}
}
// Helper function to validate name (max 50 chars, letters only)
function validateName(name) {
if (!name || typeof name !== 'string') {
return { valid: false, error: 'Name is required' };
}
const trimmedName = name.trim();
if (trimmedName.length === 0) {
return { valid: false, error: 'Name is required' };
}
if (trimmedName.length > 50) {
return { valid: false, error: 'Name must be 50 characters or less' };
}
const nameRegex = /^[A-Za-z\s]+$/;
if (!nameRegex.test(trimmedName)) {
return { valid: false, error: 'Name can only contain letters and spaces' };
}
return { valid: true, value: trimmedName };
}
// Helper function to validate email
function validateEmail(email) {
if (!email || typeof email !== 'string') {
return { valid: false, error: 'Email is required' };
}
const trimmedEmail = email.trim().toLowerCase();
if (trimmedEmail.length === 0) {
return { valid: false, error: 'Email is required' };
}
const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
if (!emailRegex.test(trimmedEmail)) {
return { valid: false, error: 'Please enter a valid email address' };
}
return { valid: true, value: trimmedEmail };
}
// Helper function to validate password (7-15 chars, 1 uppercase, 1 lowercase, 1 special char)
function validatePassword(password) {
if (!password || typeof password !== 'string') {
return { valid: false, error: 'Password is required' };
}
const errors = [];
if (password.length < 7) {
errors.push('at least 7 characters');
}
if (password.length > 15) {
errors.push('maximum 15 characters');
}
if (!/[A-Z]/.test(password)) {
errors.push('one uppercase letter');
}
if (!/[a-z]/.test(password)) {
errors.push('one lowercase letter');
}
if (!/[!@#$%^&*(),.?":{}|<>]/.test(password)) {
errors.push('one special character');
}
if (errors.length > 0) {
return { valid: false, error: `Password must contain: ${errors.join(', ')}` };
}
return { valid: true, value: password };
}
// Helper function to optimize Pokemon data for storage
function optimizePokemonData(pokemon) {
return {
id: pokemon.id,
name: pokemon.name,
sprites: {
front_default: pokemon.sprites.front_default
},
types: pokemon.types.map(t => ({
type: { name: t.type.name }
})),
abilities: pokemon.abilities.map(a => ({
ability: { name: a.ability.name }
})),
height: pokemon.height,
weight: pokemon.weight,
base_experience: pokemon.base_experience,
stats: pokemon.stats.map(s => ({
stat: { name: s.stat.name },
base_stat: s.base_stat
})),
moves: pokemon.moves.slice(0, 10).map(m => ({
move: { name: m.move.name }
})),
cries: pokemon.cries || null
};
}
// Helper function to create user folder
async function createUserFolder(email) {
// Use email as folder name (replace @ and . with safe characters)
const safeFolderName = email.replace(/[@.]/g, '_');
const userFolder = path.join(DATA_FOLDER, safeFolderName);
try {
await fs.mkdir(userFolder, { recursive: true });
// Create favorites.json for the user
const favoritesFile = path.join(userFolder, 'favorites.json');
await fs.writeFile(favoritesFile, JSON.stringify([], null, 2));
console.log(`Created folder and favorites file for user: ${email}`);
} catch (error) {
console.error('Error creating user folder:', error);
throw error;
}
}
// Middleware to track online players
app.use((req, res, next) => {
if (req.session.user) {
addOnlinePlayer(req.session.user).catch(console.error);
}
next();
});
// Cleanup offline players every 5 minutes
setInterval(cleanupOfflinePlayers, 5 * 60 * 1000);
// Route for home page
app.get('/', (req, res) => {
res.sendFile(path.join(__dirname, 'Client', 'index.html'));
});
// Route for search page (protected)
app.get('/search', (req, res) => {
if (!req.session.user) {
return res.redirect('/login');
}
res.sendFile(path.join(__dirname, 'Client', 'pokemonSearch.html'));
});
// Route for register page
app.get('/register', (req, res) => {
res.sendFile(path.join(__dirname, 'Client', 'register.html'));
});
// Route for login page
app.get('/login', (req, res) => {
res.sendFile(path.join(__dirname, 'Client', 'login.html'));
});
// Route for favorites page (protected)
app.get('/favorites', (req, res) => {
if (!req.session.user) {
return res.redirect('/login');
}
res.sendFile(path.join(__dirname, 'Client', 'pokemonFavorites.html'));
});
// Route for Pokemon details page (protected)
app.get('/pokemon/:id', (req, res) => {
if (!req.session.user) {
return res.redirect('/login');
}
res.sendFile(path.join(__dirname, 'Client', 'pokemonDetails.html'));
});
// Arena routes (all protected)
app.get('/arena', (req, res) => {
if (!req.session.user) {
return res.redirect('/login');
}
res.sendFile(path.join(__dirname, 'Client', 'arena.html'));
});
app.get('/arena/vs-bot', (req, res) => {
if (!req.session.user) {
return res.redirect('/login');
}
res.sendFile(path.join(__dirname, 'Client', 'arenaVsBot.html'));
});
app.get('/arena/random-vs-player', (req, res) => {
if (!req.session.user) {
return res.redirect('/login');
}
res.sendFile(path.join(__dirname, 'Client', 'arenaRandomVsPlayer.html'));
});
app.get('/arena/fight-history', (req, res) => {
if (!req.session.user) {
return res.redirect('/login');
}
res.sendFile(path.join(__dirname, 'Client', 'arenaFightHistory.html'));
});
app.get('/arena/leaderboard', (req, res) => {
if (!req.session.user) {
return res.redirect('/login');
}
res.sendFile(path.join(__dirname, 'Client', 'arenaLeaderboard.html'));
});
// API route to get project information
app.get('/api/project-info', async (req, res) => {
try {
const data = await fs.readFile(PROJECT_INFO_FILE, 'utf8');
const projectInfo = JSON.parse(data);
res.json(projectInfo);
} catch (error) {
console.error('Error reading project info:', error);
res.status(500).json({ error: 'Failed to load project information' });
}
});
// API route to get Pokemon by ID (proxy to PokeAPI)
app.get('/api/pokemon/:id', async (req, res) => {
if (!req.session.user) {
return res.status(401).json({ error: 'Not authenticated' });
}
try {
const pokemonId = req.params.id;
// Validate Pokemon ID
if (!pokemonId || pokemonId.trim() === '') {
return res.status(400).json({ error: 'Invalid Pokemon ID' });
}
// First, try to find the Pokemon in user's favorites
const email = req.session.user.email;
const safeFolderName = email.replace(/[@.]/g, '_');
const favoritesFile = path.join(DATA_FOLDER, safeFolderName, 'favorites.json');
try {
const data = await fs.readFile(favoritesFile, 'utf8');
const favorites = JSON.parse(data);
const favoritePokemon = favorites.find(p => p.id.toString() === pokemonId);
if (favoritePokemon) {
return res.json(favoritePokemon);
}
} catch (error) {
console.log('No favorites file or error reading it, fetching from API');
}
// If not found in favorites, fetch from PokeAPI
const response = await fetch(`https://pokeapi.co/api/v2/pokemon/${pokemonId}`);
if (!response.ok) {
return res.status(response.status).json({ error: 'Pokemon not found' });
}
const pokemonData = await response.json();
const optimizedData = optimizePokemonData(pokemonData);
res.json(optimizedData);
} catch (error) {
console.error('Error fetching Pokemon:', error);
res.status(500).json({ error: 'Failed to fetch Pokemon data', details: error.message });
}
});
// Handle registration with improved validation
app.post('/register', async (req, res) => {
try {
const { name, email, password, confirmPassword } = req.body;
// Validate all fields
const nameValidation = validateName(name);
const emailValidation = validateEmail(email);
const passwordValidation = validatePassword(password);
const fieldErrors = {};
if (!nameValidation.valid) {
fieldErrors.name = nameValidation.error;
}
if (!emailValidation.valid) {
fieldErrors.email = emailValidation.error;
}
if (!passwordValidation.valid) {
fieldErrors.password = passwordValidation.error;
}
// Check password confirmation
if (password !== confirmPassword) {
fieldErrors.confirmPassword = 'Passwords do not match';
}
// If there are validation errors, return them
if (Object.keys(fieldErrors).length > 0) {
return res.status(400).json({
error: 'Validation failed',
fieldErrors
});
}
const users = await getUsers();
// Check if email already exists
if (users.find(user => user.email === emailValidation.value)) {
return res.status(400).json({
error: 'Email already exists',
fieldErrors: { email: 'This email is already registered' }
});
}
// Create new user
const newUser = {
id: Date.now().toString(),
name: nameValidation.value,
email: emailValidation.value,
password: passwordValidation.value, // In production, hash this password!
createdAt: new Date().toISOString()
};
users.push(newUser);
await saveUsers(users);
await createUserFolder(newUser.email); // Use email as folder name
console.log('New user registered:', newUser.email);
res.json({ message: 'Registration successful', redirect: '/login' });
} catch (error) {
console.error('Registration error:', error);
res.status(500).json({ error: 'Registration failed' });
}
});
// Handle login with email instead of username
app.post('/login', async (req, res) => {
try {
const { email, password } = req.body;
const emailValidation = validateEmail(email);
const fieldErrors = {};
if (!emailValidation.valid) {
fieldErrors.email = emailValidation.error;
}
if (!password) {
fieldErrors.password = 'Password is required';
}
if (Object.keys(fieldErrors).length > 0) {
return res.status(400).json({
error: 'Validation failed',
fieldErrors
});
}
const users = await getUsers();
const user = users.find(u => u.email === emailValidation.value && u.password === password);
if (!user) {
return res.status(400).json({
error: 'Invalid credentials',
fieldErrors: {
email: 'Invalid email or password',
password: 'Invalid email or password'
}
});
}
// Create session
req.session.user = {
id: user.id,
name: user.name,
email: user.email
};
console.log('User logged in:', user.email);
res.json({ message: 'Login successful', redirect: '/search' });
} catch (error) {
console.error('Login error:', error);
res.status(500).json({ error: 'Login failed' });
}
});
// Get current user info
app.get('/api/user', (req, res) => {
if (!req.session.user) {
return res.status(401).json({ error: 'Not authenticated' });
}
res.json({ user: req.session.user });
});
// Logout
app.post('/logout', async (req, res) => {
const userId = req.session.user ? req.session.user.id : null;
const email = req.session.user ? req.session.user.email : 'Unknown';
if (userId) {
try {