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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619
  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. } else if (browser.isEdge() && browser.supportsGetDisplayMedia()) {
  127. return this.obtainScreenFromGetDisplayMedia;
  128. }
  129. logger.log(
  130. 'Screen sharing not supported by the current browser: ',
  131. browser.getName());
  132. return null;
  133. },
  134. /**
  135. * Checks whether obtaining a screen capture is supported in the current
  136. * environment.
  137. * @returns {boolean}
  138. */
  139. isSupported() {
  140. return this.obtainStream !== null;
  141. },
  142. /**
  143. * Obtains a screen capture stream on Firefox.
  144. * @param callback
  145. * @param errorCallback
  146. */
  147. obtainScreenOnFirefox(options, callback, errorCallback) {
  148. obtainWebRTCScreen(options.gumOptions, callback, errorCallback);
  149. },
  150. /**
  151. * Obtains a screen capture stream on Electron.
  152. *
  153. * @param {Object} [options] - Screen sharing options.
  154. * @param {Array<string>} [options.desktopSharingSources] - Array with the
  155. * sources that have to be displayed in the desktop picker window ('screen',
  156. * 'window', etc.).
  157. * @param onSuccess - Success callback.
  158. * @param onFailure - Failure callback.
  159. */
  160. obtainScreenOnElectron(options = {}, onSuccess, onFailure) {
  161. if (window.JitsiMeetScreenObtainer
  162. && window.JitsiMeetScreenObtainer.openDesktopPicker) {
  163. const { desktopSharingSources, gumOptions } = options;
  164. window.JitsiMeetScreenObtainer.openDesktopPicker(
  165. {
  166. desktopSharingSources: desktopSharingSources
  167. || this.options.desktopSharingChromeSources
  168. },
  169. (streamId, streamType) =>
  170. onGetStreamResponse(
  171. {
  172. response: {
  173. streamId,
  174. streamType
  175. },
  176. gumOptions
  177. },
  178. onSuccess,
  179. onFailure
  180. ),
  181. err => onFailure(new JitsiTrackError(
  182. JitsiTrackErrors.ELECTRON_DESKTOP_PICKER_ERROR,
  183. err
  184. ))
  185. );
  186. } else {
  187. onFailure(new JitsiTrackError(
  188. JitsiTrackErrors.ELECTRON_DESKTOP_PICKER_NOT_FOUND));
  189. }
  190. },
  191. /**
  192. * Asks Chrome extension to call chooseDesktopMedia and gets chrome
  193. * 'desktop' stream for returned stream token.
  194. */
  195. obtainScreenFromExtension(options, streamCallback, failCallback) {
  196. if (this.intChromeExtPromise !== null) {
  197. this.intChromeExtPromise.then(() => {
  198. this.obtainScreenFromExtension(
  199. options, streamCallback, failCallback);
  200. });
  201. return;
  202. }
  203. const {
  204. desktopSharingChromeExtId,
  205. desktopSharingChromeSources
  206. } = this.options;
  207. const {
  208. gumOptions
  209. } = options;
  210. const doGetStreamFromExtensionOptions = {
  211. desktopSharingChromeExtId,
  212. desktopSharingChromeSources:
  213. options.desktopSharingSources || desktopSharingChromeSources,
  214. gumOptions
  215. };
  216. if (chromeExtInstalled) {
  217. doGetStreamFromExtension(
  218. doGetStreamFromExtensionOptions,
  219. streamCallback,
  220. failCallback);
  221. } else {
  222. if (chromeExtUpdateRequired) {
  223. /* eslint-disable no-alert */
  224. alert(
  225. 'Jitsi Desktop Streamer requires update. '
  226. + 'Changes will take effect after next Chrome restart.');
  227. /* eslint-enable no-alert */
  228. }
  229. this.handleExternalInstall(options, streamCallback,
  230. failCallback);
  231. }
  232. },
  233. /* eslint-disable max-params */
  234. handleExternalInstall(options, streamCallback, failCallback, e) {
  235. const webStoreInstallUrl = getWebStoreInstallUrl(this.options);
  236. options.listener('waitingForExtension', webStoreInstallUrl);
  237. this.checkForChromeExtensionOnInterval(options, streamCallback,
  238. failCallback, e);
  239. },
  240. /* eslint-enable max-params */
  241. checkForChromeExtensionOnInterval(options, streamCallback, failCallback) {
  242. if (options.checkAgain() === false) {
  243. failCallback(new JitsiTrackError(
  244. JitsiTrackErrors.CHROME_EXTENSION_INSTALLATION_ERROR));
  245. return;
  246. }
  247. waitForExtensionAfterInstall(this.options, options.interval, 1)
  248. .then(() => {
  249. chromeExtInstalled = true;
  250. options.listener('extensionFound');
  251. this.obtainScreenFromExtension(options,
  252. streamCallback, failCallback);
  253. })
  254. .catch(() => {
  255. this.checkForChromeExtensionOnInterval(options,
  256. streamCallback, failCallback);
  257. });
  258. },
  259. /**
  260. * Obtains a screen capture stream using getDisplayMedia.
  261. *
  262. * @param callback - The success callback.
  263. * @param errorCallback - The error callback.
  264. */
  265. obtainScreenFromGetDisplayMedia(options, callback, errorCallback) {
  266. logger.info('Using getDisplayMedia for screen sharing');
  267. let getDisplayMedia;
  268. if (navigator.getDisplayMedia) {
  269. getDisplayMedia = navigator.getDisplayMedia.bind(navigator);
  270. } else {
  271. // eslint-disable-next-line max-len
  272. getDisplayMedia = navigator.mediaDevices.getDisplayMedia.bind(navigator.mediaDevices);
  273. }
  274. getDisplayMedia({ video: true })
  275. .then(stream => {
  276. let applyConstraintsPromise;
  277. if (stream
  278. && stream.getTracks()
  279. && stream.getTracks().length > 0) {
  280. applyConstraintsPromise = stream.getTracks()[0]
  281. .applyConstraints(options.trackOptions);
  282. } else {
  283. applyConstraintsPromise = Promise.resolve();
  284. }
  285. applyConstraintsPromise.then(() =>
  286. callback({
  287. stream,
  288. sourceId: stream.id
  289. }));
  290. })
  291. .catch(() =>
  292. errorCallback(new JitsiTrackError(JitsiTrackErrors
  293. .CHROME_EXTENSION_USER_CANCELED)));
  294. }
  295. };
  296. /**
  297. * Obtains a desktop stream using getUserMedia.
  298. * For this to work on Chrome, the
  299. * 'chrome://flags/#enable-usermedia-screen-capture' flag must be enabled.
  300. *
  301. * On firefox, the document's domain must be white-listed in the
  302. * 'media.getusermedia.screensharing.allowed_domains' preference in
  303. * 'about:config'.
  304. */
  305. function obtainWebRTCScreen(options, streamCallback, failCallback) {
  306. gumFunction([ 'screen' ], options)
  307. .then(stream => streamCallback({ stream }), failCallback);
  308. }
  309. /**
  310. * Constructs inline install URL for Chrome desktop streaming extension.
  311. * The 'chromeExtensionId' must be defined in options parameter.
  312. * @param options supports "desktopSharingChromeExtId"
  313. * @returns {string}
  314. */
  315. function getWebStoreInstallUrl(options) {
  316. return (
  317. `https://chrome.google.com/webstore/detail/${
  318. options.desktopSharingChromeExtId}`);
  319. }
  320. /**
  321. * Checks whether an update of the Chrome extension is required.
  322. * @param minVersion minimal required version
  323. * @param extVersion current extension version
  324. * @returns {boolean}
  325. */
  326. function isUpdateRequired(minVersion, extVersion) {
  327. try {
  328. const s1 = minVersion.split('.');
  329. const s2 = extVersion.split('.');
  330. const len = Math.max(s1.length, s2.length);
  331. for (let i = 0; i < len; i++) {
  332. let n1 = 0,
  333. n2 = 0;
  334. if (i < s1.length) {
  335. n1 = parseInt(s1[i], 10);
  336. }
  337. if (i < s2.length) {
  338. n2 = parseInt(s2[i], 10);
  339. }
  340. if (isNaN(n1) || isNaN(n2)) {
  341. return true;
  342. } else if (n1 !== n2) {
  343. return n1 > n2;
  344. }
  345. }
  346. // will happen if both versions have identical numbers in
  347. // their components (even if one of them is longer, has more components)
  348. return false;
  349. } catch (e) {
  350. GlobalOnErrorHandler.callErrorHandler(e);
  351. logger.error('Failed to parse extension version', e);
  352. return true;
  353. }
  354. }
  355. /**
  356. *
  357. * @param callback
  358. * @param options
  359. */
  360. function checkChromeExtInstalled(callback, options) {
  361. if (typeof chrome === 'undefined' || !chrome || !chrome.runtime) {
  362. // No API, so no extension for sure
  363. callback(false, false);
  364. return;
  365. }
  366. chrome.runtime.sendMessage(
  367. options.desktopSharingChromeExtId,
  368. { getVersion: true },
  369. response => {
  370. if (!response || !response.version) {
  371. // Communication failure - assume that no endpoint exists
  372. logger.warn(
  373. 'Extension not installed?: ', chrome.runtime.lastError);
  374. callback(false, false);
  375. return;
  376. }
  377. // Check installed extension version
  378. const extVersion = response.version;
  379. logger.log(`Extension version is: ${extVersion}`);
  380. const updateRequired
  381. = isUpdateRequired(
  382. options.desktopSharingChromeMinExtVersion,
  383. extVersion);
  384. callback(!updateRequired, updateRequired);
  385. }
  386. );
  387. }
  388. /**
  389. *
  390. * @param options
  391. * @param streamCallback
  392. * @param failCallback
  393. */
  394. function doGetStreamFromExtension(options, streamCallback, failCallback) {
  395. const {
  396. desktopSharingChromeSources,
  397. desktopSharingChromeExtId,
  398. gumOptions
  399. } = options;
  400. // Sends 'getStream' msg to the extension.
  401. // Extension id must be defined in the config.
  402. chrome.runtime.sendMessage(
  403. desktopSharingChromeExtId,
  404. {
  405. getStream: true,
  406. sources: desktopSharingChromeSources
  407. },
  408. response => {
  409. if (!response) {
  410. // possibly re-wraping error message to make code consistent
  411. const lastError = chrome.runtime.lastError;
  412. failCallback(lastError instanceof Error
  413. ? lastError
  414. : new JitsiTrackError(
  415. JitsiTrackErrors.CHROME_EXTENSION_GENERIC_ERROR,
  416. lastError));
  417. return;
  418. }
  419. logger.log('Response from extension: ', response);
  420. onGetStreamResponse(
  421. {
  422. response,
  423. gumOptions
  424. },
  425. streamCallback,
  426. failCallback
  427. );
  428. }
  429. );
  430. }
  431. /**
  432. * Initializes <link rel=chrome-webstore-item /> with extension id set in
  433. * config.js to support inline installs. Host site must be selected as main
  434. * website of published extension.
  435. * @param options supports "desktopSharingChromeExtId"
  436. */
  437. function initInlineInstalls(options) {
  438. if ($('link[rel=chrome-webstore-item]').length === 0) {
  439. $('head').append('<link rel="chrome-webstore-item">');
  440. }
  441. $('link[rel=chrome-webstore-item]').attr('href',
  442. getWebStoreInstallUrl(options));
  443. }
  444. /**
  445. *
  446. * @param options
  447. *
  448. * @return {Promise} - a Promise resolved once the initialization process is
  449. * finished.
  450. */
  451. function initChromeExtension(options) {
  452. // Initialize Chrome extension inline installs
  453. initInlineInstalls(options);
  454. return new Promise(resolve => {
  455. // Check if extension is installed
  456. checkChromeExtInstalled((installed, updateRequired) => {
  457. chromeExtInstalled = installed;
  458. chromeExtUpdateRequired = updateRequired;
  459. logger.info(
  460. `Chrome extension installed: ${
  461. chromeExtInstalled} updateRequired: ${
  462. chromeExtUpdateRequired}`);
  463. resolve();
  464. }, options);
  465. });
  466. }
  467. /**
  468. * Checks "retries" times on every "waitInterval"ms whether the ext is alive.
  469. * @param {Object} options the options passed to ScreanObtainer.obtainStream
  470. * @param {int} waitInterval the number of ms between retries
  471. * @param {int} retries the number of retries
  472. * @returns {Promise} returns promise that will be resolved when the extension
  473. * is alive and rejected if the extension is not alive even after "retries"
  474. * checks
  475. */
  476. function waitForExtensionAfterInstall(options, waitInterval, retries) {
  477. if (retries === 0) {
  478. return Promise.reject();
  479. }
  480. return new Promise((resolve, reject) => {
  481. let currentRetries = retries;
  482. const interval = window.setInterval(() => {
  483. checkChromeExtInstalled(installed => {
  484. if (installed) {
  485. window.clearInterval(interval);
  486. resolve();
  487. } else {
  488. currentRetries--;
  489. if (currentRetries === 0) {
  490. reject();
  491. window.clearInterval(interval);
  492. }
  493. }
  494. }, options);
  495. }, waitInterval);
  496. });
  497. }
  498. /**
  499. * Handles response from external application / extension and calls GUM to
  500. * receive the desktop streams or reports error.
  501. * @param {object} options
  502. * @param {object} options.response
  503. * @param {string} options.response.streamId - the streamId for the desktop
  504. * stream.
  505. * @param {string} options.response.error - error to be reported.
  506. * @param {object} options.gumOptions - options passed to GUM.
  507. * @param {Function} onSuccess - callback for success.
  508. * @param {Function} onFailure - callback for failure.
  509. * @param {object} gumOptions - options passed to GUM.
  510. */
  511. function onGetStreamResponse(
  512. options = {
  513. response: {},
  514. gumOptions: {}
  515. },
  516. onSuccess,
  517. onFailure) {
  518. const { streamId, streamType, error } = options.response || {};
  519. if (streamId) {
  520. const gumOptions = {
  521. desktopStream: streamId,
  522. ...options.gumOptions
  523. };
  524. gumFunction([ 'desktop' ], gumOptions)
  525. .then(stream => onSuccess({
  526. stream,
  527. sourceId: streamId,
  528. sourceType: streamType
  529. }), onFailure);
  530. } else {
  531. // As noted in Chrome Desktop Capture API:
  532. // If user didn't select any source (i.e. canceled the prompt)
  533. // then the callback is called with an empty streamId.
  534. if (streamId === '') {
  535. onFailure(new JitsiTrackError(
  536. JitsiTrackErrors.CHROME_EXTENSION_USER_CANCELED));
  537. return;
  538. }
  539. onFailure(new JitsiTrackError(
  540. JitsiTrackErrors.CHROME_EXTENSION_GENERIC_ERROR,
  541. error));
  542. }
  543. }
  544. export default ScreenObtainer;