repl.it
@tristanbeedell/

cube-timer

Nodejs

No description

fork
loading
Files
  • index.js
  • templates
  • package-lock.json
  • package.json
index.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
const express = require('express');
const sseExpress = require('sse-express');
const session = require('express-session'); // for sessions
const helmet = require('helmet'); // security headers
const bodyParser = require('body-parser'); // needed for request body on post requests

const app = express();

app.use(helmet());
app.use(bodyParser.urlencoded({ extended: true })); // post body parser
app.use(bodyParser.json()); //post json parser
app.set('view engine', 'ejs'); // use embedded javascript html templates
app.set('views', './templates'); // view template directory
app.use(express.static('static'));
app.use(session({
	secret: process.env.SESSION_SECRET || 'secret', // this must be secret
	name: 'session-id',
	resave: true,
	saveUninitialized: true,
	cookie: {
		httpOnly: true,
		secure: process.env.NODE_ENV === 'production' // use ssl in production
	}
}));

function makeid() {
	let text = "";
	let possible = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-=";

	for (var i = 0; i < 5; i++)
		text += possible.charAt(Math.floor(Math.random() * possible.length));

	return text;
}

let rooms = {};

class Room {	
	constructor() {
		this.pin = makeid();
		this.users = {};
		this.rounds = [];
		this.connections = [];
	}

	addUser(user) {
		this.users[user.id] = user;
		user.room = this.pin;
		this.broadcast('new-user', user);
	}

	removeUser(id) {
		if (!this.users[id]) { return }
		delete this.users[id];
		this.broadcast('remove-user', id);
	}

	broadcast(title, content) {
		this.connections.forEach(connection => {
			connection.sse(title, content);
		})
	}

	record(user, time) {
		this.rounds[this.currentRound].push({ user, time });
	}
}

class User {
	constructor(name) {
		this.id = makeid();
		this.name = name;
		this.average = Infinity;
		this.PB = Infinity;
		this.room = '';
		this.state = 'waiting'
	}

	getReady() {
		// tell the room the user is ready.
		rooms[this.room].broadcast('user-ready', this);
		this.state = 'ready';
		// if all of the room is ready, begin the next round.
		if (Object.values(rooms[this.room].users).every(user => user.state === 'ready')) {
			rooms[this.room].rounds.push([]);
			rooms[this.room].currentRound = rooms[this.room].rounds.length -1;
			setTimeout(()=>{
				rooms[this.room].broadcast('round-start');
				Object.values(rooms[this.room].users).forEach(user => {
					user.state = "solving";
				})
			}, 5000);
		}
	}

	finish(time) {
		rooms[this.room].broadcast('finished', {
			user: this,
			time
		});
		rooms[this.room].record(this, time);
		this.state = 'waiting';
	}
}

app.get('/', (req, res) => {
	if (req.session.user) {
		res.redirect(`/${req.session.user.room}/`)
	} else {
		res.render('create');
	}
});

app.post('/create-room', (req, res) => {
	// ensure a valid username
	if (!(req.body.username &&
		req.body.username.length < 32 &&
		req.body.username.length > 3)) {
		res.status(403).redirect('/');
		return;
	}

	// create the room
	const room = new Room();
	rooms[room.pin] = room;

	// add the user
	let user = new User(req.body.username)
	rooms[room.pin].addUser(user);
	req.session.user = user;

	res.redirect(`/${room.pin}/`);
});

app.get('/:pin/', (req, res, next) => {
	if (req.url.substr(-1) !== '/')
		res.redirect(req.url + '/');
	else
		next();
}, (req, res) => {
	// check that the rooms exists
	if (!rooms[req.params.pin]){
		res.redirect(404, '/');
		return;
	}

	const roomHasUser = req.session.user &&
		rooms[req.params.pin].users[req.session.user.id];

	const userHasRoom = req.session.user && 
		req.params.pin === req.session.user.room;

	if (!roomHasUser && !userHasRoom) {
		res.render('join', rooms[req.params.pin]);
		return;
	} else if (!roomHasUser && userHasRoom) {
		rooms[req.params.pin].addUser(req.session.user);
	}
	res.render('room', rooms[req.params.pin]);
});


app.get('/:pin/spectate', (req, res) => {
	// check that the rooms exists
	if (!rooms[req.params.pin]){
		res.redirect(404, '/');
		return;
	}
	req.session.user = new User();

	res.render('spectate', rooms[req.params.pin]);
});


app.get('/:pin/events', sseExpress, (req, res) => {
	// check that the rooms exists
	if (!rooms[req.params.pin]){
		res.end();
		return;
	}

	// create a connection to events in the room
	res.id = req.session.user.id;
	rooms[req.params.pin].connections.push(res);
    res.sse('connected', req.session.user.name);
	  
	req.on('close', () => {
		rooms[req.params.pin].connections = rooms[req.params.pin].connections.filter(user => user.id !== req.session.user.id);
	})
});

app.get('/:pin/exit', (req, res) => {
	// check that the rooms exists
	if (!rooms[req.params.pin]){
		res.end();
		return;
	}
	if (!req.session.user) {
		res.redirect('spectate');
		return;
	}
	rooms[req.params.pin].removeUser(req.session.user.id);
	req.session.user = new User();
	res.redirect('spectate');
});

app.post('/:pin/join/', (req, res) => {
	if (// ensure a valid username
		!(req.body.username &&
		req.body.username.length < 32 &&
		req.body.username.length > 3) ||
		// user not already in group
		(req.session.user &&
		req.session.user.room === req.params.pin)) {
			res.redirect(403, '/');
			return;
	}

	// check that the rooms exists
	if (!rooms[req.params.pin]){
		res.redirect(404, '/');
		return;
	}

	// add the user
	let user = new User(req.body.username)
	rooms[req.params.pin].addUser(user);
	req.session.user = user;

	res.redirect(`/${req.params.pin}/`);
});

app.get('/:pin/solve', (req, res) => {
	// check that the rooms exists
	if (!rooms[req.params.pin]){
		res.redirect(404, '/');
		return;
	}
	rooms[req.params.pin].users[req.session.user.id].getReady();
	res.render('solve', rooms[req.params.pin])
});

app.post('/:pin/solve', (req, res) => {
	// check that the rooms exists
	if (!rooms[req.params.pin]){
		res.redirect(404, '/');
		return;
	}
	const time = Number(req.body.time);
	if (isNaN(time)) {
		return res.status(403).end();
	}
	rooms[req.params.pin].users[req.session.user.id].finish(time);
	res.redirect(`/${req.params.pin}/results`);
});

app.get('/:pin/results', (req, res) => {
	// check that the rooms exists
	res.render('results', rooms[req.params.pin]);
});

app.use(function(req, res) {
	res.redirect(404, '/');
});

app.listen(process.env.PORT || 8080);
node v10.16.0