All files / audio-players youtube-player.jsx

1.77% Statements 2/113
0% Branches 0/43
0% Functions 0/24
1.87% Lines 2/107

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                    1x   1x                
import React, { Component } from 'react';
import PropTypes from 'prop-types';
import youTubeParamsParser from './utils/youtube-params-parser';
import youTubeFullAlbumRegistry from './utils/youtube-full-album-registry';
 
/**
 * YoutubePlayer
 *
 * Loads the youtube player and plays video of the selected track
 *
 * Also handles full albums with URN standardized time segments
 * This means, that the tracks that come along with the full album have timestamps
 * to signal where they are in the full album
 *
 * @params see PropTypes
 */
 
class YoutubePlayer extends Component {
  constructor(props) {
    super(props);
 
    const { playlist } = props;
    const fullAlbumDetails = youTubeFullAlbumRegistry(playlist);
    this.timer = null;
    this.fullAlbumVideoPoller = null;
 
    this.state = {
      fullAlbumDetails,
      player: null,
      playerAnchor: React.createRef(),
      selectedTrack: null,
      id: null,
      videoStartedPlaying: false,
    };
 
    [
      'loadPlayer',
      'onPlayerStateChange',
      'onPlayerReady',
      'onPlayerError',
      'playVideo',
      'availableVideoId',
      'syncVideoWithPlayer',
      'checkTimeAndTrack'
    ].forEach((item) => {
      this[item] = this[item].bind(this);
    });
  }
 
  /**
   * Load the youtube iframe API if not previously loaded
   * Load the youtube player object when youtube iframe api is ready
   */
  componentDidMount() {
    if (!window.YT) {
      this.loadAPI();
      window.onYouTubeIframeAPIReady = () => {
        this.loadPlayer();
      };
    } else {
      this.loadPlayer();
    }
  }
 
  /**
   * Update component only if there is a change in video id
   * If above update video id and selected track
   */
  shouldComponentUpdate(nextProps, nextState) {
    const { id, player } = this.state;
    if (!player && nextState.player) {
      return false;
    }
 
    const trackChanged = id !== nextProps.id;
    return trackChanged;
  }
 
  /**
   * Load video of passed id and default resolution
   */
  componentDidUpdate(prevProps) {
    const { selectedTrack: capturedTrack } = this.state;
    const { id, selectedTrack } = this.props;
    const { id: prevId } = prevProps;
    const trackChanged = id !== prevId;
    const playerNotStarted = capturedTrack === null;
    const setID = !trackChanged && playerNotStarted;
    if (trackChanged || setID) {
      clearTimeout(this.timer);
      this.setState({ id, selectedTrack }, this.playVideo);
    }
  }
 
  /**
   * Remove timer & interval
   */
  componentWillUnmount() {
    clearInterval(this.fullAlbumVideoPoller);
    this.fullAlbumVideoPoller = null;
    clearTimeout(this.timer);
  }
 
  /**
   * Gets available YouTube ID
   * checks between captured ID (state) & incoming ID (props)
   * when there isn't a captured ID, it means the player has loaded & user has not selected a video
   */
  availableVideoId() {
    const { id: stateID } = this.state;
    const { id: propsID } = this.props;
    const availableID = Number.isInteger(stateID) ? stateID : propsID;
    return availableID;
  }
 
  /**
   * Check player elapsed time & the track it's on
   *
   * @return { object } trackValue
   * trackValue.elapsedTime = number
   * trackValue.currentTrack = object (return from fullAlbumDetails)
   */
  checkTimeAndTrack() {
    const { fullAlbumDetails, player } = this.state;
    const elapsedTime = player.getCurrentTime();
    const currentTrack = fullAlbumDetails.filter(track => track.startSeconds <= elapsedTime).pop() || {};
 
    return { elapsedTime, currentTrack };
  }
 
  /**
   * Callback for YouTube API elapsed poller
   * Checks against what the component says what track are on
   * versus the track the video is currently on based on elapsed time.
   */
  videoTimePoller() {
    const { selectedTrack } = this.state;
    const { youtubePlaylistChange } = this.props;
    const setURLOnly = true;
    const { currentTrack } = this.checkTimeAndTrack();
    const { trackNumber } = currentTrack;
    if (selectedTrack !== trackNumber) {
      youtubePlaylistChange(trackNumber, setURLOnly);
    }
  }
 
  /**
   * Syncs Full Album Video with Audio Player
   * - pings YouTube's API to check timestamp
   * - finds current track position
   * - sends that to the callback
   */
  syncVideoWithPlayer() {
    const { videoStartedPlaying } = this.state;
 
    if (videoStartedPlaying) {
      // least disruptive in full video playing experience
      const interval = 800;
      if (!this.fullAlbumVideoPoller) {
        this.fullAlbumVideoPoller = setInterval(() => { this.videoTimePoller(); }, interval);
      }
    }
  }
 
