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

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