modified lib-jitsi-meet dev repo
Вы не можете выбрать более 25 тем Темы должны начинаться с буквы или цифры, могут содержать дефисы(-) и должны содержать не более 35 символов.

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728
  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 jid of the participant associated with the Strophe connection.
  378. *
  379. * @returns {string} The jid of the participant.
  380. */
  381. getJid() {
  382. return this.connection.jid;
  383. }
  384. /**
  385. * Returns the logs from strophe.jingle.
  386. * @returns {Object}
  387. */
  388. getJingleLog() {
  389. const jingle = this.connection.jingle;
  390. return jingle ? jingle.getLog() : {};
  391. }
  392. /**
  393. * Returns the logs from strophe.
  394. */
  395. getXmppLog() {
  396. return (this.connection.logger || {}).log || null;
  397. }
  398. /**
  399. *
  400. */
  401. dial(...args) {
  402. this.connection.rayo.dial(...args);
  403. }
  404. /**
  405. * Pings the server. Remember to check {@link isPingSupported} before using
  406. * this method.
  407. * @param timeout how many ms before a timeout should occur.
  408. * @returns {Promise} resolved on ping success and reject on an error or
  409. * a timeout.
  410. */
  411. ping(timeout) {
  412. return new Promise((resolve, reject) => {
  413. if (this.isPingSupported()) {
  414. this.connection.ping
  415. .ping(this.connection.domain, resolve, reject, timeout);
  416. } else {
  417. reject('PING operation is not supported by the server');
  418. }
  419. });
  420. }
  421. /**
  422. *
  423. * @param jid
  424. * @param mute
  425. */
  426. setMute(jid, mute) {
  427. this.connection.moderate.setMute(jid, mute);
  428. }
  429. /**
  430. *
  431. * @param jid
  432. */
  433. eject(jid) {
  434. this.connection.moderate.eject(jid);
  435. }
  436. /**
  437. *
  438. */
  439. getSessions() {
  440. return this.connection.jingle.sessions;
  441. }
  442. /**
  443. * Disconnects this from the XMPP server (if this is connected).
  444. *
  445. * @param {Object} ev - Optionally, the event which triggered the necessity to
  446. * disconnect from the XMPP server (e.g. beforeunload, unload).
  447. * @returns {Promise} - Resolves when the disconnect process is finished or rejects with an error.
  448. */
  449. disconnect(ev) {
  450. if (this.disconnectInProgress || !this.connection) {
  451. this.eventEmitter.emit(JitsiConnectionEvents.WRONG_STATE);
  452. return Promise.reject(new Error('Wrong connection state!'));
  453. }
  454. this.disconnectInProgress = true;
  455. return new Promise(resolve => {
  456. const disconnectListener = (credentials, status) => {
  457. if (status === Strophe.Status.DISCONNECTED) {
  458. resolve();
  459. this.eventEmitter.removeListener(XMPPEvents.CONNECTION_STATUS_CHANGED, disconnectListener);
  460. }
  461. };
  462. this.eventEmitter.on(XMPPEvents.CONNECTION_STATUS_CHANGED, disconnectListener);
  463. // XXX Strophe is asynchronously sending by default. Unfortunately, that
  464. // means that there may not be enough time to send an unavailable
  465. // presence or disconnect at all. Switching Strophe to synchronous
  466. // sending is not much of an option because it may lead to a noticeable
  467. // delay in navigating away from the current location. As a compromise,
  468. // we will try to increase the chances of sending an unavailable
  469. // presence and/or disconecting within the short time span that we have
  470. // upon unloading by invoking flush() on the connection. We flush() once
  471. // before disconnect() in order to attemtp to have its unavailable
  472. // presence at the top of the send queue. We flush() once more after
  473. // disconnect() in order to attempt to have its unavailable presence
  474. // sent as soon as possible.
  475. this.connection.flush();
  476. if (ev !== null && typeof ev !== 'undefined') {
  477. const evType = ev.type;
  478. if (evType === 'beforeunload' || evType === 'unload') {
  479. // XXX Whatever we said above, synchronous sending is the best
  480. // (known) way to properly disconnect from the XMPP server.
  481. // Consequently, it may be fine to have the source code and
  482. // comment it in or out depending on whether we want to run with
  483. // it for some time.
  484. this.connection.options.sync = true;
  485. }
  486. }
  487. this.connection.disconnect();
  488. if (this.connection.options.sync !== true) {
  489. this.connection.flush();
  490. }
  491. });
  492. }
  493. /**
  494. *
  495. */
  496. _initStrophePlugins() {
  497. const iceConfig = {
  498. jvb: { iceServers: [ ] },
  499. p2p: { iceServers: [ ] }
  500. };
  501. const p2pStunServers = (this.options.p2p
  502. && this.options.p2p.stunServers) || DEFAULT_STUN_SERVERS;
  503. if (Array.isArray(p2pStunServers)) {
  504. logger.info('P2P STUN servers: ', p2pStunServers);
  505. iceConfig.p2p.iceServers = p2pStunServers;
  506. }
  507. if (this.options.p2p && this.options.p2p.iceTransportPolicy) {
  508. logger.info('P2P ICE transport policy: ',
  509. this.options.p2p.iceTransportPolicy);
  510. iceConfig.p2p.iceTransportPolicy
  511. = this.options.p2p.iceTransportPolicy;
  512. }
  513. initEmuc(this);
  514. initJingle(this, this.eventEmitter, iceConfig);
  515. initStropheUtil();
  516. initPing(this);
  517. initRayo();
  518. initStropheLogger();
  519. }
  520. /**
  521. * Returns details about connection failure. Shard change or is it after
  522. * suspend.
  523. * @returns {object} contains details about a connection failure.
  524. * @private
  525. */
  526. _getConnectionFailedReasonDetails() {
  527. const details = {};
  528. // check for moving between shard if information is available
  529. if (this.options.deploymentInfo
  530. && this.options.deploymentInfo.shard
  531. && this.connection._proto
  532. && this.connection._proto.lastResponseHeaders) {
  533. // split headers by line
  534. const headersArr = this.connection._proto.lastResponseHeaders
  535. .trim().split(/[\r\n]+/);
  536. const headers = {};
  537. headersArr.forEach(line => {
  538. const parts = line.split(': ');
  539. const header = parts.shift();
  540. const value = parts.join(': ');
  541. headers[header] = value;
  542. });
  543. /* eslint-disable camelcase */
  544. details.shard_changed
  545. = this.options.deploymentInfo.shard
  546. !== headers['x-jitsi-shard'];
  547. /* eslint-enable camelcase */
  548. }
  549. /* eslint-disable camelcase */
  550. // check for possible suspend
  551. details.suspend_time = this.connection.ping.getPingSuspendTime();
  552. /* eslint-enable camelcase */
  553. return details;
  554. }
  555. /**
  556. * Notifies speaker stats component if available that we are the new
  557. * dominant speaker in the conference.
  558. * @param {String} roomJid - The room jid where the speaker event occurred.
  559. */
  560. sendDominantSpeakerEvent(roomJid) {
  561. // no speaker stats component advertised
  562. if (!this.speakerStatsComponentAddress || !roomJid) {
  563. return;
  564. }
  565. const msg = $msg({ to: this.speakerStatsComponentAddress });
  566. msg.c('speakerstats', {
  567. xmlns: 'http://jitsi.org/jitmeet',
  568. room: roomJid })
  569. .up();
  570. this.connection.send(msg);
  571. }
  572. /**
  573. * Check if the given argument is a valid JSON ENDPOINT_MESSAGE string by
  574. * parsing it and checking if it has a field called 'type'.
  575. *
  576. * @param {string} jsonString check if this string is a valid json string
  577. * and contains the special structure.
  578. * @returns {boolean, object} if given object is a valid JSON string, return
  579. * the json object. Otherwise, returns false.
  580. */
  581. tryParseJSONAndVerify(jsonString) {
  582. try {
  583. const json = JSON.parse(jsonString);
  584. // Handle non-exception-throwing cases:
  585. // Neither JSON.parse(false) or JSON.parse(1234) throw errors,
  586. // hence the type-checking,
  587. // but... JSON.parse(null) returns null, and
  588. // typeof null === "object",
  589. // so we must check for that, too.
  590. // Thankfully, null is falsey, so this suffices:
  591. if (json && typeof json === 'object') {
  592. const type = json[JITSI_MEET_MUC_TYPE];
  593. if (typeof type !== 'undefined') {
  594. return json;
  595. }
  596. logger.debug('parsing valid json but does not have correct '
  597. + 'structure', 'topic: ', type);
  598. }
  599. } catch (e) {
  600. return false;
  601. }
  602. return false;
  603. }
  604. /**
  605. * A private message is received, message that is not addressed to the muc.
  606. * We expect private message coming from speaker stats component if it is
  607. * enabled and running.
  608. *
  609. * @param {string} msg - The message.
  610. */
  611. _onPrivateMessage(msg) {
  612. const from = msg.getAttribute('from');
  613. if (!this.speakerStatsComponentAddress
  614. || from !== this.speakerStatsComponentAddress) {
  615. return;
  616. }
  617. const jsonMessage = $(msg).find('>json-message')
  618. .text();
  619. const parsedJson = this.tryParseJSONAndVerify(jsonMessage);
  620. if (parsedJson
  621. && parsedJson[JITSI_MEET_MUC_TYPE] === 'speakerstats'
  622. && parsedJson.users) {
  623. this.eventEmitter.emit(
  624. XMPPEvents.SPEAKER_STATS_RECEIVED, parsedJson.users);
  625. }
  626. return true;
  627. }
  628. }