Repository navigation
Expand file tree
/
Copy pathcontext.go
More file actions
229 lines (203 loc) · 6.56 KB
/
Copy pathcontext.go
File metadata and controls
229 lines (203 loc) · 6.56 KB
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
package main
import (
"errors"
"net/http"
"net/url"
"strconv"
"strings"
"time"
"github.com/datahearth/streamline/extensions/sdk"
"github.com/streamline-hq/streamline-subsonic-ext/envelope"
"github.com/streamline-hq/streamline-subsonic-ext/ids"
)
// reqCtx is what a /rest handler works with: the request, its parameters
// (query string and form body merged, as a Subsonic client may send either)
// and the authenticated account.
type reqCtx struct {
req sdk.Request
params url.Values
// user is the authenticated account; nil only while authenticating.
user *account
// xmlErrors answers a failure as XML whatever f says: a binary endpoint
// (stream, getCoverArt, ...) reports its errors as an XML document.
xmlErrors bool
}
// handler answers one /rest endpoint.
type handler func(c *reqCtx) sdk.Response
// decorator fills per-listener facts (star, rating, play count) into a body
// before respond sends it.
type decorator func(c *reqCtx, b *body) error
var decorators []decorator
// registerDecorator is called from an init; decorators run in registration
// order.
func registerDecorator(d decorator) { decorators = append(decorators, d) }
// newReqCtx parses the parameters. A POST form body is merged ahead of the
// query string, so a body value wins, as clients such as DSub and Symfonium
// that send the form in the body expect.
func newReqCtx(req sdk.Request) (*reqCtx, error) {
params := url.Values{}
if mediaType(
headerValue(req, "Content-Type"),
) == "application/x-www-form-urlencoded" &&
(req.Method == http.MethodPost || req.Method == http.MethodPut ||
req.Method == http.MethodPatch) {
form, err := url.ParseQuery(string(req.Body))
if err != nil {
return nil, err
}
for k, vs := range form {
params[k] = append(params[k], vs...)
}
}
query, err := url.ParseQuery(req.Query)
if err != nil {
return nil, err
}
for k, vs := range query {
params[k] = append(params[k], vs...)
}
return &reqCtx{req: req, params: params}, nil
}
func mediaType(contentType string) string {
mt, _, _ := strings.Cut(contentType, ";")
return strings.ToLower(strings.TrimSpace(mt))
}
// headerValue is the first value of a request header, whatever its case.
func headerValue(req sdk.Request, name string) string {
for k, vs := range req.Headers {
if strings.EqualFold(k, name) && len(vs) > 0 {
return vs[0]
}
}
return ""
}
// param is the first value of a parameter, "" when absent.
func (c *reqCtx) param(name string) string { return c.params.Get(name) }
// multi is every value of a repeated parameter (id, songId, ...).
func (c *reqCtx) multi(name string) []string { return c.params[name] }
// intParam reads an integer parameter clamped to [lo, hi]; an absent or
// unreadable one is def.
func (c *reqCtx) intParam(name string, def, lo, hi int) int {
n, err := strconv.Atoi(c.param(name))
if err != nil {
return def
}
return min(max(n, lo), hi)
}
// boolParam reads a Subsonic boolean; absent or unreadable is def.
func (c *reqCtx) boolParam(name string, def bool) bool {
b, err := strconv.ParseBool(c.param(name))
if err != nil {
return def
}
return b
}
// millisParam reads an epoch-milliseconds parameter. present reports whether
// it was sent at all; a value that is not a number counts as not sent.
func (c *reqCtx) millisParam(name string) (t time.Time, present bool) {
raw := c.param(name)
if raw == "" {
return time.Time{}, false
}
ms, err := strconv.ParseInt(strings.TrimSpace(raw), 10, 64)
if err != nil {
return time.Time{}, false
}
return time.UnixMilli(ms), true
}
// anyIDParam reads the named id parameter whatever kind it holds: error 10
// when absent, error 70 when malformed.
func (c *reqCtx) anyIDParam(name string) (kind string, id uint32, err error) {
raw := c.param(name)
if raw == "" {
return "", 0, envelope.MissingParam(name)
}
kind, id, parseErr := ids.Parse(raw)
if parseErr != nil {
return "", 0, envelope.NotFound()
}
return kind, id, nil
}
// idParam reads the named id parameter and requires it to be of wantKind:
// error 70 for any other kind, as for a row that does not exist.
func (c *reqCtx) idParam(name, wantKind string) (uint32, error) {
kind, id, err := c.anyIDParam(name)
if err != nil {
return 0, err
}
if kind != wantKind {
return 0, envelope.NotFound()
}
return id, nil
}
// require refuses the call with error 50 unless the account holds p.
func (c *reqCtx) require(p permission) error {
if !c.user.allowed(p) {
return envelope.NotAuthorized()
}
return nil
}
// ok answers a successful call; a nil body is the empty response.
func (c *reqCtx) ok(b *body) sdk.Response {
if b == nil {
b = &body{}
}
return c.write(
response{Status: envelope.StatusOK, body: *b},
)
}
// respond decorates b with the caller's own facts, then answers.
func (c *reqCtx) respond(b *body) sdk.Response {
for _, d := range decorators {
if err := d(c, b); err != nil {
return c.failErr(err)
}
}
return c.ok(b)
}
// fail answers a failed call. Subsonic reports it in a 200.
func (c *reqCtx) fail(code int, msg string) sdk.Response {
return c.failWith(&envelope.Error{Code: code, Message: msg})
}
func (c *reqCtx) failWith(apiErr *envelope.Error) sdk.Response {
return c.write(response{Status: envelope.StatusFailed, Error: apiErr})
}
// failErr answers a handler's error: an *envelope.Error as itself, anything
// else as a logged "Internal error", never its text.
func (c *reqCtx) failErr(err error) sdk.Response {
if apiErr, ok := errors.AsType[*envelope.Error](err); ok {
return c.failWith(apiErr)
}
sdk.Log("error", "subsonic request failed", "error", err.Error())
return c.fail(envelope.CodeGeneric, "Internal error")
}
// write encodes resp in the format f names: JSONP once serveREST checked its
// callback, and always XML for a binary endpoint's error.
func (c *reqCtx) write(resp response) sdk.Response {
format := c.param("f")
if c.xmlErrors && resp.Status == envelope.StatusFailed {
format = ""
}
contentType, out, err := envelope.Encode(
format, c.param("callback"), version, &resp,
)
if err != nil {
sdk.Log("error", "encoding a subsonic response failed", "error", err.Error())
return textResponse(http.StatusInternalServerError, "internal error")
}
return sdk.Response{
Status: http.StatusOK,
Headers: map[string][]string{"Content-Type": {contentType}},
Body: out,
}
}
func textResponse(status int, msg string) sdk.Response {
return sdk.Response{
Status: status,
Headers: map[string][]string{"Content-Type": {"text/plain; charset=utf-8"}},
Body: []byte(msg + "\n"),
}
}
func notFoundResponse() sdk.Response {
return textResponse(http.StatusNotFound, "404 page not found")
}