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

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