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