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

moderator.js 16KB

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