Du kan inte välja fler än 25 ämnen Ämnen måste starta med en bokstav eller siffra, kan innehålla bindestreck ('-') och vara max 35 tecken långa.

moderator.js 15KB

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