aboutsummaryrefslogtreecommitdiff
path: root/src/services/queue.ts
blob: 85777e5e7361f3bf6d85d8926866ffe702f1b9c5 (plain)
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
import {injectable} from 'inversify';

export interface QueuedPlaylist {
  title: string;
  source: string;
}

export interface QueuedSong {
  title: string;
  artist: string;
  url: string;
  length: number;
  playlist: QueuedPlaylist | null;
}

@injectable()
export default class {
  private readonly guildQueues = new Map<string, QueuedSong[]>();
  private readonly queuePositions = new Map<string, number>();

  forward(guildId: string): void {
    const currentPosition = this.queuePositions.get(guildId);

    if (currentPosition && currentPosition + 1 <= this.size(guildId)) {
      this.queuePositions.set(guildId, currentPosition + 1);
    } else {
      throw new Error('No songs in queue to forward to.');
    }
  }

  back(guildId: string): void {
    const currentPosition = this.queuePositions.get(guildId);

    if (currentPosition && currentPosition - 1 >= 0) {
      this.queuePositions.set(guildId, currentPosition - 1);
    } else {
      throw new Error('No songs in queue to go back to.');
    }
  }

  get(guildId: string): QueuedSong[] {
    const currentPosition = this.queuePositions.get(guildId);

    if (currentPosition === undefined) {
      return [];
    }

    const guildQueue = this.guildQueues.get(guildId);

    if (!guildQueue) {
      throw new Error('Bad state. Queue for guild exists but position does not.');
    }

    return guildQueue.slice(currentPosition);
  }

  add(guildId: string, song: QueuedSong): void {
    if (!this.guildQueues.get(guildId)) {
      this.guildQueues.set(guildId, []);
      this.queuePositions.set(guildId, 0);
    }

    if (song.playlist) {
      // Add to end of queue
      this.guildQueues.set(guildId, [...this.guildQueues.get(guildId)!, song]);
    } else if (this.guildQueues.get(guildId)!.length === 0) {
      // Queue is currently empty
      this.guildQueues.set(guildId, [song]);
    } else {
      // Not from playlist, add immediately
      let insertAt = 0;

      // Loop until playlist song
      this.guildQueues.get(guildId)!.some(song => {
        if (song.playlist) {
          return true;
        }

        insertAt++;
        return false;
      });

      this.guildQueues.set(guildId, [...this.guildQueues.get(guildId)!.slice(0, insertAt), song, ...this.guildQueues.get(guildId)!.slice(insertAt)]);
    }
  }

  size(guildId: string): number {
    return this.get(guildId).length;
  }
}