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