-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.js
More file actions
646 lines (574 loc) · 18.1 KB
/
server.js
File metadata and controls
646 lines (574 loc) · 18.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
/*
drawry
server.js
a multiplayer drawing game by Glitch Taylor
*/
"use strict";
// Including libraries
const express = require("express");
const app = express();
const server = require("http").createServer(app);
const io = require("socket.io")({ serveClient: false });
io.attach(server, { pingInterval: 10000, pingTimeout: 5000, cookie: true });
const xss = require("xss");
const path = require("path");
const sizeOf = require("image-size");
// Server constants
const CLIENTS = [];
const SOCKETS = [];
const ROOMS = {};
const SETTINGS_CONSTRAINTS = {
firstPage: ["string", ["Write", "Draw"]],
pageCount: ["number", [2, 20]],
pageOrder: ["string", ["Normal", "Random"]],
palette: ["string", ["No palette", "Blues", "Rainbow", "PICO-8" /*, "Random"*/]],
timeWrite: ["number", [0, 15]],
timeDraw: ["number", [0, 15]],
};
const SETTINGS_DEFAULT = {
firstPage: "Write",
pageCount: "8",
pageOrder: "Normal",
palette: "No palette",
timeWrite: "0",
timeDraw: "0",
};
const STATE = {
LOBBY: 0,
PLAYING: 1,
PRESENTING: 2,
};
const MAX_ROOM_SIZE = 10;
const DEBUG = process.env.DEBUG;
///// ----- ASYNC SERVER FUNCTIONS ----- /////
// Listen for incoming connections from clients
io.on("connection", (socket) => {
CLIENTS[socket.id] = {};
SOCKETS[socket.id] = socket;
/// --- LOBBY --- ///
// Listen for client joining room
socket.on("joinRoom", (data) => {
if (process.env.VERBOSE) {
console.log("joinRoom", data.id, {
name: data.name,
roomCode: data.roomCode,
});
}
// first of all, make sure no two clients connect with the same ID
let auth = true;
for (let _socketID in CLIENTS) {
if (data.id === CLIENTS[_socketID].id) {
// ensure the key matches
if (data.key === CLIENTS[_socketID].key) {
// same user, disconnect old client with matching ID
SOCKETS[_socketID].disconnect();
} else {
// different user, disconnect since ID is already taken
socket.disconnect();
auth = false;
}
break;
}
}
if (auth) {
// fetch client values
let _client = CLIENTS[socket.id];
_client.id = xss(data.id.substr(0, 10)).replace(/[^a-fA-F0-9]]/g, "") || 0;
_client.key = xss(data.key.substr(0, 20)).replace(/[^a-fA-F0-9]]/g, "") || 0;
_client.name = xss(data.name.substr(0, 32));
_client.roomCode = xss(data.roomCode.substr(0, 12)).replace(/[^a-zA-Z0-9-_]/g, "") || 0;
if (_client.id === 0 || _client.roomCode === 0) {
// ID or roomCode is invalid, boot client
io.to(socket.id).emit("kick", "invalid room code");
socket.disconnect();
} else {
// add client to the room
socket.join(_client.roomCode);
// if room doesn't exist, create it and make client the host
if (!ROOMS.hasOwnProperty(_client.roomCode)) {
// create room
ROOMS[_client.roomCode] = {
clients: [],
host: socket.id,
settings: SETTINGS_DEFAULT,
state: STATE.LOBBY,
page: 0,
submitted: 0,
books: undefined,
timer: undefined,
};
}
// check if room can be joined
let _room = ROOMS[_client.roomCode];
if (_room.state !== STATE.LOBBY) {
// game in progress, can't connect
io.to(socket.id).emit("kick", "game in progress");
socket.disconnect();
} else if (_room.clients.length >= MAX_ROOM_SIZE) {
// room is full, boot client
io.to(socket.id).emit("kick", "server full");
socket.disconnect();
} else {
// if room isn't full and is in lobby, add client to the room
_room.clients.push(socket.id);
// inform the client they've joined the room
io.to(socket.id).emit("joined", {
roomCode: _client.roomCode,
users: Object.values(CLIENTS).filter((c) => {
return c.roomCode === _client.roomCode && c.id !== _client.id;
}),
host: CLIENTS[_room.host].id,
settings: _room.settings,
});
// inform users in the room about the new client
socket.to(_client.roomCode).emit("userJoin", CLIENTS[socket.id]);
}
}
}
});
// Listen for room settings changes
socket.on("settings", (data) => {
if (CLIENTS[socket.id] !== undefined && data.key === CLIENTS[socket.id].key) {
if (process.env.VERBOSE) {
console.log("settings", CLIENTS[socket.id].id, data.settings);
}
let _roomCode = CLIENTS[socket.id].roomCode;
let _room = ROOMS[_roomCode];
// Make sure user is the host and settings are within constraints
if (socket.id === _room.host && verifySettings(data.settings)) {
// Host updating settings
_room.settings = data.settings;
// Propagate settings to other clients
socket.to(_roomCode).emit("settings", _room.settings);
} else {
// Invalid request, kick from game
io.to(socket.id).emit("kick", "invalid settings");
socket.disconnect();
}
} else {
socket.disconnect();
}
});
/// --- GAME --- ///
// Start the game for the room
socket.on("startGame", (data) => {
if (CLIENTS[socket.id] !== undefined && data.key === CLIENTS[socket.id].key) {
if (process.env.VERBOSE) {
console.log("startGame", CLIENTS[socket.id].id, data.settings);
}
let _roomCode = CLIENTS[socket.id].roomCode;
let _room = ROOMS[_roomCode];
// Make sure user is the host, player count is reached, and settings are valid
if (
(socket.id === _room.host &&
_room.clients.length >= 2 &&
verifySettings(data.settings) &&
_room.state === STATE.LOBBY) ||
DEBUG
) {
// Update settings, change room state
_room.settings = data.settings;
_room.state = STATE.PLAYING;
_room.page = 0;
// Generate page assignment order for books
generateBooks(_room);
// Start game
io.to(_roomCode).emit("startGame", {
books: _room.books,
start: _room.settings.firstPage,
});
startTimer(_roomCode, _room.settings.firstPage);
} else {
// Invalid request, kick from game
socket.disconnect();
}
}
});
// Update a player's book title
socket.on("updateTitle", (data) => {
if (CLIENTS[socket.id] !== undefined && data.key === CLIENTS[socket.id].key) {
if (process.env.VERBOSE) {
console.log("updateTitle", CLIENTS[socket.id].id, { title: data.title });
}
let _id = CLIENTS[socket.id].id;
let _roomCode = CLIENTS[socket.id].roomCode;
let _room = ROOMS[_roomCode];
// make sure to sanitise title string
let _title = xss(data.title.substr(0, 40));
// ensure title is of adequate length, otherwise make it the player name + "'s book"
if (_title.length === 0) {
_title = CLIENTS[socket.id].name + "'s book";
}
// send title to other players
if (_room.page === 0) {
io.to(_roomCode).emit("title", { id: _id, title: _title });
}
}
});
// Get page from player
socket.on("submitPage", (data) => {
if (CLIENTS[socket.id] !== undefined && data.key === CLIENTS[socket.id].key) {
if (process.env.VERBOSE) {
console.log("submitPage", CLIENTS[socket.id].id, {
mode: data.mode,
value: data.value.substr(0, 63) + (data.value.length > 63 ? "…" : ""),
});
}
let _id = CLIENTS[socket.id].id;
let _roomCode = CLIENTS[socket.id].roomCode;
let _room = ROOMS[_roomCode];
let _value = undefined;
// Fetch page data
if (data.mode === "Write") {
// Data is text
_value = xss(data.value.substr(0, 140));
} else if (data.mode === "Draw") {
// Data is encoded image
// make sure the image is expected format
if (data.value.indexOf("data:image/png;base64,") === 0) {
let img = Buffer.from(data.value.split(";base64,").pop(), "base64");
let dimensions = sizeOf(img);
// make sure image is correct size
if (dimensions.width === 800 && dimensions.height === 600) {
_value = data.value;
} else {
// if it's not the correct size, check if it's within a reasonable tolerance range (1%)
let _diffWidth = Math.abs(dimensions.width - 800);
let _diffHeight = Math.abs(dimensions.height - 600);
if (_diffWidth < 8 && _diffHeight < 6) {
// Send image data anyway, it's close enough
_value = data.value;
} else {
console.log("ERROR unexpected image size", [dimensions.width, dimensions.height]);
}
}
} else {
console.log("ERROR unexpected image format", {
format: data.value.substr(0, 22),
});
}
}
// Identify book ID to update
let _bookID;
for (let i of Object.keys(_room.books)) {
if (_room.books[i][_room.page] === _id) {
_bookID = i;
break;
}
}
// Verify data.mode is valid
let _expected = (_room.settings.firstPage === "Write") ^ _room.page % 2 ? "Write" : "Draw";
if (_expected !== data.mode) {
// Client trying to send tampered data, overwrite
_value = undefined;
console.log("ERROR unexpected data.mode", {
received: data.mode,
expected: _expected,
});
}
// Send page data to all players
io.to(_roomCode).emit("page", {
id: _bookID,
page: _room.page,
value: _value,
author: _id,
mode: _expected,
});
// Check if all players have submitted
_room.submitted += 1;
if (_room.submitted === _room.clients.length) {
_room.submitted = 0;
_room.page += 1;
if (_room.page === parseInt(_room.settings.pageCount)) {
// Finished creation part of game, move to presenting
_room.state = STATE.PRESENTING;
io.to(_roomCode).emit("startPresenting");
} else {
// Go to next page
io.to(_roomCode).emit("pageForward");
startTimer(_roomCode, _expected === "Draw" ? "Write" : "Draw");
}
}
}
});
/// --- PRESENTING --- ///
// Begin presenting a book
socket.on("presentBook", (data) => {
if (CLIENTS[socket.id] !== undefined && data.key === CLIENTS[socket.id].key) {
if (process.env.VERBOSE) {
console.log("presentBook", CLIENTS[socket.id].id, { book: data.book });
}
// let _id = CLIENTS[socket.id].id; // unused
let _roomCode = CLIENTS[socket.id].roomCode;
// Make sure request is from the host
if (socket.id === ROOMS[_roomCode].host) {
// Ensure book ID is valid
let _book = xss(data.book.toString());
if (_book in ROOMS[_roomCode].books) {
// Begin presenting book
ROOMS[_roomCode].page = -1;
ROOMS[_roomCode].presenter = _book;
// Tell all clients that a book is being presented
io.to(_roomCode).emit("presentBook", {
book: _book,
presenter: ROOMS[_roomCode].presenter,
});
}
}
}
});
// Go to next page of presentation
socket.on("presentForward", (data) => {
if (CLIENTS[socket.id] !== undefined && data.key === CLIENTS[socket.id].key) {
if (process.env.VERBOSE) {
console.log("presentForward", CLIENTS[socket.id].id);
}
let _id = CLIENTS[socket.id].id;
let _roomCode = CLIENTS[socket.id].roomCode;
// Make sure request is from the presenter
if (_id === ROOMS[_roomCode].presenter) {
if (ROOMS[_roomCode].page < parseInt(ROOMS[_roomCode].settings.pageCount) - 1) {
ROOMS[_roomCode].page += 1;
io.to(_roomCode).emit("presentForward");
}
}
}
});
// Go to previous page of presentation (hide most recently shown page)
socket.on("presentBack", (data) => {
if (CLIENTS[socket.id] !== undefined && data.key === CLIENTS[socket.id].key) {
if (process.env.VERBOSE) {
console.log("presentBack", CLIENTS[socket.id].id);
}
let _id = CLIENTS[socket.id].id;
let _roomCode = CLIENTS[socket.id].roomCode;
// Make sure request is from the presenter
if (_id === ROOMS[_roomCode].presenter) {
if (ROOMS[_roomCode].page > -1) {
ROOMS[_roomCode].page -= 1;
io.to(_roomCode).emit("presentBack");
}
}
}
});
// Take over presentation as host
socket.on("presentOverride", (data) => {
if (CLIENTS[socket.id] !== undefined && data.key === CLIENTS[socket.id].key) {
if (process.env.VERBOSE) {
console.log("presentOverride", CLIENTS[socket.id].id);
}
let _id = CLIENTS[socket.id].id;
let _roomCode = CLIENTS[socket.id].roomCode;
// Make sure request is from the host
if (socket.id === ROOMS[_roomCode].host) {
ROOMS[_roomCode].presenter = _id;
io.to(_roomCode).emit("presentOverride");
}
}
});
// Return to lobby for next book
socket.on("presentFinish", (data) => {
if (CLIENTS[socket.id] !== undefined && data.key === CLIENTS[socket.id].key) {
if (process.env.VERBOSE) {
console.log("presentFinish", CLIENTS[socket.id].id);
}
let _id = CLIENTS[socket.id].id;
let _roomCode = CLIENTS[socket.id].roomCode;
// Make sure request is from the presenter
if (_id === ROOMS[_roomCode].presenter) {
ROOMS[_roomCode].page = undefined;
ROOMS[_roomCode].presenter = undefined;
io.to(_roomCode).emit("presentFinish");
}
}
});
/// --- END --- ///
// Listen for game finish events
socket.on("finish", (data) => {
if (CLIENTS[socket.id] !== undefined && data.key === CLIENTS[socket.id].key) {
if (process.env.VERBOSE) {
console.log("finish", CLIENTS[socket.id].id);
}
// Make sure request is from the host
let _roomCode = CLIENTS[socket.id].roomCode;
if (socket.id === ROOMS[_roomCode].host) {
ROOMS[_roomCode].state = STATE.LOBBY;
ROOMS[_roomCode].page = 0;
ROOMS[_roomCode].submitted = 0;
ROOMS[_roomCode].books = undefined;
io.to(_roomCode).emit("finish");
}
}
});
// Listen for disconnect events
socket.on("disconnect", (data) => {
if (CLIENTS[socket.id] !== undefined) {
if (process.env.VERBOSE) {
if (CLIENTS[socket.id].id !== undefined) {
console.log("disconnect", CLIENTS[socket.id].id, { type: data });
}
}
if (CLIENTS[socket.id].id && CLIENTS[socket.id].roomCode) {
// remove client from the room if they've joined one
let _id = CLIENTS[socket.id].id;
let _roomCode = CLIENTS[socket.id].roomCode;
// alert others that client has left the room
socket.to(_roomCode).emit("userLeave", _id);
if (ROOMS[_roomCode]) {
// remove client from the room
let _clients = ROOMS[_roomCode].clients;
let _index = _clients.indexOf(socket.id);
if (_index !== -1) {
_clients.splice(_index, 1);
}
// delete the room if everyone has left
if (_clients.length === 0) {
delete ROOMS[_roomCode];
} else {
// if the host disconnected, assign a new host
if (socket.id === ROOMS[_roomCode].host) {
ROOMS[_roomCode].host = _clients[0];
socket.to(_roomCode).emit("userHost", CLIENTS[_clients[0]].id);
}
}
}
}
delete CLIENTS[socket.id]; // todo: instead of deleting, mark as deleted so users can rejoin
}
});
});
///// ----- SYNCHRONOUS SERVER FUNCTIONS ----- /////
// Ensure game settings are within reasonable constraints
function verifySettings(settings) {
let _valid = true;
for (let _rule in settings) {
let _setting = settings[_rule];
let _constraint = SETTINGS_CONSTRAINTS[_rule];
switch (_constraint[0]) {
case "string":
// Ensure string is in the list of valid strings
if (!_constraint[1].includes(_setting)) {
_valid = false;
}
break;
case "number":
// Ensure value is a valid integer, and is within the valid range
if (/^[0-9]+$/.test(_setting)) {
_setting = +_setting;
if (_setting < _constraint[1][0] || _setting > _constraint[1][1]) {
_valid = false;
}
} else {
_valid = false;
}
break;
}
}
return _valid;
}
// Generate books for a room
function generateBooks(room) {
// create books
room.books = {};
room.clients.forEach((id) => {
room.books[CLIENTS[id].id] = [CLIENTS[id].id.toString()];
});
let _players = Object.keys(room.books);
// assign pages
if (room.settings.pageOrder === "Normal" || _players.length <= 3) {
// normal order (cyclical)
for (let i = 1; i < room.settings.pageCount; i++) {
for (let j = 0; j < _players.length; j++) {
room.books[_players[(j + i) % _players.length]].push(_players[j]);
}
}
} else if (room.settings.pageOrder === "Random") {
// random order
let _assigned = [_players]; // variable to keep track of previous rounds
for (let i = 1; i < room.settings.pageCount; i++) {
let _prev = _assigned[i - 1];
let _next = _prev.slice(); // copy previous array
// randomly shuffle
shuffle(_next);
// ensure no pages match the previous round
for (let j = 0; j < _players.length; j++) {
if (_prev[j] === _next[j]) {
// pages match, generate random index to swap with
let _swap = Math.floor(Math.random() * (_players.length - 1));
if (_swap >= j) {
_swap += 1;
}
// swap values
[_next[j], _next[_swap]] = [_next[_swap], _next[j]];
}
}
// add round to books
_assigned.push(_next);
for (let j = 0; j < _players.length; j++) {
room.books[_players[j]].push(_next[j]);
}
}
}
}
// Shuffle array (fisher yates)
function shuffle(array) {
let t,
i,
m = array.length;
while (m) {
i = Math.floor(Math.random() * m--);
t = array[m];
array[m] = array[i];
array[i] = t;
}
return array;
}
// Room timers
function startTimer(roomCode, mode) {
let room = ROOMS[roomCode];
let time;
switch (mode) {
case "Write":
time = room.settings.timeWrite;
break;
case "Draw":
time = room.settings.timeDraw;
break;
default:
time = 0;
}
// clear the timer if it already exists
if (room.timer) {
clearTimeout(room.timer);
room.timer = undefined;
}
// set timer (plus an extra couple of seconds to account for network latency)
room.timer = setTimeout(() => {
// tell clients when the timer is done
io.to(roomCode).emit("timerFinish");
clearTimeout(room.timer);
room.timer = undefined;
}, (parseFloat(time) * 60 + 2) * 1000);
}
///// ----- HTTP SERVER ----- /////
// setup rate limiter, default max of 50 resource requests per minute
const RateLimit = require("express-rate-limit");
let limiter = new RateLimit({
windowMs: 60 * 1000,
max: process.env.RATE_LIMIT ?? 50,
});
// apply rate limiter to all resource requests
app.use(limiter);
// handle requests
app.get("/js/socket.io.min.js", (req, res) => {
res.sendFile(path.join(__dirname + "/node_modules/socket.io/client-dist/socket.io.min.js"));
});
app.get("/js/fabric.min.js", (req, res) => {
res.sendFile(path.join(__dirname + "/node_modules/fabric/dist/fabric.min.js"));
});
app.get("/js/dialog-polyfill.js", (req, res) => {
res.sendFile(path.join(__dirname + "/node_modules/dialog-polyfill/dist/dialog-polyfill.js"));
});
app.use(express.static("static"));
// Open server to manage server things
server.listen(process.env.PORT ?? 80);