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