-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathapp.js
881 lines (772 loc) · 26.5 KB
/
app.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
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
/*
* TODO Raven uses 'game' for two metaphors: Game function, and instance of Game function.
* Let's break it into 'Game' and 'Table'.
*/
var fs = require('fs'),
express = require('express'),
logger = require('./lib/logger').logger;
var session = require('express-session')
var cookieParser = require('cookie-parser')
var sharedsession = require("express-socket.io-session");
var mongoose = require('mongoose')
, socketio = require('socket.io')
, assert = require('assert')
, cas = require('cas')
, cookie = require('cookie')
, http_request = require('request')
, http = require('http')
, Rollbar = require('rollbar')
, util = require('util');
mongoose.plugin(schema => { schema.options.usePushEach = true });
var _ = require('underscore'),
moment = require('moment'),
EGSNotifier = require('./lib/egs_notifier');
function init(Game) {
var me = this;
this.configure = function(options) {
me.send_index = options.send_index;
me.send_asset = options.send_asset;
};
this.run = function() {
var metadata = Game.metadata;
var DISABLE_CAS = process.env.DISABLE_CAS || false;
var CAS_HOST = process.env.CAS_HOST || "cas.littlevikinggames.com";
var CAS_URL = process.env.CAS_URL || "https://" + CAS_HOST + "/login";
var CAS_HOST_FALLBACK = process.env.CAS_HOST_FALLBACK;
var CAS_URL_FALLBACK = process.env.CAS_URL_FALLBACK || "https://" + CAS_HOST_FALLBACK + "/login";
var SERVICE_URL = process.env.SERVICE_URL;
var PORT = process.env.PORT || 3000;
var EGS_HOST = process.env.EGS_HOST || "globalecco.org";
var EGS_PORT = process.env.EGS_PORT || 443;
var EGS_PROTOCOL = process.env.EGS_PROTOCOL || (EGS_PORT == 443 ? 'https' : 'http')
var EGS_USERNAME = process.env.EGS_USERNAME;
var EGS_PASSWORD = process.env.EGS_PASSWORD;
var GAME_PATH_PREFIX = process.env.GAME_PATH_PREFIX || "";
var ROLLBAR_ACCESS_TOKEN = process.env.ROLLBAR_ACCESS_TOKEN;
var MONGODB_URI = process.env.MONGODB_URI || 'mongodb://localhost/lvg-'+metadata.slug;
var KEY_FILE = process.env.KEY_FILE;
var CERT_FILE = process.env.CERT_FILE;
var app;
var use_ssl = false;
if (ROLLBAR_ACCESS_TOKEN) {
var rollbar = new Rollbar({
accessToken: ROLLBAR_ACCESS_TOKEN,
captureUncaught: true,
captureUnhandledRejections: true
});
logger.info("Rollbar initialised.");
}
if (KEY_FILE && CERT_FILE) {
logger.info("Using SSL");
use_ssl = true;
var server_options = {};
server_options.key = fs.readFileSync(KEY_FILE);
server_options.cert = fs.readFileSync(CERT_FILE);
app = express(server_options);
} else if ((KEY_FILE && !CERT_FILE) || (CERT_FILE && !KEY_FILE)) {
throw "If one of KEY_FILE or CERT_FILE are specified, you must supply both of them, not just one";
} else {
app = express();
}
app.use(rollbar.errorHandler());
//app.use(function(req, res, next) {
// res.header("Access-Control-Allow-Origin", "localhost:4000"); // update to match the domain you will make the request from
// res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
// next();
//});
app.use(cookieParser());
//app.use(session({secret: 'secret', key: 'express.sid'}));
//var session_store = new MemoryStore();
//app.use(session({ store: session_store, secret: 'secret', key: 'express.sid'}));
var MemoryStore = require('memorystore')(session)
var memoryStore = new MemoryStore({
checkPeriod: 86400000 // prune expired entries every 24h
})
var sessionMiddleware = session({
store: memoryStore,
secret: "secret",
key: "express.sid"
});
app.use(sessionMiddleware);
//app.use(session({
// cookie: { maxAge: 86400000 },
// store: memoryStore,
// secret: 'secret',
// key: 'express.sid'
//}))
var server = http.createServer(app);
var io = socketio(server);
//io.set('origins', '*:*');
//io.use(sharedsession(session));
io.use(function(socket, next) {
sessionMiddleware(socket.request, socket.request.res, next);
});
server.listen(PORT, function() {
logger.info("["+new Date()+"] "+metadata.name+" listening on http://localhost:" + PORT + GAME_PATH_PREFIX);
});
// global variables
var connectedUsers = 0;
// global types
var Schema = mongoose.Schema;
var userSchema = new Schema({
gaming_id: {type: String, default: null },
cas_handle: {type: String, default: null }
});
var User = mongoose.model('User', userSchema);
var sessionSchema = new Schema({
session_id: { type: String, default: null },
gaming_id: {type: String, default: null },
game_id: {type: String, default: null}
});
var Session = mongoose.model('Session', sessionSchema);
var gameSchema = new Schema({
is_in_progress: { type: Boolean, default: false },
roles: function(roles){
var results = {};
for (var i = 0; i < roles.length; i++) {
results[roles[i].slug] = { type: String, default: null };
}
return results;
}(metadata.roles),
gameState: String,
chat_messages: [{time: Date, user: String, role: String, message: {type: String, trim: true}}]
});
var GameModel = mongoose.model('Game', gameSchema);
var find_or_create_session = function(gaming_id, session_id, next) {
Session.findOne({ session_id: session_id }, function(err, session) {
if (err) { throw err; }
if (session) {
next(session);
} else {
session = new Session({ session_id: session_id, gaming_id: gaming_id });
session.save(function(err) {
if (err) { throw err; }
next(session);
});
}
});
}
// next takes the found/created user as parameter
var find_or_create_user = function(profile, session_id, next) {
var gaming_id = profile.gamingId;
find_or_create_session(gaming_id, session_id, function(session) {
User.findOne({ gaming_id: gaming_id }, function (err, user) {
if (err) {
throw err;
}
if (user) {
next(user);
} else {
var user = new User({ gaming_id: gaming_id, cas_handle: profile.casId });
user.save(function (err) {
if (err) {
throw err;
}
next(user);
});
}
});
});
};
function authenticate_with_cas(request, response, callback) {
if (DISABLE_CAS) {
var handle = request.query.handle;
logger.debug("DISABLE_CAS is true. Skipping authentication for "+handle);
callback(handle);
return;
}
var serviceTicket = request.query.ticket;
var hasServiceTicket = typeof serviceTicket !== 'undefined';
var host = CAS_HOST;
var cas_url = CAS_URL;
if (request.query.cas == "test") {
host = CAS_HOST_FALLBACK;
cas_url = CAS_URL_FALLBACK;
}
var protocol = use_ssl ? "https://" : "http://";
logger.debug("Request.url: " + request.url);
var path = request.url.replace(/[&|\?]?ticket=[\w|-]+/i, "");
logger.debug("Path: " + path);
var serviceURL = SERVICE_URL || (protocol + request.headers.host);
serviceURL += path;
logger.debug("CAS service: "+serviceURL);
var loginUrl = cas_url + '?service=' + encodeURIComponent(serviceURL);
logger.debug("CAS Login URL: "+loginUrl);
var base_url = "https://"+host;
var casInstance = new cas({
base_url: base_url,
service: serviceURL,
https: {
rejectUnauthorized: false
}
});
// initial visit
if (!hasServiceTicket) {
logger.info("Redirecting to CAS Login");
response.redirect(loginUrl);
return;
}
logger.info("Got service ticket: " + serviceTicket);
// validate service ticket
casInstance.validate(serviceTicket, function(error, status, cas_handle) {
logger.info("Validated ticket.");
if (error) {
logger.error("Error validating CAS: ", error);
}
if (error || !status) {
response.redirect(loginUrl);
return;
}
callback(cas_handle);
});
}
function handleLogin(request, response, game_id, callback) {
logger.info("Handling Login!");
applyHeaders(response);
authenticate_with_cas(request, response, function(cas_handle) {
logger.info(cas_handle + " logged in! SessionID: " + request.cookies['express.sid']);
getPlayerProfile(cas_handle, game_id, function(error, profile) {
if (error) {
respond_with_error(response, error);
return;
}
if (!profile) {
respond_with_error(response, "Unable to retrieve player profile.");
return;
}
find_or_create_user(profile, request.cookies['express.sid'], function(user) {
callback(user);
});
});
});
}
applyHeaders = function(res) {
res.header("Cache-Control", "max-age=600");
};
serve_path = function(req, res, path) {
applyHeaders(res);
logger.debug("Serving: " + path);
me.send_asset(req, res, path);
}
serve_lib = function(req, res) {
var path = req.originalUrl.replace(new RegExp(GAME_PATH_PREFIX, ""), "");
serve_path(req, res, path);
}
serve_assets = function(req, res) {
var path = "/assets" + req.originalUrl.replace(new RegExp(GAME_PATH_PREFIX, ""), "");
serve_path(req, res, path);
}
authenticateAppServer = function(req, res, callback) {
//TODO implement
callback();
};
handleNew = function(req, res) {
logger.debug("New game requested.");
authenticateAppServer(req, res, function() {
return createGame(req, res);
});
};
handlePlay = function(req, res) {
logger.debug("/play requested.");
var game_id = req.param('gid');
if (!game_id) {
res.send("gid is a required parameter", 400);
return;
}
handleLogin(req, res, game_id, function(user) {
return playGame(req, res, game_id, user);
});
};
var egs_response = function(req, res, params, next) {
if (!params.stat) { throw "Params.stat is required"; }
var format = "xml";
if (req.param('fmt')) {
format = req.param('fmt').toLowerCase();
}
var code = params.stat === "ERROR" ? 400 : 200;
if (format === "xml") {
var body = "<stat>"+params.stat+"</stat>";
if (params.msg) {
body = body + "<msg>"+params.msg+"</msg>";
}
if (params.game_id) {
body = body + "<glst><cnt>1</cnt><game><gid>"+params.game_id+"</gid></game></glst>";
}
res.send(body, { 'Content-Type': 'application/xml' }, code);
} else if (format === "json") {
var json = { stat: params.stat };
if (params.msg) {
json.msg = params.msg;
}
if (params.game_id) {
json.glst = {
cnt: 1,
game: { gid: params.game_id }
};
}
res.json(json, code);
} else if (format === "html" && req.param("dbg") === "1") {
var role1 = metadata.roles[0];
var role2 = metadata.roles[1];
var html = "";
if (!process.env.DISABLE_CAS) {
html = html + "<b>With ECCO CAS server:</b><br>";
html = html + "<a href='"+GAME_PATH_PREFIX+"/play?gid="+params.game_id+"&role="+role1.slug+"&handle="+req.param(role1.slug)+"&app=BRSR'>Join game '"+params.game_id+"' as "+role1.name+"</a> ("+req.param(role1.slug)+")<br>";
html = html + "<a href='"+GAME_PATH_PREFIX+"/play?gid="+params.game_id+"&role="+role2.slug+"&handle="+req.param(role2.slug)+"&app=BRSR'>Join game '"+params.game_id+"' as "+role2.name+"</a> ("+req.param(role2.slug)+")<br>";
html = html + "<hr><b>With test CAS server:</b><br>";
}
html = html + "<a href='"+GAME_PATH_PREFIX+"/play?gid="+params.game_id+"&cas=test&role="+role1.slug+"&handle="+req.param(role1.slug)+"&app=BRSR'>Join game '"+params.game_id+"' as "+role1.name+"</a> ("+req.param(role1.slug)+")<br>";
html = html + "<a href='"+GAME_PATH_PREFIX+"/play?gid="+params.game_id+"&cas=test&role="+role2.slug+"&handle="+req.param(role2.slug)+"&app=BRSR'>Join game '"+params.game_id+"' as "+role2.name+"</a> ("+req.param(role2.slug)+")<br>";
res.send(html, { 'Content-Type': 'text/html' }, code);
} else {
res.send("Invalid format: " + req.fmt+". Must be one of 'json' or 'xml'", 400);
}
if (typeof next === 'function') {
next();
}
};
var egs_error_response = function(req, res, message) {
return egs_response(req, res, {
stat: "ERROR",
msg: message
});
};
var egs_game_response = function(req, res, game_id, next) {
egs_response(req, res, {
stat: "OK",
game_id: game_id
}, next);
};
var getPlayerProfile = function(cas_handle, game_id, callback) {
logger.debug("getPlayerProfile() called with cas_handle: "+cas_handle+", and gameid: " + game_id);
var path = "/api/secure/jsonws/egs-portlet.gamingprofile/get?ver=1.0&title="+metadata.slug+"&gid="+encodeURIComponent(game_id)+"&email="+encodeURIComponent(cas_handle);
var auth = (EGS_USERNAME && EGS_PASSWORD) ? (encodeURIComponent(EGS_USERNAME)+":"+EGS_PASSWORD+"@") : "";
var url = EGS_PROTOCOL + "://"+auth+EGS_HOST+":"+EGS_PORT+path;
var opts = {
url: url,
method: 'GET'
};
logger.debug("Opts for request:", opts);
http_request(opts, function(error, response, body) {
if (error) {
logger.error("Error getting gaming profile from EGS. Error: " + error);
callback("Unable to retrieve gaming profile for "+cas_handle);
return;
}
if (response.statusCode !== 200) {
logger.error("Error getting gaming profile from EGS. Response code: " + (response.statusCode || 'none') );
logger.error(body);
callback("Unable to retrieve gaming profile for "+cas_handle);
return;
}
logger.debug("Response from EGS: " + body);
/*
{
"gameInstanceId": "xxx",
"gamingId":"xxxxxxx",
"casId": "some email address"
}
*/
var response = JSON.parse(body);
if (response.exception) {
callback(response.exception, null);
} else {
callback(null, response);
}
return;
});
};
var respond_with_error = function(response, message) {
logger.error("Error: " + message);
response.send(message, 400);
};
var createGame = function(req, res) {
logger.debug("Creating game.");
var lang = req.lang;
var debug = req.debug;
var app = req.app;
var role1 = metadata.roles[0];
var role2 = metadata.roles[1];
var player1 = req.param('role1') || req.param(role1.slug);
var player2 = req.param('role2') || req.param(role2.slug);
if (!player1 || !player2) {
logger.error("Got invalid request for new game:");
logger.error(req.query);
return egs_error_response(req, res, "Both roles must be provided ("+role1.slug+" and "+role2.slug+")");
}
var roles = {}
roles[role1.slug] = player1;
roles[role2.slug] = player2;
var dbgame = new GameModel({
is_in_progress: true,
roles: roles
});
dbgame.save(function (err, game) {
if (err) { throw err; }
logger.debug("Created game: "+game._id+". Roles: "+game.roles);
egs_game_response(req, res, game._id, function() {
var egs_notifier = new EGSNotifier.EGSNotifier({
host: EGS_HOST,
port: EGS_PORT,
username: EGS_USERNAME,
password: EGS_PASSWORD,
game_id: dbgame._id,
game_title: metadata.slug,
game_version: '1.0',
players: roles
});
egs_notifier.setPlayerState(Game.initialPlayerState());
});
});
};
var playGame = function(req, res, game_id, user) {
logger.debug("Request to play game '"+game_id+"' from user:", user);
var role = req.param('role');
if (!role) {
res.send("role is a required parameter", 400);
return;
}
if (role !== metadata.roles[0].slug && role !== metadata.roles[1].slug) {
res.send("role must be one of '"+metadata.roles[0].slug+"' or '"+metadata.roles[1].slug+"'");
return;
}
GameModel.findOne({_id: game_id}, function(err, game) {
if (err || !game) {
logger.error("Error looking up game '"+game_id+"'");
res.send("Could not find game with id: " + game_id, 400);
return;
}
logger.debug("Found game: " + game_id);
logger.debug(game);
logger.debug("User:");
logger.debug(user);
var requested_nickname = game.roles[role];
if (user.gaming_id !== requested_nickname) {
respond_with_error(res, "Requested game role ('"+requested_nickname+"') does not match the logged in user ('"+user.gaming_id+"').");
logger.debug("Requested role: " + role + ", saved handle: " + requested_nickname + ", current handle: " + user.gaming_id);
return;
}
// TODO HACK temporary hack to quickly lookup game_id after they connect with websockets
Session.findOne({session_id: req.cookies['express.sid']}, function(err, session) {
if (err) {
logger.error("Error looking up session for: " + req.cookies['express.sid']);
res.send("Could not find session. Try reconnecting.", 400);
return;
}
session.game_id = game_id;
logger.debug("Saved game_id to session.");
session.save(function(err) {
if (err) { throw err; }
logger.debug("Playing game: "+game_id);
me.send_index(req, res);
});
});
});
};
app.post(GAME_PATH_PREFIX+'/new', function(req, res) {
handleNew(req, res);
});
app.get(GAME_PATH_PREFIX+'/new', function(req,res) {
handleNew(req, res);
});
app.post(GAME_PATH_PREFIX+'/play', function(req, res) {
handlePlay(req, res);
});
app.get(GAME_PATH_PREFIX+'/play', function(req, res) {
handlePlay(req, res);
});
app.get(GAME_PATH_PREFIX+'/credits', function (req, res) {
var md = require("node-markdown").Markdown;
fs.readFile('CREDITS.md', 'utf-8', function(err, credits) {
if (err) {
logger.err("Error reading CREDITS.md", err);
res.send("Error!");
return;
}
var html = md(credits);
res.header("Content-Type", "text/html");
res.send(html);
});
});
app.get(GAME_PATH_PREFIX+'/status', function(req, res) {
res.send("Okay!");
});
app.get(GAME_PATH_PREFIX+'/lib/*', serve_lib);
app.get(GAME_PATH_PREFIX+'/*', serve_assets);
var debug = function(req, res) {
res.header("Content-Type", "text/html");
var html = "";
html += "<p>Hi! I'm a Raven instance running '"+metadata.name+"' at '"+req.headers.host+"'.</p>";
html += "<p>req url: " + req.url +"</p><hr>";
html += "<p>Query: <br><pre>"+JSON.stringify(req.query,null,'\t')+"</pre></p><hr>";
html += "<p>ENV VARS: <br><pre>" + JSON.stringify(process.env,null,'\t')+"</pre></p>";
res.send(html);
};
// app.get(GAME_PATH_PREFIX+'/', debug);
// app.get('/*', debug);
//Clients should set their resource to 'GAME_PATH_PREFIX/socket.io', minus the initial trailing slash
io.set('resource', GAME_PATH_PREFIX+"/socket.io");
io.set('authorization', function (data, accept) {
// check if there's a cookie header
if (data.headers.cookie) {
// if there is, parse the cookie
data.cookie = cookie.parse(data.headers.cookie);
// note that you will need to use the same key to grad the
// session id, as you specified in the Express setup.
data.sessionID = data.cookie['express.sid'];
} else {
// if there isn't, turn down the connection with a message
// and leave the function.
return accept('No cookie transmitted.', false);
}
// accept the incoming connection
accept(null, true);
});
var Table = function(dbgame) {
var table = this;
var game;
var players = {}; //indexed by gaming_id
var draw_offered_by = dbgame.draw_offered_by; //keeps track of whether a draw has been offered and by whom
this.setDrawOfferedBy = function(val) {
table.draw_offered_by = val;
dbgame.draw_offered_by = val;
dbgame.save(function(err) { if (err) throw err; });
};
var roles = {};
_.each(metadata.roles, function(role) {
roles[role.slug] = dbgame.roles[role.slug];
});
var egs_notifier = new EGSNotifier.EGSNotifier({
host: EGS_HOST,
port: EGS_PORT,
username: EGS_USERNAME,
password: EGS_PASSWORD,
game_id: dbgame._id,
game_title: metadata.slug,
game_version: '1.0',
players: roles
});
var raven = {
broadcast: function(message, data) {
_.each(players, function(player, gaming_id) {
player.socket.emit(message, data);
});
},
save: function(gameStateDTO) {
dbgame.gameState = JSON.stringify(gameStateDTO);
dbgame.save(function(err) { if (err) throw err; });
},
/*
* Portal notification methods
*/
/*
* Sets the waiting state for each role specified in `state`.
* `state` is an object which has roles for properties and their attention
* state for values. Valid values are "ATTN" and "PEND".
*
* "ATTN" indicates that the game is waiting for this player to
* provide input (for example, to take their turn). "PEND" means that
* the game is not waiting on this player (for example, it is the other
* player's turn).
*
* Example state:
* {
* white: "ATTN",
* black: "PEND"
* }
*
* As a short cut, one can call setPlayerState(role, state), which is the
* equivalent of doing setPlayerState({ role: state })
*/
setPlayerState: function(state) {
if (arguments.length === 2) {
var singleState = {}
singleState[arguments[0]] = arguments[1];
egs_notifier.setPlayerState(singleState);
} else {
egs_notifier.setPlayerState(state);
}
},
ATTN: "ATTN", // Indicates that the game is waiting for the player
PEND: "PEND", // Indicates that the game is not waiting for the player
OVER: "OVER", // Indicates that this player is done with the game.
/*
* Indicate that the player in `role` has forfeit the game
*/
forfeit: function(role) {
egs_notifier.forfeit(role);
},
/*
* Indicate that the game is over. The winner is specified by
* `winning_role`. `scores` contains the final scores
*/
gameover: function(winning_role, scores) {
egs_notifier.gameover(winning_role, scores);
}
};
if (_.isUndefined(dbgame.gameState) || dbgame.gameState === null) {
logger.info("Creating new game: "+dbgame._id);
game = Game(raven);
} else {
logger.debug("Restoring old game: "+dbgame._id);
game = Game(raven, JSON.parse(dbgame.gameState));
}
var addPlayer = function(socket, user, role) {
players[user.gaming_id] = { user: user, socket: socket, role: role};
socket.emit('userdata', { username: user.gaming_id, role: role });
game.addPlayer(socket, user, role);
raven.broadcast('user_online', user.gaming_id);
socket.emit('chat_history', dbgame.chat_messages);
if (table.draw_offered_by && table.draw_offered_by !== user.gaming_id) {
socket.emit('draw_offered', {by: table.draw_offered_by});
}
var handleError = function(callback, data) {
try {
var result = callback(data);
return result;
} catch (e) {
socket.emit('error', e);
console.log("Error: ", e);
console.log(e.stack);
}
};
var logAndHandle = function(message, callback) {
socket.on(message, function(data) {
console.log("["+user.gaming_id+"] " + message + ": ", data);
return handleError(callback, data);
});
};
logAndHandle('message', function(message) {
message = {user: user.gaming_id, message: message.message, role: role, time: new Date()};
dbgame.chat_messages.push(message);
dbgame.save();
raven.broadcast('message', message);
});
logAndHandle('offer_draw', function() {
console.log(user.gaming_id + " is offering a draw.");
if (!game.hasStarted()) {
throw "Game has not started yet!";
}
if (table.draw_offered_by) {
throw "Draw has already been offered!";
}
table.setDrawOfferedBy(user.gaming_id);
raven.broadcast('draw_offered', {by: user.gaming_id});
});
logAndHandle('accept_draw', function() {
console.log(user.gaming_id + " has accepted the draw offer");
if (!table.draw_offered_by) {
throw "No draw has been offered!";
}
if (user.gaming_id === table.draw_offered_by) {
throw "You cannot accept your own draw!";
}
raven.broadcast('draw_accepted', null);
game.draw();
table.setDrawOfferedBy(null);
egs_notifier.draw();
});
logAndHandle('reject_draw', function() {
if (!table.draw_offered_by) {
throw "No draw has been offered!";
}
if (user.gaming_id === table.draw_offered_by) {
throw "You cannot reject your own draw!";
}
raven.broadcast('draw_rejected', null);
console.log(user.gaming_id + " has rejected the draw offer");
table.setDrawOfferedBy(null);
});
socket.on('disconnect', function(socket) {
delete players[user.gaming_id];
raven.broadcast('user_offline', user.gaming_id);
logger.info(user.gaming_id + " disconnected.");
logger.info('connected users: ', totalUsers());
});
logger.debug('joined table');
logger.debug('active tables: ' + tables.length);
logger.info('connected users: ' + totalUsers());
}
return {
game: game,
dbgame: dbgame,
addPlayer: addPlayer
};
};
// TODO tables are currently never unloaded. Should unload them after all players disconnect
var tables = [];
var totalUsers = function() {
return _.reduce(tables, function(accum, table) {
return accum + table.game.getPlayerCount();
}, 0)
};
var findTable = function(dbgame) {
var i = 0;
for(i = 0; i < tables.length; i++) {
tmp = tables[i].dbgame;
if (tmp._id.equals(dbgame._id)) {
return tables[i];
}
}
return null;
}
var handleSessionError = function(socket) {
socket.emit('session_error', "Invalid socket session. Please refresh your browser.");
};
io.sockets.on('connection', function (socket) {
var session_id = socket.request.sessionID;
if (!session_id) {
// This occurs when a client reconnects after server restarts
handleSessionError(socket);
return;
}
Session.findOne({session_id: session_id}, function(err, session) {
if (err) {
throw "Error looking up session: " + err;
}
if (!session) {
handleSessionError(socket);
return;
}
var game_id = session.game_id;
GameModel.findOne({_id: game_id}, function(err, dbgame) {
if (err || !dbgame) {
logger.error("Unable to lookup game: "+game_id);
socket.emit('error', "Unable to lookup requested game. Try refreshing your browser.");
return;
}
User.findOne({gaming_id: session.gaming_id}, function(err, user) {
if (err || !user) {
logger.error("Unable to look up user by user.gaming_id '"+user.gaming_id+"': "+err);
socket.emit('error', "Unable to look up user. Try refreshing your browser.");
return;
}
var role;
_.find(dbgame.roles, function(gaming_id, role_slug) {
role = role_slug;
return gaming_id === user.gaming_id;
});
var table = findTable(dbgame);
if (!table) {
table = Table(dbgame);
logger.debug("Stuffing game into tables: " + dbgame._id);
tables.push(table);
}
table.addPlayer(socket, user, role);
});
});
});
});
var options = { server: { socketOptions: { connectTimeoutMS: 10000 }}};
mongoose.connect(MONGODB_URI, options, function(err) {
if (err) {
throw err;
}
});
}; // function run()
return {
run: me.run,
configure: me.configure
};
};
exports.init = init;