]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blob - client/src/standalone/videos/embed.ts
dc9727049b77a7c4730f540f3516222518480bbb
[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 { HttpStatusCode } from '../../../../shared/core-utils/miscs/http-error-codes'
5 import {
6 HTMLServerConfig,
7 OAuth2ErrorCode,
8 PluginType,
9 ResultList,
10 UserRefreshToken,
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 { peertubeLocalStorage } from '../../root-helpers/peertube-web-storage'
21 import { PluginsManager } from '../../root-helpers/plugins-manager'
22 import { Tokens } from '../../root-helpers/users'
23 import { objectToUrlEncoded } from '../../root-helpers/utils'
24 import { RegisterClientHelpers } from '../../types/register-client-option.model'
25 import { PeerTubeEmbedApi } from './embed-api'
26
27 type Translations = { [ id: string ]: string }
28
29 export class PeerTubeEmbed {
30 playerElement: HTMLVideoElement
31 player: videojs.Player
32 api: PeerTubeEmbedApi = null
33
34 autoplay: boolean
35 controls: boolean
36 muted: boolean
37 loop: boolean
38 subtitle: string
39 enableApi = false
40 startTime: number | string = 0
41 stopTime: number | string
42
43 title: boolean
44 warningTitle: boolean
45 peertubeLink: boolean
46 bigPlayBackgroundColor: string
47 foregroundColor: string
48
49 mode: PlayerMode
50 scope = 'peertube'
51
52 userTokens: Tokens
53 headers = new Headers()
54 LOCAL_STORAGE_OAUTH_CLIENT_KEYS = {
55 CLIENT_ID: 'client_id',
56 CLIENT_SECRET: 'client_secret'
57 }
58
59 config: HTMLServerConfig
60
61 private translationsPromise: Promise<{ [id: string]: string }>
62 private PeertubePlayerManagerModulePromise: Promise<any>
63
64 private playlist: VideoPlaylist
65 private playlistElements: VideoPlaylistElement[]
66 private currentPlaylistElement: VideoPlaylistElement
67
68 private wrapperElement: HTMLElement
69
70 private pluginsManager: PluginsManager
71
72 static async main () {
73 const videoContainerId = 'video-wrapper'
74 const embed = new PeerTubeEmbed(videoContainerId)
75 await embed.init()
76 }
77
78 constructor (private 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 getVideoUrl (id: string) {
89 return window.location.origin + '/api/v1/videos/' + id
90 }
91
92 refreshFetch (url: string, options?: RequestInit) {
93 return fetch(url, options)
94 .then((res: Response) => {
95 if (res.status !== HttpStatusCode.UNAUTHORIZED_401) return res
96
97 const refreshingTokenPromise = new Promise<void>((resolve, reject) => {
98 const clientId: string = peertubeLocalStorage.getItem(this.LOCAL_STORAGE_OAUTH_CLIENT_KEYS.CLIENT_ID)
99 const clientSecret: string = peertubeLocalStorage.getItem(this.LOCAL_STORAGE_OAUTH_CLIENT_KEYS.CLIENT_SECRET)
100
101 const headers = new Headers()
102 headers.set('Content-Type', 'application/x-www-form-urlencoded')
103
104 const data = {
105 refresh_token: this.userTokens.refreshToken,
106 client_id: clientId,
107 client_secret: clientSecret,
108 response_type: 'code',
109 grant_type: 'refresh_token'
110 }
111
112 fetch('/api/v1/users/token', {
113 headers,
114 method: 'POST',
115 body: objectToUrlEncoded(data)
116 }).then(res => {
117 if (res.status === HttpStatusCode.UNAUTHORIZED_401) return undefined
118
119 return res.json()
120 }).then((obj: UserRefreshToken & { code?: OAuth2ErrorCode }) => {
121 if (!obj || obj.code === OAuth2ErrorCode.INVALID_GRANT) {
122 Tokens.flush()
123 this.removeTokensFromHeaders()
124
125 return resolve()
126 }
127
128 this.userTokens.accessToken = obj.access_token
129 this.userTokens.refreshToken = obj.refresh_token
130 this.userTokens.save()
131
132 this.setHeadersFromTokens()
133
134 resolve()
135 }).catch((refreshTokenError: any) => {
136 reject(refreshTokenError)
137 })
138 })
139
140 return refreshingTokenPromise
141 .catch(() => {
142 Tokens.flush()
143
144 this.removeTokensFromHeaders()
145 }).then(() => fetch(url, {
146 ...options,
147 headers: this.headers
148 }))
149 })
150 }
151
152 getPlaylistUrl (id: string) {
153 return window.location.origin + '/api/v1/video-playlists/' + id
154 }
155
156 loadVideoInfo (videoId: string): Promise<Response> {
157 return this.refreshFetch(this.getVideoUrl(videoId), { headers: this.headers })
158 }
159
160 loadVideoCaptions (videoId: string): Promise<Response> {
161 return this.refreshFetch(this.getVideoUrl(videoId) + '/captions', { headers: this.headers })
162 }
163
164 loadPlaylistInfo (playlistId: string): Promise<Response> {
165 return this.refreshFetch(this.getPlaylistUrl(playlistId), { headers: this.headers })
166 }
167
168 loadPlaylistElements (playlistId: string, start = 0): Promise<Response> {
169 const url = new URL(this.getPlaylistUrl(playlistId) + '/videos')
170 url.search = new URLSearchParams({ start: '' + start, count: '100' }).toString()
171
172 return this.refreshFetch(url.toString(), { headers: this.headers })
173 }
174
175 removeElement (element: HTMLElement) {
176 element.parentElement.removeChild(element)
177 }
178
179 displayError (text: string, translations?: Translations) {
180 // Remove video element
181 if (this.playerElement) {
182 this.removeElement(this.playerElement)
183 this.playerElement = undefined
184 }
185
186 const translatedText = peertubeTranslate(text, translations)
187 const translatedSorry = peertubeTranslate('Sorry', translations)
188
189 document.title = translatedSorry + ' - ' + translatedText
190
191 const errorBlock = document.getElementById('error-block')
192 errorBlock.style.display = 'flex'
193
194 const errorTitle = document.getElementById('error-title')
195 errorTitle.innerHTML = peertubeTranslate('Sorry', translations)
196
197 const errorText = document.getElementById('error-content')
198 errorText.innerHTML = translatedText
199
200 this.wrapperElement.style.display = 'none'
201 }
202
203 videoNotFound (translations?: Translations) {
204 const text = 'This video does not exist.'
205 this.displayError(text, translations)
206 }
207
208 videoFetchError (translations?: Translations) {
209 const text = 'We cannot fetch the video. Please try again later.'
210 this.displayError(text, translations)
211 }
212
213 playlistNotFound (translations?: Translations) {
214 const text = 'This playlist does not exist.'
215 this.displayError(text, translations)
216 }
217
218 playlistFetchError (translations?: Translations) {
219 const text = 'We cannot fetch the playlist. Please try again later.'
220 this.displayError(text, translations)
221 }
222
223 getParamToggle (params: URLSearchParams, name: string, defaultValue?: boolean) {
224 return params.has(name) ? (params.get(name) === '1' || params.get(name) === 'true') : defaultValue
225 }
226
227 getParamString (params: URLSearchParams, name: string, defaultValue?: string) {
228 return params.has(name) ? params.get(name) : defaultValue
229 }
230
231 async playNextVideo () {
232 const next = this.getNextPlaylistElement()
233 if (!next) {
234 console.log('Next element not found in playlist.')
235 return
236 }
237
238 this.currentPlaylistElement = next
239
240 return this.loadVideoAndBuildPlayer(this.currentPlaylistElement.video.uuid)
241 }
242
243 async playPreviousVideo () {
244 const previous = this.getPreviousPlaylistElement()
245 if (!previous) {
246 console.log('Previous element not found in playlist.')
247 return
248 }
249
250 this.currentPlaylistElement = previous
251
252 await this.loadVideoAndBuildPlayer(this.currentPlaylistElement.video.uuid)
253 }
254
255 getCurrentPosition () {
256 if (!this.currentPlaylistElement) return -1
257
258 return this.currentPlaylistElement.position
259 }
260
261 async init () {
262 try {
263 this.userTokens = Tokens.load()
264 await this.initCore()
265 } catch (e) {
266 console.error(e)
267 }
268 }
269
270 private initializeApi () {
271 if (!this.enableApi) return
272
273 this.api = new PeerTubeEmbedApi(this)
274 this.api.initialize()
275 }
276
277 private loadParams (video: VideoDetails) {
278 try {
279 const params = new URL(window.location.toString()).searchParams
280
281 this.autoplay = this.getParamToggle(params, 'autoplay', false)
282 this.controls = this.getParamToggle(params, 'controls', true)
283 this.muted = this.getParamToggle(params, 'muted', undefined)
284 this.loop = this.getParamToggle(params, 'loop', false)
285 this.title = this.getParamToggle(params, 'title', true)
286 this.enableApi = this.getParamToggle(params, 'api', this.enableApi)
287 this.warningTitle = this.getParamToggle(params, 'warningTitle', true)
288 this.peertubeLink = this.getParamToggle(params, 'peertubeLink', true)
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() as ResultList<VideoPlaylistElement>
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 if (!alreadyHadPlayer) this.loadPlaceholder(videoInfo)
479
480 return videoInfo
481 })
482
483 const [ videoInfoTmp, serverTranslations, captionsResponse, PeertubePlayerManagerModule ] = await Promise.all([
484 videoInfoPromise,
485 this.translationsPromise,
486 captionsPromise,
487 this.PeertubePlayerManagerModulePromise
488 ])
489
490 await this.loadPlugins(serverTranslations)
491
492 const videoInfo: VideoDetails = videoInfoTmp
493
494 const PeertubePlayerManager = PeertubePlayerManagerModule.PeertubePlayerManager
495 const videoCaptions = await this.buildCaptions(serverTranslations, captionsResponse)
496
497 this.loadParams(videoInfo)
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 captions: videoCaptions.length !== 0,
524 subtitle: this.subtitle,
525
526 startTime: this.playlist ? this.currentPlaylistElement.startTimestamp : this.startTime,
527 stopTime: this.playlist ? this.currentPlaylistElement.stopTimestamp : this.stopTime,
528
529 nextVideo: this.playlist ? () => this.playNextVideo() : undefined,
530 hasNextVideo: this.playlist ? () => !!this.getNextPlaylistElement() : undefined,
531
532 previousVideo: this.playlist ? () => this.playPreviousVideo() : undefined,
533 hasPreviousVideo: this.playlist ? () => !!this.getPreviousPlaylistElement() : undefined,
534
535 playlist: playlistPlugin,
536
537 videoCaptions,
538 inactivityTimeout: 2500,
539 videoViewUrl: this.getVideoUrl(videoInfo.uuid) + '/views',
540 videoUUID: videoInfo.uuid,
541
542 isLive: videoInfo.isLive,
543
544 playerElement: this.playerElement,
545 onPlayerElementChange: (element: HTMLVideoElement) => this.playerElement = element,
546
547 videoDuration: videoInfo.duration,
548 enableHotkeys: true,
549 peertubeLink: this.peertubeLink,
550 poster: window.location.origin + videoInfo.previewPath,
551 theaterButton: false,
552
553 serverUrl: window.location.origin,
554 language: navigator.language,
555 embedUrl: window.location.origin + videoInfo.embedPath,
556 embedTitle: videoInfo.name
557 },
558
559 webtorrent: {
560 videoFiles: videoInfo.files
561 },
562
563 pluginsManager: this.pluginsManager
564 }
565
566 if (this.mode === 'p2p-media-loader') {
567 const hlsPlaylist = videoInfo.streamingPlaylists.find(p => p.type === VideoStreamingPlaylistType.HLS)
568
569 Object.assign(options, {
570 p2pMediaLoader: {
571 playlistUrl: hlsPlaylist.playlistUrl,
572 segmentsSha256Url: hlsPlaylist.segmentsSha256Url,
573 redundancyBaseUrls: hlsPlaylist.redundancies.map(r => r.baseUrl),
574 trackerAnnounce: videoInfo.trackerUrls,
575 videoFiles: hlsPlaylist.files
576 } as P2PMediaLoaderOptions
577 })
578 }
579
580 this.player = await PeertubePlayerManager.initialize(this.mode, options, (player: videojs.Player) => this.player = player)
581 this.player.on('customError', (event: any, data: any) => this.handleError(data.err, serverTranslations))
582
583 window[ 'videojsPlayer' ] = this.player
584
585 this.buildCSS()
586
587 await this.buildDock(videoInfo)
588
589 this.initializeApi()
590
591 this.removePlaceholder()
592
593 if (this.isPlaylistEmbed()) {
594 await this.buildPlaylistManager()
595
596 this.player.playlist().updateSelected()
597
598 this.player.on('stopped', () => {
599 this.playNextVideo()
600 })
601 }
602
603 this.pluginsManager.runHook('action:embed.player.loaded', undefined, { player: this.player, videojs, video: videoInfo })
604 }
605
606 private async initCore () {
607 if (this.userTokens) this.setHeadersFromTokens()
608
609 this.translationsPromise = TranslationsManager.getServerTranslations(window.location.origin, navigator.language)
610 this.PeertubePlayerManagerModulePromise = import('../../assets/player/peertube-player-manager')
611
612 let videoId: string
613
614 if (this.isPlaylistEmbed()) {
615 const playlistId = this.getResourceId()
616 const res = await this.loadPlaylist(playlistId)
617 if (!res) return undefined
618
619 this.playlist = await res.playlistResponse.json()
620
621 const playlistElementResult = await res.videosResponse.json()
622 this.playlistElements = await this.loadAllPlaylistVideos(playlistId, playlistElementResult)
623
624 const params = new URL(window.location.toString()).searchParams
625 const playlistPositionParam = this.getParamString(params, 'playlistPosition')
626
627 let position = 1
628
629 if (playlistPositionParam) {
630 position = parseInt(playlistPositionParam + '', 10)
631 }
632
633 this.currentPlaylistElement = this.playlistElements.find(e => e.position === position)
634 if (!this.currentPlaylistElement || !this.currentPlaylistElement.video) {
635 console.error('Current playlist element is not valid.', this.currentPlaylistElement)
636 this.currentPlaylistElement = this.getNextPlaylistElement()
637 }
638
639 if (!this.currentPlaylistElement) {
640 console.error('This playlist does not have any valid element.')
641 const serverTranslations = await this.translationsPromise
642 this.playlistFetchError(serverTranslations)
643 return
644 }
645
646 videoId = this.currentPlaylistElement.video.uuid
647 } else {
648 videoId = this.getResourceId()
649 }
650
651 return this.loadVideoAndBuildPlayer(videoId)
652 }
653
654 private handleError (err: Error, translations?: { [ id: string ]: string }) {
655 if (err.message.indexOf('from xs param') !== -1) {
656 this.player.dispose()
657 this.playerElement = null
658 this.displayError('This video is not available because the remote instance is not responding.', translations)
659 return
660 }
661 }
662
663 private async buildDock (videoInfo: VideoDetails) {
664 if (!this.controls) return
665
666 // On webtorrent fallback, player may have been disposed
667 if (!this.player.player_) return
668
669 const title = this.title ? videoInfo.name : undefined
670
671 const description = this.config.tracker.enabled && this.warningTitle
672 ? '<span class="text">' + peertubeTranslate('Watching this video may reveal your IP address to others.') + '</span>'
673 : undefined
674
675 if (title || description) {
676 this.player.dock({
677 title,
678 description
679 })
680 }
681 }
682
683 private buildCSS () {
684 const body = document.getElementById('custom-css')
685
686 if (this.bigPlayBackgroundColor) {
687 body.style.setProperty('--embedBigPlayBackgroundColor', this.bigPlayBackgroundColor)
688 }
689
690 if (this.foregroundColor) {
691 body.style.setProperty('--embedForegroundColor', this.foregroundColor)
692 }
693 }
694
695 private async buildCaptions (serverTranslations: any, captionsResponse: Response): Promise<VideoJSCaption[]> {
696 if (captionsResponse.ok) {
697 const { data } = (await captionsResponse.json()) as ResultList<VideoCaption>
698
699 return data.map(c => ({
700 label: peertubeTranslate(c.language.label, serverTranslations),
701 language: c.language.id,
702 src: window.location.origin + c.captionPath
703 }))
704 }
705
706 return []
707 }
708
709 private loadPlaceholder (video: VideoDetails) {
710 const placeholder = this.getPlaceholderElement()
711
712 const url = window.location.origin + video.previewPath
713 placeholder.style.backgroundImage = `url("${url}")`
714 placeholder.style.display = 'block'
715 }
716
717 private removePlaceholder () {
718 const placeholder = this.getPlaceholderElement()
719 placeholder.style.display = 'none'
720 }
721
722 private getPlaceholderElement () {
723 return document.getElementById('placeholder-preview')
724 }
725
726 private setHeadersFromTokens () {
727 this.headers.set('Authorization', `${this.userTokens.tokenType} ${this.userTokens.accessToken}`)
728 }
729
730 private removeTokensFromHeaders () {
731 this.headers.delete('Authorization')
732 }
733
734 private getResourceId () {
735 const urlParts = window.location.pathname.split('/')
736 return urlParts[ urlParts.length - 1 ]
737 }
738
739 private isPlaylistEmbed () {
740 return window.location.pathname.split('/')[1] === 'video-playlists'
741 }
742
743 private loadPlugins (translations?: { [ id: string ]: string }) {
744 this.pluginsManager = new PluginsManager({
745 peertubeHelpersFactory: _ => this.buildPeerTubeHelpers(translations)
746 })
747
748 this.pluginsManager.loadPluginsList(this.config)
749
750 return this.pluginsManager.ensurePluginsAreLoaded('embed')
751 }
752
753 private buildPeerTubeHelpers (translations?: { [ id: string ]: string }): RegisterClientHelpers {
754 function unimplemented (): any {
755 throw new Error('This helper is not implemented in embed.')
756 }
757
758 return {
759 getBaseStaticRoute: unimplemented,
760
761 getBaseRouterRoute: unimplemented,
762
763 getSettings: unimplemented,
764
765 isLoggedIn: unimplemented,
766 getAuthHeader: unimplemented,
767
768 notifier: {
769 info: unimplemented,
770 error: unimplemented,
771 success: unimplemented
772 },
773
774 showModal: unimplemented,
775
776 getServerConfig: unimplemented,
777
778 markdownRenderer: {
779 textMarkdownToHTML: unimplemented,
780 enhancedMarkdownToHTML: unimplemented
781 },
782
783 translate: (value: string) => {
784 return Promise.resolve(peertubeTranslate(value, translations))
785 }
786 }
787 }
788 }
789
790 PeerTubeEmbed.main()
791 .catch(err => console.error('Cannot init embed.', err))