Compare commits

..

No commits in common. "715144a9e745586843c7c1233b4c45991012d8c6" and "c6b4c061de625fc56df123d83bef2fb3eee68fb4" have entirely different histories.

7 changed files with 74 additions and 390 deletions

9
bot.go
View File

@ -10,7 +10,6 @@ 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"
@ -33,8 +32,6 @@ 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")
@ -60,9 +57,6 @@ 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() {
@ -78,8 +72,7 @@ func main() {
select { select {
case <-sc: case <-sc:
app.db.Close(context.Background()) app.db.Close(context.Background())
app.mpdw.Close() app.queue.Reset()
app.mpdc()
app.voice.Close() app.voice.Close()
app.discord.Close() app.discord.Close()
return return

1
db.go
View File

@ -26,6 +26,7 @@ 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,19 +1,17 @@
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"
@ -24,26 +22,24 @@ 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 int64 `json:"position"` Position int `json:"position"`
Length int64 `json:"len,omitempty"` Length int `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: 800 * time.Millisecond} var l = rate.Sometimes{Interval: 1 * time.Second}
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)
@ -56,87 +52,24 @@ 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()
if err != nil { msg["payload"] = SongInfo{
log.Println(err) Playlist: app.queue.Current().Playlist.Id,
return nil PlaylistName: app.queue.Current().Playlist.Title,
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
} }
@ -169,19 +102,12 @@ 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()
app.ambiance.Add(volume) loop := beep.Loop(-1, play)
app.ambiance.Add(loop)
discordspeaker.Unlock() discordspeaker.Unlock()
msg := make(map[string]interface{}) msg := make(map[string]interface{})
@ -250,13 +176,7 @@ func (app *App) ambianceAdd(payload ...interface{}) {
} }
func (app *App) songPosition(payload ...interface{}) { func (app *App) songPosition(payload ...interface{}) {
status, err := app.mpd.Status() if !app.queue.IsPlaying() {
if err != nil {
log.Println(err)
return
}
if status["state"] == "stop" {
return return
} }
@ -264,20 +184,9 @@ 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"] = time.Duration(slen * float64(time.Second)).Milliseconds() out["len"] = app.queue.Len()
out["position"] = time.Duration(spos * float64(time.Second)).Milliseconds() out["position"] = app.queue.Position()
msg["payload"] = out msg["payload"] = out
ws_msg <- msg ws_msg <- msg
@ -285,40 +194,54 @@ 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_info event received") log.Println("song_over event received")
msg := app.songInfoEvent("song_info") msg := app.songInfoEvent("song_info")
if msg != nil { ws_msg <- msg
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.mpd.Stop() app.queue.Reset()
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()
if err != nil { app.queue.Prev()
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()
if err != nil { app.queue.Next()
log.Println(err)
} msg := app.songInfoEvent("song_info")
ws_msg <- msg
} }
func (app *App) addPlaylist(payload ...interface{}) { func (app *App) addPlaylist(payload ...interface{}) {
@ -425,8 +348,7 @@ func (app *App) loadPlaylist(payload ...interface{}) {
return return
} }
app.mpd.Stop() app.queue.Reset()
app.mpd.Clear()
go func() { go func() {
for _, vid := range list { for _, vid := range list {
@ -448,43 +370,22 @@ func (app *App) loadPlaylist(payload ...interface{}) {
continue continue
} }
// state:stop ff, err := ffmpeg.NewPCM(string(yt), sampleRate, channels)
songid, err := app.mpd.AddID(string(yt), 0)
if err != nil { if err != nil {
log.Println(err) log.Println(err)
continue continue
} }
mpdcmd := app.mpd.Command("%s %d %s %s", mpd.Quoted("addtagid"), songid, mpd.Quoted("artist"), ytinfo.Channel) song := &Song{
err = mpdcmd.OK() Title: ytinfo.Title,
if err != nil { Channel: ytinfo.Channel,
log.Println(err) VideoID: vid,
continue Length: ytinfo.Len,
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,13 +1,11 @@
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
@ -16,6 +14,7 @@ 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
@ -83,6 +82,7 @@ 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
View File

@ -1,166 +0,0 @@
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,7 +6,6 @@ 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"
@ -19,31 +18,13 @@ 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)
mpdstream, err := NewMPD() app.queue = new(Queue)
if err != nil { app.queue.list = list.New()
log.Fatal(err) app.queue.Events = app.events
} 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.")
} }
@ -102,10 +83,10 @@ func (q Queue) Current() *Song {
} }
func (q *Queue) Reset() { func (q *Queue) Reset() {
err := app.mpd.Clear() q.playing = false
if err != nil {
log.Println(err) q.current = nil
} q.list = q.list.Init()
} }
func (q *Queue) Next() { func (q *Queue) Next() {

View File

@ -1,26 +0,0 @@
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 }}"