2 import videojs from 'video.js'
3 import { objectToUrlEncoded, peertubeLocalStorage } from '@root-helpers/index'
4 import { Tokens } from '@root-helpers/users'
5 import { peertubeTranslate } from '../../../../shared/core-utils/i18n'
14 VideoStreamingPlaylistType
15 } from '../../../../shared/models'
16 import { P2PMediaLoaderOptions, PeertubePlayerManagerOptions, PlayerMode } from '../../assets/player/peertube-player-manager'
17 import { VideoJSCaption } from '../../assets/player/peertube-videojs-typings'
18 import { TranslationsManager } from '../../assets/player/translations-manager'
19 import { PeerTubeEmbedApi } from './embed-api'
21 type Translations = { [ id: string ]: string }
23 export class PeerTubeEmbed {
24 playerElement: HTMLVideoElement
25 player: videojs.Player
26 api: PeerTubeEmbedApi = null
34 startTime: number | string = 0
35 stopTime: number | string
40 bigPlayBackgroundColor: string
41 foregroundColor: string
47 headers = new Headers()
48 LOCAL_STORAGE_OAUTH_CLIENT_KEYS = {
49 CLIENT_ID: 'client_id',
50 CLIENT_SECRET: 'client_secret'
53 private translationsPromise: Promise<{ [id: string]: string }>
54 private configPromise: Promise<ServerConfig>
55 private PeertubePlayerManagerModulePromise: Promise<any>
57 private playlist: VideoPlaylist
58 private playlistElements: VideoPlaylistElement[]
59 private currentPlaylistElement: VideoPlaylistElement
61 private wrapperElement: HTMLElement
63 static async main () {
64 const videoContainerId = 'video-wrapper'
65 const embed = new PeerTubeEmbed(videoContainerId)
69 constructor (private videoWrapperId: string) {
70 this.wrapperElement = document.getElementById(this.videoWrapperId)
73 getVideoUrl (id: string) {
74 return window.location.origin + '/api/v1/videos/' + id
77 refreshFetch (url: string, options?: RequestInit) {
78 return fetch(url, options)
79 .then((res: Response) => {
80 if (res.status !== 401) return res
82 // 401 unauthorized is not catch-ed, but then-ed
85 const refreshingTokenPromise = new Promise((resolve, reject) => {
86 const clientId: string = peertubeLocalStorage.getItem(this.LOCAL_STORAGE_OAUTH_CLIENT_KEYS.CLIENT_ID)
87 const clientSecret: string = peertubeLocalStorage.getItem(this.LOCAL_STORAGE_OAUTH_CLIENT_KEYS.CLIENT_SECRET)
89 const headers = new Headers()
90 headers.set('Content-Type', 'application/x-www-form-urlencoded')
93 refresh_token: this.userTokens.refreshToken,
95 client_secret: clientSecret,
96 response_type: 'code',
97 grant_type: 'refresh_token'
100 fetch('/api/v1/users/token', {
103 body: objectToUrlEncoded(data)
104 }).then(res => res.json())
105 .then((obj: UserRefreshToken) => {
106 this.userTokens.accessToken = obj.access_token
107 this.userTokens.refreshToken = obj.refresh_token
108 this.userTokens.save()
110 this.setHeadersFromTokens()
114 .catch((refreshTokenError: any) => {
115 reject(refreshTokenError)
119 return refreshingTokenPromise
120 .catch(() => this.removeTokensFromHeaders())
121 .then(() => fetch(url, {
123 headers: this.headers
128 getPlaylistUrl (id: string) {
129 return window.location.origin + '/api/v1/video-playlists/' + id
132 loadVideoInfo (videoId: string): Promise<Response> {
133 return this.refreshFetch(this.getVideoUrl(videoId), { headers: this.headers })
136 loadVideoCaptions (videoId: string): Promise<Response> {
137 return this.refreshFetch(this.getVideoUrl(videoId) + '/captions', { headers: this.headers })
140 loadPlaylistInfo (playlistId: string): Promise<Response> {
141 return this.refreshFetch(this.getPlaylistUrl(playlistId), { headers: this.headers })
144 loadPlaylistElements (playlistId: string, start = 0): Promise<Response> {
145 const url = new URL(this.getPlaylistUrl(playlistId) + '/videos')
146 url.search = new URLSearchParams({ start: '' + start, count: '100' }).toString()
148 return this.refreshFetch(url.toString(), { headers: this.headers })
151 loadConfig (): Promise<ServerConfig> {
152 return this.refreshFetch('/api/v1/config')
153 .then(res => res.json())
156 removeElement (element: HTMLElement) {
157 element.parentElement.removeChild(element)
160 displayError (text: string, translations?: Translations) {
161 // Remove video element
162 if (this.playerElement) {
163 this.removeElement(this.playerElement)
164 this.playerElement = undefined
167 const translatedText = peertubeTranslate(text, translations)
168 const translatedSorry = peertubeTranslate('Sorry', translations)
170 document.title = translatedSorry + ' - ' + translatedText
172 const errorBlock = document.getElementById('error-block')
173 errorBlock.style.display = 'flex'
175 const errorTitle = document.getElementById('error-title')
176 errorTitle.innerHTML = peertubeTranslate('Sorry', translations)
178 const errorText = document.getElementById('error-content')
179 errorText.innerHTML = translatedText
181 this.wrapperElement.style.display = 'none'
184 videoNotFound (translations?: Translations) {
185 const text = 'This video does not exist.'
186 this.displayError(text, translations)
189 videoFetchError (translations?: Translations) {
190 const text = 'We cannot fetch the video. Please try again later.'
191 this.displayError(text, translations)
194 playlistNotFound (translations?: Translations) {
195 const text = 'This playlist does not exist.'
196 this.displayError(text, translations)
199 playlistFetchError (translations?: Translations) {
200 const text = 'We cannot fetch the playlist. Please try again later.'
201 this.displayError(text, translations)
204 getParamToggle (params: URLSearchParams, name: string, defaultValue?: boolean) {
205 return params.has(name) ? (params.get(name) === '1' || params.get(name) === 'true') : defaultValue
208 getParamString (params: URLSearchParams, name: string, defaultValue?: string) {
209 return params.has(name) ? params.get(name) : defaultValue
212 async playNextVideo () {
213 const next = this.getNextPlaylistElement()
215 console.log('Next element not found in playlist.')
219 this.currentPlaylistElement = next
221 return this.loadVideoAndBuildPlayer(this.currentPlaylistElement.video.uuid)
224 async playPreviousVideo () {
225 const previous = this.getPreviousPlaylistElement()
227 console.log('Previous element not found in playlist.')
231 this.currentPlaylistElement = previous
233 await this.loadVideoAndBuildPlayer(this.currentPlaylistElement.video.uuid)
236 getCurrentPosition () {
237 if (!this.currentPlaylistElement) return -1
239 return this.currentPlaylistElement.position
244 this.userTokens = Tokens.load()
245 await this.initCore()
251 private initializeApi () {
252 if (!this.enableApi) return
254 this.api = new PeerTubeEmbedApi(this)
255 this.api.initialize()
258 private loadParams (video: VideoDetails) {
260 const params = new URL(window.location.toString()).searchParams
262 this.autoplay = this.getParamToggle(params, 'autoplay', false)
263 this.controls = this.getParamToggle(params, 'controls', true)
264 this.muted = this.getParamToggle(params, 'muted', undefined)
265 this.loop = this.getParamToggle(params, 'loop', false)
266 this.title = this.getParamToggle(params, 'title', true)
267 this.enableApi = this.getParamToggle(params, 'api', this.enableApi)
268 this.warningTitle = this.getParamToggle(params, 'warningTitle', true)
269 this.peertubeLink = this.getParamToggle(params, 'peertubeLink', true)
271 this.scope = this.getParamString(params, 'scope', this.scope)
272 this.subtitle = this.getParamString(params, 'subtitle')
273 this.startTime = this.getParamString(params, 'start')
274 this.stopTime = this.getParamString(params, 'stop')
276 this.bigPlayBackgroundColor = this.getParamString(params, 'bigPlayBackgroundColor')
277 this.foregroundColor = this.getParamString(params, 'foregroundColor')
279 const modeParam = this.getParamString(params, 'mode')
282 if (modeParam === 'p2p-media-loader') this.mode = 'p2p-media-loader'
283 else this.mode = 'webtorrent'
285 if (Array.isArray(video.streamingPlaylists) && video.streamingPlaylists.length !== 0) this.mode = 'p2p-media-loader'
286 else this.mode = 'webtorrent'
289 console.error('Cannot get params from URL.', err)
293 private async loadAllPlaylistVideos (playlistId: string, baseResult: ResultList<VideoPlaylistElement>) {
294 let elements = baseResult.data
295 let total = baseResult.total
298 while (total > elements.length && i < 10) {
299 const result = await this.loadPlaylistElements(playlistId, elements.length)
301 const json = await result.json() as ResultList<VideoPlaylistElement>
304 elements = elements.concat(json.data)
309 console.error('Cannot fetch all playlists elements, there are too many!')
315 private async loadPlaylist (playlistId: string) {
316 const playlistPromise = this.loadPlaylistInfo(playlistId)
317 const playlistElementsPromise = this.loadPlaylistElements(playlistId)
319 let playlistResponse: Response
320 let isResponseOk: boolean
323 playlistResponse = await playlistPromise
331 const serverTranslations = await this.translationsPromise
333 if (playlistResponse?.status === 404) {
334 this.playlistNotFound(serverTranslations)
338 this.playlistFetchError(serverTranslations)
342 return { playlistResponse, videosResponse: await playlistElementsPromise }
345 private async loadVideo (videoId: string) {
346 const videoPromise = this.loadVideoInfo(videoId)
348 let videoResponse: Response
349 let isResponseOk: boolean
352 videoResponse = await videoPromise
361 const serverTranslations = await this.translationsPromise
363 if (videoResponse?.status === 404) {
364 this.videoNotFound(serverTranslations)
368 this.videoFetchError(serverTranslations)
372 const captionsPromise = this.loadVideoCaptions(videoId)
374 return { captionsPromise, videoResponse }
377 private async buildPlaylistManager () {
378 const translations = await this.translationsPromise
381 timeout: 10000, // 10s
382 headText: peertubeTranslate('Up Next', translations),
383 cancelText: peertubeTranslate('Cancel', translations),
384 suspendedText: peertubeTranslate('Autoplay is suspended', translations),
385 getTitle: () => this.nextVideoTitle(),
386 next: () => this.playNextVideo(),
387 condition: () => !!this.getNextPlaylistElement(),
388 suspended: () => false
392 private async loadVideoAndBuildPlayer (uuid: string) {
393 const res = await this.loadVideo(uuid)
394 if (res === undefined) return
396 return this.buildVideoPlayer(res.videoResponse, res.captionsPromise)
399 private nextVideoTitle () {
400 const next = this.getNextPlaylistElement()
403 return next.video.name
406 private getNextPlaylistElement (position?: number): VideoPlaylistElement {
407 if (!position) position = this.currentPlaylistElement.position + 1
409 if (position > this.playlist.videosLength) {
413 const next = this.playlistElements.find(e => e.position === position)
415 if (!next || !next.video) {
416 return this.getNextPlaylistElement(position + 1)
422 private getPreviousPlaylistElement (position?: number): VideoPlaylistElement {
423 if (!position) position = this.currentPlaylistElement.position - 1
429 const prev = this.playlistElements.find(e => e.position === position)
431 if (!prev || !prev.video) {
432 return this.getNextPlaylistElement(position - 1)
438 private async buildVideoPlayer (videoResponse: Response, captionsPromise: Promise<Response>) {
439 let alreadyHadPlayer = false
442 this.player.dispose()
443 alreadyHadPlayer = true
446 this.playerElement = document.createElement('video')
447 this.playerElement.className = 'video-js vjs-peertube-skin'
448 this.playerElement.setAttribute('playsinline', 'true')
449 this.wrapperElement.appendChild(this.playerElement)
451 const videoInfoPromise = videoResponse.json()
452 .then((videoInfo: VideoDetails) => {
453 if (!alreadyHadPlayer) this.loadPlaceholder(videoInfo)
458 const [ videoInfoTmp, serverTranslations, captionsResponse, config, PeertubePlayerManagerModule ] = await Promise.all([
460 this.translationsPromise,
463 this.PeertubePlayerManagerModulePromise
466 const videoInfo: VideoDetails = videoInfoTmp
468 const PeertubePlayerManager = PeertubePlayerManagerModule.PeertubePlayerManager
469 const videoCaptions = await this.buildCaptions(serverTranslations, captionsResponse)
471 this.loadParams(videoInfo)
473 const playlistPlugin = this.currentPlaylistElement
475 elements: this.playlistElements,
476 playlist: this.playlist,
478 getCurrentPosition: () => this.currentPlaylistElement.position,
480 onItemClicked: (videoPlaylistElement: VideoPlaylistElement) => {
481 this.currentPlaylistElement = videoPlaylistElement
483 this.loadVideoAndBuildPlayer(this.currentPlaylistElement.video.uuid)
484 .catch(err => console.error(err))
489 const options: PeertubePlayerManagerOptions = {
491 // Autoplay in playlist mode
492 autoplay: alreadyHadPlayer ? true : this.autoplay,
493 controls: this.controls,
497 captions: videoCaptions.length !== 0,
498 subtitle: this.subtitle,
500 startTime: this.playlist ? this.currentPlaylistElement.startTimestamp : this.startTime,
501 stopTime: this.playlist ? this.currentPlaylistElement.stopTimestamp : this.stopTime,
503 nextVideo: this.playlist ? () => this.playNextVideo() : undefined,
504 hasNextVideo: this.playlist ? () => !!this.getNextPlaylistElement() : undefined,
506 previousVideo: this.playlist ? () => this.playPreviousVideo() : undefined,
507 hasPreviousVideo: this.playlist ? () => !!this.getPreviousPlaylistElement() : undefined,
509 playlist: playlistPlugin,
512 inactivityTimeout: 2500,
513 videoViewUrl: this.getVideoUrl(videoInfo.uuid) + '/views',
515 playerElement: this.playerElement,
516 onPlayerElementChange: (element: HTMLVideoElement) => this.playerElement = element,
518 videoDuration: videoInfo.duration,
520 peertubeLink: this.peertubeLink,
521 poster: window.location.origin + videoInfo.previewPath,
522 theaterButton: false,
524 serverUrl: window.location.origin,
525 language: navigator.language,
526 embedUrl: window.location.origin + videoInfo.embedPath
530 videoFiles: videoInfo.files
534 if (this.mode === 'p2p-media-loader') {
535 const hlsPlaylist = videoInfo.streamingPlaylists.find(p => p.type === VideoStreamingPlaylistType.HLS)
537 Object.assign(options, {
539 playlistUrl: hlsPlaylist.playlistUrl,
540 segmentsSha256Url: hlsPlaylist.segmentsSha256Url,
541 redundancyBaseUrls: hlsPlaylist.redundancies.map(r => r.baseUrl),
542 trackerAnnounce: videoInfo.trackerUrls,
543 videoFiles: hlsPlaylist.files
544 } as P2PMediaLoaderOptions
548 this.player = await PeertubePlayerManager.initialize(this.mode, options, (player: videojs.Player) => this.player = player)
549 this.player.on('customError', (event: any, data: any) => this.handleError(data.err, serverTranslations))
551 window[ 'videojsPlayer' ] = this.player
555 await this.buildDock(videoInfo, config)
559 this.removePlaceholder()
561 if (this.isPlaylistEmbed()) {
562 await this.buildPlaylistManager()
564 this.player.playlist().updateSelected()
566 this.player.on('stopped', () => {
572 private async initCore () {
573 if (this.userTokens) this.setHeadersFromTokens()
575 this.configPromise = this.loadConfig()
576 this.translationsPromise = TranslationsManager.getServerTranslations(window.location.origin, navigator.language)
577 this.PeertubePlayerManagerModulePromise = import('../../assets/player/peertube-player-manager')
581 if (this.isPlaylistEmbed()) {
582 const playlistId = this.getResourceId()
583 const res = await this.loadPlaylist(playlistId)
584 if (!res) return undefined
586 this.playlist = await res.playlistResponse.json()
588 const playlistElementResult = await res.videosResponse.json()
589 this.playlistElements = await this.loadAllPlaylistVideos(playlistId, playlistElementResult)
591 const params = new URL(window.location.toString()).searchParams
592 const playlistPositionParam = this.getParamString(params, 'playlistPosition')
596 if (playlistPositionParam) {
597 position = parseInt(playlistPositionParam + '', 10)
600 this.currentPlaylistElement = this.playlistElements.find(e => e.position === position)
601 if (!this.currentPlaylistElement || !this.currentPlaylistElement.video) {
602 console.error('Current playlist element is not valid.', this.currentPlaylistElement)
603 this.currentPlaylistElement = this.getNextPlaylistElement()
606 if (!this.currentPlaylistElement) {
607 console.error('This playlist does not have any valid element.')
608 const serverTranslations = await this.translationsPromise
609 this.playlistFetchError(serverTranslations)
613 videoId = this.currentPlaylistElement.video.uuid
615 videoId = this.getResourceId()
618 return this.loadVideoAndBuildPlayer(videoId)
621 private handleError (err: Error, translations?: { [ id: string ]: string }) {
622 if (err.message.indexOf('from xs param') !== -1) {
623 this.player.dispose()
624 this.playerElement = null
625 this.displayError('This video is not available because the remote instance is not responding.', translations)
630 private async buildDock (videoInfo: VideoDetails, config: ServerConfig) {
631 if (!this.controls) return
633 // On webtorrent fallback, player may have been disposed
634 if (!this.player.player_) return
636 const title = this.title ? videoInfo.name : undefined
638 const description = config.tracker.enabled && this.warningTitle
639 ? '<span class="text">' + peertubeTranslate('Watching this video may reveal your IP address to others.') + '</span>'
648 private buildCSS () {
649 const body = document.getElementById('custom-css')
651 if (this.bigPlayBackgroundColor) {
652 body.style.setProperty('--embedBigPlayBackgroundColor', this.bigPlayBackgroundColor)
655 if (this.foregroundColor) {
656 body.style.setProperty('--embedForegroundColor', this.foregroundColor)
660 private async buildCaptions (serverTranslations: any, captionsResponse: Response): Promise<VideoJSCaption[]> {
661 if (captionsResponse.ok) {
662 const { data } = (await captionsResponse.json()) as ResultList<VideoCaption>
664 return data.map(c => ({
665 label: peertubeTranslate(c.language.label, serverTranslations),
666 language: c.language.id,
667 src: window.location.origin + c.captionPath
674 private loadPlaceholder (video: VideoDetails) {
675 const placeholder = this.getPlaceholderElement()
677 const url = window.location.origin + video.previewPath
678 placeholder.style.backgroundImage = `url("${url}")`
679 placeholder.style.display = 'block'
682 private removePlaceholder () {
683 const placeholder = this.getPlaceholderElement()
684 placeholder.style.display = 'none'
687 private getPlaceholderElement () {
688 return document.getElementById('placeholder-preview')
691 private setHeadersFromTokens () {
692 this.headers.set('Authorization', `${this.userTokens.tokenType} ${this.userTokens.accessToken}`)
695 private removeTokensFromHeaders () {
696 this.headers.delete('Authorization')
699 private getResourceId () {
700 const urlParts = window.location.pathname.split('/')
701 return urlParts[ urlParts.length - 1 ]
704 private isPlaylistEmbed () {
705 return window.location.pathname.split('/')[1] === 'video-playlists'
710 .catch(err => console.error('Cannot init embed.', err))