Du kannst nicht mehr als 25 Themen auswählen Themen müssen mit entweder einem Buchstaben oder einer Ziffer beginnen. Sie können Bindestriche („-“) enthalten und bis zu 35 Zeichen lang sein.

xmpp.js 29KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789
  1. /* global $ */
  2. import { getLogger } from 'jitsi-meet-logger';
  3. import { $msg, Strophe } from 'strophe.js';
  4. import 'strophejs-plugin-disco';
  5. import RandomUtil from '../util/RandomUtil';
  6. import * as JitsiConnectionErrors from '../../JitsiConnectionErrors';
  7. import * as JitsiConnectionEvents from '../../JitsiConnectionEvents';
  8. import browser from '../browser';
  9. import MucConnectionPlugin from './strophe.emuc';
  10. import JingleConnectionPlugin from './strophe.jingle';
  11. import initStropheUtil from './strophe.util';
  12. import PingConnectionPlugin from './strophe.ping';
  13. import RayoConnectionPlugin from './strophe.rayo';
  14. import initStropheLogger from './strophe.logger';
  15. import Listenable from '../util/Listenable';
  16. import Caps from './Caps';
  17. import GlobalOnErrorHandler from '../util/GlobalOnErrorHandler';
  18. import XMPPEvents from '../../service/xmpp/XMPPEvents';
  19. import XmppConnection from './XmppConnection';
  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. }
  219. });
  220. if (this.speakerStatsComponentAddress
  221. || this.conferenceDurationComponentAddress) {
  222. this.connection.addHandler(
  223. this._onPrivateMessage.bind(this), null,
  224. 'message', null, null);
  225. }
  226. })
  227. .catch(error => {
  228. const errmsg = 'Feature discovery error';
  229. GlobalOnErrorHandler.callErrorHandler(
  230. new Error(`${errmsg}: ${error}`));
  231. logger.error(errmsg, error);
  232. });
  233. if (credentials.password) {
  234. this.authenticatedUser = true;
  235. }
  236. if (this.connection && this.connection.connected
  237. && Strophe.getResourceFromJid(this.connection.jid)) {
  238. // .connected is true while connecting?
  239. // this.connection.send($pres());
  240. this.eventEmitter.emit(
  241. JitsiConnectionEvents.CONNECTION_ESTABLISHED,
  242. Strophe.getResourceFromJid(this.connection.jid));
  243. }
  244. } else if (status === Strophe.Status.CONNFAIL) {
  245. if (msg === 'x-strophe-bad-non-anon-jid') {
  246. this.anonymousConnectionFailed = true;
  247. } else {
  248. this.connectionFailed = true;
  249. }
  250. this.lastErrorMsg = msg;
  251. if (msg === 'giving-up') {
  252. this.eventEmitter.emit(
  253. JitsiConnectionEvents.CONNECTION_FAILED,
  254. JitsiConnectionErrors.OTHER_ERROR, msg);
  255. }
  256. } else if (status === Strophe.Status.ERROR) {
  257. this.lastErrorMsg = msg;
  258. } else if (status === Strophe.Status.DISCONNECTED) {
  259. // Stop ping interval
  260. this.connection.ping.stopInterval();
  261. const wasIntentionalDisconnect = Boolean(this.disconnectInProgress);
  262. const errMsg = msg || this.lastErrorMsg;
  263. if (this.anonymousConnectionFailed) {
  264. // prompt user for username and password
  265. this.eventEmitter.emit(
  266. JitsiConnectionEvents.CONNECTION_FAILED,
  267. JitsiConnectionErrors.PASSWORD_REQUIRED);
  268. } else if (this.connectionFailed) {
  269. this.eventEmitter.emit(
  270. JitsiConnectionEvents.CONNECTION_FAILED,
  271. JitsiConnectionErrors.OTHER_ERROR,
  272. errMsg,
  273. undefined, /* credentials */
  274. this._getConnectionFailedReasonDetails());
  275. } else if (wasIntentionalDisconnect) {
  276. this.eventEmitter.emit(
  277. JitsiConnectionEvents.CONNECTION_DISCONNECTED, errMsg);
  278. } else {
  279. // XXX if Strophe drops the connection while not being asked to,
  280. // it means that most likely some serious error has occurred.
  281. // One currently known case is when a BOSH request fails for
  282. // more than 4 times. The connection is dropped without
  283. // supplying a reason(error message/event) through the API.
  284. logger.error('XMPP connection dropped!');
  285. // XXX if the last request error is within 5xx range it means it
  286. // was a server failure
  287. const lastErrorStatus = Strophe.getLastErrorStatus();
  288. if (lastErrorStatus >= 500 && lastErrorStatus < 600) {
  289. this.eventEmitter.emit(
  290. JitsiConnectionEvents.CONNECTION_FAILED,
  291. JitsiConnectionErrors.SERVER_ERROR,
  292. errMsg || 'server-error',
  293. /* credentials */ undefined,
  294. this._getConnectionFailedReasonDetails());
  295. } else {
  296. this.eventEmitter.emit(
  297. JitsiConnectionEvents.CONNECTION_FAILED,
  298. JitsiConnectionErrors.CONNECTION_DROPPED_ERROR,
  299. errMsg || 'connection-dropped-error',
  300. /* credentials */ undefined,
  301. this._getConnectionFailedReasonDetails());
  302. }
  303. }
  304. } else if (status === Strophe.Status.AUTHFAIL) {
  305. // wrong password or username, prompt user
  306. this.eventEmitter.emit(
  307. JitsiConnectionEvents.CONNECTION_FAILED,
  308. JitsiConnectionErrors.PASSWORD_REQUIRED,
  309. msg,
  310. credentials);
  311. }
  312. }
  313. /**
  314. *
  315. * @param jid
  316. * @param password
  317. */
  318. _connect(jid, password) {
  319. // connection.connect() starts the connection process.
  320. //
  321. // As the connection process proceeds, the user supplied callback will
  322. // be triggered multiple times with status updates. The callback should
  323. // take two arguments - the status code and the error condition.
  324. //
  325. // The status code will be one of the values in the Strophe.Status
  326. // constants. The error condition will be one of the conditions defined
  327. // in RFC 3920 or the condition ‘strophe-parsererror’.
  328. //
  329. // The Parameters wait, hold and route are optional and only relevant
  330. // for BOSH connections. Please see XEP 124 for a more detailed
  331. // explanation of the optional parameters.
  332. //
  333. // Connection status constants for use by the connection handler
  334. // callback.
  335. //
  336. // Status.ERROR - An error has occurred (websockets specific)
  337. // Status.CONNECTING - The connection is currently being made
  338. // Status.CONNFAIL - The connection attempt failed
  339. // Status.AUTHENTICATING - The connection is authenticating
  340. // Status.AUTHFAIL - The authentication attempt failed
  341. // Status.CONNECTED - The connection has succeeded
  342. // Status.DISCONNECTED - The connection has been terminated
  343. // Status.DISCONNECTING - The connection is currently being terminated
  344. // Status.ATTACHED - The connection has been attached
  345. this._resetState();
  346. this.connection.connect(
  347. jid,
  348. password,
  349. this.connectionHandler.bind(this, {
  350. jid,
  351. password
  352. }));
  353. }
  354. /**
  355. * Attach to existing connection. Can be used for optimizations. For
  356. * example: if the connection is created on the server we can attach to it
  357. * and start using it.
  358. *
  359. * @param options {object} connecting options - rid, sid, jid and password.
  360. */
  361. attach(options) {
  362. this._resetState();
  363. const now = this.connectionTimes.attaching = window.performance.now();
  364. logger.log('(TIME) Strophe Attaching:\t', now);
  365. this.connection.attach(options.jid, options.sid,
  366. parseInt(options.rid, 10) + 1,
  367. this.connectionHandler.bind(this, {
  368. jid: options.jid,
  369. password: options.password
  370. }));
  371. }
  372. /**
  373. * Resets any state/flag before starting a new connection.
  374. * @private
  375. */
  376. _resetState() {
  377. this.anonymousConnectionFailed = false;
  378. this.connectionFailed = false;
  379. this.lastErrorMsg = undefined;
  380. this.disconnectInProgress = undefined;
  381. }
  382. /**
  383. *
  384. * @param jid
  385. * @param password
  386. */
  387. connect(jid, password) {
  388. if (!jid) {
  389. const { anonymousdomain, domain } = this.options.hosts;
  390. let configDomain = anonymousdomain || domain;
  391. // Force authenticated domain if room is appended with '?login=true'
  392. // or if we're joining with the token
  393. // FIXME Do not rely on window.location because (1) React Native
  394. // does not have a window.location by default and (2) here we cannot
  395. // know for sure that query/search has not be stripped from
  396. // window.location by the time the following executes.
  397. const { location } = window;
  398. if (anonymousdomain) {
  399. const search = location && location.search;
  400. if ((search && search.indexOf('login=true') !== -1)
  401. || this.token) {
  402. configDomain = domain;
  403. }
  404. }
  405. // eslint-disable-next-line no-param-reassign
  406. jid = configDomain || (location && location.hostname);
  407. }
  408. return this._connect(jid, password);
  409. }
  410. /**
  411. * Joins or creates a muc with the provided jid, created from the passed
  412. * in room name and muc host and onCreateResource result.
  413. *
  414. * @param {string} roomName - The name of the muc to join.
  415. * @param {Object} options - Configuration for how to join the muc.
  416. * @param {Function} [onCreateResource] - Callback to invoke when a resource
  417. * is to be added to the jid.
  418. * @returns {Promise} Resolves with an instance of a strophe muc.
  419. */
  420. createRoom(roomName, options, onCreateResource) {
  421. let roomjid = `${roomName}@${options.customDomain
  422. ? options.customDomain : this.options.hosts.muc}/`;
  423. const mucNickname = onCreateResource
  424. ? onCreateResource(this.connection.jid, this.authenticatedUser)
  425. : RandomUtil.randomHexString(8).toLowerCase();
  426. logger.info(`JID ${this.connection.jid} using MUC nickname ${mucNickname}`);
  427. roomjid += mucNickname;
  428. return this.connection.emuc.createRoom(roomjid, null, options);
  429. }
  430. /**
  431. * Returns the jid of the participant associated with the Strophe connection.
  432. *
  433. * @returns {string} The jid of the participant.
  434. */
  435. getJid() {
  436. return this.connection.jid;
  437. }
  438. /**
  439. * Returns the logs from strophe.jingle.
  440. * @returns {Object}
  441. */
  442. getJingleLog() {
  443. const jingle = this.connection.jingle;
  444. return jingle ? jingle.getLog() : {};
  445. }
  446. /**
  447. * Returns the logs from strophe.
  448. */
  449. getXmppLog() {
  450. return (this.connection.logger || {}).log || null;
  451. }
  452. /**
  453. *
  454. */
  455. dial(...args) {
  456. this.connection.rayo.dial(...args);
  457. }
  458. /**
  459. * Pings the server. Remember to check {@link isPingSupported} before using
  460. * this method.
  461. * @param timeout how many ms before a timeout should occur.
  462. * @returns {Promise} resolved on ping success and reject on an error or
  463. * a timeout.
  464. */
  465. ping(timeout) {
  466. return new Promise((resolve, reject) => {
  467. if (this.isPingSupported()) {
  468. this.connection.ping
  469. .ping(this.connection.domain, resolve, reject, timeout);
  470. } else {
  471. reject('PING operation is not supported by the server');
  472. }
  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('ping', new PingConnectionPlugin(this));
  566. this.connection.addConnectionPlugin('rayo', new RayoConnectionPlugin());
  567. }
  568. /**
  569. * Returns details about connection failure. Shard change or is it after
  570. * suspend.
  571. * @returns {object} contains details about a connection failure.
  572. * @private
  573. */
  574. _getConnectionFailedReasonDetails() {
  575. const details = {};
  576. // check for moving between shard if information is available
  577. if (this.options.deploymentInfo
  578. && this.options.deploymentInfo.shard
  579. && this.connection.lastResponseHeaders) {
  580. // split headers by line
  581. const headersArr = this.connection.lastResponseHeaders
  582. .trim().split(/[\r\n]+/);
  583. const headers = {};
  584. headersArr.forEach(line => {
  585. const parts = line.split(': ');
  586. const header = parts.shift();
  587. const value = parts.join(': ');
  588. headers[header] = value;
  589. });
  590. /* eslint-disable camelcase */
  591. details.shard_changed
  592. = this.options.deploymentInfo.shard
  593. !== headers['x-jitsi-shard'];
  594. /* eslint-enable camelcase */
  595. }
  596. /* eslint-disable camelcase */
  597. // check for possible suspend
  598. details.suspend_time = this.connection.ping.getPingSuspendTime();
  599. details.time_since_last_success = this.connection.getTimeSinceLastSuccess();
  600. /* eslint-enable camelcase */
  601. return details;
  602. }
  603. /**
  604. * Notifies speaker stats component if available that we are the new
  605. * dominant speaker in the conference.
  606. * @param {String} roomJid - The room jid where the speaker event occurred.
  607. */
  608. sendDominantSpeakerEvent(roomJid) {
  609. // no speaker stats component advertised
  610. if (!this.speakerStatsComponentAddress || !roomJid) {
  611. return;
  612. }
  613. const msg = $msg({ to: this.speakerStatsComponentAddress });
  614. msg.c('speakerstats', {
  615. xmlns: 'http://jitsi.org/jitmeet',
  616. room: roomJid })
  617. .up();
  618. this.connection.send(msg);
  619. }
  620. /**
  621. * Check if the given argument is a valid JSON ENDPOINT_MESSAGE string by
  622. * parsing it and checking if it has a field called 'type'.
  623. *
  624. * @param {string} jsonString check if this string is a valid json string
  625. * and contains the special structure.
  626. * @returns {boolean, object} if given object is a valid JSON string, return
  627. * the json object. Otherwise, returns false.
  628. */
  629. tryParseJSONAndVerify(jsonString) {
  630. try {
  631. const json = JSON.parse(jsonString);
  632. // Handle non-exception-throwing cases:
  633. // Neither JSON.parse(false) or JSON.parse(1234) throw errors,
  634. // hence the type-checking,
  635. // but... JSON.parse(null) returns null, and
  636. // typeof null === "object",
  637. // so we must check for that, too.
  638. // Thankfully, null is falsey, so this suffices:
  639. if (json && typeof json === 'object') {
  640. const type = json[JITSI_MEET_MUC_TYPE];
  641. if (typeof type !== 'undefined') {
  642. return json;
  643. }
  644. logger.debug('parsing valid json but does not have correct '
  645. + 'structure', 'topic: ', type);
  646. }
  647. } catch (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;
  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. }