Nelze vybrat více než 25 témat Téma musí začínat písmenem nebo číslem, může obsahovat pomlčky („-“) a může být dlouhé až 35 znaků.

moderator.js 17KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580
  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.sessionId = 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;
  115. const machineUID = Settings.machineId;
  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.sessionId = 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
  302. = $(error).find('>error>session-invalid').length
  303. || $(error).find('>error>not-acceptable').length;
  304. if (invalidSession) {
  305. logger.info('Session expired! - removing');
  306. Settings.sessionId = undefined;
  307. }
  308. if ($(error).find('>error>graceful-shutdown').length) {
  309. this.eventEmitter.emit(XMPPEvents.GRACEFUL_SHUTDOWN);
  310. return;
  311. }
  312. // Check for error returned by the reservation system
  313. const reservationErr = $(error).find('>error>reservation-error');
  314. if (reservationErr.length) {
  315. // Trigger error event
  316. const errorCode = reservationErr.attr('error-code');
  317. const errorTextNode = $(error).find('>error>text');
  318. let errorMsg;
  319. if (errorTextNode) {
  320. errorMsg = errorTextNode.text();
  321. }
  322. this.eventEmitter.emit(
  323. XMPPEvents.RESERVATION_ERROR,
  324. errorCode,
  325. errorMsg);
  326. return;
  327. }
  328. // Not authorized to create new room
  329. if ($(error).find('>error>not-authorized').length) {
  330. logger.warn('Unauthorized to start the conference', error);
  331. const toDomain = Strophe.getDomainFromJid(error.getAttribute('to'));
  332. if (toDomain !== this.options.connection.hosts.anonymousdomain) {
  333. // FIXME "is external" should come either from the focus or
  334. // config.js
  335. this.externalAuthEnabled = true;
  336. }
  337. this.eventEmitter.emit(XMPPEvents.AUTHENTICATION_REQUIRED);
  338. return;
  339. }
  340. const waitMs = this.getNextErrorTimeout();
  341. const errmsg = `Focus error, retry after ${waitMs}`;
  342. GlobalOnErrorHandler.callErrorHandler(new Error(errmsg));
  343. logger.error(errmsg, error);
  344. // Show message
  345. const focusComponent = this.getFocusComponent();
  346. const retrySec = waitMs / 1000;
  347. // FIXME: message is duplicated ? Do not show in case of session invalid
  348. // which means just a retry
  349. if (!invalidSession) {
  350. this.eventEmitter.emit(
  351. XMPPEvents.FOCUS_DISCONNECTED,
  352. focusComponent,
  353. retrySec);
  354. }
  355. // Reset response timeout
  356. this.getNextTimeout(true);
  357. window.setTimeout(() => this.allocateConferenceFocus(callback), waitMs);
  358. };
  359. /**
  360. * Invoked by {@link #allocateConferenceFocus} upon its request receiving a
  361. * success (i.e. non-error) result.
  362. *
  363. * @param result - the success (i.e. non-error) result of the request that
  364. * {@link #allocateConferenceFocus} sent
  365. * @param {Function} callback - the function to be called back upon the
  366. * successful allocation of the conference focus
  367. */
  368. Moderator.prototype._allocateConferenceFocusSuccess = function(
  369. result,
  370. callback) {
  371. // Setup config options
  372. this.parseConfigOptions(result);
  373. // Reset the error timeout (because we haven't failed here).
  374. this.getNextErrorTimeout(true);
  375. // eslint-disable-next-line newline-per-chained-call
  376. if ($(result).find('conference').attr('ready') === 'true') {
  377. // Reset the non-error timeout (because we've succeeded here).
  378. this.getNextTimeout(true);
  379. // Exec callback
  380. callback();
  381. } else {
  382. const waitMs = this.getNextTimeout();
  383. logger.info(`Waiting for the focus... ${waitMs}`);
  384. window.setTimeout(() => this.allocateConferenceFocus(callback),
  385. waitMs);
  386. }
  387. };
  388. Moderator.prototype.authenticate = function() {
  389. return new Promise((resolve, reject) => {
  390. this.connection.sendIQ(
  391. this.createConferenceIq(),
  392. result => {
  393. this.parseSessionId(result);
  394. resolve();
  395. },
  396. errorIq => reject({
  397. error: $(errorIq).find('iq>error :first')
  398. .prop('tagName'),
  399. message: $(errorIq).find('iq>error>text')
  400. .text()
  401. })
  402. );
  403. });
  404. };
  405. Moderator.prototype.getLoginUrl = function(urlCallback, failureCallback) {
  406. this._getLoginUrl(/* popup */ false, urlCallback, failureCallback);
  407. };
  408. /**
  409. *
  410. * @param {boolean} popup false for {@link Moderator#getLoginUrl} or true for
  411. * {@link Moderator#getPopupLoginUrl}
  412. * @param urlCb
  413. * @param failureCb
  414. */
  415. Moderator.prototype._getLoginUrl = function(popup, urlCb, failureCb) {
  416. const iq = $iq({ to: this.getFocusComponent(),
  417. type: 'get' });
  418. const attrs = {
  419. xmlns: 'http://jitsi.org/protocol/focus',
  420. room: this.roomName,
  421. 'machine-uid': Settings.machineId
  422. };
  423. let str = 'auth url'; // for logger
  424. if (popup) {
  425. attrs.popup = true;
  426. str = `POPUP ${str}`;
  427. }
  428. iq.c('login-url', attrs);
  429. /**
  430. * Implements a failure callback which reports an error message and an error
  431. * through (1) GlobalOnErrorHandler, (2) logger, and (3) failureCb.
  432. *
  433. * @param {string} errmsg the error messsage to report
  434. * @param {*} error the error to report (in addition to errmsg)
  435. */
  436. function reportError(errmsg, err) {
  437. GlobalOnErrorHandler.callErrorHandler(new Error(errmsg));
  438. logger.error(errmsg, err);
  439. failureCb(err);
  440. }
  441. this.connection.sendIQ(
  442. iq,
  443. result => {
  444. // eslint-disable-next-line newline-per-chained-call
  445. let url = $(result).find('login-url').attr('url');
  446. url = decodeURIComponent(url);
  447. if (url) {
  448. logger.info(`Got ${str}: ${url}`);
  449. urlCb(url);
  450. } else {
  451. reportError(`Failed to get ${str} from the focus`, result);
  452. }
  453. },
  454. reportError.bind(undefined, `Get ${str} error`)
  455. );
  456. };
  457. Moderator.prototype.getPopupLoginUrl = function(urlCallback, failureCallback) {
  458. this._getLoginUrl(/* popup */ true, urlCallback, failureCallback);
  459. };
  460. Moderator.prototype.logout = function(callback) {
  461. const iq = $iq({ to: this.getFocusComponent(),
  462. type: 'set' });
  463. const { sessionId } = Settings;
  464. if (!sessionId) {
  465. callback();
  466. return;
  467. }
  468. iq.c('logout', {
  469. xmlns: 'http://jitsi.org/protocol/focus',
  470. 'session-id': sessionId
  471. });
  472. this.connection.sendIQ(
  473. iq,
  474. result => {
  475. // eslint-disable-next-line newline-per-chained-call
  476. let logoutUrl = $(result).find('logout').attr('logout-url');
  477. if (logoutUrl) {
  478. logoutUrl = decodeURIComponent(logoutUrl);
  479. }
  480. logger.info(`Log out OK, url: ${logoutUrl}`, result);
  481. Settings.sessionId = undefined;
  482. callback(logoutUrl);
  483. },
  484. error => {
  485. const errmsg = 'Logout error';
  486. GlobalOnErrorHandler.callErrorHandler(new Error(errmsg));
  487. logger.error(errmsg, error);
  488. }
  489. );
  490. };