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