modified lib-jitsi-meet dev repo
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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800
  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. let maxVersion = desktopSharingFirefoxMaxVersionExtRequired;
  224. if (typeof maxVersion === 'number') {
  225. extensionRequired = maxVersion === -1;
  226. if (maxVersion >= 0) {
  227. maxVersion = String(maxVersion);
  228. }
  229. }
  230. if (typeof maxVersion === 'string') {
  231. extensionRequired = !browser.isVersionGreaterThan(maxVersion);
  232. }
  233. if (extensionRequired) {
  234. logger.log(
  235. `Jidesha extension required on firefox version ${
  236. browser.getVersion()}`);
  237. }
  238. if (!extensionRequired || firefoxExtInstalled === true) {
  239. obtainWebRTCScreen(options, callback, errorCallback);
  240. return;
  241. }
  242. if (reDetectFirefoxExtension) {
  243. reDetectFirefoxExtension = false;
  244. initFirefoxExtensionDetection(this.options);
  245. }
  246. // Give it some (more) time to initialize, and assume lack of
  247. // extension if it hasn't.
  248. if (firefoxExtInstalled === null) {
  249. window.setTimeout(
  250. () => {
  251. if (firefoxExtInstalled === null) {
  252. firefoxExtInstalled = false;
  253. }
  254. this.obtainScreenOnFirefox(
  255. options, callback, errorCallback);
  256. },
  257. 300);
  258. logger.log(
  259. 'Waiting for detection of jidesha on firefox to finish.');
  260. return;
  261. }
  262. // We need an extension and it isn't installed.
  263. // Make sure we check for the extension when the user clicks again.
  264. firefoxExtInstalled = null;
  265. reDetectFirefoxExtension = true;
  266. // Make sure desktopsharing knows that we failed, so that it doesn't get
  267. // stuck in 'switching' mode.
  268. errorCallback(
  269. new JitsiTrackError(JitsiTrackErrors.FIREFOX_EXTENSION_NEEDED));
  270. },
  271. /**
  272. * Obtains a screen capture stream on Electron.
  273. *
  274. * @param {Object} [options] - Screen sharing options.
  275. * @param {Array<string>} [options.desktopSharingSources] - Array with the
  276. * sources that have to be displayed in the desktop picker window ('screen',
  277. * 'window', etc.).
  278. * @param onSuccess - Success callback.
  279. * @param onFailure - Failure callback.
  280. */
  281. obtainScreenOnElectron(options = {}, onSuccess, onFailure) {
  282. if (window.JitsiMeetScreenObtainer
  283. && window.JitsiMeetScreenObtainer.openDesktopPicker) {
  284. window.JitsiMeetScreenObtainer.openDesktopPicker(
  285. {
  286. desktopSharingSources:
  287. options.desktopSharingSources
  288. || this.options.desktopSharingChromeSources
  289. },
  290. (streamId, streamType) =>
  291. onGetStreamResponse(
  292. {
  293. streamId,
  294. streamType
  295. },
  296. onSuccess,
  297. onFailure
  298. ),
  299. err => onFailure(new JitsiTrackError(
  300. JitsiTrackErrors.ELECTRON_DESKTOP_PICKER_ERROR,
  301. err
  302. ))
  303. );
  304. } else {
  305. onFailure(new JitsiTrackError(
  306. JitsiTrackErrors.ELECTRON_DESKTOP_PICKER_NOT_FOUND));
  307. }
  308. },
  309. /**
  310. * Asks Chrome extension to call chooseDesktopMedia and gets chrome
  311. * 'desktop' stream for returned stream token.
  312. */
  313. obtainScreenFromExtension(options, streamCallback, failCallback) {
  314. if (this.intChromeExtPromise !== null) {
  315. this.intChromeExtPromise.then(() => {
  316. this.obtainScreenFromExtension(
  317. options, streamCallback, failCallback);
  318. });
  319. return;
  320. }
  321. const {
  322. desktopSharingChromeExtId,
  323. desktopSharingChromeSources
  324. } = this.options;
  325. const gumOptions = {
  326. desktopSharingChromeExtId,
  327. desktopSharingChromeSources:
  328. options.desktopSharingSources
  329. || desktopSharingChromeSources
  330. };
  331. if (chromeExtInstalled) {
  332. doGetStreamFromExtension(
  333. gumOptions,
  334. streamCallback,
  335. failCallback);
  336. } else {
  337. if (chromeExtUpdateRequired) {
  338. /* eslint-disable no-alert */
  339. alert(
  340. 'Jitsi Desktop Streamer requires update. '
  341. + 'Changes will take effect after next Chrome restart.');
  342. /* eslint-enable no-alert */
  343. }
  344. // for opera there is no inline install
  345. // extension "Download Chrome Extension" allows us to open
  346. // the chrome webstore and install from there and then activate our
  347. // extension
  348. if (browser.isOpera()) {
  349. this.handleExternalInstall(options, streamCallback,
  350. failCallback);
  351. return;
  352. }
  353. try {
  354. chrome.webstore.install(
  355. getWebStoreInstallUrl(this.options),
  356. arg => {
  357. logger.log('Extension installed successfully', arg);
  358. chromeExtInstalled = true;
  359. // We need to give a moment to the endpoint to become
  360. // available.
  361. waitForExtensionAfterInstall(this.options, 200, 10)
  362. .then(() => {
  363. doGetStreamFromExtension(
  364. gumOptions,
  365. streamCallback,
  366. failCallback);
  367. })
  368. .catch(() => {
  369. this.handleExtensionInstallationError(options,
  370. streamCallback, failCallback);
  371. });
  372. },
  373. this.handleExtensionInstallationError.bind(this,
  374. options, streamCallback, failCallback)
  375. );
  376. } catch (e) {
  377. this.handleExtensionInstallationError(options, streamCallback,
  378. failCallback, e);
  379. }
  380. }
  381. },
  382. /* eslint-disable max-params */
  383. handleExternalInstall(options, streamCallback, failCallback, e) {
  384. const webStoreInstallUrl = getWebStoreInstallUrl(this.options);
  385. options.listener('waitingForExtension', webStoreInstallUrl);
  386. this.checkForChromeExtensionOnInterval(options, streamCallback,
  387. failCallback, e);
  388. },
  389. handleExtensionInstallationError(options, streamCallback, failCallback, e) {
  390. const webStoreInstallUrl = getWebStoreInstallUrl(this.options);
  391. if ((CHROME_EXTENSION_POPUP_ERROR === e
  392. || CHROME_EXTENSION_IFRAME_ERROR === e
  393. || CHROME_EXTENSION_INLINE_ERROR === e
  394. || CHROME_EXTENSION_INLINE_NOT_SUPPORTED_ERROR === e)
  395. && options.interval > 0
  396. && typeof options.checkAgain === 'function'
  397. && typeof options.listener === 'function') {
  398. this.handleExternalInstall(options, streamCallback,
  399. failCallback, e);
  400. return;
  401. }
  402. const msg
  403. = `Failed to install the extension from ${webStoreInstallUrl}`;
  404. logger.log(msg, e);
  405. const error
  406. = e === CHROME_USER_GESTURE_REQ_ERROR
  407. ? JitsiTrackErrors.CHROME_EXTENSION_USER_GESTURE_REQUIRED
  408. : JitsiTrackErrors.CHROME_EXTENSION_INSTALLATION_ERROR;
  409. failCallback(new JitsiTrackError(error, msg));
  410. },
  411. /* eslint-enable max-params */
  412. checkForChromeExtensionOnInterval(options, streamCallback, failCallback) {
  413. if (options.checkAgain() === false) {
  414. failCallback(new JitsiTrackError(
  415. JitsiTrackErrors.CHROME_EXTENSION_INSTALLATION_ERROR));
  416. return;
  417. }
  418. waitForExtensionAfterInstall(this.options, options.interval, 1)
  419. .then(() => {
  420. chromeExtInstalled = true;
  421. options.listener('extensionFound');
  422. this.obtainScreenFromExtension(options,
  423. streamCallback, failCallback);
  424. })
  425. .catch(() => {
  426. this.checkForChromeExtensionOnInterval(options,
  427. streamCallback, failCallback);
  428. });
  429. }
  430. };
  431. /**
  432. * Obtains a desktop stream using getUserMedia.
  433. * For this to work on Chrome, the
  434. * 'chrome://flags/#enable-usermedia-screen-capture' flag must be enabled.
  435. *
  436. * On firefox, the document's domain must be white-listed in the
  437. * 'media.getusermedia.screensharing.allowed_domains' preference in
  438. * 'about:config'.
  439. */
  440. function obtainWebRTCScreen(options, streamCallback, failCallback) {
  441. gumFunction(
  442. [ 'screen' ],
  443. stream => streamCallback({ stream }),
  444. failCallback
  445. );
  446. }
  447. /**
  448. * Constructs inline install URL for Chrome desktop streaming extension.
  449. * The 'chromeExtensionId' must be defined in options parameter.
  450. * @param options supports "desktopSharingChromeExtId"
  451. * @returns {string}
  452. */
  453. function getWebStoreInstallUrl(options) {
  454. return (
  455. `https://chrome.google.com/webstore/detail/${
  456. options.desktopSharingChromeExtId}`);
  457. }
  458. /**
  459. * Checks whether an update of the Chrome extension is required.
  460. * @param minVersion minimal required version
  461. * @param extVersion current extension version
  462. * @returns {boolean}
  463. */
  464. function isUpdateRequired(minVersion, extVersion) {
  465. try {
  466. const s1 = minVersion.split('.');
  467. const s2 = extVersion.split('.');
  468. const len = Math.max(s1.length, s2.length);
  469. for (let i = 0; i < len; i++) {
  470. let n1 = 0,
  471. n2 = 0;
  472. if (i < s1.length) {
  473. n1 = parseInt(s1[i], 10);
  474. }
  475. if (i < s2.length) {
  476. n2 = parseInt(s2[i], 10);
  477. }
  478. if (isNaN(n1) || isNaN(n2)) {
  479. return true;
  480. } else if (n1 !== n2) {
  481. return n1 > n2;
  482. }
  483. }
  484. // will happen if both versions have identical numbers in
  485. // their components (even if one of them is longer, has more components)
  486. return false;
  487. } catch (e) {
  488. GlobalOnErrorHandler.callErrorHandler(e);
  489. logger.error('Failed to parse extension version', e);
  490. return true;
  491. }
  492. }
  493. /**
  494. *
  495. * @param callback
  496. * @param options
  497. */
  498. function checkChromeExtInstalled(callback, options) {
  499. if (typeof chrome === 'undefined' || !chrome || !chrome.runtime) {
  500. // No API, so no extension for sure
  501. callback(false, false);
  502. return;
  503. }
  504. chrome.runtime.sendMessage(
  505. options.desktopSharingChromeExtId,
  506. { getVersion: true },
  507. response => {
  508. if (!response || !response.version) {
  509. // Communication failure - assume that no endpoint exists
  510. logger.warn(
  511. 'Extension not installed?: ', chrome.runtime.lastError);
  512. callback(false, false);
  513. return;
  514. }
  515. // Check installed extension version
  516. const extVersion = response.version;
  517. logger.log(`Extension version is: ${extVersion}`);
  518. const updateRequired
  519. = isUpdateRequired(
  520. options.desktopSharingChromeMinExtVersion,
  521. extVersion);
  522. callback(!updateRequired, updateRequired);
  523. }
  524. );
  525. }
  526. /**
  527. *
  528. * @param options
  529. * @param streamCallback
  530. * @param failCallback
  531. */
  532. function doGetStreamFromExtension(options, streamCallback, failCallback) {
  533. // Sends 'getStream' msg to the extension.
  534. // Extension id must be defined in the config.
  535. chrome.runtime.sendMessage(
  536. options.desktopSharingChromeExtId,
  537. {
  538. getStream: true,
  539. sources: options.desktopSharingChromeSources
  540. },
  541. response => {
  542. if (!response) {
  543. // possibly re-wraping error message to make code consistent
  544. const lastError = chrome.runtime.lastError;
  545. failCallback(lastError instanceof Error
  546. ? lastError
  547. : new JitsiTrackError(
  548. JitsiTrackErrors.CHROME_EXTENSION_GENERIC_ERROR,
  549. lastError));
  550. return;
  551. }
  552. logger.log('Response from extension: ', response);
  553. onGetStreamResponse(response, streamCallback, failCallback);
  554. }
  555. );
  556. }
  557. /**
  558. * Initializes <link rel=chrome-webstore-item /> with extension id set in
  559. * config.js to support inline installs. Host site must be selected as main
  560. * website of published extension.
  561. * @param options supports "desktopSharingChromeExtId"
  562. */
  563. function initInlineInstalls(options) {
  564. if ($('link[rel=chrome-webstore-item]').length === 0) {
  565. $('head').append('<link rel="chrome-webstore-item">');
  566. }
  567. $('link[rel=chrome-webstore-item]').attr('href',
  568. getWebStoreInstallUrl(options));
  569. }
  570. /**
  571. *
  572. * @param options
  573. *
  574. * @return {Promise} - a Promise resolved once the initialization process is
  575. * finished.
  576. */
  577. function initChromeExtension(options) {
  578. // Initialize Chrome extension inline installs
  579. initInlineInstalls(options);
  580. return new Promise(resolve => {
  581. // Check if extension is installed
  582. checkChromeExtInstalled((installed, updateRequired) => {
  583. chromeExtInstalled = installed;
  584. chromeExtUpdateRequired = updateRequired;
  585. logger.info(
  586. `Chrome extension installed: ${
  587. chromeExtInstalled} updateRequired: ${
  588. chromeExtUpdateRequired}`);
  589. resolve();
  590. }, options);
  591. });
  592. }
  593. /**
  594. * Checks "retries" times on every "waitInterval"ms whether the ext is alive.
  595. * @param {Object} options the options passed to ScreanObtainer.obtainStream
  596. * @param {int} waitInterval the number of ms between retries
  597. * @param {int} retries the number of retries
  598. * @returns {Promise} returns promise that will be resolved when the extension
  599. * is alive and rejected if the extension is not alive even after "retries"
  600. * checks
  601. */
  602. function waitForExtensionAfterInstall(options, waitInterval, retries) {
  603. if (retries === 0) {
  604. return Promise.reject();
  605. }
  606. return new Promise((resolve, reject) => {
  607. let currentRetries = retries;
  608. const interval = window.setInterval(() => {
  609. checkChromeExtInstalled(installed => {
  610. if (installed) {
  611. window.clearInterval(interval);
  612. resolve();
  613. } else {
  614. currentRetries--;
  615. if (currentRetries === 0) {
  616. reject();
  617. window.clearInterval(interval);
  618. }
  619. }
  620. }, options);
  621. }, waitInterval);
  622. });
  623. }
  624. /**
  625. * Handles response from external application / extension and calls GUM to
  626. * receive the desktop streams or reports error.
  627. * @param {object} response
  628. * @param {string} response.streamId - the streamId for the desktop stream
  629. * @param {string} response.error - error to be reported.
  630. * @param {Function} onSuccess - callback for success.
  631. * @param {Function} onFailure - callback for failure.
  632. */
  633. function onGetStreamResponse(
  634. { streamId, streamType, error },
  635. onSuccess,
  636. onFailure) {
  637. if (streamId) {
  638. gumFunction(
  639. [ 'desktop' ],
  640. stream => onSuccess({
  641. stream,
  642. sourceId: streamId,
  643. sourceType: streamType
  644. }),
  645. onFailure,
  646. { desktopStream: streamId });
  647. } else {
  648. // As noted in Chrome Desktop Capture API:
  649. // If user didn't select any source (i.e. canceled the prompt)
  650. // then the callback is called with an empty streamId.
  651. if (streamId === '') {
  652. onFailure(new JitsiTrackError(
  653. JitsiTrackErrors.CHROME_EXTENSION_USER_CANCELED));
  654. return;
  655. }
  656. onFailure(new JitsiTrackError(
  657. JitsiTrackErrors.CHROME_EXTENSION_GENERIC_ERROR,
  658. error));
  659. }
  660. }
  661. /**
  662. * Starts the detection of an installed jidesha extension for firefox.
  663. * @param options supports "desktopSharingFirefoxDisabled",
  664. * "desktopSharingFirefoxExtId"
  665. */
  666. function initFirefoxExtensionDetection(options) {
  667. if (options.desktopSharingFirefoxDisabled) {
  668. return;
  669. }
  670. if (firefoxExtInstalled === false || firefoxExtInstalled === true) {
  671. return;
  672. }
  673. if (!options.desktopSharingFirefoxExtId) {
  674. firefoxExtInstalled = false;
  675. return;
  676. }
  677. const img = document.createElement('img');
  678. img.onload = () => {
  679. logger.log('Detected firefox screen sharing extension.');
  680. firefoxExtInstalled = true;
  681. };
  682. img.onerror = () => {
  683. logger.log('Detected lack of firefox screen sharing extension.');
  684. firefoxExtInstalled = false;
  685. };
  686. // The jidesha extension exposes an empty image file under the url:
  687. // "chrome://EXT_ID/content/DOMAIN.png"
  688. // Where EXT_ID is the ID of the extension with "@" replaced by ".", and
  689. // DOMAIN is a domain whitelisted by the extension.
  690. const extId = options.desktopSharingFirefoxExtId.replace('@', '.');
  691. const domain = document.location.hostname;
  692. const src = `chrome://${extId}/content/${domain}.png`;
  693. img.setAttribute('src', src);
  694. }
  695. export default ScreenObtainer;