您最多选择25个主题 主题必须以字母或数字开头,可以包含连字符 (-),并且长度不得超过35个字符

ScreenObtainer.js 21KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605
  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. /* eslint-disable max-params */
  258. handleExtensionInstallationError(options, streamCallback, failCallback, e) {
  259. const webStoreInstallUrl = getWebStoreInstallUrl(this.options);
  260. if ((CHROME_EXTENSION_POPUP_ERROR === e
  261. || CHROME_EXTENSION_IFRAME_ERROR === e)
  262. && options.interval > 0
  263. && typeof options.checkAgain === 'function'
  264. && typeof options.listener === 'function') {
  265. options.listener('waitingForExtension', webStoreInstallUrl);
  266. this.checkForChromeExtensionOnInterval(options, streamCallback,
  267. failCallback, e);
  268. return;
  269. }
  270. const msg
  271. = `Failed to install the extension from ${webStoreInstallUrl}`;
  272. logger.log(msg, e);
  273. failCallback(new JitsiTrackError(
  274. JitsiTrackErrors.CHROME_EXTENSION_INSTALLATION_ERROR,
  275. msg));
  276. },
  277. /* eslint-enable max-params */
  278. checkForChromeExtensionOnInterval(options, streamCallback, failCallback) {
  279. if (options.checkAgain() === false) {
  280. failCallback(new JitsiTrackError(
  281. JitsiTrackErrors.CHROME_EXTENSION_INSTALLATION_ERROR));
  282. return;
  283. }
  284. waitForExtensionAfterInstall(this.options, options.interval, 1)
  285. .then(() => {
  286. chromeExtInstalled = true;
  287. options.listener('extensionFound');
  288. this.obtainScreenFromExtension(options,
  289. streamCallback, failCallback);
  290. })
  291. .catch(() => {
  292. this.checkForChromeExtensionOnInterval(options,
  293. streamCallback, failCallback);
  294. });
  295. }
  296. };
  297. /**
  298. * Obtains a desktop stream using getUserMedia.
  299. * For this to work on Chrome, the
  300. * 'chrome://flags/#enable-usermedia-screen-capture' flag must be enabled.
  301. *
  302. * On firefox, the document's domain must be white-listed in the
  303. * 'media.getusermedia.screensharing.allowed_domains' preference in
  304. * 'about:config'.
  305. */
  306. function obtainWebRTCScreen(options, streamCallback, failCallback) {
  307. gumFunction([ 'screen' ], streamCallback, 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. function checkChromeExtInstalled(callback, options) {
  356. if (typeof chrome === 'undefined' || !chrome || !chrome.runtime) {
  357. // No API, so no extension for sure
  358. callback(false, false);
  359. return;
  360. }
  361. chrome.runtime.sendMessage(
  362. options.desktopSharingChromeExtId,
  363. { getVersion: true },
  364. response => {
  365. if (!response || !response.version) {
  366. // Communication failure - assume that no endpoint exists
  367. logger.warn(
  368. 'Extension not installed?: ', chrome.runtime.lastError);
  369. callback(false, false);
  370. return;
  371. }
  372. // Check installed extension version
  373. const extVersion = response.version;
  374. logger.log(`Extension version is: ${extVersion}`);
  375. const updateRequired
  376. = isUpdateRequired(
  377. options.desktopSharingChromeMinExtVersion,
  378. extVersion);
  379. callback(!updateRequired, updateRequired);
  380. }
  381. );
  382. }
  383. function doGetStreamFromExtension(options, streamCallback, failCallback) {
  384. // Sends 'getStream' msg to the extension.
  385. // Extension id must be defined in the config.
  386. chrome.runtime.sendMessage(
  387. options.desktopSharingChromeExtId,
  388. {
  389. getStream: true,
  390. sources: options.desktopSharingChromeSources
  391. },
  392. response => {
  393. if (!response) {
  394. // possibly re-wraping error message to make code consistent
  395. const lastError = chrome.runtime.lastError;
  396. failCallback(lastError instanceof Error
  397. ? lastError
  398. : new JitsiTrackError(
  399. JitsiTrackErrors.CHROME_EXTENSION_GENERIC_ERROR,
  400. lastError));
  401. return;
  402. }
  403. logger.log('Response from extension: ', response);
  404. onGetStreamResponse(response, streamCallback, failCallback);
  405. }
  406. );
  407. }
  408. /**
  409. * Initializes <link rel=chrome-webstore-item /> with extension id set in
  410. * config.js to support inline installs. Host site must be selected as main
  411. * website of published extension.
  412. * @param options supports "desktopSharingChromeExtId"
  413. */
  414. function initInlineInstalls(options) {
  415. if ($('link[rel=chrome-webstore-item]').length === 0) {
  416. $('head').append('<link rel="chrome-webstore-item">');
  417. }
  418. $('link[rel=chrome-webstore-item]').attr('href',
  419. getWebStoreInstallUrl(options));
  420. }
  421. function initChromeExtension(options) {
  422. // Initialize Chrome extension inline installs
  423. initInlineInstalls(options);
  424. // Check if extension is installed
  425. checkChromeExtInstalled((installed, updateRequired) => {
  426. chromeExtInstalled = installed;
  427. chromeExtUpdateRequired = updateRequired;
  428. logger.info(
  429. `Chrome extension installed: ${chromeExtInstalled
  430. } updateRequired: ${chromeExtUpdateRequired}`);
  431. }, options);
  432. }
  433. /**
  434. * Checks "retries" times on every "waitInterval"ms whether the ext is alive.
  435. * @param {Object} options the options passed to ScreanObtainer.obtainStream
  436. * @param {int} waitInterval the number of ms between retries
  437. * @param {int} retries the number of retries
  438. * @returns {Promise} returns promise that will be resolved when the extension
  439. * is alive and rejected if the extension is not alive even after "retries"
  440. * checks
  441. */
  442. function waitForExtensionAfterInstall(options, waitInterval, retries) {
  443. if (retries === 0) {
  444. return Promise.reject();
  445. }
  446. return new Promise((resolve, reject) => {
  447. let currentRetries = retries;
  448. const interval = window.setInterval(() => {
  449. checkChromeExtInstalled(installed => {
  450. if (installed) {
  451. window.clearInterval(interval);
  452. resolve();
  453. } else {
  454. currentRetries--;
  455. if (currentRetries === 0) {
  456. reject();
  457. window.clearInterval(interval);
  458. }
  459. }
  460. }, options);
  461. }, waitInterval);
  462. });
  463. }
  464. /**
  465. * Handles response from external application / extension and calls GUM to
  466. * receive the desktop streams or reports error.
  467. * @param {object} response
  468. * @param {string} response.streamId - the streamId for the desktop stream
  469. * @param {string} response.error - error to be reported.
  470. * @param {Function} onSuccess - callback for success.
  471. * @param {Function} onFailure - callback for failure.
  472. */
  473. function onGetStreamResponse(response, onSuccess, onFailure) {
  474. if (response.streamId) {
  475. gumFunction(
  476. [ 'desktop' ],
  477. stream => onSuccess(stream),
  478. onFailure,
  479. { desktopStream: response.streamId });
  480. } else {
  481. // As noted in Chrome Desktop Capture API:
  482. // If user didn't select any source (i.e. canceled the prompt)
  483. // then the callback is called with an empty streamId.
  484. if (response.streamId === '') {
  485. onFailure(new JitsiTrackError(
  486. JitsiTrackErrors.CHROME_EXTENSION_USER_CANCELED));
  487. return;
  488. }
  489. onFailure(new JitsiTrackError(
  490. JitsiTrackErrors.CHROME_EXTENSION_GENERIC_ERROR,
  491. response.error));
  492. }
  493. }
  494. /**
  495. * Starts the detection of an installed jidesha extension for firefox.
  496. * @param options supports "desktopSharingFirefoxDisabled",
  497. * "desktopSharingFirefoxExtId"
  498. */
  499. function initFirefoxExtensionDetection(options) {
  500. if (options.desktopSharingFirefoxDisabled) {
  501. return;
  502. }
  503. if (firefoxExtInstalled === false || firefoxExtInstalled === true) {
  504. return;
  505. }
  506. if (!options.desktopSharingFirefoxExtId) {
  507. firefoxExtInstalled = false;
  508. return;
  509. }
  510. const img = document.createElement('img');
  511. img.onload = () => {
  512. logger.log('Detected firefox screen sharing extension.');
  513. firefoxExtInstalled = true;
  514. };
  515. img.onerror = () => {
  516. logger.log('Detected lack of firefox screen sharing extension.');
  517. firefoxExtInstalled = false;
  518. };
  519. // The jidesha extension exposes an empty image file under the url:
  520. // "chrome://EXT_ID/content/DOMAIN.png"
  521. // Where EXT_ID is the ID of the extension with "@" replaced by ".", and
  522. // DOMAIN is a domain whitelisted by the extension.
  523. const src
  524. = `chrome://${options.desktopSharingFirefoxExtId.replace('@', '.')
  525. }/content/${document.location.hostname}.png`;
  526. img.setAttribute('src', src);
  527. }
  528. module.exports = ScreenObtainer;