aboutsummaryrefslogtreecommitdiffhomepage
path: root/client/src/assets/player/shared/peertube/peertube-plugin.ts
blob: 83c32415e833f4c8bd1b8bd6c5422badb395b6c5 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
import debug from 'debug'
import videojs from 'video.js'
import { logger } from '@root-helpers/logger'
import { isMobile } from '@root-helpers/web-browser'
import { timeToInt } from '@shared/core-utils'
import { VideoView, VideoViewEvent } from '@shared/models/videos'
import {
  getStoredLastSubtitle,
  getStoredMute,
  getStoredVolume,
  saveLastSubtitle,
  saveMuteInStore,
  saveVideoWatchHistory,
  saveVolumeInStore
} from '../../peertube-player-local-storage'
import { PeerTubePluginOptions, VideoJSCaption } from '../../types'
import { SettingsButton } from '../settings/settings-menu-button'

const debugLogger = debug('peertube:player:peertube')

const Plugin = videojs.getPlugin('plugin')

class PeerTubePlugin extends Plugin {
  private readonly videoViewUrl: string
  private readonly authorizationHeader: string

  private readonly videoUUID: string
  private readonly startTime: number

  private readonly CONSTANTS = {
    USER_VIEW_VIDEO_INTERVAL: 5000 // Every 5 seconds, notify the user is watching the video
  }

  private videoCaptions: VideoJSCaption[]
  private defaultSubtitle: string

  private videoViewInterval: any

  private menuOpened = false
  private mouseInControlBar = false
  private mouseInSettings = false
  private readonly initialInactivityTimeout: number

  constructor (player: videojs.Player, options?: PeerTubePluginOptions) {
    super(player)

    this.videoViewUrl = options.videoViewUrl
    this.authorizationHeader = options.authorizationHeader
    this.videoUUID = options.videoUUID
    this.startTime = timeToInt(options.startTime)

    this.videoCaptions = options.videoCaptions
    this.initialInactivityTimeout = this.player.options_.inactivityTimeout

    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_

      const volume = getStoredVolume()
      if (volume !== undefined) this.player.volume(volume)

      const muted = playerOptions.muted !== undefined ? playerOptions.muted : getStoredMute()
      if (muted !== undefined) this.player.muted(muted)

      this.defaultSubtitle = options.subtitle || getStoredLastSubtitle()

      this.player.on('volumechange', () => {
        saveVolumeInStore(this.player.volume())
        saveMuteInStore(this.player.muted())
      })

      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'
        })

        if (!showing) {
          saveLastSubtitle('off')
          return
        }

        saveLastSubtitle(showing.language)
      })

      this.player.on('sourcechange', () => this.initCaptions())

      this.player.duration(options.videoDuration)

      this.initializePlayer()
      this.runUserViewing()
    })
  }

  dispose () {
    if (this.videoViewInterval) clearInterval(this.videoViewInterval)
  }

  onMenuOpened () {
    this.menuOpened = true
    this.alterInactivity()
  }

  onMenuClosed () {
    this.menuOpened = false
    this.alterInactivity()
  }

  displayFatalError () {
    this.player.addClass('vjs-error-display-enabled')
  }

  hideFatalError () {
    this.player.removeClass('vjs-error-display-enabled')
  }

  private initializePlayer () {
    if (isMobile()) this.player.addClass('vjs-is-mobile')

    this.initSmoothProgressBar()

    this.initCaptions()

    this.listenControlBarMouse()

    this.listenFullScreenChange()
  }

  // ---------------------------------------------------------------------------

  private runUserViewing () {
    let lastCurrentTime = this.startTime
    let lastViewEvent: VideoViewEvent

    this.player.one('play', () => {
      this.notifyUserIsWatching(this.startTime, lastViewEvent)
    })

    this.player.on('seeked', () => {
      // Don't take into account small seek events
      if (Math.abs(this.player.currentTime() - lastCurrentTime) < 3) return

      lastViewEvent = 'seek'
    })

    this.player.one('ended', () => {
      const currentTime = Math.round(this.player.duration())
      lastCurrentTime = currentTime

      this.notifyUserIsWatching(currentTime, lastViewEvent)

      lastViewEvent = undefined
    })

    this.videoViewInterval = setInterval(() => {
      const currentTime = Math.round(this.player.currentTime())

      // No need to update
      if (currentTime === lastCurrentTime) return

      lastCurrentTime = currentTime

      this.notifyUserIsWatching(currentTime, lastViewEvent)
        .catch(err => logger.error('Cannot notify user is watching.', err))

      lastViewEvent = undefined

      // Server won't save history, so save the video position in local storage
      if (!this.authorizationHeader) {
        saveVideoWatchHistory(this.videoUUID, currentTime)
      }
    }, this.CONSTANTS.USER_VIEW_VIDEO_INTERVAL)
  }

  private notifyUserIsWatching (currentTime: number, viewEvent: VideoViewEvent) {
    if (!this.videoViewUrl) return Promise.resolve(undefined)

    const body: VideoView = {
      currentTime,
      viewEvent
    }

    const headers = new Headers({
      'Content-type': 'application/json; charset=UTF-8'
    })

    if (this.authorizationHeader) headers.set('Authorization', this.authorizationHeader)

    return fetch(this.videoViewUrl, { method: 'POST', body: JSON.stringify(body), headers })
  }

  // ---------------------------------------------------------------------------

  private listenFullScreenChange () {
    this.player.on('fullscreenchange', () => {
      if (this.player.isFullscreen()) this.player.focus()
    })
  }

  private listenControlBarMouse () {
    const controlBar = this.player.controlBar
    const settingsButton: SettingsButton = (controlBar as any).settingsButton

    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()
    })

    settingsButton.dialog.on('mouseleave', () => {
      this.mouseInSettings = false
      this.alterInactivity()
    })
  }

  private alterInactivity () {
    if (this.menuOpened || this.mouseInSettings || this.mouseInControlBar) {
      this.setInactivityTimeout(0)
      return
    }

    this.setInactivityTimeout(this.initialInactivityTimeout)
    this.player.reportUserActivity(true)
  }

  private setInactivityTimeout (timeout: number) {
    (this.player as any).cache_.inactivityTimeout = timeout
    this.player.options_.inactivityTimeout = timeout

    debugLogger('Set player inactivity to ' + timeout)
  }

  private initCaptions () {
    for (const caption of this.videoCaptions) {
      this.player.addRemoteTextTrack({
        kind: 'captions',
        label: caption.label,
        language: caption.language,
        id: caption.language,
        src: caption.src,
        default: this.defaultSubtitle === caption.language
      }, false)
    }

    this.player.trigger('captionsChanged')
  }

  // Thanks: https://github.com/videojs/video.js/issues/4460#issuecomment-312861657
  private initSmoothProgressBar () {
    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()) ?
      //   this.player_.getCache().currentTime :
      //   this.player_.currentTime()
      const time = this.player_.currentTime()
      const percent = time / this.player_.duration()
      return percent >= 1 ? 1 : percent
    }
    SeekBar.prototype.handleMouseMove = function handleMouseMove (event: any) {
      let newTime = this.calculateDistance(event) * this.player_.duration()
      if (newTime === this.player_.duration()) {
        newTime = newTime - 0.1
      }
      this.player_.currentTime(newTime)
      this.update()
    }
  }
}

videojs.registerPlugin('peertube', PeerTubePlugin)
export { PeerTubePlugin }