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 const refreshingTokenPromise = new Promise((resolve, reject) => {
83 const clientId: string = peertubeLocalStorage.getItem(this.LOCAL_STORAGE_OAUTH_CLIENT_KEYS.CLIENT_ID)
84 const clientSecret: string = peertubeLocalStorage.getItem(this.LOCAL_STORAGE_OAUTH_CLIENT_KEYS.CLIENT_SECRET)
86 const headers = new Headers()
87 headers.set('Content-Type', 'application/x-www-form-urlencoded')
90 refresh_token: this.userTokens.refreshToken,
92 client_secret: clientSecret,
93 response_type: 'code',
94 grant_type: 'refresh_token'
97 fetch('/api/v1/users/token', {
100 body: objectToUrlEncoded(data)
102 if (res.status === 401) return undefined
105 }).then((obj: UserRefreshToken & { code: 'invalid_grant'}) => {
106 if (!obj || obj.code === 'invalid_grant') {
108 this.removeTokensFromHeaders()
113 this.userTokens.accessToken = obj.access_token
114 this.userTokens.refreshToken = obj.refresh_token
115 this.userTokens.save()
117 this.setHeadersFromTokens()
121 .catch((refreshTokenError: any) => {
122 reject(refreshTokenError)
126 return refreshingTokenPromise
130 this.removeTokensFromHeaders()
131 }).then(() => fetch(url, {
133 headers: this.headers
138 getPlaylistUrl (id: string) {
139 return window.location.origin + '/api/v1/video-playlists/' + id
142 loadVideoInfo (videoId: string): Promise<Response> {
143 return this.refreshFetch(this.getVideoUrl(videoId), { headers: this.headers })
146 loadVideoCaptions (videoId: string): Promise<Response> {
147 return this.refreshFetch(this.getVideoUrl(videoId) + '/captions', { headers: this.headers })
150 loadPlaylistInfo (playlistId: string): Promise<Response> {
151 return this.refreshFetch(this.getPlaylistUrl(playlistId), { headers: this.headers })
154 loadPlaylistElements (playlistId: string, start = 0): Promise<Response> {
155 const url = new URL(this.getPlaylistUrl(playlistId) + '/videos')
156 url.search = new URLSearchParams({ start: '' + start, count: '100' }).toString()
158 return this.refreshFetch(url.toString(), { headers: this.headers })
161 loadConfig (): Promise<ServerConfig> {
162 return this.refreshFetch('/api/v1/config')
163 .then(res => res.json())
166 removeElement (element: HTMLElement) {
167 element.parentElement.removeChild(element)
170 displayError (text: string, translations?: Translations) {
171 // Remove video element
172 if (this.playerElement) {
173 this.removeElement(this.playerElement)
174 this.playerElement = undefined
177 const translatedText = peertubeTranslate(text, translations)
178 const translatedSorry = peertubeTranslate('Sorry', translations)
180 document.title = translatedSorry + ' - ' + translatedText
182 const errorBlock = document.getElementById('error-block')
183 errorBlock.style.display = 'flex'
185 const errorTitle = document.getElementById('error-title')
186 errorTitle.innerHTML = peertubeTranslate('Sorry', translations)
188 const errorText = document.getElementById('error-content')
189 errorText.innerHTML = translatedText
191 this.wrapperElement.style.display = 'none'
194 videoNotFound (translations?: Translations) {
195 const text = 'This video does not exist.'
196 this.displayError(text, translations)
199 videoFetchError (translations?: Translations) {
200 const text = 'We cannot fetch the video. Please try again later.'
201 this.displayError(text, translations)
204 playlistNotFound (translations?: Translations) {
205 const text = 'This playlist does not exist.'
206 this.displayError(text, translations)
209 playlistFetchError (translations?: Translations) {
210 const text = 'We cannot fetch the playlist. Please try again later.'
211 this.displayError(text, translations)
214 getParamToggle (params: URLSearchParams, name: string, defaultValue?: boolean) {
215 return params.has(name) ? (params.get(name) === '1' || params.get(name) === 'true') : defaultValue
218 getParamString (params: URLSearchParams, name: string, defaultValue?: string) {
219 return params.has(name) ? params.get(name) : defaultValue
222 async playNextVideo () {
223 const next = this.getNextPlaylistElement()
225 console.log('Next element not found in playlist.')
229 this.currentPlaylistElement = next
231 return this.loadVideoAndBuildPlayer(this.currentPlaylistElement.video.uuid)
234 async playPreviousVideo () {
235 const previous = this.getPreviousPlaylistElement()
237 console.log('Previous element not found in playlist.')
241 this.currentPlaylistElement = previous
243 await this.loadVideoAndBuildPlayer(this.currentPlaylistElement.video.uuid)
246 getCurrentPosition () {
247 if (!this.currentPlaylistElement) return -1
249 return this.currentPlaylistElement.position
254 this.userTokens = Tokens.load()
255 await this.initCore()
261 private initializeApi () {
262 if (!this.enableApi) return
264 this.api = new PeerTubeEmbedApi(this)
265 this.api.initialize()
268 private loadParams (video: VideoDetails) {
270 const params = new URL(window.location.toString()).searchParams
272 this.autoplay = this.getParamToggle(params, 'autoplay', false)
273 this.controls = this.getParamToggle(params, 'controls', true)
274 this.muted = this.getParamToggle(params, 'muted', undefined)
275 this.loop = this.getParamToggle(params, 'loop', false)
276 this.title = this.getParamToggle(params, 'title', true)
277 this.enableApi = this.getParamToggle(params, 'api', this.enableApi)
278 this.warningTitle = this.getParamToggle(params, 'warningTitle', true)
279 this.peertubeLink = this.getParamToggle(params, 'peertubeLink', true)
281 this.scope = this.getParamString(params, 'scope', this.scope)
282 this.subtitle = this.getParamString(params, 'subtitle')
283 this.startTime = this.getParamString(params, 'start')
284 this.stopTime = this.getParamString(params, 'stop')
286 this.bigPlayBackgroundColor = this.getParamString(params, 'bigPlayBackgroundColor')
287 this.foregroundColor = this.getParamString(params, 'foregroundColor')
289 const modeParam = this.getParamString(params, 'mode')
292 if (modeParam === 'p2p-media-loader') this.mode = 'p2p-media-loader'
293 else this.mode = 'webtorrent'
295 if (Array.isArray(video.streamingPlaylists) && video.streamingPlaylists.length !== 0) this.mode = 'p2p-media-loader'
296 else this.mode = 'webtorrent'
299 console.error('Cannot get params from URL.', err)
303 private async loadAllPlaylistVideos (playlistId: string, baseResult: ResultList<VideoPlaylistElement>) {
304 let elements = baseResult.data
305 let total = baseResult.total
308 while (total > elements.length && i < 10) {
309 const result = await this.loadPlaylistElements(playlistId, elements.length)
311 const json = await result.json() as ResultList<VideoPlaylistElement>
314 elements = elements.concat(json.data)
319 console.error('Cannot fetch all playlists elements, there are too many!')
325 private async loadPlaylist (playlistId: string) {
326 const playlistPromise = this.loadPlaylistInfo(playlistId)
327 const playlistElementsPromise = this.loadPlaylistElements(playlistId)
329 let playlistResponse: Response
330 let isResponseOk: boolean
333 playlistResponse = await playlistPromise
341 const serverTranslations = await this.translationsPromise
343 if (playlistResponse?.status === 404) {
344 this.playlistNotFound(serverTranslations)
348 this.playlistFetchError(serverTranslations)
352 return { playlistResponse, videosResponse: await playlistElementsPromise }
355 private async loadVideo (videoId: string) {
356 const videoPromise = this.loadVideoInfo(videoId)
358 let videoResponse: Response
359 let isResponseOk: boolean
362 videoResponse = await videoPromise
371 const serverTranslations = await this.translationsPromise
373 if (videoResponse?.status === 404) {
374 this.videoNotFound(serverTranslations)
378 this.videoFetchError(serverTranslations)
382 const captionsPromise = this.loadVideoCaptions(videoId)
384 return { captionsPromise, videoResponse }
387 private async buildPlaylistManager () {
388 const translations = await this.translationsPromise
391 timeout: 10000, // 10s
392 headText: peertubeTranslate('Up Next', translations),
393 cancelText: peertubeTranslate('Cancel', translations),
394 suspendedText: peertubeTranslate('Autoplay is suspended', translations),
395 getTitle: () => this.nextVideoTitle(),
396 next: () => this.playNextVideo(),
397 condition: () => !!this.getNextPlaylistElement(),
398 suspended: () => false
402 private async loadVideoAndBuildPlayer (uuid: string) {
403 const res = await this.loadVideo(uuid)
404 if (res === undefined) return
406 return this.buildVideoPlayer(res.videoResponse, res.captionsPromise)
409 private nextVideoTitle () {
410 const next = this.getNextPlaylistElement()
413 return next.video.name
416 private getNextPlaylistElement (position?: number): VideoPlaylistElement {
417 if (!position) position = this.currentPlaylistElement.position + 1
419 if (position > this.playlist.videosLength) {
423 const next = this.playlistElements.find(e => e.position === position)
425 if (!next || !next.video) {
426 return this.getNextPlaylistElement(position + 1)
432 private getPreviousPlaylistElement (position?: number): VideoPlaylistElement {
433 if (!position) position = this.currentPlaylistElement.position - 1
439 const prev = this.playlistElements.find(e => e.position === position)
441 if (!prev || !prev.video) {
442 return this.getNextPlaylistElement(position - 1)
448 private async buildVideoPlayer (videoResponse: Response, captionsPromise: Promise<Response>) {
449 let alreadyHadPlayer = false
452 this.player.dispose()
453 alreadyHadPlayer = true
456 this.playerElement = document.createElement('video')
457 this.playerElement.className = 'video-js vjs-peertube-skin'
458 this.playerElement.setAttribute('playsinline', 'true')
459 this.wrapperElement.appendChild(this.playerElement)
461 const videoInfoPromise = videoResponse.json()
462 .then((videoInfo: VideoDetails) => {
463 if (!alreadyHadPlayer) this.loadPlaceholder(videoInfo)
468 const [ videoInfoTmp, serverTranslations, captionsResponse, config, PeertubePlayerManagerModule ] = await Promise.all([
470 this.translationsPromise,
473 this.PeertubePlayerManagerModulePromise
476 const videoInfo: VideoDetails = videoInfoTmp
478 const PeertubePlayerManager = PeertubePlayerManagerModule.PeertubePlayerManager
479 const videoCaptions = await this.buildCaptions(serverTranslations, captionsResponse)
481 this.loadParams(videoInfo)
483 const playlistPlugin = this.currentPlaylistElement
485 elements: this.playlistElements,
486 playlist: this.playlist,
488 getCurrentPosition: () => this.currentPlaylistElement.position,
490 onItemClicked: (videoPlaylistElement: VideoPlaylistElement) => {
491 this.currentPlaylistElement = videoPlaylistElement
493 this.loadVideoAndBuildPlayer(this.currentPlaylistElement.video.uuid)
494 .catch(err => console.error(err))
499 const options: PeertubePlayerManagerOptions = {
501 // Autoplay in playlist mode
502 autoplay: alreadyHadPlayer ? true : this.autoplay,
503 controls: this.controls,
507 captions: videoCaptions.length !== 0,
508 subtitle: this.subtitle,
510 startTime: this.playlist ? this.currentPlaylistElement.startTimestamp : this.startTime,
511 stopTime: this.playlist ? this.currentPlaylistElement.stopTimestamp : this.stopTime,
513 nextVideo: this.playlist ? () => this.playNextVideo() : undefined,
514 hasNextVideo: this.playlist ? () => !!this.getNextPlaylistElement() : undefined,
516 previousVideo: this.playlist ? () => this.playPreviousVideo() : undefined,
517 hasPreviousVideo: this.playlist ? () => !!this.getPreviousPlaylistElement() : undefined,
519 playlist: playlistPlugin,
522 inactivityTimeout: 2500,
523 videoViewUrl: this.getVideoUrl(videoInfo.uuid) + '/views',
525 playerElement: this.playerElement,
526 onPlayerElementChange: (element: HTMLVideoElement) => this.playerElement = element,
528 videoDuration: videoInfo.duration,
530 peertubeLink: this.peertubeLink,
531 poster: window.location.origin + videoInfo.previewPath,
532 theaterButton: false,
534 serverUrl: window.location.origin,
535 language: navigator.language,
536 embedUrl: window.location.origin + videoInfo.embedPath
540 videoFiles: videoInfo.files
544 if (this.mode === 'p2p-media-loader') {
545 const hlsPlaylist = videoInfo.streamingPlaylists.find(p => p.type === VideoStreamingPlaylistType.HLS)
547 Object.assign(options, {
549 playlistUrl: hlsPlaylist.playlistUrl,
550 segmentsSha256Url: hlsPlaylist.segmentsSha256Url,
551 redundancyBaseUrls: hlsPlaylist.redundancies.map(r => r.baseUrl),
552 trackerAnnounce: videoInfo.trackerUrls,
553 videoFiles: hlsPlaylist.files
554 } as P2PMediaLoaderOptions
558 this.player = await PeertubePlayerManager.initialize(this.mode, options, (player: videojs.Player) => this.player = player)
559 this.player.on('customError', (event: any, data: any) => this.handleError(data.err, serverTranslations))
561 window[ 'videojsPlayer' ] = this.player
565 await this.buildDock(videoInfo, config)
569 this.removePlaceholder()
571 if (this.isPlaylistEmbed()) {
572 await this.buildPlaylistManager()
574 this.player.playlist().updateSelected()
576 this.player.on('stopped', () => {
582 private async initCore () {
583 if (this.userTokens) this.setHeadersFromTokens()
585 this.configPromise = this.loadConfig()
586 this.translationsPromise = TranslationsManager.getServerTranslations(window.location.origin, navigator.language)
587 this.PeertubePlayerManagerModulePromise = import('../../assets/player/peertube-player-manager')
591 if (this.isPlaylistEmbed()) {
592 const playlistId = this.getResourceId()
593 const res = await this.loadPlaylist(playlistId)
594 if (!res) return undefined
596 this.playlist = await res.playlistResponse.json()
598 const playlistElementResult = await res.videosResponse.json()
599 this.playlistElements = await this.loadAllPlaylistVideos(playlistId, playlistElementResult)
601 const params = new URL(window.location.toString()).searchParams
602 const playlistPositionParam = this.getParamString(params, 'playlistPosition')
606 if (playlistPositionParam) {
607 position = parseInt(playlistPositionParam + '', 10)
610 this.currentPlaylistElement = this.playlistElements.find(e => e.position === position)
611 if (!this.currentPlaylistElement || !this.currentPlaylistElement.video) {
612 console.error('Current playlist element is not valid.', this.currentPlaylistElement)
613 this.currentPlaylistElement = this.getNextPlaylistElement()
616 if (!this.currentPlaylistElement) {
617 console.error('This playlist does not have any valid element.')
618 const serverTranslations = await this.translationsPromise
619 this.playlistFetchError(serverTranslations)
623 videoId = this.currentPlaylistElement.video.uuid
625 videoId = this.getResourceId()
628 return this.loadVideoAndBuildPlayer(videoId)
631 private handleError (err: Error, translations?: { [ id: string ]: string }) {
632 if (err.message.indexOf('from xs param') !== -1) {
633 this.player.dispose()
634 this.playerElement = null
635 this.displayError('This video is not available because the remote instance is not responding.', translations)
640 private async buildDock (videoInfo: VideoDetails, config: ServerConfig) {
641 if (!this.controls) return
643 // On webtorrent fallback, player may have been disposed
644 if (!this.player.player_) return
646 const title = this.title ? videoInfo.name : undefined
648 const description = config.tracker.enabled && this.warningTitle
649 ? '<span class="text">' + peertubeTranslate('Watching this video may reveal your IP address to others.') + '</span>'
658 private buildCSS () {
659 const body = document.getElementById('custom-css')
661 if (this.bigPlayBackgroundColor) {
662 body.style.setProperty('--embedBigPlayBackgroundColor', this.bigPlayBackgroundColor)
665 if (this.foregroundColor) {
666 body.style.setProperty('--embedForegroundColor', this.foregroundColor)
670 private async buildCaptions (serverTranslations: any, captionsResponse: Response): Promise<VideoJSCaption[]> {
671 if (captionsResponse.ok) {
672 const { data } = (await captionsResponse.json()) as ResultList<VideoCaption>
674 return data.map(c => ({
675 label: peertubeTranslate(c.language.label, serverTranslations),
676 language: c.language.id,
677 src: window.location.origin + c.captionPath
684 private loadPlaceholder (video: VideoDetails) {
685 const placeholder = this.getPlaceholderElement()
687 const url = window.location.origin + video.previewPath
688 placeholder.style.backgroundImage = `url("${url}")`
689 placeholder.style.display = 'block'
692 private removePlaceholder () {
693 const placeholder = this.getPlaceholderElement()
694 placeholder.style.display = 'none'
697 private getPlaceholderElement () {
698 return document.getElementById('placeholder-preview')
701 private setHeadersFromTokens () {
702 this.headers.set('Authorization', `${this.userTokens.tokenType} ${this.userTokens.accessToken}`)
705 private removeTokensFromHeaders () {
706 this.headers.delete('Authorization')
709 private getResourceId () {
710 const urlParts = window.location.pathname.split('/')
711 return urlParts[ urlParts.length - 1 ]
714 private isPlaylistEmbed () {
715 return window.location.pathname.split('/')[1] === 'video-playlists'
720 .catch(err => console.error('Cannot init embed.', err))