forked from maddyblue/moggio
/
websocket.go
116 lines (107 loc) · 2.25 KB
/
websocket.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
package server
import (
"fmt"
"os"
"github.com/mjibson/moggio/codec"
"github.com/mjibson/moggio/protocol"
"golang.org/x/net/websocket"
)
type waitData struct {
Type waitType
Data interface{}
}
type waitType string
const (
waitStatus waitType = "status"
waitPlaylist = "playlist"
waitProtocols = "protocols"
waitTracks = "tracks"
waitError = "error"
)
// makeWaitData should only be called by the commands() function.
func (srv *Server) makeWaitData(wt waitType) *waitData {
var data interface{}
switch wt {
case waitProtocols:
protos := make(map[string][]string)
for p, m := range srv.Protocols {
for key := range m {
protos[p] = append(protos[p], key)
}
}
data = struct {
Available map[string]protocol.Params
Current map[string][]string
InProgress map[codec.ID]bool
}{
protocol.Get(),
protos,
srv.inprogress,
}
case waitStatus:
hostname, _ := os.Hostname()
data = &Status{
State: srv.state,
Song: srv.songID,
SongInfo: srv.info,
Elapsed: srv.elapsed,
Time: srv.info.Time,
Random: srv.Random,
Repeat: srv.Repeat,
Username: srv.Username,
Hostname: hostname,
CentralURL: srv.centralURL,
}
case waitTracks:
var songs []listItem
for name, protos := range srv.Protocols {
for key, inst := range protos {
sl, _ := inst.List()
for id, info := range sl {
sid := SongID(codec.NewID(name, key, string(id)))
songs = append(songs, listItem{
ID: sid,
Info: info,
})
}
}
}
data = struct {
Tracks []listItem
}{
Tracks: songs,
}
case waitPlaylist:
d := struct {
Queue PlaylistInfo
Playlists map[string]PlaylistInfo
}{
Queue: srv.playlistInfo(srv.Queue),
Playlists: make(map[string]PlaylistInfo),
}
for name, p := range srv.Playlists {
d.Playlists[name] = srv.playlistInfo(p)
}
data = d
default:
data = fmt.Errorf("unknown type")
}
return &waitData{
Type: wt,
Data: data,
}
}
type cmdNewWS struct {
ws *websocket.Conn
done chan struct{}
}
type cmdDeleteWS *websocket.Conn
func (srv *Server) WebSocket(ws *websocket.Conn) {
c := make(chan struct{})
srv.ch <- cmdNewWS{
ws: ws,
done: c,
}
for range c {
}
}