]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blob - client/src/standalone/videos/embed.ts
468b1889f34ab8c0e6528e888c17915ebbe78c87
[github/Chocobozzz/PeerTube.git] / client / src / standalone / videos / embed.ts
1 import './embed.scss'
2
3 import {
4 peertubeTranslate,
5 ResultList,
6 ServerConfig,
7 VideoDetails
8 } from '../../../../shared'
9 import { VideoCaption } from '../../../../shared/models/videos/caption/video-caption.model'
10 import {
11 P2PMediaLoaderOptions,
12 PeertubePlayerManagerOptions,
13 PlayerMode
14 } from '../../assets/player/peertube-player-manager'
15 import { VideoStreamingPlaylistType } from '../../../../shared/models/videos/video-streaming-playlist.type'
16 import { PeerTubeEmbedApi } from './embed-api'
17 import { TranslationsManager } from '../../assets/player/translations-manager'
18 import videojs from 'video.js'
19 import { VideoJSCaption } from '../../assets/player/peertube-videojs-typings'
20
21 type Translations = { [ id: string ]: string }
22
23 export class PeerTubeEmbed {
24 videoElement: HTMLVideoElement
25 player: videojs.Player
26 api: PeerTubeEmbedApi = null
27 autoplay: boolean
28 controls: boolean
29 muted: boolean
30 loop: boolean
31 subtitle: string
32 enableApi = false
33 startTime: number | string = 0
34 stopTime: number | string
35
36 title: boolean
37 warningTitle: boolean
38 peertubeLink: 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?: Translations) {
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?: Translations) {
95 const text = 'This video does not exist.'
96 this.displayError(text, translations)
97 }
98
99 videoFetchError (translations?: Translations) {
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', undefined)
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 this.peertubeLink = this.getParamToggle(params, 'peertubeLink', true)
139
140 this.scope = this.getParamString(params, 'scope', this.scope)
141 this.subtitle = this.getParamString(params, 'subtitle')
142 this.startTime = this.getParamString(params, 'start')
143 this.stopTime = this.getParamString(params, 'stop')
144
145 this.bigPlayBackgroundColor = this.getParamString(params, 'bigPlayBackgroundColor')
146 this.foregroundColor = this.getParamString(params, 'foregroundColor')
147
148 const modeParam = this.getParamString(params, 'mode')
149
150 if (modeParam) {
151 if (modeParam === 'p2p-media-loader') this.mode = 'p2p-media-loader'
152 else this.mode = 'webtorrent'
153 } else {
154 if (Array.isArray(video.streamingPlaylists) && video.streamingPlaylists.length !== 0) this.mode = 'p2p-media-loader'
155 else this.mode = 'webtorrent'
156 }
157 } catch (err) {
158 console.error('Cannot get params from URL.', err)
159 }
160 }
161
162 private async initCore () {
163 const urlParts = window.location.pathname.split('/')
164 const videoId = urlParts[ urlParts.length - 1 ]
165
166 const videoPromise = this.loadVideoInfo(videoId)
167 const captionsPromise = this.loadVideoCaptions(videoId)
168 const configPromise = this.loadConfig()
169
170 const translationsPromise = TranslationsManager.getServerTranslations(window.location.origin, navigator.language)
171 const videoResponse = await videoPromise
172
173 if (!videoResponse.ok) {
174 const serverTranslations = await translationsPromise
175
176 if (videoResponse.status === 404) return this.videoNotFound(serverTranslations)
177
178 return this.videoFetchError(serverTranslations)
179 }
180
181 const videoInfo: VideoDetails = await videoResponse.json()
182 this.loadPlaceholder(videoInfo)
183
184 const PeertubePlayerManagerModulePromise = import('../../assets/player/peertube-player-manager')
185
186 const promises = [ translationsPromise, captionsPromise, configPromise, PeertubePlayerManagerModulePromise ]
187 const [ serverTranslations, captionsResponse, configResponse, PeertubePlayerManagerModule ] = await Promise.all(promises)
188
189 const PeertubePlayerManager = PeertubePlayerManagerModule.PeertubePlayerManager
190 const videoCaptions = await this.buildCaptions(serverTranslations, captionsResponse)
191
192 this.loadParams(videoInfo)
193
194 const options: PeertubePlayerManagerOptions = {
195 common: {
196 autoplay: this.autoplay,
197 controls: this.controls,
198 muted: this.muted,
199 loop: this.loop,
200 captions: videoCaptions.length !== 0,
201 startTime: this.startTime,
202 stopTime: this.stopTime,
203 subtitle: this.subtitle,
204
205 videoCaptions,
206 inactivityTimeout: 2500,
207 videoViewUrl: this.getVideoUrl(videoId) + '/views',
208
209 playerElement: this.videoElement,
210 onPlayerElementChange: (element: HTMLVideoElement) => this.videoElement = element,
211
212 videoDuration: videoInfo.duration,
213 enableHotkeys: true,
214 peertubeLink: this.peertubeLink,
215 poster: window.location.origin + videoInfo.previewPath,
216 theaterButton: false,
217
218 serverUrl: window.location.origin,
219 language: navigator.language,
220 embedUrl: window.location.origin + videoInfo.embedPath
221 },
222
223 webtorrent: {
224 videoFiles: videoInfo.files
225 }
226 }
227
228 if (this.mode === 'p2p-media-loader') {
229 const hlsPlaylist = videoInfo.streamingPlaylists.find(p => p.type === VideoStreamingPlaylistType.HLS)
230
231 Object.assign(options, {
232 p2pMediaLoader: {
233 playlistUrl: hlsPlaylist.playlistUrl,
234 segmentsSha256Url: hlsPlaylist.segmentsSha256Url,
235 redundancyBaseUrls: hlsPlaylist.redundancies.map(r => r.baseUrl),
236 trackerAnnounce: videoInfo.trackerUrls,
237 videoFiles: hlsPlaylist.files
238 } as P2PMediaLoaderOptions
239 })
240 }
241
242 this.player = await PeertubePlayerManager.initialize(this.mode, options, (player: videojs.Player) => this.player = player)
243 this.player.on('customError', (event: any, data: any) => this.handleError(data.err, serverTranslations))
244
245 window[ 'videojsPlayer' ] = this.player
246
247 this.buildCSS()
248
249 await this.buildDock(videoInfo, configResponse)
250
251 this.initializeApi()
252
253 this.removePlaceholder()
254 }
255
256 private handleError (err: Error, translations?: { [ id: string ]: string }) {
257 if (err.message.indexOf('from xs param') !== -1) {
258 this.player.dispose()
259 this.videoElement = null
260 this.displayError('This video is not available because the remote instance is not responding.', translations)
261 return
262 }
263 }
264
265 private async buildDock (videoInfo: VideoDetails, configResponse: Response) {
266 if (!this.controls) return
267
268 // On webtorrent fallback, player may have been disposed
269 if (!this.player.player_) return
270
271 const title = this.title ? videoInfo.name : undefined
272
273 const config: ServerConfig = await configResponse.json()
274 const description = config.tracker.enabled && this.warningTitle
275 ? '<span class="text">' + peertubeTranslate('Watching this video may reveal your IP address to others.') + '</span>'
276 : undefined
277
278 this.player.dock({
279 title,
280 description
281 })
282 }
283
284 private buildCSS () {
285 const body = document.getElementById('custom-css')
286
287 if (this.bigPlayBackgroundColor) {
288 body.style.setProperty('--embedBigPlayBackgroundColor', this.bigPlayBackgroundColor)
289 }
290
291 if (this.foregroundColor) {
292 body.style.setProperty('--embedForegroundColor', this.foregroundColor)
293 }
294 }
295
296 private async buildCaptions (serverTranslations: any, captionsResponse: Response): Promise<VideoJSCaption[]> {
297 if (captionsResponse.ok) {
298 const { data } = (await captionsResponse.json()) as ResultList<VideoCaption>
299
300 return data.map(c => ({
301 label: peertubeTranslate(c.language.label, serverTranslations),
302 language: c.language.id,
303 src: window.location.origin + c.captionPath
304 }))
305 }
306
307 return []
308 }
309
310 private loadPlaceholder (video: VideoDetails) {
311 const placeholder = this.getPlaceholderElement()
312
313 const url = window.location.origin + video.previewPath
314 placeholder.style.backgroundImage = `url("${url}")`
315 }
316
317 private removePlaceholder () {
318 const placeholder = this.getPlaceholderElement()
319 placeholder.parentElement.removeChild(placeholder)
320 }
321
322 private getPlaceholderElement () {
323 return document.getElementById('placeholder-preview')
324 }
325 }
326
327 PeerTubeEmbed.main()
328 .catch(err => console.error('Cannot init embed.', err))