]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blob - client/src/standalone/videos/embed.ts
Update client dep
[github/Chocobozzz/PeerTube.git] / client / src / standalone / videos / embed.ts
1 import './embed.scss'
2
3 import * as Channel from 'jschannel'
4
5 import { peertubeTranslate, ResultList, VideoDetails } from '../../../../shared'
6 import { PeerTubeResolution } from '../player/definitions'
7 import { VideoJSCaption } from '../../assets/player/peertube-videojs-typings'
8 import { VideoCaption } from '../../../../shared/models/videos/caption/video-caption.model'
9 import {
10 P2PMediaLoaderOptions,
11 PeertubePlayerManager,
12 PeertubePlayerManagerOptions,
13 PlayerMode
14 } from '../../assets/player/peertube-player-manager'
15 import { VideoStreamingPlaylistType } from '../../../../shared/models/videos/video-streaming-playlist.type'
16
17 /**
18 * Embed API exposes control of the embed player to the outside world via
19 * JSChannels and window.postMessage
20 */
21 class PeerTubeEmbedApi {
22 private channel: Channel.MessagingChannel
23 private isReady = false
24 private resolutions: PeerTubeResolution[] = null
25
26 constructor (private embed: PeerTubeEmbed) {
27 }
28
29 initialize () {
30 this.constructChannel()
31 this.setupStateTracking()
32
33 // We're ready!
34
35 this.notifyReady()
36 }
37
38 private get element () {
39 return this.embed.videoElement
40 }
41
42 private constructChannel () {
43 let channel = Channel.build({ window: window.parent, origin: '*', scope: this.embed.scope })
44
45 channel.bind('play', (txn, params) => this.embed.player.play())
46 channel.bind('pause', (txn, params) => this.embed.player.pause())
47 channel.bind('seek', (txn, time) => this.embed.player.currentTime(time))
48 channel.bind('setVolume', (txn, value) => this.embed.player.volume(value))
49 channel.bind('getVolume', (txn, value) => this.embed.player.volume())
50 channel.bind('isReady', (txn, params) => this.isReady)
51 channel.bind('setResolution', (txn, resolutionId) => this.setResolution(resolutionId))
52 channel.bind('getResolutions', (txn, params) => this.resolutions)
53 channel.bind('setPlaybackRate', (txn, playbackRate) => this.embed.player.playbackRate(playbackRate))
54 channel.bind('getPlaybackRate', (txn, params) => this.embed.player.playbackRate())
55 channel.bind('getPlaybackRates', (txn, params) => this.embed.playerOptions.playbackRates)
56
57 this.channel = channel
58 }
59
60 private setResolution (resolutionId: number) {
61 if (resolutionId === -1 && this.embed.player.webtorrent().isAutoResolutionForbidden()) return
62
63 // Auto resolution
64 if (resolutionId === -1) {
65 this.embed.player.webtorrent().enableAutoResolution()
66 return
67 }
68
69 this.embed.player.webtorrent().disableAutoResolution()
70 this.embed.player.webtorrent().updateResolution(resolutionId)
71 }
72
73 /**
74 * Let the host know that we're ready to go!
75 */
76 private notifyReady () {
77 this.isReady = true
78 this.channel.notify({ method: 'ready', params: true })
79 }
80
81 private setupStateTracking () {
82 let currentState: 'playing' | 'paused' | 'unstarted' = 'unstarted'
83
84 setInterval(() => {
85 let position = this.element.currentTime
86 let volume = this.element.volume
87
88 this.channel.notify({
89 method: 'playbackStatusUpdate',
90 params: {
91 position,
92 volume,
93 playbackState: currentState
94 }
95 })
96 }, 500)
97
98 this.element.addEventListener('play', ev => {
99 currentState = 'playing'
100 this.channel.notify({ method: 'playbackStatusChange', params: 'playing' })
101 })
102
103 this.element.addEventListener('pause', ev => {
104 currentState = 'paused'
105 this.channel.notify({ method: 'playbackStatusChange', params: 'paused' })
106 })
107
108 // PeerTube specific capabilities
109
110 if (this.embed.player.webtorrent) {
111 this.embed.player.webtorrent().on('autoResolutionUpdate', () => this.loadWebTorrentResolutions())
112 this.embed.player.webtorrent().on('videoFileUpdate', () => this.loadWebTorrentResolutions())
113 }
114 }
115
116 private loadWebTorrentResolutions () {
117 let resolutions = []
118 let currentResolutionId = this.embed.player.webtorrent().getCurrentResolutionId()
119
120 for (const videoFile of this.embed.player.webtorrent().videoFiles) {
121 let label = videoFile.resolution.label
122 if (videoFile.fps && videoFile.fps >= 50) {
123 label += videoFile.fps
124 }
125
126 resolutions.push({
127 id: videoFile.resolution.id,
128 label,
129 src: videoFile.magnetUri,
130 active: videoFile.resolution.id === currentResolutionId
131 })
132 }
133
134 this.resolutions = resolutions
135 this.channel.notify({
136 method: 'resolutionUpdate',
137 params: this.resolutions
138 })
139 }
140 }
141
142 class PeerTubeEmbed {
143 videoElement: HTMLVideoElement
144 player: any
145 playerOptions: any
146 api: PeerTubeEmbedApi = null
147 autoplay: boolean
148 controls: boolean
149 muted: boolean
150 loop: boolean
151 subtitle: string
152 enableApi = false
153 startTime: number | string = 0
154 stopTime: number | string
155 mode: PlayerMode
156 scope = 'peertube'
157
158 static async main () {
159 const videoContainerId = 'video-container'
160 const embed = new PeerTubeEmbed(videoContainerId)
161 await embed.init()
162 }
163
164 constructor (private videoContainerId: string) {
165 this.videoElement = document.getElementById(videoContainerId) as HTMLVideoElement
166 }
167
168 getVideoUrl (id: string) {
169 return window.location.origin + '/api/v1/videos/' + id
170 }
171
172 loadVideoInfo (videoId: string): Promise<Response> {
173 return fetch(this.getVideoUrl(videoId))
174 }
175
176 loadVideoCaptions (videoId: string): Promise<Response> {
177 return fetch(this.getVideoUrl(videoId) + '/captions')
178 }
179
180 removeElement (element: HTMLElement) {
181 element.parentElement.removeChild(element)
182 }
183
184 displayError (text: string, translations?: { [ id: string ]: string }) {
185 // Remove video element
186 if (this.videoElement) this.removeElement(this.videoElement)
187
188 const translatedText = peertubeTranslate(text, translations)
189 const translatedSorry = peertubeTranslate('Sorry', translations)
190
191 document.title = translatedSorry + ' - ' + translatedText
192
193 const errorBlock = document.getElementById('error-block')
194 errorBlock.style.display = 'flex'
195
196 const errorTitle = document.getElementById('error-title')
197 errorTitle.innerHTML = peertubeTranslate('Sorry', translations)
198
199 const errorText = document.getElementById('error-content')
200 errorText.innerHTML = translatedText
201 }
202
203 videoNotFound (translations?: { [ id: string ]: string }) {
204 const text = 'This video does not exist.'
205 this.displayError(text, translations)
206 }
207
208 videoFetchError (translations?: { [ id: string ]: string }) {
209 const text = 'We cannot fetch the video. Please try again later.'
210 this.displayError(text, translations)
211 }
212
213 getParamToggle (params: URLSearchParams, name: string, defaultValue?: boolean) {
214 return params.has(name) ? (params.get(name) === '1' || params.get(name) === 'true') : defaultValue
215 }
216
217 getParamString (params: URLSearchParams, name: string, defaultValue?: string) {
218 return params.has(name) ? params.get(name) : defaultValue
219 }
220
221 async init () {
222 try {
223 await this.initCore()
224 } catch (e) {
225 console.error(e)
226 }
227 }
228
229 private initializeApi () {
230 if (!this.enableApi) return
231
232 this.api = new PeerTubeEmbedApi(this)
233 this.api.initialize()
234 }
235
236 private loadParams () {
237 try {
238 let params = new URL(window.location.toString()).searchParams
239
240 this.autoplay = this.getParamToggle(params, 'autoplay')
241 this.controls = this.getParamToggle(params, 'controls')
242 this.muted = this.getParamToggle(params, 'muted')
243 this.loop = this.getParamToggle(params, 'loop')
244 this.enableApi = this.getParamToggle(params, 'api', this.enableApi)
245
246 this.scope = this.getParamString(params, 'scope', this.scope)
247 this.subtitle = this.getParamString(params, 'subtitle')
248 this.startTime = this.getParamString(params, 'start')
249 this.stopTime = this.getParamString(params, 'stop')
250
251 this.mode = this.getParamString(params, 'mode') === 'p2p-media-loader' ? 'p2p-media-loader' : 'webtorrent'
252 } catch (err) {
253 console.error('Cannot get params from URL.', err)
254 }
255 }
256
257 private async initCore () {
258 const urlParts = window.location.pathname.split('/')
259 const videoId = urlParts[ urlParts.length - 1 ]
260
261 const [ serverTranslations, videoResponse, captionsResponse ] = await Promise.all([
262 PeertubePlayerManager.getServerTranslations(window.location.origin, navigator.language),
263 this.loadVideoInfo(videoId),
264 this.loadVideoCaptions(videoId)
265 ])
266
267 if (!videoResponse.ok) {
268 if (videoResponse.status === 404) return this.videoNotFound(serverTranslations)
269
270 return this.videoFetchError(serverTranslations)
271 }
272
273 const videoInfo: VideoDetails = await videoResponse.json()
274 let videoCaptions: VideoJSCaption[] = []
275 if (captionsResponse.ok) {
276 const { data } = (await captionsResponse.json()) as ResultList<VideoCaption>
277 videoCaptions = data.map(c => ({
278 label: peertubeTranslate(c.language.label, serverTranslations),
279 language: c.language.id,
280 src: window.location.origin + c.captionPath
281 }))
282 }
283
284 this.loadParams()
285
286 const options: PeertubePlayerManagerOptions = {
287 common: {
288 autoplay: this.autoplay,
289 controls: this.controls,
290 muted: this.muted,
291 loop: this.loop,
292 captions: videoCaptions.length !== 0,
293 startTime: this.startTime,
294 stopTime: this.stopTime,
295 subtitle: this.subtitle,
296
297 videoCaptions,
298 inactivityTimeout: 1500,
299 videoViewUrl: this.getVideoUrl(videoId) + '/views',
300
301 playerElement: this.videoElement,
302 onPlayerElementChange: (element: HTMLVideoElement) => this.videoElement = element,
303
304 videoDuration: videoInfo.duration,
305 enableHotkeys: true,
306 peertubeLink: true,
307 poster: window.location.origin + videoInfo.previewPath,
308 theaterMode: false,
309
310 serverUrl: window.location.origin,
311 language: navigator.language,
312 embedUrl: window.location.origin + videoInfo.embedPath
313 },
314
315 webtorrent: {
316 videoFiles: videoInfo.files
317 }
318 }
319
320 if (this.mode === 'p2p-media-loader') {
321 const hlsPlaylist = videoInfo.streamingPlaylists.find(p => p.type === VideoStreamingPlaylistType.HLS)
322
323 Object.assign(options, {
324 p2pMediaLoader: {
325 playlistUrl: hlsPlaylist.playlistUrl,
326 segmentsSha256Url: hlsPlaylist.segmentsSha256Url,
327 redundancyBaseUrls: hlsPlaylist.redundancies.map(r => r.baseUrl),
328 trackerAnnounce: videoInfo.trackerUrls,
329 videoFiles: videoInfo.files
330 } as P2PMediaLoaderOptions
331 })
332 }
333
334 this.player = await PeertubePlayerManager.initialize(this.mode, options)
335
336 this.player.on('customError', (event: any, data: any) => this.handleError(data.err, serverTranslations))
337
338 window[ 'videojsPlayer' ] = this.player
339
340 if (this.controls) {
341 this.player.dock({
342 title: videoInfo.name,
343 description: this.player.localize('Uses P2P, others may know your IP is downloading this video.')
344 })
345 }
346
347 this.initializeApi()
348 }
349
350 private handleError (err: Error, translations?: { [ id: string ]: string }) {
351 if (err.message.indexOf('from xs param') !== -1) {
352 this.player.dispose()
353 this.videoElement = null
354 this.displayError('This video is not available because the remote instance is not responding.', translations)
355 return
356 }
357 }
358 }
359
360 PeerTubeEmbed.main()
361 .catch(err => console.error('Cannot init embed.', err))