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
219func (c *Client) getRecipes(ctx context.Context, path string) ([]RecipeCard, error) {
220	var response recipeListResponse
221	decodeRecipes := func(decoder *json.Decoder) error {
222		return decoder.Decode(&response)
223	}
224	if err := c.doAuthenticated(ctx, http.MethodGet, path, nil, decodeRecipes); err != nil {
225		return nil, err
226	}
227
228	return response.Recipes, nil
229}
230
231func (c *Client) doAuthenticated(
232	ctx context.Context,
233	method, path string,
234	body []byte,
235	decodeResponse responseDecoder,
236) error {
237	c.requestMu.Lock()
238	defer c.requestMu.Unlock()
239
240	if err := c.ensureLogin(ctx); err != nil {
241		return err
242	}
243
244	err := c.do(ctx, method, c.userPath(path), body, decodeResponse)
245	if !isUnauthorized(err) {
246		return err
247	}
248
249	c.resetSession()
250	if err := c.ensureLogin(ctx); err != nil {
251		return err
252	}
253
254	return c.do(ctx, method, c.userPath(path), body, decodeResponse)
255}
256
257func (c *Client) ensureLogin(ctx context.Context) error {
258	authenticated := c.authenticatedUsername != ""
259	if authenticated {
260		return nil
261	}
262
263	body, err := json.Marshal(loginRequest{Username: c.username, Password: c.password})
264	if err != nil {
265		return fmt.Errorf("encode Cooked login request: %w", err)
266	}
267
268	var login loginResponse
269	decodeLogin := func(decoder *json.Decoder) error {
270		return decoder.Decode(&login)
271	}
272	if err := c.do(ctx, http.MethodPost, "/api/public/login", body, decodeLogin); err != nil {
273		return fmt.Errorf("authenticate with Cooked: %w", err)
274	}
275	if login.Username == "" {
276		return fmt.Errorf("authenticate with Cooked: missing username in login response")
277	}
278
279	c.authenticatedUsername = login.Username
280
281	return nil
282}
283
284func (c *Client) resetSession() {
285	jar, err := newCookieJar()
286	if err != nil {
287		return
288	}
289
290	c.authenticatedUsername = ""
291	c.http = &http.Client{Jar: jar, Timeout: c.http.Timeout}
292}
293
294func (c *Client) do(ctx context.Context, method, path string, body []byte, decodeResponse responseDecoder) error {
295	request, err := c.newRequest(ctx, method, path, body)
296	if err != nil {
297		return err
298	}
299
300	response, err := c.http.Do(request)
301	if err != nil {
302		return fmt.Errorf("call Cooked: %w", err)
303	}
304	defer func() {
305		_ = response.Body.Close()
306	}()
307
308	if response.StatusCode < http.StatusOK || response.StatusCode >= http.StatusMultipleChoices {
309		return decodeError(response)
310	}
311
312	if decodeResponse == nil {
313		return nil
314	}
315	if err := decodeResponse(json.NewDecoder(io.LimitReader(response.Body, maxResponseBytes))); err != nil {
316		return fmt.Errorf("decode Cooked response: %w", err)
317	}
318
319	return nil
320}
321
322func (c *Client) newRequest(ctx context.Context, method, path string, body []byte) (*http.Request, error) {
323	relativeURL, err := url.Parse(path)
324	if err != nil {
325		return nil, fmt.Errorf("parse Cooked request path: %w", err)
326	}
327	requestURL := c.baseURL.ResolveReference(relativeURL)
328
329	var reader io.Reader
330	if body != nil {
331		reader = bytes.NewReader(body)
332	}
333
334	request, err := http.NewRequestWithContext(ctx, method, requestURL.String(), reader)
335	if err != nil {
336		return nil, fmt.Errorf("build Cooked request: %w", err)
337	}
338	request.Header.Set("Accept", "application/json")
339	if body != nil {
340		request.Header.Set("Content-Type", "application/json")
341	}
342
343	return request, nil
344}
345
346func (c *Client) userPath(path string) string {
347	username := c.authenticatedUsername
348
349	return strings.ReplaceAll(path, "{username}", url.PathEscape(username))
350}
351
352type responseDecoder func(*json.Decoder) error
353
354type shoppingListResponse struct {
355	ShoppingList ShoppingList `json:"shopping-list"`
356	Recipes      []string     `json:"recipes"`
357}
358
359type recipeListResponse struct {
360	Recipes []RecipeCard `json:"recipes"`
361}
362
363type previewRecipeTextRequest struct {
364	RecipeName string `json:"recipe-name"`
365	RecipeText string `json:"recipe-text"`
366}
367
368type savePreparedRecipeRequest struct {
369	Title       string `json:"title"`
370	Description string `json:"description"`
371	Portions    int    `json:"portions"`
372}
373
374type updateRecipeContentRequest struct {
375	Description string `json:"description"`
376	Portions    int    `json:"portions"`
377}
378
379type saveRecipeResponse struct {
380	RecipeID string `json:"recipe-id"`
381}
382
383type loginRequest struct {
384	Username string `json:"username"`
385	Password string `json:"password"`
386}
387
388type loginResponse struct {
389	Username string `json:"username"`
390}
391
392type cookedError struct {
393	StatusCode int
394	Code       string
395	Message    string
396}
397
398func (e cookedError) Error() string {
399	var parts []string
400	parts = append(parts, fmt.Sprintf("Cooked returned HTTP %d", e.StatusCode))
401	if e.Code != "" {
402		parts = append(parts, e.Code)
403	}
404	if e.Message != "" {
405		parts = append(parts, e.Message)
406	}
407
408	return strings.Join(parts, ": ")
409}
410
411func decodeError(response *http.Response) error {
412	var payload struct {
413		Code    string `json:"code"`
414		Message string `json:"message"`
415	}
416	_ = json.NewDecoder(io.LimitReader(response.Body, 64*1024)).Decode(&payload)
417
418	return cookedError{
419		StatusCode: response.StatusCode,
420		Code:       payload.Code,
421		Message:    payload.Message,
422	}
423}
424
425func isUnauthorized(err error) bool {
426	if err == nil {
427		return false
428	}
429
430	var cookedErr cookedError
431	if !errors.As(err, &cookedErr) {
432		return false
433	}
434
435	return cookedErr.StatusCode == http.StatusUnauthorized
436}
437
438func newCookieJar() (*cookiejar.Jar, error) {
439	return cookiejar.New(&cookiejar.Options{PublicSuffixList: publicsuffix.List})
440}