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
48 bigPlayBackgroundColor: string
49 foregroundColor: string
54 userTokens: UserTokens
55 headers = new Headers()
56 LOCAL_STORAGE_OAUTH_CLIENT_KEYS = {
57 CLIENT_ID: 'client_id',
58 CLIENT_SECRET: 'client_secret'
61 config: HTMLServerConfig
63 private translationsPromise: Promise<{ [id: string]: string }>
64 private PeertubePlayerManagerModulePromise: Promise<any>
66 private playlist: VideoPlaylist
67 private playlistElements: VideoPlaylistElement[]
68 private currentPlaylistElement: VideoPlaylistElement
70 private readonly wrapperElement: HTMLElement
72 private pluginsManager: PluginsManager
74 constructor (private readonly videoWrapperId: string) {
75 this.wrapperElement = document.getElementById(this.videoWrapperId)
78 this.config = JSON.parse(window['PeerTubeServerConfig'])
80 console.error('Cannot parse HTML config.', err)
84 static async main () {
85 const videoContainerId = 'video-wrapper'
86 const embed = new PeerTubeEmbed(videoContainerId)
90 getVideoUrl (id: string) {
91 return window.location.origin + '/api/v1/videos/' + id
94 refreshFetch (url: string, options?: RequestInit) {
95 return fetch(url, options)
96 .then((res: Response) => {
97 if (res.status !== HttpStatusCode.UNAUTHORIZED_401) return res
99 const refreshingTokenPromise = new Promise<void>((resolve, reject) => {
100 const clientId: string = peertubeLocalStorage.getItem(this.LOCAL_STORAGE_OAUTH_CLIENT_KEYS.CLIENT_ID)
101 const clientSecret: string = peertubeLocalStorage.getItem(this.LOCAL_STORAGE_OAUTH_CLIENT_KEYS.CLIENT_SECRET)
103 const headers = new Headers()
104 headers.set('Content-Type', 'application/x-www-form-urlencoded')
107 refresh_token: this.userTokens.refreshToken,
109 client_secret: clientSecret,
110 response_type: 'code',
111 grant_type: 'refresh_token'
114 fetch('/api/v1/users/token', {
117 body: objectToUrlEncoded(data)
119 if (res.status === HttpStatusCode.UNAUTHORIZED_401) return undefined
122 }).then((obj: UserRefreshToken & { code?: OAuth2ErrorCode }) => {
123 if (!obj || obj.code === OAuth2ErrorCode.INVALID_GRANT) {
124 UserTokens.flushLocalStorage(peertubeLocalStorage)
125 this.removeTokensFromHeaders()
130 this.userTokens.accessToken = obj.access_token
131 this.userTokens.refreshToken = obj.refresh_token
132 UserTokens.saveToLocalStorage(peertubeLocalStorage, this.userTokens)
134 this.setHeadersFromTokens()
137 }).catch((refreshTokenError: any) => {
138 reject(refreshTokenError)
142 return refreshingTokenPromise
144 UserTokens.flushLocalStorage(peertubeLocalStorage)
146 this.removeTokensFromHeaders()
147 }).then(() => fetch(url, {
149 headers: this.headers
154 getPlaylistUrl (id: string) {
155 return window.location.origin + '/api/v1/video-playlists/' + id
158 loadVideoInfo (videoId: string): Promise<Response> {
159 return this.refreshFetch(this.getVideoUrl(videoId), { headers: this.headers })
162 loadVideoCaptions (videoId: string): Promise<Response> {
163 return this.refreshFetch(this.getVideoUrl(videoId) + '/captions', { headers: this.headers })
166 loadPlaylistInfo (playlistId: string): Promise<Response> {
167 return this.refreshFetch(this.getPlaylistUrl(playlistId), { headers: this.headers })
170 loadPlaylistElements (playlistId: string, start = 0): Promise<Response> {
171 const url = new URL(this.getPlaylistUrl(playlistId) + '/videos')
172 url.search = new URLSearchParams({ start: '' + start, count: '100' }).toString()
174 return this.refreshFetch(url.toString(), { headers: this.headers })
177 removeElement (element: HTMLElement) {
178 element.parentElement.removeChild(element)
181 displayError (text: string, translations?: Translations) {
182 // Remove video element
183 if (this.playerElement) {
184 this.removeElement(this.playerElement)
185 this.playerElement = undefined
188 const translatedText = peertubeTranslate(text, translations)
189 const translatedSorry = peertubeTranslate('Sorry', translations)
191 document.title = translatedSorry + ' - ' + translatedText
193 const errorBlock = document.getElementById('error-block')
194 errorBlock.style.display = 'flex'
196 const errorTitle = document.getElementById('error-title')
197 errorTitle.innerHTML = peertubeTranslate('Sorry', translations)
199 const errorText = document.getElementById('error-content')
200 errorText.innerHTML = translatedText
202 this.wrapperElement.style.display = 'none'
205 videoNotFound (translations?: Translations) {
206 const text = 'This video does not exist.'
207 this.displayError(text, translations)
210 videoFetchError (translations?: Translations) {
211 const text = 'We cannot fetch the video. Please try again later.'
212 this.displayError(text, translations)
215 playlistNotFound (translations?: Translations) {
216 const text = 'This playlist does not exist.'
217 this.displayError(text, translations)
220 playlistFetchError (translations?: Translations) {
221 const text = 'We cannot fetch the playlist. Please try again later.'
222 this.displayError(text, translations)
225 getParamToggle (params: URLSearchParams, name: string, defaultValue?: boolean) {
226 return params.has(name) ? (params.get(name) === '1' || params.get(name) === 'true') : defaultValue
229 getParamString (params: URLSearchParams, name: string, defaultValue?: string) {
230 return params.has(name) ? params.get(name) : defaultValue
233 async playNextVideo () {
234 const next = this.getNextPlaylistElement()
236 console.log('Next element not found in playlist.')
240 this.currentPlaylistElement = next
242 return this.loadVideoAndBuildPlayer(this.currentPlaylistElement.video.uuid)
245 async playPreviousVideo () {
246 const previous = this.getPreviousPlaylistElement()
248 console.log('Previous element not found in playlist.')
252 this.currentPlaylistElement = previous
254 await this.loadVideoAndBuildPlayer(this.currentPlaylistElement.video.uuid)
257 getCurrentPosition () {
258 if (!this.currentPlaylistElement) return -1
260 return this.currentPlaylistElement.position
264 this.userTokens = UserTokens.getUserTokens(peertubeLocalStorage)
265 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()
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 === HttpStatusCode.OK_200
348 const serverTranslations = await this.translationsPromise
350 if (playlistResponse?.status === HttpStatusCode.NOT_FOUND_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 === HttpStatusCode.OK_200
378 const serverTranslations = await this.translationsPromise
380 if (videoResponse?.status === HttpStatusCode.NOT_FOUND_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 // Issue when we parsed config from HTML, fallback to API
470 this.config = await this.refreshFetch('/api/v1/config')
471 .then(res => res.json())
474 const videoInfoPromise = videoResponse.json()
475 .then((videoInfo: VideoDetails) => {
476 this.loadParams(videoInfo)
478 if (!alreadyHadPlayer && !this.autoplay) this.loadPlaceholder(videoInfo)
483 const [ videoInfoTmp, serverTranslations, captionsResponse, PeertubePlayerManagerModule ] = await Promise.all([
485 this.translationsPromise,
487 this.PeertubePlayerManagerModulePromise
490 await this.loadPlugins(serverTranslations)
492 const videoInfo: VideoDetails = videoInfoTmp
494 const PeertubePlayerManager = PeertubePlayerManagerModule.PeertubePlayerManager
495 const videoCaptions = await this.buildCaptions(serverTranslations, captionsResponse)
497 const playlistPlugin = this.currentPlaylistElement
499 elements: this.playlistElements,
500 playlist: this.playlist,
502 getCurrentPosition: () => this.currentPlaylistElement.position,
504 onItemClicked: (videoPlaylistElement: VideoPlaylistElement) => {
505 this.currentPlaylistElement = videoPlaylistElement
507 this.loadVideoAndBuildPlayer(this.currentPlaylistElement.video.uuid)
508 .catch(err => console.error(err))
513 const options: PeertubePlayerManagerOptions = {
515 // Autoplay in playlist mode
516 autoplay: alreadyHadPlayer ? true : this.autoplay,
517 controls: this.controls,
521 p2pEnabled: this.isP2PEnabled(videoInfo),
523 captions: videoCaptions.length !== 0,
524 subtitle: this.subtitle,
526 startTime: this.playlist ? this.currentPlaylistElement.startTimestamp : this.startTime,
527 stopTime: this.playlist ? this.currentPlaylistElement.stopTimestamp : this.stopTime,
529 nextVideo: this.playlist ? () => this.playNextVideo() : undefined,
530 hasNextVideo: this.playlist ? () => !!this.getNextPlaylistElement() : undefined,
532 previousVideo: this.playlist ? () => this.playPreviousVideo() : undefined,
533 hasPreviousVideo: this.playlist ? () => !!this.getPreviousPlaylistElement() : undefined,
535 playlist: playlistPlugin,
538 inactivityTimeout: 2500,
539 videoViewUrl: this.getVideoUrl(videoInfo.uuid) + '/views',
540 videoShortUUID: videoInfo.shortUUID,
541 videoUUID: videoInfo.uuid,
543 isLive: videoInfo.isLive,
545 playerElement: this.playerElement,
546 onPlayerElementChange: (element: HTMLVideoElement) => {
547 this.playerElement = element
550 videoDuration: videoInfo.duration,
552 peertubeLink: this.peertubeLink,
553 poster: window.location.origin + videoInfo.previewPath,
554 theaterButton: false,
556 serverUrl: window.location.origin,
557 language: navigator.language,
558 embedUrl: window.location.origin + videoInfo.embedPath,
559 embedTitle: videoInfo.name
563 videoFiles: videoInfo.files
566 pluginsManager: this.pluginsManager
569 if (this.mode === 'p2p-media-loader') {
570 const hlsPlaylist = videoInfo.streamingPlaylists.find(p => p.type === VideoStreamingPlaylistType.HLS)
572 Object.assign(options, {
574 playlistUrl: hlsPlaylist.playlistUrl,
575 segmentsSha256Url: hlsPlaylist.segmentsSha256Url,
576 redundancyBaseUrls: hlsPlaylist.redundancies.map(r => r.baseUrl),
577 trackerAnnounce: videoInfo.trackerUrls,
578 videoFiles: hlsPlaylist.files
579 } as P2PMediaLoaderOptions
583 this.player = await PeertubePlayerManager.initialize(this.mode, options, (player: videojs.Player) => {
587 this.player.on('customError', (event: any, data: any) => this.handleError(data.err, serverTranslations))
589 window['videojsPlayer'] = this.player
593 this.buildDock(videoInfo)
597 this.removePlaceholder()
599 if (this.isPlaylistEmbed()) {
600 await this.buildPlaylistManager()
602 this.player.playlist().updateSelected()
604 this.player.on('stopped', () => {
609 this.pluginsManager.runHook('action:embed.player.loaded', undefined, { player: this.player, videojs, video: videoInfo })
612 private async initCore () {
613 if (this.userTokens) this.setHeadersFromTokens()
615 this.translationsPromise = TranslationsManager.getServerTranslations(window.location.origin, navigator.language)
616 this.PeertubePlayerManagerModulePromise = import('../../assets/player/peertube-player-manager')
620 if (this.isPlaylistEmbed()) {
621 const playlistId = this.getResourceId()
622 const res = await this.loadPlaylist(playlistId)
623 if (!res) return undefined
625 this.playlist = await res.playlistResponse.json()
627 const playlistElementResult = await res.videosResponse.json()
628 this.playlistElements = await this.loadAllPlaylistVideos(playlistId, playlistElementResult)
630 const params = new URL(window.location.toString()).searchParams
631 const playlistPositionParam = this.getParamString(params, 'playlistPosition')
635 if (playlistPositionParam) {
636 position = parseInt(playlistPositionParam + '', 10)
639 this.currentPlaylistElement = this.playlistElements.find(e => e.position === position)
640 if (!this.currentPlaylistElement || !this.currentPlaylistElement.video) {
641 console.error('Current playlist element is not valid.', this.currentPlaylistElement)
642 this.currentPlaylistElement = this.getNextPlaylistElement()
645 if (!this.currentPlaylistElement) {
646 console.error('This playlist does not have any valid element.')
647 const serverTranslations = await this.translationsPromise
648 this.playlistFetchError(serverTranslations)
652 videoId = this.currentPlaylistElement.video.uuid
654 videoId = this.getResourceId()
657 return this.loadVideoAndBuildPlayer(videoId)
660 private handleError (err: Error, translations?: { [ id: string ]: string }) {
661 if (err.message.includes('from xs param')) {
662 this.player.dispose()
663 this.playerElement = null
664 this.displayError('This video is not available because the remote instance is not responding.', translations)
669 private buildDock (videoInfo: VideoDetails) {
670 if (!this.controls) return
672 // On webtorrent fallback, player may have been disposed
673 if (!this.player.player_) return
675 const title = this.title ? videoInfo.name : undefined
677 const description = this.warningTitle && this.isP2PEnabled(videoInfo)
678 ? '<span class="text">' + peertubeTranslate('Watching this video may reveal your IP address to others.') + '</span>'
681 if (title || description) {
689 private buildCSS () {
690 const body = document.getElementById('custom-css')
692 if (this.bigPlayBackgroundColor) {
693 body.style.setProperty('--embedBigPlayBackgroundColor', this.bigPlayBackgroundColor)
696 if (this.foregroundColor) {
697 body.style.setProperty('--embedForegroundColor', this.foregroundColor)
701 private async buildCaptions (serverTranslations: any, captionsResponse: Response): Promise<VideoJSCaption[]> {
702 if (captionsResponse.ok) {
703 const { data } = await captionsResponse.json()
705 return data.map((c: VideoCaption) => ({
706 label: peertubeTranslate(c.language.label, serverTranslations),
707 language: c.language.id,
708 src: window.location.origin + c.captionPath
715 private loadPlaceholder (video: VideoDetails) {
716 const placeholder = this.getPlaceholderElement()
718 const url = window.location.origin + video.previewPath
719 placeholder.style.backgroundImage = `url("${url}")`
720 placeholder.style.display = 'block'
723 private removePlaceholder () {
724 const placeholder = this.getPlaceholderElement()
725 placeholder.style.display = 'none'
728 private getPlaceholderElement () {
729 return document.getElementById('placeholder-preview')
732 private setHeadersFromTokens () {
733 this.headers.set('Authorization', `${this.userTokens.tokenType} ${this.userTokens.accessToken}`)
736 private removeTokensFromHeaders () {
737 this.headers.delete('Authorization')
740 private getResourceId () {
741 const urlParts = window.location.pathname.split('/')
742 return urlParts[urlParts.length - 1]
745 private isPlaylistEmbed () {
746 return window.location.pathname.split('/')[1] === 'video-playlists'
749 private loadPlugins (translations?: { [ id: string ]: string }) {
750 this.pluginsManager = new PluginsManager({
751 peertubeHelpersFactory: _ => this.buildPeerTubeHelpers(translations)
754 this.pluginsManager.loadPluginsList(this.config)
756 return this.pluginsManager.ensurePluginsAreLoaded('embed')
759 private buildPeerTubeHelpers (translations?: { [ id: string ]: string }): RegisterClientHelpers {
760 const unimplemented = () => {
761 throw new Error('This helper is not implemented in embed.')
765 getBaseStaticRoute: unimplemented,
766 getBaseRouterRoute: unimplemented,
767 getBasePluginClientPath: unimplemented,
769 getSettings: unimplemented,
771 isLoggedIn: unimplemented,
772 getAuthHeader: unimplemented,
776 error: unimplemented,
777 success: unimplemented
780 showModal: unimplemented,
782 getServerConfig: unimplemented,
785 textMarkdownToHTML: unimplemented,
786 enhancedMarkdownToHTML: unimplemented
789 translate: (value: string) => Promise.resolve(peertubeTranslate(value, translations))
793 private isP2PEnabled (video: Video) {
794 const userP2PEnabled = getBoolOrDefault(
795 peertubeLocalStorage.getItem(UserLocalStorageKeys.P2P_ENABLED),
796 this.config.defaults.p2p.embed.enabled
799 return isP2PEnabled(video, this.config, userP2PEnabled)
805 (window as any).displayIncompatibleBrowser()
807 console.error('Cannot init embed.', err)