-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.js
More file actions
2342 lines (2060 loc) · 62 KB
/
Copy pathmain.js
File metadata and controls
2342 lines (2060 loc) · 62 KB
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
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
var fs = require("fs");
var util = require("util");
var moment = require('moment');
var constants = require('./constants.js');
var kue = require('kue');
var JsonPropertyFilter = require("json-property-filter");
var Mustache = require("mustache");
var request = require('request');
// Change "a few seconds ago" to "moments ago"
moment.localeData('en')._relativeTime.s = "moments";
GameState = constants.GameState;
PlayerState = constants.PlayerState;
SlotType = constants.SlotType;
AIDifficulty = constants.AIDifficulty;
var Promise = Parse.Promise;
var Query = Parse.Query;
var Game = Parse.Object.extend("Game");
var Config = Parse.Object.extend("Config");
var Turn = Parse.Object.extend("Turn");
var Player = Parse.Object.extend("Player");
var Contact = Parse.Object.extend("Contact");
var Invite = Parse.Object.extend("Invite");
var parseObjectConfig = {
"_User": {
filter: [
"displayName",
"objectId",
"avatar"
]
},
"Turn": {
filter: [
"**"
]
},
"Game": {
filter: [
"**",
"-lobbyTimeoutJob",
"-turnTimeoutJob",
],
post: function(game, context) {
var now = moment();
var momentCreated = moment(game.createdAt);
game.createdAgo = momentCreated.from(now);
game.updatedAgo = moment(game.updatedAt).from(now);
var momentStartTimeout = momentCreated.add(constants.START_GAME_MANUAL_TIMEOUT, "seconds");
game.startable =
game.state == GameState.Lobby &&
now.isAfter(momentStartTimeout);
// Free slots and "joined" bool
if (context && context.players) {
var slots = game.config.slots;
game.joined = false;
if (slots) {
slots.forEach(function(slot) {
slot.filled = slot.type == SlotType.AI;
}, this);
}
context.players.forEach(function(player) {
var gameId = player.get("game").id;
if (gameId != game.objectId) return;
var slotIndex = player.get("slot");
if (player.get("user").id == context.userId) {
game.joined = true;
}
if (!slots) return;
if (slotIndex < 0 || slotIndex >= slots.length) return;
var slot = slots[slotIndex];
slot.filled = true;
slot.player = filterObject(player, context);
slot.player = getPropFilter([
"slot",
"state",
"user"
]).apply(slot.player);
}, this);
if (slots) {
var slotsFree = slots.filter(function(slot) {
return slot.type == SlotType.Open && !slot.filled;
});
game.freeSlots = slotsFree.length;
}
}
return game;
}
},
"Player": {
filter: [
"**",
"-game"
]
}
};
// Hook into Object subclasses to provide master access for common methods
[Game, Config, Turn, Player, Contact, Invite].forEach(
function(Obj) {
Obj.internalSave = Obj.prototype.save;
Obj.prototype.save = function(arg1, arg2, arg3) {
var options;
var args;
var keyValueOptions = arg3 !== undefined;
if (keyValueOptions) {
if (!arg3) arg3 = {};
options = arg3;
args = [arg1, arg2, options];
} else {
if (!arg2) arg2 = {};
options = arg2;
args = [arg1, options];
}
options.useMasterKey = true;
return Obj.internalSave.apply(this, args);
};
Obj.internalDestroy = Obj.prototype.destroy;
Obj.prototype.destroy = function(options) {
if (!options) options = {};
options.useMasterKey = true;
return Obj.internalDestroy.call(this, options);
};
}
);
// Hook into Parse.Object for master access
var PObject = {};
PObject.destroyAll = Parse.Object.destroyAll;
Parse.Object.destroyAll = function(list, options) {
if (!options) options = {};
options.useMasterKey = true;
return PObject.destroyAll(list, options);
};
// Hook into Query.get for always-on master access and
// better NOT_FOUND error messages
var PQuery = {};
PQuery.get = Query.prototype.get;
Query.prototype.get = function(objectId, options) {
var that = this;
if (!options) options = {};
options.useMasterKey = true;
var query = PQuery.get.call(this, objectId, options);
return query.then(
function(result) {
return Promise.resolve(result);
},
function(err) {
if (
err instanceof Parse.Error &&
err.code == Parse.Error.OBJECT_NOT_FOUND
) {
var notFound = null;
switch (that.className) {
case "Game": notFound = constants.t.GAME_NOT_FOUND; break;
case "Player": notFound = constants.t.PLAYER_NOT_FOUND; break;
case "Contact": notFound = constants.t.CONTACT_NOT_FOUND; break;
case "User": notFound = constants.t.USER_NOT_FOUND; break;
}
if (notFound) return Promise.reject(new CodedError(notFound));
}
return Promise.reject(err);
}
);
};
PQuery.find = Query.prototype.find;
Query.prototype.find = function(options) {
if (!options) options = {};
options.useMasterKey = true;
return PQuery.find.call(this, options);
};
PQuery.first = Query.prototype.first;
Query.prototype.first = function(options) {
if (!options) options = {};
options.useMasterKey = true;
return PQuery.first.call(this, options);
};
PQuery.count = Query.prototype.count;
Query.prototype.count = function(options) {
if (!options) options = {};
options.useMasterKey = true;
return PQuery.count.call(this, options);
};
/**
* Error subclass for coded error messages.
*
* @param {Object} message Constant message object to use.
* @param {Object} context Optional Mustache template "view" context object.
* @api protected
*/
function CodedError(message, context) {
if (context !== undefined) {
this.message = Mustache.render(message.m, context);
} else {
this.message = message.m;
}
this.code = message.id;
Error.captureStackTrace(this, CodedError);
}
util.inherits(CodedError, Error);
var nameBlacklist = fs.readFileSync("name-blacklist.txt", "utf8").split("\n");
function isBlacklisted(name) {
var len = nameBlacklist.length;
var lowercase = name.toLowerCase();
for (var i = 0; i < len; i++) {
var phrase = nameBlacklist[i];
if (lowercase.indexOf(phrase) != -1) {
return true;
}
}
return false;
}
function checkNameValidity(name, existingId) {
if (!name ||
typeof(name) !== "string" ||
name.length < constants.DISPLAY_NAME_MIN ||
name.length > constants.DISPLAY_NAME_MAX) {
return Promise.resolve(constants.t.INVALID_PARAMETER);
}
if (isBlacklisted(name)) {
return Promise.resolve(constants.t.DISPLAY_NAME_BLACKLISTED);
}
var query = new Query(Parse.User);
if (existingId) query.notEqualTo("objectId", existingId)
return query
.equalTo("displayName", name)
.first()
.then(
function(result) {
if (result) {
console.log("checkNameValidity result for " + name + "," + existingId + " : " + result.get("username"));
return constants.t.DISPLAY_NAME_TAKEN;
} else {
return null;
}
}
);
}
function getTypeIdFromRequest(req) {
var typeId = req.params.typeId === undefined ?
undefined : Number(req.params.typeId);
if (typeId === undefined || isNaN(typeId)) {
typeId = undefined;
}
return typeId;
}
// Jobs
var jobs = kue.createQueue({
prefix: process.env.REDIS_PREFIX || "q",
redis: process.env.REDIS_URL
});
function addJob(name, config) {
var promise = new Promise();
var delay = config.delay; delete config.delay;
var job = jobs.create(name, config);
if (delay !== undefined) job.delay(delay);
job.removeOnComplete(true);
job.save(function(err) {
if (err) {
promise.reject(err);
} else {
promise.resolve(job);
}
});
return promise;
}
function removeJobWithError(id) {
var promise = new Promise();
kue.Job.get(id, function(err, job) {
if (err) {
promise.reject(err);
return;
}
job.remove(function(err) {
if (err) {
promise.reject(err);
return;
}
promise.resolve();
});
});
return promise;
}
function removeJob(id) {
if (isNaN(Number(id))) {
return Promise.resolve(false);
}
var promise = new Promise();
kue.Job.get(id, function(err, job) {
if (err) {
promise.resolve(false);
return;
}
job.remove(function(err) {
if (err) {
promise.resolve(false);
return;
}
promise.resolve(true);
});
});
return promise;
}
jobs.process('game turn timeout', 10, function(job, done) {
var playerId = job.data.playerId;
job.log("Player: " + playerId);
new Query(Player)
.include("game")
.include("game.config")
.include("game.currentPlayer")
.include("game.currentPlayer.user")
.get(playerId)
.then(
function(player) {
job.log("Loaded");
game = player.get("game");
currentPlayer = game.get("currentPlayer");
if (currentPlayer.id != player.id) {
job.log("Timeout player " + player.id + " does not match current player " + currentPlayer.id);
return Promise.reject(new Error("Unable to time out turn due to different current player"));
}
return dropPlayer(game, currentPlayer);
}
).then(
function() {
job.log("Done");
done();
},
function(err) {
job.log(err.toString());
done(err);
}
);
});
jobs.process('game lobby timeout', 10, function(job, done) {
var gameId = job.data.gameId;
job.log("Game: " + gameId);
var game;
new Query(Game)
.include("currentPlayer.user")
.get(gameId)
.then(
function(g) {
game = g;
if (game.get("state") != GameState.Lobby) {
return Promise.reject(new Error("Not a lobby, skipping."));
}
return new Query(Player)
.equalTo("game", game)
.include("user")
.find();
}
).then(
function(players) {
job.log("Player count: " + players.length);
job.log("Players:\n" + players);
if (players.length < 2) {
job.log("Timed out");
notifyPlayers(
players,
constants.t.GAME_LOBBY_TIMEOUT,
{ game: game }
);
game.set("state", GameState.Ended);
return game.save();
} else {
return startGame(game);
}
}
).then(
function(g) {
game = g;
var state = game.get("state");
job.log("Game state: " + GameState.getName(state));
done();
},
function(error) {
done(error);
}
);
});
function respondError(res, error, context) {
if (error === undefined && context === undefined) {
return (function(e, c) {
respondError(res, e, c);
});
}
var response;
if (error instanceof Parse.Error) {
switch (error.code) {
case Parse.Error.SCRIPT_FAILED:
if (error.message !== undefined) error = error.message;
break;
default:
error.code = 2000 + error.code;
}
}
if (error instanceof CodedError) {
response = error;
} else if (error.id && error.m) {
response = new CodedError(error, context);
} else if (error.message) {
response = new CodedError({ id: constants.t.UNKNOWN_ERROR.id, m: filterObject(error.message) });
} else {
response = filterObject(error);
}
res.error(response);
}
function errorOnInvalidUser(user, res) {
var invalid = !user;
if (invalid) respondError(res, constants.t.USER_NOT_FOUND);
return invalid;
}
function checkGameState(game, acceptable) {
var result = {};
if (!game) {
result.error = constants.t.GAME_NOT_FOUND;
} else {
var state = game.get("state");
if (acceptable.indexOf(state) == -1) {
result.error = constants.t.GAME_INVALID_STATE;
result.context = {
acceptableNames: acceptable.map(function(st) {
return GameState.getName(st);
}).join(", "),
stateName: GameState.getName(state)
};
}
}
return result;
}
function errorOnInvalidGame(game, res, acceptable) {
var stateResult = checkGameState(game, acceptable);
if (stateResult.error) {
respondError(res, stateResult.error, stateResult.context);
return true;
}
return false;
}
function getPropFilter(filter) {
return new JsonPropertyFilter.JsonPropertyFilter(
filter.concat(["__type", "className"])
);
}
function filterObject(obj, context, level) {
if (level === undefined) level = 0;
// var startTime; if (level == 0) startTime = Date.now();
if (obj === null || obj === undefined) return obj;
switch (typeof(obj)) {
case "object":
if (!Array.isArray(obj)) {
if (typeof(obj.toJSON) === "function") {
// console.log("Converting to JSON");
var className = obj.className;
obj = obj.toJSON();
obj.className = className;
}
if (obj.className) {
var config = parseObjectConfig[obj.className];
if (config) {
if (config.pre && obj.__type != "Pointer") {
// console.log("Preprocessing");
obj = config.pre(obj, context);
}
if (config.filter) {
// console.log("Filtering");
var propFilter = config.filterInstance;
if (!propFilter) {
propFilter = config.filterInstance = getPropFilter(config.filter);
}
obj = propFilter.apply(obj);
}
if (config.post && obj.__type != "Pointer") {
// console.log("Postprocessing");
obj = config.post(obj, context);
}
}
}
if (obj._context) {
context = obj._context;
delete obj._context;
}
}
if (context) {
context._parent = obj;
}
// console.log("Processing children");
for (var key in obj) {
// var prefix = ""; while (prefix.length < level) prefix = prefix + " ";
// console.log(prefix, key + ": " + typeof(obj[key]));
if (context) context._key = key;
obj[key] = filterObject(obj[key], context, level + 1);
}
break;
}
// if (level == 0) console.log("Filtering:", Date.now() - startTime);
return obj;
}
function respond(res, message, data, filter) {
data = filterObject(data);
if (filter) {
data = getPropFilter(filter).apply(data);
}
data.code = message.id;
res.success(data);
}
Parse.Cloud.define("storePushToken", function(req, res) {
var user = req.user;
if (errorOnInvalidUser(user, res)) return;
var deviceToken = req.params.deviceToken ? String(req.params.deviceToken) : null;
var pushType = req.params.pushType ? String(req.params.pushType) : null;
if (!deviceToken) {
respondError(res, constants.t.INVALID_PARAMETER);
return;
}
if (!pushType) pushType = "gcm";
var deviceType;
switch (pushType) {
case "gcm":
deviceType = "android";
break;
default:
respondError(res, constants.t.INVALID_PARAMETER);
return;
}
var sessionToken = user.get("sessionToken");
var sessionQuery = new Query(Parse.Session);
var installationId;
return sessionQuery
.equalTo("sessionToken", sessionToken)
.first()
.then(
function(session) {
if (!session) return Promise.reject(new CodedError(constants.t.PUSH_TOKEN_ERROR));
installationId = session.get("installationId");
var instQuery = new Query(Parse.Installation);
return instQuery
.equalTo("installationId", installationId)
.first()
}
)
.then(
function(inst) {
if (!inst) {
/* Installation ID is not in database, add it */
var inst = new Parse.Object("_Installation");
inst.set("installationId", installationId);
inst.set("userId", user.get("username"));
}
return inst;
}
)
.then(
function(inst) {
/* Update token on given _Installation table row */
inst.set("deviceToken", deviceToken);
inst.set("pushType", pushType);
inst.set("deviceType", deviceType);
return inst.save();
}
)
.then(
function() {
respond(res, constants.t.PUSH_TOKEN_SET, {});
},
respondError(res)
);
});
Parse.Cloud.define("checkNameFree", function(req, res) {
var name = !req.params.displayName ? null : String(req.params.displayName);
if (!name || name === "") {
respondError(res, constants.t.INVALID_PARAMETER);
return;
}
checkNameValidity(name).then(
function(err) {
respond(res, constants.t.AVAILABILITY, {
available: !err,
reason: err ? new CodedError(err) : null
});
},
respondError(res)
);
});
Parse.Cloud.define("createGame", function(req, res) {
var user = req.user;
if (errorOnInvalidUser(user, res)) return;
var gamesTotal = new Query(Game)
.equalTo("creator", user)
.count()
var recentCutoff = new Date(Date.now() - constants.GAME_LIMIT_RECENT_TIMEOUT*1000);
var gamesRecently = new Query(Game)
.equalTo("creator", user)
.greaterThan("createdAt", recentCutoff)
.count()
Promise.when(
gamesTotal,
gamesRecently
).then(
function(total, recently) {
if (total >= constants.GAME_LIMIT_TOTAL) {
return Promise.reject(new CodedError(constants.t.GAME_QUOTA_EXCEEDED));
}
if (recently >= constants.GAME_LIMIT_RECENT) {
return Promise.reject(new CodedError(constants.t.GAME_QUOTA_EXCEEDED));
}
return createConfigFromRequest(req);
}
).then(
function(config) {
return createGameFromConfig(req.user, config);
}
).then(
function(gameInfo) {
respond(res, constants.t.GAME_CREATED, gameInfo);
},
respondError(res)
);
});
function getInviteLink(invite) {
return constants.INVITE_URL_PREFIX + invite.id;
}
function getInvite(player) {
var query = new Query(Invite);
return query
.equalTo("inviter", player)
.include("inviter")
.first()
.then(
function(invite) {
if (invite) return Promise.resolve(invite);
invite = new Invite();
invite.set("inviter", player);
return invite.save();
}
).then(
function(invite) {
if (!invite) return Promise.reject(new CodedError(constants.t.GAME_INVITE_ERROR));
return Promise.resolve(invite);
}
);
}
Parse.Cloud.define("getInvite", function(req, res) {
if (errorOnInvalidUser(req.user, res)) return;
var gameId = String(req.params.gameId);
var gameQuery = new Query(Game);
gameQuery.equalTo("objectId", gameId);
var query = new Query(Player);
query
.equalTo("user", req.user)
.matchesQuery("game", gameQuery)
.first()
.then(
function(player) {
if (!player) return Promise.reject(new CodedError(constants.t.PLAYER_NOT_FOUND));
return getInvite(player);
}
).then(
function(invite) {
respond(res, constants.t.GAME_INVITE, {
"invite": invite,
"link": getInviteLink(invite)
});
},
respondError(res)
);
});
function addPaging(query, req, config) {
var limit = Number(req.params.limit);
if (isNaN(limit)) limit = config.limit.default;
if (limit < config.limit.min) limit = config.limit.min;
if (limit > config.limit.max) limit = config.limit.max;
var skip = Number(req.params.skip);
if (isNaN(skip)) skip = 0;
if (config.sort) {
for (var si = 0; si < config.sort.length; si++) {
var s = config.sort[si];
switch (s.dir) {
case "ascending": query.addAscending(s.name); break;
case "descending": query.addDescending(s.name); break;
default: throw new Error(
"Sort direction should be either 'ascending' or 'descending', not '" + s.dir + "'"
);
}
}
}
query.limit(limit);
query.skip(skip);
return { limit: limit, skip: skip };
}
function respondWithGameList(req, res, user, configQuery, pagingConfig) {
var games;
var query = new Query(Game);
addPaging(query, req, pagingConfig);
query
.matchesQuery("config", configQuery)
.equalTo("state", GameState.Lobby)
.include("config")
.include("creator")
.include("currentPlayer")
.include("currentPlayer.user")
.find()
.then(
function(g) {
games = g;
var playerQuery = new Query(Player);
if (games) playerQuery.containedIn("game", games);
playerQuery
.include("user");
return playerQuery.find();
}
).then(
function(allPlayers) {
respond(res, constants.t.GAME_LIST, {
_context: {
players: allPlayers,
userId: user.id
},
"games": games
});
},
respondError(res)
);
}
Parse.Cloud.define("findGames", function(req, res) {
var user = req.user;
if (errorOnInvalidUser(user, res)) return;
var typeId = getTypeIdFromRequest(req);
var configQuery = new Query(Config);
configQuery
.equalTo("typeId", typeId)
.equalTo("isRandom", true);
respondWithGameList(req, res, user, configQuery, constants.FIND_GAME_PAGING);
});
Parse.Cloud.define("listInvites", function(req, res) {
var user = req.user;
if (errorOnInvalidUser(user, res)) return;
var typeId = getTypeIdFromRequest(req);
var configQuery = new Query(Config);
configQuery
.equalTo("typeId", typeId)
.equalTo("slots.userId", user.id);
respondWithGameList(req, res, user, configQuery, constants.LIST_INVITES_PAGING);
});
function createConfigFromRequest(req) {
var config = new Config();
var reqSlots = req.params.slots instanceof Array ? req.params.slots : null;
if (!reqSlots) reqSlots = constants.GAME_DEFAULT_CONFIG.slots;
if (reqSlots.length > constants.GAME_MAX_SLOTS) {
return Promise.reject(new CodedError(constants.t.GAME_INVALID_CONFIG, {
reason: "Too many slots."
}));
}
var slots = [];
var displayNames = [];
var creatorSlots = 0;
var noneSlots = 0;
for (var slotIndex in reqSlots) {
var reqSlot = reqSlots[slotIndex];
var slot = {};
slot.type = SlotType.parse(reqSlot.type);
if (slot.type === null) {
return Promise.reject(new CodedError(constants.t.GAME_INVALID_CONFIG, {
reason: "Missing or invalid slot type."
}));
}
switch (slot.type) {
case SlotType.Creator:
creatorSlots++;
break;
case SlotType.Invite:
if (typeof(reqSlot.displayName) != "string") {
return Promise.reject(new CodedError(constants.t.GAME_INVALID_CONFIG, {
reason: "Missing or invalid invite slot display name."
}));
}
displayNames.push({ slot: slot, name: reqSlot.displayName });
break;
case SlotType.AI:
slot.difficulty = AIDifficulty.parse(reqSlot.difficulty);
if (slot.difficulty === null) {
return Promise.reject(new CodedError(constants.t.GAME_INVALID_CONFIG, {
reason: "Missing or invalid ai slot difficulty."
}));
}
break;
case SlotType.None:
noneSlots++;
break;
}
slots.push(slot);
}
config.set("playerNum", slots.length - noneSlots);
if (creatorSlots != 1) {
return Promise.reject(new CodedError(constants.t.GAME_INVALID_CONFIG, {
reason: "Exactly one creator slot must be present."
}));
}
var turnMaxSec = req.params.turnMaxSec === undefined ?
undefined : Number(req.params.turnMaxSec);
if (turnMaxSec === undefined || isNaN(turnMaxSec)) {
turnMaxSec = constants.GAME_DEFAULT_CONFIG.turnMaxSec;
}
config.set("turnMaxSec", turnMaxSec);
var reqFameCards = req.params.fameCards;
var fameCards = {};
if (reqFameCards) {
var fameCardNames = constants.FAME_CARD_NAMES;
for (var i in fameCardNames) {
var fameCardName = fameCardNames[i];
var reqFameCard = Number(reqFameCards[fameCardName]);
if (!isNaN(reqFameCard)) {
fameCards[fameCardName] = reqFameCard;
}
}
}
config.set("fameCards", fameCards);
var typeId = getTypeIdFromRequest(req);
config.set("typeId", typeId);
var userQuery = new Query(Parse.User);
return userQuery
.containedIn("displayName", displayNames.map(function(dn) {
return dn.name;
}))
.find()
.then(
function(users) {
if (!users || users.length != displayNames.length) {
return Promise.reject(new CodedError(constants.t.GAME_INVALID_CONFIG, {
reason: "Invite slot user(s) duplicate or not found."
}));
}
var userIds = {};
userIds[req.user.id] = true;
users.forEach(function(user) {
// Duplicate check
if (userIds[user.id]) {
return;
}
userIds[user.id] = true;
// Display name to user ID map
var dn = displayNames.find(function(dn) {
return dn.name == user.get("displayName");
});
if (dn) dn.slot.userId = user.id;
}, this);
config.set("slots", slots);
var contactQuery = new Query(Contact);
return contactQuery
.containedIn("user", users)
.equalTo("contact", req.user)
.equalTo("blocked", true)
.include("user")
.find()
}
).then(
function(blockers) {
if (blockers && blockers.length > 0) {
return Promise.reject(new CodedError(constants.t.GAME_PLAYERS_UNAVAILABLE, {
names: blockers.map(
function(blocker) {
return blocker.get("user").get("displayName");
}
).join(", "),
blockers: blockers
}))
}
return config.save();
}
);