You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

moderator.js 15KB

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