103 lines
1.9 KiB
Go
103 lines
1.9 KiB
Go
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() {
|
|
var msg interface{}
|
|
for {
|
|
msg = <-ws_msg
|
|
ws_clients.Send(msg)
|
|
}
|
|
}()
|
|
|
|
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 := songInfoEvent("song_info")
|
|
|
|
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
|
|
|
|
c.SetWriteDeadline(time.Now().Add(10 * time.Second))
|
|
c.WriteJSON(msg)
|
|
c.WriteJSON(vol)
|
|
|
|
if amb_mixer.Len() > 0 {
|
|
msg := make(map[string]interface{})
|
|
out := make(map[string]interface{})
|
|
msg["event"] = "ambiance_play"
|
|
out["id"] = amb_curr.Id
|
|
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
|
|
}
|
|
|
|
ev.Emit(events.EventName(msg.Event), msg.Payload)
|
|
}
|
|
}
|