Move adding a video view videojs peertube 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 { VideoService } from '@app/shared/video/video.service'
4 import * as videojs from 'video.js'
5 import * as WebTorrent from 'webtorrent'
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   peerTubeLink: boolean
27   videoViewUrl: string
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 currentResolution = this.player_.peertube().getCurrentResolution()
57     this.selected(this.options_.id === currentResolution)
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,
94           label: videoFile.resolutionLabel,
95           src: videoFile.magnetUri,
96           selected: videoFile.resolution === this.currentSelection
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   dispose () {
117     this.parentNode.removeChild(this)
118   }
119 }
120 MenuButton.registerComponent('ResolutionMenuButton', ResolutionMenuButton)
121
122 const Button: VideoJSComponentInterface = videojsUntyped.getComponent('Button')
123 class PeertubeLinkButton extends Button {
124
125   createEl () {
126     const link = document.createElement('a')
127     link.href = window.location.href.replace('embed', 'watch')
128     link.innerHTML = 'PeerTube'
129     link.title = 'Go to the video page'
130     link.className = 'vjs-peertube-link'
131     link.target = '_blank'
132
133     return link
134   }
135
136   handleClick () {
137     this.player_.pause()
138   }
139
140   dispose () {
141     this.parentNode.removeChild(this)
142   }
143 }
144 Button.registerComponent('PeerTubeLinkButton', PeertubeLinkButton)
145
146 class WebTorrentButton extends Button {
147   createEl () {
148     const div = document.createElement('div')
149     const subDiv = document.createElement('div')
150     div.appendChild(subDiv)
151
152     const downloadIcon = document.createElement('span')
153     downloadIcon.classList.add('icon', 'icon-download')
154     subDiv.appendChild(downloadIcon)
155
156     const downloadSpeedText = document.createElement('span')
157     downloadSpeedText.classList.add('download-speed-text')
158     const downloadSpeedNumber = document.createElement('span')
159     downloadSpeedNumber.classList.add('download-speed-number')
160     const downloadSpeedUnit = document.createElement('span')
161     downloadSpeedText.appendChild(downloadSpeedNumber)
162     downloadSpeedText.appendChild(downloadSpeedUnit)
163     subDiv.appendChild(downloadSpeedText)
164
165     const uploadIcon = document.createElement('span')
166     uploadIcon.classList.add('icon', 'icon-upload')
167     subDiv.appendChild(uploadIcon)
168
169     const uploadSpeedText = document.createElement('span')
170     uploadSpeedText.classList.add('upload-speed-text')
171     const uploadSpeedNumber = document.createElement('span')
172     uploadSpeedNumber.classList.add('upload-speed-number')
173     const uploadSpeedUnit = document.createElement('span')
174     uploadSpeedText.appendChild(uploadSpeedNumber)
175     uploadSpeedText.appendChild(uploadSpeedUnit)
176     subDiv.appendChild(uploadSpeedText)
177
178     const peersText = document.createElement('span')
179     peersText.textContent = ' peers'
180     peersText.classList.add('peers-text')
181     const peersNumber = document.createElement('span')
182     peersNumber.classList.add('peers-number')
183     subDiv.appendChild(peersNumber)
184     subDiv.appendChild(peersText)
185
186     div.className = 'vjs-webtorrent'
187     // Hide the stats before we get the info
188     subDiv.className = 'vjs-webtorrent-hidden'
189
190     this.player_.peertube().on('torrentInfo', (event, data) => {
191       const downloadSpeed = bytes(data.downloadSpeed)
192       const uploadSpeed = bytes(data.uploadSpeed)
193       const numPeers = data.numPeers
194
195       downloadSpeedNumber.textContent = downloadSpeed[0]
196       downloadSpeedUnit.textContent = ' ' + downloadSpeed[1]
197
198       uploadSpeedNumber.textContent = uploadSpeed[0]
199       uploadSpeedUnit.textContent = ' ' + uploadSpeed[1]
200
201       peersNumber.textContent = numPeers
202
203       subDiv.className = 'vjs-webtorrent-displayed'
204     })
205
206     return div
207   }
208
209   dispose () {
210     this.parentNode.removeChild(this)
211   }
212 }
213 Button.registerComponent('WebTorrentButton', WebTorrentButton)
214
215 const Plugin: VideoJSComponentInterface = videojsUntyped.getPlugin('plugin')
216 class PeerTubePlugin extends Plugin {
217   private player: any
218   private currentVideoFile: VideoFile
219   private playerElement: HTMLVideoElement
220   private videoFiles: VideoFile[]
221   private torrent: WebTorrent.Torrent
222   private autoplay = false
223   private videoViewUrl: string
224   private videoViewInterval
225
226   constructor (player: videojs.Player, options: PeertubePluginOptions) {
227     super(player, options)
228
229     // Fix canplay event on google chrome by disabling default videojs autoplay
230     this.autoplay = this.player.options_.autoplay
231     this.player.options_.autoplay = false
232
233     this.videoFiles = options.videoFiles
234     this.videoViewUrl = options.videoViewUrl
235
236     // Hack to "simulate" src link in video.js >= 6
237     // Without this, we can't play the video after pausing it
238     // https://github.com/videojs/video.js/blob/master/src/js/player.js#L1633
239     this.player.src = function () {
240       return true
241     }
242
243     this.playerElement = options.playerElement
244
245     this.player.ready(() => {
246       this.initializePlayer(options)
247       this.runTorrentInfoScheduler()
248       this.prepareRunViewAdd()
249     })
250   }
251
252   dispose () {
253     // Don't need to destroy renderer, video player will be destroyed
254     this.flushVideoFile(this.currentVideoFile, false)
255   }
256
257   getCurrentResolution () {
258     return this.currentVideoFile ? this.currentVideoFile.resolution : -1
259   }
260
261   getCurrentResolutionLabel () {
262     return this.currentVideoFile ? this.currentVideoFile.resolutionLabel : ''
263   }
264
265   updateVideoFile (videoFile?: VideoFile, done?: () => void) {
266     if (done === undefined) {
267       done = () => { /* empty */ }
268     }
269
270     // Pick the first one
271     if (videoFile === undefined) {
272       videoFile = this.videoFiles[0]
273     }
274
275     // Don't add the same video file once again
276     if (this.currentVideoFile !== undefined && this.currentVideoFile.magnetUri === videoFile.magnetUri) {
277       return
278     }
279
280     const previousVideoFile = this.currentVideoFile
281     this.currentVideoFile = videoFile
282
283     console.log('Adding ' + videoFile.magnetUri + '.')
284     this.torrent = webtorrent.add(videoFile.magnetUri, torrent => {
285       console.log('Added ' + videoFile.magnetUri + '.')
286
287       this.flushVideoFile(previousVideoFile)
288
289       const options = { autoplay: true, controls: true }
290       renderVideo(torrent.files[0], this.playerElement, options,(err, renderer) => {
291         if (err) return this.handleError(err)
292
293         this.renderer = renderer
294         if (!this.player.paused()) this.player.play().then(done)
295         else done()
296       })
297     })
298
299     this.torrent.on('error', err => this.handleError(err))
300     this.torrent.on('warning', (err: any) => {
301       // We don't support HTTP tracker but we don't care -> we use the web socket tracker
302       if (err.message.indexOf('Unsupported tracker protocol') !== -1) return
303       // Users don't care about issues with WebRTC, but developers do so log it in the console
304       if (err.message.indexOf('Ice connection failed') !== -1) {
305         console.error(err)
306         return
307       }
308
309       return this.handleError(err)
310     })
311
312     this.trigger('videoFileUpdate')
313   }
314
315   updateResolution (resolution) {
316     // Remember player state
317     const currentTime = this.player.currentTime()
318     const isPaused = this.player.paused()
319
320     // Remove poster to have black background
321     this.playerElement.poster = ''
322
323     // Hide bigPlayButton
324     if (!isPaused) {
325       this.player.bigPlayButton.hide()
326     }
327
328     const newVideoFile = this.videoFiles.find(f => f.resolution === resolution)
329     this.updateVideoFile(newVideoFile, () => {
330       this.player.currentTime(currentTime)
331       this.player.handleTechSeeked_()
332     })
333   }
334
335   flushVideoFile (videoFile: VideoFile, destroyRenderer = true) {
336     if (videoFile !== undefined && webtorrent.get(videoFile.magnetUri)) {
337       if (destroyRenderer === true) this.renderer.destroy()
338       webtorrent.remove(videoFile.magnetUri)
339       console.log('Removed ' + videoFile.magnetUri)
340     }
341   }
342
343   setVideoFiles (files: VideoFile[], videoViewUrl: string) {
344     this.videoViewUrl = videoViewUrl
345     this.videoFiles = files
346
347     // Re run view add for the new video
348     this.prepareRunViewAdd()
349     this.updateVideoFile(undefined, () => this.player.play())
350   }
351
352   private initializePlayer (options: PeertubePluginOptions) {
353     const controlBar = this.player.controlBar
354
355     const menuButton = new ResolutionMenuButton(this.player, options)
356     const fullscreenElement = controlBar.fullscreenToggle.el()
357     controlBar.resolutionSwitcher = controlBar.el().insertBefore(menuButton.el(), fullscreenElement)
358
359     if (options.peerTubeLink === true) {
360       const peerTubeLinkButton = new PeertubeLinkButton(this.player)
361       controlBar.peerTubeLink = controlBar.el().insertBefore(peerTubeLinkButton.el(), fullscreenElement)
362     }
363
364     const webTorrentButton = new WebTorrentButton(this.player)
365     controlBar.webTorrent = controlBar.el().insertBefore(webTorrentButton.el(), controlBar.progressControl.el())
366
367     if (this.autoplay === true) {
368       this.updateVideoFile(undefined, () => this.player.play())
369     } else {
370       this.player.one('play', () => {
371         this.player.pause()
372         this.updateVideoFile(undefined, () => this.player.play())
373       })
374     }
375   }
376
377   private runTorrentInfoScheduler () {
378     setInterval(() => {
379       if (this.torrent !== undefined) {
380         this.trigger('torrentInfo', {
381           downloadSpeed: this.torrent.downloadSpeed,
382           numPeers: this.torrent.numPeers,
383           uploadSpeed: this.torrent.uploadSpeed
384         })
385       }
386     }, 1000)
387   }
388
389   private prepareRunViewAdd () {
390     if (this.player.readyState() < 1) {
391       return this.player.one('loadedmetadata', () => this.runViewAdd())
392     }
393
394     this.runViewAdd()
395   }
396
397   private runViewAdd () {
398     this.clearVideoViewInterval()
399
400     // After 30 seconds (or 3/4 of the video), add a view to the video
401     let minSecondsToView = 30
402
403     const duration = this.player.duration()
404     if (duration < minSecondsToView) minSecondsToView = (duration * 3) / 4
405
406     let secondsViewed = 0
407     this.videoViewInterval = setInterval(() => {
408       if (this.player && !this.player.paused()) {
409         secondsViewed += 1
410
411         if (secondsViewed > minSecondsToView) {
412           this.clearVideoViewInterval()
413
414           this.addViewToVideo().catch(err => console.error(err))
415         }
416       }
417     }, 1000)
418   }
419
420   private clearVideoViewInterval () {
421     if (this.videoViewInterval !== undefined) {
422       clearInterval(this.videoViewInterval)
423       this.videoViewInterval = undefined
424     }
425   }
426
427   private addViewToVideo () {
428     return fetch(this.videoViewUrl, { method: 'POST' })
429   }
430
431   private handleError (err: Error | string) {
432     return this.player.trigger('customError', { err })
433   }
434 }
435 videojsUntyped.registerPlugin('peertube', PeerTubePlugin)