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