aboutsummaryrefslogtreecommitdiffhomepage
path: root/client/src/standalone/videos/shared/playlist-tracker.ts
blob: 75d10b4e277851afd696b62e0b449ee1c643102d (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
import { VideoPlaylist, VideoPlaylistElement } from '../../../../../shared/models'

export class PlaylistTracker {
  private currentPlaylistElement: VideoPlaylistElement

  constructor (
    private readonly playlist: VideoPlaylist,
    private readonly playlistElements: VideoPlaylistElement[]
  ) {

  }

  getPlaylist () {
    return this.playlist
  }

  getPlaylistElements () {
    return this.playlistElements
  }

  hasNextPlaylistElement (position?: number) {
    return !!this.getNextPlaylistElement(position)
  }

  getNextPlaylistElement (position?: number): VideoPlaylistElement {
    if (!position) position = this.currentPlaylistElement.position + 1

    if (position > this.playlist.videosLength) {
      return undefined
    }

    const next = this.playlistElements.find(e => e.position === position)

    if (!next || !next.video) {
      return this.getNextPlaylistElement(position + 1)
    }

    return next
  }

  hasPreviousPlaylistElement (position?: number) {
    return !!this.getPreviousPlaylistElement(position)
  }

  getPreviousPlaylistElement (position?: number): VideoPlaylistElement {
    if (!position) position = this.currentPlaylistElement.position - 1

    if (position < 1) {
      return undefined
    }

    const prev = this.playlistElements.find(e => e.position === position)

    if (!prev || !prev.video) {
      return this.getNextPlaylistElement(position - 1)
    }

    return prev
  }

  nextVideoTitle () {
    const next = this.getNextPlaylistElement()
    if (!next) return ''

    return next.video.name
  }

  setPosition (position: number) {
    this.currentPlaylistElement = this.playlistElements.find(e => e.position === position)
    if (!this.currentPlaylistElement || !this.currentPlaylistElement.video) {
      console.error('Current playlist element is not valid.', this.currentPlaylistElement)
      this.currentPlaylistElement = this.getNextPlaylistElement()
    }

    if (!this.currentPlaylistElement) {
      throw new Error('This playlist does not have any valid element')
    }
  }

  setCurrentElement (playlistElement: VideoPlaylistElement) {
    this.currentPlaylistElement = playlistElement
  }

  getCurrentElement () {
    return this.currentPlaylistElement
  }

  getCurrentPosition () {
    if (!this.currentPlaylistElement) return -1

    return this.currentPlaylistElement.position
  }
}