]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blobdiff - client/src/assets/player/peertube-plugin.ts
Add fixme info
[github/Chocobozzz/PeerTube.git] / client / src / assets / player / peertube-plugin.ts
index aacbf5f6efb5b1e09761730dd80423622ddfdb73..fd612dd4f0423a66d51992fcae8f81f9d216ecf1 100644 (file)
@@ -1,73 +1,61 @@
-// FIXME: something weird with our path definition in tsconfig and typings
-// @ts-ignore
-import * as videojs from 'video.js'
-import './videojs-components/settings-menu-button'
-import {
-  PeerTubePluginOptions,
-  ResolutionUpdateData,
-  UserWatching,
-  VideoJSCaption,
-  VideoJSComponentInterface,
-  videojsUntyped
-} from './peertube-videojs-typings'
-import { isMobile, timeToInt } from './utils'
+import videojs from 'video.js'
+import { timeToInt } from '@shared/core-utils'
 import {
   getStoredLastSubtitle,
   getStoredMute,
   getStoredVolume,
   saveLastSubtitle,
   saveMuteInStore,
+  saveVideoWatchHistory,
   saveVolumeInStore
 } from './peertube-player-local-storage'
+import { PeerTubePluginOptions, UserWatching, VideoJSCaption } from './peertube-videojs-typings'
+import { isMobile } from './utils'
+import { SettingsButton } from './videojs-components/settings-menu-button'
+import debug from 'debug'
+
+const logger = debug('peertube:player:peertube')
+
+const Plugin = videojs.getPlugin('plugin')
 
