2 import videojs from 'video.js'
3 import { peertubeTranslate } from '../../../../shared/core-utils/i18n'
14 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 { peertubeLocalStorage } from '../../root-helpers/peertube-web-storage'
20 import { PluginsManager } from '../../root-helpers/plugins-manager'
21 import { Tokens } from '../../root-helpers/users'
22 import { objectToUrlEncoded } from '../../root-helpers/utils'
23 import { RegisterClientHelpers } from '../../types/register-client-option.model'
24 import { PeerTubeEmbedApi } from './embed-api'
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 config: HTMLServerConfig
60 private translationsPromise: Promise<{ [id: string]: string }>
61 private PeertubePlayerManagerModulePromise: Promise<any>
63 private playlist: VideoPlaylist
64 private playlistElements: VideoPlaylistElement[]
65 private currentPlaylistElement: VideoPlaylistElement
67 private readonly wrapperElement: HTMLElement
69 private pluginsManager: PluginsManager
71 constructor (private readonly videoWrapperId: string) {
72 this.wrapperElement = document.getElementById(this.videoWrapperId)
75 this.config = JSON.parse(window['PeerTubeServerConfig'])
77 console.error('Cannot parse HTML config.', err)
81 static async main () {
82 const videoContainerId = 'video-wrapper'
83 const embed = new PeerTubeEmbed(videoContainerId)
87 getVideoUrl (id: string) {
88 return window.location.origin + '/api/v1/videos/' + id
91 refreshFetch (url: string, options?: RequestInit) {
92 return fetch(url, options)
93 .then((res: Response) => {
94 if (res.status !== HttpStatusCode.UNAUTHORIZED_401) return res
96 const refreshingTokenPromise = new Promise<void>((resolve, reject) => {
97 const clientId: string = peertubeLocalStorage.getItem(this.LOCAL_STORAGE_OAUTH_CLIENT_KEYS.CLIENT_ID)
98 const clientSecret: string = peertubeLocalStorage.getItem(this.LOCAL_STORAGE_OAUTH_CLIENT_KEYS.CLIENT_SECRET)
100 const headers = new Headers()
101 headers.set('Content-Type', 'application/x-www-form-urlencoded')
104 refresh_token: this.userTokens.refreshToken,
106 client_secret: clientSecret,
107 response_type: 'code',
108 grant_type: 'refresh_token'
111 fetch('/api/v1/users/token', {
114 body: objectToUrlEncoded(data)
116 if (res.status === HttpStatusCode.UNAUTHORIZED_401) return undefined
119 }).then((obj: UserRefreshToken & { code?: OAuth2ErrorCode }) => {
120 if (!obj || obj.code === OAuth2ErrorCode.INVALID_GRANT) {
122 this.removeTokensFromHeaders()
127 this.userTokens.accessToken = obj.access_token
128 this.userTokens.refreshToken = obj.refresh_token
129 this.userTokens.save()
131 this.setHeadersFromTokens()
134 }).catch((refreshTokenError: any) => {
135 reject(refreshTokenError)
139 return refreshingTokenPromise
143 this.removeTokensFromHeaders()
144 }).then(() => fetch(url, {
146 headers: this.headers
151 getPlaylistUrl (id: string) {
152 return window.location.origin + '/api/v1/video-playlists/' + id
155 loadVideoInfo (videoId: string): Promise<Response> {
156 return this.refreshFetch(this.getVideoUrl(videoId), { headers: this.headers })
159 loadVideoCaptions (videoId: string): Promise<Response> {
160 return this.refreshFetch(this.getVideoUrl(videoId) + '/captions', { headers: this.headers })
163 loadPlaylistInfo (playlistId: string): Promise<Response> {
164 return this.refreshFetch(this.getPlaylistUrl(playlistId), { headers: this.headers })
167 loadPlaylistElements (playlistId: string, start = 0): Promise<Response> {
168 const url = new URL(this.getPlaylistUrl(playlistId) + '/videos')
169 url.search = new URLSearchParams({ start: '' + start, count: '100' }).toString()
171 return this.refreshFetch(url.toString(), { headers: this.headers })
174 removeElement (element: HTMLElement) {
175 element.parentElement.removeChild(element)
178 displayError (text: string, translations?: Translations) {
179 // Remove video element
180 if (this.playerElement) {
181 this.removeElement(this.playerElement)
182 this.playerElement = undefined
185 const translatedText = peertubeTranslate(text, translations)
186 const translatedSorry = peertubeTranslate('Sorry', translations)
188 document.title = translatedSorry + ' - ' + translatedText
190 const errorBlock = document.getElementById('error-block')
191 errorBlock.style.display = 'flex'
193 const errorTitle = document.getElementById('error-title')
194 errorTitle.innerHTML = peertubeTranslate('Sorry', translations)
196 const errorText = document.getElementById('error-content')
197 errorText.innerHTML = translatedText
199 this.wrapperElement.style.display = 'none'
202 videoNotFound (translations?: Translations) {
203 const text = 'This video does not exist.'
204 this.displayError(text, translations)
207 videoFetchError (translations?: Translations) {
208 const text = 'We cannot fetch the video. Please try again later.'
209 this.displayError(text, translations)
212 playlistNotFound (translations?: Translations) {
213 const text = 'This playlist does not exist.'
214 this.displayError(text, translations)
217 playlistFetchError (translations?: Translations) {
218 const text = 'We cannot fetch the playlist. Please try again later.'
219 this.displayError(text, translations)
222 getParamToggle (params: URLSearchParams, name: string, defaultValue?: boolean) {
223 return params.has(name) ? (params.get(name) === '1' || params.get(name) === 'true') : defaultValue
226 getParamString (params: URLSearchParams, name: string, defaultValue?: string) {
227 return params.has(name) ? params.get(name) : defaultValue
230 async playNextVideo () {
231 const next = this.getNextPlaylistElement()
233 console.log('Next element not found in playlist.')
237 this.currentPlaylistElement = next
239 return this.loadVideoAndBuildPlayer(this.currentPlaylistElement.video.uuid)
242 async playPreviousVideo () {
243 const previous = this.getPreviousPlaylistElement()
245 console.log('Previous element not found in playlist.')
249 this.currentPlaylistElement = previous
251 await this.loadVideoAndBuildPlayer(this.currentPlaylistElement.video.uuid)
254 getCurrentPosition () {
255 if (!this.currentPlaylistElement) return -1
257 return this.currentPlaylistElement.position
261 this.userTokens = Tokens.load()
262 await this.initCore()
265 private initializeApi () {
266 if (!this.enableApi) return
268 this.api = new PeerTubeEmbedApi(this)
269 this.api.initialize()
272 private loadParams (video: VideoDetails) {
274 const params = new URL(window.location.toString()).searchParams
276 this.autoplay = this.getParamToggle(params, 'autoplay', false)
277 this.controls = this.getParamToggle(params, 'controls', true)
278 this.muted = this.getParamToggle(params, 'muted', undefined)
279 this.loop = this.getParamToggle(params, 'loop', false)
280 this.title = this.getParamToggle(params, 'title', true)
281 this.enableApi = this.getParamToggle(params, 'api', this.enableApi)
282 this.warningTitle = this.getParamToggle(params, 'warningTitle', true)
283 this.peertubeLink = this.getParamToggle(params, 'peertubeLink', true)
285 this.scope = this.getParamString(params, 'scope', this.scope)
286 this.subtitle = this.getParamString(params, 'subtitle')
287 this.startTime = this.getParamString(params, 'start')
288 this.stopTime = this.getParamString(params, 'stop')
290 this.bigPlayBackgroundColor = this.getParamString(params, 'bigPlayBackgroundColor')
291 this.foregroundColor = this.getParamString(params, 'foregroundColor')
293 const modeParam = this.getParamString(params, 'mode')
296 if (modeParam === 'p2p-media-loader') this.mode = 'p2p-media-loader'
297 else this.mode = 'webtorrent'
299 if (Array.isArray(video.streamingPlaylists) && video.streamingPlaylists.length !== 0) this.mode = 'p2p-media-loader'
300 else this.mode = 'webtorrent'
303 console.error('Cannot get params from URL.', err)
307 private async loadAllPlaylistVideos (playlistId: string, baseResult: ResultList<VideoPlaylistElement>) {
308 let elements = baseResult.data
309 let total = baseResult.total
312 while (total > elements.length && i < 10) {
313 const result = await this.loadPlaylistElements(playlistId, elements.length)
315 const json = await result.json()
318 elements = elements.concat(json.data)
323 console.error('Cannot fetch all playlists elements, there are too many!')
329 private async loadPlaylist (playlistId: string) {
330 const playlistPromise = this.loadPlaylistInfo(playlistId)
331 const playlistElementsPromise = this.loadPlaylistElements(playlistId)
333 let playlistResponse: Response
334 let isResponseOk: boolean
337 playlistResponse = await playlistPromise
338 isResponseOk = playlistResponse.status === HttpStatusCode.OK_200
345 const serverTranslations = await this.translationsPromise
347 if (playlistResponse?.status === HttpStatusCode.NOT_FOUND_404) {
348 this.playlistNotFound(serverTranslations)
352 this.playlistFetchError(serverTranslations)
356 return { playlistResponse, videosResponse: await playlistElementsPromise }
359 private async loadVideo (videoId: string) {
360 const videoPromise = this.loadVideoInfo(videoId)
362 let videoResponse: Response
363 let isResponseOk: boolean
366 videoResponse = await videoPromise
367 isResponseOk = videoResponse.status === HttpStatusCode.OK_200
375 const serverTranslations = await this.translationsPromise
377 if (videoResponse?.status === HttpStatusCode.NOT_FOUND_404) {
378 this.videoNotFound(serverTranslations)
382 this.videoFetchError(serverTranslations)
386 const captionsPromise = this.loadVideoCaptions(videoId)
388 return { captionsPromise, videoResponse }
391 private async buildPlaylistManager () {
392 const translations = await this.translationsPromise
395 timeout: 10000, // 10s
396 headText: peertubeTranslate('Up Next', translations),
397 cancelText: peertubeTranslate('Cancel', translations),
398 suspendedText: peertubeTranslate('Autoplay is suspended', translations),
399 getTitle: () => this.nextVideoTitle(),
400 next: () => this.playNextVideo(),
401 condition: () => !!this.getNextPlaylistElement(),
402 suspended: () => false
406 private async loadVideoAndBuildPlayer (uuid: string) {
407 const res = await this.loadVideo(uuid)
408 if (res === undefined) return
410 return this.buildVideoPlayer(res.videoResponse, res.captionsPromise)
413 private nextVideoTitle () {
414 const next = this.getNextPlaylistElement()
417 return next.video.name
420 private getNextPlaylistElement (position?: number): VideoPlaylistElement {
421 if (!position) position = this.currentPlaylistElement.position + 1
423 if (position > this.playlist.videosLength) {
427 const next = this.playlistElements.find(e => e.position === position)
429 if (!next || !next.video) {
430 return this.getNextPlaylistElement(position + 1)
436 private getPreviousPlaylistElement (position?: number): VideoPlaylistElement {
437 if (!position) position = this.currentPlaylistElement.position - 1
443 const prev = this.playlistElements.find(e => e.position === position)
445 if (!prev || !prev.video) {
446 return this.getNextPlaylistElement(position - 1)
452 private async buildVideoPlayer (videoResponse: Response, captionsPromise: Promise<Response>) {
453 let alreadyHadPlayer = false
456 this.player.dispose()
457 alreadyHadPlayer = true
460 this.playerElement = document.createElement('video')
461 this.playerElement.className = 'video-js vjs-peertube-skin'
462 this.playerElement.setAttribute('playsinline', 'true')
463 this.wrapperElement.appendChild(this.playerElement)
465 // Issue when we parsed config from HTML, fallback to API
467 this.config = await this.refreshFetch('/api/v1/config')
468 .then(res => res.json())
471 const videoInfoPromise = videoResponse.json()
472 .then((videoInfo: VideoDetails) => {
473 this.loadParams(videoInfo)
475 if (!alreadyHadPlayer && !this.autoplay) this.loadPlaceholder(videoInfo)
480 const [ videoInfoTmp, serverTranslations, captionsResponse, PeertubePlayerManagerModule ] = await Promise.all([
482 this.translationsPromise,
484 this.PeertubePlayerManagerModulePromise
487 await this.loadPlugins(serverTranslations)
489 const videoInfo: VideoDetails = videoInfoTmp
491 const PeertubePlayerManager = PeertubePlayerManagerModule.PeertubePlayerManager
492 const videoCaptions = await this.buildCaptions(serverTranslations, captionsResponse)
494 const playlistPlugin = this.currentPlaylistElement
496 elements: this.playlistElements,
497 playlist: this.playlist,
499 getCurrentPosition: () => this.currentPlaylistElement.position,
501 onItemClicked: (videoPlaylistElement: VideoPlaylistElement) => {
502 this.currentPlaylistElement = videoPlaylistElement
504 this.loadVideoAndBuildPlayer(this.currentPlaylistElement.video.uuid)
505 .catch(err => console.error(err))
510 const options: PeertubePlayerManagerOptions = {
512 // Autoplay in playlist mode
513 autoplay: alreadyHadPlayer ? true : this.autoplay,
514 controls: this.controls,
518 captions: videoCaptions.length !== 0,
519 subtitle: this.subtitle,
521 startTime: this.playlist ? this.currentPlaylistElement.startTimestamp : this.startTime,
522 stopTime: this.playlist ? this.currentPlaylistElement.stopTimestamp : this.stopTime,
524 nextVideo: this.playlist ? () => this.playNextVideo() : undefined,
525 hasNextVideo: this.playlist ? () => !!this.getNextPlaylistElement() : undefined,
527 previousVideo: this.playlist ? () => this.playPreviousVideo() : undefined,
528 hasPreviousVideo: this.playlist ? () => !!this.getPreviousPlaylistElement() : undefined,
530 playlist: playlistPlugin,
533 inactivityTimeout: 2500,
534 videoViewUrl: this.getVideoUrl(videoInfo.uuid) + '/views',
535 videoShortUUID: videoInfo.shortUUID,
536 videoUUID: videoInfo.uuid,
538 isLive: videoInfo.isLive,
540 playerElement: this.playerElement,
541 onPlayerElementChange: (element: HTMLVideoElement) => {
542 this.playerElement = element
545 videoDuration: videoInfo.duration,
547 peertubeLink: this.peertubeLink,
548 poster: window.location.origin + videoInfo.previewPath,
549 theaterButton: false,
551 serverUrl: window.location.origin,
552 language: navigator.language,
553 embedUrl: window.location.origin + videoInfo.embedPath,
554 embedTitle: videoInfo.name
558 videoFiles: videoInfo.files
561 pluginsManager: this.pluginsManager
564 if (this.mode === 'p2p-media-loader') {
565 const hlsPlaylist = videoInfo.streamingPlaylists.find(p => p.type === VideoStreamingPlaylistType.HLS)
567 Object.assign(options, {
569 playlistUrl: hlsPlaylist.playlistUrl,
570 segmentsSha256Url: hlsPlaylist.segmentsSha256Url,
571 redundancyBaseUrls: hlsPlaylist.redundancies.map(r => r.baseUrl),
572 trackerAnnounce: videoInfo.trackerUrls,
573 videoFiles: hlsPlaylist.files
574 } as P2PMediaLoaderOptions
578 this.player = await PeertubePlayerManager.initialize(this.mode, options, (player: videojs.Player) => {
582 this.player.on('customError', (event: any, data: any) => this.handleError(data.err, serverTranslations))
584 window['videojsPlayer'] = this.player
588 this.buildDock(videoInfo)
592 this.removePlaceholder()
594 if (this.isPlaylistEmbed()) {
595 await this.buildPlaylistManager()
597 this.player.playlist().updateSelected()
599 this.player.on('stopped', () => {
604 this.pluginsManager.runHook('action:embed.player.loaded', undefined, { player: this.player, videojs, video: videoInfo })
607 private async initCore () {
608 if (this.userTokens) this.setHeadersFromTokens()
610 this.translationsPromise = TranslationsManager.getServerTranslations(window.location.origin, navigator.language)
611 this.PeertubePlayerManagerModulePromise = import('../../assets/player/peertube-player-manager')
615 if (this.isPlaylistEmbed()) {
616 const playlistId = this.getResourceId()
617 const res = await this.loadPlaylist(playlistId)
618 if (!res) return undefined
620 this.playlist = await res.playlistResponse.json()
622 const playlistElementResult = await res.videosResponse.json()
623 this.playlistElements = await this.loadAllPlaylistVideos(playlistId, playlistElementResult)
625 const params = new URL(window.location.toString()).searchParams
626 const playlistPositionParam = this.getParamString(params, 'playlistPosition')
630 if (playlistPositionParam) {
631 position = parseInt(playlistPositionParam + '', 10)
634 this.currentPlaylistElement = this.playlistElements.find(e => e.position === position)
635 if (!this.currentPlaylistElement || !this.currentPlaylistElement.video) {
636 console.error('Current playlist element is not valid.', this.currentPlaylistElement)
637 this.currentPlaylistElement = this.getNextPlaylistElement()
640 if (!this.currentPlaylistElement) {
641 console.error('This playlist does not have any valid element.')
642 const serverTranslations = await this.translationsPromise
643 this.playlistFetchError(serverTranslations)
647 videoId = this.currentPlaylistElement.video.uuid
649 videoId = this.getResourceId()
652 return this.loadVideoAndBuildPlayer(videoId)
655 private handleError (err: Error, translations?: { [ id: string ]: string }) {
656 if (err.message.includes('from xs param')) {
657 this.player.dispose()
658 this.playerElement = null
659 this.displayError('This video is not available because the remote instance is not responding.', translations)
664 private buildDock (videoInfo: VideoDetails) {
665 if (!this.controls) return
667 // On webtorrent fallback, player may have been disposed
668 if (!this.player.player_) return
670 const title = this.title ? videoInfo.name : undefined
672 const description = this.warningTitle && (!videoInfo.isLocal || this.config.tracker.enabled)
673 ? '<span class="text">' + peertubeTranslate('Watching this video may reveal your IP address to others.') + '</span>'
676 if (title || description) {
684 private buildCSS () {
685 const body = document.getElementById('custom-css')
687 if (this.bigPlayBackgroundColor) {
688 body.style.setProperty('--embedBigPlayBackgroundColor', this.bigPlayBackgroundColor)
691 if (this.foregroundColor) {
692 body.style.setProperty('--embedForegroundColor', this.foregroundColor)
696 private async buildCaptions (serverTranslations: any, captionsResponse: Response): Promise<VideoJSCaption[]> {
697 if (captionsResponse.ok) {
698 const { data } = await captionsResponse.json()
700 return data.map((c: VideoCaption) => ({
701 label: peertubeTranslate(c.language.label, serverTranslations),
702 language: c.language.id,
703 src: window.location.origin + c.captionPath
710 private loadPlaceholder (video: VideoDetails) {
711 const placeholder = this.getPlaceholderElement()
713 const url = window.location.origin + video.previewPath
714 placeholder.style.backgroundImage = `url("${url}")`
715 placeholder.style.display = 'block'
718 private removePlaceholder () {
719 const placeholder = this.getPlaceholderElement()
720 placeholder.style.display = 'none'
723 private getPlaceholderElement () {
724 return document.getElementById('placeholder-preview')
727 private setHeadersFromTokens () {
728 this.headers.set('Authorization', `${this.userTokens.tokenType} ${this.userTokens.accessToken}`)
731 private removeTokensFromHeaders () {
732 this.headers.delete('Authorization')
735 private getResourceId () {
736 const urlParts = window.location.pathname.split('/')
737 return urlParts[urlParts.length - 1]
740 private isPlaylistEmbed () {
741 return window.location.pathname.split('/')[1] === 'video-playlists'
744 private loadPlugins (translations?: { [ id: string ]: string }) {
745 this.pluginsManager = new PluginsManager({
746 peertubeHelpersFactory: _ => this.buildPeerTubeHelpers(translations)
749 this.pluginsManager.loadPluginsList(this.config)
751 return this.pluginsManager.ensurePluginsAreLoaded('embed')
754 private buildPeerTubeHelpers (translations?: { [ id: string ]: string }): RegisterClientHelpers {
755 const unimplemented = () => {
756 throw new Error('This helper is not implemented in embed.')
760 getBaseStaticRoute: unimplemented,
762 getBaseRouterRoute: unimplemented,
764 getSettings: unimplemented,
766 isLoggedIn: unimplemented,
767 getAuthHeader: unimplemented,
771 error: unimplemented,
772 success: unimplemented
775 showModal: unimplemented,
777 getServerConfig: unimplemented,
780 textMarkdownToHTML: unimplemented,
781 enhancedMarkdownToHTML: unimplemented
784 translate: (value: string) => Promise.resolve(peertubeTranslate(value, translations))
791 (window as any).displayIncompatibleBrowser()
793 console.error('Cannot init embed.', err)