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

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