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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601
  1. /* global chrome, $, alert */
  2. const GlobalOnErrorHandler = require('../util/GlobalOnErrorHandler');
  3. const logger = require('jitsi-meet-logger').getLogger(__filename);
  4. const RTCBrowserType = require('./RTCBrowserType');
  5. import JitsiTrackError from '../../JitsiTrackError';
  6. import * as JitsiTrackErrors from '../../JitsiTrackErrors';
  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 message returned by chrome when the extension is installed.
  45. */
  46. const CHROME_NO_EXTENSION_ERROR_MSG // eslint-disable-line no-unused-vars
  47. = 'Could not establish connection. Receiving end does not exist.';
  48. /**
  49. * Handles obtaining a stream from a screen capture on different browsers.
  50. */
  51. const ScreenObtainer = {
  52. obtainStream: null,
  53. /**
  54. * Initializes the function used to obtain a screen capture
  55. * (this.obtainStream).
  56. *
  57. * @param options {object}
  58. * @param gum {Function} GUM method
  59. */
  60. init(options, gum) {
  61. let obtainDesktopStream = null;
  62. // eslint-disable-next-line no-param-reassign
  63. this.options = options = options || {};
  64. gumFunction = gum;
  65. if (RTCBrowserType.isFirefox()) {
  66. initFirefoxExtensionDetection(options);
  67. }
  68. if (RTCBrowserType.isNWJS()) {
  69. obtainDesktopStream = (_, onSuccess, onFailure) => {
  70. window.JitsiMeetNW.obtainDesktopStream(
  71. onSuccess,
  72. (error, constraints) => {
  73. let jitsiError;
  74. // FIXME:
  75. // This is very very durty 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 (RTCBrowserType.isElectron()) {
  102. obtainDesktopStream = (_, onSuccess, onFailure) =>
  103. window.JitsiMeetElectron.obtainDesktopStream(
  104. streamId =>
  105. onGetStreamResponse({ streamId }, onSuccess, onFailure),
  106. err => onFailure(new JitsiTrackError(
  107. JitsiTrackErrors.CHROME_EXTENSION_GENERIC_ERROR, err))
  108. );
  109. } else if (RTCBrowserType.isTemasysPluginUsed()) {
  110. // XXX Don't require Temasys unless it's to be used because it
  111. // doesn't run on React Native, for example.
  112. const plugin
  113. = require('./adapter.screenshare').WebRTCPlugin.plugin;
  114. if (plugin.HasScreensharingFeature) {
  115. if (plugin.isScreensharingAvailable) {
  116. obtainDesktopStream = obtainWebRTCScreen;
  117. logger.info('Using Temasys plugin for desktop sharing');
  118. } else {
  119. logger.info(
  120. 'Screensharing not available with Temasys plugin on'
  121. + ' this site');
  122. }
  123. } else {
  124. logger.info(
  125. 'Screensharing not supported by this plugin version');
  126. }
  127. } else if (RTCBrowserType.isChrome()) {
  128. if (options.desktopSharingChromeDisabled
  129. || options.desktopSharingChromeMethod === false
  130. || !options.desktopSharingChromeExtId) {
  131. // TODO: desktopSharingChromeMethod is deprecated, remove.
  132. obtainDesktopStream = null;
  133. } else if (RTCBrowserType.getChromeVersion() >= 34) {
  134. obtainDesktopStream
  135. = this.obtainScreenFromExtension;
  136. logger.info('Using Chrome extension for desktop sharing');
  137. initChromeExtension(options);
  138. } else {
  139. logger.info('Chrome extension not supported until ver 34');
  140. }
  141. } else if (RTCBrowserType.isFirefox()) {
  142. if (options.desktopSharingFirefoxDisabled) {
  143. obtainDesktopStream = null;
  144. } else if (window.location.protocol === 'http:') {
  145. logger.log('Screen sharing is not supported over HTTP. '
  146. + 'Use of HTTPS is required.');
  147. obtainDesktopStream = null;
  148. } else {
  149. obtainDesktopStream = this.obtainScreenOnFirefox;
  150. }
  151. }
  152. if (!obtainDesktopStream) {
  153. logger.info('Desktop sharing disabled');
  154. }
  155. this.obtainStream = obtainDesktopStream;
  156. },
  157. /**
  158. * Checks whether obtaining a screen capture is supported in the current
  159. * environment.
  160. * @returns {boolean}
  161. */
  162. isSupported() {
  163. return this.obtainStream !== null;
  164. },
  165. /**
  166. * Obtains a screen capture stream on Firefox.
  167. * @param callback
  168. * @param errorCallback
  169. */
  170. obtainScreenOnFirefox(options, callback, errorCallback) {
  171. let extensionRequired = false;
  172. const { desktopSharingFirefoxMaxVersionExtRequired } = this.options;
  173. if (desktopSharingFirefoxMaxVersionExtRequired === -1
  174. || (desktopSharingFirefoxMaxVersionExtRequired >= 0
  175. && RTCBrowserType.getFirefoxVersion()
  176. <= desktopSharingFirefoxMaxVersionExtRequired)) {
  177. extensionRequired = true;
  178. logger.log(
  179. `Jidesha extension required on firefox version ${
  180. RTCBrowserType.getFirefoxVersion()}`);
  181. }
  182. if (!extensionRequired || firefoxExtInstalled === true) {
  183. obtainWebRTCScreen(options, callback, errorCallback);
  184. return;
  185. }
  186. if (reDetectFirefoxExtension) {
  187. reDetectFirefoxExtension = false;
  188. initFirefoxExtensionDetection(this.options);
  189. }
  190. // Give it some (more) time to initialize, and assume lack of
  191. // extension if it hasn't.
  192. if (firefoxExtInstalled === null) {
  193. window.setTimeout(
  194. () => {
  195. if (firefoxExtInstalled === null) {
  196. firefoxExtInstalled = false;
  197. }
  198. this.obtainScreenOnFirefox(callback, errorCallback);
  199. },
  200. 300);
  201. logger.log(
  202. 'Waiting for detection of jidesha on firefox to finish.');
  203. return;
  204. }
  205. // We need an extension and it isn't installed.
  206. // Make sure we check for the extension when the user clicks again.
  207. firefoxExtInstalled = null;
  208. reDetectFirefoxExtension = true;
  209. // Make sure desktopsharing knows that we failed, so that it doesn't get
  210. // stuck in 'switching' mode.
  211. errorCallback(
  212. new JitsiTrackError(JitsiTrackErrors.FIREFOX_EXTENSION_NEEDED));
  213. },
  214. /**
  215. * Asks Chrome extension to call chooseDesktopMedia and gets chrome
  216. * 'desktop' stream for returned stream token.
  217. */
  218. obtainScreenFromExtension(options, streamCallback, failCallback) {
  219. if (chromeExtInstalled) {
  220. doGetStreamFromExtension(this.options, streamCallback,
  221. failCallback);
  222. } else {
  223. if (chromeExtUpdateRequired) {
  224. /* eslint-disable no-alert */
  225. alert(
  226. 'Jitsi Desktop Streamer requires update. '
  227. + 'Changes will take effect after next Chrome restart.');
  228. /* eslint-enable no-alert */
  229. }
  230. try {
  231. chrome.webstore.install(
  232. getWebStoreInstallUrl(this.options),
  233. arg => {
  234. logger.log('Extension installed successfully', arg);
  235. chromeExtInstalled = true;
  236. // We need to give a moment to the endpoint to become
  237. // available.
  238. waitForExtensionAfterInstall(this.options, 200, 10)
  239. .then(() => {
  240. doGetStreamFromExtension(this.options,
  241. streamCallback, failCallback);
  242. })
  243. .catch(() => {
  244. this.handleExtensionInstallationError(options,
  245. streamCallback, failCallback);
  246. });
  247. },
  248. this.handleExtensionInstallationError.bind(this,
  249. options, streamCallback, failCallback)
  250. );
  251. } catch (e) {
  252. this.handleExtensionInstallationError(options, streamCallback,
  253. failCallback, e);
  254. }
  255. }
  256. },
  257. handleExtensionInstallationError(options, streamCallback, failCallback, e) {
  258. const webStoreInstallUrl = getWebStoreInstallUrl(this.options);
  259. if ((CHROME_EXTENSION_POPUP_ERROR === e
  260. || CHROME_EXTENSION_IFRAME_ERROR === e)
  261. && options.interval > 0
  262. && typeof options.checkAgain === 'function'
  263. && typeof options.listener === 'function') {
  264. options.listener('waitingForExtension', webStoreInstallUrl);
  265. this.checkForChromeExtensionOnInterval(options, streamCallback,
  266. failCallback, e);
  267. return;
  268. }
  269. const msg
  270. = `Failed to install the extension from ${webStoreInstallUrl}`;
  271. logger.log(msg, e);
  272. failCallback(new JitsiTrackError(
  273. JitsiTrackErrors.CHROME_EXTENSION_INSTALLATION_ERROR,
  274. msg));
  275. },
  276. checkForChromeExtensionOnInterval(options, streamCallback, failCallback) {
  277. if (options.checkAgain() === false) {
  278. failCallback(new JitsiTrackError(
  279. JitsiTrackErrors.CHROME_EXTENSION_INSTALLATION_ERROR));
  280. return;
  281. }
  282. waitForExtensionAfterInstall(this.options, options.interval, 1)
  283. .then(() => {
  284. chromeExtInstalled = true;
  285. options.listener('extensionFound');
  286. this.obtainScreenFromExtension(options,
  287. streamCallback, failCallback);
  288. })
  289. .catch(() => {
  290. this.checkForChromeExtensionOnInterval(options,
  291. streamCallback, failCallback);
  292. });
  293. }
  294. };
  295. /**
  296. * Obtains a desktop stream using getUserMedia.
  297. * For this to work on Chrome, the
  298. * 'chrome://flags/#enable-usermedia-screen-capture' flag must be enabled.
  299. *
  300. * On firefox, the document's domain must be white-listed in the
  301. * 'media.getusermedia.screensharing.allowed_domains' preference in
  302. * 'about:config'.
  303. */
  304. function obtainWebRTCScreen(options, streamCallback, failCallback) {
  305. gumFunction([ 'screen' ], streamCallback, failCallback);
  306. }
  307. /**
  308. * Constructs inline install URL for Chrome desktop streaming extension.
  309. * The 'chromeExtensionId' must be defined in options parameter.
  310. * @param options supports "desktopSharingChromeExtId"
  311. * @returns {string}
  312. */
  313. function getWebStoreInstallUrl(options) {
  314. return (
  315. `https://chrome.google.com/webstore/detail/${
  316. options.desktopSharingChromeExtId}`);
  317. }
  318. /**
  319. * Checks whether an update of the Chrome extension is required.
  320. * @param minVersion minimal required version
  321. * @param extVersion current extension version
  322. * @returns {boolean}
  323. */
  324. function isUpdateRequired(minVersion, extVersion) {
  325. try {
  326. const s1 = minVersion.split('.');
  327. const s2 = extVersion.split('.');
  328. const len = Math.max(s1.length, s2.length);
  329. for (let i = 0; i < len; i++) {
  330. let n1 = 0,
  331. n2 = 0;
  332. if (i < s1.length) {
  333. n1 = parseInt(s1[i], 10);
  334. }
  335. if (i < s2.length) {
  336. n2 = parseInt(s2[i], 10);
  337. }
  338. if (isNaN(n1) || isNaN(n2)) {
  339. return true;
  340. } else if (n1 !== n2) {
  341. return n1 > n2;
  342. }
  343. }
  344. // will happen if both versions have identical numbers in
  345. // their components (even if one of them is longer, has more components)
  346. return false;
  347. } catch (e) {
  348. GlobalOnErrorHandler.callErrorHandler(e);
  349. logger.error('Failed to parse extension version', e);
  350. return true;
  351. }
  352. }
  353. function checkChromeExtInstalled(callback, options) {
  354. if (typeof chrome === 'undefined' || !chrome || !chrome.runtime) {
  355. // No API, so no extension for sure
  356. callback(false, false);
  357. return;
  358. }
  359. chrome.runtime.sendMessage(
  360. options.desktopSharingChromeExtId,
  361. { getVersion: true },
  362. response => {
  363. if (!response || !response.version) {
  364. // Communication failure - assume that no endpoint exists
  365. logger.warn(
  366. 'Extension not installed?: ', chrome.runtime.lastError);
  367. callback(false, false);
  368. return;
  369. }
  370. // Check installed extension version
  371. const extVersion = response.version;
  372. logger.log(`Extension version is: ${extVersion}`);
  373. const updateRequired
  374. = isUpdateRequired(
  375. options.desktopSharingChromeMinExtVersion,
  376. extVersion);
  377. callback(!updateRequired, updateRequired);
  378. }
  379. );
  380. }
  381. function doGetStreamFromExtension(options, streamCallback, failCallback) {
  382. // Sends 'getStream' msg to the extension.
  383. // Extension id must be defined in the config.
  384. chrome.runtime.sendMessage(
  385. options.desktopSharingChromeExtId,
  386. {
  387. getStream: true,
  388. sources: options.desktopSharingChromeSources
  389. },
  390. response => {
  391. if (!response) {
  392. // possibly re-wraping error message to make code consistent
  393. const lastError = chrome.runtime.lastError;
  394. failCallback(lastError instanceof Error
  395. ? lastError
  396. : new JitsiTrackError(
  397. JitsiTrackErrors.CHROME_EXTENSION_GENERIC_ERROR,
  398. lastError));
  399. return;
  400. }
  401. logger.log('Response from extension: ', response);
  402. onGetStreamResponse(response, streamCallback, failCallback);
  403. }
  404. );
  405. }
  406. /**
  407. * Initializes <link rel=chrome-webstore-item /> with extension id set in
  408. * config.js to support inline installs. Host site must be selected as main
  409. * website of published extension.
  410. * @param options supports "desktopSharingChromeExtId"
  411. */
  412. function initInlineInstalls(options) {
  413. if ($('link[rel=chrome-webstore-item]').length === 0) {
  414. $('head').append('<link rel="chrome-webstore-item">');
  415. }
  416. $('link[rel=chrome-webstore-item]').attr('href',
  417. getWebStoreInstallUrl(options));
  418. }
  419. function initChromeExtension(options) {
  420. // Initialize Chrome extension inline installs
  421. initInlineInstalls(options);
  422. // Check if extension is installed
  423. checkChromeExtInstalled((installed, updateRequired) => {
  424. chromeExtInstalled = installed;
  425. chromeExtUpdateRequired = updateRequired;
  426. logger.info(
  427. `Chrome extension installed: ${chromeExtInstalled
  428. } updateRequired: ${chromeExtUpdateRequired}`);
  429. }, options);
  430. }
  431. /**
  432. * Checks "retries" times on every "waitInterval"ms whether the ext is alive.
  433. * @param {Object} options the options passed to ScreanObtainer.obtainStream
  434. * @param {int} waitInterval the number of ms between retries
  435. * @param {int} retries the number of retries
  436. * @returns {Promise} returns promise that will be resolved when the extension
  437. * is alive and rejected if the extension is not alive even after "retries"
  438. * checks
  439. */
  440. function waitForExtensionAfterInstall(options, waitInterval, retries) {
  441. if (retries === 0) {
  442. return Promise.reject();
  443. }
  444. return new Promise((resolve, reject) => {
  445. let currentRetries = retries;
  446. const interval = window.setInterval(() => {
  447. checkChromeExtInstalled(installed => {
  448. if (installed) {
  449. window.clearInterval(interval);
  450. resolve();
  451. } else {
  452. currentRetries--;
  453. if (currentRetries === 0) {
  454. reject();
  455. window.clearInterval(interval);
  456. }
  457. }
  458. }, options);
  459. }, waitInterval);
  460. });
  461. }
  462. /**
  463. * Handles response from external application / extension and calls GUM to
  464. * receive the desktop streams or reports error.
  465. * @param {object} response
  466. * @param {string} response.streamId - the streamId for the desktop stream
  467. * @param {string} response.error - error to be reported.
  468. * @param {Function} onSuccess - callback for success.
  469. * @param {Function} onFailure - callback for failure.
  470. */
  471. function onGetStreamResponse(response, onSuccess, onFailure) {
  472. if (response.streamId) {
  473. gumFunction(
  474. [ 'desktop' ],
  475. stream => onSuccess(stream),
  476. onFailure,
  477. { desktopStream: response.streamId });
  478. } else {
  479. // As noted in Chrome Desktop Capture API:
  480. // If user didn't select any source (i.e. canceled the prompt)
  481. // then the callback is called with an empty streamId.
  482. if (response.streamId === '') {
  483. onFailure(new JitsiTrackError(
  484. JitsiTrackErrors.CHROME_EXTENSION_USER_CANCELED));
  485. return;
  486. }
  487. onFailure(new JitsiTrackError(
  488. JitsiTrackErrors.CHROME_EXTENSION_GENERIC_ERROR,
  489. response.error));
  490. }
  491. }
  492. /**
  493. * Starts the detection of an installed jidesha extension for firefox.
  494. * @param options supports "desktopSharingFirefoxDisabled",
  495. * "desktopSharingFirefoxExtId"
  496. */
  497. function initFirefoxExtensionDetection(options) {
  498. if (options.desktopSharingFirefoxDisabled) {
  499. return;
  500. }
  501. if (firefoxExtInstalled === false || firefoxExtInstalled === true) {
  502. return;
  503. }
  504. if (!options.desktopSharingFirefoxExtId) {
  505. firefoxExtInstalled = false;
  506. return;
  507. }
  508. const img = document.createElement('img');
  509. img.onload = () => {
  510. logger.log('Detected firefox screen sharing extension.');
  511. firefoxExtInstalled = true;
  512. };
  513. img.onerror = () => {
  514. logger.log('Detected lack of firefox screen sharing extension.');
  515. firefoxExtInstalled = false;
  516. };
  517. // The jidesha extension exposes an empty image file under the url:
  518. // "chrome://EXT_ID/content/DOMAIN.png"
  519. // Where EXT_ID is the ID of the extension with "@" replaced by ".", and
  520. // DOMAIN is a domain whitelisted by the extension.
  521. const src
  522. = `chrome://${options.desktopSharingFirefoxExtId.replace('@', '.')
  523. }/content/${document.location.hostname}.png`;
  524. img.setAttribute('src', src);
  525. }
  526. module.exports = ScreenObtainer;