Вы не можете выбрать более 25 тем Темы должны начинаться с буквы или цифры, могут содержать дефисы(-) и должны содержать не более 35 символов.

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