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

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