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 27KB

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