]>
Commit | Line | Data |
---|---|---|
202e7223 | 1 | import './embed.scss' |
583eb04b | 2 | import videojs from 'video.js' |
bd45d503 | 3 | import { peertubeTranslate } from '../../../../shared/core-utils/i18n' |
3f9c4955 | 4 | import { |
aea0b0e7 | 5 | HTMLServerConfig, |
c0e8b12e | 6 | HttpStatusCode, |
e030bfb5 | 7 | OAuth2ErrorCode, |
3f9c4955 | 8 | ResultList, |
583eb04b C |
9 | UserRefreshToken, |
10 | VideoCaption, | |
4504f09f | 11 | VideoDetails, |
5abc96fc C |
12 | VideoPlaylist, |
13 | VideoPlaylistElement, | |
aea0b0e7 | 14 | VideoStreamingPlaylistType |
583eb04b C |
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 | 18 | import { TranslationsManager } from '../../assets/player/translations-manager' |
aea0b0e7 | 19 | import { peertubeLocalStorage } from '../../root-helpers/peertube-web-storage' |
72f611ca | 20 | import { PluginsManager } from '../../root-helpers/plugins-manager' |
f9562863 | 21 | import { Tokens } from '../../root-helpers/users' |
f9562863 | 22 | import { objectToUrlEncoded } from '../../root-helpers/utils' |
f9562863 | 23 | import { RegisterClientHelpers } from '../../types/register-client-option.model' |
aea0b0e7 | 24 | import { PeerTubeEmbedApi } from './embed-api' |
abb3097e C |
25 | |
26 | type Translations = { [ id: string ]: string } | |
202e7223 | 27 | |
5efab546 | 28 | export class PeerTubeEmbed { |
5abc96fc | 29 | playerElement: HTMLVideoElement |
7e37e111 | 30 | player: videojs.Player |
902aa3a0 | 31 | api: PeerTubeEmbedApi = null |
5abc96fc | 32 | |
3b019808 C |
33 | autoplay: boolean |
34 | controls: boolean | |
35 | muted: boolean | |
36 | loop: boolean | |
37 | subtitle: string | |
902aa3a0 | 38 | enableApi = false |
1f6824c9 | 39 | startTime: number | string = 0 |
f0a39880 | 40 | stopTime: number | string |
5efab546 C |
41 | |
42 | title: boolean | |
43 | warningTitle: boolean | |
08d9ba0f | 44 | peertubeLink: boolean |
5efab546 C |
45 | bigPlayBackgroundColor: string |
46 | foregroundColor: string | |
47 | ||
3b6f205c | 48 | mode: PlayerMode |
902aa3a0 C |
49 | scope = 'peertube' |
50 | ||
a4ff3100 | 51 | userTokens: Tokens |
71ab65d0 | 52 | headers = new Headers() |
4504f09f RK |
53 | LOCAL_STORAGE_OAUTH_CLIENT_KEYS = { |
54 | CLIENT_ID: 'client_id', | |
55 | CLIENT_SECRET: 'client_secret' | |
56 | } | |
71ab65d0 | 57 | |
aea0b0e7 C |
58 | config: HTMLServerConfig |
59 | ||
5abc96fc | 60 | private translationsPromise: Promise<{ [id: string]: string }> |
5abc96fc C |
61 | private PeertubePlayerManagerModulePromise: Promise<any> |
62 | ||
63 | private playlist: VideoPlaylist | |
64 | private playlistElements: VideoPlaylistElement[] | |
65 | private currentPlaylistElement: VideoPlaylistElement | |
66 | ||
9df52d66 | 67 | private readonly wrapperElement: HTMLElement |
5abc96fc | 68 | |
72f611ca | 69 | private pluginsManager: PluginsManager |
f9562863 | 70 | |
9df52d66 | 71 | constructor (private readonly videoWrapperId: string) { |
5abc96fc | 72 | this.wrapperElement = document.getElementById(this.videoWrapperId) |
aea0b0e7 C |
73 | |
74 | try { | |
75 | this.config = JSON.parse(window['PeerTubeServerConfig']) | |
76 | } catch (err) { | |
77 | console.error('Cannot parse HTML config.', err) | |
78 | } | |
902aa3a0 C |
79 | } |
80 | ||
9df52d66 C |
81 | static async main () { |
82 | const videoContainerId = 'video-wrapper' | |
83 | const embed = new PeerTubeEmbed(videoContainerId) | |
84 | await embed.init() | |
85 | } | |
86 | ||
99941732 WL |
87 | getVideoUrl (id: string) { |
88 | return window.location.origin + '/api/v1/videos/' + id | |
89 | } | |
d4f3fea6 | 90 | |
207612df | 91 | refreshFetch (url: string, options?: RequestInit) { |
4504f09f RK |
92 | return fetch(url, options) |
93 | .then((res: Response) => { | |
f2eb23cd | 94 | if (res.status !== HttpStatusCode.UNAUTHORIZED_401) return res |
4504f09f | 95 | |
72aa835e | 96 | const refreshingTokenPromise = new Promise<void>((resolve, reject) => { |
4504f09f RK |
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) | |
207612df | 99 | |
4504f09f RK |
100 | const headers = new Headers() |
101 | headers.set('Content-Type', 'application/x-www-form-urlencoded') | |
207612df | 102 | |
4504f09f | 103 | const data = { |
a4ff3100 | 104 | refresh_token: this.userTokens.refreshToken, |
4504f09f RK |
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) | |
496d784d | 115 | }).then(res => { |
f2eb23cd | 116 | if (res.status === HttpStatusCode.UNAUTHORIZED_401) return undefined |
a4ff3100 | 117 | |
496d784d | 118 | return res.json() |
e030bfb5 C |
119 | }).then((obj: UserRefreshToken & { code?: OAuth2ErrorCode }) => { |
120 | if (!obj || obj.code === OAuth2ErrorCode.INVALID_GRANT) { | |
496d784d C |
121 | Tokens.flush() |
122 | this.removeTokensFromHeaders() | |
a4ff3100 | 123 | |
496d784d C |
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() | |
a7299d9d C |
134 | }).catch((refreshTokenError: any) => { |
135 | reject(refreshTokenError) | |
496d784d | 136 | }) |
4504f09f RK |
137 | }) |
138 | ||
139 | return refreshingTokenPromise | |
496d784d C |
140 | .catch(() => { |
141 | Tokens.flush() | |
142 | ||
143 | this.removeTokensFromHeaders() | |
144 | }).then(() => fetch(url, { | |
4504f09f RK |
145 | ...options, |
146 | headers: this.headers | |
147 | })) | |
148 | }) | |
149 | } | |
150 | ||
5abc96fc C |
151 | getPlaylistUrl (id: string) { |
152 | return window.location.origin + '/api/v1/video-playlists/' + id | |
153 | } | |
154 | ||
99941732 | 155 | loadVideoInfo (videoId: string): Promise<Response> { |
4504f09f | 156 | return this.refreshFetch(this.getVideoUrl(videoId), { headers: this.headers }) |
99941732 | 157 | } |
d4f3fea6 | 158 | |
16f7022b | 159 | loadVideoCaptions (videoId: string): Promise<Response> { |
be59656c | 160 | return this.refreshFetch(this.getVideoUrl(videoId) + '/captions', { headers: this.headers }) |
16f7022b C |
161 | } |
162 | ||
5abc96fc | 163 | loadPlaylistInfo (playlistId: string): Promise<Response> { |
be59656c | 164 | return this.refreshFetch(this.getPlaylistUrl(playlistId), { headers: this.headers }) |
5abc96fc C |
165 | } |
166 | ||
fb13852d C |
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 | ||
be59656c | 171 | return this.refreshFetch(url.toString(), { headers: this.headers }) |
5abc96fc C |
172 | } |
173 | ||
99941732 WL |
174 | removeElement (element: HTMLElement) { |
175 | element.parentElement.removeChild(element) | |
176 | } | |
d4f3fea6 | 177 | |
abb3097e | 178 | displayError (text: string, translations?: Translations) { |
99941732 | 179 | // Remove video element |
5abc96fc C |
180 | if (this.playerElement) { |
181 | this.removeElement(this.playerElement) | |
182 | this.playerElement = undefined | |
183 | } | |
99941732 | 184 | |
ad3fa0c5 C |
185 | const translatedText = peertubeTranslate(text, translations) |
186 | const translatedSorry = peertubeTranslate('Sorry', translations) | |
187 | ||
188 | document.title = translatedSorry + ' - ' + translatedText | |
99941732 WL |
189 | |
190 | const errorBlock = document.getElementById('error-block') | |
191 | errorBlock.style.display = 'flex' | |
192 | ||
ad3fa0c5 C |
193 | const errorTitle = document.getElementById('error-title') |
194 | errorTitle.innerHTML = peertubeTranslate('Sorry', translations) | |
195 | ||
99941732 | 196 | const errorText = document.getElementById('error-content') |
ad3fa0c5 | 197 | errorText.innerHTML = translatedText |
2a71d286 C |
198 | |
199 | this.wrapperElement.style.display = 'none' | |
99941732 WL |
200 | } |
201 | ||
abb3097e | 202 | videoNotFound (translations?: Translations) { |
99941732 | 203 | const text = 'This video does not exist.' |
ad3fa0c5 | 204 | this.displayError(text, translations) |
99941732 WL |
205 | } |
206 | ||
abb3097e | 207 | videoFetchError (translations?: Translations) { |
99941732 | 208 | const text = 'We cannot fetch the video. Please try again later.' |
ad3fa0c5 | 209 | this.displayError(text, translations) |
99941732 WL |
210 | } |
211 | ||
5abc96fc C |
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 | ||
3b019808 | 222 | getParamToggle (params: URLSearchParams, name: string, defaultValue?: boolean) { |
99941732 WL |
223 | return params.has(name) ? (params.get(name) === '1' || params.get(name) === 'true') : defaultValue |
224 | } | |
d4f3fea6 | 225 | |
3b019808 | 226 | getParamString (params: URLSearchParams, name: string, defaultValue?: string) { |
99941732 WL |
227 | return params.has(name) ? params.get(name) : defaultValue |
228 | } | |
da99ccf2 | 229 | |
9054a8b6 C |
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 | ||
902aa3a0 | 260 | async init () { |
c21a0aa8 C |
261 | this.userTokens = Tokens.load() |
262 | await this.initCore() | |
99941732 WL |
263 | } |
264 | ||
902aa3a0 C |
265 | private initializeApi () { |
266 | if (!this.enableApi) return | |
267 | ||
268 | this.api = new PeerTubeEmbedApi(this) | |
269 | this.api.initialize() | |
270 | } | |
271 | ||
0f2f274c | 272 | private loadParams (video: VideoDetails) { |
da99ccf2 | 273 | try { |
c4710631 | 274 | const params = new URL(window.location.toString()).searchParams |
99941732 | 275 | |
31b6ddf8 C |
276 | this.autoplay = this.getParamToggle(params, 'autoplay', false) |
277 | this.controls = this.getParamToggle(params, 'controls', true) | |
64645512 | 278 | this.muted = this.getParamToggle(params, 'muted', undefined) |
31b6ddf8 | 279 | this.loop = this.getParamToggle(params, 'loop', false) |
5efab546 | 280 | this.title = this.getParamToggle(params, 'title', true) |
99941732 | 281 | this.enableApi = this.getParamToggle(params, 'api', this.enableApi) |
5efab546 | 282 | this.warningTitle = this.getParamToggle(params, 'warningTitle', true) |
08d9ba0f | 283 | this.peertubeLink = this.getParamToggle(params, 'peertubeLink', true) |
f37bad63 | 284 | |
3b019808 C |
285 | this.scope = this.getParamString(params, 'scope', this.scope) |
286 | this.subtitle = this.getParamString(params, 'subtitle') | |
287 | this.startTime = this.getParamString(params, 'start') | |
f0a39880 | 288 | this.stopTime = this.getParamString(params, 'stop') |
3b6f205c | 289 | |
5efab546 C |
290 | this.bigPlayBackgroundColor = this.getParamString(params, 'bigPlayBackgroundColor') |
291 | this.foregroundColor = this.getParamString(params, 'foregroundColor') | |
292 | ||
0f2f274c C |
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 | } | |
da99ccf2 C |
302 | } catch (err) { |
303 | console.error('Cannot get params from URL.', err) | |
304 | } | |
99941732 WL |
305 | } |
306 | ||
fb13852d C |
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 | ||
9df52d66 | 315 | const json = await result.json() |
fb13852d C |
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 | ||
5abc96fc C |
329 | private async loadPlaylist (playlistId: string) { |
330 | const playlistPromise = this.loadPlaylistInfo(playlistId) | |
331 | const playlistElementsPromise = this.loadPlaylistElements(playlistId) | |
99941732 | 332 | |
be59656c C |
333 | let playlistResponse: Response |
334 | let isResponseOk: boolean | |
5abc96fc | 335 | |
be59656c C |
336 | try { |
337 | playlistResponse = await playlistPromise | |
f2eb23cd | 338 | isResponseOk = playlistResponse.status === HttpStatusCode.OK_200 |
be59656c C |
339 | } catch (err) { |
340 | console.error(err) | |
341 | isResponseOk = false | |
342 | } | |
343 | ||
344 | if (!isResponseOk) { | |
5abc96fc | 345 | const serverTranslations = await this.translationsPromise |
71ab65d0 | 346 | |
f2eb23cd | 347 | if (playlistResponse?.status === HttpStatusCode.NOT_FOUND_404) { |
5abc96fc C |
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) { | |
3f9c4955 | 360 | const videoPromise = this.loadVideoInfo(videoId) |
3f9c4955 | 361 | |
be59656c C |
362 | let videoResponse: Response |
363 | let isResponseOk: boolean | |
364 | ||
365 | try { | |
366 | videoResponse = await videoPromise | |
f2eb23cd | 367 | isResponseOk = videoResponse.status === HttpStatusCode.OK_200 |
be59656c C |
368 | } catch (err) { |
369 | console.error(err) | |
370 | ||
371 | isResponseOk = false | |
372 | } | |
99941732 | 373 | |
be59656c | 374 | if (!isResponseOk) { |
5abc96fc C |
375 | const serverTranslations = await this.translationsPromise |
376 | ||
f2eb23cd | 377 | if (videoResponse?.status === HttpStatusCode.NOT_FOUND_404) { |
5abc96fc C |
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 | } | |
3f9c4955 | 390 | |
5abc96fc C |
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(), | |
a950e4c8 | 400 | next: () => this.playNextVideo(), |
5abc96fc C |
401 | condition: () => !!this.getNextPlaylistElement(), |
402 | suspended: () => false | |
403 | }) | |
404 | } | |
99941732 | 405 | |
4572c3d0 C |
406 | private async loadVideoAndBuildPlayer (uuid: string) { |
407 | const res = await this.loadVideo(uuid) | |
5abc96fc C |
408 | if (res === undefined) return |
409 | ||
410 | return this.buildVideoPlayer(res.videoResponse, res.captionsPromise) | |
411 | } | |
3f9c4955 | 412 | |
5abc96fc C |
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 | ||
a950e4c8 | 436 | private getPreviousPlaylistElement (position?: number): VideoPlaylistElement { |
2a71d286 | 437 | if (!position) position = this.currentPlaylistElement.position - 1 |
a950e4c8 C |
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 | ||
5abc96fc C |
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 | ||
aea0b0e7 C |
465 | // Issue when we parsed config from HTML, fallback to API |
466 | if (!this.config) { | |
467 | this.config = await this.refreshFetch('/api/v1/config') | |
9df52d66 | 468 | .then(res => res.json()) |
aea0b0e7 C |
469 | } |
470 | ||
5abc96fc C |
471 | const videoInfoPromise = videoResponse.json() |
472 | .then((videoInfo: VideoDetails) => { | |
200eaf51 C |
473 | this.loadParams(videoInfo) |
474 | ||
475 | if (!alreadyHadPlayer && !this.autoplay) this.loadPlaceholder(videoInfo) | |
5abc96fc C |
476 | |
477 | return videoInfo | |
478 | }) | |
479 | ||
aea0b0e7 | 480 | const [ videoInfoTmp, serverTranslations, captionsResponse, PeertubePlayerManagerModule ] = await Promise.all([ |
5abc96fc C |
481 | videoInfoPromise, |
482 | this.translationsPromise, | |
483 | captionsPromise, | |
5abc96fc C |
484 | this.PeertubePlayerManagerModulePromise |
485 | ]) | |
3f9c4955 | 486 | |
72f611ca | 487 | await this.loadPlugins(serverTranslations) |
f9562863 | 488 | |
6fad8e51 C |
489 | const videoInfo: VideoDetails = videoInfoTmp |
490 | ||
3f9c4955 | 491 | const PeertubePlayerManager = PeertubePlayerManagerModule.PeertubePlayerManager |
5efab546 | 492 | const videoCaptions = await this.buildCaptions(serverTranslations, captionsResponse) |
99941732 | 493 | |
4572c3d0 C |
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) | |
9df52d66 | 505 | .catch(err => console.error(err)) |
3e0e8d4a | 506 | } |
4572c3d0 C |
507 | } |
508 | : undefined | |
509 | ||
2adfc7ea C |
510 | const options: PeertubePlayerManagerOptions = { |
511 | common: { | |
5abc96fc C |
512 | // Autoplay in playlist mode |
513 | autoplay: alreadyHadPlayer ? true : this.autoplay, | |
2adfc7ea C |
514 | controls: this.controls, |
515 | muted: this.muted, | |
516 | loop: this.loop, | |
1a8c2d74 | 517 | |
2adfc7ea | 518 | captions: videoCaptions.length !== 0, |
2adfc7ea C |
519 | subtitle: this.subtitle, |
520 | ||
1a8c2d74 C |
521 | startTime: this.playlist ? this.currentPlaylistElement.startTimestamp : this.startTime, |
522 | stopTime: this.playlist ? this.currentPlaylistElement.stopTimestamp : this.stopTime, | |
523 | ||
a950e4c8 C |
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 | ||
4572c3d0 | 530 | playlist: playlistPlugin, |
5abc96fc | 531 | |
2adfc7ea | 532 | videoCaptions, |
35f0a5e6 | 533 | inactivityTimeout: 2500, |
5abc96fc | 534 | videoViewUrl: this.getVideoUrl(videoInfo.uuid) + '/views', |
29837f88 | 535 | videoShortUUID: videoInfo.shortUUID, |
58b9ce30 | 536 | videoUUID: videoInfo.uuid, |
6ec0b75b | 537 | |
25b7c847 C |
538 | isLive: videoInfo.isLive, |
539 | ||
5abc96fc | 540 | playerElement: this.playerElement, |
9df52d66 C |
541 | onPlayerElementChange: (element: HTMLVideoElement) => { |
542 | this.playerElement = element | |
543 | }, | |
6ec0b75b | 544 | |
2adfc7ea C |
545 | videoDuration: videoInfo.duration, |
546 | enableHotkeys: true, | |
08d9ba0f | 547 | peertubeLink: this.peertubeLink, |
2adfc7ea | 548 | poster: window.location.origin + videoInfo.previewPath, |
3d9a63d3 | 549 | theaterButton: false, |
2adfc7ea C |
550 | |
551 | serverUrl: window.location.origin, | |
552 | language: navigator.language, | |
4097c6d6 TP |
553 | embedUrl: window.location.origin + videoInfo.embedPath, |
554 | embedTitle: videoInfo.name | |
6ec0b75b C |
555 | }, |
556 | ||
557 | webtorrent: { | |
558 | videoFiles: videoInfo.files | |
72f611ca | 559 | }, |
560 | ||
561 | pluginsManager: this.pluginsManager | |
3b6f205c | 562 | } |
2adfc7ea | 563 | |
3b6f205c | 564 | if (this.mode === 'p2p-media-loader') { |
09209296 C |
565 | const hlsPlaylist = videoInfo.streamingPlaylists.find(p => p.type === VideoStreamingPlaylistType.HLS) |
566 | ||
3b6f205c C |
567 | Object.assign(options, { |
568 | p2pMediaLoader: { | |
b9da21bd | 569 | playlistUrl: hlsPlaylist.playlistUrl, |
09209296 | 570 | segmentsSha256Url: hlsPlaylist.segmentsSha256Url, |
b9da21bd | 571 | redundancyBaseUrls: hlsPlaylist.redundancies.map(r => r.baseUrl), |
09209296 | 572 | trackerAnnounce: videoInfo.trackerUrls, |
5a71acd2 | 573 | videoFiles: hlsPlaylist.files |
09209296 | 574 | } as P2PMediaLoaderOptions |
3b6f205c | 575 | }) |
2adfc7ea | 576 | } |
202e7223 | 577 | |
9df52d66 C |
578 | this.player = await PeertubePlayerManager.initialize(this.mode, options, (player: videojs.Player) => { |
579 | this.player = player | |
580 | }) | |
581 | ||
2adfc7ea | 582 | this.player.on('customError', (event: any, data: any) => this.handleError(data.err, serverTranslations)) |
99941732 | 583 | |
9df52d66 | 584 | window['videojsPlayer'] = this.player |
902aa3a0 | 585 | |
5efab546 C |
586 | this.buildCSS() |
587 | ||
98ab5dc8 | 588 | this.buildDock(videoInfo) |
5efab546 C |
589 | |
590 | this.initializeApi() | |
3f9c4955 C |
591 | |
592 | this.removePlaceholder() | |
5abc96fc C |
593 | |
594 | if (this.isPlaylistEmbed()) { | |
595 | await this.buildPlaylistManager() | |
1a8c2d74 | 596 | |
4572c3d0 | 597 | this.player.playlist().updateSelected() |
1a8c2d74 C |
598 | |
599 | this.player.on('stopped', () => { | |
600 | this.playNextVideo() | |
601 | }) | |
5abc96fc | 602 | } |
f9562863 | 603 | |
72f611ca | 604 | this.pluginsManager.runHook('action:embed.player.loaded', undefined, { player: this.player, videojs, video: videoInfo }) |
5abc96fc C |
605 | } |
606 | ||
607 | private async initCore () { | |
608 | if (this.userTokens) this.setHeadersFromTokens() | |
609 | ||
5abc96fc C |
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() | |
fb13852d | 623 | this.playlistElements = await this.loadAllPlaylistVideos(playlistId, playlistElementResult) |
5abc96fc | 624 | |
2a71d286 C |
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 | ||
5abc96fc C |
647 | videoId = this.currentPlaylistElement.video.uuid |
648 | } else { | |
649 | videoId = this.getResourceId() | |
650 | } | |
651 | ||
4572c3d0 | 652 | return this.loadVideoAndBuildPlayer(videoId) |
5efab546 C |
653 | } |
654 | ||
655 | private handleError (err: Error, translations?: { [ id: string ]: string }) { | |
e5a818d3 | 656 | if (err.message.includes('from xs param')) { |
5efab546 | 657 | this.player.dispose() |
5abc96fc | 658 | this.playerElement = null |
5efab546 | 659 | this.displayError('This video is not available because the remote instance is not responding.', translations) |
9df52d66 | 660 | |
5efab546 C |
661 | } |
662 | } | |
663 | ||
98ab5dc8 | 664 | private buildDock (videoInfo: VideoDetails) { |
abb3097e | 665 | if (!this.controls) return |
5efab546 | 666 | |
818c449b C |
667 | // On webtorrent fallback, player may have been disposed |
668 | if (!this.player.player_) return | |
5efab546 | 669 | |
abb3097e | 670 | const title = this.title ? videoInfo.name : undefined |
31b6ddf8 | 671 | |
5196817c | 672 | const description = this.warningTitle && (!videoInfo.isLocal || this.config.tracker.enabled) |
abb3097e C |
673 | ? '<span class="text">' + peertubeTranslate('Watching this video may reveal your IP address to others.') + '</span>' |
674 | : undefined | |
675 | ||
b9da21bd C |
676 | if (title || description) { |
677 | this.player.dock({ | |
678 | title, | |
679 | description | |
680 | }) | |
681 | } | |
5efab546 | 682 | } |
16f7022b | 683 | |
5efab546 C |
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 | } | |
99941732 | 694 | } |
6d88de72 | 695 | |
5efab546 C |
696 | private async buildCaptions (serverTranslations: any, captionsResponse: Response): Promise<VideoJSCaption[]> { |
697 | if (captionsResponse.ok) { | |
9df52d66 | 698 | const { data } = await captionsResponse.json() |
5efab546 | 699 | |
9df52d66 | 700 | return data.map((c: VideoCaption) => ({ |
5efab546 C |
701 | label: peertubeTranslate(c.language.label, serverTranslations), |
702 | language: c.language.id, | |
703 | src: window.location.origin + c.captionPath | |
704 | })) | |
6d88de72 | 705 | } |
5efab546 C |
706 | |
707 | return [] | |
6d88de72 | 708 | } |
3f9c4955 C |
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}")` | |
5abc96fc | 715 | placeholder.style.display = 'block' |
3f9c4955 C |
716 | } |
717 | ||
718 | private removePlaceholder () { | |
719 | const placeholder = this.getPlaceholderElement() | |
5abc96fc | 720 | placeholder.style.display = 'none' |
3f9c4955 C |
721 | } |
722 | ||
723 | private getPlaceholderElement () { | |
724 | return document.getElementById('placeholder-preview') | |
725 | } | |
a4ff3100 C |
726 | |
727 | private setHeadersFromTokens () { | |
728 | this.headers.set('Authorization', `${this.userTokens.tokenType} ${this.userTokens.accessToken}`) | |
729 | } | |
5abc96fc | 730 | |
207612df C |
731 | private removeTokensFromHeaders () { |
732 | this.headers.delete('Authorization') | |
733 | } | |
734 | ||
5abc96fc C |
735 | private getResourceId () { |
736 | const urlParts = window.location.pathname.split('/') | |
9df52d66 | 737 | return urlParts[urlParts.length - 1] |
5abc96fc C |
738 | } |
739 | ||
740 | private isPlaylistEmbed () { | |
741 | return window.location.pathname.split('/')[1] === 'video-playlists' | |
742 | } | |
f9562863 | 743 | |
72f611ca | 744 | private loadPlugins (translations?: { [ id: string ]: string }) { |
745 | this.pluginsManager = new PluginsManager({ | |
746 | peertubeHelpersFactory: _ => this.buildPeerTubeHelpers(translations) | |
747 | }) | |
f9562863 | 748 | |
72f611ca | 749 | this.pluginsManager.loadPluginsList(this.config) |
f9562863 | 750 | |
72f611ca | 751 | return this.pluginsManager.ensurePluginsAreLoaded('embed') |
f9562863 C |
752 | } |
753 | ||
754 | private buildPeerTubeHelpers (translations?: { [ id: string ]: string }): RegisterClientHelpers { | |
9df52d66 | 755 | const unimplemented = () => { |
f9562863 C |
756 | throw new Error('This helper is not implemented in embed.') |
757 | } | |
758 | ||
759 | return { | |
760 | getBaseStaticRoute: unimplemented, | |
9777fe9e | 761 | getBaseRouterRoute: unimplemented, |
d63e6d46 | 762 | getBasePluginClientPath: unimplemented, |
9777fe9e | 763 | |
f9562863 C |
764 | getSettings: unimplemented, |
765 | ||
766 | isLoggedIn: unimplemented, | |
0f319334 | 767 | getAuthHeader: unimplemented, |
f9562863 C |
768 | |
769 | notifier: { | |
770 | info: unimplemented, | |
771 | error: unimplemented, | |
772 | success: unimplemented | |
773 | }, | |
774 | ||
775 | showModal: unimplemented, | |
776 | ||
5aa7abf1 C |
777 | getServerConfig: unimplemented, |
778 | ||
f9562863 C |
779 | markdownRenderer: { |
780 | textMarkdownToHTML: unimplemented, | |
781 | enhancedMarkdownToHTML: unimplemented | |
782 | }, | |
783 | ||
9df52d66 | 784 | translate: (value: string) => Promise.resolve(peertubeTranslate(value, translations)) |
f9562863 C |
785 | } |
786 | } | |
99941732 WL |
787 | } |
788 | ||
789 | PeerTubeEmbed.main() | |
c21a0aa8 C |
790 | .catch(err => { |
791 | (window as any).displayIncompatibleBrowser() | |
792 | ||
793 | console.error('Cannot init embed.', err) | |
794 | }) |