]>
Commit | Line | Data |
---|---|---|
1 | import './embed.scss' | |
2 | ||
3 | import { | |
4 | getCompleteLocale, | |
5 | is18nLocale, | |
6 | isDefaultLocale, | |
7 | peertubeTranslate, | |
8 | ResultList, | |
9 | ServerConfig, | |
10 | VideoDetails | |
11 | } from '../../../../shared' | |
12 | import { VideoJSCaption } from '../../assets/player/peertube-videojs-typings' | |
13 | import { VideoCaption } from '../../../../shared/models/videos/caption/video-caption.model' | |
14 | import { | |
15 | P2PMediaLoaderOptions, | |
16 | PeertubePlayerManagerOptions, | |
17 | PlayerMode | |
18 | } from '../../assets/player/peertube-player-manager' | |
19 | import { VideoStreamingPlaylistType } from '../../../../shared/models/videos/video-streaming-playlist.type' | |
20 | import { PeerTubeEmbedApi } from './embed-api' | |
21 | import { TranslationsManager } from '../../assets/player/translations-manager' | |
22 | ||
23 | export class PeerTubeEmbed { | |
24 | videoElement: HTMLVideoElement | |
25 | player: any | |
26 | playerOptions: any | |
27 | api: PeerTubeEmbedApi = null | |
28 | autoplay: boolean | |
29 | controls: boolean | |
30 | muted: boolean | |
31 | loop: boolean | |
32 | subtitle: string | |
33 | enableApi = false | |
34 | startTime: number | string = 0 | |
35 | stopTime: number | string | |
36 | ||
37 | title: boolean | |
38 | warningTitle: boolean | |
39 | bigPlayBackgroundColor: string | |
40 | foregroundColor: string | |
41 | ||
42 | mode: PlayerMode | |
43 | scope = 'peertube' | |
44 | ||
45 | static async main () { | |
46 | const videoContainerId = 'video-container' | |
47 | const embed = new PeerTubeEmbed(videoContainerId) | |
48 | await embed.init() | |
49 | } | |
50 | ||
51 | constructor (private videoContainerId: string) { | |
52 | this.videoElement = document.getElementById(videoContainerId) as HTMLVideoElement | |
53 | } | |
54 | ||
55 | getVideoUrl (id: string) { | |
56 | return window.location.origin + '/api/v1/videos/' + id | |
57 | } | |
58 | ||
59 | loadVideoInfo (videoId: string): Promise<Response> { | |
60 | return fetch(this.getVideoUrl(videoId)) | |
61 | } | |
62 | ||
63 | loadVideoCaptions (videoId: string): Promise<Response> { | |
64 | return fetch(this.getVideoUrl(videoId) + '/captions') | |
65 | } | |
66 | ||
67 | loadConfig (): Promise<Response> { | |
68 | return fetch('/api/v1/config') | |
69 | } | |
70 | ||
71 | removeElement (element: HTMLElement) { | |
72 | element.parentElement.removeChild(element) | |
73 | } | |
74 | ||
75 | displayError (text: string, translations?: { [ id: string ]: string }) { | |
76 | // Remove video element | |
77 | if (this.videoElement) this.removeElement(this.videoElement) | |
78 | ||
79 | const translatedText = peertubeTranslate(text, translations) | |
80 | const translatedSorry = peertubeTranslate('Sorry', translations) | |
81 | ||
82 | document.title = translatedSorry + ' - ' + translatedText | |
83 | ||
84 | const errorBlock = document.getElementById('error-block') | |
85 | errorBlock.style.display = 'flex' | |
86 | ||
87 | const errorTitle = document.getElementById('error-title') | |
88 | errorTitle.innerHTML = peertubeTranslate('Sorry', translations) | |
89 | ||
90 | const errorText = document.getElementById('error-content') | |
91 | errorText.innerHTML = translatedText | |
92 | } | |
93 | ||
94 | videoNotFound (translations?: { [ id: string ]: string }) { | |
95 | const text = 'This video does not exist.' | |
96 | this.displayError(text, translations) | |
97 | } | |
98 | ||
99 | videoFetchError (translations?: { [ id: string ]: string }) { | |
100 | const text = 'We cannot fetch the video. Please try again later.' | |
101 | this.displayError(text, translations) | |
102 | } | |
103 | ||
104 | getParamToggle (params: URLSearchParams, name: string, defaultValue?: boolean) { | |
105 | return params.has(name) ? (params.get(name) === '1' || params.get(name) === 'true') : defaultValue | |
106 | } | |
107 | ||
108 | getParamString (params: URLSearchParams, name: string, defaultValue?: string) { | |
109 | return params.has(name) ? params.get(name) : defaultValue | |
110 | } | |
111 | ||
112 | async init () { | |
113 | try { | |
114 | await this.initCore() | |
115 | } catch (e) { | |
116 | console.error(e) | |
117 | } | |
118 | } | |
119 | ||
120 | private initializeApi () { | |
121 | if (!this.enableApi) return | |
122 | ||
123 | this.api = new PeerTubeEmbedApi(this) | |
124 | this.api.initialize() | |
125 | } | |
126 | ||
127 | private loadParams (video: VideoDetails) { | |
128 | try { | |
129 | const params = new URL(window.location.toString()).searchParams | |
130 | ||
131 | this.autoplay = this.getParamToggle(params, 'autoplay', false) | |
132 | this.controls = this.getParamToggle(params, 'controls', true) | |
133 | this.muted = this.getParamToggle(params, 'muted', false) | |
134 | this.loop = this.getParamToggle(params, 'loop', false) | |
135 | this.title = this.getParamToggle(params, 'title', true) | |
136 | this.enableApi = this.getParamToggle(params, 'api', this.enableApi) | |
137 | this.warningTitle = this.getParamToggle(params, 'warningTitle', true) | |
138 | ||
139 | this.scope = this.getParamString(params, 'scope', this.scope) | |
140 | this.subtitle = this.getParamString(params, 'subtitle') | |
141 | this.startTime = this.getParamString(params, 'start') | |
142 | this.stopTime = this.getParamString(params, 'stop') | |
143 | ||
144 | this.bigPlayBackgroundColor = this.getParamString(params, 'bigPlayBackgroundColor') | |
145 | this.foregroundColor = this.getParamString(params, 'foregroundColor') | |
146 | ||
147 | const modeParam = this.getParamString(params, 'mode') | |
148 | ||
149 | if (modeParam) { | |
150 | if (modeParam === 'p2p-media-loader') this.mode = 'p2p-media-loader' | |
151 | else this.mode = 'webtorrent' | |
152 | } else { | |
153 | if (Array.isArray(video.streamingPlaylists) && video.streamingPlaylists.length !== 0) this.mode = 'p2p-media-loader' | |
154 | else this.mode = 'webtorrent' | |
155 | } | |
156 | } catch (err) { | |
157 | console.error('Cannot get params from URL.', err) | |
158 | } | |
159 | } | |
160 | ||
161 | private async initCore () { | |
162 | const urlParts = window.location.pathname.split('/') | |
163 | const videoId = urlParts[ urlParts.length - 1 ] | |
164 | ||
165 | const videoPromise = this.loadVideoInfo(videoId) | |
166 | const captionsPromise = this.loadVideoCaptions(videoId) | |
167 | const configPromise = this.loadConfig() | |
168 | ||
169 | const translationsPromise = TranslationsManager.getServerTranslations(window.location.origin, navigator.language) | |
170 | const videoResponse = await videoPromise | |
171 | ||
172 | if (!videoResponse.ok) { | |
173 | const serverTranslations = await translationsPromise | |
174 | ||
175 | if (videoResponse.status === 404) return this.videoNotFound(serverTranslations) | |
176 | ||
177 | return this.videoFetchError(serverTranslations) | |
178 | } | |
179 | ||
180 | const videoInfo: VideoDetails = await videoResponse.json() | |
181 | this.loadPlaceholder(videoInfo) | |
182 | ||
183 | const PeertubePlayerManagerModulePromise = import('../../assets/player/peertube-player-manager') | |
184 | ||
185 | const promises = [ translationsPromise, captionsPromise, configPromise, PeertubePlayerManagerModulePromise ] | |
186 | const [ serverTranslations, captionsResponse, configResponse, PeertubePlayerManagerModule ] = await Promise.all(promises) | |
187 | ||
188 | const PeertubePlayerManager = PeertubePlayerManagerModule.PeertubePlayerManager | |
189 | const videoCaptions = await this.buildCaptions(serverTranslations, captionsResponse) | |
190 | ||
191 | this.loadParams(videoInfo) | |
192 | ||
193 | const options: PeertubePlayerManagerOptions = { | |
194 | common: { | |
195 | autoplay: this.autoplay, | |
196 | controls: this.controls, | |
197 | muted: this.muted, | |
198 | loop: this.loop, | |
199 | captions: videoCaptions.length !== 0, | |
200 | startTime: this.startTime, | |
201 | stopTime: this.stopTime, | |
202 | subtitle: this.subtitle, | |
203 | ||
204 | videoCaptions, | |
205 | inactivityTimeout: 1500, | |
206 | videoViewUrl: this.getVideoUrl(videoId) + '/views', | |
207 | ||
208 | playerElement: this.videoElement, | |
209 | onPlayerElementChange: (element: HTMLVideoElement) => this.videoElement = element, | |
210 | ||
211 | videoDuration: videoInfo.duration, | |
212 | enableHotkeys: true, | |
213 | peertubeLink: true, | |
214 | poster: window.location.origin + videoInfo.previewPath, | |
215 | theaterButton: false, | |
216 | ||
217 | serverUrl: window.location.origin, | |
218 | language: navigator.language, | |
219 | embedUrl: window.location.origin + videoInfo.embedPath | |
220 | }, | |
221 | ||
222 | webtorrent: { | |
223 | videoFiles: videoInfo.files | |
224 | } | |
225 | } | |
226 | ||
227 | if (this.mode === 'p2p-media-loader') { | |
228 | const hlsPlaylist = videoInfo.streamingPlaylists.find(p => p.type === VideoStreamingPlaylistType.HLS) | |
229 | ||
230 | Object.assign(options, { | |
231 | p2pMediaLoader: { | |
232 | playlistUrl: hlsPlaylist.playlistUrl, | |
233 | segmentsSha256Url: hlsPlaylist.segmentsSha256Url, | |
234 | redundancyBaseUrls: hlsPlaylist.redundancies.map(r => r.baseUrl), | |
235 | trackerAnnounce: videoInfo.trackerUrls, | |
236 | videoFiles: hlsPlaylist.files | |
237 | } as P2PMediaLoaderOptions | |
238 | }) | |
239 | } | |
240 | ||
241 | this.player = await PeertubePlayerManager.initialize(this.mode, options, (player: any) => this.player = player) | |
242 | this.player.on('customError', (event: any, data: any) => this.handleError(data.err, serverTranslations)) | |
243 | ||
244 | window[ 'videojsPlayer' ] = this.player | |
245 | ||
246 | this.buildCSS() | |
247 | ||
248 | await this.buildDock(videoInfo, configResponse) | |
249 | ||
250 | this.initializeApi() | |
251 | ||
252 | this.removePlaceholder() | |
253 | } | |
254 | ||
255 | private handleError (err: Error, translations?: { [ id: string ]: string }) { | |
256 | if (err.message.indexOf('from xs param') !== -1) { | |
257 | this.player.dispose() | |
258 | this.videoElement = null | |
259 | this.displayError('This video is not available because the remote instance is not responding.', translations) | |
260 | return | |
261 | } | |
262 | } | |
263 | ||
264 | private async buildDock (videoInfo: VideoDetails, configResponse: Response) { | |
265 | if (this.controls) { | |
266 | const title = this.title ? videoInfo.name : undefined | |
267 | ||
268 | const config: ServerConfig = await configResponse.json() | |
269 | const description = config.tracker.enabled && this.warningTitle | |
270 | ? '<span class="text">' + this.player.localize('Watching this video may reveal your IP address to others.') + '</span>' | |
271 | : undefined | |
272 | ||
273 | this.player.dock({ | |
274 | title, | |
275 | description | |
276 | }) | |
277 | } | |
278 | } | |
279 | ||
280 | private buildCSS () { | |
281 | const body = document.getElementById('custom-css') | |
282 | ||
283 | if (this.bigPlayBackgroundColor) { | |
284 | body.style.setProperty('--embedBigPlayBackgroundColor', this.bigPlayBackgroundColor) | |
285 | } | |
286 | ||
287 | if (this.foregroundColor) { | |
288 | body.style.setProperty('--embedForegroundColor', this.foregroundColor) | |
289 | } | |
290 | } | |
291 | ||
292 | private async buildCaptions (serverTranslations: any, captionsResponse: Response): Promise<VideoJSCaption[]> { | |
293 | if (captionsResponse.ok) { | |
294 | const { data } = (await captionsResponse.json()) as ResultList<VideoCaption> | |
295 | ||
296 | return data.map(c => ({ | |
297 | label: peertubeTranslate(c.language.label, serverTranslations), | |
298 | language: c.language.id, | |
299 | src: window.location.origin + c.captionPath | |
300 | })) | |
301 | } | |
302 | ||
303 | return [] | |
304 | } | |
305 | ||
306 | private loadPlaceholder (video: VideoDetails) { | |
307 | const placeholder = this.getPlaceholderElement() | |
308 | ||
309 | const url = window.location.origin + video.previewPath | |
310 | placeholder.style.backgroundImage = `url("${url}")` | |
311 | } | |
312 | ||
313 | private removePlaceholder () { | |
314 | const placeholder = this.getPlaceholderElement() | |
315 | placeholder.parentElement.removeChild(placeholder) | |
316 | } | |
317 | ||
318 | private getPlaceholderElement () { | |
319 | return document.getElementById('placeholder-preview') | |
320 | } | |
321 | } | |
322 | ||
323 | PeerTubeEmbed.main() | |
324 | .catch(err => console.error('Cannot init embed.', err)) |