您最多选择25个主题 主题必须以字母或数字开头,可以包含连字符 (-),并且长度不得超过35个字符

xmpp.js 30KB

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