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

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