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