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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626
  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. let gumFunction = null;
  19. /**
  20. * The error message returned by chrome when the extension is installed.
  21. */
  22. const CHROME_NO_EXTENSION_ERROR_MSG // eslint-disable-line no-unused-vars
  23. = 'Could not establish connection. Receiving end does not exist.';
  24. /**
  25. * Handles obtaining a stream from a screen capture on different browsers.
  26. */
  27. const ScreenObtainer = {
  28. /**
  29. * If not <tt>null</tt> it means that the initialization process is still in
  30. * progress. It is used to make desktop stream request wait and continue
  31. * after it's done.
  32. * {@type Promise|null}
  33. */
  34. intChromeExtPromise: null,
  35. obtainStream: null,
  36. /**
  37. * Initializes the function used to obtain a screen capture
  38. * (this.obtainStream).
  39. *
  40. * @param {object} options
  41. * @param {boolean} [options.desktopSharingChromeDisabled]
  42. * @param {boolean} [options.desktopSharingChromeExtId]
  43. * @param {boolean} [options.desktopSharingFirefoxDisabled]
  44. * @param {Function} gum GUM method
  45. */
  46. init(options = {
  47. desktopSharingChromeDisabled: false,
  48. desktopSharingChromeExtId: null,
  49. desktopSharingFirefoxDisabled: false
  50. }, gum) {
  51. this.options = options;
  52. gumFunction = gum;
  53. this.obtainStream = this._createObtainStreamMethod(options);
  54. if (!this.obtainStream) {
  55. logger.info('Desktop sharing disabled');
  56. }
  57. },
  58. /**
  59. * Returns a method which will be used to obtain the screen sharing stream
  60. * (based on the browser type).
  61. *
  62. * @param {object} options passed from {@link init} - check description
  63. * there
  64. * @returns {Function}
  65. * @private
  66. */
  67. _createObtainStreamMethod(options) {
  68. if (browser.isNWJS()) {
  69. return (_, onSuccess, onFailure) => {
  70. window.JitsiMeetNW.obtainDesktopStream(
  71. onSuccess,
  72. (error, constraints) => {
  73. let jitsiError;
  74. // FIXME:
  75. // This is very very dirty fix for recognising that the
  76. // user have clicked the cancel button from the Desktop
  77. // sharing pick window. The proper solution would be to
  78. // detect this in the NWJS application by checking the
  79. // streamId === "". Even better solution would be to
  80. // stop calling GUM from the NWJS app and just pass the
  81. // streamId to lib-jitsi-meet. This way the desktop
  82. // sharing implementation for NWJS and chrome extension
  83. // will be the same and lib-jitsi-meet will be able to
  84. // control the constraints, check the streamId, etc.
  85. //
  86. // I cannot find documentation about "InvalidStateError"
  87. // but this is what we are receiving from GUM when the
  88. // streamId for the desktop sharing is "".
  89. if (error && error.name === 'InvalidStateError') {
  90. jitsiError = new JitsiTrackError(
  91. JitsiTrackErrors.CHROME_EXTENSION_USER_CANCELED
  92. );
  93. } else {
  94. jitsiError = new JitsiTrackError(
  95. error, constraints, [ 'desktop' ]);
  96. }
  97. (typeof onFailure === 'function')
  98. && onFailure(jitsiError);
  99. });
  100. };
  101. } else if (browser.isElectron()) {
  102. return this.obtainScreenOnElectron;
  103. } else if (browser.isChrome() || browser.isOpera()) {
  104. if (browser.supportsGetDisplayMedia()
  105. && !options.desktopSharingChromeDisabled) {
  106. return this.obtainScreenFromGetDisplayMedia;
  107. } else if (options.desktopSharingChromeDisabled
  108. || !options.desktopSharingChromeExtId) {
  109. return null;
  110. }
  111. logger.info('Using Chrome extension for desktop sharing');
  112. this.intChromeExtPromise
  113. = initChromeExtension(options).then(() => {
  114. this.intChromeExtPromise = null;
  115. });
  116. return this.obtainScreenFromExtension;
  117. } else if (browser.isFirefox()) {
  118. if (options.desktopSharingFirefoxDisabled) {
  119. return null;
  120. } else if (browser.supportsGetDisplayMedia()) {
  121. // Firefox 66 support getDisplayMedia
  122. return this.obtainScreenFromGetDisplayMedia;
  123. }
  124. // Legacy Firefox
  125. return this.obtainScreenOnFirefox;
  126. }
  127. logger.log(
  128. 'Screen sharing not supported by the current browser: ',
  129. browser.getName());
  130. return null;
  131. },
  132. /**
  133. * Checks whether obtaining a screen capture is supported in the current
  134. * environment.
  135. * @returns {boolean}
  136. */
  137. isSupported() {
  138. return this.obtainStream !== null;
  139. },
  140. /**
  141. * Obtains a screen capture stream on Firefox.
  142. * @param callback
  143. * @param errorCallback
  144. */
  145. obtainScreenOnFirefox(options, callback, errorCallback) {
  146. obtainWebRTCScreen(options.gumOptions, callback, errorCallback);
  147. },
  148. /**
  149. * Obtains a screen capture stream on Electron.
  150. *
  151. * @param {Object} [options] - Screen sharing options.
  152. * @param {Array<string>} [options.desktopSharingSources] - Array with the
  153. * sources that have to be displayed in the desktop picker window ('screen',
  154. * 'window', etc.).
  155. * @param onSuccess - Success callback.
  156. * @param onFailure - Failure callback.
  157. */
  158. obtainScreenOnElectron(options = {}, onSuccess, onFailure) {
  159. if (window.JitsiMeetScreenObtainer
  160. && window.JitsiMeetScreenObtainer.openDesktopPicker) {
  161. const { desktopSharingSources, gumOptions } = options;
  162. window.JitsiMeetScreenObtainer.openDesktopPicker(
  163. {
  164. desktopSharingSources: desktopSharingSources
  165. || this.options.desktopSharingChromeSources
  166. },
  167. (streamId, streamType, screenShareAudio = false) =>
  168. onGetStreamResponse(
  169. {
  170. response: {
  171. streamId,
  172. streamType,
  173. screenShareAudio
  174. },
  175. gumOptions
  176. },
  177. onSuccess,
  178. onFailure
  179. ),
  180. err => onFailure(new JitsiTrackError(
  181. JitsiTrackErrors.ELECTRON_DESKTOP_PICKER_ERROR,
  182. err
  183. ))
  184. );
  185. } else {
  186. onFailure(new JitsiTrackError(
  187. JitsiTrackErrors.ELECTRON_DESKTOP_PICKER_NOT_FOUND));
  188. }
  189. },
  190. /**
  191. * Asks Chrome extension to call chooseDesktopMedia and gets chrome
  192. * 'desktop' stream for returned stream token.
  193. */
  194. obtainScreenFromExtension(options, streamCallback, failCallback) {
  195. if (this.intChromeExtPromise !== null) {
  196. this.intChromeExtPromise.then(() => {
  197. this.obtainScreenFromExtension(
  198. options, streamCallback, failCallback);
  199. });
  200. return;
  201. }
  202. const {
  203. desktopSharingChromeExtId,
  204. desktopSharingChromeSources
  205. } = this.options;
  206. const {
  207. gumOptions
  208. } = options;
  209. const doGetStreamFromExtensionOptions = {
  210. desktopSharingChromeExtId,
  211. desktopSharingChromeSources:
  212. options.desktopSharingSources || desktopSharingChromeSources,
  213. gumOptions
  214. };
  215. if (chromeExtInstalled) {
  216. doGetStreamFromExtension(
  217. doGetStreamFromExtensionOptions,
  218. streamCallback,
  219. failCallback);
  220. } else {
  221. if (chromeExtUpdateRequired) {
  222. /* eslint-disable no-alert */
  223. alert(
  224. 'Jitsi Desktop Streamer requires update. '
  225. + 'Changes will take effect after next Chrome restart.');
  226. /* eslint-enable no-alert */
  227. }
  228. this.handleExternalInstall(options, streamCallback,
  229. failCallback);
  230. }
  231. },
  232. /* eslint-disable max-params */
  233. handleExternalInstall(options, streamCallback, failCallback, e) {
  234. const webStoreInstallUrl = getWebStoreInstallUrl(this.options);
  235. options.listener('waitingForExtension', webStoreInstallUrl);
  236. this.checkForChromeExtensionOnInterval(options, streamCallback,
  237. failCallback, e);
  238. },
  239. /* eslint-enable max-params */
  240. checkForChromeExtensionOnInterval(options, streamCallback, failCallback) {
  241. if (options.checkAgain() === false) {
  242. failCallback(new JitsiTrackError(
  243. JitsiTrackErrors.CHROME_EXTENSION_INSTALLATION_ERROR));
  244. return;
  245. }
  246. waitForExtensionAfterInstall(this.options, options.interval, 1)
  247. .then(() => {
  248. chromeExtInstalled = true;
  249. options.listener('extensionFound');
  250. this.obtainScreenFromExtension(options,
  251. streamCallback, failCallback);
  252. })
  253. .catch(() => {
  254. this.checkForChromeExtensionOnInterval(options,
  255. streamCallback, failCallback);
  256. });
  257. },
  258. /**
  259. * Obtains a screen capture stream using getDisplayMedia.
  260. *
  261. * @param callback - The success callback.
  262. * @param errorCallback - The error callback.
  263. */
  264. obtainScreenFromGetDisplayMedia(options, callback, errorCallback) {
  265. logger.info('Using getDisplayMedia for screen sharing');
  266. let getDisplayMedia;
  267. if (navigator.getDisplayMedia) {
  268. getDisplayMedia = navigator.getDisplayMedia.bind(navigator);
  269. } else {
  270. // eslint-disable-next-line max-len
  271. getDisplayMedia = navigator.mediaDevices.getDisplayMedia.bind(navigator.mediaDevices);
  272. }
  273. getDisplayMedia({ video: true,
  274. audio: true })
  275. .then(stream => {
  276. let applyConstraintsPromise;
  277. if (stream
  278. && stream.getTracks()
  279. && stream.getTracks().length > 0) {
  280. const videoTrack = stream.getVideoTracks()[0];
  281. // Apply video track constraint.
  282. if (videoTrack) {
  283. applyConstraintsPromise = videoTrack.applyConstraints(options.trackOptions);
  284. }
  285. } else {
  286. applyConstraintsPromise = Promise.resolve();
  287. }
  288. applyConstraintsPromise.then(() =>
  289. callback({
  290. stream,
  291. sourceId: stream.id
  292. }));
  293. })
  294. .catch(() =>
  295. errorCallback(new JitsiTrackError(JitsiTrackErrors
  296. .CHROME_EXTENSION_USER_CANCELED)));
  297. }
  298. };
  299. /**
  300. * Obtains a desktop stream using getUserMedia.
  301. * For this to work on Chrome, the
  302. * 'chrome://flags/#enable-usermedia-screen-capture' flag must be enabled.
  303. *
  304. * On firefox, the document's domain must be white-listed in the
  305. * 'media.getusermedia.screensharing.allowed_domains' preference in
  306. * 'about:config'.
  307. */
  308. function obtainWebRTCScreen(options, streamCallback, failCallback) {
  309. gumFunction([ 'screen' ], options)
  310. .then(stream => streamCallback({ stream }), failCallback);
  311. }
  312. /**
  313. * Constructs inline install URL for Chrome desktop streaming extension.
  314. * The 'chromeExtensionId' must be defined in options parameter.
  315. * @param options supports "desktopSharingChromeExtId"
  316. * @returns {string}
  317. */
  318. function getWebStoreInstallUrl(options) {
  319. return (
  320. `https://chrome.google.com/webstore/detail/${
  321. options.desktopSharingChromeExtId}`);
  322. }
  323. /**
  324. * Checks whether an update of the Chrome extension is required.
  325. * @param minVersion minimal required version
  326. * @param extVersion current extension version
  327. * @returns {boolean}
  328. */
  329. function isUpdateRequired(minVersion, extVersion) {
  330. try {
  331. const s1 = minVersion.split('.');
  332. const s2 = extVersion.split('.');
  333. const len = Math.max(s1.length, s2.length);
  334. for (let i = 0; i < len; i++) {
  335. let n1 = 0,
  336. n2 = 0;
  337. if (i < s1.length) {
  338. n1 = parseInt(s1[i], 10);
  339. }
  340. if (i < s2.length) {
  341. n2 = parseInt(s2[i], 10);
  342. }
  343. if (isNaN(n1) || isNaN(n2)) {
  344. return true;
  345. } else if (n1 !== n2) {
  346. return n1 > n2;
  347. }
  348. }
  349. // will happen if both versions have identical numbers in
  350. // their components (even if one of them is longer, has more components)
  351. return false;
  352. } catch (e) {
  353. GlobalOnErrorHandler.callErrorHandler(e);
  354. logger.error('Failed to parse extension version', e);
  355. return true;
  356. }
  357. }
  358. /**
  359. *
  360. * @param callback
  361. * @param options
  362. */
  363. function checkChromeExtInstalled(callback, options) {
  364. if (typeof chrome === 'undefined' || !chrome || !chrome.runtime) {
  365. // No API, so no extension for sure
  366. callback(false, false);
  367. return;
  368. }
  369. chrome.runtime.sendMessage(
  370. options.desktopSharingChromeExtId,
  371. { getVersion: true },
  372. response => {
  373. if (!response || !response.version) {
  374. // Communication failure - assume that no endpoint exists
  375. logger.warn(
  376. 'Extension not installed?: ', chrome.runtime.lastError);
  377. callback(false, false);
  378. return;
  379. }
  380. // Check installed extension version
  381. const extVersion = response.version;
  382. logger.log(`Extension version is: ${extVersion}`);
  383. const updateRequired
  384. = isUpdateRequired(
  385. options.desktopSharingChromeMinExtVersion,
  386. extVersion);
  387. callback(!updateRequired, updateRequired);
  388. }
  389. );
  390. }
  391. /**
  392. *
  393. * @param options
  394. * @param streamCallback
  395. * @param failCallback
  396. */
  397. function doGetStreamFromExtension(options, streamCallback, failCallback) {
  398. const {
  399. desktopSharingChromeSources,
  400. desktopSharingChromeExtId,
  401. gumOptions
  402. } = options;
  403. // Sends 'getStream' msg to the extension.
  404. // Extension id must be defined in the config.
  405. chrome.runtime.sendMessage(
  406. desktopSharingChromeExtId,
  407. {
  408. getStream: true,
  409. sources: desktopSharingChromeSources
  410. },
  411. response => {
  412. if (!response) {
  413. // possibly re-wraping error message to make code consistent
  414. const lastError = chrome.runtime.lastError;
  415. failCallback(lastError instanceof Error
  416. ? lastError
  417. : new JitsiTrackError(
  418. JitsiTrackErrors.CHROME_EXTENSION_GENERIC_ERROR,
  419. lastError));
  420. return;
  421. }
  422. logger.log('Response from extension: ', response);
  423. onGetStreamResponse(
  424. {
  425. response,
  426. gumOptions
  427. },
  428. streamCallback,
  429. failCallback
  430. );
  431. }
  432. );
  433. }
  434. /**
  435. * Initializes <link rel=chrome-webstore-item /> with extension id set in
  436. * config.js to support inline installs. Host site must be selected as main
  437. * website of published extension.
  438. * @param options supports "desktopSharingChromeExtId"
  439. */
  440. function initInlineInstalls(options) {
  441. if ($('link[rel=chrome-webstore-item]').length === 0) {
  442. $('head').append('<link rel="chrome-webstore-item">');
  443. }
  444. $('link[rel=chrome-webstore-item]').attr('href',
  445. getWebStoreInstallUrl(options));
  446. }
  447. /**
  448. *
  449. * @param options
  450. *
  451. * @return {Promise} - a Promise resolved once the initialization process is
  452. * finished.
  453. */
  454. function initChromeExtension(options) {
  455. // Initialize Chrome extension inline installs
  456. initInlineInstalls(options);
  457. return new Promise(resolve => {
  458. // Check if extension is installed
  459. checkChromeExtInstalled((installed, updateRequired) => {
  460. chromeExtInstalled = installed;
  461. chromeExtUpdateRequired = updateRequired;
  462. logger.info(
  463. `Chrome extension installed: ${
  464. chromeExtInstalled} updateRequired: ${
  465. chromeExtUpdateRequired}`);
  466. resolve();
  467. }, options);
  468. });
  469. }
  470. /**
  471. * Checks "retries" times on every "waitInterval"ms whether the ext is alive.
  472. * @param {Object} options the options passed to ScreanObtainer.obtainStream
  473. * @param {int} waitInterval the number of ms between retries
  474. * @param {int} retries the number of retries
  475. * @returns {Promise} returns promise that will be resolved when the extension
  476. * is alive and rejected if the extension is not alive even after "retries"
  477. * checks
  478. */
  479. function waitForExtensionAfterInstall(options, waitInterval, retries) {
  480. if (retries === 0) {
  481. return Promise.reject();
  482. }
  483. return new Promise((resolve, reject) => {
  484. let currentRetries = retries;
  485. const interval = window.setInterval(() => {
  486. checkChromeExtInstalled(installed => {
  487. if (installed) {
  488. window.clearInterval(interval);
  489. resolve();
  490. } else {
  491. currentRetries--;
  492. if (currentRetries === 0) {
  493. reject();
  494. window.clearInterval(interval);
  495. }
  496. }
  497. }, options);
  498. }, waitInterval);
  499. });
  500. }
  501. /**
  502. * Handles response from external application / extension and calls GUM to
  503. * receive the desktop streams or reports error.
  504. * @param {object} options
  505. * @param {object} options.response
  506. * @param {string} options.response.streamId - the streamId for the desktop
  507. * stream.
  508. * @param {bool} options.response.screenShareAudio - Used by electron clients to
  509. * enable system audio screen sharing.
  510. * @param {string} options.response.error - error to be reported.
  511. * @param {object} options.gumOptions - options passed to GUM.
  512. * @param {Function} onSuccess - callback for success.
  513. * @param {Function} onFailure - callback for failure.
  514. * @param {object} gumOptions - options passed to GUM.
  515. */
  516. function onGetStreamResponse(
  517. options = {
  518. response: {},
  519. gumOptions: {}
  520. },
  521. onSuccess,
  522. onFailure) {
  523. const { streamId, streamType, screenShareAudio, error } = options.response || {};
  524. if (streamId) {
  525. const gumOptions = {
  526. desktopStream: streamId,
  527. screenShareAudio,
  528. ...options.gumOptions
  529. };
  530. gumFunction([ 'desktop' ], gumOptions)
  531. .then(stream => onSuccess({
  532. stream,
  533. sourceId: streamId,
  534. sourceType: streamType
  535. }), onFailure);
  536. } else {
  537. // As noted in Chrome Desktop Capture API:
  538. // If user didn't select any source (i.e. canceled the prompt)
  539. // then the callback is called with an empty streamId.
  540. if (streamId === '') {
  541. onFailure(new JitsiTrackError(
  542. JitsiTrackErrors.CHROME_EXTENSION_USER_CANCELED));
  543. return;
  544. }
  545. onFailure(new JitsiTrackError(
  546. JitsiTrackErrors.CHROME_EXTENSION_GENERIC_ERROR,
  547. error));
  548. }
  549. }
  550. export default ScreenObtainer;