| 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 |
|
| 539 |
def _duration_to_seconds(value: str | int | float | None) -> int: |
| 540 |
if value is None: |
| 541 |
return 0 |
| 542 |
|
| 543 |
if isinstance(value, int | float): |
| 544 |
return int(value) |
| 545 |
|
| 546 |
duration = isodate.parse_duration(value).total_seconds() |
| 547 |
return int(duration) if isinstance(duration, float) else 0 |
| 548 |
|
| 549 |
def _extract_text_list( |
| 550 |
value: Sequence[str | CustomRecipeTextJSON], |
| 551 |
) -> list[str]: |
| 552 |
return [item["text"] if isinstance(item, dict) else item for item in value] |
| 553 |
|
| 554 |
recipe_content: CustomRecipeContentJSON = recipe["recipeContent"] |
| 555 |
total_time = _duration_to_seconds(recipe_content.get("totalTime")) |
| 556 |
active_time = _duration_to_seconds(recipe_content.get("prepTime")) |
| 557 |
|
| 558 |
thumbnail: str | None = None |
| 559 |
image: str | None = None |
| 560 |
|
| 561 |
image = recipe_content.get("image", None) |
| 562 |
if image: |
| 563 |
thumbnail, image = _process_image_url(image) |
| 564 |
|
| 565 |
url = _construct_recipe_url(localization, recipe["recipeId"], "created-recipes") |
| 566 |
recipe_yield = ( |
| 567 |
recipe_content.get("recipeYield") |
| 568 |
or recipe_content.get("yield") |
| 569 |
or {"value": 0, "unitText": ""} |
| 570 |
) |
| 571 |
|
| 572 |
return CookidooCustomRecipe( |
| 573 |
id=recipe["recipeId"], |
| 574 |
name=recipe_content["name"], |
| 575 |
ingredients=_extract_text_list( |
| 576 |
recipe_content.get("recipeIngredient") |
| 577 |
or recipe_content.get("ingredients", []) |
| 578 |
), |
| 579 |
instructions=_extract_text_list( |
| 580 |
recipe_content.get("recipeInstructions") |
| 581 |
or recipe_content.get("instructions", []) |
| 582 |
), |
| 583 |
serving_size=recipe_yield["value"], |
| 584 |
total_time=total_time, |
| 585 |
active_time=active_time, |
| 586 |
tools=recipe_content.get("tool") or recipe_content.get("tools", []), |
| 587 |
thumbnail=thumbnail, |
| 588 |
image=image, |
| 589 |
url=url, |
| 590 |
) |
| 591 |
|
| 592 |
|
| 593 |
def cookidoo_ingredient_from_json( |
| 594 |
ingredient: IngredientJSON | ItemJSON, |
| 595 |
) -> CookidooIngredient: |
| 596 |
"""Convert an ingredient received from the API to a cookidoo ingredient.""" |
| 597 |
return CookidooIngredient( |
| 598 |
id=ingredient["localId"] if "localId" in ingredient else ingredient["id"], # type: ignore[typeddict-item] |
| 599 |
name=ingredient["ingredientNotation"], |
| 600 |
description=f"{cookidoo_quantity_from_json(ingredient['quantity'])} {ingredient['unitNotation']}" |
| 601 |
if "unitNotation" in ingredient |
| 602 |
and ingredient["unitNotation"] |
| 603 |
and "quantity" in ingredient |
| 604 |
and ingredient["quantity"] |
| 605 |
else cookidoo_quantity_from_json(ingredient["quantity"]) |
| 606 |
if "quantity" in ingredient and ingredient["quantity"] |
| 607 |
else "", |
| 608 |
) |
| 609 |
|
| 610 |
|
| 611 |
def cookidoo_ingredient_item_from_json( |
| 612 |
item: ItemJSON, |
| 613 |
) -> CookidooIngredientItem: |
| 614 |
"""Convert an ingredient item received from the API to a cookidoo item.""" |
| 615 |
return CookidooIngredientItem( |
| 616 |
id=item["id"], |
| 617 |
name=item["ingredientNotation"], |
| 618 |
is_owned=item["isOwned"], |
| 619 |
description=f"{cookidoo_quantity_from_json(item['quantity'])} {item['unitNotation']}" |
| 620 |
if "unitNotation" in item |
| 621 |
and item["unitNotation"] |
| 622 |
and "quantity" in item |
| 623 |
and item["quantity"] |
| 624 |
else str(cookidoo_quantity_from_json(item["quantity"])) |
| 625 |
if "quantity" in item and item["quantity"] |
| 626 |
else "", |
| 627 |
) |
| 628 |
|
| 629 |
|
| 630 |
def cookidoo_additional_item_from_json( |
| 631 |
item: AdditionalItemJSON, |
| 632 |
) -> CookidooAdditionalItem: |
| 633 |
"""Convert an additional item received from the API to a cookidoo item.""" |
| 634 |
return CookidooAdditionalItem( |
| 635 |
id=item["id"], |
| 636 |
name=item["name"], |
| 637 |
is_owned=item["isOwned"], |
| 638 |
) |
| 639 |
|
| 640 |
|
| 641 |
def cookidoo_calendar_day_from_json( |
| 642 |
calendar_day: CalendarDayJSON, |
| 643 |
localization: CookidooLocalizationConfig | None = None, |
| 644 |
) -> CookidooCalendarDay: |
| 645 |
"""Convert a calendar day received from the API to a cookidoo item.""" |
| 646 |
|
| 647 |
def _to_day_recipe(recipe: CalenderDayRecipeJSON) -> CookidooCalendarDayRecipe: |
| 648 |
assets = recipe["assets"] |
| 649 |
thumbnail, image = None, None |
| 650 |
descriptive_assets = [assets["images"]] if assets and assets["images"] else None |
| 651 |
if descriptive_assets is not None: |
| 652 |
thumbnail, image = _extract_images_from_descriptive_assets( |
| 653 |
descriptive_assets |
| 654 |
) |
| 655 |
|
| 656 |
url = _construct_recipe_url(localization, recipe["id"]) |
| 657 |
|
| 658 |
return CookidooCalendarDayRecipe( |
| 659 |
id=recipe["id"], |
| 660 |
name=recipe["title"], |
| 661 |
total_time=recipe["totalTime"], |
| 662 |
thumbnail=thumbnail, |
| 663 |
image=image, |
| 664 |
url=url, |
| 665 |
) |
| 666 |
|
| 667 |
regular_recipes = [_to_day_recipe(recipe) for recipe in calendar_day["recipes"]] |
| 668 |
custom_recipes = [ |
| 669 |
_to_day_recipe(recipe) for recipe in calendar_day.get("customerRecipes", []) |
| 670 |
] |
| 671 |
|
| 672 |
return CookidooCalendarDay( |
| 673 |
id=calendar_day["id"], |
| 674 |
title=calendar_day["title"], |
| 675 |
recipes=[*regular_recipes, *custom_recipes], |
| 676 |
customer_recipe_ids=list(calendar_day.get("customerRecipeIds", [])), |
| 677 |
) |
| 678 |
|
| 679 |
|
| 680 |
async def __get_localization_options( |
| 681 |
country: str | None = None, |
| 682 |
language: str | None = None, |
| 683 |
) -> list[CookidooLocalizationConfig]: |
| 684 |
async with aiofiles.open(localization_file_path, encoding="utf-8") as file: |
| 685 |
options_ = cast(list[dict[str, str]], json.loads(await file.read())) |
| 686 |
options = (CookidooLocalizationConfig(**x) for x in options_) |
| 687 |
filtered_options = filter( |
| 688 |
lambda option: ( |
| 689 |
(not country or option.country_code == country) |
| 690 |
and (not language or option.language == language) |
| 691 |
), |
| 692 |
options, |
| 693 |
) |
| 694 |
return list(cast(list[CookidooLocalizationConfig], filtered_options)) |
| 695 |
|
| 696 |
|
| 697 |
async def get_localization_options( |
| 698 |
country: str | None = None, |
| 699 |
language: str | None = None, |
| 700 |
) -> list[CookidooLocalizationConfig]: |
| 701 |
"""Get a list of possible localization options.""" |
| 702 |
return await __get_localization_options(country, language) |
| 703 |
|
| 704 |
|
| 705 |
async def get_country_options() -> list[str]: |
| 706 |
"""Get a list of possible country options.""" |
| 707 |
return list({option.country_code for option in await get_localization_options()}) |
| 708 |
|
| 709 |
|
| 710 |
async def get_language_options() -> list[str]: |
| 711 |
"""Get a list of possible language options.""" |
| 712 |
return list({option.language for option in await get_localization_options()}) |