]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blob - client/src/standalone/videos/embed.ts
Add fixme info
[github/Chocobozzz/PeerTube.git] / client / src / standalone / videos / embed.ts
1 import './embed.scss'
2 import videojs from 'video.js'
3 import { peertubeTranslate } from '../../../../shared/core-utils/i18n'
4 import {
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'
17 import { P2PMediaLoaderOptions, PeertubePlayerManagerOptions, PlayerMode } from '../../assets/player/peertube-player-manager'
18 import { VideoJSCaption } from '../../assets/player/peertube-videojs-typings'
19 import { TranslationsManager } from '../../assets/player/translations-manager'
20 import { isP2PEnabled } from '../../assets/player/utils'
21 import { getBoolOrDefault } from '../../root-helpers/local-storage-utils'
22 import { peertubeLocalStorage } from '../../root-helpers/peertube-web-storage'
23 import { PluginsManager } from '../../root-helpers/plugins-manager'
24 import { UserLocalStorageKeys, UserTokens } from '../../root-helpers/users'
25 import { objectToUrlEncoded } from '../../root-helpers/utils'
26 import { RegisterClientHelpers } from '../../types/register-client-option.model'
27 import { PeerTubeEmbedApi } from './embed-api'
28
29 type Translations = { [ id: string ]: string }
30
31 export 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
564 webtorrent: {
565 videoFiles: videoInfo.files
566 },
567
568 pluginsManager: this.pluginsManager
569 }
570
571 if (this.mode === 'p2p-media-loader') {
572 const hlsPlaylist = videoInfo.streamingPlaylists.find(p => p.type === VideoStreamingPlaylistType.HLS)
573
574 Object.assign(options, {
575 p2pMediaLoader: {
576 playlistUrl: hlsPlaylist.playlistUrl,
577 segmentsSha256Url: hlsPlaylist.segmentsSha256Url,
578 redundancyBaseUrls: hlsPlaylist.redundancies.map(r => r.baseUrl),
579 trackerAnnounce: videoInfo.trackerUrls,
580 videoFiles: hlsPlaylist.files
581 } as P2PMediaLoaderOptions
582 })
583 }
584
585 this.player = await PeertubePlayerManager.initialize(this.mode, options, (player: videojs.Player) => {
586 this.player = player
587 })
588
589 this.player.on('customError', (event: any, data: any) => this.handleError(data.err, serverTranslations))
590
591 window['videojsPlayer'] = this.player
592
593 this.buildCSS()
594
595 this.buildDock(videoInfo)
596
597 this.initializeApi()
598
599 this.removePlaceholder()
600
601 if (this.isPlaylistEmbed()) {
602 await this.buildPlaylistManager()
603
604 this.player.playlist().updateSelected()
605
606 this.player.on('stopped', () => {
607 this.playNextVideo()
608 })
609 }
610
611 this.pluginsManager.runHook('action:embed.player.loaded', undefined, { player: this.player, videojs, video: videoInfo })
612 }
613
614 private async initCore () {
615 if (this.userTokens) this.setHeadersFromTokens()
616
617 this.translationsPromise = TranslationsManager.getServerTranslations(window.location.origin, navigator.language)
618 this.PeertubePlayerManagerModulePromise = import('../../assets/player/peertube-player-manager')
619
620 let videoId: string
621
622 if (this.isPlaylistEmbed()) {
623 const playlistId = this.getResourceId()
624 const res = await this.loadPlaylist(playlistId)
625 if (!res) return undefined
626
627 this.playlist = await res.playlistResponse.json()
628
629 const playlistElementResult = await res.videosResponse.json()
630 this.playlistElements = await this.loadAllPlaylistVideos(playlistId, playlistElementResult)
631
632 const params = new URL(window.location.toString()).searchParams
633 const playlistPositionParam = this.getParamString(params, 'playlistPosition')
634
635 let position = 1
636
637 if (playlistPositionParam) {
638 position = parseInt(playlistPositionParam + '', 10)
639 }
640
641 this.currentPlaylistElement = this.playlistElements.find(e => e.position === position)
642 if (!this.currentPlaylistElement || !this.currentPlaylistElement.video) {
643 console.error('Current playlist element is not valid.', this.currentPlaylistElement)
644 this.currentPlaylistElement = this.getNextPlaylistElement()
645 }
646
647 if (!this.currentPlaylistElement) {
648 console.error('This playlist does not have any valid element.')
649 const serverTranslations = await this.translationsPromise
650 this.playlistFetchError(serverTranslations)
651 return
652 }
653
654 videoId = this.currentPlaylistElement.video.uuid
655 } else {
656 videoId = this.getResourceId()
657 }
658
659 return this.loadVideoAndBuildPlayer(videoId)
660 }
661
662 private handleError (err: Error, translations?: { [ id: string ]: string }) {
663 if (err.message.includes('from xs param')) {
664 this.player.dispose()
665 this.playerElement = null
666 this.displayError('This video is not available because the remote instance is not responding.', translations)
667
668 }
669 }
670
671 private buildDock (videoInfo: VideoDetails) {
672 if (!this.controls) return
673
674 // On webtorrent fallback, player may have been disposed
675 if (!this.player.player_) return
676
677 const title = this.title ? videoInfo.name : undefined
678
679 const description = this.warningTitle && this.p2pEnabled
680 ? '<span class="text">' + peertubeTranslate('Watching this video may reveal your IP address to others.') + '</span>'
681 : undefined
682
683 if (title || description) {
684 this.player.dock({
685 title,
686 description
687 })
688 }
689 }
690
691 private buildCSS () {
692 const body = document.getElementById('custom-css')
693
694 if (this.bigPlayBackgroundColor) {
695 body.style.setProperty('--embedBigPlayBackgroundColor', this.bigPlayBackgroundColor)
696 }
697
698 if (this.foregroundColor) {
699 body.style.setProperty('--embedForegroundColor', this.foregroundColor)
700 }
701 }
702
703 private async buildCaptions (serverTranslations: any, captionsResponse: Response): Promise<VideoJSCaption[]> {
704 if (captionsResponse.ok) {
705 const { data } = await captionsResponse.json()
706
707 return data.map((c: VideoCaption) => ({
708 label: peertubeTranslate(c.language.label, serverTranslations),
709 language: c.language.id,
710 src: window.location.origin + c.captionPath
711 }))
712 }
713
714 return []
715 }
716
717 private loadPlaceholder (video: VideoDetails) {
718 const placeholder = this.getPlaceholderElement()
719
720 const url = window.location.origin + video.previewPath
721 placeholder.style.backgroundImage = `url("${url}")`
722 placeholder.style.display = 'block'
723 }
724
725 private removePlaceholder () {
726 const placeholder = this.getPlaceholderElement()
727 placeholder.style.display = 'none'
728 }
729
730 private getPlaceholderElement () {
731 return document.getElementById('placeholder-preview')
732 }
733
734 private setHeadersFromTokens () {
735 this.headers.set('Authorization', `${this.userTokens.tokenType} ${this.userTokens.accessToken}`)
736 }
737
738 private removeTokensFromHeaders () {
739 this.headers.delete('Authorization')
740 }
741
742 private getResourceId () {
743 const urlParts = window.location.pathname.split('/')
744 return urlParts[urlParts.length - 1]
745 }
746
747 private isPlaylistEmbed () {
748 return window.location.pathname.split('/')[1] === 'video-playlists'
749 }
750
751 private loadPlugins (translations?: { [ id: string ]: string }) {
752 this.pluginsManager = new PluginsManager({
753 peertubeHelpersFactory: _ => this.buildPeerTubeHelpers(translations)
754 })
755
756 this.pluginsManager.loadPluginsList(this.config)
757
758 return this.pluginsManager.ensurePluginsAreLoaded('embed')
759 }
760
761 private buildPeerTubeHelpers (translations?: { [ id: string ]: string }): RegisterClientHelpers {
762 const unimplemented = () => {
763 throw new Error('This helper is not implemented in embed.')
764 }
765
766 return {
767 getBaseStaticRoute: unimplemented,
768 getBaseRouterRoute: unimplemented,
769 getBasePluginClientPath: unimplemented,
770
771 getSettings: unimplemented,
772
773 isLoggedIn: unimplemented,
774 getAuthHeader: unimplemented,
775
776 notifier: {
777 info: unimplemented,
778 error: unimplemented,
779 success: unimplemented
780 },
781
782 showModal: unimplemented,
783
784 getServerConfig: unimplemented,
785
786 markdownRenderer: {
787 textMarkdownToHTML: unimplemented,
788 enhancedMarkdownToHTML: unimplemented
789 },
790
791 translate: (value: string) => Promise.resolve(peertubeTranslate(value, translations))
792 }
793 }
794
795 private isP2PEnabled (video: Video) {
796 const userP2PEnabled = getBoolOrDefault(
797 peertubeLocalStorage.getItem(UserLocalStorageKeys.P2P_ENABLED),
798 this.config.defaults.p2p.embed.enabled
799 )
800
801 return isP2PEnabled(video, this.config, userP2PEnabled)
802 }
803 }
804
805 PeerTubeEmbed.main()
806 .catch(err => {
807 (window as any).displayIncompatibleBrowser()
808
809 console.error('Cannot init embed.', err)
810 })