]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blame - client/src/standalone/videos/embed.ts
Do not display videojs poster when video is starting
[github/Chocobozzz/PeerTube.git] / client / src / standalone / videos / embed.ts
CommitLineData
202e7223 1import './embed.scss'
583eb04b 2import videojs from 'video.js'
a4ff3100
C
3import { objectToUrlEncoded, peertubeLocalStorage } from '@root-helpers/index'
4import { Tokens } from '@root-helpers/users'
bd45d503 5import { peertubeTranslate } from '../../../../shared/core-utils/i18n'
3f9c4955 6import {
3f9c4955
C
7 ResultList,
8 ServerConfig,
583eb04b
C
9 UserRefreshToken,
10 VideoCaption,
4504f09f 11 VideoDetails,
5abc96fc
C
12 VideoPlaylist,
13 VideoPlaylistElement,
583eb04b
C
14 VideoStreamingPlaylistType
15} from '../../../../shared/models'
16import { P2PMediaLoaderOptions, PeertubePlayerManagerOptions, PlayerMode } from '../../assets/player/peertube-player-manager'
abb3097e 17import { VideoJSCaption } from '../../assets/player/peertube-videojs-typings'
583eb04b
C
18import { TranslationsManager } from '../../assets/player/translations-manager'
19import { PeerTubeEmbedApi } from './embed-api'
abb3097e
C
20
21type Translations = { [ id: string ]: string }
202e7223 22
5efab546 23export class PeerTubeEmbed {
5abc96fc 24 playerElement: HTMLVideoElement
7e37e111 25 player: videojs.Player
902aa3a0 26 api: PeerTubeEmbedApi = null
5abc96fc 27
3b019808
C
28 autoplay: boolean
29 controls: boolean
30 muted: boolean
31 loop: boolean
32 subtitle: string
902aa3a0 33 enableApi = false
1f6824c9 34 startTime: number | string = 0
f0a39880 35 stopTime: number | string
5efab546
C
36
37 title: boolean
38 warningTitle: boolean
08d9ba0f 39 peertubeLink: boolean
5efab546
C
40 bigPlayBackgroundColor: string
41 foregroundColor: string
42
3b6f205c 43 mode: PlayerMode
902aa3a0
C
44 scope = 'peertube'
45
a4ff3100 46 userTokens: Tokens
71ab65d0 47 headers = new Headers()
4504f09f
RK
48 LOCAL_STORAGE_OAUTH_CLIENT_KEYS = {
49 CLIENT_ID: 'client_id',
50 CLIENT_SECRET: 'client_secret'
51 }
71ab65d0 52
5abc96fc
C
53 private translationsPromise: Promise<{ [id: string]: string }>
54 private configPromise: Promise<ServerConfig>
55 private PeertubePlayerManagerModulePromise: Promise<any>
56
57 private playlist: VideoPlaylist
58 private playlistElements: VideoPlaylistElement[]
59 private currentPlaylistElement: VideoPlaylistElement
60
61 private wrapperElement: HTMLElement
62
902aa3a0 63 static async main () {
5abc96fc 64 const videoContainerId = 'video-wrapper'
99941732
WL
65 const embed = new PeerTubeEmbed(videoContainerId)
66 await embed.init()
67 }
902aa3a0 68
5abc96fc
C
69 constructor (private videoWrapperId: string) {
70 this.wrapperElement = document.getElementById(this.videoWrapperId)
902aa3a0
C
71 }
72
99941732
WL
73 getVideoUrl (id: string) {
74 return window.location.origin + '/api/v1/videos/' + id
75 }
d4f3fea6 76
4504f09f
RK
77 refreshFetch (url: string, options?: Object) {
78 return fetch(url, options)
79 .then((res: Response) => {
80 if (res.status !== 401) return res
81
82 // 401 unauthorized is not catch-ed, but then-ed
83 const error = res
84
85 const refreshingTokenPromise = new Promise((resolve, reject) => {
86 const clientId: string = peertubeLocalStorage.getItem(this.LOCAL_STORAGE_OAUTH_CLIENT_KEYS.CLIENT_ID)
87 const clientSecret: string = peertubeLocalStorage.getItem(this.LOCAL_STORAGE_OAUTH_CLIENT_KEYS.CLIENT_SECRET)
88 const headers = new Headers()
89 headers.set('Content-Type', 'application/x-www-form-urlencoded')
90 const data = {
a4ff3100 91 refresh_token: this.userTokens.refreshToken,
4504f09f
RK
92 client_id: clientId,
93 client_secret: clientSecret,
94 response_type: 'code',
95 grant_type: 'refresh_token'
96 }
97
98 fetch('/api/v1/users/token', {
99 headers,
100 method: 'POST',
101 body: objectToUrlEncoded(data)
102 })
103 .then(res => res.json())
104 .then((obj: UserRefreshToken) => {
a4ff3100
C
105 this.userTokens.accessToken = obj.access_token
106 this.userTokens.refreshToken = obj.refresh_token
107 this.userTokens.save()
108
109 this.setHeadersFromTokens()
110
4504f09f
RK
111 resolve()
112 })
113 .catch((refreshTokenError: any) => {
114 reject(refreshTokenError)
115 })
116 })
117
118 return refreshingTokenPromise
119 .catch(() => {
120 // If refreshing fails, continue with original error
121 throw error
122 })
123 .then(() => fetch(url, {
124 ...options,
125 headers: this.headers
126 }))
127 })
128 }
129
5abc96fc
C
130 getPlaylistUrl (id: string) {
131 return window.location.origin + '/api/v1/video-playlists/' + id
132 }
133
99941732 134 loadVideoInfo (videoId: string): Promise<Response> {
4504f09f 135 return this.refreshFetch(this.getVideoUrl(videoId), { headers: this.headers })
99941732 136 }
d4f3fea6 137
16f7022b 138 loadVideoCaptions (videoId: string): Promise<Response> {
be59656c 139 return this.refreshFetch(this.getVideoUrl(videoId) + '/captions', { headers: this.headers })
16f7022b
C
140 }
141
5abc96fc 142 loadPlaylistInfo (playlistId: string): Promise<Response> {
be59656c 143 return this.refreshFetch(this.getPlaylistUrl(playlistId), { headers: this.headers })
5abc96fc
C
144 }
145
fb13852d
C
146 loadPlaylistElements (playlistId: string, start = 0): Promise<Response> {
147 const url = new URL(this.getPlaylistUrl(playlistId) + '/videos')
148 url.search = new URLSearchParams({ start: '' + start, count: '100' }).toString()
149
be59656c 150 return this.refreshFetch(url.toString(), { headers: this.headers })
5abc96fc
C
151 }
152
153 loadConfig (): Promise<ServerConfig> {
be59656c 154 return this.refreshFetch('/api/v1/config')
5abc96fc 155 .then(res => res.json())
31b6ddf8
C
156 }
157
99941732
WL
158 removeElement (element: HTMLElement) {
159 element.parentElement.removeChild(element)
160 }
d4f3fea6 161
abb3097e 162 displayError (text: string, translations?: Translations) {
99941732 163 // Remove video element
5abc96fc
C
164 if (this.playerElement) {
165 this.removeElement(this.playerElement)
166 this.playerElement = undefined
167 }
99941732 168
ad3fa0c5
C
169 const translatedText = peertubeTranslate(text, translations)
170 const translatedSorry = peertubeTranslate('Sorry', translations)
171
172 document.title = translatedSorry + ' - ' + translatedText
99941732
WL
173
174 const errorBlock = document.getElementById('error-block')
175 errorBlock.style.display = 'flex'
176
ad3fa0c5
C
177 const errorTitle = document.getElementById('error-title')
178 errorTitle.innerHTML = peertubeTranslate('Sorry', translations)
179
99941732 180 const errorText = document.getElementById('error-content')
ad3fa0c5 181 errorText.innerHTML = translatedText
2a71d286
C
182
183 this.wrapperElement.style.display = 'none'
99941732
WL
184 }
185
abb3097e 186 videoNotFound (translations?: Translations) {
99941732 187 const text = 'This video does not exist.'
ad3fa0c5 188 this.displayError(text, translations)
99941732
WL
189 }
190
abb3097e 191 videoFetchError (translations?: Translations) {
99941732 192 const text = 'We cannot fetch the video. Please try again later.'
ad3fa0c5 193 this.displayError(text, translations)
99941732
WL
194 }
195
5abc96fc
C
196 playlistNotFound (translations?: Translations) {
197 const text = 'This playlist does not exist.'
198 this.displayError(text, translations)
199 }
200
201 playlistFetchError (translations?: Translations) {
202 const text = 'We cannot fetch the playlist. Please try again later.'
203 this.displayError(text, translations)
204 }
205
3b019808 206 getParamToggle (params: URLSearchParams, name: string, defaultValue?: boolean) {
99941732
WL
207 return params.has(name) ? (params.get(name) === '1' || params.get(name) === 'true') : defaultValue
208 }
d4f3fea6 209
3b019808 210 getParamString (params: URLSearchParams, name: string, defaultValue?: string) {
99941732
WL
211 return params.has(name) ? params.get(name) : defaultValue
212 }
da99ccf2 213
9054a8b6
C
214 async playNextVideo () {
215 const next = this.getNextPlaylistElement()
216 if (!next) {
217 console.log('Next element not found in playlist.')
218 return
219 }
220
221 this.currentPlaylistElement = next
222
223 return this.loadVideoAndBuildPlayer(this.currentPlaylistElement.video.uuid)
224 }
225
226 async playPreviousVideo () {
227 const previous = this.getPreviousPlaylistElement()
228 if (!previous) {
229 console.log('Previous element not found in playlist.')
230 return
231 }
232
233 this.currentPlaylistElement = previous
234
235 await this.loadVideoAndBuildPlayer(this.currentPlaylistElement.video.uuid)
236 }
237
238 getCurrentPosition () {
239 if (!this.currentPlaylistElement) return -1
240
241 return this.currentPlaylistElement.position
242 }
243
902aa3a0 244 async init () {
99941732 245 try {
a4ff3100 246 this.userTokens = Tokens.load()
99941732
WL
247 await this.initCore()
248 } catch (e) {
249 console.error(e)
250 }
251 }
252
902aa3a0
C
253 private initializeApi () {
254 if (!this.enableApi) return
255
256 this.api = new PeerTubeEmbedApi(this)
257 this.api.initialize()
258 }
259
0f2f274c 260 private loadParams (video: VideoDetails) {
da99ccf2 261 try {
c4710631 262 const params = new URL(window.location.toString()).searchParams
99941732 263
31b6ddf8
C
264 this.autoplay = this.getParamToggle(params, 'autoplay', false)
265 this.controls = this.getParamToggle(params, 'controls', true)
64645512 266 this.muted = this.getParamToggle(params, 'muted', undefined)
31b6ddf8 267 this.loop = this.getParamToggle(params, 'loop', false)
5efab546 268 this.title = this.getParamToggle(params, 'title', true)
99941732 269 this.enableApi = this.getParamToggle(params, 'api', this.enableApi)
5efab546 270 this.warningTitle = this.getParamToggle(params, 'warningTitle', true)
08d9ba0f 271 this.peertubeLink = this.getParamToggle(params, 'peertubeLink', true)
f37bad63 272
3b019808
C
273 this.scope = this.getParamString(params, 'scope', this.scope)
274 this.subtitle = this.getParamString(params, 'subtitle')
275 this.startTime = this.getParamString(params, 'start')
f0a39880 276 this.stopTime = this.getParamString(params, 'stop')
3b6f205c 277
5efab546
C
278 this.bigPlayBackgroundColor = this.getParamString(params, 'bigPlayBackgroundColor')
279 this.foregroundColor = this.getParamString(params, 'foregroundColor')
280
0f2f274c
C
281 const modeParam = this.getParamString(params, 'mode')
282
283 if (modeParam) {
284 if (modeParam === 'p2p-media-loader') this.mode = 'p2p-media-loader'
285 else this.mode = 'webtorrent'
286 } else {
287 if (Array.isArray(video.streamingPlaylists) && video.streamingPlaylists.length !== 0) this.mode = 'p2p-media-loader'
288 else this.mode = 'webtorrent'
289 }
da99ccf2
C
290 } catch (err) {
291 console.error('Cannot get params from URL.', err)
292 }
99941732
WL
293 }
294
fb13852d
C
295 private async loadAllPlaylistVideos (playlistId: string, baseResult: ResultList<VideoPlaylistElement>) {
296 let elements = baseResult.data
297 let total = baseResult.total
298 let i = 0
299
300 while (total > elements.length && i < 10) {
301 const result = await this.loadPlaylistElements(playlistId, elements.length)
302
303 const json = await result.json() as ResultList<VideoPlaylistElement>
304 total = json.total
305
306 elements = elements.concat(json.data)
307 i++
308 }
309
310 if (i === 10) {
311 console.error('Cannot fetch all playlists elements, there are too many!')
312 }
313
314 return elements
315 }
316
5abc96fc
C
317 private async loadPlaylist (playlistId: string) {
318 const playlistPromise = this.loadPlaylistInfo(playlistId)
319 const playlistElementsPromise = this.loadPlaylistElements(playlistId)
99941732 320
be59656c
C
321 let playlistResponse: Response
322 let isResponseOk: boolean
5abc96fc 323
be59656c
C
324 try {
325 playlistResponse = await playlistPromise
326 isResponseOk = true
327 } catch (err) {
328 console.error(err)
329 isResponseOk = false
330 }
331
332 if (!isResponseOk) {
5abc96fc 333 const serverTranslations = await this.translationsPromise
71ab65d0 334
be59656c 335 if (playlistResponse?.status === 404) {
5abc96fc
C
336 this.playlistNotFound(serverTranslations)
337 return undefined
338 }
339
340 this.playlistFetchError(serverTranslations)
341 return undefined
342 }
343
344 return { playlistResponse, videosResponse: await playlistElementsPromise }
345 }
346
347 private async loadVideo (videoId: string) {
3f9c4955 348 const videoPromise = this.loadVideoInfo(videoId)
3f9c4955 349
be59656c
C
350 let videoResponse: Response
351 let isResponseOk: boolean
352
353 try {
354 videoResponse = await videoPromise
355 isResponseOk = true
356 } catch (err) {
357 console.error(err)
358
359 isResponseOk = false
360 }
99941732 361
be59656c 362 if (!isResponseOk) {
5abc96fc
C
363 const serverTranslations = await this.translationsPromise
364
be59656c 365 if (videoResponse?.status === 404) {
5abc96fc
C
366 this.videoNotFound(serverTranslations)
367 return undefined
368 }
369
370 this.videoFetchError(serverTranslations)
371 return undefined
372 }
373
374 const captionsPromise = this.loadVideoCaptions(videoId)
375
376 return { captionsPromise, videoResponse }
377 }
3f9c4955 378
5abc96fc
C
379 private async buildPlaylistManager () {
380 const translations = await this.translationsPromise
381
382 this.player.upnext({
383 timeout: 10000, // 10s
384 headText: peertubeTranslate('Up Next', translations),
385 cancelText: peertubeTranslate('Cancel', translations),
386 suspendedText: peertubeTranslate('Autoplay is suspended', translations),
387 getTitle: () => this.nextVideoTitle(),
a950e4c8 388 next: () => this.playNextVideo(),
5abc96fc
C
389 condition: () => !!this.getNextPlaylistElement(),
390 suspended: () => false
391 })
392 }
99941732 393
4572c3d0
C
394 private async loadVideoAndBuildPlayer (uuid: string) {
395 const res = await this.loadVideo(uuid)
5abc96fc
C
396 if (res === undefined) return
397
398 return this.buildVideoPlayer(res.videoResponse, res.captionsPromise)
399 }
3f9c4955 400
5abc96fc
C
401 private nextVideoTitle () {
402 const next = this.getNextPlaylistElement()
403 if (!next) return ''
404
405 return next.video.name
406 }
407
408 private getNextPlaylistElement (position?: number): VideoPlaylistElement {
409 if (!position) position = this.currentPlaylistElement.position + 1
410
411 if (position > this.playlist.videosLength) {
412 return undefined
413 }
414
415 const next = this.playlistElements.find(e => e.position === position)
416
417 if (!next || !next.video) {
418 return this.getNextPlaylistElement(position + 1)
419 }
420
421 return next
422 }
423
a950e4c8 424 private getPreviousPlaylistElement (position?: number): VideoPlaylistElement {
2a71d286 425 if (!position) position = this.currentPlaylistElement.position - 1
a950e4c8
C
426
427 if (position < 1) {
428 return undefined
429 }
430
431 const prev = this.playlistElements.find(e => e.position === position)
432
433 if (!prev || !prev.video) {
434 return this.getNextPlaylistElement(position - 1)
435 }
436
437 return prev
438 }
439
5abc96fc
C
440 private async buildVideoPlayer (videoResponse: Response, captionsPromise: Promise<Response>) {
441 let alreadyHadPlayer = false
442
443 if (this.player) {
444 this.player.dispose()
445 alreadyHadPlayer = true
446 }
447
448 this.playerElement = document.createElement('video')
449 this.playerElement.className = 'video-js vjs-peertube-skin'
450 this.playerElement.setAttribute('playsinline', 'true')
451 this.wrapperElement.appendChild(this.playerElement)
452
453 const videoInfoPromise = videoResponse.json()
454 .then((videoInfo: VideoDetails) => {
455 if (!alreadyHadPlayer) this.loadPlaceholder(videoInfo)
456
457 return videoInfo
458 })
459
6fad8e51 460 const [ videoInfoTmp, serverTranslations, captionsResponse, config, PeertubePlayerManagerModule ] = await Promise.all([
5abc96fc
C
461 videoInfoPromise,
462 this.translationsPromise,
463 captionsPromise,
464 this.configPromise,
465 this.PeertubePlayerManagerModulePromise
466 ])
3f9c4955 467
6fad8e51
C
468 const videoInfo: VideoDetails = videoInfoTmp
469
3f9c4955 470 const PeertubePlayerManager = PeertubePlayerManagerModule.PeertubePlayerManager
5efab546 471 const videoCaptions = await this.buildCaptions(serverTranslations, captionsResponse)
99941732 472
0f2f274c 473 this.loadParams(videoInfo)
da99ccf2 474
4572c3d0
C
475 const playlistPlugin = this.currentPlaylistElement
476 ? {
477 elements: this.playlistElements,
478 playlist: this.playlist,
479
480 getCurrentPosition: () => this.currentPlaylistElement.position,
481
482 onItemClicked: (videoPlaylistElement: VideoPlaylistElement) => {
483 this.currentPlaylistElement = videoPlaylistElement
484
485 this.loadVideoAndBuildPlayer(this.currentPlaylistElement.video.uuid)
486 .catch(err => console.error(err))
487 }
488 }
489 : undefined
490
2adfc7ea
C
491 const options: PeertubePlayerManagerOptions = {
492 common: {
5abc96fc
C
493 // Autoplay in playlist mode
494 autoplay: alreadyHadPlayer ? true : this.autoplay,
2adfc7ea
C
495 controls: this.controls,
496 muted: this.muted,
497 loop: this.loop,
1a8c2d74 498
2adfc7ea 499 captions: videoCaptions.length !== 0,
2adfc7ea
C
500 subtitle: this.subtitle,
501
1a8c2d74
C
502 startTime: this.playlist ? this.currentPlaylistElement.startTimestamp : this.startTime,
503 stopTime: this.playlist ? this.currentPlaylistElement.stopTimestamp : this.stopTime,
504
a950e4c8
C
505 nextVideo: this.playlist ? () => this.playNextVideo() : undefined,
506 hasNextVideo: this.playlist ? () => !!this.getNextPlaylistElement() : undefined,
507
508 previousVideo: this.playlist ? () => this.playPreviousVideo() : undefined,
509 hasPreviousVideo: this.playlist ? () => !!this.getPreviousPlaylistElement() : undefined,
510
4572c3d0 511 playlist: playlistPlugin,
5abc96fc 512
2adfc7ea 513 videoCaptions,
35f0a5e6 514 inactivityTimeout: 2500,
5abc96fc 515 videoViewUrl: this.getVideoUrl(videoInfo.uuid) + '/views',
6ec0b75b 516
5abc96fc
C
517 playerElement: this.playerElement,
518 onPlayerElementChange: (element: HTMLVideoElement) => this.playerElement = element,
6ec0b75b 519
2adfc7ea
C
520 videoDuration: videoInfo.duration,
521 enableHotkeys: true,
08d9ba0f 522 peertubeLink: this.peertubeLink,
2adfc7ea 523 poster: window.location.origin + videoInfo.previewPath,
3d9a63d3 524 theaterButton: false,
2adfc7ea
C
525
526 serverUrl: window.location.origin,
527 language: navigator.language,
528 embedUrl: window.location.origin + videoInfo.embedPath
6ec0b75b
C
529 },
530
531 webtorrent: {
532 videoFiles: videoInfo.files
2adfc7ea 533 }
3b6f205c 534 }
2adfc7ea 535
3b6f205c 536 if (this.mode === 'p2p-media-loader') {
09209296
C
537 const hlsPlaylist = videoInfo.streamingPlaylists.find(p => p.type === VideoStreamingPlaylistType.HLS)
538
3b6f205c
C
539 Object.assign(options, {
540 p2pMediaLoader: {
09209296
C
541 playlistUrl: hlsPlaylist.playlistUrl,
542 segmentsSha256Url: hlsPlaylist.segmentsSha256Url,
543 redundancyBaseUrls: hlsPlaylist.redundancies.map(r => r.baseUrl),
544 trackerAnnounce: videoInfo.trackerUrls,
5a71acd2 545 videoFiles: hlsPlaylist.files
09209296 546 } as P2PMediaLoaderOptions
3b6f205c 547 })
2adfc7ea 548 }
202e7223 549
7e37e111 550 this.player = await PeertubePlayerManager.initialize(this.mode, options, (player: videojs.Player) => this.player = player)
2adfc7ea 551 this.player.on('customError', (event: any, data: any) => this.handleError(data.err, serverTranslations))
99941732 552
2adfc7ea 553 window[ 'videojsPlayer' ] = this.player
902aa3a0 554
5efab546
C
555 this.buildCSS()
556
5abc96fc 557 await this.buildDock(videoInfo, config)
5efab546
C
558
559 this.initializeApi()
3f9c4955
C
560
561 this.removePlaceholder()
5abc96fc
C
562
563 if (this.isPlaylistEmbed()) {
564 await this.buildPlaylistManager()
1a8c2d74 565
4572c3d0 566 this.player.playlist().updateSelected()
1a8c2d74
C
567
568 this.player.on('stopped', () => {
569 this.playNextVideo()
570 })
5abc96fc
C
571 }
572 }
573
574 private async initCore () {
575 if (this.userTokens) this.setHeadersFromTokens()
576
577 this.configPromise = this.loadConfig()
578 this.translationsPromise = TranslationsManager.getServerTranslations(window.location.origin, navigator.language)
579 this.PeertubePlayerManagerModulePromise = import('../../assets/player/peertube-player-manager')
580
581 let videoId: string
582
583 if (this.isPlaylistEmbed()) {
584 const playlistId = this.getResourceId()
585 const res = await this.loadPlaylist(playlistId)
586 if (!res) return undefined
587
588 this.playlist = await res.playlistResponse.json()
589
590 const playlistElementResult = await res.videosResponse.json()
fb13852d 591 this.playlistElements = await this.loadAllPlaylistVideos(playlistId, playlistElementResult)
5abc96fc 592
2a71d286
C
593 const params = new URL(window.location.toString()).searchParams
594 const playlistPositionParam = this.getParamString(params, 'playlistPosition')
595
596 let position = 1
597
598 if (playlistPositionParam) {
599 position = parseInt(playlistPositionParam + '', 10)
600 }
601
602 this.currentPlaylistElement = this.playlistElements.find(e => e.position === position)
603 if (!this.currentPlaylistElement || !this.currentPlaylistElement.video) {
604 console.error('Current playlist element is not valid.', this.currentPlaylistElement)
605 this.currentPlaylistElement = this.getNextPlaylistElement()
606 }
607
608 if (!this.currentPlaylistElement) {
609 console.error('This playlist does not have any valid element.')
610 const serverTranslations = await this.translationsPromise
611 this.playlistFetchError(serverTranslations)
612 return
613 }
614
5abc96fc
C
615 videoId = this.currentPlaylistElement.video.uuid
616 } else {
617 videoId = this.getResourceId()
618 }
619
4572c3d0 620 return this.loadVideoAndBuildPlayer(videoId)
5efab546
C
621 }
622
623 private handleError (err: Error, translations?: { [ id: string ]: string }) {
624 if (err.message.indexOf('from xs param') !== -1) {
625 this.player.dispose()
5abc96fc 626 this.playerElement = null
5efab546
C
627 this.displayError('This video is not available because the remote instance is not responding.', translations)
628 return
629 }
630 }
631
5abc96fc 632 private async buildDock (videoInfo: VideoDetails, config: ServerConfig) {
abb3097e 633 if (!this.controls) return
5efab546 634
818c449b
C
635 // On webtorrent fallback, player may have been disposed
636 if (!this.player.player_) return
5efab546 637
abb3097e 638 const title = this.title ? videoInfo.name : undefined
31b6ddf8 639
abb3097e
C
640 const description = config.tracker.enabled && this.warningTitle
641 ? '<span class="text">' + peertubeTranslate('Watching this video may reveal your IP address to others.') + '</span>'
642 : undefined
643
644 this.player.dock({
645 title,
646 description
647 })
5efab546 648 }
16f7022b 649
5efab546
C
650 private buildCSS () {
651 const body = document.getElementById('custom-css')
652
653 if (this.bigPlayBackgroundColor) {
654 body.style.setProperty('--embedBigPlayBackgroundColor', this.bigPlayBackgroundColor)
655 }
656
657 if (this.foregroundColor) {
658 body.style.setProperty('--embedForegroundColor', this.foregroundColor)
659 }
99941732 660 }
6d88de72 661
5efab546
C
662 private async buildCaptions (serverTranslations: any, captionsResponse: Response): Promise<VideoJSCaption[]> {
663 if (captionsResponse.ok) {
664 const { data } = (await captionsResponse.json()) as ResultList<VideoCaption>
665
666 return data.map(c => ({
667 label: peertubeTranslate(c.language.label, serverTranslations),
668 language: c.language.id,
669 src: window.location.origin + c.captionPath
670 }))
6d88de72 671 }
5efab546
C
672
673 return []
6d88de72 674 }
3f9c4955
C
675
676 private loadPlaceholder (video: VideoDetails) {
677 const placeholder = this.getPlaceholderElement()
678
679 const url = window.location.origin + video.previewPath
680 placeholder.style.backgroundImage = `url("${url}")`
5abc96fc 681 placeholder.style.display = 'block'
3f9c4955
C
682 }
683
684 private removePlaceholder () {
685 const placeholder = this.getPlaceholderElement()
5abc96fc 686 placeholder.style.display = 'none'
3f9c4955
C
687 }
688
689 private getPlaceholderElement () {
690 return document.getElementById('placeholder-preview')
691 }
a4ff3100
C
692
693 private setHeadersFromTokens () {
694 this.headers.set('Authorization', `${this.userTokens.tokenType} ${this.userTokens.accessToken}`)
695 }
5abc96fc
C
696
697 private getResourceId () {
698 const urlParts = window.location.pathname.split('/')
699 return urlParts[ urlParts.length - 1 ]
700 }
701
702 private isPlaylistEmbed () {
703 return window.location.pathname.split('/')[1] === 'video-playlists'
704 }
99941732
WL
705}
706
707PeerTubeEmbed.main()
902aa3a0 708 .catch(err => console.error('Cannot init embed.', err))