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 "math/big"
16 "net/http"
17 "net/http/cookiejar"
18 "net/url"
19 "strconv"
20 "strings"
21 "sync"
22 "time"
23
24 "golang.org/x/net/publicsuffix"
25)
26
27const maxResponseBytes = 1 << 20
28
29// Client is an authenticated Cooked API client.
30type Client struct {
31 baseURL *url.URL
32 username string
33 password string
34 http *http.Client
35
36 requestMu sync.Mutex
37 authenticatedUsername string
38}
39
40// ShoppingList is the authenticated user's Cooked shopping list.
41type ShoppingList struct {
42 Aisles []Aisle `json:"aisles"`
43 Recipes []string `json:"recipes"`
44}
45
46// Aisle groups shopping-list product groups.
47type Aisle struct {
48 ID string `json:"aisle-id"`
49 Name string `json:"aisle-name"`
50 ProductGroups []ProductGroup `json:"product-groups"`
51}
52
53// ProductGroup is an item on the shopping list.
54type ProductGroup struct {
55 ID string `json:"id"`
56 Name string `json:"name"`
57 Quantity string `json:"quantity"`
58 Selected bool `json:"selected"`
59}
60
61// AddShoppingListResult is the result of adding ingredients to a shopping list.
62type AddShoppingListResult struct {
63 AddedCount int
64 Ingredients []string
65}
66
67// ShoppingListProductGroupUpdate is a full shopping-list product-group update.
68type ShoppingListProductGroupUpdate struct {
69 Name string
70 Quantity string
71 AisleID string
72 Selected bool
73}
74
75// RecipeCard is a saved recipe summary returned by Cooked list and search endpoints.
76type RecipeCard struct {
77 ID string `json:"id"`
78 Title string `json:"title"`
79 ThumbnailURL string `json:"thumbnail-url,omitempty"`
80}
81
82// RecipeMetadata is metadata for a Cooked recipe.
83type RecipeMetadata struct {
84 Title string `json:"title"`
85 ImageURLs []string `json:"image-urls"`
86 Owner string `json:"owner"`
87 EditPermission bool `json:"edit-permission"`
88}
89
90// RecipeContent is the Markdown-style body and portions for a Cooked recipe.
91type RecipeContent struct {
92 Content string `json:"content"`
93 Portions int `json:"portions"`
94}
95
96// RecipeTextPreview is Cooked's preview of raw recipe text before saving.
97type RecipeTextPreview struct {
98 Title string `json:"title"`
99 Markdown string `json:"markdown"`
100 Portions int `json:"portions"`
101}
102
103// UnmarshalJSON accepts Cooked's integer-valued decimal portions, such as 1.0.
104func (p *RecipeTextPreview) UnmarshalJSON(data []byte) error {
105 type raw RecipeTextPreview
106 var response struct {
107 raw
108 Portions json.Number `json:"portions"`
109 }
110 if err := json.Unmarshal(data, &response); err != nil {
111 return err
112 }
113
114 portions, err := jsonNumberToInt(response.Portions)
115 if err != nil {
116 return fmt.Errorf("portions: %w", err)
117 }
118
119 *p = RecipeTextPreview(response.raw)
120 p.Portions = portions
121
122 return nil
123}
124
125// RecipeURLImport is the result of importing a recipe URL.
126type RecipeURLImport struct {
127 RecipeID string
128 DraftID string
129}
130
131// NewClient returns a Cooked client with an in-memory cookie jar.
132func NewClient(baseURL *url.URL, username, password string) (*Client, error) {
133 jar, err := newCookieJar()
134 if err != nil {
135 return nil, fmt.Errorf("create cookie jar: %w", err)
136 }
137
138 return &Client{
139 baseURL: baseURL,
140 username: username,
141 password: password,
142 http: &http.Client{
143 Jar: jar,
144 Timeout: 30 * time.Second,
145 },
146 }, nil
147}
148
149// ReadShoppingList logs in when needed and returns the authenticated user's shopping list.
150func (c *Client) ReadShoppingList(ctx context.Context) (ShoppingList, error) {
151 var response shoppingListResponse
152 decodeShoppingList := func(decoder *json.Decoder) error {
153 return decoder.Decode(&response)
154 }
155 if err := c.doAuthenticated(
156 ctx,
157 http.MethodGet,
158 "/api/user/{username}/shopping-list",
159 nil,
160 decodeShoppingList,
161 ); err != nil {
162 return ShoppingList{}, err
163 }
164
165 response.ShoppingList.Recipes = response.Recipes
166 return response.ShoppingList, nil
167}
168
169// ClearShoppingList logs in when needed and clears the authenticated user's shopping list.
170func (c *Client) ClearShoppingList(ctx context.Context) error {
171 return c.doAuthenticated(ctx, http.MethodDelete, "/api/user/{username}/shopping-list", nil, nil)
172}
173
174// AddShoppingListIngredients logs in when needed and adds ingredients to the shopping list.
175func (c *Client) AddShoppingListIngredients(
176 ctx context.Context,
177 ingredients, recipeID string,
178) (AddShoppingListResult, error) {
179 body, err := json.Marshal(addShoppingListRequest{Ingredients: ingredients, RecipeID: recipeID})
180 if err != nil {
181 return AddShoppingListResult{}, fmt.Errorf("encode Cooked shopping-list add request: %w", err)
182 }
183
184 var response addShoppingListResponse
185 decodeAdd := func(decoder *json.Decoder) error {
186 return decoder.Decode(&response)
187 }
188 if err := c.doAuthenticated(ctx, http.MethodPut, "/api/user/shopping-list", body, decodeAdd); err != nil {
189 return AddShoppingListResult{}, err
190 }
191 if response.AddedCount == nil {
192 return AddShoppingListResult{}, fmt.Errorf("add shopping-list ingredients response missing added count")
193 }
194
195 return AddShoppingListResult{AddedCount: *response.AddedCount, Ingredients: response.Ingredients}, nil
196}
197
198// RemoveShoppingListProductGroups logs in when needed and removes shopping-list product groups.
199func (c *Client) RemoveShoppingListProductGroups(ctx context.Context, ids []string) error {
200 body, err := json.Marshal(removeShoppingListProductGroupsRequest{IDs: ids})
201 if err != nil {
202 return fmt.Errorf("encode Cooked shopping-list remove request: %w", err)
203 }
204
205 return c.doAuthenticated(ctx, http.MethodDelete, "/api/user/{username}/shopping-list/product-groups", body, nil)
206}
207
208// ReplaceShoppingListSelection logs in when needed and replaces the selected shopping-list product groups.
209func (c *Client) ReplaceShoppingListSelection(ctx context.Context, ids []string) error {
210 body, err := json.Marshal(replaceShoppingListSelectionRequest{Selected: ids})
211 if err != nil {
212 return fmt.Errorf("encode Cooked shopping-list selection request: %w", err)
213 }
214
215 return c.doAuthenticated(
216 ctx,
217 http.MethodPut,
218 "/api/user/{username}/shopping-list/product-groups/selection",
219 body,
220 nil,
221 )
222}
223
224// UpdateShoppingListProductGroup logs in when needed and updates a shopping-list product group.
225func (c *Client) UpdateShoppingListProductGroup(
226 ctx context.Context,
227 productGroupID string,
228 update ShoppingListProductGroupUpdate,
229) error {
230 body, err := json.Marshal(updateShoppingListProductGroupRequest(update))
231 if err != nil {
232 return fmt.Errorf("encode Cooked shopping-list product-group update request: %w", err)
233 }
234
235 path := "/api/user/{username}/shopping-list/product-groups/" + url.PathEscape(productGroupID)
236
237 return c.doAuthenticated(ctx, http.MethodPut, path, body, nil)
238}
239
240// ListRecipes logs in when needed and returns one page of saved recipes.
241func (c *Client) ListRecipes(ctx context.Context, page, limit int) ([]RecipeCard, error) {
242 query := url.Values{}
243 query.Set("page", fmt.Sprintf("%d", page))
244 query.Set("page-count", fmt.Sprintf("%d", limit))
245
246 return c.getRecipes(ctx, "/api/user/{username}/recipes?"+query.Encode())
247}
248
249// SearchRecipes logs in when needed and searches the authenticated user's saved recipes.
250func (c *Client) SearchRecipes(ctx context.Context, queryText string, page int) ([]RecipeCard, error) {
251 query := url.Values{}
252 query.Set("q", queryText)
253 query.Set("page", fmt.Sprintf("%d", page))
254
255 return c.getRecipes(ctx, "/api/user/{username}/recipes/search?"+query.Encode())
256}
257
258// ReadRecipeMetadata logs in when needed and returns recipe metadata.
259func (c *Client) ReadRecipeMetadata(ctx context.Context, recipeID string) (RecipeMetadata, error) {
260 var metadata RecipeMetadata
261 decodeMetadata := func(decoder *json.Decoder) error {
262 return decoder.Decode(&metadata)
263 }
264 path := "/api/recipe/" + url.PathEscape(recipeID) + "/metadata"
265 if err := c.doAuthenticated(ctx, http.MethodGet, path, nil, decodeMetadata); err != nil {
266 return RecipeMetadata{}, err
267 }
268
269 return metadata, nil
270}
271
272// ReadRecipeContent logs in when needed and returns recipe content and portions.
273func (c *Client) ReadRecipeContent(ctx context.Context, recipeID string) (RecipeContent, error) {
274 var content RecipeContent
275 decodeContent := func(decoder *json.Decoder) error {
276 return decoder.Decode(&content)
277 }
278 path := "/api/recipe/" + url.PathEscape(recipeID) + "/content"
279 if err := c.doAuthenticated(ctx, http.MethodGet, path, nil, decodeContent); err != nil {
280 return RecipeContent{}, err
281 }
282
283 return content, nil
284}
285
286// PreviewRecipeText logs in when needed and previews raw recipe text without saving it.
287func (c *Client) PreviewRecipeText(ctx context.Context, title, text string) (RecipeTextPreview, error) {
288 body, err := json.Marshal(previewRecipeTextRequest{RecipeName: title, RecipeText: text})
289 if err != nil {
290 return RecipeTextPreview{}, fmt.Errorf("encode Cooked recipe text preview request: %w", err)
291 }
292
293 var preview RecipeTextPreview
294 decodePreview := func(decoder *json.Decoder) error {
295 return decoder.Decode(&preview)
296 }
297 if err := c.doAuthenticated(ctx, http.MethodPost, "/api/new/from-text/preview", body, decodePreview); err != nil {
298 return RecipeTextPreview{}, err
299 }
300
301 return preview, nil
302}
303
304// SavePreparedRecipe logs in when needed and saves prepared recipe markdown as a new recipe.
305func (c *Client) SavePreparedRecipe(ctx context.Context, title, markdown string, portions int) (string, error) {
306 body, err := json.Marshal(savePreparedRecipeRequest{Title: title, Description: markdown, Portions: portions})
307 if err != nil {
308 return "", fmt.Errorf("encode Cooked prepared recipe save request: %w", err)
309 }
310
311 var response saveRecipeResponse
312 decodeSave := func(decoder *json.Decoder) error {
313 return decoder.Decode(&response)
314 }
315 if err := c.doAuthenticated(ctx, http.MethodPost, "/api/recipe/import/save", body, decodeSave); err != nil {
316 return "", err
317 }
318
319 return response.RecipeID, nil
320}
321
322// SaveRecipeDraft logs in when needed and saves a reviewed URL import draft.
323func (c *Client) SaveRecipeDraft(ctx context.Context, draftID, markdown string, portions int) (string, error) {
324 body, err := json.Marshal(recipeContentRequest{Description: markdown, Portions: portions})
325 if err != nil {
326 return "", fmt.Errorf("encode Cooked recipe draft save request: %w", err)
327 }
328
329 var response saveRecipeResponse
330 decodeSave := func(decoder *json.Decoder) error {
331 return decoder.Decode(&response)
332 }
333 path := "/api/extract/" + url.PathEscape(draftID) + "/save"
334 if err := c.doAuthenticated(ctx, http.MethodPost, path, body, decodeSave); err != nil {
335 return "", err
336 }
337
338 return response.RecipeID, nil
339}
340
341// UpdateRecipeContent logs in when needed and updates an existing recipe's content.
342func (c *Client) UpdateRecipeContent(ctx context.Context, recipeID, markdown string, portions int) error {
343 body, err := json.Marshal(recipeContentRequest{Description: markdown, Portions: portions})
344 if err != nil {
345 return fmt.Errorf("encode Cooked recipe update request: %w", err)
346 }
347
348 path := "/api/recipe/" + url.PathEscape(recipeID) + "/content"
349
350 return c.doAuthenticated(ctx, http.MethodPost, path, body, nil)
351}
352
353// ImportRecipeURL logs in when needed and starts a recipe URL import.
354func (c *Client) ImportRecipeURL(ctx context.Context, recipeURL string) (RecipeURLImport, error) {
355 body, err := json.Marshal(importRecipeURLRequest{URL: recipeURL})
356 if err != nil {
357 return RecipeURLImport{}, fmt.Errorf("encode Cooked recipe URL import request: %w", err)
358 }
359
360 var response importRecipeURLResponse
361 decodeImport := func(decoder *json.Decoder) error {
362 return decoder.Decode(&response)
363 }
364 if err := c.doAuthenticated(ctx, http.MethodPost, "/api/new", body, decodeImport); err != nil {
365 return RecipeURLImport{}, err
366 }
367
368 if strings.TrimSpace(response.RecipeID) == "" && strings.TrimSpace(response.ExtractionID) == "" {
369 return RecipeURLImport{}, fmt.Errorf("import recipe URL response missing recipe or draft ID")
370 }
371
372 return RecipeURLImport{RecipeID: response.RecipeID, DraftID: response.ExtractionID}, nil
373}
374
375// DeleteRecipe logs in when needed and deletes an existing recipe.
376func (c *Client) DeleteRecipe(ctx context.Context, recipeID string) error {
377 path := "/api/recipe/" + url.PathEscape(recipeID)
378
379 return c.doAuthenticated(ctx, http.MethodDelete, path, nil, nil)
380}
381
382func (c *Client) getRecipes(ctx context.Context, path string) ([]RecipeCard, error) {
383 var recipes []RecipeCard
384 decodeRecipes := func(decoder *json.Decoder) error {
385 return decoder.Decode(&recipes)
386 }
387 if err := c.doAuthenticated(ctx, http.MethodGet, path, nil, decodeRecipes); err != nil {
388 return nil, err
389 }
390 if err := validateRecipeCards(recipes); err != nil {
391 return nil, err
392 }
393
394 return recipes, nil
395}
396
397func validateRecipeCards(recipes []RecipeCard) error {
398 if recipes == nil {
399 return fmt.Errorf("cooked recipe list response missing recipes")
400 }
401
402 for index, recipe := range recipes {
403 if strings.TrimSpace(recipe.ID) == "" {
404 return fmt.Errorf("cooked recipe list response recipe %d missing id", index)
405 }
406 if strings.TrimSpace(recipe.Title) == "" {
407 return fmt.Errorf("cooked recipe list response recipe %d missing title", index)
408 }
409 }
410
411 return nil
412}
413
414func jsonNumberToInt(number json.Number) (int, error) {
415 text := number.String()
416 if text == "" {
417 return 0, fmt.Errorf("missing")
418 }
419
420 rational, ok := new(big.Rat).SetString(text)
421 if !ok {
422 return 0, fmt.Errorf("invalid JSON number %q", text)
423 }
424 if !rational.IsInt() {
425 return 0, fmt.Errorf("must be integer-valued, got %s", text)
426 }
427
428 integer := rational.Num()
429 if !integer.IsInt64() {
430 return 0, fmt.Errorf("out of range, got %s", text)
431 }
432
433 value := integer.Int64()
434 maxInt := int64(1<<(strconv.IntSize-1) - 1)
435 minInt := -maxInt - 1
436 if value < minInt || value > maxInt {
437 return 0, fmt.Errorf("out of range for int, got %s", text)
438 }
439
440 return int(value), nil
441}
442
443func (c *Client) doAuthenticated(
444 ctx context.Context,
445 method, path string,
446 body []byte,
447 decodeResponse responseDecoder,
448) error {
449 c.requestMu.Lock()
450 defer c.requestMu.Unlock()
451
452 if err := c.ensureLogin(ctx); err != nil {
453 return err
454 }
455
456 err := c.do(ctx, method, c.userPath(path), body, decodeResponse)
457 if !isUnauthorized(err) {
458 return err
459 }
460
461 c.resetSession()
462 if err := c.ensureLogin(ctx); err != nil {
463 return err
464 }
465
466 return c.do(ctx, method, c.userPath(path), body, decodeResponse)
467}
468
469func (c *Client) ensureLogin(ctx context.Context) error {
470 authenticated := c.authenticatedUsername != ""
471 if authenticated {
472 return nil
473 }
474
475 body, err := json.Marshal(loginRequest{Username: c.username, Password: c.password})
476 if err != nil {
477 return fmt.Errorf("encode Cooked login request: %w", err)
478 }
479
480 var login loginResponse
481 decodeLogin := func(decoder *json.Decoder) error {
482 return decoder.Decode(&login)
483 }
484 if err := c.do(ctx, http.MethodPost, "/api/public/login", body, decodeLogin); err != nil {
485 return fmt.Errorf("authenticate with Cooked: %w", err)
486 }
487 if login.Username == "" {
488 return fmt.Errorf("authenticate with Cooked: missing username in login response")
489 }
490
491 c.authenticatedUsername = login.Username
492
493 return nil
494}
495
496func (c *Client) resetSession() {
497 jar, err := newCookieJar()
498 if err != nil {
499 return
500 }
501
502 c.authenticatedUsername = ""
503 c.http = &http.Client{Jar: jar, Timeout: c.http.Timeout}
504}
505
506func (c *Client) do(ctx context.Context, method, path string, body []byte, decodeResponse responseDecoder) error {
507 request, err := c.newRequest(ctx, method, path, body)
508 if err != nil {
509 return err
510 }
511
512 response, err := c.http.Do(request)
513 if err != nil {
514 return fmt.Errorf("call Cooked: %w", err)
515 }
516 defer func() {
517 _ = response.Body.Close()
518 }()
519
520 if response.StatusCode < http.StatusOK || response.StatusCode >= http.StatusMultipleChoices {
521 return decodeError(response)
522 }
523
524 if decodeResponse == nil {
525 return nil
526 }
527 if err := decodeResponse(json.NewDecoder(io.LimitReader(response.Body, maxResponseBytes))); err != nil {
528 return fmt.Errorf("decode Cooked response: %w", err)
529 }
530
531 return nil
532}
533
534func (c *Client) newRequest(ctx context.Context, method, path string, body []byte) (*http.Request, error) {
535 relativeURL, err := url.Parse(path)
536 if err != nil {
537 return nil, fmt.Errorf("parse Cooked request path: %w", err)
538 }
539 requestURL := c.baseURL.ResolveReference(relativeURL)
540
541 var reader io.Reader
542 if body != nil {
543 reader = bytes.NewReader(body)
544 }
545
546 request, err := http.NewRequestWithContext(ctx, method, requestURL.String(), reader)
547 if err != nil {
548 return nil, fmt.Errorf("build Cooked request: %w", err)
549 }
550 request.Header.Set("Accept", "application/json")
551 if body != nil {
552 request.Header.Set("Content-Type", "application/json")
553 }
554
555 return request, nil
556}
557
558func (c *Client) userPath(path string) string {
559 username := c.authenticatedUsername
560
561 return strings.ReplaceAll(path, "{username}", url.PathEscape(username))
562}
563
564type responseDecoder func(*json.Decoder) error
565
566type shoppingListResponse struct {
567 ShoppingList ShoppingList `json:"shopping-list"`
568 Recipes []string `json:"recipes"`
569}
570
571type addShoppingListRequest struct {
572 Ingredients string `json:"ingredients"`
573 RecipeID string `json:"recipe-id,omitempty"`
574}
575
576type addShoppingListResponse struct {
577 AddedCount *int `json:"added-count"`
578 Ingredients []string `json:"ingredients"`
579}
580
581type removeShoppingListProductGroupsRequest struct {
582 IDs []string `json:"ids"`
583}
584
585type replaceShoppingListSelectionRequest struct {
586 Selected []string `json:"selected"`
587}
588
589type updateShoppingListProductGroupRequest struct {
590 Name string `json:"name"`
591 Quantity string `json:"quantity"`
592 AisleID string `json:"aisle-id"`
593 Selected bool `json:"selected"`
594}
595
596type previewRecipeTextRequest struct {
597 RecipeName string `json:"recipe-name"`
598 RecipeText string `json:"recipe-text"`
599}
600
601type savePreparedRecipeRequest struct {
602 Title string `json:"title"`
603 Description string `json:"description"`
604 Portions int `json:"portions"`
605}
606
607type recipeContentRequest struct {
608 Description string `json:"description"`
609 Portions int `json:"portions"`
610}
611
612type importRecipeURLRequest struct {
613 URL string `json:"url"`
614}
615
616type importRecipeURLResponse struct {
617 RecipeID string `json:"recipe-id"`
618 ExtractionID string `json:"extraction-id"`
619}
620
621type saveRecipeResponse struct {
622 RecipeID string `json:"recipe-id"`
623}
624
625type loginRequest struct {
626 Username string `json:"username"`
627 Password string `json:"password"`
628}
629
630type loginResponse struct {
631 Username string `json:"username"`
632}
633
634type cookedError struct {
635 StatusCode int
636 Code string
637 Message string
638}
639
640func (e cookedError) Error() string {
641 var parts []string
642 parts = append(parts, fmt.Sprintf("Cooked returned HTTP %d", e.StatusCode))
643 if e.Code != "" {
644 parts = append(parts, e.Code)
645 }
646 if e.Message != "" {
647 parts = append(parts, e.Message)
648 }
649
650 return strings.Join(parts, ": ")
651}
652
653func decodeError(response *http.Response) error {
654 var payload struct {
655 Code string `json:"code"`
656 Message string `json:"message"`
657 }
658 _ = json.NewDecoder(io.LimitReader(response.Body, 64*1024)).Decode(&payload)
659
660 return cookedError{
661 StatusCode: response.StatusCode,
662 Code: payload.Code,
663 Message: payload.Message,
664 }
665}
666
667func isUnauthorized(err error) bool {
668 if err == nil {
669 return false
670 }
671
672 var cookedErr cookedError
673 if !errors.As(err, &cookedErr) {
674 return false
675 }
676
677 return cookedErr.StatusCode == http.StatusUnauthorized
678}
679
680func newCookieJar() (*cookiejar.Jar, error) {
681 return cookiejar.New(&cookiejar.Options{PublicSuffixList: publicsuffix.List})
682}