client.go

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