]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blame - client/src/standalone/videos/embed.ts
Add migration script
[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'
3545e72c 9import { getParamString, logger, videoRequiresAuth } 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
3545e72c
C
170 const videoInfoPromise = videoResponse.json()
171 .then(async (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 }
3545e72c
C
177 const live = videoInfo.isLive
178 ? await this.videoFetcher.loadLive(videoInfo)
179 : undefined
5abc96fc 180
3545e72c
C
181 const videoFileToken = videoRequiresAuth(videoInfo)
182 ? await this.videoFetcher.loadVideoToken(videoInfo)
183 : undefined
f443a746 184
3545e72c 185 return { live, video: videoInfo, videoFileToken }
5abc96fc
C
186 })
187
3545e72c 188 const [ { video, live, videoFileToken }, translations, captionsResponse, PeertubePlayerManagerModule ] = await Promise.all([
5abc96fc
C
189 videoInfoPromise,
190 this.translationsPromise,
191 captionsPromise,
5abc96fc
C
192 this.PeertubePlayerManagerModulePromise
193 ])
3f9c4955 194
f1a0f3b7 195 await this.peertubePlugin.loadPlugins(this.config, translations)
1a8c2d74 196
f1a0f3b7 197 const PlayerManager: typeof PeertubePlayerManager = PeertubePlayerManagerModule.PeertubePlayerManager
a9bfa85d 198
f1a0f3b7
C
199 const options = await this.playerManagerOptions.getPlayerOptions({
200 video,
201 captionsResponse,
202 alreadyHadPlayer,
203 translations,
bd2b51be
C
204 serverConfig: this.config,
205
3545e72c
C
206 authorizationHeader: () => this.http.getHeaderTokenValue(),
207 videoFileToken: () => videoFileToken,
208
f1a0f3b7 209 onVideoUpdate: (uuid: string) => this.loadVideoAndBuildPlayer(uuid),
2adfc7ea 210
f1a0f3b7
C
211 playlistTracker: this.playlistTracker,
212 playNextPlaylistVideo: () => this.playNextPlaylistVideo(),
213 playPreviousPlaylistVideo: () => this.playPreviousPlaylistVideo(),
1a8c2d74 214
f1a0f3b7
C
215 live
216 })
202e7223 217
f1a0f3b7 218 this.player = await PlayerManager.initialize(this.playerManagerOptions.getMode(), options, (player: videojs.Player) => {
9df52d66
C
219 this.player = player
220 })
221
f1a0f3b7
C
222 this.player.on('customError', (event: any, data: any) => {
223 const message = data?.err?.message || ''
224 if (!message.includes('from xs param')) return
225
226 this.player.dispose()
227 this.playerHTML.removePlayerElement()
228 this.playerHTML.displayError('This video is not available because the remote instance is not responding.', translations)
229 })
99941732 230
9df52d66 231 window['videojsPlayer'] = this.player
902aa3a0 232
5efab546 233 this.buildCSS()
f1a0f3b7 234 this.buildPlayerDock(video)
5efab546 235 this.initializeApi()
3f9c4955 236
f1a0f3b7 237 this.playerHTML.removePlaceholder()
5abc96fc
C
238
239 if (this.isPlaylistEmbed()) {
f1a0f3b7 240 await this.buildPlayerPlaylistUpnext()
1a8c2d74 241
4572c3d0 242 this.player.playlist().updateSelected()
1a8c2d74
C
243
244 this.player.on('stopped', () => {
f1a0f3b7 245 this.playNextPlaylistVideo()
1a8c2d74 246 })
5abc96fc 247 }
f9562863 248
f1a0f3b7 249 this.peertubePlugin.getPluginsManager().runHook('action:embed.player.loaded', undefined, { player: this.player, videojs, video })
d3f4689b
C
250
251 if (video.isLive) {
252 this.liveManager.displayInfoAndListenForChanges({
253 video,
254 translations,
255 onPublishedVideo: () => {
256 this.liveManager.stopListeningForChanges(video)
257 this.loadVideoAndBuildPlayer(video.uuid)
258 }
259 })
260 }
5abc96fc
C
261 }
262
f1a0f3b7
C
263 private resetPlayerElement () {
264 let alreadyHadPlayer = false
5abc96fc 265
f1a0f3b7
C
266 if (this.player) {
267 this.player.dispose()
b1934b7e 268 this.player = undefined
f1a0f3b7
C
269 alreadyHadPlayer = true
270 }
5abc96fc 271
f1a0f3b7
C
272 const playerElement = document.createElement('video')
273 playerElement.className = 'video-js vjs-peertube-skin'
274 playerElement.setAttribute('playsinline', 'true')
5abc96fc 275
f1a0f3b7
C
276 this.playerHTML.setPlayerElement(playerElement)
277 this.playerHTML.addPlayerElementToDOM()
5abc96fc 278
f1a0f3b7 279 return alreadyHadPlayer
5efab546
C
280 }
281
f1a0f3b7
C
282 private async buildPlayerPlaylistUpnext () {
283 const translations = await this.translationsPromise
284
285 this.player.upnext({
286 timeout: 10000, // 10s
287 headText: peertubeTranslate('Up Next', translations),
288 cancelText: peertubeTranslate('Cancel', translations),
289 suspendedText: peertubeTranslate('Autoplay is suspended', translations),
290 getTitle: () => this.playlistTracker.nextVideoTitle(),
291 next: () => this.playNextPlaylistVideo(),
292 condition: () => !!this.playlistTracker.getNextPlaylistElement(),
293 suspended: () => false
294 })
5efab546
C
295 }
296
f1a0f3b7
C
297 private buildPlayerDock (videoInfo: VideoDetails) {
298 if (!this.playerManagerOptions.hasControls()) return
5efab546 299
818c449b
C
300 // On webtorrent fallback, player may have been disposed
301 if (!this.player.player_) return
5efab546 302
f1a0f3b7
C
303 const title = this.playerManagerOptions.hasTitle()
304 ? videoInfo.name
305 : undefined
306
307 const description = this.playerManagerOptions.hasWarningTitle() && this.playerManagerOptions.hasP2PEnabled()
abb3097e
C
308 ? '<span class="text">' + peertubeTranslate('Watching this video may reveal your IP address to others.') + '</span>'
309 : undefined
310
f1a0f3b7
C
311 if (!title && !description) return
312
01dd04cd
C
313 const availableAvatars = videoInfo.channel.avatars.filter(a => a.width < 50)
314 const avatar = availableAvatars.length !== 0
315 ? availableAvatars[0]
316 : undefined
317
f1a0f3b7
C
318 this.player.peertubeDock({
319 title,
320 description,
321 avatarUrl: title && avatar
322 ? avatar.path
323 : undefined
324 })
5efab546 325 }
16f7022b 326
5efab546
C
327 private buildCSS () {
328 const body = document.getElementById('custom-css')
329
f1a0f3b7
C
330 if (this.playerManagerOptions.hasBigPlayBackgroundColor()) {
331 body.style.setProperty('--embedBigPlayBackgroundColor', this.playerManagerOptions.getBigPlayBackgroundColor())
5efab546
C
332 }
333
f1a0f3b7
C
334 if (this.playerManagerOptions.hasForegroundColor()) {
335 body.style.setProperty('--embedForegroundColor', this.playerManagerOptions.getForegroundColor())
5efab546 336 }
99941732 337 }
6d88de72 338
f1a0f3b7 339 // ---------------------------------------------------------------------------
207612df 340
5abc96fc
C
341 private getResourceId () {
342 const urlParts = window.location.pathname.split('/')
9df52d66 343 return urlParts[urlParts.length - 1]
5abc96fc
C
344 }
345
346 private isPlaylistEmbed () {
347 return window.location.pathname.split('/')[1] === 'video-playlists'
348 }
99941732
WL
349}
350
351PeerTubeEmbed.main()
c21a0aa8
C
352 .catch(err => {
353 (window as any).displayIncompatibleBrowser()
354
42b40636 355 logger.error('Cannot init embed.', err)
c21a0aa8 356 })