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