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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582
  1. /* global $, Promise */
  2. const logger = require('jitsi-meet-logger').getLogger(__filename);
  3. import { $iq, Strophe } from 'strophe.js';
  4. const XMPPEvents = require('../../service/xmpp/XMPPEvents');
  5. const AuthenticationEvents
  6. = require('../../service/authentication/AuthenticationEvents');
  7. const GlobalOnErrorHandler = require('../util/GlobalOnErrorHandler');
  8. import RTCBrowserType from '../RTC/RTCBrowserType';
  9. import Settings from '../settings/Settings';
  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. logger.info(`Session ID: ${sessionId} machine UID: ${machineUID}`);
  118. elem.c('conference', {
  119. xmlns: 'http://jitsi.org/protocol/focus',
  120. room: this.roomName,
  121. 'machine-uid': machineUID
  122. });
  123. if (sessionId) {
  124. elem.attrs({ 'session-id': sessionId });
  125. }
  126. if (this.options.connection.enforcedBridge !== undefined) {
  127. elem.c(
  128. 'property', {
  129. name: 'enforcedBridge',
  130. value: this.options.connection.enforcedBridge
  131. }).up();
  132. }
  133. // Tell the focus we have Jigasi configured
  134. if (this.options.connection.hosts !== undefined
  135. && this.options.connection.hosts.call_control !== undefined) {
  136. elem.c(
  137. 'property', {
  138. name: 'call_control',
  139. value: this.options.connection.hosts.call_control
  140. }).up();
  141. }
  142. if (this.options.conference.channelLastN !== undefined) {
  143. elem.c(
  144. 'property', {
  145. name: 'channelLastN',
  146. value: this.options.conference.channelLastN
  147. }).up();
  148. }
  149. elem.c(
  150. 'property', {
  151. name: 'disableRtx',
  152. value: Boolean(this.options.conference.disableRtx)
  153. }).up();
  154. elem.c(
  155. 'property', {
  156. name: 'enableLipSync',
  157. value: this.options.connection.enableLipSync !== false
  158. }).up();
  159. if (this.options.conference.audioPacketDelay !== undefined) {
  160. elem.c(
  161. 'property', {
  162. name: 'audioPacketDelay',
  163. value: this.options.conference.audioPacketDelay
  164. }).up();
  165. }
  166. if (this.options.conference.startBitrate) {
  167. elem.c(
  168. 'property', {
  169. name: 'startBitrate',
  170. value: this.options.conference.startBitrate
  171. }).up();
  172. }
  173. if (this.options.conference.minBitrate) {
  174. elem.c(
  175. 'property', {
  176. name: 'minBitrate',
  177. value: this.options.conference.minBitrate
  178. }).up();
  179. }
  180. let openSctp;
  181. switch (this.options.conference.openBridgeChannel) {
  182. case 'datachannel':
  183. case true:
  184. case undefined:
  185. openSctp = true;
  186. break;
  187. case 'websocket':
  188. openSctp = false;
  189. break;
  190. }
  191. if (openSctp && !RTCBrowserType.supportsDataChannels()) {
  192. openSctp = false;
  193. }
  194. elem.c(
  195. 'property', {
  196. name: 'openSctp',
  197. value: openSctp
  198. }).up();
  199. if (this.options.conference.startAudioMuted !== undefined) {
  200. elem.c(
  201. 'property', {
  202. name: 'startAudioMuted',
  203. value: this.options.conference.startAudioMuted
  204. }).up();
  205. }
  206. if (this.options.conference.startVideoMuted !== undefined) {
  207. elem.c(
  208. 'property', {
  209. name: 'startVideoMuted',
  210. value: this.options.conference.startVideoMuted
  211. }).up();
  212. }
  213. if (this.options.conference.stereo !== undefined) {
  214. elem.c(
  215. 'property', {
  216. name: 'stereo',
  217. value: this.options.conference.stereo
  218. }).up();
  219. }
  220. if (this.options.conference.useRoomAsSharedDocumentName !== undefined) {
  221. elem.c(
  222. 'property', {
  223. name: 'useRoomAsSharedDocumentName',
  224. value: this.options.conference.useRoomAsSharedDocumentName
  225. }).up();
  226. }
  227. elem.up();
  228. return elem;
  229. };
  230. Moderator.prototype.parseSessionId = function(resultIq) {
  231. // eslint-disable-next-line newline-per-chained-call
  232. const sessionId = $(resultIq).find('conference').attr('session-id');
  233. if (sessionId) {
  234. logger.info(`Received sessionId: ${sessionId}`);
  235. Settings.sessionId = sessionId;
  236. }
  237. };
  238. Moderator.prototype.parseConfigOptions = function(resultIq) {
  239. // eslint-disable-next-line newline-per-chained-call
  240. this.setFocusUserJid($(resultIq).find('conference').attr('focusjid'));
  241. const authenticationEnabled
  242. = $(resultIq).find(
  243. '>conference>property'
  244. + '[name=\'authentication\'][value=\'true\']').length > 0;
  245. logger.info(`Authentication enabled: ${authenticationEnabled}`);
  246. this.externalAuthEnabled = $(resultIq).find(
  247. '>conference>property'
  248. + '[name=\'externalAuth\'][value=\'true\']').length > 0;
  249. logger.info(
  250. `External authentication enabled: ${this.externalAuthEnabled}`);
  251. if (!this.externalAuthEnabled) {
  252. // We expect to receive sessionId in 'internal' authentication mode
  253. this.parseSessionId(resultIq);
  254. }
  255. // eslint-disable-next-line newline-per-chained-call
  256. const authIdentity = $(resultIq).find('>conference').attr('identity');
  257. this.eventEmitter.emit(AuthenticationEvents.IDENTITY_UPDATED,
  258. authenticationEnabled, authIdentity);
  259. // Check if focus has auto-detected Jigasi component(this will be also
  260. // included if we have passed our host from the config)
  261. if ($(resultIq).find(
  262. '>conference>property'
  263. + '[name=\'sipGatewayEnabled\'][value=\'true\']').length) {
  264. this.sipGatewayEnabled = true;
  265. }
  266. logger.info(`Sip gateway enabled: ${this.sipGatewayEnabled}`);
  267. };
  268. // FIXME We need to show the fact that we're waiting for the focus to the user
  269. // (or that the focus is not available)
  270. /**
  271. * Allocates the conference focus.
  272. *
  273. * @param {Function} callback - the function to be called back upon the
  274. * successful allocation of the conference focus
  275. */
  276. Moderator.prototype.allocateConferenceFocus = function(callback) {
  277. // Try to use focus user JID from the config
  278. this.setFocusUserJid(this.options.connection.focusUserJid);
  279. // Send create conference IQ
  280. this.connection.sendIQ(
  281. this.createConferenceIq(),
  282. result => this._allocateConferenceFocusSuccess(result, callback),
  283. error => this._allocateConferenceFocusError(error, callback));
  284. // XXX We're pressed for time here because we're beginning a complex and/or
  285. // lengthy conference-establishment process which supposedly involves
  286. // multiple RTTs. We don't have the time to wait for Strophe to decide to
  287. // send our IQ.
  288. this.connection.flush();
  289. };
  290. /**
  291. * Invoked by {@link #allocateConferenceFocus} upon its request receiving an
  292. * error result.
  293. *
  294. * @param error - the error result of the request that
  295. * {@link #allocateConferenceFocus} sent
  296. * @param {Function} callback - the function to be called back upon the
  297. * successful allocation of the conference focus
  298. */
  299. Moderator.prototype._allocateConferenceFocusError = function(error, callback) {
  300. // If the session is invalid, remove and try again without session ID to get
  301. // a new one
  302. const invalidSession
  303. = $(error).find('>error>session-invalid').length
  304. || $(error).find('>error>not-acceptable').length;
  305. if (invalidSession) {
  306. logger.info('Session expired! - removing');
  307. Settings.sessionId = undefined;
  308. }
  309. if ($(error).find('>error>graceful-shutdown').length) {
  310. this.eventEmitter.emit(XMPPEvents.GRACEFUL_SHUTDOWN);
  311. return;
  312. }
  313. // Check for error returned by the reservation system
  314. const reservationErr = $(error).find('>error>reservation-error');
  315. if (reservationErr.length) {
  316. // Trigger error event
  317. const errorCode = reservationErr.attr('error-code');
  318. const errorTextNode = $(error).find('>error>text');
  319. let errorMsg;
  320. if (errorTextNode) {
  321. errorMsg = errorTextNode.text();
  322. }
  323. this.eventEmitter.emit(
  324. XMPPEvents.RESERVATION_ERROR,
  325. errorCode,
  326. errorMsg);
  327. return;
  328. }
  329. // Not authorized to create new room
  330. if ($(error).find('>error>not-authorized').length) {
  331. logger.warn('Unauthorized to start the conference', error);
  332. const toDomain = Strophe.getDomainFromJid(error.getAttribute('to'));
  333. if (toDomain !== this.options.connection.hosts.anonymousdomain) {
  334. // FIXME "is external" should come either from the focus or
  335. // config.js
  336. this.externalAuthEnabled = true;
  337. }
  338. this.eventEmitter.emit(XMPPEvents.AUTHENTICATION_REQUIRED);
  339. return;
  340. }
  341. const waitMs = this.getNextErrorTimeout();
  342. const errmsg = `Focus error, retry after ${waitMs}`;
  343. GlobalOnErrorHandler.callErrorHandler(new Error(errmsg));
  344. logger.error(errmsg, error);
  345. // Show message
  346. const focusComponent = this.getFocusComponent();
  347. const retrySec = waitMs / 1000;
  348. // FIXME: message is duplicated ? Do not show in case of session invalid
  349. // which means just a retry
  350. if (!invalidSession) {
  351. this.eventEmitter.emit(
  352. XMPPEvents.FOCUS_DISCONNECTED,
  353. focusComponent,
  354. retrySec);
  355. }
  356. // Reset response timeout
  357. this.getNextTimeout(true);
  358. window.setTimeout(() => this.allocateConferenceFocus(callback), waitMs);
  359. };
  360. /**
  361. * Invoked by {@link #allocateConferenceFocus} upon its request receiving a
  362. * success (i.e. non-error) result.
  363. *
  364. * @param result - the success (i.e. non-error) result of the request that
  365. * {@link #allocateConferenceFocus} sent
  366. * @param {Function} callback - the function to be called back upon the
  367. * successful allocation of the conference focus
  368. */
  369. Moderator.prototype._allocateConferenceFocusSuccess = function(
  370. result,
  371. callback) {
  372. // Setup config options
  373. this.parseConfigOptions(result);
  374. // Reset the error timeout (because we haven't failed here).
  375. this.getNextErrorTimeout(true);
  376. // eslint-disable-next-line newline-per-chained-call
  377. if ($(result).find('conference').attr('ready') === 'true') {
  378. // Reset the non-error timeout (because we've succeeded here).
  379. this.getNextTimeout(true);
  380. // Exec callback
  381. callback();
  382. } else {
  383. const waitMs = this.getNextTimeout();
  384. logger.info(`Waiting for the focus... ${waitMs}`);
  385. window.setTimeout(() => this.allocateConferenceFocus(callback),
  386. waitMs);
  387. }
  388. };
  389. Moderator.prototype.authenticate = function() {
  390. return new Promise((resolve, reject) => {
  391. this.connection.sendIQ(
  392. this.createConferenceIq(),
  393. result => {
  394. this.parseSessionId(result);
  395. resolve();
  396. },
  397. errorIq => reject({
  398. error: $(errorIq).find('iq>error :first')
  399. .prop('tagName'),
  400. message: $(errorIq).find('iq>error>text')
  401. .text()
  402. })
  403. );
  404. });
  405. };
  406. Moderator.prototype.getLoginUrl = function(urlCallback, failureCallback) {
  407. this._getLoginUrl(/* popup */ false, urlCallback, failureCallback);
  408. };
  409. /**
  410. *
  411. * @param {boolean} popup false for {@link Moderator#getLoginUrl} or true for
  412. * {@link Moderator#getPopupLoginUrl}
  413. * @param urlCb
  414. * @param failureCb
  415. */
  416. Moderator.prototype._getLoginUrl = function(popup, urlCb, failureCb) {
  417. const iq = $iq({ to: this.getFocusComponent(),
  418. type: 'get' });
  419. const attrs = {
  420. xmlns: 'http://jitsi.org/protocol/focus',
  421. room: this.roomName,
  422. 'machine-uid': Settings.machineId
  423. };
  424. let str = 'auth url'; // for logger
  425. if (popup) {
  426. attrs.popup = true;
  427. str = `POPUP ${str}`;
  428. }
  429. iq.c('login-url', attrs);
  430. /**
  431. * Implements a failure callback which reports an error message and an error
  432. * through (1) GlobalOnErrorHandler, (2) logger, and (3) failureCb.
  433. *
  434. * @param {string} errmsg the error messsage to report
  435. * @param {*} error the error to report (in addition to errmsg)
  436. */
  437. function reportError(errmsg, err) {
  438. GlobalOnErrorHandler.callErrorHandler(new Error(errmsg));
  439. logger.error(errmsg, err);
  440. failureCb(err);
  441. }
  442. this.connection.sendIQ(
  443. iq,
  444. result => {
  445. // eslint-disable-next-line newline-per-chained-call
  446. let url = $(result).find('login-url').attr('url');
  447. url = decodeURIComponent(url);
  448. if (url) {
  449. logger.info(`Got ${str}: ${url}`);
  450. urlCb(url);
  451. } else {
  452. reportError(`Failed to get ${str} from the focus`, result);
  453. }
  454. },
  455. reportError.bind(undefined, `Get ${str} error`)
  456. );
  457. };
  458. Moderator.prototype.getPopupLoginUrl = function(urlCallback, failureCallback) {
  459. this._getLoginUrl(/* popup */ true, urlCallback, failureCallback);
  460. };
  461. Moderator.prototype.logout = function(callback) {
  462. const iq = $iq({ to: this.getFocusComponent(),
  463. type: 'set' });
  464. const { sessionId } = Settings;
  465. if (!sessionId) {
  466. callback();
  467. return;
  468. }
  469. iq.c('logout', {
  470. xmlns: 'http://jitsi.org/protocol/focus',
  471. 'session-id': sessionId
  472. });
  473. this.connection.sendIQ(
  474. iq,
  475. result => {
  476. // eslint-disable-next-line newline-per-chained-call
  477. let logoutUrl = $(result).find('logout').attr('logout-url');
  478. if (logoutUrl) {
  479. logoutUrl = decodeURIComponent(logoutUrl);
  480. }
  481. logger.info(`Log out OK, url: ${logoutUrl}`, result);
  482. Settings.sessionId = undefined;
  483. callback(logoutUrl);
  484. },
  485. error => {
  486. const errmsg = 'Logout error';
  487. GlobalOnErrorHandler.callErrorHandler(new Error(errmsg));
  488. logger.error(errmsg, error);
  489. }
  490. );
  491. };