You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

xmpp.js 32KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844
  1. /* global $ */
  2. import { getLogger } from 'jitsi-meet-logger';
  3. import { $msg, Strophe } from 'strophe.js';
  4. import 'strophejs-plugin-disco';
  5. import * as JitsiConnectionErrors from '../../JitsiConnectionErrors';
  6. import * as JitsiConnectionEvents from '../../JitsiConnectionEvents';
  7. import XMPPEvents from '../../service/xmpp/XMPPEvents';
  8. import browser from '../browser';
  9. import { E2EEncryption } from '../e2ee/E2EEncryption';
  10. import GlobalOnErrorHandler from '../util/GlobalOnErrorHandler';
  11. import Listenable from '../util/Listenable';
  12. import RandomUtil from '../util/RandomUtil';
  13. import Caps from './Caps';
  14. import XmppConnection from './XmppConnection';
  15. import MucConnectionPlugin from './strophe.emuc';
  16. import JingleConnectionPlugin from './strophe.jingle';
  17. import initStropheLogger from './strophe.logger';
  18. import RayoConnectionPlugin from './strophe.rayo';
  19. import initStropheUtil from './strophe.util';
  20. const logger = getLogger(__filename);
  21. /**
  22. * Creates XMPP connection.
  23. *
  24. * @param {Object} options
  25. * @param {string} [options.token] - JWT token used for authentication(JWT authentication module must be enabled in
  26. * Prosody).
  27. * @param {string} options.serviceUrl - The service URL for XMPP connection.
  28. * @param {string} options.shard - The shard where XMPP connection initially landed.
  29. * @param {string} options.enableWebsocketResume - True to enable stream resumption.
  30. * @param {number} [options.websocketKeepAlive] - See {@link XmppConnection} constructor.
  31. * @param {number} [options.websocketKeepAliveUrl] - See {@link XmppConnection} constructor.
  32. * @param {Object} [options.xmppPing] - See {@link XmppConnection} constructor.
  33. * @returns {XmppConnection}
  34. */
  35. function createConnection({
  36. enableWebsocketResume,
  37. serviceUrl = '/http-bind',
  38. shard,
  39. token,
  40. websocketKeepAlive,
  41. websocketKeepAliveUrl,
  42. xmppPing }) {
  43. // Append token as URL param
  44. if (token) {
  45. // eslint-disable-next-line no-param-reassign
  46. serviceUrl += `${serviceUrl.indexOf('?') === -1 ? '?' : '&'}token=${token}`;
  47. }
  48. return new XmppConnection({
  49. enableWebsocketResume,
  50. serviceUrl,
  51. websocketKeepAlive,
  52. websocketKeepAliveUrl,
  53. xmppPing,
  54. shard
  55. });
  56. }
  57. /**
  58. * Initializes Strophe plugins that need to work with Strophe.Connection directly rather than the lib-jitsi-meet's
  59. * {@link XmppConnection} wrapper.
  60. *
  61. * @returns {void}
  62. */
  63. function initStropheNativePlugins() {
  64. initStropheUtil();
  65. initStropheLogger();
  66. }
  67. // FIXME: remove once we have a default config template. -saghul
  68. /**
  69. * A list of ice servers to use by default for P2P.
  70. */
  71. export const DEFAULT_STUN_SERVERS = [
  72. { urls: 'stun:meet-jit-si-turnrelay.jitsi.net:443' }
  73. ];
  74. /**
  75. * The name of the field used to recognize a chat message as carrying a JSON
  76. * payload from another endpoint.
  77. * If the json-message of a chat message contains a valid JSON object, and
  78. * the JSON has this key, then it is a valid json-message to be sent.
  79. */
  80. export const JITSI_MEET_MUC_TYPE = 'type';
  81. /**
  82. * The feature used by jigasi participants.
  83. * @type {string}
  84. */
  85. export const FEATURE_JIGASI = 'http://jitsi.org/protocol/jigasi';
  86. /**
  87. * The feature used by the lib to mark support for e2ee. We use the feature by putting it in the presence
  88. * to avoid additional signaling (disco-info).
  89. * @type {string}
  90. */
  91. export const FEATURE_E2EE = 'https://jitsi.org/meet/e2ee';
  92. /**
  93. *
  94. */
  95. export default class XMPP extends Listenable {
  96. /**
  97. * FIXME describe all options
  98. * @param {Object} options
  99. * @param {String} options.serviceUrl - URL passed to the XMPP client which will be used to establish XMPP
  100. * connection with the server.
  101. * @param {String} options.bosh - Deprecated, use {@code serviceUrl}.
  102. * @param {boolean} options.enableWebsocketResume - Enables XEP-0198 stream management which will make the XMPP
  103. * module try to resume the session in case the Websocket connection breaks.
  104. * @param {number} [options.websocketKeepAlive] - The websocket keep alive interval. See {@link XmppConnection}
  105. * constructor for more details.
  106. * @param {number} [options.websocketKeepAliveUrl] - The websocket keep alive url. See {@link XmppConnection}
  107. * constructor for more details.
  108. * @param {Object} [options.xmppPing] - The xmpp ping settings.
  109. * @param {Array<Object>} options.p2pStunServers see {@link JingleConnectionPlugin} for more details.
  110. * @param token
  111. */
  112. constructor(options, token) {
  113. super();
  114. this.connection = null;
  115. this.disconnectInProgress = false;
  116. this.connectionTimes = {};
  117. this.options = options;
  118. this.token = token;
  119. this.authenticatedUser = false;
  120. initStropheNativePlugins();
  121. const xmppPing = options.xmppPing || {};
  122. // let's ping the main domain (in case a guest one is used for the connection)
  123. xmppPing.domain = options.hosts.domain;
  124. this.connection = createConnection({
  125. enableWebsocketResume: options.enableWebsocketResume,
  126. // FIXME remove deprecated bosh option at some point
  127. serviceUrl: options.serviceUrl || options.bosh,
  128. token,
  129. websocketKeepAlive: options.websocketKeepAlive,
  130. websocketKeepAliveUrl: options.websocketKeepAliveUrl,
  131. xmppPing,
  132. shard: options.deploymentInfo?.shard
  133. });
  134. // forwards the shard changed event
  135. this.connection.on(XmppConnection.Events.CONN_SHARD_CHANGED, () => {
  136. /* eslint-disable camelcase */
  137. const details = {
  138. shard_changed: true,
  139. suspend_time: this.connection.ping.getPingSuspendTime(),
  140. time_since_last_success: this.connection.getTimeSinceLastSuccess()
  141. };
  142. /* eslint-enable camelcase */
  143. this.eventEmitter.emit(
  144. JitsiConnectionEvents.CONNECTION_FAILED,
  145. JitsiConnectionErrors.OTHER_ERROR,
  146. undefined,
  147. undefined,
  148. details);
  149. });
  150. this._initStrophePlugins();
  151. this.caps = new Caps(this.connection, this.options.clientNode);
  152. // Initialize features advertised in disco-info
  153. this.initFeaturesList();
  154. // Setup a disconnect on unload as a way to facilitate API consumers. It
  155. // sounds like they would want that. A problem for them though may be if
  156. // they wanted to utilize the connected connection in an unload handler
  157. // of their own. However, it should be fairly easy for them to do that
  158. // by registering their unload handler before us.
  159. $(window).on('beforeunload unload', ev => {
  160. this.disconnect(ev).catch(() => {
  161. // ignore errors in order to not brake the unload.
  162. });
  163. });
  164. }
  165. /**
  166. * Initializes the list of feature advertised through the disco-info
  167. * mechanism.
  168. */
  169. initFeaturesList() {
  170. // http://xmpp.org/extensions/xep-0167.html#support
  171. // http://xmpp.org/extensions/xep-0176.html#support
  172. this.caps.addFeature('urn:xmpp:jingle:1');
  173. this.caps.addFeature('urn:xmpp:jingle:apps:rtp:1');
  174. this.caps.addFeature('urn:xmpp:jingle:transports:ice-udp:1');
  175. this.caps.addFeature('urn:xmpp:jingle:apps:dtls:0');
  176. this.caps.addFeature('urn:xmpp:jingle:transports:dtls-sctp:1');
  177. this.caps.addFeature('urn:xmpp:jingle:apps:rtp:audio');
  178. this.caps.addFeature('urn:xmpp:jingle:apps:rtp:video');
  179. // Disable RTX on Firefox 83 and older versions because of
  180. // https://bugzilla.mozilla.org/show_bug.cgi?id=1668028
  181. if (!(this.options.disableRtx || (browser.isFirefox() && browser.isVersionLessThan(84)))) {
  182. this.caps.addFeature('urn:ietf:rfc:4588');
  183. }
  184. if (this.options.enableOpusRed === true && browser.supportsAudioRed()) {
  185. this.caps.addFeature('http://jitsi.org/opus-red');
  186. }
  187. if (typeof this.options.enableRemb === 'undefined' || this.options.enableRemb) {
  188. this.caps.addFeature('http://jitsi.org/remb');
  189. }
  190. if (typeof this.options.enableTcc === 'undefined' || this.options.enableTcc) {
  191. this.caps.addFeature('http://jitsi.org/tcc');
  192. }
  193. // this is dealt with by SDP O/A so we don't need to announce this
  194. // XEP-0293
  195. // this.caps.addFeature('urn:xmpp:jingle:apps:rtp:rtcp-fb:0');
  196. // XEP-0294
  197. // this.caps.addFeature('urn:xmpp:jingle:apps:rtp:rtp-hdrext:0');
  198. this.caps.addFeature('urn:ietf:rfc:5761'); // rtcp-mux
  199. this.caps.addFeature('urn:ietf:rfc:5888'); // a=group, e.g. bundle
  200. // this.caps.addFeature('urn:ietf:rfc:5576'); // a=ssrc
  201. // Enable Lipsync ?
  202. if (browser.isChromiumBased() && this.options.enableLipSync === true) {
  203. logger.info('Lip-sync enabled !');
  204. this.caps.addFeature('http://jitsi.org/meet/lipsync');
  205. }
  206. if (this.connection.rayo) {
  207. this.caps.addFeature('urn:xmpp:rayo:client:1');
  208. }
  209. if (E2EEncryption.isSupported(this.options)) {
  210. this.caps.addFeature(FEATURE_E2EE, false, true);
  211. }
  212. }
  213. /**
  214. *
  215. */
  216. getConnection() {
  217. return this.connection;
  218. }
  219. /**
  220. * Receive connection status changes and handles them.
  221. *
  222. * @param {Object} credentials
  223. * @param {string} credentials.jid - The user's XMPP ID passed to the
  224. * connect method. For example, 'user@xmpp.com'.
  225. * @param {string} credentials.password - The password passed to the connect
  226. * method.
  227. * @param {string} status - One of Strophe's connection status strings.
  228. * @param {string} [msg] - The connection error message provided by Strophe.
  229. */
  230. connectionHandler(credentials = {}, status, msg) {
  231. const now = window.performance.now();
  232. const statusStr = Strophe.getStatusString(status).toLowerCase();
  233. this.connectionTimes[statusStr] = now;
  234. logger.log(
  235. `(TIME) Strophe ${statusStr}${msg ? `[${msg}]` : ''}:\t`,
  236. now);
  237. this.eventEmitter.emit(XMPPEvents.CONNECTION_STATUS_CHANGED, credentials, status, msg);
  238. if (status === Strophe.Status.CONNECTED || status === Strophe.Status.ATTACHED) {
  239. this.connection.jingle.getStunAndTurnCredentials();
  240. logger.info(`My Jabber ID: ${this.connection.jid}`);
  241. // XmppConnection emits CONNECTED again on reconnect - a good opportunity to clear any "last error" flags
  242. this._resetState();
  243. // FIXME no need to do it again on stream resume
  244. this.caps.getFeaturesAndIdentities(this.options.hosts.domain)
  245. .then(({ features, identities }) => {
  246. if (!features.has(Strophe.NS.PING)) {
  247. logger.error(`Ping NOT supported by ${
  248. this.options.hosts.domain} - please enable ping in your XMPP server config`);
  249. }
  250. // check for speakerstats
  251. identities.forEach(identity => {
  252. if (identity.type === 'speakerstats') {
  253. this.speakerStatsComponentAddress = identity.name;
  254. }
  255. if (identity.type === 'conference_duration') {
  256. this.conferenceDurationComponentAddress = identity.name;
  257. }
  258. if (identity.type === 'lobbyrooms') {
  259. this.lobbySupported = true;
  260. identity.name && this.caps.getFeaturesAndIdentities(identity.name, identity.type)
  261. .then(({ features: f }) => {
  262. f.forEach(fr => {
  263. if (fr.endsWith('#displayname_required')) {
  264. this.eventEmitter.emit(
  265. JitsiConnectionEvents.DISPLAY_NAME_REQUIRED);
  266. }
  267. });
  268. })
  269. .catch(e => logger.warn('Error getting features from lobby.', e && e.message));
  270. }
  271. });
  272. if (this.speakerStatsComponentAddress
  273. || this.conferenceDurationComponentAddress) {
  274. this.connection.addHandler(
  275. this._onPrivateMessage.bind(this), null,
  276. 'message', null, null);
  277. }
  278. })
  279. .catch(error => {
  280. const errmsg = 'Feature discovery error';
  281. GlobalOnErrorHandler.callErrorHandler(
  282. new Error(`${errmsg}: ${error}`));
  283. logger.error(errmsg, error);
  284. });
  285. if (credentials.password) {
  286. this.authenticatedUser = true;
  287. }
  288. if (this.connection && this.connection.connected
  289. && Strophe.getResourceFromJid(this.connection.jid)) {
  290. // .connected is true while connecting?
  291. // this.connection.send($pres());
  292. this.eventEmitter.emit(
  293. JitsiConnectionEvents.CONNECTION_ESTABLISHED,
  294. Strophe.getResourceFromJid(this.connection.jid));
  295. }
  296. } else if (status === Strophe.Status.CONNFAIL) {
  297. if (msg === 'x-strophe-bad-non-anon-jid') {
  298. this.anonymousConnectionFailed = true;
  299. } else {
  300. this.connectionFailed = true;
  301. }
  302. this.lastErrorMsg = msg;
  303. if (msg === 'giving-up') {
  304. this.eventEmitter.emit(
  305. JitsiConnectionEvents.CONNECTION_FAILED,
  306. JitsiConnectionErrors.OTHER_ERROR, msg);
  307. }
  308. } else if (status === Strophe.Status.ERROR) {
  309. this.lastErrorMsg = msg;
  310. } else if (status === Strophe.Status.DISCONNECTED) {
  311. // Stop ping interval
  312. this.connection.ping.stopInterval();
  313. const wasIntentionalDisconnect = Boolean(this.disconnectInProgress);
  314. const errMsg = msg || this.lastErrorMsg;
  315. if (this.anonymousConnectionFailed) {
  316. // prompt user for username and password
  317. this.eventEmitter.emit(
  318. JitsiConnectionEvents.CONNECTION_FAILED,
  319. JitsiConnectionErrors.PASSWORD_REQUIRED);
  320. } else if (this.connectionFailed) {
  321. this.eventEmitter.emit(
  322. JitsiConnectionEvents.CONNECTION_FAILED,
  323. JitsiConnectionErrors.OTHER_ERROR,
  324. errMsg,
  325. undefined, /* credentials */
  326. this._getConnectionFailedReasonDetails());
  327. } else if (wasIntentionalDisconnect) {
  328. this.eventEmitter.emit(
  329. JitsiConnectionEvents.CONNECTION_DISCONNECTED, errMsg);
  330. } else {
  331. // XXX if Strophe drops the connection while not being asked to,
  332. // it means that most likely some serious error has occurred.
  333. // One currently known case is when a BOSH request fails for
  334. // more than 4 times. The connection is dropped without
  335. // supplying a reason(error message/event) through the API.
  336. logger.error('XMPP connection dropped!');
  337. // XXX if the last request error is within 5xx range it means it
  338. // was a server failure
  339. const lastErrorStatus = Strophe.getLastErrorStatus();
  340. if (lastErrorStatus >= 500 && lastErrorStatus < 600) {
  341. this.eventEmitter.emit(
  342. JitsiConnectionEvents.CONNECTION_FAILED,
  343. JitsiConnectionErrors.SERVER_ERROR,
  344. errMsg || 'server-error',
  345. /* credentials */ undefined,
  346. this._getConnectionFailedReasonDetails());
  347. } else {
  348. this.eventEmitter.emit(
  349. JitsiConnectionEvents.CONNECTION_FAILED,
  350. JitsiConnectionErrors.CONNECTION_DROPPED_ERROR,
  351. errMsg || 'connection-dropped-error',
  352. /* credentials */ undefined,
  353. this._getConnectionFailedReasonDetails());
  354. }
  355. }
  356. } else if (status === Strophe.Status.AUTHFAIL) {
  357. // wrong password or username, prompt user
  358. this.eventEmitter.emit(
  359. JitsiConnectionEvents.CONNECTION_FAILED,
  360. JitsiConnectionErrors.PASSWORD_REQUIRED,
  361. msg,
  362. credentials);
  363. }
  364. }
  365. /**
  366. *
  367. * @param jid
  368. * @param password
  369. */
  370. _connect(jid, password) {
  371. // connection.connect() starts the connection process.
  372. //
  373. // As the connection process proceeds, the user supplied callback will
  374. // be triggered multiple times with status updates. The callback should
  375. // take two arguments - the status code and the error condition.
  376. //
  377. // The status code will be one of the values in the Strophe.Status
  378. // constants. The error condition will be one of the conditions defined
  379. // in RFC 3920 or the condition ‘strophe-parsererror’.
  380. //
  381. // The Parameters wait, hold and route are optional and only relevant
  382. // for BOSH connections. Please see XEP 124 for a more detailed
  383. // explanation of the optional parameters.
  384. //
  385. // Connection status constants for use by the connection handler
  386. // callback.
  387. //
  388. // Status.ERROR - An error has occurred (websockets specific)
  389. // Status.CONNECTING - The connection is currently being made
  390. // Status.CONNFAIL - The connection attempt failed
  391. // Status.AUTHENTICATING - The connection is authenticating
  392. // Status.AUTHFAIL - The authentication attempt failed
  393. // Status.CONNECTED - The connection has succeeded
  394. // Status.DISCONNECTED - The connection has been terminated
  395. // Status.DISCONNECTING - The connection is currently being terminated
  396. // Status.ATTACHED - The connection has been attached
  397. this._resetState();
  398. this.connection.connect(
  399. jid,
  400. password,
  401. this.connectionHandler.bind(this, {
  402. jid,
  403. password
  404. }));
  405. }
  406. /**
  407. * Attach to existing connection. Can be used for optimizations. For
  408. * example: if the connection is created on the server we can attach to it
  409. * and start using it.
  410. *
  411. * @param options {object} connecting options - rid, sid, jid and password.
  412. */
  413. attach(options) {
  414. this._resetState();
  415. const now = this.connectionTimes.attaching = window.performance.now();
  416. logger.log('(TIME) Strophe Attaching:\t', now);
  417. this.connection.attach(options.jid, options.sid,
  418. parseInt(options.rid, 10) + 1,
  419. this.connectionHandler.bind(this, {
  420. jid: options.jid,
  421. password: options.password
  422. }));
  423. }
  424. /**
  425. * Resets any state/flag before starting a new connection.
  426. * @private
  427. */
  428. _resetState() {
  429. this.anonymousConnectionFailed = false;
  430. this.connectionFailed = false;
  431. this.lastErrorMsg = undefined;
  432. this.disconnectInProgress = undefined;
  433. }
  434. /**
  435. *
  436. * @param jid
  437. * @param password
  438. */
  439. connect(jid, password) {
  440. if (!jid) {
  441. const { anonymousdomain, domain } = this.options.hosts;
  442. let configDomain = anonymousdomain || domain;
  443. // Force authenticated domain if room is appended with '?login=true'
  444. // or if we're joining with the token
  445. // FIXME Do not rely on window.location because (1) React Native
  446. // does not have a window.location by default and (2) here we cannot
  447. // know for sure that query/search has not be stripped from
  448. // window.location by the time the following executes.
  449. const { location } = window;
  450. if (anonymousdomain) {
  451. const search = location && location.search;
  452. if ((search && search.indexOf('login=true') !== -1)
  453. || this.token) {
  454. configDomain = domain;
  455. }
  456. }
  457. // eslint-disable-next-line no-param-reassign
  458. jid = configDomain || (location && location.hostname);
  459. }
  460. return this._connect(jid, password);
  461. }
  462. /**
  463. * Joins or creates a muc with the provided jid, created from the passed
  464. * in room name and muc host and onCreateResource result.
  465. *
  466. * @param {string} roomName - The name of the muc to join.
  467. * @param {Object} options - Configuration for how to join the muc.
  468. * @param {Function} [onCreateResource] - Callback to invoke when a resource
  469. * is to be added to the jid.
  470. * @returns {Promise} Resolves with an instance of a strophe muc.
  471. */
  472. createRoom(roomName, options, onCreateResource) {
  473. // There are cases (when using subdomain) where muc can hold an uppercase part
  474. let roomjid = `${roomName}@${options.customDomain
  475. ? options.customDomain : this.options.hosts.muc.toLowerCase()}/`;
  476. const mucNickname = onCreateResource
  477. ? onCreateResource(this.connection.jid, this.authenticatedUser)
  478. : RandomUtil.randomHexString(8).toLowerCase();
  479. logger.info(`JID ${this.connection.jid} using MUC nickname ${mucNickname}`);
  480. roomjid += mucNickname;
  481. return this.connection.emuc.createRoom(roomjid, null, options);
  482. }
  483. /**
  484. * Returns the jid of the participant associated with the Strophe connection.
  485. *
  486. * @returns {string} The jid of the participant.
  487. */
  488. getJid() {
  489. return this.connection.jid;
  490. }
  491. /**
  492. * Returns the logs from strophe.jingle.
  493. * @returns {Object}
  494. */
  495. getJingleLog() {
  496. const jingle = this.connection.jingle;
  497. return jingle ? jingle.getLog() : {};
  498. }
  499. /**
  500. * Returns the logs from strophe.
  501. */
  502. getXmppLog() {
  503. return (this.connection.logger || {}).log || null;
  504. }
  505. /**
  506. *
  507. */
  508. dial(...args) {
  509. this.connection.rayo.dial(...args);
  510. }
  511. /**
  512. * Pings the server.
  513. * @param timeout how many ms before a timeout should occur.
  514. * @returns {Promise} resolved on ping success and reject on an error or
  515. * a timeout.
  516. */
  517. ping(timeout) {
  518. return new Promise((resolve, reject) => {
  519. this.connection.ping.ping(this.connection.pingDomain, resolve, reject, timeout);
  520. });
  521. }
  522. /**
  523. *
  524. */
  525. getSessions() {
  526. return this.connection.jingle.sessions;
  527. }
  528. /**
  529. * Disconnects this from the XMPP server (if this is connected).
  530. *
  531. * @param {Object} ev - Optionally, the event which triggered the necessity to
  532. * disconnect from the XMPP server (e.g. beforeunload, unload).
  533. * @returns {Promise} - Resolves when the disconnect process is finished or rejects with an error.
  534. */
  535. disconnect(ev) {
  536. if (this.disconnectInProgress) {
  537. return this.disconnectInProgress;
  538. } else if (!this.connection) {
  539. return Promise.resolve();
  540. }
  541. this.disconnectInProgress = new Promise(resolve => {
  542. const disconnectListener = (credentials, status) => {
  543. if (status === Strophe.Status.DISCONNECTED) {
  544. resolve();
  545. this.eventEmitter.removeListener(XMPPEvents.CONNECTION_STATUS_CHANGED, disconnectListener);
  546. }
  547. };
  548. this.eventEmitter.on(XMPPEvents.CONNECTION_STATUS_CHANGED, disconnectListener);
  549. });
  550. this._cleanupXmppConnection(ev);
  551. return this.disconnectInProgress;
  552. }
  553. /**
  554. * The method is supposed to gracefully close the XMPP connection and the main goal is to make sure that the current
  555. * participant will be removed from the conference XMPP MUC, so that it doesn't leave a "ghost" participant behind.
  556. *
  557. * @param {Object} ev - Optionally, the event which triggered the necessity to disconnect from the XMPP server
  558. * (e.g. beforeunload, unload).
  559. * @private
  560. * @returns {void}
  561. */
  562. _cleanupXmppConnection(ev) {
  563. // XXX Strophe is asynchronously sending by default. Unfortunately, that means that there may not be enough time
  564. // to send an unavailable presence or disconnect at all. Switching Strophe to synchronous sending is not much of
  565. // an option because it may lead to a noticeable delay in navigating away from the current location. As
  566. // a compromise, we will try to increase the chances of sending an unavailable presence and/or disconnecting
  567. // within the short time span that we have upon unloading by invoking flush() on the connection. We flush() once
  568. // before disconnect() in order to attempt to have its unavailable presence at the top of the send queue. We
  569. // flush() once more after disconnect() in order to attempt to have its unavailable presence sent as soon as
  570. // possible.
  571. !this.connection.isUsingWebSocket && this.connection.flush();
  572. if (!this.connection.isUsingWebSocket && ev !== null && typeof ev !== 'undefined') {
  573. const evType = ev.type;
  574. if (evType === 'beforeunload' || evType === 'unload') {
  575. // XXX Whatever we said above, synchronous sending is the best (known) way to properly disconnect from
  576. // the XMPP server. Consequently, it may be fine to have the source code and comment it in or out
  577. // depending on whether we want to run with it for some time.
  578. this.connection.options.sync = true;
  579. // This is needed in some browsers where sync xhr sending is disabled by default on unload.
  580. if (this.connection.sendUnavailableBeacon()) {
  581. return;
  582. }
  583. }
  584. }
  585. this.connection.disconnect();
  586. if (this.connection.options.sync !== true) {
  587. this.connection.flush();
  588. }
  589. }
  590. /**
  591. *
  592. */
  593. _initStrophePlugins() {
  594. const iceConfig = {
  595. jvb: { iceServers: [ ] },
  596. p2p: { iceServers: [ ] }
  597. };
  598. const p2pStunServers = (this.options.p2p
  599. && this.options.p2p.stunServers) || DEFAULT_STUN_SERVERS;
  600. if (Array.isArray(p2pStunServers)) {
  601. logger.info('P2P STUN servers: ', p2pStunServers);
  602. iceConfig.p2p.iceServers = p2pStunServers;
  603. }
  604. if (this.options.p2p && this.options.p2p.iceTransportPolicy) {
  605. logger.info('P2P ICE transport policy: ',
  606. this.options.p2p.iceTransportPolicy);
  607. iceConfig.p2p.iceTransportPolicy
  608. = this.options.p2p.iceTransportPolicy;
  609. }
  610. this.connection.addConnectionPlugin('emuc', new MucConnectionPlugin(this));
  611. this.connection.addConnectionPlugin('jingle', new JingleConnectionPlugin(this, this.eventEmitter, iceConfig));
  612. this.connection.addConnectionPlugin('rayo', new RayoConnectionPlugin());
  613. }
  614. /**
  615. * Returns details about connection failure. Shard change or is it after
  616. * suspend.
  617. * @returns {object} contains details about a connection failure.
  618. * @private
  619. */
  620. _getConnectionFailedReasonDetails() {
  621. const details = {};
  622. // check for moving between shard if information is available
  623. if (this.options.deploymentInfo
  624. && this.options.deploymentInfo.shard
  625. && this.connection.lastResponseHeaders) {
  626. // split headers by line
  627. const headersArr = this.connection.lastResponseHeaders
  628. .trim().split(/[\r\n]+/);
  629. const headers = {};
  630. headersArr.forEach(line => {
  631. const parts = line.split(': ');
  632. const header = parts.shift();
  633. const value = parts.join(': ');
  634. headers[header] = value;
  635. });
  636. /* eslint-disable camelcase */
  637. details.shard_changed
  638. = this.options.deploymentInfo.shard
  639. !== headers['x-jitsi-shard'];
  640. /* eslint-enable camelcase */
  641. }
  642. /* eslint-disable camelcase */
  643. // check for possible suspend
  644. details.suspend_time = this.connection.ping.getPingSuspendTime();
  645. details.time_since_last_success = this.connection.getTimeSinceLastSuccess();
  646. /* eslint-enable camelcase */
  647. return details;
  648. }
  649. /**
  650. * Notifies speaker stats component if available that we are the new
  651. * dominant speaker in the conference.
  652. * @param {String} roomJid - The room jid where the speaker event occurred.
  653. */
  654. sendDominantSpeakerEvent(roomJid) {
  655. // no speaker stats component advertised
  656. if (!this.speakerStatsComponentAddress || !roomJid) {
  657. return;
  658. }
  659. const msg = $msg({ to: this.speakerStatsComponentAddress });
  660. msg.c('speakerstats', {
  661. xmlns: 'http://jitsi.org/jitmeet',
  662. room: roomJid })
  663. .up();
  664. this.connection.send(msg);
  665. }
  666. /**
  667. * Check if the given argument is a valid JSON ENDPOINT_MESSAGE string by
  668. * parsing it and checking if it has a field called 'type'.
  669. *
  670. * @param {string} jsonString check if this string is a valid json string
  671. * and contains the special structure.
  672. * @returns {boolean, object} if given object is a valid JSON string, return
  673. * the json object. Otherwise, returns false.
  674. */
  675. tryParseJSONAndVerify(jsonString) {
  676. try {
  677. const json = JSON.parse(jsonString);
  678. // Handle non-exception-throwing cases:
  679. // Neither JSON.parse(false) or JSON.parse(1234) throw errors,
  680. // hence the type-checking,
  681. // but... JSON.parse(null) returns null, and
  682. // typeof null === "object",
  683. // so we must check for that, too.
  684. // Thankfully, null is falsey, so this suffices:
  685. if (json && typeof json === 'object') {
  686. const type = json[JITSI_MEET_MUC_TYPE];
  687. if (typeof type !== 'undefined') {
  688. return json;
  689. }
  690. logger.debug('parsing valid json but does not have correct '
  691. + 'structure', 'topic: ', type);
  692. }
  693. } catch (e) {
  694. logger.error(e);
  695. return false;
  696. }
  697. return false;
  698. }
  699. /**
  700. * A private message is received, message that is not addressed to the muc.
  701. * We expect private message coming from plugins component if it is
  702. * enabled and running.
  703. *
  704. * @param {string} msg - The message.
  705. */
  706. _onPrivateMessage(msg) {
  707. const from = msg.getAttribute('from');
  708. if (!(from === this.speakerStatsComponentAddress
  709. || from === this.conferenceDurationComponentAddress)) {
  710. return true;
  711. }
  712. const jsonMessage = $(msg).find('>json-message')
  713. .text();
  714. const parsedJson = this.tryParseJSONAndVerify(jsonMessage);
  715. if (parsedJson
  716. && parsedJson[JITSI_MEET_MUC_TYPE] === 'speakerstats'
  717. && parsedJson.users) {
  718. this.eventEmitter.emit(
  719. XMPPEvents.SPEAKER_STATS_RECEIVED, parsedJson.users);
  720. }
  721. if (parsedJson
  722. && parsedJson[JITSI_MEET_MUC_TYPE] === 'conference_duration'
  723. && parsedJson.created_timestamp) {
  724. this.eventEmitter.emit(
  725. XMPPEvents.CONFERENCE_TIMESTAMP_RECEIVED, parsedJson.created_timestamp);
  726. }
  727. return true;
  728. }
  729. }