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