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")
|
|
|
|
|
|
|
|
c.SetWriteDeadline(time.Now().Add(10 * time.Second))
|
|
|
|
c.WriteJSON(msg)
|
|
|
|
|
2022-11-19 16:37:49 +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"
|
|
|
|
out["type"] = app.curamb
|
|
|
|
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)
|
|
|
|
}
|
|
|
|
}
|