Refractor peertube videojs plugin
[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 { VideoFile } from '../../../../shared/models/videos/video.model'
6
7 import { renderVideo } from './video-renderer'
8
9 interface VideoJSComponentInterface {
10   _player: VideoJSPlayer
11
12   new (player: VideoJSPlayer, options?: any)
13
14   registerComponent (name: string, obj: any)
15 }
16
17 interface VideoJSPlayer extends videojs.Player {
18   peertube (): PeerTubePlugin
19 }
20
21 type PeertubePluginOptions = {
22   videoFiles: VideoFile[]
23   playerElement: HTMLVideoElement
24   peerTubeLink: boolean
25 }
26
27 // https://github.com/danrevah/ngx-pipes/blob/master/src/pipes/math/bytes.ts
28 // Don't import all Angular stuff, just copy the code with shame
29 const dictionaryBytes: Array<{max: number, type: string}> = [
30   { max: 1024, type: 'B' },
31   { max: 1048576, type: 'KB' },
32   { max: 1073741824, type: 'MB' },
33   { max: 1.0995116e12, type: 'GB' }
34 ]
35 function bytes (value) {
36   const format = dictionaryBytes.find(d => value < d.max) || dictionaryBytes[dictionaryBytes.length - 1]
37   const calc = Math.floor(value / (format.max / 1024)).toString()
38
39   return [ calc, format.type ]
40 }
41
42 // videojs typings don't have some method we need
43 const videojsUntyped = videojs as any
44 const webtorrent = new WebTorrent({ dht: false })
45
46 const MenuItem: VideoJSComponentInterface = videojsUntyped.getComponent('MenuItem')
47 class ResolutionMenuItem extends MenuItem {
48
49   constructor (player: VideoJSPlayer, options) {
50     options.selectable = true
51     super(player, options)
52
53     const currentResolution = this.player_.peertube().getCurrentResolution()
54     this.selected(this.options_.id === currentResolution)
55   }
56
57   handleClick (event) {
58     MenuItem.prototype.handleClick.call(this, event)
59     this.player_.peertube().updateResolution(this.options_.id)
60   }
61 }
62 MenuItem.registerComponent('ResolutionMenuItem', ResolutionMenuItem)
63
64 const MenuButton: VideoJSComponentInterface = videojsUntyped.getComponent('MenuButton')
65 class ResolutionMenuButton extends MenuButton {
66   label: HTMLElement
67
68   constructor (player: VideoJSPlayer, options) {
69     options.label = 'Quality'
70     super(player, options)
71
72     this.label = document.createElement('span')
73
74     this.el().setAttribute('aria-label', 'Quality')
75     this.controlText('Quality')
76
77     videojsUntyped.dom.addClass(this.label, 'vjs-resolution-button-label')
78     this.el().appendChild(this.label)
79
80     player.peertube().on('videoFileUpdate', () => this.update())
81   }
82
83   createItems () {
84     const menuItems = []
85     for (const videoFile of this.player_.peertube().videoFiles) {
86       menuItems.push(new ResolutionMenuItem(
87         this.player_,
88         {
89           id: videoFile.resolution,
90           label: videoFile.resolutionLabel,
91           src: videoFile.magnetUri,
92           selected: videoFile.resolution === this.currentSelection
93         })
94       )
95     }
96
97     return menuItems
98   }
99
100   update () {
101     if (!this.label) return
102
103     this.label.innerHTML = this.player_.peertube().getCurrentResolutionLabel()
104     this.hide()
105     return super.update()
106   }
107
108   buildCSSClass () {
109     return super.buildCSSClass() + ' vjs-resolution-button'
110   }
111
112   dispose () {
113     this.parentNode.removeChild(this)
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   dispose () {
137     this.parentNode.removeChild(this)
138   }
139 }
140 Button.registerComponent('PeerTubeLinkButton', PeertubeLinkButton)
141
142 class WebTorrentButton extends Button {
143   createEl () {
144     const div = document.createElement('div')
145     const subDiv = document.createElement('div')
146     div.appendChild(subDiv)
147
148     const downloadIcon = document.createElement('span')
149     downloadIcon.classList.add('icon', 'icon-download')
150     subDiv.appendChild(downloadIcon)
151
152     const downloadSpeedText = document.createElement('span')
153     downloadSpeedText.classList.add('download-speed-text')
154     const downloadSpeedNumber = document.createElement('span')
155     downloadSpeedNumber.classList.add('download-speed-number')
156     const downloadSpeedUnit = document.createElement('span')
157     downloadSpeedText.appendChild(downloadSpeedNumber)
158     downloadSpeedText.appendChild(downloadSpeedUnit)
159     subDiv.appendChild(downloadSpeedText)
160
161     const uploadIcon = document.createElement('span')
162     uploadIcon.classList.add('icon', 'icon-upload')
163     subDiv.appendChild(uploadIcon)
164
165     const uploadSpeedText = document.createElement('span')
166     uploadSpeedText.classList.add('upload-speed-text')
167     const uploadSpeedNumber = document.createElement('span')
168     uploadSpeedNumber.classList.add('upload-speed-number')
169     const uploadSpeedUnit = document.createElement('span')
170     uploadSpeedText.appendChild(uploadSpeedNumber)
171     uploadSpeedText.appendChild(uploadSpeedUnit)
172     subDiv.appendChild(uploadSpeedText)
173
174     const peersText = document.createElement('span')
175     peersText.textContent = ' peers'
176     peersText.classList.add('peers-text')
177     const peersNumber = document.createElement('span')
178     peersNumber.classList.add('peers-number')
179     subDiv.appendChild(peersNumber)
180     subDiv.appendChild(peersText)
181
182     div.className = 'vjs-webtorrent'
183     // Hide the stats before we get the info
184     subDiv.className = 'vjs-webtorrent-hidden'
185
186     this.player_.peertube().on('torrentInfo', (event, data) => {
187       const downloadSpeed = bytes(data.downloadSpeed)
188       const uploadSpeed = bytes(data.uploadSpeed)
189       const numPeers = data.numPeers
190
191       downloadSpeedNumber.textContent = downloadSpeed[0]
192       downloadSpeedUnit.textContent = ' ' + downloadSpeed[1]
193
194       uploadSpeedNumber.textContent = uploadSpeed[0]
195       uploadSpeedUnit.textContent = ' ' + uploadSpeed[1]
196
197       peersNumber.textContent = numPeers
198
199       subDiv.className = 'vjs-webtorrent-displayed'
200     })
201
202     return div
203   }
204
205   dispose () {
206     this.parentNode.removeChild(this)
207   }
208 }
209 Button.registerComponent('WebTorrentButton', WebTorrentButton)
210
211 const Plugin: VideoJSComponentInterface = videojsUntyped.getPlugin('plugin')
212 class PeerTubePlugin extends Plugin {
213   private player: any
214   private currentVideoFile: VideoFile
215   private playerElement: HTMLVideoElement
216   private videoFiles: VideoFile[]
217   private torrent: WebTorrent.Torrent
218
219   constructor (player: VideoJSPlayer, options: PeertubePluginOptions) {
220     super(player, options)
221
222     this.videoFiles = options.videoFiles
223
224     // Hack to "simulate" src link in video.js >= 6
225     // Without this, we can't play the video after pausing it
226     // https://github.com/videojs/video.js/blob/master/src/js/player.js#L1633
227     this.player.src = function () {
228       return true
229     }
230
231     this.playerElement = options.playerElement
232
233     this.player.ready(() => {
234       this.initializePlayer(options)
235       this.runTorrentInfoScheduler()
236     })
237   }
238
239   dispose () {
240     // Don't need to destroy renderer, video player will be destroyed
241     this.flushVideoFile(this.currentVideoFile, false)
242   }
243
244   getCurrentResolution () {
245     return this.currentVideoFile ? this.currentVideoFile.resolution : -1
246   }
247
248   getCurrentResolutionLabel () {
249     return this.currentVideoFile ? this.currentVideoFile.resolutionLabel : ''
250   }
251
252   updateVideoFile (videoFile?: VideoFile, done?: () => void) {
253     if (done === undefined) {
254       done = () => { /* empty */ }
255     }
256
257     // Pick the first one
258     if (videoFile === undefined) {
259       videoFile = this.videoFiles[0]
260     }
261
262     // Don't add the same video file once again
263     if (this.currentVideoFile !== undefined && this.currentVideoFile.magnetUri === videoFile.magnetUri) {
264       return
265     }
266
267     const previousVideoFile = this.currentVideoFile
268     this.currentVideoFile = videoFile
269
270     console.log('Adding ' + videoFile.magnetUri + '.')
271     this.torrent = webtorrent.add(videoFile.magnetUri, torrent => {
272       console.log('Added ' + videoFile.magnetUri + '.')
273
274       this.flushVideoFile(previousVideoFile)
275
276       const options = { autoplay: true, controls: true }
277       renderVideo(torrent.files[0], this.playerElement, options,(err, renderer) => {
278         if (err) return this.handleError(err)
279
280         this.renderer = renderer
281         this.player.play().then(done)
282       })
283     })
284
285     this.torrent.on('error', err => this.handleError(err))
286     this.torrent.on('warning', (err: any) => {
287       // We don't support HTTP tracker but we don't care -> we use the web socket tracker
288       if (err.message.indexOf('Unsupported tracker protocol: http') !== -1) return
289       // Users don't care about issues with WebRTC, but developers do so log it in the console
290       if (err.message.indexOf('Ice connection failed') !== -1) {
291         console.error(err)
292         return
293       }
294
295       return this.handleError(err)
296     })
297
298     this.trigger('videoFileUpdate')
299   }
300
301   updateResolution (resolution) {
302     // Remember player state
303     const currentTime = this.player.currentTime()
304     const isPaused = this.player.paused()
305
306     // Hide bigPlayButton
307     if (!isPaused) {
308       this.player.bigPlayButton.hide()
309     }
310
311     const newVideoFile = this.videoFiles.find(f => f.resolution === resolution)
312     this.updateVideoFile(newVideoFile, () => {
313       this.player.currentTime(currentTime)
314       this.player.handleTechSeeked_()
315     })
316   }
317
318   flushVideoFile (videoFile: VideoFile, destroyRenderer = true) {
319     if (videoFile !== undefined && webtorrent.get(videoFile.magnetUri)) {
320       if (destroyRenderer === true) this.renderer.destroy()
321       webtorrent.remove(videoFile.magnetUri)
322       console.log('Removed ' + videoFile.magnetUri)
323     }
324   }
325
326   setVideoFiles (files: VideoFile[]) {
327     this.videoFiles = files
328
329     this.updateVideoFile(undefined, () => this.player.play())
330   }
331
332   private initializePlayer (options: PeertubePluginOptions) {
333     const controlBar = this.player.controlBar
334
335     const menuButton = new ResolutionMenuButton(this.player, options)
336     const fullscreenElement = controlBar.fullscreenToggle.el()
337     controlBar.resolutionSwitcher = controlBar.el().insertBefore(menuButton.el(), fullscreenElement)
338
339     if (options.peerTubeLink === true) {
340       const peerTubeLinkButton = new PeertubeLinkButton(this.player)
341       controlBar.peerTubeLink = controlBar.el().insertBefore(peerTubeLinkButton.el(), fullscreenElement)
342     }
343
344     const webTorrentButton = new WebTorrentButton(this.player)
345     controlBar.webTorrent = controlBar.el().insertBefore(webTorrentButton.el(), controlBar.progressControl.el())
346
347     if (this.player.options_.autoplay === true) {
348       this.updateVideoFile()
349     } else {
350       this.player.one('play', () => {
351         // On firefox, we need to wait to load the video before playing
352         if (navigator.userAgent.toLowerCase().indexOf('firefox') !== -1) {
353           this.player.pause()
354           this.updateVideoFile(undefined, () => this.player.play())
355           return
356         }
357
358         this.updateVideoFile(undefined)
359       })
360     }
361   }
362
363   private runTorrentInfoScheduler () {
364     setInterval(() => {
365       if (this.torrent !== undefined) {
366         this.trigger('torrentInfo', {
367           downloadSpeed: this.torrent.downloadSpeed,
368           numPeers: this.torrent.numPeers,
369           uploadSpeed: this.torrent.uploadSpeed
370         })
371       }
372     }, 1000)
373   }
374
375   private handleError (err: Error | string) {
376     return this.player.trigger('customError', { err })
377   }
378 }
379 videojsUntyped.registerPlugin('peertube', PeerTubePlugin)