1// SPDX-FileCopyrightText: Amolith <amolith@secluded.site>
2//
3// SPDX-License-Identifier: LicenseRef-MutuaL-1.2
4
5// Package cooked calls the Cooked customer API.
6package cooked
7
8import (
9 "bytes"
10 "context"
11 "encoding/json"
12 "errors"
13 "fmt"
14 "io"
15 "net/http"
16 "net/http/cookiejar"
17 "net/url"
18 "strings"
19 "sync"
20 "time"
21
22 "golang.org/x/net/publicsuffix"
23)
24
25const maxResponseBytes = 1 << 20
26
27// Client is an authenticated Cooked API client.
28type Client struct {
29 baseURL *url.URL
30 username string
31 password string
32 http *http.Client
33
34 requestMu sync.Mutex
35 authenticatedUsername string
36}
37
38// ShoppingList is the authenticated user's Cooked shopping list.
39type ShoppingList struct {
40 Aisles []Aisle `json:"aisles"`
41 Recipes []string `json:"recipes"`
42}
43
44// Aisle groups shopping-list product groups.
45type Aisle struct {
46 ID string `json:"aisle-id"`
47 Name string `json:"aisle-name"`
48 ProductGroups []ProductGroup `json:"product-groups"`
49}
50
51// ProductGroup is an item on the shopping list.
52type ProductGroup struct {
53 ID string `json:"id"`
54 Name string `json:"name"`
55 Quantity string `json:"quantity"`
56 Selected bool `json:"selected"`
57}
58
59// RecipeCard is a saved recipe summary returned by Cooked list and search endpoints.
60type RecipeCard struct {
61 ID string `json:"id"`
62 Title string `json:"title"`
63 ThumbnailURL string `json:"thumbnail-url,omitempty"`
64}
65
66// RecipeMetadata is metadata for a Cooked recipe.
67type RecipeMetadata struct {
68 Title string `json:"title"`
69 ImageURLs []string `json:"image-urls"`
70 Owner string `json:"owner"`
71 EditPermission bool `json:"edit-permission"`
72}
73
74// RecipeContent is the Markdown-style body and portions for a Cooked recipe.
75type RecipeContent struct {
76 Content string `json:"content"`
77 Portions int `json:"portions"`
78}
79
80// NewClient returns a Cooked client with an in-memory cookie jar.
81func NewClient(baseURL *url.URL, username, password string) (*Client, error) {
82 jar, err := newCookieJar()
83 if err != nil {
84 return nil, fmt.Errorf("create cookie jar: %w", err)
85 }
86
87 return &Client{
88 baseURL: baseURL,
89 username: username,
90 password: password,
91 http: &http.Client{
92 Jar: jar,
93 Timeout: 30 * time.Second,
94 },
95 }, nil
96}
97
98// ReadShoppingList logs in when needed and returns the authenticated user's shopping list.
99func (c *Client) ReadShoppingList(ctx context.Context) (ShoppingList, error) {
100 var response shoppingListResponse
101 decodeShoppingList := func(decoder *json.Decoder) error {
102 return decoder.Decode(&response)
103 }
104 if err := c.doAuthenticated(ctx, http.MethodGet, "/api/user/{username}/shopping-list", nil, decodeShoppingList); err != nil {
105 return ShoppingList{}, err
106 }
107
108 response.ShoppingList.Recipes = response.Recipes
109 return response.ShoppingList, nil
110}
111
112// ListRecipes logs in when needed and returns one page of saved recipes.
113func (c *Client) ListRecipes(ctx context.Context, page, limit int) ([]RecipeCard, error) {
114 query := url.Values{}
115 query.Set("page", fmt.Sprintf("%d", page))
116 query.Set("page-count", fmt.Sprintf("%d", limit))
117
118 return c.getRecipes(ctx, "/api/user/{username}/recipes?"+query.Encode())
119}
120
121// SearchRecipes logs in when needed and searches the authenticated user's saved recipes.
122func (c *Client) SearchRecipes(ctx context.Context, queryText string, page int) ([]RecipeCard, error) {
123 query := url.Values{}
124 query.Set("q", queryText)
125 query.Set("page", fmt.Sprintf("%d", page))
126
127 return c.getRecipes(ctx, "/api/user/{username}/recipes/search?"+query.Encode())
128}
129
130// ReadRecipeMetadata logs in when needed and returns recipe metadata.
131func (c *Client) ReadRecipeMetadata(ctx context.Context, recipeID string) (RecipeMetadata, error) {
132 var metadata RecipeMetadata
133 decodeMetadata := func(decoder *json.Decoder) error {
134 return decoder.Decode(&metadata)
135 }
136 path := "/api/recipe/" + url.PathEscape(recipeID) + "/metadata"
137 if err := c.doAuthenticated(ctx, http.MethodGet, path, nil, decodeMetadata); err != nil {
138 return RecipeMetadata{}, err
139 }
140
141 return metadata, nil
142}
143
144// ReadRecipeContent logs in when needed and returns recipe content and portions.
145func (c *Client) ReadRecipeContent(ctx context.Context, recipeID string) (RecipeContent, error) {
146 var content RecipeContent
147 decodeContent := func(decoder *json.Decoder) error {
148 return decoder.Decode(&content)
149 }
150 path := "/api/recipe/" + url.PathEscape(recipeID) + "/content"
151 if err := c.doAuthenticated(ctx, http.MethodGet, path, nil, decodeContent); err != nil {
152 return RecipeContent{}, err
153 }
154
155 return content, nil
156}
157
158func (c *Client) getRecipes(ctx context.Context, path string) ([]RecipeCard, error) {
159 var response recipeListResponse
160 decodeRecipes := func(decoder *json.Decoder) error {
161 return decoder.Decode(&response)
162 }
163 if err := c.doAuthenticated(ctx, http.MethodGet, path, nil, decodeRecipes); err != nil {
164 return nil, err
165 }
166
167 return response.Recipes, nil
168}
169
170func (c *Client) doAuthenticated(ctx context.Context, method, path string, body []byte, decodeResponse responseDecoder) error {
171 c.requestMu.Lock()
172 defer c.requestMu.Unlock()
173
174 if err := c.ensureLogin(ctx); err != nil {
175 return err
176 }
177
178 err := c.do(ctx, method, c.userPath(path), body, decodeResponse)
179 if !isUnauthorized(err) {
180 return err
181 }
182
183 c.resetSession()
184 if err := c.ensureLogin(ctx); err != nil {
185 return err
186 }
187
188 return c.do(ctx, method, c.userPath(path), body, decodeResponse)
189}
190
191func (c *Client) ensureLogin(ctx context.Context) error {
192 authenticated := c.authenticatedUsername != ""
193 if authenticated {
194 return nil
195 }
196
197 body, err := json.Marshal(loginRequest{Username: c.username, Password: c.password})
198 if err != nil {
199 return fmt.Errorf("encode Cooked login request: %w", err)
200 }
201
202 var login loginResponse
203 decodeLogin := func(decoder *json.Decoder) error {
204 return decoder.Decode(&login)
205 }
206 if err := c.do(ctx, http.MethodPost, "/api/public/login", body, decodeLogin); err != nil {
207 return fmt.Errorf("authenticate with Cooked: %w", err)
208 }
209 if login.Username == "" {
210 return fmt.Errorf("authenticate with Cooked: missing username in login response")
211 }
212
213 c.authenticatedUsername = login.Username
214
215 return nil
216}
217
218func (c *Client) resetSession() {
219 jar, err := newCookieJar()
220 if err != nil {
221 return
222 }
223
224 c.authenticatedUsername = ""
225 c.http = &http.Client{Jar: jar, Timeout: c.http.Timeout}
226}
227
228func (c *Client) do(ctx context.Context, method, path string, body []byte, decodeResponse responseDecoder) error {
229 request, err := c.newRequest(ctx, method, path, body)
230 if err != nil {
231 return err
232 }
233
234 response, err := c.http.Do(request)
235 if err != nil {
236 return fmt.Errorf("call Cooked: %w", err)
237 }
238 defer func() {
239 _ = response.Body.Close()
240 }()
241
242 if response.StatusCode < http.StatusOK || response.StatusCode >= http.StatusMultipleChoices {
243 return decodeError(response)
244 }
245
246 if decodeResponse == nil {
247 return nil
248 }
249 if err := decodeResponse(json.NewDecoder(io.LimitReader(response.Body, maxResponseBytes))); err != nil {
250 return fmt.Errorf("decode Cooked response: %w", err)
251 }
252
253 return nil
254}
255
256func (c *Client) newRequest(ctx context.Context, method, path string, body []byte) (*http.Request, error) {
257 relativeURL, err := url.Parse(path)
258 if err != nil {
259 return nil, fmt.Errorf("parse Cooked request path: %w", err)
260 }
261 requestURL := c.baseURL.ResolveReference(relativeURL)
262
263 var reader io.Reader
264 if body != nil {
265 reader = bytes.NewReader(body)
266 }
267
268 request, err := http.NewRequestWithContext(ctx, method, requestURL.String(), reader)
269 if err != nil {
270 return nil, fmt.Errorf("build Cooked request: %w", err)
271 }
272 request.Header.Set("Accept", "application/json")
273 if body != nil {
274 request.Header.Set("Content-Type", "application/json")
275 }
276
277 return request, nil
278}
279
280func (c *Client) userPath(path string) string {
281 username := c.authenticatedUsername
282
283 return strings.ReplaceAll(path, "{username}", url.PathEscape(username))
284}
285
286type responseDecoder func(*json.Decoder) error
287
288type shoppingListResponse struct {
289 ShoppingList ShoppingList `json:"shopping-list"`
290 Recipes []string `json:"recipes"`
291}
292
293type recipeListResponse struct {
294 Recipes []RecipeCard `json:"recipes"`
295}
296
297type loginRequest struct {
298 Username string `json:"username"`
299 Password string `json:"password"`
300}
301
302type loginResponse struct {
303 Username string `json:"username"`
304}
305
306type cookedError struct {
307 StatusCode int
308 Code string
309 Message string
310}
311
312func (e cookedError) Error() string {
313 var parts []string
314 parts = append(parts, fmt.Sprintf("Cooked returned HTTP %d", e.StatusCode))
315 if e.Code != "" {
316 parts = append(parts, e.Code)
317 }
318 if e.Message != "" {
319 parts = append(parts, e.Message)
320 }
321
322 return strings.Join(parts, ": ")
323}
324
325func decodeError(response *http.Response) error {
326 var payload struct {
327 Code string `json:"code"`
328 Message string `json:"message"`
329 }
330 _ = json.NewDecoder(io.LimitReader(response.Body, 64*1024)).Decode(&payload)
331
332 return cookedError{
333 StatusCode: response.StatusCode,
334 Code: payload.Code,
335 Message: payload.Message,
336 }
337}
338
339func isUnauthorized(err error) bool {
340 if err == nil {
341 return false
342 }
343
344 var cookedErr cookedError
345 if !errors.As(err, &cookedErr) {
346 return false
347 }
348
349 return cookedErr.StatusCode == http.StatusUnauthorized
350}
351
352func newCookieJar() (*cookiejar.Jar, error) {
353 return cookiejar.New(&cookiejar.Options{PublicSuffixList: publicsuffix.List})
354}