]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blob - client/src/standalone/videos/embed.ts
Cleanup tokens logic 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 VideoStreamingPlaylistType
13 } from '../../../../shared/models'
14 import { P2PMediaLoaderOptions, PeertubePlayerManagerOptions, PlayerMode } from '../../assets/player/peertube-player-manager'
15 import { VideoJSCaption } from '../../assets/player/peertube-videojs-typings'
16 import { TranslationsManager } from '../../assets/player/translations-manager'
17 import { PeerTubeEmbedApi } from './embed-api'
18
19 type Translations = { [ id: string ]: string }
20
21 export class PeerTubeEmbed {
22 videoElement: HTMLVideoElement
23 player: videojs.Player
24 api: PeerTubeEmbedApi = null
25 autoplay: boolean
26 controls: boolean
27 muted: boolean
28 loop: boolean
29 subtitle: string
30 enableApi = false
31 startTime: number | string = 0
32 stopTime: number | string
33
34 title: boolean
35 warningTitle: boolean
36 peertubeLink: boolean
37 bigPlayBackgroundColor: string
38 foregroundColor: string
39
40 mode: PlayerMode
41 scope = 'peertube'
42
43 userTokens: Tokens
44 headers = new Headers()
45 LOCAL_STORAGE_OAUTH_CLIENT_KEYS = {
46 CLIENT_ID: 'client_id',
47 CLIENT_SECRET: 'client_secret'
48 }
49
50 static async main () {
51 const videoContainerId = 'video-container'
52 const embed = new PeerTubeEmbed(videoContainerId)
53 await embed.init()
54 }
55
56 constructor (private videoContainerId: string) {
57 this.videoElement = document.getElementById(videoContainerId) as HTMLVideoElement
58 }
59
60 getVideoUrl (id: string) {
61 return window.location.origin + '/api/v1/videos/' + id
62 }
63
64 refreshFetch (url: string, options?: Object) {
65 return fetch(url, options)
66 .then((res: Response) => {
67 if (res.status !== 401) return res
68
69 // 401 unauthorized is not catch-ed, but then-ed
70 const error = res
71
72 const refreshingTokenPromise = new Promise((resolve, reject) => {
73 const clientId: string = peertubeLocalStorage.getItem(this.LOCAL_STORAGE_OAUTH_CLIENT_KEYS.CLIENT_ID)
74 const clientSecret: string = peertubeLocalStorage.getItem(this.LOCAL_STORAGE_OAUTH_CLIENT_KEYS.CLIENT_SECRET)
75 const headers = new Headers()
76 headers.set('Content-Type', 'application/x-www-form-urlencoded')
77 const data = {
78 refresh_token: this.userTokens.refreshToken,
79 client_id: clientId,
80 client_secret: clientSecret,
81 response_type: 'code',
82 grant_type: 'refresh_token'
83 }
84
85 fetch('/api/v1/users/token', {
86 headers,
87 method: 'POST',
88 body: objectToUrlEncoded(data)
89 })
90 .then(res => res.json())
91 .then((obj: UserRefreshToken) => {
92 this.userTokens.accessToken = obj.access_token
93 this.userTokens.refreshToken = obj.refresh_token
94 this.userTokens.save()
95
96 this.setHeadersFromTokens()
97
98 resolve()
99 })
100 .catch((refreshTokenError: any) => {
101 reject(refreshTokenError)
102 })
103 })
104
105 return refreshingTokenPromise
106 .catch(() => {
107 // If refreshing fails, continue with original error
108 throw error
109 })
110 .then(() => fetch(url, {
111 ...options,
112 headers: this.headers
113 }))
114 })
115 }
116
117 loadVideoInfo (videoId: string): Promise<Response> {
118 return this.refreshFetch(this.getVideoUrl(videoId), { headers: this.headers })
119 }
120
121 loadVideoCaptions (videoId: string): Promise<Response> {
122 return fetch(this.getVideoUrl(videoId) + '/captions')
123 }
124
125 loadConfig (): Promise<Response> {
126 return fetch('/api/v1/config')
127 }
128
129 removeElement (element: HTMLElement) {
130 element.parentElement.removeChild(element)
131 }
132
133 displayError (text: string, translations?: Translations) {
134 // Remove video element
135 if (this.videoElement) this.removeElement(this.videoElement)
136
137 const translatedText = peertubeTranslate(text, translations)
138 const translatedSorry = peertubeTranslate('Sorry', translations)
139
140 document.title = translatedSorry + ' - ' + translatedText
141
142 const errorBlock = document.getElementById('error-block')
143 errorBlock.style.display = 'flex'
144
145 const errorTitle = document.getElementById('error-title')
146 errorTitle.innerHTML = peertubeTranslate('Sorry', translations)
147
148 const errorText = document.getElementById('error-content')
149 errorText.innerHTML = translatedText
150 }
151
152 videoNotFound (translations?: Translations) {
153 const text = 'This video does not exist.'
154 this.displayError(text, translations)
155 }
156
157 videoFetchError (translations?: Translations) {
158 const text = 'We cannot fetch the video. Please try again later.'
159 this.displayError(text, translations)
160 }
161
162 getParamToggle (params: URLSearchParams, name: string, defaultValue?: boolean) {
163 return params.has(name) ? (params.get(name) === '1' || params.get(name) === 'true') : defaultValue
164 }
165
166 getParamString (params: URLSearchParams, name: string, defaultValue?: string) {
167 return params.has(name) ? params.get(name) : defaultValue
168 }
169
170 async init () {
171 try {
172 this.userTokens = Tokens.load()
173 await this.initCore()
174 } catch (e) {
175 console.error(e)
176 }
177 }
178
179 private initializeApi () {
180 if (!this.enableApi) return
181
182 this.api = new PeerTubeEmbedApi(this)
183 this.api.initialize()
184 }
185
186 private loadParams (video: VideoDetails) {
187 try {
188 const params = new URL(window.location.toString()).searchParams
189
190 this.autoplay = this.getParamToggle(params, 'autoplay', false)
191 this.controls = this.getParamToggle(params, 'controls', true)
192 this.muted = this.getParamToggle(params, 'muted', undefined)
193 this.loop = this.getParamToggle(params, 'loop', false)
194 this.title = this.getParamToggle(params, 'title', true)
195 this.enableApi = this.getParamToggle(params, 'api', this.enableApi)
196 this.warningTitle = this.getParamToggle(params, 'warningTitle', true)
197 this.peertubeLink = this.getParamToggle(params, 'peertubeLink', true)
198
199 this.scope = this.getParamString(params, 'scope', this.scope)
200 this.subtitle = this.getParamString(params, 'subtitle')
201 this.startTime = this.getParamString(params, 'start')
202 this.stopTime = this.getParamString(params, 'stop')
203
204 this.bigPlayBackgroundColor = this.getParamString(params, 'bigPlayBackgroundColor')
205 this.foregroundColor = this.getParamString(params, 'foregroundColor')
206
207 const modeParam = this.getParamString(params, 'mode')
208
209 if (modeParam) {
210 if (modeParam === 'p2p-media-loader') this.mode = 'p2p-media-loader'
211 else this.mode = 'webtorrent'
212 } else {
213 if (Array.isArray(video.streamingPlaylists) && video.streamingPlaylists.length !== 0) this.mode = 'p2p-media-loader'
214 else this.mode = 'webtorrent'
215 }
216 } catch (err) {
217 console.error('Cannot get params from URL.', err)
218 }
219 }
220
221 private async initCore () {
222 const urlParts = window.location.pathname.split('/')
223 const videoId = urlParts[ urlParts.length - 1 ]
224
225 if (this.userTokens) this.setHeadersFromTokens()
226
227 const videoPromise = this.loadVideoInfo(videoId)
228 const captionsPromise = this.loadVideoCaptions(videoId)
229 const configPromise = this.loadConfig()
230
231 const translationsPromise = TranslationsManager.getServerTranslations(window.location.origin, navigator.language)
232 const videoResponse = await videoPromise
233
234 if (!videoResponse.ok) {
235 const serverTranslations = await translationsPromise
236
237 if (videoResponse.status === 404) return this.videoNotFound(serverTranslations)
238
239 return this.videoFetchError(serverTranslations)
240 }
241
242 const videoInfo: VideoDetails = await videoResponse.json()
243 this.loadPlaceholder(videoInfo)
244
245 const PeertubePlayerManagerModulePromise = import('../../assets/player/peertube-player-manager')
246
247 const promises = [ translationsPromise, captionsPromise, configPromise, PeertubePlayerManagerModulePromise ]
248 const [ serverTranslations, captionsResponse, configResponse, PeertubePlayerManagerModule ] = await Promise.all(promises)
249
250 const PeertubePlayerManager = PeertubePlayerManagerModule.PeertubePlayerManager
251 const videoCaptions = await this.buildCaptions(serverTranslations, captionsResponse)
252
253 this.loadParams(videoInfo)
254
255 const options: PeertubePlayerManagerOptions = {
256 common: {
257 autoplay: this.autoplay,
258 controls: this.controls,
259 muted: this.muted,
260 loop: this.loop,
261 captions: videoCaptions.length !== 0,
262 startTime: this.startTime,
263 stopTime: this.stopTime,
264 subtitle: this.subtitle,
265
266 videoCaptions,
267 inactivityTimeout: 2500,
268 videoViewUrl: this.getVideoUrl(videoId) + '/views',
269
270 playerElement: this.videoElement,
271 onPlayerElementChange: (element: HTMLVideoElement) => this.videoElement = element,
272
273 videoDuration: videoInfo.duration,
274 enableHotkeys: true,
275 peertubeLink: this.peertubeLink,
276 poster: window.location.origin + videoInfo.previewPath,
277 theaterButton: false,
278
279 serverUrl: window.location.origin,
280 language: navigator.language,
281 embedUrl: window.location.origin + videoInfo.embedPath
282 },
283
284 webtorrent: {
285 videoFiles: videoInfo.files
286 }
287 }
288
289 if (this.mode === 'p2p-media-loader') {
290 const hlsPlaylist = videoInfo.streamingPlaylists.find(p => p.type === VideoStreamingPlaylistType.HLS)
291
292 Object.assign(options, {
293 p2pMediaLoader: {
294 playlistUrl: hlsPlaylist.playlistUrl,
295 segmentsSha256Url: hlsPlaylist.segmentsSha256Url,
296 redundancyBaseUrls: hlsPlaylist.redundancies.map(r => r.baseUrl),
297 trackerAnnounce: videoInfo.trackerUrls,
298 videoFiles: hlsPlaylist.files
299 } as P2PMediaLoaderOptions
300 })
301 }
302
303 this.player = await PeertubePlayerManager.initialize(this.mode, options, (player: videojs.Player) => this.player = player)
304 this.player.on('customError', (event: any, data: any) => this.handleError(data.err, serverTranslations))
305
306 window[ 'videojsPlayer' ] = this.player
307
308 this.buildCSS()
309
310 await this.buildDock(videoInfo, configResponse)
311
312 this.initializeApi()
313
314 this.removePlaceholder()
315 }
316
317 private handleError (err: Error, translations?: { [ id: string ]: string }) {
318 if (err.message.indexOf('from xs param') !== -1) {
319 this.player.dispose()
320 this.videoElement = null
321 this.displayError('This video is not available because the remote instance is not responding.', translations)
322 return
323 }
324 }
325
326 private async buildDock (videoInfo: VideoDetails, configResponse: Response) {
327 if (!this.controls) return
328
329 // On webtorrent fallback, player may have been disposed
330 if (!this.player.player_) return
331
332 const title = this.title ? videoInfo.name : undefined
333
334 const config: ServerConfig = await configResponse.json()
335 const description = config.tracker.enabled && this.warningTitle
336 ? '<span class="text">' + peertubeTranslate('Watching this video may reveal your IP address to others.') + '</span>'
337 : undefined
338
339 this.player.dock({
340 title,
341 description
342 })
343 }
344
345 private buildCSS () {
346 const body = document.getElementById('custom-css')
347
348 if (this.bigPlayBackgroundColor) {
349 body.style.setProperty('--embedBigPlayBackgroundColor', this.bigPlayBackgroundColor)
350 }
351
352 if (this.foregroundColor) {
353 body.style.setProperty('--embedForegroundColor', this.foregroundColor)
354 }
355 }
356
357 private async buildCaptions (serverTranslations: any, captionsResponse: Response): Promise<VideoJSCaption[]> {
358 if (captionsResponse.ok) {
359 const { data } = (await captionsResponse.json()) as ResultList<VideoCaption>
360
361 return data.map(c => ({
362 label: peertubeTranslate(c.language.label, serverTranslations),
363 language: c.language.id,
364 src: window.location.origin + c.captionPath
365 }))
366 }
367
368 return []
369 }
370
371 private loadPlaceholder (video: VideoDetails) {
372 const placeholder = this.getPlaceholderElement()
373
374 const url = window.location.origin + video.previewPath
375 placeholder.style.backgroundImage = `url("${url}")`
376 }
377
378 private removePlaceholder () {
379 const placeholder = this.getPlaceholderElement()
380 placeholder.parentElement.removeChild(placeholder)
381 }
382
383 private getPlaceholderElement () {
384 return document.getElementById('placeholder-preview')
385 }
386
387 private setHeadersFromTokens () {
388 this.headers.set('Authorization', `${this.userTokens.tokenType} ${this.userTokens.accessToken}`)
389 }
390 }
391
392 PeerTubeEmbed.main()
393 .catch(err => console.error('Cannot init embed.', err))