]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blame - client/src/standalone/videos/embed.ts
Use random port for mock servers in tests
[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
C
6 ClientHookName,
7 HTMLServerConfig,
e030bfb5 8 OAuth2ErrorCode,
aea0b0e7 9 PluginType,
3f9c4955 10 ResultList,
583eb04b
C
11 UserRefreshToken,
12 VideoCaption,
4504f09f 13 VideoDetails,
5abc96fc
C
14 VideoPlaylist,
15 VideoPlaylistElement,
aea0b0e7 16 VideoStreamingPlaylistType
583eb04b
C
17} from '../../../../shared/models'
18import { P2PMediaLoaderOptions, PeertubePlayerManagerOptions, PlayerMode } from '../../assets/player/peertube-player-manager'
abb3097e 19import { VideoJSCaption } from '../../assets/player/peertube-videojs-typings'
583eb04b 20import { TranslationsManager } from '../../assets/player/translations-manager'
aea0b0e7 21import { peertubeLocalStorage } from '../../root-helpers/peertube-web-storage'
f9562863
C
22import { Hooks, loadPlugin, runHook } from '../../root-helpers/plugins'
23import { Tokens } from '../../root-helpers/users'
f9562863 24import { objectToUrlEncoded } from '../../root-helpers/utils'
f9562863 25import { RegisterClientHelpers } from '../../types/register-client-option.model'
aea0b0e7 26import { PeerTubeEmbedApi } from './embed-api'
abb3097e
C
27
28type Translations = { [ id: string ]: string }
202e7223 29
5efab546 30export class PeerTubeEmbed {
5abc96fc 31 playerElement: HTMLVideoElement
7e37e111 32 player: videojs.Player
902aa3a0 33 api: PeerTubeEmbedApi = null
5abc96fc 34
3b019808
C
35 autoplay: boolean
36 controls: boolean
37 muted: boolean
38 loop: boolean
39 subtitle: string
902aa3a0 40 enableApi = false
1f6824c9 41 startTime: number | string = 0
f0a39880 42 stopTime: number | string
5efab546
C
43
44 title: boolean
45 warningTitle: boolean
08d9ba0f 46 peertubeLink: boolean
5efab546
C
47 bigPlayBackgroundColor: string
48 foregroundColor: string
49
3b6f205c 50 mode: PlayerMode
902aa3a0
C
51 scope = 'peertube'
52
a4ff3100 53 userTokens: Tokens
71ab65d0 54 headers = new Headers()
4504f09f
RK
55 LOCAL_STORAGE_OAUTH_CLIENT_KEYS = {
56 CLIENT_ID: 'client_id',
57 CLIENT_SECRET: 'client_secret'
58 }
71ab65d0 59
aea0b0e7
C
60 config: HTMLServerConfig
61
5abc96fc 62 private translationsPromise: Promise<{ [id: string]: string }>
5abc96fc
C
63 private PeertubePlayerManagerModulePromise: Promise<any>
64
65 private playlist: VideoPlaylist
66 private playlistElements: VideoPlaylistElement[]
67 private currentPlaylistElement: VideoPlaylistElement
68
69 private wrapperElement: HTMLElement
70
f9562863
C
71 private peertubeHooks: Hooks = {}
72 private loadedScripts = new Set<string>()
73
902aa3a0 74 static async main () {
5abc96fc 75 const videoContainerId = 'video-wrapper'
99941732
WL
76 const embed = new PeerTubeEmbed(videoContainerId)
77 await embed.init()
78 }
902aa3a0 79
5abc96fc
C
80 constructor (private videoWrapperId: string) {
81 this.wrapperElement = document.getElementById(this.videoWrapperId)
aea0b0e7
C
82
83 try {
84 this.config = JSON.parse(window['PeerTubeServerConfig'])
85 } catch (err) {
86 console.error('Cannot parse HTML config.', err)
87 }
902aa3a0
C
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) {
496d784d
C
124 Tokens.flush()
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
132 this.userTokens.save()
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
C
143 .catch(() => {
144 Tokens.flush()
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 () {
99941732 264 try {
a4ff3100 265 this.userTokens = Tokens.load()
99941732
WL
266 await this.initCore()
267 } catch (e) {
268 console.error(e)
269 }
270 }
271
902aa3a0
C
272 private initializeApi () {
273 if (!this.enableApi) return
274
275 this.api = new PeerTubeEmbedApi(this)
276 this.api.initialize()
277 }
278
0f2f274c 279 private loadParams (video: VideoDetails) {
da99ccf2 280 try {
c4710631 281 const params = new URL(window.location.toString()).searchParams
99941732 282
31b6ddf8
C
283 this.autoplay = this.getParamToggle(params, 'autoplay', false)
284 this.controls = this.getParamToggle(params, 'controls', true)
64645512 285 this.muted = this.getParamToggle(params, 'muted', undefined)
31b6ddf8 286 this.loop = this.getParamToggle(params, 'loop', false)
5efab546 287 this.title = this.getParamToggle(params, 'title', true)
99941732 288 this.enableApi = this.getParamToggle(params, 'api', this.enableApi)
5efab546 289 this.warningTitle = this.getParamToggle(params, 'warningTitle', true)
08d9ba0f 290 this.peertubeLink = this.getParamToggle(params, 'peertubeLink', true)
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
322 const json = await result.json() as ResultList<VideoPlaylistElement>
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')
475 .then(res => res.json())
476 }
477
5abc96fc
C
478 const videoInfoPromise = videoResponse.json()
479 .then((videoInfo: VideoDetails) => {
480 if (!alreadyHadPlayer) this.loadPlaceholder(videoInfo)
481
482 return videoInfo
483 })
484
aea0b0e7 485 const [ videoInfoTmp, serverTranslations, captionsResponse, PeertubePlayerManagerModule ] = await Promise.all([
5abc96fc
C
486 videoInfoPromise,
487 this.translationsPromise,
488 captionsPromise,
5abc96fc
C
489 this.PeertubePlayerManagerModulePromise
490 ])
3f9c4955 491
aea0b0e7 492 await this.ensurePluginsAreLoaded(serverTranslations)
f9562863 493
6fad8e51
C
494 const videoInfo: VideoDetails = videoInfoTmp
495
3f9c4955 496 const PeertubePlayerManager = PeertubePlayerManagerModule.PeertubePlayerManager
5efab546 497 const videoCaptions = await this.buildCaptions(serverTranslations, captionsResponse)
99941732 498
0f2f274c 499 this.loadParams(videoInfo)
da99ccf2 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)
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
2adfc7ea 525 captions: videoCaptions.length !== 0,
2adfc7ea
C
526 subtitle: this.subtitle,
527
1a8c2d74
C
528 startTime: this.playlist ? this.currentPlaylistElement.startTimestamp : this.startTime,
529 stopTime: this.playlist ? this.currentPlaylistElement.stopTimestamp : this.stopTime,
530
a950e4c8
C
531 nextVideo: this.playlist ? () => this.playNextVideo() : undefined,
532 hasNextVideo: this.playlist ? () => !!this.getNextPlaylistElement() : undefined,
533
534 previousVideo: this.playlist ? () => this.playPreviousVideo() : undefined,
535 hasPreviousVideo: this.playlist ? () => !!this.getPreviousPlaylistElement() : undefined,
536
4572c3d0 537 playlist: playlistPlugin,
5abc96fc 538
2adfc7ea 539 videoCaptions,
35f0a5e6 540 inactivityTimeout: 2500,
5abc96fc 541 videoViewUrl: this.getVideoUrl(videoInfo.uuid) + '/views',
58b9ce30 542 videoUUID: videoInfo.uuid,
6ec0b75b 543
25b7c847
C
544 isLive: videoInfo.isLive,
545
5abc96fc
C
546 playerElement: this.playerElement,
547 onPlayerElementChange: (element: HTMLVideoElement) => this.playerElement = element,
6ec0b75b 548
2adfc7ea
C
549 videoDuration: videoInfo.duration,
550 enableHotkeys: true,
08d9ba0f 551 peertubeLink: this.peertubeLink,
2adfc7ea 552 poster: window.location.origin + videoInfo.previewPath,
3d9a63d3 553 theaterButton: false,
2adfc7ea
C
554
555 serverUrl: window.location.origin,
556 language: navigator.language,
4097c6d6
TP
557 embedUrl: window.location.origin + videoInfo.embedPath,
558 embedTitle: videoInfo.name
6ec0b75b
C
559 },
560
561 webtorrent: {
562 videoFiles: videoInfo.files
2adfc7ea 563 }
3b6f205c 564 }
2adfc7ea 565
3b6f205c 566 if (this.mode === 'p2p-media-loader') {
09209296
C
567 const hlsPlaylist = videoInfo.streamingPlaylists.find(p => p.type === VideoStreamingPlaylistType.HLS)
568
3b6f205c
C
569 Object.assign(options, {
570 p2pMediaLoader: {
b9da21bd 571 playlistUrl: hlsPlaylist.playlistUrl,
09209296 572 segmentsSha256Url: hlsPlaylist.segmentsSha256Url,
b9da21bd 573 redundancyBaseUrls: hlsPlaylist.redundancies.map(r => r.baseUrl),
09209296 574 trackerAnnounce: videoInfo.trackerUrls,
5a71acd2 575 videoFiles: hlsPlaylist.files
09209296 576 } as P2PMediaLoaderOptions
3b6f205c 577 })
2adfc7ea 578 }
202e7223 579
7e37e111 580 this.player = await PeertubePlayerManager.initialize(this.mode, options, (player: videojs.Player) => this.player = player)
2adfc7ea 581 this.player.on('customError', (event: any, data: any) => this.handleError(data.err, serverTranslations))
99941732 582
2adfc7ea 583 window[ 'videojsPlayer' ] = this.player
902aa3a0 584
5efab546
C
585 this.buildCSS()
586
aea0b0e7 587 await this.buildDock(videoInfo)
5efab546
C
588
589 this.initializeApi()
3f9c4955
C
590
591 this.removePlaceholder()
5abc96fc
C
592
593 if (this.isPlaylistEmbed()) {
594 await this.buildPlaylistManager()
1a8c2d74 595
4572c3d0 596 this.player.playlist().updateSelected()
1a8c2d74
C
597
598 this.player.on('stopped', () => {
599 this.playNextVideo()
600 })
5abc96fc 601 }
f9562863 602
781ba981 603 this.runHook('action:embed.player.loaded', undefined, { player: this.player, videojs, video: videoInfo })
5abc96fc
C
604 }
605
606 private async initCore () {
607 if (this.userTokens) this.setHeadersFromTokens()
608
5abc96fc
C
609 this.translationsPromise = TranslationsManager.getServerTranslations(window.location.origin, navigator.language)
610 this.PeertubePlayerManagerModulePromise = import('../../assets/player/peertube-player-manager')
611
612 let videoId: string
613
614 if (this.isPlaylistEmbed()) {
615 const playlistId = this.getResourceId()
616 const res = await this.loadPlaylist(playlistId)
617 if (!res) return undefined
618
619 this.playlist = await res.playlistResponse.json()
620
621 const playlistElementResult = await res.videosResponse.json()
fb13852d 622 this.playlistElements = await this.loadAllPlaylistVideos(playlistId, playlistElementResult)
5abc96fc 623
2a71d286
C
624 const params = new URL(window.location.toString()).searchParams
625 const playlistPositionParam = this.getParamString(params, 'playlistPosition')
626
627 let position = 1
628
629 if (playlistPositionParam) {
630 position = parseInt(playlistPositionParam + '', 10)
631 }
632
633 this.currentPlaylistElement = this.playlistElements.find(e => e.position === position)
634 if (!this.currentPlaylistElement || !this.currentPlaylistElement.video) {
635 console.error('Current playlist element is not valid.', this.currentPlaylistElement)
636 this.currentPlaylistElement = this.getNextPlaylistElement()
637 }
638
639 if (!this.currentPlaylistElement) {
640 console.error('This playlist does not have any valid element.')
641 const serverTranslations = await this.translationsPromise
642 this.playlistFetchError(serverTranslations)
643 return
644 }
645
5abc96fc
C
646 videoId = this.currentPlaylistElement.video.uuid
647 } else {
648 videoId = this.getResourceId()
649 }
650
4572c3d0 651 return this.loadVideoAndBuildPlayer(videoId)
5efab546
C
652 }
653
654 private handleError (err: Error, translations?: { [ id: string ]: string }) {
655 if (err.message.indexOf('from xs param') !== -1) {
656 this.player.dispose()
5abc96fc 657 this.playerElement = null
5efab546
C
658 this.displayError('This video is not available because the remote instance is not responding.', translations)
659 return
660 }
661 }
662
aea0b0e7 663 private async buildDock (videoInfo: VideoDetails) {
abb3097e 664 if (!this.controls) return
5efab546 665
818c449b
C
666 // On webtorrent fallback, player may have been disposed
667 if (!this.player.player_) return
5efab546 668
abb3097e 669 const title = this.title ? videoInfo.name : undefined
31b6ddf8 670
aea0b0e7 671 const description = this.config.tracker.enabled && this.warningTitle
abb3097e
C
672 ? '<span class="text">' + peertubeTranslate('Watching this video may reveal your IP address to others.') + '</span>'
673 : undefined
674
b9da21bd
C
675 if (title || description) {
676 this.player.dock({
677 title,
678 description
679 })
680 }
5efab546 681 }
16f7022b 682
5efab546
C
683 private buildCSS () {
684 const body = document.getElementById('custom-css')
685
686 if (this.bigPlayBackgroundColor) {
687 body.style.setProperty('--embedBigPlayBackgroundColor', this.bigPlayBackgroundColor)
688 }
689
690 if (this.foregroundColor) {
691 body.style.setProperty('--embedForegroundColor', this.foregroundColor)
692 }
99941732 693 }
6d88de72 694
5efab546
C
695 private async buildCaptions (serverTranslations: any, captionsResponse: Response): Promise<VideoJSCaption[]> {
696 if (captionsResponse.ok) {
697 const { data } = (await captionsResponse.json()) as ResultList<VideoCaption>
698
699 return data.map(c => ({
700 label: peertubeTranslate(c.language.label, serverTranslations),
701 language: c.language.id,
702 src: window.location.origin + c.captionPath
703 }))
6d88de72 704 }
5efab546
C
705
706 return []
6d88de72 707 }
3f9c4955
C
708
709 private loadPlaceholder (video: VideoDetails) {
710 const placeholder = this.getPlaceholderElement()
711
712 const url = window.location.origin + video.previewPath
713 placeholder.style.backgroundImage = `url("${url}")`
5abc96fc 714 placeholder.style.display = 'block'
3f9c4955
C
715 }
716
717 private removePlaceholder () {
718 const placeholder = this.getPlaceholderElement()
5abc96fc 719 placeholder.style.display = 'none'
3f9c4955
C
720 }
721
722 private getPlaceholderElement () {
723 return document.getElementById('placeholder-preview')
724 }
a4ff3100
C
725
726 private setHeadersFromTokens () {
727 this.headers.set('Authorization', `${this.userTokens.tokenType} ${this.userTokens.accessToken}`)
728 }
5abc96fc 729
207612df
C
730 private removeTokensFromHeaders () {
731 this.headers.delete('Authorization')
732 }
733
5abc96fc
C
734 private getResourceId () {
735 const urlParts = window.location.pathname.split('/')
736 return urlParts[ urlParts.length - 1 ]
737 }
738
739 private isPlaylistEmbed () {
740 return window.location.pathname.split('/')[1] === 'video-playlists'
741 }
f9562863 742
aea0b0e7
C
743 private async ensurePluginsAreLoaded (translations?: { [ id: string ]: string }) {
744 if (this.config.plugin.registered.length === 0) return
f9562863 745
aea0b0e7 746 for (const plugin of this.config.plugin.registered) {
f9562863
C
747 for (const key of Object.keys(plugin.clientScripts)) {
748 const clientScript = plugin.clientScripts[key]
749
750 if (clientScript.scopes.includes('embed') === false) continue
751
752 const script = `/plugins/${plugin.name}/${plugin.version}/client-scripts/${clientScript.script}`
753
754 if (this.loadedScripts.has(script)) continue
755
756 const pluginInfo = {
757 plugin,
758 clientScript: {
759 script,
760 scopes: clientScript.scopes
761 },
762 pluginType: PluginType.PLUGIN,
763 isTheme: false
764 }
765
7294aab0
C
766 await loadPlugin({
767 hooks: this.peertubeHooks,
768 pluginInfo,
3c47fa3b 769 onSettingsScripts: () => undefined,
7294aab0
C
770 peertubeHelpersFactory: _ => this.buildPeerTubeHelpers(translations)
771 })
f9562863
C
772 }
773 }
774 }
775
776 private buildPeerTubeHelpers (translations?: { [ id: string ]: string }): RegisterClientHelpers {
777 function unimplemented (): any {
778 throw new Error('This helper is not implemented in embed.')
779 }
780
781 return {
782 getBaseStaticRoute: unimplemented,
783
784 getSettings: unimplemented,
785
786 isLoggedIn: unimplemented,
0f319334 787 getAuthHeader: unimplemented,
f9562863
C
788
789 notifier: {
790 info: unimplemented,
791 error: unimplemented,
792 success: unimplemented
793 },
794
795 showModal: unimplemented,
796
5aa7abf1
C
797 getServerConfig: unimplemented,
798
f9562863
C
799 markdownRenderer: {
800 textMarkdownToHTML: unimplemented,
801 enhancedMarkdownToHTML: unimplemented
802 },
803
804 translate: (value: string) => {
805 return Promise.resolve(peertubeTranslate(value, translations))
806 }
807 }
808 }
809
810 private runHook <T> (hookName: ClientHookName, result?: T, params?: any): Promise<T> {
811 return runHook(this.peertubeHooks, hookName, result, params)
812 }
99941732
WL
813}
814
815PeerTubeEmbed.main()
902aa3a0 816 .catch(err => console.error('Cannot init embed.', err))