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.

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