Correctly implement p2p-media-loader
[oweals/peertube.git] / client / src / assets / player / peertube-player-manager.ts
1 import { VideoFile } from '../../../../shared/models/videos'
2 // @ts-ignore
3 import * as videojs from 'video.js'
4 import 'videojs-hotkeys'
5 import 'videojs-dock'
6 import 'videojs-contextmenu-ui'
7 import 'videojs-contrib-quality-levels'
8 import './peertube-plugin'
9 import './videojs-components/peertube-link-button'
10 import './videojs-components/resolution-menu-button'
11 import './videojs-components/settings-menu-button'
12 import './videojs-components/p2p-info-button'
13 import './videojs-components/peertube-load-progress-bar'
14 import './videojs-components/theater-button'
15 import { P2PMediaLoaderPluginOptions, UserWatching, VideoJSCaption, VideoJSPluginOptions, videojsUntyped } from './peertube-videojs-typings'
16 import { buildVideoEmbed, buildVideoLink, copyToClipboard } from './utils'
17 import { getCompleteLocale, getShortLocale, is18nLocale, isDefaultLocale } from '../../../../shared/models/i18n/i18n'
18 import { Engine } from 'p2p-media-loader-hlsjs'
19
20 // Change 'Playback Rate' to 'Speed' (smaller for our settings menu)
21 videojsUntyped.getComponent('PlaybackRateMenuButton').prototype.controlText_ = 'Speed'
22 // Change Captions to Subtitles/CC
23 videojsUntyped.getComponent('CaptionsButton').prototype.controlText_ = 'Subtitles/CC'
24 // We just want to display 'Off' instead of 'captions off', keep a space so the variable == true (hacky I know)
25 videojsUntyped.getComponent('CaptionsButton').prototype.label_ = ' '
26
27 export type PlayerMode = 'webtorrent' | 'p2p-media-loader'
28
29 export type WebtorrentOptions = {
30   videoFiles: VideoFile[]
31 }
32
33 export type P2PMediaLoaderOptions = {
34   playlistUrl: string
35 }
36
37 export type CommonOptions = {
38   playerElement: HTMLVideoElement
39
40   autoplay: boolean
41   videoDuration: number
42   enableHotkeys: boolean
43   inactivityTimeout: number
44   poster: string
45   startTime: number | string
46
47   theaterMode: boolean
48   captions: boolean
49   peertubeLink: boolean
50
51   videoViewUrl: string
52   embedUrl: string
53
54   language?: string
55   controls?: boolean
56   muted?: boolean
57   loop?: boolean
58   subtitle?: string
59
60   videoCaptions: VideoJSCaption[]
61
62   userWatching?: UserWatching
63
64   serverUrl: string
65 }
66
67 export type PeertubePlayerManagerOptions = {
68   common: CommonOptions,
69   webtorrent?: WebtorrentOptions,
70   p2pMediaLoader?: P2PMediaLoaderOptions
71 }
72
73 export class PeertubePlayerManager {
74
75   private static videojsLocaleCache: { [ path: string ]: any } = {}
76
77   static getServerTranslations (serverUrl: string, locale: string) {
78     const path = PeertubePlayerManager.getLocalePath(serverUrl, locale)
79     // It is the default locale, nothing to translate
80     if (!path) return Promise.resolve(undefined)
81
82     return fetch(path + '/server.json')
83       .then(res => res.json())
84       .catch(err => {
85         console.error('Cannot get server translations', err)
86         return undefined
87       })
88   }
89
90   static async initialize (mode: PlayerMode, options: PeertubePlayerManagerOptions) {
91     if (mode === 'webtorrent') await import('./webtorrent-plugin')
92     if (mode === 'p2p-media-loader') await import('./p2p-media-loader-plugin')
93
94     const videojsOptions = this.getVideojsOptions(mode, options)
95
96     await this.loadLocaleInVideoJS(options.common.serverUrl, options.common.language)
97
98     const self = this
99     return new Promise(res => {
100       videojs(options.common.playerElement, videojsOptions, function (this: any) {
101         const player = this
102
103         self.addContextMenu(mode, player, options.common.embedUrl)
104
105         return res(player)
106       })
107     })
108   }
109
110   private static loadLocaleInVideoJS (serverUrl: string, locale: string) {
111     const path = PeertubePlayerManager.getLocalePath(serverUrl, locale)
112     // It is the default locale, nothing to translate
113     if (!path) return Promise.resolve(undefined)
114
115     let p: Promise<any>
116
117     if (PeertubePlayerManager.videojsLocaleCache[path]) {
118       p = Promise.resolve(PeertubePlayerManager.videojsLocaleCache[path])
119     } else {
120       p = fetch(path + '/player.json')
121         .then(res => res.json())
122         .then(json => {
123           PeertubePlayerManager.videojsLocaleCache[path] = json
124           return json
125         })
126         .catch(err => {
127           console.error('Cannot get player translations', err)
128           return undefined
129         })
130     }
131
132     const completeLocale = getCompleteLocale(locale)
133     return p.then(json => videojs.addLanguage(getShortLocale(completeLocale), json))
134   }
135
136   private static getVideojsOptions (mode: PlayerMode, options: PeertubePlayerManagerOptions) {
137     const commonOptions = options.common
138     const webtorrentOptions = options.webtorrent
139     const p2pMediaLoaderOptions = options.p2pMediaLoader
140     let html5 = {}
141
142     const plugins: VideoJSPluginOptions = {
143       peertube: {
144         autoplay: commonOptions.autoplay, // Use peertube plugin autoplay because we get the file by webtorrent
145         videoViewUrl: commonOptions.videoViewUrl,
146         videoDuration: commonOptions.videoDuration,
147         startTime: commonOptions.startTime,
148         userWatching: commonOptions.userWatching,
149         subtitle: commonOptions.subtitle,
150         videoCaptions: commonOptions.videoCaptions
151       }
152     }
153
154     if (p2pMediaLoaderOptions) {
155       const p2pMediaLoader: P2PMediaLoaderPluginOptions = {
156         type: 'application/x-mpegURL',
157         src: p2pMediaLoaderOptions.playlistUrl
158       }
159
160       const config = {
161         segments: {
162           swarmId: 'swarm' // TODO: choose swarm id
163         }
164       }
165       const streamrootHls = {
166         html5: {
167           hlsjsConfig: {
168             liveSyncDurationCount: 7,
169             loader: new Engine(config).createLoaderClass()
170           }
171         }
172       }
173
174       Object.assign(plugins, { p2pMediaLoader, streamrootHls })
175       html5 = streamrootHls.html5
176     }
177
178     if (webtorrentOptions) {
179       const webtorrent = {
180         autoplay: commonOptions.autoplay,
181         videoDuration: commonOptions.videoDuration,
182         playerElement: commonOptions.playerElement,
183         videoFiles: webtorrentOptions.videoFiles
184       }
185       Object.assign(plugins, { webtorrent })
186     }
187
188     const videojsOptions = {
189       html5,
190
191       // We don't use text track settings for now
192       textTrackSettings: false,
193       controls: commonOptions.controls !== undefined ? commonOptions.controls : true,
194       loop: commonOptions.loop !== undefined ? commonOptions.loop : false,
195
196       muted: commonOptions.muted !== undefined
197         ? commonOptions.muted
198         : undefined, // Undefined so the player knows it has to check the local storage
199
200       poster: commonOptions.poster,
201       autoplay: false,
202       inactivityTimeout: commonOptions.inactivityTimeout,
203       playbackRates: [ 0.5, 0.75, 1, 1.25, 1.5, 2 ],
204       plugins,
205       controlBar: {
206         children: this.getControlBarChildren(mode, {
207           captions: commonOptions.captions,
208           peertubeLink: commonOptions.peertubeLink,
209           theaterMode: commonOptions.theaterMode
210         })
211       }
212     }
213
214     if (commonOptions.enableHotkeys === true) {
215       Object.assign(videojsOptions.plugins, {
216         hotkeys: {
217           enableVolumeScroll: false,
218           enableModifiersForNumbers: false,
219
220           fullscreenKey: function (event: KeyboardEvent) {
221             // fullscreen with the f key or Ctrl+Enter
222             return event.key === 'f' || (event.ctrlKey && event.key === 'Enter')
223           },
224
225           seekStep: function (event: KeyboardEvent) {
226             // mimic VLC seek behavior, and default to 5 (original value is 5).
227             if (event.ctrlKey && event.altKey) {
228               return 5 * 60
229             } else if (event.ctrlKey) {
230               return 60
231             } else if (event.altKey) {
232               return 10
233             } else {
234               return 5
235             }
236           },
237
238           customKeys: {
239             increasePlaybackRateKey: {
240               key: function (event: KeyboardEvent) {
241                 return event.key === '>'
242               },
243               handler: function (player: videojs.Player) {
244                 player.playbackRate((player.playbackRate() + 0.1).toFixed(2))
245               }
246             },
247             decreasePlaybackRateKey: {
248               key: function (event: KeyboardEvent) {
249                 return event.key === '<'
250               },
251               handler: function (player: videojs.Player) {
252                 player.playbackRate((player.playbackRate() - 0.1).toFixed(2))
253               }
254             },
255             frameByFrame: {
256               key: function (event: KeyboardEvent) {
257                 return event.key === '.'
258               },
259               handler: function (player: videojs.Player) {
260                 player.pause()
261                 // Calculate movement distance (assuming 30 fps)
262                 const dist = 1 / 30
263                 player.currentTime(player.currentTime() + dist)
264               }
265             }
266           }
267         }
268       })
269     }
270
271     if (commonOptions.language && !isDefaultLocale(commonOptions.language)) {
272       Object.assign(videojsOptions, { language: commonOptions.language })
273     }
274
275     return videojsOptions
276   }
277
278   private static getControlBarChildren (mode: PlayerMode, options: {
279     peertubeLink: boolean
280     theaterMode: boolean,
281     captions: boolean
282   }) {
283     const settingEntries = []
284     const loadProgressBar = mode === 'webtorrent' ? 'peerTubeLoadProgressBar' : 'loadProgressBar'
285
286     // Keep an order
287     settingEntries.push('playbackRateMenuButton')
288     if (options.captions === true) settingEntries.push('captionsButton')
289     settingEntries.push('resolutionMenuButton')
290
291     const children = {
292       'playToggle': {},
293       'currentTimeDisplay': {},
294       'timeDivider': {},
295       'durationDisplay': {},
296       'liveDisplay': {},
297
298       'flexibleWidthSpacer': {},
299       'progressControl': {
300         children: {
301           'seekBar': {
302             children: {
303               [loadProgressBar]: {},
304               'mouseTimeDisplay': {},
305               'playProgressBar': {}
306             }
307           }
308         }
309       },
310
311       'p2PInfoButton': {},
312
313       'muteToggle': {},
314       'volumeControl': {},
315
316       'settingsButton': {
317         setup: {
318           maxHeightOffset: 40
319         },
320         entries: settingEntries
321       }
322     }
323
324     if (options.peertubeLink === true) {
325       Object.assign(children, {
326         'peerTubeLinkButton': {}
327       })
328     }
329
330     if (options.theaterMode === true) {
331       Object.assign(children, {
332         'theaterButton': {}
333       })
334     }
335
336     Object.assign(children, {
337       'fullscreenToggle': {}
338     })
339
340     return children
341   }
342
343   private static addContextMenu (mode: PlayerMode, player: any, videoEmbedUrl: string) {
344     const content = [
345       {
346         label: player.localize('Copy the video URL'),
347         listener: function () {
348           copyToClipboard(buildVideoLink())
349         }
350       },
351       {
352         label: player.localize('Copy the video URL at the current time'),
353         listener: function () {
354           const player = this as videojs.Player
355           copyToClipboard(buildVideoLink(player.currentTime()))
356         }
357       },
358       {
359         label: player.localize('Copy embed code'),
360         listener: () => {
361           copyToClipboard(buildVideoEmbed(videoEmbedUrl))
362         }
363       }
364     ]
365
366     if (mode === 'webtorrent') {
367       content.push({
368         label: player.localize('Copy magnet URI'),
369         listener: function () {
370           const player = this as videojs.Player
371           copyToClipboard(player.webtorrent().getCurrentVideoFile().magnetUri)
372         }
373       })
374     }
375
376     player.contextmenuUI({ content })
377   }
378
379   private static getLocalePath (serverUrl: string, locale: string) {
380     const completeLocale = getCompleteLocale(locale)
381
382     if (!is18nLocale(completeLocale) || isDefaultLocale(completeLocale)) return undefined
383
384     return serverUrl + '/client/locales/' + completeLocale
385   }
386 }
387
388 // ############################################################################
389
390 export {
391   videojs
392 }