3 import { peertubeTranslate, ResultList, ServerConfig, VideoDetails } from '../../../../shared'
4 import { VideoJSCaption } from '../../assets/player/peertube-videojs-typings'
5 import { VideoCaption } from '../../../../shared/models/videos/caption/video-caption.model'
9 PeertubePlayerManagerOptions,
11 } from '../../assets/player/peertube-player-manager'
12 import { VideoStreamingPlaylistType } from '../../../../shared/models/videos/video-streaming-playlist.type'
13 import { PeerTubeEmbedApi } from './embed-api'
15 export class PeerTubeEmbed {
16 videoElement: HTMLVideoElement
19 api: PeerTubeEmbedApi = null
26 startTime: number | string = 0
27 stopTime: number | string
31 bigPlayBackgroundColor: string
32 foregroundColor: string
37 static async main () {
38 const videoContainerId = 'video-container'
39 const embed = new PeerTubeEmbed(videoContainerId)
43 constructor (private videoContainerId: string) {
44 this.videoElement = document.getElementById(videoContainerId) as HTMLVideoElement
47 getVideoUrl (id: string) {
48 return window.location.origin + '/api/v1/videos/' + id
51 loadVideoInfo (videoId: string): Promise<Response> {
52 return fetch(this.getVideoUrl(videoId))
55 loadVideoCaptions (videoId: string): Promise<Response> {
56 return fetch(this.getVideoUrl(videoId) + '/captions')
59 loadConfig (): Promise<Response> {
60 return fetch('/api/v1/config')
63 removeElement (element: HTMLElement) {
64 element.parentElement.removeChild(element)
67 displayError (text: string, translations?: { [ id: string ]: string }) {
68 // Remove video element
69 if (this.videoElement) this.removeElement(this.videoElement)
71 const translatedText = peertubeTranslate(text, translations)
72 const translatedSorry = peertubeTranslate('Sorry', translations)
74 document.title = translatedSorry + ' - ' + translatedText
76 const errorBlock = document.getElementById('error-block')
77 errorBlock.style.display = 'flex'
79 const errorTitle = document.getElementById('error-title')
80 errorTitle.innerHTML = peertubeTranslate('Sorry', translations)
82 const errorText = document.getElementById('error-content')
83 errorText.innerHTML = translatedText
86 videoNotFound (translations?: { [ id: string ]: string }) {
87 const text = 'This video does not exist.'
88 this.displayError(text, translations)
91 videoFetchError (translations?: { [ id: string ]: string }) {
92 const text = 'We cannot fetch the video. Please try again later.'
93 this.displayError(text, translations)
96 getParamToggle (params: URLSearchParams, name: string, defaultValue?: boolean) {
97 return params.has(name) ? (params.get(name) === '1' || params.get(name) === 'true') : defaultValue
100 getParamString (params: URLSearchParams, name: string, defaultValue?: string) {
101 return params.has(name) ? params.get(name) : defaultValue
106 await this.initCore()
112 private initializeApi () {
113 if (!this.enableApi) return
115 this.api = new PeerTubeEmbedApi(this)
116 this.api.initialize()
119 private loadParams (video: VideoDetails) {
121 const params = new URL(window.location.toString()).searchParams
123 this.autoplay = this.getParamToggle(params, 'autoplay', false)
124 this.controls = this.getParamToggle(params, 'controls', true)
125 this.muted = this.getParamToggle(params, 'muted', false)
126 this.loop = this.getParamToggle(params, 'loop', false)
127 this.title = this.getParamToggle(params, 'title', true)
128 this.enableApi = this.getParamToggle(params, 'api', this.enableApi)
129 this.warningTitle = this.getParamToggle(params, 'warningTitle', true)
131 this.scope = this.getParamString(params, 'scope', this.scope)
132 this.subtitle = this.getParamString(params, 'subtitle')
133 this.startTime = this.getParamString(params, 'start')
134 this.stopTime = this.getParamString(params, 'stop')
136 this.bigPlayBackgroundColor = this.getParamString(params, 'bigPlayBackgroundColor')
137 this.foregroundColor = this.getParamString(params, 'foregroundColor')
139 const modeParam = this.getParamString(params, 'mode')
142 if (modeParam === 'p2p-media-loader') this.mode = 'p2p-media-loader'
143 else this.mode = 'webtorrent'
145 if (Array.isArray(video.streamingPlaylists) && video.streamingPlaylists.length !== 0) this.mode = 'p2p-media-loader'
146 else this.mode = 'webtorrent'
149 console.error('Cannot get params from URL.', err)
153 private async initCore () {
154 const urlParts = window.location.pathname.split('/')
155 const videoId = urlParts[ urlParts.length - 1 ]
157 const [ serverTranslations, videoResponse, captionsResponse, configResponse ] = await Promise.all([
158 PeertubePlayerManager.getServerTranslations(window.location.origin, navigator.language),
159 this.loadVideoInfo(videoId),
160 this.loadVideoCaptions(videoId),
164 if (!videoResponse.ok) {
165 if (videoResponse.status === 404) return this.videoNotFound(serverTranslations)
167 return this.videoFetchError(serverTranslations)
170 const videoInfo: VideoDetails = await videoResponse.json()
171 const videoCaptions = await this.buildCaptions(serverTranslations, captionsResponse)
173 this.loadParams(videoInfo)
175 const options: PeertubePlayerManagerOptions = {
177 autoplay: this.autoplay,
178 controls: this.controls,
181 captions: videoCaptions.length !== 0,
182 startTime: this.startTime,
183 stopTime: this.stopTime,
184 subtitle: this.subtitle,
187 inactivityTimeout: 1500,
188 videoViewUrl: this.getVideoUrl(videoId) + '/views',
190 playerElement: this.videoElement,
191 onPlayerElementChange: (element: HTMLVideoElement) => this.videoElement = element,
193 videoDuration: videoInfo.duration,
196 poster: window.location.origin + videoInfo.previewPath,
199 serverUrl: window.location.origin,
200 language: navigator.language,
201 embedUrl: window.location.origin + videoInfo.embedPath
205 videoFiles: videoInfo.files
209 if (this.mode === 'p2p-media-loader') {
210 const hlsPlaylist = videoInfo.streamingPlaylists.find(p => p.type === VideoStreamingPlaylistType.HLS)
212 Object.assign(options, {
214 playlistUrl: hlsPlaylist.playlistUrl,
215 segmentsSha256Url: hlsPlaylist.segmentsSha256Url,
216 redundancyBaseUrls: hlsPlaylist.redundancies.map(r => r.baseUrl),
217 trackerAnnounce: videoInfo.trackerUrls,
218 videoFiles: hlsPlaylist.files
219 } as P2PMediaLoaderOptions
223 this.player = await PeertubePlayerManager.initialize(this.mode, options, player => this.player = player)
224 this.player.on('customError', (event: any, data: any) => this.handleError(data.err, serverTranslations))
226 window[ 'videojsPlayer' ] = this.player
230 await this.buildDock(videoInfo, configResponse)
235 private handleError (err: Error, translations?: { [ id: string ]: string }) {
236 if (err.message.indexOf('from xs param') !== -1) {
237 this.player.dispose()
238 this.videoElement = null
239 this.displayError('This video is not available because the remote instance is not responding.', translations)
244 private async buildDock (videoInfo: VideoDetails, configResponse: Response) {
246 const title = this.title ? videoInfo.name : undefined
248 const config: ServerConfig = await configResponse.json()
249 const description = config.tracker.enabled && this.warningTitle
250 ? '<span class="text">' + this.player.localize('Watching this video may reveal your IP address to others.') + '</span>'
260 private buildCSS () {
261 const body = document.getElementById('custom-css')
263 if (this.bigPlayBackgroundColor) {
264 body.style.setProperty('--embedBigPlayBackgroundColor', this.bigPlayBackgroundColor)
267 if (this.foregroundColor) {
268 body.style.setProperty('--embedForegroundColor', this.foregroundColor)
272 private async buildCaptions (serverTranslations: any, captionsResponse: Response): Promise<VideoJSCaption[]> {
273 if (captionsResponse.ok) {
274 const { data } = (await captionsResponse.json()) as ResultList<VideoCaption>
276 return data.map(c => ({
277 label: peertubeTranslate(c.language.label, serverTranslations),
278 language: c.language.id,
279 src: window.location.origin + c.captionPath
288 .catch(err => console.error('Cannot init embed.', err))