-
Notifications
You must be signed in to change notification settings - Fork 4
/
request.go
258 lines (218 loc) · 5.88 KB
/
request.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
package jellyfin
import (
"bytes"
"context"
"encoding/json"
"fmt"
"io"
"net/http"
"net/url"
"strconv"
"strings"
)
type params map[string]string
func (c *Client) defaultParams() params {
params := params{}
params["UserId"] = c.userID
params["DeviceId"] = c.ensureDeviceID()
return params
}
func (p params) setSorting(sort Sort) {
field := "SortName"
order := "Ascending"
if sort.Mode == SortAsc {
order = "Ascending"
} else if sort.Mode == SortDesc {
order = "Descending"
}
if sort.Field != "" {
field = string(sort.Field)
}
p["SortBy"] = field
p["SortOrder"] = order
}
func (p params) setPaging(paging Paging) {
if paging.Limit > 0 {
p["Limit"] = strconv.Itoa(paging.Limit)
}
p["StartIndex"] = strconv.Itoa(paging.StartIndex)
}
func (p params) setLimit(n int) {
p["Limit"] = strconv.Itoa(n)
}
func (p params) setIncludeTypes(itemType mediaItemType) {
p["IncludeItemTypes"] = string(itemType)
}
func (p params) setIncludeFields(fields ...string) {
p["Fields"] = strings.Join(fields, ",")
}
func (p params) enableRecursive() {
p["Recursive"] = "true"
}
func (p params) setFilter(tItem mediaItemType, filter Filter) {
f := ""
if filter.Favorite {
f = appendFilter(f, "IsFavorite", ",")
}
// jellyfin server does not seem to like sorting artists by play status.
// https://github.com/jellyfin/jellyfin/issues/2672
if tItem != mediaTypeArtist {
if filter.FilterPlayed == FilterIsPlayed {
f = appendFilter(f, "IsPlayed", ",")
} else if filter.FilterPlayed == FilterIsNotPlayed {
f = appendFilter(f, "IsUnPlayed", ",")
}
}
if tItem != mediaTypeArtist {
if filter.yearRangeValid() && filter.YearRange[0] > 0 {
years := ""
totalYears := filter.YearRange[1] - filter.YearRange[0]
if totalYears == 0 {
years = strconv.Itoa(filter.YearRange[0])
} else {
var sb strings.Builder
for i := 0; i < totalYears+1; i++ {
if i > 0 {
sb.WriteString(",")
}
year := filter.YearRange[0] + i
sb.WriteString(strconv.Itoa(year))
}
years = sb.String()
}
p["Years"] = years
}
}
if len(filter.Genres) > 0 {
p["Genres"] = strings.Join(filter.Genres, "|")
}
if f != "" {
p["Filters"] = f
}
if filter.ArtistID != "" {
p["ArtistIds"] = filter.ArtistID
}
if filter.ParentID != "" {
p["ParentId"] = filter.ParentID
}
}
func appendFilter(old, new string, separator string) string {
if old == "" {
return new
}
return old + separator + new
}
func (c *Client) get(url string, params params) (io.ReadCloser, error) {
resp, err := c.makeDo(context.Background(), http.MethodGet, url, nil, params, nil)
if resp != nil {
return resp.Body, err
}
return nil, err
}
func (c *Client) delete(url string, params params) (io.ReadCloser, error) {
resp, err := c.makeDo(context.Background(), http.MethodDelete, url, nil, params, nil)
if resp != nil {
return resp.Body, err
}
return nil, err
}
func (c *Client) post(url string, params params, body any) (io.ReadCloser, error) {
bodyEnc, err := json.Marshal(body)
if err != nil {
return nil, fmt.Errorf("marshal POST body: %v", err)
}
resp, err := c.makeDo(context.Background(), http.MethodPost, url, bodyEnc, params, nil)
if resp != nil {
return resp.Body, err
}
return nil, err
}
func (c *Client) encodeGETUrl(endpoint string, params params) (string, error) {
u, err := url.JoinPath(c.BaseURL().String(), endpoint)
if err != nil {
return "", fmt.Errorf("unable to parse url path: %w", err)
}
uri, err := url.Parse(u)
if err != nil {
return "", err
}
q := url.Values{}
for key, val := range params {
q.Add(key, val)
}
uri.RawQuery = q.Encode()
return uri.String(), nil
}
// makeDo constructs request and performs Do.
// Set authorization header and build url query.
// Make request, parse response code and raise error if needed. Else return response body
func (c *Client) makeDo(ctx context.Context, method, path string, body []byte, params params, headers map[string]string) (*http.Response, error) {
var req *http.Request
var err error
u, err := url.JoinPath(c.BaseURL().String(), path)
if err != nil {
return nil, fmt.Errorf("unable to parse url path: %w", err)
}
// generate http.Request
if body != nil {
req, err = http.NewRequestWithContext(ctx, method, u, bytes.NewBuffer(body))
} else {
req, err = http.NewRequestWithContext(ctx, method, u, nil)
}
if err != nil {
return nil, fmt.Errorf("failed to create request: %w", err)
}
// set headers
if method == http.MethodPost {
req.Header.Set("Content-Type", "application/json")
}
req.Header.Set("X-Emby-Token", c.token)
for k, v := range headers {
req.Header.Set(k, v)
}
// set params
if params != nil {
q := req.URL.Query()
for i, v := range params {
q.Add(i, v)
}
req.URL.RawQuery = q.Encode()
}
// DO
//start := time.Now()
resp, err := c.HTTPClient.Do(req)
if err != nil {
return nil, fmt.Errorf("failed to do request: %w", err)
}
//took := time.Since(start)
//logrus.Debugf("%s %s: %d (%d ms)", req.Method, req.URL.Path, resp.StatusCode, took.Milliseconds())
// check response for errors and return the response
return checkResponse(resp)
}
// checkResponse determines if there is was an error returned by jellyfin.
func checkResponse(resp *http.Response) (*http.Response, error) {
// 200 or 204 is all good
if resp.StatusCode == http.StatusOK || resp.StatusCode == http.StatusNoContent {
return resp, nil
}
// read in the body and look for an error message
bytes, _ := io.ReadAll(resp.Body)
msg := "no body"
if len(bytes) > 0 {
msg = string(bytes)
}
errMsg := errUnexpectedStatusCode
switch resp.StatusCode {
case http.StatusBadRequest:
errMsg = errInvalidRequest
case http.StatusUnauthorized:
errMsg = errUnauthorized
case http.StatusForbidden:
errMsg = errForbidden
case http.StatusNotFound:
errMsg = errNotFound
case http.StatusInternalServerError:
errMsg = errServerError
}
return resp, fmt.Errorf("%s, code: %s, msg: %s", errMsg, resp.Status, msg)
}