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