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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779
  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 === true) {
  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 = Boolean(this.disconnectInProgress);
  255. const errMsg = msg || this.lastErrorMsg;
  256. if (this.anonymousConnectionFailed) {
  257. // prompt user for username and password
  258. this.eventEmitter.emit(
  259. JitsiConnectionEvents.CONNECTION_FAILED,
  260. JitsiConnectionErrors.PASSWORD_REQUIRED);
  261. } else if (this.connectionFailed) {
  262. this.eventEmitter.emit(
  263. JitsiConnectionEvents.CONNECTION_FAILED,
  264. JitsiConnectionErrors.OTHER_ERROR,
  265. errMsg,
  266. undefined, /* credentials */
  267. this._getConnectionFailedReasonDetails());
  268. } else if (wasIntentionalDisconnect) {
  269. this.eventEmitter.emit(
  270. JitsiConnectionEvents.CONNECTION_DISCONNECTED, errMsg);
  271. } else {
  272. // XXX if Strophe drops the connection while not being asked to,
  273. // it means that most likely some serious error has occurred.
  274. // One currently known case is when a BOSH request fails for
  275. // more than 4 times. The connection is dropped without
  276. // supplying a reason(error message/event) through the API.
  277. logger.error('XMPP connection dropped!');
  278. // XXX if the last request error is within 5xx range it means it
  279. // was a server failure
  280. const lastErrorStatus = Strophe.getLastErrorStatus();
  281. if (lastErrorStatus >= 500 && lastErrorStatus < 600) {
  282. this.eventEmitter.emit(
  283. JitsiConnectionEvents.CONNECTION_FAILED,
  284. JitsiConnectionErrors.SERVER_ERROR,
  285. errMsg || 'server-error',
  286. /* credentials */ undefined,
  287. this._getConnectionFailedReasonDetails());
  288. } else {
  289. this.eventEmitter.emit(
  290. JitsiConnectionEvents.CONNECTION_FAILED,
  291. JitsiConnectionErrors.CONNECTION_DROPPED_ERROR,
  292. errMsg || 'connection-dropped-error',
  293. /* credentials */ undefined,
  294. this._getConnectionFailedReasonDetails());
  295. }
  296. }
  297. } else if (status === Strophe.Status.AUTHFAIL) {
  298. // wrong password or username, prompt user
  299. this.eventEmitter.emit(
  300. JitsiConnectionEvents.CONNECTION_FAILED,
  301. JitsiConnectionErrors.PASSWORD_REQUIRED,
  302. msg,
  303. credentials);
  304. }
  305. }
  306. /**
  307. *
  308. * @param jid
  309. * @param password
  310. */
  311. _connect(jid, password) {
  312. // connection.connect() starts the connection process.
  313. //
  314. // As the connection process proceeds, the user supplied callback will
  315. // be triggered multiple times with status updates. The callback should
  316. // take two arguments - the status code and the error condition.
  317. //
  318. // The status code will be one of the values in the Strophe.Status
  319. // constants. The error condition will be one of the conditions defined
  320. // in RFC 3920 or the condition ‘strophe-parsererror’.
  321. //
  322. // The Parameters wait, hold and route are optional and only relevant
  323. // for BOSH connections. Please see XEP 124 for a more detailed
  324. // explanation of the optional parameters.
  325. //
  326. // Connection status constants for use by the connection handler
  327. // callback.
  328. //
  329. // Status.ERROR - An error has occurred (websockets specific)
  330. // Status.CONNECTING - The connection is currently being made
  331. // Status.CONNFAIL - The connection attempt failed
  332. // Status.AUTHENTICATING - The connection is authenticating
  333. // Status.AUTHFAIL - The authentication attempt failed
  334. // Status.CONNECTED - The connection has succeeded
  335. // Status.DISCONNECTED - The connection has been terminated
  336. // Status.DISCONNECTING - The connection is currently being terminated
  337. // Status.ATTACHED - The connection has been attached
  338. this._resetState();
  339. this.connection.connect(
  340. jid,
  341. password,
  342. this.connectionHandler.bind(this, {
  343. jid,
  344. password
  345. }));
  346. }
  347. /**
  348. * Attach to existing connection. Can be used for optimizations. For
  349. * example: if the connection is created on the server we can attach to it
  350. * and start using it.
  351. *
  352. * @param options {object} connecting options - rid, sid, jid and password.
  353. */
  354. attach(options) {
  355. this._resetState();
  356. const now = this.connectionTimes.attaching = window.performance.now();
  357. logger.log('(TIME) Strophe Attaching:\t', now);
  358. this.connection.attach(options.jid, options.sid,
  359. parseInt(options.rid, 10) + 1,
  360. this.connectionHandler.bind(this, {
  361. jid: options.jid,
  362. password: options.password
  363. }));
  364. }
  365. /**
  366. * Resets any state/flag before starting a new connection.
  367. * @private
  368. */
  369. _resetState() {
  370. this.anonymousConnectionFailed = false;
  371. this.connectionFailed = false;
  372. this.lastErrorMsg = undefined;
  373. this.disconnectInProgress = undefined;
  374. }
  375. /**
  376. *
  377. * @param jid
  378. * @param password
  379. */
  380. connect(jid, password) {
  381. if (!jid) {
  382. const { anonymousdomain, domain } = this.options.hosts;
  383. let configDomain = anonymousdomain || domain;
  384. // Force authenticated domain if room is appended with '?login=true'
  385. // or if we're joining with the token
  386. // FIXME Do not rely on window.location because (1) React Native
  387. // does not have a window.location by default and (2) here we cannot
  388. // know for sure that query/search has not be stripped from
  389. // window.location by the time the following executes.
  390. const { location } = window;
  391. if (anonymousdomain) {
  392. const search = location && location.search;
  393. if ((search && search.indexOf('login=true') !== -1)
  394. || this.token) {
  395. configDomain = domain;
  396. }
  397. }
  398. // eslint-disable-next-line no-param-reassign
  399. jid = configDomain || (location && location.hostname);
  400. }
  401. return this._connect(jid, password);
  402. }
  403. /**
  404. * Joins or creates a muc with the provided jid, created from the passed
  405. * in room name and muc host and onCreateResource result.
  406. *
  407. * @param {string} roomName - The name of the muc to join.
  408. * @param {Object} options - Configuration for how to join the muc.
  409. * @param {Function} [onCreateResource] - Callback to invoke when a resource
  410. * is to be added to the jid.
  411. * @returns {Promise} Resolves with an instance of a strophe muc.
  412. */
  413. createRoom(roomName, options, onCreateResource) {
  414. let roomjid = `${roomName}@${this.options.hosts.muc}/`;
  415. const mucNickname = onCreateResource
  416. ? onCreateResource(this.connection.jid, this.authenticatedUser)
  417. : RandomUtil.randomHexString(8).toLowerCase();
  418. logger.info(`JID ${this.connection.jid} using MUC nickname ${mucNickname}`);
  419. roomjid += mucNickname;
  420. return this.connection.emuc.createRoom(roomjid, null, options);
  421. }
  422. /**
  423. * Returns the jid of the participant associated with the Strophe connection.
  424. *
  425. * @returns {string} The jid of the participant.
  426. */
  427. getJid() {
  428. return this.connection.jid;
  429. }
  430. /**
  431. * Returns the logs from strophe.jingle.
  432. * @returns {Object}
  433. */
  434. getJingleLog() {
  435. const jingle = this.connection.jingle;
  436. return jingle ? jingle.getLog() : {};
  437. }
  438. /**
  439. * Returns the logs from strophe.
  440. */
  441. getXmppLog() {
  442. return (this.connection.logger || {}).log || null;
  443. }
  444. /**
  445. *
  446. */
  447. dial(...args) {
  448. this.connection.rayo.dial(...args);
  449. }
  450. /**
  451. * Pings the server. Remember to check {@link isPingSupported} before using
  452. * this method.
  453. * @param timeout how many ms before a timeout should occur.
  454. * @returns {Promise} resolved on ping success and reject on an error or
  455. * a timeout.
  456. */
  457. ping(timeout) {
  458. return new Promise((resolve, reject) => {
  459. if (this.isPingSupported()) {
  460. this.connection.ping
  461. .ping(this.connection.domain, resolve, reject, timeout);
  462. } else {
  463. reject('PING operation is not supported by the server');
  464. }
  465. });
  466. }
  467. /**
  468. *
  469. */
  470. getSessions() {
  471. return this.connection.jingle.sessions;
  472. }
  473. /**
  474. * Disconnects this from the XMPP server (if this is connected).
  475. *
  476. * @param {Object} ev - Optionally, the event which triggered the necessity to
  477. * disconnect from the XMPP server (e.g. beforeunload, unload).
  478. * @returns {Promise} - Resolves when the disconnect process is finished or rejects with an error.
  479. */
  480. disconnect(ev) {
  481. if (this.disconnectInProgress) {
  482. return this.disconnectInProgress;
  483. } else if (!this.connection) {
  484. return Promise.resolve();
  485. }
  486. this.disconnectInProgress = new Promise(resolve => {
  487. const disconnectListener = (credentials, status) => {
  488. if (status === Strophe.Status.DISCONNECTED) {
  489. resolve();
  490. this.eventEmitter.removeListener(XMPPEvents.CONNECTION_STATUS_CHANGED, disconnectListener);
  491. }
  492. };
  493. this.eventEmitter.on(XMPPEvents.CONNECTION_STATUS_CHANGED, disconnectListener);
  494. });
  495. this._cleanupXmppConnection(ev);
  496. return this.disconnectInProgress;
  497. }
  498. /**
  499. * The method is supposed to gracefully close the XMPP connection and the main goal is to make sure that the current
  500. * participant will be removed from the conference XMPP MUC, so that it doesn't leave a "ghost" participant behind.
  501. *
  502. * @param {Object} ev - Optionally, the event which triggered the necessity to disconnect from the XMPP server
  503. * (e.g. beforeunload, unload).
  504. * @private
  505. * @returns {void}
  506. */
  507. _cleanupXmppConnection(ev) {
  508. // XXX Strophe is asynchronously sending by default. Unfortunately, that means that there may not be enough time
  509. // to send an unavailable presence or disconnect at all. Switching Strophe to synchronous sending is not much of
  510. // an option because it may lead to a noticeable delay in navigating away from the current location. As
  511. // a compromise, we will try to increase the chances of sending an unavailable presence and/or disconnecting
  512. // within the short time span that we have upon unloading by invoking flush() on the connection. We flush() once
  513. // before disconnect() in order to attempt to have its unavailable presence at the top of the send queue. We
  514. // flush() once more after disconnect() in order to attempt to have its unavailable presence sent as soon as
  515. // possible.
  516. !this.connection.isUsingWebSocket && this.connection.flush();
  517. if (!this.connection.isUsingWebSocket && ev !== null && typeof ev !== 'undefined') {
  518. const evType = ev.type;
  519. if (evType === 'beforeunload' || evType === 'unload') {
  520. // XXX Whatever we said above, synchronous sending is the best (known) way to properly disconnect from
  521. // the XMPP server. Consequently, it may be fine to have the source code and comment it in or out
  522. // depending on whether we want to run with it for some time.
  523. this.connection.options.sync = true;
  524. // This is needed in some browsers where sync xhr sending is disabled by default on unload.
  525. if (this.connection.sendUnavailableBeacon()) {
  526. return;
  527. }
  528. }
  529. }
  530. this.connection.disconnect();
  531. if (this.connection.options.sync !== true) {
  532. this.connection.flush();
  533. }
  534. }
  535. /**
  536. *
  537. */
  538. _initStrophePlugins() {
  539. const iceConfig = {
  540. jvb: { iceServers: [ ] },
  541. p2p: { iceServers: [ ] }
  542. };
  543. const p2pStunServers = (this.options.p2p
  544. && this.options.p2p.stunServers) || DEFAULT_STUN_SERVERS;
  545. if (Array.isArray(p2pStunServers)) {
  546. logger.info('P2P STUN servers: ', p2pStunServers);
  547. iceConfig.p2p.iceServers = p2pStunServers;
  548. }
  549. if (this.options.p2p && this.options.p2p.iceTransportPolicy) {
  550. logger.info('P2P ICE transport policy: ',
  551. this.options.p2p.iceTransportPolicy);
  552. iceConfig.p2p.iceTransportPolicy
  553. = this.options.p2p.iceTransportPolicy;
  554. }
  555. this.connection.addConnectionPlugin('emuc', new MucConnectionPlugin(this));
  556. this.connection.addConnectionPlugin('jingle', new JingleConnectionPlugin(this, this.eventEmitter, iceConfig));
  557. this.connection.addConnectionPlugin('ping', new PingConnectionPlugin(this));
  558. this.connection.addConnectionPlugin('rayo', new RayoConnectionPlugin());
  559. }
  560. /**
  561. * Returns details about connection failure. Shard change or is it after
  562. * suspend.
  563. * @returns {object} contains details about a connection failure.
  564. * @private
  565. */
  566. _getConnectionFailedReasonDetails() {
  567. const details = {};
  568. // check for moving between shard if information is available
  569. if (this.options.deploymentInfo
  570. && this.options.deploymentInfo.shard
  571. && this.connection.lastResponseHeaders) {
  572. // split headers by line
  573. const headersArr = this.connection.lastResponseHeaders
  574. .trim().split(/[\r\n]+/);
  575. const headers = {};
  576. headersArr.forEach(line => {
  577. const parts = line.split(': ');
  578. const header = parts.shift();
  579. const value = parts.join(': ');
  580. headers[header] = value;
  581. });
  582. /* eslint-disable camelcase */
  583. details.shard_changed
  584. = this.options.deploymentInfo.shard
  585. !== headers['x-jitsi-shard'];
  586. /* eslint-enable camelcase */
  587. }
  588. /* eslint-disable camelcase */
  589. // check for possible suspend
  590. details.suspend_time = this.connection.ping.getPingSuspendTime();
  591. details.time_since_last_success = this.connection.getTimeSinceLastSuccess();
  592. /* eslint-enable camelcase */
  593. return details;
  594. }
  595. /**
  596. * Notifies speaker stats component if available that we are the new
  597. * dominant speaker in the conference.
  598. * @param {String} roomJid - The room jid where the speaker event occurred.
  599. */
  600. sendDominantSpeakerEvent(roomJid) {
  601. // no speaker stats component advertised
  602. if (!this.speakerStatsComponentAddress || !roomJid) {
  603. return;
  604. }
  605. const msg = $msg({ to: this.speakerStatsComponentAddress });
  606. msg.c('speakerstats', {
  607. xmlns: 'http://jitsi.org/jitmeet',
  608. room: roomJid })
  609. .up();
  610. this.connection.send(msg);
  611. }
  612. /**
  613. * Check if the given argument is a valid JSON ENDPOINT_MESSAGE string by
  614. * parsing it and checking if it has a field called 'type'.
  615. *
  616. * @param {string} jsonString check if this string is a valid json string
  617. * and contains the special structure.
  618. * @returns {boolean, object} if given object is a valid JSON string, return
  619. * the json object. Otherwise, returns false.
  620. */
  621. tryParseJSONAndVerify(jsonString) {
  622. try {
  623. const json = JSON.parse(jsonString);
  624. // Handle non-exception-throwing cases:
  625. // Neither JSON.parse(false) or JSON.parse(1234) throw errors,
  626. // hence the type-checking,
  627. // but... JSON.parse(null) returns null, and
  628. // typeof null === "object",
  629. // so we must check for that, too.
  630. // Thankfully, null is falsey, so this suffices:
  631. if (json && typeof json === 'object') {
  632. const type = json[JITSI_MEET_MUC_TYPE];
  633. if (typeof type !== 'undefined') {
  634. return json;
  635. }
  636. logger.debug('parsing valid json but does not have correct '
  637. + 'structure', 'topic: ', type);
  638. }
  639. } catch (e) {
  640. return false;
  641. }
  642. return false;
  643. }
  644. /**
  645. * A private message is received, message that is not addressed to the muc.
  646. * We expect private message coming from plugins component if it is
  647. * enabled and running.
  648. *
  649. * @param {string} msg - The message.
  650. */
  651. _onPrivateMessage(msg) {
  652. const from = msg.getAttribute('from');
  653. if (!(from === this.speakerStatsComponentAddress
  654. || from === this.conferenceDurationComponentAddress)) {
  655. return;
  656. }
  657. const jsonMessage = $(msg).find('>json-message')
  658. .text();
  659. const parsedJson = this.tryParseJSONAndVerify(jsonMessage);
  660. if (parsedJson
  661. && parsedJson[JITSI_MEET_MUC_TYPE] === 'speakerstats'
  662. && parsedJson.users) {
  663. this.eventEmitter.emit(
  664. XMPPEvents.SPEAKER_STATS_RECEIVED, parsedJson.users);
  665. }
  666. if (parsedJson
  667. && parsedJson[JITSI_MEET_MUC_TYPE] === 'conference_duration'
  668. && parsedJson.created_timestamp) {
  669. this.eventEmitter.emit(
  670. XMPPEvents.CONFERENCE_TIMESTAMP_RECEIVED, parsedJson.created_timestamp);
  671. }
  672. return true;
  673. }
  674. }