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

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