modified lib-jitsi-meet dev repo
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 29KB

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