]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blob - client/src/standalone/videos/embed.ts
Add missing translations in embed template
[github/Chocobozzz/PeerTube.git] / client / src / standalone / videos / embed.ts
1 import './embed.scss'
2
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
18 import 'whatwg-fetch'
19
20 // FIXME: something weird with our path definition in tsconfig and typings
21 // @ts-ignore
22 import * as vjs from 'video.js'
23
24 import * as Channel from 'jschannel'
25
26 import { peertubeTranslate, ResultList, VideoDetails } from '../../../../shared'
27 import { addContextMenu, getServerTranslations, getVideojsOptions, loadLocaleInVideoJS } from '../../assets/player/peertube-player'
28 import { PeerTubeResolution } from '../player/definitions'
29 import { VideoJSCaption } from '../../assets/player/peertube-videojs-typings'
30 import { VideoCaption } from '../../../../shared/models/videos/caption/video-caption.model'
31
32 /**
33 * Embed API exposes control of the embed player to the outside world via
34 * JSChannels and window.postMessage
35 */
36 class PeerTubeEmbedApi {
37 private channel: Channel.MessagingChannel
38 private isReady = false
39 private resolutions: PeerTubeResolution[] = null
40
41 constructor (private embed: PeerTubeEmbed) {
42 }
43
44 initialize () {
45 this.constructChannel()
46 this.setupStateTracking()
47
48 // We're ready!
49
50 this.notifyReady()
51 }
52
53 private get element () {
54 return this.embed.videoElement
55 }
56
57 private constructChannel () {
58 let channel = Channel.build({ window: window.parent, origin: '*', scope: this.embed.scope })
59
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)
71
72 this.channel = channel
73 }
74
75 private setResolution (resolutionId: number) {
76 if (resolutionId === -1 && this.embed.player.peertube().isAutoResolutionForbidden()) return
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 */
91 private notifyReady () {
92 this.isReady = true
93 this.channel.notify({ method: 'ready', params: true })
94 }
95
96 private setupStateTracking () {
97 let currentState: 'playing' | 'paused' | 'unstarted' = 'unstarted'
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,
108 playbackState: currentState
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
129 private loadResolutions () {
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 }
138
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 }
153 }
154
155 class PeerTubeEmbed {
156 videoElement: HTMLVideoElement
157 player: any
158 playerOptions: any
159 api: PeerTubeEmbedApi = null
160 autoplay: boolean
161 controls: boolean
162 muted: boolean
163 loop: boolean
164 subtitle: string
165 enableApi = false
166 startTime: number | string = 0
167 scope = 'peertube'
168
169 static async main () {
170 const videoContainerId = 'video-container'
171 const embed = new PeerTubeEmbed(videoContainerId)
172 await embed.init()
173 }
174
175 constructor (private videoContainerId: string) {
176 this.videoElement = document.getElementById(videoContainerId) as HTMLVideoElement
177 }
178
179 getVideoUrl (id: string) {
180 return window.location.origin + '/api/v1/videos/' + id
181 }
182
183 loadVideoInfo (videoId: string): Promise<Response> {
184 return fetch(this.getVideoUrl(videoId))
185 }
186
187 loadVideoCaptions (videoId: string): Promise<Response> {
188 return fetch(this.getVideoUrl(videoId) + '/captions')
189 }
190
191 removeElement (element: HTMLElement) {
192 element.parentElement.removeChild(element)
193 }
194
195 displayError (text: string, translations?: { [ id: string ]: string }) {
196 // Remove video element
197 if (this.videoElement) this.removeElement(this.videoElement)
198
199 const translatedText = peertubeTranslate(text, translations)
200 const translatedSorry = peertubeTranslate('Sorry', translations)
201
202 document.title = translatedSorry + ' - ' + translatedText
203
204 const errorBlock = document.getElementById('error-block')
205 errorBlock.style.display = 'flex'
206
207 const errorTitle = document.getElementById('error-title')
208 errorTitle.innerHTML = peertubeTranslate('Sorry', translations)
209
210 const errorText = document.getElementById('error-content')
211 errorText.innerHTML = translatedText
212 }
213
214 videoNotFound (translations?: { [ id: string ]: string }) {
215 const text = 'This video does not exist.'
216 this.displayError(text, translations)
217 }
218
219 videoFetchError (translations?: { [ id: string ]: string }) {
220 const text = 'We cannot fetch the video. Please try again later.'
221 this.displayError(text, translations)
222 }
223
224 getParamToggle (params: URLSearchParams, name: string, defaultValue?: boolean) {
225 return params.has(name) ? (params.get(name) === '1' || params.get(name) === 'true') : defaultValue
226 }
227
228 getParamString (params: URLSearchParams, name: string, defaultValue?: string) {
229 return params.has(name) ? params.get(name) : defaultValue
230 }
231
232 async init () {
233 try {
234 await this.initCore()
235 } catch (e) {
236 console.error(e)
237 }
238 }
239
240 private initializeApi () {
241 if (!this.enableApi) return
242
243 this.api = new PeerTubeEmbedApi(this)
244 this.api.initialize()
245 }
246
247 private loadParams () {
248 try {
249 let params = new URL(window.location.toString()).searchParams
250
251 this.autoplay = this.getParamToggle(params, 'autoplay')
252 this.controls = this.getParamToggle(params, 'controls')
253 this.muted = this.getParamToggle(params, 'muted')
254 this.loop = this.getParamToggle(params, 'loop')
255 this.enableApi = this.getParamToggle(params, 'api', this.enableApi)
256
257 this.scope = this.getParamString(params, 'scope', this.scope)
258 this.subtitle = this.getParamString(params, 'subtitle')
259 this.startTime = this.getParamString(params, 'start')
260 } catch (err) {
261 console.error('Cannot get params from URL.', err)
262 }
263 }
264
265 private async initCore () {
266 const urlParts = window.location.pathname.split('/')
267 const videoId = urlParts[ urlParts.length - 1 ]
268
269 const [ , serverTranslations, videoResponse, captionsResponse ] = await Promise.all([
270 loadLocaleInVideoJS(window.location.origin, vjs, navigator.language),
271 getServerTranslations(window.location.origin, navigator.language),
272 this.loadVideoInfo(videoId),
273 this.loadVideoCaptions(videoId)
274 ])
275
276 if (!videoResponse.ok) {
277 if (videoResponse.status === 404) return this.videoNotFound(serverTranslations)
278
279 return this.videoFetchError(serverTranslations)
280 }
281
282 const videoInfo: VideoDetails = await videoResponse.json()
283 let videoCaptions: VideoJSCaption[] = []
284 if (captionsResponse.ok) {
285 const { data } = (await captionsResponse.json()) as ResultList<VideoCaption>
286 videoCaptions = data.map(c => ({
287 label: peertubeTranslate(c.language.label, serverTranslations),
288 language: c.language.id,
289 src: window.location.origin + c.captionPath
290 }))
291 }
292
293 this.loadParams()
294
295 const videojsOptions = getVideojsOptions({
296 autoplay: this.autoplay,
297 controls: this.controls,
298 muted: this.muted,
299 loop: this.loop,
300 startTime: this.startTime,
301 subtitle: this.subtitle,
302
303 videoCaptions,
304 inactivityTimeout: 1500,
305 videoViewUrl: this.getVideoUrl(videoId) + '/views',
306 playerElement: this.videoElement,
307 videoFiles: videoInfo.files,
308 videoDuration: videoInfo.duration,
309 enableHotkeys: true,
310 peertubeLink: true,
311 poster: window.location.origin + videoInfo.previewPath,
312 theaterMode: false
313 })
314
315 this.playerOptions = videojsOptions
316 this.player = vjs(this.videoContainerId, videojsOptions, () => {
317 this.player.on('customError', (event: any, data: any) => this.handleError(data.err, serverTranslations))
318
319 window[ 'videojsPlayer' ] = this.player
320
321 if (this.controls) {
322 this.player.dock({
323 title: videoInfo.name,
324 description: this.player.localize('Uses P2P, others may know your IP is downloading this video.')
325 })
326 }
327
328 addContextMenu(this.player, window.location.origin + videoInfo.embedPath)
329
330 this.initializeApi()
331 })
332 }
333
334 private handleError (err: Error, translations?: { [ id: string ]: string }) {
335 if (err.message.indexOf('from xs param') !== -1) {
336 this.player.dispose()
337 this.videoElement = null
338 this.displayError('This video is not available because the remote instance is not responding.', translations)
339 return
340 }
341 }
342 }
343
344 PeerTubeEmbed.main()
345 .catch(err => console.error('Cannot init embed.', err))