You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

xmpp.js 28KB

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