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