-
Notifications
You must be signed in to change notification settings - Fork 1
/
service_handler_play.go
102 lines (84 loc) · 2.39 KB
/
service_handler_play.go
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
package service
import (
"context"
"github.com/bwmarrin/discordgo"
"github.com/rl404/fairy/errors/stack"
"github.com/rl404/naka/internal/domain/template/entity"
)
// HandlePlay to handle play.
func (s *service) HandlePlay(ctx context.Context, m *discordgo.MessageCreate, g *discordgo.Guild, args []string) error {
// Just play the queue.
if len(args) == 0 {
return s.play(ctx, m, g)
}
// Search song.
return stack.Wrap(ctx, s.searchSong(ctx, m, g, args, true))
}
func (s *service) play(ctx context.Context, m *discordgo.MessageCreate, g *discordgo.Guild) error {
// Player already exist.
if s.discord.IsPlayerExist(g.ID) {
return nil
}
// Check queue.
if s.queue.IsEmpty(ctx, g.ID) {
if _, err := s.discord.SendMessage(ctx, m.ChannelID, entity.EmptyQueue); err != nil {
return stack.Wrap(ctx, err)
}
return nil
}
// Join channel.
if err := s.HandleJoin(ctx, m, g); err != nil {
return stack.Wrap(ctx, err)
}
// Loop the queue.
go func() error {
s.discord.SetPlayerExist(g.ID, true)
defer s.discord.SetPlayerExist(g.ID, false)
for {
// Get queue.
queue := s.queue.GetList(ctx, g.ID)
i := s.queue.GetIndex(ctx, g.ID)
if len(queue) == 0 || i >= len(queue) {
if _, err := s.discord.SendMessage(ctx, m.ChannelID, entity.EndQueue); err != nil {
return stack.Wrap(ctx, err)
}
return nil
}
song := queue[i]
if _, err := s.discord.SendMessageEmbed(ctx, m.ChannelID, s.template.GetPlaying(entity.Video{
Title: song.Title,
URL: song.URL,
ChannelTitle: song.ChannelTitle,
ChannelURL: song.ChannelURL,
Image: song.Image,
Duration: song.Duration,
View: song.View,
Like: song.Like,
Dislike: song.Dislike,
QueueI: i + 1,
QueueCnt: len(queue),
})); err != nil {
return stack.Wrap(ctx, err)
}
if err := s.discord.SetPlaying(ctx, g.ID, true); err != nil {
return stack.Wrap(ctx, err)
}
// Start stream.
if err := s.discord.Stream(ctx, g.ID, song.SourceURL); err != nil {
return stack.Wrap(ctx, err)
}
// Go next queue.
if !s.discord.GetDisableAutoNext(g.ID) {
s.queue.SetIndex(ctx, g.ID, i+1)
}
s.discord.SetDisableAutoNext(g.ID, false)
if err := s.discord.SetPlaying(ctx, g.ID, false); err != nil {
return stack.Wrap(ctx, err)
}
if s.discord.GetStopped(g.ID) {
return nil
}
}
}()
return nil
}