modified lib-jitsi-meet dev repo
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

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