src/music/queue.go (view raw)
1package music
2
3import (
4 "os"
5
6 "github.com/BiRabittoh/disgord/src/mylog"
7 "github.com/bwmarrin/discordgo"
8 "github.com/kkdai/youtube/v2"
9)
10
11var logger = mylog.NewLogger(os.Stdin, "music", mylog.DEBUG)
12
13type Queue struct {
14 nowPlaying *youtube.Video
15 items []*youtube.Video
16 audioStream *Audio
17 vc *discordgo.VoiceConnection
18}
19
20// queues stores all guild queues
21var queues = map[string]*Queue{}
22
23// GetOrCreateQueue fetches or creates a new queue for the guild
24func GetOrCreateQueue(vc *discordgo.VoiceConnection) (q *Queue) {
25 q, ok := queues[vc.GuildID]
26 if !ok {
27 q = &Queue{vc: vc}
28 queues[vc.GuildID] = q
29 return
30 }
31
32 if q.vc.Ready == false {
33 q.vc = vc
34 }
35 return
36}
37
38// GetQueue returns either nil or the queue for the requested guild
39func GetQueue(guildID string) *Queue {
40 q, ok := queues[guildID]
41 if ok {
42 return q
43 }
44 return nil
45}
46
47// AddVideo adds a new video to the queue
48func (q *Queue) AddVideo(video *youtube.Video) {
49 q.items = append(q.items, video)
50 if q.nowPlaying == nil {
51 q.PlayNext()
52 }
53}
54
55// AddVideos adds a list of videos to the queue
56func (q *Queue) AddVideos(videos []*youtube.Video) {
57 q.items = append(q.items, videos...)
58 if q.nowPlaying == nil {
59 q.PlayNext()
60 }
61}
62
63// PlayNext starts playing the next video in the queue
64func (q *Queue) PlayNext() (err error) {
65 if q.audioStream != nil {
66 q.audioStream.Stop()
67 }
68
69 if len(q.items) == 0 {
70 q.nowPlaying = nil
71 return q.vc.Disconnect()
72 }
73
74 q.nowPlaying = q.items[0]
75 q.items = q.items[1:]
76
77 formats := q.nowPlaying.Formats.WithAudioChannels()
78 if len(formats) == 0 {
79 logger.Debug("no formats with audio channels available for video " + q.nowPlaying.ID)
80 return q.PlayNext()
81 }
82
83 q.audioStream, err = NewAudio(formats[0].URL, q.vc)
84 if err != nil {
85 return
86 }
87
88 q.audioStream.Monitor(func() { q.PlayNext() })
89 return
90}
91
92// Stop stops the player and clears the queue
93func (q *Queue) Stop() error {
94 q.Clear()
95 q.nowPlaying = nil
96 q.audioStream.Stop()
97 return q.vc.Disconnect()
98}
99
100// Pause pauses the player
101func (q *Queue) Pause() {
102 q.audioStream.Pause()
103}
104
105// Resume resumes the player
106func (q *Queue) Resume() {
107 q.audioStream.Resume()
108}
109
110// Clear clears the video queue
111func (q *Queue) Clear() {
112 q.items = []*youtube.Video{}
113}
114
115// Videos returns all videos in the queue including the now playing one
116func (q *Queue) Videos() []*youtube.Video {
117 if q.nowPlaying != nil {
118 return append([]*youtube.Video{q.nowPlaying}, q.items...)
119 }
120 return q.items
121}
122
123func (q *Queue) VoiceChannelID() string {
124 return q.vc.ChannelID
125}