]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blob - client/src/standalone/videos/embed.ts
Add latency setting support
[github/Chocobozzz/PeerTube.git] / client / src / standalone / videos / embed.ts
1 import './embed.scss'
2 import '../../assets/player/dock/peertube-dock-component'
3 import '../../assets/player/dock/peertube-dock-plugin'
4 import videojs from 'video.js'
5 import { peertubeTranslate } from '../../../../shared/core-utils/i18n'
6 import {
7 HTMLServerConfig,
8 HttpStatusCode,
9 LiveVideo,
10 OAuth2ErrorCode,
11 ResultList,
12 UserRefreshToken,
13 Video,
14 VideoCaption,
15 VideoDetails,
16 VideoPlaylist,
17 VideoPlaylistElement,
18 VideoStreamingPlaylistType
19 } from '../../../../shared/models'
20 import { P2PMediaLoaderOptions, PeertubePlayerManagerOptions, PlayerMode } from '../../assets/player'
21 import { VideoJSCaption } from '../../assets/player/peertube-videojs-typings'
22 import { TranslationsManager } from '../../assets/player/translations-manager'
23 import { isP2PEnabled } from '../../assets/player/utils'
24 import { getBoolOrDefault } from '../../root-helpers/local-storage-utils'
25 import { peertubeLocalStorage } from '../../root-helpers/peertube-web-storage'
26 import { PluginsManager } from '../../root-helpers/plugins-manager'
27 import { UserLocalStorageKeys, UserTokens } from '../../root-helpers/users'
28 import { objectToUrlEncoded } from '../../root-helpers/utils'
29 import { RegisterClientHelpers } from '../../types/register-client-option.model'
30 import { PeerTubeEmbedApi } from './embed-api'
31
32 type Translations = { [ id: string ]: string }
33
34 export class PeerTubeEmbed {
35 playerElement: HTMLVideoElement
36 player: videojs.Player
37 api: PeerTubeEmbedApi = null
38
39 autoplay: boolean
40 controls: boolean
41 muted: boolean
42 loop: boolean
43 subtitle: string
44 enableApi = false
45 startTime: number | string = 0
46 stopTime: number | string
47
48 title: boolean
49 warningTitle: boolean
50 peertubeLink: boolean
51 p2pEnabled: boolean
52 bigPlayBackgroundColor: string
53 foregroundColor: string
54
55 mode: PlayerMode
56 scope = 'peertube'
57
58 userTokens: UserTokens
59 headers = new Headers()
60 LOCAL_STORAGE_OAUTH_CLIENT_KEYS = {
61 CLIENT_ID: 'client_id',
62 CLIENT_SECRET: 'client_secret'
63 }
64
65 config: HTMLServerConfig
66
67 private translationsPromise: Promise<{ [id: string]: string }>
68 private PeertubePlayerManagerModulePromise: Promise<any>
69
70 private playlist: VideoPlaylist
71 private playlistElements: VideoPlaylistElement[]
72 private currentPlaylistElement: VideoPlaylistElement
73
74 private readonly wrapperElement: HTMLElement
75
76 private pluginsManager: PluginsManager
77
78 constructor (private readonly videoWrapperId: string) {
79 this.wrapperElement = document.getElementById(this.videoWrapperId)
80
81 try {
82 this.config = JSON.parse(window['PeerTubeServerConfig'])
83 } catch (err) {
84 console.error('Cannot parse HTML config.', err)
85 }
86 }
87
88 static async main () {
89 const videoContainerId = 'video-wrapper'
90 const embed = new PeerTubeEmbed(videoContainerId)
91 await embed.init()
92 }
93
94 getVideoUrl (id: string) {
95 return window.location.origin + '/api/v1/videos/' + id
96 }
97
98 getLiveUrl (videoId: string) {
99 return window.location.origin + '/api/v1/videos/live/' + videoId
100 }
101
102 refreshFetch (url: string, options?: RequestInit) {
103 return fetch(url, options)
104 .then((res: Response) => {
105 if (res.status !== HttpStatusCode.UNAUTHORIZED_401) return res
106
107 const refreshingTokenPromise = new Promise<void>((resolve, reject) => {
108 const clientId: string = peertubeLocalStorage.getItem(this.LOCAL_STORAGE_OAUTH_CLIENT_KEYS.CLIENT_ID)
109 const clientSecret: string = peertubeLocalStorage.getItem(this.LOCAL_STORAGE_OAUTH_CLIENT_KEYS.CLIENT_SECRET)
110
111 const headers = new Headers()
112 headers.set('Content-Type', 'application/x-www-form-urlencoded')
113
114 const data = {
115 refresh_token: this.userTokens.refreshToken,
116 client_id: clientId,
117 client_secret: clientSecret,
118 response_type: 'code',
119 grant_type: 'refresh_token'
120 }
121
122 fetch('/api/v1/users/token', {
123 headers,
124 method: 'POST',
125 body: objectToUrlEncoded(data)
126 }).then(res => {
127 if (res.status === HttpStatusCode.UNAUTHORIZED_401) return undefined
128
129 return res.json()
130 }).then((obj: UserRefreshToken & { code?: OAuth2ErrorCode }) => {
131 if (!obj || obj.code === OAuth2ErrorCode.INVALID_GRANT) {
132 UserTokens.flushLocalStorage(peertubeLocalStorage)
133 this.removeTokensFromHeaders()
134
135 return resolve()
136 }
137
138 this.userTokens.accessToken = obj.access_token
139 this.userTokens.refreshToken = obj.refresh_token
140 UserTokens.saveToLocalStorage(peertubeLocalStorage, this.userTokens)
141
142 this.setHeadersFromTokens()
143
144 resolve()
145 }).catch((refreshTokenError: any) => {
146 reject(refreshTokenError)
147 })
148 })
149
150 return refreshingTokenPromise
151 .catch(() => {
152 UserTokens.flushLocalStorage(peertubeLocalStorage)
153
154 this.removeTokensFromHeaders()
155 }).then(() => fetch(url, {
156 ...options,
157 headers: this.headers
158 }))
159 })
160 }
161
162 getPlaylistUrl (id: string) {
163 return window.location.origin + '/api/v1/video-playlists/' + id
164 }
165
166 loadVideoInfo (videoId: string): Promise<Response> {
167 return this.refreshFetch(this.getVideoUrl(videoId), { headers: this.headers })
168 }
169
170 loadVideoCaptions (videoId: string): Promise<Response> {
171 return this.refreshFetch(this.getVideoUrl(videoId) + '/captions', { headers: this.headers })
172 }
173
174 loadWithLive (video: VideoDetails) {
175 return this.refreshFetch(this.getLiveUrl(video.uuid), { headers: this.headers })
176 .then(res => res.json())
177 .then((live: LiveVideo) => ({ video, live }))
178 }
179
180 loadPlaylistInfo (playlistId: string): Promise<Response> {
181 return this.refreshFetch(this.getPlaylistUrl(playlistId), { headers: this.headers })
182 }
183
184 loadPlaylistElements (playlistId: string, start = 0): Promise<Response> {
185 const url = new URL(this.getPlaylistUrl(playlistId) + '/videos')
186 url.search = new URLSearchParams({ start: '' + start, count: '100' }).toString()
187
188 return this.refreshFetch(url.toString(), { headers: this.headers })
189 }
190
191 removeElement (element: HTMLElement) {
192 element.parentElement.removeChild(element)
193 }
194
195 displayError (text: string, translations?: Translations) {
196 // Remove video element
197 if (this.playerElement) {
198 this.removeElement(this.playerElement)
199 this.playerElement = undefined
200 }
201
202 const translatedText = peertubeTranslate(text, translations)
203 const translatedSorry = peertubeTranslate('Sorry', translations)
204
205 document.title = translatedSorry + ' - ' + translatedText
206
207 const errorBlock = document.getElementById('error-block')
208 errorBlock.style.display = 'flex'
209
210 const errorTitle = document.getElementById('error-title')
211 errorTitle.innerHTML = peertubeTranslate('Sorry', translations)
212
213 const errorText = document.getElementById('error-content')
214 errorText.innerHTML = translatedText
215
216 this.wrapperElement.style.display = 'none'
217 }
218
219 videoNotFound (translations?: Translations) {
220 const text = 'This video does not exist.'
221 this.displayError(text, translations)
222 }
223
224 videoFetchError (translations?: Translations) {
225 const text = 'We cannot fetch the video. Please try again later.'
226 this.displayError(text, translations)
227 }
228
229 playlistNotFound (translations?: Translations) {
230 const text = 'This playlist does not exist.'
231 this.displayError(text, translations)
232 }
233
234 playlistFetchError (translations?: Translations) {
235 const text = 'We cannot fetch the playlist. Please try again later.'
236 this.displayError(text, translations)
237 }
238
239 getParamToggle (params: URLSearchParams, name: string, defaultValue?: boolean) {
240 return params.has(name) ? (params.get(name) === '1' || params.get(name) === 'true') : defaultValue
241 }
242
243 getParamString (params: URLSearchParams, name: string, defaultValue?: string) {
244 return params.has(name) ? params.get(name) : defaultValue
245 }
246
247 async playNextVideo () {
248 const next = this.getNextPlaylistElement()
249 if (!next) {
250 console.log('Next element not found in playlist.')
251 return
252 }
253
254 this.currentPlaylistElement = next
255
256 return this.loadVideoAndBuildPlayer(this.currentPlaylistElement.video.uuid)
257 }
258
259 async playPreviousVideo () {
260 const previous = this.getPreviousPlaylistElement()
261 if (!previous) {
262 console.log('Previous element not found in playlist.')
263 return
264 }
265
266 this.currentPlaylistElement = previous
267
268 await this.loadVideoAndBuildPlayer(this.currentPlaylistElement.video.uuid)
269 }
270
271 getCurrentPosition () {
272 if (!this.currentPlaylistElement) return -1
273
274 return this.currentPlaylistElement.position
275 }
276
277 async init () {
278 this.userTokens = UserTokens.getUserTokens(peertubeLocalStorage)
279 await this.initCore()
280 }
281
282 private initializeApi () {
283 if (!this.enableApi) return
284
285 this.api = new PeerTubeEmbedApi(this)
286 this.api.initialize()
287 }
288
289 private loadParams (video: VideoDetails) {
290 try {
291 const params = new URL(window.location.toString()).searchParams
292
293 this.autoplay = this.getParamToggle(params, 'autoplay', false)
294 this.controls = this.getParamToggle(params, 'controls', true)
295 this.muted = this.getParamToggle(params, 'muted', undefined)
296 this.loop = this.getParamToggle(params, 'loop', false)
297 this.title = this.getParamToggle(params, 'title', true)
298 this.enableApi = this.getParamToggle(params, 'api', this.enableApi)
299 this.warningTitle = this.getParamToggle(params, 'warningTitle', true)
300 this.peertubeLink = this.getParamToggle(params, 'peertubeLink', true)
301 this.p2pEnabled = this.getParamToggle(params, 'p2p', this.isP2PEnabled(video))
302
303 this.scope = this.getParamString(params, 'scope', this.scope)
304 this.subtitle = this.getParamString(params, 'subtitle')
305 this.startTime = this.getParamString(params, 'start')
306 this.stopTime = this.getParamString(params, 'stop')
307
308 this.bigPlayBackgroundColor = this.getParamString(params, 'bigPlayBackgroundColor')
309 this.foregroundColor = this.getParamString(params, 'foregroundColor')
310
311 const modeParam = this.getParamString(params, 'mode')
312
313 if (modeParam) {
314 if (modeParam === 'p2p-media-loader') this.mode = 'p2p-media-loader'
315 else this.mode = 'webtorrent'
316 } else {
317 if (Array.isArray(video.streamingPlaylists) && video.streamingPlaylists.length !== 0) this.mode = 'p2p-media-loader'
318 else this.mode = 'webtorrent'
319 }
320 } catch (err) {
321 console.error('Cannot get params from URL.', err)
322 }
323 }
324
325 private async loadAllPlaylistVideos (playlistId: string, baseResult: ResultList<VideoPlaylistElement>) {
326 let elements = baseResult.data
327 let total = baseResult.total
328 let i = 0
329
330 while (total > elements.length && i < 10) {
331 const result = await this.loadPlaylistElements(playlistId, elements.length)
332
333 const json = await result.json()
334 total = json.total
335
336 elements = elements.concat(json.data)
337 i++
338 }
339
340 if (i === 10) {
341 console.error('Cannot fetch all playlists elements, there are too many!')
342 }
343
344 return elements
345 }
346
347 private async loadPlaylist (playlistId: string) {
348 const playlistPromise = this.loadPlaylistInfo(playlistId)
349 const playlistElementsPromise = this.loadPlaylistElements(playlistId)
350
351 let playlistResponse: Response
352 let isResponseOk: boolean
353
354 try {
355 playlistResponse = await playlistPromise
356 isResponseOk = playlistResponse.status === HttpStatusCode.OK_200
357 } catch (err) {
358 console.error(err)
359 isResponseOk = false
360 }
361
362 if (!isResponseOk) {
363 const serverTranslations = await this.translationsPromise
364
365 if (playlistResponse?.status === HttpStatusCode.NOT_FOUND_404) {
366 this.playlistNotFound(serverTranslations)
367 return undefined
368 }
369
370 this.playlistFetchError(serverTranslations)
371 return undefined
372 }
373
374 return { playlistResponse, videosResponse: await playlistElementsPromise }
375 }
376
377 private async loadVideo (videoId: string) {
378 const videoPromise = this.loadVideoInfo(videoId)
379
380 let videoResponse: Response
381 let isResponseOk: boolean
382
383 try {
384 videoResponse = await videoPromise
385 isResponseOk = videoResponse.status === HttpStatusCode.OK_200
386 } catch (err) {
387 console.error(err)
388
389 isResponseOk = false
390 }
391
392 if (!isResponseOk) {
393 const serverTranslations = await this.translationsPromise
394
395 if (videoResponse?.status === HttpStatusCode.NOT_FOUND_404) {
396 this.videoNotFound(serverTranslations)
397 return undefined
398 }
399
400 this.videoFetchError(serverTranslations)
401 return undefined
402 }
403
404 const captionsPromise = this.loadVideoCaptions(videoId)
405
406 return { captionsPromise, videoResponse }
407 }
408
409 private async buildPlaylistManager () {
410 const translations = await this.translationsPromise
411
412 this.player.upnext({
413 timeout: 10000, // 10s
414 headText: peertubeTranslate('Up Next', translations),
415 cancelText: peertubeTranslate('Cancel', translations),
416 suspendedText: peertubeTranslate('Autoplay is suspended', translations),
417 getTitle: () => this.nextVideoTitle(),
418 next: () => this.playNextVideo(),
419 condition: () => !!this.getNextPlaylistElement(),
420 suspended: () => false
421 })
422 }
423
424 private async loadVideoAndBuildPlayer (uuid: string) {
425 const res = await this.loadVideo(uuid)
426 if (res === undefined) return
427
428 return this.buildVideoPlayer(res.videoResponse, res.captionsPromise)
429 }
430
431 private nextVideoTitle () {
432 const next = this.getNextPlaylistElement()
433 if (!next) return ''
434
435 return next.video.name
436 }
437
438 private getNextPlaylistElement (position?: number): VideoPlaylistElement {
439 if (!position) position = this.currentPlaylistElement.position + 1
440
441 if (position > this.playlist.videosLength) {
442 return undefined
443 }
444
445 const next = this.playlistElements.find(e => e.position === position)
446
447 if (!next || !next.video) {
448 return this.getNextPlaylistElement(position + 1)
449 }
450
451 return next
452 }
453
454 private getPreviousPlaylistElement (position?: number): VideoPlaylistElement {
455 if (!position) position = this.currentPlaylistElement.position - 1
456
457 if (position < 1) {
458 return undefined
459 }
460
461 const prev = this.playlistElements.find(e => e.position === position)
462
463 if (!prev || !prev.video) {
464 return this.getNextPlaylistElement(position - 1)
465 }
466
467 return prev
468 }
469
470 private async buildVideoPlayer (videoResponse: Response, captionsPromise: Promise<Response>) {
471 let alreadyHadPlayer = false
472
473 if (this.player) {
474 this.player.dispose()
475 alreadyHadPlayer = true
476 }
477
478 this.playerElement = document.createElement('video')
479 this.playerElement.className = 'video-js vjs-peertube-skin'
480 this.playerElement.setAttribute('playsinline', 'true')
481 this.wrapperElement.appendChild(this.playerElement)
482
483 // Issue when we parsed config from HTML, fallback to API
484 if (!this.config) {
485 this.config = await this.refreshFetch('/api/v1/config')
486 .then(res => res.json())
487 }
488
489 const videoInfoPromise: Promise<{ video: VideoDetails, live?: LiveVideo }> = videoResponse.json()
490 .then((videoInfo: VideoDetails) => {
491 this.loadParams(videoInfo)
492
493 if (!alreadyHadPlayer && !this.autoplay) this.buildPlaceholder(videoInfo)
494
495 if (!videoInfo.isLive) return { video: videoInfo }
496
497 return this.loadWithLive(videoInfo)
498 })
499
500 const [ videoInfoTmp, serverTranslations, captionsResponse, PeertubePlayerManagerModule ] = await Promise.all([
501 videoInfoPromise,
502 this.translationsPromise,
503 captionsPromise,
504 this.PeertubePlayerManagerModulePromise
505 ])
506
507 await this.loadPlugins(serverTranslations)
508
509 const { video: videoInfo, live } = videoInfoTmp
510
511 const PeertubePlayerManager = PeertubePlayerManagerModule.PeertubePlayerManager
512 const videoCaptions = await this.buildCaptions(serverTranslations, captionsResponse)
513
514 const liveOptions = videoInfo.isLive
515 ? { latencyMode: live.latencyMode }
516 : undefined
517
518 const playlistPlugin = this.currentPlaylistElement
519 ? {
520 elements: this.playlistElements,
521 playlist: this.playlist,
522
523 getCurrentPosition: () => this.currentPlaylistElement.position,
524
525 onItemClicked: (videoPlaylistElement: VideoPlaylistElement) => {
526 this.currentPlaylistElement = videoPlaylistElement
527
528 this.loadVideoAndBuildPlayer(this.currentPlaylistElement.video.uuid)
529 .catch(err => console.error(err))
530 }
531 }
532 : undefined
533
534 const options: PeertubePlayerManagerOptions = {
535 common: {
536 // Autoplay in playlist mode
537 autoplay: alreadyHadPlayer ? true : this.autoplay,
538 controls: this.controls,
539 muted: this.muted,
540 loop: this.loop,
541
542 p2pEnabled: this.p2pEnabled,
543
544 captions: videoCaptions.length !== 0,
545 subtitle: this.subtitle,
546
547 startTime: this.playlist ? this.currentPlaylistElement.startTimestamp : this.startTime,
548 stopTime: this.playlist ? this.currentPlaylistElement.stopTimestamp : this.stopTime,
549
550 nextVideo: this.playlist ? () => this.playNextVideo() : undefined,
551 hasNextVideo: this.playlist ? () => !!this.getNextPlaylistElement() : undefined,
552
553 previousVideo: this.playlist ? () => this.playPreviousVideo() : undefined,
554 hasPreviousVideo: this.playlist ? () => !!this.getPreviousPlaylistElement() : undefined,
555
556 playlist: playlistPlugin,
557
558 videoCaptions,
559 inactivityTimeout: 2500,
560 videoViewUrl: this.getVideoUrl(videoInfo.uuid) + '/views',
561 videoShortUUID: videoInfo.shortUUID,
562 videoUUID: videoInfo.uuid,
563
564 isLive: videoInfo.isLive,
565 liveOptions,
566
567 playerElement: this.playerElement,
568 onPlayerElementChange: (element: HTMLVideoElement) => {
569 this.playerElement = element
570 },
571
572 videoDuration: videoInfo.duration,
573 enableHotkeys: true,
574 peertubeLink: this.peertubeLink,
575 poster: window.location.origin + videoInfo.previewPath,
576 theaterButton: false,
577
578 serverUrl: window.location.origin,
579 language: navigator.language,
580 embedUrl: window.location.origin + videoInfo.embedPath,
581 embedTitle: videoInfo.name,
582
583 errorNotifier: () => {
584 // Empty, we don't have a notifier in the embed
585 }
586 },
587
588 webtorrent: {
589 videoFiles: videoInfo.files
590 },
591
592 pluginsManager: this.pluginsManager
593 }
594
595 if (this.mode === 'p2p-media-loader') {
596 const hlsPlaylist = videoInfo.streamingPlaylists.find(p => p.type === VideoStreamingPlaylistType.HLS)
597
598 Object.assign(options, {
599 p2pMediaLoader: {
600 playlistUrl: hlsPlaylist.playlistUrl,
601 segmentsSha256Url: hlsPlaylist.segmentsSha256Url,
602 redundancyBaseUrls: hlsPlaylist.redundancies.map(r => r.baseUrl),
603 trackerAnnounce: videoInfo.trackerUrls,
604 videoFiles: hlsPlaylist.files
605 } as P2PMediaLoaderOptions
606 })
607 }
608
609 this.player = await PeertubePlayerManager.initialize(this.mode, options, (player: videojs.Player) => {
610 this.player = player
611 })
612
613 this.player.on('customError', (event: any, data: any) => this.handleError(data.err, serverTranslations))
614
615 window['videojsPlayer'] = this.player
616
617 this.buildCSS()
618
619 this.buildDock(videoInfo)
620
621 this.initializeApi()
622
623 this.removePlaceholder()
624
625 if (this.isPlaylistEmbed()) {
626 await this.buildPlaylistManager()
627
628 this.player.playlist().updateSelected()
629
630 this.player.on('stopped', () => {
631 this.playNextVideo()
632 })
633 }
634
635 this.pluginsManager.runHook('action:embed.player.loaded', undefined, { player: this.player, videojs, video: videoInfo })
636 }
637
638 private async initCore () {
639 if (this.userTokens) this.setHeadersFromTokens()
640
641 this.translationsPromise = TranslationsManager.getServerTranslations(window.location.origin, navigator.language)
642 this.PeertubePlayerManagerModulePromise = import('../../assets/player/peertube-player-manager')
643
644 let videoId: string
645
646 if (this.isPlaylistEmbed()) {
647 const playlistId = this.getResourceId()
648 const res = await this.loadPlaylist(playlistId)
649 if (!res) return undefined
650
651 this.playlist = await res.playlistResponse.json()
652
653 const playlistElementResult = await res.videosResponse.json()
654 this.playlistElements = await this.loadAllPlaylistVideos(playlistId, playlistElementResult)
655
656 const params = new URL(window.location.toString()).searchParams
657 const playlistPositionParam = this.getParamString(params, 'playlistPosition')
658
659 let position = 1
660
661 if (playlistPositionParam) {
662 position = parseInt(playlistPositionParam + '', 10)
663 }
664
665 this.currentPlaylistElement = this.playlistElements.find(e => e.position === position)
666 if (!this.currentPlaylistElement || !this.currentPlaylistElement.video) {
667 console.error('Current playlist element is not valid.', this.currentPlaylistElement)
668 this.currentPlaylistElement = this.getNextPlaylistElement()
669 }
670
671 if (!this.currentPlaylistElement) {
672 console.error('This playlist does not have any valid element.')
673 const serverTranslations = await this.translationsPromise
674 this.playlistFetchError(serverTranslations)
675 return
676 }
677
678 videoId = this.currentPlaylistElement.video.uuid
679 } else {
680 videoId = this.getResourceId()
681 }
682
683 return this.loadVideoAndBuildPlayer(videoId)
684 }
685
686 private handleError (err: Error, translations?: { [ id: string ]: string }) {
687 if (err.message.includes('from xs param')) {
688 this.player.dispose()
689 this.playerElement = null
690 this.displayError('This video is not available because the remote instance is not responding.', translations)
691 }
692 }
693
694 private buildDock (videoInfo: VideoDetails) {
695 if (!this.controls) return
696
697 // On webtorrent fallback, player may have been disposed
698 if (!this.player.player_) return
699
700 const title = this.title ? videoInfo.name : undefined
701 const description = this.warningTitle && this.p2pEnabled
702 ? '<span class="text">' + peertubeTranslate('Watching this video may reveal your IP address to others.') + '</span>'
703 : undefined
704
705 const availableAvatars = videoInfo.channel.avatars.filter(a => a.width < 50)
706 const avatar = availableAvatars.length !== 0
707 ? availableAvatars[0]
708 : undefined
709
710 if (title || description) {
711 this.player.peertubeDock({
712 title,
713 description,
714 avatarUrl: title && avatar
715 ? avatar.path
716 : undefined
717 })
718 }
719 }
720
721 private buildCSS () {
722 const body = document.getElementById('custom-css')
723
724 if (this.bigPlayBackgroundColor) {
725 body.style.setProperty('--embedBigPlayBackgroundColor', this.bigPlayBackgroundColor)
726 }
727
728 if (this.foregroundColor) {
729 body.style.setProperty('--embedForegroundColor', this.foregroundColor)
730 }
731 }
732
733 private async buildCaptions (serverTranslations: any, captionsResponse: Response): Promise<VideoJSCaption[]> {
734 if (captionsResponse.ok) {
735 const { data } = await captionsResponse.json()
736
737 return data.map((c: VideoCaption) => ({
738 label: peertubeTranslate(c.language.label, serverTranslations),
739 language: c.language.id,
740 src: window.location.origin + c.captionPath
741 }))
742 }
743
744 return []
745 }
746
747 private buildPlaceholder (video: VideoDetails) {
748 const placeholder = this.getPlaceholderElement()
749
750 const url = window.location.origin + video.previewPath
751 placeholder.style.backgroundImage = `url("${url}")`
752 placeholder.style.display = 'block'
753 }
754
755 private removePlaceholder () {
756 const placeholder = this.getPlaceholderElement()
757 placeholder.style.display = 'none'
758 }
759
760 private getPlaceholderElement () {
761 return document.getElementById('placeholder-preview')
762 }
763
764 private setHeadersFromTokens () {
765 this.headers.set('Authorization', `${this.userTokens.tokenType} ${this.userTokens.accessToken}`)
766 }
767
768 private removeTokensFromHeaders () {
769 this.headers.delete('Authorization')
770 }
771
772 private getResourceId () {
773 const urlParts = window.location.pathname.split('/')
774 return urlParts[urlParts.length - 1]
775 }
776
777 private isPlaylistEmbed () {
778 return window.location.pathname.split('/')[1] === 'video-playlists'
779 }
780
781 private loadPlugins (translations?: { [ id: string ]: string }) {
782 this.pluginsManager = new PluginsManager({
783 peertubeHelpersFactory: _ => this.buildPeerTubeHelpers(translations)
784 })
785
786 this.pluginsManager.loadPluginsList(this.config)
787
788 return this.pluginsManager.ensurePluginsAreLoaded('embed')
789 }
790
791 private buildPeerTubeHelpers (translations?: { [ id: string ]: string }): RegisterClientHelpers {
792 const unimplemented = () => {
793 throw new Error('This helper is not implemented in embed.')
794 }
795
796 return {
797 getBaseStaticRoute: unimplemented,
798 getBaseRouterRoute: unimplemented,
799 getBasePluginClientPath: unimplemented,
800
801 getSettings: unimplemented,
802
803 isLoggedIn: unimplemented,
804 getAuthHeader: unimplemented,
805
806 notifier: {
807 info: unimplemented,
808 error: unimplemented,
809 success: unimplemented
810 },
811
812 showModal: unimplemented,
813
814 getServerConfig: unimplemented,
815
816 markdownRenderer: {
817 textMarkdownToHTML: unimplemented,
818 enhancedMarkdownToHTML: unimplemented
819 },
820
821 translate: (value: string) => Promise.resolve(peertubeTranslate(value, translations))
822 }
823 }
824
825 private isP2PEnabled (video: Video) {
826 const userP2PEnabled = getBoolOrDefault(
827 peertubeLocalStorage.getItem(UserLocalStorageKeys.P2P_ENABLED),
828 this.config.defaults.p2p.embed.enabled
829 )
830
831 return isP2PEnabled(video, this.config, userP2PEnabled)
832 }
833 }
834
835 PeerTubeEmbed.main()
836 .catch(err => {
837 (window as any).displayIncompatibleBrowser()
838
839 console.error('Cannot init embed.', err)
840 })