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

desktopsharing.js 10KB

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