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.

SharedVideo.js 18KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554
  1. /* global $, APP, YT, onPlayerReady, onPlayerStateChange, onPlayerError */
  2. import messageHandler from '../util/MessageHandler';
  3. import UIUtil from '../util/UIUtil';
  4. import UIEvents from '../../../service/UI/UIEvents';
  5. import VideoLayout from "../videolayout/VideoLayout";
  6. import LargeContainer from '../videolayout/LargeContainer';
  7. import SmallVideo from '../videolayout/SmallVideo';
  8. import FilmStrip from '../videolayout/FilmStrip';
  9. import ToolbarToggler from "../toolbars/ToolbarToggler";
  10. export const SHARED_VIDEO_CONTAINER_TYPE = "sharedvideo";
  11. /**
  12. * Example shared video link.
  13. * @type {string}
  14. */
  15. const defaultSharedVideoLink = "https://www.youtube.com/watch?v=xNXN7CZk8X0";
  16. /**
  17. * Manager of shared video.
  18. */
  19. export default class SharedVideoManager {
  20. constructor (emitter) {
  21. this.emitter = emitter;
  22. this.isSharedVideoShown = false;
  23. this.isPlayerAPILoaded = false;
  24. this.updateInterval = 5000; // milliseconds
  25. }
  26. /**
  27. * Starts shared video by asking user for url, or if its already working
  28. * asks whether the user wants to stop sharing the video.
  29. */
  30. toggleSharedVideo () {
  31. if(!this.isSharedVideoShown) {
  32. requestVideoLink().then(
  33. url => this.emitter.emit(
  34. UIEvents.UPDATE_SHARED_VIDEO, url, 'start'),
  35. err => console.error('SHARED VIDEO CANCELED', err)
  36. );
  37. return;
  38. }
  39. showStopVideoPropmpt().then(() =>
  40. this.emitter.emit(UIEvents.UPDATE_SHARED_VIDEO, null, 'stop'));
  41. }
  42. /**
  43. * Shows the player component and starts the checking function
  44. * that will be sending updates, if we are the one shared the video
  45. * @param id the id of the sender of the command
  46. * @param url the video url
  47. * @param attributes
  48. */
  49. showSharedVideo (id, url, attributes) {
  50. if (this.isSharedVideoShown)
  51. return;
  52. // the video url
  53. this.url = url;
  54. // the owner of the video
  55. this.from = id;
  56. // This code loads the IFrame Player API code asynchronously.
  57. var tag = document.createElement('script');
  58. tag.src = "https://www.youtube.com/iframe_api";
  59. var firstScriptTag = document.getElementsByTagName('script')[0];
  60. firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);
  61. var self = this;
  62. if(self.isPlayerAPILoaded)
  63. window.onYouTubeIframeAPIReady();
  64. else
  65. window.onYouTubeIframeAPIReady = function() {
  66. self.isPlayerAPILoaded = true;
  67. let showControls = APP.conference.isLocalId(self.from) ? 1 : 0;
  68. self.player = new YT.Player('sharedVideoIFrame', {
  69. height: '100%',
  70. width: '100%',
  71. videoId: self.url,
  72. playerVars: {
  73. 'origin': location.origin,
  74. 'fs': '0',
  75. 'autoplay': 1,
  76. 'controls': showControls,
  77. 'rel' : 0
  78. },
  79. events: {
  80. 'onReady': onPlayerReady,
  81. 'onStateChange': onPlayerStateChange,
  82. 'onError': onPlayerError
  83. }
  84. });
  85. };
  86. // whether we should pause the player as initial status
  87. // sometimes if we try to pause the player before it starts playing
  88. // we can end up with player in buffering mode
  89. this.initialPause = false;
  90. window.onPlayerStateChange = function(event) {
  91. if (event.data == YT.PlayerState.PLAYING) {
  92. self.playerPaused = false;
  93. // check for initial pause
  94. if(self.initialPause) {
  95. self.initialPause = false;
  96. self.player.pauseVideo();
  97. }
  98. self.updateCheck();
  99. } else if (event.data == YT.PlayerState.PAUSED) {
  100. self.playerPaused = true;
  101. self.updateCheck(true);
  102. }
  103. };
  104. window.onPlayerReady = function(event) {
  105. let player = event.target;
  106. player.playVideo();
  107. let thumb = new SharedVideoThumb(self.url);
  108. thumb.setDisplayName(player.getVideoData().title);
  109. VideoLayout.addParticipantContainer(self.url, thumb);
  110. let iframe = player.getIframe();
  111. self.sharedVideo = new SharedVideoContainer(
  112. {url, iframe, player});
  113. VideoLayout.addLargeVideoContainer(
  114. SHARED_VIDEO_CONTAINER_TYPE, self.sharedVideo);
  115. VideoLayout.handleVideoThumbClicked(self.url);
  116. self.isSharedVideoShown = true;
  117. // If we are sending the command and we are starting the player
  118. // we need to continuously send the player current time position
  119. if(APP.conference.isLocalId(self.from)) {
  120. self.intervalId = setInterval(
  121. self.updateCheck.bind(self),
  122. self.updateInterval);
  123. }
  124. // set initial state of the player if there is enough information
  125. if(attributes.state === 'pause')
  126. self.initialPause = true;
  127. else if(attributes.time > 0) {
  128. console.log("Player seekTo:", attributes.time);
  129. player.seekTo(attributes.time);
  130. }
  131. };
  132. window.onPlayerError = function(event) {
  133. console.error("Error in the player:" + event.data);
  134. };
  135. }
  136. /**
  137. * Checks current state of the player and fire an event with the values.
  138. */
  139. updateCheck(sendPauseEvent)
  140. {
  141. // ignore update checks if we are not the owner of the video
  142. if(!APP.conference.isLocalId(this.from))
  143. return;
  144. let state = this.player.getPlayerState();
  145. // if its paused and haven't been pause - send paused
  146. if (state === YT.PlayerState.PAUSED && sendPauseEvent) {
  147. this.emitter.emit(UIEvents.UPDATE_SHARED_VIDEO,
  148. this.url, 'pause');
  149. }
  150. // if its playing and it was paused - send update with time
  151. // if its playing and was playing just send update with time
  152. else if (state === YT.PlayerState.PLAYING) {
  153. this.emitter.emit(UIEvents.UPDATE_SHARED_VIDEO,
  154. this.url, 'playing',
  155. this.player.getCurrentTime(),
  156. this.player.isMuted() ? 0 : this.player.getVolume());
  157. }
  158. }
  159. /**
  160. * Updates video, if its not playing and needs starting or
  161. * if its playing and needs to be paysed
  162. * @param id the id of the sender of the command
  163. * @param url the video url
  164. * @param attributes
  165. */
  166. updateSharedVideo (id, url, attributes) {
  167. // if we are sending the event ignore
  168. if(APP.conference.isLocalId(this.from)) {
  169. return;
  170. }
  171. if (attributes.state == 'playing') {
  172. if(!this.isSharedVideoShown) {
  173. this.showSharedVideo(id, url, attributes);
  174. return;
  175. }
  176. // ocasionally we get this.player.getCurrentTime is not a function
  177. // it seems its that player hasn't really loaded
  178. if(!this.player || !this.player.getCurrentTime
  179. || !this.player.pauseVideo
  180. || !this.player.playVideo
  181. || !this.player.getVolume
  182. || !this.player.seekTo
  183. || !this.player.getVolume)
  184. return;
  185. // check received time and current time
  186. let currentPosition = this.player.getCurrentTime();
  187. let diff = Math.abs(attributes.time - currentPosition);
  188. // if we drift more than two times of the interval for checking
  189. // sync, the interval is in milliseconds
  190. if(diff > this.updateInterval*2/1000) {
  191. console.log("Player seekTo:", attributes.time,
  192. " current time is:", currentPosition, " diff:", diff);
  193. this.player.seekTo(attributes.time);
  194. }
  195. // lets check the volume
  196. if (attributes.volume !== undefined &&
  197. this.player.getVolume() != attributes.volume) {
  198. this.player.setVolume(attributes.volume);
  199. console.log("Player change of volume:" + attributes.volume);
  200. }
  201. if(this.playerPaused)
  202. this.player.playVideo();
  203. } else if (attributes.state == 'pause') {
  204. // if its not paused, pause it
  205. if(this.isSharedVideoShown) {
  206. this.player.pauseVideo();
  207. }
  208. else {
  209. // if not shown show it, passing attributes so it can
  210. // be shown paused
  211. this.showSharedVideo(id, url, attributes);
  212. }
  213. }
  214. }
  215. /**
  216. * Stop shared video if it is currently showed. If the user started the
  217. * shared video is the one in the id (called when user
  218. * left and we want to remove video if the user sharing it left).
  219. * @param id the id of the sender of the command
  220. * @param attributes
  221. */
  222. stopSharedVideo (id, attributes) {
  223. if (!this.isSharedVideoShown)
  224. return;
  225. if(this.from !== id)
  226. return;
  227. if(this.intervalId) {
  228. clearInterval(this.intervalId);
  229. this.intervalId = null;
  230. }
  231. VideoLayout.removeParticipantContainer(this.url);
  232. VideoLayout.showLargeVideoContainer(SHARED_VIDEO_CONTAINER_TYPE, false)
  233. .then(() => {
  234. VideoLayout.removeLargeVideoContainer(
  235. SHARED_VIDEO_CONTAINER_TYPE);
  236. this.player.destroy();
  237. this.player = null;
  238. });
  239. this.url = null;
  240. this.isSharedVideoShown = false;
  241. }
  242. }
  243. /**
  244. * Container for shared video iframe.
  245. */
  246. class SharedVideoContainer extends LargeContainer {
  247. constructor ({url, iframe, player}) {
  248. super();
  249. this.$iframe = $(iframe);
  250. this.url = url;
  251. this.player = player;
  252. }
  253. get $video () {
  254. return this.$iframe;
  255. }
  256. show () {
  257. let self = this;
  258. return new Promise(resolve => {
  259. this.$iframe.fadeIn(300, () => {
  260. self.bodyBackground = document.body.style.background;
  261. document.body.style.background = 'black';
  262. this.$iframe.css({opacity: 1});
  263. resolve();
  264. });
  265. });
  266. }
  267. hide () {
  268. let self = this;
  269. return new Promise(resolve => {
  270. this.$iframe.fadeOut(300, () => {
  271. document.body.style.background = self.bodyBackground;
  272. this.$iframe.css({opacity: 0});
  273. resolve();
  274. });
  275. });
  276. }
  277. onHoverIn () {
  278. ToolbarToggler.showToolbar();
  279. }
  280. get id () {
  281. return this.url;
  282. }
  283. resize (containerWidth, containerHeight) {
  284. let height = containerHeight - FilmStrip.getFilmStripHeight();
  285. let width = containerWidth;
  286. this.$iframe.width(width).height(height);
  287. }
  288. /**
  289. * @return {boolean} do not switch on dominant speaker event if on stage.
  290. */
  291. stayOnStage () {
  292. return false;
  293. }
  294. }
  295. function SharedVideoThumb (url)
  296. {
  297. this.id = url;
  298. this.url = url;
  299. this.setVideoType(SHARED_VIDEO_CONTAINER_TYPE);
  300. this.videoSpanId = "sharedVideoContainer";
  301. this.container = this.createContainer(this.videoSpanId);
  302. this.container.onclick = this.videoClick.bind(this);
  303. SmallVideo.call(this, VideoLayout);
  304. this.isVideoMuted = true;
  305. }
  306. SharedVideoThumb.prototype = Object.create(SmallVideo.prototype);
  307. SharedVideoThumb.prototype.constructor = SharedVideoThumb;
  308. /**
  309. * hide display name
  310. */
  311. SharedVideoThumb.prototype.setDeviceAvailabilityIcons = function () {};
  312. SharedVideoThumb.prototype.avatarChanged = function () {};
  313. SharedVideoThumb.prototype.createContainer = function (spanId) {
  314. var container = document.createElement('span');
  315. container.id = spanId;
  316. container.className = 'videocontainer';
  317. // add the avatar
  318. var avatar = document.createElement('img');
  319. avatar.id = 'avatar_' + this.id;
  320. avatar.className = 'sharedVideoAvatar';
  321. avatar.src = "https://img.youtube.com/vi/" + this.url + "/0.jpg";
  322. container.appendChild(avatar);
  323. var remotes = document.getElementById('remoteVideos');
  324. return remotes.appendChild(container);
  325. };
  326. /**
  327. * The thumb click handler.
  328. */
  329. SharedVideoThumb.prototype.videoClick = function () {
  330. VideoLayout.handleVideoThumbClicked(this.url);
  331. };
  332. /**
  333. * Removes RemoteVideo from the page.
  334. */
  335. SharedVideoThumb.prototype.remove = function () {
  336. console.log("Remove shared video thumb", this.id);
  337. // Make sure that the large video is updated if are removing its
  338. // corresponding small video.
  339. this.VideoLayout.updateAfterThumbRemoved(this.id);
  340. // Remove whole container
  341. if (this.container.parentNode) {
  342. this.container.parentNode.removeChild(this.container);
  343. }
  344. };
  345. /**
  346. * Sets the display name for the thumb.
  347. */
  348. SharedVideoThumb.prototype.setDisplayName = function(displayName) {
  349. if (!this.container) {
  350. console.warn( "Unable to set displayName - " + this.videoSpanId +
  351. " does not exist");
  352. return;
  353. }
  354. var nameSpan = $('#' + this.videoSpanId + '>span.displayname');
  355. // If we already have a display name for this video.
  356. if (nameSpan.length > 0) {
  357. if (displayName && displayName.length > 0) {
  358. $('#' + this.videoSpanId + '_name').text(displayName);
  359. }
  360. } else {
  361. nameSpan = document.createElement('span');
  362. nameSpan.className = 'displayname';
  363. $('#' + this.videoSpanId)[0].appendChild(nameSpan);
  364. if (displayName && displayName.length > 0)
  365. $(nameSpan).text(displayName);
  366. nameSpan.id = this.videoSpanId + '_name';
  367. }
  368. };
  369. /**
  370. * Checks if given string is youtube url.
  371. * @param {string} url string to check.
  372. * @returns {boolean}
  373. */
  374. function getYoutubeLink(url) {
  375. let p = /^(?:https?:\/\/)?(?:www\.)?(?:youtu\.be\/|youtube\.com\/(?:embed\/|v\/|watch\?v=|watch\?.+&v=))((\w|-){11})(?:\S+)?$/;//jshint ignore:line
  376. return (url.match(p)) ? RegExp.$1 : false;
  377. }
  378. /**
  379. * Ask user if he want to close shared video.
  380. */
  381. function showStopVideoPropmpt() {
  382. return new Promise(function (resolve, reject) {
  383. messageHandler.openTwoButtonDialog(
  384. "dialog.removeSharedVideoTitle",
  385. null,
  386. "dialog.removeSharedVideoMsg",
  387. null,
  388. false,
  389. "dialog.Remove",
  390. function(e,v,m,f) {
  391. if (v) {
  392. resolve();
  393. } else {
  394. reject();
  395. }
  396. }
  397. );
  398. });
  399. }
  400. /**
  401. * Ask user for shared video url to share with others.
  402. * Dialog validates client input to allow only youtube urls.
  403. */
  404. function requestVideoLink() {
  405. let i18n = APP.translation;
  406. const title = i18n.generateTranslationHTML("dialog.shareVideoTitle");
  407. const cancelButton = i18n.generateTranslationHTML("dialog.Cancel");
  408. const shareButton = i18n.generateTranslationHTML("dialog.Share");
  409. const backButton = i18n.generateTranslationHTML("dialog.Back");
  410. const linkError
  411. = i18n.generateTranslationHTML("dialog.shareVideoLinkError");
  412. const i18nOptions = {url: defaultSharedVideoLink};
  413. const defaultUrl = i18n.translateString("defaultLink", i18nOptions);
  414. return new Promise(function (resolve, reject) {
  415. let dialog = messageHandler.openDialogWithStates({
  416. state0: {
  417. html: `
  418. <h2>${title}</h2>
  419. <input name="sharedVideoUrl" type="text"
  420. data-i18n="[placeholder]defaultLink"
  421. data-i18n-options="${JSON.stringify(i18nOptions)}"
  422. placeholder="${defaultUrl}"
  423. autofocus>`,
  424. persistent: false,
  425. buttons: [
  426. {title: cancelButton, value: false},
  427. {title: shareButton, value: true}
  428. ],
  429. focus: ':input:first',
  430. defaultButton: 1,
  431. submit: function (e, v, m, f) {
  432. e.preventDefault();
  433. if (!v) {
  434. reject('cancelled');
  435. dialog.close();
  436. return;
  437. }
  438. let sharedVideoUrl = f.sharedVideoUrl;
  439. if (!sharedVideoUrl) {
  440. return;
  441. }
  442. let urlValue = encodeURI(UIUtil.escapeHtml(sharedVideoUrl));
  443. let yVideoId = getYoutubeLink(urlValue);
  444. if (!yVideoId) {
  445. dialog.goToState('state1');
  446. return false;
  447. }
  448. resolve(yVideoId);
  449. dialog.close();
  450. }
  451. },
  452. state1: {
  453. html: `<h2>${title}</h2> ${linkError}`,
  454. persistent: false,
  455. buttons: [
  456. {title: cancelButton, value: false},
  457. {title: backButton, value: true}
  458. ],
  459. focus: ':input:first',
  460. defaultButton: 1,
  461. submit: function (e, v, m, f) {
  462. e.preventDefault();
  463. if (v === 0) {
  464. reject();
  465. dialog.close();
  466. } else {
  467. dialog.goToState('state0');
  468. }
  469. }
  470. }
  471. });
  472. });
  473. }