2 import videojs from 'video.js'
3 import { peertubeTranslate } from '../../../../shared/core-utils/i18n'
12 VideoStreamingPlaylistType,
15 } from '../../../../shared/models'
16 import { HttpStatusCode } from '../../../../shared/core-utils/miscs/http-error-codes'
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 { Hooks, loadPlugin, runHook } from '../../root-helpers/plugins'
21 import { Tokens } from '../../root-helpers/users'
22 import { peertubeLocalStorage } from '../../root-helpers/peertube-web-storage'
23 import { objectToUrlEncoded } from '../../root-helpers/utils'
24 import { PeerTubeEmbedApi } from './embed-api'
25 import { RegisterClientHelpers } from '../../types/register-client-option.model'
27 type Translations = { [ id: string ]: string }
29 export class PeerTubeEmbed {
30 playerElement: HTMLVideoElement
31 player: videojs.Player
32 api: PeerTubeEmbedApi = null
40 startTime: number | string = 0
41 stopTime: number | string
46 bigPlayBackgroundColor: string
47 foregroundColor: string
53 headers = new Headers()
54 LOCAL_STORAGE_OAUTH_CLIENT_KEYS = {
55 CLIENT_ID: 'client_id',
56 CLIENT_SECRET: 'client_secret'
59 private translationsPromise: Promise<{ [id: string]: string }>
60 private configPromise: Promise<ServerConfig>
61 private PeertubePlayerManagerModulePromise: Promise<any>
63 private playlist: VideoPlaylist
64 private playlistElements: VideoPlaylistElement[]
65 private currentPlaylistElement: VideoPlaylistElement
67 private wrapperElement: HTMLElement
69 private peertubeHooks: Hooks = {}
70 private loadedScripts = new Set<string>()
72 static async main () {
73 const videoContainerId = 'video-wrapper'
74 const embed = new PeerTubeEmbed(videoContainerId)
78 constructor (private videoWrapperId: string) {
79 this.wrapperElement = document.getElementById(this.videoWrapperId)
82 getVideoUrl (id: string) {
83 return window.location.origin + '/api/v1/videos/' + id
86 refreshFetch (url: string, options?: RequestInit) {
87 return fetch(url, options)
88 .then((res: Response) => {
89 if (res.status !== HttpStatusCode.UNAUTHORIZED_401) return res
91 const refreshingTokenPromise = new Promise<void>((resolve, reject) => {
92 const clientId: string = peertubeLocalStorage.getItem(this.LOCAL_STORAGE_OAUTH_CLIENT_KEYS.CLIENT_ID)
93 const clientSecret: string = peertubeLocalStorage.getItem(this.LOCAL_STORAGE_OAUTH_CLIENT_KEYS.CLIENT_SECRET)
95 const headers = new Headers()
96 headers.set('Content-Type', 'application/x-www-form-urlencoded')
99 refresh_token: this.userTokens.refreshToken,
101 client_secret: clientSecret,
102 response_type: 'code',
103 grant_type: 'refresh_token'
106 fetch('/api/v1/users/token', {
109 body: objectToUrlEncoded(data)
111 if (res.status === HttpStatusCode.UNAUTHORIZED_401) return undefined
114 }).then((obj: UserRefreshToken & { code: 'invalid_grant'}) => {
115 if (!obj || obj.code === 'invalid_grant') {
117 this.removeTokensFromHeaders()
122 this.userTokens.accessToken = obj.access_token
123 this.userTokens.refreshToken = obj.refresh_token
124 this.userTokens.save()
126 this.setHeadersFromTokens()
129 }).catch((refreshTokenError: any) => {
130 reject(refreshTokenError)
134 return refreshingTokenPromise
138 this.removeTokensFromHeaders()
139 }).then(() => fetch(url, {
141 headers: this.headers
146 getPlaylistUrl (id: string) {
147 return window.location.origin + '/api/v1/video-playlists/' + id
150 loadVideoInfo (videoId: string): Promise<Response> {
151 return this.refreshFetch(this.getVideoUrl(videoId), { headers: this.headers })
154 loadVideoCaptions (videoId: string): Promise<Response> {
155 return this.refreshFetch(this.getVideoUrl(videoId) + '/captions', { headers: this.headers })
158 loadPlaylistInfo (playlistId: string): Promise<Response> {
159 return this.refreshFetch(this.getPlaylistUrl(playlistId), { headers: this.headers })
162 loadPlaylistElements (playlistId: string, start = 0): Promise<Response> {
163 const url = new URL(this.getPlaylistUrl(playlistId) + '/videos')
164 url.search = new URLSearchParams({ start: '' + start, count: '100' }).toString()
166 return this.refreshFetch(url.toString(), { headers: this.headers })
169 loadConfig (): Promise<ServerConfig> {
170 return this.refreshFetch('/api/v1/config')
171 .then(res => res.json())
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
262 this.userTokens = Tokens.load()
263 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)
289 this.scope = this.getParamString(params, 'scope', this.scope)
290 this.subtitle = this.getParamString(params, 'subtitle')
291 this.startTime = this.getParamString(params, 'start')
292 this.stopTime = this.getParamString(params, 'stop')
294 this.bigPlayBackgroundColor = this.getParamString(params, 'bigPlayBackgroundColor')
295 this.foregroundColor = this.getParamString(params, 'foregroundColor')
297 const modeParam = this.getParamString(params, 'mode')
300 if (modeParam === 'p2p-media-loader') this.mode = 'p2p-media-loader'
301 else this.mode = 'webtorrent'
303 if (Array.isArray(video.streamingPlaylists) && video.streamingPlaylists.length !== 0) this.mode = 'p2p-media-loader'
304 else this.mode = 'webtorrent'
307 console.error('Cannot get params from URL.', err)
311 private async loadAllPlaylistVideos (playlistId: string, baseResult: ResultList<VideoPlaylistElement>) {
312 let elements = baseResult.data
313 let total = baseResult.total
316 while (total > elements.length && i < 10) {
317 const result = await this.loadPlaylistElements(playlistId, elements.length)
319 const json = await result.json() as ResultList<VideoPlaylistElement>
322 elements = elements.concat(json.data)
327 console.error('Cannot fetch all playlists elements, there are too many!')
333 private async loadPlaylist (playlistId: string) {
334 const playlistPromise = this.loadPlaylistInfo(playlistId)
335 const playlistElementsPromise = this.loadPlaylistElements(playlistId)
337 let playlistResponse: Response
338 let isResponseOk: boolean
341 playlistResponse = await playlistPromise
342 isResponseOk = playlistResponse.status === HttpStatusCode.OK_200
349 const serverTranslations = await this.translationsPromise
351 if (playlistResponse?.status === HttpStatusCode.NOT_FOUND_404) {
352 this.playlistNotFound(serverTranslations)
356 this.playlistFetchError(serverTranslations)
360 return { playlistResponse, videosResponse: await playlistElementsPromise }
363 private async loadVideo (videoId: string) {
364 const videoPromise = this.loadVideoInfo(videoId)
366 let videoResponse: Response
367 let isResponseOk: boolean
370 videoResponse = await videoPromise
371 isResponseOk = videoResponse.status === HttpStatusCode.OK_200
379 const serverTranslations = await this.translationsPromise
381 if (videoResponse?.status === HttpStatusCode.NOT_FOUND_404) {
382 this.videoNotFound(serverTranslations)
386 this.videoFetchError(serverTranslations)
390 const captionsPromise = this.loadVideoCaptions(videoId)
392 return { captionsPromise, videoResponse }
395 private async buildPlaylistManager () {
396 const translations = await this.translationsPromise
399 timeout: 10000, // 10s
400 headText: peertubeTranslate('Up Next', translations),
401 cancelText: peertubeTranslate('Cancel', translations),
402 suspendedText: peertubeTranslate('Autoplay is suspended', translations),
403 getTitle: () => this.nextVideoTitle(),
404 next: () => this.playNextVideo(),
405 condition: () => !!this.getNextPlaylistElement(),
406 suspended: () => false
410 private async loadVideoAndBuildPlayer (uuid: string) {
411 const res = await this.loadVideo(uuid)
412 if (res === undefined) return
414 return this.buildVideoPlayer(res.videoResponse, res.captionsPromise)
417 private nextVideoTitle () {
418 const next = this.getNextPlaylistElement()
421 return next.video.name
424 private getNextPlaylistElement (position?: number): VideoPlaylistElement {
425 if (!position) position = this.currentPlaylistElement.position + 1
427 if (position > this.playlist.videosLength) {
431 const next = this.playlistElements.find(e => e.position === position)
433 if (!next || !next.video) {
434 return this.getNextPlaylistElement(position + 1)
440 private getPreviousPlaylistElement (position?: number): VideoPlaylistElement {
441 if (!position) position = this.currentPlaylistElement.position - 1
447 const prev = this.playlistElements.find(e => e.position === position)
449 if (!prev || !prev.video) {
450 return this.getNextPlaylistElement(position - 1)
456 private async buildVideoPlayer (videoResponse: Response, captionsPromise: Promise<Response>) {
457 let alreadyHadPlayer = false
460 this.player.dispose()
461 alreadyHadPlayer = true
464 this.playerElement = document.createElement('video')
465 this.playerElement.className = 'video-js vjs-peertube-skin'
466 this.playerElement.setAttribute('playsinline', 'true')
467 this.wrapperElement.appendChild(this.playerElement)
469 const videoInfoPromise = videoResponse.json()
470 .then((videoInfo: VideoDetails) => {
471 if (!alreadyHadPlayer) this.loadPlaceholder(videoInfo)
476 const [ videoInfoTmp, serverTranslations, captionsResponse, config, PeertubePlayerManagerModule ] = await Promise.all([
478 this.translationsPromise,
481 this.PeertubePlayerManagerModulePromise
484 await this.ensurePluginsAreLoaded(config, serverTranslations)
486 const videoInfo: VideoDetails = videoInfoTmp
488 const PeertubePlayerManager = PeertubePlayerManagerModule.PeertubePlayerManager
489 const videoCaptions = await this.buildCaptions(serverTranslations, captionsResponse)
491 this.loadParams(videoInfo)
493 const playlistPlugin = this.currentPlaylistElement
495 elements: this.playlistElements,
496 playlist: this.playlist,
498 getCurrentPosition: () => this.currentPlaylistElement.position,
500 onItemClicked: (videoPlaylistElement: VideoPlaylistElement) => {
501 this.currentPlaylistElement = videoPlaylistElement
503 this.loadVideoAndBuildPlayer(this.currentPlaylistElement.video.uuid)
504 .catch(err => console.error(err))
509 const options: PeertubePlayerManagerOptions = {
511 // Autoplay in playlist mode
512 autoplay: alreadyHadPlayer ? true : this.autoplay,
513 controls: this.controls,
517 captions: videoCaptions.length !== 0,
518 subtitle: this.subtitle,
520 startTime: this.playlist ? this.currentPlaylistElement.startTimestamp : this.startTime,
521 stopTime: this.playlist ? this.currentPlaylistElement.stopTimestamp : this.stopTime,
523 nextVideo: this.playlist ? () => this.playNextVideo() : undefined,
524 hasNextVideo: this.playlist ? () => !!this.getNextPlaylistElement() : undefined,
526 previousVideo: this.playlist ? () => this.playPreviousVideo() : undefined,
527 hasPreviousVideo: this.playlist ? () => !!this.getPreviousPlaylistElement() : undefined,
529 playlist: playlistPlugin,
532 inactivityTimeout: 2500,
533 videoViewUrl: this.getVideoUrl(videoInfo.uuid) + '/views',
535 isLive: videoInfo.isLive,
537 playerElement: this.playerElement,
538 onPlayerElementChange: (element: HTMLVideoElement) => this.playerElement = element,
540 videoDuration: videoInfo.duration,
542 peertubeLink: this.peertubeLink,
543 poster: window.location.origin + videoInfo.previewPath,
544 theaterButton: false,
546 serverUrl: window.location.origin,
547 language: navigator.language,
548 embedUrl: window.location.origin + videoInfo.embedPath
552 videoFiles: videoInfo.files
556 if (this.mode === 'p2p-media-loader') {
557 const hlsPlaylist = videoInfo.streamingPlaylists.find(p => p.type === VideoStreamingPlaylistType.HLS)
559 Object.assign(options, {
561 playlistUrl: hlsPlaylist.playlistUrl,
562 segmentsSha256Url: hlsPlaylist.segmentsSha256Url,
563 redundancyBaseUrls: hlsPlaylist.redundancies.map(r => r.baseUrl),
564 trackerAnnounce: videoInfo.trackerUrls,
565 videoFiles: hlsPlaylist.files
566 } as P2PMediaLoaderOptions
570 this.player = await PeertubePlayerManager.initialize(this.mode, options, (player: videojs.Player) => this.player = player)
571 this.player.on('customError', (event: any, data: any) => this.handleError(data.err, serverTranslations))
573 window[ 'videojsPlayer' ] = this.player
577 await this.buildDock(videoInfo, config)
581 this.removePlaceholder()
583 if (this.isPlaylistEmbed()) {
584 await this.buildPlaylistManager()
586 this.player.playlist().updateSelected()
588 this.player.on('stopped', () => {
593 this.runHook('action:embed.player.loaded', undefined, { player: this.player, videojs, video: videoInfo })
596 private async initCore () {
597 if (this.userTokens) this.setHeadersFromTokens()
599 this.configPromise = this.loadConfig()
600 this.translationsPromise = TranslationsManager.getServerTranslations(window.location.origin, navigator.language)
601 this.PeertubePlayerManagerModulePromise = import('../../assets/player/peertube-player-manager')
605 if (this.isPlaylistEmbed()) {
606 const playlistId = this.getResourceId()
607 const res = await this.loadPlaylist(playlistId)
608 if (!res) return undefined
610 this.playlist = await res.playlistResponse.json()
612 const playlistElementResult = await res.videosResponse.json()
613 this.playlistElements = await this.loadAllPlaylistVideos(playlistId, playlistElementResult)
615 const params = new URL(window.location.toString()).searchParams
616 const playlistPositionParam = this.getParamString(params, 'playlistPosition')
620 if (playlistPositionParam) {
621 position = parseInt(playlistPositionParam + '', 10)
624 this.currentPlaylistElement = this.playlistElements.find(e => e.position === position)
625 if (!this.currentPlaylistElement || !this.currentPlaylistElement.video) {
626 console.error('Current playlist element is not valid.', this.currentPlaylistElement)
627 this.currentPlaylistElement = this.getNextPlaylistElement()
630 if (!this.currentPlaylistElement) {
631 console.error('This playlist does not have any valid element.')
632 const serverTranslations = await this.translationsPromise
633 this.playlistFetchError(serverTranslations)
637 videoId = this.currentPlaylistElement.video.uuid
639 videoId = this.getResourceId()
642 return this.loadVideoAndBuildPlayer(videoId)
645 private handleError (err: Error, translations?: { [ id: string ]: string }) {
646 if (err.message.indexOf('from xs param') !== -1) {
647 this.player.dispose()
648 this.playerElement = null
649 this.displayError('This video is not available because the remote instance is not responding.', translations)
654 private async buildDock (videoInfo: VideoDetails, config: ServerConfig) {
655 if (!this.controls) return
657 // On webtorrent fallback, player may have been disposed
658 if (!this.player.player_) return
660 const title = this.title ? videoInfo.name : undefined
662 const description = config.tracker.enabled && this.warningTitle
663 ? '<span class="text">' + peertubeTranslate('Watching this video may reveal your IP address to others.') + '</span>'
666 if (title || description) {
674 private buildCSS () {
675 const body = document.getElementById('custom-css')
677 if (this.bigPlayBackgroundColor) {
678 body.style.setProperty('--embedBigPlayBackgroundColor', this.bigPlayBackgroundColor)
681 if (this.foregroundColor) {
682 body.style.setProperty('--embedForegroundColor', this.foregroundColor)
686 private async buildCaptions (serverTranslations: any, captionsResponse: Response): Promise<VideoJSCaption[]> {
687 if (captionsResponse.ok) {
688 const { data } = (await captionsResponse.json()) as ResultList<VideoCaption>
690 return data.map(c => ({
691 label: peertubeTranslate(c.language.label, serverTranslations),
692 language: c.language.id,
693 src: window.location.origin + c.captionPath
700 private loadPlaceholder (video: VideoDetails) {
701 const placeholder = this.getPlaceholderElement()
703 const url = window.location.origin + video.previewPath
704 placeholder.style.backgroundImage = `url("${url}")`
705 placeholder.style.display = 'block'
708 private removePlaceholder () {
709 const placeholder = this.getPlaceholderElement()
710 placeholder.style.display = 'none'
713 private getPlaceholderElement () {
714 return document.getElementById('placeholder-preview')
717 private setHeadersFromTokens () {
718 this.headers.set('Authorization', `${this.userTokens.tokenType} ${this.userTokens.accessToken}`)
721 private removeTokensFromHeaders () {
722 this.headers.delete('Authorization')
725 private getResourceId () {
726 const urlParts = window.location.pathname.split('/')
727 return urlParts[ urlParts.length - 1 ]
730 private isPlaylistEmbed () {
731 return window.location.pathname.split('/')[1] === 'video-playlists'
734 private async ensurePluginsAreLoaded (config: ServerConfig, translations?: { [ id: string ]: string }) {
735 if (config.plugin.registered.length === 0) return
737 for (const plugin of config.plugin.registered) {
738 for (const key of Object.keys(plugin.clientScripts)) {
739 const clientScript = plugin.clientScripts[key]
741 if (clientScript.scopes.includes('embed') === false) continue
743 const script = `/plugins/${plugin.name}/${plugin.version}/client-scripts/${clientScript.script}`
745 if (this.loadedScripts.has(script)) continue
751 scopes: clientScript.scopes
753 pluginType: PluginType.PLUGIN,
758 hooks: this.peertubeHooks,
760 peertubeHelpersFactory: _ => this.buildPeerTubeHelpers(translations)
766 private buildPeerTubeHelpers (translations?: { [ id: string ]: string }): RegisterClientHelpers {
767 function unimplemented (): any {
768 throw new Error('This helper is not implemented in embed.')
772 getBaseStaticRoute: unimplemented,
774 getSettings: unimplemented,
776 isLoggedIn: unimplemented,
780 error: unimplemented,
781 success: unimplemented
784 showModal: unimplemented,
786 getServerConfig: unimplemented,
789 textMarkdownToHTML: unimplemented,
790 enhancedMarkdownToHTML: unimplemented
793 translate: (value: string) => {
794 return Promise.resolve(peertubeTranslate(value, translations))
799 private runHook <T> (hookName: ClientHookName, result?: T, params?: any): Promise<T> {
800 return runHook(this.peertubeHooks, hookName, result, params)
805 .catch(err => console.error('Cannot init embed.', err))