forked from smogon/pokemon-showdown-client
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathclient-chat.js
1704 lines (1581 loc) · 56.8 KB
/
client-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
(function ($) {
var ConsoleRoom = this.ConsoleRoom = Room.extend({
type: 'chat',
title: '',
constructor: function () {
if (!this.events) this.events = {};
if (!this.events['click .username']) this.events['click .username'] = 'clickUsername';
if (!this.events['submit form']) this.events['submit form'] = 'submit';
if (!this.events['keydown textarea']) this.events['keydown textarea'] = 'keyDown';
if (!this.events['keyup textarea']) this.events['keyup textarea'] = 'keyUp';
if (!this.events['focus textarea']) this.events['focus textarea'] = 'focusText';
if (!this.events['blur textarea']) this.events['blur textarea'] = 'blurText';
if (!this.events['click .spoiler']) this.events['click .spoiler'] = 'clickSpoiler';
if (!this.events['click .message-pm i']) this.events['click .message-pm i'] = 'openPM';
this.initializeTabComplete();
// create up/down history for this room
this.chatHistory = new ChatHistory();
// this MUST set up this.$chatAdd
Room.apply(this, arguments);
app.user.on('change', this.updateUser, this);
this.updateUser();
},
updateUser: function () {
var name = app.user.get('name');
var userid = app.user.get('userid');
if (this.expired) {
this.$chatAdd.text(this.expired === true ? 'This room is expired' : this.expired);
this.$chatbox = null;
} else if (!name) {
this.$chatAdd.html('Connecting...');
this.$chatbox = null;
} else if (!app.user.get('named')) {
this.$chatAdd.html('<form><button name="login">Join chat</button></form>');
this.$chatbox = null;
} else {
this.$chatAdd.html('<form class="chatbox"><label style="' + hashColor(userid) + '">' + Tools.escapeHTML(name) + ':</label> <textarea class="textbox" type="text" size="70" autocomplete="off"></textarea></form>');
this.$chatbox = this.$chatAdd.find('textarea');
this.$chatbox.autoResize({
animate: false,
extraSpace: 0
});
if (this === app.curSideRoom || this === app.curRoom) {
this.$chatbox.focus();
}
}
},
focus: function () {
if (this.$chatbox) {
this.$chatbox.focus();
} else {
this.$('button[name=login]').focus();
}
},
focusText: function () {
if (this.$chatbox) {
var rooms = app.roomList.concat(app.sideRoomList);
var roomIndex = rooms.indexOf(this);
var roomLeft = rooms[roomIndex - 1];
var roomRight = rooms[roomIndex + 1];
if (roomLeft || roomRight) {
this.$chatbox.attr('placeholder', " " + (roomLeft ? "\u2190 " + roomLeft.title : '') + (app.arrowKeysUsed ? " | " : " (use arrow keys) ") + (roomRight ? roomRight.title + " \u2192" : ''));
} else {
this.$chatbox.attr('placeholder', "");
}
}
},
blurText: function () {
if (this.$chatbox) {
this.$chatbox.attr('placeholder', "");
}
},
clickSpoiler: function (e) {
$(e.currentTarget).toggleClass('spoiler-shown');
},
login: function () {
app.addPopup(LoginPopup);
},
submit: function (e) {
e.preventDefault();
e.stopPropagation();
var text = this.$chatbox.val();
if (!text) return;
if (!$.trim(text)) {
this.$chatbox.val('');
return;
}
this.tabComplete.reset();
this.chatHistory.push(text);
text = this.parseCommand(text);
if (this.battle && this.battle.ignoreSpects && app.user.get('userid') !== this.battle.p1.id && app.user.get('userid') !== this.battle.p2.id) {
this.add("You can't chat in this battle as you're currently ignoring spectators");
} else if (text.length > 80000) {
app.addPopupMessage("Your message is too long.");
return;
} else if (text) {
this.send(text);
}
this.$chatbox.val('');
this.$chatbox.trigger('keyup'); // force a resize
},
keyUp: function (e) {
// Android Chrome compose keycode
// Android Chrome no longer sends keyCode 13 when Enter is pressed on
// the soft keyboard, resulting in this annoying hack.
// https://bugs.chromium.org/p/chromium/issues/detail?id=118639#c232
if (!e.shiftKey && e.keyCode === 229 && this.$chatbox.val().slice(-1) === '\n') {
this.submit(e);
}
},
keyDown: function (e) {
var cmdKey = (((e.cmdKey || e.metaKey) ? 1 : 0) + (e.ctrlKey ? 1 : 0) === 1) && !e.altKey && !e.shiftKey;
var textbox = e.currentTarget;
if (e.keyCode === 13 && !e.shiftKey) { // Enter key
this.submit(e);
} else if (e.keyCode === 73 && cmdKey) { // Ctrl + I key
if (ConsoleRoom.toggleFormatChar(textbox, '_')) {
e.preventDefault();
e.stopPropagation();
}
} else if (e.keyCode === 66 && cmdKey) { // Ctrl + B key
if (ConsoleRoom.toggleFormatChar(textbox, '*')) {
e.preventDefault();
e.stopPropagation();
}
} else if (e.keyCode === 33) { // Pg Up key
this.$chatFrame.scrollTop(this.$chatFrame.scrollTop() - this.$chatFrame.height() + 60);
} else if (e.keyCode === 34) { // Pg Dn key
this.$chatFrame.scrollTop(this.$chatFrame.scrollTop() + this.$chatFrame.height() - 60);
} else if (e.keyCode === 9 && !e.ctrlKey) { // Tab key
if (!e.shiftKey) {
if (this.handleTabComplete(this.$chatbox, false)) {
e.preventDefault();
e.stopPropagation();
}
} else { // Shift + Tab
if (this.handleTabComplete(this.$chatbox, true)) {
e.preventDefault();
e.stopPropagation();
}
}
} else if (e.keyCode === 38 && !e.shiftKey && !e.altKey) { // Up key
if (this.chatHistoryUp(this.$chatbox, e)) {
e.preventDefault();
e.stopPropagation();
}
} else if (e.keyCode === 40 && !e.shiftKey && !e.altKey) { // Down key
if (this.chatHistoryDown(this.$chatbox, e)) {
e.preventDefault();
e.stopPropagation();
}
} else if (app.user.lastPM && (textbox.value === '/reply' || textbox.value === '/r' || textbox.value === '/R') && e.keyCode === 32) { // '/reply ' is being written
e.preventDefault();
e.stopPropagation();
var val = '/pm ' + app.user.lastPM + ', ';
textbox.value = val;
e.setSelectionRange(val.length, val.length);
}
},
clickUsername: function (e) {
e.stopPropagation();
e.preventDefault();
var position;
if (e.currentTarget.className === 'userbutton username') {
position = 'right';
}
var name = $(e.currentTarget).data('name') || $(e.currentTarget).text();
app.addPopup(UserPopup, {name: name, sourceEl: e.currentTarget, position: position});
},
openPM: function (e) {
e.preventDefault();
e.stopPropagation();
app.focusRoom('');
app.rooms[''].focusPM($(e.currentTarget).data('name'));
},
clear: function () {
if (this.$chat) this.$chat.html('');
},
// support for buttons that can be sent by the server:
joinRoom: function (room) {
app.joinRoom(room);
},
avatars: function () {
app.addPopup(AvatarsPopup);
},
openSounds: function () {
app.addPopup(SoundsPopup, {type: 'semimodal'});
},
openOptions: function () {
app.addPopup(OptionsPopup, {type: 'semimodal'});
},
// highlight
getHighlight: function (message) {
var highlights = Tools.prefs('highlights') || [];
if (!app.highlightRegExp) {
try {
this.updateHighlightRegExp(highlights);
} catch (e) {
// If the expression above is not a regexp, we'll get here.
// Don't throw an exception because that would prevent the chat
// message from showing up, or, when the lobby is initialising,
// it will prevent the initialisation from completing.
return false;
}
}
if (!Tools.prefs('noselfhighlight') && app.user.nameRegExp) {
if (app.user.nameRegExp.test(message)) return true;
}
return ((highlights.length > 0) && app.highlightRegExp.test(message));
},
updateHighlightRegExp: function (highlights) {
// Enforce boundary for match sides, if a letter on match side is
// a word character. For example, regular expression "a" matches
// "a", but not "abc", while regular expression "!" matches
// "!" and "!abc".
app.highlightRegExp = new RegExp('(?:\\b|(?!\\w))(?:' + highlights.join('|') + ')(?:\\b|\\B(?!\\w))', 'i');
},
// chat history
chatHistory: null,
chatHistoryUp: function ($textbox, e) {
var idx = +$textbox.prop('selectionStart');
var line = $textbox.val();
if (e && !e.ctrlKey && idx !== 0 && idx !== line.length) return false;
if (this.chatHistory.index === 0) return false;
$textbox.val(this.chatHistory.up(line));
return true;
},
chatHistoryDown: function ($textbox, e) {
var idx = +$textbox.prop('selectionStart');
var line = $textbox.val();
if (e && !e.ctrlKey && idx !== 0 && idx !== line.length) return false;
$textbox.val(this.chatHistory.down(line));
return true;
},
// tab completion
initializeTabComplete: function () {
this.tabComplete = {
candidates: null,
index: 0,
prefix: null,
cursor: null,
reset: function () {
this.cursor = null;
}
};
this.userActivity = [];
},
markUserActive: function (userid) {
var idx = this.userActivity.indexOf(userid);
if (idx !== -1) {
this.userActivity.splice(idx, 1);
}
this.userActivity.push(userid);
if (this.userActivity.length > 100) {
// Prune the list.
this.userActivity.splice(0, 20);
}
},
tabComplete: null,
userActivity: null,
handleTabComplete: function ($textbox, reverse) {
// Don't tab complete at the start of the text box.
var idx = $textbox.prop('selectionStart');
if (idx === 0) return false;
var users = this.users || (app.rooms['lobby'] ? app.rooms['lobby'].users : {});
var text = $textbox.val();
if (this.tabComplete.cursor !== null && text.substr(0, idx) === this.tabComplete.cursor) {
// The user is cycling through the candidate names.
if (reverse) {
this.tabComplete.index--;
} else {
this.tabComplete.index++;
}
if (this.tabComplete.index >= this.tabComplete.candidates.length) this.tabComplete.index = 0;
if (this.tabComplete.index < 0) this.tabComplete.index = this.tabComplete.candidates.length - 1;
} else {
// This is a new tab completion.
// There needs to be non-whitespace to the left of the cursor.
var m1 = /^(.*?)([A-Za-z0-9][^, ]*)$/.exec(text.substr(0, idx));
var m2 = /^(.*?)([A-Za-z0-9][^, ]* [^, ]*)$/.exec(text.substr(0, idx));
if (!m1 && !m2) return true;
this.tabComplete.prefix = text;
var idprefix = (m1 ? toId(m1[2]) : '');
var spaceprefix = (m2 ? m2[2].replace(/[^A-Za-z0-9 ]+/g, '').toLowerCase() : '');
var candidates = []; // array of [candidate userid, prefix length]
// don't include command names in autocomplete
if (m2 && (m2[0] === '/' || m2[0] === '!')) spaceprefix = '';
for (var i in users) {
if (spaceprefix && users[i].substr(1).replace(/[^A-Za-z0-9 ]+/g, '').toLowerCase().substr(0, spaceprefix.length) === spaceprefix) {
candidates.push([i, m2[1].length]);
} else if (idprefix && i.substr(0, idprefix.length) === idprefix) {
candidates.push([i, m1[1].length]);
}
}
// Sort by most recent to speak in the chat, or, in the case of a tie,
// in alphabetical order.
var self = this;
candidates.sort(function (a, b) {
if (a[1] !== b[1]) {
// shorter prefix length comes first
return a[1] - b[1];
}
var aidx = self.userActivity.indexOf(a[0]);
var bidx = self.userActivity.indexOf(b[0]);
if (aidx !== -1) {
if (bidx !== -1) {
return bidx - aidx;
}
return -1; // a comes first
} else if (bidx != -1) {
return 1; // b comes first
}
return (a[0] < b[0]) ? -1 : 1; // alphabetical order
});
this.tabComplete.candidates = candidates;
this.tabComplete.index = 0;
if (!candidates.length) {
this.tabComplete.cursor = null;
return true;
}
}
// Substitute in the tab-completed name.
var candidate = this.tabComplete.candidates[this.tabComplete.index];
var substituteUserId = candidate[0];
if (!users[substituteUserId]) return true;
var name = users[substituteUserId].substr(1);
name = Tools.getShortName(name);
var fullPrefix = this.tabComplete.prefix.substr(0, candidate[1]) + name;
$textbox.val(fullPrefix + text.substr(idx));
var pos = fullPrefix.length;
$textbox[0].setSelectionRange(pos, pos);
this.tabComplete.cursor = fullPrefix;
return true;
},
// command parsing
parseCommand: function (text) {
var cmd = '';
var target = '';
var noSpace = false;
if (text.substr(0, 2) !== '//' && text.substr(0, 1) === '/') {
var spaceIndex = text.indexOf(' ');
if (spaceIndex > 0) {
cmd = text.substr(1, spaceIndex - 1);
target = text.substr(spaceIndex + 1);
} else {
cmd = text.substr(1);
target = '';
noSpace = true;
}
}
switch (cmd.toLowerCase()) {
case 'chall':
case 'challenge':
var targets = target.split(',').map($.trim);
var self = this;
var challenge = function (targets) {
target = toId(targets[0]);
self.challengeData = {userid: target, format: targets[1] || '', team: targets[2] || ''};
app.on('response:userdetails', self.challengeUserdetails, self);
app.send('/cmd userdetails ' + target);
};
if (!targets[0]) {
app.addPopupPrompt("Who would you like to challenge?", "Challenge user", function (target) {
if (!target) return;
challenge([target]);
});
return false;
}
challenge(targets);
return false;
case 'accept':
var userid = toId(target);
if (userid) {
var $challenge = $('.pm-window').filter('div[data-userid="' + userid + '"]').find('button[name="acceptChallenge"]');
if (!$challenge.length) {
this.add("You do not have any pending challenge from '" + toName(target) + "' to accept.");
return false;
}
$challenge[0].click();
return false;
}
var $challenges = $('.challenge').find('button[name=acceptChallenge]');
if (!$challenges.length) {
this.add('You do not have any pending challenges to accept.');
return false;
}
if ($challenges.length > 1) {
this.add('You need to specify a user if you have more than one pending challenge to accept.');
this.parseCommand('/help accept');
return false;
}
$challenges[0].click();
return false;
case 'reject':
var userid = toId(target);
if (userid) {
var $challenge = $('.pm-window').filter('div[data-userid="' + userid + '"]').find('button[name="rejectChallenge"]');
if (!$challenge.length) {
this.add("You do not have any pending challenge from '" + toName(target) + "' to reject.");
return false;
}
$challenge[0].click();
return false;
}
var $challenges = $('.challenge').find('button[name="rejectChallenge"]');
if (!$challenges.length) {
this.add('You do not have any pending challenges to reject.');
this.parseCommand('/help reject');
return false;
}
if ($challenges.length > 1) {
this.add('You need to specify a user if you have more than one pending challenge to reject.');
this.parseCommand('/help reject');
return false;
}
$challenges[0].click();
return false;
case 'user':
case 'open':
var openUser = function (target) {
app.addPopup(UserPopup, {name: target});
};
target = toName(target);
if (!target) {
app.addPopupPrompt("Username", "Open", function (target) {
if (!target) return;
openUser(target);
});
return false;
}
openUser(target);
return false;
case 'debug':
if (target === 'extractteams') {
app.addPopup(Popup, {
type: 'modal',
htmlMessage: "Extracted team data:<br /><textarea rows=\"10\" cols=\"60\">" + Tools.escapeHTML(JSON.stringify(Storage.teams)) + "</textarea>"
});
}
return false;
case 'autojoin':
case 'cmd':
case 'query':
this.add('This is a PS system command; do not use it.');
return false;
case 'ignore':
if (!target) {
this.parseCommand('/help ignore');
return false;
}
if (toUserid(target) === app.user.get('userid')) {
this.add("You are not able to ignore yourself.");
} else if (app.ignore[toUserid(target)]) {
this.add("User '" + toName(target) + "' is already on your ignore list. (Moderator messages will not be ignored.)");
} else {
app.ignore[toUserid(target)] = 1;
this.add("User '" + toName(target) + "' ignored. (Moderator messages will not be ignored.)");
}
return false;
case 'unignore':
if (!target) {
this.parseCommand('/help unignore');
return false;
}
if (!app.ignore[toUserid(target)]) {
this.add("User '" + toName(target) + "' isn't on your ignore list.");
} else {
delete app.ignore[toUserid(target)];
this.add("User '" + toName(target) + "' no longer ignored.");
}
return false;
case 'ignorelist':
var ignoreList = Object.keys(app.ignore);
if (ignoreList.length === 0) {
this.add('You are currently not ignoring anyone.');
} else {
this.add("You are currently ignoring: " + ignoreList.join(', '));
}
return false;
case 'clear':
if (this.clear) {
this.clear();
} else {
this.add('||This room can\'t be cleared');
}
return false;
case 'clearpms':
var $pms = $('.pm-window');
if (!$pms.length) {
this.add('You do not have any PM windows open.');
return false;
}
$pms.each(function () {
var userid = $(this).data('userid');
if (!userid) {
var newsId = $(this).data('newsid');
if (newsId) {
$.cookie('showdown_readnews', '' + newsId, {expires: 365});
}
$(this).remove();
return;
}
app.rooms[''].closePM(userid);
$(this).find('.inner').empty();
});
this.add("All PM windows cleared and closed.");
return false;
case 'nick':
if ($.trim(target)) {
app.user.rename(target);
} else {
app.addPopup(LoginPopup);
}
return false;
case 'logout':
app.user.logout();
return false;
case 'showdebug':
this.add('Debug battle messages: ON');
Tools.prefs('showdebug', true);
var debugStyle = $('#debugstyle').get(0);
var onCSS = '.debug {display: block;}';
if (!debugStyle) {
$('head').append('<style id="debugstyle">' + onCSS + '</style>');
} else {
debugStyle.innerHTML = onCSS;
}
return false;
case 'hidedebug':
this.add('Debug battle messages: HIDDEN');
Tools.prefs('showdebug', false);
var debugStyle = $('#debugstyle').get(0);
var offCSS = '.debug {display: none;}';
if (!debugStyle) {
$('head').append('<style id="debugstyle">' + offCSS + '</style>');
} else {
debugStyle.innerHTML = offCSS;
}
return false;
case 'showjoins':
var showjoins = Tools.prefs('showjoins') || {};
var serverShowjoins = showjoins[Config.server.id] || {};
if (target) {
var room = toId(target);
if (serverShowjoins['global']) {
delete serverShowjoins[room];
} else {
serverShowjoins[room] = 1;
}
this.add('Join/leave messages on room ' + room + ': ON');
} else {
serverShowjoins = {global: 1};
this.add('Join/leave messages: ON');
}
showjoins[Config.server.id] = serverShowjoins;
Tools.prefs('showjoins', showjoins);
return false;
case 'hidejoins':
var showjoins = Tools.prefs('showjoins') || {};
var serverShowjoins = showjoins[Config.server.id] || {};
if (target) {
var room = toId(target);
if (!serverShowjoins['global']) {
delete serverShowjoins[room];
} else {
serverShowjoins[room] = 0;
}
this.add('Join/leave messages on room ' + room + ': HIDDEN');
} else {
serverShowjoins = {global: 0};
this.add('Join/leave messages: HIDDEN');
}
showjoins[Config.server.id] = serverShowjoins;
Tools.prefs('showjoins', showjoins);
return false;
case 'showbattles':
this.add('Battle messages: ON');
Tools.prefs('showbattles', true);
return false;
case 'hidebattles':
this.add('Battle messages: HIDDEN');
Tools.prefs('showbattles', false);
return false;
case 'unpackhidden':
this.add('Locked/banned users\' chat messages: ON');
Tools.prefs('nounlink', true);
return false;
case 'packhidden':
this.add('Locked/banned users\' chat messages: HIDDEN');
Tools.prefs('nounlink', false);
return false;
case 'timestamps':
var targets = target.split(',');
if ((['all', 'lobby', 'pms'].indexOf(targets[0]) === -1) || targets.length < 2 ||
(['off', 'minutes', 'seconds'].indexOf(targets[1] = targets[1].trim()) === -1)) {
this.add('Error: Invalid /timestamps command');
this.parseCommand('/help timestamps'); // show help
return false;
}
var timestamps = Tools.prefs('timestamps') || {};
if (typeof timestamps === 'string') {
// The previous has a timestamps preference from the previous
// regime. We can't set properties of a string, so set it to
// an empty object.
timestamps = {};
}
switch (targets[0]) {
case 'all':
timestamps.lobby = targets[1];
timestamps.pms = targets[1];
break;
case 'lobby':
timestamps.lobby = targets[1];
break;
case 'pms':
timestamps.pms = targets[1];
break;
}
this.add("Timestamps preference set to: '" + targets[1] + "' for '" + targets[0] + "'.");
Tools.prefs('timestamps', timestamps);
return false;
case 'hl':
case 'highlight':
var highlights = Tools.prefs('highlights') || [];
if (target.indexOf(',') > -1) {
var targets = target.match(/([^,]+?({\d*,\d*})?)+/g);
// trim the targets to be safe
for (var i = 0, len = targets.length; i < len; i++) {
targets[i] = targets[i].replace(/\n/g, '').trim();
}
switch (targets[0]) {
case 'add':
for (var i = 1, len = targets.length; i < len; i++) {
if (!targets[i]) continue;
if (/[\\^$*+?()|{}[\]]/.test(targets[i])) {
// Catch any errors thrown by newly added regular expressions so they don't break the entire highlight list
try {
new RegExp(targets[i]);
} catch (e) {
return this.add(e.message.substr(0, 28) === 'Invalid regular expression: ' ? e.message : 'Invalid regular expression: /' + targets[i] + '/: ' + e.message);
}
}
if (highlights.indexOf(targets[i]) > -1) {
return this.add(targets[i] + ' is already on your highlights list.');
}
}
highlights = highlights.concat(targets.slice(1));
this.add("Now highlighting on: " + highlights.join(', '));
// We update the regex
this.updateHighlightRegExp(highlights);
break;
case 'delete':
var newHls = [];
for (var i = 0, len = highlights.length; i < len; i++) {
if (targets.indexOf(highlights[i]) === -1) {
newHls.push(highlights[i]);
}
}
highlights = newHls;
this.add("Now highlighting on: " + highlights.join(', '));
// We update the regex
this.updateHighlightRegExp(highlights);
break;
default:
// Wrong command
this.add('Error: Invalid /highlight command.');
this.parseCommand('/help highlight'); // show help
return false;
}
Tools.prefs('highlights', highlights);
} else {
if (target === 'delete') {
Tools.prefs('highlights', false);
this.add("All highlights cleared");
} else if (target === 'show' || target === 'list') {
// Shows a list of the current highlighting words
if (highlights.length > 0) {
this.add("Current highlight list: " + highlights.join(", "));
} else {
this.add('Your highlight list is empty.');
}
} else {
// Wrong command
this.add('Error: Invalid /highlight command.');
this.parseCommand('/help highlight'); // show help
return false;
}
}
return false;
case 'rank':
case 'ranking':
case 'rating':
case 'ladder':
if (app.localLadder) return text;
if (!target) target = app.user.get('userid');
var targets = target.split(',');
var formatTargeting = false;
var formats = {};
for (var i = 1, len = targets.length; i < len; i++) {
formats[toId(targets[i])] = 1;
formatTargeting = true;
}
var self = this;
$.get(app.user.getActionPHP(), {
act: 'ladderget',
user: targets[0]
}, Tools.safeJSON(function (data) {
if (!data || !$.isArray(data)) return self.add('|raw|Error: corrupted ranking data');
var buffer = '<div class="ladder"><table><tr><td colspan="8">User: <strong>' + toName(targets[0]) + '</strong></td></tr>';
if (!data.length) {
buffer += '<tr><td colspan="8"><em>This user has not played any ladder games yet.</em></td></tr>';
buffer += '</table></div>';
return self.add('|raw|' + buffer);
}
buffer += '<tr><th>Format</th><th><abbr title="Elo rating">Elo</abbr></th><th><abbr title="user\'s percentage chance of winning a random battle (aka GLIXARE)">GXE</abbr></th><th><abbr title="Glicko-1 rating: rating±deviation">Glicko-1</abbr></th><th>COIL</th><th>W</th><th>L</th><th>Total</th></tr>';
var hiddenFormats = [];
for (var i = 0; i < data.length; i++) {
var row = data[i];
if (!row) return self.add('|raw|Error: corrupted ranking data');
var formatId = toId(row.formatid);
if (!formatTargeting || formats[formatId]) {
buffer += '<tr>';
} else {
buffer += '<tr class="hidden">';
hiddenFormats.push(Tools.escapeFormat(formatId));
}
// Validate all the numerical data
var values = [row.elo, row.rpr, row.rprd, row.gxe, row.w, row.l, row.t];
for (var j = 0; j < values.length; j++) {
if (typeof values[j] !== 'number' && typeof values[j] !== 'string' || isNaN(values[j])) return self.add('|raw|Error: corrupted ranking data');
}
buffer += '<td>' + Tools.escapeFormat(formatId) + '</td><td><strong>' + Math.round(row.elo) + '</strong></td>';
if (row.rprd > 100) {
// High rating deviation. Provisional rating.
buffer += '<td>–</td>';
buffer += '<td><span><em>' + Math.round(row.rpr) + '<small> ± ' + Math.round(row.rprd) + '</small></em> <small>(provisional)</small></span></td>';
} else {
var gxe = Math.round(row.gxe * 10);
buffer += '<td>' + Math.floor(gxe / 10) + '<small>.' + (gxe % 10) + '%</small></td>';
buffer += '<td><em>' + Math.round(row.rpr) + '<small> ± ' + Math.round(row.rprd) + '</small></em></td>';
}
var N = parseInt(row.w, 10) + parseInt(row.l, 10) + parseInt(row.t, 10);
var COIL_B = LadderRoom.COIL_B[formatId];
if (COIL_B) {
buffer += '<td>' + Math.round(40.0 * parseFloat(row.gxe) * Math.pow(2.0, -COIL_B / N), 0) + '</td>';
} else {
buffer += '<td>--</td>';
}
buffer += '<td>' + row.w + '</td><td>' + row.l + '</td><td>' + N + '</td></tr>';
}
if (hiddenFormats.length) {
if (hiddenFormats.length === data.length) {
buffer += '<tr class="no-matches"><td colspan="6"><em>This user has not played any ladder games that match the format targeting.</em></td></tr>';
}
buffer += '<tr><td colspan="8"><button name="showOtherFormats">' + hiddenFormats.slice(0, 3).join(', ') + (hiddenFormats.length > 3 ? ' and ' + (hiddenFormats.length - 3) + ' other formats' : '') + ' not shown</button></td></tr>';
}
var userid = toId(targets[0]);
var registered = app.user.get('registered');
if (registered && registered.userid === userid) {
buffer += '<tr><td colspan="8" style="text-align:right"><a href="//pokemonshowdown.com/users/' + userid + '">Reset W/L</a></tr></td>';
}
buffer += '</table></div>';
self.add('|raw|' + buffer);
}), 'text');
return false;
case 'buttonban':
var self = this;
app.addPopupPrompt("Why do you wish to ban this user?", "Ban user", function (reason) {
self.send('/ban ' + toName(target) + ', ' + (reason || ''));
});
return false;
case 'buttonmute':
var self = this;
app.addPopupPrompt("Why do you wish to mute this user?", "Mute user", function (reason) {
self.send('/mute ' + toName(target) + ', ' + (reason || ''));
});
return false;
case 'buttonunmute':
this.send('/unmute ' + target);
return false;
case 'buttonkick':
case 'buttonwarn':
var self = this;
app.addPopupPrompt("Why do you wish to warn this user?", "Warn user", function (reason) {
self.send('/warn ' + toName(target) + ', ' + (reason || ''));
});
return false;
case 'joim':
case 'join':
case 'j':
if (noSpace) return text;
var room = toRoomid(target);
if (app.rooms[target]) {
app.focusRoom(target);
return false;
}
room = toId(target);
if (app.rooms[room]) {
app.focusRoom(room);
return false;
}
return text; // Send the /join command through to the server.
case 'part':
case 'leave':
if (this.requestLeave && !this.requestLeave()) return false;
return text;
case 'avatar':
var parts = target.split(',');
var avatar = parseInt(parts[0], 10);
if (avatar) {
Tools.prefs('avatar', avatar);
}
return text; // Send the /avatar command through to the server.
// documentation of client commands
case 'help':
switch (toId(target)) {
case 'challenge':
this.add('/challenge - Open a prompt to challenge a user to a battle.');
this.add('/challenge [user] - Challenge the user [user] to a battle.');
return false;
case 'accept':
this.add('/accept - Accept a challenge if only one is pending.');
this.add('/accept [user] - Accept a challenge from the specified user.');
return false;
case 'reject':
this.add('/reject - Reject a challenge if only one is pending.');
this.add('/reject [user] - Reject a challenge from the specified user.');
return false;
case 'user':
case 'open':
this.add('/user [user] - Open a popup containing the user [user]\'s avatar, name, rank, and chatroom list.');
return false;
case 'ignore':
case 'unignore':
this.add('/ignore [user] - Ignore all messages from the user [user].');
this.add('/unignore [user] - Remove the user [user] from your ignore list.');
this.add('/ignorelist - List all the users that you currently ignore.');
this.add('Note that staff messages cannot be ignored.');
return false;
case 'nick':
this.add('/nick [new username] - Change your username.');
return false;
case 'clear':
this.add('/clear - Clear the room\'s chat log.');
return false;
case 'showdebug':
case 'hidedebug':
this.add('/showdebug - Receive debug messages from battle events.');
this.add('/hidedebug - Ignore debug messages from battle events.');
return false;
case 'showjoins':
case 'hidejoins':
this.add('/showjoins [room] - Receive users\' join/leave messages. Optionally for only specified room.');
this.add('/hidejoins [room] - Ignore users\' join/leave messages. Optionally for only specified room.');
return false;
case 'showbattles':
case 'hidebattles':
this.add('/showbattles - Receive links to new battles in Lobby.');
this.add('/hidebattles - Ignore links to new battles in Lobby.');
return false;
case 'unpackhidden':
case 'packhidden':
this.add('/unpackhidden - Suppress hiding locked or banned users\' chat messages after the fact.');
this.add('/packhidden - Hide locked or banned users\' chat messages after the fact.');
this.add('Hidden messages from a user can be restored by clicking the button underneath their lock/ban reason.');
return false;
case 'timestamps':
this.add('Set your timestamps preference:');
this.add('/timestamps [all|lobby|pms], [minutes|seconds|off]');
this.add('all - Change all timestamps preferences, lobby - Change only lobby chat preferences, pms - Change only PM preferences.');
this.add('off - Set timestamps off, minutes - Show timestamps of the form [hh:mm], seconds - Show timestamps of the form [hh:mm:ss].');
return false;
case 'highlight':
case 'hl':
this.add('Set up highlights:');
this.add('/highlight add, [word] - Add the word [word] to the highlight list.');
this.add('/highlight list - List all words that currently highlight you.');
this.add('/highlight delete, [word] - Delete the word [word] from the highlight list.');
this.add('/highlight delete - Clear the highlight list.');
return false;
case 'rank':
case 'ranking':
case 'rating':
case 'ladder':
this.add('/rating - Get your own rating.');
this.add('/rating [username] - Get user [username]\'s rating.');
return false;
}
}
return text;
},
challengeData: {},
challengeUserdetails: function (data) {
app.off('response:userdetails', this.challengeUserdetails);
if (!data || this.challengeData.userid !== data.userid) return;
if (data.rooms === false) {
this.add('This player does not exist or is not online.');
return;
}
app.focusRoom('');
var name = data.name || this.challengeData.userid;
if (/^[a-z0-9]/i.test(name)) name = ' ' + name;
app.rooms[''].challenge(name, this.challengeData.format, this.challengeData.team);
},
showOtherFormats: function (d, target) {
var autoscroll = (this.$chatFrame.scrollTop() + 60 >= this.$chat.height() - this.$chatFrame.height());
var $target = $(target);
var $table = $target.closest('table');
$table.find('tr.hidden').show();
$table.find('tr.no-matches').remove();
$target.closest('tr').remove();
if (autoscroll) {
this.$chatFrame.scrollTop(this.$chat.height());
}
},
destroy: function (alreadyLeft) {
app.user.off('change', this.updateUser, this);
Room.prototype.destroy.call(this, alreadyLeft);
}
}, {
toggleFormatChar: function (textbox, formatChar) {
if (!textbox.setSelectionRange) return false;
var value = textbox.value;
var start = textbox.selectionStart;
var end = textbox.selectionEnd;
// make sure start and end aren't midway through the syntax
if (value.charAt(start) === formatChar && value.charAt(start - 1) === formatChar &&