import React, { Component } from 'react'; // eslint-disable-line no-unused-vars import YouTube from 'react-youtube'; // eslint-disable-line no-unused-vars import axios from 'axios'; /* eslint no-console: ["error", { allow: ["info", "error", "warn"] }] */ class VideoPlayer extends Component { constructor(props) { super(props); this.state = { opt: { // height: '390', // width: '640', playerVars: { // https://developers.google.com/youtube/player_parameters autoplay: 0, modestbranding: 1 } }, videoId: '0J2QdDbelmY', promise1: null, promise2: null, outsideReject1: null, outsideReject2: null }; this._onPlay = this._onPlay.bind(this); this._onStateChange = this._onStateChange.bind(this); this._onReady = this._onReady.bind(this); } componentWillUpdate(nextProps, nextState) { if (nextProps.match.params.id === this.props.match.params.id) { } else if (nextProps.match.params.id) { this.setState((state, props) => { return { videoId: props.match.params.id }; }); } } componentWillReceiveProps(nextProps) { // if (nextProps.location !== this.props.location) {} } componentWillMount() { if (this.props.match.params.id) this.setState((state, props) => { return { videoId: props.match.params.id }; }); } componentWillUnmount() {} render() { return ( ); } // access to player in all event handlers via event.target _onError(event) { console.error('Error: ', event); } _onPlay(event) {} _onReady(event) {} _onStateChange(event) { let timerId1, timerId2; if (parseInt(event.data) === -1) { this.setState({ promise2: new Promise((resolve, reject) => { timerId2 = window.setInterval(() => { switch (parseInt(event.target.getPlayerState())) { case 1: resolve(1); break; case 5: resolve(5); break; default: break; } }, 500); this.setState({ outsideReject2: reject }); }) }); this.state.promise2.then(msg => { window.clearInterval(timerId2); switch (parseInt(msg)) { case 1: this.setState({ promise1: new Promise((resolve, reject) => { timerId1 = window.setInterval(() => { if (event.target.getCurrentTime() > 15) resolve(event.target.j.videoData.video_id); }, 1000); this.setState({ outsideReject1: reject }); }) }); this.state.promise1 .then( videoIdWatched => { // post request to local db axios .post('http://localhost:8000/videotrack', { id: videoIdWatched.toString() }) .then( response => console.info(response.data), error => console.info(error) ); // local storage logic for recent reccomender clearInterval(timerId1); }, error => console.info(error) ) .finally(() => this.setState({ promise1: null })); break; case 5: if (this.state.promise1) this.state.outsideReject1('Video changed'); break; default: break; } }); } } } export default VideoPlayer;