|
| 1 | +import React from 'react' |
| 2 | +import PagesContext from '../contexes/PagesContext' |
| 3 | + |
| 4 | +import styled from 'styled-components' |
| 5 | + |
| 6 | +import ReduxActionAnalytics from 'redux-action-analytics' |
| 7 | +import * as storejs from 'store' |
| 8 | +import YouTube from 'react-youtube' |
| 9 | + |
| 10 | +let analytics = undefined |
| 11 | + |
| 12 | +initAnalytics() |
| 13 | + |
| 14 | +function initAnalytics() { |
| 15 | + analytics = new ReduxActionAnalytics( |
| 16 | + 'https://usage.testmycode.io/api/v0/data', |
| 17 | + 'youtube-watch-stats', |
| 18 | + 'youtube-watch-stats', |
| 19 | + 10000, |
| 20 | + () => { |
| 21 | + const user = storejs.get('tmc.user') |
| 22 | + if (user === undefined) { |
| 23 | + return {} |
| 24 | + } |
| 25 | + return { |
| 26 | + username: user.username, |
| 27 | + } |
| 28 | + } |
| 29 | + ) |
| 30 | +} |
| 31 | + |
| 32 | +function onPlayerStateChange(event) { |
| 33 | + const player = event.target |
| 34 | + const eventCode = event.data |
| 35 | + const action = Object.entries(YouTube.PlayerState).find(o => { |
| 36 | + return o[1] == eventCode |
| 37 | + })[0] |
| 38 | + logAction(action, player) |
| 39 | +} |
| 40 | + |
| 41 | +function onPlaybackRateChange(event) { |
| 42 | + const player = event.target |
| 43 | + logAction('PLAYBACK_SPEED_CHANGED', player) |
| 44 | +} |
| 45 | + |
| 46 | +function logAction(action, player) { |
| 47 | + const happenedAt = new Date().getTime() |
| 48 | + const videoTime = player.getCurrentTime() |
| 49 | + const youtubeIdentifier = player.___youtube_identifier |
| 50 | + const playBackRate = player.getPlaybackRate() |
| 51 | + const snapshot = { |
| 52 | + action: action, |
| 53 | + video_time: videoTime, |
| 54 | + youtube_identifier: youtubeIdentifier, |
| 55 | + happened_at_milliseconds: happenedAt, |
| 56 | + playback_speed: playBackRate, |
| 57 | + } |
| 58 | + analytics.saveAction(snapshot) |
| 59 | +} |
| 60 | + |
| 61 | +const VideoWrapper = styled.div` |
| 62 | + position: relative; |
| 63 | + padding-bottom: 56.25%; /* 16:9 */ |
| 64 | + padding-top: 25px; |
| 65 | + height: 0; |
| 66 | +
|
| 67 | + iframe { |
| 68 | + position: absolute; |
| 69 | + top: 0; |
| 70 | + left: 0; |
| 71 | + width: 100%; |
| 72 | + height: 100%; |
| 73 | + } |
| 74 | +` |
| 75 | + |
| 76 | +export default props => { |
| 77 | + return ( |
| 78 | + <VideoWrapper> |
| 79 | + <YouTube |
| 80 | + videoId={props.id} |
| 81 | + onStateChange={onPlayerStateChange} |
| 82 | + onPlaybackRateChange={onPlaybackRateChange} |
| 83 | + opts={{ |
| 84 | + height: '390', |
| 85 | + width: '640', |
| 86 | + playerVars: { |
| 87 | + modestbranding: true, |
| 88 | + }, |
| 89 | + }} |
| 90 | + /> |
| 91 | + </VideoWrapper> |
| 92 | + ) |
| 93 | +} |
0 commit comments