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

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