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