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