  /**
   * Load youtube iframe API asyncronously
   * Prevent user interaction with tracklist
   */
  loadAPI() {
    document.querySelector('.audio-track-list').setAttribute('style', 'pointer-events: none');
    const tag = document.createElement('script');
    tag.src = `https://www.youtube.com/iframe_api?origin=${location.origin}`;
    const firstScriptTag = document.getElementsByTagName('script')[0];
    firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);
  }
 
  /**
   * Load youtube player object
   * Update player
   */
  loadPlayer() {
    const { playerAnchor } = this.state;
    const availableID = this.availableVideoId();
    const videoParams = youTubeParamsParser(availableID);
    const defaultParams = {
      height: '600',
      width: '600',
      playerVars: {
        fs: 1,
        rel: 0,
        enablejsapi: 1,
        origin: location.origin,
      },
      events: {
        onReady: this.onPlayerReady,
        onStateChange: this.onPlayerStateChange,
        onError: this.onPlayerError
      }
    };
    const params = Object.assign({}, defaultParams, videoParams);
    const player = new window.YT.Player(playerAnchor.current, params);
 
    this.setState({ player });
  }
 
  /**
   * Fire when video ends
   * Call youtubePlaylistChange to switch to next track number
   */
  onPlayerStateChange(event) {
    const { youtubePlaylistChange, selectedTrack } = this.props;
    const { selectedTrack: capturedTrack, videoStartedPlaying, fullAlbumDetails } = this.state;
    const { data } = event;
 
    if (data === YT.PlayerState.ENDED) {
      const currentTrack = capturedTrack || selectedTrack;
      this.setState({ videoStartedPlaying: false }, () => youtubePlaylistChange(currentTrack));
      clearInterval(this.fullAlbumVideoPoller);
      this.fullAlbumVideoPoller = null;
    }
 
    if (data === YT.PlayerState.PAUSED) {
      this.setState({ videoStartedPlaying: false });
      clearInterval(this.fullAlbumVideoPoller);
      this.fullAlbumVideoPoller = null;
    }
 
    if (data === YT.PlayerState.PLAYING) {
      const setURLOnly = true;
      if (!videoStartedPlaying) {
        this.setState({ videoStartedPlaying: true }, () => youtubePlaylistChange(selectedTrack, setURLOnly));
      }
 
      if (fullAlbumDetails) {
        this.syncVideoWithPlayer();
      }
    }
  }
 
  /**
   * Fire when player is ready
   * Allow user interaction with tracklist
   * Play loaded video
   */
  onPlayerReady(event) {
    document.querySelector('.audio-track-list').setAttribute('style', 'pointer-events: auto');
  }
 
  /**
   * Fire when an error is encountered
   * Call youtubePlaylistChange to switch to next track number after a 3 sec delay
   */
  onPlayerError(event) {
    const { youtubePlaylistChange } = this.props;
    const { selectedTrack } = this.state;
    this.timer = setTimeout(() => { youtubePlaylistChange(selectedTrack); }, 3000);
  }
 
  /**
   * Play the video
   * Gather all the correct settings and call YouTube player api to play the video
   * When there is a full album & the subsequent tracks are segmented,
   * we ping YouTube API for status & elapsed time
   * in order to move video accordingly.
   */
  playVideo() {
    const { player, selectedTrack, fullAlbumDetails } = this.state;
    const availableID = this.availableVideoId();
    const params = youTubeParamsParser(availableID);
 
    if (!fullAlbumDetails) {
      clearInterval(this.fullAlbumVideoPoller);
      player.loadVideoById(params);
      return;
    }
 
    const trackToPlay = fullAlbumDetails.find((tr = {}) => tr.trackNumber === selectedTrack);
    const { startSeconds } = trackToPlay;
 
    const playerState = player.getPlayerState();
 
    if (playerState === YT.PlayerState.CUED) {
      player.seekTo(startSeconds);
      return;
    }
 
    const { currentTrack } = this.checkTimeAndTrack();
    const sameTrack = trackToPlay.trackNumber === currentTrack.trackNumber;
    if (!sameTrack) {
      player.seekTo(startSeconds);
      if (playerState === YT.PlayerState.PAUSED) {
        player.playVideo();
      }
    }
  }
 
  render() {
    const { playerAnchor } = this.state;
    return (
      <div className="YoutubePlayer">
        <div ref={playerAnchor} />
      </div>
    );
  }
}
 
YoutubePlayer.displayName = 'YouTube Player';
 
YoutubePlayer.propTypes = {
  selectedTrack: PropTypes.number.isRequired,
  id: PropTypes.string.isRequired,
  youtubePlaylistChange: PropTypes.func.isRequired,
  playlist: PropTypes.string.isRequired,
};
 
export default YoutubePlayer;