modified lib-jitsi-meet dev repo
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.

moderator.js 16KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537
  1. import { getLogger } from '@jitsi/logger';
  2. import $ from 'jquery';
  3. import { $iq, Strophe } from 'strophe.js';
  4. import Settings from '../settings/Settings';
  5. const AuthenticationEvents
  6. = require('../../service/authentication/AuthenticationEvents');
  7. const { XMPPEvents } = require('../../service/xmpp/XMPPEvents');
  8. const GlobalOnErrorHandler = require('../util/GlobalOnErrorHandler');
  9. const logger = getLogger(__filename);
  10. /**
  11. *
  12. * @param step
  13. */
  14. function createExpBackoffTimer(step) {
  15. let count = 1;
  16. return function(reset) {
  17. // Reset call
  18. if (reset) {
  19. count = 1;
  20. return;
  21. }
  22. // Calculate next timeout
  23. const timeout = Math.pow(2, count - 1);
  24. count += 1;
  25. return timeout * step;
  26. };
  27. }
  28. /* eslint-disable max-params */
  29. /**
  30. *
  31. * @param roomName
  32. * @param xmpp
  33. * @param emitter
  34. * @param options
  35. */
  36. export default function Moderator(roomName, xmpp, emitter, options) {
  37. this.roomName = roomName;
  38. this.xmppService = xmpp;
  39. this.getNextTimeout = createExpBackoffTimer(1000);
  40. this.getNextErrorTimeout = createExpBackoffTimer(1000);
  41. // External authentication stuff
  42. this.externalAuthEnabled = false;
  43. this.options = options;
  44. // Whether SIP gateway (jigasi) support is enabled. This is set
  45. // based on conference properties received in presence.
  46. this.sipGatewayEnabled = false;
  47. this.eventEmitter = emitter;
  48. this.connection = this.xmppService.connection;
  49. // FIXME: Message listener that talks to POPUP window
  50. /**
  51. *
  52. * @param event
  53. */
  54. function listener(event) {
  55. if (event.data && event.data.sessionId) {
  56. if (event.origin !== window.location.origin) {
  57. logger.warn(
  58. `Ignoring sessionId from different origin: ${
  59. event.origin}`);
  60. return;
  61. }
  62. Settings.sessionId = event.data.sessionId;
  63. // After popup is closed we will authenticate
  64. }
  65. }
  66. // Register
  67. if (window.addEventListener) {
  68. window.addEventListener('message', listener, false);
  69. } else {
  70. window.attachEvent('onmessage', listener);
  71. }
  72. }
  73. /* eslint-enable max-params */
  74. Moderator.prototype.isExternalAuthEnabled = function() {
  75. return this.externalAuthEnabled;
  76. };
  77. Moderator.prototype.isSipGatewayEnabled = function() {
  78. return this.sipGatewayEnabled;
  79. };
  80. Moderator.prototype.onMucMemberLeft = function(jid) {
  81. const resource = Strophe.getResourceFromJid(jid);
  82. if (resource === 'focus') {
  83. logger.info(
  84. 'Focus has left the room - leaving conference');
  85. this.eventEmitter.emit(XMPPEvents.FOCUS_LEFT);
  86. }
  87. };
  88. Moderator.prototype.setFocusUserJid = function(focusJid) {
  89. if (!this.focusUserJid) {
  90. this.focusUserJid = focusJid;
  91. logger.info(`Focus jid set to: ${this.focusUserJid}`);
  92. }
  93. };
  94. Moderator.prototype.getFocusUserJid = function() {
  95. return this.focusUserJid;
  96. };
  97. Moderator.prototype.getFocusComponent = function() {
  98. // Get focus component address
  99. let focusComponent = this.options.connection.hosts.focus;
  100. // If not specified use default: 'focus.domain'
  101. if (!focusComponent) {
  102. focusComponent = `focus.${this.options.connection.hosts.domain}`;
  103. }
  104. return focusComponent;
  105. };
  106. Moderator.prototype.createConferenceIq = function() {
  107. // Generate create conference IQ
  108. const elem = $iq({ to: this.getFocusComponent(),
  109. type: 'set' });
  110. // Session Id used for authentication
  111. const { sessionId } = Settings;
  112. const machineUID = Settings.machineId;
  113. const config = this.options.conference;
  114. logger.info(`Session ID: ${sessionId} machine UID: ${machineUID}`);
  115. elem.c('conference', {
  116. xmlns: 'http://jitsi.org/protocol/focus',
  117. room: this.roomName,
  118. 'machine-uid': machineUID
  119. });
  120. if (sessionId) {
  121. elem.attrs({ 'session-id': sessionId });
  122. }
  123. if (config.startBitrate) {
  124. elem.c(
  125. 'property', {
  126. name: 'startBitrate',
  127. value: config.startBitrate
  128. }).up();
  129. }
  130. if (config.minBitrate) {
  131. elem.c(
  132. 'property', {
  133. name: 'minBitrate',
  134. value: config.minBitrate
  135. }).up();
  136. }
  137. if (this.options.conference.startAudioMuted !== undefined) {
  138. elem.c(
  139. 'property', {
  140. name: 'startAudioMuted',
  141. value: this.options.conference.startAudioMuted
  142. }).up();
  143. }
  144. if (this.options.conference.startVideoMuted !== undefined) {
  145. elem.c(
  146. 'property', {
  147. name: 'startVideoMuted',
  148. value: this.options.conference.startVideoMuted
  149. }).up();
  150. }
  151. // this flag determines whether the bridge will include this call in its
  152. // rtcstats reporting or not. If the site admin hasn't set the flag in
  153. // config.js, then the client defaults to false (see
  154. // react/features/rtcstats/functions.js in jitsi-meet). The server-side
  155. // components default to true to match the pre-existing behavior so we only
  156. // signal if false.
  157. const rtcstatsEnabled = this.options.conference?.analytics?.rtcstatsEnabled ?? false;
  158. if (!rtcstatsEnabled) {
  159. elem.c(
  160. 'property', {
  161. name: 'rtcstatsEnabled',
  162. value: false
  163. }).up();
  164. }
  165. return elem;
  166. };
  167. Moderator.prototype.parseSessionId = function(resultIq) {
  168. // eslint-disable-next-line newline-per-chained-call
  169. const sessionId = $(resultIq).find('conference').attr('session-id');
  170. if (sessionId) {
  171. logger.info(`Received sessionId: ${sessionId}`);
  172. Settings.sessionId = sessionId;
  173. }
  174. };
  175. Moderator.prototype.parseConfigOptions = function(resultIq) {
  176. // eslint-disable-next-line newline-per-chained-call
  177. this.setFocusUserJid($(resultIq).find('conference').attr('focusjid'));
  178. const authenticationEnabled
  179. = $(resultIq).find(
  180. '>conference>property'
  181. + '[name=\'authentication\'][value=\'true\']').length > 0;
  182. logger.info(`Authentication enabled: ${authenticationEnabled}`);
  183. this.externalAuthEnabled = $(resultIq).find(
  184. '>conference>property'
  185. + '[name=\'externalAuth\'][value=\'true\']').length > 0;
  186. logger.info(
  187. `External authentication enabled: ${this.externalAuthEnabled}`);
  188. if (!this.externalAuthEnabled) {
  189. // We expect to receive sessionId in 'internal' authentication mode
  190. this.parseSessionId(resultIq);
  191. }
  192. // eslint-disable-next-line newline-per-chained-call
  193. const authIdentity = $(resultIq).find('>conference').attr('identity');
  194. this.eventEmitter.emit(AuthenticationEvents.IDENTITY_UPDATED,
  195. authenticationEnabled, authIdentity);
  196. // Check if jicofo has jigasi support enabled.
  197. if ($(resultIq).find(
  198. '>conference>property'
  199. + '[name=\'sipGatewayEnabled\'][value=\'true\']').length) {
  200. this.sipGatewayEnabled = true;
  201. }
  202. logger.info(`Sip gateway enabled: ${this.sipGatewayEnabled}`);
  203. };
  204. // FIXME We need to show the fact that we're waiting for the focus to the user
  205. // (or that the focus is not available)
  206. /**
  207. * Allocates the conference focus.
  208. *
  209. * @param {Function} callback - the function to be called back upon the
  210. * successful allocation of the conference focus
  211. * @returns {Promise} - Resolved when Jicofo allows to join the room. It's never
  212. * rejected and it'll keep on pinging Jicofo forever.
  213. */
  214. Moderator.prototype.allocateConferenceFocus = function() {
  215. return new Promise(resolve => {
  216. // Try to use focus user JID from the config
  217. this.setFocusUserJid(this.options.connection.focusUserJid);
  218. // Send create conference IQ
  219. this.connection.sendIQ(
  220. this.createConferenceIq(),
  221. result => this._allocateConferenceFocusSuccess(result, resolve),
  222. error => this._allocateConferenceFocusError(error, resolve));
  223. // XXX We're pressed for time here because we're beginning a complex
  224. // and/or lengthy conference-establishment process which supposedly
  225. // involves multiple RTTs. We don't have the time to wait for Strophe to
  226. // decide to send our IQ.
  227. this.connection.flush();
  228. });
  229. };
  230. /**
  231. * Invoked by {@link #allocateConferenceFocus} upon its request receiving an
  232. * error result.
  233. *
  234. * @param error - the error result of the request that
  235. * {@link #allocateConferenceFocus} sent
  236. * @param {Function} callback - the function to be called back upon the
  237. * successful allocation of the conference focus
  238. */
  239. Moderator.prototype._allocateConferenceFocusError = function(error, callback) {
  240. // If the session is invalid, remove and try again without session ID to get
  241. // a new one
  242. const invalidSession
  243. = $(error).find('>error>session-invalid').length
  244. || $(error).find('>error>not-acceptable').length;
  245. if (invalidSession) {
  246. logger.info('Session expired! - removing');
  247. Settings.sessionId = undefined;
  248. }
  249. if ($(error).find('>error>graceful-shutdown').length) {
  250. this.eventEmitter.emit(XMPPEvents.GRACEFUL_SHUTDOWN);
  251. return;
  252. }
  253. // Check for error returned by the reservation system
  254. const reservationErr = $(error).find('>error>reservation-error');
  255. if (reservationErr.length) {
  256. // Trigger error event
  257. const errorCode = reservationErr.attr('error-code');
  258. const errorTextNode = $(error).find('>error>text');
  259. let errorMsg;
  260. if (errorTextNode) {
  261. errorMsg = errorTextNode.text();
  262. }
  263. this.eventEmitter.emit(
  264. XMPPEvents.RESERVATION_ERROR,
  265. errorCode,
  266. errorMsg);
  267. return;
  268. }
  269. // Not authorized to create new room
  270. if ($(error).find('>error>not-authorized').length) {
  271. logger.warn('Unauthorized to start the conference', error);
  272. const toDomain = Strophe.getDomainFromJid(error.getAttribute('to'));
  273. if (toDomain !== this.options.connection.hosts.anonymousdomain) {
  274. // FIXME "is external" should come either from the focus or
  275. // config.js
  276. this.externalAuthEnabled = true;
  277. }
  278. this.eventEmitter.emit(XMPPEvents.AUTHENTICATION_REQUIRED);
  279. return;
  280. }
  281. // redirect
  282. if ($(error).find('>error>redirect').length) {
  283. const conferenceIQError = $(error).find('conference');
  284. const vnode = conferenceIQError.attr('vnode');
  285. const focusJid = conferenceIQError.attr('focusjid');
  286. logger.warn(`We have been redirected to: ${vnode} new focus Jid:${focusJid}`);
  287. this.eventEmitter.emit(XMPPEvents.REDIRECTED, vnode, focusJid);
  288. return;
  289. }
  290. const waitMs = this.getNextErrorTimeout();
  291. const errmsg = `Focus error, retry after ${waitMs}`;
  292. GlobalOnErrorHandler.callErrorHandler(new Error(errmsg));
  293. logger.error(errmsg, error);
  294. // Show message
  295. const focusComponent = this.getFocusComponent();
  296. const retrySec = waitMs / 1000;
  297. // FIXME: message is duplicated ? Do not show in case of session invalid
  298. // which means just a retry
  299. if (!invalidSession) {
  300. this.eventEmitter.emit(
  301. XMPPEvents.FOCUS_DISCONNECTED,
  302. focusComponent,
  303. retrySec);
  304. }
  305. // Reset response timeout
  306. this.getNextTimeout(true);
  307. window.setTimeout(
  308. () => this.allocateConferenceFocus().then(callback),
  309. waitMs);
  310. };
  311. /**
  312. * Invoked by {@link #allocateConferenceFocus} upon its request receiving a
  313. * success (i.e. non-error) result.
  314. *
  315. * @param result - the success (i.e. non-error) result of the request that
  316. * {@link #allocateConferenceFocus} sent
  317. * @param {Function} callback - the function to be called back upon the
  318. * successful allocation of the conference focus
  319. */
  320. Moderator.prototype._allocateConferenceFocusSuccess = function(
  321. result,
  322. callback) {
  323. // Setup config options
  324. this.parseConfigOptions(result);
  325. // Reset the error timeout (because we haven't failed here).
  326. this.getNextErrorTimeout(true);
  327. // eslint-disable-next-line newline-per-chained-call
  328. if ($(result).find('conference').attr('ready') === 'true') {
  329. // Reset the non-error timeout (because we've succeeded here).
  330. this.getNextTimeout(true);
  331. // Exec callback
  332. callback();
  333. } else {
  334. const waitMs = this.getNextTimeout();
  335. logger.info(`Waiting for the focus... ${waitMs}`);
  336. window.setTimeout(
  337. () => this.allocateConferenceFocus().then(callback),
  338. waitMs);
  339. }
  340. };
  341. Moderator.prototype.authenticate = function() {
  342. return new Promise((resolve, reject) => {
  343. this.connection.sendIQ(
  344. this.createConferenceIq(),
  345. result => {
  346. this.parseSessionId(result);
  347. resolve();
  348. },
  349. errorIq => reject({
  350. error: $(errorIq).find('iq>error :first')
  351. .prop('tagName'),
  352. message: $(errorIq).find('iq>error>text')
  353. .text()
  354. })
  355. );
  356. });
  357. };
  358. Moderator.prototype.getLoginUrl = function(urlCallback, failureCallback) {
  359. this._getLoginUrl(/* popup */ false, urlCallback, failureCallback);
  360. };
  361. /**
  362. *
  363. * @param {boolean} popup false for {@link Moderator#getLoginUrl} or true for
  364. * {@link Moderator#getPopupLoginUrl}
  365. * @param urlCb
  366. * @param failureCb
  367. */
  368. Moderator.prototype._getLoginUrl = function(popup, urlCb, failureCb) {
  369. const iq = $iq({ to: this.getFocusComponent(),
  370. type: 'get' });
  371. const attrs = {
  372. xmlns: 'http://jitsi.org/protocol/focus',
  373. room: this.roomName,
  374. 'machine-uid': Settings.machineId
  375. };
  376. let str = 'auth url'; // for logger
  377. if (popup) {
  378. attrs.popup = true;
  379. str = `POPUP ${str}`;
  380. }
  381. iq.c('login-url', attrs);
  382. /**
  383. * Implements a failure callback which reports an error message and an error
  384. * through (1) GlobalOnErrorHandler, (2) logger, and (3) failureCb.
  385. *
  386. * @param {string} errmsg the error messsage to report
  387. * @param {*} error the error to report (in addition to errmsg)
  388. */
  389. function reportError(errmsg, err) {
  390. GlobalOnErrorHandler.callErrorHandler(new Error(errmsg));
  391. logger.error(errmsg, err);
  392. failureCb(err);
  393. }
  394. this.connection.sendIQ(
  395. iq,
  396. result => {
  397. // eslint-disable-next-line newline-per-chained-call
  398. let url = $(result).find('login-url').attr('url');
  399. url = decodeURIComponent(url);
  400. if (url) {
  401. logger.info(`Got ${str}: ${url}`);
  402. urlCb(url);
  403. } else {
  404. reportError(`Failed to get ${str} from the focus`, result);
  405. }
  406. },
  407. reportError.bind(undefined, `Get ${str} error`)
  408. );
  409. };
  410. Moderator.prototype.getPopupLoginUrl = function(urlCallback, failureCallback) {
  411. this._getLoginUrl(/* popup */ true, urlCallback, failureCallback);
  412. };
  413. Moderator.prototype.logout = function(callback) {
  414. const iq = $iq({ to: this.getFocusComponent(),
  415. type: 'set' });
  416. const { sessionId } = Settings;
  417. if (!sessionId) {
  418. callback();
  419. return;
  420. }
  421. iq.c('logout', {
  422. xmlns: 'http://jitsi.org/protocol/focus',
  423. 'session-id': sessionId
  424. });
  425. this.connection.sendIQ(
  426. iq,
  427. result => {
  428. // eslint-disable-next-line newline-per-chained-call
  429. let logoutUrl = $(result).find('logout').attr('logout-url');
  430. if (logoutUrl) {
  431. logoutUrl = decodeURIComponent(logoutUrl);
  432. }
  433. logger.info(`Log out OK, url: ${logoutUrl}`, result);
  434. Settings.sessionId = undefined;
  435. callback(logoutUrl);
  436. },
  437. error => {
  438. const errmsg = 'Logout error';
  439. GlobalOnErrorHandler.callErrorHandler(new Error(errmsg));
  440. logger.error(errmsg, error);
  441. }
  442. );
  443. };