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

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