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'
12 VideoStreamingPlaylistType
13 } from '../../../../shared/models'
14 import { P2PMediaLoaderOptions, PeertubePlayerManagerOptions, PlayerMode } from '../../assets/player/peertube-player-manager'
15 import { VideoJSCaption } from '../../assets/player/peertube-videojs-typings'
16 import { TranslationsManager } from '../../assets/player/translations-manager'
17 import { PeerTubeEmbedApi } from './embed-api'
19 type Translations = { [ id: string ]: string }
21 export class PeerTubeEmbed {
22 videoElement: HTMLVideoElement
23 player: videojs.Player
24 api: PeerTubeEmbedApi = null
31 startTime: number | string = 0
32 stopTime: number | string
37 bigPlayBackgroundColor: string
38 foregroundColor: string
44 headers = new Headers()
45 LOCAL_STORAGE_OAUTH_CLIENT_KEYS = {
46 CLIENT_ID: 'client_id',
47 CLIENT_SECRET: 'client_secret'
50 static async main () {
51 const videoContainerId = 'video-container'
52 const embed = new PeerTubeEmbed(videoContainerId)
56 constructor (private videoContainerId: string) {
57 this.videoElement = document.getElementById(videoContainerId) as HTMLVideoElement
60 getVideoUrl (id: string) {
61 return window.location.origin + '/api/v1/videos/' + id
64 refreshFetch (url: string, options?: Object) {
65 return fetch(url, options)
66 .then((res: Response) => {
67 if (res.status !== 401) return res
69 // 401 unauthorized is not catch-ed, but then-ed
72 const refreshingTokenPromise = new Promise((resolve, reject) => {
73 const clientId: string = peertubeLocalStorage.getItem(this.LOCAL_STORAGE_OAUTH_CLIENT_KEYS.CLIENT_ID)
74 const clientSecret: string = peertubeLocalStorage.getItem(this.LOCAL_STORAGE_OAUTH_CLIENT_KEYS.CLIENT_SECRET)
75 const headers = new Headers()
76 headers.set('Content-Type', 'application/x-www-form-urlencoded')
78 refresh_token: this.userTokens.refreshToken,
80 client_secret: clientSecret,
81 response_type: 'code',
82 grant_type: 'refresh_token'
85 fetch('/api/v1/users/token', {
88 body: objectToUrlEncoded(data)
90 .then(res => res.json())
91 .then((obj: UserRefreshToken) => {
92 this.userTokens.accessToken = obj.access_token
93 this.userTokens.refreshToken = obj.refresh_token
94 this.userTokens.save()
96 this.setHeadersFromTokens()
100 .catch((refreshTokenError: any) => {
101 reject(refreshTokenError)
105 return refreshingTokenPromise
107 // If refreshing fails, continue with original error
110 .then(() => fetch(url, {
112 headers: this.headers
117 loadVideoInfo (videoId: string): Promise<Response> {
118 return this.refreshFetch(this.getVideoUrl(videoId), { headers: this.headers })
121 loadVideoCaptions (videoId: string): Promise<Response> {
122 return fetch(this.getVideoUrl(videoId) + '/captions')
125 loadConfig (): Promise<Response> {
126 return fetch('/api/v1/config')
129 removeElement (element: HTMLElement) {
130 element.parentElement.removeChild(element)
133 displayError (text: string, translations?: Translations) {
134 // Remove video element
135 if (this.videoElement) this.removeElement(this.videoElement)
137 const translatedText = peertubeTranslate(text, translations)
138 const translatedSorry = peertubeTranslate('Sorry', translations)
140 document.title = translatedSorry + ' - ' + translatedText
142 const errorBlock = document.getElementById('error-block')
143 errorBlock.style.display = 'flex'
145 const errorTitle = document.getElementById('error-title')
146 errorTitle.innerHTML = peertubeTranslate('Sorry', translations)
148 const errorText = document.getElementById('error-content')
149 errorText.innerHTML = translatedText
152 videoNotFound (translations?: Translations) {
153 const text = 'This video does not exist.'
154 this.displayError(text, translations)
157 videoFetchError (translations?: Translations) {
158 const text = 'We cannot fetch the video. Please try again later.'
159 this.displayError(text, translations)
162 getParamToggle (params: URLSearchParams, name: string, defaultValue?: boolean) {
163 return params.has(name) ? (params.get(name) === '1' || params.get(name) === 'true') : defaultValue
166 getParamString (params: URLSearchParams, name: string, defaultValue?: string) {
167 return params.has(name) ? params.get(name) : defaultValue
172 this.userTokens = Tokens.load()
173 await this.initCore()
179 private initializeApi () {
180 if (!this.enableApi) return
182 this.api = new PeerTubeEmbedApi(this)
183 this.api.initialize()
186 private loadParams (video: VideoDetails) {
188 const params = new URL(window.location.toString()).searchParams
190 this.autoplay = this.getParamToggle(params, 'autoplay', false)
191 this.controls = this.getParamToggle(params, 'controls', true)
192 this.muted = this.getParamToggle(params, 'muted', undefined)
193 this.loop = this.getParamToggle(params, 'loop', false)
194 this.title = this.getParamToggle(params, 'title', true)
195 this.enableApi = this.getParamToggle(params, 'api', this.enableApi)
196 this.warningTitle = this.getParamToggle(params, 'warningTitle', true)
197 this.peertubeLink = this.getParamToggle(params, 'peertubeLink', true)
199 this.scope = this.getParamString(params, 'scope', this.scope)
200 this.subtitle = this.getParamString(params, 'subtitle')
201 this.startTime = this.getParamString(params, 'start')
202 this.stopTime = this.getParamString(params, 'stop')
204 this.bigPlayBackgroundColor = this.getParamString(params, 'bigPlayBackgroundColor')
205 this.foregroundColor = this.getParamString(params, 'foregroundColor')
207 const modeParam = this.getParamString(params, 'mode')
210 if (modeParam === 'p2p-media-loader') this.mode = 'p2p-media-loader'
211 else this.mode = 'webtorrent'
213 if (Array.isArray(video.streamingPlaylists) && video.streamingPlaylists.length !== 0) this.mode = 'p2p-media-loader'
214 else this.mode = 'webtorrent'
217 console.error('Cannot get params from URL.', err)
221 private async initCore () {
222 const urlParts = window.location.pathname.split('/')
223 const videoId = urlParts[ urlParts.length - 1 ]
225 if (this.userTokens) this.setHeadersFromTokens()
227 const videoPromise = this.loadVideoInfo(videoId)
228 const captionsPromise = this.loadVideoCaptions(videoId)
229 const configPromise = this.loadConfig()
231 const translationsPromise = TranslationsManager.getServerTranslations(window.location.origin, navigator.language)
232 const videoResponse = await videoPromise
234 if (!videoResponse.ok) {
235 const serverTranslations = await translationsPromise
237 if (videoResponse.status === 404) return this.videoNotFound(serverTranslations)
239 return this.videoFetchError(serverTranslations)
242 const videoInfo: VideoDetails = await videoResponse.json()
243 this.loadPlaceholder(videoInfo)
245 const PeertubePlayerManagerModulePromise = import('../../assets/player/peertube-player-manager')
247 const promises = [ translationsPromise, captionsPromise, configPromise, PeertubePlayerManagerModulePromise ]
248 const [ serverTranslations, captionsResponse, configResponse, PeertubePlayerManagerModule ] = await Promise.all(promises)
250 const PeertubePlayerManager = PeertubePlayerManagerModule.PeertubePlayerManager
251 const videoCaptions = await this.buildCaptions(serverTranslations, captionsResponse)
253 this.loadParams(videoInfo)
255 const options: PeertubePlayerManagerOptions = {
257 autoplay: this.autoplay,
258 controls: this.controls,
261 captions: videoCaptions.length !== 0,
262 startTime: this.startTime,
263 stopTime: this.stopTime,
264 subtitle: this.subtitle,
267 inactivityTimeout: 2500,
268 videoViewUrl: this.getVideoUrl(videoId) + '/views',
270 playerElement: this.videoElement,
271 onPlayerElementChange: (element: HTMLVideoElement) => this.videoElement = element,
273 videoDuration: videoInfo.duration,
275 peertubeLink: this.peertubeLink,
276 poster: window.location.origin + videoInfo.previewPath,
277 theaterButton: false,
279 serverUrl: window.location.origin,
280 language: navigator.language,
281 embedUrl: window.location.origin + videoInfo.embedPath
285 videoFiles: videoInfo.files
289 if (this.mode === 'p2p-media-loader') {
290 const hlsPlaylist = videoInfo.streamingPlaylists.find(p => p.type === VideoStreamingPlaylistType.HLS)
292 Object.assign(options, {
294 playlistUrl: hlsPlaylist.playlistUrl,
295 segmentsSha256Url: hlsPlaylist.segmentsSha256Url,
296 redundancyBaseUrls: hlsPlaylist.redundancies.map(r => r.baseUrl),
297 trackerAnnounce: videoInfo.trackerUrls,
298 videoFiles: hlsPlaylist.files
299 } as P2PMediaLoaderOptions
303 this.player = await PeertubePlayerManager.initialize(this.mode, options, (player: videojs.Player) => this.player = player)
304 this.player.on('customError', (event: any, data: any) => this.handleError(data.err, serverTranslations))
306 window[ 'videojsPlayer' ] = this.player
310 await this.buildDock(videoInfo, configResponse)
314 this.removePlaceholder()
317 private handleError (err: Error, translations?: { [ id: string ]: string }) {
318 if (err.message.indexOf('from xs param') !== -1) {
319 this.player.dispose()
320 this.videoElement = null
321 this.displayError('This video is not available because the remote instance is not responding.', translations)
326 private async buildDock (videoInfo: VideoDetails, configResponse: Response) {
327 if (!this.controls) return
329 // On webtorrent fallback, player may have been disposed
330 if (!this.player.player_) return
332 const title = this.title ? videoInfo.name : undefined
334 const config: ServerConfig = await configResponse.json()
335 const description = config.tracker.enabled && this.warningTitle
336 ? '<span class="text">' + peertubeTranslate('Watching this video may reveal your IP address to others.') + '</span>'
345 private buildCSS () {
346 const body = document.getElementById('custom-css')
348 if (this.bigPlayBackgroundColor) {
349 body.style.setProperty('--embedBigPlayBackgroundColor', this.bigPlayBackgroundColor)
352 if (this.foregroundColor) {
353 body.style.setProperty('--embedForegroundColor', this.foregroundColor)
357 private async buildCaptions (serverTranslations: any, captionsResponse: Response): Promise<VideoJSCaption[]> {
358 if (captionsResponse.ok) {
359 const { data } = (await captionsResponse.json()) as ResultList<VideoCaption>
361 return data.map(c => ({
362 label: peertubeTranslate(c.language.label, serverTranslations),
363 language: c.language.id,
364 src: window.location.origin + c.captionPath
371 private loadPlaceholder (video: VideoDetails) {
372 const placeholder = this.getPlaceholderElement()
374 const url = window.location.origin + video.previewPath
375 placeholder.style.backgroundImage = `url("${url}")`
378 private removePlaceholder () {
379 const placeholder = this.getPlaceholderElement()
380 placeholder.parentElement.removeChild(placeholder)
383 private getPlaceholderElement () {
384 return document.getElementById('placeholder-preview')
387 private setHeadersFromTokens () {
388 this.headers.set('Authorization', `${this.userTokens.tokenType} ${this.userTokens.accessToken}`)
393 .catch(err => console.error('Cannot init embed.', err))