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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742
  1. /* global $ */
  2. import { getLogger } from 'jitsi-meet-logger';
  3. import { $msg, $pres, 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. this._getConnectionFailedReasonDetails());
  251. } else {
  252. this.eventEmitter.emit(
  253. JitsiConnectionEvents.CONNECTION_FAILED,
  254. JitsiConnectionErrors.CONNECTION_DROPPED_ERROR,
  255. errMsg || 'connection-dropped-error',
  256. /* credentials */ undefined,
  257. this._getConnectionFailedReasonDetails());
  258. }
  259. }
  260. } else if (status === Strophe.Status.AUTHFAIL) {
  261. // wrong password or username, prompt user
  262. this.eventEmitter.emit(
  263. JitsiConnectionEvents.CONNECTION_FAILED,
  264. JitsiConnectionErrors.PASSWORD_REQUIRED,
  265. msg,
  266. credentials);
  267. }
  268. }
  269. /**
  270. *
  271. * @param jid
  272. * @param password
  273. */
  274. _connect(jid, password) {
  275. // connection.connect() starts the connection process.
  276. //
  277. // As the connection process proceeds, the user supplied callback will
  278. // be triggered multiple times with status updates. The callback should
  279. // take two arguments - the status code and the error condition.
  280. //
  281. // The status code will be one of the values in the Strophe.Status
  282. // constants. The error condition will be one of the conditions defined
  283. // in RFC 3920 or the condition ‘strophe-parsererror’.
  284. //
  285. // The Parameters wait, hold and route are optional and only relevant
  286. // for BOSH connections. Please see XEP 124 for a more detailed
  287. // explanation of the optional parameters.
  288. //
  289. // Connection status constants for use by the connection handler
  290. // callback.
  291. //
  292. // Status.ERROR - An error has occurred (websockets specific)
  293. // Status.CONNECTING - The connection is currently being made
  294. // Status.CONNFAIL - The connection attempt failed
  295. // Status.AUTHENTICATING - The connection is authenticating
  296. // Status.AUTHFAIL - The authentication attempt failed
  297. // Status.CONNECTED - The connection has succeeded
  298. // Status.DISCONNECTED - The connection has been terminated
  299. // Status.DISCONNECTING - The connection is currently being terminated
  300. // Status.ATTACHED - The connection has been attached
  301. this.anonymousConnectionFailed = false;
  302. this.connectionFailed = false;
  303. this.lastErrorMsg = undefined;
  304. this.connection.connect(
  305. jid,
  306. password,
  307. this.connectionHandler.bind(this, {
  308. jid,
  309. password
  310. }));
  311. }
  312. /**
  313. * Attach to existing connection. Can be used for optimizations. For
  314. * example: if the connection is created on the server we can attach to it
  315. * and start using it.
  316. *
  317. * @param options {object} connecting options - rid, sid, jid and password.
  318. */
  319. attach(options) {
  320. const now = this.connectionTimes.attaching = window.performance.now();
  321. logger.log(`(TIME) Strophe Attaching\t:${now}`);
  322. this.connection.attach(options.jid, options.sid,
  323. parseInt(options.rid, 10) + 1,
  324. this.connectionHandler.bind(this, {
  325. jid: options.jid,
  326. password: options.password
  327. }));
  328. }
  329. /**
  330. *
  331. * @param jid
  332. * @param password
  333. */
  334. connect(jid, password) {
  335. if (!jid) {
  336. const { anonymousdomain, domain } = this.options.hosts;
  337. let configDomain = anonymousdomain || domain;
  338. // Force authenticated domain if room is appended with '?login=true'
  339. // or if we're joining with the token
  340. // FIXME Do not rely on window.location because (1) React Native
  341. // does not have a window.location by default and (2) here we cannot
  342. // know for sure that query/search has not be stripped from
  343. // window.location by the time the following executes.
  344. const { location } = window;
  345. if (anonymousdomain) {
  346. const search = location && location.search;
  347. if ((search && search.indexOf('login=true') !== -1)
  348. || this.token) {
  349. configDomain = domain;
  350. }
  351. }
  352. // eslint-disable-next-line no-param-reassign
  353. jid = configDomain || (location && location.hostname);
  354. }
  355. return this._connect(jid, password);
  356. }
  357. /**
  358. * Joins or creates a muc with the provided jid, created from the passed
  359. * in room name and muc host and onCreateResource result.
  360. *
  361. * @param {string} roomName - The name of the muc to join.
  362. * @param {Object} options - Configuration for how to join the muc.
  363. * @param {Function} [onCreateResource] - Callback to invoke when a resource
  364. * is to be added to the jid.
  365. * @returns {Promise} Resolves with an instance of a strophe muc.
  366. */
  367. createRoom(roomName, options, onCreateResource) {
  368. let roomjid = `${roomName}@${this.options.hosts.muc}/`;
  369. const mucNickname = onCreateResource
  370. ? onCreateResource(this.connection.jid, this.authenticatedUser)
  371. : RandomUtil.randomHexString(8).toLowerCase();
  372. logger.info(`JID ${this.connection.jid} using MUC nickname ${mucNickname}`);
  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. */
  424. getSessions() {
  425. return this.connection.jingle.sessions;
  426. }
  427. /**
  428. * Disconnects this from the XMPP server (if this is connected).
  429. *
  430. * @param {Object} ev - Optionally, the event which triggered the necessity to
  431. * disconnect from the XMPP server (e.g. beforeunload, unload).
  432. * @returns {Promise} - Resolves when the disconnect process is finished or rejects with an error.
  433. */
  434. disconnect(ev) {
  435. if (this.disconnectInProgress || !this.connection) {
  436. this.eventEmitter.emit(JitsiConnectionEvents.WRONG_STATE);
  437. return Promise.reject(new Error('Wrong connection state!'));
  438. }
  439. this.disconnectInProgress = true;
  440. return new Promise(resolve => {
  441. const disconnectListener = (credentials, status) => {
  442. if (status === Strophe.Status.DISCONNECTED) {
  443. resolve();
  444. this.eventEmitter.removeListener(XMPPEvents.CONNECTION_STATUS_CHANGED, disconnectListener);
  445. }
  446. };
  447. this.eventEmitter.on(XMPPEvents.CONNECTION_STATUS_CHANGED, disconnectListener);
  448. // XXX Strophe is asynchronously sending by default. Unfortunately, that
  449. // means that there may not be enough time to send an unavailable
  450. // presence or disconnect at all. Switching Strophe to synchronous
  451. // sending is not much of an option because it may lead to a noticeable
  452. // delay in navigating away from the current location. As a compromise,
  453. // we will try to increase the chances of sending an unavailable
  454. // presence and/or disconecting within the short time span that we have
  455. // upon unloading by invoking flush() on the connection. We flush() once
  456. // before disconnect() in order to attemtp to have its unavailable
  457. // presence at the top of the send queue. We flush() once more after
  458. // disconnect() in order to attempt to have its unavailable presence
  459. // sent as soon as possible.
  460. this.connection.flush();
  461. if (ev !== null && typeof ev !== 'undefined') {
  462. const evType = ev.type;
  463. if (evType === 'beforeunload' || evType === 'unload') {
  464. // XXX Whatever we said above, synchronous sending is the best
  465. // (known) way to properly disconnect from the XMPP server.
  466. // Consequently, it may be fine to have the source code and
  467. // comment it in or out depending on whether we want to run with
  468. // it for some time.
  469. this.connection.options.sync = true;
  470. // This is needed in some browsers where sync xhr sending
  471. // is disabled by default on unload
  472. if (navigator.sendBeacon && !this.connection.disconnecting
  473. && this.connection.connected) {
  474. this.connection._changeConnectStatus(Strophe.Status.DISCONNECTING);
  475. this.connection.disconnecting = true;
  476. const body = this.connection._proto._buildBody()
  477. .attrs({
  478. type: 'terminate'
  479. });
  480. const pres = $pres({
  481. xmlns: Strophe.NS.CLIENT,
  482. type: 'unavailable'
  483. });
  484. body.cnode(pres.tree());
  485. const res = navigator.sendBeacon(
  486. `https:${this.connection.service}`,
  487. Strophe.serialize(body.tree()));
  488. logger.info(`Successfully send unavailable beacon ${res}`);
  489. this.connection._proto._abortAllRequests();
  490. this.connection._doDisconnect();
  491. return;
  492. }
  493. }
  494. }
  495. this.connection.disconnect();
  496. if (this.connection.options.sync !== true) {
  497. this.connection.flush();
  498. }
  499. });
  500. }
  501. /**
  502. *
  503. */
  504. _initStrophePlugins() {
  505. const iceConfig = {
  506. jvb: { iceServers: [ ] },
  507. p2p: { iceServers: [ ] }
  508. };
  509. const p2pStunServers = (this.options.p2p
  510. && this.options.p2p.stunServers) || DEFAULT_STUN_SERVERS;
  511. if (Array.isArray(p2pStunServers)) {
  512. logger.info('P2P STUN servers: ', p2pStunServers);
  513. iceConfig.p2p.iceServers = p2pStunServers;
  514. }
  515. if (this.options.p2p && this.options.p2p.iceTransportPolicy) {
  516. logger.info('P2P ICE transport policy: ',
  517. this.options.p2p.iceTransportPolicy);
  518. iceConfig.p2p.iceTransportPolicy
  519. = this.options.p2p.iceTransportPolicy;
  520. }
  521. initEmuc(this);
  522. initJingle(this, this.eventEmitter, iceConfig);
  523. initStropheUtil();
  524. initPing(this);
  525. initRayo();
  526. initStropheLogger();
  527. }
  528. /**
  529. * Returns details about connection failure. Shard change or is it after
  530. * suspend.
  531. * @returns {object} contains details about a connection failure.
  532. * @private
  533. */
  534. _getConnectionFailedReasonDetails() {
  535. const details = {};
  536. // check for moving between shard if information is available
  537. if (this.options.deploymentInfo
  538. && this.options.deploymentInfo.shard
  539. && this.connection._proto
  540. && this.connection._proto.lastResponseHeaders) {
  541. // split headers by line
  542. const headersArr = this.connection._proto.lastResponseHeaders
  543. .trim().split(/[\r\n]+/);
  544. const headers = {};
  545. headersArr.forEach(line => {
  546. const parts = line.split(': ');
  547. const header = parts.shift();
  548. const value = parts.join(': ');
  549. headers[header] = value;
  550. });
  551. /* eslint-disable camelcase */
  552. details.shard_changed
  553. = this.options.deploymentInfo.shard
  554. !== headers['x-jitsi-shard'];
  555. /* eslint-enable camelcase */
  556. }
  557. /* eslint-disable camelcase */
  558. // check for possible suspend
  559. details.suspend_time = this.connection.ping.getPingSuspendTime();
  560. details.time_since_last_success = this._lastSuccessTracker.getTimeSinceLastSuccess();
  561. /* eslint-enable camelcase */
  562. return details;
  563. }
  564. /**
  565. * Notifies speaker stats component if available that we are the new
  566. * dominant speaker in the conference.
  567. * @param {String} roomJid - The room jid where the speaker event occurred.
  568. */
  569. sendDominantSpeakerEvent(roomJid) {
  570. // no speaker stats component advertised
  571. if (!this.speakerStatsComponentAddress || !roomJid) {
  572. return;
  573. }
  574. const msg = $msg({ to: this.speakerStatsComponentAddress });
  575. msg.c('speakerstats', {
  576. xmlns: 'http://jitsi.org/jitmeet',
  577. room: roomJid })
  578. .up();
  579. this.connection.send(msg);
  580. }
  581. /**
  582. * Check if the given argument is a valid JSON ENDPOINT_MESSAGE string by
  583. * parsing it and checking if it has a field called 'type'.
  584. *
  585. * @param {string} jsonString check if this string is a valid json string
  586. * and contains the special structure.
  587. * @returns {boolean, object} if given object is a valid JSON string, return
  588. * the json object. Otherwise, returns false.
  589. */
  590. tryParseJSONAndVerify(jsonString) {
  591. try {
  592. const json = JSON.parse(jsonString);
  593. // Handle non-exception-throwing cases:
  594. // Neither JSON.parse(false) or JSON.parse(1234) throw errors,
  595. // hence the type-checking,
  596. // but... JSON.parse(null) returns null, and
  597. // typeof null === "object",
  598. // so we must check for that, too.
  599. // Thankfully, null is falsey, so this suffices:
  600. if (json && typeof json === 'object') {
  601. const type = json[JITSI_MEET_MUC_TYPE];
  602. if (typeof type !== 'undefined') {
  603. return json;
  604. }
  605. logger.debug('parsing valid json but does not have correct '
  606. + 'structure', 'topic: ', type);
  607. }
  608. } catch (e) {
  609. return false;
  610. }
  611. return false;
  612. }
  613. /**
  614. * A private message is received, message that is not addressed to the muc.
  615. * We expect private message coming from speaker stats component if it is
  616. * enabled and running.
  617. *
  618. * @param {string} msg - The message.
  619. */
  620. _onPrivateMessage(msg) {
  621. const from = msg.getAttribute('from');
  622. if (!this.speakerStatsComponentAddress
  623. || from !== this.speakerStatsComponentAddress) {
  624. return;
  625. }
  626. const jsonMessage = $(msg).find('>json-message')
  627. .text();
  628. const parsedJson = this.tryParseJSONAndVerify(jsonMessage);
  629. if (parsedJson
  630. && parsedJson[JITSI_MEET_MUC_TYPE] === 'speakerstats'
  631. && parsedJson.users) {
  632. this.eventEmitter.emit(
  633. XMPPEvents.SPEAKER_STATS_RECEIVED, parsedJson.users);
  634. }
  635. return true;
  636. }
  637. }