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