Merge branch 'develop' into unused-imports
[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 { 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 // Change 'Playback Rate' to 'Speed' (smaller for our settings menu)
18 videojsUntyped.getComponent('PlaybackRateMenuButton').prototype.controlText_ = 'Speed'
19 // Change Captions to Subtitles/CC
20 videojsUntyped.getComponent('CaptionsButton').prototype.controlText_ = 'Subtitles/CC'
21 // We just want to display 'Off' instead of 'captions off', keep a space so the variable == true (hacky I know)
22 videojsUntyped.getComponent('CaptionsButton').prototype.label_ = ' '
23
24 function getVideojsOptions (options: {
25   autoplay: boolean,
26   playerElement: HTMLVideoElement,
27   videoViewUrl: string,
28   videoDuration: number,
29   videoFiles: VideoFile[],
30   enableHotkeys: boolean,
31   inactivityTimeout: number,
32   peertubeLink: boolean,
33   poster: string,
34   startTime: number | string
35   theaterMode: boolean,
36   videoCaptions: VideoJSCaption[],
37   language?: string,
38   controls?: boolean,
39   muted?: boolean,
40   loop?: boolean
41 }) {
42   const videojsOptions = {
43     // We don't use text track settings for now
44     textTrackSettings: false,
45     controls: options.controls !== undefined ? options.controls : true,
46     muted: options.controls !== undefined ? options.muted : false,
47     loop: options.loop !== undefined ? options.loop : false,
48     poster: options.poster,
49     autoplay: false,
50     inactivityTimeout: options.inactivityTimeout,
51     playbackRates: [ 0.5, 0.75, 1, 1.25, 1.5, 2 ],
52     plugins: {
53       peertube: {
54         autoplay: options.autoplay, // Use peertube plugin autoplay because we get the file by webtorrent
55         videoCaptions: options.videoCaptions,
56         videoFiles: options.videoFiles,
57         playerElement: options.playerElement,
58         videoViewUrl: options.videoViewUrl,
59         videoDuration: options.videoDuration,
60         startTime: options.startTime
61       }
62     },
63     controlBar: {
64       children: getControlBarChildren(options)
65     }
66   }
67
68   if (options.enableHotkeys === true) {
69     Object.assign(videojsOptions.plugins, {
70       hotkeys: {
71         enableVolumeScroll: false,
72         enableModifiersForNumbers: false,
73         customKeys: {
74           increasePlaybackRateKey: {
75             key: function (event) {
76               // use '>'
77               return event.which === 51
78             },
79             handler: function (player, options, event) {
80               player.playbackRate(player.playbackRate() + 0.1)
81             }
82           },
83           decreasePlaybackRateKey: {
84             key: function (event) {
85               // use '<'
86               return event.which === 50
87             },
88             handler: function (player, options, event) {
89               player.playbackRate(player.playbackRate() - 0.1)
90             }
91           }
92         }
93       }
94     })
95   }
96
97   if (options.language && !isDefaultLocale(options.language)) {
98     Object.assign(videojsOptions, { language: options.language })
99   }
100
101   return videojsOptions
102 }
103
104 function getControlBarChildren (options: {
105   peertubeLink: boolean
106   theaterMode: boolean,
107   videoCaptions: VideoJSCaption[]
108 }) {
109   const settingEntries = []
110
111   // Keep an order
112   settingEntries.push('playbackRateMenuButton')
113   if (options.videoCaptions.length !== 0) settingEntries.push('captionsButton')
114   settingEntries.push('resolutionMenuButton')
115
116   const children = {
117     'playToggle': {},
118     'currentTimeDisplay': {},
119     'timeDivider': {},
120     'durationDisplay': {},
121     'liveDisplay': {},
122
123     'flexibleWidthSpacer': {},
124     'progressControl': {
125       children: {
126         'seekBar': {
127           children: {
128             'peerTubeLoadProgressBar': {},
129             'mouseTimeDisplay': {},
130             'playProgressBar': {}
131           }
132         }
133       }
134     },
135
136     'webTorrentButton': {},
137
138     'muteToggle': {},
139     'volumeControl': {},
140
141     'settingsButton': {
142       setup: {
143         maxHeightOffset: 40
144       },
145       entries: settingEntries
146     }
147   }
148
149   if (options.peertubeLink === true) {
150     Object.assign(children, {
151       'peerTubeLinkButton': {}
152     })
153   }
154
155   if (options.theaterMode === true) {
156     Object.assign(children, {
157       'theaterButton': {}
158     })
159   }
160
161   Object.assign(children, {
162     'fullscreenToggle': {}
163   })
164
165   return children
166 }
167
168 function addContextMenu (player: any, videoEmbedUrl: string) {
169   player.contextmenuUI({
170     content: [
171       {
172         label: player.localize('Copy the video URL'),
173         listener: function () {
174           copyToClipboard(buildVideoLink())
175         }
176       },
177       {
178         label: player.localize('Copy the video URL at the current time'),
179         listener: function () {
180           const player = this
181           copyToClipboard(buildVideoLink(player.currentTime()))
182         }
183       },
184       {
185         label: player.localize('Copy embed code'),
186         listener: () => {
187           copyToClipboard(buildVideoEmbed(videoEmbedUrl))
188         }
189       },
190       {
191         label: player.localize('Copy magnet URI'),
192         listener: function () {
193           const player = this
194           copyToClipboard(player.peertube().getCurrentVideoFile().magnetUri)
195         }
196       }
197     ]
198   })
199 }
200
201 function loadLocaleInVideoJS (serverUrl: string, videojs: any, locale: string) {
202   const path = getLocalePath(serverUrl, locale)
203   // It is the default locale, nothing to translate
204   if (!path) return Promise.resolve(undefined)
205
206   let p: Promise<any>
207
208   if (loadLocaleInVideoJS.cache[path]) {
209     p = Promise.resolve(loadLocaleInVideoJS.cache[path])
210   } else {
211     p = fetch(path + '/player.json')
212       .then(res => res.json())
213       .then(json => {
214         loadLocaleInVideoJS.cache[path] = json
215         return json
216       })
217   }
218
219   const completeLocale = getCompleteLocale(locale)
220   return p.then(json => videojs.addLanguage(getShortLocale(completeLocale), json))
221 }
222 namespace loadLocaleInVideoJS {
223   export const cache: { [ path: string ]: any } = {}
224 }
225
226 function getServerTranslations (serverUrl: string, locale: string) {
227   const path = getLocalePath(serverUrl, locale)
228   // It is the default locale, nothing to translate
229   if (!path) return Promise.resolve(undefined)
230
231   return fetch(path + '/server.json')
232     .then(res => res.json())
233 }
234
235 // ############################################################################
236
237 export {
238   getServerTranslations,
239   loadLocaleInVideoJS,
240   getVideojsOptions,
241   addContextMenu
242 }
243
244 // ############################################################################
245
246 function getLocalePath (serverUrl: string, locale: string) {
247   const completeLocale = getCompleteLocale(locale)
248
249   if (!is18nLocale(completeLocale) || isDefaultLocale(completeLocale)) return undefined
250
251   return serverUrl + '/client/locales/' + completeLocale
252 }