aboutsummaryrefslogtreecommitdiffhomepage
path: root/client/src/standalone/videos/shared/player-manager-options.ts
blob: 87a84975b8f81fcf3f5c2ed37090ea34ab35bf32 (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
import { peertubeTranslate } from '../../../../../shared/core-utils/i18n'
import {
  HTMLServerConfig,
  LiveVideo,
  Video,
  VideoCaption,
  VideoDetails,
  VideoPlaylistElement,
  VideoState,
  VideoStreamingPlaylistType
} from '../../../../../shared/models'
import { P2PMediaLoaderOptions, PeertubePlayerManagerOptions, PlayerMode, VideoJSCaption } from '../../../assets/player'
import {
  getBoolOrDefault,
  getParamString,
  getParamToggle,
  isP2PEnabled,
  logger,
  peertubeLocalStorage,
  UserLocalStorageKeys,
  videoRequiresAuth
} from '../../../root-helpers'
import { PeerTubePlugin } from './peertube-plugin'
import { PlayerHTML } from './player-html'
import { PlaylistTracker } from './playlist-tracker'
import { Translations } from './translations'
import { VideoFetcher } from './video-fetcher'

export class PlayerManagerOptions {
  private autoplay: boolean

  private controls: boolean
  private controlBar: boolean

  private muted: boolean
  private loop: boolean
  private subtitle: string
  private enableApi = false
  private startTime: number | string = 0
  private stopTime: number | string

  private title: boolean
  private warningTitle: boolean
  private peertubeLink: boolean
  private p2pEnabled: boolean
  private bigPlayBackgroundColor: string
  private foregroundColor: string

  private mode: PlayerMode
  private scope = 'peertube'

  constructor (
    private readonly playerHTML: PlayerHTML,
    private readonly videoFetcher: VideoFetcher,
    private readonly peertubePlugin: PeerTubePlugin
  ) {}

  hasAPIEnabled () {
    return this.enableApi
  }

  hasAutoplay () {
    return this.autoplay
  }

  hasControls () {
    return this.controls
  }

  hasTitle () {
    return this.title
  }

  hasWarningTitle () {
    return this.warningTitle
  }

  hasP2PEnabled () {
    return !!this.p2pEnabled
  }

  hasBigPlayBackgroundColor () {
    return !!this.bigPlayBackgroundColor
  }

  getBigPlayBackgroundColor () {
    return this.bigPlayBackgroundColor
  }

  hasForegroundColor () {
    return !!this.foregroundColor
  }

  getForegroundColor () {
    return this.foregroundColor
  }

  getMode () {
    return this.mode
  }

  getScope () {
    return this.scope
  }

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

  loadParams (config: HTMLServerConfig, video: VideoDetails) {
    try {
      const params = new URL(window.location.toString()).searchParams

      this.autoplay = getParamToggle(params, 'autoplay', false)
      // Disable auto play on live videos that are not streamed
      if (video.state.id === VideoState.LIVE_ENDED || video.state.id === VideoState.WAITING_FOR_LIVE) {
        this.autoplay = false
      }

      this.controls = getParamToggle(params, 'controls', true)
      this.controlBar = getParamToggle(params, 'controlBar', true)

      this.muted = getParamToggle(params, 'muted', undefined)
      this.loop = getParamToggle(params, 'loop', false)
      this.title = getParamToggle(params, 'title', true)
      this.enableApi = getParamToggle(params, 'api', this.enableApi)
      this.warningTitle = getParamToggle(params, 'warningTitle', true)
      this.peertubeLink = getParamToggle(params, 'peertubeLink', true)
      this.p2pEnabled = getParamToggle(params, 'p2p', this.isP2PEnabled(config, video))

      this.scope = getParamString(params, 'scope', this.scope)
      this.subtitle = getParamString(params, 'subtitle')
      this.startTime = getParamString(params, 'start')
      this.stopTime = getParamString(params, 'stop')

      this.bigPlayBackgroundColor = getParamString(params, 'bigPlayBackgroundColor')
      this.foregroundColor = getParamString(params, 'foregroundColor')

      const modeParam = getParamString(params, 'mode')

      if (modeParam) {
        if (modeParam === 'p2p-media-loader') this.mode = 'p2p-media-loader'
        else this.mode = 'webtorrent'
      } else {
        if (Array.isArray(video.streamingPlaylists) && video.streamingPlaylists.length !== 0) this.mode = 'p2p-media-loader'
        else this.mode = 'webtorrent'
      }
    } catch (err) {
      logger.error('Cannot get params from URL.', err)
    }
  }

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

  async getPlayerOptions (options: {
    video: VideoDetails
    captionsResponse: Response
    live?: LiveVideo

    authorizationHeader: () => string
    videoFileToken: () => string

    serverConfig: HTMLServerConfig

    alreadyHadPlayer: boolean

    translations: Translations

    playlistTracker?: PlaylistTracker
    playNextPlaylistVideo?: () => any
    playPreviousPlaylistVideo?: () => any
    onVideoUpdate?: (uuid: string) => any
  }) {
    const {
      video,
      captionsResponse,
      alreadyHadPlayer,
      videoFileToken,
      translations,
      playlistTracker,
      live,
      authorizationHeader,
      serverConfig
    } = options

    const videoCaptions = await this.buildCaptions(captionsResponse, translations)

    const playerOptions: PeertubePlayerManagerOptions = {
      common: {
        // Autoplay in playlist mode
        autoplay: alreadyHadPlayer ? true : this.autoplay,

        controls: this.controls,
        controlBar: this.controlBar,

        muted: this.muted,
        loop: this.loop,

        p2pEnabled: this.p2pEnabled,

        captions: videoCaptions.length !== 0,
        subtitle: this.subtitle,

        startTime: playlistTracker
          ? playlistTracker.getCurrentElement().startTimestamp
          : this.startTime,
        stopTime: playlistTracker
          ? playlistTracker.getCurrentElement().stopTimestamp
          : this.stopTime,

        videoCaptions,
        inactivityTimeout: 2500,
        videoViewUrl: this.videoFetcher.getVideoViewsUrl(video.uuid),
        metricsUrl: window.location.origin + '/api/v1/metrics/playback',

        videoShortUUID: video.shortUUID,
        videoUUID: video.uuid,

        playerElement: this.playerHTML.getPlayerElement(),
        onPlayerElementChange: (element: HTMLVideoElement) => {
          this.playerHTML.setPlayerElement(element)
        },

        videoDuration: video.duration,
        enableHotkeys: true,

        peertubeLink: this.peertubeLink,
        instanceName: serverConfig.instance.name,

        poster: window.location.origin + video.previewPath,
        theaterButton: false,

        serverUrl: window.location.origin,
        language: navigator.language,
        embedUrl: window.location.origin + video.embedPath,
        embedTitle: video.name,

        requiresAuth: videoRequiresAuth(video),
        authorizationHeader,
        videoFileToken,

        errorNotifier: () => {
          // Empty, we don't have a notifier in the embed
        },

        ...this.buildLiveOptions(video, live),

        ...this.buildPlaylistOptions(options)
      },

      webtorrent: {
        videoFiles: video.files
      },

      ...this.buildP2PMediaLoaderOptions(video),

      pluginsManager: this.peertubePlugin.getPluginsManager()
    }

    return playerOptions
  }

  private buildLiveOptions (video: VideoDetails, live: LiveVideo) {
    if (!video.isLive) return { isLive: false }

    return {
      isLive: true,
      liveOptions: {
        latencyMode: live.latencyMode
      }
    }
  }

  private buildPlaylistOptions (options: {
    playlistTracker?: PlaylistTracker
    playNextPlaylistVideo?: () => any
    playPreviousPlaylistVideo?: () => any
    onVideoUpdate?: (uuid: string) => any
  }) {
    const { playlistTracker, playNextPlaylistVideo, playPreviousPlaylistVideo, onVideoUpdate } = options

    if (!playlistTracker) return {}

    return {
      playlist: {
        elements: playlistTracker.getPlaylistElements(),
        playlist: playlistTracker.getPlaylist(),

        getCurrentPosition: () => playlistTracker.getCurrentPosition(),

        onItemClicked: (videoPlaylistElement: VideoPlaylistElement) => {
          playlistTracker.setCurrentElement(videoPlaylistElement)

          onVideoUpdate(videoPlaylistElement.video.uuid)
        }
      },

      nextVideo: () => playNextPlaylistVideo(),
      hasNextVideo: () => playlistTracker.hasNextPlaylistElement(),

      previousVideo: () => playPreviousPlaylistVideo(),
      hasPreviousVideo: () => playlistTracker.hasPreviousPlaylistElement()
    }
  }

  private buildP2PMediaLoaderOptions (video: VideoDetails) {
    if (this.mode !== 'p2p-media-loader') return {}

    const hlsPlaylist = video.streamingPlaylists.find(p => p.type === VideoStreamingPlaylistType.HLS)

    return {
      p2pMediaLoader: {
        playlistUrl: hlsPlaylist.playlistUrl,
        segmentsSha256Url: hlsPlaylist.segmentsSha256Url,
        redundancyBaseUrls: hlsPlaylist.redundancies.map(r => r.baseUrl),
        trackerAnnounce: video.trackerUrls,
        videoFiles: hlsPlaylist.files
      } as P2PMediaLoaderOptions
    }
  }

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

  private async buildCaptions (captionsResponse: Response, translations: Translations): Promise<VideoJSCaption[]> {
    if (captionsResponse.ok) {
      const { data } = await captionsResponse.json()

      return data.map((c: VideoCaption) => ({
        label: peertubeTranslate(c.language.label, translations),
        language: c.language.id,
        src: window.location.origin + c.captionPath
      }))
    }

    return []
  }

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

  private isP2PEnabled (config: HTMLServerConfig, video: Video) {
    const userP2PEnabled = getBoolOrDefault(
      peertubeLocalStorage.getItem(UserLocalStorageKeys.P2P_ENABLED),
      config.defaults.p2p.embed.enabled
    )

    return isP2PEnabled(video, config, userP2PEnabled)
  }
}