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

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