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 30KB

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