-
Notifications
You must be signed in to change notification settings - Fork 2
/
chat.js
1748 lines (1623 loc) · 59.5 KB
/
chat.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
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.js - "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 license
*/
/*
To reload chat commands:
/hotpatch chat
*/
'use strict';
/** @typedef {GlobalRoom | GameRoom | ChatRoom} Room */
/** @typedef {(query: string[], user: User, connection: Connection) => (string | null | void)} PageHandler */
/** @typedef {{[k: string]: PageHandler | PageTable}} PageTable */
/** @typedef {(this: CommandContext, target: string, room: ChatRoom | GameRoom, user: User, connection: Connection, cmd: string, message: string) => (void)} ChatHandler */
/** @typedef {{[k: string]: ChatHandler | string | true | string[] | ChatCommands}} ChatCommands */
/** @typedef {(this: CommandContext, message: string, user: User, room: ChatRoom?, connection: Connection, targetUser: User?) => (string | boolean)} ChatFilter */
/** @typedef {(name: string, user: User) => (string)} NameFilter */
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 FS = require('./lib/fs');
/** @type {(url: string) => Promise<{width: number, height: number}>} */
// @ts-ignore ignoring until there is a ts typedef available for this module.
const probe = require('probe-image-size');
let Chat = module.exports;
// Matches U+FE0F and all Emoji_Presentation characters. More details on
// http://www.unicode.org/Public/emoji/5.0/emoji-data.txt
const emojiRegex = /[\u231A\u231B\u23E9-\u23EC\u23F0\u23F3\u25FD\u25FE\u2614\u2615\u2648-\u2653\u267F\u2693\u26A1\u26AA\u26AB\u26BD\u26BE\u26C4\u26C5\u26CE\u26D4\u26EA\u26F2\u26F3\u26F5\u26FA\u26FD\u2705\u270A\u270B\u2728\u274C\u274E\u2753-\u2755\u2757\u2795-\u2797\u27B0\u27BF\u2B1B\u2B1C\u2B50\u2B55\uFE0F\u{1F004}\u{1F0CF}\u{1F18E}\u{1F191}-\u{1F19A}\u{1F1E6}-\u{1F1FF}\u{1F201}\u{1F21A}\u{1F22F}\u{1F232}-\u{1F236}\u{1F238}-\u{1F23A}\u{1F250}\u{1F251}\u{1F300}-\u{1F320}\u{1F32D}-\u{1F335}\u{1F337}-\u{1F37C}\u{1F37E}-\u{1F393}\u{1F3A0}-\u{1F3CA}\u{1F3CF}-\u{1F3D3}\u{1F3E0}-\u{1F3F0}\u{1F3F4}\u{1F3F8}-\u{1F43E}\u{1F440}\u{1F442}-\u{1F4FC}\u{1F4FF}-\u{1F53D}\u{1F54B}-\u{1F54E}\u{1F550}-\u{1F567}\u{1F57A}\u{1F595}\u{1F596}\u{1F5A4}\u{1F5FB}-\u{1F64F}\u{1F680}-\u{1F6C5}\u{1F6CC}\u{1F6D0}-\u{1F6D2}\u{1F6EB}\u{1F6EC}\u{1F6F4}-\u{1F6F8}\u{1F910}-\u{1F93A}\u{1F93C}-\u{1F93E}\u{1F940}-\u{1F945}\u{1F947}-\u{1F94C}\u{1F950}-\u{1F96B}\u{1F980}-\u{1F997}\u{1F9C0}\u{1F9D0}-\u{1F9E6}]/u;
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.
constructor() {
/** @type {string[]} */
this.elements = [];
/** @type {Set<string>} */
this.fastElements = new Set();
/** @type {?RegExp} */
this.regexp = null;
}
/**
* @param {string} elem
*/
fastNormalize(elem) {
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');
}
}
/**
* @param {string[]} elems
*/
register(...elems) {
for (const elem of elems) {
this.elements.push(elem);
if (/^[^ ^$?|()[\]]+ $/.test(elem)) {
this.fastElements.add(this.fastNormalize(elem));
}
}
this.update();
}
/**
* @param {string} text
*/
test(text) {
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);
}
}
Chat.multiLinePattern = new PatternTester();
/*********************************************************
* Load command files
*********************************************************/
/** @type {ChatCommands} */
// @ts-ignore
Chat.baseCommands = undefined;
/** @type {ChatCommands} */
// @ts-ignore
Chat.commands = undefined;
/** @type {PageTable} */
// @ts-ignore
Chat.basePages = undefined;
/** @type {PageTable} */
// @ts-ignore
Chat.pages = undefined;
/*********************************************************
* Load chat filters
*********************************************************/
/**@type {ChatFilter[]} */
Chat.filters = [];
/**
* @param {string} message
* @param {User} user
* @param {ChatRoom} room
* @param {Connection} connection
* @param {User?} [targetUser]
*/
Chat.filter = function (message, user, room, connection, targetUser = null) {
// 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
const originalMessage = message;
for (const filter of Chat.filters) {
const output = filter.call(this, message, user, room, connection, targetUser, originalMessage);
if (output !== undefined) message = output;
if (!message) return message;
}
return message;
};
/**@type {NameFilter[]} */
Chat.namefilters = [];
/**
* @param {string} name
* @param {User} user
*/
Chat.namefilter = function (name, user) {
if (!Config.disablebasicnamefilter) {
// whitelist
// \u00A1-\u00BF\u00D7\u00F7 Latin punctuation/symbols
// \u02B9-\u0362 basic combining accents
// \u2012-\u2027\u2030-\u205E Latin punctuation/symbols extended
// \u2050-\u205F fractions extended
// \u2190-\u23FA\u2500-\u2BD1 misc symbols
// \u2E80-\u32FF CJK symbols
// \u3400-\u9FFF CJK
// \uF900-\uFAFF\uFE00-\uFE6F CJK extended
name = name.replace(/[^a-zA-Z0-9 /\\.~()<>^*%&=+$@#_'?!"\u00A1-\u00BF\u00D7\u00F7\u02B9-\u0362\u2012-\u2027\u2030-\u205E\u2050-\u205F\u2190-\u23FA\u2500-\u2BD1\u2E80-\u32FF\u3400-\u9FFF\uF900-\uFAFF\uFE00-\uFE6F-]+/g, '');
// blacklist
// \u00a1 upside-down exclamation mark (i)
// \u2580-\u2590 black bars
// \u25A0\u25Ac\u25AE\u25B0 black bars
// \u534d\u5350 swastika
// \u2a0d crossed integral (f)
name = name.replace(/[\u00a1\u2580-\u2590\u25A0\u25Ac\u25AE\u25B0\u2a0d\u534d\u5350]/g, '');
// e-mail address
if (name.includes('@') && name.includes('.')) return '';
// url
if (/[a-z0-9]\.(com|net|org)/.test(name)) name = name.replace(/\./g, '');
// Limit the amount of symbols allowed in usernames to 4 maximum, and disallow (R) and (C) from being used in the middle of names.
let nameSymbols = name.replace(/[^\u00A1-\u00BF\u00D7\u00F7\u02B9-\u0362\u2012-\u2027\u2030-\u205E\u2050-\u205F\u2090-\u23FA\u2500-\u2BD1]+/g, '');
// \u00ae\u00a9 (R) (C)
if (nameSymbols.length > 4 || /[^a-z0-9][a-z0-9][^a-z0-9]/.test(name.toLowerCase() + ' ') || /[\u00ae\u00a9].*[a-zA-Z0-9]/.test(name)) name = name.replace(/[\u00A1-\u00BF\u00D7\u00F7\u02B9-\u0362\u2012-\u2027\u2030-\u205E\u2050-\u205F\u2190-\u23FA\u2500-\u2BD1\u2E80-\u32FF\u3400-\u9FFF\uF900-\uFAFF\uFE00-\uFE6F]+/g, '').replace(/[^A-Za-z0-9]{2,}/g, ' ').trim();
}
name = name.replace(/^[^A-Za-z0-9]+/, ""); // remove symbols from start
// cut name length down to 18 chars
if (/[A-Za-z0-9]/.test(name.slice(18))) {
name = name.replace(/[^A-Za-z0-9]+/g, "");
} else {
name = name.slice(0, 18);
}
name = Dex.getName(name);
for (const filter of Chat.namefilters) {
name = filter(name, user);
if (!name) return '';
}
return name;
};
/**@type {((host: string, user: User, connection: Connection) => void)[]} */
Chat.hostfilters = [];
/**
* @param {string} host
* @param {User} user
* @param {Connection} connection
*/
Chat.hostfilter = function (host, user, connection) {
for (const filter of Chat.hostfilters) {
filter(host, user, connection);
}
};
/**@type {((user: User, oldUser: User | null, usertype: string) => void)[]} */
Chat.loginfilters = [];
/**
* @param {User} user
* @param {User?} oldUser
* @param {string} usertype
*/
Chat.loginfilter = function (user, oldUser, usertype) {
for (const filter of Chat.loginfilters) {
filter(user, oldUser, usertype);
}
};
/**@type {NameFilter[]} */
Chat.nicknamefilters = [];
/**
* @param {string} nickname
* @param {User} user
*/
Chat.nicknamefilter = function (nickname, user) {
for (const filter of Chat.nicknamefilters) {
nickname = filter(nickname, user);
if (!nickname) return '';
}
return nickname;
};
/*********************************************************
* Parser
*********************************************************/
class CommandContext {
/**
* @param {{message: string, room: Room, user: User, connection: Connection, pmTarget?: User, cmd?: string, cmdToken?: string, target?: string, fullCmd?: string}} options
*/
constructor(options) {
this.message = options.message || ``;
this.recursionDepth = 0;
// message context
this.room = options.room;
this.user = options.user;
this.connection = options.connection;
this.pmTarget = options.pmTarget;
// command context
this.cmd = options.cmd || '';
this.cmdToken = options.cmdToken || '';
this.target = options.target || ``;
this.fullCmd = options.fullCmd || '';
// broadcast context
this.broadcasting = false;
this.broadcastToRoom = true;
// target user
this.targetUser = null;
this.targetUsername = "";
this.inputUsername = "";
}
/**
* @param {string} [msg]
* @return {any}
*/
parse(msg) {
if (typeof msg === 'string') {
// spawn subcontext
let subcontext = new CommandContext(this);
subcontext.recursionDepth++;
if (subcontext.recursionDepth > MAX_PARSE_RECURSION) {
throw new Error("Too much command recursion");
}
subcontext.message = msg;
return subcontext.parse();
}
/** @type {any} */
let message = this.message;
let giveExp = false;
let commandHandler = this.splitCommand(message);
if (typeof commandHandler === 'function') {
message = this.run(commandHandler);
} else {
if (commandHandler === '!') {
if (this.room === Rooms.global) {
return this.popupReply(`You tried use "${message}" as a global command, but it is not a global command.`);
} else if (this.room) {
return this.popupReply(`You tried to send "${message}" to the room "${this.room.id}" but it failed because you were not in that room.`);
}
return this.errorReply(`The command "${this.cmdToken}${this.fullCmd}" is unavailable in private messages. To send a message starting with "${this.cmdToken}${this.fullCmd}", type "${this.cmdToken}${this.cmdToken}${this.fullCmd}".`);
}
if (this.cmdToken) {
// To guard against command typos, show an error message
if (this.cmdToken === BROADCAST_TOKEN) {
if (/[a-z0-9]/.test(this.cmd.charAt(0))) {
return this.errorReply(`The command "${this.cmdToken}${this.fullCmd}" does not exist.`);
}
} else {
return this.errorReply(`The command "${this.cmdToken}${this.fullCmd}" does not exist. To send a message starting with "${this.cmdToken}${this.fullCmd}", type "${this.cmdToken}${this.cmdToken}${this.fullCmd}".`);
}
} else if (!VALID_COMMAND_TOKENS.includes(message.charAt(0)) && VALID_COMMAND_TOKENS.includes(message.trim().charAt(0))) {
message = message.trim();
if (message.charAt(0) !== BROADCAST_TOKEN) {
message = message.charAt(0) + message;
}
}
let lastMessageTime = this.user.lastMessageTime;
message = this.canTalk(message);
if (message && Date.now() > (lastMessageTime + Config.expTimer)) giveExp = true;
}
// Output the message
if (message && message !== true && typeof message.then !== 'function') {
if (this.pmTarget) {
Chat.sendPM(message, this.user, this.pmTarget);
} else {
let emoticons = Server.parseEmoticons(message);
if (emoticons && !this.room.disableEmoticons) {
if (Users.ShadowBan.checkBanned(this.user)) {
Users.ShadowBan.addMessage(this.user, "To " + this.room.id, message);
if (!Server.ignoreEmotes[this.user.userid]) this.user.sendTo(this.room, (this.room.type === 'chat' ? '|c:|' + (~~(Date.now() / 1000)) + '|' : '|c|') + this.user.getIdentity(this.room.id) + '|/html ' + emoticons);
if (Server.ignoreEmotes[this.user.userid]) this.user.sendTo(this.room, (this.room.type === 'chat' ? '|c:|' + (~~(Date.now() / 1000)) + '|' : '|c|') + this.user.getIdentity(this.room.id) + '|' + message);
this.room.update();
return false;
}
for (let u in this.room.users) {
let curUser = Users(u);
if (!curUser || !curUser.connected) continue;
if (Server.ignoreEmotes[curUser.userid]) {
curUser.sendTo(this.room, (this.room.type === 'chat' ? '|c:|' + (~~(Date.now() / 1000)) + '|' : '|c|') + this.user.getIdentity(this.room.id) + '|' + message);
continue;
}
curUser.sendTo(this.room, (this.room.type === 'chat' ? '|c:|' + (~~(Date.now() / 1000)) + '|' : '|c|') + this.user.getIdentity(this.room.id) + '|/html ' + emoticons);
}
this.room.log.log.push((this.room.type === 'chat' ? (this.room.type === 'chat' ? '|c:|' + (~~(Date.now() / 1000)) + '|' : '|c|') : '|c|') + this.user.getIdentity(this.room.id) + '|' + message);
this.room.lastUpdate = this.room.log.length;
this.room.messageCount++;
} else {
if (Users.ShadowBan.checkBanned(this.user)) {
Users.ShadowBan.addMessage(this.user, "To " + this.room.id, message);
this.user.sendTo(this.room, (this.room.type === 'chat' ? '|c:|' + (~~(Date.now() / 1000)) + '|' : '|c|') + this.user.getIdentity(this.room.id) + '|' + message);
} else {
this.room.add((this.room.type === 'chat' ? (this.room.type === 'chat' ? '|c:|' + (~~(Date.now() / 1000)) + '|' : '|c|') : '|c|') + this.user.getIdentity(this.room.id) + '|' + message);
this.room.messageCount++;
}
}
//this.room.add(`|c|${this.user.getIdentity(this.room.id)}|${message}`);
}
}
if (this.user.registered && giveExp) Server.ExpControl.addExp(this.user.userid, this.room, 1);
this.update();
return message;
}
/**
* @param {string} message
* @param {boolean} recursing
* @return {'!' | undefined | Function}
*/
splitCommand(message = this.message, recursing = false) {
this.cmd = '';
this.cmdToken = '';
this.target = '';
if (!message || !message.trim().length) return;
// hardcoded commands
if (message.startsWith(`>> `)) {
message = `/eval ${message.slice(3)}`;
} else if (message.startsWith(`>>> `)) {
message = `/evalbattle ${message.slice(4)}`;
} else if (message.startsWith(`/me`) && /[^A-Za-z0-9 ]/.test(message.charAt(3))) {
message = `/mee ${message.slice(3)}`;
} else if (message.startsWith(`/ME`) && /[^A-Za-z0-9 ]/.test(message.charAt(3))) {
message = `/MEE ${message.slice(3)}`;
}
let cmdToken = message.charAt(0);
if (!VALID_COMMAND_TOKENS.includes(cmdToken)) return;
if (cmdToken === message.charAt(1)) return;
if (cmdToken === BROADCAST_TOKEN && /[^A-Za-z0-9]/.test(message.charAt(1))) return;
let cmd = '', target = '';
let spaceIndex = message.indexOf(' ');
if (spaceIndex > 0) {
cmd = message.slice(1, spaceIndex).toLowerCase();
target = message.slice(spaceIndex + 1);
} else {
cmd = message.slice(1).toLowerCase();
target = '';
}
if (cmd.endsWith(',')) cmd = cmd.slice(0, -1);
let curCommands = Chat.commands;
let commandHandler;
let fullCmd = cmd;
do {
if (curCommands.hasOwnProperty(cmd)) {
commandHandler = curCommands[cmd];
} else {
commandHandler = undefined;
}
if (typeof commandHandler === 'string') {
// in case someone messed up, don't loop
commandHandler = curCommands[commandHandler];
} else if (Array.isArray(commandHandler) && !recursing) {
return this.splitCommand(cmdToken + 'help ' + fullCmd.slice(0, -4), true);
}
if (commandHandler && typeof commandHandler === 'object') {
let spaceIndex = target.indexOf(' ');
if (spaceIndex > 0) {
cmd = target.substr(0, spaceIndex).toLowerCase();
target = target.substr(spaceIndex + 1);
} else {
cmd = target.toLowerCase();
target = '';
}
fullCmd += ' ' + cmd;
// @ts-ignore
curCommands = commandHandler;
}
} while (commandHandler && typeof commandHandler === 'object');
if (!commandHandler && curCommands.default) {
commandHandler = curCommands.default;
if (typeof commandHandler === 'string') {
commandHandler = curCommands[commandHandler];
}
}
if (!commandHandler && !recursing) {
for (let g in Config.groups) {
let groupid = Config.groups[g].id;
if (fullCmd === groupid) {
return this.splitCommand(`/promote ${target}, ${g}`, true);
} else if (fullCmd === 'global' + groupid) {
return this.splitCommand(`/globalpromote ${target}, ${g}`, true);
} else if (fullCmd === 'de' + groupid || fullCmd === 'un' + groupid || fullCmd === 'globalde' + groupid || fullCmd === 'deglobal' + groupid) {
return this.splitCommand(`/demote ${target}`, true);
} else if (fullCmd === 'room' + groupid) {
return this.splitCommand(`/roompromote ${target}, ${g}`, true);
} else if (fullCmd === 'forceroom' + groupid) {
return this.splitCommand(`/roompromote !!!${target}, ${g}`, true);
} else if (fullCmd === 'roomde' + groupid || fullCmd === 'deroom' + groupid || fullCmd === 'roomun' + groupid) {
return this.splitCommand(`/roomdemote ${target}`, true);
}
}
}
this.cmd = cmd;
this.cmdToken = cmdToken;
this.target = target;
this.fullCmd = fullCmd;
const requireGlobalCommand = (
this.pmTarget ||
this.room === Rooms.global ||
(this.room && !(this.user.userid in this.room.users))
);
if (typeof commandHandler === 'function' && requireGlobalCommand) {
const baseCmd = typeof curCommands[cmd] === 'string' ? curCommands[cmd] : cmd;
if (!curCommands['!' + baseCmd]) {
return '!';
}
}
// @ts-ignore
return commandHandler;
}
/**
* @param {string | {call: Function}} commandHandler
*/
run(commandHandler) {
// @ts-ignore
if (typeof commandHandler === 'string') commandHandler = Chat.commands[commandHandler];
let result;
try {
// @ts-ignore
result = commandHandler.call(this, this.target, this.room, this.user, this.connection, this.cmd, this.message);
} catch (err) {
Monitor.crashlog(err, 'A chat command', {
user: this.user.name,
room: this.room && this.room.id,
pmTarget: this.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>`);
}
if (result === undefined) result = false;
return result;
}
/**
* @param {BasicChatRoom | undefined?} room
* @param {User} user
* @param {string} message
*/
checkFormat(room, user, message) {
if (!room) return true;
if (!room.filterStretching && !room.filterCaps && !room.filterEmojis) return true;
if (user.can('bypassall')) return true;
if (room.filterStretching && user.name.match(/(.+?)\1{5,}/i)) {
return this.errorReply(`Your username contains too much stretching, which this room doesn't allow.`);
}
if (room.filterCaps && user.name.match(/[A-Z\s]{6,}/)) {
return this.errorReply(`Your username contains too many capital letters, which this room doesn't allow.`);
}
if (room.filterEmojis && user.name.match(emojiRegex)) {
return this.errorReply(`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.filterStretching && message.match(/(.+?)\1{7,}/i)) {
return this.errorReply(`Your message contains too much stretching, which this room doesn't allow.`);
}
if (room.filterCaps && message.match(/[A-Z\s]{18,}/)) {
return this.errorReply(`Your message contains too many capital letters, which this room doesn't allow.`);
}
if (room.filterEmojis && message.match(emojiRegex)) {
return this.errorReply(`Your message contains emojis, which this room doesn't allow.`);
}
return true;
}
/**
* @param {BasicChatRoom | undefined?} room
* @param {User} user
*/
checkSlowchat(room, user) {
if (!room || !room.slowchat) return true;
if (user.can('broadcast', null, room)) return true;
let lastActiveSeconds = (Date.now() - user.lastMessageTime) / 1000;
if (lastActiveSeconds < room.slowchat) return false;
return true;
}
/**
* @param {BasicChatRoom | undefined?} room
* @param {string} message
*/
checkBanwords(room, message) {
if (!room) return true;
if (!room.banwordRegex) {
if (room.banwords && room.banwords.length) {
room.banwordRegex = new RegExp('(?:\\b|(?!\\w))(?:' + room.banwords.join('|') + ')(?:\\b|\\B(?!\\w))', 'i');
} else {
room.banwordRegex = true;
}
}
if (!message) return true;
if (room.banwordRegex !== true && room.banwordRegex.test(message)) {
return false;
}
return true;
}
checkGameFilter() {
if (!this.room || !this.room.game || !this.room.game.onChatMessage) return false;
return this.room.game.onChatMessage(this.message, this.user);
}
/**
* @param {string} message
*/
pmTransform(message) {
if (!this.pmTarget && this.room !== Rooms.global) throw new Error(`Not a PM`);
const targetIdentity = this.pmTarget ? this.pmTarget.getIdentity() : '~';
const prefix = `|pm|${this.user.getIdentity()}|${targetIdentity}|`;
return message.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(`|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);
}
return prefix + `/text ` + message;
}).join(`\n`);
}
/**
* @param {string} data
*/
sendReply(data) {
if (this.broadcasting && this.broadcastToRoom) {
// broadcasting
this.add(data);
} else {
// not broadcasting
if (this.pmTarget || this.room === Rooms.global) {
data = this.pmTransform(data);
this.connection.send(data);
} else {
this.connection.sendTo(this.room, data);
}
}
}
/**
* @param {string} message
*/
errorReply(message) {
this.sendReply(`|error|` + message.replace(/\n/g, `\n|error|`));
}
/**
* @param {string} html
*/
addBox(html) {
this.add(`|html|<div class="infobox">${html}</div>`);
}
/**
* @param {string} html
*/
sendReplyBox(html) {
this.sendReply(`|html|<div class="infobox">${html}</div>`);
}
/**
* @param {string} message
*/
popupReply(message) {
this.connection.popup(message);
}
/**
* @param {string} data
*/
add(data) {
if (this.pmTarget) {
data = this.pmTransform(data);
this.user.send(data);
if (this.pmTarget !== this.user) this.pmTarget.send(data);
return;
}
this.room.add(data);
}
/**
* @param {string} data
*/
send(data) {
if (this.pmTarget) {
data = this.pmTransform(data);
this.user.send(data);
if (this.pmTarget !== this.user) this.pmTarget.send(data);
return;
}
this.room.send(data);
}
/**
* @param {string} data
*/
sendModCommand(data) {
this.room.sendModsByUser(this.user, data);
}
privateModCommand() {
throw new Error(`this.privateModCommand has been renamed to this.privateModAction, which no longer writes to modlog.`);
}
/**
* @param {string} msg
*/
privateModAction(msg) {
this.room.sendMods(msg);
this.roomlog(msg);
}
/**
* @param {string} action
* @param {string | User?} user
* @param {string} note
*/
globalModlog(action, user, note) {
let buf = `(${this.room.id}) ${action}: `;
if (user) {
if (typeof user === 'string') {
buf += `[${user}]`;
} else {
let userid = user.getLastId();
buf += `[${userid}]`;
if (user.autoconfirmed && user.autoconfirmed !== userid) buf += ` ac:[${user.autoconfirmed}]`;
const alts = user.getAltUsers(false, true).slice(1).map(user => user.getLastId()).join('], [');
if (alts.length) buf += ` alts:[${alts}]`;
buf += ` [${user.latestIp}]`;
}
}
buf += note;
Rooms.global.modlog(buf);
this.room.modlog(buf);
}
/**
* @param {string} action
* @param {string | User?} [user]
* @param {string?} [note]
* @param {object} options
*/
modlog(action, user = null, note = null, options = {}) {
let buf = `(${this.room.id}) ${action}: `;
if (user) {
if (typeof user === 'string') {
buf += `[${toId(user)}]`;
} else {
let userid = user.getLastId();
buf += `[${userid}]`;
if (!options.noalts) {
if (user.autoconfirmed && user.autoconfirmed !== userid) buf += ` ac:[${user.autoconfirmed}]`;
const alts = user.getAltUsers(false, true).slice(1).map(user => user.getLastId()).join('], [');
if (alts.length) buf += ` alts:[${alts}]`;
}
if (!options.noip) buf += ` [${user.latestIp}]`;
}
}
buf += ` by ${this.user.userid}`;
if (note) buf += `: ${note}`;
this.room.modlog(buf);
}
/**
* @param {string} data
*/
roomlog(data) {
if (this.pmTarget) return;
this.room.roomlog(data);
}
logEntry() {
throw new Error(`this.logEntry has been renamed to this.roomlog.`);
}
addModCommand() {
throw new Error(`this.addModCommand has been renamed to this.addModAction, which no longer writes to modlog.`);
}
/**
* @param {string} msg
*/
addModAction(msg) {
this.room.addByUser(this.user, msg);
}
update() {
if (this.room) this.room.update();
}
/**
* @param {string} permission
* @param {string | User?} target
* @param {BasicChatRoom?} room
*/
can(permission, target = null, room = null) {
if (!this.user.can(permission, target, room)) {
this.errorReply(this.cmdToken + this.fullCmd + " - Access denied.");
return false;
}
return true;
}
/**
* @param {?boolean} ignoreCooldown
* @param {?string} suppressMessage
*/
canBroadcast(ignoreCooldown, suppressMessage) {
if (this.room instanceof Rooms.GlobalRoom) return false;
if (!this.broadcasting && this.cmdToken === BROADCAST_TOKEN) {
if (!this.pmTarget && !this.user.can('broadcast', null, this.room)) {
this.errorReply("You need to be voiced to broadcast this command's information.");
this.errorReply("To see it for yourself, use: /" + this.message.substr(1));
return false;
}
// broadcast cooldown
const broadcastMessage = (suppressMessage || this.message).toLowerCase().replace(/[^a-z0-9\s!,]/g, '');
if (!ignoreCooldown && this.room && this.room.lastBroadcast === broadcastMessage &&
this.room.lastBroadcastTime >= Date.now() - BROADCAST_COOLDOWN &&
!this.user.can('bypassall')) {
this.errorReply("You can't broadcast this because it was just broadcasted.");
return false;
}
const message = this.canTalk(suppressMessage || this.message);
if (!message) return false;
this.message = message;
this.broadcastMessage = broadcastMessage;
}
return true;
}
/**
* @param {boolean} [ignoreCooldown = false]
* @param {?string} [suppressMessage = null]
*/
runBroadcast(ignoreCooldown = false, suppressMessage = null) {
if (this.broadcasting || this.cmdToken !== BROADCAST_TOKEN) {
// Already being broadcast, or the user doesn't intend to broadcast.
return true;
}
if (!this.broadcastMessage) {
// Permission hasn't been checked yet. Do it now.
if (!this.canBroadcast(ignoreCooldown, suppressMessage)) return false;
}
this.broadcasting = true;
if (this.pmTarget) {
this.sendReply('|c~|' + (suppressMessage || this.message));
} else {
this.sendReply('|c|' + this.user.getIdentity(this.room.id) + '|' + (suppressMessage || this.message));
}
if (!ignoreCooldown && !this.pmTarget) {
// @ts-ignore this.broadcastMessage is initialized above in this.canBroadcast, or we don't get this far
this.room.lastBroadcast = this.broadcastMessage;
this.room.lastBroadcastTime = Date.now();
}
return true;
}
/**
* @param {string} text
*/
meansYes(text) {
switch (text.toLowerCase().trim()) {
case 'on': case 'enable': case 'yes': case 'true':
return true;
}
return false;
}
/**
* @param {string} text
*/
meansNo(text) {
switch (text.toLowerCase().trim()) {
case 'off': case 'disable': case 'no': case 'false':
return true;
}
return false;
}
/**
* @param {string?} message
* @param {BasicChatRoom?} [room]
* @param {User?} [targetUser]
*/
canTalk(message = null, room = null, targetUser = null) {
if (!targetUser && this.pmTarget) {
targetUser = this.pmTarget;
}
if (targetUser) {
room = null;
} else if (!room) {
if (this.room.id === 'global') {
this.connection.popup(`Your message could not be sent:\n\n${message}\n\nIt needs to be sent to a user or room.`);
return false;
}
// @ts-ignore
room = this.room;
}
let user = this.user;
let connection = this.connection;
if (!user.named) {
connection.popup(`You must choose a name before you can talk.`);
return false;
}
if (!user.can('bypassall')) {
let lockType = (user.namelocked ? `namelocked` : user.locked ? `locked` : ``);
let lockExpiration = Punishments.checkLockExpiration(user.namelocked || user.locked);
if (room) {
if (lockType && !room.isHelp) {
this.errorReply(`You are ${lockType} and can't talk in chat. ${lockExpiration}`);
this.sendReply(`|html|<a href="view-help-request--appeal" class="button">Get help with this</a>`);
return false;
}
if (room.isMuted(user)) {
this.errorReply(`You are muted and cannot talk in this room.`);
return false;
}
if (room.modchat && !user.authAtLeast(room.modchat, room)) {
if (room.modchat === 'autoconfirmed') {
this.errorReply(`Because moderated chat is set, your account must be at least one week old and you must have won at least one ladder game to speak in this room.`);
return false;
}
if (room.modchat === 'trusted') {
this.errorReply(`Because moderated chat is set, your account must be staff in a public room or have a global rank to speak in this room.`);
return false;
}
const groupName = Config.groups[room.modchat] && Config.groups[room.modchat].name || room.modchat;
this.errorReply(`Because moderated chat is set, you must be of rank ${groupName} or higher to speak in this room.`);
return false;
}
if (!(user.userid in room.users)) {
connection.popup(`You can't send a message to this room without being in it.`);
return false;
}
}
if (targetUser) {
if (lockType && !targetUser.can('lock')) {
return this.errorReply(`You are ${lockType} and can only private message members of the global moderation team (users marked by @ or above in the Help room). ${lockExpiration}`);
}
if (targetUser.locked && !user.can('lock')) {
return this.errorReply(`The user "${targetUser.name}" is locked and cannot be PMed.`);
}
if (Config.pmmodchat && !user.authAtLeast(Config.pmmodchat) && !targetUser.canPromote(user.group, Config.pmmodchat)) {
let groupName = Config.groups[Config.pmmodchat] && Config.groups[Config.pmmodchat].name || Config.pmmodchat;
return this.errorReply(`On this server, you must be of rank ${groupName} or higher to PM users.`);
}
if (targetUser.ignorePMs && targetUser.ignorePMs !== user.group && !user.can('lock')) {
if (!targetUser.can('lock')) {
return this.errorReply(`This user is blocking private messages right now.`);
} else {
this.errorReply(`This ${Config.groups[targetUser.group].name} is too busy to answer private messages right now. Please contact a different staff member.`);
return this.sendReply(`|html|If you need help, try opening a <a href="view-help-request" class="button">help ticket</a>`);
}
}
if (user.ignorePMs && user.ignorePMs !== targetUser.group && !targetUser.can('lock')) {
return this.errorReply(`You are blocking private messages right now.`);
}
}
}
if (typeof message !== 'string') return true;
if (!message) {
connection.popup("Your message can't be blank.");
return false;
}
let length = message.length;
length += 10 * message.replace(/[^\ufdfd]*/g, '').length;
if (length > MAX_MESSAGE_LENGTH && !user.can('ignorelimits')) {
this.errorReply("Your message is too long: " + message);
return false;
}
// remove zalgo
message = message.replace(/[\u0300-\u036f\u0483-\u0489\u0610-\u0615\u064B-\u065F\u0670\u06D6-\u06DC\u06DF-\u06ED\u0E31\u0E34-\u0E3A\u0E47-\u0E4E]{3,}/g, '');
if (/[\u115f\u1160\u239b-\u23b9]/.test(message)) {
this.errorReply("Your message contains banned characters.");
return false;
}
// If the corresponding config option is set, non-AC users cannot send links, except to staff.
if (Config.restrictLinks && !user.autoconfirmed) {
const links = message.match(Chat.linkRegex);
const allLinksWhitelisted = !links || links.every(link => {
link = link.toLowerCase();
const domainMatches = /^(?:http:\/\/|https:\/\/)?(?:[^/]*\.)?([^/.]*\.[^/.]*)\.?($|\/|:)/.exec(link);
const domain = domainMatches && domainMatches[1];
const hostMatches = /^(?:http:\/\/|https:\/\/)?([^/]*[^/.])\.?($|\/|:)/.exec(link);
let host = hostMatches && hostMatches[1];
if (host && host.startsWith('www.')) host = host.slice(4);
if (!domain || !host) return false;
return LINK_WHITELIST.includes(host) || LINK_WHITELIST.includes(`*.${domain}`);
});
if (!allLinksWhitelisted && !(targetUser && targetUser.can('lock'))) {
this.errorReply("Your account must be autoconfirmed to send links to other users, except for global staff.");
return false;
}
}
if (!this.checkFormat(room, user, message)) {
return false;
}
if (!this.checkSlowchat(room, user)) {
// @ts-ignore ~ The truthiness of room and room.slowchat are evaluated in checkSlowchat
this.errorReply(`This room has slow-chat enabled. You can only talk once every ${room.slowchat} seconds.`);
return false;
}
if (!this.checkBanwords(room, user.name) && !user.can('bypassall')) {
this.errorReply(`Your username contains a phrase banned by this room.`);
return false;