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 fetch(this.getVideoUrl(videoId) + '/captions')
142 loadPlaylistInfo (playlistId: string): Promise<Response> {
143 return fetch(this.getPlaylistUrl(playlistId))
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 fetch(url.toString())
153 loadConfig (): Promise<ServerConfig> {
154 return fetch('/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
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
214 this.userTokens = Tokens.load()
215 await this.initCore()
221 private initializeApi () {
222 if (!this.enableApi) return
224 this.api = new PeerTubeEmbedApi(this)
225 this.api.initialize()
228 private loadParams (video: VideoDetails) {
230 const params = new URL(window.location.toString()).searchParams
232 this.autoplay = this.getParamToggle(params, 'autoplay', false)
233 this.controls = this.getParamToggle(params, 'controls', true)
234 this.muted = this.getParamToggle(params, 'muted', undefined)
235 this.loop = this.getParamToggle(params, 'loop', false)
236 this.title = this.getParamToggle(params, 'title', true)
237 this.enableApi = this.getParamToggle(params, 'api', this.enableApi)
238 this.warningTitle = this.getParamToggle(params, 'warningTitle', true)
239 this.peertubeLink = this.getParamToggle(params, 'peertubeLink', true)
241 this.scope = this.getParamString(params, 'scope', this.scope)
242 this.subtitle = this.getParamString(params, 'subtitle')
243 this.startTime = this.getParamString(params, 'start')
244 this.stopTime = this.getParamString(params, 'stop')
246 this.bigPlayBackgroundColor = this.getParamString(params, 'bigPlayBackgroundColor')
247 this.foregroundColor = this.getParamString(params, 'foregroundColor')
249 const modeParam = this.getParamString(params, 'mode')
252 if (modeParam === 'p2p-media-loader') this.mode = 'p2p-media-loader'
253 else this.mode = 'webtorrent'
255 if (Array.isArray(video.streamingPlaylists) && video.streamingPlaylists.length !== 0) this.mode = 'p2p-media-loader'
256 else this.mode = 'webtorrent'
259 console.error('Cannot get params from URL.', err)
263 private async loadAllPlaylistVideos (playlistId: string, baseResult: ResultList<VideoPlaylistElement>) {
264 let elements = baseResult.data
265 let total = baseResult.total
268 while (total > elements.length && i < 10) {
269 const result = await this.loadPlaylistElements(playlistId, elements.length)
271 const json = await result.json() as ResultList<VideoPlaylistElement>
274 elements = elements.concat(json.data)
279 console.error('Cannot fetch all playlists elements, there are too many!')
285 private async loadPlaylist (playlistId: string) {
286 const playlistPromise = this.loadPlaylistInfo(playlistId)
287 const playlistElementsPromise = this.loadPlaylistElements(playlistId)
289 const playlistResponse = await playlistPromise
291 if (!playlistResponse.ok) {
292 const serverTranslations = await this.translationsPromise
294 if (playlistResponse.status === 404) {
295 this.playlistNotFound(serverTranslations)
299 this.playlistFetchError(serverTranslations)
303 return { playlistResponse, videosResponse: await playlistElementsPromise }
306 private async loadVideo (videoId: string) {
307 const videoPromise = this.loadVideoInfo(videoId)
309 const videoResponse = await videoPromise
311 if (!videoResponse.ok) {
312 const serverTranslations = await this.translationsPromise
314 if (videoResponse.status === 404) {
315 this.videoNotFound(serverTranslations)
319 this.videoFetchError(serverTranslations)
323 const captionsPromise = this.loadVideoCaptions(videoId)
325 return { captionsPromise, videoResponse }
328 private async buildPlaylistManager () {
329 const translations = await this.translationsPromise
332 timeout: 10000, // 10s
333 headText: peertubeTranslate('Up Next', translations),
334 cancelText: peertubeTranslate('Cancel', translations),
335 suspendedText: peertubeTranslate('Autoplay is suspended', translations),
336 getTitle: () => this.nextVideoTitle(),
337 next: () => this.playNextVideo(),
338 condition: () => !!this.getNextPlaylistElement(),
339 suspended: () => false
343 private async playNextVideo () {
344 const next = this.getNextPlaylistElement()
346 console.log('Next element not found in playlist.')
350 this.currentPlaylistElement = next
352 return this.loadVideoAndBuildPlayer(this.currentPlaylistElement.video.uuid)
355 private async playPreviousVideo () {
356 const previous = this.getPreviousPlaylistElement()
358 console.log('Previous element not found in playlist.')
362 this.currentPlaylistElement = previous
364 return this.loadVideoAndBuildPlayer(this.currentPlaylistElement.video.uuid)
367 private async loadVideoAndBuildPlayer (uuid: string) {
368 const res = await this.loadVideo(uuid)
369 if (res === undefined) return
371 return this.buildVideoPlayer(res.videoResponse, res.captionsPromise)
374 private nextVideoTitle () {
375 const next = this.getNextPlaylistElement()
378 return next.video.name
381 private getNextPlaylistElement (position?: number): VideoPlaylistElement {
382 if (!position) position = this.currentPlaylistElement.position + 1
384 if (position > this.playlist.videosLength) {
388 const next = this.playlistElements.find(e => e.position === position)
390 if (!next || !next.video) {
391 return this.getNextPlaylistElement(position + 1)
397 private getPreviousPlaylistElement (position?: number): VideoPlaylistElement {
398 if (!position) position = this.currentPlaylistElement.position -1
404 const prev = this.playlistElements.find(e => e.position === position)
406 if (!prev || !prev.video) {
407 return this.getNextPlaylistElement(position - 1)
413 private async buildVideoPlayer (videoResponse: Response, captionsPromise: Promise<Response>) {
414 let alreadyHadPlayer = false
417 this.player.dispose()
418 alreadyHadPlayer = true
421 this.playerElement = document.createElement('video')
422 this.playerElement.className = 'video-js vjs-peertube-skin'
423 this.playerElement.setAttribute('playsinline', 'true')
424 this.wrapperElement.appendChild(this.playerElement)
426 const videoInfoPromise = videoResponse.json()
427 .then((videoInfo: VideoDetails) => {
428 if (!alreadyHadPlayer) this.loadPlaceholder(videoInfo)
433 const [ videoInfo, serverTranslations, captionsResponse, config, PeertubePlayerManagerModule ] = await Promise.all([
435 this.translationsPromise,
438 this.PeertubePlayerManagerModulePromise
441 const PeertubePlayerManager = PeertubePlayerManagerModule.PeertubePlayerManager
442 const videoCaptions = await this.buildCaptions(serverTranslations, captionsResponse)
444 this.loadParams(videoInfo)
446 const playlistPlugin = this.currentPlaylistElement
448 elements: this.playlistElements,
449 playlist: this.playlist,
451 getCurrentPosition: () => this.currentPlaylistElement.position,
453 onItemClicked: (videoPlaylistElement: VideoPlaylistElement) => {
454 this.currentPlaylistElement = videoPlaylistElement
456 this.loadVideoAndBuildPlayer(this.currentPlaylistElement.video.uuid)
457 .catch(err => console.error(err))
462 const options: PeertubePlayerManagerOptions = {
464 // Autoplay in playlist mode
465 autoplay: alreadyHadPlayer ? true : this.autoplay,
466 controls: this.controls,
470 captions: videoCaptions.length !== 0,
471 subtitle: this.subtitle,
473 startTime: this.playlist ? this.currentPlaylistElement.startTimestamp : this.startTime,
474 stopTime: this.playlist ? this.currentPlaylistElement.stopTimestamp : this.stopTime,
476 nextVideo: this.playlist ? () => this.playNextVideo() : undefined,
477 hasNextVideo: this.playlist ? () => !!this.getNextPlaylistElement() : undefined,
479 previousVideo: this.playlist ? () => this.playPreviousVideo() : undefined,
480 hasPreviousVideo: this.playlist ? () => !!this.getPreviousPlaylistElement() : undefined,
482 playlist: playlistPlugin,
485 inactivityTimeout: 2500,
486 videoViewUrl: this.getVideoUrl(videoInfo.uuid) + '/views',
488 playerElement: this.playerElement,
489 onPlayerElementChange: (element: HTMLVideoElement) => this.playerElement = element,
491 videoDuration: videoInfo.duration,
493 peertubeLink: this.peertubeLink,
494 poster: window.location.origin + videoInfo.previewPath,
495 theaterButton: false,
497 serverUrl: window.location.origin,
498 language: navigator.language,
499 embedUrl: window.location.origin + videoInfo.embedPath
503 videoFiles: videoInfo.files
507 if (this.mode === 'p2p-media-loader') {
508 const hlsPlaylist = videoInfo.streamingPlaylists.find(p => p.type === VideoStreamingPlaylistType.HLS)
510 Object.assign(options, {
512 playlistUrl: hlsPlaylist.playlistUrl,
513 segmentsSha256Url: hlsPlaylist.segmentsSha256Url,
514 redundancyBaseUrls: hlsPlaylist.redundancies.map(r => r.baseUrl),
515 trackerAnnounce: videoInfo.trackerUrls,
516 videoFiles: hlsPlaylist.files
517 } as P2PMediaLoaderOptions
521 this.player = await PeertubePlayerManager.initialize(this.mode, options, (player: videojs.Player) => this.player = player)
522 this.player.on('customError', (event: any, data: any) => this.handleError(data.err, serverTranslations))
524 window[ 'videojsPlayer' ] = this.player
528 await this.buildDock(videoInfo, config)
532 this.removePlaceholder()
534 if (this.isPlaylistEmbed()) {
535 await this.buildPlaylistManager()
537 this.player.playlist().updateSelected()
539 this.player.on('stopped', () => {
545 private async initCore () {
546 if (this.userTokens) this.setHeadersFromTokens()
548 this.configPromise = this.loadConfig()
549 this.translationsPromise = TranslationsManager.getServerTranslations(window.location.origin, navigator.language)
550 this.PeertubePlayerManagerModulePromise = import('../../assets/player/peertube-player-manager')
554 if (this.isPlaylistEmbed()) {
555 const playlistId = this.getResourceId()
556 const res = await this.loadPlaylist(playlistId)
557 if (!res) return undefined
559 this.playlist = await res.playlistResponse.json()
561 const playlistElementResult = await res.videosResponse.json()
562 this.playlistElements = await this.loadAllPlaylistVideos(playlistId, playlistElementResult)
564 this.currentPlaylistElement = this.playlistElements[0]
565 videoId = this.currentPlaylistElement.video.uuid
567 videoId = this.getResourceId()
570 return this.loadVideoAndBuildPlayer(videoId)
573 private handleError (err: Error, translations?: { [ id: string ]: string }) {
574 if (err.message.indexOf('from xs param') !== -1) {
575 this.player.dispose()
576 this.playerElement = null
577 this.displayError('This video is not available because the remote instance is not responding.', translations)
582 private async buildDock (videoInfo: VideoDetails, config: ServerConfig) {
583 if (!this.controls) return
585 // On webtorrent fallback, player may have been disposed
586 if (!this.player.player_) return
588 const title = this.title ? videoInfo.name : undefined
590 const description = config.tracker.enabled && this.warningTitle
591 ? '<span class="text">' + peertubeTranslate('Watching this video may reveal your IP address to others.') + '</span>'
600 private buildCSS () {
601 const body = document.getElementById('custom-css')
603 if (this.bigPlayBackgroundColor) {
604 body.style.setProperty('--embedBigPlayBackgroundColor', this.bigPlayBackgroundColor)
607 if (this.foregroundColor) {
608 body.style.setProperty('--embedForegroundColor', this.foregroundColor)
612 private async buildCaptions (serverTranslations: any, captionsResponse: Response): Promise<VideoJSCaption[]> {
613 if (captionsResponse.ok) {
614 const { data } = (await captionsResponse.json()) as ResultList<VideoCaption>
616 return data.map(c => ({
617 label: peertubeTranslate(c.language.label, serverTranslations),
618 language: c.language.id,
619 src: window.location.origin + c.captionPath
626 private loadPlaceholder (video: VideoDetails) {
627 const placeholder = this.getPlaceholderElement()
629 const url = window.location.origin + video.previewPath
630 placeholder.style.backgroundImage = `url("${url}")`
631 placeholder.style.display = 'block'
634 private removePlaceholder () {
635 const placeholder = this.getPlaceholderElement()
636 placeholder.style.display = 'none'
639 private getPlaceholderElement () {
640 return document.getElementById('placeholder-preview')
643 private setHeadersFromTokens () {
644 this.headers.set('Authorization', `${this.userTokens.tokenType} ${this.userTokens.accessToken}`)
647 private getResourceId () {
648 const urlParts = window.location.pathname.split('/')
649 return urlParts[ urlParts.length - 1 ]
652 private isPlaylistEmbed () {
653 return window.location.pathname.split('/')[1] === 'video-playlists'
658 .catch(err => console.error('Cannot init embed.', err))