1 import debug from 'debug'
2 import videojs from 'video.js'
3 import { logger } from '@root-helpers/logger'
4 import { isMobile } from '@root-helpers/web-browser'
5 import { timeToInt } from '@shared/core-utils'
6 import { VideoView, VideoViewEvent } from '@shared/models/videos'
13 saveVideoWatchHistory,
15 } from '../../peertube-player-local-storage'
16 import { PeerTubePluginOptions, VideoJSCaption } from '../../types'
17 import { SettingsButton } from '../settings/settings-menu-button'
19 const debugLogger = debug('peertube:player:peertube')
21 const Plugin = videojs.getPlugin('plugin')
23 class PeerTubePlugin extends Plugin {
24 private readonly videoViewUrl: string
25 private readonly authorizationHeader: string
27 private readonly videoUUID: string
28 private readonly startTime: number
30 private readonly CONSTANTS = {
31 USER_VIEW_VIDEO_INTERVAL: 5000 // Every 5 seconds, notify the user is watching the video
34 private videoCaptions: VideoJSCaption[]
35 private defaultSubtitle: string
37 private videoViewInterval: any
39 private menuOpened = false
40 private mouseInControlBar = false
41 private mouseInSettings = false
42 private readonly initialInactivityTimeout: number
44 constructor (player: videojs.Player, options?: PeerTubePluginOptions) {
47 this.videoViewUrl = options.videoViewUrl
48 this.authorizationHeader = options.authorizationHeader
49 this.videoUUID = options.videoUUID
50 this.startTime = timeToInt(options.startTime)
52 this.videoCaptions = options.videoCaptions
53 this.initialInactivityTimeout = this.player.options_.inactivityTimeout
55 if (options.autoplay) this.player.addClass('vjs-has-autoplay')
57 this.player.on('autoplay-failure', () => {
58 this.player.removeClass('vjs-has-autoplay')
61 this.player.ready(() => {
62 const playerOptions = this.player.options_
64 const volume = getStoredVolume()
65 if (volume !== undefined) this.player.volume(volume)
67 const muted = playerOptions.muted !== undefined ? playerOptions.muted : getStoredMute()
68 if (muted !== undefined) this.player.muted(muted)
70 this.defaultSubtitle = options.subtitle || getStoredLastSubtitle()
72 this.player.on('volumechange', () => {
73 saveVolumeInStore(this.player.volume())
74 saveMuteInStore(this.player.muted())
77 if (options.stopTime) {
78 const stopTime = timeToInt(options.stopTime)
81 this.player.on('timeupdate', function onTimeUpdate () {
82 if (self.player.currentTime() > stopTime) {
84 self.player.trigger('stopped')
86 self.player.off('timeupdate', onTimeUpdate)
91 this.player.textTracks().addEventListener('change', () => {
92 const showing = this.player.textTracks().tracks_.find(t => {
93 return t.kind === 'captions' && t.mode === 'showing'
97 saveLastSubtitle('off')
101 saveLastSubtitle(showing.language)
104 this.player.on('sourcechange', () => this.initCaptions())
106 this.player.duration(options.videoDuration)
108 this.initializePlayer()
109 this.runUserViewing()
114 if (this.videoViewInterval) clearInterval(this.videoViewInterval)
118 this.menuOpened = true
119 this.alterInactivity()
123 this.menuOpened = false
124 this.alterInactivity()
127 displayFatalError () {
128 this.player.loadingSpinner.hide()
130 const buildModal = (error: MediaError) => {
131 const localize = this.player.localize.bind(this.player)
133 const wrapper = document.createElement('div')
134 const header = document.createElement('h1')
135 header.innerText = localize('Failed to play video')
136 wrapper.appendChild(header)
137 const desc = document.createElement('div')
138 desc.innerText = localize('The video failed to play due to technical issues.')
139 wrapper.appendChild(desc)
140 const details = document.createElement('p')
141 details.classList.add('error-details')
142 details.innerText = error.message
143 wrapper.appendChild(details)
148 const modal = this.player.createModal(buildModal(this.player.error()), {
152 modal.addClass('vjs-custom-error-display')
154 this.player.addClass('vjs-error-display-enabled')
158 this.player.removeClass('vjs-error-display-enabled')
161 private initializePlayer () {
162 if (isMobile()) this.player.addClass('vjs-is-mobile')
164 this.initSmoothProgressBar()
168 this.listenControlBarMouse()
170 this.listenFullScreenChange()
173 // ---------------------------------------------------------------------------
175 private runUserViewing () {
176 let lastCurrentTime = this.startTime
177 let lastViewEvent: VideoViewEvent
179 this.player.one('play', () => {
180 this.notifyUserIsWatching(this.startTime, lastViewEvent)
183 this.player.on('seeked', () => {
184 // Don't take into account small seek events
185 if (Math.abs(this.player.currentTime() - lastCurrentTime) < 3) return
187 lastViewEvent = 'seek'
190 this.player.one('ended', () => {
191 const currentTime = Math.round(this.player.duration())
192 lastCurrentTime = currentTime
194 this.notifyUserIsWatching(currentTime, lastViewEvent)
196 lastViewEvent = undefined
199 this.videoViewInterval = setInterval(() => {
200 const currentTime = Math.round(this.player.currentTime())
203 if (currentTime === lastCurrentTime) return
205 lastCurrentTime = currentTime
207 this.notifyUserIsWatching(currentTime, lastViewEvent)
208 .catch(err => logger.error('Cannot notify user is watching.', err))
210 lastViewEvent = undefined
212 // Server won't save history, so save the video position in local storage
213 if (!this.authorizationHeader) {
214 saveVideoWatchHistory(this.videoUUID, currentTime)
216 }, this.CONSTANTS.USER_VIEW_VIDEO_INTERVAL)
219 private notifyUserIsWatching (currentTime: number, viewEvent: VideoViewEvent) {
220 if (!this.videoViewUrl) return Promise.resolve(undefined)
222 const body: VideoView = {
227 const headers = new Headers({
228 'Content-type': 'application/json; charset=UTF-8'
231 if (this.authorizationHeader) headers.set('Authorization', this.authorizationHeader)
233 return fetch(this.videoViewUrl, { method: 'POST', body: JSON.stringify(body), headers })
236 // ---------------------------------------------------------------------------
238 private listenFullScreenChange () {
239 this.player.on('fullscreenchange', () => {
240 if (this.player.isFullscreen()) this.player.focus()
244 private listenControlBarMouse () {
245 const controlBar = this.player.controlBar
246 const settingsButton: SettingsButton = (controlBar as any).settingsButton
248 controlBar.on('mouseenter', () => {
249 this.mouseInControlBar = true
250 this.alterInactivity()
253 controlBar.on('mouseleave', () => {
254 this.mouseInControlBar = false
255 this.alterInactivity()
258 settingsButton.dialog.on('mouseenter', () => {
259 this.mouseInSettings = true
260 this.alterInactivity()
263 settingsButton.dialog.on('mouseleave', () => {
264 this.mouseInSettings = false
265 this.alterInactivity()
269 private alterInactivity () {
270 if (this.menuOpened || this.mouseInSettings || this.mouseInControlBar) {
271 this.setInactivityTimeout(0)
275 this.setInactivityTimeout(this.initialInactivityTimeout)
276 this.player.reportUserActivity(true)
279 private setInactivityTimeout (timeout: number) {
280 (this.player as any).cache_.inactivityTimeout = timeout
281 this.player.options_.inactivityTimeout = timeout
283 debugLogger('Set player inactivity to ' + timeout)
286 private initCaptions () {
287 for (const caption of this.videoCaptions) {
288 this.player.addRemoteTextTrack({
290 label: caption.label,
291 language: caption.language,
292 id: caption.language,
294 default: this.defaultSubtitle === caption.language
298 this.player.trigger('captionsChanged')
301 // Thanks: https://github.com/videojs/video.js/issues/4460#issuecomment-312861657
302 private initSmoothProgressBar () {
303 const SeekBar = videojs.getComponent('SeekBar') as any
304 SeekBar.prototype.getPercent = function getPercent () {
305 // Allows for smooth scrubbing, when player can't keep up.
306 // const time = (this.player_.scrubbing()) ?
307 // this.player_.getCache().currentTime :
308 // this.player_.currentTime()
309 const time = this.player_.currentTime()
310 const percent = time / this.player_.duration()
311 return percent >= 1 ? 1 : percent
313 SeekBar.prototype.handleMouseMove = function handleMouseMove (event: any) {
314 let newTime = this.calculateDistance(event) * this.player_.duration()
315 if (newTime === this.player_.duration()) {
316 newTime = newTime - 0.1
318 this.player_.currentTime(newTime)
324 videojs.registerPlugin('peertube', PeerTubePlugin)
325 export { PeerTubePlugin }