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 if strings.TrimSpace(response.RecipeID) == "" {
324 return "", fmt.Errorf("save prepared recipe response missing recipe ID")
325 }
326
327 return response.RecipeID, nil
328}
329
330// SaveRecipeDraft logs in when needed and saves a reviewed URL import draft.
331func (c *Client) SaveRecipeDraft(ctx context.Context, draftID, markdown string, portions int) (string, error) {
332 body, err := json.Marshal(recipeContentRequest{Description: markdown, Portions: portions})
333 if err != nil {
334 return "", fmt.Errorf("encode Cooked recipe draft save request: %w", err)
335 }
336
337 var response saveRecipeResponse
338 decodeSave := func(decoder *json.Decoder) error {
339 return decoder.Decode(&response)
340 }
341 path := "/api/extract/" + url.PathEscape(draftID) + "/save"
342 if err := c.doAuthenticated(ctx, http.MethodPost, path, body, decodeSave); err != nil {
343 return "", err
344 }
345 if strings.TrimSpace(response.RecipeID) == "" {
346 return "", fmt.Errorf("save recipe draft response missing recipe ID")
347 }
348
349 return response.RecipeID, nil
350}
351
352// UpdateRecipeContent logs in when needed and updates an existing recipe's content.
353func (c *Client) UpdateRecipeContent(ctx context.Context, recipeID, markdown string, portions int) error {
354 body, err := json.Marshal(recipeContentRequest{Description: markdown, Portions: portions})
355 if err != nil {
356 return fmt.Errorf("encode Cooked recipe update request: %w", err)
357 }
358
359 path := "/api/recipe/" + url.PathEscape(recipeID) + "/content"
360
361 return c.doAuthenticated(ctx, http.MethodPost, path, body, nil)
362}
363
364// ImportRecipeURL logs in when needed and starts a recipe URL import.
365func (c *Client) ImportRecipeURL(ctx context.Context, recipeURL string) (RecipeURLImport, error) {
366 body, err := json.Marshal(importRecipeURLRequest{URL: recipeURL})
367 if err != nil {
368 return RecipeURLImport{}, fmt.Errorf("encode Cooked recipe URL import request: %w", err)
369 }
370
371 var response importRecipeURLResponse
372 decodeImport := func(decoder *json.Decoder) error {
373 return decoder.Decode(&response)
374 }
375 if err := c.doAuthenticated(ctx, http.MethodPost, "/api/new", body, decodeImport); err != nil {
376 return RecipeURLImport{}, err
377 }
378
379 if strings.TrimSpace(response.RecipeID) == "" && strings.TrimSpace(response.ExtractionID) == "" {
380 return RecipeURLImport{}, fmt.Errorf("import recipe URL response missing recipe or draft ID")
381 }
382
383 return RecipeURLImport{RecipeID: response.RecipeID, DraftID: response.ExtractionID}, nil
384}
385
386// DeleteRecipe logs in when needed and deletes an existing recipe.
387func (c *Client) DeleteRecipe(ctx context.Context, recipeID string) error {
388 path := "/api/recipe/" + url.PathEscape(recipeID)
389
390 return c.doAuthenticated(ctx, http.MethodDelete, path, nil, nil)
391}
392
393func (c *Client) getRecipes(ctx context.Context, path string) ([]RecipeCard, error) {
394 var recipes []RecipeCard
395 decodeRecipes := func(decoder *json.Decoder) error {
396 return decoder.Decode(&recipes)
397 }
398 if err := c.doAuthenticated(ctx, http.MethodGet, path, nil, decodeRecipes); err != nil {
399 return nil, err
400 }
401 if err := validateRecipeCards(recipes); err != nil {
402 return nil, err
403 }
404
405 return recipes, nil
406}
407
408func validateRecipeCards(recipes []RecipeCard) error {
409 if recipes == nil {
410 return fmt.Errorf("cooked recipe list response missing recipes")
411 }
412
413 for index, recipe := range recipes {
414 if strings.TrimSpace(recipe.ID) == "" {
415 return fmt.Errorf("cooked recipe list response recipe %d missing id", index)
416 }
417 if strings.TrimSpace(recipe.Title) == "" {
418 return fmt.Errorf("cooked recipe list response recipe %d missing title", index)
419 }
420 }
421
422 return nil
423}
424
425func jsonNumberToInt(number json.Number) (int, error) {
426 text := number.String()
427 if text == "" {
428 return 0, fmt.Errorf("missing")
429 }
430
431 rational, ok := new(big.Rat).SetString(text)
432 if !ok {
433 return 0, fmt.Errorf("invalid JSON number %q", text)
434 }
435 if !rational.IsInt() {
436 return 0, fmt.Errorf("must be integer-valued, got %s", text)
437 }
438
439 integer := rational.Num()
440 if !integer.IsInt64() {
441 return 0, fmt.Errorf("out of range, got %s", text)
442 }
443
444 value := integer.Int64()
445 maxInt := int64(1<<(strconv.IntSize-1) - 1)
446 minInt := -maxInt - 1
447 if value < minInt || value > maxInt {
448 return 0, fmt.Errorf("out of range for int, got %s", text)
449 }
450
451 return int(value), nil
452}
453
454func (c *Client) doAuthenticated(
455 ctx context.Context,
456 method, path string,
457 body []byte,
458 decodeResponse responseDecoder,
459) error {
460 c.requestMu.Lock()
461 defer c.requestMu.Unlock()
462
463 if err := c.ensureLogin(ctx); err != nil {
464 return err
465 }
466
467 err := c.do(ctx, method, c.userPath(path), body, decodeResponse)
468 if !isUnauthorized(err) {
469 return err
470 }
471
472 c.resetSession()
473 if err := c.ensureLogin(ctx); err != nil {
474 return err
475 }
476
477 return c.do(ctx, method, c.userPath(path), body, decodeResponse)
478}
479
480func (c *Client) ensureLogin(ctx context.Context) error {
481 authenticated := c.authenticatedUsername != ""
482 if authenticated {
483 return nil
484 }
485
486 body, err := json.Marshal(loginRequest{Username: c.username, Password: c.password})
487 if err != nil {
488 return fmt.Errorf("encode Cooked login request: %w", err)
489 }
490
491 var login loginResponse
492 decodeLogin := func(decoder *json.Decoder) error {
493 return decoder.Decode(&login)
494 }
495 if err := c.do(ctx, http.MethodPost, "/api/public/login", body, decodeLogin); err != nil {
496 return fmt.Errorf("authenticate with Cooked: %w", err)
497 }
498 if login.Username == "" {
499 return fmt.Errorf("authenticate with Cooked: missing username in login response")
500 }
501
502 c.authenticatedUsername = login.Username
503
504 return nil
505}
506
507func (c *Client) resetSession() {
508 jar, err := newCookieJar()
509 if err != nil {
510 return
511 }
512
513 c.authenticatedUsername = ""
514 c.http = &http.Client{Jar: jar, Timeout: c.http.Timeout}
515}
516
517func (c *Client) do(ctx context.Context, method, path string, body []byte, decodeResponse responseDecoder) error {
518 request, err := c.newRequest(ctx, method, path, body)
519 if err != nil {
520 return err
521 }
522
523 response, err := c.http.Do(request)
524 if err != nil {
525 return fmt.Errorf("call Cooked: %w", err)
526 }
527 defer func() {
528 _ = response.Body.Close()
529 }()
530
531 if response.StatusCode < http.StatusOK || response.StatusCode >= http.StatusMultipleChoices {
532 return decodeError(response)
533 }
534
535 if decodeResponse == nil {
536 return nil
537 }
538 if err := decodeResponse(json.NewDecoder(io.LimitReader(response.Body, maxResponseBytes))); err != nil {
539 return fmt.Errorf("decode Cooked response: %w", err)
540 }
541
542 return nil
543}
544
545func (c *Client) newRequest(ctx context.Context, method, path string, body []byte) (*http.Request, error) {
546 relativeURL, err := url.Parse(path)
547 if err != nil {
548 return nil, fmt.Errorf("parse Cooked request path: %w", err)
549 }
550 requestURL := c.baseURL.ResolveReference(relativeURL)
551
552 var reader io.Reader
553 if body != nil {
554 reader = bytes.NewReader(body)
555 }
556
557 request, err := http.NewRequestWithContext(ctx, method, requestURL.String(), reader)
558 if err != nil {
559 return nil, fmt.Errorf("build Cooked request: %w", err)
560 }
561 request.Header.Set("Accept", "application/json")
562 if body != nil {
563 request.Header.Set("Content-Type", "application/json")
564 }
565
566 return request, nil
567}
568
569func (c *Client) userPath(path string) string {
570 username := c.authenticatedUsername
571
572 return strings.ReplaceAll(path, "{username}", url.PathEscape(username))
573}
574
575type responseDecoder func(*json.Decoder) error
576
577type shoppingListResponse struct {
578 ShoppingList ShoppingList `json:"shopping-list"`
579 Recipes []string `json:"recipes"`
580}
581
582type addShoppingListRequest struct {
583 Ingredients string `json:"ingredients"`
584 RecipeID string `json:"recipe-id,omitempty"`
585}
586
587type addShoppingListResponse struct {
588 AddedCount *int `json:"added-count"`
589 Ingredients []string `json:"ingredients"`
590}
591
592type removeShoppingListProductGroupsRequest struct {
593 IDs []string `json:"ids"`
594}
595
596type replaceShoppingListSelectionRequest struct {
597 Selected []string `json:"selected"`
598}
599
600type updateShoppingListProductGroupRequest struct {
601 Name string `json:"name"`
602 Quantity string `json:"quantity"`
603 AisleID string `json:"aisle-id"`
604 Selected bool `json:"selected"`
605}
606
607type previewRecipeTextRequest struct {
608 RecipeName string `json:"recipe-name"`
609 RecipeText string `json:"recipe-text"`
610}
611
612type savePreparedRecipeRequest struct {
613 Title string `json:"title"`
614 Description string `json:"description"`
615 Portions int `json:"portions"`
616}
617
618type recipeContentRequest struct {
619 Description string `json:"description"`
620 Portions int `json:"portions"`
621}
622
623type importRecipeURLRequest struct {
624 URL string `json:"url"`
625}
626
627type importRecipeURLResponse struct {
628 RecipeID string `json:"recipe-id"`
629 ExtractionID string `json:"extraction-id"`
630}
631
632type saveRecipeResponse struct {
633 RecipeID string `json:"recipe-id"`
634}
635
636type loginRequest struct {
637 Username string `json:"username"`
638 Password string `json:"password"`
639}
640
641type loginResponse struct {
642 Username string `json:"username"`
643}
644
645type cookedError struct {
646 StatusCode int
647 Code string
648 Message string
649}
650
651func (e cookedError) Error() string {
652 var parts []string
653 parts = append(parts, fmt.Sprintf("Cooked returned HTTP %d", e.StatusCode))
654 if e.Code != "" {
655 parts = append(parts, e.Code)
656 }
657 if e.Message != "" {
658 parts = append(parts, e.Message)
659 }
660
661 return strings.Join(parts, ": ")
662}
663
664func decodeError(response *http.Response) error {
665 var payload struct {
666 Code string `json:"code"`
667 Message string `json:"message"`
668 }
669 _ = json.NewDecoder(io.LimitReader(response.Body, 64*1024)).Decode(&payload)
670
671 return cookedError{
672 StatusCode: response.StatusCode,
673 Code: payload.Code,
674 Message: payload.Message,
675 }
676}
677
678func isUnauthorized(err error) bool {
679 if err == nil {
680 return false
681 }
682
683 var cookedErr cookedError
684 if !errors.As(err, &cookedErr) {
685 return false
686 }
687
688 return cookedErr.StatusCode == http.StatusUnauthorized
689}
690
691func newCookieJar() (*cookiejar.Jar, error) {
692 return cookiejar.New(&cookiejar.Options{PublicSuffixList: publicsuffix.List})
693}