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

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