-
Notifications
You must be signed in to change notification settings - Fork 0
/
server.js
96 lines (73 loc) · 2.37 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
const http = require("http")
const url = require('url')
const fs = require('fs')
const express = require('express')
const GameManager = require('./server/GameManager')
const ws = require('ws');
const wss = new ws.Server({noServer: true});
const app = express()
const port = 3000
const contents = fs.readFileSync("subtitles.txt", 'utf-8')
const arr = contents.split(/\r?\n/)
const manager = GameManager.getInstance();
const server = app.listen(port, function(){
console.log("Server listening!")
})
server.on('upgrade', (request, socket, head) => {
wss.handleUpgrade(request, socket, head, socket => {
wss.emit('connection', socket, request);
});
});
wss.on('connection', socket => {
socket.on('message', message => {
let msgStr = message.toString();
let code = msgStr.substring(0, 6);
let username = msgStr.substring(6);
manager.connectUser(socket, code, username);
})
})
app.use(express.json())
app.use(express.static("public"))
//Returns a random subtitle
app.get("/subtitle", function(req, res, next){
const random = Math.floor(Math.random() * arr.length)
res.status(200).send(arr[random])
})
//Getting the game code and username. If there exists a game with that code and username, respond with status 200.
app.post("/", function(req, res, next){
if(req.query.game && req.query.name){
const game = req.query.game;
const name = req.query.name;
const decodedName = decodeURIComponent(name)
if(manager.checkUsername(game, name)){
res.status(201).send()
}else{
res.status(400).send()
}
}else{
next()
}
})
//Getting the game code. If there exists a game with that code, respond true.
app.post("/", function(req, res, next){
if(req.query.game){
const game = req.query.game;
if (manager.checkGameCode(game)){
res.status(200).send()
} else {
res.status(404).send()
}
}else{
next()
}
})
//Creating new game. Takes owner name and creates a game object with them as owner. Returns game code.
app.post("/", function(req, res, next){
if(req.query.name){
const ownerName = req.query.name;
const decodedOwnerName = decodeURIComponent(ownerName)
res.status(201).send(manager.newGame(decodedOwnerName))
}else{
res.status(400).send()
}
})