dndmusicbot/ws.go

111 lines
1.9 KiB
Go
Raw Normal View History

2022-11-18 21:18:12 +00:00
package main
import (
"context"
"encoding/json"
"log"
"sync"
"time"
"github.com/gorilla/websocket"
"github.com/grafov/bcast"
"github.com/kataras/go-events"
)
2023-11-04 10:16:48 +00:00
type Websocket struct {
sync.Mutex
clients *bcast.Group
}
var ws *Websocket
2022-11-18 21:18:12 +00:00
func init() {
log.Println("ws.go loading..")
2023-11-04 10:16:48 +00:00
ws = new(Websocket)
2022-11-18 21:18:12 +00:00
2023-11-04 10:16:48 +00:00
ws.clients = bcast.NewGroup()
go ws.clients.Broadcast(0)
2022-11-18 21:18:12 +00:00
log.Println("ws.go done.")
}
type WSmsg struct {
Event string
Payload json.RawMessage
}
2023-11-04 10:16:48 +00:00
type Event struct {
Event string `json:"event"`
Payload any `json:"payload,omitempty"`
}
func (ws *Websocket) SendEvent(e Event) {
ws.Lock()
ws.clients.Send(e)
ws.Unlock()
}
2022-11-18 21:18:12 +00:00
2023-11-04 10:16:48 +00:00
func (ws *Websocket) join(c *websocket.Conn) error {
memb := ws.clients.Join()
2022-11-18 21:18:12 +00:00
defer memb.Close()
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
go func() {
ticker := time.NewTicker(30 * time.Second)
for {
select {
case <-ctx.Done():
return
case <-ticker.C:
c.WriteControl(websocket.PingMessage, []byte{}, time.Now().Add(10*time.Second))
case msg := <-memb.Read:
c.SetWriteDeadline(time.Now().Add(10 * time.Second))
c.WriteJSON(msg)
}
}
}()
c.SetPongHandler(func(d string) error {
return nil
})
2023-11-04 10:16:48 +00:00
msg, err := app.songInfoEvent("song_info")
if err != nil {
return err
}
2022-11-18 21:18:12 +00:00
2023-11-04 10:16:48 +00:00
vol := Event{"volume", map[string]float64{
"playlist": VolumeToPercent(pl_volume.Volume),
"ambiance": VolumeToPercent(amb_volume.Volume),
2023-11-04 10:16:48 +00:00
}}
2022-12-03 18:22:05 +00:00
2022-11-18 21:18:12 +00:00
c.SetWriteDeadline(time.Now().Add(10 * time.Second))
c.WriteJSON(msg)
2022-12-03 18:22:05 +00:00
c.WriteJSON(vol)
2022-11-18 21:18:12 +00:00
if app.ambiance.Len() > 0 {
2023-11-04 10:16:48 +00:00
msg := Event{"ambiance_play", map[string]string{
"id": app.curamb.Id,
}}
2022-11-18 21:18:12 +00:00
c.WriteJSON(msg)
} else {
2023-11-04 10:16:48 +00:00
msg := Event{"ambiance_stop", nil}
2022-11-18 21:18:12 +00:00
c.WriteJSON(msg)
}
for {
var msg WSmsg
err := c.ReadJSON(&msg)
if err != nil {
return err
}
2023-11-04 10:16:48 +00:00
app.events.Emit(events.EventName(msg.Event), msg.Payload, memb)
2022-11-18 21:18:12 +00:00
}
}