dndmusicbot/ws.go

103 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"
)
func init() {
log.Println("ws.go loading..")
go ws_clients.Broadcast(0)
ws_msg = make(chan interface{})
go func() {
2022-11-20 16:30:22 +00:00
var msg interface{}
2022-11-18 21:18:12 +00:00
for {
2022-11-20 16:30:22 +00:00
msg = <-ws_msg
ws_clients.Send(msg)
2022-11-18 21:18:12 +00:00
}
}()
log.Println("ws.go done.")
}
type WSmsg struct {
Event string
Payload json.RawMessage
}
var ws_clients = bcast.NewGroup()
var ws_msg chan interface{}
var WSMutex = &sync.Mutex{}
func handleWS(c *websocket.Conn) error {
memb := ws_clients.Join()
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
})
msg := app.songInfoEvent("song_info")
2022-12-03 18:22:05 +00:00
vol := make(map[string]interface{})
volout := make(map[string]float64)
vol["event"] = "volume"
volout["playlist"] = pl_volume.Volume
volout["ambiance"] = amb_volume.Volume
vol["payload"] = volout
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 {
2022-11-18 21:18:12 +00:00
msg := make(map[string]interface{})
out := make(map[string]interface{})
msg["event"] = "ambiance_play"
2022-11-25 13:06:26 +00:00
out["id"] = app.curamb.Id
2022-11-18 21:18:12 +00:00
msg["payload"] = out
c.WriteJSON(msg)
} else {
msg := make(map[string]interface{})
msg["event"] = "ambiance_stop"
c.WriteJSON(msg)
}
for {
var msg WSmsg
err := c.ReadJSON(&msg)
if err != nil {
return err
}
app.events.Emit(events.EventName(msg.Event), msg.Payload)
}
}