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