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 19KB

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