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