-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathserver.js
385 lines (336 loc) · 10 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
var app = require('express')();
var http = require('http').Server(app);
var io = require('socket.io')(http);
var passport = require('passport');
var SteamStrategy = require('passport-steam').Strategy;
var Datastore = require('nedb');
var session = require('express-session');
var request = require('request');
var PromiseThrottle = require('promise-throttle');
var auth = require('./auth.js');
var creds = require('./credentials.js');
var steamDbScraper = require('./steamdb-scraper.js');
var steamApiKey = creds.steamApiKey;
var sessionSecret = creds.sessionSecret;
Array.prototype.flatMap = function(lambda) {
return Array.prototype.concat.apply([], this.map(lambda));
};
var db = {};
db.users = new Datastore({
filename: 'users.db',
autoload: true
});
db.games = new Datastore({
filename: 'games.db',
autoload: true
});
var lobbies = {};
class Lobby {
constructor(id) {
this.users = [];
this.id = id;
}
}
class User {
constructor(openId, username, profilePicture, games, profile = {}) {
this.openId = openId;
this.games = games;
this.username = username;
this.profilePicture = profilePicture;
this.profile = profile;
}
}
passport.use(new SteamStrategy({
returnURL: 'https://games.sigkill.me/auth/steam/return',
realm: 'https://games.sigkill.me/',
apiKey: steamApiKey
}, function(identifier, profile, done) {
db.users.find({openId: identifier}, function(err, docs) {
if (err)
return done(err);
var user;
if (docs.length == 1) {
user = docs[0];
user.profile = profile;
user.username = profile.displayName;
db.users.update({openId: identifier}, user, function (err, numReplaced) {
});
} else if (docs.length == 0) {
user = new User(identifier, profile.displayName, '', [], profile);
db.users.insert(user, function (err, doc) {
});
} else {
console.log("FATAL ERROR. Multuple users returned");
return done(err);
}
return done(err, user);
});
}));
var sessionMiddleware = session({
secret: sessionSecret,
resave: true,
saveUninitialized: true
});
app.use(sessionMiddleware);
app.use(require('flash')());
app.use(passport.initialize());
app.use(passport.session());
app.use(require('express').static('static'));
app.get('/stats', function(req, res) {
res.write(JSON.stringify(lobbies));
res.end();
});
app.get('/favicon.ico', (req, res) => res.sendStatus(204));
app.get('/login', function(req, res) {
res.sendFile(__dirname + '/static/login.html');
});
app.get('/auth/steam', passport.authenticate('steam'),
function(req, res) {
}
);
app.get('/auth/steam/return', passport.authenticate('steam', {
failureRedirect: '/login',
failureFlash: true
}),
function(req, res) {
updateGames(req, function(err) {
var redirectTo = req.session.redirectTo || '/';
delete req.session.redirectTo;
req.session.user = req.user;
res.redirect(redirectTo);
});
}
);
app.get('/', auth.restrict, function(req, res) {
// Since we are here, there was no lobby id provided. Create a new lobby
var id = generateId();
while (getLobbyUserNicknames(id).length > 0) {
id = generateId();
}
var lobby = new Lobby(id);
lobbies[id] = lobby;
res.redirect('/' + id);
});
function generateId() {
var crypto = require('crypto');
return crypto.randomBytes(16).toString("hex");
}
app.get('/:lobbyId', auth.restrict, function(req, res) {
if (req.params.lobbyId in lobbies) {
req.session.lobbyId = req.params.lobbyId;
assignUserToLobby(req.session.lobbyId, req.user);
res.sendFile(__dirname + '/static/main.html');
} else {
res.status(404).send('Lobby not found');
}
});
function assignUserToLobby(lobbyId, user) {
addUserToLobbyIfNeeded(lobbyId, user);
}
function removeUserFromLobby(lobbyId, user) {
if (lobbyId in lobbies) {
var lobby = lobbies[lobbyId];
lobby.users = lobby.users.filter(u => u.openId !== user.openId);
}
}
function addUserToLobbyIfNeeded(lobbyId, user) {
if (lobbyId in lobbies) {
var lobby = lobbies[lobbyId];
if (!lobby.users.find(user => user.openId == user.openId)) {
lobby.users.push(user);
}
}
}
function updateGames(req, callback) {
getOwnedGames(steamApiKey, req.user.profile._json.steamid, function(games) {
db.users.find({openId: req.user.openId}, function (err, docs) {
if (docs.length == 1) {
var user = docs[0];
user.games = games;
db.users.update({openId: user.openId}, user, {}, function (err, numReplaced) {
if (!err) {
// Forces the session to update with the new user/games
req.login(docs[0], function (err) {
callback(err);
});
} else callback(err);
});
}
});
});
}
function getOwnedGames(apiKey, steamUserId, callback) {
steamurl = 'http://api.steampowered.com/IPlayerService/GetOwnedGames/v0001/?key=' + apiKey +
'&steamid=' + steamUserId +
'&include_appinfo=1' +
'&include_played_free_games=1' +
'&format=jsonwq';
request({url: steamurl}, function(error, response, body) {
if (Object.keys(JSON.parse(body).response).length === 0)
callback([]);
else
callback(JSON.parse(body).response.games);
});
}
// Accepts array of gameIds
function resolveGameInfos(games, callback) {
var promiseThrottle = new PromiseThrottle({
requestsPerSecond: 0.65, // 200 every 5 minutes
promiseImplementation: Promise
});
var promiseWrapper = function(id) { return getGameInfoApi(id).then((game) =>
{
db.games.insert(game, (err, doc) => {
return game;
});
});
};
var cachedEntities = [];
var promisedEntities = [];
var dbLookups = games.map(id => {
return new Promise(function(resolve, reject) {
db.games.find({appId: id}, function(err, docs) {
if(err)
reject(err);
if (docs.length > 0) {
cachedEntities.push(docs[0]);
} else {
promisedEntities.push(promiseThrottle.add(promiseWrapper.bind(this, id)));
}
resolve();
});
});
});
Promise.all(dbLookups).then(function() {
if (promisedEntities.length > 0) {
Promise.all(promisedEntities).then((result) => callback(cachedEntities.concat(result)));
} else {
callback(cachedEntities);
}
});
}
function getGameInfoApi(appId, callback) {
steamurl = 'https://store.steampowered.com/api/appdetails/?appids=' + appId;
return new Promise(function(resolve, reject) {
request(steamurl, function(error, response, body) {
if (error)
reject(error);
console.log(body);
var data = JSON.parse(body)[appId].data;
var multiplayer = data.categories.find(c => c.id == 1);
var coop = data.categories.find(c => c.id == 9);
resolve({
appId: appId,
name: data.name,
image: data.header_image,
multiplayer: (multiplayer != null),
coop: (coop != null)
});
});
});
}
function getGameInfo(game) {
return new Promise((resolve, reject) => {
db.games.find({appId: game.appid}, (err, docs) => {
if (err) reject(err);
if (docs.length > 0) {
resolve(docs[0]);
} else {
steamDbScraper.getAppInfo(game.appid).then(gameTags => {
gameTags.name = game.name;
gameTags.image = 'https://steamcdn-a.akamaihd.net/steam/apps/'+gameTags.appId+'/header.jpg';
db.games.insert(gameTags, (err, doc) => {
if (err) reject(err);
resolve(gameTags);
});
});
}
});
});
}
function getCommonGames(games, callback) {
// Count occurences per appId count[appId] = count
var allGames = games.flatMap(p => p.flatMap(c => c.appid));
var count = {};
allGames.forEach(function (i) { count[i] = (count[i]||0) + 1;});
// Find all appIds that has occured as many times as there are clients
// Resolve its appId to a game name
var filteredGames = Object.keys(count)
.filter(id => count[id] == games.length)
.map(id => games.flatMap(p => p.flatMap(c => c)).find(game => game.appid == id));
/*
var gameTags = filteredGames.map(game => steamDbScraper.getAppInfo(game.appid));
filteredGames = filteredGames.reduce((map, obj) => { map[obj.appid] = obj; return map; }, {});
Promise.all(gameTags).then(tags => {
var commonGames = tags.map(tag => {
tag.name = filteredGames[tag.appId].name;
tag.image = 'https://steamcdn-a.akamaihd.net/steam/apps/'+tag.appId+'/header.jpg';
return tag;
});
callback(commonGames);
});
*/
var derp = filteredGames.map(game => getGameInfo(game));
Promise.all(derp).then(games => {
callback(games);
});
}
function getLobbyUserNicknames(lobbyId) {
if (lobbyId in lobbies) {
var lobby = lobbies[lobbyId];
var nicks = lobby.users.map(user => user.username);
return nicks;
}
return [];
}
io.use(function(socket, next) {
sessionMiddleware(socket.request, socket.request.res, next);
});
io.on('connection', function(socket) {
console.log("connection");
if (!socket.request.session.user || !socket.request.session.user.profile)
return;
var lobbyId = socket.request.session.lobbyId;
var broadcastUpdates = function(socket, lobbyId) {
io.to(lobbyId).emit('users', getLobbyUserNicknames(lobbyId));
broadcastCommonGames(socket, lobbyId);
};
// Sometimes a connection dies and recreates itself during a session
// so make sure the user gets re-added if that happens
addUserToLobbyIfNeeded(lobbyId, socket.request.session.user);
socket.join(lobbyId);
console.log("Sending updates due to new connection");
broadcastUpdates(socket, lobbyId);
socket.on('disconnect', function() {
removeUserFromLobby(lobbyId, socket.request.session.user);
console.log("Sending updates due to disconnect");
broadcastUpdates(socket, lobbyId);
});
});
function broadcastCommonGames(socket, lobbyId) {
console.log("Broadcasting games to lobby id " + lobbyId);
if (lobbyId in lobbies) {
var lobby = lobbies[lobbyId];
// Only emit games if there are more than 1 users
//if (lobby.users.length > 1) {
var allGamesArray = lobby.users.map(user => user.games);
getCommonGames(allGamesArray, (games) => io.to(lobbyId).emit('games', games));
//}
} else {
console.log("FATAL ERROR. No lobby found when attempting to broadcast games");
}
}
passport.serializeUser(function(user, done) {
done(null, user.openId);
});
passport.deserializeUser(function(id, done) {
db.users.find({ openId: id }, function (err, docs) {
if (docs.length == 1)
done(err, docs[0]);
else
done(err);
});
});
http.listen(3000, function() {
console.log('Listening on 3000');
});