Você não pode selecionar mais de 25 tópicos Os tópicos devem começar com uma letra ou um número, podem incluir traços ('-') e podem ter até 35 caracteres.

moderator.js 15KB

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