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