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

ScreenObtainer.js 16KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453
  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. * Handles obtaining a stream from a screen capture on different browsers.
  35. */
  36. var ScreenObtainer = {
  37. obtainStream: null,
  38. /**
  39. * Initializes the function used to obtain a screen capture
  40. * (this.obtainStream).
  41. *
  42. * If the browser is Chrome, it uses the value of
  43. * 'options.desktopSharingChromeMethod' (or 'options.desktopSharing') to
  44. * decide whether to use the a Chrome extension (if the value is 'ext'),
  45. * use the "screen" media source (if the value is 'webrtc'),
  46. * or disable screen capture (if the value is other).
  47. * Note that for the "screen" media source to work the
  48. * 'chrome://flags/#enable-usermedia-screen-capture' flag must be set.
  49. */
  50. init: function(options, gum) {
  51. var obtainDesktopStream = null;
  52. this.options = options = options || {};
  53. GUM = gum;
  54. if (RTCBrowserType.isFirefox())
  55. initFirefoxExtensionDetection(options);
  56. // TODO remove this, options.desktopSharing is deprecated.
  57. var chromeMethod =
  58. (options.desktopSharingChromeMethod || options.desktopSharing);
  59. if (RTCBrowserType.isNWJS()) {
  60. obtainDesktopStream = function (onSuccess, onFailure) {
  61. window.JitsiMeetNW.obtainDesktopStream (
  62. onSuccess, function (error, constraints) {
  63. onFailure && onFailure(new JitsiTrackError(
  64. error, constraints, ["desktop"]));
  65. });
  66. };
  67. } else if (RTCBrowserType.isTemasysPluginUsed()) {
  68. if (!AdapterJS.WebRTCPlugin.plugin.HasScreensharingFeature) {
  69. logger.info("Screensharing not supported by this plugin " +
  70. "version");
  71. } else if(!AdapterJS.WebRTCPlugin.plugin.isScreensharingAvailable) {
  72. logger.info(
  73. "Screensharing not available with Temasys plugin on" +
  74. " this site");
  75. } else {
  76. obtainDesktopStream = obtainWebRTCScreen;
  77. logger.info("Using Temasys plugin for desktop sharing");
  78. }
  79. } else if (RTCBrowserType.isChrome()) {
  80. if (chromeMethod == "ext") {
  81. if (RTCBrowserType.getChromeVersion() >= 34) {
  82. obtainDesktopStream =
  83. this.obtainScreenFromExtension;
  84. logger.info("Using Chrome extension for desktop sharing");
  85. initChromeExtension(options);
  86. } else {
  87. logger.info("Chrome extension not supported until ver 34");
  88. }
  89. } else if (chromeMethod == "webrtc") {
  90. obtainDesktopStream = obtainWebRTCScreen;
  91. logger.info("Using Chrome WebRTC for desktop sharing");
  92. }
  93. } else if (RTCBrowserType.isFirefox()) {
  94. if (options.desktopSharingFirefoxDisabled) {
  95. obtainDesktopStream = null;
  96. } else if (window.location.protocol === "http:"){
  97. logger.log("Screen sharing is not supported over HTTP. " +
  98. "Use of HTTPS is required.");
  99. obtainDesktopStream = null;
  100. } else {
  101. obtainDesktopStream = this.obtainScreenOnFirefox;
  102. }
  103. }
  104. if (!obtainDesktopStream) {
  105. logger.info("Desktop sharing disabled");
  106. }
  107. this.obtainStream = obtainDesktopStream;
  108. },
  109. /**
  110. * Checks whether obtaining a screen capture is supported in the current
  111. * environment.
  112. * @returns {boolean}
  113. */
  114. isSupported: function() {
  115. return !!this.obtainStream;
  116. },
  117. /**
  118. * Obtains a screen capture stream on Firefox.
  119. * @param callback
  120. * @param errorCallback
  121. */
  122. obtainScreenOnFirefox:
  123. function (callback, errorCallback) {
  124. var self = this;
  125. var extensionRequired = false;
  126. if (this.options.desktopSharingFirefoxMaxVersionExtRequired === -1 ||
  127. (this.options.desktopSharingFirefoxMaxVersionExtRequired >= 0 &&
  128. RTCBrowserType.getFirefoxVersion() <=
  129. this.options.desktopSharingFirefoxMaxVersionExtRequired)) {
  130. extensionRequired = true;
  131. logger.log("Jidesha extension required on firefox version " +
  132. RTCBrowserType.getFirefoxVersion());
  133. }
  134. if (!extensionRequired || firefoxExtInstalled === true) {
  135. obtainWebRTCScreen(callback, errorCallback);
  136. return;
  137. }
  138. if (reDetectFirefoxExtension) {
  139. reDetectFirefoxExtension = false;
  140. initFirefoxExtensionDetection(this.options);
  141. }
  142. // Give it some (more) time to initialize, and assume lack of
  143. // extension if it hasn't.
  144. if (firefoxExtInstalled === null) {
  145. window.setTimeout(
  146. function() {
  147. if (firefoxExtInstalled === null)
  148. firefoxExtInstalled = false;
  149. self.obtainScreenOnFirefox(callback, errorCallback);
  150. },
  151. 300
  152. );
  153. logger.log("Waiting for detection of jidesha on firefox to " +
  154. "finish.");
  155. return;
  156. }
  157. // We need an extension and it isn't installed.
  158. // Make sure we check for the extension when the user clicks again.
  159. firefoxExtInstalled = null;
  160. reDetectFirefoxExtension = true;
  161. // Make sure desktopsharing knows that we failed, so that it doesn't get
  162. // stuck in 'switching' mode.
  163. errorCallback(
  164. new JitsiTrackError(JitsiTrackErrors.FIREFOX_EXTENSION_NEEDED));
  165. },
  166. /**
  167. * Asks Chrome extension to call chooseDesktopMedia and gets chrome
  168. * 'desktop' stream for returned stream token.
  169. */
  170. obtainScreenFromExtension: function (streamCallback, failCallback) {
  171. var self = this;
  172. if (chromeExtInstalled) {
  173. doGetStreamFromExtension(this.options, streamCallback,
  174. failCallback);
  175. } else {
  176. if (chromeExtUpdateRequired) {
  177. alert(
  178. 'Jitsi Desktop Streamer requires update. ' +
  179. 'Changes will take effect after next Chrome restart.');
  180. }
  181. try {
  182. chrome.webstore.install(
  183. getWebStoreInstallUrl(this.options),
  184. function (arg) {
  185. logger.log("Extension installed successfully", arg);
  186. chromeExtInstalled = true;
  187. // We need to give a moment for the endpoint to become
  188. // available
  189. window.setTimeout(function () {
  190. doGetStreamFromExtension(self.options,
  191. streamCallback, failCallback);
  192. }, 500);
  193. },
  194. handleExtensionInstallationError
  195. );
  196. } catch(e) {
  197. handleExtensionInstallationError(e);
  198. }
  199. }
  200. function handleExtensionInstallationError(e) {
  201. var msg = "Failed to install the extension from "
  202. + getWebStoreInstallUrl(self.options);
  203. logger.log(msg, e);
  204. failCallback(new JitsiTrackError(
  205. JitsiTrackErrors.CHROME_EXTENSION_INSTALLATION_ERROR,
  206. msg
  207. ));
  208. }
  209. }
  210. };
  211. /**
  212. * Obtains a desktop stream using getUserMedia.
  213. * For this to work on Chrome, the
  214. * 'chrome://flags/#enable-usermedia-screen-capture' flag must be enabled.
  215. *
  216. * On firefox, the document's domain must be white-listed in the
  217. * 'media.getusermedia.screensharing.allowed_domains' preference in
  218. * 'about:config'.
  219. */
  220. function obtainWebRTCScreen(streamCallback, failCallback) {
  221. GUM(
  222. ['screen'],
  223. streamCallback,
  224. failCallback
  225. );
  226. }
  227. /**
  228. * Constructs inline install URL for Chrome desktop streaming extension.
  229. * The 'chromeExtensionId' must be defined in options parameter.
  230. * @param options supports "desktopSharingChromeExtId" and "chromeExtensionId"
  231. * @returns {string}
  232. */
  233. function getWebStoreInstallUrl(options)
  234. {
  235. //TODO remove chromeExtensionId (deprecated)
  236. return "https://chrome.google.com/webstore/detail/" +
  237. (options.desktopSharingChromeExtId || options.chromeExtensionId);
  238. }
  239. /**
  240. * Checks whether an update of the Chrome extension is required.
  241. * @param minVersion minimal required version
  242. * @param extVersion current extension version
  243. * @returns {boolean}
  244. */
  245. function isUpdateRequired(minVersion, extVersion) {
  246. try {
  247. var s1 = minVersion.split('.');
  248. var s2 = extVersion.split('.');
  249. var len = Math.max(s1.length, s2.length);
  250. for (var i = 0; i < len; i++) {
  251. var n1 = 0,
  252. n2 = 0;
  253. if (i < s1.length)
  254. n1 = parseInt(s1[i]);
  255. if (i < s2.length)
  256. n2 = parseInt(s2[i]);
  257. if (isNaN(n1) || isNaN(n2)) {
  258. return true;
  259. } else if (n1 !== n2) {
  260. return n1 > n2;
  261. }
  262. }
  263. // will happen if both versions have identical numbers in
  264. // their components (even if one of them is longer, has more components)
  265. return false;
  266. }
  267. catch (e) {
  268. GlobalOnErrorHandler.callErrorHandler(e);
  269. logger.error("Failed to parse extension version", e);
  270. return true;
  271. }
  272. }
  273. function checkChromeExtInstalled(callback, options) {
  274. if (typeof chrome === "undefined" || !chrome || !chrome.runtime) {
  275. // No API, so no extension for sure
  276. callback(false, false);
  277. return;
  278. }
  279. chrome.runtime.sendMessage(
  280. //TODO: remove chromeExtensionId (deprecated)
  281. (options.desktopSharingChromeExtId || options.chromeExtensionId),
  282. { getVersion: true },
  283. function (response) {
  284. if (!response || !response.version) {
  285. // Communication failure - assume that no endpoint exists
  286. logger.warn(
  287. "Extension not installed?: ", chrome.runtime.lastError);
  288. callback(false, false);
  289. return;
  290. }
  291. // Check installed extension version
  292. var extVersion = response.version;
  293. logger.log('Extension version is: ' + extVersion);
  294. //TODO: remove minChromeExtVersion (deprecated)
  295. var updateRequired
  296. = isUpdateRequired(
  297. (options.desktopSharingChromeMinExtVersion ||
  298. options.minChromeExtVersion),
  299. extVersion);
  300. callback(!updateRequired, updateRequired);
  301. }
  302. );
  303. }
  304. function doGetStreamFromExtension(options, streamCallback, failCallback) {
  305. // Sends 'getStream' msg to the extension.
  306. // Extension id must be defined in the config.
  307. chrome.runtime.sendMessage(
  308. //TODO: remove chromeExtensionId (deprecated)
  309. (options.desktopSharingChromeExtId || options.chromeExtensionId),
  310. {
  311. getStream: true,
  312. //TODO: remove desktopSharingSources (deprecated).
  313. sources: (options.desktopSharingChromeSources ||
  314. options.desktopSharingSources)
  315. },
  316. function (response) {
  317. if (!response) {
  318. // possibly re-wraping error message to make code consistent
  319. var lastError = chrome.runtime.lastError;
  320. failCallback(lastError instanceof Error
  321. ? lastError
  322. : new JitsiTrackError(
  323. JitsiTrackErrors.CHROME_EXTENSION_GENERIC_ERROR,
  324. lastError));
  325. return;
  326. }
  327. logger.log("Response from extension: ", response);
  328. if (response.streamId) {
  329. GUM(
  330. ['desktop'],
  331. function (stream) {
  332. streamCallback(stream);
  333. },
  334. failCallback,
  335. {desktopStream: response.streamId});
  336. } else {
  337. // As noted in Chrome Desktop Capture API:
  338. // If user didn't select any source (i.e. canceled the prompt)
  339. // then the callback is called with an empty streamId.
  340. if(response.streamId === "")
  341. {
  342. failCallback(new JitsiTrackError(
  343. JitsiTrackErrors.CHROME_EXTENSION_USER_CANCELED));
  344. return;
  345. }
  346. failCallback(new JitsiTrackError(
  347. JitsiTrackErrors.CHROME_EXTENSION_GENERIC_ERROR,
  348. response.error));
  349. }
  350. }
  351. );
  352. }
  353. /**
  354. * Initializes <link rel=chrome-webstore-item /> with extension id set in
  355. * config.js to support inline installs. Host site must be selected as main
  356. * website of published extension.
  357. * @param options supports "desktopSharingChromeExtId" and "chromeExtensionId"
  358. */
  359. function initInlineInstalls(options)
  360. {
  361. if($("link[rel=chrome-webstore-item]").length === 0) {
  362. $("head").append("<link rel=\"chrome-webstore-item\">");
  363. }
  364. $("link[rel=chrome-webstore-item]").attr("href",
  365. getWebStoreInstallUrl(options));
  366. }
  367. function initChromeExtension(options) {
  368. // Initialize Chrome extension inline installs
  369. initInlineInstalls(options);
  370. // Check if extension is installed
  371. checkChromeExtInstalled(function (installed, updateRequired) {
  372. chromeExtInstalled = installed;
  373. chromeExtUpdateRequired = updateRequired;
  374. logger.info(
  375. "Chrome extension installed: " + chromeExtInstalled +
  376. " updateRequired: " + chromeExtUpdateRequired);
  377. }, options);
  378. }
  379. /**
  380. * Starts the detection of an installed jidesha extension for firefox.
  381. * @param options supports "desktopSharingFirefoxDisabled",
  382. * "desktopSharingFirefoxExtId" and "chromeExtensionId"
  383. */
  384. function initFirefoxExtensionDetection(options) {
  385. if (options.desktopSharingFirefoxDisabled) {
  386. return;
  387. }
  388. if (firefoxExtInstalled === false || firefoxExtInstalled === true)
  389. return;
  390. if (!options.desktopSharingFirefoxExtId) {
  391. firefoxExtInstalled = false;
  392. return;
  393. }
  394. var img = document.createElement('img');
  395. img.onload = function(){
  396. logger.log("Detected firefox screen sharing extension.");
  397. firefoxExtInstalled = true;
  398. };
  399. img.onerror = function(){
  400. logger.log("Detected lack of firefox screen sharing extension.");
  401. firefoxExtInstalled = false;
  402. };
  403. // The jidesha extension exposes an empty image file under the url:
  404. // "chrome://EXT_ID/content/DOMAIN.png"
  405. // Where EXT_ID is the ID of the extension with "@" replaced by ".", and
  406. // DOMAIN is a domain whitelisted by the extension.
  407. var src = "chrome://" +
  408. (options.desktopSharingFirefoxExtId.replace('@', '.')) +
  409. "/content/" + document.location.hostname + ".png";
  410. img.setAttribute('src', src);
  411. }
  412. module.exports = ScreenObtainer;