-
Notifications
You must be signed in to change notification settings - Fork 804
/
client.js
3075 lines (2892 loc) · 105 KB
/
client.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 toId() {
// toId has been renamed toID
alert("You have an old extension/script for Pokemon Showdown which is incompatible with this client. It needs to be removed or updated.");
}
(function ($) {
Config.sockjsprefix = '/showdown';
Config.root = '/';
if (window.nodewebkit) {
window.gui = require('nw.gui');
window.nwWindow = gui.Window.get();
}
if (navigator.userAgent.match(/(iPod|iPhone|iPad)/)) {
// Android mobile-web-app-capable doesn't support it very well, but iOS
// does it fine, so we're only going to show this to iOS for now
window.isiOS = true;
$('head').append('<meta name="apple-mobile-web-app-capable" content="yes" />');
}
$(document).on('keydown', function (e) {
if (e.keyCode == 27) { // Esc
e.preventDefault();
e.stopPropagation();
e.stopImmediatePropagation();
app.closePopup();
}
});
$(window).on('dragover', function (e) {
if (/^text/.test(e.target.type)) return; // Ignore text fields
e.preventDefault();
});
$(document).on('dragenter', function (e) {
if (/^text/.test(e.target.type)) return; // Ignore text fields
e.preventDefault();
if (!app.dragging && app.curRoom.id === 'teambuilder') {
var dataTransfer = e.originalEvent.dataTransfer;
if (dataTransfer.files && dataTransfer.files[0]) {
var file = dataTransfer.files[0];
if (file.name.slice(-4) === '.txt') {
// Someone dragged in a .txt file, hand it to the teambuilder
app.curRoom.defaultDragEnterTeam(e);
}
} else if (dataTransfer.items && dataTransfer.items[0]) {
// no files or no permission to access files
var item = dataTransfer.items[0];
if (item.kind === 'file' && item.type === 'text/plain') {
// Someone dragged in a .txt file, hand it to the teambuilder
app.curRoom.defaultDragEnterTeam(e);
}
}
}
// dropEffect !== 'none' prevents buggy bounce-back animation in
// Chrome/Safari/Opera
e.originalEvent.dataTransfer.dropEffect = 'move';
});
$(window).on('drop', function (e) {
if (/^text/.test(e.target.type)) return; // Ignore text fields
// The default team drop action for Firefox is to open the team as a
// URL, which needs to be prevented.
// The default file drop action for most browsers is to open the file
// in the tab, which is generally undesirable anyway.
e.preventDefault();
if (app.dragging && app.draggingRoom) {
app.rooms[app.draggingRoom].defaultDropTeam(e);
} else if (e.originalEvent.dataTransfer.files && e.originalEvent.dataTransfer.files[0]) {
var file = e.originalEvent.dataTransfer.files[0];
if (file.name.slice(-4) === '.txt' && app.curRoom.id === 'teambuilder') {
// Someone dragged in a .txt file, hand it to the teambuilder
app.curRoom.defaultDragEnterTeam(e);
app.curRoom.defaultDropTeam(e);
} else if (file.type && file.type.substr(0, 6) === 'image/') {
// It's an image file, try to set it as a background
CustomBackgroundPopup.readFile(file);
} else if (file.type && file.type === 'text/html') {
BattleRoom.readReplayFile(file);
}
}
});
if (window.nodewebkit) {
$(document).on("contextmenu", function (e) {
e.preventDefault();
var target = e.target;
var isEditable = (target.tagName === 'TEXTAREA' || target.tagName === 'INPUT');
var menu = new gui.Menu();
if (isEditable) menu.append(new gui.MenuItem({
label: "Cut",
click: function () {
document.execCommand("cut");
}
}));
var link = $(target).closest('a')[0];
if (link) menu.append(new gui.MenuItem({
label: "Copy Link URL",
click: function () {
gui.Clipboard.get().set(link.href);
}
}));
if (target.tagName === 'IMG') menu.append(new gui.MenuItem({
label: "Copy Image URL",
click: function () {
gui.Clipboard.get().set(target.src);
}
}));
menu.append(new gui.MenuItem({
label: "Copy",
click: function () {
document.execCommand("copy");
}
}));
if (isEditable) menu.append(new gui.MenuItem({
label: "Paste",
enabled: !!gui.Clipboard.get().get(),
click: function () {
document.execCommand("paste");
}
}));
menu.popup(e.originalEvent.x, e.originalEvent.y);
});
}
// support Safari 6 notifications
if (!window.Notification && window.webkitNotification) {
window.Notification = window.webkitNotification;
}
// this is called being lazy
window.selectTab = function (tab) {
app.tryJoinRoom(tab);
return false;
};
var User = this.User = Backbone.Model.extend({
defaults: {
name: '',
userid: '',
registered: false,
named: false,
avatar: 0,
settings: {},
status: '',
away: false
},
initialize: function () {
app.addGlobalListeners();
app.on('response:userdetails', function (data) {
if (data.userid === this.get('userid')) {
this.set('avatar', '' + data.avatar);
}
}, this);
var self = this;
this.on('change:name', function () {
if (!self.get('named')) {
self.nameRegExp = null;
} else {
var escaped = self.get('name').replace(/[^A-Za-z0-9]+$/, '');
// we'll use `,` as a sentinel character to mean "any non-alphanumeric char"
// unicode characters can be replaced with any non-alphanumeric char
for (var i = escaped.length - 1; i > 0; i--) {
if (/[^\ -\~]/.test(escaped[i])) {
escaped = escaped.slice(0, i) + ',' + escaped.slice(i + 1);
}
}
escaped = escaped.replace(/[\-\[\]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g, "\\$&");
escaped = escaped.replace(/,/g, "[^A-Za-z0-9]?");
self.nameRegExp = new RegExp('(?:\\b|(?!\\w))' + escaped + '(?:\\b|\\B(?!\\w))', 'i');
}
});
this.on('change:settings', function () {
Storage.prefs('serversettings', self.get('settings'));
});
var replaceList = {'A': 'AⱯȺ', 'B': 'BƂƁɃ', 'C': 'CꜾȻ', 'D': 'DĐƋƊƉꝹ', 'E': 'EƐƎ', 'F': 'FƑꝻ', 'G': 'GꞠꝽꝾ', 'H': 'HĦⱧⱵꞍ', 'I': 'IƗ', 'J': 'JɈ', 'K': 'KꞢ', 'L': 'LꝆꞀ', 'M': 'MⱮƜ', 'N': 'NȠƝꞐꞤ', 'O': 'OǪǬØǾƆƟꝊꝌ', 'P': 'PƤⱣꝐꝒꝔ', 'Q': 'QꝖꝘɊ', 'R': 'RɌⱤꝚꞦꞂ', 'S': 'SẞꞨꞄ', 'T': 'TŦƬƮȾꞆ', 'U': 'UɄ', 'V': 'VƲꝞɅ', 'W': 'WⱲ', 'X': 'X', 'Y': 'YɎỾ', 'Z': 'ZƵȤⱿⱫꝢ', 'a': 'aąⱥɐ', 'b': 'bƀƃɓ', 'c': 'cȼꜿↄ', 'd': 'dđƌɖɗꝺ', 'e': 'eɇɛǝ', 'f': 'fḟƒꝼ', 'g': 'gɠꞡᵹꝿ', 'h': 'hħⱨⱶɥ', 'i': 'iɨı', 'j': 'jɉ', 'k': 'kƙⱪꝁꝃꝅꞣ', 'l': 'lſłƚɫⱡꝉꞁꝇ', 'm': 'mɱɯ', 'n': 'nƞɲʼnꞑꞥ', 'o': 'oǫǭøǿɔꝋꝍɵ', 'p': 'pƥᵽꝑꝓꝕ', 'q': 'qɋꝗꝙ', 'r': 'rɍɽꝛꞧꞃ', 's': 'sꞩꞅẛ', 't': 'tŧƭʈⱦꞇ', 'u': 'uưừứữửựųṷṵʉ', 'v': 'vʋꝟʌ', 'w': 'wⱳ', 'x': 'x', 'y': 'yɏỿ', 'z': 'zƶȥɀⱬꝣ', 'AA': 'Ꜳ', 'AE': 'ÆǼǢ', 'AO': 'Ꜵ', 'AU': 'Ꜷ', 'AV': 'ꜸꜺ', 'AY': 'Ꜽ', 'DZ': 'DZDŽ', 'Dz': 'DzDž', 'LJ': 'LJ', 'Lj': 'Lj', 'NJ': 'NJ', 'Nj': 'Nj', 'OI': 'Ƣ', 'OO': 'Ꝏ', 'OU': 'Ȣ', 'TZ': 'Ꜩ', 'VY': 'Ꝡ', 'aa': 'ꜳ', 'ae': 'æǽǣ', 'ao': 'ꜵ', 'au': 'ꜷ', 'av': 'ꜹꜻ', 'ay': 'ꜽ', 'dz': 'dzdž', 'hv': 'ƕ', 'lj': 'lj', 'nj': 'nj', 'oi': 'ƣ', 'ou': 'ȣ', 'oo': 'ꝏ', 'ss': 'ß', 'tz': 'ꜩ', 'vy': 'ꝡ'};
var normalizeList = {'A': 'ÀÁÂẦẤẪẨÃĀĂẰẮẴẲȦǠÄǞẢÅǺǍȀȂẠẬẶḀĄ', 'B': 'ḂḄḆ', 'C': 'ĆĈĊČÇḈƇ', 'D': 'ḊĎḌḐḒḎ', 'E': 'ÈÉÊỀẾỄỂẼĒḔḖĔĖËẺĚȄȆẸỆȨḜĘḘḚ', 'F': 'Ḟ', 'G': 'ǴĜḠĞĠǦĢǤƓ', 'H': 'ĤḢḦȞḤḨḪ', 'I': 'ÌÍÎĨĪĬİÏḮỈǏȈȊỊĮḬ', 'J': 'Ĵ', 'K': 'ḰǨḲĶḴƘⱩꝀꝂꝄ', 'L': 'ĿĹĽḶḸĻḼḺŁȽⱢⱠꝈ', 'M': 'ḾṀṂ', 'N': 'ǸŃÑṄŇṆŅṊṈ', 'O': 'ÒÓÔỒỐỖỔÕṌȬṎŌṐṒŎȮȰÖȪỎŐǑȌȎƠỜỚỠỞỢỌỘ', 'P': 'ṔṖ', 'Q': '', 'R': 'ŔṘŘȐȒṚṜŖṞ', 'S': 'ŚṤŜṠŠṦṢṨȘŞⱾ', 'T': 'ṪŤṬȚŢṰṮ', 'U': 'ÙÚÛŨṸŪṺŬÜǛǗǕǙỦŮŰǓȔȖƯỪỨỮỬỰỤṲŲṶṴ', 'V': 'ṼṾ', 'W': 'ẀẂŴẆẄẈ', 'X': 'ẊẌ', 'Y': 'ỲÝŶỸȲẎŸỶỴƳ', 'Z': 'ŹẐŻŽẒẔ', 'a': 'ẚàáâầấẫẩãāăằắẵẳȧǡäǟảåǻǎȁȃạậặḁ', 'b': 'ḃḅḇ', 'c': 'ćĉċčçḉƈ', 'd': 'ḋďḍḑḓḏ', 'e': 'èéêềếễểẽēḕḗĕėëẻěȅȇẹệȩḝęḙḛ', 'f': '', 'g': 'ǵĝḡğġǧģǥ', 'h': 'ĥḣḧȟḥḩḫẖ', 'i': 'ìíîĩīĭïḯỉǐȉȋịįḭ', 'j': 'ĵǰ', 'k': 'ḱǩḳķḵ', 'l': 'ŀĺľḷḹļḽḻ', 'm': 'ḿṁṃ', 'n': 'ǹńñṅňṇņṋṉ', 'o': 'òóôồốỗổõṍȭṏōṑṓŏȯȱöȫỏőǒȍȏơờớỡởợọộ', 'p': 'ṕṗ', 'q': '', 'r': 'ŕṙřȑȓṛṝŗṟ', 's': 'śṥŝṡšṧṣṩșşȿ', 't': 'ṫẗťṭțţṱṯ', 'u': 'ùúûũṹūṻŭüǜǘǖǚủůűǔȕȗụṳ', 'v': 'ṽṿ', 'w': 'ẁẃŵẇẅẘẉ', 'x': 'ẋẍ', 'y': 'ỳýŷỹȳẏÿỷẙỵƴ', 'z': 'źẑżžẓẕ'};
for (var i in replaceList) {
replaceList[i] = new RegExp('[' + replaceList[i] + ']', 'g');
}
for (var i in normalizeList) {
normalizeList[i] = new RegExp('[' + normalizeList[i] + ']', 'g');
}
this.replaceList = replaceList;
this.normalizeList = normalizeList;
},
updateSetting: function (setting, value) {
var settings = _.clone(this.get('settings'));
if (settings[setting] !== value) {
switch (setting) {
case 'blockPMs':
app.send(value ? '/blockpms ' + value : '/unblockpms');
break;
case 'blockChallenges':
app.send(value ? '/blockchallenges' : '/unblockchallenges');
break;
case 'language':
app.send('/language ' + value);
break;
default:
throw new TypeError('Unknown setting:' + setting);
}
// Optimistically update, might get corrected by the |updateuser| response
settings[setting] = value;
this.set('settings', settings);
}
},
/**
* Return the path to the login server `action.php` file. AJAX requests
* to this file will always be made on the `play.pokemonshowdown.com`
* domain in order to have access to the correct cookies.
*/
getActionPHP: function () {
var ret = '/~~' + Config.server.id + '/action.php';
if (Config.testclient) {
ret = 'https://' + Config.routes.client + ret;
}
return (this.getActionPHP = function () {
return ret;
})();
},
/**
* Process a signed assertion returned from the login server.
* Emits the following events (arguments in brackets):
*
* `login:authrequired` (name)
* triggered if the user needs to authenticate with this name
*
* `login:invalidname` (name, error)
* triggered if the user's name is invalid
*
* `login:noresponse`
* triggered if the login server did not return a response
*/
finishRename: function (name, assertion) {
if (assertion.slice(0, 14).toLowerCase() === '<!doctype html') {
// some sort of MitM proxy; ignore it
var endIndex = assertion.indexOf('>');
if (endIndex > 0) assertion = assertion.slice(endIndex + 1);
}
if (assertion.charAt(0) === '\r') assertion = assertion.slice(1);
if (assertion.charAt(0) === '\n') assertion = assertion.slice(1);
if (assertion.indexOf('<') >= 0) {
app.addPopupMessage("Something is interfering with our connection to the login server. Most likely, your internet provider needs you to re-log-in, or your internet provider is blocking Pokémon Showdown.");
return;
}
if (assertion === ';') {
this.trigger('login:authrequired', name);
} else if (assertion === ';;@gmail') {
this.trigger('login:authrequired', name, '@gmail');
} else if (assertion.substr(0, 2) === ';;') {
this.trigger('login:invalidname', name, assertion.substr(2));
} else if (assertion.indexOf('\n') >= 0 || !assertion) {
app.addPopupMessage("Something is interfering with our connection to the login server.");
} else {
app.trigger('loggedin');
app.send('/trn ' + name + ',0,' + assertion);
}
},
/**
* Rename this user to an arbitrary username. If the username is
* registered and the user does not currently have a session
* associated with that userid, then the user will be required to
* authenticate.
*
* See `finishRename` above for a list of events this can emit.
*/
rename: function (name) {
// | , ; are not valid characters in names
name = name.replace(/[\|,;]+/g, '');
for (var i in this.replaceList) {
name = name.replace(this.replaceList[i], i);
}
for (var i in this.normalizeList) {
name = name.replace(this.normalizeList[i], i);
}
var userid = toUserid(name);
if (!userid) {
app.addPopupMessage("Usernames must contain at least one letter.");
return;
}
if (this.get('userid') !== userid) {
var self = this;
$.post(this.getActionPHP(), {
act: 'getassertion',
userid: userid,
challstr: this.challstr
}, function (data) {
self.finishRename(name, data);
});
} else {
app.send('/trn ' + name);
}
},
passwordRename: function (name, password, special) {
var self = this;
$.post(this.getActionPHP(), {
act: 'login',
name: name,
pass: password,
challstr: this.challstr
}, Storage.safeJSON(function (data) {
if (data && data.curuser && data.curuser.loggedin) {
// success!
self.set('registered', data.curuser);
self.finishRename(name, data.assertion);
} else {
// wrong password
if (special === '@gmail') {
try {
gapi.auth2.getAuthInstance().signOut(); // eslint-disable-line no-undef
} catch (e) {}
}
app.addPopup(LoginPasswordPopup, {
username: name,
error: data.error || 'Wrong password.',
special: special
});
}
}), 'text');
},
challstr: '',
receiveChallstr: function (challstr) {
if (challstr) {
/**
* Rename the user based on the `sid` and `showdown_username` cookies.
* Specifically, if the user has a valid session, the user will be
* renamed to the username associated with that session. If the user
* does not have a valid session but does have a persistent username
* (i.e. a `showdown_username` cookie), the user will be renamed to
* that name; if that name is registered, the user will be required
* to authenticate.
*
* See `finishRename` above for a list of events this can emit.
*/
this.challstr = challstr;
var self = this;
$.post(this.getActionPHP(), {
act: 'upkeep',
challstr: this.challstr
}, Storage.safeJSON(function (data) {
self.loaded = true;
if (!data.username) {
app.topbar.updateUserbar();
return;
}
// | , ; are not valid characters in names
data.username = data.username.replace(/[\|,;]+/g, '');
if (data.loggedin) {
self.set('registered', {
username: data.username,
userid: toUserid(data.username)
});
}
self.finishRename(data.username, data.assertion);
}), 'text');
}
},
/**
* Log out from the server (but remain connected as a guest).
*/
logout: function () {
$.post(this.getActionPHP(), {
act: 'logout',
userid: this.get('userid')
});
app.send('/logout');
app.trigger('init:socketclosed', "You have been logged out and disconnected.<br /><br />If you wanted to change your name while staying connected, use the 'Change Name' button or the '/nick' command.", false);
app.socket.close();
},
setPersistentName: function (name) {
if (location.host !== Config.routes.client) return;
$.cookie('showdown_username', (name !== undefined) ? name : this.get('name'), {
expires: 14
});
}
});
this.App = Backbone.Router.extend({
root: '/',
routes: {
'*path': 'dispatchFragment'
},
events: {
'submit form': 'submitSend'
},
focused: true,
initialize: function () {
// Gotta cache this since backbone removes it
this.query = window.location.search;
window.app = this;
this.initializeRooms();
this.initializePopups();
this.user = new User();
this.ignore = {};
this.supports = {};
// down
// if (document.location.hostname === 'play.pokemonshowdown.com' || document.location.hostname === 'smogtours.psim.us') this.down = true;
// this.down = true;
this.addRoom('');
this.topbar = new Topbar({el: $('#header')});
if (this.down) {
this.isDisconnected = true;
// } else if (location.origin === 'http://smogtours.psim.us') {
// this.isDisconnected = true;
// this.addPopup(Popup, {
// message: "The Smogtours server no longer supports HTTP. Please use https://smogtours.psim.us",
// type: 'modal'
// });
} else {
if (document.location.hostname === Config.routes.client || Config.testclient) {
this.addRoom('rooms', null, true);
} else {
this.addRoom('lobby', null, true);
}
Storage.whenPrefsLoaded(function () {
if (!Config.server.registered) {
app.send('/autojoin');
Backbone.history.start({pushState: !Config.testclient});
return;
}
// Support legacy tournament setting and migrate to new pref
if (Dex.prefs('notournaments') !== undefined) {
Storage.prefs('tournaments', Dex.prefs('notournaments') ? 'hide' : 'notify');
Storage.prefs('notournaments', null, true);
}
var autojoin = (Dex.prefs('autojoin') || '');
var autojoinIds = [];
if (typeof autojoin === 'string') {
// Use the existing autojoin string for showdown, and an empty string for other servers.
if (Config.server.id !== 'showdown') autojoin = '';
} else {
// If there is not autojoin data for this server, use a empty string.
autojoin = autojoin[Config.server.id] || '';
}
if (autojoin) {
var autojoins = autojoin.split(',');
for (var i = 0; i < autojoins.length; i++) {
var roomid = toRoomid(autojoins[i]);
app.addRoom(roomid, null, true, autojoins[i]);
if (roomid === 'staff' || roomid === 'upperstaff') continue;
if (Config.server.id !== 'showdown' && roomid === 'lobby') continue;
autojoinIds.push(roomid);
}
}
app.send('/autojoin ' + autojoinIds.join(','));
var settings = Dex.prefs('serversettings') || {};
if (Object.keys(settings).length) app.user.set('settings', settings);
// HTML5 history throws exceptions when running on file://
var useHistory = !Config.testclient && (location.pathname.slice(-5) !== '.html');
Backbone.history.start({pushState: useHistory});
app.ignore = app.loadIgnore();
});
}
var self = this;
Storage.whenPrefsLoaded(function () {
Storage.prefs('bg', null);
var muted = Dex.prefs('mute');
BattleSound.setMute(muted);
var theme = Dex.prefs('theme');
var colorSchemeQuery = window.matchMedia && window.matchMedia('(prefers-color-scheme: dark)');
var dark = theme === 'dark' || (theme === 'system' && colorSchemeQuery && colorSchemeQuery.matches);
$('html').toggleClass('dark', dark);
if (colorSchemeQuery && colorSchemeQuery.media !== 'not all') {
colorSchemeQuery.addEventListener('change', function (cs) {
if (Dex.prefs('theme') === 'system') $('html').toggleClass('dark', cs.matches);
});
}
var effectVolume = Dex.prefs('effectvolume');
if (effectVolume !== undefined) BattleSound.setEffectVolume(effectVolume);
var musicVolume = Dex.prefs('musicvolume');
if (musicVolume !== undefined) BattleSound.setBgmVolume(musicVolume);
if (Dex.prefs('logchat')) Storage.startLoggingChat();
if (Dex.prefs('showdebug')) {
var debugStyle = $('#debugstyle').get(0);
var onCSS = '.debug {display: block;}';
if (!debugStyle) {
$('head').append('<style id="debugstyle">' + onCSS + '</style>');
} else {
debugStyle.innerHTML = onCSS;
}
}
if (Dex.prefs('onepanel')) {
self.singlePanelMode = true;
self.updateLayout();
}
if (Dex.prefs('bwgfx') || Dex.prefs('noanim')) {
// since xy data is loaded by default, only call
// loadSpriteData if we want bw sprites or if we need bw
// sprite data (if animations are disabled)
Dex.loadSpriteData('bw');
}
});
this.on('init:unsupported', function () {
self.addPopupMessage('Your browser is unsupported.');
});
this.on('init:nothirdparty', function () {
self.addPopupMessage('You have third-party cookies disabled in your browser, which is likely to cause problems. You should enable them and then refresh this page.');
});
this.on('init:socketclosed', function (message, showNotification) {
// Display a desktop notification if the user won't immediately see the popup.
if (self.isDisconnected) return;
clearTimeout(this.hostCheckInterval);
this.hostCheckInterval = null;
self.isDisconnected = true;
if (showNotification !== false && (self.popups.length || !self.focused) && window.Notification) {
self.rooms[''].requestNotifications();
self.rooms[''].notifyOnce("Disconnected", "You have been disconnected from Pokémon Showdown.", 'disconnected');
}
self.rooms[''].updateFormats();
$('.pm-log-add form').html('<small>You are disconnected and cannot chat.</small>');
$('.chat-log-add').html('<small>You are disconnected and cannot chat.</small>');
$('.battle-log-add').html('<small>You are disconnected and cannot chat.</small>');
self.reconnectPending = (message || true);
if (!self.popups.length) self.addPopup(ReconnectPopup, {message: message});
});
this.on('init:connectionerror', function () {
self.isDisconnected = true;
self.rooms[''].updateFormats();
self.addPopup(ReconnectPopup, {cantconnect: true});
});
this.user.on('login:invalidname', function (name, reason) {
self.addPopup(LoginPopup, {name: name, reason: reason});
});
this.user.on('login:authrequired', function (name, special) {
self.addPopup(LoginPasswordPopup, {username: name, special: special});
});
this.on('loggedin', function () {
Storage.loadRemoteTeams(function () {
if (app.rooms.teambuilder) {
// if they have it open, be sure to update so it doesn't show 'no teams'
app.rooms.teambuilder.update();
}
});
});
this.on('response:savereplay', this.uploadReplay, this);
this.on('response:rooms', this.roomsResponse, this);
if (window.nodewebkit) {
nwWindow.on('focus', function () {
if (!self.focused) {
self.focused = true;
if (self.curRoom) self.curRoom.dismissNotification();
if (self.curSideRoom) self.curSideRoom.dismissNotification();
}
});
nwWindow.on('blur', function () {
self.focused = false;
});
} else {
$(window).on('focus click', function () {
if (!self.focused) {
self.focused = true;
if (self.curRoom) self.curRoom.dismissNotification();
if (self.curSideRoom) self.curSideRoom.dismissNotification();
}
});
$(window).on('blur', function () {
self.focused = false;
});
}
$(window).on('beforeunload', function (e) {
if (Config.server && Config.server.host === 'localhost') return;
if (app.isDisconnected) return;
for (var id in self.rooms) {
var room = self.rooms[id];
if (room && room.requestLeave && !room.requestLeave()) {
e.returnValue = "You have active battles.";
return e.returnValue;
}
}
if (Dex.prefs('refreshprompt')) {
e.returnValue = "Are you sure you want to refresh?";
return e.returnValue;
}
});
$(window).on('keydown', function (e) {
var el = e.target;
var tagName = el.tagName.toUpperCase();
// keypress happened in an empty textarea or a button
var safeLocation = ((tagName === 'TEXTAREA' && !el.value.length) || tagName === 'BUTTON');
var isMac = (navigator.userAgent.indexOf("Mac") !== -1);
if (e.keyCode === 70 && window.nodewebkit && (isMac ? e.metaKey : e.ctrlKey)) {
e.preventDefault();
e.stopImmediatePropagation();
var query = window.getSelection().toString();
query = window.prompt("find?", query);
if (query) window.find(query);
return;
}
if (e.keyCode === 71 && window.nodewebkit && (isMac ? e.metaKey : e.ctrlKey)) {
e.preventDefault();
e.stopImmediatePropagation();
var query = window.getSelection().toString();
if (query) window.find(query);
return;
}
if (app.curSideRoom && $(e.target).closest(app.curSideRoom.$el).length) {
// keypress happened in sideroom
if (e.shiftKey && e.keyCode === 37 && safeLocation) {
// Shift+Left on desktop client
if (app.moveRoomBy(app.curSideRoom, -1)) {
e.preventDefault();
e.stopImmediatePropagation();
}
} else if (e.shiftKey && e.keyCode === 39 && safeLocation) {
// Shift+Right on desktop client
if (app.moveRoomBy(app.curSideRoom, 1)) {
e.preventDefault();
e.stopImmediatePropagation();
}
} else if (e.keyCode === 37 && safeLocation || window.nodewebkit && e.ctrlKey && e.shiftKey && e.keyCode === 9) {
// Left or Ctrl+Shift+Tab on desktop client
if (app.focusRoomBy(app.curSideRoom, -1)) {
e.preventDefault();
e.stopImmediatePropagation();
}
} else if (e.keyCode === 39 && safeLocation || window.nodewebkit && e.ctrlKey && e.keyCode === 9) {
// Right or Ctrl+Tab on desktop client
if (app.focusRoomBy(app.curSideRoom, 1)) {
e.preventDefault();
e.stopImmediatePropagation();
}
}
return;
}
// keypress happened outside of sideroom
if (e.shiftKey && e.keyCode === 37 && safeLocation) {
// Shift+Left on desktop client
if (app.moveRoomBy(app.curRoom, -1)) {
e.preventDefault();
e.stopImmediatePropagation();
}
} else if (e.shiftKey && e.keyCode === 39 && safeLocation) {
// Shift+Right on desktop client
if (app.moveRoomBy(app.curRoom, 1)) {
e.preventDefault();
e.stopImmediatePropagation();
}
} else if (e.keyCode === 37 && safeLocation || window.nodewebkit && e.ctrlKey && e.shiftKey && e.keyCode === 9) {
// Left or Ctrl+Shift+Tab on desktop client
if (app.focusRoomBy(app.curRoom, -1)) {
e.preventDefault();
e.stopImmediatePropagation();
}
} else if (e.keyCode === 39 && safeLocation || window.nodewebkit && e.ctrlKey && e.keyCode === 9) {
// Right or Ctrl+Tab on desktop client
if (app.focusRoomBy(app.curRoom, 1)) {
e.preventDefault();
e.stopImmediatePropagation();
}
}
});
Storage.whenAppLoaded.load(this);
// load custom colors from loginserver
$.get('/config/colors.json', {}, function (data) {
Object.assign(Config.customcolors, data);
});
// get coil values too
$.get('/config/coil.json', {}, function (data) {
Object.assign(LadderRoom.COIL_B, data);
});
this.initializeConnection();
},
/**
* Start up the client, including loading teams and preferences,
* determining which server to connect to, and actually establishing
* a connection to that server.
*
* Triggers the following events (arguments in brackets):
* `init:unsupported`
* triggered if the user's browser is unsupported
*
* `init:nothirdparty`
* triggered if the user has third-party cookies disabled and
* third-party cookies/storage are necessary for full functioning
* (i.e. stuff will probably be broken for the user, so show an
* error message)
*
* `init:socketopened`
* triggered once a socket has been opened to the sim server; this
* does NOT mean that the user has signed in yet, merely that the
* SockJS connection has been established.
*
* `init:connectionerror`
* triggered if a connection to the sim server could not be
* established
*
* `init:socketclosed`
* triggered if the SockJS socket closes
*/
initializeConnection: function () {
Storage.whenPrefsLoaded(function () {
// if (Config.server.id !== 'smogtours') Config.server.afd = true;
app.connect();
});
},
/**
* This function establishes the actual connection to the sim server.
* This is intended to be called only by `initializeConnection` above.
* Don't call this function directly.
*/
connect: function () {
if (this.down) return;
if (Config.bannedHosts) {
for (var i = 0; i < Config.bannedHosts.length; i++) {
var host = Config.bannedHosts[i];
if (typeof host === 'string' ? Config.server.host === host : host.test(Config.server.host)) {
Config.server.banned = true;
break;
}
}
}
if (Config.server.banned) {
this.addPopupMessage("This server has either been deleted for breaking US law or PS global rules, or it is hosted on a platform that's often used to host rulebreaking servers.");
return;
}
var self = this;
var constructSocket = function () {
if (location.host === 'localhost.psim.us' || /[0-9]+\.[0-9]+\.[0-9]+\.[0-9]+\.psim\.us/.test(location.host)) {
// normally we assume HTTPS means HTTPS, but make an exception for
// localhost and IPs which generally can't have a signed cert anyway.
Config.server.port = 8000;
Config.server.https = false;
}
var protocol = (Config.server.port === 443 || Config.server.https) ? 'https' : 'http';
Config.server.host = $.trim(Config.server.host);
try {
if (Config.server.host === 'localhost') {
// connecting to localhost from psim.us is now banned as of Chrome 94
// thanks Docker for having vulns
// https://wicg.github.io/cors-rfc1918
// anyway, this affects SockJS because it makes HTTP requests to localhost
// but it turns out that making direct WebSocket connections to localhost is
// still supported, so we'll just bypass SockJS and use WebSocket directly.
var possiblePort = new URL(document.location + self.query).searchParams.get('port');
// We need to bypass the port as well because on most modern browsers, http gets forced
// to https, which means a ws connection is made to port 443 instead of wherever it's actually running,
// thus ensuring a failed connection.
var port = possiblePort || Config.server.port;
console.log("Bypassing SockJS for localhost");
var url = 'ws://' + Config.server.host + ':' + port + Config.sockjsprefix + '/websocket';
console.log(url);
return new WebSocket(url);
}
return new SockJS(
protocol + '://' + Config.server.host + ':' + Config.server.port + Config.sockjsprefix,
[], {timeout: 5 * 60 * 1000}
);
} catch (err) {
// The most common case this happens is if an HTTPS connection fails,
// and we fall back to HTTP, which throws a SecurityError if the URL
// is HTTPS
self.trigger('init:connectionerror');
return null;
}
};
this.socket = constructSocket();
var socketopened = false;
var altport = (Config.server.port === Config.server.altport);
var altprefix = false;
this.socket.onopen = function () {
socketopened = true;
if (altport && window.ga) {
ga('send', 'event', 'Alt port connection', Config.server.id);
}
self.trigger('init:socketopened');
var avatar = Dex.prefs('avatar');
if (avatar) {
// This will be compatible even with servers that don't support
// the second argument for /avatar yet.
self.send('/avatar ' + avatar + ',1');
}
if (self.sendQueue) {
var queue = self.sendQueue;
delete self.sendQueue;
for (var i = 0; i < queue.length; i++) {
self.send(queue[i], true);
}
}
this.hostCheckInterval = setTimeout(function checkHost() {
if (Config.server.host !== $.trim(Config.server.host)) {
app.socket.close();
} else {
app.hostCheckInterval = setTimeout(checkHost, 500);
}
}, 500);
};
this.socket.onmessage = function (msg) {
if (window.console && console.log) {
console.log('<< ' + msg.data);
}
self.receive(msg.data);
};
var reconstructSocket = function (socket) {
var s = constructSocket();
s.onopen = socket.onopen;
s.onmessage = socket.onmessage;
s.onclose = socket.onclose;
return s;
};
this.socket.onclose = function () {
if (!socketopened) {
if (Config.server.altport && !altport) {
altport = true;
Config.server.port = Config.server.altport;
self.socket = reconstructSocket(self.socket);
return;
}
if (!altprefix) {
altprefix = true;
Config.sockjsprefix = '';
self.socket = reconstructSocket(self.socket);
return;
}
return self.trigger('init:connectionerror');
}
self.trigger('init:socketclosed');
};
},
dispatchFragment: function (fragment) {
if (!Config.testclient && location.search && window.history) {
history.replaceState(null, null, location.pathname);
}
if (fragment && fragment.includes('.')) fragment = '';
this.fragment = fragment = toRoomid(fragment || '');
if (this.initialFragment === undefined) this.initialFragment = fragment;
this.tryJoinRoom(fragment);
this.updateTitle(this.rooms[fragment]);
},
/**
* Send to sim server
*/
send: function (data, room) {
if (room && room !== true) {
data = room + '|' + data;
} else if (room !== true) {
data = '|' + data;
}
if (!this.socket || (this.socket.readyState !== SockJS.OPEN)) {
if (!this.sendQueue) this.sendQueue = [];
this.sendQueue.push(data);
return;
}
if (window.console && console.log) {
console.log('>> ' + data);
}
this.socket.send(data);
},
serializeForm: function (form, checkboxOnOff) {
// querySelector dates back to IE8 so we can use it
// fortunate, because form serialization is a HUGE MESS in older browsers
var elements = form.querySelectorAll('input[name], select[name], textarea[name], keygen[name], button[value]');
var out = [];
for (var i = 0; i < elements.length; i++) {
var element = elements[i];
if ($(element).attr('type') === 'submit') continue;
if (element.type === 'checkbox' && !element.value && checkboxOnOff) {
out.push([element.name, element.checked ? 'on' : 'off']);
} else if (!['checkbox', 'radio'].includes(element.type) || element.checked) {
out.push([element.name, element.value]);
}
}
return out;
},
submitSend: function (e) {
// Most of the code relating to this is nightmarish because of some dumb choices
// made when writing the original Backbone code. At least in the Preact client, event
// handling is a lot more straightforward because it doesn't rely on Backbone's event
// dispatch system.
var target = e.currentTarget;
var dataSend = target.getAttribute('data-submitsend');
if (dataSend) {
var toSend = dataSend;
var entries = this.serializeForm(target, true);
for (var i = 0; i < entries.length; i++) {
toSend = toSend.replace('{' + entries[i][0] + '}', entries[i][1]);
}
toSend = toSend.replace(/\{[a-z]+\}/g, '');
this.send(toSend);
e.currentTarget.innerText = 'Submitted!';
e.preventDefault();
e.stopPropagation();
}
},
loadingTeam: null,
loadingTeamQueue: [],
loadTeam: function (team, callback) {
if (!team.teamid) return;
if (!this.loadingTeam) {
var app = this;
this.loadingTeam = true;
$.get(app.user.getActionPHP(), {
act: 'getteam',
teamid: team.teamid,
}, Storage.safeJSON(function (data) {
app.loadingTeam = false;
if (data.actionerror) {
return app.addPopupMessage("Error loading team: " + data.actionerror);
}
team.privacy = data.privacy;
team.team = data.team;
team.loaded = true;
callback(team);
var entry = app.loadingTeamQueue.shift();
if (entry) {
app.loadTeam(entry[0], entry[1]);
}
}));
} else {
this.loadingTeamQueue.push([team, callback]);
}
},
/**
* Send team to sim server
*/
sendTeam: function (team, callback) {
if (team && team.teamid && !team.loaded) {
return this.loadTeam(team, function (team) {
app.sendTeam(team, callback);
});
}
var packedTeam = '' + Storage.getPackedTeam(team);
if (packedTeam.length > 25 * 1024 - 6) {
alert("Your team is over 25 KB. Please use a smaller team.");
return;
}
this.send('/utm ' + packedTeam);
callback();
},
/**
* Receive from sim server
*/
receive: function (data) {
var roomid = '';
var autojoined = false;
if (data.charAt(0) === '>') {
var nlIndex = data.indexOf('\n');
if (nlIndex < 0) return;
roomid = toRoomid(data.substr(1, nlIndex - 1));
data = data.substr(nlIndex + 1);
}
if (data.substr(0, 6) === '|init|') {
if (!roomid) roomid = 'lobby';
var roomType = data.substr(6);
var roomTypeLFIndex = roomType.indexOf('\n');
if (roomTypeLFIndex >= 0) roomType = roomType.substr(0, roomTypeLFIndex);
roomType = toID(roomType);
if (this.rooms[roomid] || roomid === 'staff' || roomid === 'upperstaff') {
// autojoin rooms are joined in background