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