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