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