dndmusicbot/events.go

644 lines
12 KiB
Go
Raw Permalink Normal View History

2022-11-18 21:18:12 +00:00
package main
import (
"context"
2022-11-25 13:06:26 +00:00
"dndmusicbot/opus"
2022-11-18 21:18:12 +00:00
discordspeaker "dndmusicbot/speaker"
"encoding/json"
"log"
"net/url"
"os"
2022-11-23 07:37:59 +00:00
"strconv"
2022-11-18 21:18:12 +00:00
"time"
"github.com/faiface/beep"
2022-11-23 22:29:45 +00:00
"github.com/faiface/beep/effects"
2022-11-23 07:37:59 +00:00
"github.com/fhs/gompd/v2/mpd"
2022-11-18 21:18:12 +00:00
"github.com/google/uuid"
"github.com/kataras/go-events"
"golang.org/x/time/rate"
)
type SongInfo struct {
Playlist uuid.UUID `json:"playlist,omitempty"`
PlaylistName string `json:"playlistname,omitempty"`
Title string `json:"current,omitempty"`
Channel string `json:"channel,omitempty"`
2022-11-23 07:37:59 +00:00
Position int64 `json:"position"`
Length int64 `json:"len,omitempty"`
2022-11-18 21:18:12 +00:00
Pause bool `json:"pause"`
Song string `json:"song,omitempty"`
2022-11-18 21:18:12 +00:00
}
2022-12-22 11:43:40 +00:00
var (
l = rate.Sometimes{Interval: 800 * time.Millisecond}
)
var (
ev events.EventEmmiter
)
2022-11-18 21:18:12 +00:00
func init() {
log.Println("events.go loading...")
2022-11-23 07:37:59 +00:00
2022-12-22 11:43:40 +00:00
ev = events.New()
2022-11-18 21:18:12 +00:00
2022-12-22 11:43:40 +00:00
ev.On("load_playlist", loadPlaylist)
ev.On("add_playlist", addPlaylist)
2022-11-18 21:18:12 +00:00
2022-12-22 11:43:40 +00:00
//ev.On("preload_song", app.preloadSong)
//ev.On("song_over", app.songInfo)
//ev.On("song_start", app.songInfo)
ev.On("player", songInfo)
//ev.On("song_position", app.songPosition)
2022-11-18 21:18:12 +00:00
2022-12-22 11:43:40 +00:00
ev.On("ambiance_play", ambiancePlay)
ev.On("ambiance_stop", ambianceStop)
ev.On("ambiance_add", ambianceAdd)
2022-11-18 21:18:12 +00:00
2022-12-22 11:43:40 +00:00
ev.On("stop", stop)
ev.On("next", nextSong)
ev.On("prev", prevSong)
2022-11-18 21:18:12 +00:00
2022-12-22 11:43:40 +00:00
ev.On("vol_up", volup)
ev.On("vol_down", voldown)
ev.On("vol_set", volset)
2022-12-03 18:22:05 +00:00
2022-12-22 11:43:40 +00:00
//ev.On("tick", app.checkQueue)
ev.On("tick", songPosition)
//ev.On("tick", app.checkTimeleft)
2022-11-18 21:18:12 +00:00
}
2022-12-22 11:43:40 +00:00
func volup(payload ...interface{}) {
2022-12-03 18:22:05 +00:00
if !(len(payload) > 0) {
log.Println("volup called without a payload.")
return
}
var t string
switch data := payload[0].(type) {
case json.RawMessage:
var err error
err = json.Unmarshal(data, &t)
if err != nil {
log.Println(err)
return
}
default:
log.Println("volup called with invalid payload.")
return
}
switch t {
case "playlist":
pl_volume.Volume = pl_volume.Volume + 0.1
case "ambiance":
amb_volume.Volume = amb_volume.Volume + 0.1
}
}
2022-12-22 11:43:40 +00:00
func voldown(payload ...interface{}) {
2022-12-03 18:22:05 +00:00
if !(len(payload) > 0) {
log.Println("voldown called without a payload.")
return
}
var t string
switch data := payload[0].(type) {
case json.RawMessage:
var err error
err = json.Unmarshal(data, &t)
if err != nil {
log.Println(err)
return
}
default:
log.Println("voldown called with invalid payload.")
return
}
switch t {
case "playlist":
pl_volume.Volume = pl_volume.Volume - 0.1
case "ambiance":
amb_volume.Volume = amb_volume.Volume - 0.1
}
}
2022-12-22 11:43:40 +00:00
func volset(payload ...interface{}) {
2022-12-03 18:22:05 +00:00
if !(len(payload) > 0) {
log.Println("volset called without a payload.")
return
}
var data map[string]string
switch js := payload[0].(type) {
case json.RawMessage:
json.Unmarshal(js, &data)
default:
log.Println("volset called with invalid payload.")
return
}
vol, err := strconv.ParseFloat(data["vol"], 64)
if err != nil {
log.Println(err)
return
}
switch data["type"] {
case "playlist":
pl_volume.Volume = vol
case "ambiance":
amb_volume.Volume = vol
}
2022-12-22 11:43:40 +00:00
sendVolume()
2022-12-03 18:22:05 +00:00
}
2022-12-22 11:43:40 +00:00
func sendVolume() {
2022-12-03 18:22:05 +00:00
msg := make(map[string]interface{})
out := make(map[string]float64)
msg["event"] = "volume"
out["playlist"] = pl_volume.Volume
out["ambiance"] = amb_volume.Volume
msg["payload"] = out
ws_msg <- msg
}
2022-12-22 11:43:40 +00:00
func songInfoEvent(event string) map[string]interface{} {
2022-11-18 21:18:12 +00:00
msg := make(map[string]interface{})
msg["event"] = event
2022-12-22 11:43:40 +00:00
status, err := mpdc.Status()
2022-11-23 07:37:59 +00:00
if err != nil {
log.Println(err)
return nil
}
2022-11-18 21:18:12 +00:00
2022-12-22 11:43:40 +00:00
cur, err := mpdc.CurrentSong()
2022-11-23 07:37:59 +00:00
if err != nil {
log.Println(err)
return nil
2022-11-18 21:18:12 +00:00
}
2022-11-23 07:37:59 +00:00
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
}
2022-12-22 11:43:40 +00:00
pl, err := GetPlaylist(plid)
2022-11-23 07:37:59 +00:00
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
2022-11-18 21:18:12 +00:00
return msg
}
2022-12-22 11:43:40 +00:00
func ambiancePlay(payload ...interface{}) {
2022-11-18 21:18:12 +00:00
if !(len(payload) > 0) {
log.Println("ambiance_play called without a payload.")
return
}
2022-11-25 13:06:26 +00:00
var id string
2022-11-18 21:18:12 +00:00
switch data := payload[0].(type) {
case json.RawMessage:
var err error
2022-11-25 13:06:26 +00:00
err = json.Unmarshal(data, &id)
2022-11-18 21:18:12 +00:00
if err != nil {
log.Println(err)
return
}
default:
log.Println("loadPlaylist called with invalid payload.")
return
}
2022-11-25 13:06:26 +00:00
amb, err := GetAmbiance(id)
2022-11-18 21:18:12 +00:00
if err != nil {
2022-11-25 13:06:26 +00:00
log.Println(err)
return
}
f, err := os.Open(amb.Path)
if err != nil {
log.Println(err)
return
2022-11-18 21:18:12 +00:00
}
2022-11-25 13:06:26 +00:00
play, err := opus.New(f)
2022-11-18 21:18:12 +00:00
if err != nil {
2022-11-25 13:06:26 +00:00
log.Println(err)
return
2022-11-18 21:18:12 +00:00
}
2022-11-25 13:06:26 +00:00
2022-11-23 22:29:45 +00:00
loop := beep.Loop(-1, play)
volume := &effects.Volume{
Streamer: loop,
Base: 2,
2022-11-25 13:06:26 +00:00
Volume: -2.5,
2022-11-23 22:29:45 +00:00
Silent: false,
}
2022-11-18 21:18:12 +00:00
discordspeaker.Lock()
2022-12-22 11:43:40 +00:00
amb_mixer.Clear()
amb_mixer.Add(volume)
2022-11-18 21:18:12 +00:00
discordspeaker.Unlock()
msg := make(map[string]interface{})
out := make(map[string]interface{})
2022-12-22 11:43:40 +00:00
amb_curr = amb
2022-11-18 21:18:12 +00:00
msg["event"] = "ambiance_play"
2022-11-25 13:06:26 +00:00
out["id"] = id
2022-11-18 21:18:12 +00:00
msg["payload"] = out
ws_msg <- msg
}
2022-12-22 11:43:40 +00:00
func ambianceStop(payload ...interface{}) {
2022-11-18 21:18:12 +00:00
log.Println("Stopping ambiance")
discordspeaker.Lock()
2022-12-22 11:43:40 +00:00
amb_mixer.Clear()
2022-11-18 21:18:12 +00:00
discordspeaker.Unlock()
msg := make(map[string]interface{})
msg["event"] = "ambiance_stop"
ws_msg <- msg
}
2022-12-22 11:43:40 +00:00
func ambianceAdd(payload ...interface{}) {
2022-11-18 21:18:12 +00:00
if !(len(payload) > 0) {
log.Println("addPlaylist called without a payload.")
return
}
log.Println("ambiance_add event received")
var data map[string]string
switch js := payload[0].(type) {
case json.RawMessage:
json.Unmarshal(js, &data)
default:
log.Println("newPlaylist called with invalid payload.")
return
}
amburl, ok := data["url"]
if !ok {
log.Println("addPlaylist without url")
return
}
ambtitle, ok := data["title"]
if !ok {
log.Println("addPlaylist without title")
return
}
2022-11-25 13:06:26 +00:00
amb, err := AddAmbiance(amburl, ambtitle)
2022-11-18 21:18:12 +00:00
if err != nil {
log.Println(err)
return
}
msg := make(map[string]interface{})
out := make(map[string]interface{})
msg["event"] = "ambiance_add"
2022-11-25 13:06:26 +00:00
out["title"] = amb.Title
out["id"] = amb.Id
2022-11-18 21:18:12 +00:00
msg["payload"] = out
ws_msg <- msg
}
2022-12-22 11:43:40 +00:00
func songPosition(payload ...interface{}) {
status, err := mpdc.Status()
2022-11-23 07:37:59 +00:00
if err != nil {
log.Println(err)
return
}
if status["state"] == "stop" {
2022-11-18 21:18:12 +00:00
return
}
l.Do(func() {
msg := make(map[string]interface{})
out := make(map[string]interface{})
2022-11-23 07:37:59 +00:00
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
}
2022-11-18 21:18:12 +00:00
msg["event"] = "song_position"
2022-11-23 07:37:59 +00:00
out["len"] = time.Duration(slen * float64(time.Second)).Milliseconds()
out["position"] = time.Duration(spos * float64(time.Second)).Milliseconds()
2022-11-18 21:18:12 +00:00
msg["payload"] = out
ws_msg <- msg
})
}
2022-12-22 11:43:40 +00:00
func songInfo(payload ...interface{}) {
2022-11-23 07:37:59 +00:00
log.Println("song_info event received")
2022-11-18 21:18:12 +00:00
2022-12-22 11:43:40 +00:00
msg := songInfoEvent("song_info")
2022-11-23 07:37:59 +00:00
if msg != nil {
ws_msg <- msg
}
2022-11-18 21:18:12 +00:00
}
2022-12-22 11:43:40 +00:00
func stop(payload ...interface{}) {
2022-11-18 21:18:12 +00:00
log.Println("stop event received")
2022-11-23 07:37:59 +00:00
2022-12-22 11:43:40 +00:00
mpd_mutex.Lock()
if mpd_plcf != nil {
mpd_plcf()
}
2022-12-22 11:43:40 +00:00
mpdc.Stop()
mpd_mutex.Unlock()
2022-11-18 21:18:12 +00:00
msg := make(map[string]interface{})
msg["event"] = "stop"
ws_msg <- msg
}
2022-12-22 11:43:40 +00:00
func prevSong(payload ...interface{}) {
2022-11-18 21:18:12 +00:00
log.Println("prev_song event received")
2022-12-22 11:43:40 +00:00
mpd_mutex.Lock()
err := mpdc.Previous()
mpd_mutex.Unlock()
2022-11-23 07:37:59 +00:00
if err != nil {
log.Println(err)
}
2022-11-18 21:18:12 +00:00
}
2022-12-22 11:43:40 +00:00
func nextSong(payload ...interface{}) {
2022-11-18 21:18:12 +00:00
log.Println("next_song event received")
2022-12-22 11:43:40 +00:00
mpd_mutex.Lock()
err := mpdc.Next()
mpd_mutex.Unlock()
2022-11-23 07:37:59 +00:00
if err != nil {
log.Println(err)
}
2022-11-18 21:18:12 +00:00
}
2022-12-22 11:43:40 +00:00
func addPlaylist(payload ...interface{}) {
2022-11-18 21:18:12 +00:00
if !(len(payload) > 0) {
log.Println("addPlaylist called without a payload.")
return
}
log.Println("add_playlist event received")
var data map[string]string
switch js := payload[0].(type) {
case json.RawMessage:
json.Unmarshal(js, &data)
default:
log.Println("newPlaylist called with invalid payload.")
return
}
plurl, ok := data["url"]
if !ok {
log.Println("addPlaylist without url")
return
}
pltitle, ok := data["title"]
if !ok {
log.Println("addPlaylist without title")
return
}
pl, err := url.Parse(plurl)
if err != nil {
log.Println("addPlaylist invalid url")
return
}
plid := pl.Query().Get("list")
if plid == "" {
log.Println("addPlaylist missing list in url")
return
}
2022-12-22 11:43:40 +00:00
_, err = YTPlaylist(plid)
2022-11-18 21:18:12 +00:00
if err != nil {
log.Println("Error getting youtube playlist info,", plid)
}
2022-12-22 11:43:40 +00:00
id, err := AddPlaylist(pltitle, plid)
2022-11-18 21:18:12 +00:00
if err != nil {
log.Println("Error getting youtube playlist info,", plid)
}
msg := make(map[string]interface{})
msg["event"] = "new_playlist"
msg["payload"] = map[string]string{"url": id.String(), "title": pltitle}
ws_msg <- msg
}
2022-12-22 11:43:40 +00:00
func loadPlaylist(payload ...interface{}) {
2022-11-18 21:18:12 +00:00
log.Println("load_playlist event received")
if !(len(payload) > 0) {
log.Println("loadPlaylist called without a payload.")
return
}
var id uuid.UUID
switch data := payload[0].(type) {
case json.RawMessage:
var err error
var tmp string
json.Unmarshal(data, &tmp)
id, err = uuid.Parse(tmp)
if err != nil {
log.Println("Unable to parse UUID,", err)
}
case uuid.UUID:
id = data
default:
log.Println("loadPlaylist called with invalid payload.")
return
}
log.Println("Loading new playlist: ", id)
2022-12-22 11:43:40 +00:00
pl, err := GetPlaylist(id)
2022-11-18 21:18:12 +00:00
if err != nil {
log.Println("Unable to find playlist with id,", id)
return
}
2022-12-22 11:43:40 +00:00
list, err := YTPlaylist(pl.Url)
2022-11-18 21:18:12 +00:00
if err != nil {
log.Println("Error getting playlist info,", id)
return
}
list, err = ShufflePlaylist(list)
if err != nil {
log.Println("Unable to shuffle playlist")
return
}
2022-12-22 11:43:40 +00:00
mpd_mutex.Lock()
if mpd_plcf != nil {
mpd_plcf()
}
2022-12-22 11:43:40 +00:00
mpdc.Stop()
mpdc.Clear()
mpd_mutex.Unlock()
ctx, cancel := context.WithCancel(context.Background())
2022-12-22 11:43:40 +00:00
mpd_plcf = cancel
2022-11-18 21:18:12 +00:00
go func() {
defer cancel()
for _, vid := range list {
log.Printf("Adding %s", vid)
2022-12-22 11:43:40 +00:00
ytinfo, err := YTVideo(vid)
if err != nil {
log.Println(err)
continue
}
2022-11-18 21:18:12 +00:00
2022-12-22 11:43:40 +00:00
_, yt, err := cache.GetOrCreateBytes(vid+".txt", func() ([]byte, error) {
2022-11-19 17:05:02 +00:00
uri, err := NewYTdl(vid)
if err != nil {
return nil, err
}
return uri, nil
})
2022-11-20 16:30:22 +00:00
if err != nil {
log.Println(err)
continue
}
// Run as a local function so we can defer the mutex unlock incase one of these errors.
ok := func() (ok bool) {
2022-12-22 11:43:40 +00:00
mpd_mutex.Lock()
defer mpd_mutex.Unlock()
2022-11-23 07:37:59 +00:00
if ctx.Err() != nil {
return false
}
2022-11-23 07:37:59 +00:00
ok = true
2022-11-23 07:37:59 +00:00
// state:stop
2022-12-22 11:43:40 +00:00
songid, err := mpdc.AddID(string(yt), 0)
if err != nil {
log.Println(err)
return
}
2022-11-18 21:18:12 +00:00
2022-12-22 11:43:40 +00:00
mpdcmd := mpdc.Command("%s %d %s %s", mpd.Quoted("addtagid"), songid, mpd.Quoted("artist"), ytinfo.Channel)
err = mpdcmd.OK()
if err != nil {
log.Println(err)
return
}
2022-11-23 07:37:59 +00:00
2022-12-22 11:43:40 +00:00
mpdcmd = mpdc.Command("%s %d %s %s", mpd.Quoted("addtagid"), songid, mpd.Quoted("title"), ytinfo.Title)
err = mpdcmd.OK()
if err != nil {
log.Println(err)
return
}
2022-12-22 11:43:40 +00:00
mpdcmd = mpdc.Command("%s %d %s %s", mpd.Quoted("addtagid"), songid, mpd.Quoted("location"), vid)
err = mpdcmd.OK()
if err != nil {
log.Println(err)
return
}
2022-12-22 11:43:40 +00:00
mpdcmd = mpdc.Command("%s %d %s %s", mpd.Quoted("addtagid"), songid, mpd.Quoted("album"), pl.Id.String())
err = mpdcmd.OK()
if err != nil {
log.Println(err)
return
}
2022-12-22 11:43:40 +00:00
mpdc.Play(-1)
2022-11-23 07:37:59 +00:00
return
}()
if !ok {
break
}
2022-11-18 21:18:12 +00:00
}
}()
}