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

xmpp.js 30KB

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