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