This repository has been archived by the owner on May 23, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathserver.js
293 lines (250 loc) · 6.47 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
var express = require('express'),
everyauth = require('everyauth'),
fs = require('fs'),
app = express.createServer(),
io = require('socket.io').listen(app);
if (process.env.NODE_ENV === 'production' && !process.env.NKO_TEAM_SECRET){
throw "Please set NKO_TEAM_SECRET.";
}
require('nko')(process.env.NKO_TEAM_SECRET);
['GITHUB_ID', 'GITHUB_SECRET', 'SESSION_SECRET'].forEach(function(name){
if ( ! process.env[name] ) {
throw new Error("I need a " + name + " environment variable.");
}
});
everyauth.everymodule.moduleErrback(function (err) {
console.log('authentication error: ' + err);
});
everyauth.github
.appId(process.env.GITHUB_ID)
.appSecret(process.env.GITHUB_SECRET)
.handleAuthCallbackError(function(req, res){
res.end('bad');
})
.findOrCreateUser( function (session, accessToken, accessTokenExtra, githubUserMetadata) {
// everyauth doesn't appear to do anything with the result of this function.
// https://github.com/bnoguchi/everyauth/issues/60
return {};
})
.redirectPath('/');
var battles = {},
makeBattle = (function() {
var cid = 10000;
return function(leader) {
var battle = {
id: (cid++).toString(36),
users: [],
sockets: [],
leader: leader,
state: 'waiting'
};
battles[battle.id] = battle;
lobby.add(battle);
return battle;
};
})();
function ensureUser(req, res, next) {
if (req.user) {
next();
} else {
req.session.returnTo = req.url;
res.redirect('/auth/github');
return;
}
}
var challenges = (function() {
var files = fs.readdirSync('./public/js/challenges'),
namePattern = /^([a-zA-Z0-9]+)\./,
challenges = {};
files.forEach(function(file) {
var challengeNameMatch = namePattern.exec(file),
name;
if (challengeNameMatch) {
name = challengeNameMatch[1];
challenges[name] = name;
}
});
return Object.keys(challenges);
})();
app.use(express.static(__dirname + '/public'));
app.use(express.cookieParser());
app.use(express.session({
secret: process.env.SESSION_SECRET
}));
app.use(everyauth.middleware());
// Make user info more accessible
app.use(function(req, res, next){
var user;
if (user = req.session && req.session.auth && req.session.auth.github && req.session.auth.github.user){
req.user = {
id: user.id,
login: user.login,
gravatar: user.gravatar_id,
};
}
next();
});
everyauth.helpExpress(app);
app.register('.html', require('ejs'));
app.set('view options', {
layout: false
});
app.dynamicHelpers({
req: function(req, res){
return req;
},
user: function(req, res){
return req.user;
}
});
app.get('/', function(req, res){
if (req.session && req.session.returnTo) {
var returnTo = req.session.returnTo;
delete req.session.returnTo;
res.redirect(returnTo);
return;
}
res.render('index.html');
});
app.get('/begin', ensureUser, function(req, res) {
var battle = makeBattle(req.user);
console.log('made battle: ' + battle.id);
res.redirect('/' + battle.id);
});
app.get('/:id', ensureUser, function(req, res) {
var battle = battles[req.params.id];
if (!battle) {
res.render('no_battle.html', {status: 404});
return;
}
var isInBattle = battle.users.filter(function(u) {
return u.id === req.user.id;
}).length > 0;
if (battle.state !== 'waiting' && !isInBattle) {
res.send('TOOO LATE TO JOIN THAT BATTLE SON', 404);
return;
}
res.render('battle.html');
});
function failSocket(socket, message) {
socket.emit('bugger-off', {
message: message
});
}
io.of('/battle').on('connection', function(socket) {
var battle, user;
socket.on('disconnect', function() {
var userIndex, socketIndex;
if (!battle) return;
userIndex = battle.users.indexOf(user);
socketIndex = battle.sockets.indexOf(socket);
if (userIndex >= 0) {
battle.users.splice(userIndex, 1);
}
if (socketIndex >= 0) {
battle.sockets.splice(socketIndex, 1);
}
if (battle.sockets.length === 0) {
// Remove the battle
lobby.destroy(battle);
delete battles[battle.id];
} else {
battle.sockets.forEach(function(socket) {
socket.emit('user-fucked-off', {
user: user
});
});
lobby.update(battle);
}
});
socket.on('talking-shit', function(data) {
battle = battles[data.challengeId];
user = data.user;
if (!battle) {
failSocket(socket, 'That battle doesnt exist.');
return;
}
var alreadyPlaying = battle.users.some(function(u) {
return u.id === user.id;
});
if (!alreadyPlaying) {
// Tell other people that we've got someone connected
battle.sockets.forEach(function(otherSocket) {
otherSocket.emit('starting-something', {
user: data.user
});
});
// Add this user to the current users collection
battle.users.push(data.user);
lobby.update(battle);
}
battle.sockets.push(socket);
// Let the user know the details of the battle
socket.emit('bring-it', {
users: battle.users,
leader: battle.leader,
state: battle.state,
challengeName: battle.challengeName
});
});
socket.on('kick-off', function() {
if (!battle) {
failSocket(socket, "There's been some awesome screw up on the backend. Sorry about that...");
}
battle.state = 'fighting';
battle.challengeName = challenges[Math.floor(challenges.length * Math.random())];
lobby.update(battle);
battle.sockets.forEach(function(socket) {
socket.emit('its-kicking-off', {
challengeName: battle.challengeName
});
});
});
socket.on('attack', function(data) {
data.user = user;
battle.sockets.forEach(function(socket) {
socket.emit('attacked', data);
});
});
socket.on('winning', function(data) {
data.user = user;
battle.sockets.forEach(function(socket) {
socket.emit('game-over', data);
});
battle.state = 'over';
lobby.destroy(battle);
});
});
var lobby = new (function(){
function prepBattle(battle){
return {
id: battle.id,
leader: battle.leader,
state: battle.state,
users: battle.users
};
}
function Lobby(){
this.sockets = io.of('/lobby')
.on('connection', function(socket){
var battleArray = [];
for (var key in battles) {
if (battles[key].state !== 'over') {
battleArray.push(prepBattle(battles[key]));
}
}
socket.emit('refresh', battleArray);
});
}
Lobby.prototype.update = function(battle){
this.sockets.emit('update', prepBattle(battle));
}
Lobby.prototype.add = function(battle){
this.sockets.emit('add', prepBattle(battle));
}
Lobby.prototype.destroy = function(battle){
this.sockets.emit('destroy', battle.id);
}
return Lobby;
}());
app.listen(process.env.NODE_ENV === 'production' ? 80 : 3000);