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