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.

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