Du kannst nicht mehr als 25 Themen auswählen Themen müssen mit entweder einem Buchstaben oder einer Ziffer beginnen. Sie können Bindestriche („-“) enthalten und bis zu 35 Zeichen lang sein.

moderator.js 23KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677
  1. /* eslint-disable newline-per-chained-call */
  2. import { getLogger } from '@jitsi/logger';
  3. import $ from 'jquery';
  4. import { $iq, Strophe } from 'strophe.js';
  5. import FeatureFlags from '../flags/FeatureFlags';
  6. import Settings from '../settings/Settings';
  7. import Listenable from '../util/Listenable';
  8. const AuthenticationEvents
  9. = require('../../service/authentication/AuthenticationEvents');
  10. const { XMPPEvents } = require('../../service/xmpp/XMPPEvents');
  11. const GlobalOnErrorHandler = require('../util/GlobalOnErrorHandler');
  12. const logger = getLogger(__filename);
  13. /**
  14. * Exponential backoff timer.
  15. * @param step the step to use.
  16. */
  17. function createExpBackoffTimer(step) {
  18. let count = 1;
  19. const maxTimeout = 120000;
  20. return function(reset) {
  21. // Reset call
  22. if (reset) {
  23. count = 1;
  24. return;
  25. }
  26. // Calculate next timeout
  27. const timeout = Math.pow(2, count - 1);
  28. count += 1;
  29. return Math.min(timeout * step, maxTimeout);
  30. };
  31. }
  32. /**
  33. * The moderator/focus responsible for direct communication with jicofo
  34. */
  35. export default class Moderator extends Listenable {
  36. /**
  37. * Constructs moderator.
  38. * @param xmpp The xmpp.
  39. */
  40. constructor(xmpp) {
  41. super();
  42. this.getNextTimeout = createExpBackoffTimer(1000);
  43. this.getNextErrorTimeout = createExpBackoffTimer(1000);
  44. this.options = xmpp.options;
  45. // External authentication stuff
  46. this.externalAuthEnabled = false;
  47. // Whether SIP gateway (jigasi) support is enabled. TODO: use presence so it can be changed based on jigasi
  48. // availability.
  49. this.sipGatewayEnabled = false;
  50. this.connection = xmpp.connection;
  51. // The JID to which conference-iq requests are sent over XMPP.
  52. this.targetJid = this.options.hosts?.focus;
  53. // If not specified default to 'focus.domain'
  54. if (!this.targetJid) {
  55. this.targetJid = `focus.${this.options.hosts?.domain}`;
  56. }
  57. this.targetUrl = this.options.conferenceRequestUrl;
  58. // Whether to send conference requests over HTTP or XMPP
  59. this.mode = this.targetUrl ? 'http' : 'xmpp';
  60. logger.info(`Using ${this.mode} for conference requests.`);
  61. // The set of JIDs known to belong to jicofo. Populated from configuration
  62. // and responses from conference requests.
  63. this.focusUserJids = new Set();
  64. if (this.options.focusUserJid) {
  65. this.focusUserJids.add(this.options.focusUserJid);
  66. }
  67. // FIXME: Message listener that talks to POPUP window
  68. /**
  69. *
  70. * @param event
  71. */
  72. function listener(event) {
  73. if (event.data && event.data.sessionId) {
  74. if (event.origin !== window.location.origin) {
  75. logger.warn(`Ignoring sessionId from different origin: ${event.origin}`);
  76. return;
  77. }
  78. Settings.sessionId = event.data.sessionId;
  79. // After popup is closed we will authenticate
  80. }
  81. }
  82. // Register
  83. if (window.addEventListener) {
  84. window.addEventListener('message', listener, false);
  85. } else {
  86. window.attachEvent('onmessage', listener);
  87. }
  88. }
  89. /**
  90. * Check whether the supplied jid is a known jid for focus.
  91. * @param jid
  92. * @returns {boolean}
  93. */
  94. isFocusJid(jid) {
  95. if (!jid) {
  96. return false;
  97. }
  98. for (const focusJid of this.focusUserJids) {
  99. // jid may be a full JID, and focusUserJids may be bare JIDs
  100. if (jid.indexOf(`${focusJid}/`) === 0) {
  101. return true;
  102. }
  103. }
  104. return false;
  105. }
  106. /**
  107. * Is external authentication enabled.
  108. * @returns {boolean}
  109. */
  110. isExternalAuthEnabled() {
  111. return this.externalAuthEnabled;
  112. }
  113. /**
  114. * Is sip gw enabled.
  115. * @returns {boolean}
  116. */
  117. isSipGatewayEnabled() {
  118. return this.sipGatewayEnabled;
  119. }
  120. /**
  121. * Create a conference request based on the configured options and saved Settings.
  122. *
  123. * A conference request has the following format:
  124. * {
  125. * room: "room@example.com",
  126. * sessionId: "foo", // optional
  127. * machineUdi: "bar", // optional
  128. * identity: "baz", // optional
  129. * properties: { } // map string to string
  130. * }
  131. *
  132. * It can be encoded in either JSON or and IQ.
  133. *
  134. * @param roomJid - The room jid for which to send conference request.
  135. *
  136. * @returns the created conference request.
  137. */
  138. _createConferenceRequest(roomJid) {
  139. // Session Id used for authentication
  140. const { sessionId } = Settings;
  141. const config = this.options;
  142. const properties = {};
  143. if (config.startAudioMuted !== undefined) {
  144. properties.startAudioMuted = config.startAudioMuted;
  145. }
  146. if (config.startVideoMuted !== undefined) {
  147. properties.startVideoMuted = config.startVideoMuted;
  148. }
  149. // this flag determines whether the bridge will include this call in its
  150. // rtcstats reporting or not. If the site admin hasn't set the flag in
  151. // config.js, then the client defaults to false (see
  152. // react/features/rtcstats/functions.js in jitsi-meet). The server-side
  153. // components default to true to match the pre-existing behavior, so we only
  154. // signal if false.
  155. const rtcstatsEnabled = config?.analytics?.rtcstatsEnabled ?? false;
  156. if (!rtcstatsEnabled) {
  157. properties.rtcstatsEnabled = false;
  158. }
  159. const conferenceRequest = {
  160. properties,
  161. machineUid: Settings.machineId,
  162. room: roomJid
  163. };
  164. if (sessionId) {
  165. conferenceRequest.sessionId = sessionId;
  166. }
  167. if (FeatureFlags.isJoinAsVisitorSupported()) {
  168. conferenceRequest.properties['visitors-version'] = 1;
  169. }
  170. return conferenceRequest;
  171. }
  172. /**
  173. * Create a conference request and encode it as an IQ.
  174. *
  175. * @param roomJid - The room jid for which to send conference request.
  176. */
  177. _createConferenceIq(roomJid) {
  178. const conferenceRequest = this._createConferenceRequest(roomJid);
  179. // Generate create conference IQ
  180. const elem = $iq({
  181. to: this.targetJid,
  182. type: 'set'
  183. });
  184. elem.c('conference', {
  185. xmlns: 'http://jitsi.org/protocol/focus',
  186. room: roomJid,
  187. 'machine-uid': conferenceRequest.machineUid
  188. });
  189. if (conferenceRequest.sessionId) {
  190. elem.attrs({ 'session-id': conferenceRequest.sessionId });
  191. }
  192. for (const k in conferenceRequest.properties) {
  193. if (conferenceRequest.properties.hasOwnProperty(k)) {
  194. elem.c(
  195. 'property', {
  196. name: k,
  197. value: conferenceRequest.properties[k]
  198. })
  199. .up();
  200. }
  201. }
  202. return elem;
  203. }
  204. /**
  205. * Parses a conference IQ.
  206. * @param resultIq the result IQ that is received.
  207. * @returns {{properties: {}}} Returns an object with the parsed properties.
  208. * @private
  209. */
  210. _parseConferenceIq(resultIq) {
  211. const conferenceRequest = { properties: {} };
  212. conferenceRequest.focusJid = $(resultIq)
  213. .find('conference')
  214. .attr('focusjid');
  215. conferenceRequest.sessionId = $(resultIq)
  216. .find('conference')
  217. .attr('session-id');
  218. conferenceRequest.identity = $(resultIq)
  219. .find('>conference')
  220. .attr('identity');
  221. conferenceRequest.ready = $(resultIq)
  222. .find('conference')
  223. .attr('ready') === 'true';
  224. conferenceRequest.vnode = $(resultIq)
  225. .find('conference')
  226. .attr('vnode');
  227. if ($(resultIq).find('>conference>property[name=\'authentication\'][value=\'true\']').length > 0) {
  228. conferenceRequest.properties.authentication = 'true';
  229. }
  230. if ($(resultIq).find('>conference>property[name=\'externalAuth\'][value=\'true\']').length > 0) {
  231. conferenceRequest.properties.externalAuth = 'true';
  232. }
  233. // Check if jicofo has jigasi support enabled.
  234. if ($(resultIq).find('>conference>property[name=\'sipGatewayEnabled\'][value=\'true\']').length > 0) {
  235. conferenceRequest.properties.sipGatewayEnabled = 'true';
  236. }
  237. return conferenceRequest;
  238. }
  239. // FIXME We need to show the fact that we're waiting for the focus to the user
  240. // (or that the focus is not available)
  241. /**
  242. * Allocates the conference focus.
  243. * @param roomJid - The room jid for which to send conference request.
  244. * @returns {Promise} - Resolved when Jicofo allows to join the room. It's never
  245. * rejected, and it'll keep on pinging Jicofo forever.
  246. */
  247. sendConferenceRequest(roomJid) {
  248. return new Promise(resolve => {
  249. if (this.mode === 'xmpp') {
  250. logger.info(`Sending conference request over XMPP to ${this.targetJid}`);
  251. this.connection.sendIQ(
  252. this._createConferenceIq(roomJid),
  253. result => this._handleIqSuccess(roomJid, result, resolve),
  254. error => this._handleIqError(roomJid, error, resolve));
  255. // XXX We're pressed for time here because we're beginning a complex
  256. // and/or lengthy conference-establishment process which supposedly
  257. // involves multiple RTTs. We don't have the time to wait for Strophe to
  258. // decide to send our IQ.
  259. this.connection.flush();
  260. } else {
  261. logger.info(`Sending conference request over HTTP to ${this.targetUrl}`);
  262. fetch(this.targetUrl, {
  263. method: 'POST',
  264. body: JSON.stringify(this._createConferenceRequest(roomJid)),
  265. headers: { 'Content-Type': 'application/json' }
  266. })
  267. .then(response => {
  268. if (!response.ok) {
  269. response.text()
  270. .then(text => {
  271. logger.warn(`Received HTTP ${response.status} ${
  272. response.statusText}. Body: ${text}`);
  273. const sessionError = response.status === 400
  274. && text.indexOf('400 invalid-session') > 0;
  275. const notAuthorized = response.status === 403;
  276. this._handleError(roomJid, sessionError, notAuthorized, resolve);
  277. })
  278. .catch(error => {
  279. logger.warn(`Error: ${error}`);
  280. this._handleError(roomJid);
  281. });
  282. // _handleError has either scheduled a retry or fired an event indicating failure.
  283. return;
  284. }
  285. response.json()
  286. .then(resultJson => {
  287. this._handleSuccess(roomJid, resultJson, resolve);
  288. });
  289. })
  290. .catch(error => {
  291. logger.warn(`Error: ${error}`);
  292. this._handleError(roomJid);
  293. });
  294. }
  295. });
  296. }
  297. /**
  298. * Handles success response for conference IQ.
  299. * @param roomJid
  300. * @param conferenceRequest
  301. * @param callback
  302. * @private
  303. */
  304. _handleSuccess(roomJid, conferenceRequest, callback) {
  305. // Reset the error timeout (because we haven't failed here).
  306. this.getNextErrorTimeout(true);
  307. if (conferenceRequest.focusJid) {
  308. logger.info(`Adding focus JID: ${conferenceRequest.focusJid}`);
  309. this.focusUserJids.add(conferenceRequest.focusJid);
  310. } else {
  311. logger.warn('Conference request response contained no focusJid.');
  312. }
  313. const authenticationEnabled = conferenceRequest.properties.authentication === 'true';
  314. logger.info(`Authentication enabled: ${authenticationEnabled}`);
  315. this.externalAuthEnabled = conferenceRequest.properties.externalAuth === 'true';
  316. logger.info(`External authentication enabled: ${this.externalAuthEnabled}`);
  317. if (!this.externalAuthEnabled && conferenceRequest.sessionId) {
  318. logger.info(`Received sessionId: ${conferenceRequest.sessionId}`);
  319. Settings.sessionId = conferenceRequest.sessionId;
  320. }
  321. this.eventEmitter.emit(
  322. AuthenticationEvents.IDENTITY_UPDATED, authenticationEnabled, conferenceRequest.identity);
  323. this.sipGatewayEnabled = conferenceRequest.properties.sipGatewayEnabled;
  324. logger.info(`Sip gateway enabled: ${this.sipGatewayEnabled}`);
  325. if (conferenceRequest.ready) {
  326. // Reset the non-error timeout (because we've succeeded here).
  327. this.getNextTimeout(true);
  328. // we want to ignore redirects when this is jibri (record/live-stream or a sip jibri)
  329. if (conferenceRequest.vnode && !this.options.iAmRecorder && !this.options.iAmSipGateway) {
  330. logger.warn(`Redirected to: ${conferenceRequest.vnode} with focusJid ${conferenceRequest.focusJid} }`);
  331. this.eventEmitter.emit(XMPPEvents.REDIRECTED, conferenceRequest.vnode, conferenceRequest.focusJid);
  332. return;
  333. }
  334. logger.info('Conference-request successful, ready to join the MUC.');
  335. callback();
  336. } else {
  337. const waitMs = this.getNextTimeout();
  338. // This was a successful response, but the "ready" flag is not set. Retry after a timeout.
  339. logger.info(`Not ready yet, will retry in ${waitMs} ms.`);
  340. window.setTimeout(
  341. () => this.sendConferenceRequest(roomJid)
  342. .then(callback),
  343. waitMs);
  344. }
  345. }
  346. /**
  347. * Handles error response for conference IQ.
  348. * @param roomJid
  349. * @param sessionError
  350. * @param notAuthorized
  351. * @param callback
  352. * @private
  353. */
  354. _handleError(roomJid, sessionError, notAuthorized, callback) {
  355. // If the session is invalid, remove and try again without session ID to get
  356. // a new one
  357. if (sessionError) {
  358. logger.info('Session expired! - removing');
  359. Settings.sessionId = undefined;
  360. }
  361. // Not authorized to create new room
  362. if (notAuthorized) {
  363. logger.warn('Unauthorized to start the conference');
  364. this.eventEmitter.emit(XMPPEvents.AUTHENTICATION_REQUIRED);
  365. return;
  366. }
  367. const waitMs = this.getNextErrorTimeout();
  368. if (sessionError && waitMs < 60000) {
  369. // If the session is invalid, retry a limited number of times and then fire an error.
  370. logger.info(`Invalid session, will retry after ${waitMs} ms.`);
  371. this.getNextTimeout(true);
  372. window.setTimeout(() => this.sendConferenceRequest(roomJid)
  373. .then(callback), waitMs);
  374. } else {
  375. const errmsg = 'Failed to get a successful response, giving up.';
  376. const error = new Error(errmsg);
  377. logger.error(errmsg, error);
  378. GlobalOnErrorHandler.callErrorHandler(error);
  379. // This is a "fatal" error and the user of the lib should handle it accordingly.
  380. // TODO: change the event name to something accurate.
  381. this.eventEmitter.emit(XMPPEvents.FOCUS_DISCONNECTED);
  382. }
  383. }
  384. /**
  385. * Invoked by {@link #sendConferenceRequest} upon its request receiving an xmpp error result.
  386. *
  387. * @param roomJid - The room jid used to send conference request.
  388. * @param error - the error result of the request that {@link sendConferenceRequest} sent
  389. * @param {Function} callback - the function to be called back upon the
  390. * successful allocation of the conference focus
  391. */
  392. _handleIqError(roomJid, error, callback) {
  393. // The reservation system only works over XMPP. Handle the error separately.
  394. // Check for error returned by the reservation system
  395. const reservationErr = $(error).find('>error>reservation-error');
  396. if (reservationErr.length) {
  397. // Trigger error event
  398. const errorCode = reservationErr.attr('error-code');
  399. const errorTextNode = $(error).find('>error>text');
  400. let errorMsg;
  401. if (errorTextNode) {
  402. errorMsg = errorTextNode.text();
  403. }
  404. this.eventEmitter.emit(
  405. XMPPEvents.RESERVATION_ERROR,
  406. errorCode,
  407. errorMsg);
  408. return;
  409. }
  410. const invalidSession = Boolean($(error).find('>error>session-invalid').length
  411. || $(error).find('>error>not-acceptable').length);
  412. // Not authorized to create new room
  413. const notAuthorized = $(error).find('>error>not-authorized').length > 0;
  414. if (notAuthorized
  415. && Strophe.getDomainFromJid(error.getAttribute('to')) !== this.options.hosts.anonymousdomain) {
  416. // FIXME "is external" should come either from the focus or
  417. // config.js
  418. this.externalAuthEnabled = true;
  419. }
  420. this._handleError(roomJid, invalidSession, notAuthorized, callback);
  421. }
  422. /**
  423. * Invoked by {@link #sendConferenecRequest} upon its request receiving a
  424. * success (i.e. non-error) result.
  425. *
  426. * @param roomJid - The room jid used to send conference request.
  427. * @param result - the success (i.e. non-error) result of the request that {@link #sendConferenecRequest} sent
  428. * @param {Function} callback - the function to be called back upon the
  429. * successful allocation of the conference focus
  430. */
  431. _handleIqSuccess(roomJid, result, callback) {
  432. // Setup config options
  433. const conferenceRequest = this._parseConferenceIq(result);
  434. this._handleSuccess(roomJid, conferenceRequest, callback);
  435. }
  436. /**
  437. * Authenticate by sending a conference IQ.
  438. * @param roomJid The room jid.
  439. * @returns {Promise<unknown>}
  440. */
  441. authenticate(roomJid) {
  442. return new Promise((resolve, reject) => {
  443. this.connection.sendIQ(
  444. this._createConferenceIq(roomJid),
  445. result => {
  446. const sessionId = $(result)
  447. .find('conference')
  448. .attr('session-id');
  449. if (sessionId) {
  450. logger.info(`Received sessionId: ${sessionId}`);
  451. Settings.sessionId = sessionId;
  452. } else {
  453. logger.warn('Response did not contain a session-id');
  454. }
  455. resolve();
  456. },
  457. errorIq => reject({
  458. error: $(errorIq)
  459. .find('iq>error :first')
  460. .prop('tagName'),
  461. message: $(errorIq)
  462. .find('iq>error>text')
  463. .text()
  464. })
  465. );
  466. });
  467. }
  468. /**
  469. * Gets the login URL by requesting it to jicofo.
  470. * @param roomJid The room jid to use.
  471. * @param urlCallback The success callback.
  472. * @param failureCallback The error callback.
  473. */
  474. getLoginUrl(roomJid, urlCallback, failureCallback) {
  475. this._getLoginUrl(roomJid, /* popup */ false, urlCallback, failureCallback);
  476. }
  477. /**
  478. * Gets the login URL by requesting it to jicofo.
  479. * @param {boolean} popup false for {@link Moderator#getLoginUrl} or true for
  480. * {@link Moderator#getPopupLoginUrl}
  481. * @param roomJid - The room jid to use.
  482. * @param urlCb
  483. * @param failureCb
  484. */
  485. _getLoginUrl(roomJid, popup, urlCb, failureCb) {
  486. const iq = $iq({
  487. to: this.targetJid,
  488. type: 'get'
  489. });
  490. const attrs = {
  491. xmlns: 'http://jitsi.org/protocol/focus',
  492. room: roomJid,
  493. 'machine-uid': Settings.machineId
  494. };
  495. let str = 'auth url'; // for logger
  496. if (popup) {
  497. attrs.popup = true;
  498. str = `POPUP ${str}`;
  499. }
  500. iq.c('login-url', attrs);
  501. /**
  502. * Implements a failure callback which reports an error message and an error
  503. * through (1) GlobalOnErrorHandler, (2) logger, and (3) failureCb.
  504. *
  505. * @param {string} errmsg the error messsage to report
  506. * @param {*} error the error to report (in addition to errmsg)
  507. */
  508. function reportError(errmsg, err) {
  509. GlobalOnErrorHandler.callErrorHandler(new Error(errmsg));
  510. logger.error(errmsg, err);
  511. failureCb(err);
  512. }
  513. this.connection.sendIQ(
  514. iq,
  515. result => {
  516. let url = $(result)
  517. .find('login-url')
  518. .attr('url');
  519. url = decodeURIComponent(url);
  520. if (url) {
  521. logger.info(`Got ${str}: ${url}`);
  522. urlCb(url);
  523. } else {
  524. reportError(`Failed to get ${str} from the focus`, result);
  525. }
  526. },
  527. reportError.bind(undefined, `Get ${str} error`)
  528. );
  529. }
  530. /**
  531. * Gets the login URL by requesting it to jicofo.
  532. * @param roomJid The room jid to use.
  533. * @param urlCallback The success callback.
  534. * @param failureCallback The error callback.
  535. */
  536. getPopupLoginUrl(roomJid, urlCallback, failureCallback) {
  537. this._getLoginUrl(roomJid, /* popup */ true, urlCallback, failureCallback);
  538. }
  539. /**
  540. * Logout by sending conference IQ.
  541. * @param callback
  542. */
  543. logout(callback) {
  544. const iq = $iq({
  545. to: this.targetJid,
  546. type: 'set'
  547. });
  548. const { sessionId } = Settings;
  549. if (!sessionId) {
  550. callback();
  551. return;
  552. }
  553. iq.c('logout', {
  554. xmlns: 'http://jitsi.org/protocol/focus',
  555. 'session-id': sessionId
  556. });
  557. this.connection.sendIQ(
  558. iq,
  559. result => {
  560. let logoutUrl = $(result)
  561. .find('logout')
  562. .attr('logout-url');
  563. if (logoutUrl) {
  564. logoutUrl = decodeURIComponent(logoutUrl);
  565. }
  566. logger.info(`Log out OK, url: ${logoutUrl}`, result);
  567. Settings.sessionId = undefined;
  568. callback(logoutUrl);
  569. },
  570. error => {
  571. const errmsg = 'Logout error';
  572. GlobalOnErrorHandler.callErrorHandler(new Error(errmsg));
  573. logger.error(errmsg, error);
  574. }
  575. );
  576. }
  577. }