]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blame - client/src/assets/player/peertube-videojs-plugin.ts
Add ability to change the homepage
[github/Chocobozzz/PeerTube.git] / client / src / assets / player / peertube-videojs-plugin.ts
CommitLineData
aa8b6df4
C
1// Big thanks to: https://github.com/kmoskwiak/videojs-resolution-switcher
2
63c4db6d 3import * as videojs from 'video.js'
aa8b6df4 4import * as WebTorrent from 'webtorrent'
b6827820 5import { VideoFile } from '../../../../shared/models/videos/video.model'
aa8b6df4 6import { renderVideo } from './video-renderer'
be6a4802 7
339632b4
C
8declare module 'video.js' {
9 interface Player {
10 peertube (): PeerTubePlugin
11 }
12}
13
a22bfc3e 14interface VideoJSComponentInterface {
339632b4 15 _player: videojs.Player
a22bfc3e 16
339632b4 17 new (player: videojs.Player, options?: any)
a22bfc3e
C
18
19 registerComponent (name: string, obj: any)
20}
21
a22bfc3e
C
22type PeertubePluginOptions = {
23 videoFiles: VideoFile[]
24 playerElement: HTMLVideoElement
25 peerTubeLink: boolean
8cac1b64 26 videoViewUrl: string
3bcfff7f 27 videoDuration: number
a22bfc3e
C
28}
29
be6a4802
C
30// https://github.com/danrevah/ngx-pipes/blob/master/src/pipes/math/bytes.ts
31// Don't import all Angular stuff, just copy the code with shame
32const dictionaryBytes: Array<{max: number, type: string}> = [
33 { max: 1024, type: 'B' },
34 { max: 1048576, type: 'KB' },
35 { max: 1073741824, type: 'MB' },
36 { max: 1.0995116e12, type: 'GB' }
37]
38function bytes (value) {
39 const format = dictionaryBytes.find(d => value < d.max) || dictionaryBytes[dictionaryBytes.length - 1]
40 const calc = Math.floor(value / (format.max / 1024)).toString()
41
42 return [ calc, format.type ]
43}
aa8b6df4
C
44
45// videojs typings don't have some method we need
46const videojsUntyped = videojs as any
47const webtorrent = new WebTorrent({ dht: false })
48
a22bfc3e
C
49const MenuItem: VideoJSComponentInterface = videojsUntyped.getComponent('MenuItem')
50class ResolutionMenuItem extends MenuItem {
51
339632b4 52 constructor (player: videojs.Player, options) {
aa8b6df4 53 options.selectable = true
a22bfc3e 54 super(player, options)
aa8b6df4 55
a22bfc3e 56 const currentResolution = this.player_.peertube().getCurrentResolution()
aa8b6df4 57 this.selected(this.options_.id === currentResolution)
a22bfc3e 58 }
aa8b6df4 59
a22bfc3e 60 handleClick (event) {
531ab5b6
C
61 super.handleClick(event)
62
a22bfc3e 63 this.player_.peertube().updateResolution(this.options_.id)
aa8b6df4 64 }
a22bfc3e 65}
aa8b6df4
C
66MenuItem.registerComponent('ResolutionMenuItem', ResolutionMenuItem)
67
a22bfc3e
C
68const MenuButton: VideoJSComponentInterface = videojsUntyped.getComponent('MenuButton')
69class ResolutionMenuButton extends MenuButton {
70 label: HTMLElement
71
339632b4 72 constructor (player: videojs.Player, options) {
aa8b6df4 73 options.label = 'Quality'
a22bfc3e
C
74 super(player, options)
75
76 this.label = document.createElement('span')
aa8b6df4 77
aa8b6df4
C
78 this.el().setAttribute('aria-label', 'Quality')
79 this.controlText('Quality')
80
81 videojsUntyped.dom.addClass(this.label, 'vjs-resolution-button-label')
82 this.el().appendChild(this.label)
83
a22bfc3e
C
84 player.peertube().on('videoFileUpdate', () => this.update())
85 }
aa8b6df4 86
a22bfc3e 87 createItems () {
aa8b6df4 88 const menuItems = []
a22bfc3e 89 for (const videoFile of this.player_.peertube().videoFiles) {
aa8b6df4
C
90 menuItems.push(new ResolutionMenuItem(
91 this.player_,
92 {
93 id: videoFile.resolution,
94 label: videoFile.resolutionLabel,
95 src: videoFile.magnetUri,
96 selected: videoFile.resolution === this.currentSelection
97 })
98 )
99 }
100
101 return menuItems
a22bfc3e
C
102 }
103
104 update () {
105 if (!this.label) return
aa8b6df4 106
a22bfc3e 107 this.label.innerHTML = this.player_.peertube().getCurrentResolutionLabel()
be6a4802 108 this.hide()
a22bfc3e
C
109 return super.update()
110 }
111
112 buildCSSClass () {
113 return super.buildCSSClass() + ' vjs-resolution-button'
114 }
aa8b6df4 115
a22bfc3e
C
116 dispose () {
117 this.parentNode.removeChild(this)
aa8b6df4 118 }
a22bfc3e 119}
aa8b6df4
C
120MenuButton.registerComponent('ResolutionMenuButton', ResolutionMenuButton)
121
a22bfc3e
C
122const Button: VideoJSComponentInterface = videojsUntyped.getComponent('Button')
123class PeertubeLinkButton extends Button {
aa8b6df4 124
a22bfc3e 125 createEl () {
aa8b6df4
C
126 const link = document.createElement('a')
127 link.href = window.location.href.replace('embed', 'watch')
128 link.innerHTML = 'PeerTube'
129 link.title = 'Go to the video page'
130 link.className = 'vjs-peertube-link'
131 link.target = '_blank'
132
133 return link
a22bfc3e 134 }
aa8b6df4 135
a22bfc3e 136 handleClick () {
be6a4802 137 this.player_.pause()
aa8b6df4 138 }
aa8b6df4 139
a22bfc3e
C
140 dispose () {
141 this.parentNode.removeChild(this)
142 }
143}
144Button.registerComponent('PeerTubeLinkButton', PeertubeLinkButton)
be6a4802 145
a22bfc3e
C
146class WebTorrentButton extends Button {
147 createEl () {
be6a4802 148 const div = document.createElement('div')
bf5685f0
C
149 const subDivWebtorrent = document.createElement('div')
150 div.appendChild(subDivWebtorrent)
be6a4802
C
151
152 const downloadIcon = document.createElement('span')
153 downloadIcon.classList.add('icon', 'icon-download')
bf5685f0 154 subDivWebtorrent.appendChild(downloadIcon)
be6a4802
C
155
156 const downloadSpeedText = document.createElement('span')
157 downloadSpeedText.classList.add('download-speed-text')
158 const downloadSpeedNumber = document.createElement('span')
159 downloadSpeedNumber.classList.add('download-speed-number')
160 const downloadSpeedUnit = document.createElement('span')
161 downloadSpeedText.appendChild(downloadSpeedNumber)
162 downloadSpeedText.appendChild(downloadSpeedUnit)
bf5685f0 163 subDivWebtorrent.appendChild(downloadSpeedText)
be6a4802
C
164
165 const uploadIcon = document.createElement('span')
166 uploadIcon.classList.add('icon', 'icon-upload')
bf5685f0 167 subDivWebtorrent.appendChild(uploadIcon)
be6a4802
C
168
169 const uploadSpeedText = document.createElement('span')
170 uploadSpeedText.classList.add('upload-speed-text')
171 const uploadSpeedNumber = document.createElement('span')
172 uploadSpeedNumber.classList.add('upload-speed-number')
173 const uploadSpeedUnit = document.createElement('span')
174 uploadSpeedText.appendChild(uploadSpeedNumber)
175 uploadSpeedText.appendChild(uploadSpeedUnit)
bf5685f0 176 subDivWebtorrent.appendChild(uploadSpeedText)
be6a4802
C
177
178 const peersText = document.createElement('span')
be6a4802
C
179 peersText.classList.add('peers-text')
180 const peersNumber = document.createElement('span')
181 peersNumber.classList.add('peers-number')
bf5685f0
C
182 subDivWebtorrent.appendChild(peersNumber)
183 subDivWebtorrent.appendChild(peersText)
be6a4802 184
bf5685f0 185 div.className = 'vjs-peertube'
be6a4802 186 // Hide the stats before we get the info
bf5685f0
C
187 subDivWebtorrent.className = 'vjs-peertube-hidden'
188
189 const subDivHttp = document.createElement('div')
190 subDivHttp.className = 'vjs-peertube-hidden'
191 const subDivHttpText = document.createElement('span')
192 subDivHttpText.classList.add('peers-number')
193 subDivHttpText.textContent = 'HTTP'
194 const subDivFallbackText = document.createElement('span')
195 subDivFallbackText.classList.add('peers-text')
196 subDivFallbackText.textContent = ' fallback'
197
198 subDivHttp.appendChild(subDivHttpText)
199 subDivHttp.appendChild(subDivFallbackText)
200 div.appendChild(subDivHttp)
be6a4802 201
a22bfc3e 202 this.player_.peertube().on('torrentInfo', (event, data) => {
bf5685f0
C
203 // We are in HTTP fallback
204 if (!data) {
205 subDivHttp.className = 'vjs-peertube-displayed'
206 subDivWebtorrent.className = 'vjs-peertube-hidden'
207
208 return
209 }
210
be6a4802
C
211 const downloadSpeed = bytes(data.downloadSpeed)
212 const uploadSpeed = bytes(data.uploadSpeed)
213 const numPeers = data.numPeers
214
bf5685f0
C
215 downloadSpeedNumber.textContent = downloadSpeed[ 0 ]
216 downloadSpeedUnit.textContent = ' ' + downloadSpeed[ 1 ]
be6a4802 217
bf5685f0
C
218 uploadSpeedNumber.textContent = uploadSpeed[ 0 ]
219 uploadSpeedUnit.textContent = ' ' + uploadSpeed[ 1 ]
be6a4802
C
220
221 peersNumber.textContent = numPeers
bf5685f0 222 peersText.textContent = ' peers'
be6a4802 223
bf5685f0
C
224 subDivHttp.className = 'vjs-peertube-hidden'
225 subDivWebtorrent.className = 'vjs-peertube-displayed'
be6a4802
C
226 })
227
228 return div
229 }
be6a4802 230
a22bfc3e
C
231 dispose () {
232 this.parentNode.removeChild(this)
233 }
aa8b6df4 234}
a22bfc3e
C
235Button.registerComponent('WebTorrentButton', WebTorrentButton)
236
237const Plugin: VideoJSComponentInterface = videojsUntyped.getPlugin('plugin')
238class PeerTubePlugin extends Plugin {
239 private player: any
240 private currentVideoFile: VideoFile
241 private playerElement: HTMLVideoElement
242 private videoFiles: VideoFile[]
243 private torrent: WebTorrent.Torrent
481d3596 244 private autoplay = false
8cac1b64 245 private videoViewUrl: string
3bcfff7f 246 private videoDuration: number
8cac1b64 247 private videoViewInterval
3bcfff7f 248 private torrentInfoInterval
bf5685f0 249 private savePlayerSrcFunction: Function
a22bfc3e 250
339632b4 251 constructor (player: videojs.Player, options: PeertubePluginOptions) {
a22bfc3e
C
252 super(player, options)
253
481d3596
C
254 // Fix canplay event on google chrome by disabling default videojs autoplay
255 this.autoplay = this.player.options_.autoplay
256 this.player.options_.autoplay = false
257
a22bfc3e 258 this.videoFiles = options.videoFiles
8cac1b64 259 this.videoViewUrl = options.videoViewUrl
3bcfff7f 260 this.videoDuration = options.videoDuration
a22bfc3e 261
bf5685f0 262 this.savePlayerSrcFunction = this.player.src
a22bfc3e
C
263 // Hack to "simulate" src link in video.js >= 6
264 // Without this, we can't play the video after pausing it
265 // https://github.com/videojs/video.js/blob/master/src/js/player.js#L1633
bf5685f0 266 this.player.src = () => true
a22bfc3e
C
267
268 this.playerElement = options.playerElement
269
270 this.player.ready(() => {
271 this.initializePlayer(options)
272 this.runTorrentInfoScheduler()
3bcfff7f 273 this.runViewAdd()
a22bfc3e
C
274 })
275 }
276
277 dispose () {
3bcfff7f
C
278 clearInterval(this.videoViewInterval)
279 clearInterval(this.torrentInfoInterval)
280
a22bfc3e
C
281 // Don't need to destroy renderer, video player will be destroyed
282 this.flushVideoFile(this.currentVideoFile, false)
aa8b6df4
C
283 }
284
a22bfc3e
C
285 getCurrentResolution () {
286 return this.currentVideoFile ? this.currentVideoFile.resolution : -1
aa8b6df4
C
287 }
288
a22bfc3e
C
289 getCurrentResolutionLabel () {
290 return this.currentVideoFile ? this.currentVideoFile.resolutionLabel : ''
aa8b6df4
C
291 }
292
a22bfc3e 293 updateVideoFile (videoFile?: VideoFile, done?: () => void) {
aa8b6df4
C
294 if (done === undefined) {
295 done = () => { /* empty */ }
296 }
297
298 // Pick the first one
299 if (videoFile === undefined) {
a22bfc3e 300 videoFile = this.videoFiles[0]
aa8b6df4
C
301 }
302
303 // Don't add the same video file once again
a22bfc3e 304 if (this.currentVideoFile !== undefined && this.currentVideoFile.magnetUri === videoFile.magnetUri) {
aa8b6df4
C
305 return
306 }
307
bf5685f0
C
308 // Do not display error to user because we will have multiple fallbacks
309 this.disableErrorDisplay()
310 this.player.src = () => true
311
a22bfc3e
C
312 const previousVideoFile = this.currentVideoFile
313 this.currentVideoFile = videoFile
aa8b6df4
C
314
315 console.log('Adding ' + videoFile.magnetUri + '.')
a22bfc3e 316 this.torrent = webtorrent.add(videoFile.magnetUri, torrent => {
aa8b6df4
C
317 console.log('Added ' + videoFile.magnetUri + '.')
318
319 this.flushVideoFile(previousVideoFile)
320
321 const options = { autoplay: true, controls: true }
a22bfc3e 322 renderVideo(torrent.files[0], this.playerElement, options,(err, renderer) => {
bf5685f0 323 if (err) return this.fallbackToHttp()
aa8b6df4
C
324
325 this.renderer = renderer
3bcfff7f
C
326 if (!this.player.paused()) {
327 const playPromise = this.player.play()
328 if (playPromise !== undefined) return playPromise.then(done)
329
330 return done()
331 }
332
333 return done()
aa8b6df4
C
334 })
335 })
336
a22bfc3e
C
337 this.torrent.on('error', err => this.handleError(err))
338 this.torrent.on('warning', (err: any) => {
a96aed15 339 // We don't support HTTP tracker but we don't care -> we use the web socket tracker
531ab5b6 340 if (err.message.indexOf('Unsupported tracker protocol') !== -1) return
7dbdc3ba
C
341 // Users don't care about issues with WebRTC, but developers do so log it in the console
342 if (err.message.indexOf('Ice connection failed') !== -1) {
343 console.error(err)
344 return
345 }
a96aed15 346
a22bfc3e 347 return this.handleError(err)
a96aed15 348 })
aa8b6df4 349
a22bfc3e 350 this.trigger('videoFileUpdate')
aa8b6df4
C
351 }
352
a22bfc3e 353 updateResolution (resolution) {
aa8b6df4 354 // Remember player state
a22bfc3e
C
355 const currentTime = this.player.currentTime()
356 const isPaused = this.player.paused()
aa8b6df4 357
531ab5b6
C
358 // Remove poster to have black background
359 this.playerElement.poster = ''
360
aa8b6df4 361 // Hide bigPlayButton
8fa5653a 362 if (!isPaused) {
a22bfc3e 363 this.player.bigPlayButton.hide()
aa8b6df4
C
364 }
365
a22bfc3e
C
366 const newVideoFile = this.videoFiles.find(f => f.resolution === resolution)
367 this.updateVideoFile(newVideoFile, () => {
368 this.player.currentTime(currentTime)
369 this.player.handleTechSeeked_()
aa8b6df4
C
370 })
371 }
372
a22bfc3e 373 flushVideoFile (videoFile: VideoFile, destroyRenderer = true) {
aa8b6df4 374 if (videoFile !== undefined && webtorrent.get(videoFile.magnetUri)) {
bf5685f0
C
375 if (destroyRenderer === true && this.renderer && this.renderer.destroy) this.renderer.destroy()
376
aa8b6df4 377 webtorrent.remove(videoFile.magnetUri)
a22bfc3e 378 console.log('Removed ' + videoFile.magnetUri)
aa8b6df4
C
379 }
380 }
381
3bcfff7f 382 setVideoFiles (files: VideoFile[], videoViewUrl: string, videoDuration: number) {
8cac1b64 383 this.videoViewUrl = videoViewUrl
3bcfff7f 384 this.videoDuration = videoDuration
a22bfc3e 385 this.videoFiles = files
ed9f9f5f 386
8cac1b64 387 // Re run view add for the new video
3bcfff7f 388 this.runViewAdd()
a22bfc3e 389 this.updateVideoFile(undefined, () => this.player.play())
ed9f9f5f
C
390 }
391
a22bfc3e
C
392 private initializePlayer (options: PeertubePluginOptions) {
393 const controlBar = this.player.controlBar
aa8b6df4 394
a22bfc3e 395 const menuButton = new ResolutionMenuButton(this.player, options)
aa8b6df4
C
396 const fullscreenElement = controlBar.fullscreenToggle.el()
397 controlBar.resolutionSwitcher = controlBar.el().insertBefore(menuButton.el(), fullscreenElement)
aa8b6df4
C
398
399 if (options.peerTubeLink === true) {
a22bfc3e 400 const peerTubeLinkButton = new PeertubeLinkButton(this.player)
aa8b6df4 401 controlBar.peerTubeLink = controlBar.el().insertBefore(peerTubeLinkButton.el(), fullscreenElement)
aa8b6df4
C
402 }
403
a22bfc3e 404 const webTorrentButton = new WebTorrentButton(this.player)
be6a4802 405 controlBar.webTorrent = controlBar.el().insertBefore(webTorrentButton.el(), controlBar.progressControl.el())
be6a4802 406
481d3596
C
407 if (this.autoplay === true) {
408 this.updateVideoFile(undefined, () => this.player.play())
aa8b6df4 409 } else {
a22bfc3e 410 this.player.one('play', () => {
481d3596
C
411 this.player.pause()
412 this.updateVideoFile(undefined, () => this.player.play())
4dd551a0 413 })
aa8b6df4 414 }
a22bfc3e 415 }
aa8b6df4 416
a22bfc3e 417 private runTorrentInfoScheduler () {
3bcfff7f 418 this.torrentInfoInterval = setInterval(() => {
bf5685f0
C
419 // Not initialized yet
420 if (this.torrent === undefined) return
421
422 // Http fallback
423 if (this.torrent === null) return this.trigger('torrentInfo', false)
424
425 return this.trigger('torrentInfo', {
426 downloadSpeed: this.torrent.downloadSpeed,
427 numPeers: this.torrent.numPeers,
428 uploadSpeed: this.torrent.uploadSpeed
429 })
aa8b6df4 430 }, 1000)
a22bfc3e 431 }
aa8b6df4 432
8cac1b64
C
433 private runViewAdd () {
434 this.clearVideoViewInterval()
435
436 // After 30 seconds (or 3/4 of the video), add a view to the video
437 let minSecondsToView = 30
438
3bcfff7f 439 if (this.videoDuration < minSecondsToView) minSecondsToView = (this.videoDuration * 3) / 4
8cac1b64
C
440
441 let secondsViewed = 0
442 this.videoViewInterval = setInterval(() => {
443 if (this.player && !this.player.paused()) {
444 secondsViewed += 1
445
446 if (secondsViewed > minSecondsToView) {
447 this.clearVideoViewInterval()
448
449 this.addViewToVideo().catch(err => console.error(err))
450 }
451 }
452 }, 1000)
453 }
454
455 private clearVideoViewInterval () {
456 if (this.videoViewInterval !== undefined) {
457 clearInterval(this.videoViewInterval)
458 this.videoViewInterval = undefined
459 }
460 }
461
462 private addViewToVideo () {
463 return fetch(this.videoViewUrl, { method: 'POST' })
464 }
465
bf5685f0
C
466 private fallbackToHttp () {
467 this.flushVideoFile(this.currentVideoFile, true)
468 this.torrent = null
469
470 // Enable error display now this is our last fallback
471 this.player.one('error', () => this.enableErrorDisplay())
472
473 const httpUrl = this.currentVideoFile.fileUrl
474 this.player.src = this.savePlayerSrcFunction
475 this.player.src(httpUrl)
476 this.player.play()
477 }
478
a22bfc3e
C
479 private handleError (err: Error | string) {
480 return this.player.trigger('customError', { err })
aa8b6df4 481 }
bf5685f0
C
482
483 private enableErrorDisplay () {
484 this.player.addClass('vjs-error-display-enabled')
485 }
486
487 private disableErrorDisplay () {
488 this.player.removeClass('vjs-error-display-enabled')
489 }
aa8b6df4 490}
a22bfc3e 491videojsUntyped.registerPlugin('peertube', PeerTubePlugin)