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 27KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825
  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. this.options = options;
  104. gumFunction = gum;
  105. this.obtainStream
  106. = this.options.disableDesktopSharing
  107. ? null : this._createObtainStreamMethod(options);
  108. if (!this.obtainStream) {
  109. logger.info('Desktop sharing disabled');
  110. }
  111. },
  112. /**
  113. * Returns a method which will be used to obtain the screen sharing stream
  114. * (based on the browser type).
  115. *
  116. * @param {object} options passed from {@link init} - check description
  117. * there
  118. * @returns {Function}
  119. * @private
  120. */
  121. _createObtainStreamMethod(options) {
  122. if (browser.isNWJS()) {
  123. return (_, onSuccess, onFailure) => {
  124. window.JitsiMeetNW.obtainDesktopStream(
  125. onSuccess,
  126. (error, constraints) => {
  127. let jitsiError;
  128. // FIXME:
  129. // This is very very dirty fix for recognising that the
  130. // user have clicked the cancel button from the Desktop
  131. // sharing pick window. The proper solution would be to
  132. // detect this in the NWJS application by checking the
  133. // streamId === "". Even better solution would be to
  134. // stop calling GUM from the NWJS app and just pass the
  135. // streamId to lib-jitsi-meet. This way the desktop
  136. // sharing implementation for NWJS and chrome extension
  137. // will be the same and lib-jitsi-meet will be able to
  138. // control the constraints, check the streamId, etc.
  139. //
  140. // I cannot find documentation about "InvalidStateError"
  141. // but this is what we are receiving from GUM when the
  142. // streamId for the desktop sharing is "".
  143. if (error && error.name === 'InvalidStateError') {
  144. jitsiError = new JitsiTrackError(
  145. JitsiTrackErrors.CHROME_EXTENSION_USER_CANCELED
  146. );
  147. } else {
  148. jitsiError = new JitsiTrackError(
  149. error, constraints, [ 'desktop' ]);
  150. }
  151. (typeof onFailure === 'function')
  152. && onFailure(jitsiError);
  153. });
  154. };
  155. } else if (browser.isElectron()) {
  156. return this.obtainScreenOnElectron;
  157. } else if (browser.isTemasysPluginUsed()) {
  158. // XXX Don't require Temasys unless it's to be used because it
  159. // doesn't run on React Native, for example.
  160. const plugin
  161. = require('./adapter.screenshare').WebRTCPlugin.plugin;
  162. if (!plugin.HasScreensharingFeature) {
  163. logger.warn(
  164. 'Screensharing not supported by this plugin version');
  165. return null;
  166. } else if (!plugin.isScreensharingAvailable) {
  167. logger.warn(
  168. 'Screensharing not available with Temasys plugin on'
  169. + ' this site');
  170. return null;
  171. }
  172. logger.info('Using Temasys plugin for desktop sharing');
  173. return obtainWebRTCScreen;
  174. } else if (browser.isChrome() || browser.isOpera()) {
  175. if (browser.isVersionLessThan('34')) {
  176. logger.info('Chrome extension not supported until ver 34');
  177. return null;
  178. } else if (options.desktopSharingChromeDisabled
  179. || options.desktopSharingChromeMethod === false
  180. || !options.desktopSharingChromeExtId) {
  181. // TODO: desktopSharingChromeMethod is deprecated, remove.
  182. return null;
  183. }
  184. logger.info('Using Chrome extension for desktop sharing');
  185. this.intChromeExtPromise
  186. = initChromeExtension(options).then(() => {
  187. this.intChromeExtPromise = null;
  188. });
  189. return this.obtainScreenFromExtension;
  190. } else if (browser.isFirefox()) {
  191. if (options.desktopSharingFirefoxDisabled) {
  192. return null;
  193. } else if (window.location.protocol === 'http:') {
  194. logger.log('Screen sharing is not supported over HTTP. '
  195. + 'Use of HTTPS is required.');
  196. return null;
  197. }
  198. initFirefoxExtensionDetection(options);
  199. return this.obtainScreenOnFirefox;
  200. }
  201. logger.log(
  202. 'Screen sharing not supported by the current browser: ',
  203. browser.getName());
  204. return null;
  205. },
  206. /**
  207. * Checks whether obtaining a screen capture is supported in the current
  208. * environment.
  209. * @returns {boolean}
  210. */
  211. isSupported() {
  212. return this.obtainStream !== null;
  213. },
  214. /**
  215. * Obtains a screen capture stream on Firefox.
  216. * @param callback
  217. * @param errorCallback
  218. */
  219. obtainScreenOnFirefox(options, callback, errorCallback) {
  220. let extensionRequired = false;
  221. const { desktopSharingFirefoxMaxVersionExtRequired } = this.options;
  222. if (desktopSharingFirefoxMaxVersionExtRequired === -1
  223. || (desktopSharingFirefoxMaxVersionExtRequired >= 0
  224. && !browser.isVersionGreaterThan(
  225. desktopSharingFirefoxMaxVersionExtRequired))) {
  226. extensionRequired = true;
  227. logger.log(
  228. `Jidesha extension required on firefox version ${
  229. browser.getVersion()}`);
  230. }
  231. if (!extensionRequired || firefoxExtInstalled === true) {
  232. obtainWebRTCScreen(options.gumOptions, callback, errorCallback);
  233. return;
  234. }
  235. if (reDetectFirefoxExtension) {
  236. reDetectFirefoxExtension = false;
  237. initFirefoxExtensionDetection(this.options);
  238. }
  239. // Give it some (more) time to initialize, and assume lack of
  240. // extension if it hasn't.
  241. if (firefoxExtInstalled === null) {
  242. window.setTimeout(
  243. () => {
  244. if (firefoxExtInstalled === null) {
  245. firefoxExtInstalled = false;
  246. }
  247. this.obtainScreenOnFirefox(
  248. options, 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. const { desktopSharingSources, gumOptions } = options;
  278. window.JitsiMeetScreenObtainer.openDesktopPicker(
  279. {
  280. desktopSharingSources: desktopSharingSources
  281. || this.options.desktopSharingChromeSources
  282. },
  283. (streamId, streamType) =>
  284. onGetStreamResponse(
  285. {
  286. response: {
  287. streamId,
  288. streamType
  289. },
  290. gumOptions
  291. },
  292. onSuccess,
  293. onFailure
  294. ),
  295. err => onFailure(new JitsiTrackError(
  296. JitsiTrackErrors.ELECTRON_DESKTOP_PICKER_ERROR,
  297. err
  298. ))
  299. );
  300. } else {
  301. onFailure(new JitsiTrackError(
  302. JitsiTrackErrors.ELECTRON_DESKTOP_PICKER_NOT_FOUND));
  303. }
  304. },
  305. /**
  306. * Asks Chrome extension to call chooseDesktopMedia and gets chrome
  307. * 'desktop' stream for returned stream token.
  308. */
  309. obtainScreenFromExtension(options, streamCallback, failCallback) {
  310. if (this.intChromeExtPromise !== null) {
  311. this.intChromeExtPromise.then(() => {
  312. this.obtainScreenFromExtension(
  313. options, streamCallback, failCallback);
  314. });
  315. return;
  316. }
  317. const {
  318. desktopSharingChromeExtId,
  319. desktopSharingChromeSources
  320. } = this.options;
  321. const {
  322. gumOptions
  323. } = options;
  324. const doGetStreamFromExtensionOptions = {
  325. desktopSharingChromeExtId,
  326. desktopSharingChromeSources:
  327. options.desktopSharingSources || desktopSharingChromeSources,
  328. gumOptions
  329. };
  330. if (chromeExtInstalled) {
  331. doGetStreamFromExtension(
  332. doGetStreamFromExtensionOptions,
  333. streamCallback,
  334. failCallback);
  335. } else {
  336. if (chromeExtUpdateRequired) {
  337. /* eslint-disable no-alert */
  338. alert(
  339. 'Jitsi Desktop Streamer requires update. '
  340. + 'Changes will take effect after next Chrome restart.');
  341. /* eslint-enable no-alert */
  342. }
  343. // for opera there is no inline install
  344. // extension "Download Chrome Extension" allows us to open
  345. // the chrome webstore and install from there and then activate our
  346. // extension
  347. if (browser.isOpera()) {
  348. this.handleExternalInstall(options, streamCallback,
  349. failCallback);
  350. return;
  351. }
  352. try {
  353. chrome.webstore.install(
  354. getWebStoreInstallUrl(this.options),
  355. arg => {
  356. logger.log('Extension installed successfully', arg);
  357. chromeExtInstalled = true;
  358. // We need to give a moment to the endpoint to become
  359. // available.
  360. waitForExtensionAfterInstall(this.options, 200, 10)
  361. .then(() => {
  362. doGetStreamFromExtension(
  363. doGetStreamFromExtensionOptions,
  364. streamCallback,
  365. failCallback);
  366. })
  367. .catch(() => {
  368. this.handleExtensionInstallationError(options,
  369. streamCallback, failCallback);
  370. });
  371. },
  372. this.handleExtensionInstallationError.bind(this,
  373. options, streamCallback, failCallback)
  374. );
  375. } catch (e) {
  376. this.handleExtensionInstallationError(options, streamCallback,
  377. failCallback, e);
  378. }
  379. }
  380. },
  381. /* eslint-disable max-params */
  382. handleExternalInstall(options, streamCallback, failCallback, e) {
  383. const webStoreInstallUrl = getWebStoreInstallUrl(this.options);
  384. options.listener('waitingForExtension', webStoreInstallUrl);
  385. this.checkForChromeExtensionOnInterval(options, streamCallback,
  386. failCallback, e);
  387. },
  388. handleExtensionInstallationError(options, streamCallback, failCallback, e) {
  389. const webStoreInstallUrl = getWebStoreInstallUrl(this.options);
  390. if ((CHROME_EXTENSION_POPUP_ERROR === e
  391. || CHROME_EXTENSION_IFRAME_ERROR === e
  392. || CHROME_EXTENSION_INLINE_ERROR === e
  393. || CHROME_EXTENSION_INLINE_NOT_SUPPORTED_ERROR === e)
  394. && options.interval > 0
  395. && typeof options.checkAgain === 'function'
  396. && typeof options.listener === 'function') {
  397. this.handleExternalInstall(options, streamCallback,
  398. failCallback, e);
  399. return;
  400. }
  401. const msg
  402. = `Failed to install the extension from ${webStoreInstallUrl}`;
  403. logger.log(msg, e);
  404. const error
  405. = e === CHROME_USER_GESTURE_REQ_ERROR
  406. ? JitsiTrackErrors.CHROME_EXTENSION_USER_GESTURE_REQUIRED
  407. : JitsiTrackErrors.CHROME_EXTENSION_INSTALLATION_ERROR;
  408. failCallback(new JitsiTrackError(error, msg));
  409. },
  410. /* eslint-enable max-params */
  411. checkForChromeExtensionOnInterval(options, streamCallback, failCallback) {
  412. if (options.checkAgain() === false) {
  413. failCallback(new JitsiTrackError(
  414. JitsiTrackErrors.CHROME_EXTENSION_INSTALLATION_ERROR));
  415. return;
  416. }
  417. waitForExtensionAfterInstall(this.options, options.interval, 1)
  418. .then(() => {
  419. chromeExtInstalled = true;
  420. options.listener('extensionFound');
  421. this.obtainScreenFromExtension(options,
  422. streamCallback, failCallback);
  423. })
  424. .catch(() => {
  425. this.checkForChromeExtensionOnInterval(options,
  426. streamCallback, failCallback);
  427. });
  428. }
  429. };
  430. /**
  431. * Obtains a desktop stream using getUserMedia.
  432. * For this to work on Chrome, the
  433. * 'chrome://flags/#enable-usermedia-screen-capture' flag must be enabled.
  434. *
  435. * On firefox, the document's domain must be white-listed in the
  436. * 'media.getusermedia.screensharing.allowed_domains' preference in
  437. * 'about:config'.
  438. */
  439. function obtainWebRTCScreen(options, streamCallback, failCallback) {
  440. gumFunction(
  441. [ 'screen' ],
  442. stream => streamCallback({ stream }),
  443. failCallback,
  444. options
  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. const {
  534. desktopSharingChromeSources,
  535. desktopSharingChromeExtId,
  536. gumOptions
  537. } = options;
  538. // Sends 'getStream' msg to the extension.
  539. // Extension id must be defined in the config.
  540. chrome.runtime.sendMessage(
  541. desktopSharingChromeExtId,
  542. {
  543. getStream: true,
  544. sources: desktopSharingChromeSources
  545. },
  546. response => {
  547. if (!response) {
  548. // possibly re-wraping error message to make code consistent
  549. const lastError = chrome.runtime.lastError;
  550. failCallback(lastError instanceof Error
  551. ? lastError
  552. : new JitsiTrackError(
  553. JitsiTrackErrors.CHROME_EXTENSION_GENERIC_ERROR,
  554. lastError));
  555. return;
  556. }
  557. logger.log('Response from extension: ', response);
  558. onGetStreamResponse(
  559. {
  560. response,
  561. gumOptions
  562. },
  563. streamCallback,
  564. failCallback
  565. );
  566. }
  567. );
  568. }
  569. /**
  570. * Initializes <link rel=chrome-webstore-item /> with extension id set in
  571. * config.js to support inline installs. Host site must be selected as main
  572. * website of published extension.
  573. * @param options supports "desktopSharingChromeExtId"
  574. */
  575. function initInlineInstalls(options) {
  576. if ($('link[rel=chrome-webstore-item]').length === 0) {
  577. $('head').append('<link rel="chrome-webstore-item">');
  578. }
  579. $('link[rel=chrome-webstore-item]').attr('href',
  580. getWebStoreInstallUrl(options));
  581. }
  582. /**
  583. *
  584. * @param options
  585. *
  586. * @return {Promise} - a Promise resolved once the initialization process is
  587. * finished.
  588. */
  589. function initChromeExtension(options) {
  590. // Initialize Chrome extension inline installs
  591. initInlineInstalls(options);
  592. return new Promise(resolve => {
  593. // Check if extension is installed
  594. checkChromeExtInstalled((installed, updateRequired) => {
  595. chromeExtInstalled = installed;
  596. chromeExtUpdateRequired = updateRequired;
  597. logger.info(
  598. `Chrome extension installed: ${
  599. chromeExtInstalled} updateRequired: ${
  600. chromeExtUpdateRequired}`);
  601. resolve();
  602. }, options);
  603. });
  604. }
  605. /**
  606. * Checks "retries" times on every "waitInterval"ms whether the ext is alive.
  607. * @param {Object} options the options passed to ScreanObtainer.obtainStream
  608. * @param {int} waitInterval the number of ms between retries
  609. * @param {int} retries the number of retries
  610. * @returns {Promise} returns promise that will be resolved when the extension
  611. * is alive and rejected if the extension is not alive even after "retries"
  612. * checks
  613. */
  614. function waitForExtensionAfterInstall(options, waitInterval, retries) {
  615. if (retries === 0) {
  616. return Promise.reject();
  617. }
  618. return new Promise((resolve, reject) => {
  619. let currentRetries = retries;
  620. const interval = window.setInterval(() => {
  621. checkChromeExtInstalled(installed => {
  622. if (installed) {
  623. window.clearInterval(interval);
  624. resolve();
  625. } else {
  626. currentRetries--;
  627. if (currentRetries === 0) {
  628. reject();
  629. window.clearInterval(interval);
  630. }
  631. }
  632. }, options);
  633. }, waitInterval);
  634. });
  635. }
  636. /**
  637. * Handles response from external application / extension and calls GUM to
  638. * receive the desktop streams or reports error.
  639. * @param {object} options
  640. * @param {object} options.response
  641. * @param {string} options.response.streamId - the streamId for the desktop
  642. * stream.
  643. * @param {string} options.response.error - error to be reported.
  644. * @param {object} options.gumOptions - options passed to GUM.
  645. * @param {Function} onSuccess - callback for success.
  646. * @param {Function} onFailure - callback for failure.
  647. * @param {object} gumOptions - options passed to GUM.
  648. */
  649. function onGetStreamResponse(
  650. options = {
  651. response: {},
  652. gumOptions: {}
  653. },
  654. onSuccess,
  655. onFailure) {
  656. const { streamId, streamType, error } = options.response || {};
  657. if (streamId) {
  658. gumFunction(
  659. [ 'desktop' ],
  660. stream => onSuccess({
  661. stream,
  662. sourceId: streamId,
  663. sourceType: streamType
  664. }),
  665. onFailure,
  666. {
  667. desktopStream: streamId,
  668. ...options.gumOptions
  669. });
  670. } else {
  671. // As noted in Chrome Desktop Capture API:
  672. // If user didn't select any source (i.e. canceled the prompt)
  673. // then the callback is called with an empty streamId.
  674. if (streamId === '') {
  675. onFailure(new JitsiTrackError(
  676. JitsiTrackErrors.CHROME_EXTENSION_USER_CANCELED));
  677. return;
  678. }
  679. onFailure(new JitsiTrackError(
  680. JitsiTrackErrors.CHROME_EXTENSION_GENERIC_ERROR,
  681. error));
  682. }
  683. }
  684. /**
  685. * Starts the detection of an installed jidesha extension for firefox.
  686. * @param options supports "desktopSharingFirefoxDisabled",
  687. * "desktopSharingFirefoxExtId"
  688. */
  689. function initFirefoxExtensionDetection(options) {
  690. if (options.desktopSharingFirefoxDisabled) {
  691. return;
  692. }
  693. if (firefoxExtInstalled === false || firefoxExtInstalled === true) {
  694. return;
  695. }
  696. if (!options.desktopSharingFirefoxExtId) {
  697. firefoxExtInstalled = false;
  698. return;
  699. }
  700. const img = document.createElement('img');
  701. img.onload = () => {
  702. logger.log('Detected firefox screen sharing extension.');
  703. firefoxExtInstalled = true;
  704. };
  705. img.onerror = () => {
  706. logger.log('Detected lack of firefox screen sharing extension.');
  707. firefoxExtInstalled = false;
  708. };
  709. // The jidesha extension exposes an empty image file under the url:
  710. // "chrome://EXT_ID/content/DOMAIN.png"
  711. // Where EXT_ID is the ID of the extension with "@" replaced by ".", and
  712. // DOMAIN is a domain whitelisted by the extension.
  713. const extId = options.desktopSharingFirefoxExtId.replace('@', '.');
  714. const domain = document.location.hostname;
  715. const src = `chrome://${extId}/content/${domain}.png`;
  716. img.setAttribute('src', src);
  717. }
  718. export default ScreenObtainer;