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// RecipeCard is a saved recipe summary returned by Cooked list and search endpoints.
 60type RecipeCard struct {
 61	ID           string `json:"id"`
 62	Title        string `json:"title"`
 63	ThumbnailURL string `json:"thumbnail-url,omitempty"`
 64}
 65
 66// RecipeMetadata is metadata for a Cooked recipe.
 67type RecipeMetadata struct {
 68	Title          string   `json:"title"`
 69	ImageURLs      []string `json:"image-urls"`
 70	Owner          string   `json:"owner"`
 71	EditPermission bool     `json:"edit-permission"`
 72}
 73
 74// RecipeContent is the Markdown-style body and portions for a Cooked recipe.
 75type RecipeContent struct {
 76	Content  string `json:"content"`
 77	Portions int    `json:"portions"`
 78}
 79
 80// RecipeTextPreview is Cooked's preview of raw recipe text before saving.
 81type RecipeTextPreview struct {
 82	Title    string `json:"title"`
 83	Markdown string `json:"markdown"`
 84	Portions int    `json:"portions"`
 85}
 86
 87// NewClient returns a Cooked client with an in-memory cookie jar.
 88func NewClient(baseURL *url.URL, username, password string) (*Client, error) {
 89	jar, err := newCookieJar()
 90	if err != nil {
 91		return nil, fmt.Errorf("create cookie jar: %w", err)
 92	}
 93
 94	return &Client{
 95		baseURL:  baseURL,
 96		username: username,
 97		password: password,
 98		http: &http.Client{
 99			Jar:     jar,
100			Timeout: 30 * time.Second,
101		},
102	}, nil
103}
104
105// ReadShoppingList logs in when needed and returns the authenticated user's shopping list.
106func (c *Client) ReadShoppingList(ctx context.Context) (ShoppingList, error) {
107	var response shoppingListResponse
108	decodeShoppingList := func(decoder *json.Decoder) error {
109		return decoder.Decode(&response)
110	}
111	if err := c.doAuthenticated(
112		ctx,
113		http.MethodGet,
114		"/api/user/{username}/shopping-list",
115		nil,
116		decodeShoppingList,
117	); err != nil {
118		return ShoppingList{}, err
119	}
120
121	response.ShoppingList.Recipes = response.Recipes
122	return response.ShoppingList, nil
123}
124
125// ListRecipes logs in when needed and returns one page of saved recipes.
126func (c *Client) ListRecipes(ctx context.Context, page, limit int) ([]RecipeCard, error) {
127	query := url.Values{}
128	query.Set("page", fmt.Sprintf("%d", page))
129	query.Set("page-count", fmt.Sprintf("%d", limit))
130
131	return c.getRecipes(ctx, "/api/user/{username}/recipes?"+query.Encode())
132}
133
134// SearchRecipes logs in when needed and searches the authenticated user's saved recipes.
135func (c *Client) SearchRecipes(ctx context.Context, queryText string, page int) ([]RecipeCard, error) {
136	query := url.Values{}
137	query.Set("q", queryText)
138	query.Set("page", fmt.Sprintf("%d", page))
139
140	return c.getRecipes(ctx, "/api/user/{username}/recipes/search?"+query.Encode())
141}
142
143// ReadRecipeMetadata logs in when needed and returns recipe metadata.
144func (c *Client) ReadRecipeMetadata(ctx context.Context, recipeID string) (RecipeMetadata, error) {
145	var metadata RecipeMetadata
146	decodeMetadata := func(decoder *json.Decoder) error {
147		return decoder.Decode(&metadata)
148	}
149	path := "/api/recipe/" + url.PathEscape(recipeID) + "/metadata"
150	if err := c.doAuthenticated(ctx, http.MethodGet, path, nil, decodeMetadata); err != nil {
151		return RecipeMetadata{}, err
152	}
153
154	return metadata, nil
155}
156
157// ReadRecipeContent logs in when needed and returns recipe content and portions.
158func (c *Client) ReadRecipeContent(ctx context.Context, recipeID string) (RecipeContent, error) {
159	var content RecipeContent
160	decodeContent := func(decoder *json.Decoder) error {
161		return decoder.Decode(&content)
162	}
163	path := "/api/recipe/" + url.PathEscape(recipeID) + "/content"
164	if err := c.doAuthenticated(ctx, http.MethodGet, path, nil, decodeContent); err != nil {
165		return RecipeContent{}, err
166	}
167
168	return content, nil
169}
170
171// PreviewRecipeText logs in when needed and previews raw recipe text without saving it.
172func (c *Client) PreviewRecipeText(ctx context.Context, title, text string) (RecipeTextPreview, error) {
173	body, err := json.Marshal(previewRecipeTextRequest{RecipeName: title, RecipeText: text})
174	if err != nil {
175		return RecipeTextPreview{}, fmt.Errorf("encode Cooked recipe text preview request: %w", err)
176	}
177
178	var preview RecipeTextPreview
179	decodePreview := func(decoder *json.Decoder) error {
180		return decoder.Decode(&preview)
181	}
182	if err := c.doAuthenticated(ctx, http.MethodPost, "/api/new/from-text/preview", body, decodePreview); err != nil {
183		return RecipeTextPreview{}, err
184	}
185
186	return preview, nil
187}
188
189// SavePreparedRecipe logs in when needed and saves prepared recipe markdown as a new recipe.
190func (c *Client) SavePreparedRecipe(ctx context.Context, title, markdown string, portions int) (string, error) {
191	body, err := json.Marshal(savePreparedRecipeRequest{Title: title, Description: markdown, Portions: portions})
192	if err != nil {
193		return "", fmt.Errorf("encode Cooked prepared recipe save request: %w", err)
194	}
195
196	var response saveRecipeResponse
197	decodeSave := func(decoder *json.Decoder) error {
198		return decoder.Decode(&response)
199	}
200	if err := c.doAuthenticated(ctx, http.MethodPost, "/api/recipe/import/save", body, decodeSave); err != nil {
201		return "", err
202	}
203
204	return response.RecipeID, nil
205}
206
207// UpdateRecipeContent logs in when needed and updates an existing recipe's content.
208func (c *Client) UpdateRecipeContent(ctx context.Context, recipeID, markdown string, portions int) error {
209	body, err := json.Marshal(updateRecipeContentRequest{Description: markdown, Portions: portions})
210	if err != nil {
211		return fmt.Errorf("encode Cooked recipe update request: %w", err)
212	}
213
214	path := "/api/recipe/" + url.PathEscape(recipeID) + "/content"
215
216	return c.doAuthenticated(ctx, http.MethodPost, path, body, nil)
217}
218
219// DeleteRecipe logs in when needed and deletes an existing recipe.
220func (c *Client) DeleteRecipe(ctx context.Context, recipeID string) error {
221	path := "/api/recipe/" + url.PathEscape(recipeID)
222
223	return c.doAuthenticated(ctx, http.MethodDelete, path, nil, nil)
224}
225
226func (c *Client) getRecipes(ctx context.Context, path string) ([]RecipeCard, error) {
227	var response recipeListResponse
228	decodeRecipes := func(decoder *json.Decoder) error {
229		return decoder.Decode(&response)
230	}
231	if err := c.doAuthenticated(ctx, http.MethodGet, path, nil, decodeRecipes); err != nil {
232		return nil, err
233	}
234
235	return response.Recipes, nil
236}
237
238func (c *Client) doAuthenticated(
239	ctx context.Context,
240	method, path string,
241	body []byte,
242	decodeResponse responseDecoder,
243) error {
244	c.requestMu.Lock()
245	defer c.requestMu.Unlock()
246
247	if err := c.ensureLogin(ctx); err != nil {
248		return err
249	}
250
251	err := c.do(ctx, method, c.userPath(path), body, decodeResponse)
252	if !isUnauthorized(err) {
253		return err
254	}
255
256	c.resetSession()
257	if err := c.ensureLogin(ctx); err != nil {
258		return err
259	}
260
261	return c.do(ctx, method, c.userPath(path), body, decodeResponse)
262}
263
264func (c *Client) ensureLogin(ctx context.Context) error {
265	authenticated := c.authenticatedUsername != ""
266	if authenticated {
267		return nil
268	}
269
270	body, err := json.Marshal(loginRequest{Username: c.username, Password: c.password})
271	if err != nil {
272		return fmt.Errorf("encode Cooked login request: %w", err)
273	}
274
275	var login loginResponse
276	decodeLogin := func(decoder *json.Decoder) error {
277		return decoder.Decode(&login)
278	}
279	if err := c.do(ctx, http.MethodPost, "/api/public/login", body, decodeLogin); err != nil {
280		return fmt.Errorf("authenticate with Cooked: %w", err)
281	}
282	if login.Username == "" {
283		return fmt.Errorf("authenticate with Cooked: missing username in login response")
284	}
285
286	c.authenticatedUsername = login.Username
287
288	return nil
289}
290
291func (c *Client) resetSession() {
292	jar, err := newCookieJar()
293	if err != nil {
294		return
295	}
296
297	c.authenticatedUsername = ""
298	c.http = &http.Client{Jar: jar, Timeout: c.http.Timeout}
299}
300
301func (c *Client) do(ctx context.Context, method, path string, body []byte, decodeResponse responseDecoder) error {
302	request, err := c.newRequest(ctx, method, path, body)
303	if err != nil {
304		return err
305	}
306
307	response, err := c.http.Do(request)
308	if err != nil {
309		return fmt.Errorf("call Cooked: %w", err)
310	}
311	defer func() {
312		_ = response.Body.Close()
313	}()
314
315	if response.StatusCode < http.StatusOK || response.StatusCode >= http.StatusMultipleChoices {
316		return decodeError(response)
317	}
318
319	if decodeResponse == nil {
320		return nil
321	}
322	if err := decodeResponse(json.NewDecoder(io.LimitReader(response.Body, maxResponseBytes))); err != nil {
323		return fmt.Errorf("decode Cooked response: %w", err)
324	}
325
326	return nil
327}
328
329func (c *Client) newRequest(ctx context.Context, method, path string, body []byte) (*http.Request, error) {
330	relativeURL, err := url.Parse(path)
331	if err != nil {
332		return nil, fmt.Errorf("parse Cooked request path: %w", err)
333	}
334	requestURL := c.baseURL.ResolveReference(relativeURL)
335
336	var reader io.Reader
337	if body != nil {
338		reader = bytes.NewReader(body)
339	}
340
341	request, err := http.NewRequestWithContext(ctx, method, requestURL.String(), reader)
342	if err != nil {
343		return nil, fmt.Errorf("build Cooked request: %w", err)
344	}
345	request.Header.Set("Accept", "application/json")
346	if body != nil {
347		request.Header.Set("Content-Type", "application/json")
348	}
349
350	return request, nil
351}
352
353func (c *Client) userPath(path string) string {
354	username := c.authenticatedUsername
355
356	return strings.ReplaceAll(path, "{username}", url.PathEscape(username))
357}
358
359type responseDecoder func(*json.Decoder) error
360
361type shoppingListResponse struct {
362	ShoppingList ShoppingList `json:"shopping-list"`
363	Recipes      []string     `json:"recipes"`
364}
365
366type recipeListResponse struct {
367	Recipes []RecipeCard `json:"recipes"`
368}
369
370type previewRecipeTextRequest struct {
371	RecipeName string `json:"recipe-name"`
372	RecipeText string `json:"recipe-text"`
373}
374
375type savePreparedRecipeRequest struct {
376	Title       string `json:"title"`
377	Description string `json:"description"`
378	Portions    int    `json:"portions"`
379}
380
381type updateRecipeContentRequest struct {
382	Description string `json:"description"`
383	Portions    int    `json:"portions"`
384}
385
386type saveRecipeResponse struct {
387	RecipeID string `json:"recipe-id"`
388}
389
390type loginRequest struct {
391	Username string `json:"username"`
392	Password string `json:"password"`
393}
394
395type loginResponse struct {
396	Username string `json:"username"`
397}
398
399type cookedError struct {
400	StatusCode int
401	Code       string
402	Message    string
403}
404
405func (e cookedError) Error() string {
406	var parts []string
407	parts = append(parts, fmt.Sprintf("Cooked returned HTTP %d", e.StatusCode))
408	if e.Code != "" {
409		parts = append(parts, e.Code)
410	}
411	if e.Message != "" {
412		parts = append(parts, e.Message)
413	}
414
415	return strings.Join(parts, ": ")
416}
417
418func decodeError(response *http.Response) error {
419	var payload struct {
420		Code    string `json:"code"`
421		Message string `json:"message"`
422	}
423	_ = json.NewDecoder(io.LimitReader(response.Body, 64*1024)).Decode(&payload)
424
425	return cookedError{
426		StatusCode: response.StatusCode,
427		Code:       payload.Code,
428		Message:    payload.Message,
429	}
430}
431
432func isUnauthorized(err error) bool {
433	if err == nil {
434		return false
435	}
436
437	var cookedErr cookedError
438	if !errors.As(err, &cookedErr) {
439		return false
440	}
441
442	return cookedErr.StatusCode == http.StatusUnauthorized
443}
444
445func newCookieJar() (*cookiejar.Jar, error) {
446	return cookiejar.New(&cookiejar.Options{PublicSuffixList: publicsuffix.List})
447}