]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blob - client/src/standalone/videos/embed.ts
Merge branch 'release/5.0.0' into develop
[github/Chocobozzz/PeerTube.git] / client / src / standalone / videos / embed.ts
1 import './embed.scss'
2 import '../../assets/player/shared/dock/peertube-dock-component'
3 import '../../assets/player/shared/dock/peertube-dock-plugin'
4 import videojs from 'video.js'
5 import { peertubeTranslate } from '../../../../shared/core-utils/i18n'
6 import { HTMLServerConfig, ResultList, VideoDetails, VideoPlaylist, VideoPlaylistElement, VideoState } from '../../../../shared/models'
7 import { PeertubePlayerManager } from '../../assets/player'
8 import { TranslationsManager } from '../../assets/player/translations-manager'
9 import { getParamString, logger, videoRequiresAuth } from '../../root-helpers'
10 import { PeerTubeEmbedApi } from './embed-api'
11 import {
12 AuthHTTP,
13 LiveManager,
14 PeerTubePlugin,
15 PlayerManagerOptions,
16 PlaylistFetcher,
17 PlaylistTracker,
18 Translations,
19 VideoFetcher
20 } from './shared'
21 import { PlayerHTML } from './shared/player-html'
22
23 export class PeerTubeEmbed {
24 player: videojs.Player
25 api: PeerTubeEmbedApi = null
26
27 config: HTMLServerConfig
28
29 private translationsPromise: Promise<{ [id: string]: string }>
30 private PeertubePlayerManagerModulePromise: Promise<any>
31
32 private readonly http: AuthHTTP
33 private readonly videoFetcher: VideoFetcher
34 private readonly playlistFetcher: PlaylistFetcher
35 private readonly peertubePlugin: PeerTubePlugin
36 private readonly playerHTML: PlayerHTML
37 private readonly playerManagerOptions: PlayerManagerOptions
38 private readonly liveManager: LiveManager
39
40 private playlistTracker: PlaylistTracker
41
42 constructor (videoWrapperId: string) {
43 logger.registerServerSending(window.location.origin)
44
45 this.http = new AuthHTTP()
46
47 this.videoFetcher = new VideoFetcher(this.http)
48 this.playlistFetcher = new PlaylistFetcher(this.http)
49 this.peertubePlugin = new PeerTubePlugin(this.http)
50 this.playerHTML = new PlayerHTML(videoWrapperId)
51 this.playerManagerOptions = new PlayerManagerOptions(this.playerHTML, this.videoFetcher, this.peertubePlugin)
52 this.liveManager = new LiveManager(this.playerHTML)
53
54 try {
55 this.config = JSON.parse(window['PeerTubeServerConfig'])
56 } catch (err) {
57 logger.error('Cannot parse HTML config.', err)
58 }
59 }
60
61 static async main () {
62 const videoContainerId = 'video-wrapper'
63 const embed = new PeerTubeEmbed(videoContainerId)
64 await embed.init()
65 }
66
67 getPlayerElement () {
68 return this.playerHTML.getPlayerElement()
69 }
70
71 getScope () {
72 return this.playerManagerOptions.getScope()
73 }
74
75 // ---------------------------------------------------------------------------
76
77 async init () {
78 this.translationsPromise = TranslationsManager.getServerTranslations(window.location.origin, navigator.language)
79 this.PeertubePlayerManagerModulePromise = import('../../assets/player/peertube-player-manager')
80
81 // Issue when we parsed config from HTML, fallback to API
82 if (!this.config) {
83 this.config = await this.http.fetch('/api/v1/config', { optionalAuth: false })
84 .then(res => res.json())
85 }
86
87 const videoId = this.isPlaylistEmbed()
88 ? await this.initPlaylist()
89 : this.getResourceId()
90
91 if (!videoId) return
92
93 return this.loadVideoAndBuildPlayer({ uuid: videoId, autoplayFromPreviousVideo: false, forceAutoplay: false })
94 }
95
96 private async initPlaylist () {
97 const playlistId = this.getResourceId()
98
99 try {
100 const res = await this.playlistFetcher.loadPlaylist(playlistId)
101
102 const [ playlist, playlistElementResult ] = await Promise.all([
103 res.playlistResponse.json() as Promise<VideoPlaylist>,
104 res.videosResponse.json() as Promise<ResultList<VideoPlaylistElement>>
105 ])
106
107 const allPlaylistElements = await this.playlistFetcher.loadAllPlaylistVideos(playlistId, playlistElementResult)
108
109 this.playlistTracker = new PlaylistTracker(playlist, allPlaylistElements)
110
111 const params = new URL(window.location.toString()).searchParams
112 const playlistPositionParam = getParamString(params, 'playlistPosition')
113
114 const position = playlistPositionParam
115 ? parseInt(playlistPositionParam + '', 10)
116 : 1
117
118 this.playlistTracker.setPosition(position)
119 } catch (err) {
120 this.playerHTML.displayError(err.message, await this.translationsPromise)
121 return undefined
122 }
123
124 return this.playlistTracker.getCurrentElement().video.uuid
125 }
126
127 private initializeApi () {
128 if (this.playerManagerOptions.hasAPIEnabled()) {
129 if (this.api) {
130 this.api.reInit()
131 return
132 }
133
134 this.api = new PeerTubeEmbedApi(this)
135 this.api.initialize()
136 }
137 }
138
139 // ---------------------------------------------------------------------------
140
141 async playNextPlaylistVideo () {
142 const next = this.playlistTracker.getNextPlaylistElement()
143 if (!next) {
144 logger.info('Next element not found in playlist.')
145 return
146 }
147
148 this.playlistTracker.setCurrentElement(next)
149
150 return this.loadVideoAndBuildPlayer({ uuid: next.video.uuid, autoplayFromPreviousVideo: true, forceAutoplay: false })
151 }
152
153 async playPreviousPlaylistVideo () {
154 const previous = this.playlistTracker.getPreviousPlaylistElement()
155 if (!previous) {
156 logger.info('Previous element not found in playlist.')
157 return
158 }
159
160 this.playlistTracker.setCurrentElement(previous)
161
162 await this.loadVideoAndBuildPlayer({ uuid: previous.video.uuid, autoplayFromPreviousVideo: true, forceAutoplay: false })
163 }
164
165 getCurrentPlaylistPosition () {
166 return this.playlistTracker.getCurrentPosition()
167 }
168
169 // ---------------------------------------------------------------------------
170
171 private async loadVideoAndBuildPlayer (options: {
172 uuid: string
173 autoplayFromPreviousVideo: boolean
174 forceAutoplay: boolean
175 }) {
176 const { uuid, autoplayFromPreviousVideo, forceAutoplay } = options
177
178 try {
179 const { videoResponse, captionsPromise } = await this.videoFetcher.loadVideo(uuid)
180
181 return this.buildVideoPlayer({ videoResponse, captionsPromise, autoplayFromPreviousVideo, forceAutoplay })
182 } catch (err) {
183 this.playerHTML.displayError(err.message, await this.translationsPromise)
184 }
185 }
186
187 private async buildVideoPlayer (options: {
188 videoResponse: Response
189 captionsPromise: Promise<Response>
190 autoplayFromPreviousVideo: boolean
191 forceAutoplay: boolean
192 }) {
193 const { videoResponse, captionsPromise, autoplayFromPreviousVideo, forceAutoplay } = options
194
195 this.resetPlayerElement()
196
197 const videoInfoPromise = videoResponse.json()
198 .then(async (videoInfo: VideoDetails) => {
199 this.playerManagerOptions.loadParams(this.config, videoInfo)
200
201 if (!autoplayFromPreviousVideo && !this.playerManagerOptions.hasAutoplay()) {
202 this.playerHTML.buildPlaceholder(videoInfo)
203 }
204 const live = videoInfo.isLive
205 ? await this.videoFetcher.loadLive(videoInfo)
206 : undefined
207
208 const videoFileToken = videoRequiresAuth(videoInfo)
209 ? await this.videoFetcher.loadVideoToken(videoInfo)
210 : undefined
211
212 return { live, video: videoInfo, videoFileToken }
213 })
214
215 const [ { video, live, videoFileToken }, translations, captionsResponse, PeertubePlayerManagerModule ] = await Promise.all([
216 videoInfoPromise,
217 this.translationsPromise,
218 captionsPromise,
219 this.PeertubePlayerManagerModulePromise
220 ])
221
222 await this.peertubePlugin.loadPlugins(this.config, translations)
223
224 const PlayerManager: typeof PeertubePlayerManager = PeertubePlayerManagerModule.PeertubePlayerManager
225
226 const playerOptions = await this.playerManagerOptions.getPlayerOptions({
227 video,
228 captionsResponse,
229 autoplayFromPreviousVideo,
230 translations,
231 serverConfig: this.config,
232
233 authorizationHeader: () => this.http.getHeaderTokenValue(),
234 videoFileToken: () => videoFileToken,
235
236 onVideoUpdate: (uuid: string) => this.loadVideoAndBuildPlayer({ uuid, autoplayFromPreviousVideo: true, forceAutoplay: false }),
237
238 playlistTracker: this.playlistTracker,
239 playNextPlaylistVideo: () => this.playNextPlaylistVideo(),
240 playPreviousPlaylistVideo: () => this.playPreviousPlaylistVideo(),
241
242 live,
243 forceAutoplay
244 })
245
246 this.player = await PlayerManager.initialize(this.playerManagerOptions.getMode(), playerOptions, (player: videojs.Player) => {
247 this.player = player
248 })
249
250 this.player.on('customError', (event: any, data: any) => {
251 const message = data?.err?.message || ''
252 if (!message.includes('from xs param')) return
253
254 this.player.dispose()
255 this.playerHTML.removePlayerElement()
256 this.playerHTML.displayError('This video is not available because the remote instance is not responding.', translations)
257 })
258
259 window['videojsPlayer'] = this.player
260
261 this.buildCSS()
262 this.buildPlayerDock(video)
263 this.initializeApi()
264
265 this.playerHTML.removePlaceholder()
266
267 if (this.isPlaylistEmbed()) {
268 await this.buildPlayerPlaylistUpnext()
269
270 this.player.playlist().updateSelected()
271
272 this.player.on('stopped', () => {
273 this.playNextPlaylistVideo()
274 })
275 }
276
277 if (video.isLive) {
278 this.liveManager.listenForChanges({
279 video,
280 onPublishedVideo: () => {
281 this.liveManager.stopListeningForChanges(video)
282 this.loadVideoAndBuildPlayer({ uuid: video.uuid, autoplayFromPreviousVideo: false, forceAutoplay: true })
283 }
284 })
285
286 if (video.state.id === VideoState.WAITING_FOR_LIVE || video.state.id === VideoState.LIVE_ENDED) {
287 this.liveManager.displayInfo({ state: video.state.id, translations })
288
289 this.disablePlayer()
290 } else {
291 this.correctlyHandleLiveEnding(translations)
292 }
293 }
294
295 this.peertubePlugin.getPluginsManager().runHook('action:embed.player.loaded', undefined, { player: this.player, videojs, video })
296 }
297
298 private resetPlayerElement () {
299 if (this.player) {
300 this.player.dispose()
301 this.player = undefined
302 }
303
304 const playerElement = document.createElement('video')
305 playerElement.className = 'video-js vjs-peertube-skin'
306 playerElement.setAttribute('playsinline', 'true')
307
308 this.playerHTML.setPlayerElement(playerElement)
309 this.playerHTML.addPlayerElementToDOM()
310 }
311
312 private async buildPlayerPlaylistUpnext () {
313 const translations = await this.translationsPromise
314
315 this.player.upnext({
316 timeout: 10000, // 10s
317 headText: peertubeTranslate('Up Next', translations),
318 cancelText: peertubeTranslate('Cancel', translations),
319 suspendedText: peertubeTranslate('Autoplay is suspended', translations),
320 getTitle: () => this.playlistTracker.nextVideoTitle(),
321 next: () => this.playNextPlaylistVideo(),
322 condition: () => !!this.playlistTracker.getNextPlaylistElement(),
323 suspended: () => false
324 })
325 }
326
327 private buildPlayerDock (videoInfo: VideoDetails) {
328 if (!this.playerManagerOptions.hasControls()) return
329
330 // On webtorrent fallback, player may have been disposed
331 if (!this.player.player_) return
332
333 const title = this.playerManagerOptions.hasTitle()
334 ? videoInfo.name
335 : undefined
336
337 const description = this.playerManagerOptions.hasWarningTitle() && this.playerManagerOptions.hasP2PEnabled()
338 ? '<span class="text">' + peertubeTranslate('Watching this video may reveal your IP address to others.') + '</span>'
339 : undefined
340
341 if (!title && !description) return
342
343 const availableAvatars = videoInfo.channel.avatars.filter(a => a.width < 50)
344 const avatar = availableAvatars.length !== 0
345 ? availableAvatars[0]
346 : undefined
347
348 this.player.peertubeDock({
349 title,
350 description,
351 avatarUrl: title && avatar
352 ? avatar.path
353 : undefined
354 })
355 }
356
357 private buildCSS () {
358 const body = document.getElementById('custom-css')
359
360 if (this.playerManagerOptions.hasBigPlayBackgroundColor()) {
361 body.style.setProperty('--embedBigPlayBackgroundColor', this.playerManagerOptions.getBigPlayBackgroundColor())
362 }
363
364 if (this.playerManagerOptions.hasForegroundColor()) {
365 body.style.setProperty('--embedForegroundColor', this.playerManagerOptions.getForegroundColor())
366 }
367 }
368
369 // ---------------------------------------------------------------------------
370
371 private getResourceId () {
372 const urlParts = window.location.pathname.split('/')
373 return urlParts[urlParts.length - 1]
374 }
375
376 private isPlaylistEmbed () {
377 return window.location.pathname.split('/')[1] === 'video-playlists'
378 }
379
380 // ---------------------------------------------------------------------------
381
382 private correctlyHandleLiveEnding (translations: Translations) {
383 this.player.one('ended', () => {
384 // Display the live ended information
385 this.liveManager.displayInfo({ state: VideoState.LIVE_ENDED, translations })
386
387 this.disablePlayer()
388 })
389 }
390
391 private disablePlayer () {
392 if (this.player.isFullscreen()) {
393 this.player.exitFullscreen()
394 }
395
396 // Disable player
397 this.player.hasStarted(false)
398 this.player.removeClass('vjs-has-autoplay')
399 this.player.bigPlayButton.hide();
400
401 (this.player.el() as HTMLElement).style.pointerEvents = 'none'
402 }
403
404 }
405
406 PeerTubeEmbed.main()
407 .catch(err => {
408 (window as any).displayIncompatibleBrowser()
409
410 logger.error('Cannot init embed.', err)
411 })