-const Plugin: VideoJSComponentInterface = videojs.getPlugin('plugin')
 class PeerTubePlugin extends Plugin {
-  private readonly autoplay: boolean = false
-  private readonly startTime: number = 0
   private readonly videoViewUrl: string
   private readonly videoDuration: number
   private readonly CONSTANTS = {
     USER_WATCHING_VIDEO_INTERVAL: 5000 // Every 5 seconds, notify the user is watching the video
   }
 
-  private player: any
   private videoCaptions: VideoJSCaption[]
   private defaultSubtitle: string
 
   private videoViewInterval: any
   private userWatchingVideoInterval: any
-  private qualityObservationTimer: any
-  private lastResolutionChange: ResolutionUpdateData
 
-  constructor (player: videojs.Player, options: PeerTubePluginOptions) {
-    super(player, options)
+  private isLive: boolean
+
+  private menuOpened = false
+  private mouseInControlBar = false
+  private mouseInSettings = false
+  private readonly initialInactivityTimeout: number
+
+  constructor (player: videojs.Player, options?: PeerTubePluginOptions) {
+    super(player)
 
-    this.startTime = timeToInt(options.startTime)
     this.videoViewUrl = options.videoViewUrl
     this.videoDuration = options.videoDuration
     this.videoCaptions = options.videoCaptions
+    this.isLive = options.isLive
+    this.initialInactivityTimeout = this.player.options_.inactivityTimeout
 
-    if (this.autoplay === true) this.player.addClass('vjs-has-autoplay')
+    if (options.autoplay) this.player.addClass('vjs-has-autoplay')
+
+    this.player.on('autoplay-failure', () => {
+      this.player.removeClass('vjs-has-autoplay')
+    })
 
     this.player.ready(() => {
       const playerOptions = this.player.options_
 
-      if (options.mode === 'webtorrent') {
-        this.player.webtorrent().on('resolutionChange', (_: any, d: any) => this.handleResolutionChange(d))
-        this.player.webtorrent().on('autoResolutionChange', (_: any, d: any) => this.trigger('autoResolutionChange', d))
-      }
-
-      if (options.mode === 'p2p-media-loader') {
-        this.player.p2pMediaLoader().on('resolutionChange', (_: any, d: any) => this.handleResolutionChange(d))
-      }
-
-      this.player.tech_.on('loadedqualitydata', () => {
-        setTimeout(() => {
-          // Replay a resolution change, now we loaded all quality data
-          if (this.lastResolutionChange) this.handleResolutionChange(this.lastResolutionChange)
-        }, 0)
-      })
-
       const volume = getStoredVolume()
       if (volume !== undefined) this.player.volume(volume)
 
@@ -81,8 +69,22 @@ class PeerTubePlugin extends Plugin {
         saveMuteInStore(this.player.muted())
       })
 
-      this.player.textTracks().on('change', () => {
-        const showing = this.player.textTracks().tracks_.find((t: { kind: string, mode: string }) => {
+      if (options.stopTime) {
+        const stopTime = timeToInt(options.stopTime)
+        const self = this
+
+        this.player.on('timeupdate', function onTimeUpdate () {
+          if (self.player.currentTime() > stopTime) {
+            self.player.pause()
+            self.player.trigger('stopped')
+
+            self.player.off('timeupdate', onTimeUpdate)
+          }
+        })
+      }
+
+      this.player.textTracks().addEventListener('change', () => {
+        const showing = this.player.textTracks().tracks_.find(t => {
           return t.kind === 'captions' && t.mode === 'showing'
         })
 
@@ -101,16 +103,23 @@ class PeerTubePlugin extends Plugin {
       this.initializePlayer()
       this.runViewAdd()
 
-      if (options.userWatching) this.runUserWatchVideo(options.userWatching)
+      this.runUserWatchVideo(options.userWatching, options.videoUUID)
     })
   }
 
   dispose () {
-    clearTimeout(this.qualityObservationTimer)
+    if (this.videoViewInterval) clearInterval(this.videoViewInterval)
+    if (this.userWatchingVideoInterval) clearInterval(this.userWatchingVideoInterval)
+  }
 
-    clearInterval(this.videoViewInterval)
+  onMenuOpened () {
+    this.menuOpened = true
+    this.alterInactivity()
+  }
 
-    if (this.userWatchingVideoInterval) clearInterval(this.userWatchingVideoInterval)
+  onMenuClosed () {
+    this.menuOpened = false
+    this.alterInactivity()
   }
 
   private initializePlayer () {
@@ -120,7 +129,9 @@ class PeerTubePlugin extends Plugin {
 
     this.initCaptions()
 
-    this.alterInactivity()
+    this.listenControlBarMouse()
+
+    this.listenFullScreenChange()
   }
 
   private runViewAdd () {
@@ -129,7 +140,9 @@ class PeerTubePlugin extends Plugin {
     // After 30 seconds (or 3/4 of the video), add a view to the video
     let minSecondsToView = 30
 
-    if (this.videoDuration < minSecondsToView) minSecondsToView = (this.videoDuration * 3) / 4
+    if (!this.isLive && this.videoDuration < minSecondsToView) {
+      minSecondsToView = (this.videoDuration * 3) / 4
+    }
 
     let secondsViewed = 0
     this.videoViewInterval = setInterval(() => {
@@ -137,7 +150,12 @@ class PeerTubePlugin extends Plugin {
         secondsViewed += 1
 
         if (secondsViewed > minSecondsToView) {
-          this.clearVideoViewInterval()
+          // Restart the loop if this is a live
+          if (this.isLive) {
+            secondsViewed = 0
+          } else {
+            this.clearVideoViewInterval()
+          }
 
           this.addViewToVideo().catch(err => console.error(err))
         }
@@ -145,7 +163,7 @@ class PeerTubePlugin extends Plugin {
     }, 1000)
   }
 
-  private runUserWatchVideo (options: UserWatching) {
+  private runUserWatchVideo (options: UserWatching, videoUUID: string) {
     let lastCurrentTime = 0
 
     this.userWatchingVideoInterval = setInterval(() => {
@@ -154,8 +172,12 @@ class PeerTubePlugin extends Plugin {
       if (currentTime - lastCurrentTime >= 1) {
         lastCurrentTime = currentTime
 
-        this.notifyUserIsWatching(currentTime, options.url, options.authorizationHeader)
-          .catch(err => console.error('Cannot notify user is watching.', err))
+        if (options) {
+          this.notifyUserIsWatching(currentTime, options.url, options.authorizationHeader)
+            .catch(err => console.error('Cannot notify user is watching.', err))
+        } else {
+          saveVideoWatchHistory(videoUUID, currentTime)
+        }
       }
     }, this.CONSTANTS.USER_WATCHING_VIDEO_INTERVAL)
   }
@@ -177,43 +199,57 @@ class PeerTubePlugin extends Plugin {
     const body = new URLSearchParams()
     body.append('currentTime', currentTime.toString())
 
-    const headers = new Headers({ 'Authorization': authorizationHeader })
+    const headers = new Headers({ Authorization: authorizationHeader })
 
     return fetch(url, { method: 'PUT', body, headers })
   }
 
-  private handleResolutionChange (data: ResolutionUpdateData) {
-    this.lastResolutionChange = data
+  private listenFullScreenChange () {
+    this.player.on('fullscreenchange', () => {
+      if (this.player.isFullscreen()) this.player.focus()
+    })
+  }
 
-    const qualityLevels = this.player.qualityLevels()
+  private listenControlBarMouse () {
+    const controlBar = this.player.controlBar
+    const settingsButton: SettingsButton = (controlBar as any).settingsButton
 
-    for (let i = 0; i < qualityLevels.length; i++) {
-      if (qualityLevels[i].height === data.resolutionId) {
-        data.id = qualityLevels[i].id
-        break
-      }
-    }
+    controlBar.on('mouseenter', () => {
+      this.mouseInControlBar = true
+      this.alterInactivity()
+    })
+
+    controlBar.on('mouseleave', () => {
+      this.mouseInControlBar = false
+      this.alterInactivity()
+    })
+
+    settingsButton.dialog.on('mouseenter', () => {
+      this.mouseInSettings = true
+      this.alterInactivity()
+    })
 
-    this.trigger('resolutionChange', data)
+    settingsButton.dialog.on('mouseleave', () => {
+      this.mouseInSettings = false
+      this.alterInactivity()
+    })
   }
 
   private alterInactivity () {
-    let saveInactivityTimeout: number
-
-    const disableInactivity = () => {
-      saveInactivityTimeout = this.player.options_.inactivityTimeout
-      this.player.options_.inactivityTimeout = 0
-    }
-    const enableInactivity = () => {
-      this.player.options_.inactivityTimeout = saveInactivityTimeout
+    if (this.menuOpened || this.mouseInSettings || this.mouseInControlBar) {
+      this.setInactivityTimeout(0)
+      return
     }
 
-    const settingsDialog = this.player.children_.find((c: any) => c.name_ === 'SettingsDialog')
+    this.setInactivityTimeout(this.initialInactivityTimeout)
+    this.player.reportUserActivity(true)
+  }
+
+  private setInactivityTimeout (timeout: number) {
+    (this.player as any).cache_.inactivityTimeout = timeout
+    this.player.options_.inactivityTimeout = timeout
 
-    this.player.controlBar.on('mouseenter', () => disableInactivity())
-    settingsDialog.on('mouseenter', () => disableInactivity())
-    this.player.controlBar.on('mouseleave', () => enableInactivity())
-    settingsDialog.on('mouseleave', () => enableInactivity())
+    logger('Set player inactivity to ' + timeout)
   }
 
   private initCaptions () {
@@ -233,7 +269,7 @@ class PeerTubePlugin extends Plugin {
 
   // Thanks: https://github.com/videojs/video.js/issues/4460#issuecomment-312861657
   private initSmoothProgressBar () {
-    const SeekBar = videojsUntyped.getComponent('SeekBar')
+    const SeekBar = videojs.getComponent('SeekBar') as any
     SeekBar.prototype.getPercent = function getPercent () {
       // Allows for smooth scrubbing, when player can't keep up.
       // const time = (this.player_.scrubbing()) ?