]>
Commit | Line | Data |
---|---|---|
202e7223 | 1 | import './embed.scss' |
583eb04b C |
2 | import videojs from 'video.js' |
3 | import { objectToUrlEncoded, peertubeLocalStorage, PureAuthUser } from '@root-helpers/index' | |
bd45d503 | 4 | import { peertubeTranslate } from '../../../../shared/core-utils/i18n' |
3f9c4955 | 5 | import { |
3f9c4955 C |
6 | ResultList, |
7 | ServerConfig, | |
583eb04b C |
8 | UserRefreshToken, |
9 | VideoCaption, | |
4504f09f | 10 | VideoDetails, |
583eb04b C |
11 | VideoStreamingPlaylistType |
12 | } from '../../../../shared/models' | |
13 | import { P2PMediaLoaderOptions, PeertubePlayerManagerOptions, PlayerMode } from '../../assets/player/peertube-player-manager' | |
abb3097e | 14 | import { VideoJSCaption } from '../../assets/player/peertube-videojs-typings' |
583eb04b C |
15 | import { TranslationsManager } from '../../assets/player/translations-manager' |
16 | import { PeerTubeEmbedApi } from './embed-api' | |
abb3097e C |
17 | |
18 | type Translations = { [ id: string ]: string } | |
202e7223 | 19 | |
5efab546 | 20 | export class PeerTubeEmbed { |
902aa3a0 | 21 | videoElement: HTMLVideoElement |
7e37e111 | 22 | player: videojs.Player |
902aa3a0 | 23 | api: PeerTubeEmbedApi = null |
3b019808 C |
24 | autoplay: boolean |
25 | controls: boolean | |
26 | muted: boolean | |
27 | loop: boolean | |
28 | subtitle: string | |
902aa3a0 | 29 | enableApi = false |
1f6824c9 | 30 | startTime: number | string = 0 |
f0a39880 | 31 | stopTime: number | string |
5efab546 C |
32 | |
33 | title: boolean | |
34 | warningTitle: boolean | |
08d9ba0f | 35 | peertubeLink: boolean |
5efab546 C |
36 | bigPlayBackgroundColor: string |
37 | foregroundColor: string | |
38 | ||
3b6f205c | 39 | mode: PlayerMode |
902aa3a0 C |
40 | scope = 'peertube' |
41 | ||
4504f09f | 42 | user: PureAuthUser |
71ab65d0 | 43 | headers = new Headers() |
4504f09f RK |
44 | LOCAL_STORAGE_OAUTH_CLIENT_KEYS = { |
45 | CLIENT_ID: 'client_id', | |
46 | CLIENT_SECRET: 'client_secret' | |
47 | } | |
71ab65d0 | 48 | |
902aa3a0 | 49 | static async main () { |
c6352f2c | 50 | const videoContainerId = 'video-container' |
99941732 WL |
51 | const embed = new PeerTubeEmbed(videoContainerId) |
52 | await embed.init() | |
53 | } | |
902aa3a0 C |
54 | |
55 | constructor (private videoContainerId: string) { | |
56 | this.videoElement = document.getElementById(videoContainerId) as HTMLVideoElement | |
57 | } | |
58 | ||
99941732 WL |
59 | getVideoUrl (id: string) { |
60 | return window.location.origin + '/api/v1/videos/' + id | |
61 | } | |
d4f3fea6 | 62 | |
4504f09f RK |
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 | ||
99941732 | 113 | loadVideoInfo (videoId: string): Promise<Response> { |
4504f09f | 114 | return this.refreshFetch(this.getVideoUrl(videoId), { headers: this.headers }) |
99941732 | 115 | } |
d4f3fea6 | 116 | |
16f7022b | 117 | loadVideoCaptions (videoId: string): Promise<Response> { |
4504f09f | 118 | return fetch(this.getVideoUrl(videoId) + '/captions') |
16f7022b C |
119 | } |
120 | ||
31b6ddf8 C |
121 | loadConfig (): Promise<Response> { |
122 | return fetch('/api/v1/config') | |
123 | } | |
124 | ||
99941732 WL |
125 | removeElement (element: HTMLElement) { |
126 | element.parentElement.removeChild(element) | |
127 | } | |
d4f3fea6 | 128 | |
abb3097e | 129 | displayError (text: string, translations?: Translations) { |
99941732 | 130 | // Remove video element |
6d88de72 | 131 | if (this.videoElement) this.removeElement(this.videoElement) |
99941732 | 132 | |
ad3fa0c5 C |
133 | const translatedText = peertubeTranslate(text, translations) |
134 | const translatedSorry = peertubeTranslate('Sorry', translations) | |
135 | ||
136 | document.title = translatedSorry + ' - ' + translatedText | |
99941732 WL |
137 | |
138 | const errorBlock = document.getElementById('error-block') | |
139 | errorBlock.style.display = 'flex' | |
140 | ||
ad3fa0c5 C |
141 | const errorTitle = document.getElementById('error-title') |
142 | errorTitle.innerHTML = peertubeTranslate('Sorry', translations) | |
143 | ||
99941732 | 144 | const errorText = document.getElementById('error-content') |
ad3fa0c5 | 145 | errorText.innerHTML = translatedText |
99941732 WL |
146 | } |
147 | ||
abb3097e | 148 | videoNotFound (translations?: Translations) { |
99941732 | 149 | const text = 'This video does not exist.' |
ad3fa0c5 | 150 | this.displayError(text, translations) |
99941732 WL |
151 | } |
152 | ||
abb3097e | 153 | videoFetchError (translations?: Translations) { |
99941732 | 154 | const text = 'We cannot fetch the video. Please try again later.' |
ad3fa0c5 | 155 | this.displayError(text, translations) |
99941732 WL |
156 | } |
157 | ||
3b019808 | 158 | getParamToggle (params: URLSearchParams, name: string, defaultValue?: boolean) { |
99941732 WL |
159 | return params.has(name) ? (params.get(name) === '1' || params.get(name) === 'true') : defaultValue |
160 | } | |
d4f3fea6 | 161 | |
3b019808 | 162 | getParamString (params: URLSearchParams, name: string, defaultValue?: string) { |
99941732 WL |
163 | return params.has(name) ? params.get(name) : defaultValue |
164 | } | |
da99ccf2 | 165 | |
902aa3a0 | 166 | async init () { |
99941732 | 167 | try { |
4504f09f | 168 | this.user = PureAuthUser.load() |
99941732 WL |
169 | await this.initCore() |
170 | } catch (e) { | |
171 | console.error(e) | |
172 | } | |
173 | } | |
174 | ||
902aa3a0 C |
175 | private initializeApi () { |
176 | if (!this.enableApi) return | |
177 | ||
178 | this.api = new PeerTubeEmbedApi(this) | |
179 | this.api.initialize() | |
180 | } | |
181 | ||
0f2f274c | 182 | private loadParams (video: VideoDetails) { |
da99ccf2 | 183 | try { |
c4710631 | 184 | const params = new URL(window.location.toString()).searchParams |
99941732 | 185 | |
31b6ddf8 C |
186 | this.autoplay = this.getParamToggle(params, 'autoplay', false) |
187 | this.controls = this.getParamToggle(params, 'controls', true) | |
64645512 | 188 | this.muted = this.getParamToggle(params, 'muted', undefined) |
31b6ddf8 | 189 | this.loop = this.getParamToggle(params, 'loop', false) |
5efab546 | 190 | this.title = this.getParamToggle(params, 'title', true) |
99941732 | 191 | this.enableApi = this.getParamToggle(params, 'api', this.enableApi) |
5efab546 | 192 | this.warningTitle = this.getParamToggle(params, 'warningTitle', true) |
08d9ba0f | 193 | this.peertubeLink = this.getParamToggle(params, 'peertubeLink', true) |
f37bad63 | 194 | |
3b019808 C |
195 | this.scope = this.getParamString(params, 'scope', this.scope) |
196 | this.subtitle = this.getParamString(params, 'subtitle') | |
197 | this.startTime = this.getParamString(params, 'start') | |
f0a39880 | 198 | this.stopTime = this.getParamString(params, 'stop') |
3b6f205c | 199 | |
5efab546 C |
200 | this.bigPlayBackgroundColor = this.getParamString(params, 'bigPlayBackgroundColor') |
201 | this.foregroundColor = this.getParamString(params, 'foregroundColor') | |
202 | ||
0f2f274c C |
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 | } | |
da99ccf2 C |
212 | } catch (err) { |
213 | console.error('Cannot get params from URL.', err) | |
214 | } | |
99941732 WL |
215 | } |
216 | ||
902aa3a0 | 217 | private async initCore () { |
6385c0cb C |
218 | const urlParts = window.location.pathname.split('/') |
219 | const videoId = urlParts[ urlParts.length - 1 ] | |
99941732 | 220 | |
71ab65d0 RK |
221 | if (this.user) { |
222 | this.headers.set('Authorization', `${this.user.getTokenType()} ${this.user.getAccessToken()}`) | |
223 | } | |
224 | ||
3f9c4955 C |
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 | |
99941732 | 231 | |
16f7022b | 232 | if (!videoResponse.ok) { |
3f9c4955 C |
233 | const serverTranslations = await translationsPromise |
234 | ||
ad3fa0c5 | 235 | if (videoResponse.status === 404) return this.videoNotFound(serverTranslations) |
99941732 | 236 | |
ad3fa0c5 | 237 | return this.videoFetchError(serverTranslations) |
99941732 WL |
238 | } |
239 | ||
16f7022b | 240 | const videoInfo: VideoDetails = await videoResponse.json() |
3f9c4955 C |
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 | |
5efab546 | 249 | const videoCaptions = await this.buildCaptions(serverTranslations, captionsResponse) |
99941732 | 250 | |
0f2f274c | 251 | this.loadParams(videoInfo) |
da99ccf2 | 252 | |
2adfc7ea C |
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, | |
f0a39880 | 261 | stopTime: this.stopTime, |
2adfc7ea C |
262 | subtitle: this.subtitle, |
263 | ||
264 | videoCaptions, | |
35f0a5e6 | 265 | inactivityTimeout: 2500, |
2adfc7ea | 266 | videoViewUrl: this.getVideoUrl(videoId) + '/views', |
6ec0b75b | 267 | |
2adfc7ea | 268 | playerElement: this.videoElement, |
6ec0b75b C |
269 | onPlayerElementChange: (element: HTMLVideoElement) => this.videoElement = element, |
270 | ||
2adfc7ea C |
271 | videoDuration: videoInfo.duration, |
272 | enableHotkeys: true, | |
08d9ba0f | 273 | peertubeLink: this.peertubeLink, |
2adfc7ea | 274 | poster: window.location.origin + videoInfo.previewPath, |
3d9a63d3 | 275 | theaterButton: false, |
2adfc7ea C |
276 | |
277 | serverUrl: window.location.origin, | |
278 | language: navigator.language, | |
279 | embedUrl: window.location.origin + videoInfo.embedPath | |
6ec0b75b C |
280 | }, |
281 | ||
282 | webtorrent: { | |
283 | videoFiles: videoInfo.files | |
2adfc7ea | 284 | } |
3b6f205c | 285 | } |
2adfc7ea | 286 | |
3b6f205c | 287 | if (this.mode === 'p2p-media-loader') { |
09209296 C |
288 | const hlsPlaylist = videoInfo.streamingPlaylists.find(p => p.type === VideoStreamingPlaylistType.HLS) |
289 | ||
3b6f205c C |
290 | Object.assign(options, { |
291 | p2pMediaLoader: { | |
09209296 C |
292 | playlistUrl: hlsPlaylist.playlistUrl, |
293 | segmentsSha256Url: hlsPlaylist.segmentsSha256Url, | |
294 | redundancyBaseUrls: hlsPlaylist.redundancies.map(r => r.baseUrl), | |
295 | trackerAnnounce: videoInfo.trackerUrls, | |
5a71acd2 | 296 | videoFiles: hlsPlaylist.files |
09209296 | 297 | } as P2PMediaLoaderOptions |
3b6f205c | 298 | }) |
2adfc7ea | 299 | } |
202e7223 | 300 | |
7e37e111 | 301 | this.player = await PeertubePlayerManager.initialize(this.mode, options, (player: videojs.Player) => this.player = player) |
2adfc7ea | 302 | this.player.on('customError', (event: any, data: any) => this.handleError(data.err, serverTranslations)) |
99941732 | 303 | |
2adfc7ea | 304 | window[ 'videojsPlayer' ] = this.player |
902aa3a0 | 305 | |
5efab546 C |
306 | this.buildCSS() |
307 | ||
308 | await this.buildDock(videoInfo, configResponse) | |
309 | ||
310 | this.initializeApi() | |
3f9c4955 C |
311 | |
312 | this.removePlaceholder() | |
5efab546 C |
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) { | |
abb3097e | 325 | if (!this.controls) return |
5efab546 | 326 | |
818c449b C |
327 | // On webtorrent fallback, player may have been disposed |
328 | if (!this.player.player_) return | |
5efab546 | 329 | |
abb3097e | 330 | const title = this.title ? videoInfo.name : undefined |
31b6ddf8 | 331 | |
abb3097e C |
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 | }) | |
5efab546 | 341 | } |
16f7022b | 342 | |
5efab546 C |
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 | } | |
99941732 | 353 | } |
6d88de72 | 354 | |
5efab546 C |
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 | })) | |
6d88de72 | 364 | } |
5efab546 C |
365 | |
366 | return [] | |
6d88de72 | 367 | } |
3f9c4955 C |
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 | } | |
99941732 WL |
384 | } |
385 | ||
386 | PeerTubeEmbed.main() | |
902aa3a0 | 387 | .catch(err => console.error('Cannot init embed.', err)) |