1 import debug from 'debug'
2 import videojs from 'video.js'
3 import { isMobile } from '@root-helpers/web-browser'
4 import { timeToInt } from '@shared/core-utils'
5 import { VideoView, VideoViewEvent } from '@shared/models/videos'
12 saveVideoWatchHistory,
14 } from '../../peertube-player-local-storage'
15 import { PeerTubePluginOptions, VideoJSCaption } from '../../types'
16 import { SettingsButton } from '../settings/settings-menu-button'
18 const logger = debug('peertube:player:peertube')
20 const Plugin = videojs.getPlugin('plugin')
22 class PeerTubePlugin extends Plugin {
23 private readonly videoViewUrl: string
24 private readonly authorizationHeader: string
26 private readonly videoUUID: string
27 private readonly startTime: number
29 private readonly CONSTANTS = {
30 USER_VIEW_VIDEO_INTERVAL: 5000 // Every 5 seconds, notify the user is watching the video
33 private videoCaptions: VideoJSCaption[]
34 private defaultSubtitle: string
36 private videoViewInterval: any
38 private menuOpened = false
39 private mouseInControlBar = false
40 private mouseInSettings = false
41 private readonly initialInactivityTimeout: number
43 constructor (player: videojs.Player, options?: PeerTubePluginOptions) {
46 this.videoViewUrl = options.videoViewUrl
47 this.authorizationHeader = options.authorizationHeader
48 this.videoUUID = options.videoUUID
49 this.startTime = timeToInt(options.startTime)
51 this.videoCaptions = options.videoCaptions
52 this.initialInactivityTimeout = this.player.options_.inactivityTimeout
54 if (options.autoplay) this.player.addClass('vjs-has-autoplay')
56 this.player.on('autoplay-failure', () => {
57 this.player.removeClass('vjs-has-autoplay')
60 this.player.ready(() => {
61 const playerOptions = this.player.options_
63 const volume = getStoredVolume()
64 if (volume !== undefined) this.player.volume(volume)
66 const muted = playerOptions.muted !== undefined ? playerOptions.muted : getStoredMute()
67 if (muted !== undefined) this.player.muted(muted)
69 this.defaultSubtitle = options.subtitle || getStoredLastSubtitle()
71 this.player.on('volumechange', () => {
72 saveVolumeInStore(this.player.volume())
73 saveMuteInStore(this.player.muted())
76 if (options.stopTime) {
77 const stopTime = timeToInt(options.stopTime)
80 this.player.on('timeupdate', function onTimeUpdate () {
81 if (self.player.currentTime() > stopTime) {
83 self.player.trigger('stopped')
85 self.player.off('timeupdate', onTimeUpdate)
90 this.player.textTracks().addEventListener('change', () => {
91 const showing = this.player.textTracks().tracks_.find(t => {
92 return t.kind === 'captions' && t.mode === 'showing'
96 saveLastSubtitle('off')
100 saveLastSubtitle(showing.language)
103 this.player.on('sourcechange', () => this.initCaptions())
105 this.player.duration(options.videoDuration)
107 this.initializePlayer()
108 this.runUserViewing()
113 if (this.videoViewInterval) clearInterval(this.videoViewInterval)
117 this.menuOpened = true
118 this.alterInactivity()
122 this.menuOpened = false
123 this.alterInactivity()
126 displayFatalError () {
127 this.player.addClass('vjs-error-display-enabled')
131 this.player.removeClass('vjs-error-display-enabled')
134 private initializePlayer () {
135 if (isMobile()) this.player.addClass('vjs-is-mobile')
137 this.initSmoothProgressBar()
141 this.listenControlBarMouse()
143 this.listenFullScreenChange()
146 private runUserViewing () {
147 let lastCurrentTime = this.startTime
148 let lastViewEvent: VideoViewEvent
150 this.player.one('play', () => {
151 this.notifyUserIsWatching(this.startTime, lastViewEvent)
154 this.player.on('seeked', () => {
155 // Don't take into account small seek events
156 if (Math.abs(this.player.currentTime() - lastCurrentTime) < 3) return
158 lastViewEvent = 'seek'
161 this.player.one('ended', () => {
162 const currentTime = Math.round(this.player.duration())
163 lastCurrentTime = currentTime
165 this.notifyUserIsWatching(currentTime, lastViewEvent)
167 lastViewEvent = undefined
170 this.videoViewInterval = setInterval(() => {
171 const currentTime = Math.round(this.player.currentTime())
174 if (currentTime === lastCurrentTime) return
176 lastCurrentTime = currentTime
178 this.notifyUserIsWatching(currentTime, lastViewEvent)
179 .catch(err => console.error('Cannot notify user is watching.', err))
181 lastViewEvent = undefined
183 // Server won't save history, so save the video position in local storage
184 if (!this.authorizationHeader) {
185 saveVideoWatchHistory(this.videoUUID, currentTime)
187 }, this.CONSTANTS.USER_VIEW_VIDEO_INTERVAL)
190 private notifyUserIsWatching (currentTime: number, viewEvent: VideoViewEvent) {
191 if (!this.videoViewUrl) return Promise.resolve(undefined)
193 const body: VideoView = {
198 const headers = new Headers({
199 'Content-type': 'application/json; charset=UTF-8'
202 if (this.authorizationHeader) headers.set('Authorization', this.authorizationHeader)
204 return fetch(this.videoViewUrl, { method: 'POST', body: JSON.stringify(body), headers })
207 private listenFullScreenChange () {
208 this.player.on('fullscreenchange', () => {
209 if (this.player.isFullscreen()) this.player.focus()
213 private listenControlBarMouse () {
214 const controlBar = this.player.controlBar
215 const settingsButton: SettingsButton = (controlBar as any).settingsButton
217 controlBar.on('mouseenter', () => {
218 this.mouseInControlBar = true
219 this.alterInactivity()
222 controlBar.on('mouseleave', () => {
223 this.mouseInControlBar = false
224 this.alterInactivity()
227 settingsButton.dialog.on('mouseenter', () => {
228 this.mouseInSettings = true
229 this.alterInactivity()
232 settingsButton.dialog.on('mouseleave', () => {
233 this.mouseInSettings = false
234 this.alterInactivity()
238 private alterInactivity () {
239 if (this.menuOpened || this.mouseInSettings || this.mouseInControlBar) {
240 this.setInactivityTimeout(0)
244 this.setInactivityTimeout(this.initialInactivityTimeout)
245 this.player.reportUserActivity(true)
248 private setInactivityTimeout (timeout: number) {
249 (this.player as any).cache_.inactivityTimeout = timeout
250 this.player.options_.inactivityTimeout = timeout
252 logger('Set player inactivity to ' + timeout)
255 private initCaptions () {
256 for (const caption of this.videoCaptions) {
257 this.player.addRemoteTextTrack({
259 label: caption.label,
260 language: caption.language,
261 id: caption.language,
263 default: this.defaultSubtitle === caption.language
267 this.player.trigger('captionsChanged')
270 // Thanks: https://github.com/videojs/video.js/issues/4460#issuecomment-312861657
271 private initSmoothProgressBar () {
272 const SeekBar = videojs.getComponent('SeekBar') as any
273 SeekBar.prototype.getPercent = function getPercent () {
274 // Allows for smooth scrubbing, when player can't keep up.
275 // const time = (this.player_.scrubbing()) ?
276 // this.player_.getCache().currentTime :
277 // this.player_.currentTime()
278 const time = this.player_.currentTime()
279 const percent = time / this.player_.duration()
280 return percent >= 1 ? 1 : percent
282 SeekBar.prototype.handleMouseMove = function handleMouseMove (event: any) {
283 let newTime = this.calculateDistance(event) * this.player_.duration()
284 if (newTime === this.player_.duration()) {
285 newTime = newTime - 0.1
287 this.player_.currentTime(newTime)
293 videojs.registerPlugin('peertube', PeerTubePlugin)
294 export { PeerTubePlugin }