Debian Codegraph @

cookidoo_api/cookidoo.py

raw
1 """Cookidoo api implementation."""
2
3 import asyncio
4 import base64
5 from collections.abc import Callable, Mapping, Sequence
6 from datetime import date
7 import hashlib
8 from http import HTTPStatus
9 import json
10 from json import JSONDecodeError
11 import logging
12 import os
13 from pathlib import Path
14 import re
15 import secrets
16 import time
17 import traceback
18 from typing import TypeVar, cast
19 from urllib.parse import parse_qs, urljoin, urlparse
20
21 from aiohttp import ClientError, ClientSession
22 from yarl import URL
23
24 from cookidoo_api.const import (
25 CIAM_BASE_URL,
26 CIAM_LOGIN_SRV_URL,
27 CUSTOM_COLLECTIONS_PATH_ACCEPT,
28 CUSTOM_RECIPES_PATH_ACCEPT,
29 DEFAULT_API_HEADERS,
30 HAL_ACCEPT,
31 LOGIN_HEADERS,
32 MANAGED_COLLECTIONS_PATH_ACCEPT,
33 MOBILE_HOME_PATH,
34 OAUTH_SCOPE,
35 OIDC_DISCOVERY_URL,
36 PUSH_BUNDLE_ID,
37 PUSH_PLATFORM,
38 REL_RMI_CONFIG,
39 RMI_API_VERSION,
40 RMI_DEVICES,
41 RMI_REGISTER_TOKEN,
42 RMI_UNREGISTER,
43 TOKEN_EXPIRY_MARGIN_S,
44 )
45 from cookidoo_api.exceptions import (
46 CookidooAuthException,
47 CookidooConfigException,
48 CookidooParseException,
49 CookidooRequestException,
50 )
51 from cookidoo_api.helpers import (
52 cookidoo_additional_item_from_json,
53 cookidoo_calendar_day_from_json,
54 cookidoo_collection_from_json,
55 cookidoo_custom_recipe_from_json,
56 cookidoo_device_from_json,
57 cookidoo_ingredient_item_from_json,
58 cookidoo_recipe_details_from_json,
59 cookidoo_recipe_from_json,
60 cookidoo_search_result_from_json,
61 cookidoo_subscription_from_json,
62 cookidoo_user_info_from_json,
63 normalize_list_param,
64 normalize_tmv_param,
65 )
66 from cookidoo_api.raw_types import (
67 AdditionalItemJSON,
68 CalendarDayJSON,
69 CommunityProfileJSON,
70 CustomCollectionJSON,
71 CustomRecipeJSON,
72 CustomRecipesJSON,
73 ItemJSON,
74 ManagedCollectionJSON,
75 PaginationJSON,
76 RecipeDetailsJSON,
77 RecipeJSON,
78 SearchResultJSON,
79 SubscriptionJSON,
80 )
81 from cookidoo_api.types import (
82 CookidooAdditionalItem,
83 CookidooAuthData,
84 CookidooCalendarDay,
85 CookidooCollection,
86 CookidooConfig,
87 CookidooCustomRecipe,
88 CookidooDevice,
89 CookidooIngredientItem,
90 CookidooLocalizationConfig,
91 CookidooSearchResult,
92 CookidooShoppingRecipe,
93 CookidooShoppingRecipeDetails,
94 CookidooSubscription,
95 CookidooUserInfo,
96 ThermomixMachineType,
97 )
98 from cookidoo_api.well_known import resolve_endpoint_paths
99
100 _LOGGER = logging.getLogger(__name__)
101 _T = TypeVar("_T")
102
103
104 class Cookidoo:
105 """Unofficial Cookidoo API interface."""
106
107 _session: ClientSession
108 _cfg: CookidooConfig
109 _api_headers: dict[str, str]
110 _logged_in: bool
111 _endpoint_overrides: dict[str, str]
112 _endpoints_resolved: bool
113 _endpoints_lock: asyncio.Lock
114 _token_lock: asyncio.Lock
115 _refresh_token: str | None
116 _expires_at: float
117 _oidc: dict[str, str] | None
118 _rmi_links: dict[str, str] | None
119
120 def __init__(
121 self,
122 session: ClientSession,
123 cfg: CookidooConfig = CookidooConfig(),
124 ) -> None:
125 """Init function for Cookidoo API.
126
127 Parameters
128 ----------
129 session
130 The client session for aiohttp requests.
131 Must use a ``CookieJar(unsafe=True)`` to support cross-domain
132 cookies during the OAuth2 login flow.
133 cfg
134 Cookidoo config
135
136 """
137 self._session = session
138 self._cfg = cfg
139 self._api_headers = DEFAULT_API_HEADERS.copy()
140 self._logged_in = False
141 self._endpoint_overrides = {}
142 self._endpoints_resolved = False
143 self._endpoints_lock = asyncio.Lock()
144 self._token_lock = asyncio.Lock()
145 self._refresh_token = None
146 self._expires_at = 0.0
147 self._oidc = None
148 self._rmi_links = None
149
150 @property
151 def localization(self) -> CookidooLocalizationConfig:
152 """Localization."""
153 return self._cfg.localization
154
155 @property
156 def api_endpoint(self) -> URL:
157 """Get the api endpoint.
158
159 Returns the cookidoo domain derived from the localization URL,
160 e.g. ``https://cookidoo.ch`` or ``https://cookidoo.co.uk``.
161 """
162 parsed = urlparse(self._cfg.localization.url)
163 return URL(f"{parsed.scheme}://{parsed.netloc}")
164
165 async def _request_json(
166 self,
167 method: str,
168 url: URL,
169 operation: str,
170 *,
171 params: dict[str, str] | None = None,
172 json: object | None = None,
173 headers: dict[str, str] | None = None,
174 accepted_statuses: tuple[HTTPStatus, ...] = (
175 HTTPStatus.OK,
176 HTTPStatus.NO_CONTENT,
177 ),
178 parse_response: bool = True,
179 ) -> object | None:
180 """Execute an HTTP request and parse its JSON response.
181
182 Parameters
183 ----------
184 method
185 HTTP method (e.g. "get", "post").
186 url
187 The target URL (without query params when using ``params``).
188 operation
189 Human-readable operation name for error messages.
190 params
191 Optional query parameters passed to aiohttp.
192 json
193 Optional JSON body for the request.
194 headers
195 Optional extra headers (merged with default API headers).
196 accepted_statuses
197 HTTP status codes considered successful. Defaults to 200 and 204.
198 A 204 response always returns ``None`` (no body).
199 parse_response
200 Whether to parse a successful non-204 response as JSON.
201
202 Returns
203 -------
204 object | None
205 The parsed JSON response, or ``None`` for 204 No Content.
206
207 Raises
208 ------
209 CookidooAuthException
210 When the server responds with 401 Unauthorized.
211 CookidooRequestException
212 On connection timeout or other client errors.
213 CookidooParseException
214 When the response body cannot be parsed as JSON.
215
216 """
217 await self._ensure_token()
218 merged_headers = {**self._api_headers, **(headers or {})}
219
220 try:
221 async with self._session.request(
222 method, url, headers=merged_headers, json=json, params=params
223 ) as r:
224 _LOGGER.debug(
225 "Response from %s [%s]: %s", url, r.status, await r.text()
226 )
227
228 if r.status == HTTPStatus.UNAUTHORIZED:
229 try:
230 errmsg = await r.json()
231 except (JSONDecodeError, ClientError):
232 _LOGGER.debug(
233 "Exception: Cannot parse request response:\n %s",
234 traceback.format_exc(),
235 )
236 else:
237 _LOGGER.debug(
238 "Exception: Cannot %s: %s",
239 operation,
240 errmsg.get("error_description", ""),
241 )
242 self._raise_auth_exception(operation)
243
244 if r.status not in accepted_statuses:
245 r.raise_for_status()
246
247 if r.status == HTTPStatus.NO_CONTENT:
248 return None
249 if not parse_response:
250 return None
251 try:
252 result: object = await r.json()
253 except (JSONDecodeError, KeyError) as e:
254 _LOGGER.debug(
255 "Exception: Cannot parse %s response:\n%s",
256 operation,
257 traceback.format_exc(),
258 )
259 raise CookidooParseException(
260 f"{operation.capitalize()} failed during parsing of request response."
261 ) from e
262 else:
263 return result
264
265 except (
266 CookidooAuthException,
267 CookidooRequestException,
268 CookidooParseException,
269 ):
270 raise
271 except TimeoutError as e:
272 _LOGGER.debug(
273 "Exception: Cannot %s:\n%s", operation, traceback.format_exc()
274 )
275 raise CookidooRequestException(
276 f"{operation.capitalize()} failed due to connection timeout."
277 ) from e
278 except ClientError as e:
279 _LOGGER.debug(
280 "Exception: Cannot %s:\n%s", operation, traceback.format_exc()
281 )
282 raise CookidooRequestException(
283 f"{operation.capitalize()} failed due to request exception."
284 ) from e
285
286 @staticmethod
287 def _raise_auth_exception(operation: str) -> None:
288 """Raise the standard auth exception for request helpers."""
289 raise CookidooAuthException(
290 f"{operation.capitalize()} failed due to authorization failure, "
291 "the authorization token is invalid or expired."
292 )
293
294 @staticmethod
295 def _ensure_mapping(result: object | None, operation: str) -> Mapping[str, object]:
296 """Return a mapping response or raise the standard parse exception."""
297 if not isinstance(result, Mapping):
298 raise CookidooParseException(
299 f"{operation.capitalize()} failed during parsing of request response."
300 )
301 return result
302
303 @staticmethod
304 def _ensure_sequence(result: object | None, operation: str) -> Sequence[object]:
305 """Return a sequence response or raise the standard parse exception."""
306 if isinstance(result, str) or not isinstance(result, Sequence):
307 raise CookidooParseException(
308 f"{operation.capitalize()} failed during parsing of request response."
309 )
310 return result
311
312 @staticmethod
313 def _parse_result(operation: str, parser: Callable[[], _T]) -> _T:
314 """Convert a validated JSON response into public types."""
315 try:
316 return parser()
317 except (KeyError, TypeError, ValueError) as e:
318 raise CookidooParseException(
319 f"{operation.capitalize()} failed during parsing of request response."
320 ) from e
321
322 def _is_endpoints_resolved(self) -> bool:
323 """Return whether endpoint discovery has already completed.
324
325 Kept as a method (rather than a direct attribute read) so mypy
326 doesn't narrow ``_endpoints_resolved`` to a stale literal across the
327 ``await`` on ``_endpoints_lock`` in ``_ensure_endpoints``.
328 """
329 return self._endpoints_resolved
330
331 async def _ensure_endpoints(self) -> None:
332 """Resolve live endpoint paths via ``.well-known/home`` discovery.
333
334 Runs once per instance. There is no hardcoded fallback: a stale
335 path is worse than a clear failure, since it can look successful
336 right up until Cookidoo actually removes the old one. Discovery is
337 retried once (a transient network hiccup shouldn't need a whole new
338 request cycle to recover from); if the retry also fails, the
339 exception propagates to the caller and the next call starts over
340 from scratch.
341
342 Guarded by a lock (checked both before and inside it) so concurrent
343 callers -- e.g. an ``asyncio.gather`` of several API methods on a
344 fresh instance -- await a single in-flight resolution instead of
345 each kicking off their own full discovery round.
346
347 Raises
348 ------
349 CookidooRequestException
350 If a service's discovery document could not be reached.
351 CookidooParseException
352 If a discovered endpoint's shape can't be reconciled with ours.
353
354 """
355 if self._endpoints_resolved:
356 return
357 async with self._endpoints_lock:
358 # Re-check via a helper: a direct attribute re-check here is
359 # (correctly) flagged as unreachable by mypy, since it can't
360 # know the `await` above (waiting on the lock) may let another
361 # coroutine change `_endpoints_resolved` in the meantime.
362 if self._is_endpoints_resolved():
363 return
364 try:
365 self._endpoint_overrides = await resolve_endpoint_paths(
366 self._session, self.api_endpoint
367 )
368 except (CookidooRequestException, CookidooParseException):
369 _LOGGER.debug(
370 "Well-known endpoint discovery failed, retrying once:\n%s",
371 traceback.format_exc(),
372 )
373 self._endpoint_overrides = await resolve_endpoint_paths(
374 self._session, self.api_endpoint
375 )
376 self._endpoints_resolved = True
377
378 def _path(self, name: str) -> str:
379 """Return the live path template resolved via well-known discovery."""
380 return self._endpoint_overrides[name]
381
382 @staticmethod
383 def _empty_calendar_day(day: date) -> CookidooCalendarDay:
384 """Build an empty calendar day for a day with no recipes left.
385
386 The API returns a null ``content`` when a recipe removal leaves a
387 calendar day with no recipes, since the (now empty) day no longer
388 exists as an entity to return.
389 """
390 return CookidooCalendarDay(
391 id=day.isoformat(),
392 title=day.isoformat(),
393 recipes=[],
394 )
395
396 @property
397 def auth_data(self) -> CookidooAuthData | None:
398 """The current OAuth2 tokens, for persistence. ``None`` until logged in."""
399 if not self._logged_in or self._refresh_token is None:
400 return None
401 return CookidooAuthData(
402 access_token=self._api_headers["Authorization"].removeprefix("Bearer "),
403 refresh_token=self._refresh_token,
404 expires_at=self._expires_at,
405 )
406
407 def apply_auth_data(self, auth_data: CookidooAuthData) -> None:
408 """Restore a previous login from persisted tokens (no network call).
409
410 The access token is refreshed automatically on the next request if it
411 has expired.
412 """
413 self._api_headers["Authorization"] = f"Bearer {auth_data.access_token}"
414 self._refresh_token = auth_data.refresh_token
415 self._expires_at = auth_data.expires_at
416 self._logged_in = True
417
418 async def login(self) -> None:
419 """Perform an OAuth2 authorization-code + PKCE login.
420
421 Signs in with the configured email/password against the CIAM identity
422 provider, exchanges the resulting code for an access/refresh token, and
423 authenticates all subsequent API calls via a ``Bearer`` header:
424
425 1. discover the OIDC endpoints
426 2. open the authorize endpoint to reach the CIAM login form
427 3. POST the credentials to the CIAM login service
428 4. capture the ``code`` from the redirect to the app scheme
429 5. exchange the code for tokens (public client, PKCE, no secret)
430
431 The login redirects still rely on the session cookie jar, so a
432 ``CookieJar(unsafe=True)`` session is required. The login requests carry
433 a browser-like ``User-Agent`` (request-scoped only) since the flow is
434 served behind Cloudflare.
435
436 Raises
437 ------
438 CookidooConfigException
439 If the OAuth2 client id or redirect uri was overridden with an
440 empty value.
441 CookidooRequestException
442 If the request fails.
443 CookidooParseException
444 If the login page cannot be parsed.
445 CookidooAuthException
446 If the login fails due to invalid credentials.
447
448 """
449 self._assert_oauth_client()
450 try:
451 oidc = await self._discovery()
452 verifier, challenge = self._pkce_pair()
453 state = secrets.token_urlsafe(12)
454 language = self._cfg.localization.language
455 params = {
456 "response_type": "code",
457 "client_id": self._cfg.client_id,
458 "redirect_uri": self._cfg.redirect_uri,
459 "market": self._cfg.localization.country_code,
460 "scope": OAUTH_SCOPE,
461 "state": state,
462 "code_challenge": challenge,
463 "code_challenge_method": "S256",
464 "ui_locales": language,
465 }
466
467 # Step 2: reach the CIAM login form (follows redirects, sets cookies)
468 async with self._session.get(
469 URL(oidc["authorization_endpoint"]),
470 params=params,
471 allow_redirects=True,
472 headers=LOGIN_HEADERS,
473 ) as resp:
474 self._check_login_page_status(resp.status)
475 login_html = await resp.text()
476
477 # Step 3: submit credentials, Step 4: capture the authorization code
478 request_id = self._extract_request_id(login_html)
479 code = await self._submit_credentials(request_id, state)
480
481 # Step 5: exchange the code for tokens
482 await self._exchange_code(oidc["token_endpoint"], code, verifier)
483 self._logged_in = True
484
485 except (CookidooAuthException, CookidooParseException):
486 raise
487 except TimeoutError as e:
488 _LOGGER.debug("Exception: Login failed:\n %s", traceback.format_exc())
489 raise CookidooRequestException(
490 "Authentication failed due to connection timeout."
491 ) from e
492 except ClientError as e:
493 _LOGGER.debug("Exception: Login failed:\n %s", traceback.format_exc())
494 raise CookidooRequestException(
495 "Authentication failed due to request exception."
496 ) from e
497
498 async def refresh(self) -> None:
499 """Refresh the access token using the stored refresh token.
500
501 Raises
502 ------
503 CookidooAuthException
504 If there is no refresh token or the refresh is rejected.
505 CookidooConfigException
506 If the OAuth2 client id or redirect uri was overridden with an
507 empty value.
508 CookidooRequestException
509 If the discovery or token request fails or times out.
510
511 """
512 if self._refresh_token is None:
513 raise CookidooAuthException("Cannot refresh: no refresh token available.")
514 self._assert_oauth_client()
515 try:
516 # Inside the try: the discovery request can fail the same way the
517 # token request can, and callers only expect CookidooException.
518 oidc = await self._discovery()
519 async with self._session.post(
520 URL(oidc["token_endpoint"]),
521 data={
522 "grant_type": "refresh_token",
523 "refresh_token": self._refresh_token,
524 "client_id": self._cfg.client_id,
525 },
526 headers=LOGIN_HEADERS,
527 ) as resp:
528 if resp.status != HTTPStatus.OK:
529 raise CookidooAuthException(
530 f"Token refresh failed (status {resp.status})."
531 )
532 payload = cast(dict[str, object], await resp.json())
533 except TimeoutError as e:
534 _LOGGER.debug(
535 "Exception: Token refresh failed:\n %s", traceback.format_exc()
536 )
537 raise CookidooRequestException(
538 "Token refresh failed due to connection timeout."
539 ) from e
540 except ClientError as e:
541 _LOGGER.debug(
542 "Exception: Token refresh failed:\n %s", traceback.format_exc()
543 )
544 raise CookidooRequestException(
545 "Token refresh failed due to request exception."
546 ) from e
547 self._apply_tokens(payload)
548
549 def save_token(self, path: str | Path) -> None:
550 """Save the OAuth2 tokens to a file for later reuse.
551
552 Parameters
553 ----------
554 path
555 Path to the file where the tokens will be saved.
556
557 """
558 if (auth_data := self.auth_data) is None:
559 raise CookidooConfigException("Cannot save token: not logged in.")
560 Path(path).write_text(json.dumps(vars(auth_data)), encoding="utf-8")
561
562 def load_token(self, path: str | Path) -> None:
563 """Restore the OAuth2 tokens from a file saved with :meth:`save_token`.
564
565 Parameters
566 ----------
567 path
568 Path to the file containing the saved tokens.
569
570 Raises
571 ------
572 CookidooConfigException
573 If the token file cannot be read or parsed.
574
575 """
576 try:
577 data = json.loads(Path(path).read_text(encoding="utf-8"))
578 self.apply_auth_data(CookidooAuthData(**data))
579 except (OSError, json.JSONDecodeError, TypeError) as e:
580 raise CookidooConfigException(f"Cannot load token from {path}.") from e
581
582 # -- internal auth helpers --------------------------------------------
583 async def _discovery(self) -> dict[str, str]:
584 """Fetch and cache the OIDC discovery document."""
585 if self._oidc is None:
586 async with self._session.get(
587 URL(OIDC_DISCOVERY_URL), headers=LOGIN_HEADERS
588 ) as resp:
589 resp.raise_for_status()
590 self._oidc = cast(dict[str, str], await resp.json())
591 return self._oidc
592
593 async def _submit_credentials(self, request_id: str, state: str) -> str:
594 """POST credentials and follow the redirect chain to capture the code.
595
596 Raises ``CookidooAuthException`` when no authorization code is returned
597 (i.e. the credentials were rejected).
598 """
599 url: str = CIAM_LOGIN_SRV_URL
600 data: dict[str, str] | None = {
601 "requestId": request_id,
602 "username": self._cfg.email,
603 "password": self._cfg.password,
604 }
605 method = "post"
606 code: str | None = None
607 for _ in range(10):
608 async with self._session.request(
609 method,
610 URL(url),
611 data=data,
612 headers=LOGIN_HEADERS,
613 allow_redirects=False,
614 ) as resp:
615 location = resp.headers.get("Location")
616 if resp.status in (301, 302, 303, 307, 308) and location:
617 if location.startswith(self._cfg.redirect_uri):
618 query = parse_qs(urlparse(location).query)
619 # A missing state is a mismatch: the callback must echo
620 # the value we sent (RFC 6749 §10.12).
621 if query.get("state") != [state]:
622 raise CookidooAuthException("OAuth state mismatch.")
623 codes = query.get("code")
624 code = codes[0] if codes else None
625 break
626 url = urljoin(url, location)
627 self._assert_ciam_origin(url)
628 method, data = "get", None
629 continue
630 break
631 if code is None:
632 raise CookidooAuthException(
633 "Login failed: invalid credentials (no authorization code "
634 "returned). Please check your email and password."
635 )
636 return code
637
638 @staticmethod
639 def _assert_ciam_origin(url: str) -> None:
640 """Ensure the login flow never leaves CIAM's own origin.
641
642 The redirect chain carries the session cookies of an in-flight login, so
643 a redirect to a foreign host is refused rather than followed.
644 """
645 origin = urlparse(url)
646 expected = urlparse(CIAM_BASE_URL)
647 if (origin.scheme, origin.netloc) != (expected.scheme, expected.netloc):
648 raise CookidooAuthException(
649 f"Login flow redirected off the authentication host: {url}"
650 )
651
652 @staticmethod
653 def _check_login_page_status(status: int) -> None:
654 """Check login page response status."""
655 if status != HTTPStatus.OK:
656 raise CookidooAuthException(
657 f"Login flow failed: could not reach login page (status {status})."
658 )
659
660 async def _exchange_code(
661 self, token_endpoint: str, code: str, verifier: str
662 ) -> None:
663 """Exchange an authorization code for tokens."""
664 async with self._session.post(
665 URL(token_endpoint),
666 data={
667 "grant_type": "authorization_code",
668 "code": code,
669 "redirect_uri": self._cfg.redirect_uri,
670 "code_verifier": verifier,
671 "client_id": self._cfg.client_id,
672 },
673 headers=LOGIN_HEADERS,
674 ) as resp:
675 if resp.status != HTTPStatus.OK:
676 raise CookidooAuthException(
677 f"Token exchange failed (status {resp.status})."
678 )
679 payload = cast(dict[str, object], await resp.json())
680 self._apply_tokens(payload)
681
682 def _apply_tokens(self, payload: dict[str, object]) -> None:
683 """Store tokens from a token-endpoint response and set the auth header."""
684 try:
685 access_token = cast(str, payload["access_token"])
686 # A refresh response may omit a new refresh token; keep the old one.
687 self._refresh_token = cast(
688 str, payload.get("refresh_token", self._refresh_token)
689 )
690 expires_in = int(cast(int, payload.get("expires_in", 43200)))
691 except (KeyError, TypeError, ValueError) as e:
692 raise CookidooAuthException(f"Unexpected token response: {payload}") from e
693 self._api_headers["Authorization"] = f"Bearer {access_token}"
694 self._expires_at = time.time() + expires_in
695
696 def _is_token_expiring(self) -> bool:
697 """Whether the access token is missing or within the expiry margin."""
698 return time.time() >= self._expires_at - TOKEN_EXPIRY_MARGIN_S
699
700 async def _ensure_token(self) -> None:
701 """Refresh the access token if it is missing or about to expire.
702
703 Guarded by a lock (checked both before and inside it) so concurrent
704 callers -- e.g. an ``asyncio.gather`` of several API methods across an
705 expiry -- await a single refresh instead of each spending the same
706 refresh token. The server may rotate that token and retire the old one,
707 so a second concurrent refresh can be rejected outright.
708 """
709 if not self._logged_in or not self._is_token_expiring():
710 return
711 async with self._token_lock:
712 if self._is_token_expiring():
713 await self.refresh()
714
715 @staticmethod
716 def _pkce_pair() -> tuple[str, str]:
717 """Return a (code_verifier, code_challenge) PKCE S256 pair."""
718 verifier = base64.urlsafe_b64encode(os.urandom(48)).rstrip(b"=").decode()
719 challenge = (
720 base64.urlsafe_b64encode(hashlib.sha256(verifier.encode()).digest())
721 .rstrip(b"=")
722 .decode()
723 )
724 return verifier, challenge
725
726 def _assert_oauth_client(self) -> None:
727 """Ensure the OAuth2 client identifiers are set.
728
729 Both default to the mobile app's public identifiers, so this only trips
730 when a caller overrides one of them with an empty value.
731
732 Raises
733 ------
734 CookidooConfigException
735 If the client id or the redirect uri is missing.
736
737 """
738 missing = [
739 name
740 for name in ("client_id", "redirect_uri")
741 if not getattr(self._cfg, name)
742 ]
743 if missing:
744 raise CookidooConfigException(
745 f"Missing OAuth2 client configuration: {', '.join(missing)}. "
746 "Leave these unset to use the defaults, see docs/oauth-client.md."
747 )
748
749 @staticmethod
750 def _extract_request_id(login_html: str) -> str:
751 """Extract requestId from the CIAM login page HTML."""
752 match = re.search(
753 r'<input[^>]*name=["\']requestId["\'][^>]*value=["\']([^"\']+)["\']',
754 login_html,
755 ) or re.search(
756 r'<input[^>]*value=["\']([0-9a-f-]{36})["\'][^>]*name=["\']requestId["\']',
757 login_html,
758 )
759 if not match:
760 raise CookidooParseException(
761 "Login flow failed: could not extract requestId from login page."
762 )
763 return match.group(1)
764
765 async def get_user_info(
766 self,
767 ) -> CookidooUserInfo:
768 """Get user info.
769
770 Returns
771 -------
772 CookidooUserInfo
773 The user info
774
775 Raises
776 ------
777 CookidooAuthException
778 When the access token is not valid anymore
779 CookidooRequestException
780 If the request fails.
781 CookidooParseException
782 If the parsing of the request response fails.
783
784 """
785
786 await self._ensure_endpoints()
787 url = self.api_endpoint / self._path(
788 "community-profile:user-private-profile"
789 ).format(**self._cfg.localization.__dict__)
790 result = self._ensure_mapping(
791 await self._request_json("get", url, "loading user info"),
792 "loading user info",
793 )
794 return self._parse_result(
795 "loading user info",
796 lambda: cookidoo_user_info_from_json(cast(CommunityProfileJSON, result)),
797 )
798
799 async def get_active_subscription(
800 self,
801 ) -> CookidooSubscription | None:
802 """Get active subscription if any.
803
804 Returns
805 -------
806 CookidooSubscription
807 The active subscription
808
809 Raises
810 ------
811 CookidooAuthException
812 When the access token is not valid anymore
813 CookidooRequestException
814 If the request fails.
815 CookidooParseException
816 If the parsing of the request response fails.
817
818 """
819
820 await self._ensure_endpoints()
821 url = self.api_endpoint / self._path("ownership:subscriptions").format(
822 **self._cfg.localization.__dict__
823 )
824 subscriptions = self._ensure_sequence(
825 await self._request_json("get", url, "loading active subscription"),
826 "loading active subscription",
827 )
828 try:
829 if subscription := next(
830 (
831 subscription
832 for subscription in subscriptions
833 if isinstance(subscription, Mapping) and subscription["active"]
834 ),
835 None,
836 ):
837 return self._parse_result(
838 "loading active subscription",
839 lambda: cookidoo_subscription_from_json(
840 cast(SubscriptionJSON, subscription)
841 ),
842 )
843 except KeyError as e:
844 raise CookidooParseException(
845 "Loading active subscription failed during parsing of request response."
846 ) from e
847 return None
848
849 async def get_devices(self) -> list[CookidooDevice]:
850 """Get the Thermomix appliances paired to the account.
851
852 Returns
853 -------
854 list[CookidooDevice]
855 The paired appliances, identified by machine type (e.g. ``TM7``).
856 An empty list when no appliance is paired.
857
858 Raises
859 ------
860 CookidooAuthException
861 When the access token is not valid anymore
862 CookidooRequestException
863 If the request fails.
864 CookidooParseException
865 If the parsing of the request response fails.
866
867 """
868 await self._ensure_endpoints()
869 url = self.api_endpoint / self._path(
870 "customer-devices:thermomix-versions"
871 ).format(**self._cfg.localization.__dict__)
872 result = await self._request_json("get", url, "loading devices")
873 if result is None:
874 # An account without a paired appliance gets a 204 No Content.
875 return []
876 models = self._ensure_sequence(result, "loading devices")
877 return self._parse_result(
878 "loading devices",
879 lambda: [cookidoo_device_from_json(cast(str, model)) for model in models],
880 )
881
882 async def _resolve_rmi_links(self) -> dict[str, str]:
883 """Resolve and cache the remote-monitoring endpoint links.
884
885 Walks the mobile home document to the ``rmi-config`` sub-document and
886 returns its ``{rel: href}`` map (``rmi:register-token``, ``rmi:devices``,
887 ``rmi:unregister``, ...).
888 """
889 if self._rmi_links is not None:
890 return self._rmi_links
891
892 hal_headers = {"ACCEPT": HAL_ACCEPT}
893 home = self._ensure_mapping(
894 await self._request_json(
895 "get",
896 self.api_endpoint / MOBILE_HOME_PATH,
897 "resolving remote monitoring",
898 headers=hal_headers,
899 ),
900 "resolving remote monitoring",
901 )
902 rmi_config_url = self._hal_link(home, REL_RMI_CONFIG)
903 if rmi_config_url is None:
904 raise CookidooParseException(
905 "Resolving remote monitoring failed: rmi-config link missing."
906 )
907 rmi_home = self._ensure_mapping(
908 await self._request_json(
909 "get",
910 URL(rmi_config_url),
911 "resolving remote monitoring",
912 headers=hal_headers,
913 ),
914 "resolving remote monitoring",
915 )
916 links_obj = rmi_home.get("_links")
917 if not isinstance(links_obj, Mapping):
918 raise CookidooParseException(
919 "Resolving remote monitoring failed during parsing of request response."
920 )
921 links: dict[str, str] = {}
922 for rel, value in links_obj.items():
923 if isinstance(value, str):
924 links[rel] = value
925 elif isinstance(value, Mapping) and isinstance(value.get("href"), str):
926 links[rel] = cast(str, value["href"])
927 self._rmi_links = links
928 return links
929
930 @staticmethod
931 def _hal_link(doc: Mapping[str, object], rel: str) -> str | None:
932 """Extract a HAL link href for ``rel`` from a document's ``_links``."""
933 links = doc.get("_links")
934 if not isinstance(links, Mapping):
935 return None
936 value = links.get(rel)
937 if isinstance(value, str):
938 return value
939 if isinstance(value, Mapping) and isinstance(value.get("href"), str):
940 return cast(str, value["href"])
941 return None
942
943 async def get_monitored_device_ids(self) -> list[str]:
944 """Get the appliance IDs currently available for remote monitoring.
945
946 Note this is distinct from :meth:`get_devices` (all paired appliances):
947 an appliance only appears here while it is online/reachable for
948 monitoring, and the identifier is the opaque remote-monitoring device id.
949
950 Returns
951 -------
952 list[str]
953 The remote-monitoring device ids (empty when none are available).
954
955 Raises
956 ------
957 CookidooAuthException
958 When the access token is not valid anymore
959 CookidooRequestException
960 If the request fails.
961 CookidooParseException
962 If the parsing of the request response fails.
963
964 """
965 links = await self._resolve_rmi_links()
966 url = links.get(RMI_DEVICES)
967 if url is None:
968 raise CookidooParseException("rmi:devices link missing.")
969 devices = self._ensure_sequence(
970 await self._request_json(
971 "get", URL(url.split("{")[0]), "loading monitored devices"
972 ),
973 "loading monitored devices",
974 )
975 return self._parse_result(
976 "loading monitored devices",
977 lambda: [
978 cast(str, cast(Mapping[str, object], device)["deviceId"])
979 for device in devices
980 ],
981 )
982
983 async def register_push_token(self, push_token: str, mobile_app_id: str) -> None:
984 """Register a push token to receive remote-monitoring cook-state updates.
985
986 Appliance state is delivered as a Firebase Cloud Messaging data message
987 to the registered token; obtaining the token and receiving the messages
988 is the caller's responsibility. Decode received payloads with
989 :func:`cookidoo_api.cooking_activity_from_push`.
990
991 Parameters
992 ----------
993 push_token
994 The FCM registration token to deliver updates to.
995 mobile_app_id
996 A stable per-installation identifier for this client.
997
998 Raises
999 ------
1000 CookidooAuthException
1001 When the access token is not valid anymore
1002 CookidooRequestException
1003 If the request fails.
1004 CookidooParseException
1005 If the parsing of the request response fails.
1006
1007 """
1008 links = await self._resolve_rmi_links()
1009 url = links.get(RMI_REGISTER_TOKEN)
1010 if url is None:
1011 raise CookidooParseException("rmi:register-token link missing.")
1012 await self._request_json(
1013 "post",
1014 URL(url),
1015 "registering push token",
1016 json={
1017 "token": push_token,
1018 "bundleId": PUSH_BUNDLE_ID,
1019 "platform": PUSH_PLATFORM,
1020 "mobileAppId": mobile_app_id,
1021 },
1022 headers={"rmi-api-version": RMI_API_VERSION},
1023 parse_response=False,
1024 )
1025
1026 async def unregister_push_token(self, push_token: str) -> None:
1027 """Unregister a previously registered push token.
1028
1029 Parameters
1030 ----------
1031 push_token
1032 The FCM registration token to stop delivering updates to.
1033
1034 Raises
1035 ------
1036 CookidooAuthException
1037 When the access token is not valid anymore
1038 CookidooRequestException
1039 If the request fails.
1040 CookidooParseException
1041 If the parsing of the request response fails.
1042
1043 """
1044 links = await self._resolve_rmi_links()
1045 url = links.get(RMI_UNREGISTER)
1046 if url is None:
1047 raise CookidooParseException("rmi:unregister link missing.")
1048 await self._request_json(
1049 "delete",
1050 URL(url),
1051 "unregistering push token",
1052 json={"tokens": [push_token]},
1053 headers={"rmi-api-version": RMI_API_VERSION},
1054 parse_response=False,
1055 )
1056
1057 async def get_recipe_details(self, id: str) -> CookidooShoppingRecipeDetails:
1058 """Get recipe details.
1059
1060 Parameters
1061 ----------
1062 id
1063 The id of the recipe
1064
1065 Returns
1066 -------
1067 CookidooShoppingRecipeDetails
1068 The recipe details
1069
1070 Raises
1071 ------
1072 CookidooAuthException
1073 When the access token is not valid anymore
1074 CookidooRequestException
1075 If the request fails.
1076 CookidooParseException
1077 If the parsing of the request response fails.
1078
1079 """
1080
1081 await self._ensure_endpoints()
1082 url = self.api_endpoint / self._path("recipe:details").format(
1083 **self._cfg.localization.__dict__, id=id
1084 )
1085 result = self._ensure_mapping(
1086 await self._request_json("get", url, "loading recipe details"),
1087 "loading recipe details",
1088 )
1089 return self._parse_result(
1090 "loading recipe details",
1091 lambda: cookidoo_recipe_details_from_json(
1092 cast(RecipeDetailsJSON, result),
1093 self._cfg.localization,
1094 ),
1095 )
1096
1097 async def search_recipes(
1098 self,
1099 query: str | None = None,
1100 *,
1101 locale: str | None = None,
1102 accessories: str | list[str] | None = None,
1103 languages: str | list[str] | None = None,
1104 categories: str | list[str] | None = None,
1105 countries: str | list[str] | None = None,
1106 ingredients: str | list[str] | None = None,
1107 exclude_ingredients: str | list[str] | None = None,
1108 tags: str | list[str] | None = None,
1109 ratings: str | list[str] | None = None,
1110 difficulty: str | None = None,
1111 preparation_time: int | None = None,
1112 total_time: int | None = None,
1113 portions: int | None = None,
1114 page: int | None = None,
1115 page_size: int | None = None,
1116 tmv: ThermomixMachineType
1117 | str
1118 | list[ThermomixMachineType | str]
1119 | None = None,
1120 ) -> CookidooSearchResult:
1121 """Search recipes in Cookidoo (GET).
1122
1123 Uses the same API base as the rest of the client (api_endpoint):
1124 {api_endpoint}/search/{locale}
1125
1126 Parameters
1127 ----------
1128 query
1129 Optional search query (e.g. "chicken", "pasta").
1130 locale
1131 Locale for the search path (e.g. "es", "en", "de").
1132 Defaults to the first part of the configured language (e.g. "de-CH" -> "de").
1133 accessories
1134 Optional comma-separated accessory filters
1135 (e.g. "includingFriend,includingBladeCover,includingBladeCoverWithPeeler,includingCutter,includingSensor").
1136 languages
1137 Optional comma-separated language codes (e.g. "en,es").
1138 categories
1139 Optional comma-separated category IDs.
1140 countries
1141 Optional comma-separated country codes (e.g. "ar").
1142 ingredients
1143 Optional comma-separated ingredients.
1144 exclude_ingredients
1145 Optional comma-separated excluded ingredients.
1146 tags
1147 Optional comma-separated tags.
1148 ratings
1149 Optional comma-separated ratings (e.g. "5,4").
1150 difficulty
1151 Optional difficulty (e.g. "easy", "medium", "hard").
1152 preparation_time
1153 Optional preparation time in seconds.
1154 total_time
1155 Optional total time in seconds.
1156 portions
1157 Optional portions count.
1158 page
1159 Optional page number (API-dependent, often 0- or 1-based).
1160 page_size
1161 Optional page size (API-dependent; common keys: pageSize).
1162 tmv
1163 Optional Thermomix machine version. Use ``ThermomixMachineType``
1164 (e.g. ``ThermomixMachineType.TM7``) or a string ("TM7", "TM6", "TM5").
1165
1166 Returns
1167 -------
1168 CookidooSearchResult
1169 Search result with recipes and total count.
1170
1171 Raises
1172 ------
1173 CookidooAuthException
1174 When the access token is not valid anymore.
1175 CookidooRequestException
1176 If the request fails.
1177 CookidooParseException
1178 If the parsing of the request response fails.
1179
1180 """
1181 if locale is None:
1182 locale = self._cfg.localization.language.split("-")[0]
1183 await self._ensure_endpoints()
1184 url = self.api_endpoint / self._path("search:home").format(locale=locale)
1185 params: dict[str, str] = {}
1186 if query is not None:
1187 params["query"] = query
1188 if accessories is not None and (
1189 normalized := normalize_list_param(accessories)
1190 ):
1191 params["accessories"] = normalized
1192 if languages is not None and (normalized := normalize_list_param(languages)):
1193 params["languages"] = normalized
1194 if categories is not None and (normalized := normalize_list_param(categories)):
1195 params["categories"] = normalized
1196 if countries is not None and (normalized := normalize_list_param(countries)):
1197 params["countries"] = normalized
1198 if ingredients is not None and (
1199 normalized := normalize_list_param(ingredients)
1200 ):
1201 params["ingredients"] = normalized
1202 if exclude_ingredients is not None and (
1203 normalized := normalize_list_param(exclude_ingredients)
1204 ):
1205 params["excludeIngredients"] = normalized
1206 if tags is not None and (normalized := normalize_list_param(tags)):
1207 params["tags"] = normalized
1208 if ratings is not None and (normalized := normalize_list_param(ratings)):
1209 params["ratings"] = normalized
1210 if difficulty is not None:
1211 params["difficulty"] = difficulty
1212 if preparation_time is not None:
1213 params["preparationTime"] = str(preparation_time)
1214 if total_time is not None:
1215 params["totalTime"] = str(total_time)
1216 if portions is not None:
1217 params["portions"] = str(portions)
1218 if page is not None:
1219 params["page"] = str(page)
1220 if page_size is not None:
1221 params["pageSize"] = str(page_size)
1222 if tmv is not None and (normalized := normalize_tmv_param(tmv)):
1223 params["tmv"] = normalized
1224 result = await self._request_json("get", url, "search recipes", params=params)
1225 if result is None:
1226 return CookidooSearchResult(recipes=[], total=0)
1227 if not isinstance(result, dict):
1228 raise CookidooParseException(
1229 "Search recipes failed during parsing of request response."
1230 )
1231 return cookidoo_search_result_from_json(
1232 cast(SearchResultJSON, result), self._cfg.localization
1233 )
1234
1235 async def get_custom_recipe(self, id: str) -> CookidooCustomRecipe:
1236 """Get custom recipe.
1237
1238 Parameters
1239 ----------
1240 id
1241 The id of the custom recipe
1242
1243 Returns
1244 -------
1245 CookidooCustomRecipe
1246 The custom recipe
1247
1248 Raises
1249 ------
1250 CookidooAuthException
1251 When the access token is not valid anymore
1252 CookidooRequestException
1253 If the request fails.
1254 CookidooParseException
1255 If the parsing of the request response fails.
1256
1257 """
1258
1259 await self._ensure_endpoints()
1260 url = self.api_endpoint / self._path("customer-recipes:recipe-details").format(
1261 **self._cfg.localization.__dict__, id=id
1262 )
1263 result = self._ensure_mapping(
1264 await self._request_json("get", url, "loading custom recipe"),
1265 "loading custom recipe",
1266 )
1267 return self._parse_result(
1268 "loading custom recipe",
1269 lambda: cookidoo_custom_recipe_from_json(
1270 cast(CustomRecipeJSON, result),
1271 self._cfg.localization,
1272 ),
1273 )
1274
1275 async def list_custom_recipes(self) -> list[CookidooCustomRecipe]:
1276 """List custom recipes."""
1277 await self._ensure_endpoints()
1278 url = self.api_endpoint / self._path("customer-recipes:recipe-create").format(
1279 **self._cfg.localization.__dict__
1280 )
1281 result = self._ensure_mapping(
1282 await self._request_json(
1283 "get",
1284 url,
1285 "listing custom recipes",
1286 headers={"ACCEPT": CUSTOM_RECIPES_PATH_ACCEPT},
1287 ),
1288 "listing custom recipes",
1289 )
1290 if not isinstance(result.get("items"), list):
1291 raise CookidooParseException(
1292 "Listing custom recipes failed during parsing of request response."
1293 )
1294
1295 custom_recipes = cast(CustomRecipesJSON, result)
1296 return self._parse_result(
1297 "listing custom recipes",
1298 lambda: [
1299 cookidoo_custom_recipe_from_json(recipe, self._cfg.localization)
1300 for recipe in custom_recipes["items"]
1301 ],
1302 )
1303
1304 async def add_custom_recipe_from(
1305 self, recipeId: str, servingSize: int
1306 ) -> CookidooCustomRecipe:
1307 """Add custom recipe.
1308
1309 Parameters
1310 ----------
1311 recipeId
1312 The base recipe to copy
1313 servingSize
1314 The serving size of the custom recipe
1315
1316 Returns
1317 -------
1318 CookidooCustomRecipe
1319 The added custom recipe
1320
1321 Raises
1322 ------
1323 CookidooAuthException
1324 When the access token is not valid anymore
1325 CookidooRequestException
1326 If the request fails.
1327 CookidooParseException
1328 If the parsing of the request response fails.
1329
1330 """
1331 await self._ensure_endpoints()
1332 json_data = {
1333 "recipeUrl": str(
1334 self.api_endpoint
1335 / self._path("recipe:details").format(
1336 **self._cfg.localization.__dict__, id=recipeId
1337 )
1338 ),
1339 "servingSize": servingSize,
1340 }
1341 url = self.api_endpoint / self._path("customer-recipes:recipe-create").format(
1342 **self._cfg.localization.__dict__
1343 )
1344 result = self._ensure_mapping(
1345 await self._request_json("post", url, "add custom recipe", json=json_data),
1346 "add custom recipe",
1347 )
1348 return self._parse_result(
1349 "add custom recipe",
1350 lambda: cookidoo_custom_recipe_from_json(
1351 cast(CustomRecipeJSON, result),
1352 self._cfg.localization,
1353 ),
1354 )
1355
1356 async def remove_custom_recipe(
1357 self,
1358 custom_recipe_id: str,
1359 ) -> None:
1360 """Remove custom recipe.
1361
1362 Parameters
1363 ----------
1364 custom_recipe_id
1365 The custom recipe id to remove
1366
1367 Raises
1368 ------
1369 CookidooAuthException
1370 When the access token is not valid anymore
1371 CookidooRequestException
1372 If the request fails.
1373 CookidooParseException
1374 If the parsing of the request response fails.
1375
1376 """
1377 await self._ensure_endpoints()
1378 url = self.api_endpoint / self._path("customer-recipes:recipe-details").format(
1379 **self._cfg.localization.__dict__, id=custom_recipe_id
1380 )
1381 await self._request_json(
1382 "delete", url, "remove custom recipe", parse_response=False
1383 )
1384
1385 async def get_shopping_list_recipes(
1386 self,
1387 ) -> list[CookidooShoppingRecipe]:
1388 """Get recipes.
1389
1390 Returns
1391 -------
1392 list[CookidooShoppingRecipe]
1393 The list of the recipes
1394
1395 Raises
1396 ------
1397 CookidooAuthException
1398 When the access token is not valid anymore
1399 CookidooRequestException
1400 If the request fails.
1401 CookidooParseException
1402 If the parsing of the request response fails.
1403
1404 """
1405
1406 await self._ensure_endpoints()
1407 url = self.api_endpoint / self._path("pantry:home").format(
1408 **self._cfg.localization.__dict__
1409 )
1410 result = self._ensure_mapping(
1411 await self._request_json("get", url, "loading recipes"),
1412 "loading recipes",
1413 )
1414 return self._parse_result(
1415 "loading recipes",
1416 lambda: [
1417 cookidoo_recipe_from_json(
1418 cast(RecipeJSON, recipe), self._cfg.localization
1419 )
1420 for recipe in [
1421 *cast(Sequence[object], result["recipes"]),
1422 *cast(Sequence[object], result["customerRecipes"]),
1423 ]
1424 ],
1425 )
1426
1427 async def get_ingredient_items(
1428 self,
1429 ) -> list[CookidooIngredientItem]:
1430 """Get ingredient items.
1431
1432 Returns
1433 -------
1434 list[CookidooIngredientItem]
1435 The list of the ingredient items
1436
1437 Raises
1438 ------
1439 CookidooAuthException
1440 When the access token is not valid anymore
1441 CookidooRequestException
1442 If the request fails.
1443 CookidooParseException
1444 If the parsing of the request response fails.
1445
1446 """
1447
1448 await self._ensure_endpoints()
1449 url = self.api_endpoint / self._path("pantry:home").format(
1450 **self._cfg.localization.__dict__
1451 )
1452 result = self._ensure_mapping(
1453 await self._request_json("get", url, "loading ingredient items"),
1454 "loading ingredient items",
1455 )
1456 return self._parse_result(
1457 "loading ingredient items",
1458 lambda: [
1459 cookidoo_ingredient_item_from_json(cast(ItemJSON, ingredient))
1460 for recipe in [
1461 *cast(Sequence[Mapping[str, object]], result["recipes"]),
1462 *cast(Sequence[Mapping[str, object]], result["customerRecipes"]),
1463 ]
1464 for ingredient in cast(
1465 Sequence[object], recipe["recipeIngredientGroups"]
1466 )
1467 ],
1468 )
1469
1470 async def add_ingredient_items_for_recipes(
1471 self,
1472 recipe_ids: list[str],
1473 ) -> list[CookidooIngredientItem]:
1474 """Add ingredient items for recipes.
1475
1476 Parameters
1477 ----------
1478 recipe_ids
1479 The recipe ids for the ingredient items to add to the shopping list
1480
1481 Returns
1482 -------
1483 list[CookidooIngredientItem]
1484 The list of the added ingredient items
1485
1486 Raises
1487 ------
1488 CookidooAuthException
1489 When the access token is not valid anymore
1490 CookidooRequestException
1491 If the request fails.
1492 CookidooParseException
1493 If the parsing of the request response fails.
1494
1495 """
1496 json_data = {"recipeIDs": recipe_ids}
1497 await self._ensure_endpoints()
1498 url = self.api_endpoint / self._path("pantry:recipe-ingredients").format(
1499 **self._cfg.localization.__dict__
1500 )
1501 result = self._ensure_mapping(
1502 await self._request_json(
1503 "post", url, "add ingredient items for recipes", json=json_data
1504 ),
1505 "add ingredient items for recipes",
1506 )
1507 return self._parse_result(
1508 "loading added ingredient items",
1509 lambda: [
1510 cookidoo_ingredient_item_from_json(cast(ItemJSON, ingredient))
1511 for recipe in cast(Sequence[Mapping[str, object]], result["data"])
1512 for ingredient in cast(
1513 Sequence[object], recipe["recipeIngredientGroups"]
1514 )
1515 ],
1516 )
1517
1518 async def remove_ingredient_items_for_recipes(
1519 self,
1520 recipe_ids: list[str],
1521 ) -> None:
1522 """Remove ingredient items for recipes.
1523
1524 Parameters
1525 ----------
1526 recipe_ids
1527 The recipe ids for the ingredient items to remove to the shopping list
1528
1529 Raises
1530 ------
1531 CookidooAuthException
1532 When the access token is not valid anymore
1533 CookidooRequestException
1534 If the request fails.
1535 CookidooParseException
1536 If the parsing of the request response fails.
1537
1538 """
1539 json_data = {"recipeIDs": recipe_ids}
1540 await self._ensure_endpoints()
1541 url = self.api_endpoint / self._path("pantry:remove-recipe").format(
1542 **self._cfg.localization.__dict__
1543 )
1544 await self._request_json(
1545 "post",
1546 url,
1547 "remove ingredient items for recipes",
1548 json=json_data,
1549 parse_response=False,
1550 )
1551
1552 async def edit_ingredient_items_ownership(
1553 self,
1554 ingredient_items: list[CookidooIngredientItem],
1555 ) -> list[CookidooIngredientItem]:
1556 """Edit ownership ingredient items.
1557
1558 Parameters
1559 ----------
1560 ingredient_items
1561 The ingredient items to change the the `is_owned` value for
1562
1563 Returns
1564 -------
1565 list[CookidooIngredientItem]
1566 The list of the edited ingredient items
1567
1568 Raises
1569 ------
1570 CookidooAuthException
1571 When the access token is not valid anymore
1572 CookidooRequestException
1573 If the request fails.
1574 CookidooParseException
1575 If the parsing of the request response fails.
1576
1577 """
1578 json_data = {
1579 "ingredients": [
1580 {
1581 "id": ingredient_item.id,
1582 "isOwned": ingredient_item.is_owned,
1583 "ownedTimestamp": int(time.time()),
1584 }
1585 for ingredient_item in ingredient_items
1586 ]
1587 }
1588 await self._ensure_endpoints()
1589 url = self.api_endpoint / self._path(
1590 "pantry:edit-ingredients-ownership"
1591 ).format(**self._cfg.localization.__dict__)
1592 result = self._ensure_mapping(
1593 await self._request_json(
1594 "post", url, "edit ingredient items ownership", json=json_data
1595 ),
1596 "edit ingredient items ownership",
1597 )
1598 return self._parse_result(
1599 "loading edited ingredient items",
1600 lambda: [
1601 cookidoo_ingredient_item_from_json(cast(ItemJSON, ingredient))
1602 for ingredient in cast(Sequence[object], result["data"])
1603 ],
1604 )
1605
1606 async def add_ingredient_items_for_custom_recipes(
1607 self,
1608 recipe_ids: list[str],
1609 ) -> list[CookidooIngredientItem]:
1610 """Add ingredient items for custom recipes.
1611
1612 Parameters
1613 ----------
1614 recipe_ids
1615 The recipe ids for the ingredient items to add to the shopping list
1616
1617 Returns
1618 -------
1619 list[CookidooIngredientItem]
1620 The list of the added ingredient items
1621
1622 Raises
1623 ------
1624 CookidooAuthException
1625 When the access token is not valid anymore
1626 CookidooRequestException
1627 If the request fails.
1628 CookidooParseException
1629 If the parsing of the request response fails.
1630
1631 """
1632 json_data = {
1633 "recipeIDs": [
1634 {"id": recipe_id, "source": "CUSTOMER"} for recipe_id in recipe_ids
1635 ]
1636 }
1637 await self._ensure_endpoints()
1638 url = self.api_endpoint / self._path("pantry:recipe-ingredients").format(
1639 **self._cfg.localization.__dict__
1640 )
1641 result = self._ensure_mapping(
1642 await self._request_json(
1643 "post", url, "add ingredient items for custom recipes", json=json_data
1644 ),
1645 "add ingredient items for custom recipes",
1646 )
1647 return self._parse_result(
1648 "loading added ingredient items",
1649 lambda: [
1650 cookidoo_ingredient_item_from_json(cast(ItemJSON, ingredient))
1651 for recipe in cast(Sequence[Mapping[str, object]], result["data"])
1652 for ingredient in cast(
1653 Sequence[object], recipe["recipeIngredientGroups"]
1654 )
1655 ],
1656 )
1657
1658 async def remove_ingredient_items_for_custom_recipes(
1659 self,
1660 recipe_ids: list[str],
1661 ) -> None:
1662 """Remove ingredient items for custom recipes.
1663
1664 Parameters
1665 ----------
1666 recipe_ids
1667 The custom recipe ids for the ingredient items to remove to the shopping list
1668
1669 Raises
1670 ------
1671 CookidooAuthException
1672 When the access token is not valid anymore
1673 CookidooRequestException
1674 If the request fails.
1675 CookidooParseException
1676 If the parsing of the request response fails.
1677
1678 """
1679 json_data = {"recipeIDs": recipe_ids}
1680 await self._ensure_endpoints()
1681 url = self.api_endpoint / self._path("pantry:remove-recipe").format(
1682 **self._cfg.localization.__dict__
1683 )
1684 await self._request_json(
1685 "post",
1686 url,
1687 "remove ingredient items for custom recipes",
1688 json=json_data,
1689 parse_response=False,
1690 )
1691
1692 async def get_additional_items(
1693 self,
1694 ) -> list[CookidooAdditionalItem]:
1695 """Get additional items.
1696
1697 Returns
1698 -------
1699 list[CookidooAdditionalItem]
1700 The list of the additional items
1701
1702 Raises
1703 ------
1704 CookidooAuthException
1705 When the access token is not valid anymore
1706 CookidooRequestException
1707 If the request fails.
1708 CookidooParseException
1709 If the parsing of the request response fails.
1710
1711 """
1712
1713 await self._ensure_endpoints()
1714 url = self.api_endpoint / self._path("pantry:home").format(
1715 **self._cfg.localization.__dict__
1716 )
1717 result = self._ensure_mapping(
1718 await self._request_json("get", url, "loading additional items"),
1719 "loading additional items",
1720 )
1721 return self._parse_result(
1722 "loading additional items",
1723 lambda: [
1724 cookidoo_additional_item_from_json(
1725 cast(AdditionalItemJSON, additional_item)
1726 )
1727 for additional_item in cast(Sequence[object], result["additionalItems"])
1728 ],
1729 )
1730
1731 async def add_additional_items(
1732 self,
1733 additional_item_names: list[str],
1734 ) -> list[CookidooAdditionalItem]:
1735 """Create additional items.
1736
1737 Parameters
1738 ----------
1739 additional_item_names
1740 The additional item names to create, only the label can be set, as the default state `is_owned=false` is forced (chain with immediate update call for work-around)
1741
1742 Returns
1743 -------
1744 list[CookidooAdditionalItem]
1745 The list of the added additional items
1746
1747 Raises
1748 ------
1749 CookidooAuthException
1750 When the access token is not valid anymore
1751 CookidooRequestException
1752 If the request fails.
1753 CookidooParseException
1754 If the parsing of the request response fails.
1755
1756 """
1757 json_data = {"itemsValue": additional_item_names}
1758 await self._ensure_endpoints()
1759 url = self.api_endpoint / self._path("pantry:add-additional-items-v2").format(
1760 **self._cfg.localization.__dict__
1761 )
1762 result = self._ensure_mapping(
1763 await self._request_json(
1764 "post", url, "add additional items", json=json_data
1765 ),
1766 "add additional items",
1767 )
1768 return self._parse_result(
1769 "loading added additional items",
1770 lambda: [
1771 cookidoo_additional_item_from_json(
1772 cast(AdditionalItemJSON, additional_item)
1773 )
1774 for additional_item in cast(Sequence[object], result["data"])
1775 ],
1776 )
1777
1778 async def edit_additional_items(
1779 self,
1780 additional_items: list[CookidooAdditionalItem],
1781 ) -> list[CookidooAdditionalItem]:
1782 """Edit additional items.
1783
1784 Parameters
1785 ----------
1786 additional_items
1787 The additional items to change the the `name` value for
1788
1789 Returns
1790 -------
1791 list[CookidooAdditionalItem]
1792 The list of the edited additional items
1793
1794 Raises
1795 ------
1796 CookidooAuthException
1797 When the access token is not valid anymore
1798 CookidooRequestException
1799 If the request fails.
1800 CookidooParseException
1801 If the parsing of the request response fails.
1802
1803 """
1804 json_data = {
1805 "additionalItems": [
1806 {
1807 "id": additional_item.id,
1808 "name": additional_item.name,
1809 }
1810 for additional_item in additional_items
1811 ]
1812 }
1813 await self._ensure_endpoints()
1814 url = self.api_endpoint / self._path("pantry:edit-additional-items").format(
1815 **self._cfg.localization.__dict__
1816 )
1817 result = self._ensure_mapping(
1818 await self._request_json(
1819 "post", url, "edit additional items", json=json_data
1820 ),
1821 "edit additional items",
1822 )
1823 return self._parse_result(
1824 "loading edited additional items",
1825 lambda: [
1826 cookidoo_additional_item_from_json(
1827 cast(AdditionalItemJSON, additional_item)
1828 )
1829 for additional_item in cast(Sequence[object], result["data"])
1830 ],
1831 )
1832
1833 async def edit_additional_items_ownership(
1834 self,
1835 additional_items: list[CookidooAdditionalItem],
1836 ) -> list[CookidooAdditionalItem]:
1837 """Edit ownership additional items.
1838
1839 Parameters
1840 ----------
1841 additional_items
1842 The additional items to change the the `is_owned` value for
1843
1844 Returns
1845 -------
1846 list[CookidooAdditionalItem]
1847 The list of the edited additional items
1848
1849 Raises
1850 ------
1851 CookidooAuthException
1852 When the access token is not valid anymore
1853 CookidooRequestException
1854 If the request fails.
1855 CookidooParseException
1856 If the parsing of the request response fails.
1857
1858 """
1859 json_data = {
1860 "additionalItems": [
1861 {
1862 "id": additional_item.id,
1863 "isOwned": additional_item.is_owned,
1864 "ownedTimestamp": int(time.time()),
1865 }
1866 for additional_item in additional_items
1867 ]
1868 }
1869 await self._ensure_endpoints()
1870 url = self.api_endpoint / self._path(
1871 "pantry:edit-additional-items-ownership"
1872 ).format(**self._cfg.localization.__dict__)
1873 result = self._ensure_mapping(
1874 await self._request_json(
1875 "post", url, "edit additional items ownership", json=json_data
1876 ),
1877 "edit additional items ownership",
1878 )
1879 return self._parse_result(
1880 "loading edited additional items",
1881 lambda: [
1882 cookidoo_additional_item_from_json(
1883 cast(AdditionalItemJSON, additional_item)
1884 )
1885 for additional_item in cast(Sequence[object], result["data"])
1886 ],
1887 )
1888
1889 async def remove_additional_items(
1890 self,
1891 additional_item_ids: list[str],
1892 ) -> None:
1893 """Remove additional items.
1894
1895 Parameters
1896 ----------
1897 additional_item_ids
1898 The additional item ids to remove
1899
1900 Raises
1901 ------
1902 CookidooAuthException
1903 When the access token is not valid anymore
1904 CookidooRequestException
1905 If the request fails.
1906 CookidooParseException
1907 If the parsing of the request response fails.
1908
1909 """
1910 json_data = {"additionalItemIDs": additional_item_ids}
1911 await self._ensure_endpoints()
1912 url = self.api_endpoint / self._path("pantry:remove-additional-items").format(
1913 **self._cfg.localization.__dict__
1914 )
1915 await self._request_json(
1916 "post",
1917 url,
1918 "remove additional items",
1919 json=json_data,
1920 parse_response=False,
1921 )
1922
1923 async def clear_shopping_list(
1924 self,
1925 ) -> None:
1926 """Remove all additional items, ingredients and recipes.
1927
1928 Raises
1929 ------
1930 CookidooAuthException
1931 When the access token is not valid anymore
1932 CookidooRequestException
1933 If the request fails.
1934 CookidooParseException
1935 If the parsing of the request response fails.
1936
1937 """
1938 await self._ensure_endpoints()
1939 url = self.api_endpoint / self._path("pantry:home").format(
1940 **self._cfg.localization.__dict__
1941 )
1942 await self._request_json(
1943 "delete", url, "clear shopping list", parse_response=False
1944 )
1945
1946 async def count_managed_collections(self) -> tuple[int, int]:
1947 """Get managed collections.
1948
1949 Returns
1950 -------
1951 tuple[int, int]
1952 The number of managed collections and the number of pages
1953
1954 Raises
1955 ------
1956 CookidooAuthException
1957 When the access token is not valid anymore
1958 CookidooRequestException
1959 If the request fails.
1960 CookidooParseException
1961 If the parsing of the request response fails.
1962
1963 """
1964
1965 await self._ensure_endpoints()
1966 url = self.api_endpoint / self._path("organize:api-managed-list").format(
1967 **self._cfg.localization.__dict__
1968 )
1969 result = self._ensure_mapping(
1970 await self._request_json(
1971 "get",
1972 url,
1973 "loading managed collections",
1974 headers={"ACCEPT": MANAGED_COLLECTIONS_PATH_ACCEPT},
1975 ),
1976 "loading managed collections",
1977 )
1978 return self._parse_result(
1979 "loading managed collections",
1980 lambda: (
1981 cast(PaginationJSON, result["page"])["totalElements"],
1982 cast(PaginationJSON, result["page"])["totalPages"],
1983 ),
1984 )
1985
1986 async def get_managed_collections(self, page: int = 0) -> list[CookidooCollection]:
1987 """Get managed collections.
1988
1989 Parameters
1990 ----------
1991 page
1992 The page of the managed collections
1993
1994 Returns
1995 -------
1996 list[CookidooCollection]
1997 The list of the managed collections
1998
1999 Raises
2000 ------
2001 CookidooAuthException
2002 When the access token is not valid anymore
2003 CookidooRequestException
2004 If the request fails.
2005 CookidooParseException
2006 If the parsing of the request response fails.
2007
2008 """
2009
2010 await self._ensure_endpoints()
2011 url = self.api_endpoint / self._path("organize:api-managed-list").format(
2012 **self._cfg.localization.__dict__
2013 )
2014 result = self._ensure_mapping(
2015 await self._request_json(
2016 "get",
2017 url,
2018 "loading managed collections",
2019 params={"page": str(page)},
2020 headers={"ACCEPT": MANAGED_COLLECTIONS_PATH_ACCEPT},
2021 ),
2022 "loading managed collections",
2023 )
2024 return self._parse_result(
2025 "loading managed collections",
2026 lambda: [
2027 cookidoo_collection_from_json(cast(ManagedCollectionJSON, item))
2028 for item in cast(Sequence[object], result["managedlists"])
2029 ],
2030 )
2031
2032 async def add_managed_collection(
2033 self,
2034 managed_collection_id: str,
2035 ) -> CookidooCollection:
2036 """Add managed collections.
2037
2038 Parameters
2039 ----------
2040 managed_collection_id
2041 The managed collection id to add
2042
2043 Returns
2044 -------
2045 CookidooCollection
2046 The added managed collection
2047
2048 Raises
2049 ------
2050 CookidooAuthException
2051 When the access token is not valid anymore
2052 CookidooRequestException
2053 If the request fails.
2054 CookidooParseException
2055 If the parsing of the request response fails.
2056
2057 """
2058 json_data = {"collectionId": managed_collection_id}
2059 await self._ensure_endpoints()
2060 url = self.api_endpoint / self._path("organize:api-managed-list").format(
2061 **self._cfg.localization.__dict__
2062 )
2063 result = self._ensure_mapping(
2064 await self._request_json(
2065 "post",
2066 url,
2067 "add managed collection",
2068 json=json_data,
2069 headers={"ACCEPT": MANAGED_COLLECTIONS_PATH_ACCEPT},
2070 ),
2071 "add managed collection",
2072 )
2073 return self._parse_result(
2074 "loading added managed collection",
2075 lambda: cookidoo_collection_from_json(
2076 cast(ManagedCollectionJSON, result["content"])
2077 ),
2078 )
2079
2080 async def remove_managed_collection(
2081 self,
2082 managed_collection_id: str,
2083 ) -> None:
2084 """Remove managed collection.
2085
2086 Parameters
2087 ----------
2088 managed_collection_id
2089 The managed collection id to remove
2090
2091 Raises
2092 ------
2093 CookidooAuthException
2094 When the access token is not valid anymore
2095 CookidooRequestException
2096 If the request fails.
2097 CookidooParseException
2098 If the parsing of the request response fails.
2099
2100 """
2101 await self._ensure_endpoints()
2102 url = self.api_endpoint / self._path("organize:api-managed-list-single").format(
2103 **self._cfg.localization.__dict__, id=managed_collection_id
2104 )
2105 await self._request_json(
2106 "delete",
2107 url,
2108 "remove managed collection",
2109 headers={"ACCEPT": MANAGED_COLLECTIONS_PATH_ACCEPT},
2110 parse_response=False,
2111 )
2112
2113 async def count_custom_collections(self) -> tuple[int, int]:
2114 """Get custom collections.
2115
2116 Returns
2117 -------
2118 tuple[int, int]
2119 The number of custom collections and the number of pages
2120
2121 Raises
2122 ------
2123 CookidooAuthException
2124 When the access token is not valid anymore
2125 CookidooRequestException
2126 If the request fails.
2127 CookidooParseException
2128 If the parsing of the request response fails.
2129
2130 """
2131
2132 await self._ensure_endpoints()
2133 url = self.api_endpoint / self._path("organize:api-custom-list").format(
2134 **self._cfg.localization.__dict__
2135 )
2136 result = self._ensure_mapping(
2137 await self._request_json(
2138 "get",
2139 url,
2140 "loading custom collections",
2141 headers={"ACCEPT": CUSTOM_COLLECTIONS_PATH_ACCEPT},
2142 ),
2143 "loading custom collections",
2144 )
2145 return self._parse_result(
2146 "loading custom collections",
2147 lambda: (
2148 cast(PaginationJSON, result["page"])["totalElements"],
2149 cast(PaginationJSON, result["page"])["totalPages"],
2150 ),
2151 )
2152
2153 async def get_custom_collections(self, page: int = 0) -> list[CookidooCollection]:
2154 """Get custom collections.
2155
2156 Parameters
2157 ----------
2158 page
2159 The page of the custom collections
2160
2161 Returns
2162 -------
2163 list[CookidooCollection]
2164 The list of the custom collections
2165
2166 Raises
2167 ------
2168 CookidooAuthException
2169 When the access token is not valid anymore
2170 CookidooRequestException
2171 If the request fails.
2172 CookidooParseException
2173 If the parsing of the request response fails.
2174
2175 """
2176
2177 await self._ensure_endpoints()
2178 url = self.api_endpoint / self._path("organize:api-custom-list").format(
2179 **self._cfg.localization.__dict__
2180 )
2181 result = self._ensure_mapping(
2182 await self._request_json(
2183 "get",
2184 url,
2185 "loading custom collections",
2186 params={"page": str(page)},
2187 headers={"ACCEPT": CUSTOM_COLLECTIONS_PATH_ACCEPT},
2188 ),
2189 "loading custom collections",
2190 )
2191 return self._parse_result(
2192 "loading custom collections",
2193 lambda: [
2194 cookidoo_collection_from_json(cast(CustomCollectionJSON, item))
2195 for item in cast(Sequence[object], result["customlists"])
2196 ],
2197 )
2198
2199 async def add_custom_collection(
2200 self,
2201 custom_collection_name: str,
2202 ) -> CookidooCollection:
2203 """Add custom collections.
2204
2205 Parameters
2206 ----------
2207 custom_collection_name
2208 The custom collection name to add
2209
2210 Returns
2211 -------
2212 CookidooCollection
2213 The added custom collection
2214
2215 Raises
2216 ------
2217 CookidooAuthException
2218 When the access token is not valid anymore
2219 CookidooRequestException
2220 If the request fails.
2221 CookidooParseException
2222 If the parsing of the request response fails.
2223
2224 """
2225 json_data = {"title": custom_collection_name}
2226 await self._ensure_endpoints()
2227 url = self.api_endpoint / self._path("organize:api-custom-list").format(
2228 **self._cfg.localization.__dict__
2229 )
2230 result = self._ensure_mapping(
2231 await self._request_json(
2232 "post",
2233 url,
2234 "add custom collection",
2235 json=json_data,
2236 headers={"ACCEPT": CUSTOM_COLLECTIONS_PATH_ACCEPT},
2237 ),
2238 "add custom collection",
2239 )
2240 return self._parse_result(
2241 "loading added custom collection",
2242 lambda: cookidoo_collection_from_json(
2243 cast(CustomCollectionJSON, result["content"])
2244 ),
2245 )
2246
2247 async def remove_custom_collection(
2248 self,
2249 custom_collection_id: str,
2250 ) -> None:
2251 """Remove custom collection.
2252
2253 Parameters
2254 ----------
2255 custom_collection_id
2256 The custom collection id to remove
2257
2258 Raises
2259 ------
2260 CookidooAuthException
2261 When the access token is not valid anymore
2262 CookidooRequestException
2263 If the request fails.
2264 CookidooParseException
2265 If the parsing of the request response fails.
2266
2267 """
2268 await self._ensure_endpoints()
2269 url = self.api_endpoint / self._path("organize:api-custom-list-modify").format(
2270 **self._cfg.localization.__dict__, id=custom_collection_id
2271 )
2272 await self._request_json(
2273 "delete",
2274 url,
2275 "remove custom collection",
2276 headers={"ACCEPT": CUSTOM_COLLECTIONS_PATH_ACCEPT},
2277 parse_response=False,
2278 )
2279
2280 async def add_recipes_to_custom_collection(
2281 self,
2282 custom_collection_id: str,
2283 recipe_ids: list[str],
2284 ) -> CookidooCollection:
2285 """Add recipes to a custom collections.
2286
2287 Parameters
2288 ----------
2289 custom_collection_id
2290 The custom collection to add the recipes to
2291 recipe_ids
2292 The recipe ids to add to a custom collection
2293
2294 Returns
2295 -------
2296 CookidooCollection
2297 The changed custom collection
2298
2299 Raises
2300 ------
2301 CookidooAuthException
2302 When the access token is not valid anymore
2303 CookidooRequestException
2304 If the request fails.
2305 CookidooParseException
2306 If the parsing of the request response fails.
2307
2308 """
2309 json_data = {"recipeIds": recipe_ids}
2310 await self._ensure_endpoints()
2311 url = self.api_endpoint / self._path("organize:api-custom-list-modify").format(
2312 **self._cfg.localization.__dict__, id=custom_collection_id
2313 )
2314 result = self._ensure_mapping(
2315 await self._request_json(
2316 "put", url, "add recipes to custom collection", json=json_data
2317 ),
2318 "add recipes to custom collection",
2319 )
2320 return self._parse_result(
2321 "loading added recipes",
2322 lambda: cookidoo_collection_from_json(
2323 cast(CustomCollectionJSON, result["content"])
2324 ),
2325 )
2326
2327 async def remove_recipe_from_custom_collection(
2328 self,
2329 custom_collection_id: str,
2330 recipe_id: str,
2331 ) -> CookidooCollection:
2332 """Remove recipe from a custom collections.
2333
2334 Parameters
2335 ----------
2336 custom_collection_id
2337 The custom collection to remove the recipe from
2338 recipe_id
2339 The recipe id to remove from a custom collection
2340
2341 Returns
2342 -------
2343 CookidooCollection
2344 The changed custom collection
2345
2346 Raises
2347 ------
2348 CookidooAuthException
2349 When the access token is not valid anymore
2350 CookidooRequestException
2351 If the request fails.
2352 CookidooParseException
2353 If the parsing of the request response fails.
2354
2355 """
2356 await self._ensure_endpoints()
2357 url = self.api_endpoint / self._path("organize:api-custom-list-recipe").format(
2358 **self._cfg.localization.__dict__,
2359 id=custom_collection_id,
2360 recipe=recipe_id,
2361 )
2362 result = self._ensure_mapping(
2363 await self._request_json(
2364 "delete", url, "remove recipe from custom collection"
2365 ),
2366 "remove recipe from custom collection",
2367 )
2368 return self._parse_result(
2369 "loading removed recipe",
2370 lambda: cookidoo_collection_from_json(
2371 cast(CustomCollectionJSON, result["content"])
2372 ),
2373 )
2374
2375 async def get_recipes_in_calendar_week(
2376 self, day: date
2377 ) -> list[CookidooCalendarDay]:
2378 """Get recipes in a calendar week.
2379
2380 Parameters
2381 ----------
2382 day
2383 The date specifying the calendar week
2384
2385 Returns
2386 -------
2387 list[CookidooCalendarDay]
2388 The list of the calendar days with recipes
2389
2390 Raises
2391 ------
2392 CookidooAuthException
2393 When the access token is not valid anymore
2394 CookidooRequestException
2395 If the request fails.
2396 CookidooParseException
2397 If the parsing of the request response fails.
2398
2399 """
2400
2401 await self._ensure_endpoints()
2402 url = self.api_endpoint / self._path("planning:api-my-week-from-date").format(
2403 **self._cfg.localization.__dict__, day=day.isoformat()
2404 )
2405 result = self._ensure_mapping(
2406 await self._request_json("get", url, "loading recipes in calendar week"),
2407 "loading recipes in calendar week",
2408 )
2409 return self._parse_result(
2410 "loading recipes in calendar week",
2411 lambda: [
2412 cookidoo_calendar_day_from_json(
2413 cast(CalendarDayJSON, calendar_day), self._cfg.localization
2414 )
2415 for calendar_day in cast(Sequence[object], result["myDays"])
2416 ],
2417 )
2418
2419 async def add_recipes_to_calendar(
2420 self,
2421 day: date,
2422 recipe_ids: list[str],
2423 ) -> CookidooCalendarDay:
2424 """Add recipes to a calendar.
2425
2426 Parameters
2427 ----------
2428 day
2429 The date to add the recipes to in the calendar
2430 recipe_ids
2431 The recipe ids to add to the calendar
2432
2433 Returns
2434 -------
2435 CookidooCalendarDay
2436 The changed calendar day
2437
2438 Raises
2439 ------
2440 CookidooAuthException
2441 When the access token is not valid anymore
2442 CookidooRequestException
2443 If the request fails.
2444 CookidooParseException
2445 If the parsing of the request response fails.
2446
2447 """
2448 json_data = {"recipeIds": recipe_ids, "dayKey": day.isoformat()}
2449 await self._ensure_endpoints()
2450 url = self.api_endpoint / self._path("planning:api-my-day").format(
2451 **self._cfg.localization.__dict__
2452 )
2453 result = self._ensure_mapping(
2454 await self._request_json(
2455 "put", url, "add recipes to calendar", json=json_data
2456 ),
2457 "add recipes to calendar",
2458 )
2459 return self._parse_result(
2460 "loading added recipes",
2461 lambda: cookidoo_calendar_day_from_json(
2462 cast(CalendarDayJSON, result["content"]),
2463 self._cfg.localization,
2464 ),
2465 )
2466
2467 async def remove_recipe_from_calendar(
2468 self,
2469 day: date,
2470 recipe_id: str,
2471 ) -> CookidooCalendarDay:
2472 """Remove recipe from calendar.
2473
2474 Parameters
2475 ----------
2476 day
2477 The date to remove the recipe from in the calendar
2478 recipe_id
2479 The recipe id to remove from the calendar
2480
2481 Returns
2482 -------
2483 CookidooCalendarDay
2484 The changed calendar day
2485
2486 Raises
2487 ------
2488 CookidooAuthException
2489 When the access token is not valid anymore
2490 CookidooRequestException
2491 If the request fails.
2492 CookidooParseException
2493 If the parsing of the request response fails.
2494
2495 """
2496 await self._ensure_endpoints()
2497 url = self.api_endpoint / self._path("planning:api-my-day-recipes").format(
2498 **self._cfg.localization.__dict__,
2499 day=day.isoformat(),
2500 recipe=recipe_id,
2501 )
2502 result = self._ensure_mapping(
2503 await self._request_json("delete", url, "remove recipe from calendar"),
2504 "remove recipe from calendar",
2505 )
2506 if result.get("content") is None:
2507 # The API returns a null content when the removed recipe was the
2508 # last one for the day, since the (now empty) day no longer
2509 # exists as an entity.
2510 return self._empty_calendar_day(day)
2511 return self._parse_result(
2512 "loading removed recipe",
2513 lambda: cookidoo_calendar_day_from_json(
2514 cast(CalendarDayJSON, result["content"]),
2515 self._cfg.localization,
2516 ),
2517 )
2518
2519 async def add_custom_recipes_to_calendar(
2520 self,
2521 day: date,
2522 recipe_ids: list[str],
2523 ) -> CookidooCalendarDay:
2524 """Add custom recipes to a calendar.
2525
2526 Parameters
2527 ----------
2528 day
2529 The date to add the custom recipes to in the calendar
2530 recipe_ids
2531 The recipe ids to add to the calendar
2532
2533 Returns
2534 -------
2535 CookidooCalendarDay
2536 The changed calendar day
2537
2538 Raises
2539 ------
2540 CookidooAuthException
2541 When the access token is not valid anymore
2542 CookidooRequestException
2543 If the request fails.
2544 CookidooParseException
2545 If the parsing of the request response fails.
2546
2547 """
2548 json_data = {
2549 "recipeIds": recipe_ids,
2550 "dayKey": day.isoformat(),
2551 "recipeSource": "CUSTOMER",
2552 }
2553 await self._ensure_endpoints()
2554 url = self.api_endpoint / self._path("planning:api-my-day").format(
2555 **self._cfg.localization.__dict__
2556 )
2557 result = self._ensure_mapping(
2558 await self._request_json(
2559 "put", url, "add custom recipes to calendar", json=json_data
2560 ),
2561 "add custom recipes to calendar",
2562 )
2563 return self._parse_result(
2564 "loading added custom recipes",
2565 lambda: cookidoo_calendar_day_from_json(
2566 cast(CalendarDayJSON, result["content"]),
2567 self._cfg.localization,
2568 ),
2569 )
2570
2571 async def remove_custom_recipe_from_calendar(
2572 self,
2573 day: date,
2574 recipe_id: str,
2575 ) -> CookidooCalendarDay:
2576 """Remove custom recipe from calendar.
2577
2578 Parameters
2579 ----------
2580 day
2581 The date to remove the custom recipe from in the calendar
2582 recipe_id
2583 The custom recipe id to remove from the calendar
2584
2585 Returns
2586 -------
2587 CookidooCalendarDay
2588 The changed calendar day
2589
2590 Raises
2591 ------
2592 CookidooAuthException
2593 When the access token is not valid anymore
2594 CookidooRequestException
2595 If the request fails.
2596 CookidooParseException
2597 If the parsing of the request response fails.
2598
2599 """
2600 await self._ensure_endpoints()
2601 url = self.api_endpoint / self._path("planning:api-my-day-recipes").format(
2602 **self._cfg.localization.__dict__,
2603 day=day.isoformat(),
2604 recipe=recipe_id,
2605 )
2606 result = self._ensure_mapping(
2607 await self._request_json(
2608 "delete",
2609 url,
2610 "remove custom recipe from calendar",
2611 params={"recipeSource": "CUSTOMER"},
2612 ),
2613 "remove custom recipe from calendar",
2614 )
2615 if result.get("content") is None:
2616 # The API returns a null content when the removed recipe was the
2617 # last one for the day, since the (now empty) day no longer
2618 # exists as an entity.
2619 return self._empty_calendar_day(day)
2620 return self._parse_result(
2621 "loading custom removed recipe",
2622 lambda: cookidoo_calendar_day_from_json(
2623 cast(CalendarDayJSON, result["content"]),
2624 self._cfg.localization,
2625 ),
2626 )