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'
18 VideoStreamingPlaylistType
19 } from '../../../../shared/models'
20 import { P2PMediaLoaderOptions, PeertubePlayerManagerOptions, PlayerMode } from '../../assets/player'
21 import { VideoJSCaption } from '../../assets/player/peertube-videojs-typings'
22 import { TranslationsManager } from '../../assets/player/translations-manager'
23 import { isP2PEnabled } from '../../assets/player/utils'
24 import { getBoolOrDefault } from '../../root-helpers/local-storage-utils'
25 import { peertubeLocalStorage } from '../../root-helpers/peertube-web-storage'
26 import { PluginsManager } from '../../root-helpers/plugins-manager'
27 import { UserLocalStorageKeys, UserTokens } from '../../root-helpers/users'
28 import { objectToUrlEncoded } from '../../root-helpers/utils'
29 import { RegisterClientHelpers } from '../../types/register-client-option.model'
30 import { PeerTubeEmbedApi } from './embed-api'
32 type Translations = { [ id: string ]: string }
34 export class PeerTubeEmbed {
35 playerElement: HTMLVideoElement
36 player: videojs.Player
37 api: PeerTubeEmbedApi = null
45 startTime: number | string = 0
46 stopTime: number | string
52 bigPlayBackgroundColor: string
53 foregroundColor: string
58 userTokens: UserTokens
59 headers = new Headers()
60 LOCAL_STORAGE_OAUTH_CLIENT_KEYS = {
61 CLIENT_ID: 'client_id',
62 CLIENT_SECRET: 'client_secret'
65 config: HTMLServerConfig
67 private translationsPromise: Promise<{ [id: string]: string }>
68 private PeertubePlayerManagerModulePromise: Promise<any>
70 private playlist: VideoPlaylist
71 private playlistElements: VideoPlaylistElement[]
72 private currentPlaylistElement: VideoPlaylistElement
74 private readonly wrapperElement: HTMLElement
76 private pluginsManager: PluginsManager
78 constructor (private readonly videoWrapperId: string) {
79 this.wrapperElement = document.getElementById(this.videoWrapperId)
82 this.config = JSON.parse(window['PeerTubeServerConfig'])
84 console.error('Cannot parse HTML config.', err)
88 static async main () {
89 const videoContainerId = 'video-wrapper'
90 const embed = new PeerTubeEmbed(videoContainerId)
94 getVideoUrl (id: string) {
95 return window.location.origin + '/api/v1/videos/' + id
98 getLiveUrl (videoId: string) {
99 return window.location.origin + '/api/v1/videos/live/' + videoId
102 refreshFetch (url: string, options?: RequestInit) {
103 return fetch(url, options)
104 .then((res: Response) => {
105 if (res.status !== HttpStatusCode.UNAUTHORIZED_401) return res
107 const refreshingTokenPromise = new Promise<void>((resolve, reject) => {
108 const clientId: string = peertubeLocalStorage.getItem(this.LOCAL_STORAGE_OAUTH_CLIENT_KEYS.CLIENT_ID)
109 const clientSecret: string = peertubeLocalStorage.getItem(this.LOCAL_STORAGE_OAUTH_CLIENT_KEYS.CLIENT_SECRET)
111 const headers = new Headers()
112 headers.set('Content-Type', 'application/x-www-form-urlencoded')
115 refresh_token: this.userTokens.refreshToken,
117 client_secret: clientSecret,
118 response_type: 'code',
119 grant_type: 'refresh_token'
122 fetch('/api/v1/users/token', {
125 body: objectToUrlEncoded(data)
127 if (res.status === HttpStatusCode.UNAUTHORIZED_401) return undefined
130 }).then((obj: UserRefreshToken & { code?: OAuth2ErrorCode }) => {
131 if (!obj || obj.code === OAuth2ErrorCode.INVALID_GRANT) {
132 UserTokens.flushLocalStorage(peertubeLocalStorage)
133 this.removeTokensFromHeaders()
138 this.userTokens.accessToken = obj.access_token
139 this.userTokens.refreshToken = obj.refresh_token
140 UserTokens.saveToLocalStorage(peertubeLocalStorage, this.userTokens)
142 this.setHeadersFromTokens()
145 }).catch((refreshTokenError: any) => {
146 reject(refreshTokenError)
150 return refreshingTokenPromise
152 UserTokens.flushLocalStorage(peertubeLocalStorage)
154 this.removeTokensFromHeaders()
155 }).then(() => fetch(url, {
157 headers: this.headers
162 getPlaylistUrl (id: string) {
163 return window.location.origin + '/api/v1/video-playlists/' + id
166 loadVideoInfo (videoId: string): Promise<Response> {
167 return this.refreshFetch(this.getVideoUrl(videoId), { headers: this.headers })
170 loadVideoCaptions (videoId: string): Promise<Response> {
171 return this.refreshFetch(this.getVideoUrl(videoId) + '/captions', { headers: this.headers })
174 loadWithLive (video: VideoDetails) {
175 return this.refreshFetch(this.getLiveUrl(video.uuid), { headers: this.headers })
176 .then(res => res.json())
177 .then((live: LiveVideo) => ({ video, live }))
180 loadPlaylistInfo (playlistId: string): Promise<Response> {
181 return this.refreshFetch(this.getPlaylistUrl(playlistId), { headers: this.headers })
184 loadPlaylistElements (playlistId: string, start = 0): Promise<Response> {
185 const url = new URL(this.getPlaylistUrl(playlistId) + '/videos')
186 url.search = new URLSearchParams({ start: '' + start, count: '100' }).toString()
188 return this.refreshFetch(url.toString(), { headers: this.headers })
191 removeElement (element: HTMLElement) {
192 element.parentElement.removeChild(element)
195 displayError (text: string, translations?: Translations) {
196 // Remove video element
197 if (this.playerElement) {
198 this.removeElement(this.playerElement)
199 this.playerElement = undefined
202 const translatedText = peertubeTranslate(text, translations)
203 const translatedSorry = peertubeTranslate('Sorry', translations)
205 document.title = translatedSorry + ' - ' + translatedText
207 const errorBlock = document.getElementById('error-block')
208 errorBlock.style.display = 'flex'
210 const errorTitle = document.getElementById('error-title')
211 errorTitle.innerHTML = peertubeTranslate('Sorry', translations)
213 const errorText = document.getElementById('error-content')
214 errorText.innerHTML = translatedText
216 this.wrapperElement.style.display = 'none'
219 videoNotFound (translations?: Translations) {
220 const text = 'This video does not exist.'
221 this.displayError(text, translations)
224 videoFetchError (translations?: Translations) {
225 const text = 'We cannot fetch the video. Please try again later.'
226 this.displayError(text, translations)
229 playlistNotFound (translations?: Translations) {
230 const text = 'This playlist does not exist.'
231 this.displayError(text, translations)
234 playlistFetchError (translations?: Translations) {
235 const text = 'We cannot fetch the playlist. Please try again later.'
236 this.displayError(text, translations)
239 getParamToggle (params: URLSearchParams, name: string, defaultValue?: boolean) {
240 return params.has(name) ? (params.get(name) === '1' || params.get(name) === 'true') : defaultValue
243 getParamString (params: URLSearchParams, name: string, defaultValue?: string) {
244 return params.has(name) ? params.get(name) : defaultValue
247 async playNextVideo () {
248 const next = this.getNextPlaylistElement()
250 console.log('Next element not found in playlist.')
254 this.currentPlaylistElement = next
256 return this.loadVideoAndBuildPlayer(this.currentPlaylistElement.video.uuid)
259 async playPreviousVideo () {
260 const previous = this.getPreviousPlaylistElement()
262 console.log('Previous element not found in playlist.')
266 this.currentPlaylistElement = previous
268 await this.loadVideoAndBuildPlayer(this.currentPlaylistElement.video.uuid)
271 getCurrentPosition () {
272 if (!this.currentPlaylistElement) return -1
274 return this.currentPlaylistElement.position
278 this.userTokens = UserTokens.getUserTokens(peertubeLocalStorage)
279 await this.initCore()
282 private initializeApi () {
283 if (!this.enableApi) return
285 this.api = new PeerTubeEmbedApi(this)
286 this.api.initialize()
289 private loadParams (video: VideoDetails) {
291 const params = new URL(window.location.toString()).searchParams
293 this.autoplay = this.getParamToggle(params, 'autoplay', false)
294 this.controls = this.getParamToggle(params, 'controls', true)
295 this.muted = this.getParamToggle(params, 'muted', undefined)
296 this.loop = this.getParamToggle(params, 'loop', false)
297 this.title = this.getParamToggle(params, 'title', true)
298 this.enableApi = this.getParamToggle(params, 'api', this.enableApi)
299 this.warningTitle = this.getParamToggle(params, 'warningTitle', true)
300 this.peertubeLink = this.getParamToggle(params, 'peertubeLink', true)
301 this.p2pEnabled = this.getParamToggle(params, 'p2p', this.isP2PEnabled(video))
303 this.scope = this.getParamString(params, 'scope', this.scope)
304 this.subtitle = this.getParamString(params, 'subtitle')
305 this.startTime = this.getParamString(params, 'start')
306 this.stopTime = this.getParamString(params, 'stop')
308 this.bigPlayBackgroundColor = this.getParamString(params, 'bigPlayBackgroundColor')
309 this.foregroundColor = this.getParamString(params, 'foregroundColor')
311 const modeParam = this.getParamString(params, 'mode')
314 if (modeParam === 'p2p-media-loader') this.mode = 'p2p-media-loader'
315 else this.mode = 'webtorrent'
317 if (Array.isArray(video.streamingPlaylists) && video.streamingPlaylists.length !== 0) this.mode = 'p2p-media-loader'
318 else this.mode = 'webtorrent'
321 console.error('Cannot get params from URL.', err)
325 private async loadAllPlaylistVideos (playlistId: string, baseResult: ResultList<VideoPlaylistElement>) {
326 let elements = baseResult.data
327 let total = baseResult.total
330 while (total > elements.length && i < 10) {
331 const result = await this.loadPlaylistElements(playlistId, elements.length)
333 const json = await result.json()
336 elements = elements.concat(json.data)
341 console.error('Cannot fetch all playlists elements, there are too many!')
347 private async loadPlaylist (playlistId: string) {
348 const playlistPromise = this.loadPlaylistInfo(playlistId)
349 const playlistElementsPromise = this.loadPlaylistElements(playlistId)
351 let playlistResponse: Response
352 let isResponseOk: boolean
355 playlistResponse = await playlistPromise
356 isResponseOk = playlistResponse.status === HttpStatusCode.OK_200
363 const serverTranslations = await this.translationsPromise
365 if (playlistResponse?.status === HttpStatusCode.NOT_FOUND_404) {
366 this.playlistNotFound(serverTranslations)
370 this.playlistFetchError(serverTranslations)
374 return { playlistResponse, videosResponse: await playlistElementsPromise }
377 private async loadVideo (videoId: string) {
378 const videoPromise = this.loadVideoInfo(videoId)
380 let videoResponse: Response
381 let isResponseOk: boolean
384 videoResponse = await videoPromise
385 isResponseOk = videoResponse.status === HttpStatusCode.OK_200
393 const serverTranslations = await this.translationsPromise
395 if (videoResponse?.status === HttpStatusCode.NOT_FOUND_404) {
396 this.videoNotFound(serverTranslations)
400 this.videoFetchError(serverTranslations)
404 const captionsPromise = this.loadVideoCaptions(videoId)
406 return { captionsPromise, videoResponse }
409 private async buildPlaylistManager () {
410 const translations = await this.translationsPromise
413 timeout: 10000, // 10s
414 headText: peertubeTranslate('Up Next', translations),
415 cancelText: peertubeTranslate('Cancel', translations),
416 suspendedText: peertubeTranslate('Autoplay is suspended', translations),
417 getTitle: () => this.nextVideoTitle(),
418 next: () => this.playNextVideo(),
419 condition: () => !!this.getNextPlaylistElement(),
420 suspended: () => false
424 private async loadVideoAndBuildPlayer (uuid: string) {
425 const res = await this.loadVideo(uuid)
426 if (res === undefined) return
428 return this.buildVideoPlayer(res.videoResponse, res.captionsPromise)
431 private nextVideoTitle () {
432 const next = this.getNextPlaylistElement()
435 return next.video.name
438 private getNextPlaylistElement (position?: number): VideoPlaylistElement {
439 if (!position) position = this.currentPlaylistElement.position + 1
441 if (position > this.playlist.videosLength) {
445 const next = this.playlistElements.find(e => e.position === position)
447 if (!next || !next.video) {
448 return this.getNextPlaylistElement(position + 1)
454 private getPreviousPlaylistElement (position?: number): VideoPlaylistElement {
455 if (!position) position = this.currentPlaylistElement.position - 1
461 const prev = this.playlistElements.find(e => e.position === position)
463 if (!prev || !prev.video) {
464 return this.getNextPlaylistElement(position - 1)
470 private async buildVideoPlayer (videoResponse: Response, captionsPromise: Promise<Response>) {
471 let alreadyHadPlayer = false
474 this.player.dispose()
475 alreadyHadPlayer = true
478 this.playerElement = document.createElement('video')
479 this.playerElement.className = 'video-js vjs-peertube-skin'
480 this.playerElement.setAttribute('playsinline', 'true')
481 this.wrapperElement.appendChild(this.playerElement)
483 // Issue when we parsed config from HTML, fallback to API
485 this.config = await this.refreshFetch('/api/v1/config')
486 .then(res => res.json())
489 const videoInfoPromise: Promise<{ video: VideoDetails, live?: LiveVideo }> = videoResponse.json()
490 .then((videoInfo: VideoDetails) => {
491 this.loadParams(videoInfo)
493 if (!alreadyHadPlayer && !this.autoplay) this.buildPlaceholder(videoInfo)
495 if (!videoInfo.isLive) return { video: videoInfo }
497 return this.loadWithLive(videoInfo)
500 const [ videoInfoTmp, serverTranslations, captionsResponse, PeertubePlayerManagerModule ] = await Promise.all([
502 this.translationsPromise,
504 this.PeertubePlayerManagerModulePromise
507 await this.loadPlugins(serverTranslations)
509 const { video: videoInfo, live } = videoInfoTmp
511 const PeertubePlayerManager = PeertubePlayerManagerModule.PeertubePlayerManager
512 const videoCaptions = await this.buildCaptions(serverTranslations, captionsResponse)
514 const liveOptions = videoInfo.isLive
515 ? { latencyMode: live.latencyMode }
518 const playlistPlugin = this.currentPlaylistElement
520 elements: this.playlistElements,
521 playlist: this.playlist,
523 getCurrentPosition: () => this.currentPlaylistElement.position,
525 onItemClicked: (videoPlaylistElement: VideoPlaylistElement) => {
526 this.currentPlaylistElement = videoPlaylistElement
528 this.loadVideoAndBuildPlayer(this.currentPlaylistElement.video.uuid)
529 .catch(err => console.error(err))
534 const options: PeertubePlayerManagerOptions = {
536 // Autoplay in playlist mode
537 autoplay: alreadyHadPlayer ? true : this.autoplay,
538 controls: this.controls,
542 p2pEnabled: this.p2pEnabled,
544 captions: videoCaptions.length !== 0,
545 subtitle: this.subtitle,
547 startTime: this.playlist ? this.currentPlaylistElement.startTimestamp : this.startTime,
548 stopTime: this.playlist ? this.currentPlaylistElement.stopTimestamp : this.stopTime,
550 nextVideo: this.playlist ? () => this.playNextVideo() : undefined,
551 hasNextVideo: this.playlist ? () => !!this.getNextPlaylistElement() : undefined,
553 previousVideo: this.playlist ? () => this.playPreviousVideo() : undefined,
554 hasPreviousVideo: this.playlist ? () => !!this.getPreviousPlaylistElement() : undefined,
556 playlist: playlistPlugin,
559 inactivityTimeout: 2500,
560 videoViewUrl: this.getVideoUrl(videoInfo.uuid) + '/views',
561 videoShortUUID: videoInfo.shortUUID,
562 videoUUID: videoInfo.uuid,
564 isLive: videoInfo.isLive,
567 playerElement: this.playerElement,
568 onPlayerElementChange: (element: HTMLVideoElement) => {
569 this.playerElement = element
572 videoDuration: videoInfo.duration,
574 peertubeLink: this.peertubeLink,
575 poster: window.location.origin + videoInfo.previewPath,
576 theaterButton: false,
578 serverUrl: window.location.origin,
579 language: navigator.language,
580 embedUrl: window.location.origin + videoInfo.embedPath,
581 embedTitle: videoInfo.name,
583 errorNotifier: () => {
584 // Empty, we don't have a notifier in the embed
589 videoFiles: videoInfo.files
592 pluginsManager: this.pluginsManager
595 if (this.mode === 'p2p-media-loader') {
596 const hlsPlaylist = videoInfo.streamingPlaylists.find(p => p.type === VideoStreamingPlaylistType.HLS)
598 Object.assign(options, {
600 playlistUrl: hlsPlaylist.playlistUrl,
601 segmentsSha256Url: hlsPlaylist.segmentsSha256Url,
602 redundancyBaseUrls: hlsPlaylist.redundancies.map(r => r.baseUrl),
603 trackerAnnounce: videoInfo.trackerUrls,
604 videoFiles: hlsPlaylist.files
605 } as P2PMediaLoaderOptions
609 this.player = await PeertubePlayerManager.initialize(this.mode, options, (player: videojs.Player) => {
613 this.player.on('customError', (event: any, data: any) => this.handleError(data.err, serverTranslations))
615 window['videojsPlayer'] = this.player
619 this.buildDock(videoInfo)
623 this.removePlaceholder()
625 if (this.isPlaylistEmbed()) {
626 await this.buildPlaylistManager()
628 this.player.playlist().updateSelected()
630 this.player.on('stopped', () => {
635 this.pluginsManager.runHook('action:embed.player.loaded', undefined, { player: this.player, videojs, video: videoInfo })
638 private async initCore () {
639 if (this.userTokens) this.setHeadersFromTokens()
641 this.translationsPromise = TranslationsManager.getServerTranslations(window.location.origin, navigator.language)
642 this.PeertubePlayerManagerModulePromise = import('../../assets/player/peertube-player-manager')
646 if (this.isPlaylistEmbed()) {
647 const playlistId = this.getResourceId()
648 const res = await this.loadPlaylist(playlistId)
649 if (!res) return undefined
651 this.playlist = await res.playlistResponse.json()
653 const playlistElementResult = await res.videosResponse.json()
654 this.playlistElements = await this.loadAllPlaylistVideos(playlistId, playlistElementResult)
656 const params = new URL(window.location.toString()).searchParams
657 const playlistPositionParam = this.getParamString(params, 'playlistPosition')
661 if (playlistPositionParam) {
662 position = parseInt(playlistPositionParam + '', 10)
665 this.currentPlaylistElement = this.playlistElements.find(e => e.position === position)
666 if (!this.currentPlaylistElement || !this.currentPlaylistElement.video) {
667 console.error('Current playlist element is not valid.', this.currentPlaylistElement)
668 this.currentPlaylistElement = this.getNextPlaylistElement()
671 if (!this.currentPlaylistElement) {
672 console.error('This playlist does not have any valid element.')
673 const serverTranslations = await this.translationsPromise
674 this.playlistFetchError(serverTranslations)
678 videoId = this.currentPlaylistElement.video.uuid
680 videoId = this.getResourceId()
683 return this.loadVideoAndBuildPlayer(videoId)
686 private handleError (err: Error, translations?: { [ id: string ]: string }) {
687 if (err.message.includes('from xs param')) {
688 this.player.dispose()
689 this.playerElement = null
690 this.displayError('This video is not available because the remote instance is not responding.', translations)
694 private buildDock (videoInfo: VideoDetails) {
695 if (!this.controls) return
697 // On webtorrent fallback, player may have been disposed
698 if (!this.player.player_) return
700 const title = this.title ? videoInfo.name : undefined
701 const description = this.warningTitle && this.p2pEnabled
702 ? '<span class="text">' + peertubeTranslate('Watching this video may reveal your IP address to others.') + '</span>'
705 const availableAvatars = videoInfo.channel.avatars.filter(a => a.width < 50)
706 const avatar = availableAvatars.length !== 0
707 ? availableAvatars[0]
710 if (title || description) {
711 this.player.peertubeDock({
714 avatarUrl: title && avatar
721 private buildCSS () {
722 const body = document.getElementById('custom-css')
724 if (this.bigPlayBackgroundColor) {
725 body.style.setProperty('--embedBigPlayBackgroundColor', this.bigPlayBackgroundColor)
728 if (this.foregroundColor) {
729 body.style.setProperty('--embedForegroundColor', this.foregroundColor)
733 private async buildCaptions (serverTranslations: any, captionsResponse: Response): Promise<VideoJSCaption[]> {
734 if (captionsResponse.ok) {
735 const { data } = await captionsResponse.json()
737 return data.map((c: VideoCaption) => ({
738 label: peertubeTranslate(c.language.label, serverTranslations),
739 language: c.language.id,
740 src: window.location.origin + c.captionPath
747 private buildPlaceholder (video: VideoDetails) {
748 const placeholder = this.getPlaceholderElement()
750 const url = window.location.origin + video.previewPath
751 placeholder.style.backgroundImage = `url("${url}")`
752 placeholder.style.display = 'block'
755 private removePlaceholder () {
756 const placeholder = this.getPlaceholderElement()
757 placeholder.style.display = 'none'
760 private getPlaceholderElement () {
761 return document.getElementById('placeholder-preview')
764 private setHeadersFromTokens () {
765 this.headers.set('Authorization', `${this.userTokens.tokenType} ${this.userTokens.accessToken}`)
768 private removeTokensFromHeaders () {
769 this.headers.delete('Authorization')
772 private getResourceId () {
773 const urlParts = window.location.pathname.split('/')
774 return urlParts[urlParts.length - 1]
777 private isPlaylistEmbed () {
778 return window.location.pathname.split('/')[1] === 'video-playlists'
781 private loadPlugins (translations?: { [ id: string ]: string }) {
782 this.pluginsManager = new PluginsManager({
783 peertubeHelpersFactory: _ => this.buildPeerTubeHelpers(translations)
786 this.pluginsManager.loadPluginsList(this.config)
788 return this.pluginsManager.ensurePluginsAreLoaded('embed')
791 private buildPeerTubeHelpers (translations?: { [ id: string ]: string }): RegisterClientHelpers {
792 const unimplemented = () => {
793 throw new Error('This helper is not implemented in embed.')
797 getBaseStaticRoute: unimplemented,
798 getBaseRouterRoute: unimplemented,
799 getBasePluginClientPath: unimplemented,
801 getSettings: unimplemented,
803 isLoggedIn: unimplemented,
804 getAuthHeader: unimplemented,
808 error: unimplemented,
809 success: unimplemented
812 showModal: unimplemented,
814 getServerConfig: unimplemented,
817 textMarkdownToHTML: unimplemented,
818 enhancedMarkdownToHTML: unimplemented
821 translate: (value: string) => Promise.resolve(peertubeTranslate(value, translations))
825 private isP2PEnabled (video: Video) {
826 const userP2PEnabled = getBoolOrDefault(
827 peertubeLocalStorage.getItem(UserLocalStorageKeys.P2P_ENABLED),
828 this.config.defaults.p2p.embed.enabled
831 return isP2PEnabled(video, this.config, userP2PEnabled)
837 (window as any).displayIncompatibleBrowser()
839 console.error('Cannot init embed.', err)