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