1 import './videojs-components/settings-menu-button'
2 import videojs from 'video.js'
3 import { timeToInt } from '@shared/core-utils'
10 saveVideoWatchHistory,
12 } from './peertube-player-local-storage'
13 import { PeerTubePluginOptions, ResolutionUpdateData, UserWatching, VideoJSCaption } from './peertube-videojs-typings'
14 import { isMobile } from './utils'
16 const Plugin = videojs.getPlugin('plugin')
18 class PeerTubePlugin extends Plugin {
19 private readonly videoViewUrl: string
20 private readonly videoDuration: number
21 private readonly CONSTANTS = {
22 USER_WATCHING_VIDEO_INTERVAL: 5000 // Every 5 seconds, notify the user is watching the video
25 private videoCaptions: VideoJSCaption[]
26 private defaultSubtitle: string
28 private videoViewInterval: any
29 private userWatchingVideoInterval: any
30 private lastResolutionChange: ResolutionUpdateData
32 private isLive: boolean
34 private menuOpened = false
35 private mouseInControlBar = false
36 private readonly savedInactivityTimeout: number
38 constructor (player: videojs.Player, options?: PeerTubePluginOptions) {
41 this.videoViewUrl = options.videoViewUrl
42 this.videoDuration = options.videoDuration
43 this.videoCaptions = options.videoCaptions
44 this.isLive = options.isLive
46 this.savedInactivityTimeout = player.options_.inactivityTimeout
48 if (options.autoplay) this.player.addClass('vjs-has-autoplay')
50 this.player.on('autoplay-failure', () => {
51 this.player.removeClass('vjs-has-autoplay')
54 this.player.ready(() => {
55 const playerOptions = this.player.options_
57 if (options.mode === 'webtorrent') {
58 this.player.webtorrent().on('resolutionChange', (_: any, d: any) => this.handleResolutionChange(d))
59 this.player.webtorrent().on('autoResolutionChange', (_: any, d: any) => this.trigger('autoResolutionChange', d))
62 if (options.mode === 'p2p-media-loader') {
63 this.player.p2pMediaLoader().on('resolutionChange', (_: any, d: any) => this.handleResolutionChange(d))
66 this.player.tech(true).on('loadedqualitydata', () => {
68 // Replay a resolution change, now we loaded all quality data
69 if (this.lastResolutionChange) this.handleResolutionChange(this.lastResolutionChange)
73 const volume = getStoredVolume()
74 if (volume !== undefined) this.player.volume(volume)
76 const muted = playerOptions.muted !== undefined ? playerOptions.muted : getStoredMute()
77 if (muted !== undefined) this.player.muted(muted)
79 this.defaultSubtitle = options.subtitle || getStoredLastSubtitle()
81 this.player.on('volumechange', () => {
82 saveVolumeInStore(this.player.volume())
83 saveMuteInStore(this.player.muted())
86 if (options.stopTime) {
87 const stopTime = timeToInt(options.stopTime)
90 this.player.on('timeupdate', function onTimeUpdate () {
91 if (self.player.currentTime() > stopTime) {
93 self.player.trigger('stopped')
95 self.player.off('timeupdate', onTimeUpdate)
100 this.player.textTracks().on('change', () => {
101 const showing = this.player.textTracks().tracks_.find(t => {
102 return t.kind === 'captions' && t.mode === 'showing'
106 saveLastSubtitle('off')
110 saveLastSubtitle(showing.language)
113 this.player.on('sourcechange', () => this.initCaptions())
115 this.player.duration(options.videoDuration)
117 this.initializePlayer()
120 this.runUserWatchVideo(options.userWatching, options.videoUUID)
125 if (this.videoViewInterval) clearInterval(this.videoViewInterval)
126 if (this.userWatchingVideoInterval) clearInterval(this.userWatchingVideoInterval)
130 this.menuOpened = false
131 this.alterInactivity()
135 this.menuOpened = true
136 this.alterInactivity()
139 private initializePlayer () {
140 if (isMobile()) this.player.addClass('vjs-is-mobile')
142 this.initSmoothProgressBar()
146 this.listenControlBarMouse()
149 private runViewAdd () {
150 this.clearVideoViewInterval()
152 // After 30 seconds (or 3/4 of the video), add a view to the video
153 let minSecondsToView = 30
155 if (!this.isLive && this.videoDuration < minSecondsToView) {
156 minSecondsToView = (this.videoDuration * 3) / 4
159 let secondsViewed = 0
160 this.videoViewInterval = setInterval(() => {
161 if (this.player && !this.player.paused()) {
164 if (secondsViewed > minSecondsToView) {
165 // Restart the loop if this is a live
169 this.clearVideoViewInterval()
172 this.addViewToVideo().catch(err => console.error(err))
178 private runUserWatchVideo (options: UserWatching, videoUUID: string) {
179 let lastCurrentTime = 0
181 this.userWatchingVideoInterval = setInterval(() => {
182 const currentTime = Math.floor(this.player.currentTime())
184 if (currentTime - lastCurrentTime >= 1) {
185 lastCurrentTime = currentTime
188 this.notifyUserIsWatching(currentTime, options.url, options.authorizationHeader)
189 .catch(err => console.error('Cannot notify user is watching.', err))
191 saveVideoWatchHistory(videoUUID, currentTime)
194 }, this.CONSTANTS.USER_WATCHING_VIDEO_INTERVAL)
197 private clearVideoViewInterval () {
198 if (this.videoViewInterval !== undefined) {
199 clearInterval(this.videoViewInterval)
200 this.videoViewInterval = undefined
204 private addViewToVideo () {
205 if (!this.videoViewUrl) return Promise.resolve(undefined)
207 return fetch(this.videoViewUrl, { method: 'POST' })
210 private notifyUserIsWatching (currentTime: number, url: string, authorizationHeader: string) {
211 const body = new URLSearchParams()
212 body.append('currentTime', currentTime.toString())
214 const headers = new Headers({ 'Authorization': authorizationHeader })
216 return fetch(url, { method: 'PUT', body, headers })
219 private handleResolutionChange (data: ResolutionUpdateData) {
220 this.lastResolutionChange = data
222 const qualityLevels = this.player.qualityLevels()
224 for (let i = 0; i < qualityLevels.length; i++) {
225 if (qualityLevels[i].height === data.resolutionId) {
226 data.id = qualityLevels[i].id
231 this.trigger('resolutionChange', data)
234 private listenControlBarMouse () {
235 this.player.controlBar.on('mouseenter', () => {
236 this.mouseInControlBar = true
237 this.alterInactivity()
240 this.player.controlBar.on('mouseleave', () => {
241 this.mouseInControlBar = false
242 this.alterInactivity()
246 private alterInactivity () {
247 if (this.menuOpened) {
248 this.player.options_.inactivityTimeout = this.savedInactivityTimeout
252 if (!this.mouseInControlBar && !this.isTouchEnabled()) {
253 this.player.options_.inactivityTimeout = 1
257 private isTouchEnabled () {
258 return ('ontouchstart' in window) ||
259 navigator.maxTouchPoints > 0 ||
260 navigator.msMaxTouchPoints > 0
263 private initCaptions () {
264 for (const caption of this.videoCaptions) {
265 this.player.addRemoteTextTrack({
267 label: caption.label,
268 language: caption.language,
269 id: caption.language,
271 default: this.defaultSubtitle === caption.language
275 this.player.trigger('captionsChanged')
278 // Thanks: https://github.com/videojs/video.js/issues/4460#issuecomment-312861657
279 private initSmoothProgressBar () {
280 const SeekBar = videojs.getComponent('SeekBar') as any
281 SeekBar.prototype.getPercent = function getPercent () {
282 // Allows for smooth scrubbing, when player can't keep up.
283 // const time = (this.player_.scrubbing()) ?
284 // this.player_.getCache().currentTime :
285 // this.player_.currentTime()
286 const time = this.player_.currentTime()
287 const percent = time / this.player_.duration()
288 return percent >= 1 ? 1 : percent
290 SeekBar.prototype.handleMouseMove = function handleMouseMove (event: any) {
291 let newTime = this.calculateDistance(event) * this.player_.duration()
292 if (newTime === this.player_.duration()) {
293 newTime = newTime - 0.1
295 this.player_.currentTime(newTime)
301 videojs.registerPlugin('peertube', PeerTubePlugin)
302 export { PeerTubePlugin }