aboutsummaryrefslogtreecommitdiffhomepage
path: root/client/src/standalone/videos/embed.ts
blob: cc4274b99810792a1cb950504067ce71d850787a (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
import './embed.scss'
import '../../assets/player/shared/dock/peertube-dock-component'
import '../../assets/player/shared/dock/peertube-dock-plugin'
import videojs from 'video.js'
import { peertubeTranslate } from '../../../../shared/core-utils/i18n'
import { HTMLServerConfig, ResultList, VideoDetails, VideoPlaylist, VideoPlaylistElement, VideoState } from '../../../../shared/models'
import { PeertubePlayerManager } from '../../assets/player'
import { TranslationsManager } from '../../assets/player/translations-manager'
import { getParamString, logger, videoRequiresAuth } from '../../root-helpers'
import { PeerTubeEmbedApi } from './embed-api'
import {
  AuthHTTP,
  LiveManager,
  PeerTubePlugin,
  PlayerManagerOptions,
  PlaylistFetcher,
  PlaylistTracker,
  Translations,
  VideoFetcher
} from './shared'
import { PlayerHTML } from './shared/player-html'

export class PeerTubeEmbed {
  player: videojs.Player
  api: PeerTubeEmbedApi = null

  config: HTMLServerConfig

  private translationsPromise: Promise<{ [id: string]: string }>
  private PeertubePlayerManagerModulePromise: Promise<any>

  private readonly http: AuthHTTP
  private readonly videoFetcher: VideoFetcher
  private readonly playlistFetcher: PlaylistFetcher
  private readonly peertubePlugin: PeerTubePlugin
  private readonly playerHTML: PlayerHTML
  private readonly playerManagerOptions: PlayerManagerOptions
  private readonly liveManager: LiveManager

  private playlistTracker: PlaylistTracker

  constructor (videoWrapperId: string) {
    logger.registerServerSending(window.location.origin)

    this.http = new AuthHTTP()

    this.videoFetcher = new VideoFetcher(this.http)
    this.playlistFetcher = new PlaylistFetcher(this.http)
    this.peertubePlugin = new PeerTubePlugin(this.http)
    this.playerHTML = new PlayerHTML(videoWrapperId)
    this.playerManagerOptions = new PlayerManagerOptions(this.playerHTML, this.videoFetcher, this.peertubePlugin)
    this.liveManager = new LiveManager(this.playerHTML)

    try {
      this.config = JSON.parse((window as any)['PeerTubeServerConfig'])
    } catch (err) {
      logger.error('Cannot parse HTML config.', err)
    }
  }

  static async main () {
    const videoContainerId = 'video-wrapper'
    const embed = new PeerTubeEmbed(videoContainerId)
    await embed.init()
  }

  getPlayerElement () {
    return this.playerHTML.getPlayerElement()
  }

  getScope () {
    return this.playerManagerOptions.getScope()
  }

  // ---------------------------------------------------------------------------

  async init () {
    this.translationsPromise = TranslationsManager.getServerTranslations(window.location.origin, navigator.language)
    this.PeertubePlayerManagerModulePromise = import('../../assets/player/peertube-player-manager')

    // Issue when we parsed config from HTML, fallback to API
    if (!this.config) {
      this.config = await this.http.fetch('/api/v1/config', { optionalAuth: false })
        .then(res => res.json())
    }

    const videoId = this.isPlaylistEmbed()
      ? await this.initPlaylist()
      : this.getResourceId()

    if (!videoId) return

    return this.loadVideoAndBuildPlayer({ uuid: videoId, autoplayFromPreviousVideo: false, forceAutoplay: false })
  }

  private async initPlaylist () {
    const playlistId = this.getResourceId()

    try {
      const res = await this.playlistFetcher.loadPlaylist(playlistId)

      const [ playlist, playlistElementResult ] = await Promise.all([
        res.playlistResponse.json() as Promise<VideoPlaylist>,
        res.videosResponse.json() as Promise<ResultList<VideoPlaylistElement>>
      ])

      const allPlaylistElements = await this.playlistFetcher.loadAllPlaylistVideos(playlistId, playlistElementResult)

      this.playlistTracker = new PlaylistTracker(playlist, allPlaylistElements)

      const params = new URL(window.location.toString()).searchParams
      const playlistPositionParam = getParamString(params, 'playlistPosition')

      const position = playlistPositionParam
        ? parseInt(playlistPositionParam + '', 10)
        : 1

      this.playlistTracker.setPosition(position)
    } catch (err) {
      this.playerHTML.displayError(err.message, await this.translationsPromise)
      return undefined
    }

    return this.playlistTracker.getCurrentElement().video.uuid
  }

  private initializeApi () {
    if (this.playerManagerOptions.hasAPIEnabled()) {
      if (this.api) {
        this.api.reInit()
        return
      }

      this.api = new PeerTubeEmbedApi(this)
      this.api.initialize()
    }
  }

  // ---------------------------------------------------------------------------

  async playNextPlaylistVideo () {
    const next = this.playlistTracker.getNextPlaylistElement()
    if (!next) {
      logger.info('Next element not found in playlist.')
      return
    }

    this.playlistTracker.setCurrentElement(next)

    return this.loadVideoAndBuildPlayer({ uuid: next.video.uuid, autoplayFromPreviousVideo: true, forceAutoplay: false })
  }

  async playPreviousPlaylistVideo () {
    const previous = this.playlistTracker.getPreviousPlaylistElement()
    if (!previous) {
      logger.info('Previous element not found in playlist.')
      return
    }

    this.playlistTracker.setCurrentElement(previous)

    await this.loadVideoAndBuildPlayer({ uuid: previous.video.uuid, autoplayFromPreviousVideo: true, forceAutoplay: false })
  }

  getCurrentPlaylistPosition () {
    return this.playlistTracker.getCurrentPosition()
  }

  // ---------------------------------------------------------------------------

  private async loadVideoAndBuildPlayer (options: {
    uuid: string
    autoplayFromPreviousVideo: boolean
    forceAutoplay: boolean
  }) {
    const { uuid, autoplayFromPreviousVideo, forceAutoplay } = options

    try {
      const { videoResponse, captionsPromise } = await this.videoFetcher.loadVideo(uuid)

      return this.buildVideoPlayer({ videoResponse, captionsPromise, autoplayFromPreviousVideo, forceAutoplay })
    } catch (err) {
      this.playerHTML.displayError(err.message, await this.translationsPromise)
    }
  }

  private async buildVideoPlayer (options: {
    videoResponse: Response
    captionsPromise: Promise<Response>
    autoplayFromPreviousVideo: boolean
    forceAutoplay: boolean
  }) {
    const { videoResponse, captionsPromise, autoplayFromPreviousVideo, forceAutoplay } = options

    this.resetPlayerElement()

    const videoInfoPromise = videoResponse.json()
      .then(async (videoInfo: VideoDetails) => {
        this.playerManagerOptions.loadParams(this.config, videoInfo)

        if (!autoplayFromPreviousVideo && !this.playerManagerOptions.hasAutoplay()) {
          this.playerHTML.buildPlaceholder(videoInfo)
        }
        const live = videoInfo.isLive
          ? await this.videoFetcher.loadLive(videoInfo)
          : undefined

        const videoFileToken = videoRequiresAuth(videoInfo)
          ? await this.videoFetcher.loadVideoToken(videoInfo)
          : undefined

        return { live, video: videoInfo, videoFileToken }
      })

    const [ { video, live, videoFileToken }, translations, captionsResponse, PeertubePlayerManagerModule ] = await Promise.all([
      videoInfoPromise,
      this.translationsPromise,
      captionsPromise,
      this.PeertubePlayerManagerModulePromise
    ])

    await this.peertubePlugin.loadPlugins(this.config, translations)

    const PlayerManager: typeof PeertubePlayerManager = PeertubePlayerManagerModule.PeertubePlayerManager

    const playerOptions = await this.playerManagerOptions.getPlayerOptions({
      video,
      captionsResponse,
      autoplayFromPreviousVideo,
      translations,
      serverConfig: this.config,

      authorizationHeader: () => this.http.getHeaderTokenValue(),
      videoFileToken: () => videoFileToken,

      onVideoUpdate: (uuid: string) => this.loadVideoAndBuildPlayer({ uuid, autoplayFromPreviousVideo: true, forceAutoplay: false }),

      playlistTracker: this.playlistTracker,
      playNextPlaylistVideo: () => this.playNextPlaylistVideo(),
      playPreviousPlaylistVideo: () => this.playPreviousPlaylistVideo(),

      live,
      forceAutoplay
    })

    this.player = await PlayerManager.initialize(this.playerManagerOptions.getMode(), playerOptions, (player: videojs.Player) => {
      this.player = player
    })

    this.player.on('customError', (event: any, data: any) => {
      const message = data?.err?.message || ''
      if (!message.includes('from xs param')) return

      this.player.dispose()
      this.playerHTML.removePlayerElement()
      this.playerHTML.displayError('This video is not available because the remote instance is not responding.', translations)
    });

    (window as any)['videojsPlayer'] = this.player

    this.buildCSS()
    this.buildPlayerDock(video)
    this.initializeApi()

    this.playerHTML.removePlaceholder()

    if (this.isPlaylistEmbed()) {
      await this.buildPlayerPlaylistUpnext()

      this.player.playlist().updateSelected()

      this.player.on('stopped', () => {
        this.playNextPlaylistVideo()
      })
    }

    if (video.isLive) {
      this.liveManager.listenForChanges({
        video,
        onPublishedVideo: () => {
          this.liveManager.stopListeningForChanges(video)
          this.loadVideoAndBuildPlayer({ uuid: video.uuid, autoplayFromPreviousVideo: false, forceAutoplay: true })
        }
      })

      if (video.state.id === VideoState.WAITING_FOR_LIVE || video.state.id === VideoState.LIVE_ENDED) {
        this.liveManager.displayInfo({ state: video.state.id, translations })

        this.disablePlayer()
      } else {
        this.correctlyHandleLiveEnding(translations)
      }
    }

    this.peertubePlugin.getPluginsManager().runHook('action:embed.player.loaded', undefined, { player: this.player, videojs, video })
  }

  private resetPlayerElement () {
    if (this.player) {
      this.player.dispose()
      this.player = undefined
    }

    const playerElement = document.createElement('video')
    playerElement.className = 'video-js vjs-peertube-skin'
    playerElement.setAttribute('playsinline', 'true')

    this.playerHTML.setPlayerElement(playerElement)
    this.playerHTML.addPlayerElementToDOM()
  }

  private async buildPlayerPlaylistUpnext () {
    const translations = await this.translationsPromise

    this.player.upnext({
      timeout: 10000, // 10s
      headText: peertubeTranslate('Up Next', translations),
      cancelText: peertubeTranslate('Cancel', translations),
      suspendedText: peertubeTranslate('Autoplay is suspended', translations),
      getTitle: () => this.playlistTracker.nextVideoTitle(),
      next: () => this.playNextPlaylistVideo(),
      condition: () => !!this.playlistTracker.getNextPlaylistElement(),
      suspended: () => false
    })
  }

  private buildPlayerDock (videoInfo: VideoDetails) {
    if (!this.playerManagerOptions.hasControls()) return

    // On webtorrent fallback, player may have been disposed
    if (!this.player.player_) return

    const title = this.playerManagerOptions.hasTitle()
      ? videoInfo.name
      : undefined

    const description = this.playerManagerOptions.hasWarningTitle() && this.playerManagerOptions.hasP2PEnabled()
      ? '<span class="text">' + peertubeTranslate('Watching this video may reveal your IP address to others.') + '</span>'
      : undefined

    if (!title && !description) return

    const availableAvatars = videoInfo.channel.avatars.filter(a => a.width < 50)
    const avatar = availableAvatars.length !== 0
      ? availableAvatars[0]
      : undefined

    this.player.peertubeDock({
      title,
      description,
      avatarUrl: title && avatar
        ? avatar.path
        : undefined
    })
  }

  private buildCSS () {
    const body = document.getElementById('custom-css')

    if (this.playerManagerOptions.hasBigPlayBackgroundColor()) {
      body.style.setProperty('--embedBigPlayBackgroundColor', this.playerManagerOptions.getBigPlayBackgroundColor())
    }

    if (this.playerManagerOptions.hasForegroundColor()) {
      body.style.setProperty('--embedForegroundColor', this.playerManagerOptions.getForegroundColor())
    }
  }

  // ---------------------------------------------------------------------------

  private getResourceId () {
    const urlParts = window.location.pathname.split('/')
    return urlParts[urlParts.length - 1]
  }

  private isPlaylistEmbed () {
    return window.location.pathname.split('/')[1] === 'video-playlists'
  }

  // ---------------------------------------------------------------------------

  private correctlyHandleLiveEnding (translations: Translations) {
    this.player.one('ended', () => {
      // Display the live ended information
      this.liveManager.displayInfo({ state: VideoState.LIVE_ENDED, translations })

      this.disablePlayer()
    })
  }

  private disablePlayer () {
    if (this.player.isFullscreen()) {
      this.player.exitFullscreen()
    }

    // Disable player
    this.player.hasStarted(false)
    this.player.removeClass('vjs-has-autoplay')
    this.player.bigPlayButton.hide();

    (this.player.el() as HTMLElement).style.pointerEvents = 'none'
  }

}

PeerTubeEmbed.main()
  .catch(err => {
    (window as any).displayIncompatibleBrowser()

    logger.error('Cannot init embed.', err)
  })