2 import videojs from 'video.js'
3 import { peertubeTranslate } from '../../../../shared/core-utils/i18n'
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 { isP2PEnabled } from '../../assets/player/utils'
21 import { getBoolOrDefault } from '../../root-helpers/local-storage-utils'
22 import { peertubeLocalStorage } from '../../root-helpers/peertube-web-storage'
23 import { PluginsManager } from '../../root-helpers/plugins-manager'
24 import { UserLocalStorageKeys, UserTokens } from '../../root-helpers/users'
25 import { objectToUrlEncoded } from '../../root-helpers/utils'
26 import { RegisterClientHelpers } from '../../types/register-client-option.model'
27 import { PeerTubeEmbedApi } from './embed-api'
29 type Translations = { [ id: string ]: string }
31 export class PeerTubeEmbed {
32 playerElement: HTMLVideoElement
33 player: videojs.Player
34 api: PeerTubeEmbedApi = null
42 startTime: number | string = 0
43 stopTime: number | string
49 bigPlayBackgroundColor: string
50 foregroundColor: string
55 userTokens: UserTokens
56 headers = new Headers()
57 LOCAL_STORAGE_OAUTH_CLIENT_KEYS = {
58 CLIENT_ID: 'client_id',
59 CLIENT_SECRET: 'client_secret'
62 config: HTMLServerConfig
64 private translationsPromise: Promise<{ [id: string]: string }>
65 private PeertubePlayerManagerModulePromise: Promise<any>
67 private playlist: VideoPlaylist
68 private playlistElements: VideoPlaylistElement[]
69 private currentPlaylistElement: VideoPlaylistElement
71 private readonly wrapperElement: HTMLElement
73 private pluginsManager: PluginsManager
75 constructor (private readonly videoWrapperId: string) {
76 this.wrapperElement = document.getElementById(this.videoWrapperId)
79 this.config = JSON.parse(window['PeerTubeServerConfig'])
81 console.error('Cannot parse HTML config.', err)
85 static async main () {
86 const videoContainerId = 'video-wrapper'
87 const embed = new PeerTubeEmbed(videoContainerId)
91 getVideoUrl (id: string) {
92 return window.location.origin + '/api/v1/videos/' + id
95 refreshFetch (url: string, options?: RequestInit) {
96 return fetch(url, options)
97 .then((res: Response) => {
98 if (res.status !== HttpStatusCode.UNAUTHORIZED_401) return res
100 const refreshingTokenPromise = new Promise<void>((resolve, reject) => {
101 const clientId: string = peertubeLocalStorage.getItem(this.LOCAL_STORAGE_OAUTH_CLIENT_KEYS.CLIENT_ID)
102 const clientSecret: string = peertubeLocalStorage.getItem(this.LOCAL_STORAGE_OAUTH_CLIENT_KEYS.CLIENT_SECRET)
104 const headers = new Headers()
105 headers.set('Content-Type', 'application/x-www-form-urlencoded')
108 refresh_token: this.userTokens.refreshToken,
110 client_secret: clientSecret,
111 response_type: 'code',
112 grant_type: 'refresh_token'
115 fetch('/api/v1/users/token', {
118 body: objectToUrlEncoded(data)
120 if (res.status === HttpStatusCode.UNAUTHORIZED_401) return undefined
123 }).then((obj: UserRefreshToken & { code?: OAuth2ErrorCode }) => {
124 if (!obj || obj.code === OAuth2ErrorCode.INVALID_GRANT) {
125 UserTokens.flushLocalStorage(peertubeLocalStorage)
126 this.removeTokensFromHeaders()
131 this.userTokens.accessToken = obj.access_token
132 this.userTokens.refreshToken = obj.refresh_token
133 UserTokens.saveToLocalStorage(peertubeLocalStorage, this.userTokens)
135 this.setHeadersFromTokens()
138 }).catch((refreshTokenError: any) => {
139 reject(refreshTokenError)
143 return refreshingTokenPromise
145 UserTokens.flushLocalStorage(peertubeLocalStorage)
147 this.removeTokensFromHeaders()
148 }).then(() => fetch(url, {
150 headers: this.headers
155 getPlaylistUrl (id: string) {
156 return window.location.origin + '/api/v1/video-playlists/' + id
159 loadVideoInfo (videoId: string): Promise<Response> {
160 return this.refreshFetch(this.getVideoUrl(videoId), { headers: this.headers })
163 loadVideoCaptions (videoId: string): Promise<Response> {
164 return this.refreshFetch(this.getVideoUrl(videoId) + '/captions', { headers: this.headers })
167 loadPlaylistInfo (playlistId: string): Promise<Response> {
168 return this.refreshFetch(this.getPlaylistUrl(playlistId), { headers: this.headers })
171 loadPlaylistElements (playlistId: string, start = 0): Promise<Response> {
172 const url = new URL(this.getPlaylistUrl(playlistId) + '/videos')
173 url.search = new URLSearchParams({ start: '' + start, count: '100' }).toString()
175 return this.refreshFetch(url.toString(), { headers: this.headers })
178 removeElement (element: HTMLElement) {
179 element.parentElement.removeChild(element)
182 displayError (text: string, translations?: Translations) {
183 // Remove video element
184 if (this.playerElement) {
185 this.removeElement(this.playerElement)
186 this.playerElement = undefined
189 const translatedText = peertubeTranslate(text, translations)
190 const translatedSorry = peertubeTranslate('Sorry', translations)
192 document.title = translatedSorry + ' - ' + translatedText
194 const errorBlock = document.getElementById('error-block')
195 errorBlock.style.display = 'flex'
197 const errorTitle = document.getElementById('error-title')
198 errorTitle.innerHTML = peertubeTranslate('Sorry', translations)
200 const errorText = document.getElementById('error-content')
201 errorText.innerHTML = translatedText
203 this.wrapperElement.style.display = 'none'
206 videoNotFound (translations?: Translations) {
207 const text = 'This video does not exist.'
208 this.displayError(text, translations)
211 videoFetchError (translations?: Translations) {
212 const text = 'We cannot fetch the video. Please try again later.'
213 this.displayError(text, translations)
216 playlistNotFound (translations?: Translations) {
217 const text = 'This playlist does not exist.'
218 this.displayError(text, translations)
221 playlistFetchError (translations?: Translations) {
222 const text = 'We cannot fetch the playlist. Please try again later.'
223 this.displayError(text, translations)
226 getParamToggle (params: URLSearchParams, name: string, defaultValue?: boolean) {
227 return params.has(name) ? (params.get(name) === '1' || params.get(name) === 'true') : defaultValue
230 getParamString (params: URLSearchParams, name: string, defaultValue?: string) {
231 return params.has(name) ? params.get(name) : defaultValue
234 async playNextVideo () {
235 const next = this.getNextPlaylistElement()
237 console.log('Next element not found in playlist.')
241 this.currentPlaylistElement = next
243 return this.loadVideoAndBuildPlayer(this.currentPlaylistElement.video.uuid)
246 async playPreviousVideo () {
247 const previous = this.getPreviousPlaylistElement()
249 console.log('Previous element not found in playlist.')
253 this.currentPlaylistElement = previous
255 await this.loadVideoAndBuildPlayer(this.currentPlaylistElement.video.uuid)
258 getCurrentPosition () {
259 if (!this.currentPlaylistElement) return -1
261 return this.currentPlaylistElement.position
265 this.userTokens = UserTokens.getUserTokens(peertubeLocalStorage)
266 await this.initCore()
269 private initializeApi () {
270 if (!this.enableApi) return
272 this.api = new PeerTubeEmbedApi(this)
273 this.api.initialize()
276 private loadParams (video: VideoDetails) {
278 const params = new URL(window.location.toString()).searchParams
280 this.autoplay = this.getParamToggle(params, 'autoplay', false)
281 this.controls = this.getParamToggle(params, 'controls', true)
282 this.muted = this.getParamToggle(params, 'muted', undefined)
283 this.loop = this.getParamToggle(params, 'loop', false)
284 this.title = this.getParamToggle(params, 'title', true)
285 this.enableApi = this.getParamToggle(params, 'api', this.enableApi)
286 this.warningTitle = this.getParamToggle(params, 'warningTitle', true)
287 this.peertubeLink = this.getParamToggle(params, 'peertubeLink', true)
288 this.p2pEnabled = this.getParamToggle(params, 'p2p', this.isP2PEnabled(video))
290 this.scope = this.getParamString(params, 'scope', this.scope)
291 this.subtitle = this.getParamString(params, 'subtitle')
292 this.startTime = this.getParamString(params, 'start')
293 this.stopTime = this.getParamString(params, 'stop')
295 this.bigPlayBackgroundColor = this.getParamString(params, 'bigPlayBackgroundColor')
296 this.foregroundColor = this.getParamString(params, 'foregroundColor')
298 const modeParam = this.getParamString(params, 'mode')
301 if (modeParam === 'p2p-media-loader') this.mode = 'p2p-media-loader'
302 else this.mode = 'webtorrent'
304 if (Array.isArray(video.streamingPlaylists) && video.streamingPlaylists.length !== 0) this.mode = 'p2p-media-loader'
305 else this.mode = 'webtorrent'
308 console.error('Cannot get params from URL.', err)
312 private async loadAllPlaylistVideos (playlistId: string, baseResult: ResultList<VideoPlaylistElement>) {
313 let elements = baseResult.data
314 let total = baseResult.total
317 while (total > elements.length && i < 10) {
318 const result = await this.loadPlaylistElements(playlistId, elements.length)
320 const json = await result.json()
323 elements = elements.concat(json.data)
328 console.error('Cannot fetch all playlists elements, there are too many!')
334 private async loadPlaylist (playlistId: string) {
335 const playlistPromise = this.loadPlaylistInfo(playlistId)
336 const playlistElementsPromise = this.loadPlaylistElements(playlistId)
338 let playlistResponse: Response
339 let isResponseOk: boolean
342 playlistResponse = await playlistPromise
343 isResponseOk = playlistResponse.status === HttpStatusCode.OK_200
350 const serverTranslations = await this.translationsPromise
352 if (playlistResponse?.status === HttpStatusCode.NOT_FOUND_404) {
353 this.playlistNotFound(serverTranslations)
357 this.playlistFetchError(serverTranslations)
361 return { playlistResponse, videosResponse: await playlistElementsPromise }
364 private async loadVideo (videoId: string) {
365 const videoPromise = this.loadVideoInfo(videoId)
367 let videoResponse: Response
368 let isResponseOk: boolean
371 videoResponse = await videoPromise
372 isResponseOk = videoResponse.status === HttpStatusCode.OK_200
380 const serverTranslations = await this.translationsPromise
382 if (videoResponse?.status === HttpStatusCode.NOT_FOUND_404) {
383 this.videoNotFound(serverTranslations)
387 this.videoFetchError(serverTranslations)
391 const captionsPromise = this.loadVideoCaptions(videoId)
393 return { captionsPromise, videoResponse }
396 private async buildPlaylistManager () {
397 const translations = await this.translationsPromise
400 timeout: 10000, // 10s
401 headText: peertubeTranslate('Up Next', translations),
402 cancelText: peertubeTranslate('Cancel', translations),
403 suspendedText: peertubeTranslate('Autoplay is suspended', translations),
404 getTitle: () => this.nextVideoTitle(),
405 next: () => this.playNextVideo(),
406 condition: () => !!this.getNextPlaylistElement(),
407 suspended: () => false
411 private async loadVideoAndBuildPlayer (uuid: string) {
412 const res = await this.loadVideo(uuid)
413 if (res === undefined) return
415 return this.buildVideoPlayer(res.videoResponse, res.captionsPromise)
418 private nextVideoTitle () {
419 const next = this.getNextPlaylistElement()
422 return next.video.name
425 private getNextPlaylistElement (position?: number): VideoPlaylistElement {
426 if (!position) position = this.currentPlaylistElement.position + 1
428 if (position > this.playlist.videosLength) {
432 const next = this.playlistElements.find(e => e.position === position)
434 if (!next || !next.video) {
435 return this.getNextPlaylistElement(position + 1)
441 private getPreviousPlaylistElement (position?: number): VideoPlaylistElement {
442 if (!position) position = this.currentPlaylistElement.position - 1
448 const prev = this.playlistElements.find(e => e.position === position)
450 if (!prev || !prev.video) {
451 return this.getNextPlaylistElement(position - 1)
457 private async buildVideoPlayer (videoResponse: Response, captionsPromise: Promise<Response>) {
458 let alreadyHadPlayer = false
461 this.player.dispose()
462 alreadyHadPlayer = true
465 this.playerElement = document.createElement('video')
466 this.playerElement.className = 'video-js vjs-peertube-skin'
467 this.playerElement.setAttribute('playsinline', 'true')
468 this.wrapperElement.appendChild(this.playerElement)
470 // Issue when we parsed config from HTML, fallback to API
472 this.config = await this.refreshFetch('/api/v1/config')
473 .then(res => res.json())
476 const videoInfoPromise = videoResponse.json()
477 .then((videoInfo: VideoDetails) => {
478 this.loadParams(videoInfo)
480 if (!alreadyHadPlayer && !this.autoplay) this.loadPlaceholder(videoInfo)
485 const [ videoInfoTmp, serverTranslations, captionsResponse, PeertubePlayerManagerModule ] = await Promise.all([
487 this.translationsPromise,
489 this.PeertubePlayerManagerModulePromise
492 await this.loadPlugins(serverTranslations)
494 const videoInfo: VideoDetails = videoInfoTmp
496 const PeertubePlayerManager = PeertubePlayerManagerModule.PeertubePlayerManager
497 const videoCaptions = await this.buildCaptions(serverTranslations, captionsResponse)
499 const playlistPlugin = this.currentPlaylistElement
501 elements: this.playlistElements,
502 playlist: this.playlist,
504 getCurrentPosition: () => this.currentPlaylistElement.position,
506 onItemClicked: (videoPlaylistElement: VideoPlaylistElement) => {
507 this.currentPlaylistElement = videoPlaylistElement
509 this.loadVideoAndBuildPlayer(this.currentPlaylistElement.video.uuid)
510 .catch(err => console.error(err))
515 const options: PeertubePlayerManagerOptions = {
517 // Autoplay in playlist mode
518 autoplay: alreadyHadPlayer ? true : this.autoplay,
519 controls: this.controls,
523 p2pEnabled: this.p2pEnabled,
525 captions: videoCaptions.length !== 0,
526 subtitle: this.subtitle,
528 startTime: this.playlist ? this.currentPlaylistElement.startTimestamp : this.startTime,
529 stopTime: this.playlist ? this.currentPlaylistElement.stopTimestamp : this.stopTime,
531 nextVideo: this.playlist ? () => this.playNextVideo() : undefined,
532 hasNextVideo: this.playlist ? () => !!this.getNextPlaylistElement() : undefined,
534 previousVideo: this.playlist ? () => this.playPreviousVideo() : undefined,
535 hasPreviousVideo: this.playlist ? () => !!this.getPreviousPlaylistElement() : undefined,
537 playlist: playlistPlugin,
540 inactivityTimeout: 2500,
541 videoViewUrl: this.getVideoUrl(videoInfo.uuid) + '/views',
542 videoShortUUID: videoInfo.shortUUID,
543 videoUUID: videoInfo.uuid,
545 isLive: videoInfo.isLive,
547 playerElement: this.playerElement,
548 onPlayerElementChange: (element: HTMLVideoElement) => {
549 this.playerElement = element
552 videoDuration: videoInfo.duration,
554 peertubeLink: this.peertubeLink,
555 poster: window.location.origin + videoInfo.previewPath,
556 theaterButton: false,
558 serverUrl: window.location.origin,
559 language: navigator.language,
560 embedUrl: window.location.origin + videoInfo.embedPath,
561 embedTitle: videoInfo.name
565 videoFiles: videoInfo.files
568 pluginsManager: this.pluginsManager
571 if (this.mode === 'p2p-media-loader') {
572 const hlsPlaylist = videoInfo.streamingPlaylists.find(p => p.type === VideoStreamingPlaylistType.HLS)
574 Object.assign(options, {
576 playlistUrl: hlsPlaylist.playlistUrl,
577 segmentsSha256Url: hlsPlaylist.segmentsSha256Url,
578 redundancyBaseUrls: hlsPlaylist.redundancies.map(r => r.baseUrl),
579 trackerAnnounce: videoInfo.trackerUrls,
580 videoFiles: hlsPlaylist.files
581 } as P2PMediaLoaderOptions
585 this.player = await PeertubePlayerManager.initialize(this.mode, options, (player: videojs.Player) => {
589 this.player.on('customError', (event: any, data: any) => this.handleError(data.err, serverTranslations))
591 window['videojsPlayer'] = this.player
595 this.buildDock(videoInfo)
599 this.removePlaceholder()
601 if (this.isPlaylistEmbed()) {
602 await this.buildPlaylistManager()
604 this.player.playlist().updateSelected()
606 this.player.on('stopped', () => {
611 this.pluginsManager.runHook('action:embed.player.loaded', undefined, { player: this.player, videojs, video: videoInfo })
614 private async initCore () {
615 if (this.userTokens) this.setHeadersFromTokens()
617 this.translationsPromise = TranslationsManager.getServerTranslations(window.location.origin, navigator.language)
618 this.PeertubePlayerManagerModulePromise = import('../../assets/player/peertube-player-manager')
622 if (this.isPlaylistEmbed()) {
623 const playlistId = this.getResourceId()
624 const res = await this.loadPlaylist(playlistId)
625 if (!res) return undefined
627 this.playlist = await res.playlistResponse.json()
629 const playlistElementResult = await res.videosResponse.json()
630 this.playlistElements = await this.loadAllPlaylistVideos(playlistId, playlistElementResult)
632 const params = new URL(window.location.toString()).searchParams
633 const playlistPositionParam = this.getParamString(params, 'playlistPosition')
637 if (playlistPositionParam) {
638 position = parseInt(playlistPositionParam + '', 10)
641 this.currentPlaylistElement = this.playlistElements.find(e => e.position === position)
642 if (!this.currentPlaylistElement || !this.currentPlaylistElement.video) {
643 console.error('Current playlist element is not valid.', this.currentPlaylistElement)
644 this.currentPlaylistElement = this.getNextPlaylistElement()
647 if (!this.currentPlaylistElement) {
648 console.error('This playlist does not have any valid element.')
649 const serverTranslations = await this.translationsPromise
650 this.playlistFetchError(serverTranslations)
654 videoId = this.currentPlaylistElement.video.uuid
656 videoId = this.getResourceId()
659 return this.loadVideoAndBuildPlayer(videoId)
662 private handleError (err: Error, translations?: { [ id: string ]: string }) {
663 if (err.message.includes('from xs param')) {
664 this.player.dispose()
665 this.playerElement = null
666 this.displayError('This video is not available because the remote instance is not responding.', translations)
671 private buildDock (videoInfo: VideoDetails) {
672 if (!this.controls) return
674 // On webtorrent fallback, player may have been disposed
675 if (!this.player.player_) return
677 const title = this.title ? videoInfo.name : undefined
679 const description = this.warningTitle && this.p2pEnabled
680 ? '<span class="text">' + peertubeTranslate('Watching this video may reveal your IP address to others.') + '</span>'
683 if (title || description) {
691 private buildCSS () {
692 const body = document.getElementById('custom-css')
694 if (this.bigPlayBackgroundColor) {
695 body.style.setProperty('--embedBigPlayBackgroundColor', this.bigPlayBackgroundColor)
698 if (this.foregroundColor) {
699 body.style.setProperty('--embedForegroundColor', this.foregroundColor)
703 private async buildCaptions (serverTranslations: any, captionsResponse: Response): Promise<VideoJSCaption[]> {
704 if (captionsResponse.ok) {
705 const { data } = await captionsResponse.json()
707 return data.map((c: VideoCaption) => ({
708 label: peertubeTranslate(c.language.label, serverTranslations),
709 language: c.language.id,
710 src: window.location.origin + c.captionPath
717 private loadPlaceholder (video: VideoDetails) {
718 const placeholder = this.getPlaceholderElement()
720 const url = window.location.origin + video.previewPath
721 placeholder.style.backgroundImage = `url("${url}")`
722 placeholder.style.display = 'block'
725 private removePlaceholder () {
726 const placeholder = this.getPlaceholderElement()
727 placeholder.style.display = 'none'
730 private getPlaceholderElement () {
731 return document.getElementById('placeholder-preview')
734 private setHeadersFromTokens () {
735 this.headers.set('Authorization', `${this.userTokens.tokenType} ${this.userTokens.accessToken}`)
738 private removeTokensFromHeaders () {
739 this.headers.delete('Authorization')
742 private getResourceId () {
743 const urlParts = window.location.pathname.split('/')
744 return urlParts[urlParts.length - 1]
747 private isPlaylistEmbed () {
748 return window.location.pathname.split('/')[1] === 'video-playlists'
751 private loadPlugins (translations?: { [ id: string ]: string }) {
752 this.pluginsManager = new PluginsManager({
753 peertubeHelpersFactory: _ => this.buildPeerTubeHelpers(translations)
756 this.pluginsManager.loadPluginsList(this.config)
758 return this.pluginsManager.ensurePluginsAreLoaded('embed')
761 private buildPeerTubeHelpers (translations?: { [ id: string ]: string }): RegisterClientHelpers {
762 const unimplemented = () => {
763 throw new Error('This helper is not implemented in embed.')
767 getBaseStaticRoute: unimplemented,
768 getBaseRouterRoute: unimplemented,
769 getBasePluginClientPath: unimplemented,
771 getSettings: unimplemented,
773 isLoggedIn: unimplemented,
774 getAuthHeader: unimplemented,
778 error: unimplemented,
779 success: unimplemented
782 showModal: unimplemented,
784 getServerConfig: unimplemented,
787 textMarkdownToHTML: unimplemented,
788 enhancedMarkdownToHTML: unimplemented
791 translate: (value: string) => Promise.resolve(peertubeTranslate(value, translations))
795 private isP2PEnabled (video: Video) {
796 const userP2PEnabled = getBoolOrDefault(
797 peertubeLocalStorage.getItem(UserLocalStorageKeys.P2P_ENABLED),
798 this.config.defaults.p2p.embed.enabled
801 return isP2PEnabled(video, this.config, userP2PEnabled)
807 (window as any).displayIncompatibleBrowser()
809 console.error('Cannot init embed.', err)