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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526
  1. /* global chrome, $, alert */
  2. var logger = require("jitsi-meet-logger").getLogger(__filename);
  3. var RTCBrowserType = require("./RTCBrowserType");
  4. var AdapterJS = require("./adapter.screenshare");
  5. import JitsiTrackError from "../../JitsiTrackError";
  6. import * as JitsiTrackErrors from "../../JitsiTrackErrors";
  7. var GlobalOnErrorHandler = require("../util/GlobalOnErrorHandler");
  8. /**
  9. * Indicates whether the Chrome desktop sharing extension is installed.
  10. * @type {boolean}
  11. */
  12. var chromeExtInstalled = false;
  13. /**
  14. * Indicates whether an update of the Chrome desktop sharing extension is
  15. * required.
  16. * @type {boolean}
  17. */
  18. var chromeExtUpdateRequired = false;
  19. /**
  20. * Whether the jidesha extension for firefox is installed for the domain on
  21. * which we are running. Null designates an unknown value.
  22. * @type {null}
  23. */
  24. var firefoxExtInstalled = null;
  25. /**
  26. * If set to true, detection of an installed firefox extension will be started
  27. * again the next time obtainScreenOnFirefox is called (e.g. next time the
  28. * user tries to enable screen sharing).
  29. */
  30. var reDetectFirefoxExtension = false;
  31. var GUM = null;
  32. /**
  33. * The error returned by chrome when trying to start inline installation from
  34. * popup.
  35. */
  36. const CHROME_EXTENSION_POPUP_ERROR
  37. = "Inline installs can not be initiated from pop-up windows.";
  38. /**
  39. * The error message returned by chrome when the extension is installed.
  40. */
  41. const CHROME_NO_EXTENSION_ERROR_MSG // eslint-disable-line no-unused-vars
  42. = "Could not establish connection. Receiving end does not exist.";
  43. /**
  44. * Handles obtaining a stream from a screen capture on different browsers.
  45. */
  46. var ScreenObtainer = {
  47. obtainStream: null,
  48. /**
  49. * Initializes the function used to obtain a screen capture
  50. * (this.obtainStream).
  51. *
  52. * If the browser is Chrome, it uses the value of
  53. * 'options.desktopSharingChromeMethod' (or 'options.desktopSharing') to
  54. * decide whether to use the a Chrome extension (if the value is 'ext'),
  55. * use the "screen" media source (if the value is 'webrtc'),
  56. * or disable screen capture (if the value is other).
  57. * Note that for the "screen" media source to work the
  58. * 'chrome://flags/#enable-usermedia-screen-capture' flag must be set.
  59. * @param options {object}
  60. * @param gum {Function} GUM method
  61. */
  62. init: function(options, gum) {
  63. var obtainDesktopStream = null;
  64. this.options = options = options || {};
  65. GUM = gum;
  66. if (RTCBrowserType.isFirefox())
  67. initFirefoxExtensionDetection(options);
  68. // TODO remove this, options.desktopSharing is deprecated.
  69. var chromeMethod =
  70. (options.desktopSharingChromeMethod || options.desktopSharing);
  71. if (RTCBrowserType.isNWJS()) {
  72. obtainDesktopStream = function (options, onSuccess, onFailure) {
  73. window.JitsiMeetNW.obtainDesktopStream (
  74. onSuccess, function (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. if (!AdapterJS.WebRTCPlugin.plugin.HasScreensharingFeature) {
  105. logger.info("Screensharing not supported by this plugin " +
  106. "version");
  107. } else if(!AdapterJS.WebRTCPlugin.plugin.isScreensharingAvailable) {
  108. logger.info(
  109. "Screensharing not available with Temasys plugin on" +
  110. " this site");
  111. } else {
  112. obtainDesktopStream = obtainWebRTCScreen;
  113. logger.info("Using Temasys plugin for desktop sharing");
  114. }
  115. } else if (RTCBrowserType.isChrome()) {
  116. if (chromeMethod == "ext") {
  117. if (RTCBrowserType.getChromeVersion() >= 34) {
  118. obtainDesktopStream =
  119. this.obtainScreenFromExtension;
  120. logger.info("Using Chrome extension for desktop sharing");
  121. initChromeExtension(options);
  122. } else {
  123. logger.info("Chrome extension not supported until ver 34");
  124. }
  125. } else if (chromeMethod == "webrtc") {
  126. obtainDesktopStream = obtainWebRTCScreen;
  127. logger.info("Using Chrome WebRTC for desktop sharing");
  128. }
  129. } else if (RTCBrowserType.isFirefox()) {
  130. if (options.desktopSharingFirefoxDisabled) {
  131. obtainDesktopStream = null;
  132. } else if (window.location.protocol === "http:"){
  133. logger.log("Screen sharing is not supported over HTTP. " +
  134. "Use of HTTPS is required.");
  135. obtainDesktopStream = null;
  136. } else {
  137. obtainDesktopStream = this.obtainScreenOnFirefox;
  138. }
  139. }
  140. if (!obtainDesktopStream) {
  141. logger.info("Desktop sharing disabled");
  142. }
  143. this.obtainStream = obtainDesktopStream;
  144. },
  145. /**
  146. * Checks whether obtaining a screen capture is supported in the current
  147. * environment.
  148. * @returns {boolean}
  149. */
  150. isSupported: function() {
  151. return !!this.obtainStream;
  152. },
  153. /**
  154. * Obtains a screen capture stream on Firefox.
  155. * @param callback
  156. * @param errorCallback
  157. */
  158. obtainScreenOnFirefox:
  159. function (options, callback, errorCallback) {
  160. var self = this;
  161. var extensionRequired = false;
  162. if (this.options.desktopSharingFirefoxMaxVersionExtRequired === -1 ||
  163. (this.options.desktopSharingFirefoxMaxVersionExtRequired >= 0 &&
  164. RTCBrowserType.getFirefoxVersion() <=
  165. this.options.desktopSharingFirefoxMaxVersionExtRequired)) {
  166. extensionRequired = true;
  167. logger.log("Jidesha extension required on firefox version " +
  168. RTCBrowserType.getFirefoxVersion());
  169. }
  170. if (!extensionRequired || firefoxExtInstalled === true) {
  171. obtainWebRTCScreen(options, callback, errorCallback);
  172. return;
  173. }
  174. if (reDetectFirefoxExtension) {
  175. reDetectFirefoxExtension = false;
  176. initFirefoxExtensionDetection(this.options);
  177. }
  178. // Give it some (more) time to initialize, and assume lack of
  179. // extension if it hasn't.
  180. if (firefoxExtInstalled === null) {
  181. window.setTimeout(
  182. function() {
  183. if (firefoxExtInstalled === null)
  184. firefoxExtInstalled = false;
  185. self.obtainScreenOnFirefox(callback, errorCallback);
  186. },
  187. 300
  188. );
  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: function(options, streamCallback, failCallback) {
  207. var self = this;
  208. if (chromeExtInstalled) {
  209. doGetStreamFromExtension(this.options, streamCallback,
  210. failCallback);
  211. } else {
  212. if (chromeExtUpdateRequired) {
  213. alert(
  214. 'Jitsi Desktop Streamer requires update. ' +
  215. 'Changes will take effect after next Chrome restart.');
  216. }
  217. try {
  218. chrome.webstore.install(
  219. getWebStoreInstallUrl(this.options),
  220. function (arg) {
  221. logger.log("Extension installed successfully", arg);
  222. chromeExtInstalled = true;
  223. // We need to give a moment for the endpoint to become
  224. // available
  225. window.setTimeout(function () {
  226. doGetStreamFromExtension(self.options,
  227. streamCallback, failCallback);
  228. }, 2000);
  229. },
  230. this.handleExtensionInstallationError.bind(this,
  231. options, streamCallback, failCallback)
  232. );
  233. } catch(e) {
  234. this.handleExtensionInstallationError(options, streamCallback,
  235. failCallback, e);
  236. }
  237. }
  238. },
  239. handleExtensionInstallationError: function (options, streamCallback,
  240. failCallback, e) {
  241. if( CHROME_EXTENSION_POPUP_ERROR === e && options.interval > 0 &&
  242. typeof(options.checkAgain) === "function" &&
  243. typeof(options.listener) === "function") {
  244. options.listener("waitingForExtension",
  245. getWebStoreInstallUrl(this.options));
  246. this.checkForChromeExtensionOnInterval(options,
  247. streamCallback, failCallback, e);
  248. return;
  249. }
  250. var msg = "Failed to install the extension from "
  251. + getWebStoreInstallUrl(this.options);
  252. logger.log(msg, e);
  253. failCallback(new JitsiTrackError(
  254. JitsiTrackErrors.CHROME_EXTENSION_INSTALLATION_ERROR,
  255. msg
  256. ));
  257. },
  258. checkForChromeExtensionOnInterval: function (options,
  259. streamCallback, failCallback) {
  260. if (options.checkAgain() === false) {
  261. failCallback(new JitsiTrackError(
  262. JitsiTrackErrors.CHROME_EXTENSION_INSTALLATION_ERROR));
  263. return;
  264. }
  265. var self = this;
  266. window.setTimeout(function () {
  267. checkChromeExtInstalled(function (installed, updateRequired) {
  268. chromeExtInstalled = installed;
  269. chromeExtUpdateRequired = updateRequired;
  270. if(installed) {
  271. options.listener("extensionFound");
  272. self.obtainScreenFromExtension(options,
  273. streamCallback, failCallback);
  274. } else {
  275. self.checkForChromeExtensionOnInterval(options,
  276. streamCallback, failCallback);
  277. }
  278. }, self.options);
  279. }, options.interval);
  280. }
  281. };
  282. /**
  283. * Obtains a desktop stream using getUserMedia.
  284. * For this to work on Chrome, the
  285. * 'chrome://flags/#enable-usermedia-screen-capture' flag must be enabled.
  286. *
  287. * On firefox, the document's domain must be white-listed in the
  288. * 'media.getusermedia.screensharing.allowed_domains' preference in
  289. * 'about:config'.
  290. */
  291. function obtainWebRTCScreen(options, streamCallback, failCallback) {
  292. GUM(
  293. ['screen'],
  294. streamCallback,
  295. failCallback
  296. );
  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" and "chromeExtensionId"
  302. * @returns {string}
  303. */
  304. function getWebStoreInstallUrl(options)
  305. {
  306. //TODO remove chromeExtensionId (deprecated)
  307. return "https://chrome.google.com/webstore/detail/" +
  308. (options.desktopSharingChromeExtId || options.chromeExtensionId);
  309. }
  310. /**
  311. * Checks whether an update of the Chrome extension is required.
  312. * @param minVersion minimal required version
  313. * @param extVersion current extension version
  314. * @returns {boolean}
  315. */
  316. function isUpdateRequired(minVersion, extVersion) {
  317. try {
  318. var s1 = minVersion.split('.');
  319. var s2 = extVersion.split('.');
  320. var len = Math.max(s1.length, s2.length);
  321. for (var i = 0; i < len; i++) {
  322. var n1 = 0,
  323. n2 = 0;
  324. if (i < s1.length)
  325. n1 = parseInt(s1[i]);
  326. if (i < s2.length)
  327. n2 = parseInt(s2[i]);
  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. }
  338. catch (e) {
  339. GlobalOnErrorHandler.callErrorHandler(e);
  340. logger.error("Failed to parse extension version", e);
  341. return true;
  342. }
  343. }
  344. function checkChromeExtInstalled(callback, options) {
  345. if (typeof chrome === "undefined" || !chrome || !chrome.runtime) {
  346. // No API, so no extension for sure
  347. callback(false, false);
  348. return;
  349. }
  350. chrome.runtime.sendMessage(
  351. //TODO: remove chromeExtensionId (deprecated)
  352. (options.desktopSharingChromeExtId || options.chromeExtensionId),
  353. { getVersion: true },
  354. function (response) {
  355. if (!response || !response.version) {
  356. // Communication failure - assume that no endpoint exists
  357. logger.warn(
  358. "Extension not installed?: ", chrome.runtime.lastError);
  359. callback(false, false);
  360. return;
  361. }
  362. // Check installed extension version
  363. var extVersion = response.version;
  364. logger.log('Extension version is: ' + extVersion);
  365. //TODO: remove minChromeExtVersion (deprecated)
  366. var updateRequired
  367. = isUpdateRequired(
  368. (options.desktopSharingChromeMinExtVersion ||
  369. options.minChromeExtVersion),
  370. extVersion);
  371. callback(!updateRequired, updateRequired);
  372. }
  373. );
  374. }
  375. function doGetStreamFromExtension(options, streamCallback, failCallback) {
  376. // Sends 'getStream' msg to the extension.
  377. // Extension id must be defined in the config.
  378. chrome.runtime.sendMessage(
  379. //TODO: remove chromeExtensionId (deprecated)
  380. (options.desktopSharingChromeExtId || options.chromeExtensionId),
  381. {
  382. getStream: true,
  383. //TODO: remove desktopSharingSources (deprecated).
  384. sources: (options.desktopSharingChromeSources ||
  385. options.desktopSharingSources)
  386. },
  387. function (response) {
  388. if (!response) {
  389. // possibly re-wraping error message to make code consistent
  390. var lastError = chrome.runtime.lastError;
  391. failCallback(lastError instanceof Error
  392. ? lastError
  393. : new JitsiTrackError(
  394. JitsiTrackErrors.CHROME_EXTENSION_GENERIC_ERROR,
  395. lastError));
  396. return;
  397. }
  398. logger.log("Response from extension: ", response);
  399. if (response.streamId) {
  400. GUM(
  401. ['desktop'],
  402. function (stream) {
  403. streamCallback(stream);
  404. },
  405. failCallback,
  406. {desktopStream: response.streamId});
  407. } else {
  408. // As noted in Chrome Desktop Capture API:
  409. // If user didn't select any source (i.e. canceled the prompt)
  410. // then the callback is called with an empty streamId.
  411. if(response.streamId === "")
  412. {
  413. failCallback(new JitsiTrackError(
  414. JitsiTrackErrors.CHROME_EXTENSION_USER_CANCELED));
  415. return;
  416. }
  417. failCallback(new JitsiTrackError(
  418. JitsiTrackErrors.CHROME_EXTENSION_GENERIC_ERROR,
  419. response.error));
  420. }
  421. }
  422. );
  423. }
  424. /**
  425. * Initializes <link rel=chrome-webstore-item /> with extension id set in
  426. * config.js to support inline installs. Host site must be selected as main
  427. * website of published extension.
  428. * @param options supports "desktopSharingChromeExtId" and "chromeExtensionId"
  429. */
  430. function initInlineInstalls(options)
  431. {
  432. if($("link[rel=chrome-webstore-item]").length === 0) {
  433. $("head").append("<link rel=\"chrome-webstore-item\">");
  434. }
  435. $("link[rel=chrome-webstore-item]").attr("href",
  436. getWebStoreInstallUrl(options));
  437. }
  438. function initChromeExtension(options) {
  439. // Initialize Chrome extension inline installs
  440. initInlineInstalls(options);
  441. // Check if extension is installed
  442. checkChromeExtInstalled(function (installed, updateRequired) {
  443. chromeExtInstalled = installed;
  444. chromeExtUpdateRequired = updateRequired;
  445. logger.info(
  446. "Chrome extension installed: " + chromeExtInstalled +
  447. " updateRequired: " + chromeExtUpdateRequired);
  448. }, options);
  449. }
  450. /**
  451. * Starts the detection of an installed jidesha extension for firefox.
  452. * @param options supports "desktopSharingFirefoxDisabled",
  453. * "desktopSharingFirefoxExtId" and "chromeExtensionId"
  454. */
  455. function initFirefoxExtensionDetection(options) {
  456. if (options.desktopSharingFirefoxDisabled) {
  457. return;
  458. }
  459. if (firefoxExtInstalled === false || firefoxExtInstalled === true)
  460. return;
  461. if (!options.desktopSharingFirefoxExtId) {
  462. firefoxExtInstalled = false;
  463. return;
  464. }
  465. var img = document.createElement('img');
  466. img.onload = function(){
  467. logger.log("Detected firefox screen sharing extension.");
  468. firefoxExtInstalled = true;
  469. };
  470. img.onerror = function(){
  471. logger.log("Detected lack of firefox screen sharing extension.");
  472. firefoxExtInstalled = false;
  473. };
  474. // The jidesha extension exposes an empty image file under the url:
  475. // "chrome://EXT_ID/content/DOMAIN.png"
  476. // Where EXT_ID is the ID of the extension with "@" replaced by ".", and
  477. // DOMAIN is a domain whitelisted by the extension.
  478. var src = "chrome://" +
  479. (options.desktopSharingFirefoxExtId.replace('@', '.')) +
  480. "/content/" + document.location.hostname + ".png";
  481. img.setAttribute('src', src);
  482. }
  483. module.exports = ScreenObtainer;