forked from flowersinthesand/portal
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathjquery.socket.js
More file actions
1628 lines (1427 loc) · 43.4 KB
/
jquery.socket.js
File metadata and controls
1628 lines (1427 loc) · 43.4 KB
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
/*
* jQuery stringifyJSON
* http://github.com/flowersinthesand/jquery-stringifyJSON
*
* Copyright 2011, Donghwan Kim
* Licensed under the Apache License, Version 2.0
* http://www.apache.org/licenses/LICENSE-2.0
*/
// This plugin is heavily based on Douglas Crockford's reference implementation
(function($) {
var escapable = /[\\\"\x00-\x1f\x7f-\x9f\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g,
meta = {
'\b' : '\\b',
'\t' : '\\t',
'\n' : '\\n',
'\f' : '\\f',
'\r' : '\\r',
'"' : '\\"',
'\\' : '\\\\'
};
function quote(string) {
return '"' + string.replace(escapable, function(a) {
var c = meta[a];
return typeof c === "string" ? c : "\\u" + ("0000" + a.charCodeAt(0).toString(16)).slice(-4);
}) + '"';
}
function f(n) {
return n < 10 ? "0" + n : n;
}
function str(key, holder) {
var i, v, len, partial, value = holder[key], type = typeof value;
if (value && typeof value === "object" && typeof value.toJSON === "function") {
value = value.toJSON(key);
type = typeof value;
}
switch (type) {
case "string":
return quote(value);
case "number":
return isFinite(value) ? String(value) : "null";
case "boolean":
return String(value);
case "object":
if (!value) {
return "null";
}
switch (Object.prototype.toString.call(value)) {
case "[object Date]":
return isFinite(value.valueOf()) ? '"' + value.getUTCFullYear() + "-" + f(value.getUTCMonth() + 1) + "-" + f(value.getUTCDate()) + "T" +
f(value.getUTCHours()) + ":" + f(value.getUTCMinutes()) + ":" + f(value.getUTCSeconds()) + "Z" + '"' : "null";
case "[object Array]":
len = value.length;
partial = [];
for (i = 0; i < len; i++) {
partial.push(str(i, value) || "null");
}
return "[" + partial.join(",") + "]";
default:
partial = [];
for (i in value) {
if (Object.prototype.hasOwnProperty.call(value, i)) {
v = str(i, value);
if (v) {
partial.push(quote(i) + ":" + v);
}
}
}
return "{" + partial.join(",") + "}";
}
}
}
$.stringifyJSON = function(value) {
if (window.JSON && window.JSON.stringify) {
return window.JSON.stringify(value);
}
return str("", {"": value});
};
}(jQuery));
/*
* jQuery Socket
* http://github.com/flowersinthesand/jquery-socket
*
* Copyright 2012, Donghwan Kim
* Licensed under the Apache License, Version 2.0
* http://www.apache.org/licenses/LICENSE-2.0
*/
(function($, undefined) {
var // Default options
defaults,
// Transports
transports,
// Socket instances
sockets = {},
// A global identifier
guid = $.now(),
// Callback names for JSONP
jsonpCallbacks = [],
// Is the unload event being processed?
unloading;
// From jQuery.Callbacks
function callbacks(deferred) {
var list = [],
locked,
memory,
firing,
firingStart,
firingLength,
firingIndex,
fire = function(context, args) {
args = args || [];
memory = !deferred || [context, args];
firing = true;
firingIndex = firingStart || 0;
firingStart = 0;
firingLength = list.length;
for (; firingIndex < firingLength; firingIndex++) {
list[firingIndex].apply(context, args);
}
firing = false;
},
self = {
add: function(fn) {
var length = list.length;
list.push(fn);
if (firing) {
firingLength = list.length;
} else if (!locked && memory && memory !== true) {
firingStart = length;
fire(memory[0], memory[1]);
}
},
remove: function(fn) {
var i;
for (i = 0; i < list.length; i++) {
if (fn === list[i] || (fn.guid && fn.guid === list[i].guid)) {
if (firing) {
if (i <= firingLength) {
firingLength--;
if (i <= firingIndex) {
firingIndex--;
}
}
}
list.splice(i--, 1);
}
}
},
fire: function(context, args) {
if (!locked && !firing && !(deferred && memory)) {
fire(context, args);
}
},
lock: function() {
locked = true;
},
locked: function() {
return !!locked;
},
unlock: function() {
locked = memory = firing = firingStart = firingLength = firingIndex = undefined;
}
};
return self;
}
function isBinary(data) {
var string = Object.prototype.toString.call(data);
return string === "[object Blob]" || string === "[object ArrayBuffer]";
}
function iterate(fn) {
var timeoutId;
// Though the interval is 1ms for real-time application, there is a delay between setTimeout calls
// For detail, see https://developer.mozilla.org/en/window.setTimeout#Minimum_delay_and_timeout_nesting
(function loop() {
timeoutId = setTimeout(function() {
if (fn() === false) {
return;
}
loop();
}, 1);
})();
return function() {
clearTimeout(timeoutId);
};
}
function getAbsoluteURL(url) {
return decodeURI($('<a href="' + url + '"/>')[0].href);
}
// Socket function
function socket(url, options) {
var // Final options
opts,
// Transport
transport,
// The state of the connection
state,
// Event helpers
events = {},
eventId = 0,
// Reply callbacks
replyCallbacks = {},
// Buffer
buffer = [],
// Reconnection
reconnectTimer,
reconnectDelay,
reconnectTry,
// Map of the session-scoped values
session = {},
// From jQuery.ajax
parts = /^([\w\+\.\-]+:)(?:\/\/([^\/?#:]*)(?::(\d+))?)?/.exec(url.toLowerCase()),
// Socket object
self = {
// Finds the value of an option
option: function(key) {
return opts[key];
},
// Gets or sets a session-scoped value
session: function(key, value) {
if (value === undefined) {
return session[key];
}
session[key] = value;
return this;
},
// Returns the state
state: function() {
return state;
},
// Adds event handler
on: function(type, fn) {
var event = events[type];
// For custom event
if (!event) {
if (events.message.locked()) {
return this;
}
event = events[type] = callbacks();
event.order = events.message.order;
}
event.add(fn);
return this;
},
// Removes event handler
off: function(type, fn) {
var event = events[type];
if (event) {
event.remove(fn);
}
return this;
},
// Adds one time event handler
one: function(type, fn) {
function proxy() {
self.off(type, proxy);
fn.apply(this, arguments);
}
fn.guid = fn.guid || guid++;
proxy.guid = fn.guid;
return self.on(type, proxy);
},
// Fires event handlers
fire: function(type) {
var event = events[type];
if (event) {
event.fire(self, $.makeArray(arguments).slice(1));
}
return this;
},
// Establishes a connection
open: function() {
var type,
latch,
connect = function() {
var candidates, type;
if (!latch) {
latch = true;
candidates = session.candidates = $.makeArray(opts.transports);
while (!transport && candidates.length) {
type = candidates.shift();
session.transport = type;
session.url = self.buildURL();
transport = transports[type](self, opts);
}
// Increases the number of reconnection attempts
if (reconnectTry) {
reconnectTry++;
}
// Fires the connecting event and connects
if (transport) {
self.fire("connecting");
// Gives the user the opportunity to bind connecting event handlers
setTimeout(function() {
transport.open();
}, 50);
} else {
self.fire("close", "notransport");
}
}
},
cancel = function() {
if (!latch) {
latch = true;
self.fire("close", "canceled");
}
};
// Cancels the scheduled connection
if (reconnectTimer) {
clearTimeout(reconnectTimer);
reconnectTimer = null;
}
// Resets the session scope and event helpers
session = {};
for (type in events) {
events[type].unlock();
}
// Chooses transport
transport = undefined;
// From null or waiting state
state = "preparing";
// Check if possible to make use of a shared socket
if (opts.sharing) {
session.transport = "local";
transport = transports.local(self, opts);
}
// Executes the prepare handler if a physical connection is needed
if (transport) {
connect();
} else {
opts.prepare.call(self, connect, cancel, opts);
}
return this;
},
// Transmits event using the connection
send: function(type, data, callback) {
var event;
// Defers sending an event until the state become opened
if (state !== "opened") {
buffer.push(arguments);
} else {
// Standardize .send(data) and .send(data, callback) into .send(event, data, callback)
if (data === undefined || $.isFunction(data)) {
callback = data;
data = type;
type = "message";
}
// Outbound event
event = {
id: ++eventId,
socket: opts.id,
type: type,
data: data,
reply: !!callback
};
if (callback) {
// Shared socket needs to know the callback event name
// because it fires the callback event directly instead of using reply event
if (session.transport === "local") {
event.callback = callback;
} else {
replyCallbacks[eventId] = callback;
}
}
// Delegates to the transport
transport.send(isBinary(data) ? data : opts.outbound.call(self, event));
}
return this;
},
// Disconnects the connection
close: function() {
// Prevents reconnection
opts.reconnect = false;
if (reconnectTimer) {
clearTimeout(reconnectTimer);
reconnectTimer = null;
}
// Fires the close event immediately for transport which doesn't give feedback on disconnection
if (unloading || !transport || !transport.feedback) {
self.fire("close", unloading ? "error" : "aborted");
}
// Delegates to the transport
if (transport) {
transport.close();
}
return this;
},
// Broadcasts event to session sockets
broadcast: function(type, data) {
// TODO rename
var broadcastable = session.broadcastable;
if (broadcastable) {
broadcastable.broadcast({type: "fire", data: {type: type, data: data}});
}
return this;
},
// For internal use only
// fires events from the server
_fire: function(data, isChunk) {
if (isChunk) {
// Strips off the padding of the chunk
// the first chunk of some streaming transports and every chunk for Android browser 2 and 3 has padding
// technically, regular expression, /\S/.test("\xA0") ? (/^[\s\xA0]+/g) : /^\s+/g, is right according to jQuery.trim
// but, I believe no one use non-breaking spaces when printing padding
data = opts.streamParser.call(self, data.replace(/^\s+/g, ""));
while (data.length) {
self._fire(data.shift());
}
} else {
$.each(isBinary(data) ? [{type: "message", data: data}] : $.makeArray(opts.inbound.call(self, data)),
function(i, event) {
var latch, args = [event.type, event.data];
opts.lastEventId = event.id;
if (event.reply) {
args.push(function(result) {
if (!latch) {
latch = true;
self.send("reply", {id: event.id, data: result});
}
});
}
self.fire.apply(self, args).fire("_message", args);
});
}
return this;
},
// For internal use only
// builds an effective URL
buildURL: function(params) {
return opts.urlBuilder.call(self, url, $.extend({
id: opts.id,
transport: session.transport,
heartbeat: opts.heartbeat,
lastEventId: opts.lastEventId,
_: $.now()
}, opts.params, params));
}
};
// Create the final options
opts = $.extend(true, {}, defaults, options);
if (options) {
// Array should not be deep extended
if (options.transports) {
opts.transports = $.makeArray(options.transports);
}
}
// Saves original URL
opts.url = url;
// Generates socket id,
opts.id = opts.idGenerator.call(self);
opts.crossDomain = !!(parts &&
// protocol and hostname
(parts[1] != location.protocol || parts[2] != location.hostname ||
// port
(parts[3] || (parts[1] === "http:" ? 80 : 443)) != (location.port || (location.protocol === "http:" ? 80 : 443))));
$.each(["connecting", "open", "message", "close", "waiting"], function(i, type) {
// Creates event helper
events[type] = callbacks(type !== "message");
events[type].order = i;
// Shortcuts for on method
var old = self[type],
on = function(fn) {
return self.on(type, fn);
};
self[type] = !old ? on : function(fn) {
return ($.isFunction(fn) ? on : old).apply(this, arguments);
};
});
// Initializes
self.connecting(function() {
// From preparing state
state = "connecting";
var timeoutTimer;
// Sets timeout timer
function setTimeoutTimer() {
timeoutTimer = setTimeout(function() {
transport.close();
self.fire("close", "timeout");
}, opts.timeout);
}
// Clears timeout timer
function clearTimeoutTimer() {
clearTimeout(timeoutTimer);
}
// Makes the socket sharable
// TODO to be extracted as plugin
function share() {
var traceTimer,
server,
name = "socket-" + url,
servers = {
// Powered by the storage event and the localStorage
// http://www.w3.org/TR/webstorage/#event-storage
storage: function() {
if (!$.support.storageEvent) {
return;
}
var storage = window.localStorage;
return {
init: function() {
// Handles the storage event
$(window).on("storage.socket", function(event) {
event = event.originalEvent;
// When a deletion, newValue initialized to null
if (event.key === name && event.newValue) {
listener(event.newValue);
}
});
self.one("close", function(reason) {
$(window).off("storage.socket");
// Defers again to clean the storage
self.one("close", function() {
storage.removeItem(name);
storage.removeItem(name + "-opened");
storage.removeItem(name + "-children");
});
});
},
broadcast: function(obj) {
var string = $.stringifyJSON(obj);
storage.setItem(name, string);
// Storage event is not fired in window which did trigger that event
// but, IE does not
// TODO remove and use identifier instead
if (!$.browser.msie) {
setTimeout(function() {
listener(string);
}, 50);
}
},
get: function(key) {
return $.parseJSON(storage.getItem(name + "-" + key));
},
set: function(key, value) {
storage.setItem(name + "-" + key, $.stringifyJSON(value));
}
};
},
// Powered by the window.open method
// https://developer.mozilla.org/en/DOM/window.open
windowref: function() {
// Internet Explorer raises an invalid argument error
// when calling the window.open method with the name containing non-word characters
var neim = name.replace(/\W/g, ""),
win = ($('iframe[name="' + neim + '"]')[0] || $('<iframe name="' + neim + '" />').hide().appendTo("body")[0])
.contentWindow;
return {
init: function() {
// Callbacks from different windows
win.callbacks = [listener];
// In IE 8 and less, only string argument can be safely passed to the function in other window
win.fire = function(string) {
var i;
for (i = 0; i < win.callbacks.length; i++) {
win.callbacks[i](string);
}
};
},
broadcast: function(obj) {
if (!win.closed && win.fire) {
win.fire($.stringifyJSON(obj));
}
},
get: function(key) {
return !win.closed ? win[key] : null;
},
set: function(key, value) {
if (!win.closed) {
win[key] = value;
}
}
};
}
};
// Receives send and close command from the children
function listener(string) {
var command = $.parseJSON(string), data = command.data;
if (!command.target) {
if (command.type === "fire") {
self.fire(data.type, data.data);
}
} else if (command.target === "p") {
switch (command.type) {
case "send":
self.send(data.type, data.data, data.callback);
break;
case "close":
self.close();
break;
}
}
}
function propagateMessageEvent(args) {
server.broadcast({target: "c", type: "message", data: args});
}
function leaveTrace() {
document.cookie = encodeURIComponent(name) + "=" +
// Opera's parseFloat and JSON.stringify causes a strange bug with a number larger than 10 digit
// JSON.stringify(parseFloat(10000000000) + 1).length === 11;
// JSON.stringify(parseFloat(10000000000 + 1)).length === 10;
encodeURIComponent($.stringifyJSON({ts: $.now() + 1, heir: (server.get("children") || [])[0]}));
}
// Chooses a server
server = servers.storage() || servers.windowref();
server.init();
// For broadcast method
session.broadcastable = server;
// List of children sockets
server.set("children", []);
// Flag indicating the parent socket is opened
server.set("opened", false);
// Leaves traces
leaveTrace();
traceTimer = setInterval(leaveTrace, 1000);
self.on("_message", propagateMessageEvent)
.one("open", function() {
server.set("opened", true);
server.broadcast({target: "c", type: "open"});
})
.one("close", function(reason) {
// Clears trace timer
clearInterval(traceTimer);
// Removes the trace
document.cookie = encodeURIComponent(name) + "=; expires=Thu, 01 Jan 1970 00:00:00 GMT";
// The heir is the parent unless unloading
server.broadcast({target: "c", type: "close", data: {reason: reason, heir: !unloading ? opts.id : (server.get("children") || [])[0]}});
self.off("_message", propagateMessageEvent);
});
}
if (opts.timeout > 0) {
setTimeoutTimer();
self.one("open", clearTimeoutTimer).one("close", clearTimeoutTimer);
}
// Share the socket if possible
if (opts.sharing && session.transport !== "local") {
share();
}
})
.open(function() {
// From connecting state
state = "opened";
var heartbeatTimer;
// Sets heartbeat timer
function setHeartbeatTimer() {
heartbeatTimer = setTimeout(function() {
self.send("heartbeat", null).one("heartbeat", function() {
clearHeartbeatTimer();
setHeartbeatTimer();
});
heartbeatTimer = setTimeout(function() {
transport.close();
self.fire("close", "error");
}, opts._heartbeat);
}, opts.heartbeat - opts._heartbeat);
}
// Clears heartbeat timer
function clearHeartbeatTimer() {
clearTimeout(heartbeatTimer);
}
if (opts.heartbeat > opts._heartbeat) {
setHeartbeatTimer();
self.one("close", clearHeartbeatTimer);
}
// Locks the connecting event
events.connecting.lock();
// Initializes variables related with reconnection
reconnectTimer = reconnectDelay = reconnectTry = null;
// Flushes buffer
while (buffer.length) {
self.send.apply(self, buffer.shift());
}
})
.close(function() {
// From preparing, connecting, or opened state
state = "closed";
var type, event, order = events.close.order;
// Locks event whose order is lower than close event
for (type in events) {
event = events[type];
if (event.order < order) {
event.lock();
}
}
// Schedules reconnection
if (opts.reconnect) {
self.one("close", function() {
reconnectTry = reconnectTry || 1;
reconnectDelay = opts.reconnect.call(self, reconnectDelay, reconnectTry);
if (reconnectDelay !== false) {
reconnectTimer = setTimeout(function() {
self.open();
}, reconnectDelay);
self.fire("waiting", reconnectDelay, reconnectTry);
}
});
}
})
.waiting(function() {
// From closed state
state = "waiting";
})
.on("reply", function(reply) {
var id = reply.id, data = reply.data, callback = replyCallbacks[id];
if (callback) {
if (typeof callback === "string") {
self.fire(callback, data).fire("_message", [callback, data]);
} else if ($.isFunction(callback)) {
callback.call(self, data);
}
delete replyCallbacks[id];
}
});
return self.open();
}
$.support.storageEvent = (function() {
var storage = window.localStorage;
if (storage) {
try {
storage.setItem("t", "t");
storage.removeItem("t");
// Internet Explorer 9 has no StorageEvent object but supports the storage event
return !!window.StorageEvent || Object.prototype.toString.call(storage) === "[object Storage]";
} catch (e) {}
}
return false;
})();
// Default options
defaults = {
transports: ["ws", "sse", "stream", "longpoll"],
timeout: false,
heartbeat: false,
_heartbeat: 5000,
lastEventId: "",
credentials: false,
sharing: true,
prepare: function(connect) {
connect();
},
reconnect: function(lastDelay) {
return 2 * (lastDelay || 250);
},
idGenerator: function() {
// Generates a random UUID
// Logic borrowed from http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/2117523#2117523
return "xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g, function(c) {
var r = Math.random() * 16 | 0,
v = c === "x" ? r : (r & 0x3 | 0x8);
return v.toString(16);
});
},
urlBuilder: function(url, params) {
return url + (/\?/.test(url) ? "&" : "?") + $.param(params);
},
inbound: $.parseJSON,
outbound: $.stringifyJSON,
xdrURL: function(url) {
// Maintaining session by rewriting URL
// http://stackoverflow.com/questions/6453779/maintaining-session-by-rewriting-url
var match = /(?:^|; )(JSESSIONID|PHPSESSID)=([^;]*)/.exec(document.cookie);
switch (match && match[1]) {
case "JSESSIONID":
return url.replace(/;jsessionid=[^\?]*|(\?)|$/, ";jsessionid=" + match[2] + "$1");
case "PHPSESSID":
return url.replace(/\?PHPSESSID=[^&]*&?|\?|$/, "?PHPSESSID=" + match[2] + "&").replace(/&$/, "");
default:
return false;
}
},
streamParser: function(chunk) {
// Chunks are formatted according to the event stream format
// http://www.w3.org/TR/eventsource/#event-stream-interpretation
var reol = /\r\n|[\r\n]/g, lines = [], data = this.session("data"), array = [], i = 0,
match, line;
// String.prototype.split is not reliable cross-browser
while (match = reol.exec(chunk)) {
lines.push(chunk.substring(i, match.index));
i = match.index + match[0].length;
}
lines.push(chunk.length === i ? "" : chunk.substring(i));
if (!data) {
data = [];
this.session("data", data);
}
// Processes the data field only
for (i = 0; i < lines.length; i++) {
line = lines[i];
if (!line) {
// Finish
array.push(data.join("\n"));
data = [];
this.session("data", data);
} else if (/^data:\s/.test(line)) {
// A single data field
data.push(line.substring("data: ".length));
} else {
// A fragment of a data field
data[data.length - 1] += line;
}
}
return array;
}
};
// Transports
transports = {
// Local socket
local: function(socket, options) {
var trace,
orphan,
connector,
name = "socket-" + options.url,
// TODO to be extracted as plugin
connectors = {
storage: function() {
if (!$.support.storageEvent) {
return;
}
var storage = window.localStorage,
get = function(key) {
return $.parseJSON(storage.getItem(name + "-" + key));
},
set = function(key, value) {
storage.setItem(name + "-" + key, $.stringifyJSON(value));
};
return {
init: function() {
set("children", get("children").concat([options.id]));
$(window).on("storage.socket", function(event) {
event = event.originalEvent;
if (event.key === name && event.newValue) {
listener(event.newValue);
}
});
socket.one("close", function() {
var index, children = get("children");
$(window).off("storage.socket");
if (children) {
index = $.inArray(options.id, children);
if (index > -1) {
children.splice(index, 1);
set("children", children);
}
}
});
return get("opened");
},
broadcast: function(obj) {
var string = $.stringifyJSON(obj);
storage.setItem(name, string);
if (!$.browser.msie) {
setTimeout(function() {
listener(string);
}, 50);
}
}
};
},
windowref: function() {
var win = window.open("", name.replace(/\W/g, ""));
if (!win || win.closed || !win.callbacks) {
return;
}
return {
init: function() {
win.callbacks.push(listener);
win.children.push(options.id);
socket.one("close", function() {
function remove(array, e) {
var index = $.inArray(e, array);
if (index > -1) {
array.splice(index, 1);
}
}
// Removes traces only if the parent is alive
if (!orphan) {
remove(win.callbacks, listener);
remove(win.children, options.id);
}
});
return win.opened;
},
broadcast: function(obj) {
if (!win.closed && win.fire) {
win.fire($.stringifyJSON(obj));