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