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 import * as Channel from 'jschannel'
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'
29 * Embed API exposes control of the embed player to the outside world via
30 * JSChannels and window.postMessage
32 class PeerTubeEmbedApi {
33 private channel: Channel.MessagingChannel
34 private isReady = false
35 private resolutions: PeerTubeResolution[] = null
37 constructor (private embed: PeerTubeEmbed) {
41 this.constructChannel()
42 this.setupStateTracking()
49 private get element () {
50 return this.embed.videoElement
53 private constructChannel () {
54 let channel = Channel.build({ window: window.parent, origin: '*', scope: this.embed.scope })
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)
68 this.channel = channel
71 private setResolution (resolutionId: number) {
72 if (resolutionId === -1 && this.embed.player.webtorrent().isAutoResolutionForbidden()) return
75 if (resolutionId === -1) {
76 this.embed.player.webtorrent().enableAutoResolution()
80 this.embed.player.webtorrent().disableAutoResolution()
81 this.embed.player.webtorrent().updateResolution(resolutionId)
85 * Let the host know that we're ready to go!
87 private notifyReady () {
89 this.channel.notify({ method: 'ready', params: true })
92 private setupStateTracking () {
93 let currentState: 'playing' | 'paused' | 'unstarted' = 'unstarted'
96 let position = this.element.currentTime
97 let volume = this.element.volume
100 method: 'playbackStatusUpdate',
104 playbackState: currentState
109 this.element.addEventListener('play', ev => {
110 currentState = 'playing'
111 this.channel.notify({ method: 'playbackStatusChange', params: 'playing' })
114 this.element.addEventListener('pause', ev => {
115 currentState = 'paused'
116 this.channel.notify({ method: 'playbackStatusChange', params: 'paused' })
119 // PeerTube specific capabilities
121 if (this.embed.player.webtorrent) {
122 this.embed.player.webtorrent().on('autoResolutionUpdate', () => this.loadWebTorrentResolutions())
123 this.embed.player.webtorrent().on('videoFileUpdate', () => this.loadWebTorrentResolutions())
127 private loadWebTorrentResolutions () {
129 let currentResolutionId = this.embed.player.webtorrent().getCurrentResolutionId()
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
138 id: videoFile.resolution.id,
140 src: videoFile.magnetUri,
141 active: videoFile.resolution.id === currentResolutionId
145 this.resolutions = resolutions
146 this.channel.notify({
147 method: 'resolutionUpdate',
148 params: this.resolutions
153 class PeerTubeEmbed {
154 videoElement: HTMLVideoElement
157 api: PeerTubeEmbedApi = null
164 startTime: number | string = 0
167 static async main () {
168 const videoContainerId = 'video-container'
169 const embed = new PeerTubeEmbed(videoContainerId)
173 constructor (private videoContainerId: string) {
174 this.videoElement = document.getElementById(videoContainerId) as HTMLVideoElement
177 getVideoUrl (id: string) {
178 return window.location.origin + '/api/v1/videos/' + id
181 loadVideoInfo (videoId: string): Promise<Response> {
182 return fetch(this.getVideoUrl(videoId))
185 loadVideoCaptions (videoId: string): Promise<Response> {
186 return fetch(this.getVideoUrl(videoId) + '/captions')
189 removeElement (element: HTMLElement) {
190 element.parentElement.removeChild(element)
193 displayError (text: string, translations?: { [ id: string ]: string }) {
194 // Remove video element
195 if (this.videoElement) this.removeElement(this.videoElement)
197 const translatedText = peertubeTranslate(text, translations)
198 const translatedSorry = peertubeTranslate('Sorry', translations)
200 document.title = translatedSorry + ' - ' + translatedText
202 const errorBlock = document.getElementById('error-block')
203 errorBlock.style.display = 'flex'
205 const errorTitle = document.getElementById('error-title')
206 errorTitle.innerHTML = peertubeTranslate('Sorry', translations)
208 const errorText = document.getElementById('error-content')
209 errorText.innerHTML = translatedText
212 videoNotFound (translations?: { [ id: string ]: string }) {
213 const text = 'This video does not exist.'
214 this.displayError(text, translations)
217 videoFetchError (translations?: { [ id: string ]: string }) {
218 const text = 'We cannot fetch the video. Please try again later.'
219 this.displayError(text, translations)
222 getParamToggle (params: URLSearchParams, name: string, defaultValue?: boolean) {
223 return params.has(name) ? (params.get(name) === '1' || params.get(name) === 'true') : defaultValue
226 getParamString (params: URLSearchParams, name: string, defaultValue?: string) {
227 return params.has(name) ? params.get(name) : defaultValue
232 await this.initCore()
238 private initializeApi () {
239 if (!this.enableApi) return
241 this.api = new PeerTubeEmbedApi(this)
242 this.api.initialize()
245 private loadParams () {
247 let params = new URL(window.location.toString()).searchParams
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)
255 this.scope = this.getParamString(params, 'scope', this.scope)
256 this.subtitle = this.getParamString(params, 'subtitle')
257 this.startTime = this.getParamString(params, 'start')
259 console.error('Cannot get params from URL.', err)
263 private async initCore () {
264 const urlParts = window.location.pathname.split('/')
265 const videoId = urlParts[ urlParts.length - 1 ]
267 const [ serverTranslations, videoResponse, captionsResponse ] = await Promise.all([
268 PeertubePlayerManager.getServerTranslations(window.location.origin, navigator.language),
269 this.loadVideoInfo(videoId),
270 this.loadVideoCaptions(videoId)
273 if (!videoResponse.ok) {
274 if (videoResponse.status === 404) return this.videoNotFound(serverTranslations)
276 return this.videoFetchError(serverTranslations)
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
292 const options: PeertubePlayerManagerOptions = {
294 autoplay: this.autoplay,
295 controls: this.controls,
298 captions: videoCaptions.length !== 0,
299 startTime: this.startTime,
300 subtitle: this.subtitle,
303 inactivityTimeout: 1500,
304 videoViewUrl: this.getVideoUrl(videoId) + '/views',
305 playerElement: this.videoElement,
306 videoDuration: videoInfo.duration,
309 poster: window.location.origin + videoInfo.previewPath,
312 serverUrl: window.location.origin,
313 language: navigator.language,
314 embedUrl: window.location.origin + videoInfo.embedPath
318 videoFiles: videoInfo.files
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'
328 this.player = await PeertubePlayerManager.initialize('webtorrent', options)
330 this.player.on('customError', (event: any, data: any) => this.handleError(data.err, serverTranslations))
332 window[ 'videojsPlayer' ] = this.player
336 title: videoInfo.name,
337 description: this.player.localize('Uses P2P, others may know your IP is downloading this video.')
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)
355 .catch(err => console.error('Cannot init embed.', err))