Compare commits

...

4 Commits

7 changed files with 390 additions and 74 deletions

9
bot.go
View File

@ -10,6 +10,7 @@ import (
"github.com/bwmarrin/discordgo" "github.com/bwmarrin/discordgo"
"github.com/faiface/beep" "github.com/faiface/beep"
"github.com/fhs/gompd/v2/mpd"
"github.com/gohugoio/hugo/cache/filecache" "github.com/gohugoio/hugo/cache/filecache"
"github.com/jackc/pgx/v5" "github.com/jackc/pgx/v5"
"github.com/julienschmidt/httprouter" "github.com/julienschmidt/httprouter"
@ -32,6 +33,8 @@ var (
) )
func init() { func init() {
log.SetFlags(log.Ltime | log.Lshortfile)
log.Println("bot.go loading..") log.Println("bot.go loading..")
config.SetConfigName("config") config.SetConfigName("config")
config.SetConfigType("yaml") config.SetConfigType("yaml")
@ -57,6 +60,9 @@ type App struct {
active []string active []string
plidx int plidx int
cache *filecache.Cache cache *filecache.Cache
mpdc context.CancelFunc
mpdw *mpd.Watcher
mpd *mpd.Client
} }
func main() { func main() {
@ -72,7 +78,8 @@ func main() {
select { select {
case <-sc: case <-sc:
app.db.Close(context.Background()) app.db.Close(context.Background())
app.queue.Reset() app.mpdw.Close()
app.mpdc()
app.voice.Close() app.voice.Close()
app.discord.Close() app.discord.Close()
return return

1
db.go
View File

@ -26,7 +26,6 @@ type Playlist struct {
} }
func (app App) GetPlaylists() (playlists []Playlist, err error) { func (app App) GetPlaylists() (playlists []Playlist, err error) {
log.Println(app.db.Ping(context.Background()))
rows, err := app.db.Query(context.Background(), "SELECT id, url, title FROM playlists") rows, err := app.db.Query(context.Background(), "SELECT id, url, title FROM playlists")
if err != nil { if err != nil {
return nil, err return nil, err

221
events.go
View File

@ -1,17 +1,19 @@
package main package main
import ( import (
"dndmusicbot/ffmpeg"
discordspeaker "dndmusicbot/speaker" discordspeaker "dndmusicbot/speaker"
"encoding/json" "encoding/json"
"fmt" "fmt"
"log" "log"
"net/url" "net/url"
"os" "os"
"strconv"
"time" "time"
"github.com/faiface/beep" "github.com/faiface/beep"
"github.com/faiface/beep/effects"
"github.com/faiface/beep/mp3" "github.com/faiface/beep/mp3"
"github.com/fhs/gompd/v2/mpd"
"github.com/google/uuid" "github.com/google/uuid"
"github.com/kataras/go-events" "github.com/kataras/go-events"
"golang.org/x/time/rate" "golang.org/x/time/rate"
@ -22,24 +24,26 @@ type SongInfo struct {
PlaylistName string `json:"playlistname,omitempty"` PlaylistName string `json:"playlistname,omitempty"`
Title string `json:"current,omitempty"` Title string `json:"current,omitempty"`
Channel string `json:"channel,omitempty"` Channel string `json:"channel,omitempty"`
Position int `json:"position"` Position int64 `json:"position"`
Length int `json:"len,omitempty"` Length int64 `json:"len,omitempty"`
Pause bool `json:"pause"` Pause bool `json:"pause"`
Song string `json:"song,omitempty"` Song string `json:"song,omitempty"`
} }
var l = rate.Sometimes{Interval: 1 * time.Second} var l = rate.Sometimes{Interval: 800 * time.Millisecond}
func init() { func init() {
log.Println("events.go loading...") log.Println("events.go loading...")
app.events = events.New() app.events = events.New()
app.events.On("load_playlist", app.loadPlaylist) app.events.On("load_playlist", app.loadPlaylist)
app.events.On("add_playlist", app.addPlaylist) app.events.On("add_playlist", app.addPlaylist)
//app.events.On("preload_song", app.preloadSong) //app.events.On("preload_song", app.preloadSong)
app.events.On("song_over", app.songInfo) //app.events.On("song_over", app.songInfo)
app.events.On("song_start", app.songInfo) //app.events.On("song_start", app.songInfo)
app.events.On("player", app.songInfo)
//app.events.On("song_position", app.songPosition) //app.events.On("song_position", app.songPosition)
app.events.On("ambiance_play", app.ambiancePlay) app.events.On("ambiance_play", app.ambiancePlay)
@ -52,24 +56,87 @@ func init() {
//app.events.On("tick", app.checkQueue) //app.events.On("tick", app.checkQueue)
app.events.On("tick", app.songPosition) app.events.On("tick", app.songPosition)
app.events.On("tick", app.checkTimeleft) //app.events.On("tick", app.checkTimeleft)
} }
func (app *App) songInfoEvent(event string) map[string]interface{} { func (app *App) songInfoEvent(event string) map[string]interface{} {
msg := make(map[string]interface{}) msg := make(map[string]interface{})
msg["event"] = event msg["event"] = event
status, err := app.mpd.Status()
msg["payload"] = SongInfo{ if err != nil {
Playlist: app.queue.Current().Playlist.Id, log.Println(err)
PlaylistName: app.queue.Current().Playlist.Title, return nil
Title: app.queue.Current().Title,
Channel: app.queue.Current().Channel,
Position: 0,
Length: app.queue.Len(),
Pause: !app.queue.IsPlaying(),
Song: app.queue.Current().VideoID,
} }
cur, err := app.mpd.CurrentSong()
if err != nil {
log.Println(err)
return nil
}
info := new(SongInfo)
if status["state"] != "play" {
info.Pause = true
msg["payload"] = info
return msg
}
duration, ok := status["duration"]
if ok && duration != "" {
slen, err := strconv.ParseFloat(duration, 64)
if err != nil {
log.Println(err)
return nil
}
info.Length = time.Duration(slen * float64(time.Second)).Milliseconds()
}
elapsed, ok := status["elapsed"]
if ok && elapsed != "" {
spos, err := strconv.ParseFloat(elapsed, 64)
if err != nil {
log.Println(err)
return nil
}
info.Position = time.Duration(spos * float64(time.Second)).Milliseconds()
}
album, ok := cur["Album"]
if ok {
plid, err := uuid.ParseBytes([]byte(album))
if err != nil {
log.Println(err)
return nil
}
pl, err := app.GetPlaylist(plid)
if err != nil {
log.Println(err)
return nil
}
info.Playlist = pl.Id
info.PlaylistName = pl.Title
}
title, ok := cur["Title"]
if ok {
info.Title = title
}
artist, ok := cur["Artist"]
if ok {
info.Channel = artist
}
location, ok := cur["Location"]
if ok {
info.Song = location
}
msg["payload"] = *info
return msg return msg
} }
@ -102,12 +169,19 @@ func (app *App) ambiancePlay(payload ...interface{}) {
if err != nil { if err != nil {
log.Fatal(err) log.Fatal(err)
} }
loop := beep.Loop(-1, play)
volume := &effects.Volume{
Streamer: loop,
Base: 2,
Volume: -2,
Silent: false,
}
discordspeaker.Pause(false) discordspeaker.Pause(false)
discordspeaker.Lock() discordspeaker.Lock()
app.ambiance.Clear() app.ambiance.Clear()
loop := beep.Loop(-1, play) app.ambiance.Add(volume)
app.ambiance.Add(loop)
discordspeaker.Unlock() discordspeaker.Unlock()
msg := make(map[string]interface{}) msg := make(map[string]interface{})
@ -176,7 +250,13 @@ func (app *App) ambianceAdd(payload ...interface{}) {
} }
func (app *App) songPosition(payload ...interface{}) { func (app *App) songPosition(payload ...interface{}) {
if !app.queue.IsPlaying() { status, err := app.mpd.Status()
if err != nil {
log.Println(err)
return
}
if status["state"] == "stop" {
return return
} }
@ -184,9 +264,20 @@ func (app *App) songPosition(payload ...interface{}) {
msg := make(map[string]interface{}) msg := make(map[string]interface{})
out := make(map[string]interface{}) out := make(map[string]interface{})
slen, err := strconv.ParseFloat(status["duration"], 64)
if err != nil {
log.Println(err)
return
}
spos, err := strconv.ParseFloat(status["elapsed"], 64)
if err != nil {
return
}
msg["event"] = "song_position" msg["event"] = "song_position"
out["len"] = app.queue.Len() out["len"] = time.Duration(slen * float64(time.Second)).Milliseconds()
out["position"] = app.queue.Position() out["position"] = time.Duration(spos * float64(time.Second)).Milliseconds()
msg["payload"] = out msg["payload"] = out
ws_msg <- msg ws_msg <- msg
@ -194,54 +285,40 @@ func (app *App) songPosition(payload ...interface{}) {
} }
func (app *App) checkTimeleft(payload ...interface{}) {
if !app.queue.IsPlaying() {
return
}
timeleft := app.queue.Len() - app.queue.Position()
if timeleft <= 10000 && timeleft > 0 && !app.next {
app.events.Emit("preload_song")
}
}
func (app *App) songInfo(payload ...interface{}) { func (app *App) songInfo(payload ...interface{}) {
log.Println("song_over event received") log.Println("song_info event received")
msg := app.songInfoEvent("song_info") msg := app.songInfoEvent("song_info")
ws_msg <- msg if msg != nil {
ws_msg <- msg
app.next = false }
} }
func (app *App) stop(payload ...interface{}) { func (app *App) stop(payload ...interface{}) {
log.Println("stop event received") log.Println("stop event received")
discordspeaker.Lock()
app.queue.Reset() app.mpd.Stop()
discordspeaker.Unlock()
msg := make(map[string]interface{}) msg := make(map[string]interface{})
msg["event"] = "stop" msg["event"] = "stop"
ws_msg <- msg ws_msg <- msg
} }
func (app *App) prevSong(payload ...interface{}) { func (app *App) prevSong(payload ...interface{}) {
log.Println("prev_song event received") log.Println("prev_song event received")
err := app.mpd.Previous()
app.queue.Prev() if err != nil {
log.Println(err)
msg := app.songInfoEvent("song_info") }
ws_msg <- msg
} }
func (app *App) nextSong(payload ...interface{}) { func (app *App) nextSong(payload ...interface{}) {
log.Println("next_song event received") log.Println("next_song event received")
err := app.mpd.Next()
app.queue.Next() if err != nil {
log.Println(err)
msg := app.songInfoEvent("song_info") }
ws_msg <- msg
} }
func (app *App) addPlaylist(payload ...interface{}) { func (app *App) addPlaylist(payload ...interface{}) {
@ -348,7 +425,8 @@ func (app *App) loadPlaylist(payload ...interface{}) {
return return
} }
app.queue.Reset() app.mpd.Stop()
app.mpd.Clear()
go func() { go func() {
for _, vid := range list { for _, vid := range list {
@ -370,22 +448,43 @@ func (app *App) loadPlaylist(payload ...interface{}) {
continue continue
} }
ff, err := ffmpeg.NewPCM(string(yt), sampleRate, channels) // state:stop
songid, err := app.mpd.AddID(string(yt), 0)
if err != nil { if err != nil {
log.Println(err) log.Println(err)
continue continue
} }
song := &Song{ mpdcmd := app.mpd.Command("%s %d %s %s", mpd.Quoted("addtagid"), songid, mpd.Quoted("artist"), ytinfo.Channel)
Title: ytinfo.Title, err = mpdcmd.OK()
Channel: ytinfo.Channel, if err != nil {
VideoID: vid, log.Println(err)
Length: ytinfo.Len, continue
PCM: ff,
Playlist: *pl,
DLuri: string(yt),
} }
app.queue.Add(song)
mpdcmd = app.mpd.Command("%s %d %s %s", mpd.Quoted("addtagid"), songid, mpd.Quoted("title"), ytinfo.Title)
err = mpdcmd.OK()
if err != nil {
log.Println(err)
continue
}
mpdcmd = app.mpd.Command("%s %d %s %s", mpd.Quoted("addtagid"), songid, mpd.Quoted("location"), vid)
err = mpdcmd.OK()
if err != nil {
log.Println(err)
continue
}
mpdcmd = app.mpd.Command("%s %d %s %s", mpd.Quoted("addtagid"), songid, mpd.Quoted("album"), pl.Id.String())
err = mpdcmd.OK()
if err != nil {
log.Println(err)
continue
}
app.mpd.Play(-1)
} }
}() }()
} }

6
go.mod
View File

@ -1,11 +1,13 @@
module dndmusicbot module dndmusicbot
replace github.com/fhs/gompd/v2 => /home/steino/dev/go/gompd/
go 1.19 go 1.19
require ( require (
github.com/bwmarrin/discordgo v0.26.1 github.com/bwmarrin/discordgo v0.26.1
github.com/dpup/gohubbub v0.0.0-20140517235056-2dc6969d22d8
github.com/faiface/beep v1.1.0 github.com/faiface/beep v1.1.0
github.com/fhs/gompd/v2 v2.3.0
github.com/gohugoio/hugo v0.106.0 github.com/gohugoio/hugo v0.106.0
github.com/google/uuid v1.3.0 github.com/google/uuid v1.3.0
github.com/gorilla/websocket v1.5.0 github.com/gorilla/websocket v1.5.0
@ -14,7 +16,6 @@ require (
github.com/julienschmidt/httprouter v1.3.0 github.com/julienschmidt/httprouter v1.3.0
github.com/kataras/go-events v0.0.3 github.com/kataras/go-events v0.0.3
github.com/pkg/errors v0.9.1 github.com/pkg/errors v0.9.1
github.com/r3labs/sse/v2 v2.8.2
github.com/sosodev/duration v1.0.1 github.com/sosodev/duration v1.0.1
github.com/spf13/afero v1.9.3 github.com/spf13/afero v1.9.3
github.com/spf13/viper v1.14.0 github.com/spf13/viper v1.14.0
@ -82,7 +83,6 @@ require (
google.golang.org/genproto v0.0.0-20221027153422-115e99e71e1c // indirect google.golang.org/genproto v0.0.0-20221027153422-115e99e71e1c // indirect
google.golang.org/grpc v1.50.1 // indirect google.golang.org/grpc v1.50.1 // indirect
google.golang.org/protobuf v1.28.1 // indirect google.golang.org/protobuf v1.28.1 // indirect
gopkg.in/cenkalti/backoff.v1 v1.1.0 // indirect
gopkg.in/fatih/set.v0 v0.2.1 // indirect gopkg.in/fatih/set.v0 v0.2.1 // indirect
gopkg.in/ini.v1 v1.67.0 // indirect gopkg.in/ini.v1 v1.67.0 // indirect
gopkg.in/yaml.v2 v2.4.0 // indirect gopkg.in/yaml.v2 v2.4.0 // indirect

166
mpd.go Normal file
View File

@ -0,0 +1,166 @@
package main
import (
"bytes"
"context"
"io"
"log"
"os"
"os/exec"
"strconv"
"text/template"
"time"
"github.com/faiface/beep"
"github.com/fhs/gompd/v2/mpd"
"github.com/kataras/go-events"
)
type MPD struct {
file *os.File
f beep.Format
}
func init() {
log.Println("mpd.go loading..")
f, err := os.OpenFile(config.GetString("mpd.config"), os.O_RDWR|os.O_CREATE, 0755)
if err != nil {
log.Fatal(err)
}
t, err := template.New("mpd.tmpl").ParseFiles("tmpl/mpd.tmpl")
if err != nil {
log.Fatal(err)
}
err = t.Execute(f, config.GetStringMapString("mpd"))
if err != nil {
log.Fatal(err)
}
f.Close()
pidstr, err := os.ReadFile(config.GetString("mpd.pid"))
switch err {
case os.ErrNotExist:
log.Println("Pidfile not found, doing nothing")
case nil:
pid, _ := strconv.Atoi(string(bytes.TrimSpace(pidstr)))
proc, err := os.FindProcess(pid)
switch err {
case nil:
log.Println(proc.Kill())
case os.ErrProcessDone:
log.Println("Pid alreadt finished, doing nothing.")
default:
log.Fatal(err)
}
default:
log.Fatal(err)
}
ctx, cancel := context.WithCancel(context.Background())
app.mpdc = cancel
cmd := exec.CommandContext(
ctx,
config.GetString("mpd.cmd"),
"--no-daemon",
config.GetString("mpd.config"),
"-v",
)
cmd.Stdout = os.Stdout
cmd.Stderr = os.Stderr
go func() {
err := cmd.Run()
if err != nil {
log.Println(err)
}
cancel()
}()
// wait for mpd to start.
time.Sleep(2 * time.Second)
app.mpd, err = mpd.Dial("unix", config.GetString("mpd.sock"))
if err != nil {
log.Fatal(err)
}
app.mpd.Repeat(true)
app.mpd.Random(true)
err = app.mpd.EnableOutput(0)
if err != nil {
log.Fatal(err)
}
app.mpdw, err = mpd.NewWatcher("unix", config.GetString("mpd.sock"), "")
if err != nil {
log.Fatal(err)
}
go func() {
for {
select {
case ev := <-app.mpdw.Event:
app.events.Emit(events.EventName(ev))
case err := <-app.mpdw.Error:
log.Println(err)
return
}
}
}()
log.Println("mpd.go done.")
}
func NewMPD() (*MPD, error) {
out := new(MPD)
f, err := os.Open(config.GetString("mpd.fifo"))
if err != nil {
return nil, err
}
out.f = beep.Format{
SampleRate: beep.SampleRate(sampleRate),
NumChannels: channels,
Precision: 2,
}
out.file = f
return out, nil
}
func (m *MPD) Err() error {
return nil
}
func (m *MPD) Stream(samples [][2]float64) (n int, ok bool) {
tmp := make([]byte, m.f.NumChannels+2)
for i := range samples {
dn, err := m.file.Read(tmp)
if dn == len(tmp) {
samples[i], _ = m.f.DecodeSigned(tmp)
ok = true
}
if err == io.EOF {
ok = false
break
}
if err != nil {
log.Println(err)
ok = false
break
}
}
return len(samples), ok
}

View File

@ -6,6 +6,7 @@ import (
"time" "time"
"github.com/faiface/beep" "github.com/faiface/beep"
"github.com/faiface/beep/effects"
"github.com/kataras/go-events" "github.com/kataras/go-events"
"dndmusicbot/ffmpeg" "dndmusicbot/ffmpeg"
@ -18,13 +19,31 @@ type Ambiance struct {
} }
func init() { func init() {
log.Println("queue.go loading..")
app.ambiance = beep.Mixer{} app.ambiance = beep.Mixer{}
discordspeaker.Play(&app.ambiance) discordspeaker.Play(&app.ambiance)
app.queue = new(Queue) mpdstream, err := NewMPD()
app.queue.list = list.New() if err != nil {
app.queue.Events = app.events log.Fatal(err)
discordspeaker.Play(app.queue) }
volume := &effects.Volume{
Streamer: mpdstream,
Base: 2,
Volume: -2,
Silent: false,
}
discordspeaker.Play(volume)
/*
app.queue = new(Queue)
app.queue.list = list.New()
app.queue.Events = app.events
discordspeaker.Play(app.queue)
*/
log.Println("queue.go done.") log.Println("queue.go done.")
} }
@ -83,10 +102,10 @@ func (q Queue) Current() *Song {
} }
func (q *Queue) Reset() { func (q *Queue) Reset() {
q.playing = false err := app.mpd.Clear()
if err != nil {
q.current = nil log.Println(err)
q.list = q.list.Init() }
} }
func (q *Queue) Next() { func (q *Queue) Next() {

26
tmpl/mpd.tmpl Normal file
View File

@ -0,0 +1,26 @@
audio_output {
type "fifo"
name "fifo-output"
path "{{ .fifo }}"
}
decoder {
plugin "wildmidi"
enabled "no"
}
decoder {
plugin "hybrid_dsd"
enabled "no"
}
input {
plugin "qobuz"
enabled "no"
}
resampler {
plugin "soxr"
quality "very high"
}
volume_normalization "yes"
audio_output_format "48000:16:2"
bind_to_address "{{ .sock }}"
pid_file "{{ .pid }}"