您最多选择25个主题 主题必须以字母或数字开头,可以包含连字符 (-),并且长度不得超过35个字符

xmpp.js 25KB

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