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