]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blame - client/src/standalone/videos/embed.ts
Fast forward on HLS decode error
[github/Chocobozzz/PeerTube.git] / client / src / standalone / videos / embed.ts
CommitLineData
202e7223 1import './embed.scss'
583eb04b 2import videojs from 'video.js'
bd45d503 3import { peertubeTranslate } from '../../../../shared/core-utils/i18n'
3f9c4955 4import {
aea0b0e7 5 HTMLServerConfig,
c0e8b12e 6 HttpStatusCode,
e030bfb5 7 OAuth2ErrorCode,
3f9c4955 8 ResultList,
583eb04b 9 UserRefreshToken,
a9bfa85d 10 Video,
583eb04b 11 VideoCaption,
4504f09f 12 VideoDetails,
5abc96fc
C
13 VideoPlaylist,
14 VideoPlaylistElement,
aea0b0e7 15 VideoStreamingPlaylistType
583eb04b 16} from '../../../../shared/models'
c4207f97 17import { P2PMediaLoaderOptions, PeertubePlayerManagerOptions, PlayerMode } from '../../assets/player'
abb3097e 18import { VideoJSCaption } from '../../assets/player/peertube-videojs-typings'
583eb04b 19import { TranslationsManager } from '../../assets/player/translations-manager'
a9bfa85d
C
20import { isP2PEnabled } from '../../assets/player/utils'
21import { getBoolOrDefault } from '../../root-helpers/local-storage-utils'
aea0b0e7 22import { peertubeLocalStorage } from '../../root-helpers/peertube-web-storage'
72f611ca 23import { PluginsManager } from '../../root-helpers/plugins-manager'
a9bfa85d 24import { UserLocalStorageKeys, UserTokens } from '../../root-helpers/users'
f9562863 25import { objectToUrlEncoded } from '../../root-helpers/utils'
f9562863 26import { RegisterClientHelpers } from '../../types/register-client-option.model'
aea0b0e7 27import { PeerTubeEmbedApi } from './embed-api'
abb3097e
C
28
29type Translations = { [ id: string ]: string }
202e7223 30
5efab546 31export class PeerTubeEmbed {
5abc96fc 32 playerElement: HTMLVideoElement
7e37e111 33 player: videojs.Player
902aa3a0 34 api: PeerTubeEmbedApi = null
5abc96fc 35
3b019808
C
36 autoplay: boolean
37 controls: boolean
38 muted: boolean
39 loop: boolean
40 subtitle: string
902aa3a0 41 enableApi = false
1f6824c9 42 startTime: number | string = 0
f0a39880 43 stopTime: number | string
5efab546
C
44
45 title: boolean
46 warningTitle: boolean
08d9ba0f 47 peertubeLink: boolean
85302118 48 p2pEnabled: boolean
5efab546
C
49 bigPlayBackgroundColor: string
50 foregroundColor: string
51
3b6f205c 52 mode: PlayerMode
902aa3a0
C
53 scope = 'peertube'
54
a9bfa85d 55 userTokens: UserTokens
71ab65d0 56 headers = new Headers()
4504f09f
RK
57 LOCAL_STORAGE_OAUTH_CLIENT_KEYS = {
58 CLIENT_ID: 'client_id',
59 CLIENT_SECRET: 'client_secret'
60 }
71ab65d0 61
aea0b0e7
C
62 config: HTMLServerConfig
63
5abc96fc 64 private translationsPromise: Promise<{ [id: string]: string }>
5abc96fc
C
65 private PeertubePlayerManagerModulePromise: Promise<any>
66
67 private playlist: VideoPlaylist
68 private playlistElements: VideoPlaylistElement[]
69 private currentPlaylistElement: VideoPlaylistElement
70
9df52d66 71 private readonly wrapperElement: HTMLElement
5abc96fc 72
72f611ca 73 private pluginsManager: PluginsManager
f9562863 74
9df52d66 75 constructor (private readonly videoWrapperId: string) {
5abc96fc 76 this.wrapperElement = document.getElementById(this.videoWrapperId)
aea0b0e7
C
77
78 try {
79 this.config = JSON.parse(window['PeerTubeServerConfig'])
80 } catch (err) {
81 console.error('Cannot parse HTML config.', err)
82 }
902aa3a0
C
83 }
84
9df52d66
C
85 static async main () {
86 const videoContainerId = 'video-wrapper'
87 const embed = new PeerTubeEmbed(videoContainerId)
88 await embed.init()
89 }
90
99941732
WL
91 getVideoUrl (id: string) {
92 return window.location.origin + '/api/v1/videos/' + id
93 }
d4f3fea6 94
207612df 95 refreshFetch (url: string, options?: RequestInit) {
4504f09f
RK
96 return fetch(url, options)
97 .then((res: Response) => {
f2eb23cd 98 if (res.status !== HttpStatusCode.UNAUTHORIZED_401) return res
4504f09f 99
72aa835e 100 const refreshingTokenPromise = new Promise<void>((resolve, reject) => {
4504f09f
RK
101 const clientId: string = peertubeLocalStorage.getItem(this.LOCAL_STORAGE_OAUTH_CLIENT_KEYS.CLIENT_ID)
102 const clientSecret: string = peertubeLocalStorage.getItem(this.LOCAL_STORAGE_OAUTH_CLIENT_KEYS.CLIENT_SECRET)
207612df 103
4504f09f
RK
104 const headers = new Headers()
105 headers.set('Content-Type', 'application/x-www-form-urlencoded')
207612df 106
4504f09f 107 const data = {
a4ff3100 108 refresh_token: this.userTokens.refreshToken,
4504f09f
RK
109 client_id: clientId,
110 client_secret: clientSecret,
111 response_type: 'code',
112 grant_type: 'refresh_token'
113 }
114
115 fetch('/api/v1/users/token', {
116 headers,
117 method: 'POST',
118 body: objectToUrlEncoded(data)
496d784d 119 }).then(res => {
f2eb23cd 120 if (res.status === HttpStatusCode.UNAUTHORIZED_401) return undefined
a4ff3100 121
496d784d 122 return res.json()
e030bfb5
C
123 }).then((obj: UserRefreshToken & { code?: OAuth2ErrorCode }) => {
124 if (!obj || obj.code === OAuth2ErrorCode.INVALID_GRANT) {
a9bfa85d 125 UserTokens.flushLocalStorage(peertubeLocalStorage)
496d784d 126 this.removeTokensFromHeaders()
a4ff3100 127
496d784d
C
128 return resolve()
129 }
130
131 this.userTokens.accessToken = obj.access_token
132 this.userTokens.refreshToken = obj.refresh_token
a9bfa85d 133 UserTokens.saveToLocalStorage(peertubeLocalStorage, this.userTokens)
496d784d
C
134
135 this.setHeadersFromTokens()
136
137 resolve()
a7299d9d
C
138 }).catch((refreshTokenError: any) => {
139 reject(refreshTokenError)
496d784d 140 })
4504f09f
RK
141 })
142
143 return refreshingTokenPromise
496d784d 144 .catch(() => {
a9bfa85d 145 UserTokens.flushLocalStorage(peertubeLocalStorage)
496d784d
C
146
147 this.removeTokensFromHeaders()
148 }).then(() => fetch(url, {
4504f09f
RK
149 ...options,
150 headers: this.headers
151 }))
152 })
153 }
154
5abc96fc
C
155 getPlaylistUrl (id: string) {
156 return window.location.origin + '/api/v1/video-playlists/' + id
157 }
158
99941732 159 loadVideoInfo (videoId: string): Promise<Response> {
4504f09f 160 return this.refreshFetch(this.getVideoUrl(videoId), { headers: this.headers })
99941732 161 }
d4f3fea6 162
16f7022b 163 loadVideoCaptions (videoId: string): Promise<Response> {
be59656c 164 return this.refreshFetch(this.getVideoUrl(videoId) + '/captions', { headers: this.headers })
16f7022b
C
165 }
166
5abc96fc 167 loadPlaylistInfo (playlistId: string): Promise<Response> {
be59656c 168 return this.refreshFetch(this.getPlaylistUrl(playlistId), { headers: this.headers })
5abc96fc
C
169 }
170
fb13852d
C
171 loadPlaylistElements (playlistId: string, start = 0): Promise<Response> {
172 const url = new URL(this.getPlaylistUrl(playlistId) + '/videos')
173 url.search = new URLSearchParams({ start: '' + start, count: '100' }).toString()
174
be59656c 175 return this.refreshFetch(url.toString(), { headers: this.headers })
5abc96fc
C
176 }
177
99941732
WL
178 removeElement (element: HTMLElement) {
179 element.parentElement.removeChild(element)
180 }
d4f3fea6 181
abb3097e 182 displayError (text: string, translations?: Translations) {
99941732 183 // Remove video element
5abc96fc
C
184 if (this.playerElement) {
185 this.removeElement(this.playerElement)
186 this.playerElement = undefined
187 }
99941732 188
ad3fa0c5
C
189 const translatedText = peertubeTranslate(text, translations)
190 const translatedSorry = peertubeTranslate('Sorry', translations)
191
192 document.title = translatedSorry + ' - ' + translatedText
99941732
WL
193
194 const errorBlock = document.getElementById('error-block')
195 errorBlock.style.display = 'flex'
196
ad3fa0c5
C
197 const errorTitle = document.getElementById('error-title')
198 errorTitle.innerHTML = peertubeTranslate('Sorry', translations)
199
99941732 200 const errorText = document.getElementById('error-content')
ad3fa0c5 201 errorText.innerHTML = translatedText
2a71d286
C
202
203 this.wrapperElement.style.display = 'none'
99941732
WL
204 }
205
abb3097e 206 videoNotFound (translations?: Translations) {
99941732 207 const text = 'This video does not exist.'
ad3fa0c5 208 this.displayError(text, translations)
99941732
WL
209 }
210
abb3097e 211 videoFetchError (translations?: Translations) {
99941732 212 const text = 'We cannot fetch the video. Please try again later.'
ad3fa0c5 213 this.displayError(text, translations)
99941732
WL
214 }
215
5abc96fc
C
216 playlistNotFound (translations?: Translations) {
217 const text = 'This playlist does not exist.'
218 this.displayError(text, translations)
219 }
220
221 playlistFetchError (translations?: Translations) {
222 const text = 'We cannot fetch the playlist. Please try again later.'
223 this.displayError(text, translations)
224 }
225
3b019808 226 getParamToggle (params: URLSearchParams, name: string, defaultValue?: boolean) {
99941732
WL
227 return params.has(name) ? (params.get(name) === '1' || params.get(name) === 'true') : defaultValue
228 }
d4f3fea6 229
3b019808 230 getParamString (params: URLSearchParams, name: string, defaultValue?: string) {
99941732
WL
231 return params.has(name) ? params.get(name) : defaultValue
232 }
da99ccf2 233
9054a8b6
C
234 async playNextVideo () {
235 const next = this.getNextPlaylistElement()
236 if (!next) {
237 console.log('Next element not found in playlist.')
238 return
239 }
240
241 this.currentPlaylistElement = next
242
243 return this.loadVideoAndBuildPlayer(this.currentPlaylistElement.video.uuid)
244 }
245
246 async playPreviousVideo () {
247 const previous = this.getPreviousPlaylistElement()
248 if (!previous) {
249 console.log('Previous element not found in playlist.')
250 return
251 }
252
253 this.currentPlaylistElement = previous
254
255 await this.loadVideoAndBuildPlayer(this.currentPlaylistElement.video.uuid)
256 }
257
258 getCurrentPosition () {
259 if (!this.currentPlaylistElement) return -1
260
261 return this.currentPlaylistElement.position
262 }
263
902aa3a0 264 async init () {
a9bfa85d 265 this.userTokens = UserTokens.getUserTokens(peertubeLocalStorage)
c21a0aa8 266 await this.initCore()
99941732
WL
267 }
268
902aa3a0
C
269 private initializeApi () {
270 if (!this.enableApi) return
271
272 this.api = new PeerTubeEmbedApi(this)
273 this.api.initialize()
274 }
275
0f2f274c 276 private loadParams (video: VideoDetails) {
da99ccf2 277 try {
c4710631 278 const params = new URL(window.location.toString()).searchParams
99941732 279
31b6ddf8
C
280 this.autoplay = this.getParamToggle(params, 'autoplay', false)
281 this.controls = this.getParamToggle(params, 'controls', true)
64645512 282 this.muted = this.getParamToggle(params, 'muted', undefined)
31b6ddf8 283 this.loop = this.getParamToggle(params, 'loop', false)
5efab546 284 this.title = this.getParamToggle(params, 'title', true)
99941732 285 this.enableApi = this.getParamToggle(params, 'api', this.enableApi)
5efab546 286 this.warningTitle = this.getParamToggle(params, 'warningTitle', true)
08d9ba0f 287 this.peertubeLink = this.getParamToggle(params, 'peertubeLink', true)
85302118 288 this.p2pEnabled = this.getParamToggle(params, 'p2p', this.isP2PEnabled(video))
f37bad63 289
3b019808
C
290 this.scope = this.getParamString(params, 'scope', this.scope)
291 this.subtitle = this.getParamString(params, 'subtitle')
292 this.startTime = this.getParamString(params, 'start')
f0a39880 293 this.stopTime = this.getParamString(params, 'stop')
3b6f205c 294
5efab546
C
295 this.bigPlayBackgroundColor = this.getParamString(params, 'bigPlayBackgroundColor')
296 this.foregroundColor = this.getParamString(params, 'foregroundColor')
297
0f2f274c
C
298 const modeParam = this.getParamString(params, 'mode')
299
300 if (modeParam) {
301 if (modeParam === 'p2p-media-loader') this.mode = 'p2p-media-loader'
302 else this.mode = 'webtorrent'
303 } else {
304 if (Array.isArray(video.streamingPlaylists) && video.streamingPlaylists.length !== 0) this.mode = 'p2p-media-loader'
305 else this.mode = 'webtorrent'
306 }
da99ccf2
C
307 } catch (err) {
308 console.error('Cannot get params from URL.', err)
309 }
99941732
WL
310 }
311
fb13852d
C
312 private async loadAllPlaylistVideos (playlistId: string, baseResult: ResultList<VideoPlaylistElement>) {
313 let elements = baseResult.data
314 let total = baseResult.total
315 let i = 0
316
317 while (total > elements.length && i < 10) {
318 const result = await this.loadPlaylistElements(playlistId, elements.length)
319
9df52d66 320 const json = await result.json()
fb13852d
C
321 total = json.total
322
323 elements = elements.concat(json.data)
324 i++
325 }
326
327 if (i === 10) {
328 console.error('Cannot fetch all playlists elements, there are too many!')
329 }
330
331 return elements
332 }
333
5abc96fc
C
334 private async loadPlaylist (playlistId: string) {
335 const playlistPromise = this.loadPlaylistInfo(playlistId)
336 const playlistElementsPromise = this.loadPlaylistElements(playlistId)
99941732 337
be59656c
C
338 let playlistResponse: Response
339 let isResponseOk: boolean
5abc96fc 340
be59656c
C
341 try {
342 playlistResponse = await playlistPromise
f2eb23cd 343 isResponseOk = playlistResponse.status === HttpStatusCode.OK_200
be59656c
C
344 } catch (err) {
345 console.error(err)
346 isResponseOk = false
347 }
348
349 if (!isResponseOk) {
5abc96fc 350 const serverTranslations = await this.translationsPromise
71ab65d0 351
f2eb23cd 352 if (playlistResponse?.status === HttpStatusCode.NOT_FOUND_404) {
5abc96fc
C
353 this.playlistNotFound(serverTranslations)
354 return undefined
355 }
356
357 this.playlistFetchError(serverTranslations)
358 return undefined
359 }
360
361 return { playlistResponse, videosResponse: await playlistElementsPromise }
362 }
363
364 private async loadVideo (videoId: string) {
3f9c4955 365 const videoPromise = this.loadVideoInfo(videoId)
3f9c4955 366
be59656c
C
367 let videoResponse: Response
368 let isResponseOk: boolean
369
370 try {
371 videoResponse = await videoPromise
f2eb23cd 372 isResponseOk = videoResponse.status === HttpStatusCode.OK_200
be59656c
C
373 } catch (err) {
374 console.error(err)
375
376 isResponseOk = false
377 }
99941732 378
be59656c 379 if (!isResponseOk) {
5abc96fc
C
380 const serverTranslations = await this.translationsPromise
381
f2eb23cd 382 if (videoResponse?.status === HttpStatusCode.NOT_FOUND_404) {
5abc96fc
C
383 this.videoNotFound(serverTranslations)
384 return undefined
385 }
386
387 this.videoFetchError(serverTranslations)
388 return undefined
389 }
390
391 const captionsPromise = this.loadVideoCaptions(videoId)
392
393 return { captionsPromise, videoResponse }
394 }
3f9c4955 395
5abc96fc
C
396 private async buildPlaylistManager () {
397 const translations = await this.translationsPromise
398
399 this.player.upnext({
400 timeout: 10000, // 10s
401 headText: peertubeTranslate('Up Next', translations),
402 cancelText: peertubeTranslate('Cancel', translations),
403 suspendedText: peertubeTranslate('Autoplay is suspended', translations),
404 getTitle: () => this.nextVideoTitle(),
a950e4c8 405 next: () => this.playNextVideo(),
5abc96fc
C
406 condition: () => !!this.getNextPlaylistElement(),
407 suspended: () => false
408 })
409 }
99941732 410
4572c3d0
C
411 private async loadVideoAndBuildPlayer (uuid: string) {
412 const res = await this.loadVideo(uuid)
5abc96fc
C
413 if (res === undefined) return
414
415 return this.buildVideoPlayer(res.videoResponse, res.captionsPromise)
416 }
3f9c4955 417
5abc96fc
C
418 private nextVideoTitle () {
419 const next = this.getNextPlaylistElement()
420 if (!next) return ''
421
422 return next.video.name
423 }
424
425 private getNextPlaylistElement (position?: number): VideoPlaylistElement {
426 if (!position) position = this.currentPlaylistElement.position + 1
427
428 if (position > this.playlist.videosLength) {
429 return undefined
430 }
431
432 const next = this.playlistElements.find(e => e.position === position)
433
434 if (!next || !next.video) {
435 return this.getNextPlaylistElement(position + 1)
436 }
437
438 return next
439 }
440
a950e4c8 441 private getPreviousPlaylistElement (position?: number): VideoPlaylistElement {
2a71d286 442 if (!position) position = this.currentPlaylistElement.position - 1
a950e4c8
C
443
444 if (position < 1) {
445 return undefined
446 }
447
448 const prev = this.playlistElements.find(e => e.position === position)
449
450 if (!prev || !prev.video) {
451 return this.getNextPlaylistElement(position - 1)
452 }
453
454 return prev
455 }
456
5abc96fc
C
457 private async buildVideoPlayer (videoResponse: Response, captionsPromise: Promise<Response>) {
458 let alreadyHadPlayer = false
459
460 if (this.player) {
461 this.player.dispose()
462 alreadyHadPlayer = true
463 }
464
465 this.playerElement = document.createElement('video')
466 this.playerElement.className = 'video-js vjs-peertube-skin'
467 this.playerElement.setAttribute('playsinline', 'true')
468 this.wrapperElement.appendChild(this.playerElement)
469
aea0b0e7
C
470 // Issue when we parsed config from HTML, fallback to API
471 if (!this.config) {
472 this.config = await this.refreshFetch('/api/v1/config')
9df52d66 473 .then(res => res.json())
aea0b0e7
C
474 }
475
5abc96fc
C
476 const videoInfoPromise = videoResponse.json()
477 .then((videoInfo: VideoDetails) => {
200eaf51
C
478 this.loadParams(videoInfo)
479
480 if (!alreadyHadPlayer && !this.autoplay) this.loadPlaceholder(videoInfo)
5abc96fc
C
481
482 return videoInfo
483 })
484
aea0b0e7 485 const [ videoInfoTmp, serverTranslations, captionsResponse, PeertubePlayerManagerModule ] = await Promise.all([
5abc96fc
C
486 videoInfoPromise,
487 this.translationsPromise,
488 captionsPromise,
5abc96fc
C
489 this.PeertubePlayerManagerModulePromise
490 ])
3f9c4955 491
72f611ca 492 await this.loadPlugins(serverTranslations)
f9562863 493
6fad8e51
C
494 const videoInfo: VideoDetails = videoInfoTmp
495
3f9c4955 496 const PeertubePlayerManager = PeertubePlayerManagerModule.PeertubePlayerManager
5efab546 497 const videoCaptions = await this.buildCaptions(serverTranslations, captionsResponse)
99941732 498
4572c3d0
C
499 const playlistPlugin = this.currentPlaylistElement
500 ? {
501 elements: this.playlistElements,
502 playlist: this.playlist,
503
504 getCurrentPosition: () => this.currentPlaylistElement.position,
505
506 onItemClicked: (videoPlaylistElement: VideoPlaylistElement) => {
507 this.currentPlaylistElement = videoPlaylistElement
508
509 this.loadVideoAndBuildPlayer(this.currentPlaylistElement.video.uuid)
9df52d66 510 .catch(err => console.error(err))
3e0e8d4a 511 }
4572c3d0
C
512 }
513 : undefined
514
2adfc7ea
C
515 const options: PeertubePlayerManagerOptions = {
516 common: {
5abc96fc
C
517 // Autoplay in playlist mode
518 autoplay: alreadyHadPlayer ? true : this.autoplay,
2adfc7ea
C
519 controls: this.controls,
520 muted: this.muted,
521 loop: this.loop,
1a8c2d74 522
85302118 523 p2pEnabled: this.p2pEnabled,
a9bfa85d 524
2adfc7ea 525 captions: videoCaptions.length !== 0,
2adfc7ea
C
526 subtitle: this.subtitle,
527
1a8c2d74
C
528 startTime: this.playlist ? this.currentPlaylistElement.startTimestamp : this.startTime,
529 stopTime: this.playlist ? this.currentPlaylistElement.stopTimestamp : this.stopTime,
530
a950e4c8
C
531 nextVideo: this.playlist ? () => this.playNextVideo() : undefined,
532 hasNextVideo: this.playlist ? () => !!this.getNextPlaylistElement() : undefined,
533
534 previousVideo: this.playlist ? () => this.playPreviousVideo() : undefined,
535 hasPreviousVideo: this.playlist ? () => !!this.getPreviousPlaylistElement() : undefined,
536
4572c3d0 537 playlist: playlistPlugin,
5abc96fc 538
2adfc7ea 539 videoCaptions,
35f0a5e6 540 inactivityTimeout: 2500,
5abc96fc 541 videoViewUrl: this.getVideoUrl(videoInfo.uuid) + '/views',
29837f88 542 videoShortUUID: videoInfo.shortUUID,
58b9ce30 543 videoUUID: videoInfo.uuid,
6ec0b75b 544
25b7c847
C
545 isLive: videoInfo.isLive,
546
5abc96fc 547 playerElement: this.playerElement,
9df52d66
C
548 onPlayerElementChange: (element: HTMLVideoElement) => {
549 this.playerElement = element
550 },
6ec0b75b 551
2adfc7ea
C
552 videoDuration: videoInfo.duration,
553 enableHotkeys: true,
08d9ba0f 554 peertubeLink: this.peertubeLink,
2adfc7ea 555 poster: window.location.origin + videoInfo.previewPath,
3d9a63d3 556 theaterButton: false,
2adfc7ea
C
557
558 serverUrl: window.location.origin,
559 language: navigator.language,
4097c6d6 560 embedUrl: window.location.origin + videoInfo.embedPath,
c4207f97
C
561 embedTitle: videoInfo.name,
562
563 errorNotifier: () => {
564 // Empty, we don't have a notifier in the embed
565 }
6ec0b75b
C
566 },
567
568 webtorrent: {
569 videoFiles: videoInfo.files
72f611ca 570 },
571
572 pluginsManager: this.pluginsManager
3b6f205c 573 }
2adfc7ea 574
3b6f205c 575 if (this.mode === 'p2p-media-loader') {
09209296
C
576 const hlsPlaylist = videoInfo.streamingPlaylists.find(p => p.type === VideoStreamingPlaylistType.HLS)
577
3b6f205c
C
578 Object.assign(options, {
579 p2pMediaLoader: {
b9da21bd 580 playlistUrl: hlsPlaylist.playlistUrl,
09209296 581 segmentsSha256Url: hlsPlaylist.segmentsSha256Url,
b9da21bd 582 redundancyBaseUrls: hlsPlaylist.redundancies.map(r => r.baseUrl),
09209296 583 trackerAnnounce: videoInfo.trackerUrls,
5a71acd2 584 videoFiles: hlsPlaylist.files
09209296 585 } as P2PMediaLoaderOptions
3b6f205c 586 })
2adfc7ea 587 }
202e7223 588
9df52d66
C
589 this.player = await PeertubePlayerManager.initialize(this.mode, options, (player: videojs.Player) => {
590 this.player = player
591 })
592
2adfc7ea 593 this.player.on('customError', (event: any, data: any) => this.handleError(data.err, serverTranslations))
99941732 594
9df52d66 595 window['videojsPlayer'] = this.player
902aa3a0 596
5efab546
C
597 this.buildCSS()
598
98ab5dc8 599 this.buildDock(videoInfo)
5efab546
C
600
601 this.initializeApi()
3f9c4955
C
602
603 this.removePlaceholder()
5abc96fc
C
604
605 if (this.isPlaylistEmbed()) {
606 await this.buildPlaylistManager()
1a8c2d74 607
4572c3d0 608 this.player.playlist().updateSelected()
1a8c2d74
C
609
610 this.player.on('stopped', () => {
611 this.playNextVideo()
612 })
5abc96fc 613 }
f9562863 614
72f611ca 615 this.pluginsManager.runHook('action:embed.player.loaded', undefined, { player: this.player, videojs, video: videoInfo })
5abc96fc
C
616 }
617
618 private async initCore () {
619 if (this.userTokens) this.setHeadersFromTokens()
620
5abc96fc
C
621 this.translationsPromise = TranslationsManager.getServerTranslations(window.location.origin, navigator.language)
622 this.PeertubePlayerManagerModulePromise = import('../../assets/player/peertube-player-manager')
623
624 let videoId: string
625
626 if (this.isPlaylistEmbed()) {
627 const playlistId = this.getResourceId()
628 const res = await this.loadPlaylist(playlistId)
629 if (!res) return undefined
630
631 this.playlist = await res.playlistResponse.json()
632
633 const playlistElementResult = await res.videosResponse.json()
fb13852d 634 this.playlistElements = await this.loadAllPlaylistVideos(playlistId, playlistElementResult)
5abc96fc 635
2a71d286
C
636 const params = new URL(window.location.toString()).searchParams
637 const playlistPositionParam = this.getParamString(params, 'playlistPosition')
638
639 let position = 1
640
641 if (playlistPositionParam) {
642 position = parseInt(playlistPositionParam + '', 10)
643 }
644
645 this.currentPlaylistElement = this.playlistElements.find(e => e.position === position)
646 if (!this.currentPlaylistElement || !this.currentPlaylistElement.video) {
647 console.error('Current playlist element is not valid.', this.currentPlaylistElement)
648 this.currentPlaylistElement = this.getNextPlaylistElement()
649 }
650
651 if (!this.currentPlaylistElement) {
652 console.error('This playlist does not have any valid element.')
653 const serverTranslations = await this.translationsPromise
654 this.playlistFetchError(serverTranslations)
655 return
656 }
657
5abc96fc
C
658 videoId = this.currentPlaylistElement.video.uuid
659 } else {
660 videoId = this.getResourceId()
661 }
662
4572c3d0 663 return this.loadVideoAndBuildPlayer(videoId)
5efab546
C
664 }
665
666 private handleError (err: Error, translations?: { [ id: string ]: string }) {
e5a818d3 667 if (err.message.includes('from xs param')) {
5efab546 668 this.player.dispose()
5abc96fc 669 this.playerElement = null
5efab546 670 this.displayError('This video is not available because the remote instance is not responding.', translations)
5efab546
C
671 }
672 }
673
98ab5dc8 674 private buildDock (videoInfo: VideoDetails) {
abb3097e 675 if (!this.controls) return
5efab546 676
818c449b
C
677 // On webtorrent fallback, player may have been disposed
678 if (!this.player.player_) return
5efab546 679
abb3097e 680 const title = this.title ? videoInfo.name : undefined
31b6ddf8 681
85302118 682 const description = this.warningTitle && this.p2pEnabled
abb3097e
C
683 ? '<span class="text">' + peertubeTranslate('Watching this video may reveal your IP address to others.') + '</span>'
684 : undefined
685
b9da21bd
C
686 if (title || description) {
687 this.player.dock({
688 title,
689 description
690 })
691 }
5efab546 692 }
16f7022b 693
5efab546
C
694 private buildCSS () {
695 const body = document.getElementById('custom-css')
696
697 if (this.bigPlayBackgroundColor) {
698 body.style.setProperty('--embedBigPlayBackgroundColor', this.bigPlayBackgroundColor)
699 }
700
701 if (this.foregroundColor) {
702 body.style.setProperty('--embedForegroundColor', this.foregroundColor)
703 }
99941732 704 }
6d88de72 705
5efab546
C
706 private async buildCaptions (serverTranslations: any, captionsResponse: Response): Promise<VideoJSCaption[]> {
707 if (captionsResponse.ok) {
9df52d66 708 const { data } = await captionsResponse.json()
5efab546 709
9df52d66 710 return data.map((c: VideoCaption) => ({
5efab546
C
711 label: peertubeTranslate(c.language.label, serverTranslations),
712 language: c.language.id,
713 src: window.location.origin + c.captionPath
714 }))
6d88de72 715 }
5efab546
C
716
717 return []
6d88de72 718 }
3f9c4955
C
719
720 private loadPlaceholder (video: VideoDetails) {
721 const placeholder = this.getPlaceholderElement()
722
723 const url = window.location.origin + video.previewPath
724 placeholder.style.backgroundImage = `url("${url}")`
5abc96fc 725 placeholder.style.display = 'block'
3f9c4955
C
726 }
727
728 private removePlaceholder () {
729 const placeholder = this.getPlaceholderElement()
5abc96fc 730 placeholder.style.display = 'none'
3f9c4955
C
731 }
732
733 private getPlaceholderElement () {
734 return document.getElementById('placeholder-preview')
735 }
a4ff3100
C
736
737 private setHeadersFromTokens () {
738 this.headers.set('Authorization', `${this.userTokens.tokenType} ${this.userTokens.accessToken}`)
739 }
5abc96fc 740
207612df
C
741 private removeTokensFromHeaders () {
742 this.headers.delete('Authorization')
743 }
744
5abc96fc
C
745 private getResourceId () {
746 const urlParts = window.location.pathname.split('/')
9df52d66 747 return urlParts[urlParts.length - 1]
5abc96fc
C
748 }
749
750 private isPlaylistEmbed () {
751 return window.location.pathname.split('/')[1] === 'video-playlists'
752 }
f9562863 753
72f611ca 754 private loadPlugins (translations?: { [ id: string ]: string }) {
755 this.pluginsManager = new PluginsManager({
756 peertubeHelpersFactory: _ => this.buildPeerTubeHelpers(translations)
757 })
f9562863 758
72f611ca 759 this.pluginsManager.loadPluginsList(this.config)
f9562863 760
72f611ca 761 return this.pluginsManager.ensurePluginsAreLoaded('embed')
f9562863
C
762 }
763
764 private buildPeerTubeHelpers (translations?: { [ id: string ]: string }): RegisterClientHelpers {
9df52d66 765 const unimplemented = () => {
f9562863
C
766 throw new Error('This helper is not implemented in embed.')
767 }
768
769 return {
770 getBaseStaticRoute: unimplemented,
9777fe9e 771 getBaseRouterRoute: unimplemented,
d63e6d46 772 getBasePluginClientPath: unimplemented,
9777fe9e 773
f9562863
C
774 getSettings: unimplemented,
775
776 isLoggedIn: unimplemented,
0f319334 777 getAuthHeader: unimplemented,
f9562863
C
778
779 notifier: {
780 info: unimplemented,
781 error: unimplemented,
782 success: unimplemented
783 },
784
785 showModal: unimplemented,
786
5aa7abf1
C
787 getServerConfig: unimplemented,
788
f9562863
C
789 markdownRenderer: {
790 textMarkdownToHTML: unimplemented,
791 enhancedMarkdownToHTML: unimplemented
792 },
793
9df52d66 794 translate: (value: string) => Promise.resolve(peertubeTranslate(value, translations))
f9562863
C
795 }
796 }
a9bfa85d
C
797
798 private isP2PEnabled (video: Video) {
799 const userP2PEnabled = getBoolOrDefault(
800 peertubeLocalStorage.getItem(UserLocalStorageKeys.P2P_ENABLED),
b65de1be 801 this.config.defaults.p2p.embed.enabled
a9bfa85d
C
802 )
803
804 return isP2PEnabled(video, this.config, userP2PEnabled)
805 }
99941732
WL
806}
807
808PeerTubeEmbed.main()
c21a0aa8
C
809 .catch(err => {
810 (window as any).displayIncompatibleBrowser()
811
812 console.error('Cannot init embed.', err)
813 })