-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathknuspr_cli.py
More file actions
executable file
Β·4631 lines (3843 loc) Β· 193 KB
/
Copy pathknuspr_cli.py
File metadata and controls
executable file
Β·4631 lines (3843 loc) Β· 193 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
"""Knuspr CLI - Einkaufen bei Knuspr.de vom Terminal aus.
REST-Γ€hnliche, AI-Agent-freundliche Struktur.
Rein Python, keine externen Dependencies (nur stdlib).
Nutzung:
knuspr auth login # Einloggen
knuspr auth status # Login-Status
knuspr config set # PrΓ€ferenzen einrichten
knuspr product search "Milch" # Produkte suchen
knuspr product show 123456 # Produktdetails
knuspr product rette # Rette Lebensmittel
knuspr cart show # Warenkorb anzeigen
knuspr cart add 123456 # Produkt hinzufΓΌgen
knuspr slot list # Lieferzeitfenster
knuspr slot reserve 12345 # Slot reservieren
knuspr order list # Bestellhistorie
knuspr order show 123 # Bestelldetails
knuspr delivery show # Lieferinfo
knuspr account show # Account-Info
knuspr favorite list # Favoriten anzeigen
knuspr list show # Einkaufslisten anzeigen
knuspr list show 224328 # Produkte einer Liste
knuspr list create "Wocheneinkauf" # Neue Liste erstellen
knuspr list delete 224328 # Liste lΓΆschen
knuspr list rename 224328 "Neu" # Liste umbenennen
knuspr list add 224328 3386 # Produkt zur Liste hinzufΓΌgen
knuspr list remove 224328 3386 # Produkt von Liste entfernen
knuspr list to-cart 224328 # Alle Produkte in den Warenkorb
knuspr deals # Aktionen & Angebote
knuspr deals --type week-sales # Nur Wochenangebote
"""
import argparse
import getpass
import http.cookiejar
import json
import os
import sys
import time
import urllib.error
import urllib.parse
import urllib.request
import webbrowser
from datetime import datetime
from pathlib import Path
from typing import Any, Optional
# Configuration
BASE_URL = "https://www.knuspr.de"
SESSION_FILE = Path.home() / ".knuspr_session.json"
CREDENTIALS_FILE = Path.home() / ".knuspr_credentials.json"
CONFIG_FILE = Path.home() / ".knuspr_config.json"
# Exit codes
EXIT_OK = 0
EXIT_ERROR = 1
EXIT_AUTH_ERROR = 2
class KnusprAPIError(Exception):
"""Custom exception for Knuspr API errors."""
def __init__(self, message: str, status: Optional[int] = None):
super().__init__(message)
self.status = status
class KnusprAPI:
"""Knuspr.de API client using only Python stdlib."""
def __init__(self):
self.cookies: dict[str, str] = {}
self.user_id: Optional[int] = None
self.address_id: Optional[int] = None
self._last_request_time: float = 0
self._min_request_interval: float = 0.1 # 100ms between requests
self._load_session()
def _rate_limit(self) -> None:
"""Apply rate limiting between requests."""
now = time.time()
elapsed = now - self._last_request_time
if elapsed < self._min_request_interval:
time.sleep(self._min_request_interval - elapsed)
self._last_request_time = time.time()
def _get_headers(self) -> dict[str, str]:
"""Get default HTTP headers."""
headers = {
"Accept": "application/json, text/plain, */*",
"Accept-Language": "de-DE,de;q=0.9,en;q=0.8",
"Content-Type": "application/json",
"User-Agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/119.0.0.0 Safari/537.36",
"Referer": BASE_URL,
"Origin": BASE_URL,
"sec-ch-ua": '"Google Chrome";v="119", "Chromium";v="119", "Not?A_Brand";v="24"',
"sec-ch-ua-mobile": "?0",
"sec-ch-ua-platform": '"macOS"',
"sec-fetch-dest": "empty",
"sec-fetch-mode": "cors",
"sec-fetch-site": "same-origin",
}
if self.cookies:
cookie_str = "; ".join(f"{k}={v}" for k, v in self.cookies.items())
headers["Cookie"] = cookie_str
return headers
def _make_request(
self,
endpoint: str,
method: str = "GET",
data: Optional[dict] = None
) -> dict[str, Any]:
"""Make HTTP request to Knuspr API."""
self._rate_limit()
url = f"{BASE_URL}{endpoint}"
headers = self._get_headers()
body = None
if data:
body = json.dumps(data).encode("utf-8")
request = urllib.request.Request(url, data=body, headers=headers, method=method)
try:
with urllib.request.urlopen(request, timeout=30) as response:
# Parse Set-Cookie headers
for header in response.headers.get_all("Set-Cookie") or []:
self._parse_cookie(header)
content = response.read().decode("utf-8")
if content:
return json.loads(content)
return {}
except urllib.error.HTTPError as e:
error_body = ""
try:
error_body = e.read().decode("utf-8")
except:
pass
raise KnusprAPIError(f"HTTP {e.code}: {e.reason}. {error_body}", e.code)
except urllib.error.URLError as e:
raise KnusprAPIError(f"Connection error: {e.reason}")
def _parse_cookie(self, cookie_header: str) -> None:
"""Parse Set-Cookie header and store cookies."""
parts = cookie_header.split(";")
if parts:
cookie_part = parts[0].strip()
if "=" in cookie_part:
name, value = cookie_part.split("=", 1)
self.cookies[name.strip()] = value.strip()
def _save_session(self) -> None:
"""Save session cookies to file."""
session_data = {
"cookies": self.cookies,
"user_id": self.user_id,
"address_id": self.address_id,
}
with open(SESSION_FILE, "w") as f:
json.dump(session_data, f)
def _load_session(self) -> None:
"""Load session cookies from file."""
if SESSION_FILE.exists():
try:
with open(SESSION_FILE) as f:
data = json.load(f)
self.cookies = data.get("cookies", {})
self.user_id = data.get("user_id")
self.address_id = data.get("address_id")
except (json.JSONDecodeError, IOError):
pass
def _clear_session(self) -> None:
"""Clear session data."""
self.cookies = {}
self.user_id = None
self.address_id = None
if SESSION_FILE.exists():
SESSION_FILE.unlink()
def is_logged_in(self) -> bool:
"""Check if we have a valid session."""
return bool(self.cookies and self.user_id)
def login(self, email: str, password: str) -> dict[str, Any]:
"""Login to Knuspr.de."""
login_data = {
"email": email,
"password": password,
"name": ""
}
response = self._make_request(
"/services/frontend-service/login",
method="POST",
data=login_data
)
# Check response
status = response.get("status", 200)
if status not in (200, 202, None):
messages = response.get("messages", [])
error_msg = messages[0].get("content") if messages else "Login failed"
raise KnusprAPIError(f"Login failed: {error_msg}", status)
# Extract user data
data = response.get("data", {})
user = data.get("user", {})
if not user.get("id"):
raise KnusprAPIError("Login succeeded but no user data received")
self.user_id = user["id"]
self.address_id = data.get("address", {}).get("id")
self._save_session()
return {
"user_id": self.user_id,
"email": user.get("email"),
"name": f"{user.get('name', '')} {user.get('surname', '')}".strip(),
"address_id": self.address_id,
}
def logout(self) -> None:
"""Logout from Knuspr.de."""
try:
self._make_request("/services/frontend-service/logout", method="POST")
except KnusprAPIError:
pass # Ignore logout errors
finally:
self._clear_session()
# Mapping from CLI sort names to Knuspr API sortType values
SORT_TYPE_MAP = {
"relevance": "orderRecommended",
"price_asc": "orderPriceAsc",
"price_desc": "orderPriceDesc",
"unit_price_asc": "orderUnitPriceAsc",
}
def search_products(
self,
query: str,
limit: int = 10,
favorites_only: bool = False,
expiring_only: bool = False,
bio_only: bool = False,
on_sale: bool = False,
sort_order: str = "relevance"
) -> list[dict[str, Any]]:
"""Search for products."""
if not self.is_logged_in():
raise KnusprAPIError("Not logged in. Run 'knuspr auth login' first.")
needs_extra = expiring_only or bio_only or on_sale
request_limit = limit + 50 if needs_extra else limit + 5
api_filters = []
filter_data: dict[str, Any] = {"filters": api_filters}
sort_type = self.SORT_TYPE_MAP.get(sort_order)
if sort_type:
filter_data["sortType"] = sort_type
params = urllib.parse.urlencode({
"search": query,
"offset": "0",
"limit": str(request_limit),
"companyId": "1",
"filterData": json.dumps(filter_data),
"canCorrect": "true"
})
response = self._make_request(f"/services/frontend-service/search-metadata?{params}")
products = response.get("data", {}).get("productList", [])
# Filter out sponsored products
products = [
p for p in products
if not any(
badge.get("slug") == "promoted"
for badge in p.get("badge", [])
)
]
# Filter expiring products
if expiring_only:
products = [
p for p in products
if any(
badge.get("slug") == "expiring" or badge.get("type") == "EXPIRING"
for badge in p.get("badge", [])
)
]
# Filter BIO products
if bio_only:
products = [
p for p in products
if any(
badge.get("slug") == "bio" or badge.get("type") == "bio"
for badge in p.get("badge", [])
)
]
# Filter on-sale products
if on_sale:
products = [
p for p in products
if any(
s.get("active") and s.get("type") in ("sale", "week-sale")
for s in p.get("sales", [])
)
]
# Filter favorites
if favorites_only:
products = [p for p in products if p.get("favourite")]
products = products[:limit]
results = []
for p in products:
price_info = p.get("price", {})
expiry_text = None
discount_text = None
for badge in p.get("badge", []):
if badge.get("type") == "EXPIRING" or badge.get("slug") == "expiring":
expiry_text = badge.get("text") or badge.get("label")
if badge.get("position") == "PRICE":
discount_text = badge.get("text") or badge.get("label")
# Extract best active sale
best_sale = None
for s in p.get("sales", []):
if s.get("active"):
sale_price = s.get("price", {}).get("full")
orig = s.get("originalPrice", {}).get("full")
if sale_price and (best_sale is None or sale_price < best_sale.get("sale_price", 999)):
best_sale = {
"type": s.get("type"),
"sale_price": sale_price,
"original_price": orig,
"discount_percent": s.get("discountPercentage", 0),
"ends_at": s.get("endsAt"),
}
results.append({
"id": p.get("productId"),
"name": p.get("productName"),
"price": price_info.get("full"),
"currency": price_info.get("currency", "EUR"),
"unit_price": price_info.get("unitPrice"),
"brand": p.get("brand"),
"amount": p.get("textualAmount"),
"in_stock": p.get("inStock", True),
"image": p.get("image"),
"expiry": expiry_text,
"discount": discount_text,
"sale": best_sale,
})
return results
def get_cart(self) -> dict[str, Any]:
"""Get cart contents."""
if not self.is_logged_in():
raise KnusprAPIError("Not logged in. Run 'knuspr auth login' first.")
response = self._make_request("/services/frontend-service/v2/cart")
data = response.get("data", {})
items = data.get("items", {})
products = []
for product_id, item in items.items():
quantity = item.get("quantity", 0)
price = item.get("price", 0)
item_total = item.get("totalPrice", 0) or (quantity * price)
products.append({
"id": product_id,
"order_field_id": item.get("orderFieldId"),
"name": item.get("productName"),
"quantity": quantity,
"price": price,
"total_price": item_total,
"category": item.get("primaryCategoryName"),
"brand": item.get("brand"),
"image": item.get("image"),
})
return {
"total_price": data.get("totalPrice", 0),
"currency": "EUR",
"item_count": len(products),
"can_order": data.get("submitConditionPassed", False),
"min_order_price": data.get("minOrderPrice"),
"products": products,
}
def add_to_cart(self, product_id: int, quantity: int = 1) -> bool:
"""Add product to cart."""
if not self.is_logged_in():
raise KnusprAPIError("Not logged in. Run 'knuspr auth login' first.")
payload = {
"actionId": None,
"productId": product_id,
"quantity": quantity,
"recipeId": None,
"source": "true:Search"
}
self._make_request(
"/services/frontend-service/v2/cart",
method="POST",
data=payload
)
return True
def remove_from_cart(self, order_field_id: str) -> bool:
"""Remove product from cart using order_field_id."""
if not self.is_logged_in():
raise KnusprAPIError("Not logged in. Run 'knuspr auth login' first.")
self._make_request(
f"/services/frontend-service/v2/cart?orderFieldId={order_field_id}",
method="DELETE"
)
return True
def clear_cart(self) -> bool:
"""Clear all items from cart."""
if not self.is_logged_in():
raise KnusprAPIError("Not logged in. Run 'knuspr auth login' first.")
cart = self.get_cart()
for product in cart.get("products", []):
order_field_id = product.get("order_field_id")
if order_field_id:
self.remove_from_cart(str(order_field_id))
return True
def update_cart_quantity(self, order_field_id: str, quantity: int) -> bool:
"""Update quantity of a cart item."""
if not self.is_logged_in():
raise KnusprAPIError("Not logged in. Run 'knuspr auth login' first.")
payload = {
"orderFieldId": order_field_id,
"quantity": quantity,
}
self._make_request(
"/services/frontend-service/v2/cart",
method="PUT",
data=payload
)
return True
def get_delivery_info(self) -> dict[str, Any]:
"""Get delivery information."""
if not self.is_logged_in():
raise KnusprAPIError("Not logged in. Run 'knuspr auth login' first.")
response = self._make_request(
"/services/frontend-service/first-delivery?reasonableDeliveryTime=true"
)
return response.get("data", response)
def get_upcoming_orders(self) -> list[dict[str, Any]]:
"""Get upcoming/pending orders."""
if not self.is_logged_in():
raise KnusprAPIError("Not logged in. Run 'knuspr auth login' first.")
response = self._make_request("/api/v3/orders/upcoming")
if isinstance(response, list):
return response
data = response.get("data", response) if isinstance(response, dict) else response
return data if isinstance(data, list) else []
def get_order_history(self, limit: int = 10) -> list[dict[str, Any]]:
"""Get order history."""
if not self.is_logged_in():
raise KnusprAPIError("Not logged in. Run 'knuspr auth login' first.")
response = self._make_request(f"/api/v3/orders/delivered?offset=0&limit={limit}")
if isinstance(response, list):
return response
data = response.get("data", response) if isinstance(response, dict) else response
return data if isinstance(data, list) else [data] if data else []
def get_order_detail(self, order_id: str) -> dict[str, Any]:
"""Get details of a specific order."""
if not self.is_logged_in():
raise KnusprAPIError("Not logged in. Run 'knuspr auth login' first.")
response = self._make_request(f"/api/v3/orders/{order_id}")
if isinstance(response, dict):
return response.get("data", response)
return response
def get_delivery_slots(self) -> list[dict[str, Any]]:
"""Get available delivery time slots."""
if not self.is_logged_in():
raise KnusprAPIError("Not logged in. Run 'knuspr auth login' first.")
if not self.user_id or not self.address_id:
raise KnusprAPIError("User ID or Address ID not available")
response = self._make_request(
f"/services/frontend-service/timeslots-api/0?userId={self.user_id}&addressId={self.address_id}&reasonableDeliveryTime=true"
)
if isinstance(response, list):
return response
data = response.get("data", response) if isinstance(response, dict) else response
return data if isinstance(data, list) else [data] if data else []
def get_premium_info(self) -> dict[str, Any]:
"""Get premium membership information."""
if not self.is_logged_in():
raise KnusprAPIError("Not logged in. Run 'knuspr auth login' first.")
response = self._make_request("/services/frontend-service/premium/profile")
if isinstance(response, dict):
return response.get("data", response)
return response if response else {}
def get_reusable_bags_info(self) -> dict[str, Any]:
"""Get reusable bags information."""
if not self.is_logged_in():
raise KnusprAPIError("Not logged in. Run 'knuspr auth login' first.")
response = self._make_request("/api/v1/reusable-bags/user-info")
if isinstance(response, dict):
return response.get("data", response)
return response if response else {}
def get_announcements(self) -> list[dict[str, Any]]:
"""Get announcements."""
if not self.is_logged_in():
raise KnusprAPIError("Not logged in. Run 'knuspr auth login' first.")
response = self._make_request("/services/frontend-service/announcements/top")
if isinstance(response, list):
return response
data = response.get("data", response) if isinstance(response, dict) else response
return data if isinstance(data, list) else []
def get_current_reservation(self) -> Optional[dict[str, Any]]:
"""Get current timeslot reservation."""
if not self.is_logged_in():
raise KnusprAPIError("Not logged in. Run 'knuspr auth login' first.")
try:
response = self._make_request("/services/frontend-service/v1/timeslot-reservation")
if isinstance(response, dict):
return response.get("data", response) if response else None
return response
except KnusprAPIError as e:
if e.status == 404:
return None
raise
def reserve_slot(self, slot_id: int, slot_type: str = "ON_TIME") -> dict[str, Any]:
"""Reserve a delivery time slot."""
if not self.is_logged_in():
raise KnusprAPIError("Not logged in. Run 'knuspr auth login' first.")
payload = {
"slotId": slot_id,
"slotType": slot_type
}
response = self._make_request(
"/services/frontend-service/v1/timeslot-reservation",
method="POST",
data=payload
)
if isinstance(response, dict):
return response.get("data", response)
return response if response else {}
def cancel_reservation(self) -> bool:
"""Cancel current timeslot reservation."""
if not self.is_logged_in():
raise KnusprAPIError("Not logged in. Run 'knuspr auth login' first.")
self._make_request(
"/services/frontend-service/v1/timeslot-reservation",
method="DELETE"
)
return True
def get_available_filters(self, query: str) -> list[dict[str, Any]]:
"""Get available filters for a search query."""
if not self.is_logged_in():
raise KnusprAPIError("Not logged in. Run 'knuspr auth login' first.")
body = {
"search": query,
"warehouseId": 10000,
"isFuzzy": False,
"type": "PRODUCT",
"filters": []
}
response = self._make_request("/api/v1/filters/search", method="POST", data=body)
filter_groups = []
for group in response.get("filterGroups", []):
options = []
for opt in group.get("options", []):
options.append({
"title": opt.get("title"),
"key": opt.get("key"),
"value": opt.get("value"),
"filter_string": f"{opt.get('key')}:{opt.get('value')}",
"count": opt.get("matchingProductCount"),
})
filter_groups.append({
"tag": group.get("tag"),
"title": group.get("title"),
"options": options,
})
return filter_groups
def get_product_details(self, product_id: int) -> dict[str, Any]:
"""Get detailed product information."""
if not self.is_logged_in():
raise KnusprAPIError("Not logged in. Run 'knuspr auth login' first.")
response = self._make_request(f"/api/v1/products/{product_id}/details")
if not response:
raise KnusprAPIError(f"Produkt {product_id} nicht gefunden")
product = response.get("product", {})
stock = response.get("stock", {})
prices = response.get("prices", {})
countries = product.get("countries", [])
country_name = countries[0].get("name") if countries else None
country_code = countries[0].get("code") if countries else None
badges = []
for badge in product.get("badges", []):
badges.append({
"type": badge.get("type"),
"title": badge.get("title"),
"subtitle": badge.get("subtitle"),
})
shelf_life = stock.get("shelfLife", {}) or {}
freshness = stock.get("freshness", {}) or {}
price_obj = prices.get("price", {})
unit_price_obj = prices.get("pricePerUnit", {})
sales = prices.get("sales", [])
sale_info = None
if sales:
sale = sales[0]
sale_info = {
"title": sale.get("title"),
"original_price": sale.get("originalPrice"),
"sale_price": sale.get("salePrice"),
}
story = product.get("productStory")
story_info = None
if story:
story_info = {
"title": story.get("title"),
"text": story.get("text"),
}
tooltips = []
for tooltip in stock.get("tooltips", []):
tooltips.append({
"type": tooltip.get("type"),
"message": tooltip.get("message"),
})
return {
"id": product.get("id"),
"name": product.get("name"),
"slug": product.get("slug"),
"brand": product.get("brand"),
"amount": product.get("textualAmount"),
"unit": product.get("unit"),
"price": price_obj.get("amount"),
"currency": price_obj.get("currency", "EUR"),
"unit_price": unit_price_obj.get("amount"),
"unit_price_currency": unit_price_obj.get("currency", "EUR"),
"in_stock": stock.get("inStock", False),
"max_quantity": stock.get("maxBasketAmount"),
"country": country_name,
"country_code": country_code,
"badges": badges,
"images": product.get("images", []),
"shelf_life": {
"type": shelf_life.get("type"),
"average_days": shelf_life.get("average"),
"minimum_days": shelf_life.get("minimal"),
"best_before": shelf_life.get("bestBefore"),
} if shelf_life else None,
"freshness_message": freshness.get("message") if freshness else None,
"sale": sale_info,
"story": story_info,
"tooltips": tooltips,
"information": product.get("information", []),
"advice_for_safe_use": product.get("adviceForSafeUse"),
"weighted_item": product.get("weightedItem", False),
"premium_only": product.get("premiumOnly", False),
"archived": product.get("archived", False),
}
def get_rette_products(self, category_id: Optional[int] = None) -> list[dict[str, Any]]:
"""Get all 'Rette Lebensmittel' (expiring) products."""
if not self.is_logged_in():
raise KnusprAPIError("Not logged in. Run 'knuspr auth login' first.")
import re
# Dynamically fetch categories from the Rette Lebensmittel page
categories: dict[int, str] = {}
if category_id:
categories = {category_id: "Unbekannt"}
else:
try:
url = f"{BASE_URL}/rette-lebensmittel"
headers = self._get_headers()
headers["Accept"] = "text/html"
request = urllib.request.Request(url, headers=headers)
with urllib.request.urlopen(request, timeout=15) as response:
html = response.read().decode("utf-8")
# Extract category IDs and names from page data
cat_matches = re.findall(r'"categoryId":(\d+),"name":"([^"]*)"', html)
for cid, cname in cat_matches:
cname = cname.replace("\\u0026", "&")
categories[int(cid)] = cname
except Exception:
pass
if not categories:
# Fallback to known categories
categories = {
652: "Fleisch & Fisch", 532: "KΓΌhlregal", 663: "Wurst & Schinken",
480: "Brot & GebΓ€ck", 2416: "Plant Based", 29: "Kochen & Backen",
833: "Baby & Kinder", 4668: "SΓΌΓes & Salziges", 4915: "Bistro",
}
all_product_ids = set()
for cat_id in categories.keys():
try:
url = f"{BASE_URL}/rette-lebensmittel/c{cat_id}"
headers = self._get_headers()
headers["Accept"] = "text/html"
request = urllib.request.Request(url, headers=headers)
with urllib.request.urlopen(request, timeout=15) as response:
html = response.read().decode("utf-8")
pids = re.findall(r'"productId":(\d+)', html)
all_product_ids.update(pids)
except Exception:
continue
if not all_product_ids:
return []
# API has a limit per request, so batch product IDs
product_ids = list(all_product_ids)
BATCH_SIZE = 20
result = []
for i in range(0, len(product_ids), BATCH_SIZE):
batch = product_ids[i:i + BATCH_SIZE]
params = "&".join([f"products={pid}" for pid in batch])
try:
batch_result = self._make_request(f"/api/v1/products/card?{params}&categoryType=last-minute")
if isinstance(batch_result, list):
result.extend(batch_result)
except KnusprAPIError:
continue
if not result:
return []
products = []
for p in result:
expiry_text = None
discount_text = None
for badge in p.get("badges", []):
if badge.get("type") == "EXPIRING":
expiry_text = badge.get("text")
if badge.get("position") == "PRICE":
discount_text = badge.get("text")
prices = p.get("prices", {})
products.append({
"id": p.get("productId"),
"name": p.get("name"),
"price": prices.get("salePrice") or prices.get("originalPrice"),
"original_price": prices.get("originalPrice"),
"currency": prices.get("currency", "EUR"),
"unit_price": prices.get("unitPrice"),
"brand": p.get("brand"),
"amount": p.get("textualAmount"),
"in_stock": p.get("stock", {}).get("availabilityStatus") == "AVAILABLE",
"expiry": expiry_text,
"discount": discount_text,
})
def expiry_sort(p):
exp = (p.get("expiry") or "").lower()
if "heute" in exp:
return 0
elif "morgen" in exp:
return 1
else:
return 2
products.sort(key=expiry_sort)
return products
def get_favorites(self) -> list[dict[str, Any]]:
"""Get all favorite products."""
if not self.is_logged_in():
raise KnusprAPIError("Not logged in. Run 'knuspr auth login' first.")
response = self._make_request("/api/v1/categories/favorite/products?limit=500")
product_ids = response.get("productIds", [])
if not product_ids:
return []
favorites = []
batch_size = 50
for i in range(0, len(product_ids), batch_size):
batch_ids = product_ids[i:i + batch_size]
ids_param = ",".join(map(str, batch_ids))
try:
cards = self._make_request(f"/api/v1/products/card?products={ids_param}")
for card in cards:
prices = card.get("prices", {})
stock = card.get("stock", {})
price = prices.get("salePrice") or prices.get("originalPrice")
favorites.append({
"id": card.get("productId"),
"name": card.get("name"),
"price": price,
"currency": prices.get("currency", "EUR"),
"unit_price": prices.get("unitPrice"),
"brand": card.get("brand"),
"amount": card.get("textualAmount"),
"in_stock": stock.get("availabilityStatus") == "AVAILABLE",
"image": card.get("image", {}).get("path") if isinstance(card.get("image"), dict) else card.get("image"),
})
except KnusprAPIError:
for pid in batch_ids:
try:
card = self._make_request(f"/api/v1/products/{pid}/card")
prices = card.get("prices", {})
stock = card.get("stock", {})
price = prices.get("salePrice") or prices.get("originalPrice")
favorites.append({
"id": card.get("productId"),
"name": card.get("name"),
"price": price,
"currency": prices.get("currency", "EUR"),
"unit_price": prices.get("unitPrice"),
"brand": card.get("brand"),
"amount": card.get("textualAmount"),
"in_stock": stock.get("availabilityStatus") == "AVAILABLE",
"image": card.get("image", {}).get("path") if isinstance(card.get("image"), dict) else card.get("image"),
})
except KnusprAPIError:
continue
return sorted(favorites, key=lambda p: (p.get("name") or "").lower())
def add_favorite(self, product_id: int) -> dict[str, Any]:
"""Add a product to favorites."""
if not self.is_logged_in():
raise KnusprAPIError("Not logged in. Run 'knuspr auth login' first.")
payload = {
"productId": product_id,
"favourite": True
}
response = self._make_request(
"/services/frontend-service/product/favourite",
method="POST",
data=payload
)
data = response.get("data", {})
if not data.get("favourite"):
raise KnusprAPIError(f"Failed to add product {product_id} to favorites")
return data
def remove_favorite(self, product_id: int) -> dict[str, Any]:
"""Remove a product from favorites."""
if not self.is_logged_in():
raise KnusprAPIError("Not logged in. Run 'knuspr auth login' first.")
payload = {
"productId": product_id,
"favourite": False
}
response = self._make_request(
"/services/frontend-service/product/favourite",
method="POST",
data=payload
)
data = response.get("data", {})
if data.get("favourite"):
raise KnusprAPIError(f"Failed to remove product {product_id} from favorites")
return data
# βββ Shopping List API βββββββββββββββββββββββββββββββββββββββββββββββ
def get_shopping_lists(self) -> list[int]:
"""Get all shopping list IDs."""
if not self.is_logged_in():
raise KnusprAPIError("Not logged in. Run 'knuspr auth login' first.")
response = self._make_request('/api/v1/components/shopping-lists')
return response.get("shoppingLists", [])
def get_shopping_list(self, list_id: int) -> dict[str, Any]:
"""Get shopping list details with products."""
if not self.is_logged_in():
raise KnusprAPIError("Not logged in. Run 'knuspr auth login' first.")
return self._make_request(f'/api/v2/shopping-lists/id/{list_id}')
def create_shopping_list(self, name: str) -> dict[str, Any]:
"""Create a new shopping list."""
if not self.is_logged_in():
raise KnusprAPIError("Not logged in. Run 'knuspr auth login' first.")
return self._make_request('/api/v1/shopping-lists', method='POST', data={'name': name})
def delete_shopping_list(self, list_id: int) -> bool:
"""Delete a shopping list."""
if not self.is_logged_in():
raise KnusprAPIError("Not logged in. Run 'knuspr auth login' first.")
self._make_request(f'/api/v1/shopping-lists/id/{list_id}', method='DELETE')
return True
def rename_shopping_list(self, list_id: int, name: str) -> dict[str, Any]:
"""Rename a shopping list."""
if not self.is_logged_in():
raise KnusprAPIError("Not logged in. Run 'knuspr auth login' first.")
return self._make_request(f'/api/v2/shopping-lists/id/{list_id}', method='POST', data={'name': name})
def add_to_shopping_list(self, list_id: int, product_id: int, amount: int = 1) -> bool:
"""Add/update product in shopping list. Amount is ADDED to existing."""
if not self.is_logged_in():
raise KnusprAPIError("Not logged in. Run 'knuspr auth login' first.")
self._make_request(
f'/api/v1/shopping-lists/id/{list_id}/product/{product_id}/{amount}',
method='PUT',
data={'source': 'Shopping Lists'}
)
return True
def remove_from_shopping_list(self, list_id: int, product_id: int, amount: int = 0) -> bool:
"""Remove product from shopping list. Amount 0 removes completely."""
if not self.is_logged_in():
raise KnusprAPIError("Not logged in. Run 'knuspr auth login' first.")
self._make_request(
f'/api/v1/shopping-lists/id/{list_id}/product/{product_id}/{amount}',