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.

ScreenObtainer.js 26KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791
  1. /* global chrome, $, alert */
  2. import JitsiTrackError from '../../JitsiTrackError';
  3. import * as JitsiTrackErrors from '../../JitsiTrackErrors';
  4. import browser from '../browser';
  5. const logger = require('jitsi-meet-logger').getLogger(__filename);
  6. const GlobalOnErrorHandler = require('../util/GlobalOnErrorHandler');
  7. /**
  8. * Indicates whether the Chrome desktop sharing extension is installed.
  9. * @type {boolean}
  10. */
  11. let chromeExtInstalled = false;
  12. /**
  13. * Indicates whether an update of the Chrome desktop sharing extension is
  14. * required.
  15. * @type {boolean}
  16. */
  17. let chromeExtUpdateRequired = false;
  18. /**
  19. * Whether the jidesha extension for firefox is installed for the domain on
  20. * which we are running. Null designates an unknown value.
  21. * @type {null}
  22. */
  23. let firefoxExtInstalled = null;
  24. /**
  25. * If set to true, detection of an installed firefox extension will be started
  26. * again the next time obtainScreenOnFirefox is called (e.g. next time the
  27. * user tries to enable screen sharing).
  28. */
  29. let reDetectFirefoxExtension = false;
  30. let gumFunction = null;
  31. /**
  32. * The error returned by chrome when trying to start inline installation from
  33. * popup.
  34. */
  35. const CHROME_EXTENSION_POPUP_ERROR
  36. = 'Inline installs can not be initiated from pop-up windows.';
  37. /**
  38. * The error returned by chrome when trying to start inline installation from
  39. * iframe.
  40. */
  41. const CHROME_EXTENSION_IFRAME_ERROR
  42. = 'Chrome Web Store installations can only be started by the top frame.';
  43. /**
  44. * The error returned by chrome when trying to start inline installation
  45. * not from the "main" whitelisted site.
  46. * @type {string}
  47. */
  48. const CHROME_EXTENSION_INLINE_ERROR
  49. = 'Installs can only be initiated by one of'
  50. + ' the Chrome Web Store item\'s verified sites.';
  51. /**
  52. * The error returned by chrome when trying to start inline installation
  53. * with extension that doesn't support inline installation.
  54. *
  55. * @type {string}
  56. */
  57. const CHROME_EXTENSION_INLINE_NOT_SUPPORTED_ERROR
  58. = 'Inline installation is not supported for this item. '
  59. + 'The user will be redirected to the Chrome Web Store.';
  60. /**
  61. * The error message returned by chrome when the extension is installed.
  62. */
  63. const CHROME_NO_EXTENSION_ERROR_MSG // eslint-disable-line no-unused-vars
  64. = 'Could not establish connection. Receiving end does not exist.';
  65. /**
  66. * The error message returned by chrome when the extension install action needs
  67. * to be initiated by a user gesture.
  68. * @type {string}
  69. */
  70. const CHROME_USER_GESTURE_REQ_ERROR
  71. = 'Chrome Web Store installations can only be initated by a user gesture.';
  72. /**
  73. * Handles obtaining a stream from a screen capture on different browsers.
  74. */
  75. const ScreenObtainer = {
  76. /**
  77. * If not <tt>null</tt> it means that the initialization process is still in
  78. * progress. It is used to make desktop stream request wait and continue
  79. * after it's done.
  80. * {@type Promise|null}
  81. */
  82. intChromeExtPromise: null,
  83. obtainStream: null,
  84. /**
  85. * Initializes the function used to obtain a screen capture
  86. * (this.obtainStream).
  87. *
  88. * @param {object} options
  89. * @param {boolean} [options.disableDesktopSharing]
  90. * @param {boolean} [options.desktopSharingChromeDisabled]
  91. * @param {boolean} [options.desktopSharingChromeExtId]
  92. * @param {boolean} [options.desktopSharingFirefoxDisabled]
  93. * @param {boolean} [options.desktopSharingFirefoxExtId] (deprecated)
  94. * @param {Function} gum GUM method
  95. */
  96. init(options = {
  97. disableDesktopSharing: false,
  98. desktopSharingChromeDisabled: false,
  99. desktopSharingChromeExtId: null,
  100. desktopSharingFirefoxDisabled: false,
  101. desktopSharingFirefoxExtId: null
  102. }, gum) {
  103. // eslint-disable-next-line no-param-reassign
  104. this.options = options = options || {};
  105. gumFunction = gum;
  106. this.obtainStream
  107. = this.options.disableDesktopSharing
  108. ? null : this._createObtainStreamMethod(options);
  109. if (!this.obtainStream) {
  110. logger.info('Desktop sharing disabled');
  111. }
  112. },
  113. /**
  114. * Returns a method which will be used to obtain the screen sharing stream
  115. * (based on the browser type).
  116. *
  117. * @param {object} options passed from {@link init} - check description
  118. * there
  119. * @returns {Function}
  120. * @private
  121. */
  122. _createObtainStreamMethod(options) {
  123. if (browser.isNWJS()) {
  124. return (_, onSuccess, onFailure) => {
  125. window.JitsiMeetNW.obtainDesktopStream(
  126. onSuccess,
  127. (error, constraints) => {
  128. let jitsiError;
  129. // FIXME:
  130. // This is very very dirty fix for recognising that the
  131. // user have clicked the cancel button from the Desktop
  132. // sharing pick window. The proper solution would be to
  133. // detect this in the NWJS application by checking the
  134. // streamId === "". Even better solution would be to
  135. // stop calling GUM from the NWJS app and just pass the
  136. // streamId to lib-jitsi-meet. This way the desktop
  137. // sharing implementation for NWJS and chrome extension
  138. // will be the same and lib-jitsi-meet will be able to
  139. // control the constraints, check the streamId, etc.
  140. //
  141. // I cannot find documentation about "InvalidStateError"
  142. // but this is what we are receiving from GUM when the
  143. // streamId for the desktop sharing is "".
  144. if (error && error.name === 'InvalidStateError') {
  145. jitsiError = new JitsiTrackError(
  146. JitsiTrackErrors.CHROME_EXTENSION_USER_CANCELED
  147. );
  148. } else {
  149. jitsiError = new JitsiTrackError(
  150. error, constraints, [ 'desktop' ]);
  151. }
  152. (typeof onFailure === 'function')
  153. && onFailure(jitsiError);
  154. });
  155. };
  156. } else if (browser.isElectron()) {
  157. return this.obtainScreenOnElectron;
  158. } else if (browser.isTemasysPluginUsed()) {
  159. // XXX Don't require Temasys unless it's to be used because it
  160. // doesn't run on React Native, for example.
  161. const plugin
  162. = require('./adapter.screenshare').WebRTCPlugin.plugin;
  163. if (!plugin.HasScreensharingFeature) {
  164. logger.warn(
  165. 'Screensharing not supported by this plugin version');
  166. return null;
  167. } else if (!plugin.isScreensharingAvailable) {
  168. logger.warn(
  169. 'Screensharing not available with Temasys plugin on'
  170. + ' this site');
  171. return null;
  172. }
  173. logger.info('Using Temasys plugin for desktop sharing');
  174. return obtainWebRTCScreen;
  175. } else if (browser.isChrome() || browser.isOpera()) {
  176. if (browser.isVersionLessThan('34')) {
  177. logger.info('Chrome extension not supported until ver 34');
  178. return null;
  179. } else if (options.desktopSharingChromeDisabled
  180. || options.desktopSharingChromeMethod === false
  181. || !options.desktopSharingChromeExtId) {
  182. // TODO: desktopSharingChromeMethod is deprecated, remove.
  183. return null;
  184. }
  185. logger.info('Using Chrome extension for desktop sharing');
  186. this.intChromeExtPromise
  187. = initChromeExtension(options).then(() => {
  188. this.intChromeExtPromise = null;
  189. });
  190. return this.obtainScreenFromExtension;
  191. } else if (browser.isFirefox()) {
  192. if (options.desktopSharingFirefoxDisabled) {
  193. return null;
  194. } else if (window.location.protocol === 'http:') {
  195. logger.log('Screen sharing is not supported over HTTP. '
  196. + 'Use of HTTPS is required.');
  197. return null;
  198. }
  199. initFirefoxExtensionDetection(options);
  200. return this.obtainScreenOnFirefox;
  201. }
  202. logger.log(
  203. 'Screen sharing not supported by the current browser: ',
  204. browser.getName());
  205. return null;
  206. },
  207. /**
  208. * Checks whether obtaining a screen capture is supported in the current
  209. * environment.
  210. * @returns {boolean}
  211. */
  212. isSupported() {
  213. return this.obtainStream !== null;
  214. },
  215. /**
  216. * Obtains a screen capture stream on Firefox.
  217. * @param callback
  218. * @param errorCallback
  219. */
  220. obtainScreenOnFirefox(options, callback, errorCallback) {
  221. let extensionRequired = false;
  222. const { desktopSharingFirefoxMaxVersionExtRequired } = this.options;
  223. if (desktopSharingFirefoxMaxVersionExtRequired === -1
  224. || (desktopSharingFirefoxMaxVersionExtRequired >= 0
  225. && !browser.isVersionGreaterThan(
  226. desktopSharingFirefoxMaxVersionExtRequired))) {
  227. extensionRequired = true;
  228. logger.log(
  229. `Jidesha extension required on firefox version ${
  230. browser.getVersion()}`);
  231. }
  232. if (!extensionRequired || firefoxExtInstalled === true) {
  233. obtainWebRTCScreen(options, callback, errorCallback);
  234. return;
  235. }
  236. if (reDetectFirefoxExtension) {
  237. reDetectFirefoxExtension = false;
  238. initFirefoxExtensionDetection(this.options);
  239. }
  240. // Give it some (more) time to initialize, and assume lack of
  241. // extension if it hasn't.
  242. if (firefoxExtInstalled === null) {
  243. window.setTimeout(
  244. () => {
  245. if (firefoxExtInstalled === null) {
  246. firefoxExtInstalled = false;
  247. }
  248. this.obtainScreenOnFirefox(callback, errorCallback);
  249. },
  250. 300);
  251. logger.log(
  252. 'Waiting for detection of jidesha on firefox to finish.');
  253. return;
  254. }
  255. // We need an extension and it isn't installed.
  256. // Make sure we check for the extension when the user clicks again.
  257. firefoxExtInstalled = null;
  258. reDetectFirefoxExtension = true;
  259. // Make sure desktopsharing knows that we failed, so that it doesn't get
  260. // stuck in 'switching' mode.
  261. errorCallback(
  262. new JitsiTrackError(JitsiTrackErrors.FIREFOX_EXTENSION_NEEDED));
  263. },
  264. /**
  265. * Obtains a screen capture stream on Electron.
  266. *
  267. * @param {Object} [options] - Screen sharing options.
  268. * @param {Array<string>} [options.desktopSharingSources] - Array with the
  269. * sources that have to be displayed in the desktop picker window ('screen',
  270. * 'window', etc.).
  271. * @param onSuccess - Success callback.
  272. * @param onFailure - Failure callback.
  273. */
  274. obtainScreenOnElectron(options = {}, onSuccess, onFailure) {
  275. if (window.JitsiMeetScreenObtainer
  276. && window.JitsiMeetScreenObtainer.openDesktopPicker) {
  277. window.JitsiMeetScreenObtainer.openDesktopPicker(
  278. {
  279. desktopSharingSources:
  280. options.desktopSharingSources
  281. || this.options.desktopSharingChromeSources
  282. },
  283. (streamId, streamType) =>
  284. onGetStreamResponse(
  285. {
  286. streamId,
  287. streamType
  288. },
  289. onSuccess,
  290. onFailure
  291. ),
  292. err => onFailure(new JitsiTrackError(
  293. JitsiTrackErrors.ELECTRON_DESKTOP_PICKER_ERROR,
  294. err
  295. ))
  296. );
  297. } else {
  298. onFailure(new JitsiTrackError(
  299. JitsiTrackErrors.ELECTRON_DESKTOP_PICKER_NOT_FOUND));
  300. }
  301. },
  302. /**
  303. * Asks Chrome extension to call chooseDesktopMedia and gets chrome
  304. * 'desktop' stream for returned stream token.
  305. */
  306. obtainScreenFromExtension(options, streamCallback, failCallback) {
  307. if (this.intChromeExtPromise !== null) {
  308. this.intChromeExtPromise.then(() => {
  309. this.obtainScreenFromExtension(
  310. options, streamCallback, failCallback);
  311. });
  312. return;
  313. }
  314. const {
  315. desktopSharingChromeExtId,
  316. desktopSharingChromeSources
  317. } = this.options;
  318. const gumOptions = {
  319. desktopSharingChromeExtId,
  320. desktopSharingChromeSources:
  321. options.desktopSharingSources
  322. || desktopSharingChromeSources
  323. };
  324. if (chromeExtInstalled) {
  325. doGetStreamFromExtension(
  326. gumOptions,
  327. streamCallback,
  328. failCallback);
  329. } else {
  330. if (chromeExtUpdateRequired) {
  331. /* eslint-disable no-alert */
  332. alert(
  333. 'Jitsi Desktop Streamer requires update. '
  334. + 'Changes will take effect after next Chrome restart.');
  335. /* eslint-enable no-alert */
  336. }
  337. // for opera there is no inline install
  338. // extension "Download Chrome Extension" allows us to open
  339. // the chrome webstore and install from there and then activate our
  340. // extension
  341. if (browser.isOpera()) {
  342. this.handleExternalInstall(options, streamCallback,
  343. failCallback);
  344. return;
  345. }
  346. try {
  347. chrome.webstore.install(
  348. getWebStoreInstallUrl(this.options),
  349. arg => {
  350. logger.log('Extension installed successfully', arg);
  351. chromeExtInstalled = true;
  352. // We need to give a moment to the endpoint to become
  353. // available.
  354. waitForExtensionAfterInstall(this.options, 200, 10)
  355. .then(() => {
  356. doGetStreamFromExtension(
  357. gumOptions,
  358. streamCallback,
  359. failCallback);
  360. })
  361. .catch(() => {
  362. this.handleExtensionInstallationError(options,
  363. streamCallback, failCallback);
  364. });
  365. },
  366. this.handleExtensionInstallationError.bind(this,
  367. options, streamCallback, failCallback)
  368. );
  369. } catch (e) {
  370. this.handleExtensionInstallationError(options, streamCallback,
  371. failCallback, e);
  372. }
  373. }
  374. },
  375. /* eslint-disable max-params */
  376. handleExternalInstall(options, streamCallback, failCallback, e) {
  377. const webStoreInstallUrl = getWebStoreInstallUrl(this.options);
  378. options.listener('waitingForExtension', webStoreInstallUrl);
  379. this.checkForChromeExtensionOnInterval(options, streamCallback,
  380. failCallback, e);
  381. },
  382. handleExtensionInstallationError(options, streamCallback, failCallback, e) {
  383. const webStoreInstallUrl = getWebStoreInstallUrl(this.options);
  384. if ((CHROME_EXTENSION_POPUP_ERROR === e
  385. || CHROME_EXTENSION_IFRAME_ERROR === e
  386. || CHROME_EXTENSION_INLINE_ERROR === e
  387. || CHROME_EXTENSION_INLINE_NOT_SUPPORTED_ERROR === e)
  388. && options.interval > 0
  389. && typeof options.checkAgain === 'function'
  390. && typeof options.listener === 'function') {
  391. this.handleExternalInstall(options, streamCallback,
  392. failCallback, e);
  393. return;
  394. }
  395. const msg
  396. = `Failed to install the extension from ${webStoreInstallUrl}`;
  397. logger.log(msg, e);
  398. const error
  399. = e === CHROME_USER_GESTURE_REQ_ERROR
  400. ? JitsiTrackErrors.CHROME_EXTENSION_USER_GESTURE_REQUIRED
  401. : JitsiTrackErrors.CHROME_EXTENSION_INSTALLATION_ERROR;
  402. failCallback(new JitsiTrackError(error, msg));
  403. },
  404. /* eslint-enable max-params */
  405. checkForChromeExtensionOnInterval(options, streamCallback, failCallback) {
  406. if (options.checkAgain() === false) {
  407. failCallback(new JitsiTrackError(
  408. JitsiTrackErrors.CHROME_EXTENSION_INSTALLATION_ERROR));
  409. return;
  410. }
  411. waitForExtensionAfterInstall(this.options, options.interval, 1)
  412. .then(() => {
  413. chromeExtInstalled = true;
  414. options.listener('extensionFound');
  415. this.obtainScreenFromExtension(options,
  416. streamCallback, failCallback);
  417. })
  418. .catch(() => {
  419. this.checkForChromeExtensionOnInterval(options,
  420. streamCallback, failCallback);
  421. });
  422. }
  423. };
  424. /**
  425. * Obtains a desktop stream using getUserMedia.
  426. * For this to work on Chrome, the
  427. * 'chrome://flags/#enable-usermedia-screen-capture' flag must be enabled.
  428. *
  429. * On firefox, the document's domain must be white-listed in the
  430. * 'media.getusermedia.screensharing.allowed_domains' preference in
  431. * 'about:config'.
  432. */
  433. function obtainWebRTCScreen(options, streamCallback, failCallback) {
  434. gumFunction(
  435. [ 'screen' ],
  436. stream => streamCallback({ stream }),
  437. failCallback
  438. );
  439. }
  440. /**
  441. * Constructs inline install URL for Chrome desktop streaming extension.
  442. * The 'chromeExtensionId' must be defined in options parameter.
  443. * @param options supports "desktopSharingChromeExtId"
  444. * @returns {string}
  445. */
  446. function getWebStoreInstallUrl(options) {
  447. return (
  448. `https://chrome.google.com/webstore/detail/${
  449. options.desktopSharingChromeExtId}`);
  450. }
  451. /**
  452. * Checks whether an update of the Chrome extension is required.
  453. * @param minVersion minimal required version
  454. * @param extVersion current extension version
  455. * @returns {boolean}
  456. */
  457. function isUpdateRequired(minVersion, extVersion) {
  458. try {
  459. const s1 = minVersion.split('.');
  460. const s2 = extVersion.split('.');
  461. const len = Math.max(s1.length, s2.length);
  462. for (let i = 0; i < len; i++) {
  463. let n1 = 0,
  464. n2 = 0;
  465. if (i < s1.length) {
  466. n1 = parseInt(s1[i], 10);
  467. }
  468. if (i < s2.length) {
  469. n2 = parseInt(s2[i], 10);
  470. }
  471. if (isNaN(n1) || isNaN(n2)) {
  472. return true;
  473. } else if (n1 !== n2) {
  474. return n1 > n2;
  475. }
  476. }
  477. // will happen if both versions have identical numbers in
  478. // their components (even if one of them is longer, has more components)
  479. return false;
  480. } catch (e) {
  481. GlobalOnErrorHandler.callErrorHandler(e);
  482. logger.error('Failed to parse extension version', e);
  483. return true;
  484. }
  485. }
  486. /**
  487. *
  488. * @param callback
  489. * @param options
  490. */
  491. function checkChromeExtInstalled(callback, options) {
  492. if (typeof chrome === 'undefined' || !chrome || !chrome.runtime) {
  493. // No API, so no extension for sure
  494. callback(false, false);
  495. return;
  496. }
  497. chrome.runtime.sendMessage(
  498. options.desktopSharingChromeExtId,
  499. { getVersion: true },
  500. response => {
  501. if (!response || !response.version) {
  502. // Communication failure - assume that no endpoint exists
  503. logger.warn(
  504. 'Extension not installed?: ', chrome.runtime.lastError);
  505. callback(false, false);
  506. return;
  507. }
  508. // Check installed extension version
  509. const extVersion = response.version;
  510. logger.log(`Extension version is: ${extVersion}`);
  511. const updateRequired
  512. = isUpdateRequired(
  513. options.desktopSharingChromeMinExtVersion,
  514. extVersion);
  515. callback(!updateRequired, updateRequired);
  516. }
  517. );
  518. }
  519. /**
  520. *
  521. * @param options
  522. * @param streamCallback
  523. * @param failCallback
  524. */
  525. function doGetStreamFromExtension(options, streamCallback, failCallback) {
  526. // Sends 'getStream' msg to the extension.
  527. // Extension id must be defined in the config.
  528. chrome.runtime.sendMessage(
  529. options.desktopSharingChromeExtId,
  530. {
  531. getStream: true,
  532. sources: options.desktopSharingChromeSources
  533. },
  534. response => {
  535. if (!response) {
  536. // possibly re-wraping error message to make code consistent
  537. const lastError = chrome.runtime.lastError;
  538. failCallback(lastError instanceof Error
  539. ? lastError
  540. : new JitsiTrackError(
  541. JitsiTrackErrors.CHROME_EXTENSION_GENERIC_ERROR,
  542. lastError));
  543. return;
  544. }
  545. logger.log('Response from extension: ', response);
  546. onGetStreamResponse(response, streamCallback, failCallback);
  547. }
  548. );
  549. }
  550. /**
  551. * Initializes <link rel=chrome-webstore-item /> with extension id set in
  552. * config.js to support inline installs. Host site must be selected as main
  553. * website of published extension.
  554. * @param options supports "desktopSharingChromeExtId"
  555. */
  556. function initInlineInstalls(options) {
  557. if ($('link[rel=chrome-webstore-item]').length === 0) {
  558. $('head').append('<link rel="chrome-webstore-item">');
  559. }
  560. $('link[rel=chrome-webstore-item]').attr('href',
  561. getWebStoreInstallUrl(options));
  562. }
  563. /**
  564. *
  565. * @param options
  566. *
  567. * @return {Promise} - a Promise resolved once the initialization process is
  568. * finished.
  569. */
  570. function initChromeExtension(options) {
  571. // Initialize Chrome extension inline installs
  572. initInlineInstalls(options);
  573. return new Promise(resolve => {
  574. // Check if extension is installed
  575. checkChromeExtInstalled((installed, updateRequired) => {
  576. chromeExtInstalled = installed;
  577. chromeExtUpdateRequired = updateRequired;
  578. logger.info(
  579. `Chrome extension installed: ${
  580. chromeExtInstalled} updateRequired: ${
  581. chromeExtUpdateRequired}`);
  582. resolve();
  583. }, options);
  584. });
  585. }
  586. /**
  587. * Checks "retries" times on every "waitInterval"ms whether the ext is alive.
  588. * @param {Object} options the options passed to ScreanObtainer.obtainStream
  589. * @param {int} waitInterval the number of ms between retries
  590. * @param {int} retries the number of retries
  591. * @returns {Promise} returns promise that will be resolved when the extension
  592. * is alive and rejected if the extension is not alive even after "retries"
  593. * checks
  594. */
  595. function waitForExtensionAfterInstall(options, waitInterval, retries) {
  596. if (retries === 0) {
  597. return Promise.reject();
  598. }
  599. return new Promise((resolve, reject) => {
  600. let currentRetries = retries;
  601. const interval = window.setInterval(() => {
  602. checkChromeExtInstalled(installed => {
  603. if (installed) {
  604. window.clearInterval(interval);
  605. resolve();
  606. } else {
  607. currentRetries--;
  608. if (currentRetries === 0) {
  609. reject();
  610. window.clearInterval(interval);
  611. }
  612. }
  613. }, options);
  614. }, waitInterval);
  615. });
  616. }
  617. /**
  618. * Handles response from external application / extension and calls GUM to
  619. * receive the desktop streams or reports error.
  620. * @param {object} response
  621. * @param {string} response.streamId - the streamId for the desktop stream
  622. * @param {string} response.error - error to be reported.
  623. * @param {Function} onSuccess - callback for success.
  624. * @param {Function} onFailure - callback for failure.
  625. */
  626. function onGetStreamResponse(
  627. { streamId, streamType, error },
  628. onSuccess,
  629. onFailure) {
  630. if (streamId) {
  631. gumFunction(
  632. [ 'desktop' ],
  633. stream => onSuccess({
  634. stream,
  635. sourceId: streamId,
  636. sourceType: streamType
  637. }),
  638. onFailure,
  639. { desktopStream: streamId });
  640. } else {
  641. // As noted in Chrome Desktop Capture API:
  642. // If user didn't select any source (i.e. canceled the prompt)
  643. // then the callback is called with an empty streamId.
  644. if (streamId === '') {
  645. onFailure(new JitsiTrackError(
  646. JitsiTrackErrors.CHROME_EXTENSION_USER_CANCELED));
  647. return;
  648. }
  649. onFailure(new JitsiTrackError(
  650. JitsiTrackErrors.CHROME_EXTENSION_GENERIC_ERROR,
  651. error));
  652. }
  653. }
  654. /**
  655. * Starts the detection of an installed jidesha extension for firefox.
  656. * @param options supports "desktopSharingFirefoxDisabled",
  657. * "desktopSharingFirefoxExtId"
  658. */
  659. function initFirefoxExtensionDetection(options) {
  660. if (options.desktopSharingFirefoxDisabled) {
  661. return;
  662. }
  663. if (firefoxExtInstalled === false || firefoxExtInstalled === true) {
  664. return;
  665. }
  666. if (!options.desktopSharingFirefoxExtId) {
  667. firefoxExtInstalled = false;
  668. return;
  669. }
  670. const img = document.createElement('img');
  671. img.onload = () => {
  672. logger.log('Detected firefox screen sharing extension.');
  673. firefoxExtInstalled = true;
  674. };
  675. img.onerror = () => {
  676. logger.log('Detected lack of firefox screen sharing extension.');
  677. firefoxExtInstalled = false;
  678. };
  679. // The jidesha extension exposes an empty image file under the url:
  680. // "chrome://EXT_ID/content/DOMAIN.png"
  681. // Where EXT_ID is the ID of the extension with "@" replaced by ".", and
  682. // DOMAIN is a domain whitelisted by the extension.
  683. const extId = options.desktopSharingFirefoxExtId.replace('@', '.');
  684. const domain = document.location.hostname;
  685. const src = `chrome://${extId}/content/${domain}.png`;
  686. img.setAttribute('src', src);
  687. }
  688. export default ScreenObtainer;