-
Notifications
You must be signed in to change notification settings - Fork 20
Expand file tree
/
Copy pathclient.go
More file actions
309 lines (262 loc) · 7.78 KB
/
Copy pathclient.go
File metadata and controls
309 lines (262 loc) · 7.78 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
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
package appie
import (
"bytes"
"context"
"encoding/json"
"fmt"
"io"
"log"
"net/http"
"os"
"path/filepath"
"strings"
"sync"
"time"
)
const (
defaultBaseURL = "https://api.ah.nl"
defaultUserAgent = "Appie/9.28 (iPhone17,3; iPhone; CPU OS 26_1 like Mac OS X)"
defaultClientID = "appie-ios"
defaultClientVersion = "9.28"
)
// Client is the AH API client. It handles authentication, token management,
// and provides methods to interact with products, orders, shopping lists, and more.
//
// Client is safe for concurrent use. Token state is protected by a mutex.
type Client struct {
httpClient *http.Client
baseURL string
userAgent string
clientID string
clientVersion string
mu sync.RWMutex
accessToken string
refreshToken string
memberID string
expiresAt time.Time
orderID string // sent as appie-current-order-id header, mirroring the iOS app; the API may use this (not server-side state) to determine the active order
orderHash string
configPath string
loginBaseURL string // overridable for testing; defaults to "https://login.ah.nl"
openBrowser func(string) // overridable for testing; nil uses default
logger *log.Logger
}
// Option configures the client. Use With* functions to create options.
type Option func(*Client)
// WithHTTPClient sets a custom HTTP client.
func WithHTTPClient(hc *http.Client) Option {
return func(c *Client) {
c.httpClient = hc
}
}
// WithBaseURL sets a custom base URL.
func WithBaseURL(url string) Option {
return func(c *Client) {
c.baseURL = url
}
}
// WithTokens sets the access and refresh tokens.
func WithTokens(accessToken, refreshToken string) Option {
return func(c *Client) {
c.accessToken = accessToken
c.refreshToken = refreshToken
}
}
// WithLogger sets a logger for verbose request logging.
func WithLogger(l *log.Logger) Option {
return func(c *Client) {
c.logger = l
}
}
// WithConfigPath sets the path to the config file.
func WithConfigPath(path string) Option {
return func(c *Client) {
c.configPath = path
}
}
// New creates a new AH API client.
func New(opts ...Option) *Client {
c := &Client{
httpClient: http.DefaultClient,
baseURL: defaultBaseURL,
userAgent: defaultUserAgent,
clientID: defaultClientID,
clientVersion: defaultClientVersion,
logger: log.New(io.Discard, "", 0),
}
for _, opt := range opts {
opt(c)
}
return c
}
// DefaultConfigPath returns the standard XDG config path for the appie config
// file ($XDG_CONFIG_HOME/appie/config.json, falling back to ~/.config/appie/config.json).
// If the user's home directory cannot be determined it returns ".appie.json" in cwd.
func DefaultConfigPath() string {
dir := os.Getenv("XDG_CONFIG_HOME")
if dir == "" {
home, err := os.UserHomeDir()
if err != nil {
return ".appie.json"
}
dir = filepath.Join(home, ".config")
}
return filepath.Join(dir, "appie", "config.json")
}
// NewWithConfig creates a new client and loads config from the given path.
func NewWithConfig(configPath string, opts ...Option) (*Client, error) {
c := New(append([]Option{WithConfigPath(configPath)}, opts...)...)
if err := c.loadConfig(); err != nil {
if os.IsNotExist(err) {
return c, nil // Config doesn't exist yet, that's OK
}
return nil, err
}
return c, nil
}
// loadConfig loads the configuration from the config file.
func (c *Client) loadConfig() error {
if c.configPath == "" {
return fmt.Errorf("no config path set")
}
data, err := os.ReadFile(c.configPath)
if err != nil {
return err
}
var cfg config
if err := json.Unmarshal(data, &cfg); err != nil {
return fmt.Errorf("failed to parse config: %w", err)
}
c.mu.Lock()
c.accessToken = cfg.AccessToken
c.refreshToken = cfg.RefreshToken
c.memberID = cfg.MemberID
c.expiresAt = cfg.ExpiresAt
c.mu.Unlock()
return nil
}
// saveConfig saves the current configuration to the config file.
func (c *Client) saveConfig() error {
if c.configPath == "" {
return fmt.Errorf("no config path set")
}
c.mu.RLock()
cfg := config{
AccessToken: c.accessToken,
RefreshToken: c.refreshToken,
MemberID: c.memberID,
ExpiresAt: c.expiresAt,
}
c.mu.RUnlock()
data, err := json.MarshalIndent(cfg, "", " ")
if err != nil {
return err
}
return os.WriteFile(c.configPath, data, 0600)
}
// IsAuthenticated returns true if the client has an access token.
func (c *Client) IsAuthenticated() bool {
c.mu.RLock()
defer c.mu.RUnlock()
return c.accessToken != ""
}
// setHeaders sets the common headers for API requests.
func (c *Client) setHeaders(req *http.Request) {
req.Header.Set("User-Agent", c.userAgent)
req.Header.Set("x-client-name", c.clientID)
req.Header.Set("x-client-version", c.clientVersion)
req.Header.Set("x-application", "AHWEBSHOP")
req.Header.Set("Accept", "application/json")
req.Header.Set("Content-Type", "application/json")
c.mu.RLock()
if c.accessToken != "" {
req.Header.Set("Authorization", "Bearer "+c.accessToken)
}
if c.orderID != "" {
req.Header.Set("appie-current-order-id", c.orderID)
if c.orderHash != "" {
req.Header.Set("appie-current-order-hash", c.orderHash)
}
}
c.mu.RUnlock()
}
// ensureFreshToken refreshes the access token if it has expired and a refresh token is available.
// Auth endpoints are excluded to avoid infinite loops.
func (c *Client) ensureFreshToken(ctx context.Context, path string) {
// Don't auto-refresh for auth endpoints
if strings.HasPrefix(path, "/mobile-auth/") {
return
}
c.mu.RLock()
expired := !c.expiresAt.IsZero() && time.Now().After(c.expiresAt)
hasRefresh := c.refreshToken != ""
c.mu.RUnlock()
if expired && hasRefresh {
// Best-effort refresh; if it fails, the original request will proceed
// with the expired token and the API will return an appropriate error.
if err := c.refreshAccessToken(ctx); err == nil {
_ = c.saveConfig()
}
}
}
// DoRequest performs an HTTP request and decodes the response.
func (c *Client) DoRequest(ctx context.Context, method, path string, body, result any) error {
c.ensureFreshToken(ctx, path)
var bodyReader io.Reader
if body != nil {
data, err := json.Marshal(body)
if err != nil {
return fmt.Errorf("failed to marshal request body: %w", err)
}
bodyReader = bytes.NewReader(data)
}
req, err := http.NewRequestWithContext(ctx, method, c.baseURL+path, bodyReader)
if err != nil {
return fmt.Errorf("failed to create request: %w", err)
}
c.setHeaders(req)
start := time.Now()
resp, err := c.httpClient.Do(req)
if err != nil {
return fmt.Errorf("request failed: %w", err)
}
defer resp.Body.Close()
c.logger.Printf("%s %s %d %s", method, path, resp.StatusCode, time.Since(start).Truncate(time.Millisecond))
respBody, err := io.ReadAll(resp.Body)
if err != nil {
return fmt.Errorf("failed to read response: %w", err)
}
if resp.StatusCode >= 400 {
var apiErr apiError
if json.Unmarshal(respBody, &apiErr) == nil && (apiErr.Code != "" || apiErr.Message != "") {
return &apiErr
}
return fmt.Errorf("API error: %d %s", resp.StatusCode, string(respBody))
}
if result != nil && len(respBody) > 0 {
if err := json.Unmarshal(respBody, result); err != nil {
return fmt.Errorf("failed to decode response: %w", err)
}
}
return nil
}
// DoGraphQL performs a GraphQL request.
func (c *Client) DoGraphQL(ctx context.Context, query string, variables map[string]any, result any) error {
req := graphQLRequest{
Query: query,
Variables: variables,
}
var resp graphQLResponse[json.RawMessage]
if err := c.DoRequest(ctx, http.MethodPost, "/graphql", req, &resp); err != nil {
return err
}
if len(resp.Errors) > 0 {
return fmt.Errorf("graphql error: %s", resp.Errors[0].Message)
}
if result != nil {
if err := json.Unmarshal(resp.Data, result); err != nil {
return fmt.Errorf("failed to decode graphql response: %w", err)
}
}
return nil
}