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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701
  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. VideoLayout.addLargeVideoContainer(
  165. SHARED_VIDEO_CONTAINER_TYPE, self.sharedVideo);
  166. VideoLayout.handleVideoThumbClicked(self.url);
  167. // If we are sending the command and we are starting the player
  168. // we need to continuously send the player current time position
  169. if(APP.conference.isLocalId(self.from)) {
  170. self.intervalId = setInterval(
  171. self.updateCheck.bind(self),
  172. updateInterval);
  173. }
  174. };
  175. window.onPlayerError = function(event) {
  176. console.error("Error in the player:", event.data);
  177. // store the error player, so we can remove it
  178. self.errorInPlayer = event.target;
  179. };
  180. }
  181. /**
  182. * Process attributes, whether player needs to be paused or seek.
  183. * @param player the player to operate over
  184. * @param attributes the attributes with the player state we want
  185. * @param playerPaused current saved state for the player
  186. */
  187. processAttributes (player, attributes, playerPaused)
  188. {
  189. if(!attributes)
  190. return;
  191. if (attributes.state == 'playing') {
  192. this.processTime(player, attributes, playerPaused);
  193. // lets check the volume
  194. if (attributes.volume !== undefined &&
  195. player.getVolume() != attributes.volume
  196. && APP.conference.isLocalAudioMuted()) {
  197. player.setVolume(attributes.volume);
  198. console.info("Player change of volume:" + attributes.volume);
  199. this.notifyUserComfortableVideoMute(false);
  200. }
  201. if(playerPaused)
  202. player.playVideo();
  203. } else if (attributes.state == 'pause') {
  204. // if its not paused, pause it
  205. player.pauseVideo();
  206. this.processTime(player, attributes, true);
  207. } else if (attributes.state == 'stop') {
  208. this.stopSharedVideo(this.from);
  209. }
  210. }
  211. /**
  212. * Check for time in attributes and if needed seek in current player
  213. * @param player the player to operate over
  214. * @param attributes the attributes with the player state we want
  215. * @param forceSeek whether seek should be forced
  216. */
  217. processTime (player, attributes, forceSeek)
  218. {
  219. if(forceSeek) {
  220. console.info("Player seekTo:", attributes.time);
  221. player.seekTo(attributes.time);
  222. return;
  223. }
  224. // check received time and current time
  225. let currentPosition = player.getCurrentTime();
  226. let diff = Math.abs(attributes.time - currentPosition);
  227. // if we drift more than the interval for checking
  228. // sync, the interval is in milliseconds
  229. if(diff > updateInterval/1000) {
  230. console.info("Player seekTo:", attributes.time,
  231. " current time is:", currentPosition, " diff:", diff);
  232. player.seekTo(attributes.time);
  233. }
  234. }
  235. /**
  236. * Checks current state of the player and fire an event with the values.
  237. */
  238. updateCheck(sendPauseEvent)
  239. {
  240. // ignore update checks if we are not the owner of the video
  241. // or there is still no player defined or we are stopped
  242. // (in a process of stopping)
  243. if(!APP.conference.isLocalId(this.from) || !this.player
  244. || !this.isSharedVideoShown)
  245. return;
  246. let state = this.player.getPlayerState();
  247. // if its paused and haven't been pause - send paused
  248. if (state === YT.PlayerState.PAUSED && sendPauseEvent) {
  249. this.emitter.emit(UIEvents.UPDATE_SHARED_VIDEO,
  250. this.url, 'pause', this.player.getCurrentTime());
  251. }
  252. // if its playing and it was paused - send update with time
  253. // if its playing and was playing just send update with time
  254. else if (state === YT.PlayerState.PLAYING) {
  255. this.emitter.emit(UIEvents.UPDATE_SHARED_VIDEO,
  256. this.url, 'playing',
  257. this.player.getCurrentTime(),
  258. this.player.isMuted() ? 0 : this.player.getVolume());
  259. }
  260. }
  261. /**
  262. * Updates video, if its not playing and needs starting or
  263. * if its playing and needs to be paysed
  264. * @param id the id of the sender of the command
  265. * @param url the video url
  266. * @param attributes
  267. */
  268. updateSharedVideo (id, url, attributes) {
  269. // if we are sending the event ignore
  270. if(APP.conference.isLocalId(this.from)) {
  271. return;
  272. }
  273. if(!this.isSharedVideoShown) {
  274. this.showSharedVideo(id, url, attributes);
  275. return;
  276. }
  277. if(!this.player)
  278. this.initialAttributes = attributes;
  279. else {
  280. this.processAttributes(this.player, attributes, this.playerPaused);
  281. }
  282. }
  283. /**
  284. * Stop shared video if it is currently showed. If the user started the
  285. * shared video is the one in the id (called when user
  286. * left and we want to remove video if the user sharing it left).
  287. * @param id the id of the sender of the command
  288. */
  289. stopSharedVideo (id, attributes) {
  290. if (!this.isSharedVideoShown)
  291. return;
  292. if(this.from !== id)
  293. return;
  294. if(!this.player){
  295. // if there is no error in the player till now,
  296. // store the initial attributes
  297. if (!this.errorInPlayer) {
  298. this.initialAttributes = attributes;
  299. return;
  300. }
  301. }
  302. if(this.intervalId) {
  303. clearInterval(this.intervalId);
  304. this.intervalId = null;
  305. }
  306. this.emitter.removeListener(UIEvents.AUDIO_MUTED,
  307. this.localAudioMutedListener);
  308. this.localAudioMutedListener = null;
  309. VideoLayout.removeParticipantContainer(this.url);
  310. VideoLayout.showLargeVideoContainer(SHARED_VIDEO_CONTAINER_TYPE, false)
  311. .then(() => {
  312. VideoLayout.removeLargeVideoContainer(
  313. SHARED_VIDEO_CONTAINER_TYPE);
  314. if(this.player) {
  315. this.player.destroy();
  316. this.player = null;
  317. } // if there is an error in player, remove that instance
  318. else if (this.errorInPlayer) {
  319. this.errorInPlayer.destroy();
  320. this.errorInPlayer = null;
  321. }
  322. });
  323. this.url = null;
  324. this.isSharedVideoShown = false;
  325. this.initialAttributes = null;
  326. }
  327. /**
  328. * Receives events for local audio mute/unmute by local user.
  329. * @param muted boolena whether it is muted or not.
  330. */
  331. localAudioMuted (muted) {
  332. if(!this.player)
  333. return;
  334. if(muted)
  335. return;
  336. // if we are un-muting and player is not muted, lets muted
  337. // to not pollute the conference
  338. if(this.player.getVolume() > 0 || !this.player.isMuted()){
  339. this.player.setVolume(0);
  340. this.notifyUserComfortableVideoMute(true);
  341. }
  342. }
  343. /**
  344. * Notifies user for muting its audio due to video is unmuted.
  345. * @param show boolean, show or hide the notification
  346. */
  347. notifyUserComfortableMicMute (show) {
  348. if(show) {
  349. this.notifyUserComfortableVideoMute(false);
  350. console.log("Your audio was muted to enjoy the video");
  351. }
  352. else
  353. console.log("Hide notification local audio muted");
  354. }
  355. /**
  356. * Notifies user for muting the video due to audio is unmuted.
  357. * @param show boolean, show or hide the notification
  358. */
  359. notifyUserComfortableVideoMute (show) {
  360. if(show) {
  361. this.notifyUserComfortableMicMute(false);
  362. console.log(
  363. "Your shared video was muted in order to speak freely!");
  364. }
  365. else
  366. console.log("Hide notification share video muted");
  367. }
  368. }
  369. /**
  370. * Container for shared video iframe.
  371. */
  372. class SharedVideoContainer extends LargeContainer {
  373. constructor ({url, iframe, player}) {
  374. super();
  375. this.$iframe = $(iframe);
  376. this.url = url;
  377. this.player = player;
  378. }
  379. get $video () {
  380. return this.$iframe;
  381. }
  382. show () {
  383. let self = this;
  384. return new Promise(resolve => {
  385. this.$iframe.fadeIn(300, () => {
  386. self.bodyBackground = document.body.style.background;
  387. document.body.style.background = 'black';
  388. this.$iframe.css({opacity: 1});
  389. ToolbarToggler.dockToolbar(true);
  390. resolve();
  391. });
  392. });
  393. }
  394. hide () {
  395. let self = this;
  396. ToolbarToggler.dockToolbar(false);
  397. return new Promise(resolve => {
  398. this.$iframe.fadeOut(300, () => {
  399. document.body.style.background = self.bodyBackground;
  400. this.$iframe.css({opacity: 0});
  401. resolve();
  402. });
  403. });
  404. }
  405. onHoverIn () {
  406. ToolbarToggler.showToolbar();
  407. }
  408. get id () {
  409. return this.url;
  410. }
  411. resize (containerWidth, containerHeight) {
  412. let height = containerHeight - FilmStrip.getFilmStripHeight();
  413. let width = containerWidth;
  414. this.$iframe.width(width).height(height);
  415. }
  416. /**
  417. * @return {boolean} do not switch on dominant speaker event if on stage.
  418. */
  419. stayOnStage () {
  420. return false;
  421. }
  422. }
  423. function SharedVideoThumb (url)
  424. {
  425. this.id = url;
  426. this.url = url;
  427. this.setVideoType(SHARED_VIDEO_CONTAINER_TYPE);
  428. this.videoSpanId = "sharedVideoContainer";
  429. this.container = this.createContainer(this.videoSpanId);
  430. this.container.onclick = this.videoClick.bind(this);
  431. SmallVideo.call(this, VideoLayout);
  432. this.isVideoMuted = true;
  433. }
  434. SharedVideoThumb.prototype = Object.create(SmallVideo.prototype);
  435. SharedVideoThumb.prototype.constructor = SharedVideoThumb;
  436. /**
  437. * hide display name
  438. */
  439. SharedVideoThumb.prototype.setDeviceAvailabilityIcons = function () {};
  440. SharedVideoThumb.prototype.avatarChanged = function () {};
  441. SharedVideoThumb.prototype.createContainer = function (spanId) {
  442. var container = document.createElement('span');
  443. container.id = spanId;
  444. container.className = 'videocontainer';
  445. // add the avatar
  446. var avatar = document.createElement('img');
  447. avatar.id = 'avatar_' + this.id;
  448. avatar.className = 'sharedVideoAvatar';
  449. avatar.src = "https://img.youtube.com/vi/" + this.url + "/0.jpg";
  450. container.appendChild(avatar);
  451. var remotes = document.getElementById('remoteVideos');
  452. return remotes.appendChild(container);
  453. };
  454. /**
  455. * The thumb click handler.
  456. */
  457. SharedVideoThumb.prototype.videoClick = function () {
  458. VideoLayout.handleVideoThumbClicked(this.url);
  459. };
  460. /**
  461. * Removes RemoteVideo from the page.
  462. */
  463. SharedVideoThumb.prototype.remove = function () {
  464. console.log("Remove shared video thumb", this.id);
  465. // Make sure that the large video is updated if are removing its
  466. // corresponding small video.
  467. this.VideoLayout.updateAfterThumbRemoved(this.id);
  468. // Remove whole container
  469. if (this.container.parentNode) {
  470. this.container.parentNode.removeChild(this.container);
  471. }
  472. };
  473. /**
  474. * Sets the display name for the thumb.
  475. */
  476. SharedVideoThumb.prototype.setDisplayName = function(displayName) {
  477. if (!this.container) {
  478. console.warn( "Unable to set displayName - " + this.videoSpanId +
  479. " does not exist");
  480. return;
  481. }
  482. var nameSpan = $('#' + this.videoSpanId + '>span.displayname');
  483. // If we already have a display name for this video.
  484. if (nameSpan.length > 0) {
  485. if (displayName && displayName.length > 0) {
  486. $('#' + this.videoSpanId + '_name').text(displayName);
  487. }
  488. } else {
  489. nameSpan = document.createElement('span');
  490. nameSpan.className = 'displayname';
  491. $('#' + this.videoSpanId)[0].appendChild(nameSpan);
  492. if (displayName && displayName.length > 0)
  493. $(nameSpan).text(displayName);
  494. nameSpan.id = this.videoSpanId + '_name';
  495. }
  496. };
  497. /**
  498. * Checks if given string is youtube url.
  499. * @param {string} url string to check.
  500. * @returns {boolean}
  501. */
  502. function getYoutubeLink(url) {
  503. let p = /^(?:https?:\/\/)?(?:www\.)?(?:youtu\.be\/|youtube\.com\/(?:embed\/|v\/|watch\?v=|watch\?.+&v=))((\w|-){11})(?:\S+)?$/;//jshint ignore:line
  504. return (url.match(p)) ? RegExp.$1 : false;
  505. }
  506. /**
  507. * Ask user if he want to close shared video.
  508. */
  509. function showStopVideoPropmpt() {
  510. return new Promise(function (resolve, reject) {
  511. messageHandler.openTwoButtonDialog(
  512. "dialog.removeSharedVideoTitle",
  513. null,
  514. "dialog.removeSharedVideoMsg",
  515. null,
  516. false,
  517. "dialog.Remove",
  518. function(e,v,m,f) {
  519. if (v) {
  520. resolve();
  521. } else {
  522. reject();
  523. }
  524. }
  525. );
  526. });
  527. }
  528. /**
  529. * Ask user for shared video url to share with others.
  530. * Dialog validates client input to allow only youtube urls.
  531. */
  532. function requestVideoLink() {
  533. let i18n = APP.translation;
  534. const title = i18n.generateTranslationHTML("dialog.shareVideoTitle");
  535. const cancelButton = i18n.generateTranslationHTML("dialog.Cancel");
  536. const shareButton = i18n.generateTranslationHTML("dialog.Share");
  537. const backButton = i18n.generateTranslationHTML("dialog.Back");
  538. const linkError
  539. = i18n.generateTranslationHTML("dialog.shareVideoLinkError");
  540. const i18nOptions = {url: defaultSharedVideoLink};
  541. const defaultUrl = i18n.translateString("defaultLink", i18nOptions);
  542. return new Promise(function (resolve, reject) {
  543. let dialog = messageHandler.openDialogWithStates({
  544. state0: {
  545. html: `
  546. <h2>${title}</h2>
  547. <input name="sharedVideoUrl" type="text"
  548. data-i18n="[placeholder]defaultLink"
  549. data-i18n-options="${JSON.stringify(i18nOptions)}"
  550. placeholder="${defaultUrl}"
  551. autofocus>`,
  552. persistent: false,
  553. buttons: [
  554. {title: cancelButton, value: false},
  555. {title: shareButton, value: true}
  556. ],
  557. focus: ':input:first',
  558. defaultButton: 1,
  559. submit: function (e, v, m, f) {
  560. e.preventDefault();
  561. if (!v) {
  562. reject('cancelled');
  563. dialog.close();
  564. return;
  565. }
  566. let sharedVideoUrl = f.sharedVideoUrl;
  567. if (!sharedVideoUrl) {
  568. return;
  569. }
  570. let urlValue = encodeURI(UIUtil.escapeHtml(sharedVideoUrl));
  571. let yVideoId = getYoutubeLink(urlValue);
  572. if (!yVideoId) {
  573. dialog.goToState('state1');
  574. return false;
  575. }
  576. resolve(yVideoId);
  577. dialog.close();
  578. }
  579. },
  580. state1: {
  581. html: `<h2>${title}</h2> ${linkError}`,
  582. persistent: false,
  583. buttons: [
  584. {title: cancelButton, value: false},
  585. {title: backButton, value: true}
  586. ],
  587. focus: ':input:first',
  588. defaultButton: 1,
  589. submit: function (e, v, m, f) {
  590. e.preventDefault();
  591. if (v === 0) {
  592. reject();
  593. dialog.close();
  594. } else {
  595. dialog.goToState('state0');
  596. }
  597. }
  598. }
  599. });
  600. });
  601. }