1 // FIXME: something weird with our path definition in tsconfig and typings
3 import * as videojs from 'video.js'
4 import './videojs-components/settings-menu-button'
5 import { PeerTubePluginOptions, UserWatching, VideoJSCaption, VideoJSComponentInterface, videojsUntyped } from './peertube-videojs-typings'
6 import { isMobile, timeToInt } from './utils'
14 } from './peertube-player-local-storage'
16 const Plugin: VideoJSComponentInterface = videojs.getPlugin('plugin')
17 class PeerTubePlugin extends Plugin {
18 private readonly autoplay: boolean = false
19 private readonly startTime: number = 0
20 private readonly videoViewUrl: string
21 private readonly videoDuration: number
22 private readonly CONSTANTS = {
23 USER_WATCHING_VIDEO_INTERVAL: 5000 // Every 5 seconds, notify the user is watching the video
27 private videoCaptions: VideoJSCaption[]
28 private defaultSubtitle: string
30 private videoViewInterval: any
31 private userWatchingVideoInterval: any
32 private qualityObservationTimer: any
34 constructor (player: videojs.Player, options: PeerTubePluginOptions) {
35 super(player, options)
37 this.startTime = timeToInt(options.startTime)
38 this.videoViewUrl = options.videoViewUrl
39 this.videoDuration = options.videoDuration
40 this.videoCaptions = options.videoCaptions
42 if (this.autoplay === true) this.player.addClass('vjs-has-autoplay')
44 this.player.ready(() => {
45 const playerOptions = this.player.options_
47 const volume = getStoredVolume()
48 if (volume !== undefined) this.player.volume(volume)
50 const muted = playerOptions.muted !== undefined ? playerOptions.muted : getStoredMute()
51 if (muted !== undefined) this.player.muted(muted)
53 this.defaultSubtitle = options.subtitle || getStoredLastSubtitle()
55 this.player.on('volumechange', () => {
56 saveVolumeInStore(this.player.volume())
57 saveMuteInStore(this.player.muted())
60 this.player.textTracks().on('change', () => {
61 const showing = this.player.textTracks().tracks_.find((t: { kind: string, mode: string }) => {
62 return t.kind === 'captions' && t.mode === 'showing'
66 saveLastSubtitle('off')
70 saveLastSubtitle(showing.language)
73 this.player.on('sourcechange', () => this.initCaptions())
75 this.player.duration(options.videoDuration)
77 this.initializePlayer()
80 if (options.userWatching) this.runUserWatchVideo(options.userWatching)
85 clearTimeout(this.qualityObservationTimer)
87 clearInterval(this.videoViewInterval)
89 if (this.userWatchingVideoInterval) clearInterval(this.userWatchingVideoInterval)
92 private initializePlayer () {
93 if (isMobile()) this.player.addClass('vjs-is-mobile')
95 this.initSmoothProgressBar()
99 this.alterInactivity()
102 private runViewAdd () {
103 this.clearVideoViewInterval()
105 // After 30 seconds (or 3/4 of the video), add a view to the video
106 let minSecondsToView = 30
108 if (this.videoDuration < minSecondsToView) minSecondsToView = (this.videoDuration * 3) / 4
110 let secondsViewed = 0
111 this.videoViewInterval = setInterval(() => {
112 if (this.player && !this.player.paused()) {
115 if (secondsViewed > minSecondsToView) {
116 this.clearVideoViewInterval()
118 this.addViewToVideo().catch(err => console.error(err))
124 private runUserWatchVideo (options: UserWatching) {
125 let lastCurrentTime = 0
127 this.userWatchingVideoInterval = setInterval(() => {
128 const currentTime = Math.floor(this.player.currentTime())
130 if (currentTime - lastCurrentTime >= 1) {
131 lastCurrentTime = currentTime
133 this.notifyUserIsWatching(currentTime, options.url, options.authorizationHeader)
134 .catch(err => console.error('Cannot notify user is watching.', err))
136 }, this.CONSTANTS.USER_WATCHING_VIDEO_INTERVAL)
139 private clearVideoViewInterval () {
140 if (this.videoViewInterval !== undefined) {
141 clearInterval(this.videoViewInterval)
142 this.videoViewInterval = undefined
146 private addViewToVideo () {
147 if (!this.videoViewUrl) return Promise.resolve(undefined)
149 return fetch(this.videoViewUrl, { method: 'POST' })
152 private notifyUserIsWatching (currentTime: number, url: string, authorizationHeader: string) {
153 const body = new URLSearchParams()
154 body.append('currentTime', currentTime.toString())
156 const headers = new Headers({ 'Authorization': authorizationHeader })
158 return fetch(url, { method: 'PUT', body, headers })
161 private alterInactivity () {
162 let saveInactivityTimeout: number
164 const disableInactivity = () => {
165 saveInactivityTimeout = this.player.options_.inactivityTimeout
166 this.player.options_.inactivityTimeout = 0
168 const enableInactivity = () => {
169 this.player.options_.inactivityTimeout = saveInactivityTimeout
172 const settingsDialog = this.player.children_.find((c: any) => c.name_ === 'SettingsDialog')
174 this.player.controlBar.on('mouseenter', () => disableInactivity())
175 settingsDialog.on('mouseenter', () => disableInactivity())
176 this.player.controlBar.on('mouseleave', () => enableInactivity())
177 settingsDialog.on('mouseleave', () => enableInactivity())
180 private initCaptions () {
181 for (const caption of this.videoCaptions) {
182 this.player.addRemoteTextTrack({
184 label: caption.label,
185 language: caption.language,
186 id: caption.language,
188 default: this.defaultSubtitle === caption.language
192 this.player.trigger('captionsChanged')
195 // Thanks: https://github.com/videojs/video.js/issues/4460#issuecomment-312861657
196 private initSmoothProgressBar () {
197 const SeekBar = videojsUntyped.getComponent('SeekBar')
198 SeekBar.prototype.getPercent = function getPercent () {
199 // Allows for smooth scrubbing, when player can't keep up.
200 // const time = (this.player_.scrubbing()) ?
201 // this.player_.getCache().currentTime :
202 // this.player_.currentTime()
203 const time = this.player_.currentTime()
204 const percent = time / this.player_.duration()
205 return percent >= 1 ? 1 : percent
207 SeekBar.prototype.handleMouseMove = function handleMouseMove (event: any) {
208 let newTime = this.calculateDistance(event) * this.player_.duration()
209 if (newTime === this.player_.duration()) {
210 newTime = newTime - 0.1
212 this.player_.currentTime(newTime)
218 videojs.registerPlugin('peertube', PeerTubePlugin)
219 export { PeerTubePlugin }