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

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