dndmusicbot/events.go

342 lines
7.0 KiB
Go

package main
import (
"context"
"dndmusicbot/reisenstreamer"
discordspeaker "dndmusicbot/speaker"
"encoding/json"
"log"
"math/rand"
"net/url"
"path/filepath"
"time"
"github.com/google/uuid"
"github.com/gopxl/beep"
"github.com/kataras/go-events"
"golang.org/x/time/rate"
ytdl "github.com/kkdai/youtube/v2"
)
var l = rate.Sometimes{Interval: 800 * time.Millisecond}
var ytdl_client = ytdl.Client{}
func init() {
log.Println("events.go loading...")
app.events = events.New()
app.events.On("load_playlist", app.loadPlaylist)
app.events.On("add_playlist", app.addPlaylist)
//app.events.On("preload_song", app.preloadSong)
//app.events.On("song_over", 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("ambiance_play", app.ambiancePlay)
app.events.On("ambiance_stop", app.ambianceStop)
app.events.On("ambiance_add", app.ambianceAdd)
app.events.On("play", app.play)
app.events.On("stop", app.stop)
app.events.On("next", app.nextSong)
app.events.On("prev", app.prevSong)
app.events.On("vol_up", app.volup)
app.events.On("vol_down", app.voldown)
app.events.On("vol_set", app.volset)
//app.events.On("tick", app.checkQueue)
app.events.On("tick", app.songPosition)
//app.events.On("tick", app.checkTimeleft)
}
func (app *App) songInfoEvent(event string) (ev Event, err error) {
ev.Event = event
info := new(SongInfo)
info.Pause = !player.Playing
if player.current == nil || info.Pause {
ev.Payload = *info
return
}
item := player.current.Value.(*PlayerItem)
info.Title = item.Title
info.Channel = item.Artist
info.Song = item.ID
info.Length = item.Duration.Milliseconds()
info.Position = item.Position.Milliseconds()
info.Index = item.Idx
pl, err := app.GetPlaylist(player.PlaylistID)
if err != nil {
log.Println(err)
return
}
info.Playlist = pl.Id
info.PlaylistName = pl.Title
ev.Payload = *info
return ev, nil
}
func (app *App) ambiancePlay(payload ...interface{}) {
if !(len(payload) > 0) {
log.Println("ambiance_play called without a payload.")
return
}
var id string
switch data := payload[0].(type) {
case json.RawMessage:
var err error
err = json.Unmarshal(data, &id)
if err != nil {
log.Println(err)
return
}
default:
log.Println("loadPlaylist called with invalid payload.")
return
}
amb, err := GetAmbiance(id)
if err != nil {
log.Println(err)
return
}
discordspeaker.Lock()
ambMixer.Clear()
stream := reisenstreamer.New(context.Background(), filepath.Join(cwd, amb.Path))
stream.Repeat = true
ambMixer.Add(beep.Resample(3, beep.SampleRate(stream.SampleRate), beep.SampleRate(48000), stream.StreamerFunc()))
discordspeaker.Unlock()
ev := Event{"ambiance_play", map[string]string{
"id": id,
}}
go ws.SendEvent(ev)
}
func (app *App) ambianceStop(payload ...interface{}) {
log.Println("Stopping ambiance")
discordspeaker.Lock()
ambMixer.Clear()
discordspeaker.Unlock()
go ws.SendEvent(Event{"ambiance_stop", nil})
}
func (app *App) ambianceAdd(payload ...interface{}) {
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
}
amb, err := AddAmbiance(amburl, ambtitle)
if err != nil {
log.Println(err)
return
}
ev := Event{"ambiance_add", map[string]string{
"title": amb.Title,
"id": amb.Id,
}}
go ws.SendEvent(ev)
}
func (app *App) songPosition(payload ...interface{}) {
if player.current == nil {
return
}
item := player.current.Value.(*PlayerItem)
l.Do(func() {
ev := Event{"song_position", map[string]int64{
"len": item.Duration.Milliseconds(),
"position": item.Position.Milliseconds(),
}}
go ws.SendEvent(ev)
})
}
func (app *App) songInfo(payload ...interface{}) {
log.Println("song_info event received")
ev, err := app.songInfoEvent("song_info")
if err != nil {
log.Println(err)
return
}
go ws.SendEvent(ev)
}
func (app *App) play(payload ...interface{}) {
if !(len(payload) > 0) {
log.Println("play called without a payload.")
return
}
raw := payload[0].(json.RawMessage)
var idx int
json.Unmarshal(raw, &idx)
go player.Play(idx)
}
func (app *App) stop(payload ...interface{}) {
log.Println("stop event received")
go player.Stop()
go ws.SendEvent(Event{"stop", nil})
}
func (app *App) prevSong(payload ...interface{}) {
log.Println("prev_song event received")
go player.Prev()
}
func (app *App) nextSong(payload ...interface{}) {
log.Println("next_song event received")
go player.Next()
}
func (app *App) addPlaylist(payload ...interface{}) {
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
}
_, err = ytdl_client.GetPlaylist(plurl)
if err != nil {
log.Println("Error getting youtube playlist info,", plid)
}
id, err := app.AddPlaylist(pltitle, plid)
if err != nil {
log.Println("Error getting youtube playlist info,", plid)
}
ev := Event{"new_playlist", map[string]string{
"url": id.String(),
"title": pltitle,
}}
go ws.SendEvent(ev)
}
func (app *App) loadPlaylist(payload ...interface{}) {
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)
pl, err := app.GetPlaylist(id)
if err != nil {
log.Printf("Unable to find playlist with id %s (%v)\n", id, err)
return
}
list, err := ytdl_client.GetPlaylist(pl.Url)
if err != nil {
log.Println("Error getting playlist info,", id)
return
}
rand.Shuffle(len(list.Videos), func(i, j int) { list.Videos[i], list.Videos[j] = list.Videos[j], list.Videos[i] })
go player.LoadPlaylist(pl.Id, list)
}