Better typings
[oweals/peertube.git] / client / src / assets / player / peertube-player.ts
1 import { VideoFile } from '../../../../shared/models/videos'
2
3 import 'videojs-hotkeys'
4 import 'videojs-dock'
5 import 'videojs-contextmenu-ui'
6 import './peertube-link-button'
7 import './resolution-menu-button'
8 import './settings-menu-button'
9 import './webtorrent-info-button'
10 import './peertube-videojs-plugin'
11 import './peertube-load-progress-bar'
12 import './theater-button'
13 import { UserWatching, VideoJSCaption, videojsUntyped } from './peertube-videojs-typings'
14 import { buildVideoEmbed, buildVideoLink, copyToClipboard } from './utils'
15 import { getCompleteLocale, getShortLocale, is18nLocale, isDefaultLocale } from '../../../../shared/models/i18n/i18n'
16
17 // FIXME: something weird with our path definition in tsconfig and typings
18 // @ts-ignore
19 import { Player } from 'video.js'
20
21 // Change 'Playback Rate' to 'Speed' (smaller for our settings menu)
22 videojsUntyped.getComponent('PlaybackRateMenuButton').prototype.controlText_ = 'Speed'
23 // Change Captions to Subtitles/CC
24 videojsUntyped.getComponent('CaptionsButton').prototype.controlText_ = 'Subtitles/CC'
25 // We just want to display 'Off' instead of 'captions off', keep a space so the variable == true (hacky I know)
26 videojsUntyped.getComponent('CaptionsButton').prototype.label_ = ' '
27
28 function getVideojsOptions (options: {
29   autoplay: boolean,
30   playerElement: HTMLVideoElement,
31   videoViewUrl: string,
32   videoDuration: number,
33   videoFiles: VideoFile[],
34   enableHotkeys: boolean,
35   inactivityTimeout: number,
36   peertubeLink: boolean,
37   poster: string,
38   startTime: number | string
39   theaterMode: boolean,
40   videoCaptions: VideoJSCaption[],
41
42   language?: string,
43   controls?: boolean,
44   muted?: boolean,
45   loop?: boolean
46
47   userWatching?: UserWatching
48 }) {
49   const videojsOptions = {
50     // We don't use text track settings for now
51     textTrackSettings: false,
52     controls: options.controls !== undefined ? options.controls : true,
53     muted: options.controls !== undefined ? options.muted : false,
54     loop: options.loop !== undefined ? options.loop : false,
55     poster: options.poster,
56     autoplay: false,
57     inactivityTimeout: options.inactivityTimeout,
58     playbackRates: [ 0.5, 0.75, 1, 1.25, 1.5, 2 ],
59     plugins: {
60       peertube: {
61         autoplay: options.autoplay, // Use peertube plugin autoplay because we get the file by webtorrent
62         videoCaptions: options.videoCaptions,
63         videoFiles: options.videoFiles,
64         playerElement: options.playerElement,
65         videoViewUrl: options.videoViewUrl,
66         videoDuration: options.videoDuration,
67         startTime: options.startTime,
68         userWatching: options.userWatching
69       }
70     },
71     controlBar: {
72       children: getControlBarChildren(options)
73     }
74   }
75
76   if (options.enableHotkeys === true) {
77     Object.assign(videojsOptions.plugins, {
78       hotkeys: {
79         enableVolumeScroll: false,
80         enableModifiersForNumbers: false,
81
82         fullscreenKey: function (event: KeyboardEvent) {
83           // fullscreen with the f key or Ctrl+Enter
84           return event.key === 'f' || (event.ctrlKey && event.key === 'Enter')
85         },
86
87         seekStep: function (event: KeyboardEvent) {
88           // mimic VLC seek behavior, and default to 5 (original value is 5).
89           if (event.ctrlKey && event.altKey) {
90             return 5 * 60
91           } else if (event.ctrlKey) {
92             return 60
93           } else if (event.altKey) {
94             return 10
95           } else {
96             return 5
97           }
98         },
99
100         customKeys: {
101           increasePlaybackRateKey: {
102             key: function (event: KeyboardEvent) {
103               return event.key === '>'
104             },
105             handler: function (player: Player) {
106               player.playbackRate((player.playbackRate() + 0.1).toFixed(2))
107             }
108           },
109           decreasePlaybackRateKey: {
110             key: function (event: KeyboardEvent) {
111               return event.key === '<'
112             },
113             handler: function (player: Player) {
114               player.playbackRate((player.playbackRate() - 0.1).toFixed(2))
115             }
116           },
117           frameByFrame: {
118             key: function (event: KeyboardEvent) {
119               return event.key === '.'
120             },
121             handler: function (player: Player) {
122               player.pause()
123               // Calculate movement distance (assuming 30 fps)
124               const dist = 1 / 30
125               player.currentTime(player.currentTime() + dist)
126             }
127           }
128         }
129       }
130     })
131   }
132
133   if (options.language && !isDefaultLocale(options.language)) {
134     Object.assign(videojsOptions, { language: options.language })
135   }
136
137   return videojsOptions
138 }
139
140 function getControlBarChildren (options: {
141   peertubeLink: boolean
142   theaterMode: boolean,
143   videoCaptions: VideoJSCaption[]
144 }) {
145   const settingEntries = []
146
147   // Keep an order
148   settingEntries.push('playbackRateMenuButton')
149   if (options.videoCaptions.length !== 0) settingEntries.push('captionsButton')
150   settingEntries.push('resolutionMenuButton')
151
152   const children = {
153     'playToggle': {},
154     'currentTimeDisplay': {},
155     'timeDivider': {},
156     'durationDisplay': {},
157     'liveDisplay': {},
158
159     'flexibleWidthSpacer': {},
160     'progressControl': {
161       children: {
162         'seekBar': {
163           children: {
164             'peerTubeLoadProgressBar': {},
165             'mouseTimeDisplay': {},
166             'playProgressBar': {}
167           }
168         }
169       }
170     },
171
172     'webTorrentButton': {},
173
174     'muteToggle': {},
175     'volumeControl': {},
176
177     'settingsButton': {
178       setup: {
179         maxHeightOffset: 40
180       },
181       entries: settingEntries
182     }
183   }
184
185   if (options.peertubeLink === true) {
186     Object.assign(children, {
187       'peerTubeLinkButton': {}
188     })
189   }
190
191   if (options.theaterMode === true) {
192     Object.assign(children, {
193       'theaterButton': {}
194     })
195   }
196
197   Object.assign(children, {
198     'fullscreenToggle': {}
199   })
200
201   return children
202 }
203
204 function addContextMenu (player: any, videoEmbedUrl: string) {
205   player.contextmenuUI({
206     content: [
207       {
208         label: player.localize('Copy the video URL'),
209         listener: function () {
210           copyToClipboard(buildVideoLink())
211         }
212       },
213       {
214         label: player.localize('Copy the video URL at the current time'),
215         listener: function () {
216           const player = this
217           copyToClipboard(buildVideoLink(player.currentTime()))
218         }
219       },
220       {
221         label: player.localize('Copy embed code'),
222         listener: () => {
223           copyToClipboard(buildVideoEmbed(videoEmbedUrl))
224         }
225       },
226       {
227         label: player.localize('Copy magnet URI'),
228         listener: function () {
229           const player = this
230           copyToClipboard(player.peertube().getCurrentVideoFile().magnetUri)
231         }
232       }
233     ]
234   })
235 }
236
237 function loadLocaleInVideoJS (serverUrl: string, videojs: any, locale: string) {
238   const path = getLocalePath(serverUrl, locale)
239   // It is the default locale, nothing to translate
240   if (!path) return Promise.resolve(undefined)
241
242   let p: Promise<any>
243
244   if (loadLocaleInVideoJS.cache[path]) {
245     p = Promise.resolve(loadLocaleInVideoJS.cache[path])
246   } else {
247     p = fetch(path + '/player.json')
248       .then(res => res.json())
249       .then(json => {
250         loadLocaleInVideoJS.cache[path] = json
251         return json
252       })
253   }
254
255   const completeLocale = getCompleteLocale(locale)
256   return p.then(json => videojs.addLanguage(getShortLocale(completeLocale), json))
257 }
258 namespace loadLocaleInVideoJS {
259   export const cache: { [ path: string ]: any } = {}
260 }
261
262 function getServerTranslations (serverUrl: string, locale: string) {
263   const path = getLocalePath(serverUrl, locale)
264   // It is the default locale, nothing to translate
265   if (!path) return Promise.resolve(undefined)
266
267   return fetch(path + '/server.json')
268     .then(res => res.json())
269 }
270
271 // ############################################################################
272
273 export {
274   getServerTranslations,
275   loadLocaleInVideoJS,
276   getVideojsOptions,
277   addContextMenu
278 }
279
280 // ############################################################################
281
282 function getLocalePath (serverUrl: string, locale: string) {
283   const completeLocale = getCompleteLocale(locale)
284
285   if (!is18nLocale(completeLocale) || isDefaultLocale(completeLocale)) return undefined
286
287   return serverUrl + '/client/locales/' + completeLocale
288 }