8 } from '../../../../shared'
9 import { VideoCaption } from '../../../../shared/models/videos/caption/video-caption.model'
11 P2PMediaLoaderOptions,
12 PeertubePlayerManagerOptions,
14 } from '../../assets/player/peertube-player-manager'
15 import { VideoStreamingPlaylistType } from '../../../../shared/models/videos/video-streaming-playlist.type'
16 import { PeerTubeEmbedApi } from './embed-api'
17 import { TranslationsManager } from '../../assets/player/translations-manager'
18 import videojs from 'video.js'
19 import { VideoJSCaption } from '../../assets/player/peertube-videojs-typings'
21 type Translations = { [ id: string ]: string }
23 export class PeerTubeEmbed {
24 videoElement: HTMLVideoElement
25 player: videojs.Player
26 api: PeerTubeEmbedApi = null
33 startTime: number | string = 0
34 stopTime: number | string
38 bigPlayBackgroundColor: string
39 foregroundColor: string
44 static async main () {
45 const videoContainerId = 'video-container'
46 const embed = new PeerTubeEmbed(videoContainerId)
50 constructor (private videoContainerId: string) {
51 this.videoElement = document.getElementById(videoContainerId) as HTMLVideoElement
54 getVideoUrl (id: string) {
55 return window.location.origin + '/api/v1/videos/' + id
58 loadVideoInfo (videoId: string): Promise<Response> {
59 return fetch(this.getVideoUrl(videoId))
62 loadVideoCaptions (videoId: string): Promise<Response> {
63 return fetch(this.getVideoUrl(videoId) + '/captions')
66 loadConfig (): Promise<Response> {
67 return fetch('/api/v1/config')
70 removeElement (element: HTMLElement) {
71 element.parentElement.removeChild(element)
74 displayError (text: string, translations?: Translations) {
75 // Remove video element
76 if (this.videoElement) this.removeElement(this.videoElement)
78 const translatedText = peertubeTranslate(text, translations)
79 const translatedSorry = peertubeTranslate('Sorry', translations)
81 document.title = translatedSorry + ' - ' + translatedText
83 const errorBlock = document.getElementById('error-block')
84 errorBlock.style.display = 'flex'
86 const errorTitle = document.getElementById('error-title')
87 errorTitle.innerHTML = peertubeTranslate('Sorry', translations)
89 const errorText = document.getElementById('error-content')
90 errorText.innerHTML = translatedText
93 videoNotFound (translations?: Translations) {
94 const text = 'This video does not exist.'
95 this.displayError(text, translations)
98 videoFetchError (translations?: Translations) {
99 const text = 'We cannot fetch the video. Please try again later.'
100 this.displayError(text, translations)
103 getParamToggle (params: URLSearchParams, name: string, defaultValue?: boolean) {
104 return params.has(name) ? (params.get(name) === '1' || params.get(name) === 'true') : defaultValue
107 getParamString (params: URLSearchParams, name: string, defaultValue?: string) {
108 return params.has(name) ? params.get(name) : defaultValue
113 await this.initCore()
119 private initializeApi () {
120 if (!this.enableApi) return
122 this.api = new PeerTubeEmbedApi(this)
123 this.api.initialize()
126 private loadParams (video: VideoDetails) {
128 const params = new URL(window.location.toString()).searchParams
130 this.autoplay = this.getParamToggle(params, 'autoplay', false)
131 this.controls = this.getParamToggle(params, 'controls', true)
132 this.muted = this.getParamToggle(params, 'muted', undefined)
133 this.loop = this.getParamToggle(params, 'loop', false)
134 this.title = this.getParamToggle(params, 'title', true)
135 this.enableApi = this.getParamToggle(params, 'api', this.enableApi)
136 this.warningTitle = this.getParamToggle(params, 'warningTitle', true)
138 this.scope = this.getParamString(params, 'scope', this.scope)
139 this.subtitle = this.getParamString(params, 'subtitle')
140 this.startTime = this.getParamString(params, 'start')
141 this.stopTime = this.getParamString(params, 'stop')
143 this.bigPlayBackgroundColor = this.getParamString(params, 'bigPlayBackgroundColor')
144 this.foregroundColor = this.getParamString(params, 'foregroundColor')
146 const modeParam = this.getParamString(params, 'mode')
149 if (modeParam === 'p2p-media-loader') this.mode = 'p2p-media-loader'
150 else this.mode = 'webtorrent'
152 if (Array.isArray(video.streamingPlaylists) && video.streamingPlaylists.length !== 0) this.mode = 'p2p-media-loader'
153 else this.mode = 'webtorrent'
156 console.error('Cannot get params from URL.', err)
160 private async initCore () {
161 const urlParts = window.location.pathname.split('/')
162 const videoId = urlParts[ urlParts.length - 1 ]
164 const videoPromise = this.loadVideoInfo(videoId)
165 const captionsPromise = this.loadVideoCaptions(videoId)
166 const configPromise = this.loadConfig()
168 const translationsPromise = TranslationsManager.getServerTranslations(window.location.origin, navigator.language)
169 const videoResponse = await videoPromise
171 if (!videoResponse.ok) {
172 const serverTranslations = await translationsPromise
174 if (videoResponse.status === 404) return this.videoNotFound(serverTranslations)
176 return this.videoFetchError(serverTranslations)
179 const videoInfo: VideoDetails = await videoResponse.json()
180 this.loadPlaceholder(videoInfo)
182 const PeertubePlayerManagerModulePromise = import('../../assets/player/peertube-player-manager')
184 const promises = [ translationsPromise, captionsPromise, configPromise, PeertubePlayerManagerModulePromise ]
185 const [ serverTranslations, captionsResponse, configResponse, PeertubePlayerManagerModule ] = await Promise.all(promises)
187 const PeertubePlayerManager = PeertubePlayerManagerModule.PeertubePlayerManager
188 const videoCaptions = await this.buildCaptions(serverTranslations, captionsResponse)
190 this.loadParams(videoInfo)
192 const options: PeertubePlayerManagerOptions = {
194 autoplay: this.autoplay,
195 controls: this.controls,
198 captions: videoCaptions.length !== 0,
199 startTime: this.startTime,
200 stopTime: this.stopTime,
201 subtitle: this.subtitle,
204 inactivityTimeout: 1500,
205 videoViewUrl: this.getVideoUrl(videoId) + '/views',
207 playerElement: this.videoElement,
208 onPlayerElementChange: (element: HTMLVideoElement) => this.videoElement = element,
210 videoDuration: videoInfo.duration,
213 poster: window.location.origin + videoInfo.previewPath,
214 theaterButton: false,
216 serverUrl: window.location.origin,
217 language: navigator.language,
218 embedUrl: window.location.origin + videoInfo.embedPath
222 videoFiles: videoInfo.files
226 if (this.mode === 'p2p-media-loader') {
227 const hlsPlaylist = videoInfo.streamingPlaylists.find(p => p.type === VideoStreamingPlaylistType.HLS)
229 Object.assign(options, {
231 playlistUrl: hlsPlaylist.playlistUrl,
232 segmentsSha256Url: hlsPlaylist.segmentsSha256Url,
233 redundancyBaseUrls: hlsPlaylist.redundancies.map(r => r.baseUrl),
234 trackerAnnounce: videoInfo.trackerUrls,
235 videoFiles: hlsPlaylist.files
236 } as P2PMediaLoaderOptions
240 this.player = await PeertubePlayerManager.initialize(this.mode, options, (player: videojs.Player) => this.player = player)
241 this.player.on('customError', (event: any, data: any) => this.handleError(data.err, serverTranslations))
243 window[ 'videojsPlayer' ] = this.player
247 await this.buildDock(videoInfo, configResponse)
251 this.removePlaceholder()
254 private handleError (err: Error, translations?: { [ id: string ]: string }) {
255 if (err.message.indexOf('from xs param') !== -1) {
256 this.player.dispose()
257 this.videoElement = null
258 this.displayError('This video is not available because the remote instance is not responding.', translations)
263 private async buildDock (videoInfo: VideoDetails, configResponse: Response) {
264 if (!this.controls) return
266 // On webtorrent fallback, player may have been disposed
267 if (!this.player.player_) return
269 const title = this.title ? videoInfo.name : undefined
271 const config: ServerConfig = await configResponse.json()
272 const description = config.tracker.enabled && this.warningTitle
273 ? '<span class="text">' + peertubeTranslate('Watching this video may reveal your IP address to others.') + '</span>'
282 private buildCSS () {
283 const body = document.getElementById('custom-css')
285 if (this.bigPlayBackgroundColor) {
286 body.style.setProperty('--embedBigPlayBackgroundColor', this.bigPlayBackgroundColor)
289 if (this.foregroundColor) {
290 body.style.setProperty('--embedForegroundColor', this.foregroundColor)
294 private async buildCaptions (serverTranslations: any, captionsResponse: Response): Promise<VideoJSCaption[]> {
295 if (captionsResponse.ok) {
296 const { data } = (await captionsResponse.json()) as ResultList<VideoCaption>
298 return data.map(c => ({
299 label: peertubeTranslate(c.language.label, serverTranslations),
300 language: c.language.id,
301 src: window.location.origin + c.captionPath
308 private loadPlaceholder (video: VideoDetails) {
309 const placeholder = this.getPlaceholderElement()
311 const url = window.location.origin + video.previewPath
312 placeholder.style.backgroundImage = `url("${url}")`
315 private removePlaceholder () {
316 const placeholder = this.getPlaceholderElement()
317 placeholder.parentElement.removeChild(placeholder)
320 private getPlaceholderElement () {
321 return document.getElementById('placeholder-preview')
326 .catch(err => console.error('Cannot init embed.', err))