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