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