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'
27 P2PMediaLoaderOptions,
28 PeertubePlayerManager,
29 PeertubePlayerManagerOptions,
31 } from '../../assets/player/peertube-player-manager'
32 import { VideoStreamingPlaylistType } from '../../../../shared/models/videos/video-streaming-playlist.type'
35 * Embed API exposes control of the embed player to the outside world via
36 * JSChannels and window.postMessage
38 class PeerTubeEmbedApi {
39 private channel: Channel.MessagingChannel
40 private isReady = false
41 private resolutions: PeerTubeResolution[] = null
43 constructor (private embed: PeerTubeEmbed) {
47 this.constructChannel()
48 this.setupStateTracking()
55 private get element () {
56 return this.embed.videoElement
59 private constructChannel () {
60 let channel = Channel.build({ window: window.parent, origin: '*', scope: this.embed.scope })
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)
74 this.channel = channel
77 private setResolution (resolutionId: number) {
78 if (resolutionId === -1 && this.embed.player.webtorrent().isAutoResolutionForbidden()) return
81 if (resolutionId === -1) {
82 this.embed.player.webtorrent().enableAutoResolution()
86 this.embed.player.webtorrent().disableAutoResolution()
87 this.embed.player.webtorrent().updateResolution(resolutionId)
91 * Let the host know that we're ready to go!
93 private notifyReady () {
95 this.channel.notify({ method: 'ready', params: true })
98 private setupStateTracking () {
99 let currentState: 'playing' | 'paused' | 'unstarted' = 'unstarted'
102 let position = this.element.currentTime
103 let volume = this.element.volume
105 this.channel.notify({
106 method: 'playbackStatusUpdate',
110 playbackState: currentState
115 this.element.addEventListener('play', ev => {
116 currentState = 'playing'
117 this.channel.notify({ method: 'playbackStatusChange', params: 'playing' })
120 this.element.addEventListener('pause', ev => {
121 currentState = 'paused'
122 this.channel.notify({ method: 'playbackStatusChange', params: 'paused' })
125 // PeerTube specific capabilities
127 if (this.embed.player.webtorrent) {
128 this.embed.player.webtorrent().on('autoResolutionUpdate', () => this.loadWebTorrentResolutions())
129 this.embed.player.webtorrent().on('videoFileUpdate', () => this.loadWebTorrentResolutions())
133 private loadWebTorrentResolutions () {
135 let currentResolutionId = this.embed.player.webtorrent().getCurrentResolutionId()
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
144 id: videoFile.resolution.id,
146 src: videoFile.magnetUri,
147 active: videoFile.resolution.id === currentResolutionId
151 this.resolutions = resolutions
152 this.channel.notify({
153 method: 'resolutionUpdate',
154 params: this.resolutions
159 class PeerTubeEmbed {
160 videoElement: HTMLVideoElement
163 api: PeerTubeEmbedApi = null
170 startTime: number | string = 0
174 static async main () {
175 const videoContainerId = 'video-container'
176 const embed = new PeerTubeEmbed(videoContainerId)
180 constructor (private videoContainerId: string) {
181 this.videoElement = document.getElementById(videoContainerId) as HTMLVideoElement
184 getVideoUrl (id: string) {
185 return window.location.origin + '/api/v1/videos/' + id
188 loadVideoInfo (videoId: string): Promise<Response> {
189 return fetch(this.getVideoUrl(videoId))
192 loadVideoCaptions (videoId: string): Promise<Response> {
193 return fetch(this.getVideoUrl(videoId) + '/captions')
196 removeElement (element: HTMLElement) {
197 element.parentElement.removeChild(element)
200 displayError (text: string, translations?: { [ id: string ]: string }) {
201 // Remove video element
202 if (this.videoElement) this.removeElement(this.videoElement)
204 const translatedText = peertubeTranslate(text, translations)
205 const translatedSorry = peertubeTranslate('Sorry', translations)
207 document.title = translatedSorry + ' - ' + translatedText
209 const errorBlock = document.getElementById('error-block')
210 errorBlock.style.display = 'flex'
212 const errorTitle = document.getElementById('error-title')
213 errorTitle.innerHTML = peertubeTranslate('Sorry', translations)
215 const errorText = document.getElementById('error-content')
216 errorText.innerHTML = translatedText
219 videoNotFound (translations?: { [ id: string ]: string }) {
220 const text = 'This video does not exist.'
221 this.displayError(text, translations)
224 videoFetchError (translations?: { [ id: string ]: string }) {
225 const text = 'We cannot fetch the video. Please try again later.'
226 this.displayError(text, translations)
229 getParamToggle (params: URLSearchParams, name: string, defaultValue?: boolean) {
230 return params.has(name) ? (params.get(name) === '1' || params.get(name) === 'true') : defaultValue
233 getParamString (params: URLSearchParams, name: string, defaultValue?: string) {
234 return params.has(name) ? params.get(name) : defaultValue
239 await this.initCore()
245 private initializeApi () {
246 if (!this.enableApi) return
248 this.api = new PeerTubeEmbedApi(this)
249 this.api.initialize()
252 private loadParams () {
254 let params = new URL(window.location.toString()).searchParams
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)
262 this.scope = this.getParamString(params, 'scope', this.scope)
263 this.subtitle = this.getParamString(params, 'subtitle')
264 this.startTime = this.getParamString(params, 'start')
266 this.mode = this.getParamString(params, 'mode') === 'p2p-media-loader' ? 'p2p-media-loader' : 'webtorrent'
268 console.error('Cannot get params from URL.', err)
272 private async initCore () {
273 const urlParts = window.location.pathname.split('/')
274 const videoId = urlParts[ urlParts.length - 1 ]
276 const [ serverTranslations, videoResponse, captionsResponse ] = await Promise.all([
277 PeertubePlayerManager.getServerTranslations(window.location.origin, navigator.language),
278 this.loadVideoInfo(videoId),
279 this.loadVideoCaptions(videoId)
282 if (!videoResponse.ok) {
283 if (videoResponse.status === 404) return this.videoNotFound(serverTranslations)
285 return this.videoFetchError(serverTranslations)
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
301 const options: PeertubePlayerManagerOptions = {
303 autoplay: this.autoplay,
304 controls: this.controls,
307 captions: videoCaptions.length !== 0,
308 startTime: this.startTime,
309 subtitle: this.subtitle,
312 inactivityTimeout: 1500,
313 videoViewUrl: this.getVideoUrl(videoId) + '/views',
315 playerElement: this.videoElement,
316 onPlayerElementChange: (element: HTMLVideoElement) => this.videoElement = element,
318 videoDuration: videoInfo.duration,
321 poster: window.location.origin + videoInfo.previewPath,
324 serverUrl: window.location.origin,
325 language: navigator.language,
326 embedUrl: window.location.origin + videoInfo.embedPath
330 videoFiles: videoInfo.files
334 if (this.mode === 'p2p-media-loader') {
335 const hlsPlaylist = videoInfo.streamingPlaylists.find(p => p.type === VideoStreamingPlaylistType.HLS)
337 Object.assign(options, {
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
348 this.player = await PeertubePlayerManager.initialize(this.mode, options)
350 this.player.on('customError', (event: any, data: any) => this.handleError(data.err, serverTranslations))
352 window[ 'videojsPlayer' ] = this.player
356 title: videoInfo.name,
357 description: this.player.localize('Uses P2P, others may know your IP is downloading this video.')
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)
375 .catch(err => console.error('Cannot init embed.', err))