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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710
  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. const updateInterval = 5000; // milliseconds
  17. /**
  18. * Manager of shared video.
  19. */
  20. export default class SharedVideoManager {
  21. constructor (emitter) {
  22. this.emitter = emitter;
  23. this.isSharedVideoShown = false;
  24. this.isPlayerAPILoaded = false;
  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. if(APP.conference.isLocalId(this.from)) {
  40. showStopVideoPropmpt().then(() =>
  41. this.emitter.emit(
  42. UIEvents.UPDATE_SHARED_VIDEO, this.url, 'stop'));
  43. } else {
  44. messageHandler.openMessageDialog(
  45. "dialog.shareVideoTitle",
  46. "dialog.alreadySharedVideoMsg"
  47. );
  48. }
  49. }
  50. /**
  51. * Shows the player component and starts the checking function
  52. * that will be sending updates, if we are the one shared the video
  53. * @param id the id of the sender of the command
  54. * @param url the video url
  55. * @param attributes
  56. */
  57. showSharedVideo (id, url, attributes) {
  58. if (this.isSharedVideoShown)
  59. return;
  60. this.isSharedVideoShown = true;
  61. // the video url
  62. this.url = url;
  63. // the owner of the video
  64. this.from = id;
  65. //listen for local audio mute events
  66. this.localAudioMutedListener = this.localAudioMuted.bind(this);
  67. this.emitter.on(UIEvents.AUDIO_MUTED, this.localAudioMutedListener);
  68. // This code loads the IFrame Player API code asynchronously.
  69. var tag = document.createElement('script');
  70. tag.src = "https://www.youtube.com/iframe_api";
  71. var firstScriptTag = document.getElementsByTagName('script')[0];
  72. firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);
  73. // sometimes we receive errors like player not defined
  74. // or player.pauseVideo is not a function
  75. // we need to operate with player after start playing
  76. // self.player will be defined once it start playing
  77. // and will process any initial attributes if any
  78. this.initialAttributes = attributes;
  79. var self = this;
  80. if(self.isPlayerAPILoaded)
  81. window.onYouTubeIframeAPIReady();
  82. else
  83. window.onYouTubeIframeAPIReady = function() {
  84. self.isPlayerAPILoaded = true;
  85. let showControls = APP.conference.isLocalId(self.from) ? 1 : 0;
  86. let p = new YT.Player('sharedVideoIFrame', {
  87. height: '100%',
  88. width: '100%',
  89. videoId: self.url,
  90. playerVars: {
  91. 'origin': location.origin,
  92. 'fs': '0',
  93. 'autoplay': 0,
  94. 'controls': showControls,
  95. 'rel' : 0
  96. },
  97. events: {
  98. 'onReady': onPlayerReady,
  99. 'onStateChange': onPlayerStateChange,
  100. 'onError': onPlayerError
  101. }
  102. });
  103. // add listener for volume changes
  104. p.addEventListener(
  105. "onVolumeChange", "onVolumeChange");
  106. if (APP.conference.isLocalId(self.from)){
  107. // adds progress listener that will be firing events
  108. // while we are paused and we change the progress of the
  109. // video (seeking forward or backward on the video)
  110. p.addEventListener(
  111. "onVideoProgress", "onVideoProgress");
  112. }
  113. };
  114. window.onPlayerStateChange = function(event) {
  115. if (event.data == YT.PlayerState.PLAYING) {
  116. self.playerPaused = false;
  117. self.player = event.target;
  118. if(self.initialAttributes)
  119. {
  120. self.processAttributes(
  121. self.player, self.initialAttributes, self.playerPaused);
  122. self.initialAttributes = null;
  123. }
  124. self.updateCheck();
  125. } else if (event.data == YT.PlayerState.PAUSED) {
  126. self.playerPaused = true;
  127. self.updateCheck(true);
  128. }
  129. };
  130. /**
  131. * Track player progress while paused.
  132. * @param event
  133. */
  134. window.onVideoProgress = function (event) {
  135. let state = event.target.getPlayerState();
  136. if (state == YT.PlayerState.PAUSED) {
  137. self.updateCheck(true);
  138. }
  139. };
  140. /**
  141. * Gets notified for volume state changed.
  142. * @param event
  143. */
  144. window.onVolumeChange = function (event) {
  145. self.updateCheck();
  146. // let's check, if player is not muted lets mute locally
  147. if(event.data.volume > 0 && !event.data.muted
  148. && !APP.conference.isLocalAudioMuted()){
  149. self.emitter.emit(UIEvents.AUDIO_MUTED, true);
  150. self.notifyUserComfortableMicMute(true);
  151. }
  152. };
  153. window.onPlayerReady = function(event) {
  154. let player = event.target;
  155. // do not relay on autoplay as it is not sending all of the events
  156. // in onPlayerStateChange
  157. player.playVideo();
  158. let thumb = new SharedVideoThumb(self.url);
  159. thumb.setDisplayName(player.getVideoData().title);
  160. VideoLayout.addParticipantContainer(self.url, thumb);
  161. let iframe = player.getIframe();
  162. self.sharedVideo = new SharedVideoContainer(
  163. {url, iframe, player});
  164. //prevents pausing participants not sharing the video
  165. // to pause the video
  166. if (!APP.conference.isLocalId(self.from)) {
  167. $("#sharedVideo").css("pointer-events","none");
  168. }
  169. VideoLayout.addLargeVideoContainer(
  170. SHARED_VIDEO_CONTAINER_TYPE, self.sharedVideo);
  171. VideoLayout.handleVideoThumbClicked(self.url);
  172. // If we are sending the command and we are starting the player
  173. // we need to continuously send the player current time position
  174. if(APP.conference.isLocalId(self.from)) {
  175. self.intervalId = setInterval(
  176. self.updateCheck.bind(self),
  177. updateInterval);
  178. }
  179. };
  180. window.onPlayerError = function(event) {
  181. console.error("Error in the player:", event.data);
  182. // store the error player, so we can remove it
  183. self.errorInPlayer = event.target;
  184. };
  185. }
  186. /**
  187. * Process attributes, whether player needs to be paused or seek.
  188. * @param player the player to operate over
  189. * @param attributes the attributes with the player state we want
  190. * @param playerPaused current saved state for the player
  191. */
  192. processAttributes (player, attributes, playerPaused)
  193. {
  194. if(!attributes)
  195. return;
  196. if (attributes.state == 'playing') {
  197. this.processTime(player, attributes, playerPaused);
  198. // lets check the volume
  199. if (attributes.volume !== undefined &&
  200. player.getVolume() != attributes.volume
  201. && APP.conference.isLocalAudioMuted()) {
  202. player.setVolume(attributes.volume);
  203. console.info("Player change of volume:" + attributes.volume);
  204. this.notifyUserComfortableVideoMute(false);
  205. }
  206. if(playerPaused)
  207. player.playVideo();
  208. } else if (attributes.state == 'pause') {
  209. // if its not paused, pause it
  210. player.pauseVideo();
  211. this.processTime(player, attributes, true);
  212. } else if (attributes.state == 'stop') {
  213. this.stopSharedVideo(this.from);
  214. }
  215. }
  216. /**
  217. * Check for time in attributes and if needed seek in current player
  218. * @param player the player to operate over
  219. * @param attributes the attributes with the player state we want
  220. * @param forceSeek whether seek should be forced
  221. */
  222. processTime (player, attributes, forceSeek)
  223. {
  224. if(forceSeek) {
  225. console.info("Player seekTo:", attributes.time);
  226. player.seekTo(attributes.time);
  227. return;
  228. }
  229. // check received time and current time
  230. let currentPosition = player.getCurrentTime();
  231. let diff = Math.abs(attributes.time - currentPosition);
  232. // if we drift more than the interval for checking
  233. // sync, the interval is in milliseconds
  234. if(diff > updateInterval/1000) {
  235. console.info("Player seekTo:", attributes.time,
  236. " current time is:", currentPosition, " diff:", diff);
  237. player.seekTo(attributes.time);
  238. }
  239. }
  240. /**
  241. * Checks current state of the player and fire an event with the values.
  242. */
  243. updateCheck(sendPauseEvent)
  244. {
  245. // ignore update checks if we are not the owner of the video
  246. // or there is still no player defined or we are stopped
  247. // (in a process of stopping)
  248. if(!APP.conference.isLocalId(this.from) || !this.player
  249. || !this.isSharedVideoShown)
  250. return;
  251. let state = this.player.getPlayerState();
  252. // if its paused and haven't been pause - send paused
  253. if (state === YT.PlayerState.PAUSED && sendPauseEvent) {
  254. this.emitter.emit(UIEvents.UPDATE_SHARED_VIDEO,
  255. this.url, 'pause', this.player.getCurrentTime());
  256. }
  257. // if its playing and it was paused - send update with time
  258. // if its playing and was playing just send update with time
  259. else if (state === YT.PlayerState.PLAYING) {
  260. this.emitter.emit(UIEvents.UPDATE_SHARED_VIDEO,
  261. this.url, 'playing',
  262. this.player.getCurrentTime(),
  263. this.player.isMuted() ? 0 : this.player.getVolume());
  264. }
  265. }
  266. /**
  267. * Updates video, if its not playing and needs starting or
  268. * if its playing and needs to be paysed
  269. * @param id the id of the sender of the command
  270. * @param url the video url
  271. * @param attributes
  272. */
  273. updateSharedVideo (id, url, attributes) {
  274. // if we are sending the event ignore
  275. if(APP.conference.isLocalId(this.from)) {
  276. return;
  277. }
  278. if(!this.isSharedVideoShown) {
  279. this.showSharedVideo(id, url, attributes);
  280. return;
  281. }
  282. if(!this.player)
  283. this.initialAttributes = attributes;
  284. else {
  285. this.processAttributes(this.player, attributes, this.playerPaused);
  286. }
  287. }
  288. /**
  289. * Stop shared video if it is currently showed. If the user started the
  290. * shared video is the one in the id (called when user
  291. * left and we want to remove video if the user sharing it left).
  292. * @param id the id of the sender of the command
  293. */
  294. stopSharedVideo (id, attributes) {
  295. if (!this.isSharedVideoShown)
  296. return;
  297. if(this.from !== id)
  298. return;
  299. if(!this.player){
  300. // if there is no error in the player till now,
  301. // store the initial attributes
  302. if (!this.errorInPlayer) {
  303. this.initialAttributes = attributes;
  304. return;
  305. }
  306. }
  307. if(this.intervalId) {
  308. clearInterval(this.intervalId);
  309. this.intervalId = null;
  310. }
  311. this.emitter.removeListener(UIEvents.AUDIO_MUTED,
  312. this.localAudioMutedListener);
  313. this.localAudioMutedListener = null;
  314. VideoLayout.removeParticipantContainer(this.url);
  315. VideoLayout.showLargeVideoContainer(SHARED_VIDEO_CONTAINER_TYPE, false)
  316. .then(() => {
  317. VideoLayout.removeLargeVideoContainer(
  318. SHARED_VIDEO_CONTAINER_TYPE);
  319. if(this.player) {
  320. this.player.destroy();
  321. this.player = null;
  322. } // if there is an error in player, remove that instance
  323. else if (this.errorInPlayer) {
  324. this.errorInPlayer.destroy();
  325. this.errorInPlayer = null;
  326. }
  327. // revert to original behavior (prevents pausing
  328. // for participants not sharing the video to pause it)
  329. $("#sharedVideo").css("pointer-events","auto");
  330. });
  331. this.url = null;
  332. this.isSharedVideoShown = false;
  333. this.initialAttributes = null;
  334. }
  335. /**
  336. * Receives events for local audio mute/unmute by local user.
  337. * @param muted boolena whether it is muted or not.
  338. */
  339. localAudioMuted (muted) {
  340. if(!this.player)
  341. return;
  342. if(muted)
  343. return;
  344. // if we are un-muting and player is not muted, lets muted
  345. // to not pollute the conference
  346. if(this.player.getVolume() > 0 || !this.player.isMuted()){
  347. this.player.setVolume(0);
  348. this.notifyUserComfortableVideoMute(true);
  349. }
  350. }
  351. /**
  352. * Notifies user for muting its audio due to video is unmuted.
  353. * @param show boolean, show or hide the notification
  354. */
  355. notifyUserComfortableMicMute (show) {
  356. if(show) {
  357. this.notifyUserComfortableVideoMute(false);
  358. console.log("Your audio was muted to enjoy the video");
  359. }
  360. else
  361. console.log("Hide notification local audio muted");
  362. }
  363. /**
  364. * Notifies user for muting the video due to audio is unmuted.
  365. * @param show boolean, show or hide the notification
  366. */
  367. notifyUserComfortableVideoMute (show) {
  368. if(show) {
  369. this.notifyUserComfortableMicMute(false);
  370. console.log(
  371. "Your shared video was muted in order to speak freely!");
  372. }
  373. else
  374. console.log("Hide notification share video muted");
  375. }
  376. }
  377. /**
  378. * Container for shared video iframe.
  379. */
  380. class SharedVideoContainer extends LargeContainer {
  381. constructor ({url, iframe, player}) {
  382. super();
  383. this.$iframe = $(iframe);
  384. this.url = url;
  385. this.player = player;
  386. }
  387. get $video () {
  388. return this.$iframe;
  389. }
  390. show () {
  391. let self = this;
  392. return new Promise(resolve => {
  393. this.$iframe.fadeIn(300, () => {
  394. self.bodyBackground = document.body.style.background;
  395. document.body.style.background = 'black';
  396. this.$iframe.css({opacity: 1});
  397. ToolbarToggler.dockToolbar(true);
  398. resolve();
  399. });
  400. });
  401. }
  402. hide () {
  403. let self = this;
  404. ToolbarToggler.dockToolbar(false);
  405. return new Promise(resolve => {
  406. this.$iframe.fadeOut(300, () => {
  407. document.body.style.background = self.bodyBackground;
  408. this.$iframe.css({opacity: 0});
  409. resolve();
  410. });
  411. });
  412. }
  413. onHoverIn () {
  414. ToolbarToggler.showToolbar();
  415. }
  416. get id () {
  417. return this.url;
  418. }
  419. resize (containerWidth, containerHeight) {
  420. let height = containerHeight - FilmStrip.getFilmStripHeight();
  421. let width = containerWidth;
  422. this.$iframe.width(width).height(height);
  423. }
  424. /**
  425. * @return {boolean} do not switch on dominant speaker event if on stage.
  426. */
  427. stayOnStage () {
  428. return false;
  429. }
  430. }
  431. function SharedVideoThumb (url)
  432. {
  433. this.id = url;
  434. this.url = url;
  435. this.setVideoType(SHARED_VIDEO_CONTAINER_TYPE);
  436. this.videoSpanId = "sharedVideoContainer";
  437. this.container = this.createContainer(this.videoSpanId);
  438. this.container.onclick = this.videoClick.bind(this);
  439. SmallVideo.call(this, VideoLayout);
  440. this.isVideoMuted = true;
  441. }
  442. SharedVideoThumb.prototype = Object.create(SmallVideo.prototype);
  443. SharedVideoThumb.prototype.constructor = SharedVideoThumb;
  444. /**
  445. * hide display name
  446. */
  447. SharedVideoThumb.prototype.setDeviceAvailabilityIcons = function () {};
  448. SharedVideoThumb.prototype.avatarChanged = function () {};
  449. SharedVideoThumb.prototype.createContainer = function (spanId) {
  450. var container = document.createElement('span');
  451. container.id = spanId;
  452. container.className = 'videocontainer';
  453. // add the avatar
  454. var avatar = document.createElement('img');
  455. avatar.id = 'avatar_' + this.id;
  456. avatar.className = 'sharedVideoAvatar';
  457. avatar.src = "https://img.youtube.com/vi/" + this.url + "/0.jpg";
  458. container.appendChild(avatar);
  459. var remotes = document.getElementById('remoteVideos');
  460. return remotes.appendChild(container);
  461. };
  462. /**
  463. * The thumb click handler.
  464. */
  465. SharedVideoThumb.prototype.videoClick = function () {
  466. VideoLayout.handleVideoThumbClicked(this.url);
  467. };
  468. /**
  469. * Removes RemoteVideo from the page.
  470. */
  471. SharedVideoThumb.prototype.remove = function () {
  472. console.log("Remove shared video thumb", this.id);
  473. // Make sure that the large video is updated if are removing its
  474. // corresponding small video.
  475. this.VideoLayout.updateAfterThumbRemoved(this.id);
  476. // Remove whole container
  477. if (this.container.parentNode) {
  478. this.container.parentNode.removeChild(this.container);
  479. }
  480. };
  481. /**
  482. * Sets the display name for the thumb.
  483. */
  484. SharedVideoThumb.prototype.setDisplayName = function(displayName) {
  485. if (!this.container) {
  486. console.warn( "Unable to set displayName - " + this.videoSpanId +
  487. " does not exist");
  488. return;
  489. }
  490. var nameSpan = $('#' + this.videoSpanId + '>span.displayname');
  491. // If we already have a display name for this video.
  492. if (nameSpan.length > 0) {
  493. if (displayName && displayName.length > 0) {
  494. $('#' + this.videoSpanId + '_name').text(displayName);
  495. }
  496. } else {
  497. nameSpan = document.createElement('span');
  498. nameSpan.className = 'displayname';
  499. $('#' + this.videoSpanId)[0].appendChild(nameSpan);
  500. if (displayName && displayName.length > 0)
  501. $(nameSpan).text(displayName);
  502. nameSpan.id = this.videoSpanId + '_name';
  503. }
  504. };
  505. /**
  506. * Checks if given string is youtube url.
  507. * @param {string} url string to check.
  508. * @returns {boolean}
  509. */
  510. function getYoutubeLink(url) {
  511. let p = /^(?:https?:\/\/)?(?:www\.)?(?:youtu\.be\/|youtube\.com\/(?:embed\/|v\/|watch\?v=|watch\?.+&v=))((\w|-){11})(?:\S+)?$/;//jshint ignore:line
  512. return (url.match(p)) ? RegExp.$1 : false;
  513. }
  514. /**
  515. * Ask user if he want to close shared video.
  516. */
  517. function showStopVideoPropmpt() {
  518. return new Promise(function (resolve, reject) {
  519. messageHandler.openTwoButtonDialog(
  520. "dialog.removeSharedVideoTitle",
  521. null,
  522. "dialog.removeSharedVideoMsg",
  523. null,
  524. false,
  525. "dialog.Remove",
  526. function(e,v,m,f) {
  527. if (v) {
  528. resolve();
  529. } else {
  530. reject();
  531. }
  532. }
  533. );
  534. });
  535. }
  536. /**
  537. * Ask user for shared video url to share with others.
  538. * Dialog validates client input to allow only youtube urls.
  539. */
  540. function requestVideoLink() {
  541. let i18n = APP.translation;
  542. const title = i18n.generateTranslationHTML("dialog.shareVideoTitle");
  543. const cancelButton = i18n.generateTranslationHTML("dialog.Cancel");
  544. const shareButton = i18n.generateTranslationHTML("dialog.Share");
  545. const backButton = i18n.generateTranslationHTML("dialog.Back");
  546. const linkError
  547. = i18n.generateTranslationHTML("dialog.shareVideoLinkError");
  548. const i18nOptions = {url: defaultSharedVideoLink};
  549. const defaultUrl = i18n.translateString("defaultLink", i18nOptions);
  550. return new Promise(function (resolve, reject) {
  551. let dialog = messageHandler.openDialogWithStates({
  552. state0: {
  553. html: `
  554. <h2>${title}</h2>
  555. <input name="sharedVideoUrl" type="text"
  556. data-i18n="[placeholder]defaultLink"
  557. data-i18n-options="${JSON.stringify(i18nOptions)}"
  558. placeholder="${defaultUrl}"
  559. autofocus>`,
  560. persistent: false,
  561. buttons: [
  562. {title: cancelButton, value: false},
  563. {title: shareButton, value: true}
  564. ],
  565. focus: ':input:first',
  566. defaultButton: 1,
  567. submit: function (e, v, m, f) {
  568. e.preventDefault();
  569. if (!v) {
  570. reject('cancelled');
  571. dialog.close();
  572. return;
  573. }
  574. let sharedVideoUrl = f.sharedVideoUrl;
  575. if (!sharedVideoUrl) {
  576. return;
  577. }
  578. let urlValue = encodeURI(UIUtil.escapeHtml(sharedVideoUrl));
  579. let yVideoId = getYoutubeLink(urlValue);
  580. if (!yVideoId) {
  581. dialog.goToState('state1');
  582. return false;
  583. }
  584. resolve(yVideoId);
  585. dialog.close();
  586. }
  587. },
  588. state1: {
  589. html: `<h2>${title}</h2> ${linkError}`,
  590. persistent: false,
  591. buttons: [
  592. {title: cancelButton, value: false},
  593. {title: backButton, value: true}
  594. ],
  595. focus: ':input:first',
  596. defaultButton: 1,
  597. submit: function (e, v, m, f) {
  598. e.preventDefault();
  599. if (v === 0) {
  600. reject();
  601. dialog.close();
  602. } else {
  603. dialog.goToState('state0');
  604. }
  605. }
  606. }
  607. });
  608. });
  609. }