]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blob - client/src/standalone/videos/embed.ts
Add lazy loading in player
[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, PlayerMode } 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 mode: PlayerMode
166 scope = 'peertube'
167
168 static async main () {
169 const videoContainerId = 'video-container'
170 const embed = new PeerTubeEmbed(videoContainerId)
171 await embed.init()
172 }
173
174 constructor (private videoContainerId: string) {
175 this.videoElement = document.getElementById(videoContainerId) as HTMLVideoElement
176 }
177
178 getVideoUrl (id: string) {
179 return window.location.origin + '/api/v1/videos/' + id
180 }
181
182 loadVideoInfo (videoId: string): Promise<Response> {
183 return fetch(this.getVideoUrl(videoId))
184 }
185
186 loadVideoCaptions (videoId: string): Promise<Response> {
187 return fetch(this.getVideoUrl(videoId) + '/captions')
188 }
189
190 removeElement (element: HTMLElement) {
191 element.parentElement.removeChild(element)
192 }
193
194 displayError (text: string, translations?: { [ id: string ]: string }) {
195 // Remove video element
196 if (this.videoElement) this.removeElement(this.videoElement)
197
198 const translatedText = peertubeTranslate(text, translations)
199 const translatedSorry = peertubeTranslate('Sorry', translations)
200
201 document.title = translatedSorry + ' - ' + translatedText
202
203 const errorBlock = document.getElementById('error-block')
204 errorBlock.style.display = 'flex'
205
206 const errorTitle = document.getElementById('error-title')
207 errorTitle.innerHTML = peertubeTranslate('Sorry', translations)
208
209 const errorText = document.getElementById('error-content')
210 errorText.innerHTML = translatedText
211 }
212
213 videoNotFound (translations?: { [ id: string ]: string }) {
214 const text = 'This video does not exist.'
215 this.displayError(text, translations)
216 }
217
218 videoFetchError (translations?: { [ id: string ]: string }) {
219 const text = 'We cannot fetch the video. Please try again later.'
220 this.displayError(text, translations)
221 }
222
223 getParamToggle (params: URLSearchParams, name: string, defaultValue?: boolean) {
224 return params.has(name) ? (params.get(name) === '1' || params.get(name) === 'true') : defaultValue
225 }
226
227 getParamString (params: URLSearchParams, name: string, defaultValue?: string) {
228 return params.has(name) ? params.get(name) : defaultValue
229 }
230
231 async init () {
232 try {
233 await this.initCore()
234 } catch (e) {
235 console.error(e)
236 }
237 }
238
239 private initializeApi () {
240 if (!this.enableApi) return
241
242 this.api = new PeerTubeEmbedApi(this)
243 this.api.initialize()
244 }
245
246 private loadParams () {
247 try {
248 let params = new URL(window.location.toString()).searchParams
249
250 this.autoplay = this.getParamToggle(params, 'autoplay')
251 this.controls = this.getParamToggle(params, 'controls')
252 this.muted = this.getParamToggle(params, 'muted')
253 this.loop = this.getParamToggle(params, 'loop')
254 this.enableApi = this.getParamToggle(params, 'api', this.enableApi)
255
256 this.scope = this.getParamString(params, 'scope', this.scope)
257 this.subtitle = this.getParamString(params, 'subtitle')
258 this.startTime = this.getParamString(params, 'start')
259
260 this.mode = this.getParamToggle(params, 'p2p-media-loader') ? 'p2p-media-loader' : 'webtorrent'
261 } catch (err) {
262 console.error('Cannot get params from URL.', err)
263 }
264 }
265
266 private async initCore () {
267 const urlParts = window.location.pathname.split('/')
268 const videoId = urlParts[ urlParts.length - 1 ]
269
270 const [ serverTranslations, videoResponse, captionsResponse ] = await Promise.all([
271 PeertubePlayerManager.getServerTranslations(window.location.origin, navigator.language),
272 this.loadVideoInfo(videoId),
273 this.loadVideoCaptions(videoId)
274 ])
275
276 if (!videoResponse.ok) {
277 if (videoResponse.status === 404) return this.videoNotFound(serverTranslations)
278
279 return this.videoFetchError(serverTranslations)
280 }
281
282 const videoInfo: VideoDetails = await videoResponse.json()
283 let videoCaptions: VideoJSCaption[] = []
284 if (captionsResponse.ok) {
285 const { data } = (await captionsResponse.json()) as ResultList<VideoCaption>
286 videoCaptions = data.map(c => ({
287 label: peertubeTranslate(c.language.label, serverTranslations),
288 language: c.language.id,
289 src: window.location.origin + c.captionPath
290 }))
291 }
292
293 this.loadParams()
294
295 const options: PeertubePlayerManagerOptions = {
296 common: {
297 autoplay: this.autoplay,
298 controls: this.controls,
299 muted: this.muted,
300 loop: this.loop,
301 captions: videoCaptions.length !== 0,
302 startTime: this.startTime,
303 subtitle: this.subtitle,
304
305 videoCaptions,
306 inactivityTimeout: 1500,
307 videoViewUrl: this.getVideoUrl(videoId) + '/views',
308 playerElement: this.videoElement,
309 videoDuration: videoInfo.duration,
310 enableHotkeys: true,
311 peertubeLink: true,
312 poster: window.location.origin + videoInfo.previewPath,
313 theaterMode: false,
314
315 serverUrl: window.location.origin,
316 language: navigator.language,
317 embedUrl: window.location.origin + videoInfo.embedPath
318 }
319 }
320
321 if (this.mode === 'p2p-media-loader') {
322 Object.assign(options, {
323 p2pMediaLoader: {
324 // playlistUrl: 'https://akamai-axtest.akamaized.net/routes/lapd-v1-acceptance/www_c4/Manifest.m3u8'
325 // playlistUrl: 'https://d2zihajmogu5jn.cloudfront.net/bipbop-advanced/bipbop_16x9_variant.m3u8'
326 // trackerAnnounce: [ window.location.origin.replace(/^http/, 'ws') + '/tracker/socket' ],
327 playlistUrl: 'https://cdn.theoplayer.com/video/elephants-dream/playlist.m3u8'
328 }
329 })
330 } else {
331 Object.assign(options, {
332 webtorrent: {
333 videoFiles: videoInfo.files
334 }
335 })
336 }
337
338 this.player = await PeertubePlayerManager.initialize(this.mode, options)
339
340 this.player.on('customError', (event: any, data: any) => this.handleError(data.err, serverTranslations))
341
342 window[ 'videojsPlayer' ] = this.player
343
344 if (this.controls) {
345 this.player.dock({
346 title: videoInfo.name,
347 description: this.player.localize('Uses P2P, others may know your IP is downloading this video.')
348 })
349 }
350
351 this.initializeApi()
352 }
353
354 private handleError (err: Error, translations?: { [ id: string ]: string }) {
355 if (err.message.indexOf('from xs param') !== -1) {
356 this.player.dispose()
357 this.videoElement = null
358 this.displayError('This video is not available because the remote instance is not responding.', translations)
359 return
360 }
361 }
362 }
363
364 PeerTubeEmbed.main()
365 .catch(err => console.error('Cannot init embed.', err))