forked from vavallee/bindery
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathclient.go
More file actions
293 lines (267 loc) · 7.18 KB
/
Copy pathclient.go
File metadata and controls
293 lines (267 loc) · 7.18 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
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
291
292
293
// Package abs provides Audiobookshelf client, normalization, and import logic.
package abs
import (
"context"
"encoding/json"
"errors"
"fmt"
"io"
"net"
"net/http"
"net/url"
"strings"
"time"
"github.com/vavallee/bindery/internal/useragent"
)
const (
defaultTimeout = 10 * time.Second
maxAttempts = 3
)
type APIError struct {
StatusCode int
Message string
}
func (e *APIError) Error() string {
if e.Message == "" {
return fmt.Sprintf("abs api error (%d)", e.StatusCode)
}
return e.Message
}
func NormalizeBaseURL(raw string) (string, error) {
raw = strings.TrimSpace(raw)
if raw == "" {
return "", errors.New("base_url is required")
}
u, err := url.Parse(raw)
if err != nil {
return "", fmt.Errorf("base_url %q: %w", raw, err)
}
if u.Scheme != "http" && u.Scheme != "https" {
return "", fmt.Errorf("base_url %q must use http or https", raw)
}
if u.Host == "" {
return "", fmt.Errorf("base_url %q is missing a host", raw)
}
u.RawQuery = ""
u.Fragment = ""
if u.Path != "/" {
u.Path = strings.TrimRight(u.Path, "/")
} else {
u.Path = ""
}
return u.String(), nil
}
func NormalizeAPIKey(raw string) (string, error) {
key := strings.TrimSpace(raw)
for _, r := range key {
if r < 0x20 || r == 0x7f {
return "", errors.New("api_key contains invalid control characters")
}
}
return key, nil
}
// UserAgent delegates to the shared canonical helper so abs traffic carries
// the same identity as the rest of Bindery's outbound HTTP.
func UserAgent(version string) string {
return useragent.Build(version)
}
type Client struct {
baseURL string
apiKey string
httpClient *http.Client
userAgent string
}
func NewClient(baseURL, apiKey string) (*Client, error) {
normalized, err := NormalizeBaseURL(baseURL)
if err != nil {
return nil, err
}
normalizedKey, err := NormalizeAPIKey(apiKey)
if err != nil {
return nil, err
}
if normalizedKey == "" {
return nil, errors.New("api_key is required")
}
return &Client{
baseURL: normalized,
apiKey: normalizedKey,
httpClient: &http.Client{
Timeout: defaultTimeout,
},
userAgent: useragent.Get(),
}, nil
}
func (c *Client) WithVersion(version string) *Client {
c.userAgent = UserAgent(version)
return c
}
func (c *Client) WithUserAgent(userAgent string) *Client {
userAgent = strings.TrimSpace(userAgent)
if userAgent == "" {
userAgent = useragent.Get()
}
c.userAgent = userAgent
return c
}
func (c *Client) Authorize(ctx context.Context) (*AuthorizeResponse, error) {
var out AuthorizeResponse
if err := c.doJSON(ctx, http.MethodPost, "/api/authorize", nil, &out); err != nil {
return nil, err
}
return &out, nil
}
func (c *Client) ListLibraries(ctx context.Context) ([]Library, error) {
var out librariesResponse
if err := c.doJSON(ctx, http.MethodGet, "/api/libraries", nil, &out); err != nil {
return nil, err
}
return out.Libraries, nil
}
func (c *Client) GetLibrary(ctx context.Context, id string) (*Library, error) {
id = strings.TrimSpace(id)
if id == "" {
return nil, errors.New("library_id is required")
}
var out Library
if err := c.doJSON(ctx, http.MethodGet, "/api/libraries/"+url.PathEscape(id), nil, &out); err != nil {
return nil, err
}
return &out, nil
}
func (c *Client) ListLibraryItems(ctx context.Context, libraryID string, page, limit int) (*LibraryItemsPage, error) {
libraryID = strings.TrimSpace(libraryID)
if libraryID == "" {
return nil, errors.New("library_id is required")
}
values := url.Values{}
if limit > 0 {
values.Set("limit", fmt.Sprintf("%d", limit))
}
if page >= 0 {
values.Set("page", fmt.Sprintf("%d", page))
}
values.Set("minified", "1")
var out LibraryItemsPage
if err := c.doJSON(ctx, http.MethodGet, "/api/libraries/"+url.PathEscape(libraryID)+"/items?"+values.Encode(), nil, &out); err != nil {
return nil, err
}
return &out, nil
}
// ScanLibrary triggers an ABS library folder scan. ABS will walk all folders
// configured for the library and surface any newly-added items. This is called
// after a successful audiobook import so the item appears in ABS promptly
// rather than waiting for the next scheduled scan (Bug #10).
func (c *Client) ScanLibrary(ctx context.Context, libraryID string) error {
libraryID = strings.TrimSpace(libraryID)
if libraryID == "" {
return errors.New("library_id is required")
}
return c.doJSON(ctx, http.MethodPost, "/api/libraries/"+url.PathEscape(libraryID)+"/scan", nil, nil)
}
func (c *Client) GetLibraryItem(ctx context.Context, id string) (*LibraryItem, error) {
id = strings.TrimSpace(id)
if id == "" {
return nil, errors.New("item_id is required")
}
values := url.Values{}
values.Set("expanded", "1")
values.Set("include", "authors")
var out LibraryItem
if err := c.doJSON(ctx, http.MethodGet, "/api/items/"+url.PathEscape(id)+"?"+values.Encode(), nil, &out); err != nil {
return nil, err
}
return &out, nil
}
func (c *Client) doJSON(ctx context.Context, method, path string, body io.Reader, out any) error {
var lastErr error
for attempt := 0; attempt < maxAttempts; attempt++ {
req, err := http.NewRequestWithContext(ctx, method, c.baseURL+path, body)
if err != nil {
return err
}
req.Header.Set("Authorization", "Bearer "+c.apiKey)
req.Header.Set("Accept", "application/json")
req.Header.Set("User-Agent", c.userAgent)
if body != nil {
req.Header.Set("Content-Type", "application/json")
}
resp, err := c.httpClient.Do(req)
if err != nil {
lastErr = err
if attempt < maxAttempts-1 && shouldRetry(err) {
sleepBackoff(ctx, attempt)
continue
}
return err
}
if resp.StatusCode >= http.StatusInternalServerError && attempt < maxAttempts-1 {
drainAndClose(resp.Body)
sleepBackoff(ctx, attempt)
continue
}
if resp.StatusCode < http.StatusOK || resp.StatusCode >= http.StatusMultipleChoices {
err := decodeAPIError(resp)
_ = resp.Body.Close()
return err
}
if out == nil {
_ = resp.Body.Close()
return nil
}
if err := json.NewDecoder(resp.Body).Decode(out); err != nil {
_ = resp.Body.Close()
return fmt.Errorf("decode %s %s response: %w", method, path, err)
}
_ = resp.Body.Close()
return nil
}
return lastErr
}
func decodeAPIError(resp *http.Response) error {
body, _ := io.ReadAll(io.LimitReader(resp.Body, 8<<10))
message := strings.TrimSpace(string(body))
if message != "" {
var payload map[string]any
if err := json.Unmarshal(body, &payload); err == nil {
if s, ok := payload["error"].(string); ok && s != "" {
message = s
} else if s, ok := payload["message"].(string); ok && s != "" {
message = s
}
}
}
if message == "" {
message = resp.Status
}
return &APIError{StatusCode: resp.StatusCode, Message: message}
}
func sleepBackoff(ctx context.Context, attempt int) {
delay := 150 * time.Millisecond
for i := 0; i < attempt; i++ {
delay *= 2
}
timer := time.NewTimer(delay)
defer timer.Stop()
select {
case <-ctx.Done():
case <-timer.C:
}
}
func shouldRetry(err error) bool {
if errors.Is(err, context.Canceled) || errors.Is(err, context.DeadlineExceeded) {
return false
}
var netErr net.Error
if errors.As(err, &netErr) {
return netErr.Timeout()
}
return false
}
func drainAndClose(rc io.ReadCloser) {
if rc == nil {
return
}
_, _ = io.Copy(io.Discard, rc)
_ = rc.Close()
}