Add ability to download a video from direct link or torrent file
[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 videojs, { Player } from 'video.js'
4 import * as WebTorrent from 'webtorrent'
5
6 import { renderVideo } from './video-renderer'
7 import { VideoFile } from '../../../../shared'
8
9 // videojs typings don't have some method we need
10 const videojsUntyped = videojs as any
11 const webtorrent = new WebTorrent({ dht: false })
12
13 const MenuItem = videojsUntyped.getComponent('MenuItem')
14 const ResolutionMenuItem = videojsUntyped.extend(MenuItem, {
15   constructor: function (player: Player, options) {
16     options.selectable = true
17     MenuItem.call(this, player, options)
18
19     const currentResolution = this.player_.getCurrentResolution()
20     this.selected(this.options_.id === currentResolution)
21   },
22
23   handleClick: function (event) {
24     MenuItem.prototype.handleClick.call(this, event)
25     this.player_.updateResolution(this.options_.id)
26   }
27 })
28 MenuItem.registerComponent('ResolutionMenuItem', ResolutionMenuItem)
29
30 const MenuButton = videojsUntyped.getComponent('MenuButton')
31 const ResolutionMenuButton = videojsUntyped.extend(MenuButton, {
32   constructor: function (player, options) {
33     this.label = document.createElement('span')
34     options.label = 'Quality'
35
36     MenuButton.call(this, player, options)
37     this.el().setAttribute('aria-label', 'Quality')
38     this.controlText('Quality')
39
40     videojsUntyped.dom.addClass(this.label, 'vjs-resolution-button-label')
41     this.el().appendChild(this.label)
42
43     player.on('videoFileUpdate', videojs.bind(this, this.update))
44   },
45
46   createItems: function () {
47     const menuItems = []
48     for (const videoFile of this.player_.videoFiles) {
49       menuItems.push(new ResolutionMenuItem(
50         this.player_,
51         {
52           id: videoFile.resolution,
53           label: videoFile.resolutionLabel,
54           src: videoFile.magnetUri,
55           selected: videoFile.resolution === this.currentSelection
56         })
57       )
58     }
59
60     return menuItems
61   },
62
63   update: function () {
64     this.label.innerHTML = this.player_.getCurrentResolutionLabel()
65     return MenuButton.prototype.update.call(this)
66   },
67
68   buildCSSClass: function () {
69     return MenuButton.prototype.buildCSSClass.call(this) + ' vjs-resolution-button'
70   }
71 })
72 MenuButton.registerComponent('ResolutionMenuButton', ResolutionMenuButton)
73
74 const Button = videojsUntyped.getComponent('Button')
75 const PeertubeLinkButton = videojsUntyped.extend(Button, {
76   constructor: function (player) {
77     Button.apply(this, arguments)
78     this.player = player
79   },
80
81   createEl: function () {
82     const link = document.createElement('a')
83     link.href = window.location.href.replace('embed', 'watch')
84     link.innerHTML = 'PeerTube'
85     link.title = 'Go to the video page'
86     link.className = 'vjs-peertube-link'
87     link.target = '_blank'
88
89     return link
90   },
91
92   handleClick: function () {
93     this.player.pause()
94   }
95 })
96 Button.registerComponent('PeerTubeLinkButton', PeertubeLinkButton)
97
98 type PeertubePluginOptions = {
99   videoFiles: VideoFile[]
100   playerElement: HTMLVideoElement
101   autoplay: boolean
102   peerTubeLink: boolean
103 }
104 const peertubePlugin = function (options: PeertubePluginOptions) {
105   const player = this
106   let currentVideoFile: VideoFile = undefined
107   const playerElement = options.playerElement
108   player.videoFiles = options.videoFiles
109
110   // Hack to "simulate" src link in video.js >= 6
111   // Without this, we can't play the video after pausing it
112   // https://github.com/videojs/video.js/blob/master/src/js/player.js#L1633
113   player.src = function () {
114     return true
115   }
116
117   player.getCurrentResolution = function () {
118     return currentVideoFile ? currentVideoFile.resolution : -1
119   }
120
121   player.getCurrentResolutionLabel = function () {
122     return currentVideoFile ? currentVideoFile.resolutionLabel : ''
123   }
124
125   player.updateVideoFile = function (videoFile: VideoFile, done: () => void) {
126     if (done === undefined) {
127       done = () => { /* empty */ }
128     }
129
130     // Pick the first one
131     if (videoFile === undefined) {
132       videoFile = player.videoFiles[0]
133     }
134
135     // Don't add the same video file once again
136     if (currentVideoFile !== undefined && currentVideoFile.magnetUri === videoFile.magnetUri) {
137       return
138     }
139
140     const previousVideoFile = currentVideoFile
141     currentVideoFile = videoFile
142
143     console.log('Adding ' + videoFile.magnetUri + '.')
144     player.torrent = webtorrent.add(videoFile.magnetUri, torrent => {
145       console.log('Added ' + videoFile.magnetUri + '.')
146
147       this.flushVideoFile(previousVideoFile)
148
149       const options = { autoplay: true, controls: true }
150       renderVideo(torrent.files[0], playerElement, options,(err, renderer) => {
151         if (err) return handleError(err)
152
153         this.renderer = renderer
154         player.play()
155
156         return done()
157       })
158     })
159
160     player.torrent.on('error', err => handleError(err))
161     player.torrent.on('warning', err => {
162       // We don't support HTTP tracker but we don't care -> we use the web socket tracker
163       if (err.message.indexOf('Unsupported tracker protocol: http://') !== -1) return
164
165       return handleError(err)
166     })
167
168     player.trigger('videoFileUpdate')
169
170     return player
171   }
172
173   player.updateResolution = function (resolution) {
174     // Remember player state
175     const currentTime = player.currentTime()
176     const isPaused = player.paused()
177
178     // Hide bigPlayButton
179     if (!isPaused && this.player_.options_.bigPlayButton) {
180       this.player_.bigPlayButton.hide()
181     }
182
183     const newVideoFile = player.videoFiles.find(f => f.resolution === resolution)
184     player.updateVideoFile(newVideoFile, () => {
185       player.currentTime(currentTime)
186       player.handleTechSeeked_()
187     })
188   }
189
190   player.flushVideoFile = function (videoFile: VideoFile, destroyRenderer = true) {
191     if (videoFile !== undefined && webtorrent.get(videoFile.magnetUri)) {
192       if (destroyRenderer === true) this.renderer.destroy()
193       webtorrent.remove(videoFile.magnetUri)
194     }
195   }
196
197   player.ready(function () {
198     const controlBar = player.controlBar
199
200     const menuButton = new ResolutionMenuButton(player, options)
201     const fullscreenElement = controlBar.fullscreenToggle.el()
202     controlBar.resolutionSwitcher = controlBar.el().insertBefore(menuButton.el(), fullscreenElement)
203     controlBar.resolutionSwitcher.dispose = function () {
204       this.parentNode.removeChild(this)
205     }
206
207     player.dispose = function () {
208       // Don't need to destroy renderer, video player will be destroyed
209       player.flushVideoFile(currentVideoFile, false)
210     }
211
212     if (options.peerTubeLink === true) {
213       const peerTubeLinkButton = new PeertubeLinkButton(player)
214       controlBar.peerTubeLink = controlBar.el().insertBefore(peerTubeLinkButton.el(), fullscreenElement)
215
216       controlBar.peerTubeLink.dispose = function () {
217         this.parentNode.removeChild(this)
218       }
219     }
220
221     if (options.autoplay === true) {
222       player.updateVideoFile()
223     } else {
224       player.one('play', () => {
225         // Pause, we wait the video to load before
226         player.pause()
227
228         player.updateVideoFile(undefined, () => player.play())
229       })
230     }
231
232     setInterval(() => {
233       if (player.torrent !== undefined) {
234         player.trigger('torrentInfo', {
235           downloadSpeed: player.torrent.downloadSpeed,
236           numPeers: player.torrent.numPeers,
237           uploadSpeed: player.torrent.uploadSpeed
238         })
239       }
240     }, 1000)
241   })
242
243   function handleError (err: Error|string) {
244     return player.trigger('customError', { err })
245   }
246 }
247
248 videojsUntyped.registerPlugin('peertube', peertubePlugin)