modified lib-jitsi-meet dev repo
Nevar pievienot vairāk kā 25 tēmas Tēmai ir jāsākas ar burtu vai ciparu, tā var saturēt domu zīmes ('-') un var būt līdz 35 simboliem gara.

moderator.js 16KB

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