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