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