2 import videojs from 'video.js'
3 import { peertubeTranslate } from '../../../../shared/core-utils/i18n'
12 VideoStreamingPlaylistType,
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'
26 type Translations = { [ id: string ]: string }
28 export class PeerTubeEmbed {
29 playerElement: HTMLVideoElement
30 player: videojs.Player
31 api: PeerTubeEmbedApi = null
39 startTime: number | string = 0
40 stopTime: number | string
45 bigPlayBackgroundColor: string
46 foregroundColor: string
52 headers = new Headers()
53 LOCAL_STORAGE_OAUTH_CLIENT_KEYS = {
54 CLIENT_ID: 'client_id',
55 CLIENT_SECRET: 'client_secret'
58 private translationsPromise: Promise<{ [id: string]: string }>
59 private configPromise: Promise<ServerConfig>
60 private PeertubePlayerManagerModulePromise: Promise<any>
62 private playlist: VideoPlaylist
63 private playlistElements: VideoPlaylistElement[]
64 private currentPlaylistElement: VideoPlaylistElement
66 private wrapperElement: HTMLElement
68 private peertubeHooks: Hooks = {}
69 private loadedScripts = new Set<string>()
71 static async main () {
72 const videoContainerId = 'video-wrapper'
73 const embed = new PeerTubeEmbed(videoContainerId)
77 constructor (private videoWrapperId: string) {
78 this.wrapperElement = document.getElementById(this.videoWrapperId)
81 getVideoUrl (id: string) {
82 return window.location.origin + '/api/v1/videos/' + id
85 refreshFetch (url: string, options?: RequestInit) {
86 return fetch(url, options)
87 .then((res: Response) => {
88 if (res.status !== 401) return res
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)
94 const headers = new Headers()
95 headers.set('Content-Type', 'application/x-www-form-urlencoded')
98 refresh_token: this.userTokens.refreshToken,
100 client_secret: clientSecret,
101 response_type: 'code',
102 grant_type: 'refresh_token'
105 fetch('/api/v1/users/token', {
108 body: objectToUrlEncoded(data)
110 if (res.status === 401) return undefined
113 }).then((obj: UserRefreshToken & { code: 'invalid_grant'}) => {
114 if (!obj || obj.code === 'invalid_grant') {
116 this.removeTokensFromHeaders()
121 this.userTokens.accessToken = obj.access_token
122 this.userTokens.refreshToken = obj.refresh_token
123 this.userTokens.save()
125 this.setHeadersFromTokens()
128 }).catch((refreshTokenError: any) => {
129 reject(refreshTokenError)
133 return refreshingTokenPromise
137 this.removeTokensFromHeaders()
138 }).then(() => fetch(url, {
140 headers: this.headers
145 getPlaylistUrl (id: string) {
146 return window.location.origin + '/api/v1/video-playlists/' + id
149 loadVideoInfo (videoId: string): Promise<Response> {
150 return this.refreshFetch(this.getVideoUrl(videoId), { headers: this.headers })
153 loadVideoCaptions (videoId: string): Promise<Response> {
154 return this.refreshFetch(this.getVideoUrl(videoId) + '/captions', { headers: this.headers })
157 loadPlaylistInfo (playlistId: string): Promise<Response> {
158 return this.refreshFetch(this.getPlaylistUrl(playlistId), { headers: this.headers })
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()
165 return this.refreshFetch(url.toString(), { headers: this.headers })
168 loadConfig (): Promise<ServerConfig> {
169 return this.refreshFetch('/api/v1/config')
170 .then(res => res.json())
173 removeElement (element: HTMLElement) {
174 element.parentElement.removeChild(element)
177 displayError (text: string, translations?: Translations) {
178 // Remove video element
179 if (this.playerElement) {
180 this.removeElement(this.playerElement)
181 this.playerElement = undefined
184 const translatedText = peertubeTranslate(text, translations)
185 const translatedSorry = peertubeTranslate('Sorry', translations)
187 document.title = translatedSorry + ' - ' + translatedText
189 const errorBlock = document.getElementById('error-block')
190 errorBlock.style.display = 'flex'
192 const errorTitle = document.getElementById('error-title')
193 errorTitle.innerHTML = peertubeTranslate('Sorry', translations)
195 const errorText = document.getElementById('error-content')
196 errorText.innerHTML = translatedText
198 this.wrapperElement.style.display = 'none'
201 videoNotFound (translations?: Translations) {
202 const text = 'This video does not exist.'
203 this.displayError(text, translations)
206 videoFetchError (translations?: Translations) {
207 const text = 'We cannot fetch the video. Please try again later.'
208 this.displayError(text, translations)
211 playlistNotFound (translations?: Translations) {
212 const text = 'This playlist does not exist.'
213 this.displayError(text, translations)
216 playlistFetchError (translations?: Translations) {
217 const text = 'We cannot fetch the playlist. Please try again later.'
218 this.displayError(text, translations)
221 getParamToggle (params: URLSearchParams, name: string, defaultValue?: boolean) {
222 return params.has(name) ? (params.get(name) === '1' || params.get(name) === 'true') : defaultValue
225 getParamString (params: URLSearchParams, name: string, defaultValue?: string) {
226 return params.has(name) ? params.get(name) : defaultValue
229 async playNextVideo () {
230 const next = this.getNextPlaylistElement()
232 console.log('Next element not found in playlist.')
236 this.currentPlaylistElement = next
238 return this.loadVideoAndBuildPlayer(this.currentPlaylistElement.video.uuid)
241 async playPreviousVideo () {
242 const previous = this.getPreviousPlaylistElement()
244 console.log('Previous element not found in playlist.')
248 this.currentPlaylistElement = previous
250 await this.loadVideoAndBuildPlayer(this.currentPlaylistElement.video.uuid)
253 getCurrentPosition () {
254 if (!this.currentPlaylistElement) return -1
256 return this.currentPlaylistElement.position
261 this.userTokens = Tokens.load()
262 await this.initCore()
268 private initializeApi () {
269 if (!this.enableApi) return
271 this.api = new PeerTubeEmbedApi(this)
272 this.api.initialize()
275 private loadParams (video: VideoDetails) {
277 const params = new URL(window.location.toString()).searchParams
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)
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')
293 this.bigPlayBackgroundColor = this.getParamString(params, 'bigPlayBackgroundColor')
294 this.foregroundColor = this.getParamString(params, 'foregroundColor')
296 const modeParam = this.getParamString(params, 'mode')
299 if (modeParam === 'p2p-media-loader') this.mode = 'p2p-media-loader'
300 else this.mode = 'webtorrent'
302 if (Array.isArray(video.streamingPlaylists) && video.streamingPlaylists.length !== 0) this.mode = 'p2p-media-loader'
303 else this.mode = 'webtorrent'
306 console.error('Cannot get params from URL.', err)
310 private async loadAllPlaylistVideos (playlistId: string, baseResult: ResultList<VideoPlaylistElement>) {
311 let elements = baseResult.data
312 let total = baseResult.total
315 while (total > elements.length && i < 10) {
316 const result = await this.loadPlaylistElements(playlistId, elements.length)
318 const json = await result.json() as ResultList<VideoPlaylistElement>
321 elements = elements.concat(json.data)
326 console.error('Cannot fetch all playlists elements, there are too many!')
332 private async loadPlaylist (playlistId: string) {
333 const playlistPromise = this.loadPlaylistInfo(playlistId)
334 const playlistElementsPromise = this.loadPlaylistElements(playlistId)
336 let playlistResponse: Response
337 let isResponseOk: boolean
340 playlistResponse = await playlistPromise
341 isResponseOk = playlistResponse.status === 200
348 const serverTranslations = await this.translationsPromise
350 if (playlistResponse?.status === 404) {
351 this.playlistNotFound(serverTranslations)
355 this.playlistFetchError(serverTranslations)
359 return { playlistResponse, videosResponse: await playlistElementsPromise }
362 private async loadVideo (videoId: string) {
363 const videoPromise = this.loadVideoInfo(videoId)
365 let videoResponse: Response
366 let isResponseOk: boolean
369 videoResponse = await videoPromise
370 isResponseOk = videoResponse.status === 200
378 const serverTranslations = await this.translationsPromise
380 if (videoResponse?.status === 404) {
381 this.videoNotFound(serverTranslations)
385 this.videoFetchError(serverTranslations)
389 const captionsPromise = this.loadVideoCaptions(videoId)
391 return { captionsPromise, videoResponse }
394 private async buildPlaylistManager () {
395 const translations = await this.translationsPromise
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
409 private async loadVideoAndBuildPlayer (uuid: string) {
410 const res = await this.loadVideo(uuid)
411 if (res === undefined) return
413 return this.buildVideoPlayer(res.videoResponse, res.captionsPromise)
416 private nextVideoTitle () {
417 const next = this.getNextPlaylistElement()
420 return next.video.name
423 private getNextPlaylistElement (position?: number): VideoPlaylistElement {
424 if (!position) position = this.currentPlaylistElement.position + 1
426 if (position > this.playlist.videosLength) {
430 const next = this.playlistElements.find(e => e.position === position)
432 if (!next || !next.video) {
433 return this.getNextPlaylistElement(position + 1)
439 private getPreviousPlaylistElement (position?: number): VideoPlaylistElement {
440 if (!position) position = this.currentPlaylistElement.position - 1
446 const prev = this.playlistElements.find(e => e.position === position)
448 if (!prev || !prev.video) {
449 return this.getNextPlaylistElement(position - 1)
455 private async buildVideoPlayer (videoResponse: Response, captionsPromise: Promise<Response>) {
456 let alreadyHadPlayer = false
459 this.player.dispose()
460 alreadyHadPlayer = true
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)
468 const videoInfoPromise = videoResponse.json()
469 .then((videoInfo: VideoDetails) => {
470 if (!alreadyHadPlayer) this.loadPlaceholder(videoInfo)
475 const [ videoInfoTmp, serverTranslations, captionsResponse, config, PeertubePlayerManagerModule ] = await Promise.all([
477 this.translationsPromise,
480 this.PeertubePlayerManagerModulePromise
483 await this.ensurePluginsAreLoaded(config, serverTranslations)
485 const videoInfo: VideoDetails = videoInfoTmp
487 const PeertubePlayerManager = PeertubePlayerManagerModule.PeertubePlayerManager
488 const videoCaptions = await this.buildCaptions(serverTranslations, captionsResponse)
490 this.loadParams(videoInfo)
492 const playlistPlugin = this.currentPlaylistElement
494 elements: this.playlistElements,
495 playlist: this.playlist,
497 getCurrentPosition: () => this.currentPlaylistElement.position,
499 onItemClicked: (videoPlaylistElement: VideoPlaylistElement) => {
500 this.currentPlaylistElement = videoPlaylistElement
502 this.loadVideoAndBuildPlayer(this.currentPlaylistElement.video.uuid)
503 .catch(err => console.error(err))
508 const options: PeertubePlayerManagerOptions = {
510 // Autoplay in playlist mode
511 autoplay: alreadyHadPlayer ? true : this.autoplay,
512 controls: this.controls,
516 captions: videoCaptions.length !== 0,
517 subtitle: this.subtitle,
519 startTime: this.playlist ? this.currentPlaylistElement.startTimestamp : this.startTime,
520 stopTime: this.playlist ? this.currentPlaylistElement.stopTimestamp : this.stopTime,
522 nextVideo: this.playlist ? () => this.playNextVideo() : undefined,
523 hasNextVideo: this.playlist ? () => !!this.getNextPlaylistElement() : undefined,
525 previousVideo: this.playlist ? () => this.playPreviousVideo() : undefined,
526 hasPreviousVideo: this.playlist ? () => !!this.getPreviousPlaylistElement() : undefined,
528 playlist: playlistPlugin,
531 inactivityTimeout: 2500,
532 videoViewUrl: this.getVideoUrl(videoInfo.uuid) + '/views',
534 isLive: videoInfo.isLive,
536 playerElement: this.playerElement,
537 onPlayerElementChange: (element: HTMLVideoElement) => this.playerElement = element,
539 videoDuration: videoInfo.duration,
541 peertubeLink: this.peertubeLink,
542 poster: window.location.origin + videoInfo.previewPath,
543 theaterButton: false,
545 serverUrl: window.location.origin,
546 language: navigator.language,
547 embedUrl: window.location.origin + videoInfo.embedPath
551 videoFiles: videoInfo.files
555 if (this.mode === 'p2p-media-loader') {
556 const hlsPlaylist = videoInfo.streamingPlaylists.find(p => p.type === VideoStreamingPlaylistType.HLS)
558 Object.assign(options, {
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
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))
572 window[ 'videojsPlayer' ] = this.player
576 await this.buildDock(videoInfo, config)
580 this.removePlaceholder()
582 if (this.isPlaylistEmbed()) {
583 await this.buildPlaylistManager()
585 this.player.playlist().updateSelected()
587 this.player.on('stopped', () => {
592 this.runHook('action:embed.player.loaded', undefined, { player: this.player, videojs, video: videoInfo })
595 private async initCore () {
596 if (this.userTokens) this.setHeadersFromTokens()
598 this.configPromise = this.loadConfig()
599 this.translationsPromise = TranslationsManager.getServerTranslations(window.location.origin, navigator.language)
600 this.PeertubePlayerManagerModulePromise = import('../../assets/player/peertube-player-manager')
604 if (this.isPlaylistEmbed()) {
605 const playlistId = this.getResourceId()
606 const res = await this.loadPlaylist(playlistId)
607 if (!res) return undefined
609 this.playlist = await res.playlistResponse.json()
611 const playlistElementResult = await res.videosResponse.json()
612 this.playlistElements = await this.loadAllPlaylistVideos(playlistId, playlistElementResult)
614 const params = new URL(window.location.toString()).searchParams
615 const playlistPositionParam = this.getParamString(params, 'playlistPosition')
619 if (playlistPositionParam) {
620 position = parseInt(playlistPositionParam + '', 10)
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()
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)
636 videoId = this.currentPlaylistElement.video.uuid
638 videoId = this.getResourceId()
641 return this.loadVideoAndBuildPlayer(videoId)
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)
653 private async buildDock (videoInfo: VideoDetails, config: ServerConfig) {
654 if (!this.controls) return
656 // On webtorrent fallback, player may have been disposed
657 if (!this.player.player_) return
659 const title = this.title ? videoInfo.name : undefined
661 const description = config.tracker.enabled && this.warningTitle
662 ? '<span class="text">' + peertubeTranslate('Watching this video may reveal your IP address to others.') + '</span>'
665 if (title || description) {
673 private buildCSS () {
674 const body = document.getElementById('custom-css')
676 if (this.bigPlayBackgroundColor) {
677 body.style.setProperty('--embedBigPlayBackgroundColor', this.bigPlayBackgroundColor)
680 if (this.foregroundColor) {
681 body.style.setProperty('--embedForegroundColor', this.foregroundColor)
685 private async buildCaptions (serverTranslations: any, captionsResponse: Response): Promise<VideoJSCaption[]> {
686 if (captionsResponse.ok) {
687 const { data } = (await captionsResponse.json()) as ResultList<VideoCaption>
689 return data.map(c => ({
690 label: peertubeTranslate(c.language.label, serverTranslations),
691 language: c.language.id,
692 src: window.location.origin + c.captionPath
699 private loadPlaceholder (video: VideoDetails) {
700 const placeholder = this.getPlaceholderElement()
702 const url = window.location.origin + video.previewPath
703 placeholder.style.backgroundImage = `url("${url}")`
704 placeholder.style.display = 'block'
707 private removePlaceholder () {
708 const placeholder = this.getPlaceholderElement()
709 placeholder.style.display = 'none'
712 private getPlaceholderElement () {
713 return document.getElementById('placeholder-preview')
716 private setHeadersFromTokens () {
717 this.headers.set('Authorization', `${this.userTokens.tokenType} ${this.userTokens.accessToken}`)
720 private removeTokensFromHeaders () {
721 this.headers.delete('Authorization')
724 private getResourceId () {
725 const urlParts = window.location.pathname.split('/')
726 return urlParts[ urlParts.length - 1 ]
729 private isPlaylistEmbed () {
730 return window.location.pathname.split('/')[1] === 'video-playlists'
733 private async ensurePluginsAreLoaded (config: ServerConfig, translations?: { [ id: string ]: string }) {
734 if (config.plugin.registered.length === 0) return
736 for (const plugin of config.plugin.registered) {
737 for (const key of Object.keys(plugin.clientScripts)) {
738 const clientScript = plugin.clientScripts[key]
740 if (clientScript.scopes.includes('embed') === false) continue
742 const script = `/plugins/${plugin.name}/${plugin.version}/client-scripts/${clientScript.script}`
744 if (this.loadedScripts.has(script)) continue
750 scopes: clientScript.scopes
752 pluginType: PluginType.PLUGIN,
757 hooks: this.peertubeHooks,
759 peertubeHelpersFactory: _ => this.buildPeerTubeHelpers(translations)
765 private buildPeerTubeHelpers (translations?: { [ id: string ]: string }): RegisterClientHelpers {
766 function unimplemented (): any {
767 throw new Error('This helper is not implemented in embed.')
771 getBaseStaticRoute: unimplemented,
773 getSettings: unimplemented,
775 isLoggedIn: unimplemented,
779 error: unimplemented,
780 success: unimplemented
783 showModal: unimplemented,
786 textMarkdownToHTML: unimplemented,
787 enhancedMarkdownToHTML: unimplemented
790 translate: (value: string) => {
791 return Promise.resolve(peertubeTranslate(value, translations))
796 private runHook <T> (hookName: ClientHookName, result?: T, params?: any): Promise<T> {
797 return runHook(this.peertubeHooks, hookName, result, params)
802 .catch(err => console.error('Cannot init embed.', err))