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'
18 VideoStreamingPlaylistType
19 } from '../../../../shared/models'
20 import { P2PMediaLoaderOptions, PeertubePlayerManagerOptions, PlayerMode, VideoJSCaption } from '../../assets/player'
21 import { TranslationsManager } from '../../assets/player/translations-manager'
22 import { getBoolOrDefault } from '../../root-helpers/local-storage-utils'
23 import { peertubeLocalStorage } from '../../root-helpers/peertube-web-storage'
24 import { PluginsManager } from '../../root-helpers/plugins-manager'
25 import { UserLocalStorageKeys, UserTokens } from '../../root-helpers/users'
26 import { objectToUrlEncoded } from '../../root-helpers/utils'
27 import { isP2PEnabled } from '../../root-helpers/video'
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 getLiveUrl (videoId: string) {
98 return window.location.origin + '/api/v1/videos/live/' + videoId
101 refreshFetch (url: string, options?: RequestInit) {
102 return fetch(url, options)
103 .then((res: Response) => {
104 if (res.status !== HttpStatusCode.UNAUTHORIZED_401) return res
106 const refreshingTokenPromise = new Promise<void>((resolve, reject) => {
107 const clientId: string = peertubeLocalStorage.getItem(this.LOCAL_STORAGE_OAUTH_CLIENT_KEYS.CLIENT_ID)
108 const clientSecret: string = peertubeLocalStorage.getItem(this.LOCAL_STORAGE_OAUTH_CLIENT_KEYS.CLIENT_SECRET)
110 const headers = new Headers()
111 headers.set('Content-Type', 'application/x-www-form-urlencoded')
114 refresh_token: this.userTokens.refreshToken,
116 client_secret: clientSecret,
117 response_type: 'code',
118 grant_type: 'refresh_token'
121 fetch('/api/v1/users/token', {
124 body: objectToUrlEncoded(data)
126 if (res.status === HttpStatusCode.UNAUTHORIZED_401) return undefined
129 }).then((obj: UserRefreshToken & { code?: OAuth2ErrorCode }) => {
130 if (!obj || obj.code === OAuth2ErrorCode.INVALID_GRANT) {
131 UserTokens.flushLocalStorage(peertubeLocalStorage)
132 this.removeTokensFromHeaders()
137 this.userTokens.accessToken = obj.access_token
138 this.userTokens.refreshToken = obj.refresh_token
139 UserTokens.saveToLocalStorage(peertubeLocalStorage, this.userTokens)
141 this.setHeadersFromTokens()
144 }).catch((refreshTokenError: any) => {
145 reject(refreshTokenError)
149 return refreshingTokenPromise
151 UserTokens.flushLocalStorage(peertubeLocalStorage)
153 this.removeTokensFromHeaders()
154 }).then(() => fetch(url, {
156 headers: this.headers
161 getPlaylistUrl (id: string) {
162 return window.location.origin + '/api/v1/video-playlists/' + id
165 loadVideoInfo (videoId: string): Promise<Response> {
166 return this.refreshFetch(this.getVideoUrl(videoId), { headers: this.headers })
169 loadVideoCaptions (videoId: string): Promise<Response> {
170 return this.refreshFetch(this.getVideoUrl(videoId) + '/captions', { headers: this.headers })
173 loadWithLive (video: VideoDetails) {
174 return this.refreshFetch(this.getLiveUrl(video.uuid), { headers: this.headers })
175 .then(res => res.json())
176 .then((live: LiveVideo) => ({ video, live }))
179 loadPlaylistInfo (playlistId: string): Promise<Response> {
180 return this.refreshFetch(this.getPlaylistUrl(playlistId), { headers: this.headers })
183 loadPlaylistElements (playlistId: string, start = 0): Promise<Response> {
184 const url = new URL(this.getPlaylistUrl(playlistId) + '/videos')
185 url.search = new URLSearchParams({ start: '' + start, count: '100' }).toString()
187 return this.refreshFetch(url.toString(), { headers: this.headers })
190 removeElement (element: HTMLElement) {
191 element.parentElement.removeChild(element)
194 displayError (text: string, translations?: Translations) {
195 // Remove video element
196 if (this.playerElement) {
197 this.removeElement(this.playerElement)
198 this.playerElement = undefined
201 const translatedText = peertubeTranslate(text, translations)
202 const translatedSorry = peertubeTranslate('Sorry', translations)
204 document.title = translatedSorry + ' - ' + translatedText
206 const errorBlock = document.getElementById('error-block')
207 errorBlock.style.display = 'flex'
209 const errorTitle = document.getElementById('error-title')
210 errorTitle.innerHTML = peertubeTranslate('Sorry', translations)
212 const errorText = document.getElementById('error-content')
213 errorText.innerHTML = translatedText
215 this.wrapperElement.style.display = 'none'
218 videoNotFound (translations?: Translations) {
219 const text = 'This video does not exist.'
220 this.displayError(text, translations)
223 videoFetchError (translations?: Translations) {
224 const text = 'We cannot fetch the video. Please try again later.'
225 this.displayError(text, translations)
228 playlistNotFound (translations?: Translations) {
229 const text = 'This playlist does not exist.'
230 this.displayError(text, translations)
233 playlistFetchError (translations?: Translations) {
234 const text = 'We cannot fetch the playlist. Please try again later.'
235 this.displayError(text, translations)
238 getParamToggle (params: URLSearchParams, name: string, defaultValue?: boolean) {
239 return params.has(name) ? (params.get(name) === '1' || params.get(name) === 'true') : defaultValue
242 getParamString (params: URLSearchParams, name: string, defaultValue?: string) {
243 return params.has(name) ? params.get(name) : defaultValue
246 async playNextVideo () {
247 const next = this.getNextPlaylistElement()
249 console.log('Next element not found in playlist.')
253 this.currentPlaylistElement = next
255 return this.loadVideoAndBuildPlayer(this.currentPlaylistElement.video.uuid)
258 async playPreviousVideo () {
259 const previous = this.getPreviousPlaylistElement()
261 console.log('Previous element not found in playlist.')
265 this.currentPlaylistElement = previous
267 await this.loadVideoAndBuildPlayer(this.currentPlaylistElement.video.uuid)
270 getCurrentPosition () {
271 if (!this.currentPlaylistElement) return -1
273 return this.currentPlaylistElement.position
277 this.userTokens = UserTokens.getUserTokens(peertubeLocalStorage)
278 await this.initCore()
281 private initializeApi () {
282 if (!this.enableApi) return
284 this.api = new PeerTubeEmbedApi(this)
285 this.api.initialize()
288 private loadParams (video: VideoDetails) {
290 const params = new URL(window.location.toString()).searchParams
292 this.autoplay = this.getParamToggle(params, 'autoplay', false)
293 this.controls = this.getParamToggle(params, 'controls', true)
294 this.muted = this.getParamToggle(params, 'muted', undefined)
295 this.loop = this.getParamToggle(params, 'loop', false)
296 this.title = this.getParamToggle(params, 'title', true)
297 this.enableApi = this.getParamToggle(params, 'api', this.enableApi)
298 this.warningTitle = this.getParamToggle(params, 'warningTitle', true)
299 this.peertubeLink = this.getParamToggle(params, 'peertubeLink', true)
300 this.p2pEnabled = this.getParamToggle(params, 'p2p', this.isP2PEnabled(video))
302 this.scope = this.getParamString(params, 'scope', this.scope)
303 this.subtitle = this.getParamString(params, 'subtitle')
304 this.startTime = this.getParamString(params, 'start')
305 this.stopTime = this.getParamString(params, 'stop')
307 this.bigPlayBackgroundColor = this.getParamString(params, 'bigPlayBackgroundColor')
308 this.foregroundColor = this.getParamString(params, 'foregroundColor')
310 const modeParam = this.getParamString(params, 'mode')
313 if (modeParam === 'p2p-media-loader') this.mode = 'p2p-media-loader'
314 else this.mode = 'webtorrent'
316 if (Array.isArray(video.streamingPlaylists) && video.streamingPlaylists.length !== 0) this.mode = 'p2p-media-loader'
317 else this.mode = 'webtorrent'
320 console.error('Cannot get params from URL.', err)
324 private async loadAllPlaylistVideos (playlistId: string, baseResult: ResultList<VideoPlaylistElement>) {
325 let elements = baseResult.data
326 let total = baseResult.total
329 while (total > elements.length && i < 10) {
330 const result = await this.loadPlaylistElements(playlistId, elements.length)
332 const json = await result.json()
335 elements = elements.concat(json.data)
340 console.error('Cannot fetch all playlists elements, there are too many!')
346 private async loadPlaylist (playlistId: string) {
347 const playlistPromise = this.loadPlaylistInfo(playlistId)
348 const playlistElementsPromise = this.loadPlaylistElements(playlistId)
350 let playlistResponse: Response
351 let isResponseOk: boolean
354 playlistResponse = await playlistPromise
355 isResponseOk = playlistResponse.status === HttpStatusCode.OK_200
362 const serverTranslations = await this.translationsPromise
364 if (playlistResponse?.status === HttpStatusCode.NOT_FOUND_404) {
365 this.playlistNotFound(serverTranslations)
369 this.playlistFetchError(serverTranslations)
373 return { playlistResponse, videosResponse: await playlistElementsPromise }
376 private async loadVideo (videoId: string) {
377 const videoPromise = this.loadVideoInfo(videoId)
379 let videoResponse: Response
380 let isResponseOk: boolean
383 videoResponse = await videoPromise
384 isResponseOk = videoResponse.status === HttpStatusCode.OK_200
392 const serverTranslations = await this.translationsPromise
394 if (videoResponse?.status === HttpStatusCode.NOT_FOUND_404) {
395 this.videoNotFound(serverTranslations)
399 this.videoFetchError(serverTranslations)
403 const captionsPromise = this.loadVideoCaptions(videoId)
405 return { captionsPromise, videoResponse }
408 private async buildPlaylistManager () {
409 const translations = await this.translationsPromise
412 timeout: 10000, // 10s
413 headText: peertubeTranslate('Up Next', translations),
414 cancelText: peertubeTranslate('Cancel', translations),
415 suspendedText: peertubeTranslate('Autoplay is suspended', translations),
416 getTitle: () => this.nextVideoTitle(),
417 next: () => this.playNextVideo(),
418 condition: () => !!this.getNextPlaylistElement(),
419 suspended: () => false
423 private async loadVideoAndBuildPlayer (uuid: string) {
424 const res = await this.loadVideo(uuid)
425 if (res === undefined) return
427 return this.buildVideoPlayer(res.videoResponse, res.captionsPromise)
430 private nextVideoTitle () {
431 const next = this.getNextPlaylistElement()
434 return next.video.name
437 private getNextPlaylistElement (position?: number): VideoPlaylistElement {
438 if (!position) position = this.currentPlaylistElement.position + 1
440 if (position > this.playlist.videosLength) {
444 const next = this.playlistElements.find(e => e.position === position)
446 if (!next || !next.video) {
447 return this.getNextPlaylistElement(position + 1)
453 private getPreviousPlaylistElement (position?: number): VideoPlaylistElement {
454 if (!position) position = this.currentPlaylistElement.position - 1
460 const prev = this.playlistElements.find(e => e.position === position)
462 if (!prev || !prev.video) {
463 return this.getNextPlaylistElement(position - 1)
469 private async buildVideoPlayer (videoResponse: Response, captionsPromise: Promise<Response>) {
470 let alreadyHadPlayer = false
473 this.player.dispose()
474 alreadyHadPlayer = true
477 this.playerElement = document.createElement('video')
478 this.playerElement.className = 'video-js vjs-peertube-skin'
479 this.playerElement.setAttribute('playsinline', 'true')
480 this.wrapperElement.appendChild(this.playerElement)
482 // Issue when we parsed config from HTML, fallback to API
484 this.config = await this.refreshFetch('/api/v1/config')
485 .then(res => res.json())
488 const videoInfoPromise: Promise<{ video: VideoDetails, live?: LiveVideo }> = videoResponse.json()
489 .then((videoInfo: VideoDetails) => {
490 this.loadParams(videoInfo)
492 if (!alreadyHadPlayer && !this.autoplay) this.buildPlaceholder(videoInfo)
494 if (!videoInfo.isLive) return { video: videoInfo }
496 return this.loadWithLive(videoInfo)
499 const [ videoInfoTmp, serverTranslations, captionsResponse, PeertubePlayerManagerModule ] = await Promise.all([
501 this.translationsPromise,
503 this.PeertubePlayerManagerModulePromise
506 await this.loadPlugins(serverTranslations)
508 const { video: videoInfo, live } = videoInfoTmp
510 const PeertubePlayerManager = PeertubePlayerManagerModule.PeertubePlayerManager
511 const videoCaptions = await this.buildCaptions(serverTranslations, captionsResponse)
513 const liveOptions = videoInfo.isLive
514 ? { latencyMode: live.latencyMode }
517 const playlistPlugin = this.currentPlaylistElement
519 elements: this.playlistElements,
520 playlist: this.playlist,
522 getCurrentPosition: () => this.currentPlaylistElement.position,
524 onItemClicked: (videoPlaylistElement: VideoPlaylistElement) => {
525 this.currentPlaylistElement = videoPlaylistElement
527 this.loadVideoAndBuildPlayer(this.currentPlaylistElement.video.uuid)
528 .catch(err => console.error(err))
533 const options: PeertubePlayerManagerOptions = {
535 // Autoplay in playlist mode
536 autoplay: alreadyHadPlayer ? true : this.autoplay,
537 controls: this.controls,
541 p2pEnabled: this.p2pEnabled,
543 captions: videoCaptions.length !== 0,
544 subtitle: this.subtitle,
546 startTime: this.playlist ? this.currentPlaylistElement.startTimestamp : this.startTime,
547 stopTime: this.playlist ? this.currentPlaylistElement.stopTimestamp : this.stopTime,
549 nextVideo: this.playlist ? () => this.playNextVideo() : undefined,
550 hasNextVideo: this.playlist ? () => !!this.getNextPlaylistElement() : undefined,
552 previousVideo: this.playlist ? () => this.playPreviousVideo() : undefined,
553 hasPreviousVideo: this.playlist ? () => !!this.getPreviousPlaylistElement() : undefined,
555 playlist: playlistPlugin,
558 inactivityTimeout: 2500,
559 videoViewUrl: this.getVideoUrl(videoInfo.uuid) + '/views',
560 videoShortUUID: videoInfo.shortUUID,
561 videoUUID: videoInfo.uuid,
563 isLive: videoInfo.isLive,
566 playerElement: this.playerElement,
567 onPlayerElementChange: (element: HTMLVideoElement) => {
568 this.playerElement = element
571 videoDuration: videoInfo.duration,
573 peertubeLink: this.peertubeLink,
574 poster: window.location.origin + videoInfo.previewPath,
575 theaterButton: false,
577 serverUrl: window.location.origin,
578 language: navigator.language,
579 embedUrl: window.location.origin + videoInfo.embedPath,
580 embedTitle: videoInfo.name,
582 errorNotifier: () => {
583 // Empty, we don't have a notifier in the embed
588 videoFiles: videoInfo.files
591 pluginsManager: this.pluginsManager
594 if (this.mode === 'p2p-media-loader') {
595 const hlsPlaylist = videoInfo.streamingPlaylists.find(p => p.type === VideoStreamingPlaylistType.HLS)
597 Object.assign(options, {
599 playlistUrl: hlsPlaylist.playlistUrl,
600 segmentsSha256Url: hlsPlaylist.segmentsSha256Url,
601 redundancyBaseUrls: hlsPlaylist.redundancies.map(r => r.baseUrl),
602 trackerAnnounce: videoInfo.trackerUrls,
603 videoFiles: hlsPlaylist.files
604 } as P2PMediaLoaderOptions
608 this.player = await PeertubePlayerManager.initialize(this.mode, options, (player: videojs.Player) => {
612 this.player.on('customError', (event: any, data: any) => this.handleError(data.err, serverTranslations))
614 window['videojsPlayer'] = this.player
618 this.buildDock(videoInfo)
622 this.removePlaceholder()
624 if (this.isPlaylistEmbed()) {
625 await this.buildPlaylistManager()
627 this.player.playlist().updateSelected()
629 this.player.on('stopped', () => {
634 this.pluginsManager.runHook('action:embed.player.loaded', undefined, { player: this.player, videojs, video: videoInfo })
637 private async initCore () {
638 if (this.userTokens) this.setHeadersFromTokens()
640 this.translationsPromise = TranslationsManager.getServerTranslations(window.location.origin, navigator.language)
641 this.PeertubePlayerManagerModulePromise = import('../../assets/player/peertube-player-manager')
645 if (this.isPlaylistEmbed()) {
646 const playlistId = this.getResourceId()
647 const res = await this.loadPlaylist(playlistId)
648 if (!res) return undefined
650 this.playlist = await res.playlistResponse.json()
652 const playlistElementResult = await res.videosResponse.json()
653 this.playlistElements = await this.loadAllPlaylistVideos(playlistId, playlistElementResult)
655 const params = new URL(window.location.toString()).searchParams
656 const playlistPositionParam = this.getParamString(params, 'playlistPosition')
660 if (playlistPositionParam) {
661 position = parseInt(playlistPositionParam + '', 10)
664 this.currentPlaylistElement = this.playlistElements.find(e => e.position === position)
665 if (!this.currentPlaylistElement || !this.currentPlaylistElement.video) {
666 console.error('Current playlist element is not valid.', this.currentPlaylistElement)
667 this.currentPlaylistElement = this.getNextPlaylistElement()
670 if (!this.currentPlaylistElement) {
671 console.error('This playlist does not have any valid element.')
672 const serverTranslations = await this.translationsPromise
673 this.playlistFetchError(serverTranslations)
677 videoId = this.currentPlaylistElement.video.uuid
679 videoId = this.getResourceId()
682 return this.loadVideoAndBuildPlayer(videoId)
685 private handleError (err: Error, translations?: { [ id: string ]: string }) {
686 if (err.message.includes('from xs param')) {
687 this.player.dispose()
688 this.playerElement = null
689 this.displayError('This video is not available because the remote instance is not responding.', translations)
693 private buildDock (videoInfo: VideoDetails) {
694 if (!this.controls) return
696 // On webtorrent fallback, player may have been disposed
697 if (!this.player.player_) return
699 const title = this.title ? videoInfo.name : undefined
700 const description = this.warningTitle && this.p2pEnabled
701 ? '<span class="text">' + peertubeTranslate('Watching this video may reveal your IP address to others.') + '</span>'
704 const availableAvatars = videoInfo.channel.avatars.filter(a => a.width < 50)
705 const avatar = availableAvatars.length !== 0
706 ? availableAvatars[0]
709 if (title || description) {
710 this.player.peertubeDock({
713 avatarUrl: title && avatar
720 private buildCSS () {
721 const body = document.getElementById('custom-css')
723 if (this.bigPlayBackgroundColor) {
724 body.style.setProperty('--embedBigPlayBackgroundColor', this.bigPlayBackgroundColor)
727 if (this.foregroundColor) {
728 body.style.setProperty('--embedForegroundColor', this.foregroundColor)
732 private async buildCaptions (serverTranslations: any, captionsResponse: Response): Promise<VideoJSCaption[]> {
733 if (captionsResponse.ok) {
734 const { data } = await captionsResponse.json()
736 return data.map((c: VideoCaption) => ({
737 label: peertubeTranslate(c.language.label, serverTranslations),
738 language: c.language.id,
739 src: window.location.origin + c.captionPath
746 private buildPlaceholder (video: VideoDetails) {
747 const placeholder = this.getPlaceholderElement()
749 const url = window.location.origin + video.previewPath
750 placeholder.style.backgroundImage = `url("${url}")`
751 placeholder.style.display = 'block'
754 private removePlaceholder () {
755 const placeholder = this.getPlaceholderElement()
756 placeholder.style.display = 'none'
759 private getPlaceholderElement () {
760 return document.getElementById('placeholder-preview')
763 private setHeadersFromTokens () {
764 this.headers.set('Authorization', `${this.userTokens.tokenType} ${this.userTokens.accessToken}`)
767 private removeTokensFromHeaders () {
768 this.headers.delete('Authorization')
771 private getResourceId () {
772 const urlParts = window.location.pathname.split('/')
773 return urlParts[urlParts.length - 1]
776 private isPlaylistEmbed () {
777 return window.location.pathname.split('/')[1] === 'video-playlists'
780 private loadPlugins (translations?: { [ id: string ]: string }) {
781 this.pluginsManager = new PluginsManager({
782 peertubeHelpersFactory: _ => this.buildPeerTubeHelpers(translations)
785 this.pluginsManager.loadPluginsList(this.config)
787 return this.pluginsManager.ensurePluginsAreLoaded('embed')
790 private buildPeerTubeHelpers (translations?: { [ id: string ]: string }): RegisterClientHelpers {
791 const unimplemented = () => {
792 throw new Error('This helper is not implemented in embed.')
796 getBaseStaticRoute: unimplemented,
797 getBaseRouterRoute: unimplemented,
798 getBasePluginClientPath: unimplemented,
800 getSettings: unimplemented,
802 isLoggedIn: unimplemented,
803 getAuthHeader: unimplemented,
807 error: unimplemented,
808 success: unimplemented
811 showModal: unimplemented,
813 getServerConfig: unimplemented,
816 textMarkdownToHTML: unimplemented,
817 enhancedMarkdownToHTML: unimplemented
820 translate: (value: string) => Promise.resolve(peertubeTranslate(value, translations))
824 private isP2PEnabled (video: Video) {
825 const userP2PEnabled = getBoolOrDefault(
826 peertubeLocalStorage.getItem(UserLocalStorageKeys.P2P_ENABLED),
827 this.config.defaults.p2p.embed.enabled
830 return isP2PEnabled(video, this.config, userP2PEnabled)
836 (window as any).displayIncompatibleBrowser()
838 console.error('Cannot init embed.', err)