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