You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

xmpp.js 26KB

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