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.

desktopsharing.js 11KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368
  1. /* global $, alert, APP, changeLocalVideo, chrome, config, getConferenceHandler,
  2. getUserMediaWithConstraints */
  3. /**
  4. * Indicates that desktop stream is currently in use(for toggle purpose).
  5. * @type {boolean}
  6. */
  7. var isUsingScreenStream = false;
  8. /**
  9. * Indicates that switch stream operation is in progress and prevent from
  10. * triggering new events.
  11. * @type {boolean}
  12. */
  13. var switchInProgress = false;
  14. /**
  15. * Method used to get screen sharing stream.
  16. *
  17. * @type {function (stream_callback, failure_callback}
  18. */
  19. var obtainDesktopStream = null;
  20. /**
  21. * Indicates whether desktop sharing extension is installed.
  22. * @type {boolean}
  23. */
  24. var extInstalled = false;
  25. /**
  26. * Indicates whether update of desktop sharing extension is required.
  27. * @type {boolean}
  28. */
  29. var extUpdateRequired = false;
  30. /**
  31. * Flag used to cache desktop sharing enabled state. Do not use directly as
  32. * it can be <tt>null</tt>.
  33. *
  34. * @type {null|boolean}
  35. */
  36. var _desktopSharingEnabled = null;
  37. var EventEmitter = require("events");
  38. var eventEmitter = new EventEmitter();
  39. var DesktopSharingEventTypes
  40. = require("../../service/desktopsharing/DesktopSharingEventTypes");
  41. /**
  42. * Method obtains desktop stream from WebRTC 'screen' source.
  43. * Flag 'chrome://flags/#enable-usermedia-screen-capture' must be enabled.
  44. */
  45. function obtainWebRTCScreen(streamCallback, failCallback) {
  46. APP.RTC.getUserMediaWithConstraints(
  47. ['screen'],
  48. streamCallback,
  49. failCallback
  50. );
  51. }
  52. /**
  53. * Constructs inline install URL for Chrome desktop streaming extension.
  54. * The 'chromeExtensionId' must be defined in config.js.
  55. * @returns {string}
  56. */
  57. function getWebStoreInstallUrl()
  58. {
  59. return "https://chrome.google.com/webstore/detail/" +
  60. config.chromeExtensionId;
  61. }
  62. /**
  63. * Checks whether extension update is required.
  64. * @param minVersion minimal required version
  65. * @param extVersion current extension version
  66. * @returns {boolean}
  67. */
  68. function isUpdateRequired(minVersion, extVersion)
  69. {
  70. try
  71. {
  72. var s1 = minVersion.split('.');
  73. var s2 = extVersion.split('.');
  74. var len = Math.max(s1.length, s2.length);
  75. for (var i = 0; i < len; i++)
  76. {
  77. var n1 = 0,
  78. n2 = 0;
  79. if (i < s1.length)
  80. n1 = parseInt(s1[i]);
  81. if (i < s2.length)
  82. n2 = parseInt(s2[i]);
  83. if (isNaN(n1) || isNaN(n2))
  84. {
  85. return true;
  86. }
  87. else if (n1 !== n2)
  88. {
  89. return n1 > n2;
  90. }
  91. }
  92. // will happen if boths version has identical numbers in
  93. // their components (even if one of them is longer, has more components)
  94. return false;
  95. }
  96. catch (e)
  97. {
  98. console.error("Failed to parse extension version", e);
  99. APP.UI.messageHandler.showError("dialog.error",
  100. "dialog.detectext");
  101. return true;
  102. }
  103. }
  104. function checkExtInstalled(callback) {
  105. if (!chrome.runtime) {
  106. // No API, so no extension for sure
  107. callback(false, false);
  108. return;
  109. }
  110. chrome.runtime.sendMessage(
  111. config.chromeExtensionId,
  112. { getVersion: true },
  113. function (response) {
  114. if (!response || !response.version) {
  115. // Communication failure - assume that no endpoint exists
  116. console.warn(
  117. "Extension not installed?: ", chrome.runtime.lastError);
  118. callback(false, false);
  119. return;
  120. }
  121. // Check installed extension version
  122. var extVersion = response.version;
  123. console.log('Extension version is: ' + extVersion);
  124. var updateRequired
  125. = isUpdateRequired(config.minChromeExtVersion, extVersion);
  126. callback(!updateRequired, updateRequired);
  127. }
  128. );
  129. }
  130. function doGetStreamFromExtension(streamCallback, failCallback) {
  131. // Sends 'getStream' msg to the extension.
  132. // Extension id must be defined in the config.
  133. chrome.runtime.sendMessage(
  134. config.chromeExtensionId,
  135. { getStream: true, sources: config.desktopSharingSources },
  136. function (response) {
  137. if (!response) {
  138. failCallback(chrome.runtime.lastError);
  139. return;
  140. }
  141. console.log("Response from extension: " + response);
  142. if (response.streamId) {
  143. APP.RTC.getUserMediaWithConstraints(
  144. ['desktop'],
  145. function (stream) {
  146. streamCallback(stream);
  147. },
  148. failCallback,
  149. null, null, null,
  150. response.streamId);
  151. } else {
  152. failCallback("Extension failed to get the stream");
  153. }
  154. }
  155. );
  156. }
  157. /**
  158. * Asks Chrome extension to call chooseDesktopMedia and gets chrome 'desktop'
  159. * stream for returned stream token.
  160. */
  161. function obtainScreenFromExtension(streamCallback, failCallback) {
  162. if (extInstalled) {
  163. doGetStreamFromExtension(streamCallback, failCallback);
  164. } else {
  165. if (extUpdateRequired) {
  166. alert(
  167. 'Jitsi Desktop Streamer requires update. ' +
  168. 'Changes will take effect after next Chrome restart.');
  169. }
  170. chrome.webstore.install(
  171. getWebStoreInstallUrl(),
  172. function (arg) {
  173. console.log("Extension installed successfully", arg);
  174. extInstalled = true;
  175. // We need to give a moment for the endpoint to become available
  176. window.setTimeout(function () {
  177. doGetStreamFromExtension(streamCallback, failCallback);
  178. }, 500);
  179. },
  180. function (arg) {
  181. console.log("Failed to install the extension", arg);
  182. failCallback(arg);
  183. APP.UI.messageHandler.showError("dialog.error",
  184. "dialog.failtoinstall");
  185. }
  186. );
  187. }
  188. }
  189. /**
  190. * Call this method to toggle desktop sharing feature.
  191. * @param method pass "ext" to use chrome extension for desktop capture(chrome
  192. * extension required), pass "webrtc" to use WebRTC "screen" desktop
  193. * source('chrome://flags/#enable-usermedia-screen-capture' must be
  194. * enabled), pass any other string or nothing in order to disable this
  195. * feature completely.
  196. */
  197. function setDesktopSharing(method) {
  198. // Check if we are running chrome
  199. if (!navigator.webkitGetUserMedia) {
  200. obtainDesktopStream = null;
  201. console.info("Desktop sharing disabled");
  202. } else if (method == "ext") {
  203. obtainDesktopStream = obtainScreenFromExtension;
  204. console.info("Using Chrome extension for desktop sharing");
  205. } else if (method == "webrtc") {
  206. obtainDesktopStream = obtainWebRTCScreen;
  207. console.info("Using Chrome WebRTC for desktop sharing");
  208. }
  209. // Reset enabled cache
  210. _desktopSharingEnabled = null;
  211. }
  212. /**
  213. * Initializes <link rel=chrome-webstore-item /> with extension id set in
  214. * config.js to support inline installs. Host site must be selected as main
  215. * website of published extension.
  216. */
  217. function initInlineInstalls()
  218. {
  219. $("link[rel=chrome-webstore-item]").attr("href", getWebStoreInstallUrl());
  220. }
  221. function getVideoStreamFailed(error) {
  222. console.error("Failed to obtain the stream to switch to", error);
  223. switchInProgress = false;
  224. isUsingScreenStream = false;
  225. newStreamCreated(null);
  226. }
  227. function getDesktopStreamFailed(error) {
  228. console.error("Failed to obtain the stream to switch to", error);
  229. switchInProgress = false;
  230. }
  231. function streamSwitchDone() {
  232. switchInProgress = false;
  233. eventEmitter.emit(
  234. DesktopSharingEventTypes.SWITCHING_DONE,
  235. isUsingScreenStream);
  236. }
  237. function newStreamCreated(stream)
  238. {
  239. eventEmitter.emit(DesktopSharingEventTypes.NEW_STREAM_CREATED,
  240. stream, isUsingScreenStream, streamSwitchDone);
  241. }
  242. module.exports = {
  243. isUsingScreenStream: function () {
  244. return isUsingScreenStream;
  245. },
  246. /**
  247. * @returns {boolean} <tt>true</tt> if desktop sharing feature is available
  248. * and enabled.
  249. */
  250. isDesktopSharingEnabled: function () {
  251. if (_desktopSharingEnabled === null) {
  252. if (obtainDesktopStream === obtainScreenFromExtension) {
  253. // Parse chrome version
  254. var userAgent = navigator.userAgent.toLowerCase();
  255. // We can assume that user agent is chrome, because it's
  256. // enforced when 'ext' streaming method is set
  257. var ver = parseInt(userAgent.match(/chrome\/(\d+)\./)[1], 10);
  258. console.log("Chrome version" + userAgent, ver);
  259. _desktopSharingEnabled = ver >= 34;
  260. } else {
  261. _desktopSharingEnabled =
  262. obtainDesktopStream === obtainWebRTCScreen;
  263. }
  264. }
  265. return _desktopSharingEnabled;
  266. },
  267. init: function () {
  268. setDesktopSharing(config.desktopSharing);
  269. // Initialize Chrome extension inline installs
  270. if (config.chromeExtensionId) {
  271. initInlineInstalls();
  272. // Check if extension is installed
  273. checkExtInstalled(function (installed, updateRequired) {
  274. extInstalled = installed;
  275. extUpdateRequired = updateRequired;
  276. console.info(
  277. "Chrome extension installed: " + extInstalled +
  278. " updateRequired: " + extUpdateRequired);
  279. });
  280. }
  281. eventEmitter.emit(DesktopSharingEventTypes.INIT);
  282. },
  283. addListener: function (listener, type)
  284. {
  285. eventEmitter.on(type, listener);
  286. },
  287. removeListener: function (listener, type) {
  288. eventEmitter.removeListener(type, listener);
  289. },
  290. /*
  291. * Toggles screen sharing.
  292. */
  293. toggleScreenSharing: function () {
  294. if (switchInProgress || !obtainDesktopStream) {
  295. console.warn("Switch in progress or no method defined");
  296. return;
  297. }
  298. switchInProgress = true;
  299. if (!isUsingScreenStream)
  300. {
  301. // Switch to desktop stream
  302. obtainDesktopStream(
  303. function (stream) {
  304. // We now use screen stream
  305. isUsingScreenStream = true;
  306. // Hook 'ended' event to restore camera
  307. // when screen stream stops
  308. stream.addEventListener('ended',
  309. function (e) {
  310. if (!switchInProgress && isUsingScreenStream) {
  311. APP.desktopsharing.toggleScreenSharing();
  312. }
  313. }
  314. );
  315. newStreamCreated(stream);
  316. },
  317. getDesktopStreamFailed);
  318. } else {
  319. // Disable screen stream
  320. APP.RTC.getUserMediaWithConstraints(
  321. ['video'],
  322. function (stream) {
  323. // We are now using camera stream
  324. isUsingScreenStream = false;
  325. newStreamCreated(stream);
  326. },
  327. getVideoStreamFailed, config.resolution || '360'
  328. );
  329. }
  330. }
  331. };