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.playNextVideo(),
313 condition: () => !!this.getNextPlaylistElement(),
314 suspended: () => false
318 private async playNextVideo () {
319 const next = this.getNextPlaylistElement()
321 console.log('Next element not found in playlist.')
325 this.currentPlaylistElement = next
327 return this.loadVideoAndBuildPlayer(this.currentPlaylistElement.video.uuid)
330 private async playPreviousVideo () {
331 const previous = this.getPreviousPlaylistElement()
333 console.log('Previous element not found in playlist.')
337 this.currentPlaylistElement = previous
339 return this.loadVideoAndBuildPlayer(this.currentPlaylistElement.video.uuid)
342 private async loadVideoAndBuildPlayer (uuid: string) {
343 const res = await this.loadVideo(uuid)
344 if (res === undefined) return
346 return this.buildVideoPlayer(res.videoResponse, res.captionsPromise)
349 private nextVideoTitle () {
350 const next = this.getNextPlaylistElement()
353 return next.video.name
356 private getNextPlaylistElement (position?: number): VideoPlaylistElement {
357 if (!position) position = this.currentPlaylistElement.position + 1
359 if (position > this.playlist.videosLength) {
363 const next = this.playlistElements.find(e => e.position === position)
365 if (!next || !next.video) {
366 return this.getNextPlaylistElement(position + 1)
372 private getPreviousPlaylistElement (position?: number): VideoPlaylistElement {
373 if (!position) position = this.currentPlaylistElement.position -1
379 const prev = this.playlistElements.find(e => e.position === position)
381 if (!prev || !prev.video) {
382 return this.getNextPlaylistElement(position - 1)
388 private async buildVideoPlayer (videoResponse: Response, captionsPromise: Promise<Response>) {
389 let alreadyHadPlayer = false
392 this.player.dispose()
393 alreadyHadPlayer = true
396 this.playerElement = document.createElement('video')
397 this.playerElement.className = 'video-js vjs-peertube-skin'
398 this.playerElement.setAttribute('playsinline', 'true')
399 this.wrapperElement.appendChild(this.playerElement)
401 const videoInfoPromise = videoResponse.json()
402 .then((videoInfo: VideoDetails) => {
403 if (!alreadyHadPlayer) this.loadPlaceholder(videoInfo)
408 const [ videoInfo, serverTranslations, captionsResponse, config, PeertubePlayerManagerModule ] = await Promise.all([
410 this.translationsPromise,
413 this.PeertubePlayerManagerModulePromise
416 const PeertubePlayerManager = PeertubePlayerManagerModule.PeertubePlayerManager
417 const videoCaptions = await this.buildCaptions(serverTranslations, captionsResponse)
419 this.loadParams(videoInfo)
421 const playlistPlugin = this.currentPlaylistElement
423 elements: this.playlistElements,
424 playlist: this.playlist,
426 getCurrentPosition: () => this.currentPlaylistElement.position,
428 onItemClicked: (videoPlaylistElement: VideoPlaylistElement) => {
429 this.currentPlaylistElement = videoPlaylistElement
431 this.loadVideoAndBuildPlayer(this.currentPlaylistElement.video.uuid)
432 .catch(err => console.error(err))
437 const options: PeertubePlayerManagerOptions = {
439 // Autoplay in playlist mode
440 autoplay: alreadyHadPlayer ? true : this.autoplay,
441 controls: this.controls,
445 captions: videoCaptions.length !== 0,
446 subtitle: this.subtitle,
448 startTime: this.playlist ? this.currentPlaylistElement.startTimestamp : this.startTime,
449 stopTime: this.playlist ? this.currentPlaylistElement.stopTimestamp : this.stopTime,
451 nextVideo: this.playlist ? () => this.playNextVideo() : undefined,
452 hasNextVideo: this.playlist ? () => !!this.getNextPlaylistElement() : undefined,
454 previousVideo: this.playlist ? () => this.playPreviousVideo() : undefined,
455 hasPreviousVideo: this.playlist ? () => !!this.getPreviousPlaylistElement() : undefined,
457 playlist: playlistPlugin,
460 inactivityTimeout: 2500,
461 videoViewUrl: this.getVideoUrl(videoInfo.uuid) + '/views',
463 playerElement: this.playerElement,
464 onPlayerElementChange: (element: HTMLVideoElement) => this.playerElement = element,
466 videoDuration: videoInfo.duration,
468 peertubeLink: this.peertubeLink,
469 poster: window.location.origin + videoInfo.previewPath,
470 theaterButton: false,
472 serverUrl: window.location.origin,
473 language: navigator.language,
474 embedUrl: window.location.origin + videoInfo.embedPath
478 videoFiles: videoInfo.files
482 if (this.mode === 'p2p-media-loader') {
483 const hlsPlaylist = videoInfo.streamingPlaylists.find(p => p.type === VideoStreamingPlaylistType.HLS)
485 Object.assign(options, {
487 playlistUrl: hlsPlaylist.playlistUrl,
488 segmentsSha256Url: hlsPlaylist.segmentsSha256Url,
489 redundancyBaseUrls: hlsPlaylist.redundancies.map(r => r.baseUrl),
490 trackerAnnounce: videoInfo.trackerUrls,
491 videoFiles: hlsPlaylist.files
492 } as P2PMediaLoaderOptions
496 this.player = await PeertubePlayerManager.initialize(this.mode, options, (player: videojs.Player) => this.player = player)
497 this.player.on('customError', (event: any, data: any) => this.handleError(data.err, serverTranslations))
499 window[ 'videojsPlayer' ] = this.player
503 await this.buildDock(videoInfo, config)
507 this.removePlaceholder()
509 if (this.isPlaylistEmbed()) {
510 await this.buildPlaylistManager()
512 this.player.playlist().updateSelected()
514 this.player.on('stopped', () => {
520 private async initCore () {
521 if (this.userTokens) this.setHeadersFromTokens()
523 this.configPromise = this.loadConfig()
524 this.translationsPromise = TranslationsManager.getServerTranslations(window.location.origin, navigator.language)
525 this.PeertubePlayerManagerModulePromise = import('../../assets/player/peertube-player-manager')
529 if (this.isPlaylistEmbed()) {
530 const playlistId = this.getResourceId()
531 const res = await this.loadPlaylist(playlistId)
532 if (!res) return undefined
534 this.playlist = await res.playlistResponse.json()
536 const playlistElementResult = await res.videosResponse.json()
537 this.playlistElements = playlistElementResult.data
539 this.currentPlaylistElement = this.playlistElements[0]
540 videoId = this.currentPlaylistElement.video.uuid
542 videoId = this.getResourceId()
545 return this.loadVideoAndBuildPlayer(videoId)
548 private handleError (err: Error, translations?: { [ id: string ]: string }) {
549 if (err.message.indexOf('from xs param') !== -1) {
550 this.player.dispose()
551 this.playerElement = null
552 this.displayError('This video is not available because the remote instance is not responding.', translations)
557 private async buildDock (videoInfo: VideoDetails, config: ServerConfig) {
558 if (!this.controls) return
560 // On webtorrent fallback, player may have been disposed
561 if (!this.player.player_) return
563 const title = this.title ? videoInfo.name : undefined
565 const description = config.tracker.enabled && this.warningTitle
566 ? '<span class="text">' + peertubeTranslate('Watching this video may reveal your IP address to others.') + '</span>'
575 private buildCSS () {
576 const body = document.getElementById('custom-css')
578 if (this.bigPlayBackgroundColor) {
579 body.style.setProperty('--embedBigPlayBackgroundColor', this.bigPlayBackgroundColor)
582 if (this.foregroundColor) {
583 body.style.setProperty('--embedForegroundColor', this.foregroundColor)
587 private async buildCaptions (serverTranslations: any, captionsResponse: Response): Promise<VideoJSCaption[]> {
588 if (captionsResponse.ok) {
589 const { data } = (await captionsResponse.json()) as ResultList<VideoCaption>
591 return data.map(c => ({
592 label: peertubeTranslate(c.language.label, serverTranslations),
593 language: c.language.id,
594 src: window.location.origin + c.captionPath
601 private loadPlaceholder (video: VideoDetails) {
602 const placeholder = this.getPlaceholderElement()
604 const url = window.location.origin + video.previewPath
605 placeholder.style.backgroundImage = `url("${url}")`
606 placeholder.style.display = 'block'
609 private removePlaceholder () {
610 const placeholder = this.getPlaceholderElement()
611 placeholder.style.display = 'none'
614 private getPlaceholderElement () {
615 return document.getElementById('placeholder-preview')
618 private setHeadersFromTokens () {
619 this.headers.set('Authorization', `${this.userTokens.tokenType} ${this.userTokens.accessToken}`)
622 private getResourceId () {
623 const urlParts = window.location.pathname.split('/')
624 return urlParts[ urlParts.length - 1 ]
627 private isPlaylistEmbed () {
628 return window.location.pathname.split('/')[1] === 'video-playlists'
633 .catch(err => console.error('Cannot init embed.', err))