3 import * as Channel from 'jschannel'
5 import { peertubeTranslate, ResultList, ServerConfig, VideoDetails } from '../../../../shared'
6 import { PeerTubeResolution } from '../player/definitions'
7 import { VideoJSCaption } from '../../assets/player/peertube-videojs-typings'
8 import { VideoCaption } from '../../../../shared/models/videos/caption/video-caption.model'
10 P2PMediaLoaderOptions,
11 PeertubePlayerManager,
12 PeertubePlayerManagerOptions,
14 } from '../../assets/player/peertube-player-manager'
15 import { VideoStreamingPlaylistType } from '../../../../shared/models/videos/video-streaming-playlist.type'
18 * Embed API exposes control of the embed player to the outside world via
19 * JSChannels and window.postMessage
21 class PeerTubeEmbedApi {
22 private channel: Channel.MessagingChannel
23 private isReady = false
24 private resolutions: PeerTubeResolution[] = null
26 constructor (private embed: PeerTubeEmbed) {
30 this.constructChannel()
31 this.setupStateTracking()
38 private get element () {
39 return this.embed.videoElement
42 private constructChannel () {
43 const channel = Channel.build({ window: window.parent, origin: '*', scope: this.embed.scope })
45 channel.bind('play', (txn, params) => this.embed.player.play())
46 channel.bind('pause', (txn, params) => this.embed.player.pause())
47 channel.bind('seek', (txn, time) => this.embed.player.currentTime(time))
48 channel.bind('setVolume', (txn, value) => this.embed.player.volume(value))
49 channel.bind('getVolume', (txn, value) => this.embed.player.volume())
50 channel.bind('isReady', (txn, params) => this.isReady)
51 channel.bind('setResolution', (txn, resolutionId) => this.setResolution(resolutionId))
52 channel.bind('getResolutions', (txn, params) => this.resolutions)
53 channel.bind('setPlaybackRate', (txn, playbackRate) => this.embed.player.playbackRate(playbackRate))
54 channel.bind('getPlaybackRate', (txn, params) => this.embed.player.playbackRate())
55 channel.bind('getPlaybackRates', (txn, params) => this.embed.playerOptions.playbackRates)
57 this.channel = channel
60 private setResolution (resolutionId: number) {
61 if (resolutionId === -1 && this.embed.player.webtorrent().isAutoResolutionForbidden()) return
64 if (resolutionId === -1) {
65 this.embed.player.webtorrent().enableAutoResolution()
69 this.embed.player.webtorrent().disableAutoResolution()
70 this.embed.player.webtorrent().updateResolution(resolutionId)
74 * Let the host know that we're ready to go!
76 private notifyReady () {
78 this.channel.notify({ method: 'ready', params: true })
81 private setupStateTracking () {
82 let currentState: 'playing' | 'paused' | 'unstarted' = 'unstarted'
85 const position = this.element.currentTime
86 const volume = this.element.volume
89 method: 'playbackStatusUpdate',
93 playbackState: currentState
98 this.element.addEventListener('play', ev => {
99 currentState = 'playing'
100 this.channel.notify({ method: 'playbackStatusChange', params: 'playing' })
103 this.element.addEventListener('pause', ev => {
104 currentState = 'paused'
105 this.channel.notify({ method: 'playbackStatusChange', params: 'paused' })
108 // PeerTube specific capabilities
110 if (this.embed.player.webtorrent) {
111 this.embed.player.webtorrent().on('autoResolutionUpdate', () => this.loadWebTorrentResolutions())
112 this.embed.player.webtorrent().on('videoFileUpdate', () => this.loadWebTorrentResolutions())
116 private loadWebTorrentResolutions () {
117 const resolutions = []
118 const currentResolutionId = this.embed.player.webtorrent().getCurrentResolutionId()
120 for (const videoFile of this.embed.player.webtorrent().videoFiles) {
121 let label = videoFile.resolution.label
122 if (videoFile.fps && videoFile.fps >= 50) {
123 label += videoFile.fps
127 id: videoFile.resolution.id,
129 src: videoFile.magnetUri,
130 active: videoFile.resolution.id === currentResolutionId
134 this.resolutions = resolutions
135 this.channel.notify({
136 method: 'resolutionUpdate',
137 params: this.resolutions
142 class PeerTubeEmbed {
143 videoElement: HTMLVideoElement
146 api: PeerTubeEmbedApi = null
153 startTime: number | string = 0
154 stopTime: number | string
158 static async main () {
159 const videoContainerId = 'video-container'
160 const embed = new PeerTubeEmbed(videoContainerId)
164 constructor (private videoContainerId: string) {
165 this.videoElement = document.getElementById(videoContainerId) as HTMLVideoElement
168 getVideoUrl (id: string) {
169 return window.location.origin + '/api/v1/videos/' + id
172 loadVideoInfo (videoId: string): Promise<Response> {
173 return fetch(this.getVideoUrl(videoId))
176 loadVideoCaptions (videoId: string): Promise<Response> {
177 return fetch(this.getVideoUrl(videoId) + '/captions')
180 loadConfig (): Promise<Response> {
181 return fetch('/api/v1/config')
184 removeElement (element: HTMLElement) {
185 element.parentElement.removeChild(element)
188 displayError (text: string, translations?: { [ id: string ]: string }) {
189 // Remove video element
190 if (this.videoElement) this.removeElement(this.videoElement)
192 const translatedText = peertubeTranslate(text, translations)
193 const translatedSorry = peertubeTranslate('Sorry', translations)
195 document.title = translatedSorry + ' - ' + translatedText
197 const errorBlock = document.getElementById('error-block')
198 errorBlock.style.display = 'flex'
200 const errorTitle = document.getElementById('error-title')
201 errorTitle.innerHTML = peertubeTranslate('Sorry', translations)
203 const errorText = document.getElementById('error-content')
204 errorText.innerHTML = translatedText
207 videoNotFound (translations?: { [ id: string ]: string }) {
208 const text = 'This video does not exist.'
209 this.displayError(text, translations)
212 videoFetchError (translations?: { [ id: string ]: string }) {
213 const text = 'We cannot fetch the video. Please try again later.'
214 this.displayError(text, translations)
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 const params = new URL(window.location.toString()).searchParams
244 this.autoplay = this.getParamToggle(params, 'autoplay', false)
245 this.controls = this.getParamToggle(params, 'controls', true)
246 this.muted = this.getParamToggle(params, 'muted', false)
247 this.loop = this.getParamToggle(params, 'loop', false)
248 this.enableApi = this.getParamToggle(params, 'api', this.enableApi)
250 this.scope = this.getParamString(params, 'scope', this.scope)
251 this.subtitle = this.getParamString(params, 'subtitle')
252 this.startTime = this.getParamString(params, 'start')
253 this.stopTime = this.getParamString(params, 'stop')
255 this.mode = this.getParamString(params, 'mode') === 'p2p-media-loader' ? 'p2p-media-loader' : 'webtorrent'
257 console.error('Cannot get params from URL.', err)
261 private async initCore () {
262 const urlParts = window.location.pathname.split('/')
263 const videoId = urlParts[ urlParts.length - 1 ]
265 const [ serverTranslations, videoResponse, captionsResponse, configResponse ] = await Promise.all([
266 PeertubePlayerManager.getServerTranslations(window.location.origin, navigator.language),
267 this.loadVideoInfo(videoId),
268 this.loadVideoCaptions(videoId),
272 if (!videoResponse.ok) {
273 if (videoResponse.status === 404) return this.videoNotFound(serverTranslations)
275 return this.videoFetchError(serverTranslations)
278 const videoInfo: VideoDetails = await videoResponse.json()
279 let videoCaptions: VideoJSCaption[] = []
280 if (captionsResponse.ok) {
281 const { data } = (await captionsResponse.json()) as ResultList<VideoCaption>
282 videoCaptions = data.map(c => ({
283 label: peertubeTranslate(c.language.label, serverTranslations),
284 language: c.language.id,
285 src: window.location.origin + c.captionPath
291 const options: PeertubePlayerManagerOptions = {
293 autoplay: this.autoplay,
294 controls: this.controls,
297 captions: videoCaptions.length !== 0,
298 startTime: this.startTime,
299 stopTime: this.stopTime,
300 subtitle: this.subtitle,
303 inactivityTimeout: 1500,
304 videoViewUrl: this.getVideoUrl(videoId) + '/views',
306 playerElement: this.videoElement,
307 onPlayerElementChange: (element: HTMLVideoElement) => this.videoElement = element,
309 videoDuration: videoInfo.duration,
312 poster: window.location.origin + videoInfo.previewPath,
315 serverUrl: window.location.origin,
316 language: navigator.language,
317 embedUrl: window.location.origin + videoInfo.embedPath
321 videoFiles: videoInfo.files
325 if (this.mode === 'p2p-media-loader') {
326 const hlsPlaylist = videoInfo.streamingPlaylists.find(p => p.type === VideoStreamingPlaylistType.HLS)
328 Object.assign(options, {
330 playlistUrl: hlsPlaylist.playlistUrl,
331 segmentsSha256Url: hlsPlaylist.segmentsSha256Url,
332 redundancyBaseUrls: hlsPlaylist.redundancies.map(r => r.baseUrl),
333 trackerAnnounce: videoInfo.trackerUrls,
334 videoFiles: videoInfo.files
335 } as P2PMediaLoaderOptions
339 this.player = await PeertubePlayerManager.initialize(this.mode, options)
341 this.player.on('customError', (event: any, data: any) => this.handleError(data.err, serverTranslations))
343 window[ 'videojsPlayer' ] = this.player
346 const config: ServerConfig = await configResponse.json()
347 const description = config.tracker.enabled
348 ? '<span class="text">' + this.player.localize('Uses P2P, others may know your IP is downloading this video.') + '</span>'
352 title: videoInfo.name,
360 private handleError (err: Error, translations?: { [ id: string ]: string }) {
361 if (err.message.indexOf('from xs param') !== -1) {
362 this.player.dispose()
363 this.videoElement = null
364 this.displayError('This video is not available because the remote instance is not responding.', translations)
371 .catch(err => console.error('Cannot init embed.', err))