This repository has been archived by the owner on Oct 8, 2019. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 35
/
ladders.js
625 lines (577 loc) · 17.5 KB
/
ladders.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
/**
* Matchmaker
* Pokemon Showdown - http://pokemonshowdown.com/
*
* This keeps track of challenges to battle made between users, setting up
* matches between users looking for a battle, and starting new battles.
*
* @License MIT License
*/
'use strict';
/** @type {typeof LadderStoreT} */
const LadderStore = require(typeof Config === 'object' && Config.remoteladder ? './ladders-remote' : './ladders-local');
/** @type {number} */
const PERIODIC_MATCH_INTERVAL = 60 * 1000;
/**
* This represents a user's search for a battle under a format.
*/
class BattleReady {
/**
* @param {string} userid
* @param {string} formatid
* @param {string} team
* @param {number} [rating = 1000]
*/
constructor(userid, formatid, team, rating = 0) {
/** @type {string} */
this.userid = userid;
/** @type {string} */
this.formatid = formatid;
/** @type {string} */
this.team = team;
/** @type {number} */
this.rating = rating;
/** @type {number} */
this.time = Date.now();
}
}
/**
* formatid:userid:BattleReady
* @type {Map<string, Map<string, BattleReady>>}
*/
const searches = new Map();
class Challenge {
/**
* @param {BattleReady} ready
* @param {string} to
*/
constructor(ready, to) {
this.from = ready.userid;
this.to = to;
this.formatid = ready.formatid;
this.ready = ready;
}
}
/**
* formatid:userid:BattleReady
* @type {Map<string, Challenge[]>}
*/
const challenges = new Map();
/**
* This keeps track of searches for battles, creating a new battle for a newly
* added search if a valid match can be made, otherwise periodically
* attempting to make a match with looser restrictions until one can be made.
*/
class Ladder extends LadderStore {
/**
* @param {string} formatid
*/
constructor(formatid) {
super(formatid);
}
/**
* @param {Connection} connection
* @param {string?} team
* @return {Promise<BattleReady?>}
*/
async prepBattle(connection, team = null, isRated = false) {
// all validation for a battle goes through here
const user = connection.user;
const userid = user.userid;
if (team === null) team = user.team;
if (Rooms.global.lockdown && Rooms.global.lockdown !== 'pre') {
let message = `The server is restarting. Battles will be available again in a few minutes.`;
if (Rooms.global.lockdown === 'ddos') {
message = `The server is under attack. Battles cannot be started at this time.`;
}
connection.popup(message);
return null;
}
if (Punishments.isBattleBanned(user)) {
connection.popup(`You are barred from starting any new games until your battle ban expires.`);
return null;
}
let gameCount = user.games.size;
if (Monitor.countConcurrentBattle(gameCount, connection)) {
return null;
}
if (Monitor.countPrepBattle(connection.ip, connection)) {
return null;
}
try {
// @ts-ignore TypeScript bug: self-reference
this.formatid = Dex.validateFormat(this.formatid);
} catch (e) {
connection.popup(`Your selected format is invalid:\n\n- ${e.message}`);
return null;
}
let rating = 0, valResult;
if (isRated && !Ladders.disabled) {
let userid = user.userid;
[valResult, rating] = await Promise.all([
TeamValidatorAsync(this.formatid).validateTeam(team, user.locked || user.namelocked),
this.getRating(userid),
]);
if (userid !== user.userid) {
// User feedback for renames handled elsewhere.
return null;
}
if (!rating) rating = 1;
} else {
if (Ladders.disabled) {
connection.popup(`The ladder is temporarily disabled due to technical difficulties - you will not receive ladder rating for this game.`);
rating = 1;
}
valResult = await TeamValidatorAsync(this.formatid).validateTeam(team, user.locked || user.namelocked);
}
if (valResult.charAt(0) !== '1') {
connection.popup(
`Your team was rejected for the following reasons:\n\n` +
`- ` + valResult.slice(1).replace(/\n/g, `\n- `)
);
return null;
}
return new BattleReady(userid, this.formatid, valResult.slice(1), rating);
}
/**
* @param {User} user
*/
static cancelChallenging(user) {
const chall = Ladder.getChallenging(user.userid);
if (chall) {
Ladder.removeChallenge(chall);
return true;
}
return false;
}
/**
* @param {User} user
* @param {User} targetUsername
*/
static rejectChallenge(user, targetUsername) {
const targetUserid = toId(targetUsername);
const chall = Ladder.getChallenging(targetUserid);
if (chall && chall.to === user.userid) {
Ladder.removeChallenge(chall);
return true;
}
return false;
}
/**
* @param {string} username
*/
static clearChallenges(username) {
const userid = toId(username);
const userChalls = Ladders.challenges.get(userid);
if (userChalls) {
for (const chall of userChalls.slice()) {
let otherUserid;
if (chall.from === userid) {
otherUserid = chall.to;
} else {
otherUserid = chall.from;
}
Ladder.removeChallenge(chall, true);
const otherUser = Users(otherUserid);
if (otherUser) Ladder.updateChallenges(otherUser);
}
const user = Users(userid);
if (user) Ladder.updateChallenges(user);
return true;
}
return false;
}
/**
* @param {Connection} connection
* @param {User} targetUser
*/
async makeChallenge(connection, targetUser) {
const user = connection.user;
if (targetUser === user) {
connection.popup(`You can't battle yourself. The best you can do is open PS in Private Browsing (or another browser) and log into a different username, and battle that username.`);
return false;
}
if (Ladder.getChallenging(user.userid)) {
connection.popup(`You are already challenging someone. Cancel that challenge before challenging someone else.`);
return false;
}
if (targetUser.blockChallenges && !user.can('bypassblocks', targetUser)) {
connection.popup(`The user '${targetUser.name}' is not accepting challenges right now.`);
return false;
}
if (Date.now() < user.lastChallenge + 10000) {
// 10 seconds ago, probable misclick
connection.popup(`You challenged less than 10 seconds after your last challenge! It's cancelled in case it's a misclick.`);
return false;
}
const ready = await this.prepBattle(connection);
if (!ready) return false;
Ladder.addChallenge(new Challenge(ready, targetUser.userid));
user.lastChallenge = Date.now();
return true;
}
/**
* @param {Connection} connection
* @param {User} targetUser
*/
static async acceptChallenge(connection, targetUser) {
const chall = Ladder.getChallenging(targetUser.userid);
if (!chall || chall.to !== connection.user.userid) {
connection.popup(`${targetUser.userid} is not challenging you. Maybe they cancelled before you accepted?`);
return false;
}
const ladder = Ladders(chall.formatid);
const ready = await ladder.prepBattle(connection);
if (!ready) return false;
if (Ladder.removeChallenge(chall)) {
Ladders.match(chall.ready, ready);
}
return true;
}
/**
* @param {string} userid
*/
static getChallenging(userid) {
const userChalls = Ladders.challenges.get(userid);
if (userChalls) {
for (const chall of userChalls) {
if (chall.from === userid) return chall;
}
}
return null;
}
/**
* @param {Challenge} challenge
*/
static addChallenge(challenge, skipUpdate = false) {
let challs1 = Ladders.challenges.get(challenge.from);
if (!challs1) Ladders.challenges.set(challenge.from, challs1 = []);
let challs2 = Ladders.challenges.get(challenge.to);
if (!challs2) Ladders.challenges.set(challenge.to, challs2 = []);
challs1.push(challenge);
challs2.push(challenge);
if (!skipUpdate) {
const fromUser = Users(challenge.from);
if (fromUser) Ladder.updateChallenges(fromUser);
const toUser = Users(challenge.to);
if (toUser) Ladder.updateChallenges(toUser);
}
}
/**
* @param {Challenge} challenge
*/
static removeChallenge(challenge, skipUpdate = false) {
const fromChalls = /** @type {Challenge[]} */ (Ladders.challenges.get(challenge.from));
// the challenge may have been cancelled
if (!fromChalls) return false;
const fromIndex = fromChalls.indexOf(challenge);
if (fromIndex < 0) return false;
fromChalls.splice(fromIndex, 1);
if (!fromChalls.length) Ladders.challenges.delete(challenge.from);
const toChalls = /** @type {Challenge[]} */ (Ladders.challenges.get(challenge.to));
toChalls.splice(toChalls.indexOf(challenge), 1);
if (!toChalls.length) Ladders.challenges.delete(challenge.to);
if (!skipUpdate) {
const fromUser = Users(challenge.from);
if (fromUser) Ladder.updateChallenges(fromUser);
const toUser = Users(challenge.to);
if (toUser) Ladder.updateChallenges(toUser);
}
return true;
}
/**
* @param {User} user
* @param {Connection?} connection
*/
static updateChallenges(user, connection = null) {
if (!user.connected) return;
let challengeTo = null;
let challengesFrom = {};
const userChalls = Ladders.challenges.get(user.userid);
if (userChalls) {
for (const chall of userChalls) {
if (chall.from === user.userid) {
challengeTo = {
to: chall.to,
format: chall.formatid,
};
} else {
challengesFrom[chall.from] = chall.formatid;
}
}
}
(connection || user).send(`|updatechallenges|` + JSON.stringify({
challengesFrom: challengesFrom,
challengeTo: challengeTo,
}));
}
/**
* @param {User} user
* @return {boolean}
*/
cancelSearch(user) {
const formatid = toId(this.formatid);
const formatTable = Ladders.searches.get(formatid);
if (!formatTable) return false;
if (!formatTable.has(user.userid)) return false;
formatTable.delete(user.userid);
Ladder.updateSearch(user);
return true;
}
/**
* @param {User} user
* @return {number} cancel count
*/
static cancelSearches(user) {
let cancelCount = 0;
for (let formatTable of Ladders.searches.values()) {
const search = formatTable.get(user.userid);
if (!search) continue;
formatTable.delete(user.userid);
cancelCount++;
}
Ladder.updateSearch(user);
return cancelCount;
}
/**
* @param {BattleReady} search
*/
getSearcher(search) {
const formatid = toId(this.formatid);
const user = Users.get(search.userid);
if (!user || !user.connected || user.userid !== search.userid) {
const formatTable = Ladders.searches.get(formatid);
if (formatTable) formatTable.delete(search.userid);
if (user && user.connected) {
user.popup(`You changed your name and are no longer looking for a battle in ${formatid}`);
Ladder.updateSearch(user);
}
return null;
}
return user;
}
/**
* @param {User} user
*/
static getSearches(user) {
let userSearches = [];
for (const [formatid, formatTable] of Ladders.searches) {
if (formatTable.has(user.userid)) userSearches.push(formatid);
}
return userSearches;
}
/**
* @param {User} user
* @param {Connection?} connection
*/
static updateSearch(user, connection = null) {
let games = /** @type {any} */ ({});
let atLeastOne = false;
for (const roomid of user.games) {
const room = Rooms(roomid);
if (!room) {
Monitor.warn(`while searching, room ${roomid} expired for user ${user.userid} in rooms ${[...user.inRooms]} and games ${[...user.games]}`);
user.games.delete(roomid);
return;
}
const game = room.game;
if (!game) {
Monitor.warn(`while searching, room ${roomid} has no game for user ${user.userid} in rooms ${[...user.inRooms]} and games ${[...user.games]}`);
user.games.delete(roomid);
return;
}
games[roomid] = game.title + (game.allowRenames ? '' : '*');
atLeastOne = true;
}
if (!atLeastOne) games = null;
let searching = Ladders.getSearches(user);
(connection || user).send(`|updatesearch|` + JSON.stringify({
searching: searching,
games: games,
}));
}
/**
* @param {User} user
*/
hasSearch(user) {
const formatid = toId(this.formatid);
const formatTable = Ladders.searches.get(formatid);
if (!formatTable) return false;
return formatTable.has(user.userid);
}
/**
* Validates a user's team and fetches their rating for a given format
* before creating a search for a battle.
* @param {User} user
* @param {Connection} connection
* @return {Promise<void>}
*/
async searchBattle(user, connection) {
if (!user.connected) return;
const format = Dex.getFormat(this.formatid);
if (!format.searchShow) {
connection.popup(`Error: Your format ${format.id} is not ladderable.`);
return;
}
let oldUserid = user.userid;
const search = await this.prepBattle(connection, null, format.rated !== false);
if (oldUserid !== user.userid) return;
if (!search) return;
this.addSearch(search, user);
}
/**
* Verifies whether or not a match made between two users is valid. Returns
* @param {BattleReady} search1
* @param {BattleReady} search2
* @param {User=} user1
* @param {User=} user2
* @return {boolean}
*/
matchmakingOK(search1, search2, user1, user2) {
const formatid = toId(this.formatid);
if (!user1 || !user2) {
// This should never happen.
require('./lib/crashlogger')(new Error(`Matched user ${user1 ? search2.userid : search1.userid} not found`), "The main process");
return false;
}
// users must be different
if (user1 === user2) return false;
// users must have different IPs
if (user1.latestIp === user2.latestIp) return false;
// users must not have been matched immediately previously
if (user1.lastMatch === user2.userid || user2.lastMatch === user1.userid) return false;
// search must be within range
let searchRange = 100;
let elapsed = Date.now() - Math.min(search1.time, search2.time);
if (formatid === 'gen7ou' || formatid === 'gen7oucurrent' ||
formatid === 'gen7oususpecttest' || formatid === 'gen7randombattle') {
searchRange = 50;
}
searchRange += elapsed / 300; // +1 every .3 seconds
if (searchRange > 300) searchRange = 300 + (searchRange - 300) / 10; // +1 every 3 sec after 300
if (searchRange > 600) searchRange = 600;
if (Math.abs(search1.rating - search2.rating) > searchRange) return false;
user1.lastMatch = user2.userid;
user2.lastMatch = user1.userid;
return true;
}
/**
* Starts a search for a battle for a user under the given format.
* @param {BattleReady} newSearch
* @param {User} user
*/
addSearch(newSearch, user) {
const formatid = newSearch.formatid;
let formatTable = Ladders.searches.get(formatid);
if (!formatTable) {
formatTable = new Map();
Ladders.searches.set(formatid, formatTable);
}
if (formatTable.has(user.userid)) {
user.popup(`Couldn't search: You are already searching for a ${formatid} battle.`);
return;
}
// In order from longest waiting to shortest waiting
for (let search of formatTable.values()) {
const searcher = this.getSearcher(search);
if (!searcher) continue;
const matched = this.matchmakingOK(search, newSearch, searcher, user);
if (matched) {
formatTable.delete(search.userid);
Ladder.match(search, newSearch);
return;
}
}
formatTable.set(newSearch.userid, newSearch);
Ladder.updateSearch(user);
}
/**
* Creates a match for a new battle for each format in this.searches if a
* valid match can be made. This is run periodically depending on
* PERIODIC_MATCH_INTERVAL.
*/
static periodicMatch() {
// In order from longest waiting to shortest waiting
for (const [formatid, formatTable] of Ladders.searches) {
const matchmaker = Ladders(formatid);
let longest = /** @type {[BattleReady, User]?} */ (null);
for (let search of formatTable.values()) {
if (!longest) {
const longestSearcher = matchmaker.getSearcher(search);
if (!longestSearcher) continue;
longest = [search, longestSearcher];
continue;
}
let searcher = matchmaker.getSearcher(search);
if (!searcher) continue;
let [longestSearch, longestSearcher] = longest;
let matched = matchmaker.matchmakingOK(search, longestSearch, searcher, longestSearcher);
if (matched) {
formatTable.delete(search.userid);
formatTable.delete(longestSearch.userid);
Ladder.match(longestSearch, search);
return;
}
}
}
}
/**
* @param {BattleReady} ready1
* @param {BattleReady} ready2
*/
static match(ready1, ready2) {
if (ready1.formatid !== ready2.formatid) throw new Error(`Format IDs don't match`);
const user1 = Users(ready1.userid);
const user2 = Users(ready2.userid);
if (!user1) {
if (!user2) return false;
user2.popup(`Sorry, your opponent ${ready1.userid} went offline before your battle could start.`);
return false;
}
if (!user2) {
user1.popup(`Sorry, your opponent ${ready2.userid} went offline before your battle could start.`);
return false;
}
Rooms.createBattle(ready1.formatid, {
p1: user1,
p1team: ready1.team,
p2: user2,
p2team: ready2.team,
rated: Math.min(ready1.rating, ready2.rating),
});
}
}
/**
* @param {string} formatid
*/
function getLadder(formatid) {
return new Ladder(formatid);
}
/** @type {?NodeJS.Timer} */
let periodicMatchInterval = setInterval(
() => Ladder.periodicMatch(),
PERIODIC_MATCH_INTERVAL
);
const Ladders = Object.assign(getLadder, {
BattleReady,
LadderStore,
Ladder,
cancelSearches: Ladder.cancelSearches,
updateSearch: Ladder.updateSearch,
rejectChallenge: Ladder.rejectChallenge,
acceptChallenge: Ladder.acceptChallenge,
cancelChallenging: Ladder.cancelChallenging,
clearChallenges: Ladder.clearChallenges,
updateChallenges: Ladder.updateChallenges,
visualizeAll: Ladder.visualizeAll,
getSearches: Ladder.getSearches,
match: Ladder.match,
searches,
challenges,
periodicMatchInterval,
// tells the client to ask the server for format information
formatsListPrefix: LadderStore.formatsListPrefix,
/** @type {true | false | 'db'} */
disabled: false,
});
module.exports = Ladders;