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
20 // FIXME: something weird with our path definition in tsconfig and typings
22 import * as vjs from 'video.js'
24 import * as Channel from 'jschannel'
26 import { peertubeTranslate, ResultList, VideoDetails } from '../../../../shared'
27 import { addContextMenu, getServerTranslations, getVideojsOptions, loadLocaleInVideoJS } from '../../assets/player/peertube-player'
28 import { PeerTubeResolution } from '../player/definitions'
29 import { VideoJSCaption } from '../../assets/player/peertube-videojs-typings'
30 import { VideoCaption } from '../../../../shared/models/videos/caption/video-caption.model'
33 * Embed API exposes control of the embed player to the outside world via
34 * JSChannels and window.postMessage
36 class PeerTubeEmbedApi {
37 private channel: Channel.MessagingChannel
38 private isReady = false
39 private resolutions: PeerTubeResolution[] = null
41 constructor (private embed: PeerTubeEmbed) {
45 this.constructChannel()
46 this.setupStateTracking()
53 private get element () {
54 return this.embed.videoElement
57 private constructChannel () {
58 let channel = Channel.build({ window: window.parent, origin: '*', scope: this.embed.scope })
60 channel.bind('play', (txn, params) => this.embed.player.play())
61 channel.bind('pause', (txn, params) => this.embed.player.pause())
62 channel.bind('seek', (txn, time) => this.embed.player.currentTime(time))
63 channel.bind('setVolume', (txn, value) => this.embed.player.volume(value))
64 channel.bind('getVolume', (txn, value) => this.embed.player.volume())
65 channel.bind('isReady', (txn, params) => this.isReady)
66 channel.bind('setResolution', (txn, resolutionId) => this.setResolution(resolutionId))
67 channel.bind('getResolutions', (txn, params) => this.resolutions)
68 channel.bind('setPlaybackRate', (txn, playbackRate) => this.embed.player.playbackRate(playbackRate))
69 channel.bind('getPlaybackRate', (txn, params) => this.embed.player.playbackRate())
70 channel.bind('getPlaybackRates', (txn, params) => this.embed.playerOptions.playbackRates)
72 this.channel = channel
75 private setResolution (resolutionId: number) {
76 if (resolutionId === -1 && this.embed.player.peertube().isAutoResolutionForbidden()) return
79 if (resolutionId === -1) {
80 this.embed.player.peertube().enableAutoResolution()
84 this.embed.player.peertube().disableAutoResolution()
85 this.embed.player.peertube().updateResolution(resolutionId)
89 * Let the host know that we're ready to go!
91 private notifyReady () {
93 this.channel.notify({ method: 'ready', params: true })
96 private setupStateTracking () {
97 let currentState: 'playing' | 'paused' | 'unstarted' = 'unstarted'
100 let position = this.element.currentTime
101 let volume = this.element.volume
103 this.channel.notify({
104 method: 'playbackStatusUpdate',
108 playbackState: currentState
113 this.element.addEventListener('play', ev => {
114 currentState = 'playing'
115 this.channel.notify({ method: 'playbackStatusChange', params: 'playing' })
118 this.element.addEventListener('pause', ev => {
119 currentState = 'paused'
120 this.channel.notify({ method: 'playbackStatusChange', params: 'paused' })
123 // PeerTube specific capabilities
125 this.embed.player.peertube().on('autoResolutionUpdate', () => this.loadResolutions())
126 this.embed.player.peertube().on('videoFileUpdate', () => this.loadResolutions())
129 private loadResolutions () {
131 let currentResolutionId = this.embed.player.peertube().getCurrentResolutionId()
133 for (const videoFile of this.embed.player.peertube().videoFiles) {
134 let label = videoFile.resolution.label
135 if (videoFile.fps && videoFile.fps >= 50) {
136 label += videoFile.fps
140 id: videoFile.resolution.id,
142 src: videoFile.magnetUri,
143 active: videoFile.resolution.id === currentResolutionId
147 this.resolutions = resolutions
148 this.channel.notify({
149 method: 'resolutionUpdate',
150 params: this.resolutions
155 class PeerTubeEmbed {
156 videoElement: HTMLVideoElement
159 api: PeerTubeEmbedApi = null
165 startTime: number | string = 0
168 static async main () {
169 const videoContainerId = 'video-container'
170 const embed = new PeerTubeEmbed(videoContainerId)
174 constructor (private videoContainerId: string) {
175 this.videoElement = document.getElementById(videoContainerId) as HTMLVideoElement
178 getVideoUrl (id: string) {
179 return window.location.origin + '/api/v1/videos/' + id
182 loadVideoInfo (videoId: string): Promise<Response> {
183 return fetch(this.getVideoUrl(videoId))
186 loadVideoCaptions (videoId: string): Promise<Response> {
187 return fetch(this.getVideoUrl(videoId) + '/captions')
190 removeElement (element: HTMLElement) {
191 element.parentElement.removeChild(element)
194 displayError (text: string) {
195 // Remove video element
196 if (this.videoElement) this.removeElement(this.videoElement)
198 document.title = 'Sorry - ' + text
200 const errorBlock = document.getElementById('error-block')
201 errorBlock.style.display = 'flex'
203 const errorText = document.getElementById('error-content')
204 errorText.innerHTML = text
208 const text = 'This video does not exist.'
209 this.displayError(text)
213 const text = 'We cannot fetch the video. Please try again later.'
214 this.displayError(text)
217 getParamToggle (params: URLSearchParams, name: string, defaultValue: boolean) {
218 return params.has(name) ? (params.get(name) === '1' || params.get(name) === 'true') : defaultValue
221 getParamString (params: URLSearchParams, name: string, defaultValue: string) {
222 return params.has(name) ? params.get(name) : defaultValue
227 await this.initCore()
233 private initializeApi () {
234 if (!this.enableApi) return
236 this.api = new PeerTubeEmbedApi(this)
237 this.api.initialize()
240 private loadParams () {
242 let params = new URL(window.location.toString()).searchParams
244 this.autoplay = this.getParamToggle(params, 'autoplay', this.autoplay)
245 this.controls = this.getParamToggle(params, 'controls', this.controls)
246 this.muted = this.getParamToggle(params, 'muted', this.muted)
247 this.loop = this.getParamToggle(params, 'loop', this.loop)
248 this.enableApi = this.getParamToggle(params, 'api', this.enableApi)
249 this.scope = this.getParamString(params, 'scope', this.scope)
251 const startTimeParamString = params.get('start')
252 if (startTimeParamString) this.startTime = startTimeParamString
254 console.error('Cannot get params from URL.', err)
258 private async initCore () {
259 const urlParts = window.location.href.split('/')
260 const lastPart = urlParts[ urlParts.length - 1 ]
261 const videoId = lastPart.indexOf('?') === -1 ? lastPart : lastPart.split('?')[ 0 ]
263 const [ , serverTranslations, videoResponse, captionsResponse ] = await Promise.all([
264 loadLocaleInVideoJS(window.location.origin, vjs, navigator.language),
265 getServerTranslations(window.location.origin, navigator.language),
266 this.loadVideoInfo(videoId),
267 this.loadVideoCaptions(videoId)
270 if (!videoResponse.ok) {
271 if (videoResponse.status === 404) return this.videoNotFound()
273 return this.videoFetchError()
276 const videoInfo: VideoDetails = await videoResponse.json()
277 let videoCaptions: VideoJSCaption[] = []
278 if (captionsResponse.ok) {
279 const { data } = (await captionsResponse.json()) as ResultList<VideoCaption>
280 videoCaptions = data.map(c => ({
281 label: peertubeTranslate(c.language.label, serverTranslations),
282 language: c.language.id,
283 src: window.location.origin + c.captionPath
289 const videojsOptions = getVideojsOptions({
290 autoplay: this.autoplay,
291 controls: this.controls,
294 startTime: this.startTime,
297 inactivityTimeout: 1500,
298 videoViewUrl: this.getVideoUrl(videoId) + '/views',
299 playerElement: this.videoElement,
300 videoFiles: videoInfo.files,
301 videoDuration: videoInfo.duration,
304 poster: window.location.origin + videoInfo.previewPath,
308 this.playerOptions = videojsOptions
309 this.player = vjs(this.videoContainerId, videojsOptions, () => {
310 this.player.on('customError', (event: any, data: any) => this.handleError(data.err))
312 window[ 'videojsPlayer' ] = this.player
316 title: videoInfo.name,
317 description: this.player.localize('Uses P2P, others may know your IP is downloading this video.')
321 addContextMenu(this.player, window.location.origin + videoInfo.embedPath)
327 private handleError (err: Error) {
328 if (err.message.indexOf('from xs param') !== -1) {
329 this.player.dispose()
330 this.videoElement = null
331 this.displayError('This video is not available because the remote instance is not responding.')
338 .catch(err => console.error('Cannot init embed.', err))