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