-
Notifications
You must be signed in to change notification settings - Fork 1
/
serve.go
183 lines (152 loc) · 4.04 KB
/
serve.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
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
package main
import (
"encoding/json"
"fmt"
"io"
"math/rand"
"net/http"
"time"
"github.com/gorilla/mux"
"github.com/gorilla/websocket"
"github.com/prometheus/client_golang/prometheus/promhttp"
"go.uber.org/zap"
"go.uber.org/zap/zapcore"
)
var upgrader = websocket.Upgrader{
CheckOrigin: func(r *http.Request) bool { return true },
ReadBufferSize: 1024,
WriteBufferSize: 1024,
}
var logger *zap.SugaredLogger
// Handle players downloading audio
func audio(w http.ResponseWriter, r *http.Request) {
vars := mux.Vars(r)
for _, v := range queues {
if fmt.Sprint(v.Player.GetID()) == vars["id"] {
logger.Debugw("new audio request",
"player", v.Player.GetID(),
"bufLen", v.Buffer.Len(),
"bufSecs", v.Buffer.Len()/44100/2/2)
io.Copy(w, v.Buffer)
return
}
}
}
// Handle clients getting all the players
func getPlayers(w http.ResponseWriter, r *http.Request) {
// Inlining a struct seems like the simplest solution
type resp struct {
ID string `json:"id"`
Name string `json:"name"`
Type string `json:"type"`
// Thumbnail string `json:"thumbnail"`
}
var out []resp
for _, v := range queues {
out = append(out, resp{
ID: v.Player.GetID(),
Type: v.Player.GetModel(),
Name: v.Player.GetName(),
})
}
b, err := json.Marshal(out)
if err != nil {
logger.Errorw("unable to encode player information",
"err", err)
return
}
w.Write(b)
}
// Handle the websocket connection from any client
func ws(w http.ResponseWriter, r *http.Request) {
// Upgrade the connection to ws
conn, err := upgrader.Upgrade(w, r, nil)
if err != nil {
logger.Errorw("unable to upgrade connection to websocket",
"err", err)
return
}
// Add the client to our list
c := &Client{Conn: conn}
clients = append(clients, c)
metricConnectedClients.Inc()
// Set the close handler on the ws connection
conn.SetCloseHandler(func(code int, text string) error {
// Boilerplate close handler
message := websocket.FormatCloseMessage(code, "")
conn.WriteControl(websocket.CloseMessage, message, time.Now().Add(time.Second))
// Remove the client from our list
for k, v := range clients {
if v == c {
clients = append(clients[:k], clients[k+1:]...)
}
}
return nil
})
// Update the client with all player states
for _, v := range queues {
v.UpdateClients()
}
go c.Listener()
}
func loadVidID(w http.ResponseWriter, r *http.Request) {
playerID := r.URL.Query().Get("player")
videoID := r.URL.Query().Get("vid")
var queue *Queue
for _, v := range queues {
if v.Player.GetID() == playerID {
queue = v
}
}
queue.Songs = []Song{{ID: videoID, Artists: []Artist{{Name: "idk"}}}}
queue.Index = -1
queue.Next()
}
// A middleware to cope for any CORS requests
func corsMiddleware(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.Header().Add("Access-Control-Allow-Origin", "*")
if r.Method == "OPTIONS" {
w.Header().Add("Access-Control-Allow-Headers", "Content-Type")
return
}
next.ServeHTTP(w, r)
})
}
// Entrypoint
func main() {
// Seed random number generator
rand.Seed(time.Now().UTC().UnixNano())
// Load persistent data
LoadPersistent()
// Start the logger
conf := zap.NewProductionConfig()
conf.OutputPaths = append(conf.OutputPaths, persistent.LogLocations...)
conf.Level.SetLevel(zap.DebugLevel)
conf.EncoderConfig = zap.NewProductionEncoderConfig()
conf.EncoderConfig.EncodeTime = zapcore.ISO8601TimeEncoder
l, err := conf.Build()
if err != nil {
panic(err)
}
defer l.Sync()
logger = l.Sugar()
logger.Info("slimytm is starting")
// Start slimproto listeners
go udpListener()
go tcpListener()
// Start xpl
xplInit()
go xplListener()
// Start webserver
r := mux.NewRouter()
r.Use(corsMiddleware)
r.Path("/players").HandlerFunc(getPlayers)
r.Path("/player/{id}/audio.wav").HandlerFunc(audio)
r.Path("/ws").HandlerFunc(ws)
r.Path("/metrics").Handler(promhttp.Handler())
r.Path("/playID").HandlerFunc(loadVidID)
logger.Panicw("unable to start http server",
"port", 9001,
"err", http.ListenAndServe(":9001", r))
}