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 if strings.TrimSpace(ingredients) != "" && *response.AddedCount == 0 {
195 return AddShoppingListResult{}, fmt.Errorf(
196 "add shopping-list ingredients response returned added-count 0 for nonblank ingredients",
197 )
198 }
199
200 return AddShoppingListResult{AddedCount: *response.AddedCount, Ingredients: response.Ingredients}, nil
201}
202
203// RemoveShoppingListProductGroups logs in when needed and removes shopping-list product groups.
204func (c *Client) RemoveShoppingListProductGroups(ctx context.Context, ids []string) error {
205 body, err := json.Marshal(removeShoppingListProductGroupsRequest{IDs: ids})
206 if err != nil {
207 return fmt.Errorf("encode Cooked shopping-list remove request: %w", err)
208 }
209
210 return c.doAuthenticated(ctx, http.MethodDelete, "/api/user/{username}/shopping-list/product-groups", body, nil)
211}
212
213// ReplaceShoppingListSelection logs in when needed and replaces the selected shopping-list product groups.
214func (c *Client) ReplaceShoppingListSelection(ctx context.Context, ids []string) error {
215 body, err := json.Marshal(replaceShoppingListSelectionRequest{Selected: ids})
216 if err != nil {
217 return fmt.Errorf("encode Cooked shopping-list selection request: %w", err)
218 }
219
220 return c.doAuthenticated(
221 ctx,
222 http.MethodPut,
223 "/api/user/{username}/shopping-list/product-groups/selection",
224 body,
225 nil,
226 )
227}
228
229// UpdateShoppingListProductGroup logs in when needed and updates a shopping-list product group.
230func (c *Client) UpdateShoppingListProductGroup(
231 ctx context.Context,
232 productGroupID string,
233 update ShoppingListProductGroupUpdate,
234) error {
235 body, err := json.Marshal(updateShoppingListProductGroupRequest(update))
236 if err != nil {
237 return fmt.Errorf("encode Cooked shopping-list product-group update request: %w", err)
238 }
239
240 path := "/api/user/{username}/shopping-list/product-groups/" + url.PathEscape(productGroupID)
241
242 return c.doAuthenticated(ctx, http.MethodPut, path, body, nil)
243}
244
245// ListRecipes logs in when needed and returns one page of saved recipes.
246func (c *Client) ListRecipes(ctx context.Context, page, limit int) ([]RecipeCard, error) {
247 query := url.Values{}
248 query.Set("page", fmt.Sprintf("%d", page))
249 query.Set("page-count", fmt.Sprintf("%d", limit))
250
251 return c.getRecipes(ctx, "/api/user/{username}/recipes?"+query.Encode())
252}
253
254// SearchRecipes logs in when needed and searches the authenticated user's saved recipes.
255func (c *Client) SearchRecipes(ctx context.Context, queryText string, page int) ([]RecipeCard, error) {
256 query := url.Values{}
257 query.Set("q", queryText)
258 query.Set("page", fmt.Sprintf("%d", page))
259
260 return c.getRecipes(ctx, "/api/user/{username}/recipes/search?"+query.Encode())
261}
262
263// ReadRecipeMetadata logs in when needed and returns recipe metadata.
264func (c *Client) ReadRecipeMetadata(ctx context.Context, recipeID string) (RecipeMetadata, error) {
265 var metadata RecipeMetadata
266 decodeMetadata := func(decoder *json.Decoder) error {
267 return decoder.Decode(&metadata)
268 }
269 path := "/api/recipe/" + url.PathEscape(recipeID) + "/metadata"
270 if err := c.doAuthenticated(ctx, http.MethodGet, path, nil, decodeMetadata); err != nil {
271 return RecipeMetadata{}, err
272 }
273
274 return metadata, nil
275}
276
277// ReadRecipeContent logs in when needed and returns recipe content and portions.
278func (c *Client) ReadRecipeContent(ctx context.Context, recipeID string) (RecipeContent, error) {
279 var content RecipeContent
280 decodeContent := func(decoder *json.Decoder) error {
281 return decoder.Decode(&content)
282 }
283 path := "/api/recipe/" + url.PathEscape(recipeID) + "/content"
284 if err := c.doAuthenticated(ctx, http.MethodGet, path, nil, decodeContent); err != nil {
285 return RecipeContent{}, err
286 }
287
288 return content, nil
289}
290
291// PreviewRecipeText logs in when needed and previews raw recipe text without saving it.
292func (c *Client) PreviewRecipeText(ctx context.Context, title, text string) (RecipeTextPreview, error) {
293 body, err := json.Marshal(previewRecipeTextRequest{RecipeName: title, RecipeText: text})
294 if err != nil {
295 return RecipeTextPreview{}, fmt.Errorf("encode Cooked recipe text preview request: %w", err)
296 }
297
298 var preview RecipeTextPreview
299 decodePreview := func(decoder *json.Decoder) error {
300 return decoder.Decode(&preview)
301 }
302 if err := c.doAuthenticated(ctx, http.MethodPost, "/api/new/from-text/preview", body, decodePreview); err != nil {
303 return RecipeTextPreview{}, err
304 }
305
306 return preview, nil
307}
308
309// SavePreparedRecipe logs in when needed and saves prepared recipe markdown as a new recipe.
310func (c *Client) SavePreparedRecipe(ctx context.Context, title, markdown string, portions int) (string, error) {
311 body, err := json.Marshal(savePreparedRecipeRequest{Title: title, Description: markdown, Portions: portions})
312 if err != nil {
313 return "", fmt.Errorf("encode Cooked prepared recipe save request: %w", err)
314 }
315
316 var response saveRecipeResponse
317 decodeSave := func(decoder *json.Decoder) error {
318 return decoder.Decode(&response)
319 }
320 if err := c.doAuthenticated(ctx, http.MethodPost, "/api/recipe/import/save", body, decodeSave); err != nil {
321 return "", err
322 }
323
324 return response.RecipeID, nil
325}
326
327// SaveRecipeDraft logs in when needed and saves a reviewed URL import draft.
328func (c *Client) SaveRecipeDraft(ctx context.Context, draftID, markdown string, portions int) (string, error) {
329 body, err := json.Marshal(recipeContentRequest{Description: markdown, Portions: portions})
330 if err != nil {
331 return "", fmt.Errorf("encode Cooked recipe draft save request: %w", err)
332 }
333
334 var response saveRecipeResponse
335 decodeSave := func(decoder *json.Decoder) error {
336 return decoder.Decode(&response)
337 }
338 path := "/api/extract/" + url.PathEscape(draftID) + "/save"
339 if err := c.doAuthenticated(ctx, http.MethodPost, path, body, decodeSave); err != nil {
340 return "", err
341 }
342 if strings.TrimSpace(response.RecipeID) == "" {
343 return "", fmt.Errorf("save recipe draft response missing recipe ID")
344 }
345
346 return response.RecipeID, nil
347}
348
349// UpdateRecipeContent logs in when needed and updates an existing recipe's content.
350func (c *Client) UpdateRecipeContent(ctx context.Context, recipeID, markdown string, portions int) error {
351 body, err := json.Marshal(recipeContentRequest{Description: markdown, Portions: portions})
352 if err != nil {
353 return fmt.Errorf("encode Cooked recipe update request: %w", err)
354 }
355
356 path := "/api/recipe/" + url.PathEscape(recipeID) + "/content"
357
358 return c.doAuthenticated(ctx, http.MethodPost, path, body, nil)
359}
360
361// ImportRecipeURL logs in when needed and starts a recipe URL import.
362func (c *Client) ImportRecipeURL(ctx context.Context, recipeURL string) (RecipeURLImport, error) {
363 body, err := json.Marshal(importRecipeURLRequest{URL: recipeURL})
364 if err != nil {
365 return RecipeURLImport{}, fmt.Errorf("encode Cooked recipe URL import request: %w", err)
366 }
367
368 var response importRecipeURLResponse
369 decodeImport := func(decoder *json.Decoder) error {
370 return decoder.Decode(&response)
371 }
372 if err := c.doAuthenticated(ctx, http.MethodPost, "/api/new", body, decodeImport); err != nil {
373 return RecipeURLImport{}, err
374 }
375
376 if strings.TrimSpace(response.RecipeID) == "" && strings.TrimSpace(response.ExtractionID) == "" {
377 return RecipeURLImport{}, fmt.Errorf("import recipe URL response missing recipe or draft ID")
378 }
379
380 return RecipeURLImport{RecipeID: response.RecipeID, DraftID: response.ExtractionID}, nil
381}
382
383// DeleteRecipe logs in when needed and deletes an existing recipe.
384func (c *Client) DeleteRecipe(ctx context.Context, recipeID string) error {
385 path := "/api/recipe/" + url.PathEscape(recipeID)
386
387 return c.doAuthenticated(ctx, http.MethodDelete, path, nil, nil)
388}
389
390func (c *Client) getRecipes(ctx context.Context, path string) ([]RecipeCard, error) {
391 var recipes []RecipeCard
392 decodeRecipes := func(decoder *json.Decoder) error {
393 return decoder.Decode(&recipes)
394 }
395 if err := c.doAuthenticated(ctx, http.MethodGet, path, nil, decodeRecipes); err != nil {
396 return nil, err
397 }
398 if err := validateRecipeCards(recipes); err != nil {
399 return nil, err
400 }
401
402 return recipes, nil
403}
404
405func validateRecipeCards(recipes []RecipeCard) error {
406 if recipes == nil {
407 return fmt.Errorf("cooked recipe list response missing recipes")
408 }
409
410 for index, recipe := range recipes {
411 if strings.TrimSpace(recipe.ID) == "" {
412 return fmt.Errorf("cooked recipe list response recipe %d missing id", index)
413 }
414 if strings.TrimSpace(recipe.Title) == "" {
415 return fmt.Errorf("cooked recipe list response recipe %d missing title", index)
416 }
417 }
418
419 return nil
420}
421
422func jsonNumberToInt(number json.Number) (int, error) {
423 text := number.String()
424 if text == "" {
425 return 0, fmt.Errorf("missing")
426 }
427
428 rational, ok := new(big.Rat).SetString(text)
429 if !ok {
430 return 0, fmt.Errorf("invalid JSON number %q", text)
431 }
432 if !rational.IsInt() {
433 return 0, fmt.Errorf("must be integer-valued, got %s", text)
434 }
435
436 integer := rational.Num()
437 if !integer.IsInt64() {
438 return 0, fmt.Errorf("out of range, got %s", text)
439 }
440
441 value := integer.Int64()
442 maxInt := int64(1<<(strconv.IntSize-1) - 1)
443 minInt := -maxInt - 1
444 if value < minInt || value > maxInt {
445 return 0, fmt.Errorf("out of range for int, got %s", text)
446 }
447
448 return int(value), nil
449}
450
451func (c *Client) doAuthenticated(
452 ctx context.Context,
453 method, path string,
454 body []byte,
455 decodeResponse responseDecoder,
456) error {
457 c.requestMu.Lock()
458 defer c.requestMu.Unlock()
459
460 if err := c.ensureLogin(ctx); err != nil {
461 return err
462 }
463
464 err := c.do(ctx, method, c.userPath(path), body, decodeResponse)
465 if !isUnauthorized(err) {
466 return err
467 }
468
469 c.resetSession()
470 if err := c.ensureLogin(ctx); err != nil {
471 return err
472 }
473
474 return c.do(ctx, method, c.userPath(path), body, decodeResponse)
475}
476
477func (c *Client) ensureLogin(ctx context.Context) error {
478 authenticated := c.authenticatedUsername != ""
479 if authenticated {
480 return nil
481 }
482
483 body, err := json.Marshal(loginRequest{Username: c.username, Password: c.password})
484 if err != nil {
485 return fmt.Errorf("encode Cooked login request: %w", err)
486 }
487
488 var login loginResponse
489 decodeLogin := func(decoder *json.Decoder) error {
490 return decoder.Decode(&login)
491 }
492 if err := c.do(ctx, http.MethodPost, "/api/public/login", body, decodeLogin); err != nil {
493 return fmt.Errorf("authenticate with Cooked: %w", err)
494 }
495 if login.Username == "" {
496 return fmt.Errorf("authenticate with Cooked: missing username in login response")
497 }
498
499 c.authenticatedUsername = login.Username
500
501 return nil
502}
503
504func (c *Client) resetSession() {
505 jar, err := newCookieJar()
506 if err != nil {
507 return
508 }
509
510 c.authenticatedUsername = ""
511 c.http = &http.Client{Jar: jar, Timeout: c.http.Timeout}
512}
513
514func (c *Client) do(ctx context.Context, method, path string, body []byte, decodeResponse responseDecoder) error {
515 request, err := c.newRequest(ctx, method, path, body)
516 if err != nil {
517 return err
518 }
519
520 response, err := c.http.Do(request)
521 if err != nil {
522 return fmt.Errorf("call Cooked: %w", err)
523 }
524 defer func() {
525 _ = response.Body.Close()
526 }()
527
528 if response.StatusCode < http.StatusOK || response.StatusCode >= http.StatusMultipleChoices {
529 return decodeError(response)
530 }
531
532 if decodeResponse == nil {
533 return nil
534 }
535 if err := decodeResponse(json.NewDecoder(io.LimitReader(response.Body, maxResponseBytes))); err != nil {
536 return fmt.Errorf("decode Cooked response: %w", err)
537 }
538
539 return nil
540}
541
542func (c *Client) newRequest(ctx context.Context, method, path string, body []byte) (*http.Request, error) {
543 relativeURL, err := url.Parse(path)
544 if err != nil {
545 return nil, fmt.Errorf("parse Cooked request path: %w", err)
546 }
547 requestURL := c.baseURL.ResolveReference(relativeURL)
548
549 var reader io.Reader
550 if body != nil {
551 reader = bytes.NewReader(body)
552 }
553
554 request, err := http.NewRequestWithContext(ctx, method, requestURL.String(), reader)
555 if err != nil {
556 return nil, fmt.Errorf("build Cooked request: %w", err)
557 }
558 request.Header.Set("Accept", "application/json")
559 if body != nil {
560 request.Header.Set("Content-Type", "application/json")
561 }
562
563 return request, nil
564}
565
566func (c *Client) userPath(path string) string {
567 username := c.authenticatedUsername
568
569 return strings.ReplaceAll(path, "{username}", url.PathEscape(username))
570}
571
572type responseDecoder func(*json.Decoder) error
573
574type shoppingListResponse struct {
575 ShoppingList ShoppingList `json:"shopping-list"`
576 Recipes []string `json:"recipes"`
577}
578
579type addShoppingListRequest struct {
580 Ingredients string `json:"ingredients"`
581 RecipeID string `json:"recipe-id,omitempty"`
582}
583
584type addShoppingListResponse struct {
585 AddedCount *int `json:"added-count"`
586 Ingredients []string `json:"ingredients"`
587}
588
589type removeShoppingListProductGroupsRequest struct {
590 IDs []string `json:"ids"`
591}
592
593type replaceShoppingListSelectionRequest struct {
594 Selected []string `json:"selected"`
595}
596
597type updateShoppingListProductGroupRequest struct {
598 Name string `json:"name"`
599 Quantity string `json:"quantity"`
600 AisleID string `json:"aisle-id"`
601 Selected bool `json:"selected"`
602}
603
604type previewRecipeTextRequest struct {
605 RecipeName string `json:"recipe-name"`
606 RecipeText string `json:"recipe-text"`
607}
608
609type savePreparedRecipeRequest struct {
610 Title string `json:"title"`
611 Description string `json:"description"`
612 Portions int `json:"portions"`
613}
614
615type recipeContentRequest struct {
616 Description string `json:"description"`
617 Portions int `json:"portions"`
618}
619
620type importRecipeURLRequest struct {
621 URL string `json:"url"`
622}
623
624type importRecipeURLResponse struct {
625 RecipeID string `json:"recipe-id"`
626 ExtractionID string `json:"extraction-id"`
627}
628
629type saveRecipeResponse struct {
630 RecipeID string `json:"recipe-id"`
631}
632
633type loginRequest struct {
634 Username string `json:"username"`
635 Password string `json:"password"`
636}
637
638type loginResponse struct {
639 Username string `json:"username"`
640}
641
642type cookedError struct {
643 StatusCode int
644 Code string
645 Message string
646}
647
648func (e cookedError) Error() string {
649 var parts []string
650 parts = append(parts, fmt.Sprintf("Cooked returned HTTP %d", e.StatusCode))
651 if e.Code != "" {
652 parts = append(parts, e.Code)
653 }
654 if e.Message != "" {
655 parts = append(parts, e.Message)
656 }
657
658 return strings.Join(parts, ": ")
659}
660
661func decodeError(response *http.Response) error {
662 var payload struct {
663 Code string `json:"code"`
664 Message string `json:"message"`
665 }
666 _ = json.NewDecoder(io.LimitReader(response.Body, 64*1024)).Decode(&payload)
667
668 return cookedError{
669 StatusCode: response.StatusCode,
670 Code: payload.Code,
671 Message: payload.Message,
672 }
673}
674
675func isUnauthorized(err error) bool {
676 if err == nil {
677 return false
678 }
679
680 var cookedErr cookedError
681 if !errors.As(err, &cookedErr) {
682 return false
683 }
684
685 return cookedErr.StatusCode == http.StatusUnauthorized
686}
687
688func newCookieJar() (*cookiejar.Jar, error) {
689 return cookiejar.New(&cookiejar.Options{PublicSuffixList: publicsuffix.List})
690}