modified lib-jitsi-meet dev repo
Nevar pievienot vairāk kā 25 tēmas Tēmai ir jāsākas ar burtu vai ciparu, tā var saturēt domu zīmes ('-') un var būt līdz 35 simboliem gara.

xmpp.js 28KB

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