-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathwebsocket-server.js
More file actions
2049 lines (1812 loc) · 58.1 KB
/
websocket-server.js
File metadata and controls
2049 lines (1812 loc) · 58.1 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 WebSocket = require('ws');
const http = require('http');
const fs = require('fs');
const path = require('path');
const bcrypt = require('bcrypt');
const crypto = require('crypto');
const savelib = require('./libs/save.js');
const tribesRegistry = require('./libs/tribesRegistry.js');
const util = require('./libs/util.js');
const pop = require('./libs/population.js');
const help = require('./libs/help.js');
const logger = require('./libs/logger.js');
const PORT = process.env.PORT || 8000;
const referees = require('./libs/referees.json');
// Timestamped logging function
function logWithTimestamp(message, ...args) {
const timestamp = new Date().toLocaleString();
const logMessage = `[${timestamp}] ${message} ${args.join(' ')}`;
// Log to console
console.log(`[${timestamp}]`, message, ...args);
// Log to file
try {
// Ensure logs directory exists
const logsDir = path.join(__dirname, 'logs');
if (!fs.existsSync(logsDir)) {
fs.mkdirSync(logsDir, { recursive: true });
}
// Create daily log file name
const today = new Date().toISOString().split('T')[0]; // YYYY-MM-DD format
const logFile = path.join(logsDir, `tribes-${today}.log`);
// Append to log file
fs.appendFileSync(logFile, logMessage + '\n');
} catch (error) {
// If logging to file fails, at least log the error to console
console.error('[LOG ERROR] Failed to write to log file:', error.message);
}
}
let wss;
let allGames = {};
let usersDict = {};
// Track connected clients and their player names
let connectedClients = new Map(); // Map of playerName -> Set of WebSocket connections
let tribeConnections = new Map(); // Map of tribeName -> Set of WebSocket connections
// Rate limiting for authentication attempts
let loginAttempts = new Map(); // Map of identifier -> { count, lastAttempt, lockoutUntil }
// Session management
let activeSessions = new Map(); // token -> { playerName, createdAt, lastActivity, ipAddress }
let playerSessions = new Map(); // playerName -> Set of tokens
const SESSION_TIMEOUT = 24 * 60 * 60 * 1000; // 24 hours
const SESSION_CLEANUP_INTERVAL = 5 * 60 * 1000; // Clean up every 5 minutes
// Load users data
try {
// Ensure tribe-data directory exists
if (!fs.existsSync('./tribe-data')) {
fs.mkdirSync('./tribe-data', { recursive: true });
logWithTimestamp('Created tribe-data directory');
}
usersDict = loadJson('./tribe-data/users.json');
} catch (error) {
logWithTimestamp('No existing users.json, starting fresh');
usersDict = {};
}
// Load all commands dynamically from the commands folder
const commands = new Map();
// Session management functions
function generateSessionToken() {
return crypto.randomBytes(32).toString('hex');
}
function createSession(playerName, ipAddress = 'unknown') {
const token = generateSessionToken();
const session = {
playerName,
createdAt: Date.now(),
lastActivity: Date.now(),
ipAddress,
};
activeSessions.set(token, session);
if (!playerSessions.has(playerName)) {
playerSessions.set(playerName, new Set());
}
playerSessions.get(playerName).add(token);
logWithTimestamp(
`[SESSION] Created session for ${playerName} from ${ipAddress}`
);
return token;
}
function validateSession(token) {
const session = activeSessions.get(token);
if (!session) {
return null;
}
// Check if session has expired
if (Date.now() - session.lastActivity > SESSION_TIMEOUT) {
destroySession(token);
return null;
}
// Update last activity
session.lastActivity = Date.now();
return session;
}
function destroySession(token) {
const session = activeSessions.get(token);
if (session) {
const playerName = session.playerName;
activeSessions.delete(token);
if (playerSessions.has(playerName)) {
playerSessions.get(playerName).delete(token);
if (playerSessions.get(playerName).size === 0) {
playerSessions.delete(playerName);
}
}
logWithTimestamp(`[SESSION] Destroyed session for ${playerName}`);
}
}
function destroyAllPlayerSessions(playerName) {
const playerTokens = playerSessions.get(playerName);
if (playerTokens) {
for (const token of playerTokens) {
activeSessions.delete(token);
}
playerSessions.delete(playerName);
logWithTimestamp(`[SESSION] Destroyed all sessions for ${playerName}`);
}
}
function cleanupExpiredSessions() {
const now = Date.now();
const expiredTokens = [];
for (const [token, session] of activeSessions) {
if (now - session.lastActivity > SESSION_TIMEOUT) {
expiredTokens.push(token);
}
}
for (const token of expiredTokens) {
destroySession(token);
}
if (expiredTokens.length > 0) {
logWithTimestamp(
`[SESSION] Cleaned up ${expiredTokens.length} expired sessions`
);
}
}
// Start session cleanup timer only when not in test mode
let sessionCleanupTimer = null;
if (process.env.NODE_ENV !== 'test') {
sessionCleanupTimer = setInterval(
cleanupExpiredSessions,
SESSION_CLEANUP_INTERVAL
);
}
function getClientIP(ws, req) {
return (
req?.socket?.remoteAddress ||
req?.headers['x-forwarded-for']?.split(',')[0] ||
'unknown'
);
}
function loadCommands() {
const commandsPath = path.join(__dirname, 'commands');
const commandFolders = fs.readdirSync(commandsPath);
for (const folder of commandFolders) {
const folderPath = path.join(commandsPath, folder);
const commandFiles = fs
.readdirSync(folderPath)
.filter((file) => file.endsWith('.js'));
for (const file of commandFiles) {
const filePath = path.join(folderPath, file);
try {
const command = require(filePath);
if ('data' in command && 'execute' in command) {
const commandName = command.data.name;
commands.set(commandName, {
...command,
category: folder,
filepath: filePath,
});
logWithTimestamp(`Loaded command: ${commandName} (${folder})`);
} else {
logWithTimestamp(
`[WARNING] The command at ${filePath} is missing "data" or "execute" property.`
);
}
} catch (error) {
console.error(`Error loading command ${filePath}:`, error);
}
}
}
console.log(`Loaded ${commands.size} commands total`);
console.log('Tribes WebSocket Server starting...');
}
// Create mock interaction object for websocket compatibility
function createMockInteraction(data, ws, gameState) {
const mockMember = {
displayName: data.playerName || 'Unknown',
};
const mockUser = {
send: (message) => {
ws.send(
JSON.stringify({
type: 'privateMessage',
message: message,
clientId: data.clientId,
})
);
},
displayName: data.playerName || 'Unknown',
};
const mockOptions = {
// Handle different parameter types
getString: (name) => {
const value = data.parameters && data.parameters[name];
if (Array.isArray(value)) {
// For empty arrays, return null to indicate no data provided
if (value.length === 0) {
return null;
}
return value.join(','); // Convert arrays to comma-separated strings for compatibility
}
return value;
},
getInteger: (name) => data.parameters && parseInt(data.parameters[name]),
getBoolean: (name) => {
const value = data.parameters && data.parameters[name];
if (typeof value === 'boolean') return value;
if (typeof value === 'string') {
return value.toLowerCase() === 'true' || value === '1';
}
return false;
},
getUser: (name) => {
const paramValue = data.parameters && data.parameters[name];
if (!paramValue) return null;
// Create a mock user object with the parameter value as display name
return {
displayName: paramValue,
id: `user_${paramValue}`,
send: (message) => {
// Mock send function - could log or handle differently if needed
console.log(`[MOCK] Message to ${paramValue}: ${message}`);
},
};
},
getMember: (name) => {
const paramValue = data.parameters && data.parameters[name];
if (!paramValue) return null;
// Create a mock member object with the parameter value as display name
return {
displayName: paramValue,
id: `member_${paramValue}`,
user: {
displayName: paramValue,
id: `user_${paramValue}`,
},
};
},
};
return {
member: mockMember,
user: mockUser,
options: mockOptions,
reply: (response) => {
let content = response.content || response;
if (response.embeds && response.embeds.length > 0) {
content = response.embeds[0].description || content;
}
ws.send(
JSON.stringify({
type: 'commandResponse',
command: data.command,
success: true,
message: content,
clientId: data.clientId,
})
);
},
isRepliable: () => true,
replied: false,
channelId: `${gameState.name}_channel`,
commandName: data.command,
nickName: data.playerName || 'Unknown',
};
}
function startServer() {
try {
// Create HTTP server for health checks and static file serving
const httpServer = http.createServer((req, res) => {
// Add CORS headers for cloud deployments
res.setHeader('Access-Control-Allow-Origin', '*');
res.setHeader('Access-Control-Allow-Methods', 'GET, POST, OPTIONS');
res.setHeader('Access-Control-Allow-Headers', 'Content-Type');
if (req.method === 'OPTIONS') {
res.writeHead(200);
res.end();
return;
}
if (req.url === '/health') {
res.writeHead(200, { 'Content-Type': 'application/json' });
res.end(
JSON.stringify({
status: 'OK',
timestamp: new Date().toISOString(),
connections: wss ? wss.clients.size : 0,
commands: commands.size,
})
);
} else if (req.url === '/' || req.url === '/index.html') {
// Serve the HTML interface with WebSocket configuration
fs.readFile(
path.join(__dirname, 'tribes-interface.html'),
'utf8', // Read as text to allow modifications
(err, data) => {
if (err) {
res.writeHead(404, { 'Content-Type': 'text/plain' });
res.end('Interface not found');
} else {
// Inject WebSocket configuration into the HTML
const wsConfig = {
port: PORT,
protocol:
req.headers['x-forwarded-proto'] ||
(req.connection.encrypted ? 'https' : 'http'),
host: req.headers.host || req.headers['x-forwarded-host'],
};
// Insert WebSocket config right after the <head> tag
const configScript = `<script>window.TRIBES_WS_CONFIG = ${JSON.stringify(wsConfig)};</script>`;
const modifiedData = data.replace(
'<head>',
'<head>\n ' + configScript
);
res.writeHead(200, { 'Content-Type': 'text/html' });
res.end(modifiedData);
}
}
);
} else if (
req.url.endsWith('.png') ||
req.url.endsWith('.jpg') ||
req.url.endsWith('.gif') ||
req.url.endsWith('.jpeg')
) {
// Serve static image files
const filePath = path.join(__dirname, req.url);
fs.readFile(filePath, (err, data) => {
if (err) {
res.writeHead(404, { 'Content-Type': 'text/plain' });
res.end('Image not found');
} else {
const ext = path.extname(req.url).toLowerCase();
let contentType = 'image/png';
if (ext === '.jpg' || ext === '.jpeg') contentType = 'image/jpeg';
else if (ext === '.gif') contentType = 'image/gif';
res.writeHead(200, { 'Content-Type': contentType });
res.end(data);
}
});
} else {
res.writeHead(404, { 'Content-Type': 'application/json' });
res.end(JSON.stringify({ error: 'Not found' }));
}
});
// Create WebSocket server on the same port with cloud-friendly options
wss = new WebSocket.Server({
server: httpServer,
perMessageDeflate: false, // Disable compression for better compatibility
maxPayload: 16 * 1024, // 16KB max message size
});
httpServer.listen(PORT, '0.0.0.0', () => {
logWithTimestamp(
`Tribes server (WebSocket + HTTP) started on port ${PORT}`
);
logWithTimestamp(`Local access:`);
logWithTimestamp(` Health check: http://localhost:${PORT}/health`);
logWithTimestamp(` Game interface: http://localhost:${PORT}/`);
// Only show network access info if we can detect a local IP
const os = require('os');
const networkInterfaces = os.networkInterfaces();
let localIP = null;
for (const [name, addresses] of Object.entries(networkInterfaces)) {
for (const address of addresses) {
if (
address.family === 'IPv4' &&
!address.internal &&
(address.address.startsWith('192.168.') ||
address.address.startsWith('10.') ||
address.address.startsWith('172.'))
) {
localIP = address.address;
break;
}
}
if (localIP) break;
}
if (localIP) {
logWithTimestamp(`Network access:`);
logWithTimestamp(` Health check: http://${localIP}:${PORT}/health`);
logWithTimestamp(` Game interface: http://${localIP}:${PORT}/`);
logWithTimestamp(
`Share the network URL with others on your local network!`
);
} else {
logWithTimestamp(
`Cloud deployment detected - access via your cloud service URL`
);
}
});
wss.on('connection', (ws, req) => {
const clientIP = getClientIP(ws, req);
logWithTimestamp(`New client connected from ${clientIP}`);
ws.on('message', async (message) => {
try {
const data = JSON.parse(message.toString());
logWithTimestamp(
'Received:',
data.type,
data.command || '',
`from ${data.playerName || ws.playerName || 'unknown'}`
);
// Store client IP for session management
if (!ws.clientIP) {
ws.clientIP = clientIP;
}
await handleWebSocketMessage(ws, data);
} catch (error) {
console.error('Error processing message:', error);
ws.send(
JSON.stringify({
type: 'error',
message: 'Error processing command: ' + error.message,
clientId: data.clientId,
})
);
}
});
ws.on('error', (error) => {
logWithTimestamp('WebSocket error:', error.message);
// Cleanup connections on error
if (ws.currentTribe && tribeConnections.has(ws.currentTribe)) {
tribeConnections.get(ws.currentTribe).delete(ws);
if (tribeConnections.get(ws.currentTribe).size === 0) {
tribeConnections.delete(ws.currentTribe);
}
}
if (ws.currentPlayer && connectedClients.has(ws.currentPlayer)) {
connectedClients.get(ws.currentPlayer).delete(ws);
if (connectedClients.get(ws.currentPlayer).size === 0) {
connectedClients.delete(ws.currentPlayer);
}
}
});
ws.on('close', () => {
logWithTimestamp(`Client disconnected: ${ws.playerName || 'unknown'}`);
// Remove from tribe connections
if (ws.currentTribe && tribeConnections.has(ws.currentTribe)) {
tribeConnections.get(ws.currentTribe).delete(ws);
if (tribeConnections.get(ws.currentTribe).size === 0) {
tribeConnections.delete(ws.currentTribe);
}
}
// Remove from player connections
if (ws.currentPlayer && connectedClients.has(ws.currentPlayer)) {
connectedClients.get(ws.currentPlayer).delete(ws);
if (connectedClients.get(ws.currentPlayer).size === 0) {
connectedClients.delete(ws.currentPlayer);
}
}
// Note: We don't destroy sessions on disconnect - they persist for reconnection
});
});
} catch (error) {
console.error('Error setting up webserver:', error);
process.exit(1);
}
}
async function handleWebSocketMessage(ws, data) {
let tribe = data.tribe || 'bug';
let gameState = await getGameState(tribe);
logWithTimestamp('got gamestate for', tribe);
// Track this client's tribe connection
if (!tribeConnections.has(tribe)) {
tribeConnections.set(tribe, new Set());
}
tribeConnections.get(tribe).add(ws);
ws.currentTribe = tribe; // Store tribe on the websocket for cleanup
// Track this client's player name if provided
if (data.playerName) {
if (!connectedClients.has(data.playerName)) {
connectedClients.set(data.playerName, new Set());
}
connectedClients.get(data.playerName).add(ws);
ws.currentPlayer = data.playerName; // Store player name on websocket for cleanup
}
logWithTimestamp('added a client record for', data.playerName);
logWithTimestamp('data type', data.type);
switch (data.type) {
case 'authenticateSession':
handleSessionAuthentication(ws, data);
break;
case 'manageTribe':
handleManageTribe(ws, data);
break;
case 'manageUsers':
await handleManageUsers(ws, data);
break;
case 'logout':
handleLogout(ws, data);
break;
case 'infoRequest':
handleInfoRequest(ws, data, gameState);
break;
case 'registerRequest':
await handleRegisterRequest(ws, data, gameState);
break;
case 'command':
await handleCommandRequest(ws, data, gameState);
break;
case 'romanceRequest':
await handleRomanceRequest(ws, data, gameState);
break;
case 'listCommands':
handleListCommands(ws, data, gameState);
break;
case 'helpRequest':
handleHelpRequest(ws, data);
break;
case 'exportGame':
await handleExportGame(ws, data);
break;
case 'importGame':
await handleImportGame(ws, data, gameState);
break;
default:
logWithTimestamp('default case ', data.playerName);
ws.send(
JSON.stringify({
type: 'error',
message: 'Unknown request type: ' + data.type,
clientId: data.clientId,
})
);
}
}
async function getGameState(tribeName) {
if (allGames[tribeName]) {
return allGames[tribeName];
}
let gameState = savelib.loadTribe(tribeName);
if (!gameState) {
gameState = savelib.initGame(tribeName);
}
allGames[tribeName] = gameState;
return gameState;
}
function handleSessionAuthentication(ws, data) {
const { token } = data;
if (!token) {
ws.send(
JSON.stringify({
type: 'sessionAuthResponse',
success: false,
message: 'Session token required',
clientId: data.clientId,
})
);
logWithTimestamp('sent sessionAuthResponse', data.clientId);
return;
}
const session = validateSession(token);
if (!session) {
ws.send(
JSON.stringify({
type: 'sessionAuthResponse',
success: false,
message: 'Invalid or expired session token',
clientId: data.clientId,
})
);
return;
}
// Associate this WebSocket with the session
ws.sessionToken = token;
ws.playerName = session.playerName;
ws.currentPlayer = session.playerName;
// Track this client's player connections
if (!connectedClients.has(session.playerName)) {
connectedClients.set(session.playerName, new Set());
}
connectedClients.get(session.playerName).add(ws);
logWithTimestamp(
`[SESSION] ${session.playerName} authenticated with existing session`
);
ws.send(
JSON.stringify({
type: 'sessionAuthResponse',
success: true,
playerName: session.playerName,
message: 'Session authenticated successfully',
clientId: data.clientId,
})
);
}
function handleLogout(ws, data) {
const { logoutAll = false } = data;
if (ws.sessionToken) {
if (logoutAll && ws.playerName) {
// Destroy all sessions for this player
destroyAllPlayerSessions(ws.playerName);
// Disconnect all WebSockets for this player
const playerConnections = connectedClients.get(ws.playerName);
if (playerConnections) {
for (const connection of playerConnections) {
if (connection !== ws) {
connection.send(
JSON.stringify({
type: 'forceLogout',
message: 'Logged out from another device',
})
);
connection.close();
}
}
}
} else {
// Destroy only this session
destroySession(ws.sessionToken);
}
ws.sessionToken = null;
ws.playerName = null;
ws.currentPlayer = null;
}
ws.send(
JSON.stringify({
type: 'logoutResponse',
success: true,
message: logoutAll
? 'Logged out from all devices'
: 'Logged out successfully',
clientId: data.clientId,
})
);
}
function handleInfoRequest(ws, data, gameState) {
const selection = data.selection;
let messageData = null;
switch (selection) {
case 'population':
const cleanPop = removeClunkyKeys(gameState.population);
messageData = {
type: 'infoRequest',
label: 'population',
content: cleanPop,
};
break;
case 'children':
messageData = {
type: 'infoRequest',
label: 'children',
content: removeFatherReferences(gameState.children),
};
break;
case 'status':
const statusMessage = util.gameStateMessage(gameState);
messageData = {
type: 'infoRequest',
label: 'status',
content: statusMessage,
gameState: {
round: gameState.round || 'work',
workRound: gameState.workRound,
foodRound: gameState.foodRound,
reproductionRound: gameState.reproductionRound,
seasonCounter: gameState.seasonCounter,
currentLocationName: gameState.currentLocationName,
year: Math.floor(gameState.seasonCounter / 2),
startStamp: gameState.startStamp,
},
};
break;
case 'romance':
const playerName = data.playerName;
const userData = gameState.population && gameState.population[playerName];
let conList = [];
let decList = [];
if (userData?.consentDict) {
for (const [n, r] of Object.entries(userData.consentDict)) {
if (r === 'consent') conList.push(n);
if (r === 'decline') decList.push(n);
}
} else {
conList = userData?.consentList || [];
decList = userData?.declineList || [];
}
let romanceLists = {
inviteList: userData?.inviteList || [],
consentList: conList,
declineList: decList,
consentDict: userData?.consentDict || {},
};
messageData = {
type: 'infoRequest',
label: 'romance',
content: romanceLists,
};
break;
default:
messageData = {
type: 'infoRequest',
label: 'error',
content: 'Invalid infoRequest: ' + selection,
};
}
ws.send(JSON.stringify(messageData));
}
async function handleCommandRequest(ws, data, gameState) {
const commandName = data.command;
const command = commands.get(commandName);
if (!command) {
ws.send(
JSON.stringify({
type: 'commandResponse',
command: commandName,
success: false,
message: `Command '${commandName}' not found`,
clientId: data.clientId,
})
);
return;
}
// Validate user if required
try {
if (!(await validateUser(data))) {
ws.send(
JSON.stringify({
type: 'commandResponse',
command: commandName,
success: false,
message: 'Invalid user credentials',
clientId: data.clientId,
})
);
return;
}
} catch (error) {
ws.send(
JSON.stringify({
type: 'commandResponse',
command: commandName,
success: false,
message: error.message,
clientId: data.clientId,
})
);
return;
}
try {
// Create mock interaction object
const interaction = createMockInteraction(data, ws, gameState);
// Clear messages before command execution
gameState.messages = {};
// Execute the command
await command.execute(interaction, gameState, null);
// Send any game messages
await sendGameMessages(ws, gameState, data);
// Save game state if needed
if (gameState.saveRequired) {
savelib.saveTribe(gameState);
gameState.saveRequired = false;
// Refresh game data for all tribe members after state changes
await refreshTribeGameData(gameState, data.tribe || 'bug');
// Check if commands need refreshing (e.g., after chief change)
if (gameState.commandsNeedRefresh) {
await refreshTribeCommandLists(gameState, data.tribe || 'bug');
delete gameState.commandsNeedRefresh;
}
}
if (gameState.archiveRequired) {
const tribeName = gameState.name;
const gameEnded = gameState.ended;
await savelib.archiveTribe(gameState);
gameState.archiveRequired = false;
// After archiving an ended game, the main file is cleared. Replace in-memory
// state with a fresh game so the next /join can start a new instance.
if (gameEnded) {
allGames[tribeName] = savelib.initGame(tribeName);
}
}
} catch (error) {
console.error(`Error executing command ${commandName}:`, error);
ws.send(
JSON.stringify({
type: 'commandResponse',
command: commandName,
success: false,
message: 'Command execution failed: ' + error.message,
clientId: data.clientId,
})
);
}
}
async function refreshTribeCommandLists(gameState, tribeName) {
const tribeMembers = tribeConnections.get(tribeName);
if (!tribeMembers || tribeMembers.size === 0) {
return; // No one online to refresh
}
logWithTimestamp(
`Refreshing command lists for ${tribeMembers.size} members of ${tribeName} tribe`
);
// Send updated command lists to all tribe members
for (const memberWs of tribeMembers) {
if (memberWs.readyState === WebSocket.OPEN && memberWs.currentPlayer) {
try {
// Create a mock data object for handleListCommands
const mockData = {
playerName: memberWs.currentPlayer,
clientId: memberWs.clientId || 'refresh',
};
// Call handleListCommands to generate and send the updated command list
handleListCommands(memberWs, mockData, gameState);
} catch (error) {
console.error(
`Error refreshing commands for ${memberWs.currentPlayer}:`,
error
);
}
}
}
}
async function refreshTribeGameData(gameState, tribeName) {
const tribeMembers = tribeConnections.get(tribeName);
if (!tribeMembers || tribeMembers.size === 0) {
return; // No one online to refresh
}
logWithTimestamp(
`Refreshing game data for ${tribeMembers.size} members of ${tribeName} tribe`
);
// Prepare data packages
const populationData = {
type: 'infoRequest',
label: 'population',
content: removeClunkyKeys(gameState.population),
};
const childrenData = {
type: 'infoRequest',
label: 'children',
content: removeFatherReferences(gameState.children),
};
const statusData = {
type: 'infoRequest',
label: 'status',
content: util.gameStateMessage(gameState),
gameState: {
round: gameState.round || 'work',
workRound: gameState.workRound,
foodRound: gameState.foodRound,
reproductionRound: gameState.reproductionRound,
seasonCounter: gameState.seasonCounter,
currentLocationName: gameState.currentLocationName,
year: Math.floor(gameState.seasonCounter / 2),
},
};
// Send to all tribe members
for (const memberWs of tribeMembers) {
if (memberWs.readyState === 1) {
// WebSocket.OPEN
try {
memberWs.send(JSON.stringify(populationData));
memberWs.send(JSON.stringify(childrenData));
memberWs.send(JSON.stringify(statusData));
} catch (error) {
console.error('Error sending refresh data to tribe member:', error);
}
}
}
}
async function sendGameMessages(ws, gameState, data) {
if (!gameState.messages) return;
const tribe = data.tribe || 'bug';
// Send tribe-wide messages to ALL players in this tribe
if (gameState.messages.tribe) {