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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528
  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. var JitsiTrackErrors = require("../../JitsiTrackErrors");
  7. var JitsiTrackError = require("../../JitsiTrackError");
  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. }, 500);
  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(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, e) {
  260. if ( CHROME_EXTENSION_POPUP_ERROR !== e &&
  261. (e.name !== JitsiTrackErrors.CHROME_EXTENSION_GENERIC_ERROR ||
  262. !e.message ||
  263. e.message.message !== CHROME_NO_EXTENSION_ERROR_MSG)) {
  264. this.handleExtensionInstallationError(null, streamCallback,
  265. failCallback, e);
  266. return;
  267. }
  268. if (options.checkAgain() === false) {
  269. failCallback(new JitsiTrackError(
  270. JitsiTrackErrors.CHROME_EXTENSION_INSTALLATION_ERROR));
  271. return;
  272. }
  273. var args = arguments;
  274. var self = this;
  275. window.setTimeout(function () {
  276. doGetStreamFromExtension(self.options,
  277. function () {
  278. chromeExtInstalled = true;
  279. streamCallback.apply(null, arguments);
  280. }, self.checkForChromeExtensionOnInterval.bind(
  281. self, options, streamCallback, failCallback));
  282. }, options.interval);
  283. }
  284. };
  285. /**
  286. * Obtains a desktop stream using getUserMedia.
  287. * For this to work on Chrome, the
  288. * 'chrome://flags/#enable-usermedia-screen-capture' flag must be enabled.
  289. *
  290. * On firefox, the document's domain must be white-listed in the
  291. * 'media.getusermedia.screensharing.allowed_domains' preference in
  292. * 'about:config'.
  293. */
  294. function obtainWebRTCScreen(options, streamCallback, failCallback) {
  295. GUM(
  296. ['screen'],
  297. streamCallback,
  298. failCallback
  299. );
  300. }
  301. /**
  302. * Constructs inline install URL for Chrome desktop streaming extension.
  303. * The 'chromeExtensionId' must be defined in options parameter.
  304. * @param options supports "desktopSharingChromeExtId" and "chromeExtensionId"
  305. * @returns {string}
  306. */
  307. function getWebStoreInstallUrl(options)
  308. {
  309. //TODO remove chromeExtensionId (deprecated)
  310. return "https://chrome.google.com/webstore/detail/" +
  311. (options.desktopSharingChromeExtId || options.chromeExtensionId);
  312. }
  313. /**
  314. * Checks whether an update of the Chrome extension is required.
  315. * @param minVersion minimal required version
  316. * @param extVersion current extension version
  317. * @returns {boolean}
  318. */
  319. function isUpdateRequired(minVersion, extVersion) {
  320. try {
  321. var s1 = minVersion.split('.');
  322. var s2 = extVersion.split('.');
  323. var len = Math.max(s1.length, s2.length);
  324. for (var i = 0; i < len; i++) {
  325. var n1 = 0,
  326. n2 = 0;
  327. if (i < s1.length)
  328. n1 = parseInt(s1[i]);
  329. if (i < s2.length)
  330. n2 = parseInt(s2[i]);
  331. if (isNaN(n1) || isNaN(n2)) {
  332. return true;
  333. } else if (n1 !== n2) {
  334. return n1 > n2;
  335. }
  336. }
  337. // will happen if both versions have identical numbers in
  338. // their components (even if one of them is longer, has more components)
  339. return false;
  340. }
  341. catch (e) {
  342. GlobalOnErrorHandler.callErrorHandler(e);
  343. logger.error("Failed to parse extension version", e);
  344. return true;
  345. }
  346. }
  347. function checkChromeExtInstalled(callback, options) {
  348. if (typeof chrome === "undefined" || !chrome || !chrome.runtime) {
  349. // No API, so no extension for sure
  350. callback(false, false);
  351. return;
  352. }
  353. chrome.runtime.sendMessage(
  354. //TODO: remove chromeExtensionId (deprecated)
  355. (options.desktopSharingChromeExtId || options.chromeExtensionId),
  356. { getVersion: true },
  357. function (response) {
  358. if (!response || !response.version) {
  359. // Communication failure - assume that no endpoint exists
  360. logger.warn(
  361. "Extension not installed?: ", chrome.runtime.lastError);
  362. callback(false, false);
  363. return;
  364. }
  365. // Check installed extension version
  366. var extVersion = response.version;
  367. logger.log('Extension version is: ' + extVersion);
  368. //TODO: remove minChromeExtVersion (deprecated)
  369. var updateRequired
  370. = isUpdateRequired(
  371. (options.desktopSharingChromeMinExtVersion ||
  372. options.minChromeExtVersion),
  373. extVersion);
  374. callback(!updateRequired, updateRequired);
  375. }
  376. );
  377. }
  378. function doGetStreamFromExtension(options, streamCallback, failCallback) {
  379. // Sends 'getStream' msg to the extension.
  380. // Extension id must be defined in the config.
  381. chrome.runtime.sendMessage(
  382. //TODO: remove chromeExtensionId (deprecated)
  383. (options.desktopSharingChromeExtId || options.chromeExtensionId),
  384. {
  385. getStream: true,
  386. //TODO: remove desktopSharingSources (deprecated).
  387. sources: (options.desktopSharingChromeSources ||
  388. options.desktopSharingSources)
  389. },
  390. function (response) {
  391. if (!response) {
  392. // possibly re-wraping error message to make code consistent
  393. var lastError = chrome.runtime.lastError;
  394. failCallback(lastError instanceof Error
  395. ? lastError
  396. : new JitsiTrackError(
  397. JitsiTrackErrors.CHROME_EXTENSION_GENERIC_ERROR,
  398. lastError));
  399. return;
  400. }
  401. logger.log("Response from extension: ", response);
  402. if (response.streamId) {
  403. GUM(
  404. ['desktop'],
  405. function (stream) {
  406. streamCallback(stream);
  407. },
  408. failCallback,
  409. {desktopStream: response.streamId});
  410. } else {
  411. // As noted in Chrome Desktop Capture API:
  412. // If user didn't select any source (i.e. canceled the prompt)
  413. // then the callback is called with an empty streamId.
  414. if(response.streamId === "")
  415. {
  416. failCallback(new JitsiTrackError(
  417. JitsiTrackErrors.CHROME_EXTENSION_USER_CANCELED));
  418. return;
  419. }
  420. failCallback(new JitsiTrackError(
  421. JitsiTrackErrors.CHROME_EXTENSION_GENERIC_ERROR,
  422. response.error));
  423. }
  424. }
  425. );
  426. }
  427. /**
  428. * Initializes <link rel=chrome-webstore-item /> with extension id set in
  429. * config.js to support inline installs. Host site must be selected as main
  430. * website of published extension.
  431. * @param options supports "desktopSharingChromeExtId" and "chromeExtensionId"
  432. */
  433. function initInlineInstalls(options)
  434. {
  435. if($("link[rel=chrome-webstore-item]").length === 0) {
  436. $("head").append("<link rel=\"chrome-webstore-item\">");
  437. }
  438. $("link[rel=chrome-webstore-item]").attr("href",
  439. getWebStoreInstallUrl(options));
  440. }
  441. function initChromeExtension(options) {
  442. // Initialize Chrome extension inline installs
  443. initInlineInstalls(options);
  444. // Check if extension is installed
  445. checkChromeExtInstalled(function (installed, updateRequired) {
  446. chromeExtInstalled = installed;
  447. chromeExtUpdateRequired = updateRequired;
  448. logger.info(
  449. "Chrome extension installed: " + chromeExtInstalled +
  450. " updateRequired: " + chromeExtUpdateRequired);
  451. }, options);
  452. }
  453. /**
  454. * Starts the detection of an installed jidesha extension for firefox.
  455. * @param options supports "desktopSharingFirefoxDisabled",
  456. * "desktopSharingFirefoxExtId" and "chromeExtensionId"
  457. */
  458. function initFirefoxExtensionDetection(options) {
  459. if (options.desktopSharingFirefoxDisabled) {
  460. return;
  461. }
  462. if (firefoxExtInstalled === false || firefoxExtInstalled === true)
  463. return;
  464. if (!options.desktopSharingFirefoxExtId) {
  465. firefoxExtInstalled = false;
  466. return;
  467. }
  468. var img = document.createElement('img');
  469. img.onload = function(){
  470. logger.log("Detected firefox screen sharing extension.");
  471. firefoxExtInstalled = true;
  472. };
  473. img.onerror = function(){
  474. logger.log("Detected lack of firefox screen sharing extension.");
  475. firefoxExtInstalled = false;
  476. };
  477. // The jidesha extension exposes an empty image file under the url:
  478. // "chrome://EXT_ID/content/DOMAIN.png"
  479. // Where EXT_ID is the ID of the extension with "@" replaced by ".", and
  480. // DOMAIN is a domain whitelisted by the extension.
  481. var src = "chrome://" +
  482. (options.desktopSharingFirefoxExtId.replace('@', '.')) +
  483. "/content/" + document.location.hostname + ".png";
  484. img.setAttribute('src', src);
  485. }
  486. module.exports = ScreenObtainer;