-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathserver.js
553 lines (418 loc) · 13.6 KB
/
server.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
/**************************************************************************************************************
USE: manages gameshow, saves data, syncs clients
AUTHOR: Yanik Kendler
DEPENDS ON: socket, express, filsystem, npm
***************************************************************************************************************/
const express = require("express")
const http = require("http")
const fs = require('fs');
const playerpath = "./src/player.json"
const questionpath = "./src/boards.json"
const app = express()
const server = http.createServer(app)
const io = require("socket.io")(server, {
cors: {
origin: "https://gameshow-kappa.vercel.app/"
}
})
const port = 80
app.use(express.static("public"))
io.listen(8000)
server.listen(port, () => {
console.log(`listenin on port ${port}`)
})
let ffACount = 0 //used to automatically display a new ffa
let ffaRunning = false //used to only collect and send awnsers if question is ffa
let timerRunning = false //used to alternate between starting / restting the timer
let answers = [] //used to collect awnsers and send to the gamemaster
//used to safe selected question
let safedSet
let safedId
//used to store wheter rules or categories are open rn
let categories = false
let rules = false
//compiled list of name and uuid of all boards
let boardList = []
//all calls are named from client perspective: "send" - client sends to server | "get" - clients request data
io.on("connection", (socket) => {
console.log("client connected")
//sends player and question data to all clients
socket.emit("loadPlayers", manager.players)
socket.emit("loadQuestions", manager.questions)
socket.emit("selectQuestion", safedSet, safedId)
if(ffaRunning == true)
socket.emit("loadFFA", manager.freeForAll[ffACount-1])
if(rules == true)
socket.emit("openRules")
if(categories == true)
socket.emit("openCategories")
socket.emit("boardList", boardList)
socket.on("sendFFA", () => {
console.log("ffa triggerd count:", ffACount);
if(ffACount >= manager.freeForAll.length){
io.emit("loadFFA", {"type": 11,"question": "Out of 'free for all' Questions","solution": ""})
return
}
ffaRunning = true
io.emit("loadFFA", manager.freeForAll[ffACount])
ffACount++
})
socket.on("getPlayers", () => {
io.emit("loadPlayers", manager.players)
})
socket.on("getQuestions", () => {
io.emit("loadQuestions", manager.questions)
})
socket.on("sendTimer", () => {
console.log("sendTimer recieved:", timerRunning);
if (timerRunning == false) {
console.log("starting timer");
timerRunning = true
setTimer(30)
}
else if(timerRunning == true){
stopTimer()
}
})
let timeRec = setTimeout(function(){},0)
function setTimer(value){
if(value <= 0 || timerRunning == false){
setTimeout(() => {
stopTimer(true)
}, 1000);
}
else{
timerRec = setTimeout(function(){
setTimer(value-1)
},1000)
}
io.emit("setTimer", value)
}
let imageMode = 0
socket.on("sendSelectQuestion", (set, id) => {
console.log("selecting question", set, id);
imageMode = 0
safedId = id
safedSet = set
socket.broadcast.emit("selectQuestion", set, id)
manager.questions[set].questions[id].used = true
})
socket.on("sendCloseQuestion", () => {
console.log("closing question");
ffaRunning = false
socket.broadcast.emit("closeQuestion")
io.emit("loadQuestions", manager.questions)
if(timerRunning == true)
stopTimer()
safedId = null
safedSet = null
})
socket.on("toggleImage", (hint, solution) => {
console.log("toggle image");
if(imageMode == 0){
imageMode = 1
io.emit("toggleImage", solution)
}
else{
io.emit("toggleImage", hint)
imageMode = 0
}
})
socket.on("sendOpenRules", () => {
socket.broadcast.emit("openRules")
rules = true
})
socket.on("sendOpenCategories", () => {
categories = true
socket.broadcast.emit("openCategories")
})
socket.on("sendCloseInfo", () => {
socket.broadcast.emit("closeInfo")
categories = false
rules = false
console.log("closeinfo");
})
socket.on("deletePlayer", (name) => {
manager.deletePlayer(name)
io.emit("loadPlayers", manager.players)
updatePlayerFile()
})
socket.on("deletePlayerID", (id) => {
manager.deletePlayerID(id)
io.emit("loadPlayers", manager.players)
updatePlayerFile()
})
socket.on("sendScrollPlayers", (direction) => {
io.emit("scrollPlayers", direction)
})
socket.on("sendAnswer", (player, answer) => { //collects answers for ffa
let erg = {player: player, answer: answer}
answers.push(erg)
console.log("answer recieved:", answer);
})
socket.on("sendSpecialUsed", (player) => {
if (manager.players[player].special == true) {
manager.players[player].special = false
}
else {
manager.players[player].special = true
}
updatePlayerFile()
io.emit("loadPlayers", manager.players)
})
socket.on("changeScore", (plusMinus, value, player) => {
if (value == "") {}
else if (plusMinus == "plus") {
manager.players[player].score = parseInt(manager.players[player].score) + parseInt(value)
console.log("plus");
}
else if (plusMinus == "minus") {
manager.players[player].score = parseInt(manager.players[player].score) - parseInt(value)
}
updatePlayerFile()
io.emit("loadPlayers", manager.players)
})
socket.on("postPlayer", (name) => {
name = name.toLowerCase()
manager.addPlayer(name)
updatePlayerFile()
io.emit("loadPlayers", manager.players)
})
socket.on("reset", () => { //resets all scores specials and questions
for (let i = 0; i < manager.players.length; i++) {
manager.players[i].score = 0
manager.players[i].special = true
}
io.emit("loadPlayers", manager.players)
updatePlayerFile()
manager.questions.forEach((category)=>{
category.questions.forEach((question)=>{
question.used = false
})
})
})
socket.on("deleteAll", () => {
manager.players = []
updatePlayerFile()
manager.questions.forEach((category)=>{
category.questions.forEach((question)=>{
question.used = false
})
})
io.emit("loadQuestions", manager.questions)
io.emit("loadPlayers", manager.players)
})
socket.on("update-board", (board) => {
manager.updateBoard(board)
})
socket.on("add-board", (board) => {
manager.addBoard(board)
})
socket.on("request-board", (uuid) => {
manager.boards.forEach(item => {
if(item.uuid == uuid)
socket.emit("loadBoard", item)
})
})
socket.on("setQuestions", (uuid) => {
manager.setQuestions(uuid)
})
socket.on("delete-board", (uuid) => {
manager.deleteBoard(uuid)
})
socket.on("force-backup", () => {
backUpBoards(true)
})
})
function stopTimer(sound = false){
io.emit("stopTimer", sound)
setTimeout(function(){//super ugly but should fix things and im drunk rn so doesnt matter
if (ffaRunning == true) { //if current question is a ffa send collected answers to gamemaster
console.log("answer sent to clients");
io.emit("answers", answers)
answers = []
}
},500)
timerRunning = false
clearTimeout(timerRec)
}
function createBoardList(){ //compiles list of all names and uuids of boards
boardList = []
manager.boards.forEach(item => {
boardList.push({"name" : item.name, "uuid": item.uuid})
});
io.emit("boardList", boardList)
console.log(boardList);
}
//SAVE DATA TO JSON FILES
try {
if (!fs.existsSync("./src/backups")) {
fs.mkdirSync("./src/backups");
}
}
catch (err) {
console.error(err);
}
const secsInADay = 86400000
const secsInHour = 3600000
const daysToKeepBackups = 7
let lastCheck = Date.now()
function backUpBoards(force = false){
const now = Date.now()
if(now - lastCheck < secsInHour && force === false) return
lastCheck = now
let newestBackup = -1
let backupContents = fs.readdirSync("./src/backups/")
let backupsToDelete = []
backupContents.forEach(item => {
let timeInt = parseInt(item)
if(timeInt > newestBackup)
newestBackup = timeInt
if(backupContents.length - backupsToDelete.length > 7 &&
timeInt < now - (secsInADay * daysToKeepBackups))
backupsToDelete.push(item)
});
if(now - newestBackup > secsInADay || force === true){
fs.writeFile(`./src/backups/${now}.json`, JSON.stringify(manager.boards, 0, 2), 'utf8', ( (error) => {
if(error) throw error;
}))
}
backupsToDelete.forEach((item) => {
fs.unlink("./src/backups/" + item, (err) => {
if (err) throw err;
});
})
}
//initially reads players
if (fs.existsSync(playerpath)) {
fs.readFile(playerpath, 'utf-8', (err, data_string) => {
if (err) throw err;
let data = JSON.parse(data_string);
console.log(data);
manager.setPlayers(data)
})
}
//initially reads questions
readQuestions()
function readQuestions(){
return new Promise((resolve, reject) => {
if (fs.existsSync(questionpath)) {
fs.readFile(questionpath, 'utf-8', (err, data_string) => {
if (err) {reject("error when reading"); throw err};
let data = JSON.parse(data_string);
manager.setBoards(data)
resolve("file read")
})
}
})
}
function updatePlayerFile(){
fs.writeFile(playerpath, JSON.stringify(manager.players, 0, 2), 'utf8', (error => {
if (error) throw error;
}))
}
function updateBoardFile(){
fs.writeFile(questionpath, JSON.stringify(manager.boards, 0, 2), 'utf8', (error=>{
if(error) throw error;
}))
}
class Manager {
constructor() {
this.boards = new Array();
this.players = new Array();
this.questions = new Array();
this.freeForAll = new Array();
this.currentBoardUUID = null
}
addPlayer(name) {
if (name != "" && name != null) {
name = name.toLowerCase()
let newPlayer = {
name: name,
score: 0,
special: true,
};
this.players.push(newPlayer);
}
}
deletePlayer(name){
for (let i = 0; i < manager.players.length; i++) {
if(manager.players[i].name == name){
manager.players.splice(i,1)
}
}
}
deletePlayerID(id){
manager.players.splice(id,1)
}
setQuestions(uuid){ //sets currently used question set
if(uuid == "clear"){
this.questions = []
this.freeForAll = []
this.currentBoardUUID = null
io.emit("loadQuestions", this.questions)
return
}
this.boards.forEach(item => {
if(item.uuid == uuid){
this.questions = item.board
//sets all question usages to false in case a running game changed them
this.questions.forEach((category)=>{
category.questions.forEach((question)=>{
question.used = false
})
})
updateBoardFile()
this.freeForAll = item.ffa
this.currentBoardUUID = uuid
io.emit("loadQuestions", this.questions)
}
});
}
setBoards(boards){
this.boards = boards
createBoardList()
}
addBoard(board){
this.boards.push(board)
updateBoardFile()
}
deleteBoard(uuid){
for (let i = 0; i < this.boards.length; i++) {
if(this.boards[i].uuid == uuid){ //uuids match
console.log("deleting");
this.boards.splice(i,1)
}
}
createBoardList()
updateBoardFile()
}
updateBoard(board){
console.log("update board");
for (let i = 0; i < this.boards.length; i++) {
if(this.boards[i].uuid == board.uuid){ //uuids match - item will be replaced
this.boards[i] = board
if(this.currentBoardUUID == this.boards[i].uuid){
this.questions = this.boards[i]
this.setQuestions(this.currentBoardUUID)
io.emit("loadQuestions", manager.questions)
}
updateBoardFile()
createBoardList()
backUpBoards()
}
}
}
addBoard(board){
this.boards.push(board)
updateBoardFile()
createBoardList()
}
setPlayers(players){
manager.players = players
}
setFFA(ffa){
manager.freeForAll = ffa
}
}
let manager = new Manager