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

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