Você não pode selecionar mais de 25 tópicos Os tópicos devem começar com uma letra ou um número, podem incluir traços ('-') e podem ter até 35 caracteres.

xmpp.js 31KB

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