-
Notifications
You must be signed in to change notification settings - Fork 0
/
icecast.go
290 lines (220 loc) · 6.95 KB
/
icecast.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
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
package icecast
// ////////////////////////////////////////////////////////////////////////////////// //
// //
// Copyright (c) 2023 ESSENTIAL KAOS //
// Apache License, Version 2.0 <https://www.apache.org/licenses/LICENSE-2.0> //
// //
// ////////////////////////////////////////////////////////////////////////////////// //
import (
"encoding/base64"
"encoding/xml"
"errors"
"fmt"
"net/url"
"runtime"
"strconv"
"time"
"github.com/valyala/fasthttp"
)
// ////////////////////////////////////////////////////////////////////////////////// //
// API is Confluence API struct
type API struct {
Client *fasthttp.Client // Client is client for http requests
url string // confluence URL
basicAuth string // basic auth
}
// ////////////////////////////////////////////////////////////////////////////////// //
// API errors
var (
ErrInitEmptyURL = errors.New("URL can't be empty")
ErrInitEmptyUser = errors.New("User can't be empty")
ErrInitEmptyPassword = errors.New("Password can't be empty")
)
// ////////////////////////////////////////////////////////////////////////////////// //
// NewAPI creates new API struct
func NewAPI(url, user, password string) (*API, error) {
switch {
case url == "":
return nil, ErrInitEmptyURL
case user == "":
return nil, ErrInitEmptyUser
case password == "":
return nil, ErrInitEmptyPassword
}
return &API{
Client: &fasthttp.Client{
Name: getUserAgent("", ""),
MaxIdleConnDuration: 5 * time.Second,
ReadTimeout: 3 * time.Second,
WriteTimeout: 3 * time.Second,
MaxConnsPerHost: 150,
},
url: url,
basicAuth: genBasicAuthHeader(user, password),
}, nil
}
// ////////////////////////////////////////////////////////////////////////////////// //
// SetUserAgent set user-agent string based on app name and version
func (api *API) SetUserAgent(app, version string) {
api.Client.Name = getUserAgent(app, version)
}
// ////////////////////////////////////////////////////////////////////////////////// //
// GetStats fetches info about Icecast server
func (api *API) GetStats() (*Stats, error) {
data, err := api.doRequest("/stats")
if err != nil {
return nil, err
}
return parseStatsData(data)
}
// ListMounts fetches info about mounted sources
func (api *API) ListMounts() ([]*Mount, error) {
data, err := api.doRequest("/listmounts")
if err != nil {
return nil, err
}
return parseMountsData(data)
}
// ListClients fetches list of listeners connected to given mount point
func (api *API) ListClients(mount string) ([]*Listener, error) {
data, err := api.doRequest("/listclients?mount=" + mount)
if err != nil {
return nil, err
}
return parseClientListData(data)
}
// UpdateMeta updates meta for given mount source
func (api *API) UpdateMeta(mount string, meta TrackMeta) error {
url := "/metadata?mode=updinfo&mount=" + mount + "&" + meta.ToQuery()
data, err := api.doRequest(url)
if err != nil {
return err
}
return checkResponseData(data)
}
// UpdateFallback updates fallback for given mount source
func (api *API) UpdateFallback(mount, fallback string) error {
url := "/fallback?mount=" + mount + "&fallback=" + fallback
data, err := api.doRequest(url)
if err != nil {
return err
}
return checkResponseData(data)
}
// MoveClients moves clients from one source to another
func (api *API) MoveClients(from, to string) error {
url := "/moveclients?mount=" + from + "&destination=" + to
data, err := api.doRequest(url)
if err != nil {
return err
}
return checkResponseData(data)
}
// KillClient kills client with given ID connected to given mount point
func (api *API) KillClient(mount string, id int) error {
data, err := api.doRequest("/killclient?mount=" + mount + "&id=" + strconv.Itoa(id))
if err != nil {
return err
}
return checkResponseData(data)
}
// KillSource kills the source with given mount point
func (api *API) KillSource(mount string) error {
data, err := api.doRequest("/killsource?mount=" + mount)
if err != nil {
return err
}
return checkResponseData(data)
}
// ////////////////////////////////////////////////////////////////////////////////// //
// parseStatsData parses raw XML data with Icecast stats
func parseStatsData(data []byte) (*Stats, error) {
server := &iceStats{}
err := xml.Unmarshal(data, server)
if err != nil {
return nil, err
}
return convertStats(server), nil
}
// parseMountsData parses raw XML data with Icecast mounts info
func parseMountsData(data []byte) ([]*Mount, error) {
mounts := &iceMounts{}
err := xml.Unmarshal(data, mounts)
if err != nil {
return nil, err
}
return mounts.Mounts, nil
}
// parseClientListData parses raw XML data with Icecast listeners
func parseClientListData(data []byte) ([]*Listener, error) {
listeners := &iceListeners{}
err := xml.Unmarshal(data, listeners)
if err != nil {
return nil, err
}
return listeners.Listeners, nil
}
// checkResponseData checks default Icecast response for errors
func checkResponseData(data []byte) error {
if len(data) == 0 {
return nil
}
response := &iceResponse{}
err := xml.Unmarshal(data, response)
if err != nil {
return err
}
if response.Return == 1 {
return nil
}
return fmt.Errorf(response.Message)
}
// ////////////////////////////////////////////////////////////////////////////////// //
// codebeat:disable[ARITY]
// doRequest creates and executes request
func (api *API) doRequest(uri string) ([]byte, error) {
req := api.acquireRequest(uri)
resp := fasthttp.AcquireResponse()
defer fasthttp.ReleaseRequest(req)
defer fasthttp.ReleaseResponse(resp)
err := api.Client.Do(req, resp)
if err != nil {
return nil, err
}
statusCode := resp.StatusCode()
if statusCode != 200 {
return nil, fmt.Errorf("Server return status code %d", statusCode)
}
return resp.Body(), nil
}
// acquireRequest acquire new request with given params
func (api *API) acquireRequest(uri string) *fasthttp.Request {
req := fasthttp.AcquireRequest()
req.SetRequestURI(api.url + "/admin" + uri)
// Set auth header
req.Header.Add("Authorization", "Basic "+api.basicAuth)
return req
}
// getUserAgent generate user-agent string for client
func getUserAgent(app, version string) string {
if app != "" && version != "" {
return fmt.Sprintf(
"%s/%s %s/%s (go; %s; %s-%s)",
app, version, NAME, VERSION, runtime.Version(),
runtime.GOARCH, runtime.GOOS,
)
}
return fmt.Sprintf(
"%s/%s (go; %s; %s-%s)",
NAME, VERSION, runtime.Version(),
runtime.GOARCH, runtime.GOOS,
)
}
// genBasicAuthHeader generate basic auth header
func genBasicAuthHeader(username, password string) string {
return base64.StdEncoding.EncodeToString([]byte(username + ":" + password))
}
// esc escapes the string so it can be safely placed inside a URL query
func esc(s string) string {
return url.QueryEscape(s)
}