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

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