forked from zaheerm/flumotion-extra
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Orbited.js
2700 lines (2449 loc) · 101 KB
/
Orbited.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
// NOTE: to log/debug with Orbited, there are two methods:
// Use firebug
// 1) include Orbited.js (and not Log4js)
// 2) Orbited.loggers[LOGGERNAME].enabled = true
// And it should do logging for that logger
// Use log4js
// 1) include log4js.js BEFORE including Orbited.js
// 2) Orbited.loggers[LOGGERNAME].setLevel(Log4js.Level.ALL)
// 3) Orbited.loggers[LOGGERNAME].addAppender(new Log4js.ConsoleAppender())
// Note: Other levels and appenders can be set as well (see Log4js docs)
//
// For either method to work, you must set Orbited.settings.log to true.
//
// When you are making a call to the logger, prefix the line (first three
// Characters) with ;;; which we will strip out at build time. So if you
// have an if statement thats logging specific, start that line with ;;;
// as well. If you do a try/catch thats specific to logging, prefix all
// lines involved with ;;;. You'll want to put the try closing } and the
// catch statement on the same line, or this won't work.
//
// the logging functions (info, warn, debug, error, etc.) take any number
// of arguments, like in firebug. If you're using firebug for the logging,
// you'll actually be able to inspect the objects that you log. Therefore
// don't do logger.debug(obj1 + " -> " + obj2); as this will convert both
// objects to strings and not allow you to inspect them in firebug.
// Instead call logger.debug(obj1, "->" obj2); Of course, for the Log4js
// back-end, it will still toString the objects.
(function() {
var HANDSHAKE_TIMEOUT = 30000;
var RETRY_INTERVAL = 250;
var RETRY_TIMEOUT = 30000;
Orbited = {};
Orbited.settings = {};
Orbited.settings.hostname = document.domain;
Orbited.settings.port = (location.port.length > 0) ? location.port : 80;
Orbited.settings.protocol = location.protocol.slice(0, -1);
Orbited.settings.log = false;
Orbited.settings.streaming = true;
Orbited.settings.HEARTBEAT_TIMEOUT = 6000;
Orbited.settings.POLL_INTERVAL = 2000;
Orbited.settings.pageLoggerHeight = '200px';
Orbited.settings.pageLoggerWidth = null;
Orbited.settings.enableFFPrivileges = false;
Orbited.singleton = {};
// Orbited CometSession Errors
Orbited.Errors = {};
Orbited.Errors.ConnectionTimeout = 101;
Orbited.Errors.InvalidHandshake = 102;
Orbited.Errors.UserConnectionReset = 103;
Orbited.Errors.Unauthorized = 106;
Orbited.Errors.RemoteConnectionFailed = 108;
Orbited.Statuses = {};
Orbited.Statuses.ServerClosedConnection = 201;
Orbited.Statuses.SocketControlKilled = 301;
Orbited.util = {};
Orbited.util.browser = null;
if (typeof(ActiveXObject) != "undefined") {
Orbited.util.browser = 'ie';
} else if (navigator.userAgent.indexOf('WebKit') != -1 || navigator.userAgent.indexOf('Konqueror') != -1) {
Orbited.util.browser = 'webkit';
} else if (navigator.product == 'Gecko' && window.find && !navigator.savePreferences) {
Orbited.util.browser = 'firefox';
} else if((typeof window.addEventStream) === 'function') {
Orbited.util.browser = 'opera';
}
////
// NB: Base64 code was borrowed from Dojo; we had to fix decode for not
// striping NULs though. Tom Trenka from Dojo wont fix this because
// he claims it helped to detect and avoid broken encoded data.
// See http://svn.dojotoolkit.org/src/dojox/trunk/encoding/base64.js
// See http://bugs.dojotoolkit.org/ticket/7400
(function(){
Orbited.base64 = {};
var p = "=";
var tab = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
if (window.btoa && window.btoa('1') == 'MQ==') {
Orbited.base64.encode = function(data) { return btoa(data); };
Orbited.base64.decode = function(data) { return atob(data); };
return;
}
Orbited.base64.encode=function(/* String */ba){
// summary
// Encode a string as a base64-encoded string
var s=[];
var l=ba.length;
var rm=l%3;
var x=l-rm;
for (var i=0; i<x;){
var t=ba.charCodeAt(i++)<<16|ba.charCodeAt(i++)<<8|ba.charCodeAt(i++);
s.push(tab.charAt((t>>>18)&0x3f));
s.push(tab.charAt((t>>>12)&0x3f));
s.push(tab.charAt((t>>>6)&0x3f));
s.push(tab.charAt(t&0x3f));
}
// deal with trailers, based on patch from Peter Wood.
switch(rm){
case 2:
t=ba.charCodeAt(i++)<<16|ba.charCodeAt(i++)<<8;
s.push(tab.charAt((t>>>18)&0x3f));
s.push(tab.charAt((t>>>12)&0x3f));
s.push(tab.charAt((t>>>6)&0x3f));
s.push(p);
break;
case 1:
t=ba.charCodeAt(i++)<<16;
s.push(tab.charAt((t>>>18)&0x3f));
s.push(tab.charAt((t>>>12)&0x3f));
s.push(p);
s.push(p);
break;
}
return s.join(""); // string
};
Orbited.base64.decode=function(/* string */str){
// summary
// Convert a base64-encoded string to an array of bytes
var s=str.split("");
var out=[];
var l=s.length;
var tl=0;
while(s[--l]==p){ ++tl; } // strip off trailing padding
for (var i=0; i<l;){
var t=tab.indexOf(s[i++])<<18;
if(i<=l){ t|=tab.indexOf(s[i++])<<12; }
if(i<=l){ t|=tab.indexOf(s[i++])<<6; }
if(i<=l){ t|=tab.indexOf(s[i++]); }
out.push(String.fromCharCode((t>>>16)&0xff));
out.push(String.fromCharCode((t>>>8)&0xff));
out.push(String.fromCharCode(t&0xff));
}
// strip off trailing padding
while(tl--){ out.pop(); }
return out.join(""); // string
};
})();
Orbited.loggers = {};
Orbited.Loggers = {};
Orbited.util.loggingSystem = null;
if (window.Log4js) {
Orbited.util.loggingSystem = 'log4js';
}
else if (window.console && console.firebug && console.firebug != "1.3.0") {
Orbited.util.loggingSystem = 'firebug';
}
Orbited.getLogger = function(name) {
if (!Orbited.loggers[name]) {
var logger = null;
switch (Orbited.util.loggingSystem) {
case 'firebug':
logger = new Orbited.Loggers.FirebugLogger(name);
break;
case 'log4js':
logger = new Orbited.Loggers.Log4jsLogger(name);
break;
default:
logger = new Orbited.Loggers.PageLogger(name);
break;
}
Orbited.loggers[name] = logger;
}
return Orbited.loggers[name];
};
// TODO: is it confusing to have Orbited.Loggers be the various logging classes
// and Orbited.loggers be actual instances of logging classes?
Orbited.Loggers.FirebugLogger = function(name) {
var self = this;
self.name = name;
self.enabled = false;
var padArgs = function(args) {
var newArgs = [ name + ":" ];
for (var i = 0; i < args.length; ++i) {
newArgs.push(args[i]);
}
return newArgs;
};
self.log = function() {
if (!self.enabled) { return; }
console.log.apply(this, padArgs(arguments));
};
self.debug = function() {
if (!self.enabled) { return; }
console.debug.apply(this, padArgs(arguments));
};
self.info = function() {
if (!self.enabled) { return; }
console.info.apply(this, padArgs(arguments));
};
self.warn = function() {
if (!self.enabled) { return; }
console.warn.apply(this, padArgs(arguments));
};
self.error = function() {
if (!self.enabled) { return; }
console.error.apply(this, padArgs(arguments));
};
self.assert = function() {
if (!self.enabled) { return; }
var newArgs = [arguments[0], name + ":" ];
for (var i = 1; i < arguments.length; ++i) {
newArgs.push(arguments[i]);
}
console.assert.apply(this, newArgs);
};
self.trace = function() {
if (!self.enabled) { return; }
console.trace.apply(this, padArgs(arguments));
};
};
Orbited.singleton.pageLoggerPane = null;
Orbited.Loggers.PageLogger = function(name) {
var self = this;
self.enabled = false;
self.name = name;
var checkPane = function() {
if (!Orbited.singleton.pageLoggerPane) {
var p = document.createElement("div");
p.border = "1px solid black";
if(Orbited.settings.pageLoggerHeight) {
p.style.height = Orbited.settings.pageLoggerHeight;
}
if(Orbited.settings.pageLoggerWidth) {
p.style.height = Orbited.settings.pageLoggerWidth;
}
p.style.overflow = "scroll";
document.body.appendChild(p);
Orbited.singleton.pageLoggerPane = p;
}
};
var show = function(data) {
checkPane();
var d = document.createElement('div');
d.innerHTML = data;
Orbited.singleton.pageLoggerPane.appendChild(d);
Orbited.singleton.pageLoggerPane.scrollTop = Orbited.singleton.pageLoggerPane.scrollHeight;
};
self.log = function() {
if (!self.enabled) { return; }
var newArgs = [ "log", new Date(), "debug", "<b>" + name + "</b>" ];
for (var i = 0; i < arguments.length; ++i) {
newArgs.push(arguments[i]);
}
show(newArgs.join(", "));
};
self.debug = function() {
if (!self.enabled) { return; }
var newArgs = [ new Date(), "debug", "<b>" + name + "</b>" ];
for (var i = 0; i < arguments.length; ++i) {
newArgs.push(arguments[i]);
}
show(newArgs.join(", "));
};
self.info = function() {
if (!self.enabled) { return; }
var newArgs = [ new Date(), "info", "<b>" + name + "</b>" ];
for (var i = 0; i < arguments.length; ++i) {
newArgs.push(arguments[i]);
}
show(newArgs.join(", "));
};
self.warn = function() {
};
self.error = function() {
};
self.assert = function() {
};
self.trace = function() {
};
};
Orbited.Loggers.Log4jsLogger = function(name) {
var self = this;
self.name = name;
// NOTE: Why oh WHY doesn't Log4js accept dots in the logger names, and
// more importantly, why don't they have reasonble error messages?!
var log4jsName = name;
while (log4jsName.indexOf('.') != -1) {
log4jsName = log4jsName.replace('.', '_');
}
var logger = Log4js.getLogger(log4jsName);
self.logger = logger;
logger.setLevel(Log4js.Level.OFF);
var generateOutput = function(args) {
var newArgs = [ name + ":" ];
for (var i = 0; i < args.length; ++i) {
newArgs.push(args[i]);
}
return newArgs.join(" ");
};
self.setLevel = function(level) {
logger.setLevel(level);
};
self.addAppender = function(a) {
logger.addAppender(a);
};
self.log= function() {
// NOTE: log doesn't mean anything in Log4js. mapping it to info
logger.info(generateOutput(arguments));
};
self.debug = function() {
logger.debug(generateOutput(arguments));
};
self.info = function() {
logger.info(generateOutput(arguments));
};
self.warn = function() {
logger.warn(generateOutput(arguments));
};
self.error = function() {
logger.error(generateOutput(arguments));
};
self.assert = function() {
};
self.trace = function() {
};
};
Orbited.system = Orbited.getLogger('system');
Orbited.CometTransports = {};
Orbited.util.chooseTransport = function() {
if (Orbited.settings.streaming == false || Orbited.util.browser == "webkit") {
return Orbited.CometTransports.LongPoll;
}
var choices = [];
for (var name in Orbited.CometTransports) {
var transport = Orbited.CometTransports[name];
if (typeof(transport[Orbited.util.browser]) == "number") {
Orbited.system.log('viable transport: ', name);
choices.push(transport);
}
}
// TODO: sort the choices by the values of transport[Orbited.util.browser]
// and return the transport with the highest value.
// return XHRStream
return choices[0];
};
var createXHR = function () {
try { return new XMLHttpRequest(); } catch(e) {}
try { return new ActiveXObject('MSXML3.XMLHTTP'); } catch(e) {}
try { return new ActiveXObject('MSXML2.XMLHTTP.3.0'); } catch(e) {}
try { return new ActiveXObject('Msxml2.XMLHTTP'); } catch(e) {}
try { return new ActiveXObject('Microsoft.XMLHTTP'); } catch(e) {}
throw new Error('Could not find XMLHttpRequest or an alternative.');
};
Orbited.legacy = {};
//Orbited.web.connect = function() {
//
//}
Orbited.CometSession = function() {
var self = this;
self.readyState = self.READY_STATE_INITIALIZED;
self.onopen = function() {};
self.onread = function() {};
self.onclose = function() {};
var sessionUrl = null;
var sessionKey = null;
var sendQueue = [];
var packetCount = 0;
var xhr = null;
var handshakeTimer = null;
var cometTransport = null;
var pingInterval = 30000;
var pingTimeout = 30000;
var timeoutTimer = null;
var lastPacketId = 0;
var sending = false;
var xsdClose = null;
/*
* This will always fire same-domain and cross-subdomain.
* It will fire most of the time cross-port, but it's not
* strictly guaranteed.
* -mario
*/
var hardClose = function() {
var tdata = encodePackets([[++packetCount, "close"]]);
if (xsdClose) {
xsdClose.contentWindow.sendCloseFrame(sessionUrl.render(),tdata);
}
else {
xhr.open('POST', sessionUrl.render(), !sessionUrl.isSameDomain(location.href));
xhr.send(tdata);
}
}
/*
* self.open can only be used when readyState is INITIALIZED. Immediately
* following a call to self.open, the readyState will be OPENING until a
* connection with the server has been negotiated. self.open takes a url
* as a single argument which desiginates the remote url with which to
* establish the connection.
*/
self.open = function(_url) {
;;; self.logger.debug('open');
self.readyState = self.READY_STATE_OPENING;
sessionUrl = new Orbited.URL(_url);
if (sessionUrl.isSameDomain(location.href)) {
xhr = createXHR();
}
else {
xhr = new Orbited.XSDR();
if (sessionUrl.isSamePort(location.href)) {
xsdClose = document.createElement('iframe');
xsdClose.style.display = 'block';
xsdClose.style.width = '0';
xsdClose.style.height = '0';
xsdClose.style.border = '0';
xsdClose.style.margin = '0';
xsdClose.style.padding = '0';
xsdClose.style.overflow = 'hidden';
xsdClose.style.visibility = 'hidden';
var ifUrl = new Orbited.URL("");
ifUrl.protocol = Orbited.settings.protocol;
ifUrl.domain = Orbited.settings.hostname;
ifUrl.port = Orbited.settings.port;
ifUrl.path = '/static/xsdClose.html';
ifUrl.hash = document.domain;
xsdClose.src = ifUrl.render();
document.body.appendChild(xsdClose);
}
}
if (Orbited.settings.enableFFPrivileges) {
try {
netscape.security.PrivilegeManager.enablePrivilege('UniversalBrowserRead');
} catch (ex) { }
}
xhr.open('GET', _url, true);
xhr.onreadystatechange = function() {
if (xhr.readyState == 4) {
if (xhr.status == 200) {
sessionKey = xhr.responseText;
;;; self.logger.debug('session key is: ', sessionKey);
resetTimeout();
// START new URL way
// sessionUrl.extendPath(sessionKey)
// END: new URL way
// START: old URL way
if (sessionUrl.path[sessionUrl.path.length] != '/') {
sessionUrl.path += '/';
}
sessionUrl.path += sessionKey;
// END: old Url way
var transportClass = Orbited.util.chooseTransport();
cometTransport = new transportClass();
cometTransport.timeoutResetter = resetTimeout;
cometTransport.isSubDomain = sessionUrl.isSubDomain(location.href);
cometTransport.onReadFrame = transportOnReadFrame;
cometTransport.onclose = transportOnClose;
cometTransport.connect(sessionUrl.render());
} else {
xhr = null;
self.readyState = self.READY_STATE_CLOSED;
self.onclose(Orbited.Errors.InvalidHandshake);
}
}
};
xhr.send(null);
};
/*
* self.send is only callable when readyState is OPEN. It will queue the data
* up for delivery as soon as the upstream xhr is ready.
*/
self.send = function(data) {
;;; self.logger.debug('send', data);
if (self.readyState != self.READY_STATE_OPEN) {
throw new Error("Invalid readyState");
}
// if (cometTransport.limbo) {
//;;; self.logger.debug('limbo is true. setting sending to false');
// sending = false;
// }
data = Orbited.base64.encode(data);
sendQueue.push([++packetCount, "data", data]);
;;; self.logger.debug('sending ==', sending);
if (!sending) {
;;; self.logger.debug('starting send');
doSend();
}
};
/*
* self.close sends a close frame to the server, at the end of the queue.
* It also sets the readyState to CLOSING so that no further data may be
* sent. onclose is not called immediately -- it waits for the server to
* send a close event.
*/
self.close = function() {
switch(self.readyState) {
case self.READY_STATE_CLOSING:
case self.READY_STATE_CLOSED:
return;
case self.READY_STATE_INITIALIZED:
// TODO: call onclose here?
self.readyState = self.READY_STATE_CLOSED;
return;
default:
break;
}
self.readyState = self.READY_STATE_CLOSING;
sendQueue.push([++packetCount, "close"]);
if (!sending) {
doSend();
}
};
/* self.reset is a way to close immediately. The send queue will be discarded
* and a close frame will be sent to the server. onclose is called immediately
* without waiting for a reply from the server.
*/
self.reset = function() {
;;; self.logger.debug('reset');
var origState = self.readyState;
self.readyState = self.READY_STATE_CLOSED;
switch(origState) {
case self.READY_STATE_INITIALIZED:
self.onclose(Orbited.Errors.UserConnectionReset);
break;
case self.READY_STATE_OPENING:
xhr.onreadystatechange = function() {};
xhr.abort();
self.onclose(Orbited.Errors.UserConnectionReset);
break;
case self.READY_STATE_OPEN:
self.sendQueue = [];
self.sending = false;
if (xhr.readyState < 4) {
xhr.onreadystatechange = function() {};
xhr.abort();
}
doClose(Orbited.Errors.UserConnectionReset);
hardClose();
break;
case self.READY_STATE_CLOSING:
// TODO: Do nothing here?
// we need to figure out if we've attempted to send the close
// frame yet or not If not, we do something similar to case
// OPEN. either way, we should kill the transport and
// trigger onclose
// -mcarter 7-29-08
break;
case self.READY_STATE_CLOSED:
break;
}
};
self.cleanup = function() {
self.readyState = self.READY_STATE_CLOSED;
cometTransport.close();
}
var transportOnReadFrame = function(frame) {
;;; self.logger.debug('transportOnReadFrame');
;;; self.logger.debug('READ FRAME: ', frame.id, frame.name, frame.data ? frame.data.length : '');
if (!isNaN(frame.id)) {
lastPacketId = Math.max(lastPacketId, frame.id);
}
;;; self.logger.debug(frame);
switch(frame.name) {
case 'close':
if (self.readyState < self.READY_STATE_CLOSED) {
doClose(Orbited.Statuses.ServerClosedConnection);
}
break;
case 'data':
;;; self.logger.debug('base64 decoding ' + frame.data.length + ' bytes of data');
var data = Orbited.base64.decode(frame.data);
;;; self.logger.debug('decode complete');
self.onread(data);
break;
case 'open':
if (self.readyState == self.READY_STATE_OPENING) {
self.readyState = self.READY_STATE_OPEN;
;;; self.logger.debug('Call self.onopen()');
self.onopen();
}
else {
//TODO Throw and error?
}
break;
case 'ping':
// TODO: don't have a third element (remove the null).
// NOTE: don't waste a request when we get a longpoll ping.
switch(cometTransport.name) {
case 'longpoll':
break;
case 'poll':
break;
default:
sendQueue.push([++packetCount, "ping", null]);
if (!sending) {
doSend();
}
break;
}
break;
case 'opt':
var args = frame.data.split(',');
switch(args[0]) {
case 'pingTimeout':
pingTimeout = parseInt(args[1])*1000;
break;
case 'pingInterval':
pingInterval = parseInt(args[1])*1000;
break;
default:
;;; self.logger.warn('unknown opt key', args[0]);
break;
}
break;
}
;;; self.logger.debug("resetting timeout from transportOnReadFrame");
resetTimeout();
};
var transportOnClose = function() {
;;; self.logger.debug('transportOnClose');
if (self.readyState < self.READY_STATE_CLOSED) {
try {
doClose(Orbited.Statuses.ServerClosedConnection);
}
catch(e) {
// Fix for navigation-close
return;
}
}
};
var encodePackets = function(queue) {
//TODO: optimize this.
var output = [];
for (var i =0; i < queue.length; ++i) {
var frame = queue[i];
for (var j =0; j < frame.length; ++j) {
var arg = frame[j];
if (arg == null) {
arg = "";
}
if (j == frame.length-1) {
output.push('0');
}
else {
output.push('1');
}
output.push(arg.toString().length);
output.push(',');
output.push(arg.toString());
}
}
return output.join("");
};
var doSend = function(retries) {
;;; self.logger.debug('in doSend');
if (typeof(retries) == "undefined") {
retries = 0;
}
// TODO: I don't think this timeout formula is quite right...
// -mcarter 8-3-08
if (retries*RETRY_INTERVAL >= RETRY_TIMEOUT) {
doClose(Orbited.Errors.ConnectionTimeout);
sending = false;
return;
}
if (sendQueue.length == 0) {
;;; self.logger.debug('sendQueue exhausted');
sending = false;
return;
}
sending = true;
;;; self.logger.debug('setting sending=true');
var numSent = sendQueue.length;
sessionUrl.setQsParameter('ack', lastPacketId);
var tdata = encodePackets(sendQueue);
;;; self.logger.debug('post', retries, tdata);
if (Orbited.settings.enableFFPrivileges) {
try {
netscape.security.PrivilegeManager.enablePrivilege('UniversalBrowserRead');
} catch (ex) { }
}
xhr.open('POST', sessionUrl.render(), true);
// NB: its awkard, but for reusing the XHR object in IE (7 at least),
// we can only reset the onreadystatechange *after* we call open;
// if we don't do this, the XHR will stop sending data.
// See "Reusing XMLHttpRequest Object in IE"
// at http://keelypavan.blogspot.com/2006/03/reusing-xmlhttprequest-object-in-ie.html
xhr.onreadystatechange = function() {
;;; self.logger.debug('doSend onreadystatechange');
switch(xhr.readyState) {
case 4:
if (xhr.status == 200) {
resetTimeout();
sendQueue.splice(0, numSent);
return doSend();
}
else {
//TODO: implement retry back-off;
window.setTimeout(function(){doSend(++retries);},RETRY_INTERVAL);
}
break;
}
};
xhr.send(tdata);
};
var doClose = function(code) {
;;; self.logger.debug('doClose', code);
unsetTimeout();
self.readyState = self.READY_STATE_CLOSED;
if (cometTransport != null) {
// TODO: is this line necessary?
cometTransport.onReadFrame = function() {};
cometTransport.onclose = function() { };
cometTransport.close();
}
self.onclose(code);
};
var resetTimeout = function() {
;;; self.logger.debug('reset Timeout', pingInterval+pingTimeout);
unsetTimeout();
timeoutTimer = window.setTimeout(timedOut, pingInterval + pingTimeout);
};
var unsetTimeout = function() {
window.clearTimeout(timeoutTimer);
};
var timedOut = function() {
;;; self.logger.debug('timed out!');
doClose(Orbited.Errors.ConnectionTimeout);
};
};
Orbited.CometSession.prototype.logger = Orbited.getLogger("Orbited.CometSession");
Orbited.CometSession.prototype.READY_STATE_INITIALIZED = 1;
Orbited.CometSession.prototype.READY_STATE_OPENING = 2;
Orbited.CometSession.prototype.READY_STATE_OPEN = 3;
Orbited.CometSession.prototype.READY_STATE_CLOSING = 4;
Orbited.CometSession.prototype.READY_STATE_CLOSED = 5;
var currentTCPSocketId = 0;
var openSockets = {};
Orbited.test = {};
Orbited.test.logger = Orbited.getLogger("Orbited.test");
Orbited.test.socketcontrol = {};
Orbited.test.socketcontrol.kill = function(t) {
;;; Orbited.test.logger.debug("kill ordered for socket:", t);
if (openSockets[t.id]) {
openSockets[t.id](Orbited.Statuses.SocketControlKilled);
t = null;
;;; Orbited.test.logger.debug("socket killed");
}
else {
;;; Orbited.test.logger.debug("socket not found");
}
};
Orbited.test.stompdispatcher = {};
Orbited.test.stompdispatcher.send = function(dest, msg) {
;;; Orbited.test.logger.debug("stompdispatcher dispatching "+msg+" to "+dest);
var s = document.createElement('script');
s.src = "http://"+Orbited.settings.hostname+":"+Orbited.settings.port+"/system/test/stomp?";
s.src += "msg="+msg;
s.src += "&dest="+dest;
document.body.appendChild(s);
};
Orbited.TCPSocket = function() {
var self = this;
self.id = ++currentTCPSocketId;
// So we don't completely ambush people used to the 0.5 api...
if (arguments.length > 0) {
throw new Error("TCPSocket() accepts no arguments");
}
self.readyState = self.READY_STATE_INITIALIZED;
self.onopen = function() { };
self.onread = function() { };
self.onclose = function() { };
var onCloseTriggered = false;
var buffer = "";
var session = null;
var binary = false;
var handshakeState = null;
var hostname = null;
var port = null;
/* self.open attempts to establish a tcp connection to the specified remote
* hostname on the specified port. When specified as true, the optional
* argument, isBinary, will cause onread to return byte arrays, and send
* will only accept a byte array.
*/
self.open = function(_hostname, _port, isBinary) {
if (self.readyState != self.READY_STATE_INITIALIZED) {
// TODO: allow reuse from readyState == self.READY_STATE_CLOSED?
// Re-use makes sense for xhr due to memory concerns, but
// probably not for tcp sockets. How often do you reconnect
// in the same page?
// -mcarter 7-30-08
throw new Error("Invalid readyState");
}
if (_hostname == false) {
throw new Error("No hostname specified");
}
if (isNaN(_port)) {
throw new Error("Invalid port specified");
}
// handle isBinary undefined/null case
binary = !!isBinary;
self.readyState = self.READY_STATE_OPENING;
hostname = _hostname;
port = _port;
session = new Orbited.CometSession();
var sessionUrl = new Orbited.URL('/tcp');
sessionUrl.domain = Orbited.settings.hostname;
sessionUrl.port = Orbited.settings.port;
sessionUrl.protocol = Orbited.settings.protocol;
sessionUrl.setQsParameter('nocache', Math.random());
session.open(sessionUrl.render());
session.onopen = sessionOnOpen;
session.onread = sessionOnRead;
session.onclose = sessionOnClose;
handshakeState = "initial";
};
self.close = function() {
if (self.readyState == self.READY_STATE_CLOSED) {
return;
}
self.readyState = self.READY_STATE_CLOSED;
doClose(Orbited.Errors.UserConnectionReset);
};
/* self.reset closes the connection from this end immediately. The server
* may be notified, but there is no guarantee. The main purpose of the reset
* function is for a quick teardown in the case of a user navigation.
* if reset is not called when IE navigates, for instance, there will be
* potential issues with future TCPSocket communication.
*/
self.reset = function() {
if (session) {session.reset();}
};
self.send = function(data) {
if (self.readyState != self.READY_STATE_OPEN) {
throw new Error("Invalid readyState");
}
if (!binary) {
data = Orbited.utf8.encode(data);
}
;;; self.logger.debug('SEND: ', data);
// try {
session.send(data);
// }
// catch(e) {
// alert("Why sending: typeof(data) = " + typeof(data));
//}
};
var process = function() {
var result = Orbited.utf8.decode(buffer);
var data = result[0];
var i = result[1];
buffer = buffer.slice(i);
if (data.length > 0) {
window.setTimeout(function() { self.onread(data); }, 0);
}
};
var sessionOnRead = function(data) {
switch(self.readyState) {
case self.READY_STATE_OPEN:
;;; self.logger.debug('READ: ', data);
if (binary) {
window.setTimeout(function() { self.onread(data); }, 0);
}
else {
;;; self.logger.debug('start buffer size:', buffer.length);
buffer += data;
process();
;;; self.logger.debug('end buffer size:', buffer.length);
}
break;
case self.READY_STATE_OPENING:
switch(handshakeState) {
case 'initial':
// NOTE: we should only get complete payloads during
// the handshake. no need to buffer, then parse
data = Orbited.utf8.decode(data)[0];
;;; self.logger.debug('initial');
;;; self.logger.debug('data', data);
;;; self.logger.debug('len', data.length);
;;; self.logger.debug('typeof(data)', typeof(data));
;;; self.logger.debug('data[0] ', data.slice(0,1));
;;; self.logger.debug('type ', typeof(data.slice(0,1)));
var result = (data.slice(0,1) == '1');
;;; self.logger.debug('result', result);
if (!result) {
;;; self.logger.debug('!result');
var errorCode = data.slice(1,4);
doClose(parseInt(errorCode));
}
if (result) {
self.readyState = self.READY_STATE_OPEN;
;;; self.logger.debug('tcpsocket.onopen..');
self.onopen();
;;; self.logger.debug('did onopen');
}
break;
}
break;
}
};
var doClose = function(code) {
;;; self.logger.debug('doClose', code);
if (session) {
if (code == Orbited.Statuses.ServerClosedConnection || code == Orbited.Errors.Unauthorized || code == Orbited.Errors.RemoteConnectionFailed) {
session.cleanup();
}
else {
sessionOnClose = function() {};
session.close();
}
session = null;
}
;;; self.logger.debug('onCloseTriggered', onCloseTriggered);
if (!onCloseTriggered) {
;;; self.logger.debug('triggerClose timer', code);
onCloseTriggered = true;
window.setTimeout(function() {
;;; self.logger.debug('onclose!', code);
self.onclose(code);
}, 0);
}
};
openSockets[self.id] = doClose;
var sessionOnOpen = function(data) {
// TODO: TCPSocket handshake
var payload = hostname + ':' + port + '\n';
;;; self.logger.debug('sessionOpen; sending:', payload);
payload = Orbited.utf8.encode(payload);
;;; self.logger.debug('encoded payload:', payload);
X = payload;
session.send(payload);
handshakeState = 'initial';
};
var sessionOnClose = function(code) {
;;; self.logger.debug('sessionOnClose');
// If we are in the OPENING state, then the handshake code should
// handle the close