forked from smogon/pokemon-showdown
-
Notifications
You must be signed in to change notification settings - Fork 0
/
chat.ts
2592 lines (2382 loc) · 93.9 KB
/
chat.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
/**
* Chat
* Pokemon Showdown - http://pokemonshowdown.com/
*
* This handles chat and chat commands sent from users to chatrooms
* and PMs. The main function you're looking for is Chat.parse
* (scroll down to its definition for details)
*
* Individual commands are put in:
* chat-commands/ - "core" commands that shouldn't be modified
* chat-plugins/ - other commands that can be safely modified
*
* The command API is (mostly) documented in chat-plugins/COMMANDS.md
*
* @license MIT
*/
/*
To reload chat commands:
/hotpatch chat
*/
import type {RoomPermission, GlobalPermission} from './user-groups';
import type {Punishment} from './punishments';
import type {PartialModlogEntry} from './modlog';
import {FriendsDatabase, PM} from './friends';
import {SQL, Repl, FS, Utils} from '../lib';
import {Dex} from '../sim';
import {resolve} from 'path';
import * as JSX from './chat-jsx';
export type PageHandler = (this: PageContext, query: string[], user: User, connection: Connection)
=> Promise<string | null | void | JSX.VNode> | string | null | void | JSX.VNode;
export interface PageTable {
[k: string]: PageHandler | PageTable;
}
export type ChatHandler = (
this: CommandContext,
target: string,
room: Room | null,
user: User,
connection: Connection,
cmd: string,
message: string
) => void;
export type AnnotatedChatHandler = ChatHandler & {
requiresRoom: boolean | RoomID,
hasRoomPermissions: boolean,
broadcastable: boolean,
cmd: string,
fullCmd: string,
isPrivate: boolean,
disabled: boolean,
aliases: string[],
requiredPermission?: GlobalPermission | RoomPermission,
};
export interface ChatCommands {
[k: string]: ChatHandler | string | string[] | ChatCommands;
}
export interface AnnotatedChatCommands {
[k: string]: AnnotatedChatHandler | string | string[] | AnnotatedChatCommands;
}
export interface Handlers {
onRoomClose?: (id: string, user: User, connection: Connection, page: boolean) => any;
onRenameRoom?: (oldId: RoomID, newID: RoomID, room: BasicRoom) => void;
onBattleStart?: (user: User, room: GameRoom) => void;
onBattleLeave?: (user: User, room: GameRoom) => void;
onDisconnect?: (user: User) => void;
}
export interface ChatPlugin {
commands?: AnnotatedChatCommands;
pages?: PageTable;
destroy?: () => void;
roomSettings?: SettingsHandler | SettingsHandler[];
[k: string]: any;
}
export type SettingsHandler = (
room: Room,
user: User,
connection: Connection
) => {
label: string,
permission: boolean | RoomPermission,
// button label, command | disabled
options: [string, string | true][],
};
export type CRQHandler = (this: CommandContext, target: string, user: User, trustable?: boolean) => any;
export type RoomCloseHandler = (id: string, user: User, connection: Connection, page: boolean) => any;
/**
* Chat filters can choose to:
* 1. return false OR null - to not send a user's message
* 2. return an altered string - to alter a user's message
* 3. return undefined to send the original message through
*/
export type ChatFilter = ((
this: CommandContext,
message: string,
user: User,
room: Room | null,
connection: Connection,
targetUser: User | null,
originalMessage: string
) => string | false | null | undefined) & {priority?: number};
export type NameFilter = (name: string, user: User) => string;
export type NicknameFilter = (name: string, user: User) => string | false;
export type StatusFilter = (status: string, user: User) => string;
export type PunishmentFilter = (user: User | ID, punishment: Punishment) => void;
export type LoginFilter = (user: User, oldUser: User | null, userType: string) => void;
export type HostFilter = (host: string, user: User, connection: Connection, hostType: string) => void;
export interface Translations {
name?: string;
strings: {[english: string]: string};
}
const LINK_WHITELIST = [
'*.pokemonshowdown.com', 'psim.us', 'smogtours.psim.us',
'*.smogon.com', '*.pastebin.com', '*.hastebin.com',
];
const MAX_MESSAGE_LENGTH = 300;
const BROADCAST_COOLDOWN = 20 * 1000;
const MESSAGE_COOLDOWN = 5 * 60 * 1000;
const MAX_PARSE_RECURSION = 10;
const VALID_COMMAND_TOKENS = '/!';
const BROADCAST_TOKEN = '!';
const PLUGIN_DATABASE_PATH = './databases/chat-plugins.db';
const MAX_PLUGIN_LOADING_DEPTH = 3;
const VALID_PLUGIN_ENDINGS = ['.jsx', '.tsx', '.js', '.ts'];
import {formatText, linkRegex, stripFormatting} from './chat-formatter';
// @ts-ignore no typedef available
import ProbeModule = require('probe-image-size');
const probe: (url: string) => Promise<{width: number, height: number}> = ProbeModule;
const EMOJI_REGEX = /[\p{Emoji_Modifier_Base}\p{Emoji_Presentation}\uFE0F]/u;
// to account for Sucrase
const TRANSLATION_PATH = __dirname.endsWith('.server-dist') ? `../.translations-dist` : `../translations`;
const TRANSLATION_DIRECTORY = `${__dirname}/${TRANSLATION_PATH}`;
class PatternTester {
// This class sounds like a RegExp
// In fact, one could in theory implement it as a RegExp subclass
// However, ES2016 RegExp subclassing is a can of worms, and it wouldn't allow us
// to tailor the test method for fast command parsing.
readonly elements: string[];
readonly fastElements: Set<string>;
regexp: RegExp | null;
constructor() {
this.elements = [];
this.fastElements = new Set();
this.regexp = null;
}
fastNormalize(elem: string) {
return elem.slice(0, -1);
}
update() {
const slowElements = this.elements.filter(elem => !this.fastElements.has(this.fastNormalize(elem)));
if (slowElements.length) {
this.regexp = new RegExp('^(' + slowElements.map(elem => '(?:' + elem + ')').join('|') + ')', 'i');
}
}
register(...elems: string[]) {
for (const elem of elems) {
this.elements.push(elem);
if (/^[^ ^$?|()[\]]+ $/.test(elem)) {
this.fastElements.add(this.fastNormalize(elem));
}
}
this.update();
}
testCommand(text: string) {
const spaceIndex = text.indexOf(' ');
if (this.fastElements.has(spaceIndex >= 0 ? text.slice(0, spaceIndex) : text)) {
return true;
}
if (!this.regexp) return false;
return this.regexp.test(text);
}
test(text: string) {
if (!text.includes('\n')) return null;
if (this.testCommand(text)) return text;
// The PM matching is a huge mess, and really needs to be replaced with
// the new multiline command system soon.
const pmMatches = /^(\/(?:pm|w|whisper|msg) [^,]*, ?)(.*)/i.exec(text);
if (pmMatches && this.testCommand(pmMatches[2])) {
if (text.split('\n').every(line => line.startsWith(pmMatches[1]))) {
return text.replace(/\n\/(?:pm|w|whisper|msg) [^,]*, ?/g, '\n');
}
return text;
}
return null;
}
}
/*********************************************************
* Parser
*********************************************************/
/**
* An ErrorMessage will, if used in a command/page context, simply show the user
* the error, rather than logging a crash. It's used to simplify showing errors.
*
* Outside of a command/page context, it would still cause a crash.
*/
export class ErrorMessage extends Error {
constructor(message: string) {
super(message);
this.name = 'ErrorMessage';
Error.captureStackTrace(this, ErrorMessage);
}
}
export class Interruption extends Error {
constructor() {
super('');
this.name = 'Interruption';
Error.captureStackTrace(this, ErrorMessage);
}
}
// These classes need to be declared here because they aren't hoisted
export abstract class MessageContext {
readonly user: User;
language: ID | null;
recursionDepth: number;
constructor(user: User, language: ID | null = null) {
this.user = user;
this.language = language;
this.recursionDepth = 0;
}
splitOne(target: string) {
const commaIndex = target.indexOf(',');
if (commaIndex < 0) {
return [target.trim(), ''];
}
return [target.slice(0, commaIndex).trim(), target.slice(commaIndex + 1).trim()];
}
meansYes(text: string) {
switch (text.toLowerCase().trim()) {
case 'on': case 'enable': case 'yes': case 'true': case 'allow': case '1':
return true;
}
return false;
}
meansNo(text: string) {
switch (text.toLowerCase().trim()) {
case 'off': case 'disable': case 'no': case 'false': case 'disallow': case '0':
return true;
}
return false;
}
/**
* Given an array of strings (or a comma-delimited string), check the
* first and last string for a format/mod/gen. If it exists, remove
* it from the array.
*
* @returns `format` (null if no format was found), `dex` (the dex
* for the format/mod, or the default dex if none was found), and
* `targets` (the rest of the array).
*/
splitFormat(target: string | string[], atLeastOneTarget?: boolean) {
const targets = typeof target === 'string' ? target.split(',') : target;
if (!targets[0].trim()) targets.pop();
if (targets.length > (atLeastOneTarget ? 1 : 0)) {
const {dex, format, isMatch} = this.extractFormat(targets[0].trim());
if (isMatch) {
targets.shift();
return {dex, format, targets};
}
}
if (targets.length > 1) {
const {dex, format, isMatch} = this.extractFormat(targets[targets.length - 1].trim());
if (isMatch) {
targets.pop();
return {dex, format, targets};
}
}
const room = (this as any as CommandContext).room;
const {dex, format} = this.extractFormat(room?.settings.defaultFormat || room?.battle?.format);
return {dex, format, targets};
}
extractFormat(formatOrMod?: string): {dex: ModdedDex, format: Format | null, isMatch: boolean} {
if (!formatOrMod) {
return {dex: Dex.includeData(), format: null, isMatch: false};
}
const format = Dex.formats.get(formatOrMod);
if (format.exists) {
return {dex: Dex.forFormat(format), format: format, isMatch: true};
}
if (toID(formatOrMod) in Dex.dexes) {
return {dex: Dex.mod(toID(formatOrMod)).includeData(), format: null, isMatch: true};
}
return this.extractFormat();
}
splitUser(target: string, {exactName}: {exactName?: boolean} = {}) {
const [inputUsername, rest] = this.splitOne(target).map(str => str.trim());
const targetUser = Users.get(inputUsername, exactName);
return {
targetUser,
inputUsername,
targetUsername: targetUser ? targetUser.name : inputUsername,
rest,
};
}
requireUser(target: string, options: {allowOffline?: boolean, exactName?: boolean} = {}) {
const {targetUser, targetUsername, rest} = this.splitUser(target, options);
if (!targetUser) {
throw new Chat.ErrorMessage(`The user "${targetUsername}" is offline or misspelled.`);
}
if (!options.allowOffline && !targetUser.connected) {
throw new Chat.ErrorMessage(`The user "${targetUsername}" is offline.`);
}
// `inputUsername` and `targetUsername` are never needed because we already handle the "user not found" error messages
// just use `targetUser.name` where previously necessary
return {targetUser, rest};
}
getUserOrSelf(target: string, {exactName}: {exactName?: boolean} = {}) {
if (!target.trim()) return this.user;
return Users.get(target, exactName);
}
tr(strings: TemplateStringsArray | string, ...keys: any[]) {
return Chat.tr(this.language, strings, ...keys);
}
}
export class PageContext extends MessageContext {
readonly connection: Connection;
room: Room | null;
pageid: string;
initialized: boolean;
title: string;
args: string[];
constructor(options: {pageid: string, user: User, connection: Connection, language?: ID}) {
super(options.user, options.language);
this.connection = options.connection;
this.room = null;
this.pageid = options.pageid;
this.args = this.pageid.split('-');
this.initialized = false;
this.title = 'Page';
}
checkCan(permission: RoomPermission, target: User | null, room: Room): boolean;
checkCan(permission: GlobalPermission, target?: User | null): boolean;
checkCan(permission: string, target: User | null = null, room: Room | null = null) {
if (!this.user.can(permission as any, target, room as any)) {
throw new Chat.ErrorMessage(`<h2>Permission denied.</h2>`);
}
return true;
}
privatelyCheckCan(permission: RoomPermission, target: User | null, room: Room): boolean;
privatelyCheckCan(permission: GlobalPermission, target?: User | null): boolean;
privatelyCheckCan(permission: string, target: User | null = null, room: Room | null = null) {
if (!this.user.can(permission as any, target, room as any)) {
this.pageDoesNotExist();
}
return true;
}
pageDoesNotExist(): never {
throw new Chat.ErrorMessage(`Page "${this.pageid}" not found`);
}
requireRoom(pageid?: string) {
const room = this.extractRoom(pageid);
if (!room) {
throw new Chat.ErrorMessage(`Invalid link: This page requires a room ID.`);
}
this.room = room;
return room;
}
extractRoom(pageid?: string) {
if (!pageid) pageid = this.pageid;
const parts = pageid.split('-');
// The roomid for the page should be view-pagename-roomid
const room = Rooms.get(parts[2]) || null;
this.room = room;
return room;
}
setHTML(html: string) {
const roomid = this.room ? `[${this.room.roomid}] ` : '';
let content = `|title|${roomid}${this.title}\n|pagehtml|${html}`;
if (!this.initialized) {
content = `|init|html\n${content}`;
this.initialized = true;
}
this.send(content);
}
errorReply(message: string) {
this.setHTML(`<div class="pad"><p class="message-error">${message}</p></div>`);
}
send(content: string) {
this.connection.send(`>${this.pageid}\n${content}`);
}
close() {
this.send('|deinit');
}
async resolve(pageid?: string) {
if (pageid) this.pageid = pageid;
const parts = this.pageid.split('-');
parts.shift(); // first part is always `view`
if (!this.connection.openPages) this.connection.openPages = new Set();
this.connection.openPages.add(parts.join('-'));
let handler: PageHandler | PageTable = Chat.pages;
while (handler) {
if (typeof handler === 'function') {
break;
}
handler = handler[parts.shift() || 'default'] || handler[''];
}
this.args = parts;
let res;
try {
if (typeof handler !== 'function') this.pageDoesNotExist();
res = await handler.call(this, parts, this.user, this.connection);
} catch (err: any) {
if (err.name?.endsWith('ErrorMessage')) {
if (err.message) this.errorReply(err.message);
return;
}
if (err.name.endsWith('Interruption')) {
return;
}
Monitor.crashlog(err, 'A chat page', {
user: this.user.name,
room: this.room && this.room.roomid,
pageid: this.pageid,
});
this.setHTML(
`<div class="pad"><div class="broadcast-red">` +
`<strong>Pokemon Showdown crashed!</strong><br />Don't worry, we're working on fixing it.` +
`</div></div>`
);
}
if (typeof res === 'object' && res) res = JSX.render(res);
if (typeof res === 'string') {
this.setHTML(res);
res = undefined;
}
return res;
}
}
/**
* This is a message sent in a PM or to a chat/battle room.
*
* There are three cases to be aware of:
* - PM to user: `context.pmTarget` will exist and `context.room` will be `null`
* - message to room: `context.room` will exist and `context.pmTarget` will be `null`
* - console command (PM to `~`): `context.pmTarget` and `context.room` will both be `null`
*/
export class CommandContext extends MessageContext {
message: string;
pmTarget: User | null;
room: Room | null;
connection: Connection;
cmd: string;
cmdToken: string;
target: string;
fullCmd: string;
handler: AnnotatedChatHandler | null;
isQuiet: boolean;
broadcasting: boolean;
broadcastToRoom: boolean;
/** Used only by !rebroadcast */
broadcastPrefix: string;
broadcastMessage: string;
constructor(options: {
message: string, user: User, connection: Connection,
room?: Room | null, pmTarget?: User | null, cmd?: string, cmdToken?: string, target?: string, fullCmd?: string,
recursionDepth?: number, isQuiet?: boolean, broadcastPrefix?: string,
}) {
super(
options.user, options.room && options.room.settings.language ?
options.room.settings.language : options.user.language
);
this.message = options.message || ``;
this.recursionDepth = options.recursionDepth || 0;
// message context
this.pmTarget = options.pmTarget || null;
this.room = options.room || null;
this.connection = options.connection;
// command context
this.cmd = options.cmd || '';
this.cmdToken = options.cmdToken || '';
this.target = options.target || ``;
this.fullCmd = options.fullCmd || '';
this.handler = null;
this.isQuiet = options.isQuiet || false;
// broadcast context
this.broadcasting = false;
this.broadcastToRoom = true;
this.broadcastPrefix = options.broadcastPrefix || '';
this.broadcastMessage = '';
}
// TODO: return should be void | boolean | Promise<void | boolean>
parse(msg?: string, options: {isQuiet?: boolean, broadcastPrefix?: string} = {}): any {
if (typeof msg === 'string') {
// spawn subcontext
const subcontext = new CommandContext({
message: msg,
user: this.user,
connection: this.connection,
room: this.room,
pmTarget: this.pmTarget,
recursionDepth: this.recursionDepth + 1,
...options,
});
if (subcontext.recursionDepth > MAX_PARSE_RECURSION) {
throw new Error("Too much command recursion");
}
return subcontext.parse();
}
let message: string | void | boolean | Promise<string | void | boolean> = this.message;
const parsedCommand = Chat.parseCommand(message);
if (parsedCommand) {
this.cmd = parsedCommand.cmd;
this.fullCmd = parsedCommand.fullCmd;
this.cmdToken = parsedCommand.cmdToken;
this.target = parsedCommand.target;
this.handler = parsedCommand.handler;
}
if (this.room && !(this.user.id in this.room.users)) {
return this.popupReply(`You tried to send "${message}" to the room "${this.room.roomid}" but it failed because you were not in that room.`);
}
if (this.user.statusType === 'idle' && !['unaway', 'unafk', 'back'].includes(this.cmd)) {
this.user.setStatusType('online');
}
try {
if (this.handler) {
if (this.handler.disabled) {
throw new Chat.ErrorMessage(
`The command /${this.cmd} is temporarily unavailable due to technical difficulties. Please try again in a few hours.`
);
}
message = this.run(this.handler);
} else {
if (this.cmdToken) {
// To guard against command typos, show an error message
if (!(this.shouldBroadcast() && !/[a-z0-9]/.test(this.cmd.charAt(0)))) {
this.commandDoesNotExist();
}
} else if (!VALID_COMMAND_TOKENS.includes(message.charAt(0)) &&
VALID_COMMAND_TOKENS.includes(message.trim().charAt(0))) {
message = message.trim();
if (!message.startsWith(BROADCAST_TOKEN)) {
message = message.charAt(0) + message;
}
}
message = this.checkChat(message);
}
} catch (err: any) {
if (err.name?.endsWith('ErrorMessage')) {
this.errorReply(err.message);
this.update();
return false;
}
if (err.name.endsWith('Interruption')) {
this.update();
return;
}
Monitor.crashlog(err, 'A chat command', {
user: this.user.name,
room: this.room?.roomid,
pmTarget: this.pmTarget?.name,
message: this.message,
});
this.sendReply(`|html|<div class="broadcast-red"><b>Pokemon Showdown crashed!</b><br />Don't worry, we're working on fixing it.</div>`);
return;
}
// Output the message
if (message && typeof (message as any).then === 'function') {
this.update();
return (message as Promise<string | boolean | void>).then(resolvedMessage => {
if (resolvedMessage && resolvedMessage !== true) {
this.sendChatMessage(resolvedMessage);
}
this.update();
if (resolvedMessage === false) return false;
}).catch(err => {
if (err.name?.endsWith('ErrorMessage')) {
this.errorReply(err.message);
this.update();
return false;
}
if (err.name.endsWith('Interruption')) {
this.update();
return;
}
Monitor.crashlog(err, 'An async chat command', {
user: this.user.name,
room: this.room?.roomid,
pmTarget: this.pmTarget?.name,
message: this.message,
});
this.sendReply(`|html|<div class="broadcast-red"><b>Pokemon Showdown crashed!</b><br />Don't worry, we're working on fixing it.</div>`);
return false;
});
} else if (message && message !== true) {
this.sendChatMessage(message as string);
message = true;
}
this.update();
return message;
}
sendChatMessage(message: string) {
if (this.pmTarget) {
const blockInvites = this.pmTarget.settings.blockInvites;
if (blockInvites && /^<<.*>>$/.test(message.trim())) {
if (
!this.user.can('lock') && blockInvites === true ||
!Users.globalAuth.atLeast(this.user, blockInvites as GroupSymbol)
) {
Chat.maybeNotifyBlocked(`invite`, this.pmTarget, this.user);
return this.errorReply(`${this.pmTarget.name} is blocking room invites.`);
}
}
Chat.sendPM(message, this.user, this.pmTarget);
} else if (this.room) {
this.room.add(`|c|${this.user.getIdentity(this.room)}|${message}`);
if (this.room.game && this.room.game.onLogMessage) {
this.room.game.onLogMessage(message, this.user);
}
} else {
this.connection.popup(`Your message could not be sent:\n\n${message}\n\nIt needs to be sent to a user or room.`);
}
}
run(handler: string | AnnotatedChatHandler) {
if (typeof handler === 'string') handler = Chat.commands[handler] as AnnotatedChatHandler;
if (!handler.broadcastable && this.cmdToken === '!') {
this.errorReply(`The command "${this.fullCmd}" can't be broadcast.`);
this.errorReply(`Use /${this.fullCmd} instead.`);
return false;
}
let result: any = handler.call(this, this.target, this.room, this.user, this.connection, this.cmd, this.message);
if (result === undefined) result = false;
return result;
}
checkFormat(room: BasicRoom | null | undefined, user: User, message: string) {
if (!room) return true;
if (!room.settings.filterStretching && !room.settings.filterCaps && !room.settings.filterEmojis) return true;
if (user.can('bypassall')) return true;
if (room.settings.filterStretching && /(.+?)\1{5,}/i.test(user.name)) {
throw new Chat.ErrorMessage(`Your username contains too much stretching, which this room doesn't allow.`);
}
if (room.settings.filterCaps && /[A-Z\s]{6,}/.test(user.name)) {
throw new Chat.ErrorMessage(`Your username contains too many capital letters, which this room doesn't allow.`);
}
if (room.settings.filterEmojis && EMOJI_REGEX.test(user.name)) {
throw new Chat.ErrorMessage(`Your username contains emojis, which this room doesn't allow.`);
}
// Removes extra spaces and null characters
message = message.trim().replace(/[ \u0000\u200B-\u200F]+/g, ' ');
if (room.settings.filterStretching && /(.+?)\1{7,}/i.test(message)) {
throw new Chat.ErrorMessage(`Your message contains too much stretching, which this room doesn't allow.`);
}
if (room.settings.filterCaps && /[A-Z\s]{18,}/.test(message)) {
throw new Chat.ErrorMessage(`Your message contains too many capital letters, which this room doesn't allow.`);
}
if (room.settings.filterEmojis && EMOJI_REGEX.test(message)) {
throw new Chat.ErrorMessage(`Your message contains emojis, which this room doesn't allow.`);
}
return true;
}
checkSlowchat(room: Room | null | undefined, user: User) {
if (!room?.settings.slowchat) return true;
if (user.can('show', null, room)) return true;
const lastActiveSeconds = (Date.now() - user.lastMessageTime) / 1000;
if (lastActiveSeconds < room.settings.slowchat) {
throw new Chat.ErrorMessage(this.tr`This room has slow-chat enabled. You can only talk once every ${room.settings.slowchat} seconds.`);
}
return true;
}
checkBanwords(room: BasicRoom | null | undefined, message: string): boolean {
if (!room) return true;
if (!room.banwordRegex) {
if (room.settings.banwords && room.settings.banwords.length) {
room.banwordRegex = new RegExp('(?:\\b|(?!\\w))(?:' + room.settings.banwords.join('|') + ')(?:\\b|\\B(?!\\w))', 'i');
} else {
room.banwordRegex = true;
}
}
if (!message) return true;
if (room.banwordRegex !== true && room.banwordRegex.test(message)) {
throw new Chat.ErrorMessage(`Your username, status, or message contained a word banned by this room.`);
}
return this.checkBanwords(room.parent as ChatRoom, message);
}
checkGameFilter() {
if (!this.room?.game || !this.room.game.onChatMessage) return;
return this.room.game.onChatMessage(this.message, this.user);
}
pmTransform(originalMessage: string, sender?: User, receiver?: User | null | string) {
if (!sender) {
if (this.room) throw new Error(`Not a PM`);
sender = this.user;
receiver = this.pmTarget;
}
const targetIdentity = typeof receiver === 'string' ? ` ${receiver}` : receiver ? receiver.getIdentity() : '~';
const prefix = `|pm|${sender.getIdentity()}|${targetIdentity}|`;
return originalMessage.split('\n').map(message => {
if (message.startsWith('||')) {
return prefix + `/text ` + message.slice(2);
} else if (message.startsWith(`|html|`)) {
return prefix + `/raw ` + message.slice(6);
} else if (message.startsWith(`|uhtml|`)) {
const [uhtmlid, html] = Utils.splitFirst(message.slice(7), '|');
return prefix + `/uhtml ${uhtmlid},${html}`;
} else if (message.startsWith(`|uhtmlchange|`)) {
const [uhtmlid, html] = Utils.splitFirst(message.slice(13), '|');
return prefix + `/uhtmlchange ${uhtmlid},${html}`;
} else if (message.startsWith(`|modaction|`)) {
return prefix + `/log ` + message.slice(11);
} else if (message.startsWith(`|raw|`)) {
return prefix + `/raw ` + message.slice(5);
} else if (message.startsWith(`|error|`)) {
return prefix + `/error ` + message.slice(7);
} else if (message.startsWith(`|c~|`)) {
return prefix + message.slice(4);
} else if (message.startsWith(`|c|~|/`)) {
return prefix + message.slice(5);
} else if (message.startsWith(`|c|~|`)) {
return prefix + `/text ` + message.slice(5);
}
return prefix + `/text ` + message;
}).join(`\n`);
}
sendReply(data: string) {
if (this.isQuiet) return;
if (this.broadcasting && this.broadcastToRoom) {
// broadcasting
this.add(data);
} else {
// not broadcasting
if (!this.room) {
data = this.pmTransform(data);
this.connection.send(data);
} else {
this.connection.sendTo(this.room, data);
}
}
}
errorReply(message: string) {
this.sendReply(`|error|` + message.replace(/\n/g, `\n|error|`));
}
addBox(htmlContent: string | JSX.VNode) {
if (typeof htmlContent !== 'string') htmlContent = JSX.render(htmlContent);
this.add(`|html|<div class="infobox">${htmlContent}</div>`);
}
sendReplyBox(htmlContent: string | JSX.VNode) {
if (typeof htmlContent !== 'string') htmlContent = JSX.render(htmlContent);
this.sendReply(`|c|${this.room && this.broadcasting ? this.user.getIdentity() : '~'}|/raw <div class="infobox">${htmlContent}</div>`);
}
popupReply(message: string) {
this.connection.popup(message);
}
add(data: string) {
if (this.room) {
this.room.add(data);
} else {
this.send(data);
}
}
send(data: string) {
if (this.room) {
this.room.send(data);
} else {
data = this.pmTransform(data);
this.user.send(data);
if (this.pmTarget && this.pmTarget !== this.user) {
this.pmTarget.send(data);
}
}
}
/** like privateModAction, but also notify Staff room */
privateGlobalModAction(msg: string) {
this.privateModAction(msg);
if (this.room?.roomid !== 'staff') {
Rooms.get('staff')?.addByUser(this.user, `${this.room ? `<<${this.room.roomid}>>` : `<PM:${this.pmTarget}>`} ${msg}`).update();
}
}
addGlobalModAction(msg: string) {
this.addModAction(msg);
if (this.room?.roomid !== 'staff') {
Rooms.get('staff')?.addByUser(this.user, `${this.room ? `<<${this.room.roomid}>>` : `<PM:${this.pmTarget}>`} ${msg}`).update();
}
}
privateModAction(msg: string) {
if (this.room) {
if (this.room.roomid === 'staff') {
this.room.addByUser(this.user, `(${msg})`);
} else {
this.room.sendModsByUser(this.user, `(${msg})`);
// roomlogging in staff causes a duplicate log message, since we do addByUser
// and roomlogging in pms has no effect, so we can _just_ call this here
this.roomlog(`(${msg})`);
}
} else {
const data = this.pmTransform(`|modaction|${msg}`);
this.user.send(data);
if (this.pmTarget && this.pmTarget !== this.user && this.pmTarget.isStaff) {
this.pmTarget.send(data);
}
}
}
globalModlog(action: string, user: string | User | null = null, note: string | null = null, ip?: string) {
const entry: PartialModlogEntry = {
action,
isGlobal: true,
loggedBy: this.user.id,
note: note?.replace(/\n/gm, ' ') || '',
};
if (user) {
if (typeof user === 'string') {
entry.userid = toID(user);
} else {
entry.ip = user.latestIp;
const userid = user.getLastId();
entry.userid = userid;
if (user.autoconfirmed && user.autoconfirmed !== userid) entry.autoconfirmedID = user.autoconfirmed;
const alts = user.getAltUsers(false, true).slice(1).map(alt => alt.getLastId());
if (alts.length) entry.alts = alts;
}
}
if (ip) entry.ip = ip;
if (this.room) {
this.room.modlog(entry);
} else {
Rooms.global.modlog(entry);
}
}
modlog(
action: string,
user: string | User | null = null,
note: string | null = null,
options: Partial<{noalts: any, noip: any}> = {}
) {
const entry: PartialModlogEntry = {
action,
loggedBy: this.user.id,
note: note?.replace(/\n/gm, ' ') || '',
};
if (user) {
if (typeof user === 'string') {
entry.userid = toID(user);
} else {
const userid = user.getLastId();
entry.userid = userid;
if (!options.noalts) {
if (user.autoconfirmed && user.autoconfirmed !== userid) entry.autoconfirmedID = user.autoconfirmed;
const alts = user.getAltUsers(false, true).slice(1).map(alt => alt.getLastId());
if (alts.length) entry.alts = alts;
}
if (!options.noip) entry.ip = user.latestIp;
}
}
(this.room || Rooms.global).modlog(entry);
}
parseSpoiler(reason: string) {
if (!reason) return {publicReason: "", privateReason: ""};
let publicReason = reason;
let privateReason = reason;
const targetLowercase = reason.toLowerCase();
if (targetLowercase.includes('spoiler:') || targetLowercase.includes('spoilers:')) {
const proofIndex = targetLowercase.indexOf(targetLowercase.includes('spoilers:') ? 'spoilers:' : 'spoiler:');
const proofOffset = (targetLowercase.includes('spoilers:') ? 9 : 8);
const proof = reason.slice(proofIndex + proofOffset).trim();
publicReason = reason.slice(0, proofIndex).trim();
privateReason = `${publicReason}${proof ? ` (PROOF: ${proof})` : ''}`;
}
return {publicReason, privateReason};
}
roomlog(data: string) {
if (this.room) this.room.roomlog(data);
}
stafflog(data: string) {
(Rooms.get('staff') || Rooms.lobby || this.room)?.roomlog(data);
}
addModAction(msg: string) {
if (this.room) {
this.room.addByUser(this.user, msg);
} else {
this.send(`|modaction|${msg}`);
}
}
update() {
if (this.room) this.room.update();
}
filter(message: string) {
return Chat.filter(message, this);
}
statusfilter(status: string) {
return Chat.statusfilter(status, this.user);
}
checkCan(permission: RoomPermission, target: User | ID | null, room: Room): undefined;
checkCan(permission: GlobalPermission, target?: User | ID | null): undefined;
checkCan(permission: string, target: User | ID | null = null, room: Room | null = null) {
if (!Users.Auth.hasPermission(this.user, permission, target, room, this.fullCmd)) {
throw new Chat.ErrorMessage(`${this.cmdToken}${this.fullCmd} - Access denied.`);
}
}
privatelyCheckCan(permission: RoomPermission, target: User | ID | null, room: Room): boolean;
privatelyCheckCan(permission: GlobalPermission, target?: User | ID | null): boolean;
privatelyCheckCan(permission: string, target: User | ID | null = null, room: Room | null = null) {
this.handler!.isPrivate = true;
if (Users.Auth.hasPermission(this.user, permission, target, room, this.fullCmd)) {
return true;
}
this.commandDoesNotExist();
}
canUseConsole() {
if (!this.user.hasConsoleAccess(this.connection)) {
throw new Chat.ErrorMessage(
this.cmdToken + this.fullCmd + " - Requires console access, please set up `Config.consoleips`."
);
}
return true;
}
shouldBroadcast() {
return this.cmdToken === BROADCAST_TOKEN;
}
checkBroadcast(overrideCooldown?: boolean | string, suppressMessage?: string | null) {
if (this.broadcasting || !this.shouldBroadcast()) {
return true;
}
if (this.room && !this.user.can('show', null, this.room)) {
this.errorReply(`You need to be voiced to broadcast this command's information.`);
throw new Chat.ErrorMessage(`To see it for yourself, use: /${this.message.slice(1)}`);
}
if (!this.room && !this.pmTarget) {
this.errorReply(`Broadcasting a command with "!" in a PM or chatroom will show it that user or room.`);
throw new Chat.ErrorMessage(`To see it for yourself, use: /${this.message.slice(1)}`);