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

xmpp.js 28KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752
  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 MucConnectionPlugin from './strophe.emuc';
  10. import JingleConnectionPlugin from './strophe.jingle';
  11. import initStropheUtil from './strophe.util';
  12. import PingConnectionPlugin from './strophe.ping';
  13. import RayoConnectionPlugin 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. import XmppConnection from './XmppConnection';
  20. const logger = getLogger(__filename);
  21. /**
  22. * Creates XMPP connection.
  23. *
  24. * @param {XMPP} xmpp - The XMPP module instance.
  25. * @param {string} [token] - JWT token used for authentication(JWT authentication module must be enabled in Prosody).
  26. * @param {string} serviceUrl - The service URL for XMPP connection.
  27. * @returns {XmppConnection}
  28. */
  29. function createConnection(xmpp, token, serviceUrl = '/http-bind') {
  30. // Append token as URL param
  31. if (token) {
  32. // eslint-disable-next-line no-param-reassign
  33. serviceUrl += `${serviceUrl.indexOf('?') === -1 ? '?' : '&'}token=${token}`;
  34. }
  35. return new XmppConnection(xmpp, serviceUrl);
  36. }
  37. /**
  38. * Initializes Strophe plugins that need to work with Strophe.Connection directly rather than the lib-jitsi-meet's
  39. * {@link XmppConnection} wrapper.
  40. *
  41. * @returns {void}
  42. */
  43. function initStropheNativePlugins() {
  44. initStropheUtil();
  45. initStropheLogger();
  46. }
  47. // FIXME: remove once we have a default config template. -saghul
  48. /**
  49. * A list of ice servers to use by default for P2P.
  50. */
  51. export const DEFAULT_STUN_SERVERS = [
  52. { urls: 'stun:stun.l.google.com:19302' },
  53. { urls: 'stun:stun1.l.google.com:19302' },
  54. { urls: 'stun:stun2.l.google.com:19302' }
  55. ];
  56. /**
  57. * The name of the field used to recognize a chat message as carrying a JSON
  58. * payload from another endpoint.
  59. * If the json-message of a chat message contains a valid JSON object, and
  60. * the JSON has this key, then it is a valid json-message to be sent.
  61. */
  62. export const JITSI_MEET_MUC_TYPE = 'type';
  63. /**
  64. *
  65. */
  66. export default class XMPP extends Listenable {
  67. /**
  68. * FIXME describe all options
  69. * @param {Object} options
  70. * @param {String} options.serviceUrl - URL passed to the XMPP client which will be used to establish XMPP
  71. * connection with the server.
  72. * @param {String} options.bosh - Deprecated, use {@code serviceUrl}.
  73. * @param {Array<Object>} options.p2pStunServers see
  74. * {@link JingleConnectionPlugin} for more details.
  75. * @param token
  76. */
  77. constructor(options, token) {
  78. super();
  79. this.connection = null;
  80. this.disconnectInProgress = false;
  81. this.connectionTimes = {};
  82. this.options = options;
  83. this.token = token;
  84. this.authenticatedUser = false;
  85. // FIXME remove deprecated bosh option at some point
  86. const serviceUrl = options.serviceUrl || options.bosh;
  87. initStropheNativePlugins();
  88. this.connection = createConnection(this, token, serviceUrl);
  89. this._initStrophePlugins();
  90. this.caps = new Caps(this.connection, this.options.clientNode);
  91. // Initialize features advertised in disco-info
  92. this.initFeaturesList();
  93. // Setup a disconnect on unload as a way to facilitate API consumers. It
  94. // sounds like they would want that. A problem for them though may be if
  95. // they wanted to utilize the connected connection in an unload handler
  96. // of their own. However, it should be fairly easy for them to do that
  97. // by registering their unload handler before us.
  98. $(window).on('beforeunload unload', ev => {
  99. this.disconnect(ev).catch(() => {
  100. // ignore errors in order to not brake the unload.
  101. });
  102. });
  103. }
  104. /**
  105. * Initializes the list of feature advertised through the disco-info
  106. * mechanism.
  107. */
  108. initFeaturesList() {
  109. // http://xmpp.org/extensions/xep-0167.html#support
  110. // http://xmpp.org/extensions/xep-0176.html#support
  111. this.caps.addFeature('urn:xmpp:jingle:1');
  112. this.caps.addFeature('urn:xmpp:jingle:apps:rtp:1');
  113. this.caps.addFeature('urn:xmpp:jingle:transports:ice-udp:1');
  114. this.caps.addFeature('urn:xmpp:jingle:apps:dtls:0');
  115. this.caps.addFeature('urn:xmpp:jingle:transports:dtls-sctp:1');
  116. this.caps.addFeature('urn:xmpp:jingle:apps:rtp:audio');
  117. this.caps.addFeature('urn:xmpp:jingle:apps:rtp:video');
  118. if (!this.options.disableRtx && browser.supportsRtx()) {
  119. this.caps.addFeature('urn:ietf:rfc:4588');
  120. }
  121. // this is dealt with by SDP O/A so we don't need to announce this
  122. // XEP-0293
  123. // this.caps.addFeature('urn:xmpp:jingle:apps:rtp:rtcp-fb:0');
  124. // XEP-0294
  125. // this.caps.addFeature('urn:xmpp:jingle:apps:rtp:rtp-hdrext:0');
  126. this.caps.addFeature('urn:ietf:rfc:5761'); // rtcp-mux
  127. this.caps.addFeature('urn:ietf:rfc:5888'); // a=group, e.g. bundle
  128. // this.caps.addFeature('urn:ietf:rfc:5576'); // a=ssrc
  129. // Enable Lipsync ?
  130. if (browser.isChrome() && this.options.enableLipSync !== false) {
  131. logger.info('Lip-sync enabled !');
  132. this.caps.addFeature('http://jitsi.org/meet/lipsync');
  133. }
  134. if (this.connection.rayo) {
  135. this.caps.addFeature('urn:xmpp:rayo:client:1');
  136. }
  137. }
  138. /**
  139. * Returns {@code true} if the PING functionality is supported by the server
  140. * or {@code false} otherwise.
  141. * @returns {boolean}
  142. */
  143. isPingSupported() {
  144. return this._pingSupported !== false;
  145. }
  146. /**
  147. *
  148. */
  149. getConnection() {
  150. return this.connection;
  151. }
  152. /**
  153. * Receive connection status changes and handles them.
  154. *
  155. * @param {Object} credentials
  156. * @param {string} credentials.jid - The user's XMPP ID passed to the
  157. * connect method. For example, 'user@xmpp.com'.
  158. * @param {string} credentials.password - The password passed to the connect
  159. * method.
  160. * @param {string} status - One of Strophe's connection status strings.
  161. * @param {string} [msg] - The connection error message provided by Strophe.
  162. */
  163. connectionHandler(credentials = {}, status, msg) {
  164. const now = window.performance.now();
  165. const statusStr = Strophe.getStatusString(status).toLowerCase();
  166. this.connectionTimes[statusStr] = now;
  167. logger.log(
  168. `(TIME) Strophe ${statusStr}${msg ? `[${msg}]` : ''}:\t`,
  169. now);
  170. this.eventEmitter.emit(XMPPEvents.CONNECTION_STATUS_CHANGED, credentials, status, msg);
  171. if (status === Strophe.Status.CONNECTED
  172. || status === Strophe.Status.ATTACHED) {
  173. if (this.options.useStunTurn
  174. || (this.options.p2p && this.options.p2p.useStunTurn)) {
  175. this.connection.jingle.getStunAndTurnCredentials();
  176. }
  177. logger.info(`My Jabber ID: ${this.connection.jid}`);
  178. // Schedule ping ?
  179. const pingJid = this.connection.domain;
  180. this.caps.getFeaturesAndIdentities(pingJid)
  181. .then(({ features, identities }) => {
  182. if (features.has(Strophe.NS.PING)) {
  183. this._pingSupported = true;
  184. this.connection.ping.startInterval(pingJid);
  185. } else {
  186. logger.warn(`Ping NOT supported by ${pingJid}`);
  187. }
  188. // check for speakerstats
  189. identities.forEach(identity => {
  190. if (identity.type === 'speakerstats') {
  191. this.speakerStatsComponentAddress = identity.name;
  192. }
  193. if (identity.type === 'conference_duration') {
  194. this.conferenceDurationComponentAddress = identity.name;
  195. }
  196. });
  197. if (this.speakerStatsComponentAddress
  198. || this.conferenceDurationComponentAddress) {
  199. this.connection.addHandler(
  200. this._onPrivateMessage.bind(this), null,
  201. 'message', null, null);
  202. }
  203. })
  204. .catch(error => {
  205. const errmsg = 'Feature discovery error';
  206. GlobalOnErrorHandler.callErrorHandler(
  207. new Error(`${errmsg}: ${error}`));
  208. logger.error(errmsg, error);
  209. });
  210. if (credentials.password) {
  211. this.authenticatedUser = true;
  212. }
  213. if (this.connection && this.connection.connected
  214. && Strophe.getResourceFromJid(this.connection.jid)) {
  215. // .connected is true while connecting?
  216. // this.connection.send($pres());
  217. this.eventEmitter.emit(
  218. JitsiConnectionEvents.CONNECTION_ESTABLISHED,
  219. Strophe.getResourceFromJid(this.connection.jid));
  220. }
  221. } else if (status === Strophe.Status.CONNFAIL) {
  222. if (msg === 'x-strophe-bad-non-anon-jid') {
  223. this.anonymousConnectionFailed = true;
  224. } else {
  225. this.connectionFailed = true;
  226. }
  227. this.lastErrorMsg = msg;
  228. if (msg === 'giving-up') {
  229. this.eventEmitter.emit(
  230. JitsiConnectionEvents.CONNECTION_FAILED,
  231. JitsiConnectionErrors.OTHER_ERROR, msg);
  232. }
  233. } else if (status === Strophe.Status.DISCONNECTED) {
  234. // Stop ping interval
  235. this.connection.ping.stopInterval();
  236. const wasIntentionalDisconnect = this.disconnectInProgress;
  237. const errMsg = msg || this.lastErrorMsg;
  238. this.disconnectInProgress = false;
  239. if (this.anonymousConnectionFailed) {
  240. // prompt user for username and password
  241. this.eventEmitter.emit(
  242. JitsiConnectionEvents.CONNECTION_FAILED,
  243. JitsiConnectionErrors.PASSWORD_REQUIRED);
  244. } else if (this.connectionFailed) {
  245. this.eventEmitter.emit(
  246. JitsiConnectionEvents.CONNECTION_FAILED,
  247. JitsiConnectionErrors.OTHER_ERROR,
  248. errMsg,
  249. undefined, /* credentials */
  250. this._getConnectionFailedReasonDetails());
  251. } else if (wasIntentionalDisconnect) {
  252. this.eventEmitter.emit(
  253. JitsiConnectionEvents.CONNECTION_DISCONNECTED, errMsg);
  254. } else {
  255. // XXX if Strophe drops the connection while not being asked to,
  256. // it means that most likely some serious error has occurred.
  257. // One currently known case is when a BOSH request fails for
  258. // more than 4 times. The connection is dropped without
  259. // supplying a reason(error message/event) through the API.
  260. logger.error('XMPP connection dropped!');
  261. // XXX if the last request error is within 5xx range it means it
  262. // was a server failure
  263. const lastErrorStatus = Strophe.getLastErrorStatus();
  264. if (lastErrorStatus >= 500 && lastErrorStatus < 600) {
  265. this.eventEmitter.emit(
  266. JitsiConnectionEvents.CONNECTION_FAILED,
  267. JitsiConnectionErrors.SERVER_ERROR,
  268. errMsg || 'server-error',
  269. /* credentials */ undefined,
  270. this._getConnectionFailedReasonDetails());
  271. } else {
  272. this.eventEmitter.emit(
  273. JitsiConnectionEvents.CONNECTION_FAILED,
  274. JitsiConnectionErrors.CONNECTION_DROPPED_ERROR,
  275. errMsg || 'connection-dropped-error',
  276. /* credentials */ undefined,
  277. this._getConnectionFailedReasonDetails());
  278. }
  279. }
  280. } else if (status === Strophe.Status.AUTHFAIL) {
  281. // wrong password or username, prompt user
  282. this.eventEmitter.emit(
  283. JitsiConnectionEvents.CONNECTION_FAILED,
  284. JitsiConnectionErrors.PASSWORD_REQUIRED,
  285. msg,
  286. credentials);
  287. }
  288. }
  289. /**
  290. *
  291. * @param jid
  292. * @param password
  293. */
  294. _connect(jid, password) {
  295. // connection.connect() starts the connection process.
  296. //
  297. // As the connection process proceeds, the user supplied callback will
  298. // be triggered multiple times with status updates. The callback should
  299. // take two arguments - the status code and the error condition.
  300. //
  301. // The status code will be one of the values in the Strophe.Status
  302. // constants. The error condition will be one of the conditions defined
  303. // in RFC 3920 or the condition ‘strophe-parsererror’.
  304. //
  305. // The Parameters wait, hold and route are optional and only relevant
  306. // for BOSH connections. Please see XEP 124 for a more detailed
  307. // explanation of the optional parameters.
  308. //
  309. // Connection status constants for use by the connection handler
  310. // callback.
  311. //
  312. // Status.ERROR - An error has occurred (websockets specific)
  313. // Status.CONNECTING - The connection is currently being made
  314. // Status.CONNFAIL - The connection attempt failed
  315. // Status.AUTHENTICATING - The connection is authenticating
  316. // Status.AUTHFAIL - The authentication attempt failed
  317. // Status.CONNECTED - The connection has succeeded
  318. // Status.DISCONNECTED - The connection has been terminated
  319. // Status.DISCONNECTING - The connection is currently being terminated
  320. // Status.ATTACHED - The connection has been attached
  321. this.anonymousConnectionFailed = false;
  322. this.connectionFailed = false;
  323. this.lastErrorMsg = undefined;
  324. this.connection.connect(
  325. jid,
  326. password,
  327. this.connectionHandler.bind(this, {
  328. jid,
  329. password
  330. }));
  331. }
  332. /**
  333. * Attach to existing connection. Can be used for optimizations. For
  334. * example: if the connection is created on the server we can attach to it
  335. * and start using it.
  336. *
  337. * @param options {object} connecting options - rid, sid, jid and password.
  338. */
  339. attach(options) {
  340. const now = this.connectionTimes.attaching = window.performance.now();
  341. logger.log('(TIME) Strophe Attaching:\t', now);
  342. this.connection.attach(options.jid, options.sid,
  343. parseInt(options.rid, 10) + 1,
  344. this.connectionHandler.bind(this, {
  345. jid: options.jid,
  346. password: options.password
  347. }));
  348. }
  349. /**
  350. *
  351. * @param jid
  352. * @param password
  353. */
  354. connect(jid, password) {
  355. if (!jid) {
  356. const { anonymousdomain, domain } = this.options.hosts;
  357. let configDomain = anonymousdomain || domain;
  358. // Force authenticated domain if room is appended with '?login=true'
  359. // or if we're joining with the token
  360. // FIXME Do not rely on window.location because (1) React Native
  361. // does not have a window.location by default and (2) here we cannot
  362. // know for sure that query/search has not be stripped from
  363. // window.location by the time the following executes.
  364. const { location } = window;
  365. if (anonymousdomain) {
  366. const search = location && location.search;
  367. if ((search && search.indexOf('login=true') !== -1)
  368. || this.token) {
  369. configDomain = domain;
  370. }
  371. }
  372. // eslint-disable-next-line no-param-reassign
  373. jid = configDomain || (location && location.hostname);
  374. }
  375. return this._connect(jid, password);
  376. }
  377. /**
  378. * Joins or creates a muc with the provided jid, created from the passed
  379. * in room name and muc host and onCreateResource result.
  380. *
  381. * @param {string} roomName - The name of the muc to join.
  382. * @param {Object} options - Configuration for how to join the muc.
  383. * @param {Function} [onCreateResource] - Callback to invoke when a resource
  384. * is to be added to the jid.
  385. * @returns {Promise} Resolves with an instance of a strophe muc.
  386. */
  387. createRoom(roomName, options, onCreateResource) {
  388. let roomjid = `${roomName}@${this.options.hosts.muc}/`;
  389. const mucNickname = onCreateResource
  390. ? onCreateResource(this.connection.jid, this.authenticatedUser)
  391. : RandomUtil.randomHexString(8).toLowerCase();
  392. logger.info(`JID ${this.connection.jid} using MUC nickname ${mucNickname}`);
  393. roomjid += mucNickname;
  394. return this.connection.emuc.createRoom(roomjid, null, options);
  395. }
  396. /**
  397. * Returns the jid of the participant associated with the Strophe connection.
  398. *
  399. * @returns {string} The jid of the participant.
  400. */
  401. getJid() {
  402. return this.connection.jid;
  403. }
  404. /**
  405. * Returns the logs from strophe.jingle.
  406. * @returns {Object}
  407. */
  408. getJingleLog() {
  409. const jingle = this.connection.jingle;
  410. return jingle ? jingle.getLog() : {};
  411. }
  412. /**
  413. * Returns the logs from strophe.
  414. */
  415. getXmppLog() {
  416. return (this.connection.logger || {}).log || null;
  417. }
  418. /**
  419. *
  420. */
  421. dial(...args) {
  422. this.connection.rayo.dial(...args);
  423. }
  424. /**
  425. * Pings the server. Remember to check {@link isPingSupported} before using
  426. * this method.
  427. * @param timeout how many ms before a timeout should occur.
  428. * @returns {Promise} resolved on ping success and reject on an error or
  429. * a timeout.
  430. */
  431. ping(timeout) {
  432. return new Promise((resolve, reject) => {
  433. if (this.isPingSupported()) {
  434. this.connection.ping
  435. .ping(this.connection.domain, resolve, reject, timeout);
  436. } else {
  437. reject('PING operation is not supported by the server');
  438. }
  439. });
  440. }
  441. /**
  442. *
  443. */
  444. getSessions() {
  445. return this.connection.jingle.sessions;
  446. }
  447. /**
  448. * Disconnects this from the XMPP server (if this is connected).
  449. *
  450. * @param {Object} ev - Optionally, the event which triggered the necessity to
  451. * disconnect from the XMPP server (e.g. beforeunload, unload).
  452. * @returns {Promise} - Resolves when the disconnect process is finished or rejects with an error.
  453. */
  454. disconnect(ev) {
  455. if (this.disconnectInProgress || !this.connection) {
  456. this.eventEmitter.emit(JitsiConnectionEvents.WRONG_STATE);
  457. return Promise.reject(new Error('Wrong connection state!'));
  458. }
  459. this.disconnectInProgress = true;
  460. return new Promise(resolve => {
  461. const disconnectListener = (credentials, status) => {
  462. if (status === Strophe.Status.DISCONNECTED) {
  463. resolve();
  464. this.eventEmitter.removeListener(XMPPEvents.CONNECTION_STATUS_CHANGED, disconnectListener);
  465. }
  466. };
  467. this.eventEmitter.on(XMPPEvents.CONNECTION_STATUS_CHANGED, disconnectListener);
  468. this._cleanupXmppConnection(ev);
  469. });
  470. }
  471. /**
  472. * The method is supposed to gracefully close the XMPP connection and the main goal is to make sure that the current
  473. * participant will be removed from the conference XMPP MUC, so that it doesn't leave a "ghost" participant behind.
  474. *
  475. * @param {Object} ev - Optionally, the event which triggered the necessity to disconnect from the XMPP server
  476. * (e.g. beforeunload, unload).
  477. * @private
  478. * @returns {void}
  479. */
  480. _cleanupXmppConnection(ev) {
  481. // XXX Strophe is asynchronously sending by default. Unfortunately, that means that there may not be enough time
  482. // to send an unavailable presence or disconnect at all. Switching Strophe to synchronous sending is not much of
  483. // an option because it may lead to a noticeable delay in navigating away from the current location. As
  484. // a compromise, we will try to increase the chances of sending an unavailable presence and/or disconnecting
  485. // within the short time span that we have upon unloading by invoking flush() on the connection. We flush() once
  486. // before disconnect() in order to attempt to have its unavailable presence at the top of the send queue. We
  487. // flush() once more after disconnect() in order to attempt to have its unavailable presence sent as soon as
  488. // possible.
  489. !this.connection.isUsingWebSocket && this.connection.flush();
  490. if (!this.connection.isUsingWebSocket && 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 (known) way to properly disconnect from
  494. // the XMPP server. Consequently, it may be fine to have the source code and comment it in or out
  495. // depending on whether we want to run with it for some time.
  496. this.connection.options.sync = true;
  497. // This is needed in some browsers where sync xhr sending is disabled by default on unload.
  498. if (navigator.sendBeacon && !this.connection.disconnecting && this.connection.connected) {
  499. this.connection.sendUnavailableBeacon();
  500. return;
  501. }
  502. }
  503. }
  504. this.connection.disconnect();
  505. if (this.connection.options.sync !== true) {
  506. this.connection.flush();
  507. }
  508. }
  509. /**
  510. *
  511. */
  512. _initStrophePlugins() {
  513. const iceConfig = {
  514. jvb: { iceServers: [ ] },
  515. p2p: { iceServers: [ ] }
  516. };
  517. const p2pStunServers = (this.options.p2p
  518. && this.options.p2p.stunServers) || DEFAULT_STUN_SERVERS;
  519. if (Array.isArray(p2pStunServers)) {
  520. logger.info('P2P STUN servers: ', p2pStunServers);
  521. iceConfig.p2p.iceServers = p2pStunServers;
  522. }
  523. if (this.options.p2p && this.options.p2p.iceTransportPolicy) {
  524. logger.info('P2P ICE transport policy: ',
  525. this.options.p2p.iceTransportPolicy);
  526. iceConfig.p2p.iceTransportPolicy
  527. = this.options.p2p.iceTransportPolicy;
  528. }
  529. this.connection.addConnectionPlugin('emuc', new MucConnectionPlugin(this));
  530. this.connection.addConnectionPlugin('jingle', new JingleConnectionPlugin(this, this.eventEmitter, iceConfig));
  531. this.connection.addConnectionPlugin('ping', new PingConnectionPlugin(this));
  532. this.connection.addConnectionPlugin('rayo', new RayoConnectionPlugin());
  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.lastResponseHeaders) {
  546. // split headers by line
  547. const headersArr = this.connection.lastResponseHeaders
  548. .trim().split(/[\r\n]+/);
  549. const headers = {};
  550. headersArr.forEach(line => {
  551. const parts = line.split(': ');
  552. const header = parts.shift();
  553. const value = parts.join(': ');
  554. headers[header] = value;
  555. });
  556. /* eslint-disable camelcase */
  557. details.shard_changed
  558. = this.options.deploymentInfo.shard
  559. !== headers['x-jitsi-shard'];
  560. /* eslint-enable camelcase */
  561. }
  562. /* eslint-disable camelcase */
  563. // check for possible suspend
  564. details.suspend_time = this.connection.ping.getPingSuspendTime();
  565. details.time_since_last_success = this.connection.getTimeSinceLastBOSHSuccess();
  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 plugins 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 (!(from === this.speakerStatsComponentAddress
  628. || from === this.conferenceDurationComponentAddress)) {
  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. if (parsedJson
  641. && parsedJson[JITSI_MEET_MUC_TYPE] === 'conference_duration'
  642. && parsedJson.created_timestamp) {
  643. this.eventEmitter.emit(
  644. XMPPEvents.CONFERENCE_TIMESTAMP_RECEIVED, parsedJson.created_timestamp);
  645. }
  646. return true;
  647. }
  648. }