2 import '../../assets/player/shared/dock/peertube-dock-component'
3 import '../../assets/player/shared/dock/peertube-dock-plugin'
4 import videojs from 'video.js'
5 import { peertubeTranslate } from '../../../../shared/core-utils/i18n'
19 VideoStreamingPlaylistType
20 } from '../../../../shared/models'
21 import { P2PMediaLoaderOptions, PeertubePlayerManagerOptions, PlayerMode, VideoJSCaption } from '../../assets/player'
22 import { TranslationsManager } from '../../assets/player/translations-manager'
23 import { getBoolOrDefault } from '../../root-helpers/local-storage-utils'
24 import { peertubeLocalStorage } from '../../root-helpers/peertube-web-storage'
25 import { PluginInfo, PluginsManager } from '../../root-helpers/plugins-manager'
26 import { UserLocalStorageKeys, UserTokens } from '../../root-helpers/users'
27 import { objectToUrlEncoded } from '../../root-helpers/utils'
28 import { isP2PEnabled } from '../../root-helpers/video'
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
103 return window.location.origin + '/api/v1/plugins'
106 refreshFetch (url: string, options?: RequestInit) {
107 return fetch(url, options)
108 .then((res: Response) => {
109 if (res.status !== HttpStatusCode.UNAUTHORIZED_401) return res
111 const refreshingTokenPromise = new Promise<void>((resolve, reject) => {
112 const clientId: string = peertubeLocalStorage.getItem(this.LOCAL_STORAGE_OAUTH_CLIENT_KEYS.CLIENT_ID)
113 const clientSecret: string = peertubeLocalStorage.getItem(this.LOCAL_STORAGE_OAUTH_CLIENT_KEYS.CLIENT_SECRET)
115 const headers = new Headers()
116 headers.set('Content-Type', 'application/x-www-form-urlencoded')
119 refresh_token: this.userTokens.refreshToken,
121 client_secret: clientSecret,
122 response_type: 'code',
123 grant_type: 'refresh_token'
126 fetch('/api/v1/users/token', {
129 body: objectToUrlEncoded(data)
131 if (res.status === HttpStatusCode.UNAUTHORIZED_401) return undefined
134 }).then((obj: UserRefreshToken & { code?: OAuth2ErrorCode }) => {
135 if (!obj || obj.code === OAuth2ErrorCode.INVALID_GRANT) {
136 UserTokens.flushLocalStorage(peertubeLocalStorage)
137 this.removeTokensFromHeaders()
142 this.userTokens.accessToken = obj.access_token
143 this.userTokens.refreshToken = obj.refresh_token
144 UserTokens.saveToLocalStorage(peertubeLocalStorage, this.userTokens)
146 this.setHeadersFromTokens()
149 }).catch((refreshTokenError: any) => {
150 reject(refreshTokenError)
154 return refreshingTokenPromise
156 UserTokens.flushLocalStorage(peertubeLocalStorage)
158 this.removeTokensFromHeaders()
159 }).then(() => fetch(url, {
161 headers: this.headers
166 getPlaylistUrl (id: string) {
167 return window.location.origin + '/api/v1/video-playlists/' + id
170 loadVideoInfo (videoId: string): Promise<Response> {
171 return this.refreshFetch(this.getVideoUrl(videoId), { headers: this.headers })
174 loadVideoCaptions (videoId: string): Promise<Response> {
175 return this.refreshFetch(this.getVideoUrl(videoId) + '/captions', { headers: this.headers })
178 loadWithLive (video: VideoDetails) {
179 return this.refreshFetch(this.getLiveUrl(video.uuid), { headers: this.headers })
180 .then(res => res.json())
181 .then((live: LiveVideo) => ({ video, live }))
184 loadPlaylistInfo (playlistId: string): Promise<Response> {
185 return this.refreshFetch(this.getPlaylistUrl(playlistId), { headers: this.headers })
188 loadPlaylistElements (playlistId: string, start = 0): Promise<Response> {
189 const url = new URL(this.getPlaylistUrl(playlistId) + '/videos')
190 url.search = new URLSearchParams({ start: '' + start, count: '100' }).toString()
192 return this.refreshFetch(url.toString(), { headers: this.headers })
195 removeElement (element: HTMLElement) {
196 element.parentElement.removeChild(element)
199 displayError (text: string, translations?: Translations) {
200 // Remove video element
201 if (this.playerElement) {
202 this.removeElement(this.playerElement)
203 this.playerElement = undefined
206 const translatedText = peertubeTranslate(text, translations)
207 const translatedSorry = peertubeTranslate('Sorry', translations)
209 document.title = translatedSorry + ' - ' + translatedText
211 const errorBlock = document.getElementById('error-block')
212 errorBlock.style.display = 'flex'
214 const errorTitle = document.getElementById('error-title')
215 errorTitle.innerHTML = peertubeTranslate('Sorry', translations)
217 const errorText = document.getElementById('error-content')
218 errorText.innerHTML = translatedText
220 this.wrapperElement.style.display = 'none'
223 videoNotFound (translations?: Translations) {
224 const text = 'This video does not exist.'
225 this.displayError(text, translations)
228 videoFetchError (translations?: Translations) {
229 const text = 'We cannot fetch the video. Please try again later.'
230 this.displayError(text, translations)
233 playlistNotFound (translations?: Translations) {
234 const text = 'This playlist does not exist.'
235 this.displayError(text, translations)
238 playlistFetchError (translations?: Translations) {
239 const text = 'We cannot fetch the playlist. Please try again later.'
240 this.displayError(text, translations)
243 getParamToggle (params: URLSearchParams, name: string, defaultValue?: boolean) {
244 return params.has(name) ? (params.get(name) === '1' || params.get(name) === 'true') : defaultValue
247 getParamString (params: URLSearchParams, name: string, defaultValue?: string) {
248 return params.has(name) ? params.get(name) : defaultValue
251 async playNextVideo () {
252 const next = this.getNextPlaylistElement()
254 console.log('Next element not found in playlist.')
258 this.currentPlaylistElement = next
260 return this.loadVideoAndBuildPlayer(this.currentPlaylistElement.video.uuid)
263 async playPreviousVideo () {
264 const previous = this.getPreviousPlaylistElement()
266 console.log('Previous element not found in playlist.')
270 this.currentPlaylistElement = previous
272 await this.loadVideoAndBuildPlayer(this.currentPlaylistElement.video.uuid)
275 getCurrentPosition () {
276 if (!this.currentPlaylistElement) return -1
278 return this.currentPlaylistElement.position
282 this.userTokens = UserTokens.getUserTokens(peertubeLocalStorage)
283 await this.initCore()
286 private initializeApi () {
287 if (!this.enableApi) return
289 this.api = new PeerTubeEmbedApi(this)
290 this.api.initialize()
293 private loadParams (video: VideoDetails) {
295 const params = new URL(window.location.toString()).searchParams
297 this.autoplay = this.getParamToggle(params, 'autoplay', false)
298 this.controls = this.getParamToggle(params, 'controls', true)
299 this.muted = this.getParamToggle(params, 'muted', undefined)
300 this.loop = this.getParamToggle(params, 'loop', false)
301 this.title = this.getParamToggle(params, 'title', true)
302 this.enableApi = this.getParamToggle(params, 'api', this.enableApi)
303 this.warningTitle = this.getParamToggle(params, 'warningTitle', true)
304 this.peertubeLink = this.getParamToggle(params, 'peertubeLink', true)
305 this.p2pEnabled = this.getParamToggle(params, 'p2p', this.isP2PEnabled(video))
307 this.scope = this.getParamString(params, 'scope', this.scope)
308 this.subtitle = this.getParamString(params, 'subtitle')
309 this.startTime = this.getParamString(params, 'start')
310 this.stopTime = this.getParamString(params, 'stop')
312 this.bigPlayBackgroundColor = this.getParamString(params, 'bigPlayBackgroundColor')
313 this.foregroundColor = this.getParamString(params, 'foregroundColor')
315 const modeParam = this.getParamString(params, 'mode')
318 if (modeParam === 'p2p-media-loader') this.mode = 'p2p-media-loader'
319 else this.mode = 'webtorrent'
321 if (Array.isArray(video.streamingPlaylists) && video.streamingPlaylists.length !== 0) this.mode = 'p2p-media-loader'
322 else this.mode = 'webtorrent'
325 console.error('Cannot get params from URL.', err)
329 private async loadAllPlaylistVideos (playlistId: string, baseResult: ResultList<VideoPlaylistElement>) {
330 let elements = baseResult.data
331 let total = baseResult.total
334 while (total > elements.length && i < 10) {
335 const result = await this.loadPlaylistElements(playlistId, elements.length)
337 const json = await result.json()
340 elements = elements.concat(json.data)
345 console.error('Cannot fetch all playlists elements, there are too many!')
351 private async loadPlaylist (playlistId: string) {
352 const playlistPromise = this.loadPlaylistInfo(playlistId)
353 const playlistElementsPromise = this.loadPlaylistElements(playlistId)
355 let playlistResponse: Response
356 let isResponseOk: boolean
359 playlistResponse = await playlistPromise
360 isResponseOk = playlistResponse.status === HttpStatusCode.OK_200
367 const serverTranslations = await this.translationsPromise
369 if (playlistResponse?.status === HttpStatusCode.NOT_FOUND_404) {
370 this.playlistNotFound(serverTranslations)
374 this.playlistFetchError(serverTranslations)
378 return { playlistResponse, videosResponse: await playlistElementsPromise }
381 private async loadVideo (videoId: string) {
382 const videoPromise = this.loadVideoInfo(videoId)
384 let videoResponse: Response
385 let isResponseOk: boolean
388 videoResponse = await videoPromise
389 isResponseOk = videoResponse.status === HttpStatusCode.OK_200
397 const serverTranslations = await this.translationsPromise
399 if (videoResponse?.status === HttpStatusCode.NOT_FOUND_404) {
400 this.videoNotFound(serverTranslations)
404 this.videoFetchError(serverTranslations)
408 const captionsPromise = this.loadVideoCaptions(videoId)
410 return { captionsPromise, videoResponse }
413 private async buildPlaylistManager () {
414 const translations = await this.translationsPromise
417 timeout: 10000, // 10s
418 headText: peertubeTranslate('Up Next', translations),
419 cancelText: peertubeTranslate('Cancel', translations),
420 suspendedText: peertubeTranslate('Autoplay is suspended', translations),
421 getTitle: () => this.nextVideoTitle(),
422 next: () => this.playNextVideo(),
423 condition: () => !!this.getNextPlaylistElement(),
424 suspended: () => false
428 private async loadVideoAndBuildPlayer (uuid: string) {
429 const res = await this.loadVideo(uuid)
430 if (res === undefined) return
432 return this.buildVideoPlayer(res.videoResponse, res.captionsPromise)
435 private nextVideoTitle () {
436 const next = this.getNextPlaylistElement()
439 return next.video.name
442 private getNextPlaylistElement (position?: number): VideoPlaylistElement {
443 if (!position) position = this.currentPlaylistElement.position + 1
445 if (position > this.playlist.videosLength) {
449 const next = this.playlistElements.find(e => e.position === position)
451 if (!next || !next.video) {
452 return this.getNextPlaylistElement(position + 1)
458 private getPreviousPlaylistElement (position?: number): VideoPlaylistElement {
459 if (!position) position = this.currentPlaylistElement.position - 1
465 const prev = this.playlistElements.find(e => e.position === position)
467 if (!prev || !prev.video) {
468 return this.getNextPlaylistElement(position - 1)
474 private async buildVideoPlayer (videoResponse: Response, captionsPromise: Promise<Response>) {
475 let alreadyHadPlayer = false
478 this.player.dispose()
479 alreadyHadPlayer = true
482 this.playerElement = document.createElement('video')
483 this.playerElement.className = 'video-js vjs-peertube-skin'
484 this.playerElement.setAttribute('playsinline', 'true')
485 this.wrapperElement.appendChild(this.playerElement)
487 // Issue when we parsed config from HTML, fallback to API
489 this.config = await this.refreshFetch('/api/v1/config')
490 .then(res => res.json())
493 const videoInfoPromise: Promise<{ video: VideoDetails, live?: LiveVideo }> = videoResponse.json()
494 .then((videoInfo: VideoDetails) => {
495 this.loadParams(videoInfo)
497 if (!alreadyHadPlayer && !this.autoplay) this.buildPlaceholder(videoInfo)
499 if (!videoInfo.isLive) return { video: videoInfo }
501 return this.loadWithLive(videoInfo)
504 const [ videoInfoTmp, serverTranslations, captionsResponse, PeertubePlayerManagerModule ] = await Promise.all([
506 this.translationsPromise,
508 this.PeertubePlayerManagerModulePromise
511 await this.loadPlugins(serverTranslations)
513 const { video: videoInfo, live } = videoInfoTmp
515 const PeertubePlayerManager = PeertubePlayerManagerModule.PeertubePlayerManager
516 const videoCaptions = await this.buildCaptions(serverTranslations, captionsResponse)
518 const liveOptions = videoInfo.isLive
519 ? { latencyMode: live.latencyMode }
522 const playlistPlugin = this.currentPlaylistElement
524 elements: this.playlistElements,
525 playlist: this.playlist,
527 getCurrentPosition: () => this.currentPlaylistElement.position,
529 onItemClicked: (videoPlaylistElement: VideoPlaylistElement) => {
530 this.currentPlaylistElement = videoPlaylistElement
532 this.loadVideoAndBuildPlayer(this.currentPlaylistElement.video.uuid)
533 .catch(err => console.error(err))
538 const options: PeertubePlayerManagerOptions = {
540 // Autoplay in playlist mode
541 autoplay: alreadyHadPlayer ? true : this.autoplay,
542 controls: this.controls,
546 p2pEnabled: this.p2pEnabled,
548 captions: videoCaptions.length !== 0,
549 subtitle: this.subtitle,
551 startTime: this.playlist ? this.currentPlaylistElement.startTimestamp : this.startTime,
552 stopTime: this.playlist ? this.currentPlaylistElement.stopTimestamp : this.stopTime,
554 nextVideo: this.playlist ? () => this.playNextVideo() : undefined,
555 hasNextVideo: this.playlist ? () => !!this.getNextPlaylistElement() : undefined,
557 previousVideo: this.playlist ? () => this.playPreviousVideo() : undefined,
558 hasPreviousVideo: this.playlist ? () => !!this.getPreviousPlaylistElement() : undefined,
560 playlist: playlistPlugin,
563 inactivityTimeout: 2500,
564 videoViewUrl: this.getVideoUrl(videoInfo.uuid) + '/views',
565 videoShortUUID: videoInfo.shortUUID,
566 videoUUID: videoInfo.uuid,
568 isLive: videoInfo.isLive,
571 playerElement: this.playerElement,
572 onPlayerElementChange: (element: HTMLVideoElement) => {
573 this.playerElement = element
576 videoDuration: videoInfo.duration,
578 peertubeLink: this.peertubeLink,
579 poster: window.location.origin + videoInfo.previewPath,
580 theaterButton: false,
582 serverUrl: window.location.origin,
583 language: navigator.language,
584 embedUrl: window.location.origin + videoInfo.embedPath,
585 embedTitle: videoInfo.name,
587 errorNotifier: () => {
588 // Empty, we don't have a notifier in the embed
593 videoFiles: videoInfo.files
596 pluginsManager: this.pluginsManager
599 if (this.mode === 'p2p-media-loader') {
600 const hlsPlaylist = videoInfo.streamingPlaylists.find(p => p.type === VideoStreamingPlaylistType.HLS)
602 Object.assign(options, {
604 playlistUrl: hlsPlaylist.playlistUrl,
605 segmentsSha256Url: hlsPlaylist.segmentsSha256Url,
606 redundancyBaseUrls: hlsPlaylist.redundancies.map(r => r.baseUrl),
607 trackerAnnounce: videoInfo.trackerUrls,
608 videoFiles: hlsPlaylist.files
609 } as P2PMediaLoaderOptions
613 this.player = await PeertubePlayerManager.initialize(this.mode, options, (player: videojs.Player) => {
617 this.player.on('customError', (event: any, data: any) => this.handleError(data.err, serverTranslations))
619 window['videojsPlayer'] = this.player
623 this.buildDock(videoInfo)
627 this.removePlaceholder()
629 if (this.isPlaylistEmbed()) {
630 await this.buildPlaylistManager()
632 this.player.playlist().updateSelected()
634 this.player.on('stopped', () => {
639 this.pluginsManager.runHook('action:embed.player.loaded', undefined, { player: this.player, videojs, video: videoInfo })
642 private async initCore () {
643 if (this.userTokens) this.setHeadersFromTokens()
645 this.translationsPromise = TranslationsManager.getServerTranslations(window.location.origin, navigator.language)
646 this.PeertubePlayerManagerModulePromise = import('../../assets/player/peertube-player-manager')
650 if (this.isPlaylistEmbed()) {
651 const playlistId = this.getResourceId()
652 const res = await this.loadPlaylist(playlistId)
653 if (!res) return undefined
655 this.playlist = await res.playlistResponse.json()
657 const playlistElementResult = await res.videosResponse.json()
658 this.playlistElements = await this.loadAllPlaylistVideos(playlistId, playlistElementResult)
660 const params = new URL(window.location.toString()).searchParams
661 const playlistPositionParam = this.getParamString(params, 'playlistPosition')
665 if (playlistPositionParam) {
666 position = parseInt(playlistPositionParam + '', 10)
669 this.currentPlaylistElement = this.playlistElements.find(e => e.position === position)
670 if (!this.currentPlaylistElement || !this.currentPlaylistElement.video) {
671 console.error('Current playlist element is not valid.', this.currentPlaylistElement)
672 this.currentPlaylistElement = this.getNextPlaylistElement()
675 if (!this.currentPlaylistElement) {
676 console.error('This playlist does not have any valid element.')
677 const serverTranslations = await this.translationsPromise
678 this.playlistFetchError(serverTranslations)
682 videoId = this.currentPlaylistElement.video.uuid
684 videoId = this.getResourceId()
687 return this.loadVideoAndBuildPlayer(videoId)
690 private handleError (err: Error, translations?: { [ id: string ]: string }) {
691 if (err.message.includes('from xs param')) {
692 this.player.dispose()
693 this.playerElement = null
694 this.displayError('This video is not available because the remote instance is not responding.', translations)
698 private buildDock (videoInfo: VideoDetails) {
699 if (!this.controls) return
701 // On webtorrent fallback, player may have been disposed
702 if (!this.player.player_) return
704 const title = this.title ? videoInfo.name : undefined
705 const description = this.warningTitle && this.p2pEnabled
706 ? '<span class="text">' + peertubeTranslate('Watching this video may reveal your IP address to others.') + '</span>'
709 const availableAvatars = videoInfo.channel.avatars.filter(a => a.width < 50)
710 const avatar = availableAvatars.length !== 0
711 ? availableAvatars[0]
714 if (title || description) {
715 this.player.peertubeDock({
718 avatarUrl: title && avatar
725 private buildCSS () {
726 const body = document.getElementById('custom-css')
728 if (this.bigPlayBackgroundColor) {
729 body.style.setProperty('--embedBigPlayBackgroundColor', this.bigPlayBackgroundColor)
732 if (this.foregroundColor) {
733 body.style.setProperty('--embedForegroundColor', this.foregroundColor)
737 private async buildCaptions (serverTranslations: any, captionsResponse: Response): Promise<VideoJSCaption[]> {
738 if (captionsResponse.ok) {
739 const { data } = await captionsResponse.json()
741 return data.map((c: VideoCaption) => ({
742 label: peertubeTranslate(c.language.label, serverTranslations),
743 language: c.language.id,
744 src: window.location.origin + c.captionPath
751 private buildPlaceholder (video: VideoDetails) {
752 const placeholder = this.getPlaceholderElement()
754 const url = window.location.origin + video.previewPath
755 placeholder.style.backgroundImage = `url("${url}")`
756 placeholder.style.display = 'block'
759 private removePlaceholder () {
760 const placeholder = this.getPlaceholderElement()
761 placeholder.style.display = 'none'
764 private getPlaceholderElement () {
765 return document.getElementById('placeholder-preview')
768 private getHeaderTokenValue () {
769 return `${this.userTokens.tokenType} ${this.userTokens.accessToken}`
772 private setHeadersFromTokens () {
773 this.headers.set('Authorization', this.getHeaderTokenValue())
776 private removeTokensFromHeaders () {
777 this.headers.delete('Authorization')
780 private getResourceId () {
781 const urlParts = window.location.pathname.split('/')
782 return urlParts[urlParts.length - 1]
785 private isPlaylistEmbed () {
786 return window.location.pathname.split('/')[1] === 'video-playlists'
789 private loadPlugins (translations?: { [ id: string ]: string }) {
790 this.pluginsManager = new PluginsManager({
791 peertubeHelpersFactory: pluginInfo => this.buildPeerTubeHelpers(pluginInfo, translations)
794 this.pluginsManager.loadPluginsList(this.config)
796 return this.pluginsManager.ensurePluginsAreLoaded('embed')
799 private buildPeerTubeHelpers (pluginInfo: PluginInfo, translations?: { [ id: string ]: string }): RegisterClientHelpers {
800 const unimplemented = () => {
801 throw new Error('This helper is not implemented in embed.')
805 getBaseStaticRoute: unimplemented,
806 getBaseRouterRoute: unimplemented,
807 getBasePluginClientPath: unimplemented,
810 const url = this.getPluginUrl() + '/' + pluginInfo.plugin.npmName + '/public-settings'
812 return this.refreshFetch(url, { headers: this.headers })
813 .then(res => res.json())
814 .then((obj: PublicServerSetting) => obj.publicSettings)
817 isLoggedIn: () => !!this.userTokens,
818 getAuthHeader: () => {
819 if (!this.userTokens) return undefined
821 return { Authorization: this.getHeaderTokenValue() }
826 error: unimplemented,
827 success: unimplemented
830 showModal: unimplemented,
832 getServerConfig: unimplemented,
835 textMarkdownToHTML: unimplemented,
836 enhancedMarkdownToHTML: unimplemented
839 translate: (value: string) => Promise.resolve(peertubeTranslate(value, translations))
843 private isP2PEnabled (video: Video) {
844 const userP2PEnabled = getBoolOrDefault(
845 peertubeLocalStorage.getItem(UserLocalStorageKeys.P2P_ENABLED),
846 this.config.defaults.p2p.embed.enabled
849 return isP2PEnabled(video, this.config, userP2PEnabled)
855 (window as any).displayIncompatibleBrowser()
857 console.error('Cannot init embed.', err)