1 import videojs from 'video.js'
2 import './videojs-components/settings-menu-button'
8 } from './peertube-videojs-typings'
9 import { isMobile, timeToInt } from './utils'
11 getStoredLastSubtitle,
16 saveVideoWatchHistory,
18 } from './peertube-player-local-storage'
20 const Plugin = videojs.getPlugin('plugin')
22 class PeerTubePlugin extends Plugin {
23 private readonly videoViewUrl: string
24 private readonly videoDuration: number
25 private readonly CONSTANTS = {
26 USER_WATCHING_VIDEO_INTERVAL: 5000 // Every 5 seconds, notify the user is watching the video
29 private videoCaptions: VideoJSCaption[]
30 private defaultSubtitle: string
32 private videoViewInterval: any
33 private userWatchingVideoInterval: any
34 private lastResolutionChange: ResolutionUpdateData
36 private isLive: boolean
38 private menuOpened = false
39 private mouseInControlBar = false
40 private readonly savedInactivityTimeout: number
42 constructor (player: videojs.Player, options?: PeerTubePluginOptions) {
45 this.videoViewUrl = options.videoViewUrl
46 this.videoDuration = options.videoDuration
47 this.videoCaptions = options.videoCaptions
48 this.isLive = options.isLive
50 this.savedInactivityTimeout = player.options_.inactivityTimeout
52 if (options.autoplay) this.player.addClass('vjs-has-autoplay')
54 this.player.on('autoplay-failure', () => {
55 this.player.removeClass('vjs-has-autoplay')
58 this.player.ready(() => {
59 const playerOptions = this.player.options_
61 if (options.mode === 'webtorrent') {
62 this.player.webtorrent().on('resolutionChange', (_: any, d: any) => this.handleResolutionChange(d))
63 this.player.webtorrent().on('autoResolutionChange', (_: any, d: any) => this.trigger('autoResolutionChange', d))
66 if (options.mode === 'p2p-media-loader') {
67 this.player.p2pMediaLoader().on('resolutionChange', (_: any, d: any) => this.handleResolutionChange(d))
70 this.player.tech(true).on('loadedqualitydata', () => {
72 // Replay a resolution change, now we loaded all quality data
73 if (this.lastResolutionChange) this.handleResolutionChange(this.lastResolutionChange)
77 const volume = getStoredVolume()
78 if (volume !== undefined) this.player.volume(volume)
80 const muted = playerOptions.muted !== undefined ? playerOptions.muted : getStoredMute()
81 if (muted !== undefined) this.player.muted(muted)
83 this.defaultSubtitle = options.subtitle || getStoredLastSubtitle()
85 this.player.on('volumechange', () => {
86 saveVolumeInStore(this.player.volume())
87 saveMuteInStore(this.player.muted())
90 if (options.stopTime) {
91 const stopTime = timeToInt(options.stopTime)
94 this.player.on('timeupdate', function onTimeUpdate () {
95 if (self.player.currentTime() > stopTime) {
97 self.player.trigger('stopped')
99 self.player.off('timeupdate', onTimeUpdate)
104 this.player.textTracks().on('change', () => {
105 const showing = this.player.textTracks().tracks_.find(t => {
106 return t.kind === 'captions' && t.mode === 'showing'
110 saveLastSubtitle('off')
114 saveLastSubtitle(showing.language)
117 this.player.on('sourcechange', () => this.initCaptions())
119 this.player.duration(options.videoDuration)
121 this.initializePlayer()
124 this.runUserWatchVideo(options.userWatching, options.videoUUID)
129 if (this.videoViewInterval) clearInterval(this.videoViewInterval)
130 if (this.userWatchingVideoInterval) clearInterval(this.userWatchingVideoInterval)
134 this.menuOpened = false
135 this.alterInactivity()
139 this.menuOpened = true
140 this.alterInactivity()
143 private initializePlayer () {
144 if (isMobile()) this.player.addClass('vjs-is-mobile')
146 this.initSmoothProgressBar()
150 this.listenControlBarMouse()
153 private runViewAdd () {
154 this.clearVideoViewInterval()
156 // After 30 seconds (or 3/4 of the video), add a view to the video
157 let minSecondsToView = 30
159 if (!this.isLive && this.videoDuration < minSecondsToView) {
160 minSecondsToView = (this.videoDuration * 3) / 4
163 let secondsViewed = 0
164 this.videoViewInterval = setInterval(() => {
165 if (this.player && !this.player.paused()) {
168 if (secondsViewed > minSecondsToView) {
169 // Restart the loop if this is a live
173 this.clearVideoViewInterval()
176 this.addViewToVideo().catch(err => console.error(err))
182 private runUserWatchVideo (options: UserWatching, videoUUID: string) {
183 let lastCurrentTime = 0
185 this.userWatchingVideoInterval = setInterval(() => {
186 const currentTime = Math.floor(this.player.currentTime())
188 if (currentTime - lastCurrentTime >= 1) {
189 lastCurrentTime = currentTime
192 this.notifyUserIsWatching(currentTime, options.url, options.authorizationHeader)
193 .catch(err => console.error('Cannot notify user is watching.', err))
195 saveVideoWatchHistory(videoUUID, currentTime)
198 }, this.CONSTANTS.USER_WATCHING_VIDEO_INTERVAL)
201 private clearVideoViewInterval () {
202 if (this.videoViewInterval !== undefined) {
203 clearInterval(this.videoViewInterval)
204 this.videoViewInterval = undefined
208 private addViewToVideo () {
209 if (!this.videoViewUrl) return Promise.resolve(undefined)
211 return fetch(this.videoViewUrl, { method: 'POST' })
214 private notifyUserIsWatching (currentTime: number, url: string, authorizationHeader: string) {
215 const body = new URLSearchParams()
216 body.append('currentTime', currentTime.toString())
218 const headers = new Headers({ 'Authorization': authorizationHeader })
220 return fetch(url, { method: 'PUT', body, headers })
223 private handleResolutionChange (data: ResolutionUpdateData) {
224 this.lastResolutionChange = data
226 const qualityLevels = this.player.qualityLevels()
228 for (let i = 0; i < qualityLevels.length; i++) {
229 if (qualityLevels[i].height === data.resolutionId) {
230 data.id = qualityLevels[i].id
235 this.trigger('resolutionChange', data)
238 private listenControlBarMouse () {
239 this.player.controlBar.on('mouseenter', () => {
240 this.mouseInControlBar = true
241 this.alterInactivity()
244 this.player.controlBar.on('mouseleave', () => {
245 this.mouseInControlBar = false
246 this.alterInactivity()
250 private alterInactivity () {
251 if (this.menuOpened) {
252 this.player.options_.inactivityTimeout = this.savedInactivityTimeout
256 if (!this.mouseInControlBar && !this.isTouchEnabled()) {
257 this.player.options_.inactivityTimeout = 1
261 private isTouchEnabled () {
262 return ('ontouchstart' in window) ||
263 navigator.maxTouchPoints > 0 ||
264 navigator.msMaxTouchPoints > 0
267 private initCaptions () {
268 for (const caption of this.videoCaptions) {
269 this.player.addRemoteTextTrack({
271 label: caption.label,
272 language: caption.language,
273 id: caption.language,
275 default: this.defaultSubtitle === caption.language
279 this.player.trigger('captionsChanged')
282 // Thanks: https://github.com/videojs/video.js/issues/4460#issuecomment-312861657
283 private initSmoothProgressBar () {
284 const SeekBar = videojs.getComponent('SeekBar') as any
285 SeekBar.prototype.getPercent = function getPercent () {
286 // Allows for smooth scrubbing, when player can't keep up.
287 // const time = (this.player_.scrubbing()) ?
288 // this.player_.getCache().currentTime :
289 // this.player_.currentTime()
290 const time = this.player_.currentTime()
291 const percent = time / this.player_.duration()
292 return percent >= 1 ? 1 : percent
294 SeekBar.prototype.handleMouseMove = function handleMouseMove (event: any) {
295 let newTime = this.calculateDistance(event) * this.player_.duration()
296 if (newTime === this.player_.duration()) {
297 newTime = newTime - 0.1
299 this.player_.currentTime(newTime)
305 videojs.registerPlugin('peertube', PeerTubePlugin)
306 export { PeerTubePlugin }