2 import '../../assets/player/dock/peertube-dock-component'
3 import '../../assets/player/dock/peertube-dock-plugin'
4 import videojs from 'video.js'
5 import { peertubeTranslate } from '../../../../shared/core-utils/i18n'
17 VideoStreamingPlaylistType
18 } from '../../../../shared/models'
19 import { P2PMediaLoaderOptions, PeertubePlayerManagerOptions, PlayerMode } from '../../assets/player'
20 import { VideoJSCaption } from '../../assets/player/peertube-videojs-typings'
21 import { TranslationsManager } from '../../assets/player/translations-manager'
22 import { isP2PEnabled } from '../../assets/player/utils'
23 import { getBoolOrDefault } from '../../root-helpers/local-storage-utils'
24 import { peertubeLocalStorage } from '../../root-helpers/peertube-web-storage'
25 import { PluginsManager } from '../../root-helpers/plugins-manager'
26 import { UserLocalStorageKeys, UserTokens } from '../../root-helpers/users'
27 import { objectToUrlEncoded } from '../../root-helpers/utils'
28 import { RegisterClientHelpers } from '../../types/register-client-option.model'
29 import { PeerTubeEmbedApi } from './embed-api'
31 type Translations = { [ id: string ]: string }
33 export class PeerTubeEmbed {
34 playerElement: HTMLVideoElement
35 player: videojs.Player
36 api: PeerTubeEmbedApi = null
44 startTime: number | string = 0
45 stopTime: number | string
51 bigPlayBackgroundColor: string
52 foregroundColor: string
57 userTokens: UserTokens
58 headers = new Headers()
59 LOCAL_STORAGE_OAUTH_CLIENT_KEYS = {
60 CLIENT_ID: 'client_id',
61 CLIENT_SECRET: 'client_secret'
64 config: HTMLServerConfig
66 private translationsPromise: Promise<{ [id: string]: string }>
67 private PeertubePlayerManagerModulePromise: Promise<any>
69 private playlist: VideoPlaylist
70 private playlistElements: VideoPlaylistElement[]
71 private currentPlaylistElement: VideoPlaylistElement
73 private readonly wrapperElement: HTMLElement
75 private pluginsManager: PluginsManager
77 constructor (private readonly videoWrapperId: string) {
78 this.wrapperElement = document.getElementById(this.videoWrapperId)
81 this.config = JSON.parse(window['PeerTubeServerConfig'])
83 console.error('Cannot parse HTML config.', err)
87 static async main () {
88 const videoContainerId = 'video-wrapper'
89 const embed = new PeerTubeEmbed(videoContainerId)
93 getVideoUrl (id: string) {
94 return window.location.origin + '/api/v1/videos/' + id
97 refreshFetch (url: string, options?: RequestInit) {
98 return fetch(url, options)
99 .then((res: Response) => {
100 if (res.status !== HttpStatusCode.UNAUTHORIZED_401) return res
102 const refreshingTokenPromise = new Promise<void>((resolve, reject) => {
103 const clientId: string = peertubeLocalStorage.getItem(this.LOCAL_STORAGE_OAUTH_CLIENT_KEYS.CLIENT_ID)
104 const clientSecret: string = peertubeLocalStorage.getItem(this.LOCAL_STORAGE_OAUTH_CLIENT_KEYS.CLIENT_SECRET)
106 const headers = new Headers()
107 headers.set('Content-Type', 'application/x-www-form-urlencoded')
110 refresh_token: this.userTokens.refreshToken,
112 client_secret: clientSecret,
113 response_type: 'code',
114 grant_type: 'refresh_token'
117 fetch('/api/v1/users/token', {
120 body: objectToUrlEncoded(data)
122 if (res.status === HttpStatusCode.UNAUTHORIZED_401) return undefined
125 }).then((obj: UserRefreshToken & { code?: OAuth2ErrorCode }) => {
126 if (!obj || obj.code === OAuth2ErrorCode.INVALID_GRANT) {
127 UserTokens.flushLocalStorage(peertubeLocalStorage)
128 this.removeTokensFromHeaders()
133 this.userTokens.accessToken = obj.access_token
134 this.userTokens.refreshToken = obj.refresh_token
135 UserTokens.saveToLocalStorage(peertubeLocalStorage, this.userTokens)
137 this.setHeadersFromTokens()
140 }).catch((refreshTokenError: any) => {
141 reject(refreshTokenError)
145 return refreshingTokenPromise
147 UserTokens.flushLocalStorage(peertubeLocalStorage)
149 this.removeTokensFromHeaders()
150 }).then(() => fetch(url, {
152 headers: this.headers
157 getPlaylistUrl (id: string) {
158 return window.location.origin + '/api/v1/video-playlists/' + id
161 loadVideoInfo (videoId: string): Promise<Response> {
162 return this.refreshFetch(this.getVideoUrl(videoId), { headers: this.headers })
165 loadVideoCaptions (videoId: string): Promise<Response> {
166 return this.refreshFetch(this.getVideoUrl(videoId) + '/captions', { headers: this.headers })
169 loadPlaylistInfo (playlistId: string): Promise<Response> {
170 return this.refreshFetch(this.getPlaylistUrl(playlistId), { headers: this.headers })
173 loadPlaylistElements (playlistId: string, start = 0): Promise<Response> {
174 const url = new URL(this.getPlaylistUrl(playlistId) + '/videos')
175 url.search = new URLSearchParams({ start: '' + start, count: '100' }).toString()
177 return this.refreshFetch(url.toString(), { headers: this.headers })
180 removeElement (element: HTMLElement) {
181 element.parentElement.removeChild(element)
184 displayError (text: string, translations?: Translations) {
185 // Remove video element
186 if (this.playerElement) {
187 this.removeElement(this.playerElement)
188 this.playerElement = undefined
191 const translatedText = peertubeTranslate(text, translations)
192 const translatedSorry = peertubeTranslate('Sorry', translations)
194 document.title = translatedSorry + ' - ' + translatedText
196 const errorBlock = document.getElementById('error-block')
197 errorBlock.style.display = 'flex'
199 const errorTitle = document.getElementById('error-title')
200 errorTitle.innerHTML = peertubeTranslate('Sorry', translations)
202 const errorText = document.getElementById('error-content')
203 errorText.innerHTML = translatedText
205 this.wrapperElement.style.display = 'none'
208 videoNotFound (translations?: Translations) {
209 const text = 'This video does not exist.'
210 this.displayError(text, translations)
213 videoFetchError (translations?: Translations) {
214 const text = 'We cannot fetch the video. Please try again later.'
215 this.displayError(text, translations)
218 playlistNotFound (translations?: Translations) {
219 const text = 'This playlist does not exist.'
220 this.displayError(text, translations)
223 playlistFetchError (translations?: Translations) {
224 const text = 'We cannot fetch the playlist. Please try again later.'
225 this.displayError(text, translations)
228 getParamToggle (params: URLSearchParams, name: string, defaultValue?: boolean) {
229 return params.has(name) ? (params.get(name) === '1' || params.get(name) === 'true') : defaultValue
232 getParamString (params: URLSearchParams, name: string, defaultValue?: string) {
233 return params.has(name) ? params.get(name) : defaultValue
236 async playNextVideo () {
237 const next = this.getNextPlaylistElement()
239 console.log('Next element not found in playlist.')
243 this.currentPlaylistElement = next
245 return this.loadVideoAndBuildPlayer(this.currentPlaylistElement.video.uuid)
248 async playPreviousVideo () {
249 const previous = this.getPreviousPlaylistElement()
251 console.log('Previous element not found in playlist.')
255 this.currentPlaylistElement = previous
257 await this.loadVideoAndBuildPlayer(this.currentPlaylistElement.video.uuid)
260 getCurrentPosition () {
261 if (!this.currentPlaylistElement) return -1
263 return this.currentPlaylistElement.position
267 this.userTokens = UserTokens.getUserTokens(peertubeLocalStorage)
268 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)
290 this.p2pEnabled = this.getParamToggle(params, 'p2p', this.isP2PEnabled(video))
292 this.scope = this.getParamString(params, 'scope', this.scope)
293 this.subtitle = this.getParamString(params, 'subtitle')
294 this.startTime = this.getParamString(params, 'start')
295 this.stopTime = this.getParamString(params, 'stop')
297 this.bigPlayBackgroundColor = this.getParamString(params, 'bigPlayBackgroundColor')
298 this.foregroundColor = this.getParamString(params, 'foregroundColor')
300 const modeParam = this.getParamString(params, 'mode')
303 if (modeParam === 'p2p-media-loader') this.mode = 'p2p-media-loader'
304 else this.mode = 'webtorrent'
306 if (Array.isArray(video.streamingPlaylists) && video.streamingPlaylists.length !== 0) this.mode = 'p2p-media-loader'
307 else this.mode = 'webtorrent'
310 console.error('Cannot get params from URL.', err)
314 private async loadAllPlaylistVideos (playlistId: string, baseResult: ResultList<VideoPlaylistElement>) {
315 let elements = baseResult.data
316 let total = baseResult.total
319 while (total > elements.length && i < 10) {
320 const result = await this.loadPlaylistElements(playlistId, elements.length)
322 const json = await result.json()
325 elements = elements.concat(json.data)
330 console.error('Cannot fetch all playlists elements, there are too many!')
336 private async loadPlaylist (playlistId: string) {
337 const playlistPromise = this.loadPlaylistInfo(playlistId)
338 const playlistElementsPromise = this.loadPlaylistElements(playlistId)
340 let playlistResponse: Response
341 let isResponseOk: boolean
344 playlistResponse = await playlistPromise
345 isResponseOk = playlistResponse.status === HttpStatusCode.OK_200
352 const serverTranslations = await this.translationsPromise
354 if (playlistResponse?.status === HttpStatusCode.NOT_FOUND_404) {
355 this.playlistNotFound(serverTranslations)
359 this.playlistFetchError(serverTranslations)
363 return { playlistResponse, videosResponse: await playlistElementsPromise }
366 private async loadVideo (videoId: string) {
367 const videoPromise = this.loadVideoInfo(videoId)
369 let videoResponse: Response
370 let isResponseOk: boolean
373 videoResponse = await videoPromise
374 isResponseOk = videoResponse.status === HttpStatusCode.OK_200
382 const serverTranslations = await this.translationsPromise
384 if (videoResponse?.status === HttpStatusCode.NOT_FOUND_404) {
385 this.videoNotFound(serverTranslations)
389 this.videoFetchError(serverTranslations)
393 const captionsPromise = this.loadVideoCaptions(videoId)
395 return { captionsPromise, videoResponse }
398 private async buildPlaylistManager () {
399 const translations = await this.translationsPromise
402 timeout: 10000, // 10s
403 headText: peertubeTranslate('Up Next', translations),
404 cancelText: peertubeTranslate('Cancel', translations),
405 suspendedText: peertubeTranslate('Autoplay is suspended', translations),
406 getTitle: () => this.nextVideoTitle(),
407 next: () => this.playNextVideo(),
408 condition: () => !!this.getNextPlaylistElement(),
409 suspended: () => false
413 private async loadVideoAndBuildPlayer (uuid: string) {
414 const res = await this.loadVideo(uuid)
415 if (res === undefined) return
417 return this.buildVideoPlayer(res.videoResponse, res.captionsPromise)
420 private nextVideoTitle () {
421 const next = this.getNextPlaylistElement()
424 return next.video.name
427 private getNextPlaylistElement (position?: number): VideoPlaylistElement {
428 if (!position) position = this.currentPlaylistElement.position + 1
430 if (position > this.playlist.videosLength) {
434 const next = this.playlistElements.find(e => e.position === position)
436 if (!next || !next.video) {
437 return this.getNextPlaylistElement(position + 1)
443 private getPreviousPlaylistElement (position?: number): VideoPlaylistElement {
444 if (!position) position = this.currentPlaylistElement.position - 1
450 const prev = this.playlistElements.find(e => e.position === position)
452 if (!prev || !prev.video) {
453 return this.getNextPlaylistElement(position - 1)
459 private async buildVideoPlayer (videoResponse: Response, captionsPromise: Promise<Response>) {
460 let alreadyHadPlayer = false
463 this.player.dispose()
464 alreadyHadPlayer = true
467 this.playerElement = document.createElement('video')
468 this.playerElement.className = 'video-js vjs-peertube-skin'
469 this.playerElement.setAttribute('playsinline', 'true')
470 this.wrapperElement.appendChild(this.playerElement)
472 // Issue when we parsed config from HTML, fallback to API
474 this.config = await this.refreshFetch('/api/v1/config')
475 .then(res => res.json())
478 const videoInfoPromise = videoResponse.json()
479 .then((videoInfo: VideoDetails) => {
480 this.loadParams(videoInfo)
482 if (!alreadyHadPlayer && !this.autoplay) this.loadPlaceholder(videoInfo)
487 const [ videoInfoTmp, serverTranslations, captionsResponse, PeertubePlayerManagerModule ] = await Promise.all([
489 this.translationsPromise,
491 this.PeertubePlayerManagerModulePromise
494 await this.loadPlugins(serverTranslations)
496 const videoInfo: VideoDetails = videoInfoTmp
498 const PeertubePlayerManager = PeertubePlayerManagerModule.PeertubePlayerManager
499 const videoCaptions = await this.buildCaptions(serverTranslations, captionsResponse)
501 const playlistPlugin = this.currentPlaylistElement
503 elements: this.playlistElements,
504 playlist: this.playlist,
506 getCurrentPosition: () => this.currentPlaylistElement.position,
508 onItemClicked: (videoPlaylistElement: VideoPlaylistElement) => {
509 this.currentPlaylistElement = videoPlaylistElement
511 this.loadVideoAndBuildPlayer(this.currentPlaylistElement.video.uuid)
512 .catch(err => console.error(err))
517 const options: PeertubePlayerManagerOptions = {
519 // Autoplay in playlist mode
520 autoplay: alreadyHadPlayer ? true : this.autoplay,
521 controls: this.controls,
525 p2pEnabled: this.p2pEnabled,
527 captions: videoCaptions.length !== 0,
528 subtitle: this.subtitle,
530 startTime: this.playlist ? this.currentPlaylistElement.startTimestamp : this.startTime,
531 stopTime: this.playlist ? this.currentPlaylistElement.stopTimestamp : this.stopTime,
533 nextVideo: this.playlist ? () => this.playNextVideo() : undefined,
534 hasNextVideo: this.playlist ? () => !!this.getNextPlaylistElement() : undefined,
536 previousVideo: this.playlist ? () => this.playPreviousVideo() : undefined,
537 hasPreviousVideo: this.playlist ? () => !!this.getPreviousPlaylistElement() : undefined,
539 playlist: playlistPlugin,
542 inactivityTimeout: 2500,
543 videoViewUrl: this.getVideoUrl(videoInfo.uuid) + '/views',
544 videoShortUUID: videoInfo.shortUUID,
545 videoUUID: videoInfo.uuid,
547 isLive: videoInfo.isLive,
549 playerElement: this.playerElement,
550 onPlayerElementChange: (element: HTMLVideoElement) => {
551 this.playerElement = element
554 videoDuration: videoInfo.duration,
556 peertubeLink: this.peertubeLink,
557 poster: window.location.origin + videoInfo.previewPath,
558 theaterButton: false,
560 serverUrl: window.location.origin,
561 language: navigator.language,
562 embedUrl: window.location.origin + videoInfo.embedPath,
563 embedTitle: videoInfo.name,
565 errorNotifier: () => {
566 // Empty, we don't have a notifier in the embed
571 videoFiles: videoInfo.files
574 pluginsManager: this.pluginsManager
577 if (this.mode === 'p2p-media-loader') {
578 const hlsPlaylist = videoInfo.streamingPlaylists.find(p => p.type === VideoStreamingPlaylistType.HLS)
580 Object.assign(options, {
582 playlistUrl: hlsPlaylist.playlistUrl,
583 segmentsSha256Url: hlsPlaylist.segmentsSha256Url,
584 redundancyBaseUrls: hlsPlaylist.redundancies.map(r => r.baseUrl),
585 trackerAnnounce: videoInfo.trackerUrls,
586 videoFiles: hlsPlaylist.files
587 } as P2PMediaLoaderOptions
591 this.player = await PeertubePlayerManager.initialize(this.mode, options, (player: videojs.Player) => {
595 this.player.on('customError', (event: any, data: any) => this.handleError(data.err, serverTranslations))
597 window['videojsPlayer'] = this.player
601 this.buildDock(videoInfo)
605 this.removePlaceholder()
607 if (this.isPlaylistEmbed()) {
608 await this.buildPlaylistManager()
610 this.player.playlist().updateSelected()
612 this.player.on('stopped', () => {
617 this.pluginsManager.runHook('action:embed.player.loaded', undefined, { player: this.player, videojs, video: videoInfo })
620 private async initCore () {
621 if (this.userTokens) this.setHeadersFromTokens()
623 this.translationsPromise = TranslationsManager.getServerTranslations(window.location.origin, navigator.language)
624 this.PeertubePlayerManagerModulePromise = import('../../assets/player/peertube-player-manager')
628 if (this.isPlaylistEmbed()) {
629 const playlistId = this.getResourceId()
630 const res = await this.loadPlaylist(playlistId)
631 if (!res) return undefined
633 this.playlist = await res.playlistResponse.json()
635 const playlistElementResult = await res.videosResponse.json()
636 this.playlistElements = await this.loadAllPlaylistVideos(playlistId, playlistElementResult)
638 const params = new URL(window.location.toString()).searchParams
639 const playlistPositionParam = this.getParamString(params, 'playlistPosition')
643 if (playlistPositionParam) {
644 position = parseInt(playlistPositionParam + '', 10)
647 this.currentPlaylistElement = this.playlistElements.find(e => e.position === position)
648 if (!this.currentPlaylistElement || !this.currentPlaylistElement.video) {
649 console.error('Current playlist element is not valid.', this.currentPlaylistElement)
650 this.currentPlaylistElement = this.getNextPlaylistElement()
653 if (!this.currentPlaylistElement) {
654 console.error('This playlist does not have any valid element.')
655 const serverTranslations = await this.translationsPromise
656 this.playlistFetchError(serverTranslations)
660 videoId = this.currentPlaylistElement.video.uuid
662 videoId = this.getResourceId()
665 return this.loadVideoAndBuildPlayer(videoId)
668 private handleError (err: Error, translations?: { [ id: string ]: string }) {
669 if (err.message.includes('from xs param')) {
670 this.player.dispose()
671 this.playerElement = null
672 this.displayError('This video is not available because the remote instance is not responding.', translations)
676 private buildDock (videoInfo: VideoDetails) {
677 if (!this.controls) return
679 // On webtorrent fallback, player may have been disposed
680 if (!this.player.player_) return
682 const title = this.title ? videoInfo.name : undefined
683 const description = this.warningTitle && this.p2pEnabled
684 ? '<span class="text">' + peertubeTranslate('Watching this video may reveal your IP address to others.') + '</span>'
687 const availableAvatars = videoInfo.channel.avatars.filter(a => a.width < 50)
688 const avatar = availableAvatars.length !== 0
689 ? availableAvatars[0]
692 if (title || description) {
693 this.player.peertubeDock({
696 avatarUrl: title && avatar
703 private buildCSS () {
704 const body = document.getElementById('custom-css')
706 if (this.bigPlayBackgroundColor) {
707 body.style.setProperty('--embedBigPlayBackgroundColor', this.bigPlayBackgroundColor)
710 if (this.foregroundColor) {
711 body.style.setProperty('--embedForegroundColor', this.foregroundColor)
715 private async buildCaptions (serverTranslations: any, captionsResponse: Response): Promise<VideoJSCaption[]> {
716 if (captionsResponse.ok) {
717 const { data } = await captionsResponse.json()
719 return data.map((c: VideoCaption) => ({
720 label: peertubeTranslate(c.language.label, serverTranslations),
721 language: c.language.id,
722 src: window.location.origin + c.captionPath
729 private loadPlaceholder (video: VideoDetails) {
730 const placeholder = this.getPlaceholderElement()
732 const url = window.location.origin + video.previewPath
733 placeholder.style.backgroundImage = `url("${url}")`
734 placeholder.style.display = 'block'
737 private removePlaceholder () {
738 const placeholder = this.getPlaceholderElement()
739 placeholder.style.display = 'none'
742 private getPlaceholderElement () {
743 return document.getElementById('placeholder-preview')
746 private setHeadersFromTokens () {
747 this.headers.set('Authorization', `${this.userTokens.tokenType} ${this.userTokens.accessToken}`)
750 private removeTokensFromHeaders () {
751 this.headers.delete('Authorization')
754 private getResourceId () {
755 const urlParts = window.location.pathname.split('/')
756 return urlParts[urlParts.length - 1]
759 private isPlaylistEmbed () {
760 return window.location.pathname.split('/')[1] === 'video-playlists'
763 private loadPlugins (translations?: { [ id: string ]: string }) {
764 this.pluginsManager = new PluginsManager({
765 peertubeHelpersFactory: _ => this.buildPeerTubeHelpers(translations)
768 this.pluginsManager.loadPluginsList(this.config)
770 return this.pluginsManager.ensurePluginsAreLoaded('embed')
773 private buildPeerTubeHelpers (translations?: { [ id: string ]: string }): RegisterClientHelpers {
774 const unimplemented = () => {
775 throw new Error('This helper is not implemented in embed.')
779 getBaseStaticRoute: unimplemented,
780 getBaseRouterRoute: unimplemented,
781 getBasePluginClientPath: 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) => Promise.resolve(peertubeTranslate(value, translations))
807 private isP2PEnabled (video: Video) {
808 const userP2PEnabled = getBoolOrDefault(
809 peertubeLocalStorage.getItem(UserLocalStorageKeys.P2P_ENABLED),
810 this.config.defaults.p2p.embed.enabled
813 return isP2PEnabled(video, this.config, userP2PEnabled)
819 (window as any).displayIncompatibleBrowser()
821 console.error('Cannot init embed.', err)