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

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