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): Promise<Response> {
147 return fetch(this.getPlaylistUrl(playlistId) + '/videos')
150 loadConfig (): Promise<ServerConfig> {
151 return fetch('/api/v1/config')
152 .then(res => res.json())
155 removeElement (element: HTMLElement) {
156 element.parentElement.removeChild(element)
159 displayError (text: string, translations?: Translations) {
160 // Remove video element
161 if (this.playerElement) {
162 this.removeElement(this.playerElement)
163 this.playerElement = undefined
166 const translatedText = peertubeTranslate(text, translations)
167 const translatedSorry = peertubeTranslate('Sorry', translations)
169 document.title = translatedSorry + ' - ' + translatedText
171 const errorBlock = document.getElementById('error-block')
172 errorBlock.style.display = 'flex'
174 const errorTitle = document.getElementById('error-title')
175 errorTitle.innerHTML = peertubeTranslate('Sorry', translations)
177 const errorText = document.getElementById('error-content')
178 errorText.innerHTML = translatedText
181 videoNotFound (translations?: Translations) {
182 const text = 'This video does not exist.'
183 this.displayError(text, translations)
186 videoFetchError (translations?: Translations) {
187 const text = 'We cannot fetch the video. Please try again later.'
188 this.displayError(text, translations)
191 playlistNotFound (translations?: Translations) {
192 const text = 'This playlist does not exist.'
193 this.displayError(text, translations)
196 playlistFetchError (translations?: Translations) {
197 const text = 'We cannot fetch the playlist. Please try again later.'
198 this.displayError(text, translations)
201 getParamToggle (params: URLSearchParams, name: string, defaultValue?: boolean) {
202 return params.has(name) ? (params.get(name) === '1' || params.get(name) === 'true') : defaultValue
205 getParamString (params: URLSearchParams, name: string, defaultValue?: string) {
206 return params.has(name) ? params.get(name) : defaultValue
211 this.userTokens = Tokens.load()
212 await this.initCore()
218 private initializeApi () {
219 if (!this.enableApi) return
221 this.api = new PeerTubeEmbedApi(this)
222 this.api.initialize()
225 private loadParams (video: VideoDetails) {
227 const params = new URL(window.location.toString()).searchParams
229 this.autoplay = this.getParamToggle(params, 'autoplay', false)
230 this.controls = this.getParamToggle(params, 'controls', true)
231 this.muted = this.getParamToggle(params, 'muted', undefined)
232 this.loop = this.getParamToggle(params, 'loop', false)
233 this.title = this.getParamToggle(params, 'title', true)
234 this.enableApi = this.getParamToggle(params, 'api', this.enableApi)
235 this.warningTitle = this.getParamToggle(params, 'warningTitle', true)
236 this.peertubeLink = this.getParamToggle(params, 'peertubeLink', true)
238 this.scope = this.getParamString(params, 'scope', this.scope)
239 this.subtitle = this.getParamString(params, 'subtitle')
240 this.startTime = this.getParamString(params, 'start')
241 this.stopTime = this.getParamString(params, 'stop')
243 this.bigPlayBackgroundColor = this.getParamString(params, 'bigPlayBackgroundColor')
244 this.foregroundColor = this.getParamString(params, 'foregroundColor')
246 const modeParam = this.getParamString(params, 'mode')
249 if (modeParam === 'p2p-media-loader') this.mode = 'p2p-media-loader'
250 else this.mode = 'webtorrent'
252 if (Array.isArray(video.streamingPlaylists) && video.streamingPlaylists.length !== 0) this.mode = 'p2p-media-loader'
253 else this.mode = 'webtorrent'
256 console.error('Cannot get params from URL.', err)
260 private async loadPlaylist (playlistId: string) {
261 const playlistPromise = this.loadPlaylistInfo(playlistId)
262 const playlistElementsPromise = this.loadPlaylistElements(playlistId)
264 const playlistResponse = await playlistPromise
266 if (!playlistResponse.ok) {
267 const serverTranslations = await this.translationsPromise
269 if (playlistResponse.status === 404) {
270 this.playlistNotFound(serverTranslations)
274 this.playlistFetchError(serverTranslations)
278 return { playlistResponse, videosResponse: await playlistElementsPromise }
281 private async loadVideo (videoId: string) {
282 const videoPromise = this.loadVideoInfo(videoId)
284 const videoResponse = await videoPromise
286 if (!videoResponse.ok) {
287 const serverTranslations = await this.translationsPromise
289 if (videoResponse.status === 404) {
290 this.videoNotFound(serverTranslations)
294 this.videoFetchError(serverTranslations)
298 const captionsPromise = this.loadVideoCaptions(videoId)
300 return { captionsPromise, videoResponse }
303 private async buildPlaylistManager () {
304 const translations = await this.translationsPromise
307 timeout: 10000, // 10s
308 headText: peertubeTranslate('Up Next', translations),
309 cancelText: peertubeTranslate('Cancel', translations),
310 suspendedText: peertubeTranslate('Autoplay is suspended', translations),
311 getTitle: () => this.nextVideoTitle(),
312 next: () => this.autoplayNext(),
313 condition: () => !!this.getNextPlaylistElement(),
314 suspended: () => false
318 private async autoplayNext () {
319 const next = this.getNextPlaylistElement()
321 console.log('Next element not found in playlist.')
325 this.currentPlaylistElement = next
327 const res = await this.loadVideo(this.currentPlaylistElement.video.uuid)
328 if (res === undefined) return
330 return this.buildVideoPlayer(res.videoResponse, res.captionsPromise)
333 private nextVideoTitle () {
334 const next = this.getNextPlaylistElement()
337 return next.video.name
340 private getNextPlaylistElement (position?: number): VideoPlaylistElement {
341 if (!position) position = this.currentPlaylistElement.position + 1
343 if (position > this.playlist.videosLength) {
347 const next = this.playlistElements.find(e => e.position === position)
349 if (!next || !next.video) {
350 return this.getNextPlaylistElement(position + 1)
356 private async buildVideoPlayer (videoResponse: Response, captionsPromise: Promise<Response>) {
357 let alreadyHadPlayer = false
360 this.player.dispose()
361 alreadyHadPlayer = true
364 this.playerElement = document.createElement('video')
365 this.playerElement.className = 'video-js vjs-peertube-skin'
366 this.playerElement.setAttribute('playsinline', 'true')
367 this.wrapperElement.appendChild(this.playerElement)
369 const videoInfoPromise = videoResponse.json()
370 .then((videoInfo: VideoDetails) => {
371 if (!alreadyHadPlayer) this.loadPlaceholder(videoInfo)
376 const [ videoInfo, serverTranslations, captionsResponse, config, PeertubePlayerManagerModule ] = await Promise.all([
378 this.translationsPromise,
381 this.PeertubePlayerManagerModulePromise
384 const PeertubePlayerManager = PeertubePlayerManagerModule.PeertubePlayerManager
385 const videoCaptions = await this.buildCaptions(serverTranslations, captionsResponse)
387 this.loadParams(videoInfo)
389 const options: PeertubePlayerManagerOptions = {
391 // Autoplay in playlist mode
392 autoplay: alreadyHadPlayer ? true : this.autoplay,
393 controls: this.controls,
396 captions: videoCaptions.length !== 0,
397 startTime: this.startTime,
398 stopTime: this.stopTime,
399 subtitle: this.subtitle,
401 nextVideo: () => this.autoplayNext(),
404 inactivityTimeout: 2500,
405 videoViewUrl: this.getVideoUrl(videoInfo.uuid) + '/views',
407 playerElement: this.playerElement,
408 onPlayerElementChange: (element: HTMLVideoElement) => this.playerElement = element,
410 videoDuration: videoInfo.duration,
412 peertubeLink: this.peertubeLink,
413 poster: window.location.origin + videoInfo.previewPath,
414 theaterButton: false,
416 serverUrl: window.location.origin,
417 language: navigator.language,
418 embedUrl: window.location.origin + videoInfo.embedPath
422 videoFiles: videoInfo.files
426 if (this.mode === 'p2p-media-loader') {
427 const hlsPlaylist = videoInfo.streamingPlaylists.find(p => p.type === VideoStreamingPlaylistType.HLS)
429 Object.assign(options, {
431 playlistUrl: hlsPlaylist.playlistUrl,
432 segmentsSha256Url: hlsPlaylist.segmentsSha256Url,
433 redundancyBaseUrls: hlsPlaylist.redundancies.map(r => r.baseUrl),
434 trackerAnnounce: videoInfo.trackerUrls,
435 videoFiles: hlsPlaylist.files
436 } as P2PMediaLoaderOptions
440 this.player = await PeertubePlayerManager.initialize(this.mode, options, (player: videojs.Player) => this.player = player)
441 this.player.on('customError', (event: any, data: any) => this.handleError(data.err, serverTranslations))
443 window[ 'videojsPlayer' ] = this.player
447 await this.buildDock(videoInfo, config)
451 this.removePlaceholder()
453 if (this.isPlaylistEmbed()) {
454 await this.buildPlaylistManager()
458 private async initCore () {
459 if (this.userTokens) this.setHeadersFromTokens()
461 this.configPromise = this.loadConfig()
462 this.translationsPromise = TranslationsManager.getServerTranslations(window.location.origin, navigator.language)
463 this.PeertubePlayerManagerModulePromise = import('../../assets/player/peertube-player-manager')
467 if (this.isPlaylistEmbed()) {
468 const playlistId = this.getResourceId()
469 const res = await this.loadPlaylist(playlistId)
470 if (!res) return undefined
472 this.playlist = await res.playlistResponse.json()
474 const playlistElementResult = await res.videosResponse.json()
475 this.playlistElements = playlistElementResult.data
477 this.currentPlaylistElement = this.playlistElements[0]
478 videoId = this.currentPlaylistElement.video.uuid
480 videoId = this.getResourceId()
483 const res = await this.loadVideo(videoId)
484 if (res === undefined) return
486 return this.buildVideoPlayer(res.videoResponse, res.captionsPromise)
489 private handleError (err: Error, translations?: { [ id: string ]: string }) {
490 if (err.message.indexOf('from xs param') !== -1) {
491 this.player.dispose()
492 this.playerElement = null
493 this.displayError('This video is not available because the remote instance is not responding.', translations)
498 private async buildDock (videoInfo: VideoDetails, config: ServerConfig) {
499 if (!this.controls) return
501 // On webtorrent fallback, player may have been disposed
502 if (!this.player.player_) return
504 const title = this.title ? videoInfo.name : undefined
506 const description = config.tracker.enabled && this.warningTitle
507 ? '<span class="text">' + peertubeTranslate('Watching this video may reveal your IP address to others.') + '</span>'
516 private buildCSS () {
517 const body = document.getElementById('custom-css')
519 if (this.bigPlayBackgroundColor) {
520 body.style.setProperty('--embedBigPlayBackgroundColor', this.bigPlayBackgroundColor)
523 if (this.foregroundColor) {
524 body.style.setProperty('--embedForegroundColor', this.foregroundColor)
528 private async buildCaptions (serverTranslations: any, captionsResponse: Response): Promise<VideoJSCaption[]> {
529 if (captionsResponse.ok) {
530 const { data } = (await captionsResponse.json()) as ResultList<VideoCaption>
532 return data.map(c => ({
533 label: peertubeTranslate(c.language.label, serverTranslations),
534 language: c.language.id,
535 src: window.location.origin + c.captionPath
542 private loadPlaceholder (video: VideoDetails) {
543 const placeholder = this.getPlaceholderElement()
545 const url = window.location.origin + video.previewPath
546 placeholder.style.backgroundImage = `url("${url}")`
547 placeholder.style.display = 'block'
550 private removePlaceholder () {
551 const placeholder = this.getPlaceholderElement()
552 placeholder.style.display = 'none'
555 private getPlaceholderElement () {
556 return document.getElementById('placeholder-preview')
559 private setHeadersFromTokens () {
560 this.headers.set('Authorization', `${this.userTokens.tokenType} ${this.userTokens.accessToken}`)
563 private getResourceId () {
564 const urlParts = window.location.pathname.split('/')
565 return urlParts[ urlParts.length - 1 ]
568 private isPlaylistEmbed () {
569 return window.location.pathname.split('/')[1] === 'video-playlists'
574 .catch(err => console.error('Cannot init embed.', err))