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