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