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

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