Nelze vybrat více než 25 témat Téma musí začínat písmenem nebo číslem, může obsahovat pomlčky („-“) a může být dlouhé až 35 znaků.

ScreenObtainer.js 21KB

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