-
Notifications
You must be signed in to change notification settings - Fork 0
/
sockets.js
652 lines (593 loc) · 19.9 KB
/
sockets.js
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
const { Server } = require('socket.io');
const {
getRoomIndex,
filterPlayer
} = require('./api/routes/multiplayer');
const {
GAME_CONSTANTS,
PLAYER_ROLE,
GAME_START_COUNTDOWN,
GAME_MODE,
ROOM_TTL,
NOTIFICATION_TYPES
} = require('./constants');
const { randomInt } = require('./utils/math');
const { validateStr, limitNum } = require('./utils/validate');
const getIP = require('./utils/getIP').getIPFromSocket;
const { sendPushNotif } = require('./api/routes/push');
module.exports = server => {
// Timers
const roomDeletionTimer = {};
const gameStartTimer = {};
const countdownTimer = {};
const io = new Server(server, {
cors: {
origin: ['http://localhost', process.env.DOMAIN_NAME],
methods: ['GET', 'POST']
}
});
io.on('connection', socket => {
console.log('connect !');
// Enter room
const { roomID } = socket.handshake.query;
getRoomIndex(
roomID,
roomIndex => {
if (!validateStr(socket.id)) return false; // prevent XSS
const room = global.rooms[roomIndex];
const ip = getIP(socket);
// Look for IP address in room
const uid = socket.id + ip;
const playerInRoom = room.players.find(player => player.ip === ip);
if (!playerInRoom) {
// Player is not already in room
// Abort deleting the room
clearTimeout(roomDeletionTimer[roomID]);
delete roomDeletionTimer[roomID];
// Add player
socket.join(roomID);
const player = {
uid, ip,
socketID: socket.id,
participates: false,
score: 0,
receiveNotifications: false
};
// Check if player is admin
if (room.admin.ip === ip) {
// Player is admin
global.rooms[roomIndex].admin.uid = uid; // Set admin's current ID
global.rooms[roomIndex].admin.socketID = socket.id;
player.role = PLAYER_ROLE.ADMIN;
player.name = room.admin.name;
} else {
// Player is not admin
player.role = PLAYER_ROLE.BASIC;
player.name = `Player_${room.players.length + 1}`;
}
global.rooms[roomIndex].players.push(player);
// Notify other players about player join
io.to(roomID).emit('player join', filterPlayer(player));
} else {
// Player is already in the room
// Check if player is admin
if (room.admin.ip === ip) {
// Player is admin
global.rooms[roomIndex].admin.uid = uid; // Update admin's IDs with new socket
global.rooms[roomIndex].admin.socketID = socket.id;
// Notify other players
socket.broadcast.to(roomID).emit('admin ID change', socket.id);
}
// Update players with current player's new IDs
let prevSocketID = null;
global.rooms[roomIndex].players = room.players.map(player => {
if (player.ip === ip) {
prevSocketID = player.socketID;
player.socketID = socket.id;
player.uid = uid;
return player;
}
return player;
});
// Notify other players
socket.broadcast.to(roomID).emit('player ID change',
{ previous: prevSocketID, current: socket.id }
);
}
},
() => socket.disconnect(true)
);
// Game start
socket.on('start game', () => {
// Get current room
getRoomIndex(
roomID,
roomIndex => {
const room = global.rooms[roomIndex];
const ip = getIP(socket);
// Only admin can start games
if ( room && room.admin.ip === ip ) {
// Start countdown
const ms = GAME_START_COUNTDOWN * 1000;
io.to(roomID).emit('game start countdown');
global.rooms[roomIndex].gameStartCountdown = Date.now();
// Warn non admins about game start
room.players.forEach(player => {
const isAdmin = room.admin.ip === player.ip;
if (isAdmin) return;
sendPushNotif(player.ip, JSON.stringify({
title: `${room.name}:`,
body: `Get ready, a game will start in ${GAME_START_COUNTDOWN} seconds`,
timestamp: Date.now(),
data: {
type: NOTIFICATION_TYPES.GAME_START,
room: roomID
}
}));
});
gameStartTimer[roomID] = setTimeout(() => {
try {
// Reset timer ID
global.rooms[roomIndex].gameStartCountdown = null;
// There needs to be at least 2 participating players
const participants = room.players.filter(player => player.participates);
if ( participants.length > 1 ) {
// Successfully starting game
// Modify room status
global.rooms[roomIndex].isPlaying = true;
global.rooms[roomIndex].gameStart = Date.now();
// Notify players
io.to(roomID).emit('game start');
// In COUNTDOWN mode, start countdown at game start
if (room.settings.gameMode.mode === GAME_MODE.COUNTDOWN) {
countdownTimer[roomID] = setTimeout(() => {
// Winner is the one who has the highest score at this moment
let winner = participants[0];
participants.forEach((participant, index) => {
if (participant.score > winner.score) {
// Get player with highest score
winner = participant;
// Set participate property to false
global.rooms[roomIndex].players[index].participates = false;
}
});
// Reset room variables
global.rooms[roomIndex].isPlaying = false;
global.rooms[roomIndex].gameStart = null;
// Reset player variables
room.players.forEach((player, index) => {
global.rooms[roomIndex].players[index].participates = false;
global.rooms[roomIndex].players[index].score = 0;
});
// Notify players about who's the winner
io.to(roomID).emit('victory', winner.socketID);
}, room.settings.gameMode.countdown * 1000);
}
} else {
// Send error to admin
if (room && room.admin.ip === ip) {
socket.emit('error', {
type: 'get-ready',
msg: 'There needs to be at least 2 participating players to start a game'
});
}
}
} catch {
clearTimeout(gameStartTimer[roomID]);
io.to(roomID).emit('abort game start');
global.rooms[roomIndex].gameStart = null;
global.rooms[roomIndex].gameStartCountdown = null;
}
}, ms);
} // else You don't have the permission to start a game in this room
},
() => false
);
});
socket.on('abort game start', () => {
// Get current room
getRoomIndex(
roomID,
roomIndex => {
const room = global.rooms[roomIndex];
const ip = getIP(socket);
// Only admin can abort game start
if ( room && room.admin.ip === ip ) {
// Stop timer
clearTimeout(gameStartTimer[roomID]);
// Notify players
io.to(roomID).emit('abort game start');
// Change room data
global.rooms[roomIndex].gameStart = null;
global.rooms[roomIndex].gameStartCountdown = null;
} // else You don't have the permission to abort a game in this room
},
() => false
);
});
// Player
socket.on('player change', ({ type, payload }) => {
function isRequestFromSamePlayer (addConditions /*: Array<(room, player) => boolean>*/)
/*: ({player, roomIndex, playerIndex, room}|false) */ {
let returnValue = false;
// Get current room
getRoomIndex(
roomID,
roomIndex => {
const room = global.rooms[roomIndex];
const ip = getIP(socket);
// Make sure user who sent the request has the same IP address as the registered player
let playerIndex; // (get player index)
const player = room.players.find((player, index) => {
playerIndex = index;
return player.ip === ip;
});
// Additional conditions that can reject the request
if ( addConditions && addConditions.some(condition => !condition(room, player)) ) {
return;
}
if (!!player) {
// A player who verifies all the conditions has been found
returnValue = { player, room, roomIndex, playerIndex };
return true;
}
},
() => false
);
return returnValue;
}
function updatePlayer (object, key, value/*{roomIndex, playerIndex}*/)/*: boolean*/ {
try {
if (
!object.hasOwnProperty('roomIndex') ||
!object.hasOwnProperty('playerIndex') ||
!object.hasOwnProperty('player')
) {
return false;
}
const { roomIndex, playerIndex } = object;
global.rooms[roomIndex].players[playerIndex][key] = value;
return true;
} catch {
return false;
}
}
switch (type) {
case 'rename player': {
const name = payload;
if (!name || !validateStr(name)) break;
// Player can only rename oneself
const playerWhoCanBeRenamed = isRequestFromSamePlayer();
if (!updatePlayer(playerWhoCanBeRenamed, 'name', name)) break;
const { player } = playerWhoCanBeRenamed;
socket.broadcast.to(roomID).emit('player renamed', player.socketID, name);
break;
} case 'participate': {
/*
Additional condition:
Players can only participate as long as game has not started yet
*/
const hasGameNotStarted = room => !room.isPlaying;
// Add condition: player must not be participating
const isLurking = (room, player) => !player.participates;
// Players can only decide to participate by their own choice
const playerWhoCanParticipate = isRequestFromSamePlayer([hasGameNotStarted, isLurking])
if (
// Update player's state
!updatePlayer(playerWhoCanParticipate, 'participates', true)
) {
break;
}
// Emit event
const { player } = playerWhoCanParticipate;
io.to(roomID).emit('participates', filterPlayer(player));
break;
} case 'give up': {
// Players can only decide to stop participating by their own choice
const playerWhoCanGiveUp = isRequestFromSamePlayer([(room, player) => {
// Additional condition: player must be participating
return player.participates;
}]);
if (
// Update player's state
!updatePlayer(playerWhoCanGiveUp, 'participates', false)
) {
break;
}
// Emit event
const { player } = playerWhoCanGiveUp;
io.to(roomID).emit('gave up', filterPlayer(player));
break;
} case 'score': {
getRoomIndex(
roomID,
roomIndex => {
const room = global.rooms[roomIndex];
const ip = getIP(socket);
let newScore = payload;
// Player can only update his own score
let playerIndex = null;
const player = room.players.find((player, index) => {
playerIndex = index;
return player.ip === ip;
});
if (!player) return false;
// Compute score difference between new and old score
const diff = payload - player.score; // newScore - prevScore
let validDiff = diff;
if (room.isPlaying) {
// Limit score gain/loss during game
validDiff = limitNum(
diff,
GAME_CONSTANTS.maxScoreLoss,
GAME_CONSTANTS.maxScoreGain
);
if (validDiff === false) return false;
newScore = player.score + validDiff;
}
// Update player's score
const oldScore = global.rooms[roomIndex].players[playerIndex].score; // Memorize previous score
try {
// Update current score with new score
global.rooms[roomIndex].players[playerIndex].score = newScore;
} catch {
return;
}
// Handle REACH_SCORE mode
if (
room.isPlaying &&
room.settings.gameMode.mode === GAME_MODE.REACH_SCORE
) {
// Trigger victory event when a player has reached score
if (newScore >= room.settings.gameMode.scoreToReach) {
io.to(roomID).emit(
'updated score',
player.socketID, // socketID
room.settings.gameMode.scoreToReach, // currentScore
room.settings.gameMode.scoreToReach - oldScore // diff (gain/loss)
);
io.to(roomID).emit(
'victory', player.socketID
);
// Reset room variables
global.rooms[roomIndex].isPlaying = false;
global.rooms[roomIndex].gameStart = null;
// Reset player variables
room.players.forEach((player, index) => {
global.rooms[roomIndex].players[index].participates = false;
global.rooms[roomIndex].players[index].score = 0;
});
return true;
}
}
// Emit event (notify other players about new score)
io.to(roomID).emit(
'updated score', player.socketID, newScore, validDiff
);
},
() => false
);
break;
} default: return false;
}
});
// Room settings
socket.on('room setting change', ({ type, value }) => {
getRoomIndex(
roomID,
roomIndex => {
const room = global.rooms[roomIndex];
const ip = getIP(socket);
// Only admin can change the room's settings
if (room.admin.ip !== ip) return false
// Cannot change settings during game
if (room.isPlaying) {
socket.emit('error', {
type: 'game-settings',
msg: 'Cannot change settings during game !'
});
return false;
}
// Validate new setting
switch (type) {
case 'goblets-count': {
const validated = limitNum(
parseInt(value),
GAME_CONSTANTS.minGoblets,
GAME_CONSTANTS.maxGoblets
);
if (validated === false) {
socket.emit('error', {
type: 'game-settings',
msg: `Invalid number of goblets ! It should be between ${GAME_CONSTANTS.minGoblets} and ${GAME_CONSTANTS.maxGoblets}`
});
return false;
}
global.rooms[roomIndex].settings.goblets = validated;
socket.broadcast.to(roomID).emit('game setting changed', {
type, value: validated
});
break;
} case 'shuffle-count': {
const validated = limitNum(
parseInt(value),
GAME_CONSTANTS.minShuffleCount,
GAME_CONSTANTS.maxShuffleCount
);
if (validated === false) {
socket.emit('error', {
type: 'game-settings',
msg: `Invalid number of goblet permutations ! It should be between ${GAME_CONSTANTS.minShuffleCount} and ${GAME_CONSTANTS.maxShuffleCount}`
});
return false;
}
global.rooms[roomIndex].settings.shuffleCount = validated;
socket.broadcast.to(roomID).emit('game setting changed', {
type, value: validated
});
break;
} case 'shuffle-speed': {
const validated = limitNum(
parseFloat(value),
GAME_CONSTANTS.minShuffleSpeed,
GAME_CONSTANTS.maxShuffleSpeed
);
if (validated === false) {
socket.emit('error', {
type: 'game-settings',
msg: 'Invalid shuffle speed !'
});
return false;
}
global.rooms[roomIndex].settings.shuffleSpeed = validated;
socket.broadcast.to(roomID).emit('game setting changed', {
type, value: validated
});
break;
} case 'stackGoblets':
case 'gobletsDiversity': {
const checked = typeof value === 'boolean' ? value : false; // Defaults to false
global.rooms[roomIndex].settings[type] = checked;
socket.broadcast.to(roomID).emit('game setting changed', {
type, value: checked
});
break;
} case 'game-mode': {
const isValidMode = Object.keys(GAME_MODE).includes(value);
if (!isValidMode) {
socket.emit('error', {
type: 'game-settings',
msg: 'This game mode does not exist'
});
return false;
}
global.rooms[roomIndex].settings.gameMode.mode = value;
io.to(roomID).emit('game setting changed', { type, value });
break;
} case 'score-to-reach': {
const validated = limitNum(
parseInt(value),
GAME_CONSTANTS.minScoreToReach,
GAME_CONSTANTS.maxScoreToReach
)
if (validated === false) {
socket.emit('error', {
type: 'game-settings',
msg: `Invalid score ! It should be between ${GAME_CONSTANTS.minScoreToReach} and ${GAME_CONSTANTS.maxScoreToReach}`
});
return false;
}
global.rooms[roomIndex].settings.gameMode = { mode: GAME_MODE.REACH_SCORE, scoreToReach: value };
io.to(roomID).emit('game setting changed', { type, value });
break;
} case 'countdown': {
const validated = limitNum(
parseInt(value),
GAME_CONSTANTS.minCountdown,
GAME_CONSTANTS.maxCountdown
);
if (validated === false) {
socket.emit('error', {
type: 'game-settings',
msg: `Invalid countdown ! It should be between ${GAME_CONSTANTS.minCountdown} and ${GAME_CONSTANTS.maxCountdown}`
});
return false;
}
global.rooms[roomIndex].settings.gameMode = { mode: GAME_MODE.COUNTDOWN, countdown: value };
io.to(roomID).emit('game setting changed', { type, value });
break;
} default: return false;
}
},
() => false
);
});
// Chat
socket.on('chat msg', (unescapedMSG) => {
if (!unescapedMSG) return;
// No need to verify socket belongs to a player who is in this room
const timestamp = Date.now();
io.to(roomID).emit('chat msg', {
socketID: socket.id,
msg: unescapedMSG,
timestamp
});
// Send notification to all other players of the room
getRoomIndex(
roomID,
roomIndex => {
const senderIp = getIP(socket);
// Get current room
const room = global.rooms[roomIndex];
// Send to all players
room.players.forEach(player => {
const isSender = player.ip === senderIp;
if (isSender) return;
sendPushNotif(player.ip, JSON.stringify({
title: `${player.name}:`,
body: unescapedMSG,
timestamp,
data: {
type: NOTIFICATION_TYPES.CHAT_MSG,
author: filterPlayer(player),
room: roomID
}
}));
});
},
() => false
);
});
// Disconnect
socket.on('disconnect', () => {
// Delete user from room
console.log('disconnect')
getRoomIndex(
roomID,
roomIndex => {
const room = global.rooms[roomIndex];
const ip = getIP(socket);
// Look for IP address in room
const uid = socket.id + ip;
const playerInRoom = room.players.find(player => player.ip === ip);
if (playerInRoom) {
// Player is still in the room
socket.leave(roomID); // Leave room
// Remove player
const remainingPlayers = global.rooms[roomIndex].players.filter(player => {
return player.uid !== uid;
});
global.rooms[roomIndex].players = remainingPlayers;
// Delete room if there's no player left in the group
if (remainingPlayers.length <= 0) {
// Delete room after 5 seconds
roomDeletionTimer[roomID] = setTimeout(() => {
global.rooms = global.rooms.filter(room => room.id !== roomID);
delete roomDeletionTimer[roomID];
// Clear all timers/intervals related to this room
clearInterval(gameStartTimer[roomID]); delete gameStartTimer[roomID];
clearInterval(countdownTimer[roomID]); delete countdownTimer[roomID];
}, ROOM_TTL * 1000);
} else {
// Notify other players about player leave
socket.broadcast.to(roomID).emit('player leave', playerInRoom.socketID);
// Make new admin if leaving user was admin
if (playerInRoom.role === PLAYER_ROLE.ADMIN) {
// Give ADMIN role to random remaining player
const playerIndex = randomInt(0, remainingPlayers.length - 1);
const newAdmin = remainingPlayers[playerIndex];
global.rooms[roomIndex].admin = newAdmin; // Set new admin to room
newAdmin.role = PLAYER_ROLE.ADMIN;
remainingPlayers[playerIndex] = newAdmin;
global.rooms[roomIndex].players = remainingPlayers;
// Notify other players about new admin
socket.broadcast.to(roomID).emit('new admin', newAdmin.socketID);
}
}
}
},
() => false
);
});
});
};