Vous ne pouvez pas sélectionner plus de 25 sujets Les noms de sujets doivent commencer par une lettre ou un nombre, peuvent contenir des tirets ('-') et peuvent comporter jusqu'à 35 caractères.

xmpp.js 26KB

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