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