forked from smogon/pokemon-showdown-client
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathclient.js
2769 lines (2599 loc) · 95.4 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($) {
if (window.nodewebkit) {
window.gui = require('nw.gui');
window.nwWindow = gui.Window.get();
}
$(document).on('click', 'a', function(e) {
if (this.href && this.className !== 'closebutton' && (this.href.substr(0, 32) === 'http://play.pokemonshowdown.com/' || this.href.substr(0, 33) === 'https://play.pokemonshowdown.com/')) {
var target;
if (this.href.charAt(4) === ':') {
target = this.href.substr(32);
} else {
target = this.href.substr(33);
}
if (target.indexOf('/') < 0 && target.indexOf('.') < 0) {
window.app.tryJoinRoom(target);
e.preventDefault();
e.stopPropagation();
e.stopImmediatePropagation();
return;
}
}
if (window.nodewebkit && this.target === '_blank') {
gui.Shell.openExternal(this.href);
e.preventDefault();
e.stopPropagation();
e.stopImmediatePropagation();
}
});
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);
});
}
Config.version = '0.9.3';
Config.origindomain = 'play.pokemonshowdown.com';
// `defaultserver` specifies the server to use when the domain name in the
// address bar is `Config.origindomain`.
Config.defaultserver = {
id: 'showdown',
host: 'sim.smogon.com',
port: 443,
httpport: 8000,
altport: 80,
registered: true
};
Config.sockjsprefix = '/showdown';
Config.root = '/';
// sanitize a room ID
// shouldn't actually do anything except against a malicious server
var toRoomid = this.toRoomid = function(roomid) {
return roomid.replace(/[^a-zA-Z0-9-]+/g, '');
};
// 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;
};
// placeholder until the real chart loads
window.Chart = {
pokemonRow: function() {},
itemRow: function() {},
abilityRow: function() {},
moveRow: function() {}
};
var User = this.User = Backbone.Model.extend({
defaults: {
name: '',
userid: '',
registered: false,
named: false,
avatar: 0
},
initialize: function() {
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 {
self.nameRegExp = new RegExp('\\b'+Tools.escapeRegExp(self.get('name'))+'\\b', 'i');
}
});
},
/**
* 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.origindomain + 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 === ';') {
this.trigger('login:authrequired', name);
} else if (assertion.substr(0, 2) === ';;') {
this.trigger('login:invalidname', name, assertion.substr(2));
} else if (assertion.indexOf('\n') >= 0) {
this.trigger('login:noresponse');
} else {
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, '');
var userid = toUserid(name);
if (!userid) {
app.addPopupMessage("Usernames must contain at least one letter or number.");
return;
}
if (this.get('userid') !== userid) {
var query = this.getActionPHP() + '?act=getassertion&userid=' +
encodeURIComponent(userid) +
'&challengekeyid=' + encodeURIComponent(this.challengekeyid) +
'&challenge=' + encodeURIComponent(this.challenge);
var self = this;
$.get(query, function(data) {
self.finishRename(name, data);
});
} else {
app.send('/trn ' + name);
}
},
passwordRename: function(name, password) {
var self = this;
$.post(this.getActionPHP(), {
act: 'login',
name: name,
pass: password,
challengekeyid: this.challengekeyid,
challenge: this.challenge
}, Tools.safeJSON(function(data) {
if (data && data.curuser && data.curuser.loggedin) {
// success!
self.set('registered', data.curuser);
self.finishRename(name, data.assertion);
} else {
// wrong password
app.addPopup(LoginPasswordPopup, {
username: name,
error: 'Wrong password.'
});
}
}), 'text');
},
challengekeyid: -1,
challenge: '',
receiveChallenge: function(attrs) {
if (attrs.challenge) {
/**
* 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.
*/
var query = this.getActionPHP() + '?act=upkeep' +
'&challengekeyid=' + encodeURIComponent(attrs.challengekeyid) +
'&challenge=' + encodeURIComponent(attrs.challenge);
var self = this;
$.get(query, Tools.safeJSON(function(data) {
if (!data.username) 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');
}
this.challengekeyid = attrs.challengekeyid;
this.challenge = attrs.challenge;
},
/**
* 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');
},
setPersistentName: function(name) {
$.cookie('showdown_username', (name !== undefined) ? name : this.get('name'), {
expires: 14
});
},
});
var App = this.App = Backbone.Router.extend({
root: '/',
routes: {
'*path': 'dispatchFragment'
},
focused: true,
initialize: function() {
window.app = this;
this.initializeRooms();
this.initializePopups();
this.user = new User();
this.ignore = {};
this.supports = {};
// down
// if (document.location.hostname === 'play.pokemonshowdown.com') this.down = 'dos';
if (document.location.hostname === 'play.pokemonshowdown.com') {
app.supports['rooms'] = true;
}
this.topbar = new Topbar({el: $('#header')});
this.addRoom('');
if (!this.down && $(window).width() >= 916) {
if (document.location.hostname === 'play.pokemonshowdown.com') {
this.addRoom('rooms');
} else {
this.addRoom('lobby');
}
}
var self = this;
this.prefsLoaded = false;
this.on('init:loadprefs', function() {
self.prefsLoaded = true;
var bg = Tools.prefs('bg');
if (bg) {
$(document.body).css({
background: bg,
'background-size': 'cover'
});
} else if (Config.server.id === 'smogtours') {
$(document.body).css({
background: '#546bac url(//play.pokemonshowdown.com/fx/client-bg-shaymin.jpg) no-repeat left center fixed',
'background-size': 'cover'
});
}
var muted = Tools.prefs('mute');
BattleSound.setMute(muted);
var effectVolume = Tools.prefs('effectvolume');
if (effectVolume !== undefined) BattleSound.setEffectVolume(effectVolume);
var musicVolume = Tools.prefs('musicvolume');
if (musicVolume !== undefined) BattleSound.setBgmVolume(musicVolume);
if (Tools.prefs('logchat')) Storage.startLoggingChat();
if (Tools.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 (Tools.prefs('bwgfx') || Tools.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)
Tools.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() {
self.reconnectPending = true;
if (!self.popups.length) self.addPopup(ReconnectPopup);
});
this.on('init:connectionerror', function() {
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) {
self.addPopup(LoginPasswordPopup, {username: name});
});
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('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');
if (app.curSideRoom && $(e.target).closest(app.curSideRoom.$el).length) {
// keypress happened in sideroom
if (e.keyCode === 37 && safeLocation || window.nodewebkit && e.ctrlKey && e.shiftKey && e.keyCode === 9) {
// Left or Ctrl+Shift+Tab on desktop client
if (app.topbar.curSideRoomLeft) {
e.preventDefault();
e.stopImmediatePropagation();
app.focusRoom(app.topbar.curSideRoomLeft);
}
} else if (e.keyCode === 39 && safeLocation || window.nodewebkit && e.ctrlKey && e.keyCode === 9) {
// Right or Ctrl+Tab on desktop client
if (app.topbar.curSideRoomRight) {
e.preventDefault();
e.stopImmediatePropagation();
app.focusRoom(app.topbar.curSideRoomRight);
}
}
return;
}
// keypress happened outside of sideroom
if (e.keyCode === 37 && safeLocation || window.nodewebkit && e.ctrlKey && e.shiftKey && e.keyCode === 9) {
// Left or Ctrl+Shift+Tab on desktop client
if (app.topbar.curRoomLeft) {
e.preventDefault();
e.stopImmediatePropagation();
app.focusRoom(app.topbar.curRoomLeft);
}
} else if (e.keyCode === 39 && safeLocation || window.nodewebkit && e.ctrlKey && e.keyCode === 9) {
// Right or Ctrl+Tab on desktop client
if (app.topbar.curRoomRight) {
e.preventDefault();
e.stopImmediatePropagation();
app.focusRoom(app.topbar.curRoomRight);
}
}
});
this.initializeConnection();
Backbone.history.start({pushState: true});
},
/**
* 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:loadprefs`
* triggered when preferences/teams are finished loading and are
* safe to read
*
* `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() {
if ((document.location.hostname !== Config.origindomain) && !Config.testclient) {
// Handle *.psim.us.
return this.initializeCrossDomainConnection();
} else if (Config.testclient) {
this.initializeTestClient();
} else if (document.location.protocol === 'https:') {
/* if (!$.cookie('showdown_ssl')) {
// Never used HTTPS before, so we have to copy over the
// HTTP origin localStorage. We have to redirect to the
// HTTP site in order to do this. We set a cookie
// indicating that we redirected for the purpose of copying
// over the localStorage.
$.cookie('showdown_ssl_convert', 1);
return document.location.replace('http://' + document.location.hostname +
document.location.pathname);
} */
// Renew the `showdown_ssl` cookie.
$.cookie('showdown_ssl', 1, {expires: 365*3});
} else if (!$.cookie('showdown_ssl')) {
// localStorage is currently located on the HTTP origin.
if (!$.cookie('showdown_ssl_convert') || !('postMessage' in window)) {
// This user is not using HTTPS now and has never used
// HTTPS before, so her localStorage is still under the
// HTTP origin domain: connect on port 8000, not 443.
Config.defaultserver.port = Config.defaultserver.httpport;
} else {
// First time using HTTPS: copy the existing HTTP storage
// over to the HTTPS origin.
$(window).on('message', function($e) {
var e = $e.originalEvent;
var origin = 'https://' + Config.origindomain;
if (e.origin !== origin) return;
if (e.data === 'init') {
Storage.loadTeams();
e.source.postMessage($.toJSON({
teams: $.toJSON(Storage.teams),
prefs: $.toJSON(Tools.prefs.data)
}), origin);
} else if (e.data === 'done') {
// Set a cookie to indicate that localStorage is now under
// the HTTPS origin.
$.cookie('showdown_ssl', 1, {expires: 365*3});
localStorage.clear();
return document.location.replace('https://' + document.location.hostname +
document.location.pathname);
}
});
var $iframe = $('<iframe src="https://play.pokemonshowdown.com/crossprotocol.html" style="display: none;"></iframe>');
$('body').append($iframe);
return;
}
} else {
// The user is using HTTP right now, but has used HTTPS in the
// past, so her localStorage is located on the HTTPS origin:
// hence we need to use the cross-domain code to load the
// localStorage because the HTTPS origin is considered a
// different domain for the purpose of localStorage.
return this.initializeCrossDomainConnection();
}
// Simple connection: no cross-domain logic needed.
Config.server = Config.server || Config.defaultserver;
// Config.server.afd = true;
Storage.loadTeams();
this.trigger('init:loadprefs');
return this.connect();
},
/**
* Initialise the client when running on the file:// filesystem.
*/
initializeTestClient: function() {
var self = this;
var showUnsupported = function() {
self.addPopupMessage('The requested action is not supported by testclient.html. Please complete this action in the official client instead.');
};
$.get = function(uri, callback, type) {
if (type === 'html') {
uri += '&testclient';
}
if (uri[0] === '/') { // relative URI
uri = Tools.resourcePrefix + uri.substr(1);
}
self.addPopup(ProxyPopup, {uri: uri, callback: callback});
};
$.post = function(/*uri, data, callback, type*/) {
showUnsupported();
};
},
/**
* Handle a cross-domain connection: that is, a connection where the
* client is loaded from a different domain from the one where the
* user's localStorage is located.
*/
initializeCrossDomainConnection: function() {
if (!('postMessage' in window)) {
// browser does not support cross-document messaging
return this.trigger('init:unsupported');
}
// If the URI in the address bar is not `play.pokemonshowdown.com`,
// we receive teams, prefs, and server connection information from
// crossdomain.php on play.pokemonshowdown.com.
var self = this;
$(window).on('message', (function() {
var origin;
var callbacks = {};
var callbackIdx = 0;
return function($e) {
var e = $e.originalEvent;
if ((e.origin === 'http://' + Config.origindomain) ||
(e.origin === 'https://' + Config.origindomain)) {
origin = e.origin;
} else {
return; // unauthorised source origin
}
var data = $.parseJSON(e.data);
if (data.server) {
var postCrossDomainMessage = function(data) {
return e.source.postMessage($.toJSON(data), origin);
};
// server config information
Config.server = data.server;
// Config.server.afd = true;
if (Config.server.registered) {
var $link = $('<link rel="stylesheet" ' +
'href="//play.pokemonshowdown.com/customcss.php?server=' +
encodeURIComponent(Config.server.id) + '" />');
$('head').append($link);
}
// persistent username
self.user.setPersistentName = function(name) {
postCrossDomainMessage({
username: ((name !== undefined) ? name : this.get('name'))
});
};
// ajax requests
$.get = function(uri, callback, type) {
var idx = callbackIdx++;
callbacks[idx] = callback;
postCrossDomainMessage({get: [uri, idx, type]});
};
$.post = function(uri, data, callback, type) {
var idx = callbackIdx++;
callbacks[idx] = callback;
postCrossDomainMessage({post: [uri, data, idx, type]});
};
// teams
if (data.teams) {
Storage.teams = $.parseJSON(data.teams) || [];
} else {
Storage.teams = [];
}
self.trigger('init:loadteams');
Storage.saveTeams = function() {
postCrossDomainMessage({teams: $.toJSON(Storage.teams)});
};
// prefs
if (data.prefs) {
Tools.prefs.data = $.parseJSON(data.prefs);
}
self.trigger('init:loadprefs');
Tools.prefs.save = function() {
postCrossDomainMessage({prefs: $.toJSON(this.data)});
};
// check for third-party cookies being disabled
if (data.nothirdparty) {
self.trigger('init:nothirdparty');
}
// connect
self.connect();
} else if (data.ajax) {
var idx = data.ajax[0];
if (callbacks[idx]) {
callbacks[idx](data.ajax[1]);
delete callbacks[idx];
}
}
};
})());
var $iframe = $(
'<iframe src="//play.pokemonshowdown.com/crossdomain.php?host=' +
encodeURIComponent(document.location.hostname) +
'&path=' + encodeURIComponent(document.location.pathname.substr(1)) +
'" style="display: none;"></iframe>'
);
$('body').append($iframe);
},
/**
* 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;
var bannedHosts = ['cool.jit.su'];
if (Config.server.banned || bannedHosts.indexOf(Config.server.host) >= 0) {
this.addPopupMessage("This server has been deleted for breaking US laws or impersonating PS global staff.");
return;
}
var self = this;
var constructSocket = function() {
var protocol = (Config.server.port === 443) ? 'https' : 'http';
return new SockJS(protocol + '://' + Config.server.host + ':' +
Config.server.port + Config.sockjsprefix);
};
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 = Tools.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.socket.onmessage = function(msg) {
if (window.console && console.log) {
console.log('<< '+msg.data);
}
if (msg.data.charAt(0) !== '{') {
self.receive(msg.data);
return;
}
alert("This server is using an outdated version of Pokémon Showdown and needs to be updated.");
};
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) {
if (document.location.protocol === 'https:') {
if (confirm("Could not connect with HTTPS. Try HTTP?")) {
return document.location.replace('http://' +
document.location.host + document.location.pathname);
}
}
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) {
// Fragment dispatching doesn't work in testclient.html.
// Just open the main menu.
fragment = '';
}
fragment = toRoomid(fragment || '');
if (this.initialFragment === undefined) this.initialFragment = fragment;
this.tryJoinRoom(fragment);
},
/**
* Send to sim server
*/
send: function(data, room) {
if (room && room !== 'lobby' && 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);
},
/**
* Send team to sim server
*/
sendTeam: function(team) {
this.send('/utm '+Storage.packTeam(team));
},
/**
* Receive from sim server
*/
receive: function(data) {
var roomid = '';
if (data.substr(0,1) === '>') {
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') {
// staff is always joined in background
this.addRoom(roomid, roomType, true);
} else {
this.joinRoom(roomid, roomType, true);
}
} else if ((data+'|').substr(0,8) === '|expire|') {
var room = this.rooms[roomid];
if (room) {
room.expired = true;
if (room.updateUser) room.updateUser();
}
return;
} else if ((data+'|').substr(0,8) === '|deinit|' || (data+'|').substr(0,8) === '|noinit|') {
if (!roomid) roomid = 'lobby';
if (this.rooms[roomid] && this.rooms[roomid].expired) {
// expired rooms aren't closed when left
return;
}
var isdeinit = (data.charAt(1) === 'd');
data = data.substr(8);
var pipeIndex = data.indexOf('|');
var errormessage;
if (pipeIndex >= 0) {
errormessage = data.substr(pipeIndex+1);
data = data.substr(0, pipeIndex);
}
// handle error codes here
// data is the error code
if (data === 'namerequired') {
this.removeRoom(roomid);
var self = this;
this.once('init:choosename', function() {
self.joinRoom(roomid);
});
} else {
if (isdeinit) { // deinit
this.removeRoom(roomid, true);
} else { // noinit
this.unjoinRoom(roomid);
if (roomid === 'lobby') this.joinRoom('rooms');
}
if (errormessage) {
this.addPopupMessage(errormessage);
}
}
return;
}
if (roomid) {
if (this.rooms[roomid]) {
this.rooms[roomid].receive(data);
}
return;
}
// Since roomid is blank, it could be either a global message or
// a lobby message. (For bandwidth reasons, lobby messages can
// have blank roomids.)
// If it starts with a messagetype in the global messagetype
// list, we'll assume global; otherwise, we'll assume lobby.
var parts;
if (data.charAt(0) === '|') {
parts = data.substr(1).split('|');
} else {
parts = [];
}
switch (parts[0]) {
case 'challenge-string':
case 'challstr':
this.user.receiveChallenge({
challengekeyid: parseInt(parts[1], 10),
challenge: parts[2]
});
break;
case 'formats':
this.parseFormats(parts);
break;
case 'updateuser':
var nlIndex = data.indexOf('\n');
if (nlIndex > 0) {
this.receive(data.substr(nlIndex+1));
nlIndex = parts[3].indexOf('\n');
parts[3] = parts[3].substr(0, nlIndex);
}
var name = parts[1];
var named = !!+parts[2];
this.user.set({
name: name,
userid: toUserid(name),
named: named,
avatar: parts[3]
});
this.user.setPersistentName(named ? name : null);
if (named) {
this.trigger('init:choosename');
}
break;
case 'nametaken':
app.addPopup(LoginPopup, {name: parts[1] || '', error: parts[2] || ''});
break;
case 'queryresponse':
var responseData = JSON.parse(data.substr(16+parts[1].length));
app.trigger('response:'+parts[1], responseData);
break;
case 'updatechallenges':
if (this.rooms['']) {
this.rooms[''].updateChallenges($.parseJSON(data.substr(18)));
}
break;
case 'updatesearch':
if (this.rooms['']) {
this.rooms[''].updateSearch($.parseJSON(data.substr(14)));
}
break;
case 'popup':
this.addPopupMessage(data.substr(7).replace(/\|\|/g, '\n'));
if (this.rooms['']) this.rooms[''].resetPending();
break;
case 'pm':
var message = parts.slice(3).join('|');
this.rooms[''].addPM(parts[1], message, parts[2]);
break;
case 'roomerror':
// deprecated; use |deinit| or |noinit|
this.unjoinRoom(parts[1]);
this.addPopupMessage(parts.slice(2).join('|'));
break;
case 'c':
case 'chat':
if (parts[1] === '~') {
if (parts[2].substr(0, 6) === '/warn ') {
app.addPopup(RulesPopup, {warning: parts[2].substr(6)});
break;
}
}
/* fall through */
default:
// the messagetype wasn't in our list of recognized global
// messagetypes; so the message is presumed to be for the
// lobby.
if (this.rooms['lobby']) {
this.rooms['lobby'].receive(data);
}
break;
}
},
parseFormats: function(formatsList) {
var isSection = false;
var section = '';
var column = 0;
var columnChanged = false;
BattleFormats = {};
for (var j=1; j<formatsList.length; j++) {
if (isSection) {
section = formatsList[j];
isSection = false;
} else if (formatsList[j] === '' || (formatsList[j].substr(0, 1) === ',' && !isNaN(formatsList[j].substr(1)))) {
isSection = true;
if (formatsList[j]) {
var newColumn = parseInt(formatsList[j].substr(1)) || 0;