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?: Object) {
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)
88 const headers = new Headers()
89 headers.set('Content-Type', 'application/x-www-form-urlencoded')
91 refresh_token: this.userTokens.refreshToken,
93 client_secret: clientSecret,
94 response_type: 'code',
95 grant_type: 'refresh_token'
98 fetch('/api/v1/users/token', {
101 body: objectToUrlEncoded(data)
103 .then(res => res.json())
104 .then((obj: UserRefreshToken) => {
105 this.userTokens.accessToken = obj.access_token
106 this.userTokens.refreshToken = obj.refresh_token
107 this.userTokens.save()
109 this.setHeadersFromTokens()
113 .catch((refreshTokenError: any) => {
114 reject(refreshTokenError)
118 return refreshingTokenPromise
120 // If refreshing fails, continue with original error
123 .then(() => fetch(url, {
125 headers: this.headers
130 getPlaylistUrl (id: string) {
131 return window.location.origin + '/api/v1/video-playlists/' + id
134 loadVideoInfo (videoId: string): Promise<Response> {
135 return this.refreshFetch(this.getVideoUrl(videoId), { headers: this.headers })
138 loadVideoCaptions (videoId: string): Promise<Response> {
139 return this.refreshFetch(this.getVideoUrl(videoId) + '/captions', { headers: this.headers })
142 loadPlaylistInfo (playlistId: string): Promise<Response> {
143 return this.refreshFetch(this.getPlaylistUrl(playlistId), { headers: this.headers })
146 loadPlaylistElements (playlistId: string, start = 0): Promise<Response> {
147 const url = new URL(this.getPlaylistUrl(playlistId) + '/videos')
148 url.search = new URLSearchParams({ start: '' + start, count: '100' }).toString()
150 return this.refreshFetch(url.toString(), { headers: this.headers })
153 loadConfig (): Promise<ServerConfig> {
154 return this.refreshFetch('/api/v1/config')
155 .then(res => res.json())
158 removeElement (element: HTMLElement) {
159 element.parentElement.removeChild(element)
162 displayError (text: string, translations?: Translations) {
163 // Remove video element
164 if (this.playerElement) {
165 this.removeElement(this.playerElement)
166 this.playerElement = undefined
169 const translatedText = peertubeTranslate(text, translations)
170 const translatedSorry = peertubeTranslate('Sorry', translations)
172 document.title = translatedSorry + ' - ' + translatedText
174 const errorBlock = document.getElementById('error-block')
175 errorBlock.style.display = 'flex'
177 const errorTitle = document.getElementById('error-title')
178 errorTitle.innerHTML = peertubeTranslate('Sorry', translations)
180 const errorText = document.getElementById('error-content')
181 errorText.innerHTML = translatedText
183 this.wrapperElement.style.display = 'none'
186 videoNotFound (translations?: Translations) {
187 const text = 'This video does not exist.'
188 this.displayError(text, translations)
191 videoFetchError (translations?: Translations) {
192 const text = 'We cannot fetch the video. Please try again later.'
193 this.displayError(text, translations)
196 playlistNotFound (translations?: Translations) {
197 const text = 'This playlist does not exist.'
198 this.displayError(text, translations)
201 playlistFetchError (translations?: Translations) {
202 const text = 'We cannot fetch the playlist. Please try again later.'
203 this.displayError(text, translations)
206 getParamToggle (params: URLSearchParams, name: string, defaultValue?: boolean) {
207 return params.has(name) ? (params.get(name) === '1' || params.get(name) === 'true') : defaultValue
210 getParamString (params: URLSearchParams, name: string, defaultValue?: string) {
211 return params.has(name) ? params.get(name) : defaultValue
214 async playNextVideo () {
215 const next = this.getNextPlaylistElement()
217 console.log('Next element not found in playlist.')
221 this.currentPlaylistElement = next
223 return this.loadVideoAndBuildPlayer(this.currentPlaylistElement.video.uuid)
226 async playPreviousVideo () {
227 const previous = this.getPreviousPlaylistElement()
229 console.log('Previous element not found in playlist.')
233 this.currentPlaylistElement = previous
235 await this.loadVideoAndBuildPlayer(this.currentPlaylistElement.video.uuid)
238 getCurrentPosition () {
239 if (!this.currentPlaylistElement) return -1
241 return this.currentPlaylistElement.position
246 this.userTokens = Tokens.load()
247 await this.initCore()
253 private initializeApi () {
254 if (!this.enableApi) return
256 this.api = new PeerTubeEmbedApi(this)
257 this.api.initialize()
260 private loadParams (video: VideoDetails) {
262 const params = new URL(window.location.toString()).searchParams
264 this.autoplay = this.getParamToggle(params, 'autoplay', false)
265 this.controls = this.getParamToggle(params, 'controls', true)
266 this.muted = this.getParamToggle(params, 'muted', undefined)
267 this.loop = this.getParamToggle(params, 'loop', false)
268 this.title = this.getParamToggle(params, 'title', true)
269 this.enableApi = this.getParamToggle(params, 'api', this.enableApi)
270 this.warningTitle = this.getParamToggle(params, 'warningTitle', true)
271 this.peertubeLink = this.getParamToggle(params, 'peertubeLink', true)
273 this.scope = this.getParamString(params, 'scope', this.scope)
274 this.subtitle = this.getParamString(params, 'subtitle')
275 this.startTime = this.getParamString(params, 'start')
276 this.stopTime = this.getParamString(params, 'stop')
278 this.bigPlayBackgroundColor = this.getParamString(params, 'bigPlayBackgroundColor')
279 this.foregroundColor = this.getParamString(params, 'foregroundColor')
281 const modeParam = this.getParamString(params, 'mode')
284 if (modeParam === 'p2p-media-loader') this.mode = 'p2p-media-loader'
285 else this.mode = 'webtorrent'
287 if (Array.isArray(video.streamingPlaylists) && video.streamingPlaylists.length !== 0) this.mode = 'p2p-media-loader'
288 else this.mode = 'webtorrent'
291 console.error('Cannot get params from URL.', err)
295 private async loadAllPlaylistVideos (playlistId: string, baseResult: ResultList<VideoPlaylistElement>) {
296 let elements = baseResult.data
297 let total = baseResult.total
300 while (total > elements.length && i < 10) {
301 const result = await this.loadPlaylistElements(playlistId, elements.length)
303 const json = await result.json() as ResultList<VideoPlaylistElement>
306 elements = elements.concat(json.data)
311 console.error('Cannot fetch all playlists elements, there are too many!')
317 private async loadPlaylist (playlistId: string) {
318 const playlistPromise = this.loadPlaylistInfo(playlistId)
319 const playlistElementsPromise = this.loadPlaylistElements(playlistId)
321 let playlistResponse: Response
322 let isResponseOk: boolean
325 playlistResponse = await playlistPromise
333 const serverTranslations = await this.translationsPromise
335 if (playlistResponse?.status === 404) {
336 this.playlistNotFound(serverTranslations)
340 this.playlistFetchError(serverTranslations)
344 return { playlistResponse, videosResponse: await playlistElementsPromise }
347 private async loadVideo (videoId: string) {
348 const videoPromise = this.loadVideoInfo(videoId)
350 let videoResponse: Response
351 let isResponseOk: boolean
354 videoResponse = await videoPromise
363 const serverTranslations = await this.translationsPromise
365 if (videoResponse?.status === 404) {
366 this.videoNotFound(serverTranslations)
370 this.videoFetchError(serverTranslations)
374 const captionsPromise = this.loadVideoCaptions(videoId)
376 return { captionsPromise, videoResponse }
379 private async buildPlaylistManager () {
380 const translations = await this.translationsPromise
383 timeout: 10000, // 10s
384 headText: peertubeTranslate('Up Next', translations),
385 cancelText: peertubeTranslate('Cancel', translations),
386 suspendedText: peertubeTranslate('Autoplay is suspended', translations),
387 getTitle: () => this.nextVideoTitle(),
388 next: () => this.playNextVideo(),
389 condition: () => !!this.getNextPlaylistElement(),
390 suspended: () => false
394 private async loadVideoAndBuildPlayer (uuid: string) {
395 const res = await this.loadVideo(uuid)
396 if (res === undefined) return
398 return this.buildVideoPlayer(res.videoResponse, res.captionsPromise)
401 private nextVideoTitle () {
402 const next = this.getNextPlaylistElement()
405 return next.video.name
408 private getNextPlaylistElement (position?: number): VideoPlaylistElement {
409 if (!position) position = this.currentPlaylistElement.position + 1
411 if (position > this.playlist.videosLength) {
415 const next = this.playlistElements.find(e => e.position === position)
417 if (!next || !next.video) {
418 return this.getNextPlaylistElement(position + 1)
424 private getPreviousPlaylistElement (position?: number): VideoPlaylistElement {
425 if (!position) position = this.currentPlaylistElement.position - 1
431 const prev = this.playlistElements.find(e => e.position === position)
433 if (!prev || !prev.video) {
434 return this.getNextPlaylistElement(position - 1)
440 private async buildVideoPlayer (videoResponse: Response, captionsPromise: Promise<Response>) {
441 let alreadyHadPlayer = false
444 this.player.dispose()
445 alreadyHadPlayer = true
448 this.playerElement = document.createElement('video')
449 this.playerElement.className = 'video-js vjs-peertube-skin'
450 this.playerElement.setAttribute('playsinline', 'true')
451 this.wrapperElement.appendChild(this.playerElement)
453 const videoInfoPromise = videoResponse.json()
454 .then((videoInfo: VideoDetails) => {
455 if (!alreadyHadPlayer) this.loadPlaceholder(videoInfo)
460 const [ videoInfoTmp, serverTranslations, captionsResponse, config, PeertubePlayerManagerModule ] = await Promise.all([
462 this.translationsPromise,
465 this.PeertubePlayerManagerModulePromise
468 const videoInfo: VideoDetails = videoInfoTmp
470 const PeertubePlayerManager = PeertubePlayerManagerModule.PeertubePlayerManager
471 const videoCaptions = await this.buildCaptions(serverTranslations, captionsResponse)
473 this.loadParams(videoInfo)
475 const playlistPlugin = this.currentPlaylistElement
477 elements: this.playlistElements,
478 playlist: this.playlist,
480 getCurrentPosition: () => this.currentPlaylistElement.position,
482 onItemClicked: (videoPlaylistElement: VideoPlaylistElement) => {
483 this.currentPlaylistElement = videoPlaylistElement
485 this.loadVideoAndBuildPlayer(this.currentPlaylistElement.video.uuid)
486 .catch(err => console.error(err))
491 const options: PeertubePlayerManagerOptions = {
493 // Autoplay in playlist mode
494 autoplay: alreadyHadPlayer ? true : this.autoplay,
495 controls: this.controls,
499 captions: videoCaptions.length !== 0,
500 subtitle: this.subtitle,
502 startTime: this.playlist ? this.currentPlaylistElement.startTimestamp : this.startTime,
503 stopTime: this.playlist ? this.currentPlaylistElement.stopTimestamp : this.stopTime,
505 nextVideo: this.playlist ? () => this.playNextVideo() : undefined,
506 hasNextVideo: this.playlist ? () => !!this.getNextPlaylistElement() : undefined,
508 previousVideo: this.playlist ? () => this.playPreviousVideo() : undefined,
509 hasPreviousVideo: this.playlist ? () => !!this.getPreviousPlaylistElement() : undefined,
511 playlist: playlistPlugin,
514 inactivityTimeout: 2500,
515 videoViewUrl: this.getVideoUrl(videoInfo.uuid) + '/views',
517 playerElement: this.playerElement,
518 onPlayerElementChange: (element: HTMLVideoElement) => this.playerElement = element,
520 videoDuration: videoInfo.duration,
522 peertubeLink: this.peertubeLink,
523 poster: window.location.origin + videoInfo.previewPath,
524 theaterButton: false,
526 serverUrl: window.location.origin,
527 language: navigator.language,
528 embedUrl: window.location.origin + videoInfo.embedPath
532 videoFiles: videoInfo.files
536 if (this.mode === 'p2p-media-loader') {
537 const hlsPlaylist = videoInfo.streamingPlaylists.find(p => p.type === VideoStreamingPlaylistType.HLS)
539 Object.assign(options, {
541 playlistUrl: hlsPlaylist.playlistUrl,
542 segmentsSha256Url: hlsPlaylist.segmentsSha256Url,
543 redundancyBaseUrls: hlsPlaylist.redundancies.map(r => r.baseUrl),
544 trackerAnnounce: videoInfo.trackerUrls,
545 videoFiles: hlsPlaylist.files
546 } as P2PMediaLoaderOptions
550 this.player = await PeertubePlayerManager.initialize(this.mode, options, (player: videojs.Player) => this.player = player)
551 this.player.on('customError', (event: any, data: any) => this.handleError(data.err, serverTranslations))
553 window[ 'videojsPlayer' ] = this.player
557 await this.buildDock(videoInfo, config)
561 this.removePlaceholder()
563 if (this.isPlaylistEmbed()) {
564 await this.buildPlaylistManager()
566 this.player.playlist().updateSelected()
568 this.player.on('stopped', () => {
574 private async initCore () {
575 if (this.userTokens) this.setHeadersFromTokens()
577 this.configPromise = this.loadConfig()
578 this.translationsPromise = TranslationsManager.getServerTranslations(window.location.origin, navigator.language)
579 this.PeertubePlayerManagerModulePromise = import('../../assets/player/peertube-player-manager')
583 if (this.isPlaylistEmbed()) {
584 const playlistId = this.getResourceId()
585 const res = await this.loadPlaylist(playlistId)
586 if (!res) return undefined
588 this.playlist = await res.playlistResponse.json()
590 const playlistElementResult = await res.videosResponse.json()
591 this.playlistElements = await this.loadAllPlaylistVideos(playlistId, playlistElementResult)
593 const params = new URL(window.location.toString()).searchParams
594 const playlistPositionParam = this.getParamString(params, 'playlistPosition')
598 if (playlistPositionParam) {
599 position = parseInt(playlistPositionParam + '', 10)
602 this.currentPlaylistElement = this.playlistElements.find(e => e.position === position)
603 if (!this.currentPlaylistElement || !this.currentPlaylistElement.video) {
604 console.error('Current playlist element is not valid.', this.currentPlaylistElement)
605 this.currentPlaylistElement = this.getNextPlaylistElement()
608 if (!this.currentPlaylistElement) {
609 console.error('This playlist does not have any valid element.')
610 const serverTranslations = await this.translationsPromise
611 this.playlistFetchError(serverTranslations)
615 videoId = this.currentPlaylistElement.video.uuid
617 videoId = this.getResourceId()
620 return this.loadVideoAndBuildPlayer(videoId)
623 private handleError (err: Error, translations?: { [ id: string ]: string }) {
624 if (err.message.indexOf('from xs param') !== -1) {
625 this.player.dispose()
626 this.playerElement = null
627 this.displayError('This video is not available because the remote instance is not responding.', translations)
632 private async buildDock (videoInfo: VideoDetails, config: ServerConfig) {
633 if (!this.controls) return
635 // On webtorrent fallback, player may have been disposed
636 if (!this.player.player_) return
638 const title = this.title ? videoInfo.name : undefined
640 const description = config.tracker.enabled && this.warningTitle
641 ? '<span class="text">' + peertubeTranslate('Watching this video may reveal your IP address to others.') + '</span>'
650 private buildCSS () {
651 const body = document.getElementById('custom-css')
653 if (this.bigPlayBackgroundColor) {
654 body.style.setProperty('--embedBigPlayBackgroundColor', this.bigPlayBackgroundColor)
657 if (this.foregroundColor) {
658 body.style.setProperty('--embedForegroundColor', this.foregroundColor)
662 private async buildCaptions (serverTranslations: any, captionsResponse: Response): Promise<VideoJSCaption[]> {
663 if (captionsResponse.ok) {
664 const { data } = (await captionsResponse.json()) as ResultList<VideoCaption>
666 return data.map(c => ({
667 label: peertubeTranslate(c.language.label, serverTranslations),
668 language: c.language.id,
669 src: window.location.origin + c.captionPath
676 private loadPlaceholder (video: VideoDetails) {
677 const placeholder = this.getPlaceholderElement()
679 const url = window.location.origin + video.previewPath
680 placeholder.style.backgroundImage = `url("${url}")`
681 placeholder.style.display = 'block'
684 private removePlaceholder () {
685 const placeholder = this.getPlaceholderElement()
686 placeholder.style.display = 'none'
689 private getPlaceholderElement () {
690 return document.getElementById('placeholder-preview')
693 private setHeadersFromTokens () {
694 this.headers.set('Authorization', `${this.userTokens.tokenType} ${this.userTokens.accessToken}`)
697 private getResourceId () {
698 const urlParts = window.location.pathname.split('/')
699 return urlParts[ urlParts.length - 1 ]
702 private isPlaylistEmbed () {
703 return window.location.pathname.split('/')[1] === 'video-playlists'
708 .catch(err => console.error('Cannot init embed.', err))