forked from smogon/pokemon-showdown
-
Notifications
You must be signed in to change notification settings - Fork 1
/
rooms.ts
2297 lines (2087 loc) · 71.3 KB
/
rooms.ts
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
/**
* Rooms
* Pokemon Showdown - http://pokemonshowdown.com/
*
* Every chat room and battle is a room, and what they do is done in
* rooms.ts. There's also a global room which every user is in, and
* handles miscellaneous things like welcoming the user.
*
* `Rooms.rooms` is the global table of all rooms, a `Map` of `RoomID:Room`.
* Rooms should normally be accessed with `Rooms.get(roomid)`.
*
* All rooms extend `BasicRoom`, whose important properties like `.users`
* and `.game` are documented near the the top of its class definition.
*
* @license MIT
*/
const ALPHABET = '0123456789abcdefghijklmnopqrstuvwxyz'.split('');
const TIMEOUT_EMPTY_DEALLOCATE = 10 * 60 * 1000;
const TIMEOUT_INACTIVE_DEALLOCATE = 40 * 60 * 1000;
const REPORT_USER_STATS_INTERVAL = 10 * 60 * 1000;
const MAX_CHATROOM_ID_LENGTH = 225;
const CRASH_REPORT_THROTTLE = 60 * 60 * 1000;
const LAST_BATTLE_WRITE_THROTTLE = 10;
const RETRY_AFTER_LOGIN = null;
import {FS, Utils, Streams} from '../lib';
import {RoomSection, RoomSections} from './chat-commands/room-settings';
import {QueuedHunt} from './chat-plugins/scavengers';
import {ScavengerGameTemplate} from './chat-plugins/scavenger-games';
import {RepeatedPhrase} from './chat-plugins/repeats';
import {
PM as RoomBattlePM, RoomBattle, RoomBattlePlayer, RoomBattleTimer, type RoomBattleOptions,
} from "./room-battle";
import {BestOfGame} from './room-battle-bestof';
import {RoomGame, SimpleRoomGame, RoomGamePlayer} from './room-game';
import {MinorActivity, MinorActivityData} from './room-minor-activity';
import {Roomlogs, type Roomlog} from './roomlogs';
import {RoomAuth} from './user-groups';
import {PartialModlogEntry, mainModlog} from './modlog';
import {Replays} from './replays';
/*********************************************************
* the Room object.
*********************************************************/
interface MuteEntry {
userid: ID;
time: number;
guestNum: number;
autoconfirmed: string;
}
interface ChatRoomTable {
title: string;
desc: string;
userCount: number;
section?: string;
subRooms?: string[];
spotlight?: string;
privacy: RoomSettings['isPrivate'];
}
interface ShowRequest {
name: string;
link: string;
comment: string;
dimensions?: [number, number, boolean];
}
interface BattleRoomTable {
p1?: string;
p2?: string;
minElo?: 'tour' | number;
}
interface UserTable {
[userid: string]: User;
}
export interface RoomSettings {
title: string;
auth: {[userid: string]: GroupSymbol};
creationTime: number;
section?: RoomSection;
readonly autojoin?: boolean;
aliases?: string[];
banwords?: string[];
isPrivate?: PrivacySetting;
modjoin?: AuthLevel | true | null;
modchat?: AuthLevel | null;
staffRoom?: boolean;
language?: ID | false;
slowchat?: number | false;
events?: {[k: string]: RoomEvent | RoomEventAlias | RoomEventCategory};
filterStretching?: boolean;
filterEmojis?: boolean;
filterCaps?: boolean;
filterLinks?: boolean;
jeopardyDisabled?: boolean;
mafiaDisabled?: boolean;
unoDisabled?: boolean;
hangmanDisabled?: boolean;
auctionDisabled?: boolean;
gameNumber?: number;
highTraffic?: boolean;
spotlight?: string;
parentid?: string | null;
desc?: string | null;
introMessage?: string | null;
staffMessage?: string | null;
rulesLink?: string | null;
dataCommandTierDisplay?: 'tiers' | 'doubles tiers' | 'National Dex tiers' | 'numbers';
requestShowEnabled?: boolean | null;
permissions?: {[k: string]: GroupSymbol};
minorActivity?: PollData | AnnouncementData;
minorActivityQueue?: MinorActivityData[];
repeats?: RepeatedPhrase[];
topics?: string[];
autoModchat?: {
rank: GroupSymbol,
time: number,
// stores previous modchat setting. if true, modchat was fully off
active: boolean | AuthLevel,
};
tournaments?: TournamentRoomSettings;
defaultFormat?: string;
scavSettings?: AnyObject;
scavQueue?: QueuedHunt[];
// should not ever be saved because they're inapplicable to persistent rooms
/** This includes groupchats, battles, and help-ticket rooms. */
isPersonal?: boolean;
isHelp?: boolean;
noLogTimes?: boolean;
noAutoTruncate?: boolean;
isMultichannel?: boolean;
}
export type MessageHandler = (room: BasicRoom, message: string) => void;
export type Room = GameRoom | ChatRoom;
export type PrivacySetting = boolean | 'hidden' | 'voice' | 'unlisted';
import type {AnnouncementData} from './chat-plugins/announcements';
import type {PollData} from './chat-plugins/poll';
import type {AutoResponder} from './chat-plugins/responder';
import type {RoomEvent, RoomEventAlias, RoomEventCategory} from './chat-plugins/room-events';
import type {Tournament, TournamentRoomSettings} from './tournaments/index';
export abstract class BasicRoom {
/** to rename use room.rename */
readonly roomid: RoomID;
title: string;
readonly type: 'chat' | 'battle';
readonly users: UserTable;
/**
* Scrollback log. This is the log that's sent to users when
* joining the room. Should roughly match what's on everyone's
* screen.
*/
readonly log: Roomlog;
/**
* The room's current RoomGame, if it exists. Each room can have 0 to 2
* `RoomGame`s, and `this.game.room === this`.
* Rooms may also have an additional game in `this.subGame`.
* However, `subGame`s do not update `user.game`.
*/
game: RoomGame | null;
subGame: RoomGame | null;
/**
* The room's current battle. Battles are a type of RoomGame, so in battle
* rooms (which can only be `GameRoom`s), `this.battle === this.game`.
* In all other rooms, `this.battle` is `null`.
*/
battle: RoomBattle | null;
/**
* The room's current best-of set. Best-of sets are a type of RoomGame, so in best-of set
* rooms (which can only be `GameRoom`s), `this.bestof === this.game`.
* In all other rooms, `this.bestof` is `null`.
*/
bestOf: BestOfGame | null;
/**
* The game room's current tournament. If the room is a battle room whose
* battle is part of a tournament, `this.tour === this.parent.game`.
* In all other rooms, `this.tour` is `null`.
*/
tour: Tournament | null;
auth: RoomAuth;
/** use `setParent` to set this */
readonly parent: Room | null;
/** use `subroom.setParent` to set this, or `clearSubRooms` to clear it */
readonly subRooms: ReadonlyMap<string, Room> | null;
readonly muteQueue: MuteEntry[];
userCount: number;
active: boolean;
muteTimer: NodeJS.Timer | null;
modchatTimer: NodeJS.Timer | null;
lastUpdate: number;
lastBroadcast: string;
lastBroadcastTime: number;
settings: RoomSettings;
/** If true, this room's settings will be saved in config/chatrooms.json, allowing it to stay past restarts. */
persist: boolean;
scavgame: ScavengerGameTemplate | null;
scavLeaderboard: AnyObject;
responder?: AutoResponder | null;
privacySetter?: Set<ID> | null;
hideReplay: boolean;
reportJoins: boolean;
batchJoins: number;
reportJoinsInterval: NodeJS.Timer | null;
minorActivity: MinorActivity | null;
minorActivityQueue: MinorActivityData[] | null;
banwordRegex: RegExp | true | null;
logUserStatsInterval: NodeJS.Timer | null;
expireTimer: NodeJS.Timer | null;
userList: string;
pendingApprovals: Map<string, ShowRequest> | null;
messagesSent: number;
/**
* These handlers will be invoked every n messages.
* handler:number-of-messages map
*/
nthMessageHandlers: Map<MessageHandler, number>;
constructor(roomid: RoomID, title?: string, options: Partial<RoomSettings> = {}) {
this.users = Object.create(null);
this.type = 'chat';
this.muteQueue = [];
this.battle = null;
this.bestOf = null;
this.game = null;
this.subGame = null;
this.tour = null;
this.roomid = roomid;
this.title = (title || roomid);
this.parent = null;
this.userCount = 0;
this.game = null;
this.active = false;
this.muteTimer = null;
this.lastUpdate = 0;
this.lastBroadcast = '';
this.lastBroadcastTime = 0;
// room settings
this.settings = {
title: this.title,
auth: Object.create(null),
creationTime: Date.now(),
};
this.persist = false;
this.hideReplay = false;
this.subRooms = null;
this.scavgame = null;
this.scavLeaderboard = {};
this.auth = new RoomAuth(this);
this.reportJoins = true;
this.batchJoins = 0;
this.reportJoinsInterval = null;
options.title = this.title;
if (options.isHelp) options.noAutoTruncate = true;
this.reportJoins = !!(Config.reportjoins || options.isPersonal);
this.batchJoins = options.isPersonal ? 0 : Config.reportjoinsperiod || 0;
if (!options.auth) options.auth = {};
this.log = Roomlogs.create(this, options);
this.banwordRegex = null;
this.settings = options as RoomSettings;
if (!this.settings.creationTime) this.settings.creationTime = Date.now();
this.auth.load();
if (!options.isPersonal) this.persist = true;
this.minorActivity = null;
this.minorActivityQueue = null;
if (options.parentid) {
this.setParent(Rooms.get(options.parentid) || null);
}
this.subRooms = null;
this.active = false;
this.muteTimer = null;
this.modchatTimer = null;
this.logUserStatsInterval = null;
this.expireTimer = null;
if (Config.logchat) {
this.roomlog('NEW CHATROOM: ' + this.roomid);
if (Config.loguserstats) {
this.logUserStatsInterval = setInterval(() => this.logUserStats(), Config.loguserstats);
}
}
this.userList = '';
if (this.batchJoins) {
this.userList = this.getUserList();
}
this.pendingApprovals = null;
this.messagesSent = 0;
this.nthMessageHandlers = new Map();
this.tour = null;
this.game = null;
this.battle = null;
this.validateTitle(this.title, this.roomid);
}
toString() {
return this.roomid;
}
/**
* Send a room message to all users in the room, without recording it
* in the scrollback log.
*/
send(message: string) {
if (this.roomid !== 'lobby') message = '>' + this.roomid + '\n' + message;
if (this.userCount) Sockets.roomBroadcast(this.roomid, message);
}
sendMods(data: string) {
this.sendRankedUsers(data, '*');
}
sendRankedUsers(data: string, minRank: GroupSymbol = '+') {
if (this.settings.staffRoom) {
if (!this.log) throw new Error(`Staff room ${this.roomid} has no log`);
this.log.add(data);
return;
}
for (const i in this.users) {
const user = this.users[i];
// hardcoded for performance reasons (this is an inner loop)
if (user.isStaff || this.auth.atLeast(user, minRank)) {
user.sendTo(this, data);
}
}
}
/**
* Send a room message to a single user.
*/
sendUser(user: Connection | User, message: string) {
user.sendTo(this, message);
}
/**
* Add a room message to the room log, so it shows up in the room
* for everyone, and appears in the scrollback for new users who
* join.
*/
add(message: string) {
this.log.add(message);
return this;
}
roomlog(message: string) {
this.log.roomlog(message);
return this;
}
/**
* Writes an entry to the modlog for that room, and the global modlog if entry.isGlobal is true.
*/
modlog(entry: PartialModlogEntry) {
const override = this.tour ? `${this.roomid} tournament: ${this.tour.roomid}` : undefined;
this.log.modlog(entry, override);
return this;
}
uhtmlchange(name: string, message: string) {
this.log.uhtmlchange(name, message);
}
attributedUhtmlchange(user: User, name: string, message: string) {
this.log.attributedUhtmlchange(user, name, message);
}
hideText(userids: ID[], lineCount = 0, hideRevealButton?: boolean) {
const cleared = this.log.clearText(userids, lineCount);
for (const userid of cleared) {
this.send(`|hidelines|${hideRevealButton ? 'delete' : 'hide'}|${userid}|${lineCount}`);
}
this.update();
}
/**
* Inserts (sanitized) HTML into the room log.
*/
addRaw(message: string) {
return this.add('|raw|' + message);
}
/**
* Inserts some text into the room log, attributed to user. The
* attribution will not appear, and is used solely as a hint not to
* highlight the user.
*/
addByUser(user: User, text: string): this {
return this.add('|c|' + user.getIdentity(this) + '|/log ' + text);
}
/**
* Like addByUser, but without logging
*/
sendByUser(user: User | null, text: string) {
this.send('|c|' + (user ? user.getIdentity(this) : '~') + '|/log ' + text);
}
/**
* Like addByUser, but sends to mods only.
*/
sendModsByUser(user: User, text: string) {
this.sendMods('|c|' + user.getIdentity(this) + '|/log ' + text);
}
update() {
if (!this.log.broadcastBuffer.length) return;
if (this.reportJoinsInterval) {
clearInterval(this.reportJoinsInterval);
this.reportJoinsInterval = null;
this.userList = this.getUserList();
}
this.send(this.log.broadcastBuffer.join('\n'));
this.log.broadcastBuffer = [];
this.log.truncate();
this.pokeExpireTimer();
}
getUserList() {
let buffer = '';
let counter = 0;
for (const i in this.users) {
if (!this.users[i].named) {
continue;
}
counter++;
buffer += ',' + this.users[i].getIdentityWithStatus(this);
}
const msg = `|users|${counter}${buffer}`;
return msg;
}
nextGameNumber() {
const gameNumber = (this.settings.gameNumber || 0) + 1;
this.settings.gameNumber = gameNumber;
this.saveSettings();
return gameNumber;
}
// mute handling
runMuteTimer(forceReschedule = false) {
if (forceReschedule && this.muteTimer) {
clearTimeout(this.muteTimer);
this.muteTimer = null;
}
if (this.muteTimer || this.muteQueue.length === 0) return;
const timeUntilExpire = this.muteQueue[0].time - Date.now();
if (timeUntilExpire <= 1000) { // one second of leeway
this.unmute(this.muteQueue[0].userid, "Your mute in '" + this.title + "' has expired.");
// runMuteTimer() is called again in unmute() so this function instance should be closed
return;
}
this.muteTimer = setTimeout(() => {
this.muteTimer = null;
this.runMuteTimer(true);
}, timeUntilExpire);
}
isMuted(user: User): ID | undefined {
if (!user) return;
if (this.muteQueue) {
for (const entry of this.muteQueue) {
if (user.id === entry.userid ||
user.guestNum === entry.guestNum ||
(user.autoconfirmed && user.autoconfirmed === entry.autoconfirmed)) {
if (entry.time - Date.now() < 0) {
this.unmute(user.id);
return;
} else {
return entry.userid;
}
}
}
}
if (this.parent) return this.parent.isMuted(user);
}
getMuteTime(user: User): number | undefined {
const userid = this.isMuted(user);
if (!userid) return;
for (const entry of this.muteQueue) {
if (userid === entry.userid) {
return entry.time - Date.now();
}
}
if (this.parent) return this.parent.getMuteTime(user);
}
// I think putting the `new` before the signature is confusing the linter
// eslint-disable-next-line @typescript-eslint/type-annotation-spacing
getGame<T extends RoomGame>(constructor: new (...args: any[]) => T, subGame = false): T | null {
// TODO: switch to `static readonly gameid` when all game files are TypeScripted
if (subGame && this.subGame && this.subGame.constructor.name === constructor.name) return this.subGame as T;
if (this.game && this.game.constructor.name === constructor.name) return this.game as T;
return null;
}
getMinorActivity<T extends MinorActivity>(constructor: new (...args: any[]) => T): T | null {
if (this.minorActivity?.constructor.name === constructor.name) return this.minorActivity as T;
return null;
}
getMinorActivityQueue(settings = false): MinorActivityData[] | null {
const usedQueue = settings ? this.settings.minorActivityQueue : this.minorActivityQueue;
if (!usedQueue?.length) return null;
return usedQueue;
}
queueMinorActivity(activity: MinorActivityData): void {
if (!this.minorActivityQueue) this.minorActivityQueue = [];
this.minorActivityQueue.push(activity);
this.settings.minorActivityQueue = this.minorActivityQueue;
}
clearMinorActivityQueue(slot?: number, depth = 1) {
if (!this.minorActivityQueue) return;
if (slot === undefined) {
this.minorActivityQueue = null;
delete this.settings.minorActivityQueue;
this.saveSettings();
} else {
this.minorActivityQueue.splice(slot, depth);
this.settings.minorActivityQueue = this.minorActivityQueue;
this.saveSettings();
if (!this.minorActivityQueue.length) this.clearMinorActivityQueue();
}
}
setMinorActivity(activity: MinorActivity | null, noDisplay = false): void {
this.minorActivity?.endTimer();
this.minorActivity = activity;
if (this.minorActivity) {
this.minorActivity.save();
if (!noDisplay) this.minorActivity.display();
} else {
delete this.settings.minorActivity;
this.saveSettings();
}
}
saveSettings() {
if (!this.persist) return;
if (!Rooms.global) return; // during initialization
Rooms.global.writeChatRoomData();
}
checkModjoin(user: User) {
if (user.id in this.users) return true;
if (!this.settings.modjoin) return true;
// users with a room rank can always join
if (this.auth.has(user.id)) return true;
const modjoinSetting = this.settings.modjoin !== true ? this.settings.modjoin : this.settings.modchat;
if (!modjoinSetting) return true;
if (!Users.Auth.isAuthLevel(modjoinSetting)) {
Monitor.error(`Invalid modjoin setting in ${this.roomid}: ${modjoinSetting}`);
}
return (
this.auth.atLeast(user, modjoinSetting) || Users.globalAuth.atLeast(user, modjoinSetting)
);
}
mute(user: User, setTime?: number) {
const userid = user.id;
if (!setTime) setTime = 7 * 60000; // default time: 7 minutes
if (setTime > 90 * 60000) setTime = 90 * 60000; // limit 90 minutes
// If the user is already muted, the existing queue position for them should be removed
if (this.isMuted(user)) this.unmute(userid);
// Place the user in a queue for the unmute timer
for (let i = 0; i <= this.muteQueue.length; i++) {
const time = Date.now() + setTime;
if (i === this.muteQueue.length || time < this.muteQueue[i].time) {
const entry = {
userid,
time,
guestNum: user.guestNum,
autoconfirmed: user.autoconfirmed,
};
this.muteQueue.splice(i, 0, entry);
// The timer needs to be switched to the new entry if it is to be unmuted
// before the entry the timer is currently running for
if (i === 0 && this.muteTimer) {
clearTimeout(this.muteTimer);
this.muteTimer = null;
}
break;
}
}
this.runMuteTimer();
user.updateIdentity();
if (!(this.settings.isPrivate === true || this.settings.isPersonal)) {
void Punishments.monitorRoomPunishments(user);
}
return userid;
}
unmute(userid: string, notifyText?: string) {
let successUserid = '';
const user = Users.get(userid);
let autoconfirmed = '';
if (user) {
userid = user.id;
autoconfirmed = user.autoconfirmed;
}
for (const [i, entry] of this.muteQueue.entries()) {
if (entry.userid === userid ||
(user && entry.guestNum === user.guestNum) ||
(autoconfirmed && entry.autoconfirmed === autoconfirmed)) {
if (i === 0) {
this.muteQueue.splice(0, 1);
this.runMuteTimer(true);
} else {
this.muteQueue.splice(i, 1);
}
successUserid = entry.userid;
break;
}
}
if (user && successUserid && userid in this.users) {
user.updateIdentity();
if (notifyText) user.popup(notifyText);
}
return successUserid;
}
logUserStats() {
let total = 0;
let guests = 0;
const groups: {[k: string]: number} = {};
for (const group of Config.groupsranking) {
groups[group] = 0;
}
for (const i in this.users) {
const user = this.users[i];
++total;
if (!user.named) {
++guests;
}
++groups[this.auth.get(user.id)];
}
let entry = '|userstats|total:' + total + '|guests:' + guests;
for (const i in groups) {
entry += '|' + i + ':' + groups[i];
}
this.roomlog(entry);
}
pokeExpireTimer() {
if (this.expireTimer) clearTimeout(this.expireTimer);
if (this.settings.isPersonal) {
this.expireTimer = setTimeout(() => this.expire(), TIMEOUT_INACTIVE_DEALLOCATE);
} else {
this.expireTimer = null;
}
}
expire() {
this.send('|expire|');
this.destroy();
}
reportJoin(type: 'j' | 'l' | 'n', entry: string, user: User) {
const canTalk = this.auth.atLeast(user, this.settings.modchat ?? 'unlocked') && !this.isMuted(user);
if (this.reportJoins && (canTalk || this.auth.has(user.id))) {
this.add(`|${type}|${entry}`).update();
return;
}
let ucType = '';
switch (type) {
case 'j': ucType = 'J'; break;
case 'l': ucType = 'L'; break;
case 'n': ucType = 'N'; break;
}
entry = `|${ucType}|${entry}`;
if (this.batchJoins) {
this.log.broadcastBuffer.push(entry);
if (!this.reportJoinsInterval) {
this.reportJoinsInterval = setTimeout(
() => this.update(), this.batchJoins
);
}
} else {
this.send(entry);
}
this.roomlog(entry);
}
getIntroMessage(user: User) {
let message = Utils.html`\n|raw|<div class="infobox"> You joined ${this.title}`;
if (this.settings.modchat) {
message += ` [${this.settings.modchat} or higher to talk]`;
}
if (this.settings.modjoin) {
const modjoin = this.settings.modjoin === true ? this.settings.modchat : this.settings.modjoin;
message += ` [${modjoin} or higher to join]`;
}
if (this.settings.slowchat) {
message += ` [Slowchat ${this.settings.slowchat}s]`;
}
message += `</div>`;
if (this.settings.introMessage) {
message += `\n|raw|<div class="infobox infobox-roomintro"><div ${(this.settings.section !== 'official' ? 'class="infobox-limited"' : '')}>` +
this.settings.introMessage.replace(/\n/g, '') +
`</div></div>`;
}
const staffIntro = this.getStaffIntroMessage(user);
if (staffIntro) message += `\n${staffIntro}`;
return message;
}
getStaffIntroMessage(user: User) {
if (!user.can('mute', null, this)) return ``;
const messages = [];
if (this.settings.staffMessage) {
messages.push(`|raw|<div class="infobox">(Staff intro:)<br /><div>` +
this.settings.staffMessage.replace(/\n/g, '') +
`</div>`);
}
if (this.pendingApprovals?.size) {
let message = `|raw|<div class="infobox">`;
message += `<details open><summary>(Pending media requests: ${this.pendingApprovals.size})</summary>`;
for (const [userid, entry] of this.pendingApprovals) {
message += `<div class="infobox">`;
message += `<strong>Requester ID:</strong> ${userid}<br />`;
if (entry.dimensions) {
const [width, height, resized] = entry.dimensions;
message += `<strong>Link:</strong><br /> <img src="${entry.link}" width="${width}" height="${height}"><br />`;
if (resized) message += `(Resized)<br />`;
} else {
message += `<strong>Link:</strong><br /> <a href="${entry.link}"">Link</a><br />`;
}
message += `<strong>Comment:</strong> ${entry.comment ? entry.comment : 'None.'}<br />`;
message += `<button class="button" name="send" value="/approveshow ${userid}">Approve</button>` +
`<button class="button" name="send" value="/denyshow ${userid}">Deny</button></div>`;
message += `<hr />`;
}
message += `</details></div>`;
messages.push(message);
}
if (!this.settings.isPrivate && !this.settings.isPersonal &&
this.settings.modchat && this.settings.modchat !== 'autoconfirmed') {
messages.push(`|raw|<div class="broadcast-red">Modchat currently set to ${this.settings.modchat}</div>`);
}
return messages.join('\n');
}
getSubRooms(includeSecret = false) {
if (!this.subRooms) return [];
return [...this.subRooms.values()].filter(
room => includeSecret ? true : !room.settings.isPrivate && !room.settings.isPersonal
);
}
validateTitle(newTitle: string, newID?: string, oldID?: string) {
if (!newID) newID = toID(newTitle);
// `,` is a delimiter used by a lot of /commands
// `|` and `[` are delimiters used by the protocol
// `-` has special meaning in roomids
if (newTitle.includes(',') || newTitle.includes('|')) {
throw new Chat.ErrorMessage(`Room title "${newTitle}" can't contain any of: ,|`);
}
if ((!newID.includes('-') || newID.startsWith('groupchat-')) && newTitle.includes('-')) {
throw new Chat.ErrorMessage(`Room title "${newTitle}" can't contain -`);
}
if (newID.length > MAX_CHATROOM_ID_LENGTH) throw new Chat.ErrorMessage("The given room title is too long.");
if (newID !== oldID && Rooms.search(newTitle)) throw new Chat.ErrorMessage(`The room '${newTitle}' already exists.`);
}
setParent(room: Room | null) {
if (this.parent === room) return;
if (this.parent) {
(this.parent.subRooms as any).delete(this.roomid);
if (!this.parent.subRooms!.size) {
(this.parent.subRooms as any) = null;
}
}
(this as any).parent = room;
if (room) {
if (!room.subRooms) {
(room as any).subRooms = new Map();
}
(room as any).subRooms.set(this.roomid, this);
this.settings.parentid = room.roomid;
} else {
delete this.settings.parentid;
}
this.saveSettings();
for (const userid in this.users) {
this.users[userid].updateIdentity(this.roomid);
}
}
clearSubRooms() {
if (!this.subRooms) return;
for (const room of this.subRooms.values()) {
(room as any).parent = null;
}
(this as any).subRooms = null;
// this doesn't update parentid or subroom user symbols because it's
// intended to be used for cleanup only
}
setPrivate(privacy: PrivacySetting) {
this.settings.isPrivate = privacy;
this.saveSettings();
if (privacy) {
for (const user of Object.values(this.users)) {
if (!user.named) {
user.leaveRoom(this.roomid);
user.popup(`The room <<${this.roomid}>> has been made private; you must log in to be in private rooms.`);
}
}
}
if (this.battle || this.bestOf) {
if (privacy) {
if (this.roomid.endsWith('pw')) return true;
// This is the same password generation approach as genPassword in the client replays.lib.php
// but obviously will not match given mt_rand there uses a different RNG and seed.
let password = '';
for (let i = 0; i < 31; i++) password += ALPHABET[Math.floor(Math.random() * ALPHABET.length)];
this.rename(this.title, `${this.roomid}-${password}pw` as RoomID, true);
} else {
if (!this.roomid.endsWith('pw')) return true;
const lastDashIndex = this.roomid.lastIndexOf('-');
if (lastDashIndex < 0) throw new Error(`invalid battle ID ${this.roomid}`);
this.rename(this.title, this.roomid.slice(0, lastDashIndex) as RoomID);
}
}
this.bestOf?.setPrivacyOfGames(privacy);
if (this.game) {
for (const player of this.game.players) {
player.getUser()?.updateSearch();
}
}
}
validateSection(section: string) {
const target = toID(section);
if (!RoomSections.sections.includes(target as any)) {
throw new Chat.ErrorMessage(`"${target}" is not a valid room section. Valid categories include: ${RoomSections.sections.join(', ')}`);
}
return target as RoomSection;
}
setSection(section?: string) {
if (!this.persist) {
throw new Chat.ErrorMessage(`You cannot change the section of temporary rooms.`);
}
if (section) {
const validatedSection = this.validateSection(section);
if (this.settings.isPrivate && [true, 'hidden'].includes(this.settings.isPrivate)) {
throw new Chat.ErrorMessage(`Only public rooms can change their section.`);
}
const oldSection = this.settings.section;
if (oldSection === section) {
throw new Chat.ErrorMessage(`${this.title}'s room section is already set to "${RoomSections.sectionNames[oldSection]}".`);
}
this.settings.section = validatedSection;
this.saveSettings();
return validatedSection;
}
delete this.settings.section;
this.saveSettings();
return undefined;
}
/**
* Displays a warning popup to all non-staff users users in the room.
* Returns a list of all the user IDs that were warned.
*/
warnParticipants(message: string) {
const warned = Object.values(this.users).filter(u => !u.can('lock'));
for (const user of warned) {
user.popup(`|modal|${message}`);
}
return warned;
}
/**
* @param newID Add this param if the roomid is different from `toID(newTitle)`
* @param noAlias Set this param to true to not redirect aliases and the room's old name to its new name.
*/
rename(newTitle: string, newID?: RoomID, noAlias?: boolean) {
if (!newID) newID = toID(newTitle) as RoomID;
const oldID = this.roomid;
this.validateTitle(newTitle, newID, oldID);
if (this.type === 'chat' && this.game) {
throw new Chat.ErrorMessage(`Please finish your game (${this.game.title}) before renaming ${this.roomid}.`);
}
(this as any).roomid = newID;
this.title = this.settings.title = newTitle;
this.saveSettings();
if (newID === oldID) {
for (const user of Object.values(this.users)) {
user.sendTo(this, `|title|${newTitle}`);
}
return;
}
Rooms.rooms.delete(oldID);
Rooms.rooms.set(newID, this as Room);
if (this.battle && oldID) {
for (const player of this.battle.players) {
if (player.invite) {
const chall = Ladders.challenges.searchByRoom(player.invite, oldID);
if (chall) chall.roomid = this.roomid;
}
}
}
if (oldID === 'lobby') {
Rooms.lobby = null;
} else if (newID === 'lobby') {
Rooms.lobby = this as ChatRoom;
}
if (!noAlias) {
for (const [alias, roomid] of Rooms.aliases.entries()) {
if (roomid === oldID) {
Rooms.aliases.set(alias, newID);
}
}
// add an alias from the old id
Rooms.aliases.set(oldID, newID);
if (!this.settings.aliases) this.settings.aliases = [];
// resolve an old (fixed) bug in /renameroom
if (!this.settings.aliases.includes(oldID)) this.settings.aliases.push(oldID);
} else {
// clear aliases
for (const [alias, roomid] of Rooms.aliases.entries()) {
if (roomid === oldID) {
Rooms.aliases.delete(alias);
}
}
this.settings.aliases = undefined;
}
this.game?.renameRoom(newID);
for (const user of Object.values(this.users)) {
user.moveConnections(oldID, newID);
user.send(`>${oldID}\n|noinit|rename|${newID}|${newTitle}`);
}
if (this.parent && this.parent.subRooms) {
(this as any).parent.subRooms.delete(oldID);
(this as any).parent.subRooms.set(newID, this as ChatRoom);
}
if (this.subRooms) {
for (const subRoom of this.subRooms.values()) {
(subRoom as any).parent = this as ChatRoom;
subRoom.settings.parentid = newID;
}
}
this.saveSettings();
Punishments.renameRoom(oldID, newID);
void this.log.rename(newID);
}
onConnect(user: User, connection: Connection) {
const userList = this.userList ? this.userList : this.getUserList();
this.sendUser(
connection,
'|init|chat\n|title|' + this.title + '\n' + userList + '\n' + this.log.getScrollback() + this.getIntroMessage(user)
);
this.minorActivity?.onConnect?.(user, connection);
this.game?.onConnect?.(user, connection);
}
onJoin(user: User, connection: Connection) {
if (!user) return false; // ???
if (this.users[user.id]) return false;