forked from jsxc/jsxc.roundcube
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathjsxc.js
11131 lines (9123 loc) · 313 KB
/
jsxc.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
/*!
* jsxc v3.0.1 - 2016-10-28
*
* Copyright (c) 2016 Klaus Herberth <[email protected]> <br>
* Released under the MIT license
*
* Please see http://www.jsxc.org/
*
* @author Klaus Herberth <[email protected]>
* @version 3.0.1
* @license MIT
*/
/*! This file is concatenated for the browser. */
var jsxc = null, RTC = null, RTCPeerconnection = null;
(function($) {
"use strict";
/**
* JavaScript Xmpp Chat namespace
*
* @namespace jsxc
*/
jsxc = {
/** Version of jsxc */
version: '3.0.1',
/** True if i'm the master */
master: false,
/** True if the role allocation is finished */
role_allocation: false,
/** Timeout for keepalive */
to: [],
/** Timeout after normal keepalive starts */
toBusy: null,
/** Timeout for notification */
toNotification: null,
/** Timeout delay for notification */
toNotificationDelay: 500,
/** Interval for keep-alive */
keepaliveInterval: null,
/** True if jid, sid and rid was used to connect */
reconnect: false,
/** True if restore is complete */
restoreCompleted: false,
/** True if login through box */
triggeredFromBox: false,
/** True if logout through element click */
triggeredFromElement: false,
/** True if logout through logout click */
triggeredFromLogout: false,
/** last values which we wrote into localstorage (IE workaround) */
ls: [],
/**
* storage event is even fired if I write something into storage (IE
* workaround) 0: conform, 1: not conform, 2: not shure
*/
storageNotConform: null,
/** Timeout for storageNotConform test */
toSNC: null,
/** My bar id */
bid: null,
/** Some constants */
CONST: {
NOTIFICATION_DEFAULT: 'default',
NOTIFICATION_GRANTED: 'granted',
NOTIFICATION_DENIED: 'denied',
STATUS: ['offline', 'dnd', 'xa', 'away', 'chat', 'online'],
SOUNDS: {
MSG: 'incomingMessage.wav',
CALL: 'Rotary-Phone6.mp3',
NOTICE: 'Ping1.mp3'
},
REGEX: {
JID: new RegExp('\\b[^"&\'\\/:<>@\\s]+@[\\w-_.]+\\b', 'ig'),
URL: new RegExp(/(https?:\/\/|www\.)[^\s<>'"]+/gi)
},
NS: {
CARBONS: 'urn:xmpp:carbons:2',
FORWARD: 'urn:xmpp:forward:0'
},
HIDDEN: 'hidden',
SHOWN: 'shown'
},
/**
* Parse a unix timestamp and return a formatted time string
*
* @memberOf jsxc
* @param {Object} unixtime
* @returns time of day and/or date
*/
getFormattedTime: function(unixtime) {
var msgDate = new Date(parseInt(unixtime));
var day = ('0' + msgDate.getDate()).slice(-2);
var month = ('0' + (msgDate.getMonth() + 1)).slice(-2);
var year = msgDate.getFullYear();
var hours = ('0' + msgDate.getHours()).slice(-2);
var minutes = ('0' + msgDate.getMinutes()).slice(-2);
var dateNow = new Date();
var date = (typeof msgDate.toLocaleDateString === 'function') ? msgDate.toLocaleDateString() : day + '.' + month + '.' + year;
var time = (typeof msgDate.toLocaleTimeString === 'function') ? msgDate.toLocaleTimeString() : hours + ':' + minutes;
// compare dates only
dateNow.setHours(0, 0, 0, 0);
msgDate.setHours(0, 0, 0, 0);
if (dateNow.getTime() !== msgDate.getTime()) {
return date + ' ' + time;
}
return time;
},
/**
* Write debug message to console and to log.
*
* @memberOf jsxc
* @param {String} msg Debug message
* @param {Object} data
* @param {String} Could be warn|error|null
*/
debug: function(msg, data, level) {
if (level) {
msg = '[' + level + '] ' + msg;
}
if (data) {
if (jsxc.storage.getItem('debug') === true) {
console.log(msg, data);
}
// try to convert data to string
var d;
try {
// clone html snippet
d = $("<span>").prepend($(data).clone()).html();
} catch (err) {
try {
d = JSON.stringify(data);
} catch (err2) {
d = 'see js console';
}
}
jsxc.log = jsxc.log + '$ ' + msg + ': ' + d + '\n';
} else {
console.log(msg);
jsxc.log = jsxc.log + '$ ' + msg + '\n';
}
},
/**
* Write warn message.
*
* @memberOf jsxc
* @param {String} msg Warn message
* @param {Object} data
*/
warn: function(msg, data) {
jsxc.debug(msg, data, 'WARN');
},
/**
* Write error message.
*
* @memberOf jsxc
* @param {String} msg Error message
* @param {Object} data
*/
error: function(msg, data) {
jsxc.debug(msg, data, 'ERROR');
},
/** debug log */
log: '',
/**
* This function initializes important core functions and event handlers.
* Afterwards it performs the following actions in the given order:
*
* <ol>
* <li>If (loginForm.ifFound = 'force' and form was found) or (jid or rid or
* sid was not found) intercept form, and listen for credentials.</li>
* <li>Attach with jid, rid and sid from storage, if no form was found or
* loginForm.ifFound = 'attach'</li>
* <li>Attach with jid, rid and sid from options.xmpp, if no form was found or
* loginForm.ifFound = 'attach'</li>
* </ol>
*
* @memberOf jsxc
* @param {object} options See {@link jsxc.options}
*/
init: function(options) {
if (options && options.loginForm && typeof options.loginForm.attachIfFound === 'boolean' && !options.loginForm.ifFound) {
// translate deprated option attachIfFound found to new ifFound
options.loginForm.ifFound = (options.loginForm.attachIfFound) ? 'attach' : 'pause';
}
if (options) {
// override default options
$.extend(true, jsxc.options, options);
}
// Check localStorage
if (typeof(localStorage) === 'undefined') {
jsxc.warn("Browser doesn't support localStorage.");
return;
}
/**
* Getter method for options. Saved options will override default one.
*
* @param {string} key option key
* @returns default or saved option value
*/
jsxc.options.get = function(key) {
if (jsxc.bid) {
var local = jsxc.storage.getUserItem('options') || {};
return (typeof local[key] !== 'undefined') ? local[key] : jsxc.options[key];
}
return jsxc.options[key];
};
/**
* Setter method for options. Will write into localstorage.
*
* @param {string} key option key
* @param {object} value option value
*/
jsxc.options.set = function(key, value) {
jsxc.storage.updateItem('options', key, value, true);
};
jsxc.storageNotConform = jsxc.storage.getItem('storageNotConform');
if (jsxc.storageNotConform === null) {
jsxc.storageNotConform = 2;
}
// detect language
var lang;
if (jsxc.storage.getItem('lang') !== null) {
lang = jsxc.storage.getItem('lang');
} else if (jsxc.options.autoLang && navigator.languages && navigator.languages.length > 0) {
lang = navigator.languages[0].substr(0, 2);
} else if (jsxc.options.autoLang && navigator.language) {
lang = navigator.language.substr(0, 2);
} else {
lang = jsxc.options.defaultLang;
}
// initialize i18n translator
$.i18n.init({
lng: lang,
fallbackLng: 'en',
resStore: I18next,
// use localStorage and set expiration to a day
useLocalStorage: true,
localStorageExpirationTime: 60 * 60 * 24 * 1000,
debug: jsxc.storage.getItem('debug') === true
});
if (jsxc.storage.getItem('debug') === true) {
jsxc.options.otr.debug = true;
}
// Register event listener for the storage event
window.addEventListener('storage', jsxc.storage.onStorage, false);
$(document).on('attached.jsxc', jsxc.registerLogout);
var isStorageAttachParameters = jsxc.storage.getItem('rid') && jsxc.storage.getItem('sid') && jsxc.storage.getItem('jid');
var isOptionsAttachParameters = jsxc.options.xmpp.rid && jsxc.options.xmpp.sid && jsxc.options.xmpp.jid;
var isForceLoginForm = jsxc.options.loginForm && jsxc.options.loginForm.ifFound === 'force' && jsxc.isLoginForm();
// Check if we have to establish a new connection
if ((!isStorageAttachParameters && !isOptionsAttachParameters) || isForceLoginForm) {
// clean up rid and sid
jsxc.storage.removeItem('rid');
jsxc.storage.removeItem('sid');
// Looking for a login form
if (!jsxc.isLoginForm()) {
if (jsxc.options.displayRosterMinimized()) {
// Show minimized roster
jsxc.storage.setUserItem('roster', 'hidden');
jsxc.gui.roster.init();
jsxc.gui.roster.noConnection();
}
return;
}
if (typeof jsxc.options.formFound === 'function') {
jsxc.options.formFound.call();
}
// create jquery object
var form = jsxc.options.loginForm.form = $(jsxc.options.loginForm.form);
var events = form.data('events') || {
submit: []
};
var submits = [];
// save attached submit events and remove them. Will be reattached
// in jsxc.submitLoginForm
$.each(events.submit, function(index, val) {
submits.push(val.handler);
});
form.data('submits', submits);
form.off('submit');
// Add jsxc login action to form
form.submit(function() {
jsxc.prepareLogin(function(settings) {
if (settings !== false) {
// settings.xmpp.onlogin is deprecated since v2.1.0
var enabled = (settings.loginForm && settings.loginForm.enable) || (settings.xmpp && settings.xmpp.onlogin);
enabled = enabled === "true" || enabled === true;
if (enabled) {
jsxc.options.loginForm.triggered = true;
jsxc.xmpp.login(jsxc.options.xmpp.jid, jsxc.options.xmpp.password);
}
} else {
jsxc.submitLoginForm();
}
});
// Trigger submit in jsxc.xmpp.connected()
return false;
});
} else if (!jsxc.isLoginForm() || (jsxc.options.loginForm && jsxc.options.loginForm.ifFound === 'attach')) {
// Restore old connection
if (typeof jsxc.storage.getItem('alive') === 'undefined') {
jsxc.onMaster();
} else {
jsxc.checkMaster();
}
}
},
/**
* Attach to previous session if jid, sid and rid are available
* in storage or options (default behaviour also for {@link jsxc.init}).
*
* @memberOf jsxc
*/
/**
* Start new chat session with given jid and password.
*
* @memberOf jsxc
* @param {string} jid Jabber Id
* @param {string} password Jabber password
*/
/**
* Attach to new chat session with jid, sid and rid.
*
* @memberOf jsxc
* @param {string} jid Jabber Id
* @param {string} sid Session Id
* @param {string} rid Request Id
*/
start: function() {
var args = arguments;
if (jsxc.role_allocation && !jsxc.master) {
jsxc.debug('There is an other master tab');
return false;
}
if (jsxc.xmpp.conn && jsxc.xmpp.connected) {
jsxc.debug('We are already connected');
return false;
}
if (args.length === 3) {
$(document).one('attached.jsxc', function() {
// save rid after first attachment
jsxc.xmpp.onRidChange(jsxc.xmpp.conn._proto.rid);
jsxc.onMaster();
});
}
jsxc.checkMaster(function() {
jsxc.xmpp.login.apply(this, args);
});
},
registerLogout: function() {
// Looking for logout element
if (jsxc.options.logoutElement !== null && $(jsxc.options.logoutElement).length > 0) {
var logout = function(ev) {
ev.stopPropagation();
ev.preventDefault();
jsxc.options.logoutElement = $(this);
jsxc.triggeredFromLogout = true;
jsxc.xmpp.logout();
};
jsxc.options.logoutElement = $(jsxc.options.logoutElement);
jsxc.options.logoutElement.off('click', null, logout).one('click', logout);
}
},
/**
* Returns true if login form is found.
*
* @memberOf jsxc
* @returns {boolean} True if login form was found.
*/
isLoginForm: function() {
return jsxc.options.loginForm.form && jsxc.el_exists(jsxc.options.loginForm.form) && jsxc.el_exists(jsxc.options.loginForm.jid) && jsxc.el_exists(jsxc.options.loginForm.pass);
},
/**
* Load settings and prepare jid.
*
* @memberOf jsxc
* @param {string} username
* @param {string} password
* @param {function} cb Called after login is prepared with result as param
*/
prepareLogin: function(username, password, cb) {
if (typeof username === 'function') {
cb = username;
username = null;
}
username = username || $(jsxc.options.loginForm.jid).val();
password = password || $(jsxc.options.loginForm.pass).val();
if (!jsxc.triggeredFromBox && (jsxc.options.loginForm.onConnecting === 'dialog' || typeof jsxc.options.loginForm.onConnecting === 'undefined')) {
jsxc.gui.showWaitAlert($.t('Logging_in'));
}
var settings;
if (typeof jsxc.options.loadSettings === 'function') {
settings = jsxc.options.loadSettings.call(this, username, password, function(s) {
jsxc._prepareLogin(username, password, cb, s);
});
if (typeof settings !== 'undefined') {
jsxc._prepareLogin(username, password, cb, settings);
}
} else {
jsxc._prepareLogin(username, password, cb);
}
},
/**
* Process xmpp settings and save loaded settings.
*
* @private
* @memberOf jsxc
* @param {string} username
* @param {string} password
* @param {function} cb Called after login is prepared with result as param
* @param {object} [loadedSettings] additonal options
*/
_prepareLogin: function(username, password, cb, loadedSettings) {
if (loadedSettings === false) {
jsxc.warn('No settings provided');
cb(false);
return;
}
// prevent to modify the original object
var settings = $.extend(true, {}, jsxc.options);
if (loadedSettings) {
// overwrite current options with loaded settings;
settings = $.extend(true, settings, loadedSettings);
} else {
loadedSettings = {};
}
if (typeof settings.xmpp.username === 'string') {
username = settings.xmpp.username;
}
var resource = (settings.xmpp.resource) ? '/' + settings.xmpp.resource : '';
var domain = settings.xmpp.domain;
var jid;
if (username.match(/@(.*)$/)) {
jid = (username.match(/\/(.*)$/)) ? username : username + resource;
} else {
jid = username + '@' + domain + resource;
}
if (typeof jsxc.options.loginForm.preJid === 'function') {
jid = jsxc.options.loginForm.preJid(jid);
}
jsxc.bid = jsxc.jidToBid(jid);
settings.xmpp.username = jid.split('@')[0];
settings.xmpp.domain = jid.split('@')[1].split('/')[0];
settings.xmpp.resource = jid.split('@')[1].split('/')[1] || "";
if (!loadedSettings.xmpp) {
// force xmpp settings to be saved to storage
loadedSettings.xmpp = {};
}
// save loaded settings to storage
$.each(loadedSettings, function(key) {
var old = jsxc.options.get(key);
var val = settings[key];
val = $.extend(true, old, val);
jsxc.options.set(key, val);
});
jsxc.options.xmpp.jid = jid;
jsxc.options.xmpp.password = password;
cb(settings);
},
/**
* Called if the script is a slave
*/
onSlave: function() {
jsxc.debug('I am the slave.');
jsxc.role_allocation = true;
jsxc.bid = jsxc.jidToBid(jsxc.storage.getItem('jid'));
jsxc.gui.init();
$('#jsxc_roster').removeClass('jsxc_noConnection');
jsxc.restoreRoster();
jsxc.restoreWindows();
jsxc.restoreCompleted = true;
jsxc.registerLogout();
jsxc.gui.updateAvatar($('#jsxc_roster > .jsxc_bottom'), jsxc.jidToBid(jsxc.storage.getItem('jid')), 'own');
$(document).trigger('restoreCompleted.jsxc');
},
/**
* Called if the script is the master
*/
onMaster: function() {
jsxc.debug('I am master.');
jsxc.master = true;
// Init local storage
jsxc.storage.setItem('alive', 0);
jsxc.storage.setItem('alive_busy', 0);
// Sending keepalive signal
jsxc.startKeepAlive();
jsxc.role_allocation = true;
jsxc.xmpp.login();
},
/**
* Checks if there is a master
*
* @param {function} [cb] Called if no master was found.
*/
checkMaster: function(cb) {
jsxc.debug('check master');
cb = (cb && typeof cb === 'function') ? cb : jsxc.onMaster;
if (typeof jsxc.storage.getItem('alive') === 'undefined') {
cb.call();
} else {
jsxc.to.push(window.setTimeout(cb, 1000));
jsxc.keepAlive('slave');
}
},
masterActions: function() {
if (!jsxc.xmpp.conn || !jsxc.xmpp.conn.authenticated) {
return;
}
//prepare notifications
var noti = jsxc.storage.getUserItem('notification');
noti = (typeof noti === 'number') ? noti : 2;
if (jsxc.options.notification && noti > 0 && jsxc.notification.hasSupport()) {
if (jsxc.notification.hasPermission()) {
jsxc.notification.init();
} else {
jsxc.notification.prepareRequest();
}
} else {
// No support => disable
jsxc.options.notification = false;
}
if (jsxc.options.get('otr').enable) {
// create or load DSA key
jsxc.otr.createDSA();
}
jsxc.gui.updateAvatar($('#jsxc_roster > .jsxc_bottom'), jsxc.jidToBid(jsxc.storage.getItem('jid')), 'own');
},
/**
* Start sending keep-alive signal
*/
startKeepAlive: function() {
jsxc.keepaliveInterval = window.setInterval(jsxc.keepAlive, jsxc.options.timeout - 1000);
},
/**
* Sends the keep-alive signal to signal that the master is still there.
*/
keepAlive: function(role) {
var next = parseInt(jsxc.storage.getItem('alive')) + 1;
role = role || 'master';
jsxc.storage.setItem('alive', next + ':' + role);
},
/**
* Send one keep-alive signal with higher timeout, and than resume with
* normal signal
*/
keepBusyAlive: function() {
if (jsxc.toBusy) {
window.clearTimeout(jsxc.toBusy);
}
if (jsxc.keepaliveInterval) {
window.clearInterval(jsxc.keepaliveInterval);
}
jsxc.storage.ink('alive_busy');
jsxc.toBusy = window.setTimeout(jsxc.startKeepAlive, jsxc.options.busyTimeout - 1000);
},
/**
* Generates a random integer number between 0 and max
*
* @param {Integer} max
* @return {Integer} random integer between 0 and max
*/
random: function(max) {
return Math.floor(Math.random() * max);
},
/**
* Checks if there is a element with the given selector
*
* @param {String} selector jQuery selector
* @return {Boolean}
*/
el_exists: function(selector) {
return $(selector).length > 0;
},
/**
* Creates a CSS compatible string from a JID
*
* @param {type} jid Valid Jabber ID
* @returns {String} css Compatible string
*/
jidToCid: function(jid) {
jsxc.warn('jsxc.jidToCid is deprecated!');
var cid = Strophe.getBareJidFromJid(jid).replace('@', '-').replace(/\./g, '-').toLowerCase();
return cid;
},
/**
* Create comparable bar jid.
*
* @memberOf jsxc
* @param jid
* @returns comparable bar jid
*/
jidToBid: function(jid) {
return Strophe.unescapeNode(Strophe.getBareJidFromJid(jid).toLowerCase());
},
/**
* Restore roster
*/
restoreRoster: function() {
var buddies = jsxc.storage.getUserItem('buddylist');
if (!buddies || buddies.length === 0) {
jsxc.debug('No saved buddylist.');
jsxc.gui.roster.empty();
return;
}
$.each(buddies, function(index, value) {
jsxc.gui.roster.add(value);
});
jsxc.gui.roster.loaded = true;
$(document).trigger('cloaded.roster.jsxc');
},
/**
* Restore all windows
*/
restoreWindows: function() {
var windows = jsxc.storage.getUserItem('windowlist');
if (windows === null) {
return;
}
$.each(windows, function(index, bid) {
var win = jsxc.storage.getUserItem('window', bid);
if (!win) {
jsxc.debug('Associated window-element is missing: ' + bid);
return true;
}
jsxc.gui.window.init(bid);
if (!win.minimize) {
jsxc.gui.window.show(bid);
} else {
jsxc.gui.window.hide(bid);
}
jsxc.gui.window.setText(bid, win.text);
});
},
/**
* This method submits the specified login form.
*/
submitLoginForm: function() {
var form = $(jsxc.options.loginForm.form).off('submit');
// Attach original events
var submits = form.data('submits') || [];
$.each(submits, function(index, val) {
form.submit(val);
});
if (form.find('#submit').length > 0) {
form.find('#submit').click();
} else {
form.submit();
}
},
/**
* Escapes some characters to HTML character
*/
escapeHTML: function(text) {
text = text.replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>');
return text.replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>');
},
/**
* Removes all html tags.
*
* @memberOf jsxc
* @param text
* @returns stripped text
*/
removeHTML: function(text) {
return $('<span>').html(text).text();
},
/**
* Executes only one of the given events
*
* @param {string} obj.key event name
* @param {function} obj.value function to execute
* @returns {string} namespace of all events
*/
switchEvents: function(obj) {
var ns = Math.random().toString(36).substr(2, 12);
var self = this;
$.each(obj, function(key, val) {
$(document).one(key + '.' + ns, function() {
$(document).off('.' + ns);
val.apply(self, arguments);
});
});
return ns;
},
/**
* Checks if tab is hidden.
*
* @returns {boolean} True if tab is hidden
*/
isHidden: function() {
var hidden = false;
if (typeof document.hidden !== 'undefined') {
hidden = document.hidden;
} else if (typeof document.webkitHidden !== 'undefined') {
hidden = document.webkitHidden;
} else if (typeof document.mozHidden !== 'undefined') {
hidden = document.mozHidden;
} else if (typeof document.msHidden !== 'undefined') {
hidden = document.msHidden;
}
// handle multiple tabs
if (hidden && jsxc.master) {
jsxc.storage.ink('hidden', 0);
} else if (!hidden && !jsxc.master) {
jsxc.storage.ink('hidden');
}
return hidden;
},
/**
* Checks if tab has focus.
*
* @returns {boolean} True if tabs has focus
*/
hasFocus: function() {
var focus = true;
if (typeof document.hasFocus === 'function') {
focus = document.hasFocus();
}
if (!focus && jsxc.master) {
jsxc.storage.ink('focus', 0);
} else if (focus && !jsxc.master) {
jsxc.storage.ink('focus');
}
return focus;
},
/**
* Executes the given function in jsxc namespace.
*
* @memberOf jsxc
* @param {string} fnName Function name
* @param {array} fnParams Function parameters
* @returns Function return value
*/
exec: function(fnName, fnParams) {
var fnList = fnName.split('.');
var fn = jsxc[fnList[0]];
var i;
for (i = 1; i < fnList.length; i++) {
fn = fn[fnList[i]];
}
if (typeof fn === 'function') {
return fn.apply(null, fnParams);
}
},
/**
* Hash string into 32-bit signed integer.
*
* @memberOf jsxc
* @param {string} str input string
* @returns {integer} 32-bit signed integer
*/
hashStr: function(str) {
var hash = 0,
i;
if (str.length === 0) {
return hash;
}
for (i = 0; i < str.length; i++) {
hash = ((hash << 5) - hash) + str.charCodeAt(i);
hash |= 0; // Convert to 32bit integer
}
return hash;
},
isExtraSmallDevice: function() {
return $(window).width() < 500;
}
};
/**
* Handle XMPP stuff.
*
* @namespace jsxc.xmpp
*/
jsxc.xmpp = {
conn: null, // connection
/**
* Create new connection or attach to old
*
* @name login
* @memberOf jsxc.xmpp
* @private
*/
/**
* Create new connection with given parameters.
*
* @name login^2
* @param {string} jid
* @param {string} password
* @memberOf jsxc.xmpp
* @private
*/
/**
* Attach connection with given parameters.
*
* @name login^3
* @param {string} jid
* @param {string} sid
* @param {string} rid
* @memberOf jsxc.xmpp
* @private
*/
login: function() {
if (jsxc.xmpp.conn && jsxc.xmpp.conn.authenticated) {
jsxc.debug('Connection already authenticated.');
return;
}
var jid = null,
password = null,
sid = null,
rid = null;
switch (arguments.length) {
case 2:
jid = arguments[0];
password = arguments[1];
break;
case 3:
jid = arguments[0];
sid = arguments[1];
rid = arguments[2];
break;
default:
sid = jsxc.storage.getItem('sid');
rid = jsxc.storage.getItem('rid');
if (sid !== null && rid !== null) {
jid = jsxc.storage.getItem('jid');
} else {
sid = jsxc.options.xmpp.sid || null;
rid = jsxc.options.xmpp.rid || null;
jid = jsxc.options.xmpp.jid;
}