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