]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blob - client/src/standalone/videos/embed.ts
Translated using Weblate (Croatian)
[github/Chocobozzz/PeerTube.git] / client / src / standalone / videos / embed.ts
1 import './embed.scss'
2 import '../../assets/player/shared/dock/peertube-dock-component'
3 import '../../assets/player/shared/dock/peertube-dock-plugin'
4 import videojs from 'video.js'
5 import { peertubeTranslate } from '../../../../shared/core-utils/i18n'
6 import { HTMLServerConfig, LiveVideo, ResultList, VideoDetails, VideoPlaylist, VideoPlaylistElement } from '../../../../shared/models'
7 import { PeertubePlayerManager } from '../../assets/player'
8 import { TranslationsManager } from '../../assets/player/translations-manager'
9 import { getParamString } from '../../root-helpers'
10 import { PeerTubeEmbedApi } from './embed-api'
11 import { AuthHTTP, LiveManager, PeerTubePlugin, PlayerManagerOptions, PlaylistFetcher, PlaylistTracker, VideoFetcher } from './shared'
12 import { PlayerHTML } from './shared/player-html'
13
14 export class PeerTubeEmbed {
15 player: videojs.Player
16 api: PeerTubeEmbedApi = null
17
18 config: HTMLServerConfig
19
20 private translationsPromise: Promise<{ [id: string]: string }>
21 private PeertubePlayerManagerModulePromise: Promise<any>
22
23 private readonly http: AuthHTTP
24 private readonly videoFetcher: VideoFetcher
25 private readonly playlistFetcher: PlaylistFetcher
26 private readonly peertubePlugin: PeerTubePlugin
27 private readonly playerHTML: PlayerHTML
28 private readonly playerManagerOptions: PlayerManagerOptions
29 private readonly liveManager: LiveManager
30
31 private playlistTracker: PlaylistTracker
32
33 constructor (videoWrapperId: string) {
34 this.http = new AuthHTTP()
35
36 this.videoFetcher = new VideoFetcher(this.http)
37 this.playlistFetcher = new PlaylistFetcher(this.http)
38 this.peertubePlugin = new PeerTubePlugin(this.http)
39 this.playerHTML = new PlayerHTML(videoWrapperId)
40 this.playerManagerOptions = new PlayerManagerOptions(this.playerHTML, this.videoFetcher, this.peertubePlugin)
41 this.liveManager = new LiveManager(this.playerHTML)
42
43 try {
44 this.config = JSON.parse(window['PeerTubeServerConfig'])
45 } catch (err) {
46 console.error('Cannot parse HTML config.', err)
47 }
48 }
49
50 static async main () {
51 const videoContainerId = 'video-wrapper'
52 const embed = new PeerTubeEmbed(videoContainerId)
53 await embed.init()
54 }
55
56 getPlayerElement () {
57 return this.playerHTML.getPlayerElement()
58 }
59
60 getScope () {
61 return this.playerManagerOptions.getScope()
62 }
63
64 // ---------------------------------------------------------------------------
65
66 async init () {
67 this.translationsPromise = TranslationsManager.getServerTranslations(window.location.origin, navigator.language)
68 this.PeertubePlayerManagerModulePromise = import('../../assets/player/peertube-player-manager')
69
70 // Issue when we parsed config from HTML, fallback to API
71 if (!this.config) {
72 this.config = await this.http.fetch('/api/v1/config', { optionalAuth: false })
73 .then(res => res.json())
74 }
75
76 const videoId = this.isPlaylistEmbed()
77 ? await this.initPlaylist()
78 : this.getResourceId()
79
80 if (!videoId) return
81
82 return this.loadVideoAndBuildPlayer(videoId)
83 }
84
85 private async initPlaylist () {
86 const playlistId = this.getResourceId()
87
88 try {
89 const res = await this.playlistFetcher.loadPlaylist(playlistId)
90
91 const [ playlist, playlistElementResult ] = await Promise.all([
92 res.playlistResponse.json() as Promise<VideoPlaylist>,
93 res.videosResponse.json() as Promise<ResultList<VideoPlaylistElement>>
94 ])
95
96 const allPlaylistElements = await this.playlistFetcher.loadAllPlaylistVideos(playlistId, playlistElementResult)
97
98 this.playlistTracker = new PlaylistTracker(playlist, allPlaylistElements)
99
100 const params = new URL(window.location.toString()).searchParams
101 const playlistPositionParam = getParamString(params, 'playlistPosition')
102
103 const position = playlistPositionParam
104 ? parseInt(playlistPositionParam + '', 10)
105 : 1
106
107 this.playlistTracker.setPosition(position)
108 } catch (err) {
109 this.playerHTML.displayError(err.message, await this.translationsPromise)
110 return undefined
111 }
112
113 return this.playlistTracker.getCurrentElement().video.uuid
114 }
115
116 private initializeApi () {
117 if (this.playerManagerOptions.hasAPIEnabled()) {
118 this.api = new PeerTubeEmbedApi(this)
119 this.api.initialize()
120 }
121 }
122
123 // ---------------------------------------------------------------------------
124
125 async playNextPlaylistVideo () {
126 const next = this.playlistTracker.getNextPlaylistElement()
127 if (!next) {
128 console.log('Next element not found in playlist.')
129 return
130 }
131
132 this.playlistTracker.setCurrentElement(next)
133
134 return this.loadVideoAndBuildPlayer(next.video.uuid)
135 }
136
137 async playPreviousPlaylistVideo () {
138 const previous = this.playlistTracker.getPreviousPlaylistElement()
139 if (!previous) {
140 console.log('Previous element not found in playlist.')
141 return
142 }
143
144 this.playlistTracker.setCurrentElement(previous)
145
146 await this.loadVideoAndBuildPlayer(previous.video.uuid)
147 }
148
149 getCurrentPlaylistPosition () {
150 return this.playlistTracker.getCurrentPosition()
151 }
152
153 // ---------------------------------------------------------------------------
154
155 private async loadVideoAndBuildPlayer (uuid: string) {
156 try {
157 const { videoResponse, captionsPromise } = await this.videoFetcher.loadVideo(uuid)
158
159 return this.buildVideoPlayer(videoResponse, captionsPromise)
160 } catch (err) {
161 this.playerHTML.displayError(err.message, await this.translationsPromise)
162 }
163 }
164
165 private async buildVideoPlayer (videoResponse: Response, captionsPromise: Promise<Response>) {
166 const alreadyHadPlayer = this.resetPlayerElement()
167
168 const videoInfoPromise: Promise<{ video: VideoDetails, live?: LiveVideo }> = videoResponse.json()
169 .then((videoInfo: VideoDetails) => {
170 this.playerManagerOptions.loadParams(this.config, videoInfo)
171
172 if (!alreadyHadPlayer && !this.playerManagerOptions.hasAutoplay()) {
173 this.playerHTML.buildPlaceholder(videoInfo)
174 }
175
176 if (!videoInfo.isLive) {
177 return { video: videoInfo }
178 }
179
180 return this.videoFetcher.loadVideoWithLive(videoInfo)
181 })
182
183 const [ { video, live }, translations, captionsResponse, PeertubePlayerManagerModule ] = await Promise.all([
184 videoInfoPromise,
185 this.translationsPromise,
186 captionsPromise,
187 this.PeertubePlayerManagerModulePromise
188 ])
189
190 await this.peertubePlugin.loadPlugins(this.config, translations)
191
192 const PlayerManager: typeof PeertubePlayerManager = PeertubePlayerManagerModule.PeertubePlayerManager
193
194 const options = await this.playerManagerOptions.getPlayerOptions({
195 video,
196 captionsResponse,
197 alreadyHadPlayer,
198 translations,
199 serverConfig: this.config,
200
201 onVideoUpdate: (uuid: string) => this.loadVideoAndBuildPlayer(uuid),
202
203 playlistTracker: this.playlistTracker,
204 playNextPlaylistVideo: () => this.playNextPlaylistVideo(),
205 playPreviousPlaylistVideo: () => this.playPreviousPlaylistVideo(),
206
207 live
208 })
209
210 this.player = await PlayerManager.initialize(this.playerManagerOptions.getMode(), options, (player: videojs.Player) => {
211 this.player = player
212 })
213
214 this.player.on('customError', (event: any, data: any) => {
215 const message = data?.err?.message || ''
216 if (!message.includes('from xs param')) return
217
218 this.player.dispose()
219 this.playerHTML.removePlayerElement()
220 this.playerHTML.displayError('This video is not available because the remote instance is not responding.', translations)
221 })
222
223 window['videojsPlayer'] = this.player
224
225 this.buildCSS()
226 this.buildPlayerDock(video)
227 this.initializeApi()
228
229 this.playerHTML.removePlaceholder()
230
231 if (this.isPlaylistEmbed()) {
232 await this.buildPlayerPlaylistUpnext()
233
234 this.player.playlist().updateSelected()
235
236 this.player.on('stopped', () => {
237 this.playNextPlaylistVideo()
238 })
239 }
240
241 this.peertubePlugin.getPluginsManager().runHook('action:embed.player.loaded', undefined, { player: this.player, videojs, video })
242
243 if (video.isLive) {
244 this.liveManager.displayInfoAndListenForChanges({
245 video,
246 translations,
247 onPublishedVideo: () => {
248 this.liveManager.stopListeningForChanges(video)
249 this.loadVideoAndBuildPlayer(video.uuid)
250 }
251 })
252 }
253 }
254
255 private resetPlayerElement () {
256 let alreadyHadPlayer = false
257
258 if (this.player) {
259 this.player.dispose()
260 alreadyHadPlayer = true
261 }
262
263 const playerElement = document.createElement('video')
264 playerElement.className = 'video-js vjs-peertube-skin'
265 playerElement.setAttribute('playsinline', 'true')
266
267 this.playerHTML.setPlayerElement(playerElement)
268 this.playerHTML.addPlayerElementToDOM()
269
270 return alreadyHadPlayer
271 }
272
273 private async buildPlayerPlaylistUpnext () {
274 const translations = await this.translationsPromise
275
276 this.player.upnext({
277 timeout: 10000, // 10s
278 headText: peertubeTranslate('Up Next', translations),
279 cancelText: peertubeTranslate('Cancel', translations),
280 suspendedText: peertubeTranslate('Autoplay is suspended', translations),
281 getTitle: () => this.playlistTracker.nextVideoTitle(),
282 next: () => this.playNextPlaylistVideo(),
283 condition: () => !!this.playlistTracker.getNextPlaylistElement(),
284 suspended: () => false
285 })
286 }
287
288 private buildPlayerDock (videoInfo: VideoDetails) {
289 if (!this.playerManagerOptions.hasControls()) return
290
291 // On webtorrent fallback, player may have been disposed
292 if (!this.player.player_) return
293
294 const title = this.playerManagerOptions.hasTitle()
295 ? videoInfo.name
296 : undefined
297
298 const description = this.playerManagerOptions.hasWarningTitle() && this.playerManagerOptions.hasP2PEnabled()
299 ? '<span class="text">' + peertubeTranslate('Watching this video may reveal your IP address to others.') + '</span>'
300 : undefined
301
302 if (!title && !description) return
303
304 const availableAvatars = videoInfo.channel.avatars.filter(a => a.width < 50)
305 const avatar = availableAvatars.length !== 0
306 ? availableAvatars[0]
307 : undefined
308
309 this.player.peertubeDock({
310 title,
311 description,
312 avatarUrl: title && avatar
313 ? avatar.path
314 : undefined
315 })
316 }
317
318 private buildCSS () {
319 const body = document.getElementById('custom-css')
320
321 if (this.playerManagerOptions.hasBigPlayBackgroundColor()) {
322 body.style.setProperty('--embedBigPlayBackgroundColor', this.playerManagerOptions.getBigPlayBackgroundColor())
323 }
324
325 if (this.playerManagerOptions.hasForegroundColor()) {
326 body.style.setProperty('--embedForegroundColor', this.playerManagerOptions.getForegroundColor())
327 }
328 }
329
330 // ---------------------------------------------------------------------------
331
332 private getResourceId () {
333 const urlParts = window.location.pathname.split('/')
334 return urlParts[urlParts.length - 1]
335 }
336
337 private isPlaylistEmbed () {
338 return window.location.pathname.split('/')[1] === 'video-playlists'
339 }
340 }
341
342 PeerTubeEmbed.main()
343 .catch(err => {
344 (window as any).displayIncompatibleBrowser()
345
346 console.error('Cannot init embed.', err)
347 })