forked from conversejs/converse.js
-
Notifications
You must be signed in to change notification settings - Fork 0
/
converse-core.js
2034 lines (1892 loc) · 76.2 KB
/
converse-core.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
// Converse.js
// https://conversejs.org
//
// Copyright (c) 2013-2019, the Converse.js developers
// Licensed under the Mozilla Public License (MPLv2)
import * as bosh from 'strophe.js/src/bosh';
import * as strophe from 'strophe.js/src/core';
import * as websocket from 'strophe.js/src/websocket';
import Backbone from "backbone";
import BrowserStorage from "backbone.browserStorage";
import Promise from "es6-promise/dist/es6-promise.auto";
import _ from "./lodash.noconflict";
import advancedFormat from 'dayjs/plugin/advancedFormat';
import dayjs from "dayjs";
import i18n from "./i18n";
import pluggable from "pluggable.js/src/pluggable";
import polyfill from "./polyfill";
import sizzle from "sizzle";
import u from "@converse/headless/utils/core";
const Strophe = strophe.default.Strophe;
const $build = strophe.default.$build;
const $iq = strophe.default.$iq;
const $msg = strophe.default.$msg;
const $pres = strophe.default.$pres;
Backbone = Backbone.noConflict();
dayjs.extend(advancedFormat);
// Add Strophe Namespaces
Strophe.addNamespace('CARBONS', 'urn:xmpp:carbons:2');
Strophe.addNamespace('CHATSTATES', 'http://jabber.org/protocol/chatstates');
Strophe.addNamespace('CSI', 'urn:xmpp:csi:0');
Strophe.addNamespace('DELAY', 'urn:xmpp:delay');
Strophe.addNamespace('FORWARD', 'urn:xmpp:forward:0');
Strophe.addNamespace('HINTS', 'urn:xmpp:hints');
Strophe.addNamespace('HTTPUPLOAD', 'urn:xmpp:http:upload:0');
Strophe.addNamespace('IDLE', 'urn:xmpp:idle:1');
Strophe.addNamespace('MAM', 'urn:xmpp:mam:2');
Strophe.addNamespace('NICK', 'http://jabber.org/protocol/nick');
Strophe.addNamespace('OMEMO', "eu.siacs.conversations.axolotl");
Strophe.addNamespace('OUTOFBAND', 'jabber:x:oob');
Strophe.addNamespace('PUBSUB', 'http://jabber.org/protocol/pubsub');
Strophe.addNamespace('REGISTER', 'jabber:iq:register');
Strophe.addNamespace('ROSTERX', 'http://jabber.org/protocol/rosterx');
Strophe.addNamespace('RSM', 'http://jabber.org/protocol/rsm');
Strophe.addNamespace('SID', 'urn:xmpp:sid:0');
Strophe.addNamespace('SPOILER', 'urn:xmpp:spoiler:0');
Strophe.addNamespace('STANZAS', 'urn:ietf:params:xml:ns:xmpp-stanzas');
Strophe.addNamespace('VCARD', 'vcard-temp');
Strophe.addNamespace('VCARDUPDATE', 'vcard-temp:x:update');
Strophe.addNamespace('XFORM', 'jabber:x:data');
// Use Mustache style syntax for variable interpolation
/* Configuration of Lodash templates (this config is distinct to the
* config of requirejs-tpl in main.js). This one is for normal inline templates.
*/
_.templateSettings = {
'escape': /\{\{\{([\s\S]+?)\}\}\}/g,
'evaluate': /\{\[([\s\S]+?)\]\}/g,
'interpolate': /\{\{([\s\S]+?)\}\}/g,
'imports': { '_': _ }
};
// Setting wait to 59 instead of 60 to avoid timing conflicts with the
// webserver, which is often also set to 60 and might therefore sometimes
// return a 504 error page instead of passing through to the BOSH proxy.
const BOSH_WAIT = 59;
// Core plugins are whitelisted automatically
// These are just the @converse/headless plugins, for the full converse,
// the other plugins are whitelisted in src/converse.js
const CORE_PLUGINS = [
'converse-bookmarks',
'converse-caps',
'converse-chatboxes',
'converse-disco',
'converse-mam',
'converse-muc',
'converse-ping',
'converse-pubsub',
'converse-roster',
'converse-rsm',
'converse-smacks',
'converse-vcard'
];
/**
* A private, closured object containing the private api (via {@link _converse.api})
* as well as private methods and internal data-structures.
*
* @namespace _converse
*/
const _converse = {
'templates': {},
'promises': {}
}
_converse.VERSION_NAME = "v4.2.0";
Object.assign(_converse, Backbone.Events);
// Make converse pluggable
pluggable.enable(_converse, '_converse', 'pluggable');
_converse.keycodes = {
TAB: 9,
ENTER: 13,
SHIFT: 16,
CTRL: 17,
ALT: 18,
ESCAPE: 27,
UP_ARROW: 38,
DOWN_ARROW: 40,
FORWARD_SLASH: 47,
AT: 50,
META: 91,
META_RIGHT: 93
};
// Module-level constants
_converse.STATUS_WEIGHTS = {
'offline': 6,
'unavailable': 5,
'xa': 4,
'away': 3,
'dnd': 2,
'chat': 1, // We currently don't differentiate between "chat" and "online"
'online': 1
};
_converse.PRETTY_CHAT_STATUS = {
'offline': 'Offline',
'unavailable': 'Unavailable',
'xa': 'Extended Away',
'away': 'Away',
'dnd': 'Do not disturb',
'chat': 'Chattty',
'online': 'Online'
};
_converse.ANONYMOUS = "anonymous";
_converse.CLOSED = 'closed';
_converse.EXTERNAL = "external";
_converse.LOGIN = "login";
_converse.LOGOUT = "logout";
_converse.OPENED = 'opened';
_converse.PREBIND = "prebind";
_converse.IQ_TIMEOUT = 20000;
_converse.CONNECTION_STATUS = {
0: 'ERROR',
1: 'CONNECTING',
2: 'CONNFAIL',
3: 'AUTHENTICATING',
4: 'AUTHFAIL',
5: 'CONNECTED',
6: 'DISCONNECTED',
7: 'DISCONNECTING',
8: 'ATTACHED',
9: 'REDIRECT',
10: 'RECONNECTING',
};
_converse.SUCCESS = 'success';
_converse.FAILURE = 'failure';
// Generated from css/images/user.svg
_converse.DEFAULT_IMAGE_TYPE = 'image/svg+xml';
_converse.DEFAULT_IMAGE = "PD94bWwgdmVyc2lvbj0iMS4wIj8+CjxzdmcgeG1sbnM9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvc3ZnIiB3aWR0aD0iMTI4IiBoZWlnaHQ9IjEyOCI+CiA8cmVjdCB3aWR0aD0iMTI4IiBoZWlnaHQ9IjEyOCIgZmlsbD0iIzU1NSIvPgogPGNpcmNsZSBjeD0iNjQiIGN5PSI0MSIgcj0iMjQiIGZpbGw9IiNmZmYiLz4KIDxwYXRoIGQ9Im0yOC41IDExMiB2LTEyIGMwLTEyIDEwLTI0IDI0LTI0IGgyMyBjMTQgMCAyNCAxMiAyNCAyNCB2MTIiIGZpbGw9IiNmZmYiLz4KPC9zdmc+Cg==";
_converse.TIMEOUTS = { // Set as module attr so that we can override in tests.
'PAUSED': 10000,
'INACTIVE': 90000
};
// XEP-0085 Chat states
// https://xmpp.org/extensions/xep-0085.html
_converse.INACTIVE = 'inactive';
_converse.ACTIVE = 'active';
_converse.COMPOSING = 'composing';
_converse.PAUSED = 'paused';
_converse.GONE = 'gone';
// Chat types
_converse.PRIVATE_CHAT_TYPE = 'chatbox';
_converse.CHATROOMS_TYPE = 'chatroom';
_converse.HEADLINES_TYPE = 'headline';
_converse.CONTROLBOX_TYPE = 'controlbox';
_converse.default_connection_options = {'explicitResourceBinding': true};
// Default configuration values
// ----------------------------
_converse.default_settings = {
allow_non_roster_messaging: false,
authentication: 'login', // Available values are "login", "prebind", "anonymous" and "external".
auto_away: 0, // Seconds after which user status is set to 'away'
auto_login: false, // Currently only used in connection with anonymous login
auto_reconnect: true,
auto_xa: 0, // Seconds after which user status is set to 'xa'
blacklisted_plugins: [],
bosh_service_url: undefined,
connection_options: {},
credentials_url: null, // URL from where login credentials can be fetched
csi_waiting_time: 0, // Support for XEP-0352. Seconds before client is considered idle and CSI is sent out.
debug: false,
default_state: 'online',
expose_rid_and_sid: false,
geouri_regex: /https:\/\/www.openstreetmap.org\/.*#map=[0-9]+\/([\-0-9.]+)\/([\-0-9.]+)\S*/g,
geouri_replacement: 'https://www.openstreetmap.org/?mlat=$1&mlon=$2#map=18/$1/$2',
idle_presence_timeout: 300, // Seconds after which an idle presence is sent
jid: undefined,
keepalive: true,
locales_url: 'locale/{{{locale}}}/LC_MESSAGES/converse.json',
locales: [
'af', 'ar', 'bg', 'ca', 'cs', 'de', 'eo', 'es', 'eu', 'en', 'fr', 'gl',
'he', 'hi', 'hu', 'id', 'it', 'ja', 'nb', 'nl',
'pl', 'pt_BR', 'ro', 'ru', 'tr', 'uk', 'zh_CN', 'zh_TW'
],
message_carbons: true,
nickname: undefined,
password: undefined,
prebind_url: null,
priority: 0,
rid: undefined,
root: window.document,
sid: undefined,
singleton: false,
strict_plugin_dependencies: false,
trusted: true,
view_mode: 'overlayed', // Choices are 'overlayed', 'fullscreen', 'mobile'
websocket_url: undefined,
whitelisted_plugins: []
};
/**
* Logs messages to the browser's developer console.
* Available loglevels are 0 for 'debug', 1 for 'info', 2 for 'warn',
* 3 for 'error' and 4 for 'fatal'.
* When using the 'error' or 'warn' loglevels, a full stacktrace will be
* logged as well.
* @method log
* @private
* @memberOf _converse
* @param { string } message - The message to be logged
* @param { integer } level - The loglevel which allows for filtering of log messages
*/
_converse.log = function (message, level, style='') {
if (level === Strophe.LogLevel.ERROR || level === Strophe.LogLevel.FATAL) {
style = style || 'color: maroon';
}
if (message instanceof Error) {
message = message.stack;
} else if (_.isElement(message)) {
message = message.outerHTML;
}
const prefix = style ? '%c' : '';
const logger = Object.assign({
'debug': _.get(console, 'log') ? console.log.bind(console) : _.noop,
'error': _.get(console, 'log') ? console.log.bind(console) : _.noop,
'info': _.get(console, 'log') ? console.log.bind(console) : _.noop,
'warn': _.get(console, 'log') ? console.log.bind(console) : _.noop
}, console);
if (level === Strophe.LogLevel.ERROR) {
logger.error(`${prefix} ERROR: ${message}`, style);
} else if (level === Strophe.LogLevel.WARN) {
if (_converse.debug) {
logger.warn(`${prefix} ${(new Date()).toISOString()} WARNING: ${message}`, style);
}
} else if (level === Strophe.LogLevel.FATAL) {
logger.error(`${prefix} FATAL: ${message}`, style);
} else if (_converse.debug) {
if (level === Strophe.LogLevel.DEBUG) {
logger.debug(`${prefix} ${(new Date()).toISOString()} DEBUG: ${message}`, style);
} else {
logger.info(`${prefix} ${(new Date()).toISOString()} INFO: ${message}`, style);
}
}
};
Strophe.log = function (level, msg) { _converse.log(level+' '+msg, level); };
Strophe.error = function (msg) { _converse.log(msg, Strophe.LogLevel.ERROR); };
/**
* Translate the given string based on the current locale.
* Handles all MUC presence stanzas.
* @method __
* @private
* @memberOf _converse
* @param { String } str - The string to translate
*/
_converse.__ = function (str) {
if (_.isUndefined(i18n)) {
return str;
}
return i18n.translate.apply(i18n, arguments);
}
const __ = _converse.__;
const PROMISES = [
'afterResourceBinding',
'connectionInitialized',
'initialized',
'pluginsInitialized',
'statusInitialized'
];
function addPromise (promise) {
/* Private function, used to add a new promise to the ones already
* available via the `waitUntil` api method.
*/
_converse.promises[promise] = u.getResolveablePromise();
}
function isTestEnv () {
return _.get(_converse.connection, 'service') === 'jasmine tests';
}
_converse.isUniView = function () {
/* We distinguish between UniView and MultiView instances.
*
* UniView means that only one chat is visible, even though there might be multiple ongoing chats.
* MultiView means that multiple chats may be visible simultaneously.
*/
return _.includes(['mobile', 'fullscreen', 'embedded'], _converse.view_mode);
}
_converse.router = new Backbone.Router();
function initPlugins() {
// If initialize gets called a second time (e.g. during tests), then we
// need to re-apply all plugins (for a new converse instance), and we
// therefore need to clear this array that prevents plugins from being
// initialized twice.
// If initialize is called for the first time, then this array is empty
// in any case.
_converse.pluggable.initialized_plugins = [];
const whitelist = CORE_PLUGINS.concat(_converse.whitelisted_plugins);
if (_converse.singleton) {
_.forEach([ // eslint-disable-line lodash/prefer-map
"converse-bookmarks",
"converse-controlbox",
"converse-headline",
"converse-register"
], (name) => {
_converse.blacklisted_plugins.push(name)
});
}
_converse.pluggable.initializePlugins(
{'_converse': _converse},
whitelist, _converse.blacklisted_plugins
);
/**
* Triggered once all plugins have been initialized. This is a useful event if you want to
* register event handlers but would like your own handlers to be overridable by
* plugins. In that case, you need to first wait until all plugins have been
* initialized, so that their overrides are active. One example where this is used
* is in [converse-notifications.js](https://github.com/jcbrand/converse.js/blob/master/src/converse-notification.js)`.
*
* Also available as an [ES2015 Promise](http://es6-features.org/#PromiseUsage)
* which can be listened to with `_converse.api.waitUntil`.
*
* @event _converse#pluginsInitialized
* @memberOf _converse
* @example _converse.api.listen.on('pluginsInitialized', () => { ... });
* @example _converse.api.waitUntil('pluginsInitialized').then(() => { ... });
*/
_converse.api.trigger('pluginsInitialized');
}
function initClientConfig () {
/* The client config refers to configuration of the client which is
* independent of any particular user.
* What this means is that config values need to persist across
* user sessions.
*/
const id = 'converse.client-config';
_converse.config = new Backbone.Model({
'id': id,
'trusted': _converse.trusted && true || false,
'storage': _converse.trusted ? 'local' : 'session'
});
_converse.config.browserStorage = new BrowserStorage.session(id);
_converse.config.fetch();
/**
* Triggered once the XMPP-client configuration has been initialized.
* The client configuration is independent of any particular and its values
* persist across user sessions.
*
* @event _converse#clientConfigInitialized
* @example
* _converse.api.listen.on('clientConfigInitialized', () => { ... });
*/
_converse.api.trigger('clientConfigInitialized');
}
function tearDown () {
_converse.api.trigger('beforeTearDown');
window.removeEventListener('click', _converse.onUserActivity);
window.removeEventListener('focus', _converse.onUserActivity);
window.removeEventListener('keypress', _converse.onUserActivity);
window.removeEventListener('mousemove', _converse.onUserActivity);
window.removeEventListener(_converse.unloadevent, _converse.onUserActivity);
window.clearInterval(_converse.everySecondTrigger);
_converse.api.trigger('afterTearDown');
return _converse;
}
function reconnect () {
_converse.log('RECONNECTING: the connection has dropped, attempting to reconnect.');
_converse.setConnectionStatus(
Strophe.Status.RECONNECTING,
__('The connection has dropped, attempting to reconnect.')
);
/**
* Triggered when the connection has dropped, but Converse will attempt
* to reconnect again.
*
* @event _converse#will-reconnect
*/
_converse.api.trigger('will-reconnect');
_converse.connection.reconnecting = true;
tearDown();
_converse.api.user.login(null, null, true);
}
const debouncedReconnect = _.debounce(reconnect, 2000);
function clearSession () {
if (!_.isUndefined(_converse.bosh_session)) {
_converse.bosh_session.destroy();
delete _converse.bosh_session;
}
if (!_.isUndefined(_converse.session)) {
_converse.session.destroy();
delete _converse.session;
}
// TODO: Refactor so that we don't clear
if (!_converse.config.get('trusted') || isTestEnv()) {
window.localStorage.clear();
window.sessionStorage.clear();
} else {
if (!_.isUndefined(_converse.bosh_session)) {
_converse.bosh_session.destroy();
delete _converse.bosh_session;
}
if (!_.isUndefined(_converse.session)) {
_converse.session.destroy();
delete _converse.session;
}
_.get(_converse, 'bosh_session.browserStorage', {'_clear': _.noop})._clear();
_.get(_converse, 'session.browserStorage', {'_clear': _.noop})._clear();
}
/**
* Triggered once the session information has been cleared,
* for example when the user has logged out or when Converse has
* disconnected for some other reason.
* @event _converse#clearSession
*/
_converse.api.trigger('clearSession');
}
_converse.initConnection = function () {
/* Creates a new Strophe.Connection instance if we don't already have one.
*/
if (!_converse.connection) {
if (!_converse.bosh_service_url && ! _converse.websocket_url) {
throw new Error("initConnection: you must supply a value for either the bosh_service_url or websocket_url or both.");
}
if (('WebSocket' in window || 'MozWebSocket' in window) && _converse.websocket_url) {
_converse.connection = new Strophe.Connection(
_converse.websocket_url,
Object.assign(_converse.default_connection_options, _converse.connection_options)
);
} else if (_converse.bosh_service_url) {
_converse.connection = new Strophe.Connection(
_converse.bosh_service_url,
Object.assign(_converse.default_connection_options, _converse.connection_options, {'keepalive': _converse.keepalive})
);
} else {
throw new Error("initConnection: this browser does not support websockets and bosh_service_url wasn't specified.");
}
}
setUpXMLLogging();
/**
* Triggered once the `Strophe.Connection` constructor has been initialized, which
* will be responsible for managing the connection to the XMPP server.
*
* @event _converse#connectionInitialized
*/
_converse.api.trigger('connectionInitialized');
}
async function initBOSHSession () {
const id = 'converse.bosh-session';
_converse.bosh_session = new Backbone.Model({id});
_converse.bosh_session.browserStorage = new BrowserStorage.session(id);
try {
await new Promise((success, error) => _converse.bosh_session.fetch({success, error}));
if (_converse.jid && !u.isSameBareJID(_converse.bosh_session.get('jid'), _converse.jid)) {
_converse.bosh_session.clear({'silent': true});
_converse.bosh_session.save({'jid': _converse.jid, id});
}
} catch (e) {
if (_converse.jid) {
_converse.bosh_session.save({'jid': _converse.jid});
}
}
/**
* Triggered once the session has been initialized. The session is a
* persistent object which stores session information in the browser storage.
* @event _converse#BOSHSessionInitialized
* @memberOf _converse
*/
_converse.api.trigger('BOSHSessionInitialized');
}
async function initUserSession (jid) {
const bare_jid = Strophe.getBareJidFromJid(jid);
const id = `converse.session-${bare_jid}`;
if (!_converse.session || _converse.session.get('id') !== id) {
_converse.session = new Backbone.Model({id});
_converse.session.browserStorage = new BrowserStorage.session(id);
await new Promise(r => _converse.session.fetch({'success': r, 'error': r}));
/**
* Triggered once the user's session has been initialized. The session is a
* cache which stores information about the user's current session.
* @event _converse#userSessionInitialized
* @memberOf _converse
*/
_converse.api.trigger('userSessionInitialized');
}
}
function setUserJID (jid) {
if (!Strophe.getResourceFromJid(jid)) {
jid = jid.toLowerCase() + _converse.generateResource();
}
jid = jid.toLowerCase();
initUserSession(jid);
_converse.jid = jid;
_converse.bare_jid = Strophe.getBareJidFromJid(jid);
_converse.resource = Strophe.getResourceFromJid(jid);
_converse.domain = Strophe.getDomainFromJid(jid);
_converse.session.save({
'jid': jid,
'bare_jid': _converse.bare_jid,
'resource': _converse.resource,
'domain': _converse.domain
});
}
async function onConnected (reconnecting) {
/* Called as soon as a new connection has been established, either
* by logging in or by attaching to an existing BOSH session.
*/
_converse.connection.flush(); // Solves problem of returned PubSub BOSH response not received by browser
setUserJID(_converse.connection.jid);
/**
* Synchronous event triggered after we've sent an IQ to bind the
* user's JID resource for this session.
* @event _converse#afterResourceBinding
*/
await _converse.api.trigger('afterResourceBinding', {'synchronous': true});
_converse.enableCarbons();
_converse.initStatus(reconnecting)
}
function setUpXMLLogging () {
Strophe.log = function (level, msg) {
_converse.log(msg, level);
};
_converse.connection.xmlInput = function (body) {
if (_converse.debug) {
_converse.log(body.outerHTML, Strophe.LogLevel.DEBUG, 'color: darkgoldenrod');
}
};
_converse.connection.xmlOutput = function (body) {
if (_converse.debug) {
_converse.log(body.outerHTML, Strophe.LogLevel.DEBUG, 'color: darkcyan');
}
};
}
async function finishInitialization () {
initClientConfig();
initPlugins();
_converse.initConnection();
await initBOSHSession();
_converse.api.user.login();
_converse.registerGlobalEventHandlers();
if (!Backbone.history.started) {
Backbone.history.start();
}
if (_converse.idle_presence_timeout > 0) {
_converse.api.listen.on('addClientFeatures', () => {
_converse.api.disco.own.features.add(Strophe.NS.IDLE);
});
}
}
function fetchLoginCredentials (wait=0) {
return new Promise(_.debounce((resolve, reject) => {
const xhr = new XMLHttpRequest();
xhr.open('GET', _converse.credentials_url, true);
xhr.setRequestHeader('Accept', "application/json, text/javascript");
xhr.onload = () => {
if (xhr.status >= 200 && xhr.status < 400) {
const data = JSON.parse(xhr.responseText);
resolve({
'jid': data.jid,
'password': data.password
});
} else {
reject(new Error(`${xhr.status}: ${xhr.responseText}`));
}
};
xhr.onerror = reject;
xhr.send();
}, wait));
}
async function getLoginCredentials () {
let credentials;
let wait = 0;
while (!credentials) {
try {
credentials = await fetchLoginCredentials(wait); // eslint-disable-line no-await-in-loop
} catch (e) {
_converse.log("Could not fetch login credentials", Strophe.LogLevel.ERROR);
_converse.log(e, Strophe.LogLevel.ERROR);
}
// If unsuccessful, we wait 2 seconds between subsequent attempts to
// fetch the credentials.
wait = 2000;
}
return credentials;
}
function unregisterGlobalEventHandlers () {
document.removeEventListener("visibilitychange", _converse.saveWindowState);
_converse.api.trigger('unregisteredGlobalEventHandlers');
}
function cleanup () {
// Looks like _converse.initialized was called again without logging
// out or disconnecting in the previous session.
// This happens in tests. We therefore first clean up.
Backbone.history.stop();
unregisterGlobalEventHandlers();
delete _converse.controlboxtoggle;
if (_converse.chatboxviews) {
delete _converse.chatboxviews;
}
_converse.stopListening();
_converse.off();
}
_converse.initialize = async function (settings, callback) {
settings = !_.isUndefined(settings) ? settings : {};
const init_promise = u.getResolveablePromise();
PROMISES.forEach(addPromise);
if (!_.isUndefined(_converse.connection)) {
cleanup();
}
if ('onpagehide' in window) {
// Pagehide gets thrown in more cases than unload. Specifically it
// gets thrown when the page is cached and not just
// closed/destroyed. It's the only viable event on mobile Safari.
// https://www.webkit.org/blog/516/webkit-page-cache-ii-the-unload-event/
_converse.unloadevent = 'pagehide';
} else if ('onbeforeunload' in window) {
_converse.unloadevent = 'beforeunload';
} else if ('onunload' in window) {
_converse.unloadevent = 'unload';
}
_.assignIn(this, this.default_settings);
// Allow only whitelisted configuration attributes to be overwritten
_.assignIn(this, _.pick(settings, Object.keys(this.default_settings)));
if (this.authentication === _converse.ANONYMOUS) {
if (this.auto_login && !this.jid) {
throw new Error("Config Error: you need to provide the server's " +
"domain via the 'jid' option when using anonymous " +
"authentication with auto_login.");
}
}
_converse.router.route(/^converse\?debug=(true|false)$/, 'debug', debug => {
if (debug === "true") {
_converse.debug = true;
} else {
_converse.debug = false;
}
});
/* Localisation */
if (!_.isUndefined(i18n)) {
i18n.setLocales(settings.i18n, _converse);
} else {
_converse.locale = 'en';
}
// Module-level variables
// ----------------------
this.callback = callback || _.noop;
/* When reloading the page:
* For new sessions, we need to send out a presence stanza to notify
* the server/network that we're online.
* When re-attaching to an existing session (e.g. via the keepalive
* option), we don't need to again send out a presence stanza, because
* it's as if "we never left" (see onConnectStatusChanged).
* https://github.com/jcbrand/converse.js/issues/521
*/
this.send_initial_presence = true;
this.msg_counter = 0;
this.user_settings = settings; // Save the user settings so that they can be used by plugins
// Module-level functions
// ----------------------
this.generateResource = () => `/converse.js-${Math.floor(Math.random()*139749528).toString()}`;
/**
* Send out a Chat Status Notification (XEP-0352)
* @private
* @method sendCSI
* @memberOf _converse
* @param { String } stat - The user's chat status
*/
this.sendCSI = function (stat) {
_converse.api.send($build(stat, {xmlns: Strophe.NS.CSI}));
_converse.inactive = (stat === _converse.INACTIVE) ? true : false;
};
this.onUserActivity = function () {
/* Resets counters and flags relating to CSI and auto_away/auto_xa */
if (_converse.idle_seconds > 0) {
_converse.idle_seconds = 0;
}
if (!_converse.connection.authenticated) {
// We can't send out any stanzas when there's no authenticated connection.
// This can happen when the connection reconnects.
return;
}
if (_converse.inactive) {
_converse.sendCSI(_converse.ACTIVE);
}
if (_converse.idle) {
_converse.idle = false;
_converse.xmppstatus.sendPresence();
}
if (_converse.auto_changed_status === true) {
_converse.auto_changed_status = false;
// XXX: we should really remember the original state here, and
// then set it back to that...
_converse.xmppstatus.set('status', _converse.default_state);
}
};
this.onEverySecond = function () {
/* An interval handler running every second.
* Used for CSI and the auto_away and auto_xa features.
*/
if (!_converse.connection.authenticated) {
// We can't send out any stanzas when there's no authenticated connection.
// This can happen when the connection reconnects.
return;
}
const stat = _converse.xmppstatus.get('status');
_converse.idle_seconds++;
if (_converse.csi_waiting_time > 0 &&
_converse.idle_seconds > _converse.csi_waiting_time &&
!_converse.inactive) {
_converse.sendCSI(_converse.INACTIVE);
}
if (_converse.idle_presence_timeout > 0 &&
_converse.idle_seconds > _converse.idle_presence_timeout &&
!_converse.idle) {
_converse.idle = true;
_converse.xmppstatus.sendPresence();
}
if (_converse.auto_away > 0 &&
_converse.idle_seconds > _converse.auto_away &&
stat !== 'away' && stat !== 'xa' && stat !== 'dnd') {
_converse.auto_changed_status = true;
_converse.xmppstatus.set('status', 'away');
} else if (_converse.auto_xa > 0 &&
_converse.idle_seconds > _converse.auto_xa &&
stat !== 'xa' && stat !== 'dnd') {
_converse.auto_changed_status = true;
_converse.xmppstatus.set('status', 'xa');
}
};
this.registerIntervalHandler = function () {
/* Set an interval of one second and register a handler for it.
* Required for the auto_away, auto_xa and csi_waiting_time features.
*/
if (_converse.auto_away < 1 && _converse.auto_xa < 1 && _converse.csi_waiting_time < 1 && _converse.idle_presence_timeout < 1) {
// Waiting time of less then one second means features aren't used.
return;
}
_converse.idle_seconds = 0
_converse.auto_changed_status = false; // Was the user's status changed by Converse?
window.addEventListener('click', _converse.onUserActivity);
window.addEventListener('focus', _converse.onUserActivity);
window.addEventListener('keypress', _converse.onUserActivity);
window.addEventListener('mousemove', _converse.onUserActivity);
const options = {'once': true, 'passive': true};
window.addEventListener(_converse.unloadevent, _converse.onUserActivity, options);
_converse.everySecondTrigger = window.setInterval(_converse.onEverySecond, 1000);
};
this.setConnectionStatus = function (connection_status, message) {
_converse.connfeedback.set({
'connection_status': connection_status,
'message': message
});
};
/**
* Reject or cancel another user's subscription to our presence updates.
* @method rejectPresenceSubscription
* @private
* @memberOf _converse
* @param { String } jid - The Jabber ID of the user whose subscription is being canceled
* @param { String } message - An optional message to the user
*/
this.rejectPresenceSubscription = function (jid, message) {
const pres = $pres({to: jid, type: "unsubscribed"});
if (message && message !== "") { pres.c("status").t(message); }
_converse.api.send(pres);
};
/**
* Properly tear down the session so that it's possible to manually connect again.
* @method finishDisconnection
* @private
* @memberOf _converse
*/
this.finishDisconnection = function () {
_converse.log('DISCONNECTED');
delete _converse.connection.reconnecting;
_converse.connection.reset();
tearDown();
clearSession();
/**
* Triggered after converse.js has disconnected from the XMPP server.
* @event _converse#disconnected
* @memberOf _converse
* @example _converse.api.listen.on('disconnected', () => { ... });
*/
_converse.api.trigger('disconnected');
};
/**
* Gets called once strophe's status reaches Strophe.Status.DISCONNECTED.
* Will either start a teardown process for converse.js or attempt
* to reconnect.
* @method onDisconnected
* @private
* @memberOf _converse
*/
this.onDisconnected = function () {
const reason = _converse.disconnection_reason;
if (_converse.disconnection_cause === Strophe.Status.AUTHFAIL) {
if (_converse.credentials_url && _converse.auto_reconnect) {
/* In this case, we reconnect, because we might be receiving
* expirable tokens from the credentials_url.
*/
return _converse.api.connection.reconnect();
} else {
return _converse.finishDisconnection();
}
} else if (_converse.disconnection_cause === _converse.LOGOUT ||
(!_.isUndefined(reason) && reason === _.get(Strophe, 'ErrorCondition.NO_AUTH_MECH')) ||
reason === "host-unknown" ||
reason === "remote-connection-failed" ||
!_converse.auto_reconnect) {
return _converse.finishDisconnection();
}
_converse.api.connection.reconnect();
};
this.setDisconnectionCause = function (cause, reason, override) {
/* Used to keep track of why we got disconnected, so that we can
* decide on what the next appropriate action is (in onDisconnected)
*/
if (_.isUndefined(cause)) {
delete _converse.disconnection_cause;
delete _converse.disconnection_reason;
} else if (_.isUndefined(_converse.disconnection_cause) || override) {
_converse.disconnection_cause = cause;
_converse.disconnection_reason = reason;
}
};
this.onConnectStatusChanged = function (status, message) {
/* Callback method called by Strophe as the Strophe.Connection goes
* through various states while establishing or tearing down a
* connection.
*/
_converse.log(`Status changed to: ${_converse.CONNECTION_STATUS[status]}`);
if (status === Strophe.Status.CONNECTED || status === Strophe.Status.ATTACHED) {
_converse.setConnectionStatus(status);
// By default we always want to send out an initial presence stanza.
_converse.send_initial_presence = true;
_converse.setDisconnectionCause();
if (_converse.connection.reconnecting) {
_converse.log(status === Strophe.Status.CONNECTED ? 'Reconnected' : 'Reattached');
onConnected(true);
} else {
_converse.log(status === Strophe.Status.CONNECTED ? 'Connected' : 'Attached');
if (_converse.connection.restored) {
// No need to send an initial presence stanza when
// we're restoring an existing session.
_converse.send_initial_presence = false;
}
onConnected();
}
} else if (status === Strophe.Status.DISCONNECTED) {
_converse.setDisconnectionCause(status, message);
_converse.onDisconnected();
} else if (status === Strophe.Status.BINDREQUIRED) {
_converse.bindResource();
} else if (status === Strophe.Status.ERROR) {
_converse.setConnectionStatus(
status,
__('An error occurred while connecting to the chat server.')
);
} else if (status === Strophe.Status.CONNECTING) {
_converse.setConnectionStatus(status);
} else if (status === Strophe.Status.AUTHENTICATING) {
_converse.setConnectionStatus(status);
} else if (status === Strophe.Status.AUTHFAIL) {
if (!message) {
message = __('Your Jabber ID and/or password is incorrect. Please try again.');
}
_converse.setConnectionStatus(status, message);
_converse.setDisconnectionCause(status, message, true);
_converse.onDisconnected();
} else if (status === Strophe.Status.CONNFAIL) {
let feedback = message;
if (message === "host-unknown" || message == "remote-connection-failed") {
feedback = __("Sorry, we could not connect to the XMPP host with domain: %1$s",
`\"${Strophe.getDomainFromJid(_converse.connection.jid)}\"`);
} else if (!_.isUndefined(message) && message === _.get(Strophe, 'ErrorCondition.NO_AUTH_MECH')) {
feedback = __("The XMPP server did not offer a supported authentication mechanism");
}
_converse.setConnectionStatus(status, feedback);
_converse.setDisconnectionCause(status, message);
} else if (status === Strophe.Status.DISCONNECTING) {
_converse.setDisconnectionCause(status, message);
}
};
this.incrementMsgCounter = function () {
this.msg_counter += 1;
const unreadMsgCount = this.msg_counter;
let title = document.title;
if (_.isNil(title)) {
return;
}
if (title.search(/^Messages \(\d+\) /) === -1) {
title = `Messages (${unreadMsgCount}) ${title}`;
} else {
title = title.replace(/^Messages \(\d+\) /, `Messages (${unreadMsgCount})`);
}
};