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