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