您最多选择25个主题 主题必须以字母或数字开头,可以包含连字符 (-),并且长度不得超过35个字符

moderator.js 16KB

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