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.

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