]>
Commit | Line | Data |
---|---|---|
202e7223 | 1 | import './embed.scss' |
583eb04b | 2 | import videojs from 'video.js' |
a4ff3100 C |
3 | import { objectToUrlEncoded, peertubeLocalStorage } from '@root-helpers/index' |
4 | import { Tokens } from '@root-helpers/users' | |
bd45d503 | 5 | import { peertubeTranslate } from '../../../../shared/core-utils/i18n' |
3f9c4955 | 6 | import { |
3f9c4955 C |
7 | ResultList, |
8 | ServerConfig, | |
583eb04b C |
9 | UserRefreshToken, |
10 | VideoCaption, | |
4504f09f | 11 | VideoDetails, |
5abc96fc C |
12 | VideoPlaylist, |
13 | VideoPlaylistElement, | |
583eb04b C |
14 | VideoStreamingPlaylistType |
15 | } from '../../../../shared/models' | |
16 | import { P2PMediaLoaderOptions, PeertubePlayerManagerOptions, PlayerMode } from '../../assets/player/peertube-player-manager' | |
abb3097e | 17 | import { VideoJSCaption } from '../../assets/player/peertube-videojs-typings' |
583eb04b C |
18 | import { TranslationsManager } from '../../assets/player/translations-manager' |
19 | import { PeerTubeEmbedApi } from './embed-api' | |
abb3097e C |
20 | |
21 | type Translations = { [ id: string ]: string } | |
202e7223 | 22 | |
5efab546 | 23 | export class PeerTubeEmbed { |
5abc96fc | 24 | playerElement: HTMLVideoElement |
7e37e111 | 25 | player: videojs.Player |
902aa3a0 | 26 | api: PeerTubeEmbedApi = null |
5abc96fc | 27 | |
3b019808 C |
28 | autoplay: boolean |
29 | controls: boolean | |
30 | muted: boolean | |
31 | loop: boolean | |
32 | subtitle: string | |
902aa3a0 | 33 | enableApi = false |
1f6824c9 | 34 | startTime: number | string = 0 |
f0a39880 | 35 | stopTime: number | string |
5efab546 C |
36 | |
37 | title: boolean | |
38 | warningTitle: boolean | |
08d9ba0f | 39 | peertubeLink: boolean |
5efab546 C |
40 | bigPlayBackgroundColor: string |
41 | foregroundColor: string | |
42 | ||
3b6f205c | 43 | mode: PlayerMode |
902aa3a0 C |
44 | scope = 'peertube' |
45 | ||
a4ff3100 | 46 | userTokens: Tokens |
71ab65d0 | 47 | headers = new Headers() |
4504f09f RK |
48 | LOCAL_STORAGE_OAUTH_CLIENT_KEYS = { |
49 | CLIENT_ID: 'client_id', | |
50 | CLIENT_SECRET: 'client_secret' | |
51 | } | |
71ab65d0 | 52 | |
5abc96fc C |
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 | ||
902aa3a0 | 63 | static async main () { |
5abc96fc | 64 | const videoContainerId = 'video-wrapper' |
99941732 WL |
65 | const embed = new PeerTubeEmbed(videoContainerId) |
66 | await embed.init() | |
67 | } | |
902aa3a0 | 68 | |
5abc96fc C |
69 | constructor (private videoWrapperId: string) { |
70 | this.wrapperElement = document.getElementById(this.videoWrapperId) | |
902aa3a0 C |
71 | } |
72 | ||
99941732 WL |
73 | getVideoUrl (id: string) { |
74 | return window.location.origin + '/api/v1/videos/' + id | |
75 | } | |
d4f3fea6 | 76 | |
207612df | 77 | refreshFetch (url: string, options?: RequestInit) { |
4504f09f RK |
78 | return fetch(url, options) |
79 | .then((res: Response) => { | |
80 | if (res.status !== 401) return res | |
81 | ||
4504f09f RK |
82 | const refreshingTokenPromise = new Promise((resolve, reject) => { |
83 | const clientId: string = peertubeLocalStorage.getItem(this.LOCAL_STORAGE_OAUTH_CLIENT_KEYS.CLIENT_ID) | |
84 | const clientSecret: string = peertubeLocalStorage.getItem(this.LOCAL_STORAGE_OAUTH_CLIENT_KEYS.CLIENT_SECRET) | |
207612df | 85 | |
4504f09f RK |
86 | const headers = new Headers() |
87 | headers.set('Content-Type', 'application/x-www-form-urlencoded') | |
207612df | 88 | |
4504f09f | 89 | const data = { |
a4ff3100 | 90 | refresh_token: this.userTokens.refreshToken, |
4504f09f RK |
91 | client_id: clientId, |
92 | client_secret: clientSecret, | |
93 | response_type: 'code', | |
94 | grant_type: 'refresh_token' | |
95 | } | |
96 | ||
97 | fetch('/api/v1/users/token', { | |
98 | headers, | |
99 | method: 'POST', | |
100 | body: objectToUrlEncoded(data) | |
496d784d C |
101 | }).then(res => { |
102 | if (res.status === 401) return undefined | |
a4ff3100 | 103 | |
496d784d C |
104 | return res.json() |
105 | }).then((obj: UserRefreshToken & { code: 'invalid_grant'}) => { | |
106 | if (!obj || obj.code === 'invalid_grant') { | |
107 | Tokens.flush() | |
108 | this.removeTokensFromHeaders() | |
a4ff3100 | 109 | |
496d784d C |
110 | return resolve() |
111 | } | |
112 | ||
113 | this.userTokens.accessToken = obj.access_token | |
114 | this.userTokens.refreshToken = obj.refresh_token | |
115 | this.userTokens.save() | |
116 | ||
117 | this.setHeadersFromTokens() | |
118 | ||
119 | resolve() | |
120 | }) | |
4504f09f RK |
121 | .catch((refreshTokenError: any) => { |
122 | reject(refreshTokenError) | |
123 | }) | |
124 | }) | |
125 | ||
126 | return refreshingTokenPromise | |
496d784d C |
127 | .catch(() => { |
128 | Tokens.flush() | |
129 | ||
130 | this.removeTokensFromHeaders() | |
131 | }).then(() => fetch(url, { | |
4504f09f RK |
132 | ...options, |
133 | headers: this.headers | |
134 | })) | |
135 | }) | |
136 | } | |
137 | ||
5abc96fc C |
138 | getPlaylistUrl (id: string) { |
139 | return window.location.origin + '/api/v1/video-playlists/' + id | |
140 | } | |
141 | ||
99941732 | 142 | loadVideoInfo (videoId: string): Promise<Response> { |
4504f09f | 143 | return this.refreshFetch(this.getVideoUrl(videoId), { headers: this.headers }) |
99941732 | 144 | } |
d4f3fea6 | 145 | |
16f7022b | 146 | loadVideoCaptions (videoId: string): Promise<Response> { |
be59656c | 147 | return this.refreshFetch(this.getVideoUrl(videoId) + '/captions', { headers: this.headers }) |
16f7022b C |
148 | } |
149 | ||
5abc96fc | 150 | loadPlaylistInfo (playlistId: string): Promise<Response> { |
be59656c | 151 | return this.refreshFetch(this.getPlaylistUrl(playlistId), { headers: this.headers }) |
5abc96fc C |
152 | } |
153 | ||
fb13852d C |
154 | loadPlaylistElements (playlistId: string, start = 0): Promise<Response> { |
155 | const url = new URL(this.getPlaylistUrl(playlistId) + '/videos') | |
156 | url.search = new URLSearchParams({ start: '' + start, count: '100' }).toString() | |
157 | ||
be59656c | 158 | return this.refreshFetch(url.toString(), { headers: this.headers }) |
5abc96fc C |
159 | } |
160 | ||
161 | loadConfig (): Promise<ServerConfig> { | |
be59656c | 162 | return this.refreshFetch('/api/v1/config') |
5abc96fc | 163 | .then(res => res.json()) |
31b6ddf8 C |
164 | } |
165 | ||
99941732 WL |
166 | removeElement (element: HTMLElement) { |
167 | element.parentElement.removeChild(element) | |
168 | } | |
d4f3fea6 | 169 | |
abb3097e | 170 | displayError (text: string, translations?: Translations) { |
99941732 | 171 | // Remove video element |
5abc96fc C |
172 | if (this.playerElement) { |
173 | this.removeElement(this.playerElement) | |
174 | this.playerElement = undefined | |
175 | } | |
99941732 | 176 | |
ad3fa0c5 C |
177 | const translatedText = peertubeTranslate(text, translations) |
178 | const translatedSorry = peertubeTranslate('Sorry', translations) | |
179 | ||
180 | document.title = translatedSorry + ' - ' + translatedText | |
99941732 WL |
181 | |
182 | const errorBlock = document.getElementById('error-block') | |
183 | errorBlock.style.display = 'flex' | |
184 | ||
ad3fa0c5 C |
185 | const errorTitle = document.getElementById('error-title') |
186 | errorTitle.innerHTML = peertubeTranslate('Sorry', translations) | |
187 | ||
99941732 | 188 | const errorText = document.getElementById('error-content') |
ad3fa0c5 | 189 | errorText.innerHTML = translatedText |
2a71d286 C |
190 | |
191 | this.wrapperElement.style.display = 'none' | |
99941732 WL |
192 | } |
193 | ||
abb3097e | 194 | videoNotFound (translations?: Translations) { |
99941732 | 195 | const text = 'This video does not exist.' |
ad3fa0c5 | 196 | this.displayError(text, translations) |
99941732 WL |
197 | } |
198 | ||
abb3097e | 199 | videoFetchError (translations?: Translations) { |
99941732 | 200 | const text = 'We cannot fetch the video. Please try again later.' |
ad3fa0c5 | 201 | this.displayError(text, translations) |
99941732 WL |
202 | } |
203 | ||
5abc96fc C |
204 | playlistNotFound (translations?: Translations) { |
205 | const text = 'This playlist does not exist.' | |
206 | this.displayError(text, translations) | |
207 | } | |
208 | ||
209 | playlistFetchError (translations?: Translations) { | |
210 | const text = 'We cannot fetch the playlist. Please try again later.' | |
211 | this.displayError(text, translations) | |
212 | } | |
213 | ||
3b019808 | 214 | getParamToggle (params: URLSearchParams, name: string, defaultValue?: boolean) { |
99941732 WL |
215 | return params.has(name) ? (params.get(name) === '1' || params.get(name) === 'true') : defaultValue |
216 | } | |
d4f3fea6 | 217 | |
3b019808 | 218 | getParamString (params: URLSearchParams, name: string, defaultValue?: string) { |
99941732 WL |
219 | return params.has(name) ? params.get(name) : defaultValue |
220 | } | |
da99ccf2 | 221 | |
9054a8b6 C |
222 | async playNextVideo () { |
223 | const next = this.getNextPlaylistElement() | |
224 | if (!next) { | |
225 | console.log('Next element not found in playlist.') | |
226 | return | |
227 | } | |
228 | ||
229 | this.currentPlaylistElement = next | |
230 | ||
231 | return this.loadVideoAndBuildPlayer(this.currentPlaylistElement.video.uuid) | |
232 | } | |
233 | ||
234 | async playPreviousVideo () { | |
235 | const previous = this.getPreviousPlaylistElement() | |
236 | if (!previous) { | |
237 | console.log('Previous element not found in playlist.') | |
238 | return | |
239 | } | |
240 | ||
241 | this.currentPlaylistElement = previous | |
242 | ||
243 | await this.loadVideoAndBuildPlayer(this.currentPlaylistElement.video.uuid) | |
244 | } | |
245 | ||
246 | getCurrentPosition () { | |
247 | if (!this.currentPlaylistElement) return -1 | |
248 | ||
249 | return this.currentPlaylistElement.position | |
250 | } | |
251 | ||
902aa3a0 | 252 | async init () { |
99941732 | 253 | try { |
a4ff3100 | 254 | this.userTokens = Tokens.load() |
99941732 WL |
255 | await this.initCore() |
256 | } catch (e) { | |
257 | console.error(e) | |
258 | } | |
259 | } | |
260 | ||
902aa3a0 C |
261 | private initializeApi () { |
262 | if (!this.enableApi) return | |
263 | ||
264 | this.api = new PeerTubeEmbedApi(this) | |
265 | this.api.initialize() | |
266 | } | |
267 | ||
0f2f274c | 268 | private loadParams (video: VideoDetails) { |
da99ccf2 | 269 | try { |
c4710631 | 270 | const params = new URL(window.location.toString()).searchParams |
99941732 | 271 | |
31b6ddf8 C |
272 | this.autoplay = this.getParamToggle(params, 'autoplay', false) |
273 | this.controls = this.getParamToggle(params, 'controls', true) | |
64645512 | 274 | this.muted = this.getParamToggle(params, 'muted', undefined) |
31b6ddf8 | 275 | this.loop = this.getParamToggle(params, 'loop', false) |
5efab546 | 276 | this.title = this.getParamToggle(params, 'title', true) |
99941732 | 277 | this.enableApi = this.getParamToggle(params, 'api', this.enableApi) |
5efab546 | 278 | this.warningTitle = this.getParamToggle(params, 'warningTitle', true) |
08d9ba0f | 279 | this.peertubeLink = this.getParamToggle(params, 'peertubeLink', true) |
f37bad63 | 280 | |
3b019808 C |
281 | this.scope = this.getParamString(params, 'scope', this.scope) |
282 | this.subtitle = this.getParamString(params, 'subtitle') | |
283 | this.startTime = this.getParamString(params, 'start') | |
f0a39880 | 284 | this.stopTime = this.getParamString(params, 'stop') |
3b6f205c | 285 | |
5efab546 C |
286 | this.bigPlayBackgroundColor = this.getParamString(params, 'bigPlayBackgroundColor') |
287 | this.foregroundColor = this.getParamString(params, 'foregroundColor') | |
288 | ||
0f2f274c C |
289 | const modeParam = this.getParamString(params, 'mode') |
290 | ||
291 | if (modeParam) { | |
292 | if (modeParam === 'p2p-media-loader') this.mode = 'p2p-media-loader' | |
293 | else this.mode = 'webtorrent' | |
294 | } else { | |
295 | if (Array.isArray(video.streamingPlaylists) && video.streamingPlaylists.length !== 0) this.mode = 'p2p-media-loader' | |
296 | else this.mode = 'webtorrent' | |
297 | } | |
da99ccf2 C |
298 | } catch (err) { |
299 | console.error('Cannot get params from URL.', err) | |
300 | } | |
99941732 WL |
301 | } |
302 | ||
fb13852d C |
303 | private async loadAllPlaylistVideos (playlistId: string, baseResult: ResultList<VideoPlaylistElement>) { |
304 | let elements = baseResult.data | |
305 | let total = baseResult.total | |
306 | let i = 0 | |
307 | ||
308 | while (total > elements.length && i < 10) { | |
309 | const result = await this.loadPlaylistElements(playlistId, elements.length) | |
310 | ||
311 | const json = await result.json() as ResultList<VideoPlaylistElement> | |
312 | total = json.total | |
313 | ||
314 | elements = elements.concat(json.data) | |
315 | i++ | |
316 | } | |
317 | ||
318 | if (i === 10) { | |
319 | console.error('Cannot fetch all playlists elements, there are too many!') | |
320 | } | |
321 | ||
322 | return elements | |
323 | } | |
324 | ||
5abc96fc C |
325 | private async loadPlaylist (playlistId: string) { |
326 | const playlistPromise = this.loadPlaylistInfo(playlistId) | |
327 | const playlistElementsPromise = this.loadPlaylistElements(playlistId) | |
99941732 | 328 | |
be59656c C |
329 | let playlistResponse: Response |
330 | let isResponseOk: boolean | |
5abc96fc | 331 | |
be59656c C |
332 | try { |
333 | playlistResponse = await playlistPromise | |
334 | isResponseOk = true | |
335 | } catch (err) { | |
336 | console.error(err) | |
337 | isResponseOk = false | |
338 | } | |
339 | ||
340 | if (!isResponseOk) { | |
5abc96fc | 341 | const serverTranslations = await this.translationsPromise |
71ab65d0 | 342 | |
be59656c | 343 | if (playlistResponse?.status === 404) { |
5abc96fc C |
344 | this.playlistNotFound(serverTranslations) |
345 | return undefined | |
346 | } | |
347 | ||
348 | this.playlistFetchError(serverTranslations) | |
349 | return undefined | |
350 | } | |
351 | ||
352 | return { playlistResponse, videosResponse: await playlistElementsPromise } | |
353 | } | |
354 | ||
355 | private async loadVideo (videoId: string) { | |
3f9c4955 | 356 | const videoPromise = this.loadVideoInfo(videoId) |
3f9c4955 | 357 | |
be59656c C |
358 | let videoResponse: Response |
359 | let isResponseOk: boolean | |
360 | ||
361 | try { | |
362 | videoResponse = await videoPromise | |
363 | isResponseOk = true | |
364 | } catch (err) { | |
365 | console.error(err) | |
366 | ||
367 | isResponseOk = false | |
368 | } | |
99941732 | 369 | |
be59656c | 370 | if (!isResponseOk) { |
5abc96fc C |
371 | const serverTranslations = await this.translationsPromise |
372 | ||
be59656c | 373 | if (videoResponse?.status === 404) { |
5abc96fc C |
374 | this.videoNotFound(serverTranslations) |
375 | return undefined | |
376 | } | |
377 | ||
378 | this.videoFetchError(serverTranslations) | |
379 | return undefined | |
380 | } | |
381 | ||
382 | const captionsPromise = this.loadVideoCaptions(videoId) | |
383 | ||
384 | return { captionsPromise, videoResponse } | |
385 | } | |
3f9c4955 | 386 | |
5abc96fc C |
387 | private async buildPlaylistManager () { |
388 | const translations = await this.translationsPromise | |
389 | ||
390 | this.player.upnext({ | |
391 | timeout: 10000, // 10s | |
392 | headText: peertubeTranslate('Up Next', translations), | |
393 | cancelText: peertubeTranslate('Cancel', translations), | |
394 | suspendedText: peertubeTranslate('Autoplay is suspended', translations), | |
395 | getTitle: () => this.nextVideoTitle(), | |
a950e4c8 | 396 | next: () => this.playNextVideo(), |
5abc96fc C |
397 | condition: () => !!this.getNextPlaylistElement(), |
398 | suspended: () => false | |
399 | }) | |
400 | } | |
99941732 | 401 | |
4572c3d0 C |
402 | private async loadVideoAndBuildPlayer (uuid: string) { |
403 | const res = await this.loadVideo(uuid) | |
5abc96fc C |
404 | if (res === undefined) return |
405 | ||
406 | return this.buildVideoPlayer(res.videoResponse, res.captionsPromise) | |
407 | } | |
3f9c4955 | 408 | |
5abc96fc C |
409 | private nextVideoTitle () { |
410 | const next = this.getNextPlaylistElement() | |
411 | if (!next) return '' | |
412 | ||
413 | return next.video.name | |
414 | } | |
415 | ||
416 | private getNextPlaylistElement (position?: number): VideoPlaylistElement { | |
417 | if (!position) position = this.currentPlaylistElement.position + 1 | |
418 | ||
419 | if (position > this.playlist.videosLength) { | |
420 | return undefined | |
421 | } | |
422 | ||
423 | const next = this.playlistElements.find(e => e.position === position) | |
424 | ||
425 | if (!next || !next.video) { | |
426 | return this.getNextPlaylistElement(position + 1) | |
427 | } | |
428 | ||
429 | return next | |
430 | } | |
431 | ||
a950e4c8 | 432 | private getPreviousPlaylistElement (position?: number): VideoPlaylistElement { |
2a71d286 | 433 | if (!position) position = this.currentPlaylistElement.position - 1 |
a950e4c8 C |
434 | |
435 | if (position < 1) { | |
436 | return undefined | |
437 | } | |
438 | ||
439 | const prev = this.playlistElements.find(e => e.position === position) | |
440 | ||
441 | if (!prev || !prev.video) { | |
442 | return this.getNextPlaylistElement(position - 1) | |
443 | } | |
444 | ||
445 | return prev | |
446 | } | |
447 | ||
5abc96fc C |
448 | private async buildVideoPlayer (videoResponse: Response, captionsPromise: Promise<Response>) { |
449 | let alreadyHadPlayer = false | |
450 | ||
451 | if (this.player) { | |
452 | this.player.dispose() | |
453 | alreadyHadPlayer = true | |
454 | } | |
455 | ||
456 | this.playerElement = document.createElement('video') | |
457 | this.playerElement.className = 'video-js vjs-peertube-skin' | |
458 | this.playerElement.setAttribute('playsinline', 'true') | |
459 | this.wrapperElement.appendChild(this.playerElement) | |
460 | ||
461 | const videoInfoPromise = videoResponse.json() | |
462 | .then((videoInfo: VideoDetails) => { | |
463 | if (!alreadyHadPlayer) this.loadPlaceholder(videoInfo) | |
464 | ||
465 | return videoInfo | |
466 | }) | |
467 | ||
6fad8e51 | 468 | const [ videoInfoTmp, serverTranslations, captionsResponse, config, PeertubePlayerManagerModule ] = await Promise.all([ |
5abc96fc C |
469 | videoInfoPromise, |
470 | this.translationsPromise, | |
471 | captionsPromise, | |
472 | this.configPromise, | |
473 | this.PeertubePlayerManagerModulePromise | |
474 | ]) | |
3f9c4955 | 475 | |
6fad8e51 C |
476 | const videoInfo: VideoDetails = videoInfoTmp |
477 | ||
3f9c4955 | 478 | const PeertubePlayerManager = PeertubePlayerManagerModule.PeertubePlayerManager |
5efab546 | 479 | const videoCaptions = await this.buildCaptions(serverTranslations, captionsResponse) |
99941732 | 480 | |
0f2f274c | 481 | this.loadParams(videoInfo) |
da99ccf2 | 482 | |
4572c3d0 C |
483 | const playlistPlugin = this.currentPlaylistElement |
484 | ? { | |
485 | elements: this.playlistElements, | |
486 | playlist: this.playlist, | |
487 | ||
488 | getCurrentPosition: () => this.currentPlaylistElement.position, | |
489 | ||
490 | onItemClicked: (videoPlaylistElement: VideoPlaylistElement) => { | |
491 | this.currentPlaylistElement = videoPlaylistElement | |
492 | ||
493 | this.loadVideoAndBuildPlayer(this.currentPlaylistElement.video.uuid) | |
494 | .catch(err => console.error(err)) | |
495 | } | |
496 | } | |
497 | : undefined | |
498 | ||
2adfc7ea C |
499 | const options: PeertubePlayerManagerOptions = { |
500 | common: { | |
5abc96fc C |
501 | // Autoplay in playlist mode |
502 | autoplay: alreadyHadPlayer ? true : this.autoplay, | |
2adfc7ea C |
503 | controls: this.controls, |
504 | muted: this.muted, | |
505 | loop: this.loop, | |
1a8c2d74 | 506 | |
2adfc7ea | 507 | captions: videoCaptions.length !== 0, |
2adfc7ea C |
508 | subtitle: this.subtitle, |
509 | ||
1a8c2d74 C |
510 | startTime: this.playlist ? this.currentPlaylistElement.startTimestamp : this.startTime, |
511 | stopTime: this.playlist ? this.currentPlaylistElement.stopTimestamp : this.stopTime, | |
512 | ||
a950e4c8 C |
513 | nextVideo: this.playlist ? () => this.playNextVideo() : undefined, |
514 | hasNextVideo: this.playlist ? () => !!this.getNextPlaylistElement() : undefined, | |
515 | ||
516 | previousVideo: this.playlist ? () => this.playPreviousVideo() : undefined, | |
517 | hasPreviousVideo: this.playlist ? () => !!this.getPreviousPlaylistElement() : undefined, | |
518 | ||
4572c3d0 | 519 | playlist: playlistPlugin, |
5abc96fc | 520 | |
2adfc7ea | 521 | videoCaptions, |
35f0a5e6 | 522 | inactivityTimeout: 2500, |
5abc96fc | 523 | videoViewUrl: this.getVideoUrl(videoInfo.uuid) + '/views', |
6ec0b75b | 524 | |
5abc96fc C |
525 | playerElement: this.playerElement, |
526 | onPlayerElementChange: (element: HTMLVideoElement) => this.playerElement = element, | |
6ec0b75b | 527 | |
2adfc7ea C |
528 | videoDuration: videoInfo.duration, |
529 | enableHotkeys: true, | |
08d9ba0f | 530 | peertubeLink: this.peertubeLink, |
2adfc7ea | 531 | poster: window.location.origin + videoInfo.previewPath, |
3d9a63d3 | 532 | theaterButton: false, |
2adfc7ea C |
533 | |
534 | serverUrl: window.location.origin, | |
535 | language: navigator.language, | |
536 | embedUrl: window.location.origin + videoInfo.embedPath | |
6ec0b75b C |
537 | }, |
538 | ||
539 | webtorrent: { | |
540 | videoFiles: videoInfo.files | |
2adfc7ea | 541 | } |
3b6f205c | 542 | } |
2adfc7ea | 543 | |
3b6f205c | 544 | if (this.mode === 'p2p-media-loader') { |
09209296 C |
545 | const hlsPlaylist = videoInfo.streamingPlaylists.find(p => p.type === VideoStreamingPlaylistType.HLS) |
546 | ||
3b6f205c C |
547 | Object.assign(options, { |
548 | p2pMediaLoader: { | |
09209296 C |
549 | playlistUrl: hlsPlaylist.playlistUrl, |
550 | segmentsSha256Url: hlsPlaylist.segmentsSha256Url, | |
551 | redundancyBaseUrls: hlsPlaylist.redundancies.map(r => r.baseUrl), | |
552 | trackerAnnounce: videoInfo.trackerUrls, | |
5a71acd2 | 553 | videoFiles: hlsPlaylist.files |
09209296 | 554 | } as P2PMediaLoaderOptions |
3b6f205c | 555 | }) |
2adfc7ea | 556 | } |
202e7223 | 557 | |
7e37e111 | 558 | this.player = await PeertubePlayerManager.initialize(this.mode, options, (player: videojs.Player) => this.player = player) |
2adfc7ea | 559 | this.player.on('customError', (event: any, data: any) => this.handleError(data.err, serverTranslations)) |
99941732 | 560 | |
2adfc7ea | 561 | window[ 'videojsPlayer' ] = this.player |
902aa3a0 | 562 | |
5efab546 C |
563 | this.buildCSS() |
564 | ||
5abc96fc | 565 | await this.buildDock(videoInfo, config) |
5efab546 C |
566 | |
567 | this.initializeApi() | |
3f9c4955 C |
568 | |
569 | this.removePlaceholder() | |
5abc96fc C |
570 | |
571 | if (this.isPlaylistEmbed()) { | |
572 | await this.buildPlaylistManager() | |
1a8c2d74 | 573 | |
4572c3d0 | 574 | this.player.playlist().updateSelected() |
1a8c2d74 C |
575 | |
576 | this.player.on('stopped', () => { | |
577 | this.playNextVideo() | |
578 | }) | |
5abc96fc C |
579 | } |
580 | } | |
581 | ||
582 | private async initCore () { | |
583 | if (this.userTokens) this.setHeadersFromTokens() | |
584 | ||
585 | this.configPromise = this.loadConfig() | |
586 | this.translationsPromise = TranslationsManager.getServerTranslations(window.location.origin, navigator.language) | |
587 | this.PeertubePlayerManagerModulePromise = import('../../assets/player/peertube-player-manager') | |
588 | ||
589 | let videoId: string | |
590 | ||
591 | if (this.isPlaylistEmbed()) { | |
592 | const playlistId = this.getResourceId() | |
593 | const res = await this.loadPlaylist(playlistId) | |
594 | if (!res) return undefined | |
595 | ||
596 | this.playlist = await res.playlistResponse.json() | |
597 | ||
598 | const playlistElementResult = await res.videosResponse.json() | |
fb13852d | 599 | this.playlistElements = await this.loadAllPlaylistVideos(playlistId, playlistElementResult) |
5abc96fc | 600 | |
2a71d286 C |
601 | const params = new URL(window.location.toString()).searchParams |
602 | const playlistPositionParam = this.getParamString(params, 'playlistPosition') | |
603 | ||
604 | let position = 1 | |
605 | ||
606 | if (playlistPositionParam) { | |
607 | position = parseInt(playlistPositionParam + '', 10) | |
608 | } | |
609 | ||
610 | this.currentPlaylistElement = this.playlistElements.find(e => e.position === position) | |
611 | if (!this.currentPlaylistElement || !this.currentPlaylistElement.video) { | |
612 | console.error('Current playlist element is not valid.', this.currentPlaylistElement) | |
613 | this.currentPlaylistElement = this.getNextPlaylistElement() | |
614 | } | |
615 | ||
616 | if (!this.currentPlaylistElement) { | |
617 | console.error('This playlist does not have any valid element.') | |
618 | const serverTranslations = await this.translationsPromise | |
619 | this.playlistFetchError(serverTranslations) | |
620 | return | |
621 | } | |
622 | ||
5abc96fc C |
623 | videoId = this.currentPlaylistElement.video.uuid |
624 | } else { | |
625 | videoId = this.getResourceId() | |
626 | } | |
627 | ||
4572c3d0 | 628 | return this.loadVideoAndBuildPlayer(videoId) |
5efab546 C |
629 | } |
630 | ||
631 | private handleError (err: Error, translations?: { [ id: string ]: string }) { | |
632 | if (err.message.indexOf('from xs param') !== -1) { | |
633 | this.player.dispose() | |
5abc96fc | 634 | this.playerElement = null |
5efab546 C |
635 | this.displayError('This video is not available because the remote instance is not responding.', translations) |
636 | return | |
637 | } | |
638 | } | |
639 | ||
5abc96fc | 640 | private async buildDock (videoInfo: VideoDetails, config: ServerConfig) { |
abb3097e | 641 | if (!this.controls) return |
5efab546 | 642 | |
818c449b C |
643 | // On webtorrent fallback, player may have been disposed |
644 | if (!this.player.player_) return | |
5efab546 | 645 | |
abb3097e | 646 | const title = this.title ? videoInfo.name : undefined |
31b6ddf8 | 647 | |
abb3097e C |
648 | const description = config.tracker.enabled && this.warningTitle |
649 | ? '<span class="text">' + peertubeTranslate('Watching this video may reveal your IP address to others.') + '</span>' | |
650 | : undefined | |
651 | ||
652 | this.player.dock({ | |
653 | title, | |
654 | description | |
655 | }) | |
5efab546 | 656 | } |
16f7022b | 657 | |
5efab546 C |
658 | private buildCSS () { |
659 | const body = document.getElementById('custom-css') | |
660 | ||
661 | if (this.bigPlayBackgroundColor) { | |
662 | body.style.setProperty('--embedBigPlayBackgroundColor', this.bigPlayBackgroundColor) | |
663 | } | |
664 | ||
665 | if (this.foregroundColor) { | |
666 | body.style.setProperty('--embedForegroundColor', this.foregroundColor) | |
667 | } | |
99941732 | 668 | } |
6d88de72 | 669 | |
5efab546 C |
670 | private async buildCaptions (serverTranslations: any, captionsResponse: Response): Promise<VideoJSCaption[]> { |
671 | if (captionsResponse.ok) { | |
672 | const { data } = (await captionsResponse.json()) as ResultList<VideoCaption> | |
673 | ||
674 | return data.map(c => ({ | |
675 | label: peertubeTranslate(c.language.label, serverTranslations), | |
676 | language: c.language.id, | |
677 | src: window.location.origin + c.captionPath | |
678 | })) | |
6d88de72 | 679 | } |
5efab546 C |
680 | |
681 | return [] | |
6d88de72 | 682 | } |
3f9c4955 C |
683 | |
684 | private loadPlaceholder (video: VideoDetails) { | |
685 | const placeholder = this.getPlaceholderElement() | |
686 | ||
687 | const url = window.location.origin + video.previewPath | |
688 | placeholder.style.backgroundImage = `url("${url}")` | |
5abc96fc | 689 | placeholder.style.display = 'block' |
3f9c4955 C |
690 | } |
691 | ||
692 | private removePlaceholder () { | |
693 | const placeholder = this.getPlaceholderElement() | |
5abc96fc | 694 | placeholder.style.display = 'none' |
3f9c4955 C |
695 | } |
696 | ||
697 | private getPlaceholderElement () { | |
698 | return document.getElementById('placeholder-preview') | |
699 | } | |
a4ff3100 C |
700 | |
701 | private setHeadersFromTokens () { | |
702 | this.headers.set('Authorization', `${this.userTokens.tokenType} ${this.userTokens.accessToken}`) | |
703 | } | |
5abc96fc | 704 | |
207612df C |
705 | private removeTokensFromHeaders () { |
706 | this.headers.delete('Authorization') | |
707 | } | |
708 | ||
5abc96fc C |
709 | private getResourceId () { |
710 | const urlParts = window.location.pathname.split('/') | |
711 | return urlParts[ urlParts.length - 1 ] | |
712 | } | |
713 | ||
714 | private isPlaylistEmbed () { | |
715 | return window.location.pathname.split('/')[1] === 'video-playlists' | |
716 | } | |
99941732 WL |
717 | } |
718 | ||
719 | PeerTubeEmbed.main() | |
902aa3a0 | 720 | .catch(err => console.error('Cannot init embed.', err)) |