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