]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blob - client/src/standalone/videos/shared/player-manager-options.ts
Correctly terminate an ended live
[github/Chocobozzz/PeerTube.git] / client / src / standalone / videos / shared / player-manager-options.ts
1 import { peertubeTranslate } from '../../../../../shared/core-utils/i18n'
2 import {
3 HTMLServerConfig,
4 LiveVideo,
5 Video,
6 VideoCaption,
7 VideoDetails,
8 VideoPlaylistElement,
9 VideoState,
10 VideoStreamingPlaylistType
11 } from '../../../../../shared/models'
12 import { P2PMediaLoaderOptions, PeertubePlayerManagerOptions, PlayerMode, VideoJSCaption } from '../../../assets/player'
13 import {
14 getBoolOrDefault,
15 getParamString,
16 getParamToggle,
17 isP2PEnabled,
18 logger,
19 peertubeLocalStorage,
20 UserLocalStorageKeys,
21 videoRequiresAuth
22 } from '../../../root-helpers'
23 import { PeerTubePlugin } from './peertube-plugin'
24 import { PlayerHTML } from './player-html'
25 import { PlaylistTracker } from './playlist-tracker'
26 import { Translations } from './translations'
27 import { VideoFetcher } from './video-fetcher'
28
29 export class PlayerManagerOptions {
30 private autoplay: boolean
31
32 private controls: boolean
33 private controlBar: boolean
34
35 private muted: boolean
36 private loop: boolean
37 private subtitle: string
38 private enableApi = false
39 private startTime: number | string = 0
40 private stopTime: number | string
41
42 private title: boolean
43 private warningTitle: boolean
44 private peertubeLink: boolean
45 private p2pEnabled: boolean
46 private bigPlayBackgroundColor: string
47 private foregroundColor: string
48
49 private mode: PlayerMode
50 private scope = 'peertube'
51
52 constructor (
53 private readonly playerHTML: PlayerHTML,
54 private readonly videoFetcher: VideoFetcher,
55 private readonly peertubePlugin: PeerTubePlugin
56 ) {}
57
58 hasAPIEnabled () {
59 return this.enableApi
60 }
61
62 hasAutoplay () {
63 return this.autoplay
64 }
65
66 hasControls () {
67 return this.controls
68 }
69
70 hasTitle () {
71 return this.title
72 }
73
74 hasWarningTitle () {
75 return this.warningTitle
76 }
77
78 hasP2PEnabled () {
79 return !!this.p2pEnabled
80 }
81
82 hasBigPlayBackgroundColor () {
83 return !!this.bigPlayBackgroundColor
84 }
85
86 getBigPlayBackgroundColor () {
87 return this.bigPlayBackgroundColor
88 }
89
90 hasForegroundColor () {
91 return !!this.foregroundColor
92 }
93
94 getForegroundColor () {
95 return this.foregroundColor
96 }
97
98 getMode () {
99 return this.mode
100 }
101
102 getScope () {
103 return this.scope
104 }
105
106 // ---------------------------------------------------------------------------
107
108 loadParams (config: HTMLServerConfig, video: VideoDetails) {
109 try {
110 const params = new URL(window.location.toString()).searchParams
111
112 this.autoplay = getParamToggle(params, 'autoplay', false)
113 // Disable auto play on live videos that are not streamed
114 if (video.state.id === VideoState.LIVE_ENDED || video.state.id === VideoState.WAITING_FOR_LIVE) {
115 this.autoplay = false
116 }
117
118 this.controls = getParamToggle(params, 'controls', true)
119 this.controlBar = getParamToggle(params, 'controlBar', true)
120
121 this.muted = getParamToggle(params, 'muted', undefined)
122 this.loop = getParamToggle(params, 'loop', false)
123 this.title = getParamToggle(params, 'title', true)
124 this.enableApi = getParamToggle(params, 'api', this.enableApi)
125 this.warningTitle = getParamToggle(params, 'warningTitle', true)
126 this.peertubeLink = getParamToggle(params, 'peertubeLink', true)
127 this.p2pEnabled = getParamToggle(params, 'p2p', this.isP2PEnabled(config, video))
128
129 this.scope = getParamString(params, 'scope', this.scope)
130 this.subtitle = getParamString(params, 'subtitle')
131 this.startTime = getParamString(params, 'start')
132 this.stopTime = getParamString(params, 'stop')
133
134 this.bigPlayBackgroundColor = getParamString(params, 'bigPlayBackgroundColor')
135 this.foregroundColor = getParamString(params, 'foregroundColor')
136
137 const modeParam = getParamString(params, 'mode')
138
139 if (modeParam) {
140 if (modeParam === 'p2p-media-loader') this.mode = 'p2p-media-loader'
141 else this.mode = 'webtorrent'
142 } else {
143 if (Array.isArray(video.streamingPlaylists) && video.streamingPlaylists.length !== 0) this.mode = 'p2p-media-loader'
144 else this.mode = 'webtorrent'
145 }
146 } catch (err) {
147 logger.error('Cannot get params from URL.', err)
148 }
149 }
150
151 // ---------------------------------------------------------------------------
152
153 async getPlayerOptions (options: {
154 video: VideoDetails
155 captionsResponse: Response
156 live?: LiveVideo
157
158 authorizationHeader: () => string
159 videoFileToken: () => string
160
161 serverConfig: HTMLServerConfig
162
163 alreadyHadPlayer: boolean
164
165 translations: Translations
166
167 playlistTracker?: PlaylistTracker
168 playNextPlaylistVideo?: () => any
169 playPreviousPlaylistVideo?: () => any
170 onVideoUpdate?: (uuid: string) => any
171 }) {
172 const {
173 video,
174 captionsResponse,
175 alreadyHadPlayer,
176 videoFileToken,
177 translations,
178 playlistTracker,
179 live,
180 authorizationHeader,
181 serverConfig
182 } = options
183
184 const videoCaptions = await this.buildCaptions(captionsResponse, translations)
185
186 const playerOptions: PeertubePlayerManagerOptions = {
187 common: {
188 // Autoplay in playlist mode
189 autoplay: alreadyHadPlayer ? true : this.autoplay,
190
191 controls: this.controls,
192 controlBar: this.controlBar,
193
194 muted: this.muted,
195 loop: this.loop,
196
197 p2pEnabled: this.p2pEnabled,
198
199 captions: videoCaptions.length !== 0,
200 subtitle: this.subtitle,
201
202 startTime: playlistTracker
203 ? playlistTracker.getCurrentElement().startTimestamp
204 : this.startTime,
205 stopTime: playlistTracker
206 ? playlistTracker.getCurrentElement().stopTimestamp
207 : this.stopTime,
208
209 videoCaptions,
210 inactivityTimeout: 2500,
211 videoViewUrl: this.videoFetcher.getVideoViewsUrl(video.uuid),
212 metricsUrl: window.location.origin + '/api/v1/metrics/playback',
213
214 videoShortUUID: video.shortUUID,
215 videoUUID: video.uuid,
216
217 playerElement: this.playerHTML.getPlayerElement(),
218 onPlayerElementChange: (element: HTMLVideoElement) => {
219 this.playerHTML.setPlayerElement(element)
220 },
221
222 videoDuration: video.duration,
223 enableHotkeys: true,
224
225 peertubeLink: this.peertubeLink,
226 instanceName: serverConfig.instance.name,
227
228 poster: window.location.origin + video.previewPath,
229 theaterButton: false,
230
231 serverUrl: window.location.origin,
232 language: navigator.language,
233 embedUrl: window.location.origin + video.embedPath,
234 embedTitle: video.name,
235
236 requiresAuth: videoRequiresAuth(video),
237 authorizationHeader,
238 videoFileToken,
239
240 errorNotifier: () => {
241 // Empty, we don't have a notifier in the embed
242 },
243
244 ...this.buildLiveOptions(video, live),
245
246 ...this.buildPlaylistOptions(options)
247 },
248
249 webtorrent: {
250 videoFiles: video.files
251 },
252
253 ...this.buildP2PMediaLoaderOptions(video),
254
255 pluginsManager: this.peertubePlugin.getPluginsManager()
256 }
257
258 return playerOptions
259 }
260
261 private buildLiveOptions (video: VideoDetails, live: LiveVideo) {
262 if (!video.isLive) return { isLive: false }
263
264 return {
265 isLive: true,
266 liveOptions: {
267 latencyMode: live.latencyMode
268 }
269 }
270 }
271
272 private buildPlaylistOptions (options: {
273 playlistTracker?: PlaylistTracker
274 playNextPlaylistVideo?: () => any
275 playPreviousPlaylistVideo?: () => any
276 onVideoUpdate?: (uuid: string) => any
277 }) {
278 const { playlistTracker, playNextPlaylistVideo, playPreviousPlaylistVideo, onVideoUpdate } = options
279
280 if (!playlistTracker) return {}
281
282 return {
283 playlist: {
284 elements: playlistTracker.getPlaylistElements(),
285 playlist: playlistTracker.getPlaylist(),
286
287 getCurrentPosition: () => playlistTracker.getCurrentPosition(),
288
289 onItemClicked: (videoPlaylistElement: VideoPlaylistElement) => {
290 playlistTracker.setCurrentElement(videoPlaylistElement)
291
292 onVideoUpdate(videoPlaylistElement.video.uuid)
293 }
294 },
295
296 nextVideo: () => playNextPlaylistVideo(),
297 hasNextVideo: () => playlistTracker.hasNextPlaylistElement(),
298
299 previousVideo: () => playPreviousPlaylistVideo(),
300 hasPreviousVideo: () => playlistTracker.hasPreviousPlaylistElement()
301 }
302 }
303
304 private buildP2PMediaLoaderOptions (video: VideoDetails) {
305 if (this.mode !== 'p2p-media-loader') return {}
306
307 const hlsPlaylist = video.streamingPlaylists.find(p => p.type === VideoStreamingPlaylistType.HLS)
308
309 return {
310 p2pMediaLoader: {
311 playlistUrl: hlsPlaylist.playlistUrl,
312 segmentsSha256Url: hlsPlaylist.segmentsSha256Url,
313 redundancyBaseUrls: hlsPlaylist.redundancies.map(r => r.baseUrl),
314 trackerAnnounce: video.trackerUrls,
315 videoFiles: hlsPlaylist.files
316 } as P2PMediaLoaderOptions
317 }
318 }
319
320 // ---------------------------------------------------------------------------
321
322 private async buildCaptions (captionsResponse: Response, translations: Translations): Promise<VideoJSCaption[]> {
323 if (captionsResponse.ok) {
324 const { data } = await captionsResponse.json()
325
326 return data.map((c: VideoCaption) => ({
327 label: peertubeTranslate(c.language.label, translations),
328 language: c.language.id,
329 src: window.location.origin + c.captionPath
330 }))
331 }
332
333 return []
334 }
335
336 // ---------------------------------------------------------------------------
337
338 private isP2PEnabled (config: HTMLServerConfig, video: Video) {
339 const userP2PEnabled = getBoolOrDefault(
340 peertubeLocalStorage.getItem(UserLocalStorageKeys.P2P_ENABLED),
341 config.defaults.p2p.embed.enabled
342 )
343
344 return isP2PEnabled(video, config, userP2PEnabled)
345 }
346 }