2 import videojs from 'video.js'
3 import { peertubeTranslate } from '../../../../shared/core-utils/i18n'
4 import { HttpStatusCode } from '../../../../shared/core-utils/miscs/http-error-codes'
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 { peertubeLocalStorage } from '../../root-helpers/peertube-web-storage'
21 import { Hooks, loadPlugin, runHook } from '../../root-helpers/plugins'
22 import { Tokens } from '../../root-helpers/users'
23 import { objectToUrlEncoded } from '../../root-helpers/utils'
24 import { RegisterClientHelpers } from '../../types/register-client-option.model'
25 import { PeerTubeEmbedApi } from './embed-api'
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 config: HTMLServerConfig
61 private translationsPromise: Promise<{ [id: string]: string }>
62 private PeertubePlayerManagerModulePromise: Promise<any>
64 private playlist: VideoPlaylist
65 private playlistElements: VideoPlaylistElement[]
66 private currentPlaylistElement: VideoPlaylistElement
68 private wrapperElement: HTMLElement
70 private peertubeHooks: Hooks = {}
71 private loadedScripts = new Set<string>()
73 static async main () {
74 const videoContainerId = 'video-wrapper'
75 const embed = new PeerTubeEmbed(videoContainerId)
79 constructor (private videoWrapperId: string) {
80 this.wrapperElement = document.getElementById(this.videoWrapperId)
83 this.config = JSON.parse(window['PeerTubeServerConfig'])
85 console.error('Cannot parse HTML config.', err)
89 getVideoUrl (id: string) {
90 return window.location.origin + '/api/v1/videos/' + id
93 refreshFetch (url: string, options?: RequestInit) {
94 return fetch(url, options)
95 .then((res: Response) => {
96 if (res.status !== HttpStatusCode.UNAUTHORIZED_401) return res
98 const refreshingTokenPromise = new Promise<void>((resolve, reject) => {
99 const clientId: string = peertubeLocalStorage.getItem(this.LOCAL_STORAGE_OAUTH_CLIENT_KEYS.CLIENT_ID)
100 const clientSecret: string = peertubeLocalStorage.getItem(this.LOCAL_STORAGE_OAUTH_CLIENT_KEYS.CLIENT_SECRET)
102 const headers = new Headers()
103 headers.set('Content-Type', 'application/x-www-form-urlencoded')
106 refresh_token: this.userTokens.refreshToken,
108 client_secret: clientSecret,
109 response_type: 'code',
110 grant_type: 'refresh_token'
113 fetch('/api/v1/users/token', {
116 body: objectToUrlEncoded(data)
118 if (res.status === HttpStatusCode.UNAUTHORIZED_401) return undefined
121 }).then((obj: UserRefreshToken & { code: 'invalid_grant'}) => {
122 if (!obj || obj.code === 'invalid_grant') {
124 this.removeTokensFromHeaders()
129 this.userTokens.accessToken = obj.access_token
130 this.userTokens.refreshToken = obj.refresh_token
131 this.userTokens.save()
133 this.setHeadersFromTokens()
136 }).catch((refreshTokenError: any) => {
137 reject(refreshTokenError)
141 return refreshingTokenPromise
145 this.removeTokensFromHeaders()
146 }).then(() => fetch(url, {
148 headers: this.headers
153 getPlaylistUrl (id: string) {
154 return window.location.origin + '/api/v1/video-playlists/' + id
157 loadVideoInfo (videoId: string): Promise<Response> {
158 return this.refreshFetch(this.getVideoUrl(videoId), { headers: this.headers })
161 loadVideoCaptions (videoId: string): Promise<Response> {
162 return this.refreshFetch(this.getVideoUrl(videoId) + '/captions', { headers: this.headers })
165 loadPlaylistInfo (playlistId: string): Promise<Response> {
166 return this.refreshFetch(this.getPlaylistUrl(playlistId), { headers: this.headers })
169 loadPlaylistElements (playlistId: string, start = 0): Promise<Response> {
170 const url = new URL(this.getPlaylistUrl(playlistId) + '/videos')
171 url.search = new URLSearchParams({ start: '' + start, count: '100' }).toString()
173 return this.refreshFetch(url.toString(), { headers: this.headers })
176 removeElement (element: HTMLElement) {
177 element.parentElement.removeChild(element)
180 displayError (text: string, translations?: Translations) {
181 // Remove video element
182 if (this.playerElement) {
183 this.removeElement(this.playerElement)
184 this.playerElement = undefined
187 const translatedText = peertubeTranslate(text, translations)
188 const translatedSorry = peertubeTranslate('Sorry', translations)
190 document.title = translatedSorry + ' - ' + translatedText
192 const errorBlock = document.getElementById('error-block')
193 errorBlock.style.display = 'flex'
195 const errorTitle = document.getElementById('error-title')
196 errorTitle.innerHTML = peertubeTranslate('Sorry', translations)
198 const errorText = document.getElementById('error-content')
199 errorText.innerHTML = translatedText
201 this.wrapperElement.style.display = 'none'
204 videoNotFound (translations?: Translations) {
205 const text = 'This video does not exist.'
206 this.displayError(text, translations)
209 videoFetchError (translations?: Translations) {
210 const text = 'We cannot fetch the video. Please try again later.'
211 this.displayError(text, translations)
214 playlistNotFound (translations?: Translations) {
215 const text = 'This playlist does not exist.'
216 this.displayError(text, translations)
219 playlistFetchError (translations?: Translations) {
220 const text = 'We cannot fetch the playlist. Please try again later.'
221 this.displayError(text, translations)
224 getParamToggle (params: URLSearchParams, name: string, defaultValue?: boolean) {
225 return params.has(name) ? (params.get(name) === '1' || params.get(name) === 'true') : defaultValue
228 getParamString (params: URLSearchParams, name: string, defaultValue?: string) {
229 return params.has(name) ? params.get(name) : defaultValue
232 async playNextVideo () {
233 const next = this.getNextPlaylistElement()
235 console.log('Next element not found in playlist.')
239 this.currentPlaylistElement = next
241 return this.loadVideoAndBuildPlayer(this.currentPlaylistElement.video.uuid)
244 async playPreviousVideo () {
245 const previous = this.getPreviousPlaylistElement()
247 console.log('Previous element not found in playlist.')
251 this.currentPlaylistElement = previous
253 await this.loadVideoAndBuildPlayer(this.currentPlaylistElement.video.uuid)
256 getCurrentPosition () {
257 if (!this.currentPlaylistElement) return -1
259 return this.currentPlaylistElement.position
264 this.userTokens = Tokens.load()
265 await this.initCore()
271 private initializeApi () {
272 if (!this.enableApi) return
274 this.api = new PeerTubeEmbedApi(this)
275 this.api.initialize()
278 private loadParams (video: VideoDetails) {
280 const params = new URL(window.location.toString()).searchParams
282 this.autoplay = this.getParamToggle(params, 'autoplay', false)
283 this.controls = this.getParamToggle(params, 'controls', true)
284 this.muted = this.getParamToggle(params, 'muted', undefined)
285 this.loop = this.getParamToggle(params, 'loop', false)
286 this.title = this.getParamToggle(params, 'title', true)
287 this.enableApi = this.getParamToggle(params, 'api', this.enableApi)
288 this.warningTitle = this.getParamToggle(params, 'warningTitle', true)
289 this.peertubeLink = this.getParamToggle(params, 'peertubeLink', true)
291 this.scope = this.getParamString(params, 'scope', this.scope)
292 this.subtitle = this.getParamString(params, 'subtitle')
293 this.startTime = this.getParamString(params, 'start')
294 this.stopTime = this.getParamString(params, 'stop')
296 this.bigPlayBackgroundColor = this.getParamString(params, 'bigPlayBackgroundColor')
297 this.foregroundColor = this.getParamString(params, 'foregroundColor')
299 const modeParam = this.getParamString(params, 'mode')
302 if (modeParam === 'p2p-media-loader') this.mode = 'p2p-media-loader'
303 else this.mode = 'webtorrent'
305 if (Array.isArray(video.streamingPlaylists) && video.streamingPlaylists.length !== 0) this.mode = 'p2p-media-loader'
306 else this.mode = 'webtorrent'
309 console.error('Cannot get params from URL.', err)
313 private async loadAllPlaylistVideos (playlistId: string, baseResult: ResultList<VideoPlaylistElement>) {
314 let elements = baseResult.data
315 let total = baseResult.total
318 while (total > elements.length && i < 10) {
319 const result = await this.loadPlaylistElements(playlistId, elements.length)
321 const json = await result.json() as ResultList<VideoPlaylistElement>
324 elements = elements.concat(json.data)
329 console.error('Cannot fetch all playlists elements, there are too many!')
335 private async loadPlaylist (playlistId: string) {
336 const playlistPromise = this.loadPlaylistInfo(playlistId)
337 const playlistElementsPromise = this.loadPlaylistElements(playlistId)
339 let playlistResponse: Response
340 let isResponseOk: boolean
343 playlistResponse = await playlistPromise
344 isResponseOk = playlistResponse.status === HttpStatusCode.OK_200
351 const serverTranslations = await this.translationsPromise
353 if (playlistResponse?.status === HttpStatusCode.NOT_FOUND_404) {
354 this.playlistNotFound(serverTranslations)
358 this.playlistFetchError(serverTranslations)
362 return { playlistResponse, videosResponse: await playlistElementsPromise }
365 private async loadVideo (videoId: string) {
366 const videoPromise = this.loadVideoInfo(videoId)
368 let videoResponse: Response
369 let isResponseOk: boolean
372 videoResponse = await videoPromise
373 isResponseOk = videoResponse.status === HttpStatusCode.OK_200
381 const serverTranslations = await this.translationsPromise
383 if (videoResponse?.status === HttpStatusCode.NOT_FOUND_404) {
384 this.videoNotFound(serverTranslations)
388 this.videoFetchError(serverTranslations)
392 const captionsPromise = this.loadVideoCaptions(videoId)
394 return { captionsPromise, videoResponse }
397 private async buildPlaylistManager () {
398 const translations = await this.translationsPromise
401 timeout: 10000, // 10s
402 headText: peertubeTranslate('Up Next', translations),
403 cancelText: peertubeTranslate('Cancel', translations),
404 suspendedText: peertubeTranslate('Autoplay is suspended', translations),
405 getTitle: () => this.nextVideoTitle(),
406 next: () => this.playNextVideo(),
407 condition: () => !!this.getNextPlaylistElement(),
408 suspended: () => false
412 private async loadVideoAndBuildPlayer (uuid: string) {
413 const res = await this.loadVideo(uuid)
414 if (res === undefined) return
416 return this.buildVideoPlayer(res.videoResponse, res.captionsPromise)
419 private nextVideoTitle () {
420 const next = this.getNextPlaylistElement()
423 return next.video.name
426 private getNextPlaylistElement (position?: number): VideoPlaylistElement {
427 if (!position) position = this.currentPlaylistElement.position + 1
429 if (position > this.playlist.videosLength) {
433 const next = this.playlistElements.find(e => e.position === position)
435 if (!next || !next.video) {
436 return this.getNextPlaylistElement(position + 1)
442 private getPreviousPlaylistElement (position?: number): VideoPlaylistElement {
443 if (!position) position = this.currentPlaylistElement.position - 1
449 const prev = this.playlistElements.find(e => e.position === position)
451 if (!prev || !prev.video) {
452 return this.getNextPlaylistElement(position - 1)
458 private async buildVideoPlayer (videoResponse: Response, captionsPromise: Promise<Response>) {
459 let alreadyHadPlayer = false
462 this.player.dispose()
463 alreadyHadPlayer = true
466 this.playerElement = document.createElement('video')
467 this.playerElement.className = 'video-js vjs-peertube-skin'
468 this.playerElement.setAttribute('playsinline', 'true')
469 this.wrapperElement.appendChild(this.playerElement)
471 // Issue when we parsed config from HTML, fallback to API
473 this.config = await this.refreshFetch('/api/v1/config')
474 .then(res => res.json())
477 const videoInfoPromise = videoResponse.json()
478 .then((videoInfo: VideoDetails) => {
479 if (!alreadyHadPlayer) this.loadPlaceholder(videoInfo)
484 const [ videoInfoTmp, serverTranslations, captionsResponse, PeertubePlayerManagerModule ] = await Promise.all([
486 this.translationsPromise,
488 this.PeertubePlayerManagerModulePromise
491 await this.ensurePluginsAreLoaded(serverTranslations)
493 const videoInfo: VideoDetails = videoInfoTmp
495 const PeertubePlayerManager = PeertubePlayerManagerModule.PeertubePlayerManager
496 const videoCaptions = await this.buildCaptions(serverTranslations, captionsResponse)
498 this.loadParams(videoInfo)
500 const playlistPlugin = this.currentPlaylistElement
502 elements: this.playlistElements,
503 playlist: this.playlist,
505 getCurrentPosition: () => this.currentPlaylistElement.position,
507 onItemClicked: (videoPlaylistElement: VideoPlaylistElement) => {
508 this.currentPlaylistElement = videoPlaylistElement
510 this.loadVideoAndBuildPlayer(this.currentPlaylistElement.video.uuid)
511 .catch(err => console.error(err))
516 const options: PeertubePlayerManagerOptions = {
518 // Autoplay in playlist mode
519 autoplay: alreadyHadPlayer ? true : this.autoplay,
520 controls: this.controls,
524 captions: videoCaptions.length !== 0,
525 subtitle: this.subtitle,
527 startTime: this.playlist ? this.currentPlaylistElement.startTimestamp : this.startTime,
528 stopTime: this.playlist ? this.currentPlaylistElement.stopTimestamp : this.stopTime,
530 nextVideo: this.playlist ? () => this.playNextVideo() : undefined,
531 hasNextVideo: this.playlist ? () => !!this.getNextPlaylistElement() : undefined,
533 previousVideo: this.playlist ? () => this.playPreviousVideo() : undefined,
534 hasPreviousVideo: this.playlist ? () => !!this.getPreviousPlaylistElement() : undefined,
536 playlist: playlistPlugin,
539 inactivityTimeout: 2500,
540 videoViewUrl: this.getVideoUrl(videoInfo.uuid) + '/views',
541 videoUUID: videoInfo.uuid,
543 isLive: videoInfo.isLive,
545 playerElement: this.playerElement,
546 onPlayerElementChange: (element: HTMLVideoElement) => this.playerElement = element,
548 videoDuration: videoInfo.duration,
550 peertubeLink: this.peertubeLink,
551 poster: window.location.origin + videoInfo.previewPath,
552 theaterButton: false,
554 serverUrl: window.location.origin,
555 language: navigator.language,
556 embedUrl: window.location.origin + videoInfo.embedPath,
557 embedTitle: videoInfo.name
561 videoFiles: videoInfo.files
565 if (this.mode === 'p2p-media-loader') {
566 const hlsPlaylist = videoInfo.streamingPlaylists.find(p => p.type === VideoStreamingPlaylistType.HLS)
568 Object.assign(options, {
570 playlistUrl: hlsPlaylist.playlistUrl,
571 segmentsSha256Url: hlsPlaylist.segmentsSha256Url,
572 redundancyBaseUrls: hlsPlaylist.redundancies.map(r => r.baseUrl),
573 trackerAnnounce: videoInfo.trackerUrls,
574 videoFiles: hlsPlaylist.files
575 } as P2PMediaLoaderOptions
579 this.player = await PeertubePlayerManager.initialize(this.mode, options, (player: videojs.Player) => this.player = player)
580 this.player.on('customError', (event: any, data: any) => this.handleError(data.err, serverTranslations))
582 window[ 'videojsPlayer' ] = this.player
586 await this.buildDock(videoInfo)
590 this.removePlaceholder()
592 if (this.isPlaylistEmbed()) {
593 await this.buildPlaylistManager()
595 this.player.playlist().updateSelected()
597 this.player.on('stopped', () => {
602 this.runHook('action:embed.player.loaded', undefined, { player: this.player, videojs, video: videoInfo })
605 private async initCore () {
606 if (this.userTokens) this.setHeadersFromTokens()
608 this.translationsPromise = TranslationsManager.getServerTranslations(window.location.origin, navigator.language)
609 this.PeertubePlayerManagerModulePromise = import('../../assets/player/peertube-player-manager')
613 if (this.isPlaylistEmbed()) {
614 const playlistId = this.getResourceId()
615 const res = await this.loadPlaylist(playlistId)
616 if (!res) return undefined
618 this.playlist = await res.playlistResponse.json()
620 const playlistElementResult = await res.videosResponse.json()
621 this.playlistElements = await this.loadAllPlaylistVideos(playlistId, playlistElementResult)
623 const params = new URL(window.location.toString()).searchParams
624 const playlistPositionParam = this.getParamString(params, 'playlistPosition')
628 if (playlistPositionParam) {
629 position = parseInt(playlistPositionParam + '', 10)
632 this.currentPlaylistElement = this.playlistElements.find(e => e.position === position)
633 if (!this.currentPlaylistElement || !this.currentPlaylistElement.video) {
634 console.error('Current playlist element is not valid.', this.currentPlaylistElement)
635 this.currentPlaylistElement = this.getNextPlaylistElement()
638 if (!this.currentPlaylistElement) {
639 console.error('This playlist does not have any valid element.')
640 const serverTranslations = await this.translationsPromise
641 this.playlistFetchError(serverTranslations)
645 videoId = this.currentPlaylistElement.video.uuid
647 videoId = this.getResourceId()
650 return this.loadVideoAndBuildPlayer(videoId)
653 private handleError (err: Error, translations?: { [ id: string ]: string }) {
654 if (err.message.indexOf('from xs param') !== -1) {
655 this.player.dispose()
656 this.playerElement = null
657 this.displayError('This video is not available because the remote instance is not responding.', translations)
662 private async buildDock (videoInfo: VideoDetails) {
663 if (!this.controls) return
665 // On webtorrent fallback, player may have been disposed
666 if (!this.player.player_) return
668 const title = this.title ? videoInfo.name : undefined
670 const description = this.config.tracker.enabled && this.warningTitle
671 ? '<span class="text">' + peertubeTranslate('Watching this video may reveal your IP address to others.') + '</span>'
674 if (title || description) {
682 private buildCSS () {
683 const body = document.getElementById('custom-css')
685 if (this.bigPlayBackgroundColor) {
686 body.style.setProperty('--embedBigPlayBackgroundColor', this.bigPlayBackgroundColor)
689 if (this.foregroundColor) {
690 body.style.setProperty('--embedForegroundColor', this.foregroundColor)
694 private async buildCaptions (serverTranslations: any, captionsResponse: Response): Promise<VideoJSCaption[]> {
695 if (captionsResponse.ok) {
696 const { data } = (await captionsResponse.json()) as ResultList<VideoCaption>
698 return data.map(c => ({
699 label: peertubeTranslate(c.language.label, serverTranslations),
700 language: c.language.id,
701 src: window.location.origin + c.captionPath
708 private loadPlaceholder (video: VideoDetails) {
709 const placeholder = this.getPlaceholderElement()
711 const url = window.location.origin + video.previewPath
712 placeholder.style.backgroundImage = `url("${url}")`
713 placeholder.style.display = 'block'
716 private removePlaceholder () {
717 const placeholder = this.getPlaceholderElement()
718 placeholder.style.display = 'none'
721 private getPlaceholderElement () {
722 return document.getElementById('placeholder-preview')
725 private setHeadersFromTokens () {
726 this.headers.set('Authorization', `${this.userTokens.tokenType} ${this.userTokens.accessToken}`)
729 private removeTokensFromHeaders () {
730 this.headers.delete('Authorization')
733 private getResourceId () {
734 const urlParts = window.location.pathname.split('/')
735 return urlParts[ urlParts.length - 1 ]
738 private isPlaylistEmbed () {
739 return window.location.pathname.split('/')[1] === 'video-playlists'
742 private async ensurePluginsAreLoaded (translations?: { [ id: string ]: string }) {
743 if (this.config.plugin.registered.length === 0) return
745 for (const plugin of this.config.plugin.registered) {
746 for (const key of Object.keys(plugin.clientScripts)) {
747 const clientScript = plugin.clientScripts[key]
749 if (clientScript.scopes.includes('embed') === false) continue
751 const script = `/plugins/${plugin.name}/${plugin.version}/client-scripts/${clientScript.script}`
753 if (this.loadedScripts.has(script)) continue
759 scopes: clientScript.scopes
761 pluginType: PluginType.PLUGIN,
766 hooks: this.peertubeHooks,
768 onSettingsScripts: () => undefined,
769 peertubeHelpersFactory: _ => this.buildPeerTubeHelpers(translations)
775 private buildPeerTubeHelpers (translations?: { [ id: string ]: string }): RegisterClientHelpers {
776 function unimplemented (): any {
777 throw new Error('This helper is not implemented in embed.')
781 getBaseStaticRoute: unimplemented,
783 getSettings: unimplemented,
785 isLoggedIn: unimplemented,
786 getAuthHeader: unimplemented,
790 error: unimplemented,
791 success: unimplemented
794 showModal: unimplemented,
796 getServerConfig: unimplemented,
799 textMarkdownToHTML: unimplemented,
800 enhancedMarkdownToHTML: unimplemented
803 translate: (value: string) => {
804 return Promise.resolve(peertubeTranslate(value, translations))
809 private runHook <T> (hookName: ClientHookName, result?: T, params?: any): Promise<T> {
810 return runHook(this.peertubeHooks, hookName, result, params)
815 .catch(err => console.error('Cannot init embed.', err))