]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blame - client/src/standalone/videos/embed.ts
Increase abuse length to 3000
[github/Chocobozzz/PeerTube.git] / client / src / standalone / videos / embed.ts
CommitLineData
202e7223
C
1import './embed.scss'
2
d1bd87e0
C
3import 'core-js/es6/symbol'
4import 'core-js/es6/object'
5import 'core-js/es6/function'
6import 'core-js/es6/parse-int'
7import 'core-js/es6/parse-float'
8import 'core-js/es6/number'
9import 'core-js/es6/math'
10import 'core-js/es6/string'
11import 'core-js/es6/date'
12import 'core-js/es6/array'
13import 'core-js/es6/regexp'
14import 'core-js/es6/map'
15import 'core-js/es6/weak-map'
16import 'core-js/es6/set'
cd4d7a2c
C
17// For google bot that uses Chrome 41 and does not understand fetch
18import 'whatwg-fetch'
19
c199c427
C
20// FIXME: something weird with our path definition in tsconfig and typings
21// @ts-ignore
e0628695 22import * as vjs from 'video.js'
c199c427 23
99941732 24import * as Channel from 'jschannel'
c6352f2c 25
3dfa8494
C
26import { peertubeTranslate, ResultList, VideoDetails } from '../../../../shared'
27import { addContextMenu, getServerTranslations, getVideojsOptions, loadLocaleInVideoJS } from '../../assets/player/peertube-player'
902aa3a0 28import { PeerTubeResolution } from '../player/definitions'
16f7022b 29import { VideoJSCaption } from '../../assets/player/peertube-videojs-typings'
59c76ffa 30import { VideoCaption } from '../../../../shared/models/videos/caption/video-caption.model'
202e7223 31
99941732 32/**
902aa3a0 33 * Embed API exposes control of the embed player to the outside world via
99941732
WL
34 * JSChannels and window.postMessage
35 */
36class PeerTubeEmbedApi {
902aa3a0 37 private channel: Channel.MessagingChannel
99941732 38 private isReady = false
902aa3a0
C
39 private resolutions: PeerTubeResolution[] = null
40
41 constructor (private embed: PeerTubeEmbed) {
42 }
d4f3fea6 43
902aa3a0 44 initialize () {
99941732
WL
45 this.constructChannel()
46 this.setupStateTracking()
d4f3fea6 47
99941732 48 // We're ready!
d4f3fea6 49
99941732
WL
50 this.notifyReady()
51 }
902aa3a0
C
52
53 private get element () {
99941732
WL
54 return this.embed.videoElement
55 }
d4f3fea6 56
902aa3a0 57 private constructChannel () {
99941732 58 let channel = Channel.build({ window: window.parent, origin: '*', scope: this.embed.scope })
902aa3a0 59
99941732
WL
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)
d4f3fea6 71
99941732
WL
72 this.channel = channel
73 }
d4f3fea6 74
902aa3a0
C
75 private setResolution (resolutionId: number) {
76 if (resolutionId === -1 && this.embed.player.peertube().isAutoResolutionForbidden()) return
99941732
WL
77
78 // Auto resolution
79 if (resolutionId === -1) {
80 this.embed.player.peertube().enableAutoResolution()
81 return
82 }
83
84 this.embed.player.peertube().disableAutoResolution()
85 this.embed.player.peertube().updateResolution(resolutionId)
86 }
87
88 /**
89 * Let the host know that we're ready to go!
90 */
902aa3a0 91 private notifyReady () {
99941732
WL
92 this.isReady = true
93 this.channel.notify({ method: 'ready', params: true })
94 }
95
902aa3a0
C
96 private setupStateTracking () {
97 let currentState: 'playing' | 'paused' | 'unstarted' = 'unstarted'
99941732
WL
98
99 setInterval(() => {
100 let position = this.element.currentTime
101 let volume = this.element.volume
102
103 this.channel.notify({
104 method: 'playbackStatusUpdate',
105 params: {
106 position,
107 volume,
902aa3a0 108 playbackState: currentState
99941732
WL
109 }
110 })
111 }, 500)
112
113 this.element.addEventListener('play', ev => {
114 currentState = 'playing'
115 this.channel.notify({ method: 'playbackStatusChange', params: 'playing' })
116 })
117
118 this.element.addEventListener('pause', ev => {
119 currentState = 'paused'
120 this.channel.notify({ method: 'playbackStatusChange', params: 'paused' })
121 })
122
123 // PeerTube specific capabilities
124
125 this.embed.player.peertube().on('autoResolutionUpdate', () => this.loadResolutions())
126 this.embed.player.peertube().on('videoFileUpdate', () => this.loadResolutions())
127 }
128
902aa3a0 129 private loadResolutions () {
99941732
WL
130 let resolutions = []
131 let currentResolutionId = this.embed.player.peertube().getCurrentResolutionId()
132
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
137 }
d4f3fea6 138
99941732
WL
139 resolutions.push({
140 id: videoFile.resolution.id,
141 label,
142 src: videoFile.magnetUri,
143 active: videoFile.resolution.id === currentResolutionId
144 })
145 }
146
147 this.resolutions = resolutions
148 this.channel.notify({
149 method: 'resolutionUpdate',
150 params: this.resolutions
151 })
152 }
202e7223
C
153}
154
99941732 155class PeerTubeEmbed {
902aa3a0
C
156 videoElement: HTMLVideoElement
157 player: any
158 playerOptions: any
159 api: PeerTubeEmbedApi = null
3b019808
C
160 autoplay: boolean
161 controls: boolean
162 muted: boolean
163 loop: boolean
164 subtitle: string
902aa3a0 165 enableApi = false
1f6824c9 166 startTime: number | string = 0
902aa3a0
C
167 scope = 'peertube'
168
169 static async main () {
c6352f2c 170 const videoContainerId = 'video-container'
99941732
WL
171 const embed = new PeerTubeEmbed(videoContainerId)
172 await embed.init()
173 }
902aa3a0
C
174
175 constructor (private videoContainerId: string) {
176 this.videoElement = document.getElementById(videoContainerId) as HTMLVideoElement
177 }
178
99941732
WL
179 getVideoUrl (id: string) {
180 return window.location.origin + '/api/v1/videos/' + id
181 }
d4f3fea6 182
99941732
WL
183 loadVideoInfo (videoId: string): Promise<Response> {
184 return fetch(this.getVideoUrl(videoId))
185 }
d4f3fea6 186
16f7022b
C
187 loadVideoCaptions (videoId: string): Promise<Response> {
188 return fetch(this.getVideoUrl(videoId) + '/captions')
189 }
190
99941732
WL
191 removeElement (element: HTMLElement) {
192 element.parentElement.removeChild(element)
193 }
d4f3fea6 194
6d88de72 195 displayError (text: string) {
99941732 196 // Remove video element
6d88de72 197 if (this.videoElement) this.removeElement(this.videoElement)
99941732
WL
198
199 document.title = 'Sorry - ' + text
200
201 const errorBlock = document.getElementById('error-block')
202 errorBlock.style.display = 'flex'
203
204 const errorText = document.getElementById('error-content')
205 errorText.innerHTML = text
206 }
207
6d88de72 208 videoNotFound () {
99941732 209 const text = 'This video does not exist.'
6d88de72 210 this.displayError(text)
99941732
WL
211 }
212
6d88de72 213 videoFetchError () {
99941732 214 const text = 'We cannot fetch the video. Please try again later.'
6d88de72 215 this.displayError(text)
99941732
WL
216 }
217
3b019808 218 getParamToggle (params: URLSearchParams, name: string, defaultValue?: boolean) {
99941732
WL
219 return params.has(name) ? (params.get(name) === '1' || params.get(name) === 'true') : defaultValue
220 }
d4f3fea6 221
3b019808 222 getParamString (params: URLSearchParams, name: string, defaultValue?: string) {
99941732
WL
223 return params.has(name) ? params.get(name) : defaultValue
224 }
da99ccf2 225
902aa3a0 226 async init () {
99941732
WL
227 try {
228 await this.initCore()
229 } catch (e) {
230 console.error(e)
231 }
232 }
233
902aa3a0
C
234 private initializeApi () {
235 if (!this.enableApi) return
236
237 this.api = new PeerTubeEmbedApi(this)
238 this.api.initialize()
239 }
240
241 private loadParams () {
da99ccf2
C
242 try {
243 let params = new URL(window.location.toString()).searchParams
99941732 244
3b019808
C
245 this.autoplay = this.getParamToggle(params, 'autoplay')
246 this.controls = this.getParamToggle(params, 'controls')
247 this.muted = this.getParamToggle(params, 'muted')
248 this.loop = this.getParamToggle(params, 'loop')
99941732 249 this.enableApi = this.getParamToggle(params, 'api', this.enableApi)
f37bad63 250
3b019808
C
251 this.scope = this.getParamString(params, 'scope', this.scope)
252 this.subtitle = this.getParamString(params, 'subtitle')
253 this.startTime = this.getParamString(params, 'start')
da99ccf2
C
254 } catch (err) {
255 console.error('Cannot get params from URL.', err)
256 }
99941732
WL
257 }
258
902aa3a0 259 private async initCore () {
6385c0cb
C
260 const urlParts = window.location.pathname.split('/')
261 const videoId = urlParts[ urlParts.length - 1 ]
99941732 262
3dfa8494
C
263 const [ , serverTranslations, videoResponse, captionsResponse ] = await Promise.all([
264 loadLocaleInVideoJS(window.location.origin, vjs, navigator.language),
265 getServerTranslations(window.location.origin, navigator.language),
16f7022b
C
266 this.loadVideoInfo(videoId),
267 this.loadVideoCaptions(videoId)
268 ])
99941732 269
16f7022b 270 if (!videoResponse.ok) {
6d88de72 271 if (videoResponse.status === 404) return this.videoNotFound()
99941732 272
6d88de72 273 return this.videoFetchError()
99941732
WL
274 }
275
16f7022b
C
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 => ({
3dfa8494 281 label: peertubeTranslate(c.language.label, serverTranslations),
16f7022b
C
282 language: c.language.id,
283 src: window.location.origin + c.captionPath
284 }))
285 }
99941732
WL
286
287 this.loadParams()
da99ccf2 288
c6352f2c 289 const videojsOptions = getVideojsOptions({
99941732
WL
290 autoplay: this.autoplay,
291 controls: this.controls,
292 muted: this.muted,
293 loop: this.loop,
902aa3a0 294 startTime: this.startTime,
3b019808 295 subtitle: this.subtitle,
99941732 296
16f7022b 297 videoCaptions,
c6352f2c 298 inactivityTimeout: 1500,
99941732
WL
299 videoViewUrl: this.getVideoUrl(videoId) + '/views',
300 playerElement: this.videoElement,
c6352f2c
C
301 videoFiles: videoInfo.files,
302 videoDuration: videoInfo.duration,
303 enableHotkeys: true,
33d78552 304 peertubeLink: true,
f37bad63 305 poster: window.location.origin + videoInfo.previewPath,
054a103b 306 theaterMode: false
c6352f2c 307 })
202e7223 308
99941732
WL
309 this.playerOptions = videojsOptions
310 this.player = vjs(this.videoContainerId, videojsOptions, () => {
c199c427 311 this.player.on('customError', (event: any, data: any) => this.handleError(data.err))
e945b184 312
902aa3a0 313 window[ 'videojsPlayer' ] = this.player
99941732
WL
314
315 if (this.controls) {
902aa3a0 316 this.player.dock({
99941732
WL
317 title: videoInfo.name,
318 description: this.player.localize('Uses P2P, others may know your IP is downloading this video.')
319 })
320 }
902aa3a0 321
99941732 322 addContextMenu(this.player, window.location.origin + videoInfo.embedPath)
16f7022b 323
99941732 324 this.initializeApi()
202e7223 325 })
99941732 326 }
6d88de72
C
327
328 private handleError (err: Error) {
0f7fedc3 329 if (err.message.indexOf('from xs param') !== -1) {
6d88de72
C
330 this.player.dispose()
331 this.videoElement = null
332 this.displayError('This video is not available because the remote instance is not responding.')
333 return
334 }
335 }
99941732
WL
336}
337
338PeerTubeEmbed.main()
902aa3a0 339 .catch(err => console.error('Cannot init embed.', err))