您最多选择25个主题 主题必须以字母或数字开头,可以包含连字符 (-),并且长度不得超过35个字符

moderator.js 21KB

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