This repository has been archived by the owner on Jan 7, 2019. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 6
/
ApePubSub.js
1960 lines (1742 loc) · 45.7 KB
/
ApePubSub.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
/**
* @author Pablo Tejada
* @repo https://github.com/ptejada/ApePubSub
* @version 1.6.5
* Built on 2014-02-27 @ 03:09
*/
/**
* Client function to generates a random string
*
* @param {number} length - determines the length
* @param {string} [keys] - an optional string of alternative characters to use
* @returns {string}
* @memberOf module:Client~
*/
function randomString(length, keys){
var chars = keys || "0123456789ABCDEFGHIJKLMNOPQRSTUVWXTZabcdefghiklmnopqrstuvwxyz";
var string_length = length || 32;
var randomstring = '';
for (var i=0; i<string_length; i++) {
var rnum = Math.floor(Math.random() * chars.length);
randomstring += chars.substring(rnum,rnum+1);
}
return randomstring;
}
/*
* Official bind polyfill at developer.mozilla.org
*/
if(!Function.prototype.bind){
Function.prototype.bind = function(oThis){
if(typeof this !== "function"){
// closest thing possible to the ECMAScript 5 internal IsCallable function
throw new TypeError("Function.prototype.bind - what is trying to be bound is not callable");
}
var aArgs = Array.prototype.slice.call(arguments, 1),
fToBind = this,
fNOP = function(){},
fBound = function(){
return fToBind.apply(this instanceof fNOP
? this
: oThis || window,
aArgs.concat(Array.prototype.slice.call(arguments)));
};
fNOP.prototype = this.prototype;
fBound.prototype = new fNOP();
return fBound;
};
}
/**
* Groups all client side classes documentation and definition
* @module Client
*/
/**
* The client constructor
*
* @version 1.6.5
*
* @param {string} server - The APE Server domain name including port number if other than 80
* @param {object} [events] - Event handlers to be added to the client
* @param {object} [options] - Options to configure the client {@link APS#option}
*
* @returns {APS} An APS client instance
* @constructor
* @memberOf module:Client~
*/
function APS( server, events, options ){
/**
* The client options
*
* @type {{poll: number, debug: boolean, session: boolean, connectionArgs: {}, server: string, transport: Array, transport: string, secure: boolean, eventPush: boolean, addFrequency: boolean, autoUpdate: boolean}}
*
* @property {bool} [debug=false] - Enable and disable debugging features
* such as the log() function output
* @property {bool} [session=true] - Enable and disable user sessions
* @property {string} [transport] - Explicitly use a transport. ws = WebSocket, lp = LongPolling
* @property {Array} [transport=['ws','lp']] - Which transport to try
* and on what order
* @property {bool} [secure=false] - Whether the connection to the server should secure
* @property {string} [eventPush] - Path to a script to re-route all events to.
*/
this.option = {
poll: 25000,
debug: false,
session: true,
connectionArgs: {},
server: server,
transport: ["ws", "lp"],
//transport: "lp", //Should be the default transport option for APE Server v1.1.1
secure: false,
eventPush: false,
addFrequency: true,
autoUpdate: true
}
/**
* The client identifier
* @type {string}
*/
this.identifier = "APS";
/**
* The client version
* @type {string}
*/
this.version = '1.6.5';
/**
* The state of the client: 0=disconnected, 1=connected, 2=connecting
* @type {number}
*/
this.state = 0;
/**
* The client events stack
* @type {Object}
* @private
*/
this._events = {};
/**
* The current user object
* @type {APS.CUser}
*/
this.user = {};
/**
* The collection of all objects on the client as pipes, both channels and users
* @type {Object}
* @private
*/
this.pipes = {};
/**
* The collection of all channel object on the client
* @type {Object}
*/
this.channels = {};
/**
* A second event stack to hold/cache the event of channels
* Use when reconnecting to the server and for channels that have been
* subscribe to yet
* @type {Object}
* @private
*/
this.eQueue = {};
//Add Events
if(!!events)
this.on(events);
//Update options
if(!!options){
for(var opt in options){
this.option[opt] = options[opt];
}
}
//IE9 crap - log function fix
if(navigator.appName == "Microsoft Internet Explorer"){
if(typeof window.console == "undefined"){
this.log = function(){};
}else{
this.log = function(){
if(this.option.debug == false) return;
var args = Array.prototype.slice.call(arguments);
args.unshift("["+this.identifier+"]");
window.console.log(args.join().replace(",",""));
}
}
}
/**
* The current user session object
* @type {APS.Session}
*/
this.session = new APS.Session(this);
return this;
}
/**
* Handles the initial connection to the server
*
* @param args Arguments to send with the initial connect request
* @private
*
* @return bool The client reference or false if the connection request has been canceled
*/
APS.prototype.connect = function(args){
var fserver = this.option.server;
function TransportError(e){
this.trigger("dead", [e]);
this.transport.close();
}
var cb = {
'onmessage': this.onMessage.bind(this),
'onerror': TransportError.bind(this)
}
if(this.state == 1)
return this.log("Already Connected!");
var cmd = "CONNECT";
args = this.option.connectionArgs = args || this.option.connectionArgs;
var restore = this.session.restore();
//increase frequency
this.session.saveFreq();
//Handle sessions
if(this.option.session == true){
if(typeof restore == "object"){
args = restore;
//Change initial command CONNECT by RESTORE
cmd = "RESTORE";
}else{
//Fresh Connect
if(this.trigger("connect") == false)
return false;
}
}else{
//Fresh Connect
this.state = 0;
//this.session.id = "";
if(this.trigger("connect") == false)
return false;
}
//Apply frequency to the server
if(this.option.addFrequency)
fserver = this.session.getFreq() + "." + fserver;
//Handle transport
if(!!this.transport){
if(this.transport.state == 0){
this.transport = new APS.Transport(fserver, cb, this);
}else{
//Use current active transport
}
}else{
this.transport = new APS.Transport(fserver, cb, this);
}
//Attach version of client framework
args.version = this.version;
//Send seleced command and arguments
this.sendCmd(cmd, args);
return this;
}
/**
* Restore the connection to the server
* @returns {*}
*/
APS.prototype.reconnect = function(){
if(this.state > 0 && this.transport.state > 0)
return this.log("Client already connected!");
//Clear channels stack
this.channels = {};
this.connect();
}
/**
* Triggers events
*
* @param {string} ev - Name of the event to trigger, not case sensitive
* @param {Object} args - An array of arguments to passed to the event handler function
*
* @return {bool} False if any of the event handlers explicitly returns false, otherwise true
*/
APS.prototype.trigger = function(ev, args){
ev = ev.toLowerCase();
if(!(args instanceof Array)) args = [args];
//GLobal
if("_client" in this){
for(var i in this._client._events[ev]){
if(this._client._events[ev].hasOwnProperty(i)){
this.log("{{{ " + ev + " }}}["+i+"] on client ", this._client);
if(this._client._events[ev][i].apply(this, args) === false)
return false;
}
}
}
//Local
for(var i in this._events[ev]){
if(this._events[ev].hasOwnProperty(i)){
if(!this._client){
this.log("{{{ " + ev + " }}}["+i+"] on client ", this);
}else{
this.log("{{{ " + ev + " }}}["+i+"] ", this);
}
if(this._events[ev][i].apply(this, args) === false)
return false;
}
}
return true;
}
/**
* Add event handler(s) to the client
*
* Events added to the client are considered to be global event. For example
* if adding the **message** event handler on the client it will be triggered
* every time a channel receives a message event
*
* @param {string} ev Name of the event handler to add, not case sensitive
* @param {function} fn Function to handle the event
*
* @return {bool|APS} False if wrong parameters are passed, otherwise the client or parent object reference
*/
APS.prototype.on = function(ev, fn){
var Events = [];
if(typeof ev == 'string' && typeof fn == 'function'){
Events[ev] = fn;
}else if(typeof ev == "object"){
Events = ev;
}else{
this.log("Wrong parameters passed to on() method");
return false;
}
for(var e in Events){
if(!Events.hasOwnProperty(e)) continue;
var fn = Events[e];
e = e.toLowerCase();
if(!this._events[e])
this._events[e] = [];
this._events[e].push(fn);
}
return this;
}
/**
* Get any object by its unique publisher id, user or channel
*
* @param {string} pubid A string hash
* @return {bool|APS.User|APS.Channel}
*/
APS.prototype.getPipe = function( pubid ){
if(pubid in this.pipes){
return this.pipes[pubid];
}
return false;
}
/**
* Sends an event through a pipe/user/channel
* This function is not useful in this context
* Its real use is when bound to a user or channel
* objects. Consider using {@link APS.User#send user.send()} and
* {@link APS.Channel#send channel.send()} instead
*
* Although it could be useful if a developer has
* its own way of getting a user's or channels's pubid
* who object does not resides in the local client
*
* @param {string|object} pipe The pubid string or pipe object of user or channel
* @param {string} $event The name of the event to send
* @param {*} data The data to send with the event
* @param {bool} sync Weather to sync event across the user's session or not
* @param {function} callback Function to call after the event has been sent
*
* @return {APS} client or parent object reference
*/
APS.prototype.send = function(pipe, $event, data, sync, callback){
this.sendCmd("Event", {
event: $event,
data: data,
sync: sync
}, pipe, callback);
return this;
}
/**
* Internal method to wrap events and send them as commands to the server
*
* @param {string} cmd Name of command in the server which will handle the request
* @param {*} args The data to send with the command
* @param {string|object} pipe The pubid string or pipe object of user or channel
* @param {function} callback Function to after the event has been sent
* @private
*
* @return (object) client reference
*/
APS.prototype.sendCmd = function(cmd, args, pipe, callback){
var specialCmd = {CONNECT: 0, RESTORE:0};
if(this.state == 1 || cmd in specialCmd){
var tmp = {
'cmd': cmd,
'chl': this.transport.chl,
'freq': this.session.getFreq()
}
if(args) tmp.params = args;
if(pipe) {
tmp.params.pipe = typeof pipe == 'string' ? pipe : pipe.pubid;
}
if(this.session.getID()) tmp.sessid = this.session.getID();
this.log('<<<< ', cmd.toUpperCase() , " >>>> ", tmp);
if(typeof callback != "function") callback = function(){};
var data = [];
try {
data = JSON.stringify([tmp]);
}catch(e){
this.log(e);
this.log("Data Could not be strigify:", data);
this.quit();
}
//Send command
if(this.transport.send(data, callback, tmp) != "pushed"){
this.transport.chl++;
}
} else {
this.on('ready', this.sendCmd.bind(this, cmd, args));
}
return this;
}
/**
* Polls the server for information when using the Long Polling transport
* @private
*/
APS.prototype.poll = function(){
if(this.transport.id == 0){
clearTimeout(this.poller);
this.poller = setTimeout(this.check.bind(this), this.option.poll);
}
}
/**
* Sends a check command to the server
* @private
*/
APS.prototype.check = function(force){
if(this.transport.id == 0 || !!force){
this.sendCmd('CHECK');
this.poll();
}
}
/**
* Log the user out and kill the client
*
* Sends the QUIT command to the server and completely destroys the client instance
* and session
*/
APS.prototype.quit = function(){
this.sendCmd('QUIT');
this.transport.close();
this.trigger("dead");
//Clear session on 'quit'
this.session.destroy();
this.state = 0;
}
/**
* Subscribe to a channel
*
* @param {string} channel - Name of the channel to subscribe to
* @param {object} Events - List of event handlers to add to the channel
* @param {function} callback - Function to be called when a user successfully subscribes to the channel
*
* @return {APS} client reference
*/
APS.prototype.sub = function(channel, Events, callback){
//Handle the events
if(typeof Events == "object"){
if(typeof channel == "object"){
for(var chan in channel){
this.onChannel(channel[chan], Events);
}
}else{
this.onChannel(channel, Events);
}
}
//Handle callback
if(typeof callback == "function"){
if(typeof channel == "object"){
for(var chan in channel){
this.onChannel(channel[chan], "joined", callback);
}
}else{
this.onChannel(channel, "joined", callback);
}
}
//Join Channel
if(this.state == 0){
this.on("ready", this.sub.bind(this, channel));
this.connect({user: this.user});
}else{
//Logic to only send the JOIN request to only non-existing channels in the client object
if(typeof channel == "string"){
//Single Channel
channel = channel.toLowerCase();
if(typeof this.channels[channel] != "object"){
this.sendCmd('JOIN', {'channels': [channel]});
}else{
this.log("User already subscribed to [" + channel + "]");
}
}else{
//Multi Channel
var toJoin = [];
for(var x in channel){
if(typeof this.channels[channel[x].toLowerCase()] != "object")
toJoin.push(channel[x]);
}
if(toJoin.length > 0)
this.sendCmd('JOIN', {'channels': toJoin});
}
}
return this;
}
/**
* Alias for {@link APS#sub}
* @see APS#sub
* @methodOf APS
* @function
*/
APS.prototype.subscribe = APS.prototype.sub;
/**
* Publishes anything in a channel, a string, object, array or integer
*
* @param {string} channel The name of the channel
* @param {*} data Data to send to the channel
* @param {bool} sync Whether to to synchronize the event across the uer session
* @param {function} callback Function called after the event is sent
*/
APS.prototype.pub = function(channel, data, sync, callback){
var pipe = this.getChannel(channel);
if(!pipe && channel.length == 32) pipe = this.getPipe(channel);
if(pipe){
var $event = typeof data == "string" ? "message" : "data";
if($event == "message") data = encodeURIComponent(data);
pipe.send($event, data, sync, callback);
}else{
this.log("NO Channel " + channel);
}
};
/**
* Alias for {@link APS#pub}
* @see APS#pub
* @methodOf APS
* @function
*/
APS.prototype.publish = APS.prototype.pub;
/**
* Get a channel object by its name
*
* @param channel Name of the channel
* @return {bool|APS.Channel} Returns the channel object if it exists or false otherwise
*/
APS.prototype.getChannel = function(channel){
channel = channel.toLowerCase();
if(channel in this.channels){
return this.channels[channel];
}
return false;
}
/**
* Add event handler(s) to a channel
*
* With this method event handler(s) can be added to a channel event if the user is not subscribe to it yet.
* @param {string} channel The channel name
* @param {string|object} Events Either an event name or key pair of multiple events
* @param {function} [fn] The callback function if Events is a string
* @returns {bool|APS.Channel}
*/
APS.prototype.onChannel = function(channel, Events, fn){
channel = channel.toLowerCase();
if(channel in this.channels)
{
this.channels[channel].on(Events, fn);
}
else
{
if(typeof Events == "object"){
//add events to queue
if(typeof this.eQueue[channel] != "object")
this.eQueue[channel] = [];
//this.eQueue[channel].push(Events);
for(var $event in Events){
fn = Events[$event];
this.eQueue[channel].push([$event, fn]);
this.log("Adding ["+channel+"] event '"+$event+"' to queue");
}
}else{
var xnew = Object();
xnew[Events] = fn;
this.onChannel(channel,xnew);
}
}
}
/**
* Unsubscribe from a channel
*
* @param {string} channel - Name of the channel to unsubscribe
*/
APS.prototype.unSub = function(channel){
if(channel == "") return;
this.getChannel(channel).leave();
}
/**
* Alias of {@link APS#unSub}
* @see APS#unSub
* @methodOf APS
* @function
*/
APS.prototype.unSubscribe = APS.prototype.unSub;
/*
* Debug Function for Browsers console
*/
if(navigator.appName != "Microsoft Internet Explorer"){
/**
* Logs data to the browser console if debugging is enable
* @type {Function}
*/
APS.prototype.log = function(){
if(this.option.debug)
{
var args = Array.prototype.slice.call(arguments);
args.unshift("["+this.identifier+"]");
window.console.log.apply(console, args);
}
};
}
/*
* The function parses all incoming information from the server.
* Is the magical function, it takes the raw information
* and convert into useful dynamic data and objects. It is
* also responsible for triggering most of the events in the
* framework
*/
APS.prototype.onMessage = function(data){
try {
data = JSON.parse(data)
}catch(e){
//Temporary FIX for malformed JSON with escape single quotes
data = data.replace(/\\'/g, "'");
try {
data = JSON.parse(data);
}catch(e){
e.type = "close";
this.trigger("dead", [e]);
return this.transport.close();
}
}
//Initiate variables to be used in the loop below
var raw, args, pipe, info, isIdent = false, check = true;
for(var i in data){
if(!data.hasOwnProperty(i)) continue;
//Assign RAW paramenters to the variable for easy access
raw = data[i].raw;
args = data[i].data;
pipe = null;
//Log the name of the incoming RAW
this.log('>>>> ', raw , " <<<< ", args);
/*
* Filter the actions to be taking according to the
* type of RAW recived
*/
switch(raw){
case 'LOGIN':
check = false;
/*
* User has logged in the server
* Store its session ID
*/
this.state = this.state == 0 ? 1 : this.state;
this.session.save(args.sessid);
this.trigger("login", [args.sessid]);
break;
case 'IDENT':
check = false;
isIdent = true; //Flag to trigger the restored event
/*
* Following the LOGIN raw this raw brings the user
* object and all its properties
*
* Initiate and store the current user object
*/
var user = new APS.CUser(args.user, this);
this.pipes[user.pubid] = user;
this.user = user;
/*
* Trigger the ready event only if the state of the
* client is 1 -> connected
*/
if(this.state == 1)
this.trigger('ready');
break;
case 'CHANNEL':
//The pipe is the channel object
pipe = new APS.Channel(args.pipe, this);
this.pipes[pipe.pubid] = pipe;
this.channels[pipe.name] = pipe;
var u = args.users;
/*
* Below, the user objects of the channels subscribers
* get initiated and stored in the channel object, as
* well as in the client general pipes array
*/
if(!!u){
//import users from channel to client if any
for(var i = 0; i < u.length; i++){
user = pipe.addUser(u[i]);
}
}
//Add events to channel from queue
var name = pipe.name.toLowerCase();
if(typeof this.eQueue[name] == "object"){
var queue = this.eQueue[name];
var ev, fn;
for(var i in queue){
if(!queue.hasOwnProperty(i)) continue;
ev = queue[i][0];
fn = queue[i][1];
pipe.on(ev,fn);
}
}
pipe.trigger('joined',[this.user, pipe]);
this.trigger('newChannel', [pipe]);
break;
case "SYNC":
/*
* Synchronizes events across multiple client instances
*/
user = this.user;
pipe = this.pipes[args.chanid];
//Decode the message data string
if(args.event == "message")
args.data = decodeURIComponent(args.data);
if(pipe instanceof APS.User){
user.trigger(args.event, [args.data, user, pipe]);
}else{
pipe.trigger(args.event, [args.data, user, pipe]);
}
break;
case "EVENT-X":
/*
* Handle events without a sender, recipient and sender
* will be same in this case of events
*/
pipe = this.pipes[args.pipe.pubid];
//Trigger event on target
pipe.trigger(args.event, [args.data, pipe, pipe]);
break;
case "EVENT":
/*
* Parses and triggers an incoming Event
*/
user = this.pipes[args.from.pubid];
if(typeof user == "undefined" && !!args.from){
//Create user it doesn't exists
this.pipes[args.from.pubid] = new APS.User(args.from, this);
user = this.pipes[args.from.pubid];
}
pipe = this.pipes[args.pipe.pubid];
if(pipe.pubid == user.pubid){
pipe = this.user;
}
//Decode the message data string
if(args.event == "message")
args.data = decodeURIComponent(args.data);
//Trigger event on target
pipe.trigger(args.event, [args.data, user, pipe]);
break;
case "NOJOIN":
this.trigger("notjoined", [args])
break;
case 'JOIN':
/*
* A new user has join a channel
* Parse the raw and trigger the corresponding
* events
*/
//pipe is the channel object
pipe = this.pipes[args.pipe.pubid];
//Add user to channel list
user = pipe.addUser(args.user);
pipe.trigger('join', [user, pipe]);
break;
case 'LEFT':
/*
* A user as left a channel
* Parse event to trigger the corresponding events
* and delete the user references from channel but
* keep user object in the client in case is being
* use by another channel
*/
pipe = this.pipes[args.pipe.pubid];
user = this.pipes[args.user.pubid];
delete pipe.users[args.user.pubid];
pipe.trigger('left', [user, pipe]);
break;
case "UPDATE":
if(this.option.autoUpdate){
pipe = this.pipes[args.pipe.pubid];
pipe._update(args.pipe.properties);
}
break;
case "SESSION_UPDATE":
this.session._update(args);
break;
case 'CLOSE':
/*
* Required by the longPolling protocol to avoid
* a racing effect with AJax requests
*/
check = false
break;
case 'ERR' :
/*
* Parses default server errors,
* Handle them and trigger the API
* friendly events
*/
check = false;
info = [args.code, args.value, args];
switch(args.code){
case "001":
case "002":
case "003":
clearTimeout(this.poller);
this.trigger("dead", info);
break;
case "004":
case "250":
this.state = 0;
this.session.destroy(true);
if(this.option.session){
this.reconnect();
}
break;
default:
this.check();
}
this.trigger("error", info);
this.trigger("error"+args.code, info);
break;
default:
//trigger custom raws
info = [];
for(var i in args){
if(!args.hasOwnProperty(i)) continue;
info.push(args[i]);
}
this.trigger("raw"+raw, info);
}
}
/*
* Handle The Session restored
* callback event triggers
*/
if(isIdent && this.state != 1){
check = true;
//Session restored completed
this.state = 1;
if(this.trigger('restored') !== false)
this.trigger('ready');
}
/*
* Conditionally called the check() method for the long polling method
*/
if(this.transport.id == 0 && check && this.transport.state == 1){
this.check();
}
}
APS.Transport = function(server, callback, client){
this.state = 0;//0 = Not initialized, 1 = Initialized and ready to exchange data, 2 = Request is running
this.stack = [];
this.callback = callback;
this.chl = 0;
var trans = client.option.transport;
var args = Array.prototype.slice.call(arguments);
/*
* Choosing the right transport according to the option
*/
if(typeof trans == "object"){
/*
* Loop through the array of given objects
* and use the first compatible one
* if a transport is not compatible it should return false
*/
for(var t in trans){
var ret = APS.Transport[trans[t]].apply(this, args);
if(ret != false) break;
}
}else if(typeof trans == "string"){
/*
* Use the specify transport explicitly
*/
APS.Transport[trans].apply(this, args);
}
/*
* Ajax request function for the eventPush feature
*/
function getRequest() {
if('XMLHttpRequest' in window) return XMLHttpRequest;
if('ActiveXObject' in window) {
var names = [
"Msxml2.XMLHTTP.6.0",
"Msxml2.XMLHTTP.3.0",
"Msxml2.XMLHTTP",
"Microsoft.XMLHTTP"
];
for(var i in names){
try{ return ActiveXObject(names[i]); }
catch(e){}