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