-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathDelonghiCoffeeLinkAPI.py
More file actions
2066 lines (1716 loc) · 67.8 KB
/
Copy pathDelonghiCoffeeLinkAPI.py
File metadata and controls
2066 lines (1716 loc) · 67.8 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python3
import base64
from dataclasses import asdict, dataclass
import json
import datetime
import logging
import os
import re
import struct
import time
from typing import Any, Callable, Dict, List, Optional, Tuple, Union
import requests
# ─────────────────────────── Logging ───────────────────────────
def make_default_logger(name: str = "DeLonghiAPI") -> logging.Logger:
"""Create a default silent logger."""
logger = logging.getLogger(name)
logger.addHandler(logging.NullHandler())
return logger
# ─────────────────────────── Global logging bridge ───────────────────────────
_global_logger: logging.Logger = make_default_logger("DeLonghiAPI")
def attach_logger(logger: logging.Logger) -> None:
"""
Attach a global logger for free functions and static helpers.
This allows top-level functions (like json_or_debug or print_jwt_info)
to log via the same logger used by DeLonghiAPI / AylaClient.
"""
global _global_logger
_global_logger = logger
def get_logger(name: Optional[str] = None) -> logging.Logger:
"""
Retrieve the currently active global logger, optionally namespaced.
If no logger is attached, returns a silent default logger.
"""
if name:
return _global_logger.getChild(name)
return _global_logger
# ─────────────────────────── Helpers ───────────────────────────
def _parse_json_safe(val: Optional[str]) -> Optional[Dict[str, Any]]:
if not val:
return None
try:
return json.loads(val)
except Exception:
return None
def json_or_debug(resp: requests.Response, label: str) -> Union[Dict[str, Any], List[Dict[str, Any]]]:
"""
Safely parse a JSON response, with debug fallback on error.
This helper tries to decode the response body as JSON. If parsing fails
(e.g. invalid content type or malformed body), it logs detailed
diagnostic output (HTTP status, first 800 bytes of the body) and re-raises
the exception.
Args:
resp (requests.Response): The HTTP response object returned by `requests`.
label (str): A short identifier (e.g. endpoint name) used in error logs.
Returns:
Union[Dict[str, Any], List[Dict[str, Any]]]: Parsed JSON payload.
Raises:
ValueError: If the response body is not valid JSON.
requests.RequestException: If any request-related errors occur.
"""
log = get_logger("helpers")
try:
return resp.json()
except Exception as exc:
text_preview = resp.text[:800].replace("\n", "\\n")
log.error(f"[!] {label}: Failed to parse JSON (HTTP {resp.status_code})")
log.debug(f"↳ Response snippet:\n{text_preview}")
raise ValueError(f"Invalid JSON in {label}: {exc}") from exc
def print_jwt_info(jwt: str, verbose: bool = False) -> Optional[Dict[str, Any]]:
"""
Decode and print basic information from a JSON Web Token (JWT).
This function extracts and base64-decodes the JWT payload, then logs the
main fields (`sub`, `iss`, `iat`, `exp`). If an expiration (`exp`) field is
present, the remaining lifetime is also shown. Optionally, the entire
decoded payload can be logged at debug level for inspection.
Args:
jwt (str): The raw JWT string in standard `header.payload.signature` format.
verbose (bool, optional): If True, logs the full decoded payload.
Returns:
Optional[Dict[str, Any]]: The decoded JWT payload dictionary, or None on error.
Raises:
ValueError: If the JWT is malformed or cannot be base64-decoded.
"""
log = get_logger("helpers")
try:
parts = jwt.split(".")
if len(parts) < 2:
raise ValueError("Invalid JWT structure: missing payload section")
_, payload, *_ = parts
# JWTs use base64url encoding without padding, so restore correct padding
padded = payload + "=" * ((4 - len(payload) % 4) % 4)
decoded_bytes = base64.urlsafe_b64decode(padded)
data: Dict[str, Any] = json.loads(decoded_bytes)
exp = data.get("exp")
core_info = {k: data.get(k) for k in ("sub", "iss", "iat", "exp") if k in data}
log.debug(f"[i] JWT core info: {core_info}")
if exp is not None:
remaining = exp - int(time.time())
log.debug(f" → expires in: {remaining} seconds")
if verbose:
log.debug(f"[i] Full JWT payload:\n{json.dumps(data, indent=2)}")
return data
except Exception as exc:
log.error(f"[!] Failed to decode JWT: {exc}")
return None
# ─────────────────────────── Cache Layer ───────────────────────────
class _JsonCache:
"""
Lightweight on-disk JSON key-value cache with optional time-based expiry.
This class provides a simple way to persist small key-value dictionaries
between program runs. Each value is stored with a timestamp to allow
time-to-live (TTL) validation on retrieval.
Attributes:
path (str): Path to the JSON cache file on disk.
data (Dict[str, Any]): The in-memory dictionary representing cached data.
Example:
>>> cache = _JsonCache("cache.json")
>>> cache.set("session", {"token": "abc"})
>>> cache.get("session", ttl=3600)
{'token': 'abc'}
"""
def __init__(self, path: str):
"""
Initialize the JSON cache and load data from disk if available.
Args:
path (str): Filesystem path to the cache file.
"""
self.path = path
self.data: Dict[str, Any] = {}
try:
if os.path.exists(path):
# Use safe blocking call
with open(path, "r", encoding="utf-8") as f:
self.data = json.load(f)
except Exception as exc:
print(f"[Cache] Failed to load cache {path}: {exc}")
self.log = make_default_logger("DeLonghiAPI._JsonCache")
if os.path.exists(path):
try:
with open(path, "r", encoding="utf-8") as f:
self.data = json.load(f)
except Exception as exc:
self.log.warning(f"[!] Failed to read cache from {path}: {exc}")
self.data = {}
def get(self, key: str, *, ttl: Optional[int] = None) -> Optional[Any]:
"""
Retrieve a cached value by key, optionally enforcing a time-to-live (TTL).
Args:
key (str): The cache key to look up.
ttl (Optional[int]): Optional time-to-live in seconds. If provided,
entries older than this value are considered expired and ignored.
Returns:
Optional[Any]: The cached value, or None if not found or expired.
"""
item = self.data.get(key)
if not item:
return None
if ttl is not None:
ts = float(item.get("ts", 0))
if time.time() - ts > ttl:
self.log.debug(f"[→] Cache expired for key '{key}' (TTL={ttl}s)")
return None
return item.get("value")
def set(self, key: str, value: Any) -> None:
"""
Store a value in the cache with a timestamp and persist to disk.
Args:
key (str): The cache key.
value (Any): The value to store (must be JSON serializable).
"""
self.data[key] = {"value": value, "ts": time.time()}
try:
with open(self.path, "w", encoding="utf-8") as f:
json.dump(self.data, f, indent=2)
self.log.debug(f"[✓] Cache updated: {key}")
except Exception as exc:
self.log.error(f"[!] Failed to write cache {self.path}: {exc}")
# ─────────────────────────── AylaClient ───────────────────────────
class AylaClient:
"""
HTTP client for authenticating and communicating with the Ayla Cloud API.
Handles login via token-based authentication, manages token caching,
and provides a thin wrapper around the Ayla endpoints with built-in
re-authentication support.
Attributes:
app_id (str): The Ayla app ID for authentication.
app_secret (str): The Ayla app secret for authentication.
cache (_JsonCache): Persistent cache for storing authentication tokens.
main_session (requests.Session): Configured session with headers.
default_timeout (int): Default timeout (in seconds) for all requests.
auth_token (Optional[str]): The current active Ayla authentication token.
"""
BASE_USER = "https://user-field-eu.aylanetworks.com"
BASE_DEVICES = "https://ads-eu.aylanetworks.com/apiv1"
def __init__(
self,
app_id: str,
app_secret: str,
*,
ua_token: str = "DeLonghiComfort/3 CFNetwork/1568.300.101 Darwin/24.2.0",
cache_path: str = "auth_cache.json",
session: Optional[requests.Session] = None,
default_timeout: int = 20,
):
"""
Initialize the Ayla API client.
Args:
app_id (str): The Ayla application ID.
app_secret (str): The Ayla application secret.
ua_token (str, optional): User-Agent string for API requests.
cache_path (str, optional): Path to the authentication cache file.
session (Optional[requests.Session], optional): Custom session object.
default_timeout (int, optional): Default timeout (seconds) for requests.
"""
self.app_id = app_id
self.app_secret = app_secret
self.cache = _JsonCache(cache_path)
self.default_timeout = default_timeout
self.main_session = session or requests.Session()
self.main_session.headers.update({
"User-Agent": ua_token,
"Accept": "application/json",
})
self.auth_token: Optional[str] = None
self._email: Optional[str] = None
self._password: Optional[str] = None
self.log = make_default_logger("DeLonghiAPI.AylaClient")
# ─────────────────────── Helpers ───────────────────────
def _auth_headers(self) -> Dict[str, str]:
"""
Build headers for authenticated requests.
Returns:
Dict[str, str]: Headers containing the current auth token.
Raises:
RuntimeError: If no valid authentication token is available.
"""
if not self.auth_token:
raise RuntimeError("Not authenticated — call login() first")
return {"Authorization": f"auth_token {self.auth_token}"}
def _has_valid_cached_token(self) -> bool:
"""
Check for a valid, non-expired cached token.
Returns:
bool: True if a valid cached token exists and is loaded.
"""
cached = self.cache.get("ayla_auth", ttl=None)
if not cached:
return False
token = cached.get("auth_token")
exp = cached.get("expires_at", 0)
if token and exp > time.time():
self.auth_token = token
self.log.debug("[✓] Using cached Ayla token.")
return True
self.log.debug("[→] Cached token missing or expired.")
return False
def _store_token(self, token: str, *, lifetime_seconds: int = 23 * 3600) -> None:
"""
Store a freshly obtained authentication token in the cache.
Args:
token (str): The authentication token string.
lifetime_seconds (int, optional): Token lifetime in seconds.
"""
self.auth_token = token
expires_at = int(time.time()) + lifetime_seconds
self.cache.set("ayla_auth", {
"auth_token": token,
"expires_at": expires_at,
})
self.log.debug(f"[✓] Stored new Ayla token (expires in {lifetime_seconds}s).")
# ─────────────────────── Core Methods ───────────────────────
def ayla_token_sign_in(self, id_token: str) -> str:
"""
Exchange a Gigya or external ID token for an Ayla auth token.
Args:
id_token (str): The external identity token (e.g. from Gigya).
Returns:
str: The Ayla access/auth token.
Raises:
RuntimeError: If the server response does not include a token.
requests.RequestException: On network or HTTP error.
"""
self.log.debug("Performing Ayla token_sign_in...")
url = f"{self.BASE_USER}/api/v1/token_sign_in"
data = {
"app_id": self.app_id,
"app_secret": self.app_secret,
"token": id_token,
}
headers = {"Content-Type": "application/x-www-form-urlencoded; charset=UTF-8"}
self.log.debug(f"[→] POST {url} with data: {data}")
r = self.main_session.post(url, data=data, headers=headers, timeout=self.default_timeout)
r.raise_for_status()
js = json_or_debug(r, "ayla/token_sign_in")
if not isinstance(js, dict):
raise TypeError(f"Expected dict from ayla/token_sign_in, got {type(js).__name__}: {js}")
token_val = js.get("access_token") or js.get("auth_token") or js.get("token")
if not isinstance(token_val, str) or not token_val.strip():
raise RuntimeError(f"Invalid or missing auth token in response: {js}")
token: str = token_val.strip()
self.log.debug("[✓] Ayla token_sign_in successful.")
return token
def _request(
self,
method: str,
url: str,
*,
headers: Optional[Dict[str, str]] = None,
params: Optional[Dict[str, Any]] = None,
data: Optional[Any] = None,
json: Optional[Any] = None,
allow_refresh: bool = True,
timeout: Optional[int] = None,
) -> requests.Response:
"""
Perform an HTTP request with automatic token refresh on 401 errors.
Args:
method (str): HTTP method (GET, POST, PUT, DELETE, etc.).
url (str): Full endpoint URL.
headers (Optional[Dict[str, str]]): Additional request headers.
params (Optional[Dict[str, Any]]): Query string parameters.
data (Optional[Any]): Form data for POST/PUT requests.
json (Optional[Any]): JSON body for POST/PUT requests.
allow_refresh (bool, optional): Whether to retry once on 401 Unauthorized.
timeout (Optional[int], optional): Request timeout in seconds.
Returns:
requests.Response: The HTTP response object.
Raises:
requests.HTTPError: If the response code indicates a fatal error.
RuntimeError: If re-authentication fails.
"""
if timeout is None:
timeout = self.default_timeout
self.log.debug(f"[→] {method} {url} (timeout={timeout})")
r = self.main_session.request(
method,
url,
headers=headers,
params=params,
data=data,
json=json,
timeout=timeout,
)
if r.status_code == 401 and allow_refresh:
self.log.warning("[!] Auth expired — refreshing and retrying once...")
self._refresh_auth()
r = self.main_session.request(
method,
url,
headers=headers,
params=params,
data=data,
json=json,
timeout=timeout,
)
r.raise_for_status()
self.log.debug(f"[✓] {method} {url} → {r.status_code}")
return r
def ayla_list_devices(self) -> List[Dict[str, Any]]:
"""
Retrieve the list of all devices linked to the authenticated Ayla account.
Performs a GET request to the `/devices.json` endpoint using the current
authentication token and writes the raw response to a local dump file
(`DUMP_devices.json`) for debugging.
Returns:
List[Dict[str, Any]]: A list of device objects as returned by Ayla Cloud.
Raises:
RuntimeError: If authentication is missing or invalid.
requests.HTTPError: On HTTP request failure.
TypeError: If the response JSON is not a list.
"""
self.log.debug("Fetching device list...")
url = f"{self.BASE_DEVICES}/devices.json"
headers = self._auth_headers()
r = self._request("GET", url, headers=headers)
# Dump for debugging (optional but useful)
try:
with open("DUMP_devices.json", "w", encoding="utf-8") as f:
f.write(r.text)
self.log.debug("[✓] Device list saved to DUMP_devices.json")
except Exception as exc:
self.log.warning(f"[!] Could not write device dump: {exc}")
js = json_or_debug(r, "ayla/devices")
if not isinstance(js, list):
raise TypeError(
f"Expected list response for ayla/devices, got {type(js).__name__}: {js}"
)
self.log.debug(f"[✓] Retrieved {len(js)} device entries.")
return js
def ayla_list_device_properties(self, device_key: str) -> List[Dict[str, Any]]:
"""
Fetch the full list of properties for a specific Ayla device.
Args:
device_key (str): The unique device identifier (DSN or device key).
Returns:
List[Dict[str, Any]]: A list of property objects for the specified device.
Raises:
RuntimeError: If authentication is missing.
requests.HTTPError: On network or API failure.
TypeError: If the response JSON is not a list.
"""
self.log.debug(f"Fetching properties for device {device_key}...")
url = f"{self.BASE_DEVICES}/devices/{device_key}/properties.json"
headers = self._auth_headers()
r = self._request("GET", url, headers=headers, timeout=25)
js = json_or_debug(r, "device/properties")
if not isinstance(js, list):
raise TypeError(
f"Expected list response for device/properties, got {type(js).__name__}: {js}"
)
self.log.debug(f"[✓] Retrieved {len(js)} properties for device {device_key}.")
return js
# ─────────────────────── Auth Utilities ───────────────────────
def login_with_cached_token_or(self, fresh_login_callable: Callable[[], str]) -> None:
"""
Attempt to use a cached Ayla token; if unavailable or expired, perform a fresh login.
This helper first checks the token cache for a valid authentication token.
If one exists and has not expired, it is loaded and reused. Otherwise, it
calls the provided function (`fresh_login_callable`) to obtain a new token,
stores it, and logs the event.
Args:
fresh_login_callable (Callable[[], str]): A callback returning a new auth token.
Raises:
RuntimeError: If the provided callable does not return a valid token.
"""
self.log.debug("Checking for cached Ayla token...")
if self._has_valid_cached_token():
cached = self.cache.get("ayla_auth")
if cached:
remaining = int(cached.get("expires_at", 0) - time.time())
self.log.debug(f"[+] Using cached Ayla token (valid {max(0, remaining)}s)")
return
self.log.debug("[*] Performing fresh login…")
token = fresh_login_callable()
if not token:
raise RuntimeError("Login callback returned an empty or invalid token")
token = str(token).strip()
if not token:
raise RuntimeError("Login callback returned a blank token")
self._store_token(token)
self.log.debug("[✓] Cached new Ayla token.")
def login(self, email: str, password: str, force_refresh: bool = False) -> None:
"""
Placeholder login method for subclasses.
Overridden by DeLonghiAPI to perform real authentication.
"""
self.log.warning("[!] AylaClient.login() called directly — no implementation available.")
raise RuntimeError("Base AylaClient does not implement login() — use a subclass.")
def _refresh_auth(self) -> None:
"""
Refresh the current authentication token using stored credentials.
This is automatically triggered when a 401 Unauthorized response is
received. The method reuses the previously stored email and password
to reauthenticate the client.
Raises:
RuntimeError: If stored credentials are missing.
"""
if not (self._email and self._password):
raise RuntimeError("Cannot refresh auth: missing credentials.")
self.log.debug("[→] Refreshing Ayla authentication token...")
self.login(self._email, self._password, force_refresh=True)
self.log.debug("[✓] Authentication successfully refreshed.")
# ─────────────────────── Device Wrappers ───────────────────────
def get_devices(self) -> List["DeLonghiDevice"]:
"""
Retrieve all connected DeLonghi devices from Ayla Cloud.
Wraps the raw device list in `DeLonghiDevice` objects for higher-level access.
Returns:
List[DeLonghiDevice]: List of initialized device wrappers.
Raises:
RuntimeError: If the response structure is invalid or missing device keys.
"""
self.log.debug("Loading DeLonghi device list...")
raw_devices = self.ayla_list_devices()
devices: List["DeLonghiDevice"] = []
for entry in raw_devices:
device = entry.get("device")
if device:
devices.append(DeLonghiDevice(self, device))
else:
self.log.warning(f"[!] Skipped invalid device entry: {entry}")
self.log.debug(f"[✓] Loaded {len(devices)} device(s).")
return devices
def get_first_device(self) -> "DeLonghiDevice":
"""
Convenience method to retrieve the first available device.
Returns:
DeLonghiDevice: The first device in the list.
Raises:
RuntimeError: If no devices are available in the account.
"""
devices = self.get_devices()
if not devices:
raise RuntimeError("No devices found for the current account.")
self.log.debug(f"[✓] Selected first device: {devices[0]}")
return devices[0]
# ─────────────────────────── DeLonghiAPI ───────────────────────────
class DeLonghiAPI(AylaClient):
"""
High-level API client for DeLonghi Coffee Link Cloud.
This class extends :class:`AylaClient` to handle Gigya authentication,
Ayla token exchange, and integration with DeLonghi's Reply.it endpoints.
It encapsulates the entire authentication chain:
Gigya → Ayla Cloud → DeLonghi devices.
Attributes:
gigya_api_key (str): Gigya API key used for authentication.
datacenter (str): Gigya data center region (e.g., "eu1").
SOCIALIZE (str): Base URL for Gigya's Socialize API.
ACCOUNTS (str): Base URL for Gigya's Accounts API.
REPLY_BASE (str): Base URL for DeLonghi's Reply.it API.
_transcode_table (Optional[Dict[str, Any]]): Cached Reply.it translation table.
"""
def __init__(
self,
app_id: str = "DLonghiCoffeeIdKit-sQ-id",
app_secret: str = "DLonghiCoffeeIdKit-HT6b0VNd4y6CSha9ivM5k8navLw",
gigya_api_key: str = "4_mXSplGaqrFT0H88TAjqJuA",
datacenter: str = "eu1",
ua_token: str = "DeLonghiComfort/3 CFNetwork/1568.300.101 Darwin/24.2.0",
cache_path: str = "auth_cache.json",
):
"""
Initialize a new DeLonghi Coffee Link API client.
Args:
app_id (str, optional): Ayla app ID. Defaults to the official DeLonghi one.
app_secret (str, optional): Ayla app secret. Defaults to DeLonghi value.
gigya_api_key (str, optional): Gigya API key for authentication.
datacenter (str, optional): Gigya datacenter (e.g., "eu1").
ua_token (str, optional): User-Agent string for HTTP requests.
cache_path (str, optional): Path to persistent authentication cache.
"""
super().__init__(
app_id=app_id,
app_secret=app_secret,
ua_token=ua_token,
cache_path=cache_path,
)
self.gigya_api_key = gigya_api_key
self.datacenter = datacenter
self.SOCIALIZE = f"https://socialize.{datacenter}.gigya.com"
self.ACCOUNTS = f"https://accounts.{datacenter}.gigya.com"
self.REPLY_BASE = "https://delonghibe.reply.it/api"
self._transcode_table: Optional[Dict[str, Any]] = None
self.log = make_default_logger("DeLonghiAPI")
def set_logger(self, logger: logging.Logger) -> None:
"""
Attach a custom logger to this API (and propagate to child components).
"""
self.log = logger
# Also attach to AylaClient base
if hasattr(super(), "log"):
super().log = logger
# ─────────────────────── Gigya & Ayla Authentication ───────────────────────
def _gigya_get_session_ids(self) -> Tuple[str, str, str]:
"""
Retrieve session identifiers (GMID, UCID, GMID ticket) from Gigya.
Returns:
Tuple[str, str, str]: A tuple containing:
- GMID (Global Machine ID)
- UCID (User Connection ID)
- GMID ticket (temporary session ticket)
Raises:
requests.RequestException: On network or HTTP error.
RuntimeError: If Gigya response structure is invalid.
TypeError: If the API returns an unexpected response type.
"""
url = f"{self.SOCIALIZE}/socialize.getIDs"
params = {
"APIKey": self.gigya_api_key,
"includeTicket": "true",
"pageURL": "https://aylaopenid.delonghigroup.com/",
"sdk": "Android_6.0.0",
"format": "json",
}
self.log.debug(f"[→] GET {url} with params: {params}")
r = self.main_session.get(url, params=params, timeout=15)
r.raise_for_status()
js = json_or_debug(r, "socialize.getIDs")
# Type narrowing: ensure JSON is a dict
if not isinstance(js, dict):
raise TypeError(
f"Expected dict response for socialize.getIDs, got {type(js).__name__}: {js}"
)
raw_gmid = js.get("gmid")
raw_ucid = js.get("ucid")
raw_ticket = js.get("gmidTicket")
# Validate each field individually so Pylance knows they’re strings now
if not isinstance(raw_gmid, str) or not raw_gmid.strip():
raise RuntimeError(f"Missing or invalid 'gmid' in response: {js}")
if not isinstance(raw_ucid, str) or not raw_ucid.strip():
raise RuntimeError(f"Missing or invalid 'ucid' in response: {js}")
if not isinstance(raw_ticket, str) or not raw_ticket.strip():
raise RuntimeError(f"Missing or invalid 'gmidTicket' in response: {js}")
gmid: str = raw_gmid.strip()
ucid: str = raw_ucid.strip()
ticket: str = raw_ticket.strip()
self.log.debug(f"[✓] Gigya session IDs acquired (gmid={gmid[:8]}..., ucid={ucid[:8]}...)")
return gmid, ucid, ticket
def _gigya_login(self, email: str, password: str) -> str:
"""
Log into the user's Gigya account and obtain an ID token.
Args:
email (str): The user's DeLonghi/Gigya account email.
password (str): The user's password.
Returns:
str: The returned Gigya ID token.
Raises:
RuntimeError: If Gigya does not return an `id_token`.
requests.RequestException: On network or HTTP failure.
TypeError: If the API response is not a JSON object.
"""
url = f"{self.ACCOUNTS}/accounts.login"
data = {
"APIKey": self.gigya_api_key,
"loginID": email,
"password": password,
"targetEnv": "mobile",
"include": "profile,data,emails,subscriptions,preferences,sessionInfo,id_token",
"includeUserInfo": "true",
"format": "json",
"sdk": "Android_6.0.0",
"sdkBuild": "33001",
"pageURL": "https://aylaopenid.delonghigroup.com/",
}
headers = {
"Origin": "https://aylaopenid.delonghigroup.com",
"Content-Type": "application/x-www-form-urlencoded",
"X-Gigya-Client-Device-Type": "Android",
"X-Gigya-Client-Device-ID": "android-" + str(int(time.time())),
}
self.log.debug(f"[→] POST {url} with headers={headers} and data={data}")
r = self.main_session.post(url, data=data, headers=headers, timeout=20)
r.raise_for_status()
js = json_or_debug(r, "accounts.login")
# Ensure we have a dict
if not isinstance(js, dict):
raise TypeError(
f"Expected dict response for accounts.login, got {type(js).__name__}: {js}"
)
raw_token = js.get("id_token") or js.get("idToken")
if not isinstance(raw_token, str) or not raw_token.strip():
raise RuntimeError(f"accounts.login did not return a valid idToken: {js}")
token: str = raw_token.strip()
self.log.debug("[✓] Gigya login successful.")
return token
def login(self, email: str, password: str, force_refresh: bool = False) -> None:
"""
Perform the full DeLonghi login flow via Gigya → Ayla.
Args:
email (str): User's DeLonghi Coffee Link login email.
password (str): Account password.
force_refresh (bool, optional): If True, forces a new login even if cached.
Raises:
RuntimeError: On authentication failure or network error.
"""
self._email, self._password = email, password
if not force_refresh and self._has_valid_cached_token():
cached = self.cache.get("ayla_auth")
if cached:
remaining = int(cached.get("expires_at", 0) - time.time())
self.log.debug(f"[+] Using cached Ayla token (valid {max(0, remaining)}s)")
return
self.log.debug("[*] Performing fresh login…")
try:
_, _, _ = self._gigya_get_session_ids()
id_token = self._gigya_login(email, password)
print_jwt_info(id_token)
ayla_token = self.ayla_token_sign_in(id_token)
self._store_token(ayla_token, lifetime_seconds=23 * 3600)
self.log.debug("[✓] Cached new Ayla token.")
except Exception as exc:
self.log.error(f"[!] Login sequence failed: {exc}")
raise
def _refresh_auth(self) -> None:
"""
Refresh authentication token using stored credentials.
This overrides the parent implementation to ensure Gigya → Ayla refresh flow.
Raises:
RuntimeError: If stored credentials are missing.
"""
if not (self._email and self._password):
raise RuntimeError("Cannot refresh auth: missing credentials.")
self.log.debug("[→] Refreshing DeLonghi authentication token...")
self.login(self._email, self._password, force_refresh=True)
self.log.debug("[✓] Authentication successfully refreshed.")
# ─────────────────────── Reply.it Helpers ───────────────────────
def _reply_body(self, endpoint: str) -> Dict[str, Any]:
"""
Construct the correct JSON body for a given Reply.it API endpoint.
The payload mirrors the structure used by the Coffee Link app (v4.9.1,
tableVersion 1.510) for compatibility with DeLonghi backend APIs.
Args:
endpoint (str): Name of the Reply.it endpoint, e.g. "getTranscodeTable".
Returns:
Dict[str, Any]: The properly formatted request body.
"""
body: Dict[str, Any] = {
"locale": "en_US",
"appVersion": "4.9.1",
"tableVersion": "1.510",
"helpVersion": 0,
}
if endpoint == "getAddictionalCommonData":
body["countryCode"] = "DE"
elif endpoint == "getTranscodeTable":
body["currentVersion"] = "1.510"
self.log.debug(f"[→] Constructed Reply.it request body for '{endpoint}': {body}")
return body
def _reply_post(self, endpoint: str) -> Dict[str, Any]:
"""
Send a POST request to a Reply.it API endpoint with the correct headers and body.
Args:
endpoint (str): Name of the endpoint (without `.sr` suffix),
e.g. ``"getTranscodeTable"``.
Returns:
Dict[str, Any]: Parsed JSON response from the Reply.it API.
Raises:
requests.HTTPError: If the response status code is not successful.
ValueError: If the response body is not valid JSON.
"""
url = f"{self.REPLY_BASE}/{endpoint}.sr"
headers = {
"Content-Type": "application/json",
"Accept": "application/json",
"User-Agent": "DeLonghiCoffeeLink/4.9.1 (Android)",
}
body = self._reply_body(endpoint)
self.log.info(f"[→] POST {endpoint}.sr with {body}")
r = self.main_session.post(url, headers=headers, json=body, timeout=25)
print(headers)
print(body)
r.raise_for_status()
try:
js: Dict[str, Any] = r.json()
self.log.debug(f"[✓] {endpoint}.sr → {len(json.dumps(js))} bytes JSON")
return js
except Exception as exc:
self.log.error(f"[!] Failed to parse Reply.it response for {endpoint}: {exc}")
raise ValueError(f"Invalid JSON in Reply.it response for {endpoint}") from exc
def get_transcode_table(self, *, force_refresh: bool = False) -> Dict[str, Any]:
"""
Retrieve and cache the DeLonghi transcode table from Reply.it.
Loads the ``getTranscodeTable.sr`` JSON from the Reply.it API and stores
it in the persistent cache. The cached copy is valid for 7 days by default.
Args:
force_refresh (bool, optional): If True, forces a fresh fetch
even if a valid cached table exists.
Returns:
Dict[str, Any]: The transcode table dictionary.
Raises:
Exception: If no valid cache or online data is available.
"""
self.log.debug("Fetching transcode table from Reply.it...")
TTL = 7 * 24 * 3600 # 7 days
if not force_refresh:
cached = self.cache.get("reply_transcode_table", ttl=TTL)
if cached:
self._transcode_table = cached
self.log.debug("[✓] Using cached transcode table.")
return cached
try:
self.cache.set("reply_transcode_table", js)
self._transcode_table = js
self.log.debug("[✓] Transcode table fetched and cached.")
return js
except Exception as exc:
# fallback logic
if self._transcode_table:
self.log.warning(f"[!] Using in-memory transcode table after fetch error: {exc}")
return self._transcode_table
cached_no_ttl = self.cache.get("reply_transcode_table", ttl=None)
if cached_no_ttl:
self.log.warning(f"[!] Using expired cached transcode table after fetch error: {exc}")
self._transcode_table = cached_no_ttl
return cached_no_ttl
raise RuntimeError("Failed to fetch or restore transcode table") from exc
# ─────────────────────────── Device Model ───────────────────────────
_ALNUM_RE = re.compile(rb"[0-9A-Z]{10,}")
@dataclass
class MachineSettings:
"""Represents core machine settings (decoded from base64)."""
brewing_temperature: Optional[Dict[str, Any]] = None
auto_shutoff_duration: Optional[Dict[str, Any]] = None
water_hardness_level: Optional[Dict[str, Any]] = None
profile: Optional[int] = None
# ─────────────────────────── Helpers ───────────────────────────
@staticmethod
def _b64decode(val: Optional[str]) -> Optional[bytes]:
if not val:
return None
try:
return base64.b64decode(val)
except Exception:
return None
@staticmethod
def _b64text(val: Optional[str]) -> Optional[str]:
data = MachineSettings._b64decode(val)
if not data:
return None
return data.decode(errors="ignore").strip("\x00")
@staticmethod
def _b64byte_level(val: Optional[str]) -> Optional[int]:
data = MachineSettings._b64decode(val)
if data and len(data) >= 10:
return data[9]
return None
@staticmethod