-
Notifications
You must be signed in to change notification settings - Fork 3
/
sail.strophe.js
611 lines (517 loc) · 22.8 KB
/
sail.strophe.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
/*jshint browser: true, devel: true, eqeqeq:false, eqnull:true, undef:false */
/*globals Strophe, $ */
/**
@fileOverview
Wrapper around strophe.js that adds some convenience and Sail-specific functionality.
*/
var Sail = window.Sail || {};
/** @namespace */
Sail.Strophe = {
/** URL of the XMPP over BOSH or Websockets service we'll be connecting to. */
xmppUrl: null,
/** JID to connect as (e.g. "[email protected]"). */
jid: null,
/** Password to use during authentication with the XMPP server. */
password: null,
/** Data mode to use for serializing Sail events. Currently on 'json' is supported. */
dataMode: 'json', // 'xml' || 'json'
/**
Log messages at a level lower than this will be ignored.
@see Sail.Strophe.log
*/
logLevel: Strophe.LogLevel.INFO,
groupchats: [],
/**
Connect to the XMPP service using current Sail.Strophe settings.
`Sail.Strophe.onConnect` is used as the strophe callback function.
@see Sail.Strophe.xmppUrl
@see Sail.Strophe.jid
@see Sail.Strophe.password
@see Sail.Strophe.onConnect
*/
connect: function() {
if (!this.xmppUrl) throw "No xmppUrl set!";
if (!this.jid) throw "No jid set!";
//if (!this.password) throw "No password set!"
this.conn = new Strophe.Connection(this.xmppUrl);
// turn off sync in case it was set during previous detach (see bindDetacher)
this.conn.sync = false;
// this.conn.xmlInput = function(data) {
// console.log("IN:", $(data).children()[0])
// }
// this.conn.xmlOutput = function(data) {
// console.log("OUT:", $(data).children()[0])
// }
Sail.Strophe.groupchats = [];
this.conn.connect(this.jid, this.password, this.onConnect);
},
/**
Disconnect from the XMPP service.
The connection is set to synchronous mode and any outstanding data is flushed
before the disconnect is sent.
Be careful when using this in 'onUnload' -- in WebKit-based browser the disconnect
request doesn't always complete before the page is unloaded.
*/
disconnect: function() {
console.log("sending disconnect request...");
Sail.Strophe.conn.sync = true;
Sail.Strophe.conn.flush();
Sail.Strophe.conn.disconnect();
},
addStanzaHandler: function(handler, ns, name, type, id, from) {
if (!Sail.Strophe.conn) {
throw "Must connect before you can add handlers";
}
Sail.Strophe.conn.addHandler(function(stanza) {
handler(stanza);
return true;
}, ns, name, type, id, from);
},
addOneoffStanzaHandler: function(handler, ns, name, type, id, from) {
if (!Sail.Strophe.conn) throw "Must connect before you can add handlers";
Sail.Strophe.conn.addHandler(function(stanza){
handler(stanza);
return false;
}, ns, name, type, id, from);
},
addErrorStanzaHandler: function(handler, type, condition) {
Sail.Strophe.conn.addHandler(function(stanza, text){
error = $(stanza).children('error').eq(0);
if (type && $(error).attr('type') != type) {
return true; // this error isn't of the desired type, so bail out
}
if (condition && $(error).children(condition).length === 0) {
return true; // this error doesn't contain the desired condition, so bail out
}
text = error.children('text').text();
handler(error, text);
}, null, null, 'error');
},
pinger: function() {
this.conn.ping.addPingHandler(function(ping) {
console.log("GOT PING! sending pong...");
Sail.Strophe.conn.ping.pong(ping);
});
// set up a pinger to keep the connection alive
pingInterval = 14 * 1000; // default is 14 seconds
this.conn.addTimedHandler(pingInterval, function() {
console.log("Ping ...");
Sail.Strophe.conn.ping.ping(Strophe.getDomainFromJid(Sail.Strophe.conn.jid),
function() {
console.log("... Pong");
},
function() {
console.warn("Ping failed!");
console.error("XMPP connection seems to have gone away :(");
jQuery(Sail.app).trigger('connection_lost');
}
);
return true;
});
},
bindDetacher: function() {
Sail.Strophe.detacherAlreadyRan = false;
var onUnload = function() {
if (Sail.Strophe.detacherAlreadyRan) {
console.warn("Tried to run Sail.Strophe's onUnload by it has already ran!");
} else {
console.log("Running Sail.Strophe's onUnload...");
// hack to try to force the browser to wait until strophe is done sending stuff
Sail.Strophe.conn.sync = true;
// need to leave groupchats to get presence stanzas when we come back
for (i = 0; i < Sail.Strophe.groupchats.length; i++) {
console.log("Leaving "+Sail.Strophe.groupchats[i].room+" before detaching...");
Sail.Strophe.groupchats[i].leave();
}
Sail.Strophe.conn.flush();
Sail.Strophe.conn.pause(); // prevent any further messages from being sent in order to freeze rid
Sail.Strophe.storeConnInfo();
Sail.Strophe.detacherAlreadyRan = true;
}
};
$(window).unload(onUnload);
$(window).bind('beforeunload', onUnload);
},
/**
Called by strophe.js at different stages in connecting to the XMPP service.
Triggers the various `connect_` events.
@private
*/
onConnect: function (status, error) {
switch (status) {
case Strophe.Status.ERROR:
console.error('CONNECTION ERROR: '+error);
/**
Some general error occurred while trying to connect.
@event
@name Sail.Strophe.connect_error
@params {string} error - Foo
@see http://strophe.im/strophejs/doc/1.0.2/files2/strophe-js.html#Strophe.Connection_Status_Constants
*/
$(Sail.Strophe).trigger('connect_error', error);
break;
case Strophe.Status.CONNECTING:
console.log('CONNECTING to '+Sail.Strophe.xmppUrl+' as '+Sail.Strophe.jid+'/'+Sail.Strophe.password);
/**
The connection is currently being established.
@event
@name Sail.Strophe.connect_connecting
@see http://strophe.im/strophejs/doc/1.0.2/files2/strophe-js.html#Strophe.Connection_Status_Constants
*/
$(Sail.Strophe).trigger('connect_connecting');
break;
case Strophe.Status.CONNFAIL:
msg = 'CONNECTION as '+Sail.Strophe.jid+' FAILED BECAUSE: ';
console.error(msg, error);
/**
The connection attempt failed, for example because the server rejected it.
@event
@name Sail.Strophe.connect_connfail
@param {string} error - Foo
@see http://strophe.im/strophejs/doc/1.0.2/files2/strophe-js.html#Strophe.Connection_Status_Constants
*/
$(Sail.Strophe).trigger('connect_connfail', error);
break;
case Strophe.Status.AUTHENTICATING:
console.log('AUTHENTICATING');
/**
Connection credentials are being authenticated.
@event
@name Sail.Strophe.connect_authenticating
@see http://strophe.im/strophejs/doc/1.0.2/files2/strophe-js.html#Strophe.Connection_Status_Constants
*/
$(Sail.Strophe).trigger('connect_authenticating', error);
break;
case Strophe.Status.AUTHFAIL:
console.error("AUTHENTICATION as "+Sail.Strophe.jid+" FAILED: ", error);
/**
Authentication with the XMPP server failed.
@event
@name Sail.Strophe.connect_authfail
@param {string} error - Foo
@see http://strophe.im/strophejs/doc/1.0.2/files2/strophe-js.html#Strophe.Connection_Status_Constants
*/
$(Sail.Strophe).trigger('connect_authfail', error);
break;
case Strophe.Status.CONNECTED:
console.log('CONNECTED to '+Sail.Strophe.xmppUrl+' as '+Sail.Strophe.jid);
Sail.Strophe.bindDetacher();
Sail.Strophe.addDefaultXmppHandlers();
/**
The connection has been successfully established.
@event
@name Sail.Strophe.connect_connected
@see http://strophe.im/strophejs/doc/1.0.2/files2/strophe-js.html#Strophe.Connection_Status_Constants
*/
$(Sail.Strophe).trigger('connect_connected', error);
break;
case Strophe.Status.DISCONNECTED:
/**
The connection has been terminated.
@event
@name Sail.Strophe.connect_disconnected
@see http://strophe.im/strophejs/doc/1.0.2/files2/strophe-js.html#Strophe.Connection_Status_Constants
*/
$(Sail.Strophe).trigger('connect_disconnected');
break;
case Strophe.Status.DISCONNECTING:
/**
The connection is currently being terminated.
@event
@name Sail.Strophe.connect_disconnecting
@see http://strophe.im/strophejs/doc/1.0.2/files2/strophe-js.html#Strophe.Connection_Status_Constants
*/
$(Sail.Strophe).trigger('connect_disconnecting');
console.log('DISCONNECTING...');
break;
case Strophe.Status.ATTACHED:
/**
The connection has been attached.
@event
@name Sail.Strophe.connect_attached
@see http://strophe.im/strophejs/doc/1.0.2/files2/strophe-js.html#Strophe.Connection_Status_Constants
*/
Sail.Strophe.bindDetacher();
Sail.Strophe.addDefaultXmppHandlers();
$(Sail.Strophe).trigger('connect_attached');
break;
default:
/**
The connection process has entered an unrecognized state.
This should never really happen.
@event
@name Sail.Strophe.connect_unknown
@see http://strophe.im/strophejs/doc/1.0.2/files2/strophe-js.html#Strophe.Connection_Status_Constants
*/
console.warn('UNKNOWN CONNECTION STATUS: '+status+', ERROR: '+error);
$(Sail.Strophe).trigger('connect_unknown');
}
},
/**
Adds default handlers/behaviour to the current strophe connection,
such as a default error stanza handler and a timed pinger.
*/
addDefaultXmppHandlers: function() {
Sail.Strophe.addErrorStanzaHandler(Sail.Strophe.defaultErrorStanzaHandler);
Sail.Strophe.pinger();
},
/**
The default error stanza handler. Prints out the error text and object to the console.
*/
defaultErrorStanzaHandler: function(error, text) {
console.error("XMPP ERROR: ", text, error);
return true;
},
/**
Log some text messsage at the given level (DEBUG, INFO, WARN, ERROR, FATAL) optionally with some additional data.
@param {string} level - The level/importance of this message. Should be a Strophe.LogLevel constant.
@param {string} message - The message to log.
@param [data] - Some additional data to log with the message. Can be a complex type like an object.
@see http://strophe.im/strophejs/doc/1.0.2/files2/strophe-js.html#Strophe.Log_Level_Constants
*/
log: function(level, message, data) {
switch(0) {
case Strophe.LogLevel.DEBUG:
logFunc = 'debug';
logMsg = "DEBUG: "+message;
break;
case Strophe.LogLevel.INFO:
logFunc = 'info';
logMsg = "INFO: "+message;
break;
case Strophe.LogLevel.WARN:
logFunc = 'warn';
logMsg = "WARN: "+message;
break;
case Strophe.LogLevel.ERROR:
logFunc = 'error';
logMsg = "ERROR: "+message;
break;
case Strophe.LogLevel.FATAL:
logFunc = 'error';
logMsg = "FATAL: "+message;
break;
default:
logFunc = 'log';
logMsg = message;
break;
}
if (Sail.Strophe.logLevel <= level)
console[logFunc](logMsg, data);
},
// The following methods could potentially be used
// to implement conn.attach() behaviour. Currently
// they are unused.
storeConnInfo: function() {
console.log("Storing connection info: ", Sail.Strophe.conn);
$.cookie('Sail.jid', Sail.Strophe.conn.jid);
$.cookie('Sail.sid', Sail.Strophe.conn.sid);
$.cookie('Sail.rid', Sail.Strophe.conn.rid);
},
retrieveConnInfo: function() {
return {
jid: $.cookie('Sail.jid'),
sid: $.cookie('Sail.sid'),
rid: $.cookie('Sail.rid')
};
},
clearConnInfo: function() {
console.log("Clearing connection info...");
Sail.Strophe.conn.jid = null;
Sail.Strophe.conn.sid = null;
Sail.Strophe.conn.rid = null;
$.cookie('Sail.jid', null);
$.cookie('Sail.sid', null);
$.cookie('Sail.rid', null);
},
hasExistingConnInfo: function() {
info = Sail.Strophe.retrieveConnInfo();
return info.jid && info.rid && info.sid;
},
reconnect: function() {
if (!Sail.Strophe.xmppUrl) throw "No xmppUrl set!";
info = Sail.Strophe.retrieveConnInfo();
Sail.Strophe.conn = new Strophe.Connection(Sail.Strophe.xmppUrl);
console.log('REATTACHING TO '+Sail.Strophe.xmppUrl+'WITH: ', info);
Sail.Strophe.conn.attach(info.jid, info.sid, info.rid + 1, this.onConnect);
}
};
Sail.Strophe.Groupchat = function(room, resource, conn) {
this.room = room;
this.conn = conn || Sail.Strophe.conn;
this.resource = resource || Sail.Strophe.jid;
if (!this.conn) {
throw "No connection given for Groupchat!";
}
};
Sail.Strophe.Groupchat.prototype = {
participants: {},
join: function() {
if (this.joined) {
console.error("Room '"+this.room+"' is already joined... cannot join again.");
} else {
console.log("Joining "+this.room+" as "+this.jid());
pres = $pres({to: this.jid()}).c('x', {xmlns: 'http://jabber.org/protocol/muc'});
this.conn.send(pres.tree());
this.addDefaultNicknameConflictHandler();
this.addDefaultPresenceHandlers();
Sail.Strophe.groupchats.push(this);
}
},
leave: function() {
if (this.joined) {
console.log("Leaving "+this.room+" as "+this.jid());
pres = $pres({to: this.jid(), type: 'unavailable'}).c('x', {xmlns: 'http://jabber.org/protocol/muc'});
this.conn.send(pres.tree());
idx = Sail.Strophe.groupchats.indexOf(this);
if (idx >= 0) {
Sail.Strophe.groupchats.splice(idx, 1);
}
} else {
console.error("Cannot leave '"+this.room+"' because it has not yet been joined.");
}
},
jid: function() {
return this.room + "/" + this.resource;
},
// executes yes callback if this Groupchat object is joined to the room, no callback otherwise or on error
isJoined: function (yes, no) {
var iq = $iq({to: this.room, type: 'get'}).c('query', {xmlns: 'http://jabber.org/protocol/disco#items'});
var cb = function(riq) {
if ($(riq).find('item[jid="'+Sail.app.groupchat.jid()+'"]').length > 0) {
yes();
} else {
no();
}
};
this.conn.sendIQ(iq, cb, no, 4000); // wait 4 seconds for response then call no()... prosody never seems to send error response if we're not joined (or maybe we're just not catching it properly)
this.conn.flush();
},
sendEvent: function(event) {
if (Sail.app.allowRunlessEvents === false && !event.run) {
err = "Cannot create a Sail.Event without a run because this Sail app does not allow runless events!";
console.error(err);
throw err;
}
/*if (Sail.Strophe.dataMode == 'xml')
this.sendXML(event.toXML())
else*/ if (Sail.Strophe.dataMode == 'json') {
this.sendJSON(event.toJSON());
} else { // FIXME: this isn't really right...
this.sendText(event);
}
},
sendXML: function(xml) {
msg = $msg({to: this.room, type: 'groupchat'}).c('body').cnode($(xml)[0]);
this.conn.send(msg.tree());
},
sendText: function(text) {
msg = $msg({to: this.room, type: 'groupchat'}).c('body').t(text);
this.conn.send(msg.tree());
},
sendJSON: function(json) {
if (typeof json == "string") {
json_string = json;
} else {
json_string = JSON.stringify(json);
}
msg = $msg({to: this.room, type: 'groupchat'}).c('body').t(json_string);
this.conn.send(msg.tree());
},
addEventHandler: function(handler, eventType, origin, payload, run) {
return this.addGroupchatStanzaHandler(Sail.generateSailEventHandler(handler, eventType, origin, payload, run));
},
addOneoffEventHandler: function(handler, eventType, origin, payload, run) {
var handlerRef;
var conn = this.conn;
if (!conn) {
throw "Must connect before you can add handlers";
}
var selfDeletingHandler = function(sev) {
handler(sev);
conn.deleteHandler(handlerRef);
};
var sailEventHandler = Sail.generateSailEventHandler(selfDeletingHandler, eventType, origin, payload, run);
handlerRef = this.addGroupchatStanzaHandler(sailEventHandler);
return handlerRef;
},
addGroupchatStanzaHandler: function(handler, ns, name, id, from) {
if (!this.conn) throw "Must connect before you can add handlers";
return this.conn.addHandler(function(stanza){handler(stanza);return true;}, ns, name, "groupchat", id, from);
},
addOneoffGroupchatStanzaHandler: function(handler, ns, name, id, from) {
if (!this.conn) {
throw "Must connect before you can add handlers";
}
return this.conn.addHandler(function(stanza) {
handler(stanza);
return false;
}, ns, name, "groupchat", id, from);
},
addParticipantJoinedHandler: function(handler) {
return this.conn.addHandler(function(stanza){
if ($(stanza).attr('type') != null) {
return true; // doesn't seem to be a way to do this at addHandler's filter level
}
who = $(stanza).attr('from');
handler(who, stanza);
return true;
}, null, "presence", null, null, this.room, {matchBare: true});
},
addParticipantLeftHandler: function(handler) {
return this.conn.addHandler(function(stanza){
who = $(stanza).attr('from');
handler(who, stanza);
return true;
}, null, "presence", "unavailable", null, this.room, {matchBare: true});
},
addSelfJoinedHandler: function(handler) {
return this.conn.addHandler(function(stanza){
if ($(stanza).attr('type') != null) {
return true; // doesn't seem to be a way to do this at addHandler's filter level
}
handler(stanza);
return true;
}, null, "presence", null, null, this.jid());
},
addSelfLeftHandler: function(handler) {
return this.conn.addHandler(function(stanza){
handler(stanza);
return true;
}, null, "presence", "unavailable", null, this.jid());
},
addDefaultNicknameConflictHandler: function() {
chat = this;
chat.conn.addHandler(function(stanza, text) {
error = $(stanza).children('error').eq(0);
// we're looking for errors of type 'cancel' with a 'conflict' element
if ($(error).attr('type') != 'cancel' || $(error).children('conflict').length === 0) {
return true; // not what we're looking for, ignore it
}
newNick = chat.resource+'~'+Math.floor((Math.random()*1e7)).toString(25);
console.warn("Nickname '"+chat.resource+"' is already taken in '"+chat.room+"'. Will try to join as '"+newNick+"'.");
chat.resource = newNick;
chat.join();
return true;
}, null, null, 'error');
},
addDefaultPresenceHandlers: function() {
chat = this;
this.addParticipantJoinedHandler(function(who, stanza) {
chat.participants[who] = who;
console.log(who+" JOINED "+chat.room);
});
this.addParticipantLeftHandler(function(who, stanza) {
delete chat.participants[who];
console.log(who+" LEFT "+chat.room);
});
this.addSelfJoinedHandler(function(who, stanza) {
chat.joined = true;
console.log("JOINED "+chat.room);
});
this.addSelfLeftHandler(function(who, stanza) {
console.log("LEFT "+chat.room);
});
}
};
Strophe.log = Sail.Strophe.log;