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