]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blame - client/src/standalone/videos/embed.ts
Remove octet stream fallback for video extension
[github/Chocobozzz/PeerTube.git] / client / src / standalone / videos / embed.ts
CommitLineData
202e7223
C
1import './embed.scss'
2
3f9c4955
C
3import {
4 getCompleteLocale,
5 is18nLocale,
6 isDefaultLocale,
7 peertubeTranslate,
8 ResultList,
9 ServerConfig,
10 VideoDetails
11} from '../../../../shared'
16f7022b 12import { VideoJSCaption } from '../../assets/player/peertube-videojs-typings'
59c76ffa 13import { VideoCaption } from '../../../../shared/models/videos/caption/video-caption.model'
09209296
C
14import {
15 P2PMediaLoaderOptions,
09209296
C
16 PeertubePlayerManagerOptions,
17 PlayerMode
18} from '../../assets/player/peertube-player-manager'
19import { VideoStreamingPlaylistType } from '../../../../shared/models/videos/video-streaming-playlist.type'
5efab546 20import { PeerTubeEmbedApi } from './embed-api'
3f9c4955 21import { TranslationsManager } from '../../assets/player/translations-manager'
202e7223 22
5efab546 23export class PeerTubeEmbed {
902aa3a0
C
24 videoElement: HTMLVideoElement
25 player: any
902aa3a0 26 api: PeerTubeEmbedApi = null
3b019808
C
27 autoplay: boolean
28 controls: boolean
29 muted: boolean
30 loop: boolean
31 subtitle: string
902aa3a0 32 enableApi = false
1f6824c9 33 startTime: number | string = 0
f0a39880 34 stopTime: number | string
5efab546
C
35
36 title: boolean
37 warningTitle: boolean
38 bigPlayBackgroundColor: string
39 foregroundColor: string
40
3b6f205c 41 mode: PlayerMode
902aa3a0
C
42 scope = 'peertube'
43
44 static async main () {
c6352f2c 45 const videoContainerId = 'video-container'
99941732
WL
46 const embed = new PeerTubeEmbed(videoContainerId)
47 await embed.init()
48 }
902aa3a0
C
49
50 constructor (private videoContainerId: string) {
51 this.videoElement = document.getElementById(videoContainerId) as HTMLVideoElement
52 }
53
99941732
WL
54 getVideoUrl (id: string) {
55 return window.location.origin + '/api/v1/videos/' + id
56 }
d4f3fea6 57
99941732
WL
58 loadVideoInfo (videoId: string): Promise<Response> {
59 return fetch(this.getVideoUrl(videoId))
60 }
d4f3fea6 61
16f7022b
C
62 loadVideoCaptions (videoId: string): Promise<Response> {
63 return fetch(this.getVideoUrl(videoId) + '/captions')
64 }
65
31b6ddf8
C
66 loadConfig (): Promise<Response> {
67 return fetch('/api/v1/config')
68 }
69
99941732
WL
70 removeElement (element: HTMLElement) {
71 element.parentElement.removeChild(element)
72 }
d4f3fea6 73
ad3fa0c5 74 displayError (text: string, translations?: { [ id: string ]: string }) {
99941732 75 // Remove video element
6d88de72 76 if (this.videoElement) this.removeElement(this.videoElement)
99941732 77
ad3fa0c5
C
78 const translatedText = peertubeTranslate(text, translations)
79 const translatedSorry = peertubeTranslate('Sorry', translations)
80
81 document.title = translatedSorry + ' - ' + translatedText
99941732
WL
82
83 const errorBlock = document.getElementById('error-block')
84 errorBlock.style.display = 'flex'
85
ad3fa0c5
C
86 const errorTitle = document.getElementById('error-title')
87 errorTitle.innerHTML = peertubeTranslate('Sorry', translations)
88
99941732 89 const errorText = document.getElementById('error-content')
ad3fa0c5 90 errorText.innerHTML = translatedText
99941732
WL
91 }
92
ad3fa0c5 93 videoNotFound (translations?: { [ id: string ]: string }) {
99941732 94 const text = 'This video does not exist.'
ad3fa0c5 95 this.displayError(text, translations)
99941732
WL
96 }
97
ad3fa0c5 98 videoFetchError (translations?: { [ id: string ]: string }) {
99941732 99 const text = 'We cannot fetch the video. Please try again later.'
ad3fa0c5 100 this.displayError(text, translations)
99941732
WL
101 }
102
3b019808 103 getParamToggle (params: URLSearchParams, name: string, defaultValue?: boolean) {
99941732
WL
104 return params.has(name) ? (params.get(name) === '1' || params.get(name) === 'true') : defaultValue
105 }
d4f3fea6 106
3b019808 107 getParamString (params: URLSearchParams, name: string, defaultValue?: string) {
99941732
WL
108 return params.has(name) ? params.get(name) : defaultValue
109 }
da99ccf2 110
902aa3a0 111 async init () {
99941732
WL
112 try {
113 await this.initCore()
114 } catch (e) {
115 console.error(e)
116 }
117 }
118
902aa3a0
C
119 private initializeApi () {
120 if (!this.enableApi) return
121
122 this.api = new PeerTubeEmbedApi(this)
123 this.api.initialize()
124 }
125
0f2f274c 126 private loadParams (video: VideoDetails) {
da99ccf2 127 try {
c4710631 128 const params = new URL(window.location.toString()).searchParams
99941732 129
31b6ddf8
C
130 this.autoplay = this.getParamToggle(params, 'autoplay', false)
131 this.controls = this.getParamToggle(params, 'controls', true)
132 this.muted = this.getParamToggle(params, 'muted', false)
133 this.loop = this.getParamToggle(params, 'loop', false)
5efab546 134 this.title = this.getParamToggle(params, 'title', true)
99941732 135 this.enableApi = this.getParamToggle(params, 'api', this.enableApi)
5efab546 136 this.warningTitle = this.getParamToggle(params, 'warningTitle', true)
f37bad63 137
3b019808
C
138 this.scope = this.getParamString(params, 'scope', this.scope)
139 this.subtitle = this.getParamString(params, 'subtitle')
140 this.startTime = this.getParamString(params, 'start')
f0a39880 141 this.stopTime = this.getParamString(params, 'stop')
3b6f205c 142
5efab546
C
143 this.bigPlayBackgroundColor = this.getParamString(params, 'bigPlayBackgroundColor')
144 this.foregroundColor = this.getParamString(params, 'foregroundColor')
145
0f2f274c
C
146 const modeParam = this.getParamString(params, 'mode')
147
148 if (modeParam) {
149 if (modeParam === 'p2p-media-loader') this.mode = 'p2p-media-loader'
150 else this.mode = 'webtorrent'
151 } else {
152 if (Array.isArray(video.streamingPlaylists) && video.streamingPlaylists.length !== 0) this.mode = 'p2p-media-loader'
153 else this.mode = 'webtorrent'
154 }
da99ccf2
C
155 } catch (err) {
156 console.error('Cannot get params from URL.', err)
157 }
99941732
WL
158 }
159
902aa3a0 160 private async initCore () {
6385c0cb
C
161 const urlParts = window.location.pathname.split('/')
162 const videoId = urlParts[ urlParts.length - 1 ]
99941732 163
3f9c4955
C
164 const videoPromise = this.loadVideoInfo(videoId)
165 const captionsPromise = this.loadVideoCaptions(videoId)
166 const configPromise = this.loadConfig()
167
168 const translationsPromise = TranslationsManager.getServerTranslations(window.location.origin, navigator.language)
169 const videoResponse = await videoPromise
99941732 170
16f7022b 171 if (!videoResponse.ok) {
3f9c4955
C
172 const serverTranslations = await translationsPromise
173
ad3fa0c5 174 if (videoResponse.status === 404) return this.videoNotFound(serverTranslations)
99941732 175
ad3fa0c5 176 return this.videoFetchError(serverTranslations)
99941732
WL
177 }
178
16f7022b 179 const videoInfo: VideoDetails = await videoResponse.json()
3f9c4955
C
180 this.loadPlaceholder(videoInfo)
181
182 const PeertubePlayerManagerModulePromise = import('../../assets/player/peertube-player-manager')
183
184 const promises = [ translationsPromise, captionsPromise, configPromise, PeertubePlayerManagerModulePromise ]
185 const [ serverTranslations, captionsResponse, configResponse, PeertubePlayerManagerModule ] = await Promise.all(promises)
186
187 const PeertubePlayerManager = PeertubePlayerManagerModule.PeertubePlayerManager
5efab546 188 const videoCaptions = await this.buildCaptions(serverTranslations, captionsResponse)
99941732 189
0f2f274c 190 this.loadParams(videoInfo)
da99ccf2 191
2adfc7ea
C
192 const options: PeertubePlayerManagerOptions = {
193 common: {
194 autoplay: this.autoplay,
195 controls: this.controls,
196 muted: this.muted,
197 loop: this.loop,
198 captions: videoCaptions.length !== 0,
199 startTime: this.startTime,
f0a39880 200 stopTime: this.stopTime,
2adfc7ea
C
201 subtitle: this.subtitle,
202
203 videoCaptions,
204 inactivityTimeout: 1500,
205 videoViewUrl: this.getVideoUrl(videoId) + '/views',
6ec0b75b 206
2adfc7ea 207 playerElement: this.videoElement,
6ec0b75b
C
208 onPlayerElementChange: (element: HTMLVideoElement) => this.videoElement = element,
209
2adfc7ea
C
210 videoDuration: videoInfo.duration,
211 enableHotkeys: true,
212 peertubeLink: true,
213 poster: window.location.origin + videoInfo.previewPath,
3d9a63d3 214 theaterButton: false,
2adfc7ea
C
215
216 serverUrl: window.location.origin,
217 language: navigator.language,
218 embedUrl: window.location.origin + videoInfo.embedPath
6ec0b75b
C
219 },
220
221 webtorrent: {
222 videoFiles: videoInfo.files
2adfc7ea 223 }
3b6f205c 224 }
2adfc7ea 225
3b6f205c 226 if (this.mode === 'p2p-media-loader') {
09209296
C
227 const hlsPlaylist = videoInfo.streamingPlaylists.find(p => p.type === VideoStreamingPlaylistType.HLS)
228
3b6f205c
C
229 Object.assign(options, {
230 p2pMediaLoader: {
09209296
C
231 playlistUrl: hlsPlaylist.playlistUrl,
232 segmentsSha256Url: hlsPlaylist.segmentsSha256Url,
233 redundancyBaseUrls: hlsPlaylist.redundancies.map(r => r.baseUrl),
234 trackerAnnounce: videoInfo.trackerUrls,
5a71acd2 235 videoFiles: hlsPlaylist.files
09209296 236 } as P2PMediaLoaderOptions
3b6f205c 237 })
2adfc7ea 238 }
202e7223 239
3f9c4955 240 this.player = await PeertubePlayerManager.initialize(this.mode, options, (player: any) => this.player = player)
2adfc7ea 241 this.player.on('customError', (event: any, data: any) => this.handleError(data.err, serverTranslations))
99941732 242
2adfc7ea 243 window[ 'videojsPlayer' ] = this.player
902aa3a0 244
5efab546
C
245 this.buildCSS()
246
247 await this.buildDock(videoInfo, configResponse)
248
249 this.initializeApi()
3f9c4955
C
250
251 this.removePlaceholder()
5efab546
C
252 }
253
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)
259 return
260 }
261 }
262
263 private async buildDock (videoInfo: VideoDetails, configResponse: Response) {
2adfc7ea 264 if (this.controls) {
5efab546
C
265 const title = this.title ? videoInfo.name : undefined
266
31b6ddf8 267 const config: ServerConfig = await configResponse.json()
5efab546 268 const description = config.tracker.enabled && this.warningTitle
13176a07 269 ? '<span class="text">' + this.player.localize('Watching this video may reveal your IP address to others.') + '</span>'
31b6ddf8
C
270 : undefined
271
2adfc7ea 272 this.player.dock({
5efab546 273 title,
31b6ddf8 274 description
2adfc7ea
C
275 })
276 }
5efab546 277 }
16f7022b 278
5efab546
C
279 private buildCSS () {
280 const body = document.getElementById('custom-css')
281
282 if (this.bigPlayBackgroundColor) {
283 body.style.setProperty('--embedBigPlayBackgroundColor', this.bigPlayBackgroundColor)
284 }
285
286 if (this.foregroundColor) {
287 body.style.setProperty('--embedForegroundColor', this.foregroundColor)
288 }
99941732 289 }
6d88de72 290
5efab546
C
291 private async buildCaptions (serverTranslations: any, captionsResponse: Response): Promise<VideoJSCaption[]> {
292 if (captionsResponse.ok) {
293 const { data } = (await captionsResponse.json()) as ResultList<VideoCaption>
294
295 return data.map(c => ({
296 label: peertubeTranslate(c.language.label, serverTranslations),
297 language: c.language.id,
298 src: window.location.origin + c.captionPath
299 }))
6d88de72 300 }
5efab546
C
301
302 return []
6d88de72 303 }
3f9c4955
C
304
305 private loadPlaceholder (video: VideoDetails) {
306 const placeholder = this.getPlaceholderElement()
307
308 const url = window.location.origin + video.previewPath
309 placeholder.style.backgroundImage = `url("${url}")`
310 }
311
312 private removePlaceholder () {
313 const placeholder = this.getPlaceholderElement()
314 placeholder.parentElement.removeChild(placeholder)
315 }
316
317 private getPlaceholderElement () {
318 return document.getElementById('placeholder-preview')
319 }
99941732
WL
320}
321
322PeerTubeEmbed.main()
902aa3a0 323 .catch(err => console.error('Cannot init embed.', err))