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