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