Debian Codegraph @

cookidoo_api/helpers.py

raw
1 """Cookidoo API helpers."""
2
3 from collections.abc import Mapping, Sequence
4 from datetime import UTC, datetime
5 import json
6 import logging
7 import os
8 from typing import cast
9 from urllib.parse import urlparse
10
11 import aiofiles
12 import isodate
13
14 from cookidoo_api.raw_types import (
15 AdditionalItemJSON,
16 CalendarDayJSON,
17 CalenderDayRecipeJSON,
18 CommunityProfileJSON,
19 CustomCollectionJSON,
20 CustomRecipeContentJSON,
21 CustomRecipeJSON,
22 CustomRecipeTextJSON,
23 DescriptiveAssetJSON,
24 IngredientJSON,
25 ItemJSON,
26 ManagedCollectionJSON,
27 QuantityJSON,
28 RecipeDetailsJSON,
29 RecipeJSON,
30 SearchRecipeHitJSON,
31 SearchResultJSON,
32 SubscriptionJSON,
33 )
34 from cookidoo_api.types import (
35 CookidooAdditionalItem,
36 CookidooCalendarDay,
37 CookidooCalendarDayRecipe,
38 CookidooCategory,
39 CookidooChapter,
40 CookidooChapterRecipe,
41 CookidooCollection,
42 CookidooCookingActivity,
43 CookidooCookState,
44 CookidooCustomRecipe,
45 CookidooDevice,
46 CookidooIngredient,
47 CookidooIngredientItem,
48 CookidooLocalizationConfig,
49 CookidooNutrition,
50 CookidooNutritionGroup,
51 CookidooRecipeCollection,
52 CookidooRecipeNutrition,
53 CookidooRecipeStep,
54 CookidooRecipeStepGroup,
55 CookidooSearchRecipeHit,
56 CookidooSearchResult,
57 CookidooShoppingRecipe,
58 CookidooShoppingRecipeDetails,
59 CookidooSubscription,
60 CookidooUserInfo,
61 ThermomixMachineType,
62 )
63
64 _LOGGER = logging.getLogger(__name__)
65
66 localization_file_path = os.path.join(os.path.dirname(__file__), "localization.json")
67
68
69 def normalize_list_param(value: str | list[str] | None) -> str | None:
70 """Normalize list/string params to comma-separated string."""
71 if value is None:
72 return None
73 if isinstance(value, list):
74 return ",".join([v for v in value if v])
75 return value
76
77
78 def normalize_tmv_param(
79 value: ThermomixMachineType | str | list[ThermomixMachineType | str] | None,
80 ) -> str | None:
81 """Normalize TMV param to comma-separated string."""
82 if value is None:
83 return None
84 if isinstance(value, list):
85 normalized: list[str] = []
86 for item in value:
87 normalized.append(
88 item.value if isinstance(item, ThermomixMachineType) else str(item)
89 )
90 return ",".join([v for v in normalized if v])
91 return value.value if isinstance(value, ThermomixMachineType) else value
92
93
94 def cookidoo_user_info_from_json(
95 profile: CommunityProfileJSON,
96 ) -> CookidooUserInfo:
97 """Convert a community profile received from the API to a cookidoo user info."""
98 user_info = profile["userInfo"]
99 return CookidooUserInfo(
100 id=profile["id"],
101 username=user_info["username"],
102 description=user_info.get("description"),
103 picture=user_info["picture"],
104 )
105
106
107 def cookidoo_subscription_from_json(
108 subscription: SubscriptionJSON,
109 ) -> CookidooSubscription:
110 """Convert a subscription received from the API to a cookidoo subscription."""
111 return CookidooSubscription(
112 active=subscription["active"],
113 expires=subscription["expires"],
114 start_date=subscription["startDate"],
115 status=subscription["status"],
116 subscription_level=subscription["subscriptionLevel"],
117 subscription_source=subscription["subscriptionSource"],
118 type=subscription["type"],
119 extended_type=subscription["extendedType"],
120 )
121
122
123 def cookidoo_device_from_json(model: str) -> CookidooDevice:
124 """Convert a device machine type received from the API to a cookidoo device.
125
126 The devices endpoint returns bare machine-type strings (e.g. ``"TM7"``).
127 """
128 return CookidooDevice(type=ThermomixMachineType(model))
129
130
131 def _push_timestamp(value: object) -> datetime | None:
132 """Parse a push timestamp (ISO-8601 or epoch millis/seconds)."""
133 if value is None or value == "":
134 return None
135 if isinstance(value, (int, float)):
136 seconds = value / 1000.0 if value > 1e12 else float(value)
137 return datetime.fromtimestamp(seconds, tz=UTC)
138 if isinstance(value, str):
139 text = value.strip()
140 if text.isdigit():
141 return _push_timestamp(int(text))
142 try:
143 return datetime.fromisoformat(text.replace("Z", "+00:00"))
144 except ValueError:
145 return None
146 return None
147
148
149 def _push_number(value: object) -> float | None:
150 """Parse a numeric display field; the app uses ``"---"`` for 'no value'."""
151 if value is None:
152 return None
153 if isinstance(value, (int, float)):
154 return float(value)
155 text = str(value).strip()
156 if not text or set(text) <= {"-", "–", "—"}:
157 return None
158 try:
159 return float(text.replace(",", "."))
160 except ValueError:
161 return None
162
163
164 def _push_bool(value: object) -> bool:
165 """Parse a boolean; push values are strings, so ``"false"`` must be falsy."""
166 if isinstance(value, bool):
167 return value
168 if isinstance(value, str):
169 return value.strip().lower() in ("true", "1", "yes")
170 return bool(value)
171
172
173 def cooking_activity_from_push(
174 data: Mapping[str, object],
175 ) -> CookidooCookingActivity:
176 """Convert a remote-monitoring push payload into a cooking activity.
177
178 Appliance state is delivered out of band (a Firebase Cloud Messaging data
179 message) rather than as an HTTP response, so consumers receive it via their
180 own push channel and decode it here. Both the on-the-wire field names
181 (``leadingText``/``trailingText``/``completedDate``/``staleDate``/…) and the
182 app's parsed names are accepted.
183 """
184
185 def first(*keys: str) -> object:
186 for key in keys:
187 if key in data and data[key] is not None:
188 return data[key]
189 return None
190
191 remaining_raw = first("remainingDuration")
192 remaining: int | None = None
193 if isinstance(remaining_raw, (int, str)):
194 try:
195 remaining = int(remaining_raw)
196 except ValueError:
197 remaining = None
198 completed_at = _push_timestamp(first("completedDate", "completedTimestamp"))
199 end_at = _push_timestamp(first("endTimestamp"))
200 # The wire payload has no remainingDuration; derive it from the finish time.
201 if remaining is None:
202 finish = completed_at or end_at
203 if finish is not None:
204 remaining = max(0, int((finish - datetime.now(UTC)).total_seconds()))
205
206 state_raw = first("state")
207 state = CookidooCookState(str(state_raw).upper()) if state_raw is not None else None
208 recipe_type = first("recipeType")
209
210 return CookidooCookingActivity(
211 device_id=str(first("deviceId") or ""),
212 cooking_activity_id=cast("str | None", first("cookingActivityId")),
213 state=state,
214 recipe_id=cast("str | None", first("recipeId")),
215 recipe_type=str(recipe_type).upper() if recipe_type is not None else None,
216 recipe_name=cast(
217 "str | None", first("leadingText", "leadingInfoText", "infoText")
218 ),
219 step=cast("str | None", first("trailingText", "trailingInfoText")),
220 remaining_seconds=remaining,
221 is_time_estimated=_push_bool(data.get("isTimeEstimated", False)),
222 current_temperature=_push_number(first("primaryInfo")),
223 target_temperature=_push_number(first("secondaryInfo")),
224 message_title=cast("str | None", first("messageTitle")),
225 message_body=cast("str | None", first("messageBody")),
226 message_criticality=cast("str | None", first("messageCriticality")),
227 completed_at=completed_at,
228 stale_at=_push_timestamp(first("staleDate", "staleTimestamp")),
229 )
230
231
232 def cookidoo_collection_from_json(
233 collection: CustomCollectionJSON | ManagedCollectionJSON,
234 ) -> CookidooCollection:
235 """Convert a collection received from the API to a cookidoo collection."""
236 return CookidooCollection(
237 id=collection["id"],
238 name=collection["title"],
239 description=cast(str, collection.get("description", None)),
240 chapters=[
241 CookidooChapter(
242 name=chapter["title"],
243 recipes=[
244 CookidooChapterRecipe(
245 id=recipe["id"],
246 name=recipe["title"],
247 total_time=int(float(recipe["totalTime"])),
248 )
249 for recipe in chapter["recipes"]
250 ],
251 )
252 for chapter in collection["chapters"]
253 ],
254 )
255
256
257 def _process_image_url(url: str) -> tuple[str, str]:
258 """Process image URL by replacing transformation placeholders.
259
260 Returns
261 -------
262 tuple[str, str]
263 A tuple of (thumbnail_url, image_url) where:
264 - thumbnail_url uses t_web_shared_recipe_221x240 transformation
265 - image_url uses t_web_rdp_recipe_584x480_1_5x transformation
266
267 """
268 thumbnail = url.replace("{transformation}", "t_web_shared_recipe_221x240")
269 image = url.replace("{transformation}", "t_web_rdp_recipe_584x480_1_5x")
270 return thumbnail, image
271
272
273 def _extract_images_from_descriptive_assets(
274 descriptive_assets: list[DescriptiveAssetJSON],
275 ) -> tuple[str | None, str | None]:
276 """Extract thumbnail and image URLs from descriptive assets.
277
278 Returns
279 -------
280 tuple[str | None, str | None]
281 A tuple of (thumbnail_url, image_url) extracted from the first
282 available image URL in descriptive assets.
283
284 """
285 thumbnail: str | None = None
286 image: str | None = None
287
288 # Get the first available image URL from any variant
289 for asset in descriptive_assets:
290 _LOGGER.debug(asset)
291 for variant, url in asset.items():
292 _LOGGER.debug(variant)
293 if url and variant in ("square", "portrait", "landscape"):
294 thumbnail, image = _process_image_url(str(url))
295 break
296 if thumbnail:
297 break
298
299 return thumbnail, image
300
301
302 def _construct_recipe_url(
303 localization: CookidooLocalizationConfig | None,
304 recipe_id: str,
305 path_prefix: str = "recipes/recipe",
306 ) -> str:
307 """Construct a recipe URL from localization config and recipe ID.
308
309 Parameters
310 ----------
311 localization
312 The localization config containing the domain and language.
313 recipe_id
314 The recipe ID to use in the URL.
315 path_prefix
316 The path prefix for the recipe URL. Defaults to "recipes/recipe".
317
318 Returns
319 -------
320 str
321 The constructed recipe URL, or empty string if localization is None.
322
323 """
324 if not localization:
325 return ""
326
327 parsed_url = urlparse(localization.url)
328 domain = parsed_url.netloc
329 return f"https://{domain}/{path_prefix}/{localization.language}/{recipe_id}"
330
331
332 def cookidoo_recipe_from_json(
333 recipe: RecipeJSON,
334 localization: CookidooLocalizationConfig | None = None,
335 ) -> CookidooShoppingRecipe:
336 """Convert a shopping recipe received from the API to a cookidoo shopping recipe."""
337 thumbnail, image = None, None
338 descriptive_assets = recipe.get("descriptiveAssets")
339 if descriptive_assets is not None:
340 thumbnail, image = _extract_images_from_descriptive_assets(descriptive_assets)
341 url = _construct_recipe_url(localization, recipe["id"])
342
343 return CookidooShoppingRecipe(
344 id=recipe["id"],
345 name=recipe["title"],
346 ingredients=[
347 cookidoo_ingredient_from_json(ingredient)
348 for ingredient in recipe["recipeIngredientGroups"]
349 ],
350 thumbnail=thumbnail,
351 image=image,
352 url=url,
353 )
354
355
356 def cookidoo_search_result_from_json(
357 data: SearchResultJSON,
358 localization: CookidooLocalizationConfig | None = None,
359 ) -> CookidooSearchResult:
360 """Convert a search result received from the API to a CookidooSearchResult.
361
362 The API may return recipes in ``data`` (search endpoint) or ``recipes``;
363 total is optional and defaults to the number of valid parsed hits.
364
365 Parameters
366 ----------
367 data
368 The raw JSON response from the search API.
369 localization
370 Optional localization config used to construct recipe URLs.
371
372 Returns
373 -------
374 CookidooSearchResult
375 The parsed search result with recipe hits and total count.
376
377 """
378 if "data" in data:
379 raw_recipes: list[SearchRecipeHitJSON] = data["data"] or []
380 elif "recipes" in data:
381 raw_recipes = data["recipes"] or []
382 else:
383 raw_recipes = []
384 recipes_data: list[object] = list(raw_recipes)
385 total_raw = data.get("total")
386 hits: list[CookidooSearchRecipeHit] = []
387 for item in recipes_data:
388 if not isinstance(item, dict):
389 continue
390 recipe_id = item.get("id", "")
391 name = item.get("title") or item.get("name", "")
392 thumbnail, image = None, None
393 descriptive_assets = item.get("descriptiveAssets")
394 if descriptive_assets and isinstance(descriptive_assets, list):
395 thumbnail, image = _extract_images_from_descriptive_assets(
396 descriptive_assets
397 )
398 url = _construct_recipe_url(localization, recipe_id)
399 hits.append(
400 CookidooSearchRecipeHit(
401 id=recipe_id,
402 name=name,
403 thumbnail=thumbnail,
404 image=image,
405 url=url,
406 )
407 )
408 total = total_raw if isinstance(total_raw, int) else len(hits)
409 return CookidooSearchResult(recipes=hits, total=total)
410
411
412 def cookidoo_quantity_from_json(
413 quantity: QuantityJSON,
414 ) -> str:
415 """Convert an quantity received from the API to a str."""
416 if "value" in quantity and quantity["value"]:
417 return str(quantity["value"])
418 elif (
419 "from" in quantity and "to" in quantity and quantity["from"] and quantity["to"]
420 ):
421 return f"{quantity['from']} - {quantity['to']}"
422 else:
423 return ""
424
425
426 def cookidoo_recipe_details_from_json(
427 recipe: RecipeDetailsJSON,
428 localization: CookidooLocalizationConfig | None = None,
429 ) -> CookidooShoppingRecipeDetails:
430 """Convert an recipe details received from the API to a cookidoo recipe details."""
431 thumbnail, image = None, None
432 descriptive_assets = recipe.get("descriptiveAssets")
433 if descriptive_assets is not None:
434 thumbnail, image = _extract_images_from_descriptive_assets(descriptive_assets)
435 url = _construct_recipe_url(localization, recipe["id"])
436
437 active_time = next(
438 (
439 time_["quantity"]["value"]
440 for time_ in recipe["times"]
441 if time_["type"] == "activeTime" and time_["quantity"]["value"]
442 ),
443 None,
444 )
445 if active_time is None:
446 raise ValueError(
447 "Recipe details response is missing a non-null 'activeTime' entry in 'times'."
448 )
449 total_time = next(
450 (
451 time_["quantity"]["value"]
452 for time_ in recipe["times"]
453 if time_["type"] == "totalTime" and time_["quantity"]["value"]
454 ),
455 None,
456 )
457 if total_time is None:
458 raise ValueError(
459 "Recipe details response is missing a non-null 'totalTime' entry in 'times'."
460 )
461
462 return CookidooShoppingRecipeDetails(
463 id=recipe["id"],
464 name=recipe["title"],
465 ingredients=[
466 cookidoo_ingredient_from_json(ingredient)
467 for ingredientGroup in recipe["recipeIngredientGroups"]
468 for ingredient in ingredientGroup["recipeIngredients"]
469 ],
470 difficulty=recipe["difficulty"],
471 notes=[
472 additional_notes["content"]
473 for additional_notes in recipe["additionalInformation"]
474 ],
475 categories=[
476 CookidooCategory(
477 id=category["id"], name=category["title"], notes=category["subtitle"]
478 )
479 for category in recipe["categories"]
480 ],
481 collections=[
482 CookidooRecipeCollection(
483 id=collection["id"],
484 name=collection["title"],
485 total_recipes=collection["recipesCount"]["value"],
486 )
487 for collection in recipe["inCollections"]
488 ],
489 utensils=[utensil["utensilNotation"] for utensil in recipe["recipeUtensils"]],
490 serving_size=recipe["servingSize"]["quantity"]["value"] or 0,
491 active_time=active_time,
492 total_time=total_time,
493 nutrition_groups=[
494 CookidooNutritionGroup(
495 name=ng["name"],
496 recipe_nutritions=[
497 CookidooRecipeNutrition(
498 nutritions=[
499 CookidooNutrition(
500 number=n["number"],
501 type=n["type"],
502 unittype=n["unittype"],
503 )
504 for n in rn["nutritions"]
505 ],
506 quantity=rn["quantity"],
507 unit_notation=rn["unitNotation"],
508 )
509 for rn in ng["recipeNutritions"]
510 ],
511 )
512 for ng in recipe.get("nutritionGroups", [])
513 ],
514 step_groups=[
515 CookidooRecipeStepGroup(
516 title=sg["title"],
517 recipe_steps=[
518 CookidooRecipeStep(
519 title=step["title"],
520 formatted_text=step["formattedText"],
521 )
522 for step in sg["recipeSteps"]
523 ],
524 )
525 for sg in recipe.get("recipeStepGroups", [])
526 ],
527 thumbnail=thumbnail,
528 image=image,
529 url=url,
530 )
531
532
533 def cookidoo_custom_recipe_from_json(
534 recipe: CustomRecipeJSON,
535 localization: CookidooLocalizationConfig | None = None,
536 ) -> CookidooCustomRecipe:
537 """Convert a custom recipe received from the API to a cookidoo custom recipe."""
538 def _duration_to_seconds(value: str | int | float | None) -> int:
539 if value is None:
540 return 0
541
542 if isinstance(value, int | float):
543 return int(value)
544
545 duration = isodate.parse_duration(value).total_seconds()
546 return int(duration) if isinstance(duration, float) else 0
547
548 def _extract_text_list(
549 value: Sequence[str | CustomRecipeTextJSON],
550 ) -> list[str]:
551 return [item["text"] if isinstance(item, dict) else item for item in value]
552
553 recipe_content: CustomRecipeContentJSON = recipe["recipeContent"]
554 total_time = _duration_to_seconds(recipe_content.get("totalTime"))
555 active_time = _duration_to_seconds(recipe_content.get("prepTime"))
556
557 thumbnail: str | None = None
558 image: str | None = None
559
560 image = recipe_content.get("image", None)
561 if image:
562 thumbnail, image = _process_image_url(image)
563
564 url = _construct_recipe_url(localization, recipe["recipeId"], "created-recipes")
565 recipe_yield = (
566 recipe_content.get("recipeYield")
567 or recipe_content.get("yield")
568 or {"value": 0, "unitText": ""}
569 )
570
571 return CookidooCustomRecipe(
572 id=recipe["recipeId"],
573 name=recipe_content["name"],
574 ingredients=_extract_text_list(
575 recipe_content.get("recipeIngredient")
576 or recipe_content.get("ingredients", [])
577 ),
578 instructions=_extract_text_list(
579 recipe_content.get("recipeInstructions")
580 or recipe_content.get("instructions", [])
581 ),
582 serving_size=recipe_yield["value"],
583 total_time=total_time,
584 active_time=active_time,
585 tools=recipe_content.get("tool") or recipe_content.get("tools", []),
586 thumbnail=thumbnail,
587 image=image,
588 url=url,
589 )
590
591
592 def cookidoo_ingredient_from_json(
593 ingredient: IngredientJSON | ItemJSON,
594 ) -> CookidooIngredient:
595 """Convert an ingredient received from the API to a cookidoo ingredient."""
596 return CookidooIngredient(
597 id=ingredient["localId"] if "localId" in ingredient else ingredient["id"], # type: ignore[typeddict-item]
598 name=ingredient["ingredientNotation"],
599 description=f"{cookidoo_quantity_from_json(ingredient['quantity'])} {ingredient['unitNotation']}"
600 if "unitNotation" in ingredient
601 and ingredient["unitNotation"]
602 and "quantity" in ingredient
603 and ingredient["quantity"]
604 else cookidoo_quantity_from_json(ingredient["quantity"])
605 if "quantity" in ingredient and ingredient["quantity"]
606 else "",
607 )
608
609
610 def cookidoo_ingredient_item_from_json(
611 item: ItemJSON,
612 ) -> CookidooIngredientItem:
613 """Convert an ingredient item received from the API to a cookidoo item."""
614 return CookidooIngredientItem(
615 id=item["id"],
616 name=item["ingredientNotation"],
617 is_owned=item["isOwned"],
618 description=f"{cookidoo_quantity_from_json(item['quantity'])} {item['unitNotation']}"
619 if "unitNotation" in item
620 and item["unitNotation"]
621 and "quantity" in item
622 and item["quantity"]
623 else str(cookidoo_quantity_from_json(item["quantity"]))
624 if "quantity" in item and item["quantity"]
625 else "",
626 )
627
628
629 def cookidoo_additional_item_from_json(
630 item: AdditionalItemJSON,
631 ) -> CookidooAdditionalItem:
632 """Convert an additional item received from the API to a cookidoo item."""
633 return CookidooAdditionalItem(
634 id=item["id"],
635 name=item["name"],
636 is_owned=item["isOwned"],
637 )
638
639
640 def cookidoo_calendar_day_from_json(
641 calendar_day: CalendarDayJSON,
642 localization: CookidooLocalizationConfig | None = None,
643 ) -> CookidooCalendarDay:
644 """Convert a calendar day received from the API to a cookidoo item."""
645
646 def _to_day_recipe(recipe: CalenderDayRecipeJSON) -> CookidooCalendarDayRecipe:
647 assets = recipe["assets"]
648 thumbnail, image = None, None
649 descriptive_assets = [assets["images"]] if assets and assets["images"] else None
650 if descriptive_assets is not None:
651 thumbnail, image = _extract_images_from_descriptive_assets(
652 descriptive_assets
653 )
654
655 url = _construct_recipe_url(localization, recipe["id"])
656
657 return CookidooCalendarDayRecipe(
658 id=recipe["id"],
659 name=recipe["title"],
660 total_time=recipe["totalTime"],
661 thumbnail=thumbnail,
662 image=image,
663 url=url,
664 )
665
666 regular_recipes = [_to_day_recipe(recipe) for recipe in calendar_day["recipes"]]
667 custom_recipes = [
668 _to_day_recipe(recipe) for recipe in calendar_day.get("customerRecipes", [])
669 ]
670
671 return CookidooCalendarDay(
672 id=calendar_day["id"],
673 title=calendar_day["title"],
674 recipes=[*regular_recipes, *custom_recipes],
675 customer_recipe_ids=list(calendar_day.get("customerRecipeIds", [])),
676 )
677
678
679 async def __get_localization_options(
680 country: str | None = None,
681 language: str | None = None,
682 ) -> list[CookidooLocalizationConfig]:
683 async with aiofiles.open(localization_file_path, encoding="utf-8") as file:
684 options_ = cast(list[dict[str, str]], json.loads(await file.read()))
685 options = (CookidooLocalizationConfig(**x) for x in options_)
686 filtered_options = filter(
687 lambda option: (
688 (not country or option.country_code == country)
689 and (not language or option.language == language)
690 ),
691 options,
692 )
693 return list(cast(list[CookidooLocalizationConfig], filtered_options))
694
695
696 async def get_localization_options(
697 country: str | None = None,
698 language: str | None = None,
699 ) -> list[CookidooLocalizationConfig]:
700 """Get a list of possible localization options."""
701 return await __get_localization_options(country, language)
702
703
704 async def get_country_options() -> list[str]:
705 """Get a list of possible country options."""
706 return list({option.country_code for option in await get_localization_options()})
707
708
709 async def get_language_options() -> list[str]:
710 """Get a list of possible language options."""
711 return list({option.language for option in await get_localization_options()})