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