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