Вы не можете выбрать более 25 тем Темы должны начинаться с буквы или цифры, могут содержать дефисы(-) и должны содержать не более 35 символов.

moderator.js 15KB

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